Skip to content

Commit

Permalink
feat: add AR::make() method
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk committed Jul 3, 2024
1 parent 3cb2bc0 commit a5a37fe
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/ActiveRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,36 @@
use Cycle\ORM\RepositoryInterface;
use Cycle\ORM\Transaction\StateInterface;

/**
* A base class for entities that are managed by the ORM.
* Adds a set of ActiveRecord methods to the extending entity class.
*/
abstract class ActiveRecord
{
/**
* Creates a new entity instance with the given data.
* It is preferable to use this method instead of the constructor because
* it uses ORM services to create the entity.
*
* Equals to calling {@see ORMInterface::make()}.
*
* @param array<non-empty-string, mixed> $data An associative array where keys are property names
* and values are property values.
*
* Example:
*
* ```php
* $user = User::make([
* 'name' => 'John Doe',
* 'email' => '[email protected]',
* ]);
* ```
*/
public static function make(array $data): static
{
return self::getOrm()->make(static::class, $data);
}

/**
* Finds a single record based on the given primary key.
*/
Expand Down
10 changes: 10 additions & 0 deletions tests/src/Functional/ActiveRecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ public function it_uses_query_to_select_entity(): void
self::assertSame('Antony', $user->name);
}

#[Test]
public function it_creates_entity_instance_using_make(): void
{
$user = User::make(['name' => 'Alex']);

self::assertInstanceOf(User::class, $user);
self::assertNotSame(User::class, $user::class, 'An Entity Proxy is created');
self::assertSame('Alex', $user->name);
}

/**
* @throws \Throwable
*/
Expand Down

0 comments on commit a5a37fe

Please sign in to comment.