Skip to content

Commit

Permalink
fix: ObjectCast implementation
Browse files Browse the repository at this point in the history
But I don't know it makes sense.
  • Loading branch information
kenjis committed Sep 30, 2023
1 parent 02df574 commit d77ec8f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
10 changes: 5 additions & 5 deletions system/Entity/Cast/ObjectCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,23 @@ public static function toDatabase($value, array $params = [])
}

// @TODO How to implement?
return serialize($value);
return serialize((array) $value);
}

/**
* {@inheritDoc}
*/
public static function fromDatabase($value, array $params = []): array
public static function fromDatabase($value, array $params = []): object
{
if (! is_string($value)) {
self::invalidTypeValueError($value);
}

// @TODO How to implement?
if ((strpos($value, 'a:') === 0 || strpos($value, 's:') === 0)) {
$value = unserialize($value);
if ((strpos($value, 'a:') === 0)) {
return (object) unserialize($value, ['allowed_classes' => false]);
}

return (array) $value;
self::invalidTypeValueError($value);
}
}
9 changes: 6 additions & 3 deletions tests/system/Entity/EntityLiveTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@

namespace CodeIgniter\Entity;

use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\I18n\Time;
use CodeIgniter\Model;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use Config\Services;
use stdClass;

/**
* @internal
Expand Down Expand Up @@ -85,8 +85,6 @@ public function testEntityReturnsValuesWithCorrectTypes()
*/
public function testCastObject(): void
{
$this->expectException(DatabaseException::class);

$entity = new class () extends Entity {
protected $casts = [
'id' => 'int',
Expand All @@ -103,5 +101,10 @@ public function testCastObject(): void
};
$entity->fill(['username' => 'johnsmith', 'active' => false, 'memo' => ['foo', 'bar']]);
$model->save($entity);

$user = $model->asObject(get_class($entity))->find(1);

$this->assertInstanceOf(stdClass::class, $user->memo);
$this->assertSame(['foo', 'bar'], (array) $user->memo);
}
}

0 comments on commit d77ec8f

Please sign in to comment.