Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement the interface ArrayableInterface for BaseActiveRecord #273

Merged
merged 24 commits into from
Dec 16, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
12c3300
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
be499a5
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
3988dcc
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
424f841
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
b64dde5
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
0f680fe
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
594a222
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
08711a6
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
cb9db0e
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
044755d
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
fa7c4cb
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 9, 2023
0af5333
Update src/BaseActiveRecord.php
niqingyang Dec 10, 2023
baf1889
Update src/ActiveRecordInterface.php
niqingyang Dec 10, 2023
b479a12
Revert "Update src/ActiveRecordInterface.php"
niqingyang Dec 10, 2023
0af32f1
Revert "Update src/BaseActiveRecord.php"
niqingyang Dec 10, 2023
c84a97d
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 10, 2023
2b82b2b
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 10, 2023
32cc7b4
Update tests/Driver/Oracle/ActiveRecordTest.php
niqingyang Dec 11, 2023
8583269
Update tests/Driver/Pgsql/ActiveRecordTest.php
niqingyang Dec 11, 2023
e299dfa
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 11, 2023
1f86104
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 11, 2023
43f615b
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 11, 2023
418be7d
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 11, 2023
564e019
implement the interface ArrayableInterface for BaseActiveRecord
niqingyang Dec 11, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"require": {
"php": "^8.0",
"ext-json": "*",
"yiisoft/arrays": "^3.0",
"yiisoft/db": "^1.1",
"yiisoft/factory": "^1.0"
},
Expand Down
12 changes: 11 additions & 1 deletion src/ActiveRecordInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,16 @@ public function populateRecord(array|object $row): void;

/**
* Serializes the active record into its array implementation with attribute name as a key, and it values as value.
*
* @param array $fields the fields that the output array should contain. Fields not specified
* in {@see fields()} will be ignored. If this parameter is empty, all fields as specified
* in {@see fields()} will be returned.
* @param array $expand the additional fields that the output array should contain.
* Fields not specified in {@see extraFields()} will be ignored. If this parameter is empty, no extra fields
* will be returned.
* @param bool $recursive Whether to recursively return array representation of embedded objects.
*
* @return array The array representation of the object.
*/
public function toArray(): array;
public function toArray(array $fields = [], array $expand = [], bool $recursive = true): array;
niqingyang marked this conversation as resolved.
Show resolved Hide resolved
Tigrov marked this conversation as resolved.
Show resolved Hide resolved
}
33 changes: 23 additions & 10 deletions src/BaseActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
use IteratorAggregate;
use ReflectionException;
use Throwable;
use Yiisoft\Arrays\ArrayableInterface;
use Yiisoft\Arrays\ArrayableTrait;
use Yiisoft\Arrays\ArrayHelper;
use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Exception\Exception;
use Yiisoft\Db\Exception\InvalidArgumentException;
Expand Down Expand Up @@ -40,8 +43,9 @@
* @template-implements ArrayAccess<int, mixed>
* @template-implements IteratorAggregate<int>
*/
abstract class BaseActiveRecord implements ActiveRecordInterface, IteratorAggregate, ArrayAccess
abstract class BaseActiveRecord implements ActiveRecordInterface, IteratorAggregate, ArrayAccess, ArrayableInterface
{
use ArrayableTrait;
use BaseActiveRecordTrait;

private array $attributes = [];
Expand Down Expand Up @@ -117,7 +121,7 @@
/**
* @psalm-suppress MixedReturnTypeCoercion
*/
public function fields(): array

Check failure on line 124 in src/BaseActiveRecord.php

View workflow job for this annotation

GitHub Actions / PHP 8-ubuntu-latest

LessSpecificImplementedReturnType: The inherited return type 'array<string, Closure|string>' for Yiisoft\ActiveRecord\ActiveRecordInterface::fields is more specific than the implemented return type for Yiisoft\ActiveRecord\BaseActiveRecord::fields 'array<array-key, mixed>'

Check failure on line 124 in src/BaseActiveRecord.php

View workflow job for this annotation

GitHub Actions / PHP 8.1-ubuntu-latest

LessSpecificImplementedReturnType: The inherited return type 'array<string, Closure|string>' for Yiisoft\ActiveRecord\ActiveRecordInterface::fields is more specific than the implemented return type for Yiisoft\ActiveRecord\BaseActiveRecord::fields 'array<array-key, mixed>'
{
$fields = array_keys($this->attributes);

Expand Down Expand Up @@ -1266,19 +1270,28 @@
return $this->tableName;
}

public function toArray(): array
/**
* @inheritDoc
*/
public function toArray(array $fields = [], array $expand = [], bool $recursive = true): array
niqingyang marked this conversation as resolved.
Show resolved Hide resolved
{
$data = [];

foreach ($this->fields() as $key => $value) {
if ($value instanceof Closure) {
/** @var mixed */
$data[$key] = $value($this);
} else {
/** @var mixed */
$data[$value] = $this[$value];
foreach ($this->resolveFields($fields, $expand) as $field => $definition) {
$attribute = $definition instanceof Closure ? $definition($this, $field) : $this[$definition];

if ($recursive) {
$nestedFields = $this->extractFieldsFor($fields, $field);
$nestedExpand = $this->extractFieldsFor($expand, $field);
if ($attribute instanceof ArrayableInterface) {
$attribute = $attribute->toArray($nestedFields, $nestedExpand);
} elseif (is_array($attribute) && ($nestedExpand || $nestedFields)) {
$attribute = $this->filterAndExpand($attribute, $nestedFields, $nestedExpand);
}
}
$data[$field] = $attribute;
}
return $data;

return $recursive ? ArrayHelper::toArray($data) : $data;
}
}
6 changes: 3 additions & 3 deletions src/BaseActiveRecordTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@
return $this->$getter();
}

if (method_exists($this, 'set' . ucfirst($name))) {

Check warning on line 79 in src/BaseActiveRecordTrait.php

View workflow job for this annotation

GitHub Actions / PHP 8-ubuntu-latest

Escaped Mutant for Mutator "UnwrapUcFirst": --- Original +++ New @@ @@ /** read property, e.g. getName() */ return $this->{$getter}(); } - if (method_exists($this, 'set' . ucfirst($name))) { + if (method_exists($this, 'set' . $name)) { throw new InvalidCallException('Getting write-only property: ' . static::class . '::' . $name); } throw new UnknownPropertyException('Getting unknown property: ' . static::class . '::' . $name);
throw new InvalidCallException('Getting write-only property: ' . static::class . '::' . $name);
}

throw new UnknownPropertyException('Getting unknown property: ' . static::class . '::' . $name);

Check warning on line 83 in src/BaseActiveRecordTrait.php

View workflow job for this annotation

GitHub Actions / PHP 8-ubuntu-latest

Escaped Mutant for Mutator "ConcatOperandRemoval": --- Original +++ New @@ @@ if (method_exists($this, 'set' . ucfirst($name))) { throw new InvalidCallException('Getting write-only property: ' . static::class . '::' . $name); } - throw new UnknownPropertyException('Getting unknown property: ' . static::class . '::' . $name); + throw new UnknownPropertyException(static::class . '::' . $name); } /** * Returns the relation object with the specified name.
}

/**
Expand Down Expand Up @@ -250,11 +250,11 @@
* It is implicitly called when you use something like `$model[$offset] = $item;`.
*
* @param mixed $offset the offset to set element.
* @param mixed $item the element value.
* @param mixed $value the element value.
*/
public function offsetSet(mixed $offset, mixed $item): void
public function offsetSet(mixed $offset, mixed $value): void
{
$this->$offset = $item;
$this->$offset = $value;
}

/**
Expand Down
55 changes: 55 additions & 0 deletions tests/ActiveRecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Cat;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Customer;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerClosureField;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerForArrayable;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerWithAlias;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Dog;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Item;
Expand Down Expand Up @@ -763,4 +764,58 @@ public function testToArrayWithClosure(): void
$customer->toArray(),
);
}

public function testToArrayForArrayable(): void
{
$this->checkFixture($this->db, 'customer', true);

$customerQuery = new ActiveQuery(CustomerForArrayable::class, $this->db);

/** @var CustomerForArrayable $customer */
$customer = $customerQuery->findOne(1);
/** @var CustomerForArrayable $customer2 */
$customer2 = $customerQuery->findOne(2);
/** @var CustomerForArrayable $customer3 */
$customer3 = $customerQuery->findOne(3);

$customer->setItem($customer2);
$customer->setItems($customer3);

$this->assertSame(
[
'id' => 1,
'email' => '[email protected]',
'name' => 'user1',
'address' => 'address1',
'status' => 'active',
'item' => [
'id' => 2,
'email' => '[email protected]',
'name' => 'user2',
'status' => 'active',
],
'items' => [
[
'id' => 3,
'email' => '[email protected]',
'name' => 'user3',
'status' => 'inactive',
],
],
],
$customer->toArray([
'id',
'name',
'email',
'address',
'status',
'item.id',
'item.name',
'item.email',
'items.0.id',
'items.0.name',
'items.0.email',
]),
);
}
}
55 changes: 55 additions & 0 deletions tests/Driver/Oracle/ActiveRecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Yiisoft\ActiveRecord\ActiveQuery;
use Yiisoft\ActiveRecord\Tests\Driver\Oracle\Stubs\Customer;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerClosureField;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerForArrayable;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Type;
use Yiisoft\ActiveRecord\Tests\Support\OracleHelper;

Expand Down Expand Up @@ -166,4 +167,58 @@ public function testToArrayWithClosure(): void
$customer->toArray(),
);
}

public function testToArrayForArrayable(): void
{
$this->checkFixture($this->db, 'customer', true);

$customerQuery = new ActiveQuery(CustomerForArrayable::class, $this->db);

/** @var CustomerForArrayable $customer */
$customer = $customerQuery->findOne(1);
/** @var CustomerForArrayable $customer2 */
$customer2 = $customerQuery->findOne(2);
/** @var CustomerForArrayable $customer3 */
$customer3 = $customerQuery->findOne(3);

$customer->setItem($customer2);
$customer->setItems($customer3);

$this->assertSame(
[
'id' => 1,
'email' => '[email protected]',
'name' => 'user1',
'address' => 'address1',
'status' => 'active',
'item' => [
'id' => 2,
'email' => '[email protected]',
'name' => 'user2',
'status' => 'active',
],
'items' => [
[
'id' => 3,
'email' => '[email protected]',
'name' => 'user3',
'status' => 'inactive',
],
],
],
$customer->toArray([
'id',
'name',
'email',
'address',
'status',
'item.id',
'item.name',
'item.email',
'items.0.id',
'items.0.name',
'items.0.email',
]),
);
}
niqingyang marked this conversation as resolved.
Show resolved Hide resolved
}
55 changes: 55 additions & 0 deletions tests/Driver/Pgsql/ActiveRecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\BoolAR;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\Customer;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerClosureField;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\CustomerForArrayable;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\DefaultPk;
use Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord\UserAR;
use Yiisoft\ActiveRecord\Tests\Support\PgsqlHelper;
Expand Down Expand Up @@ -381,4 +382,58 @@ public function testToArrayWithClosure(): void
$customer->toArray(),
);
}

public function testToArrayForArrayable(): void
{
$this->checkFixture($this->db, 'customer', true);

$customerQuery = new ActiveQuery(CustomerForArrayable::class, $this->db);

/** @var CustomerForArrayable $customer */
$customer = $customerQuery->findOne(1);
/** @var CustomerForArrayable $customer2 */
$customer2 = $customerQuery->findOne(2);
/** @var CustomerForArrayable $customer3 */
$customer3 = $customerQuery->findOne(3);

$customer->setItem($customer2);
$customer->setItems($customer3);

$this->assertSame(
[
'id' => 1,
'email' => '[email protected]',
'name' => 'user1',
'address' => 'address1',
'status' => 'active',
'item' => [
'id' => 2,
'email' => '[email protected]',
'name' => 'user2',
'status' => 'active',
],
'items' => [
[
'id' => 3,
'email' => '[email protected]',
'name' => 'user3',
'status' => 'inactive',
],
],
],
$customer->toArray([
'id',
'name',
'email',
'address',
'status',
'item.id',
'item.email',
'item.name',
'items.0.id',
'items.0.email',
'items.0.name',
]),
);
}
niqingyang marked this conversation as resolved.
Show resolved Hide resolved
}
57 changes: 57 additions & 0 deletions tests/Stubs/ActiveRecord/CustomerForArrayable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

declare(strict_types=1);

namespace Yiisoft\ActiveRecord\Tests\Stubs\ActiveRecord;

use Yiisoft\ActiveRecord\ActiveRecord;

/**
* Class CustomerClosureField.
*
* @property int $id
* @property string $name
* @property string $email
* @property string $address
* @property int $status
*/
class CustomerForArrayable extends ActiveRecord
{
public array $items = [];

public ?CustomerForArrayable $item = null;

public function getTableName(): string
{
return 'customer';
}

public function fields(): array
{
$fields = parent::fields();

$fields['item'] = 'item';
$fields['items'] = 'items';

return $fields;
}

public function setItem(self $item)
{
$this->item = $item;
}

public function setItems(self ...$items)
{
$this->items = $items;
}

public function toArray(array $fields = [], array $expand = [], bool $recursive = true): array
{
$data = parent::toArray($fields, $expand, $recursive);

$data['status'] = $this->status == 1 ? 'active' : 'inactive';

return $data;
}
}
Loading