Skip to content

Commit

Permalink
fix SQL Expressionable typecast
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek committed Oct 2, 2021
1 parent c7a049b commit 5f2d4ef
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions src/Persistence.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,10 +174,7 @@ public function typecastSaveRow(Model $model, array $row): array

$field = $model->getField($fieldName);

// SQL Expression cannot be converted
if (!$value instanceof \Atk4\Data\Persistence\Sql\Expressionable) {
$value = $this->typecastSaveField($field, $value);
}
$value = $this->typecastSaveField($field, $value);

// check null values for mandatory fields
if ($value === null && $field->mandatory) {
Expand All @@ -197,6 +194,10 @@ public function typecastSaveRow(Model $model, array $row): array
* NOTE: Please DO NOT perform "actual" field mapping here, because data
* may be "aliased" from SQL persistencies or mapped depending on persistence
* driver.
*
* @param array<string, scalar|null> $row
*
* @return array<string, mixed>
*/
public function typecastLoadRow(Model $model, array $row): array
{
Expand Down Expand Up @@ -232,11 +233,15 @@ public function typecastSaveField(Field $field, $value)
return null;
}

// SQL Expression cannot be converted
if ($value instanceof Persistence\Sql\Expressionable) {
return $value;
}

try {
$v = $this->_typecastSaveField($field, $value);
if ($v !== null && !is_scalar($v) && !$v instanceof Persistence\Sql\Expressionable) { // @phpstan-ignore-line
throw (new Exception('Unexpected non-scalar value'))
->addMoreInfo('type', get_debug_type($v));
if ($v !== null && !is_scalar($v)) {
throw new Exception('Unexpected non-scalar value');
}

return $v;
Expand All @@ -250,14 +255,16 @@ public function typecastSaveField(Field $field, $value)
* Cast specific field value from the way how it's stored inside
* persistence to a PHP format.
*
* @param mixed $value
* @param scalar|null $value
*
* @return mixed
*/
public function typecastLoadField(Field $field, $value)
{
if ($value === null) {
return null;
} elseif (!is_scalar($value)) {
throw new Exception('Unexpected non-scalar value');
}

try {
Expand All @@ -274,7 +281,7 @@ public function typecastLoadField(Field $field, $value)
*
* @param mixed $value
*
* @return scalar|Persistence\Sql\Expressionable|null
* @return scalar|null
*/
protected function _typecastSaveField(Field $field, $value)
{
Expand Down Expand Up @@ -310,7 +317,7 @@ protected function _typecastSaveField(Field $field, $value)
* This is the actual field typecasting, which you can override in your
* persistence to implement necessary typecasting.
*
* @param mixed $value
* @param scalar|null $value
*
* @return mixed
*/
Expand Down

0 comments on commit 5f2d4ef

Please sign in to comment.