Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
96 changes: 96 additions & 0 deletions tests/Feature/Common/EventListener/JoinedInheritanceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

declare(strict_types=1);

namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\EventListener;

use Cycle\ORM\Entity\Behavior\Listener\CreatedAt;
use Cycle\ORM\Entity\Behavior\Listener\UpdatedAt;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\JoinedInheritance\Document;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\JoinedInheritance\Invoice;
use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase;
use Cycle\ORM\Schema;
use Cycle\ORM\SchemaInterface;
use Cycle\ORM\Select;
use Testo\Assert;
use Testo\Lifecycle\BeforeTest;
use Testo\Test;

final class JoinedInheritanceTest extends ListenerTestCase
{
#[Test]
public function parentListenersFillParentColumnsOnCreate(): void
{
$invoice = new Invoice();
$invoice->title = 'first';
$invoice->amount = 10;

$this->save($invoice);

$row = $this->getDatabase()->select()->from('documents')->fetchAll()[0];
Assert::same($row['title'], 'first');
Assert::notNull($row['created_at']);
Assert::notNull($row['updated_at']);
Assert::same((int) $this->getDatabase()->select()->from('invoices')->fetchAll()[0]['amount'], 10);
}

#[Test]
public function updateWritesParentColumns(): void
{
$invoice = new Invoice();
$invoice->title = 'first';
$this->save($invoice);

$this->orm->getHeap()->clean();
$invoice = (new Select($this->orm, Invoice::class))->fetchOne();
$invoice->title = 'second';
$invoice->amount = 20;
$this->save($invoice);

$row = $this->getDatabase()->select()->from('documents')->fetchAll()[0];
Assert::same($row['title'], 'second');
Assert::same((int) $this->getDatabase()->select()->from('invoices')->fetchAll()[0]['amount'], 20);
}

#[BeforeTest]
protected function setUp(): void
{
$this->makeTable('documents', [
'id' => 'primary',
'title' => 'string',
'created_at' => 'datetime,nullable',
'updated_at' => 'datetime,nullable',
]);
$this->makeTable('invoices', ['id' => 'integer', 'amount' => 'integer'], pk: ['id']);

$this->withSchema(new Schema([
Document::class => [
SchemaInterface::ROLE => 'document',
SchemaInterface::DATABASE => 'default',
SchemaInterface::TABLE => 'documents',
SchemaInterface::PRIMARY_KEY => 'id',
SchemaInterface::COLUMNS => [
'id' => 'id',
'title' => 'title',
'createdAt' => 'created_at',
'updatedAt' => 'updated_at',
],
SchemaInterface::LISTENERS => [CreatedAt::class, UpdatedAt::class],
SchemaInterface::TYPECAST => ['id' => 'int', 'createdAt' => 'datetime', 'updatedAt' => 'datetime'],
SchemaInterface::SCHEMA => [],
SchemaInterface::RELATIONS => [],
],
Invoice::class => [
SchemaInterface::ROLE => 'invoice',
SchemaInterface::PARENT => 'document',
SchemaInterface::DATABASE => 'default',
SchemaInterface::TABLE => 'invoices',
SchemaInterface::PRIMARY_KEY => 'id',
SchemaInterface::COLUMNS => ['id' => 'id', 'amount' => 'amount'],
SchemaInterface::TYPECAST => ['id' => 'int', 'amount' => 'int'],
SchemaInterface::SCHEMA => [],
SchemaInterface::RELATIONS => [],
],
]));
}
}
53 changes: 53 additions & 0 deletions tests/Feature/Common/EventListener/ListenerProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@

namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\EventListener;

use Cycle\ORM\Entity\Behavior\Attribute\Listen;
use Cycle\ORM\Entity\Behavior\Exception\Dispatcher\RuntimeException;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\AuditService;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\BrokenAttributeService;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\BrokenEventListService;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\EventListener\Post;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\PostService;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\UncallableEventListService;
use Cycle\ORM\Entity\Behavior\Tests\Support\ListenerTestCase;
use Cycle\ORM\Heap\Heap;
use Cycle\ORM\Schema;
Expand Down Expand Up @@ -65,6 +68,56 @@ public function testEventListMustHoldEventMethodPairs(): never
$this->withListeners(BrokenEventListService::class);
}

#[Test]
public function testDefinitionOfMissingClassIsSkipped(): void
{
$this->withListeners('Cycle\ORM\Entity\Behavior\Tests\Fixtures\MissingListener', AuditService::class);

$this->save(new Post());

Assert::same($this->fetchPost()->title, 'created');
}

#[Test]
public function testListenerWithoutEventsIsSkipped(): void
{
$this->withListeners(\ArrayObject::class);

$this->save(new Post());

Assert::null($this->fetchPost()->title);
}

#[Test]
public function testProvidedListenerMustBeCallable(): never
{
Expect::exception(\Exception::class)
->withMessage(\sprintf("Cann't create listener `%s` for the `post` role.", UncallableEventListService::class))
->withPrevious(
RuntimeException::class,
static fn(ExpectedException $previous) => $previous->withMessage(\sprintf(
"Cann't build callable from instance of `%s` and `missing` method name.",
UncallableEventListService::class,
)),
);

$this->withListeners(UncallableEventListService::class);
}

#[Test]
public function testBrokenListenAttributeIsReported(): never
{
Expect::exception(RuntimeException::class)
->withMessage(\sprintf(
"Cann't instantiate attribute %s in the %s::onCreate method.",
Listen::class,
BrokenAttributeService::class,
))
->withPrevious(\ArgumentCountError::class);

$this->withListeners(BrokenAttributeService::class);
}

#[BeforeTest]
protected function createTable(): void
{
Expand Down
20 changes: 20 additions & 0 deletions tests/Feature/Common/OptimisticLock/OptimisticLockTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
namespace Cycle\ORM\Entity\Behavior\Tests\Feature\Common\OptimisticLock;

use Cycle\Database\ColumnInterface;
use Cycle\ORM\Entity\Behavior\Exception\BehaviorCompilationException;
use Cycle\ORM\Entity\Behavior\Listener\OptimisticLock as Listener;
use Cycle\ORM\Entity\Behavior\OptimisticLock;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Article;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Comment;
use Cycle\ORM\Entity\Behavior\Tests\Fixtures\OptimisticLock\Item;
Expand All @@ -17,9 +19,12 @@
use Cycle\ORM\Entity\Behavior\Tests\Support\SchemaTestCase;
use Cycle\ORM\Schema\GeneratedField;
use Cycle\ORM\SchemaInterface;
use Cycle\Schema\Definition\Entity;
use Cycle\Schema\Registry;
use Spiral\Tokenizer\Config\TokenizerConfig;
use Spiral\Tokenizer\Tokenizer;
use Testo\Assert;
use Testo\Expect;
use Testo\Lifecycle\BeforeTest;
use Testo\Test;

Expand Down Expand Up @@ -133,6 +138,21 @@ public function testComputeConfiguresDeclaredField(): void
Assert::same($field->getGenerated(), GeneratedField::BEFORE_INSERT | GeneratedField::BEFORE_UPDATE);
}

#[Test]
public function testUnknownRuleIsRejected(): never
{
$registry = new Registry($this->dbal);
$entity = (new Entity())->setRole('post');
$registry->register($entity);
$registry->linkTable($entity, 'default', 'posts');

Expect::exception(BehaviorCompilationException::class)->withMessage(
\sprintf('Wrong rule `unknown` for the %s behavior in the `post.version` field.', OptimisticLock::class),
);

(new OptimisticLock(rule: 'unknown'))->withRole('post')->render($registry);
}

#[BeforeTest]
protected function setUp(): void
{
Expand Down
34 changes: 34 additions & 0 deletions tests/Feature/Common/Schema/RegistryModifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Cycle\Testing\Database\DatabaseTestCase;
use Ramsey\Uuid\Uuid;
use Testo\Assert;
use Testo\Data\DataSet;
use Testo\Expect;
use Testo\Lifecycle\BeforeTest;
use Testo\Test;
Expand Down Expand Up @@ -252,6 +253,39 @@ public function testAddExistingStringFieldSetsGenerated(): void
);
}

#[Test]
#[DataSet(['addIntegerColumn'], 'integer')]
#[DataSet(['addBigIntegerColumn'], 'big integer')]
#[DataSet(['addDatetimeColumn'], 'datetime')]
#[DataSet(['addStringColumn'], 'string')]
#[DataSet(['addSnowflakeColumn'], 'snowflake')]
#[DataSet(['addUlidColumn'], 'ulid')]
#[DataSet(['addUuidColumn'], 'uuid')]
public function testExistingFieldOfSameTypeIsReused(string $method): void
{
$this->modifier->{$method}('value_column', 'value');

$column = $this->modifier->{$method}('value_column', 'value', GeneratedField::BEFORE_INSERT);

$fields = $this->registry->getEntity(self::ROLE_TEST)->getFields();
Assert::same($fields->count(), 1);
Assert::same($fields->get('value')->getGenerated(), GeneratedField::BEFORE_INSERT);
Assert::same($column->getName(), 'value_column');
}

#[Test]
#[DataSet(['addIntegerColumn', 'Field value must be of type integer.'], 'integer')]
#[DataSet(['addStringColumn', 'Field value must be of type string.'], 'string')]
#[DataSet(['addDatetimeColumn', 'Field value must be of type datetime.'], 'datetime')]
public function testExistingFieldOfOtherTypeIsRejected(string $method, string $message): void
{
$this->modifier->addUuidColumn('value_column', 'value');

Expect::exception(BehaviorCompilationException::class)->withMessage($message);

$this->modifier->{$method}('value_column', 'value');
}

#[Test]
public function testDefaultTypecastHandlerIsNotAddedToEntity(): void
{
Expand Down
23 changes: 23 additions & 0 deletions tests/Fixtures/ArgumentlessModifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Cycle\ORM\Entity\Behavior\Tests\Fixtures;

use Cycle\ORM\Entity\Behavior\Schema\BaseModifier;

/**
* A custom behavior whose listener takes no arguments.
*/
final class ArgumentlessModifier extends BaseModifier
{
protected function getListenerClass(): string
{
return AuditService::class;
}

protected function getListenerArgs(): array
{
return [];
}
}
17 changes: 17 additions & 0 deletions tests/Fixtures/BrokenAttributeService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Cycle\ORM\Entity\Behavior\Tests\Fixtures;

use Cycle\ORM\Entity\Behavior\Attribute\Listen;
use Cycle\ORM\Entity\Behavior\Event\Mapper\Command\OnCreate;

/**
* Declares {@see Listen} without the event, so the attribute cannot be instantiated.
*/
class BrokenAttributeService
{
#[Listen]
public function onCreate(OnCreate $event): void {}
}
13 changes: 13 additions & 0 deletions tests/Fixtures/JoinedInheritance/Document.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Cycle\ORM\Entity\Behavior\Tests\Fixtures\JoinedInheritance;

class Document
{
public ?int $id = null;
public ?\DateTimeImmutable $createdAt = null;
public ?\DateTimeImmutable $updatedAt = null;
public string $title = '';
}
10 changes: 10 additions & 0 deletions tests/Fixtures/JoinedInheritance/Invoice.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Cycle\ORM\Entity\Behavior\Tests\Fixtures\JoinedInheritance;

class Invoice extends Document
{
public int $amount = 0;
}
21 changes: 21 additions & 0 deletions tests/Fixtures/UncallableEventListService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Cycle\ORM\Entity\Behavior\Tests\Fixtures;

use Cycle\ORM\Entity\Behavior\Dispatcher\EventListProviderInterface;
use Cycle\ORM\Entity\Behavior\Event\Mapper\Command\OnCreate;

/**
* Names a method it does not have in {@see getEventsList()}.
*/
class UncallableEventListService implements EventListProviderInterface
{
public function getEventsList(): array
{
return [
[OnCreate::class, 'missing'],
];
}
}
Loading
Loading