diff --git a/tests/Fixtures/Configurator/Draft.php b/tests/Fixtures/Configurator/Draft.php new file mode 100644 index 00000000..eddf095d --- /dev/null +++ b/tests/Fixtures/Configurator/Draft.php @@ -0,0 +1,23 @@ +error; + } + + public function getConstantMetadata(\ReflectionClassConstant $constant, ?string $name = null): iterable + { + return []; + } + + public function getParameterMetadata(\ReflectionParameter $parameter, ?string $name = null): iterable + { + return []; + } +} diff --git a/tests/Fixtures/TableInheritance/Animal.php b/tests/Fixtures/TableInheritance/Animal.php new file mode 100644 index 00000000..28034378 --- /dev/null +++ b/tests/Fixtures/TableInheritance/Animal.php @@ -0,0 +1,18 @@ + [ManyToMany::class, ['through' => 'postTag'], 'manyToMany']; + yield 'refers to' => [RefersTo::class, [], 'refersTo']; + yield 'morphed has one' => [MorphedHasOne::class, [], 'morphedHasOne']; + yield 'morphed has many' => [MorphedHasMany::class, [], 'morphedHasMany']; + yield 'belongs to morphed' => [BelongsToMorphed::class, [], 'belongsToMorphed']; + yield 'refers to morphed' => [RefersToMorphed::class, [], 'refersToMorphed']; + } + public function entityKeepsSeveralTypecastHandlers(): void { $entity = new Entity(typecast: ['Foo', 'Bar']); @@ -94,4 +113,25 @@ public function relationLoadsLazilyByDefault(): void Assert::same((new HasOne(target: 'user'))->getLoad(), 'lazy'); Assert::same((new HasOne(target: 'user', load: 'eager'))->getLoad(), 'eager'); } + + /** + * @param class-string $class + */ + #[DataProvider('relationsWithInverse')] + public function relationKeepsItsConstructorArguments(string $class, array $arguments, string $type): void + { + $inverse = new Inverse(as: 'owner', type: 'belongsTo'); + + $relation = new $class(...$arguments, target: 'target', load: 'eager', inverse: $inverse); + + Assert::same($relation->getType(), $type); + Assert::same($relation->getLoad(), 'eager'); + Assert::same($relation->getInverse(), $inverse); + Assert::array($relation->getOptions())->doesNotHaveKeys('target', 'inverse'); + } + + public function discriminatorColumnKeepsItsName(): void + { + Assert::same((new DiscriminatorColumn(name: 'kind'))->getName(), 'kind'); + } } diff --git a/tests/Unit/Attribute/ColumnTest.php b/tests/Unit/Attribute/ColumnTest.php index 8c43f88c..70150ebf 100644 --- a/tests/Unit/Attribute/ColumnTest.php +++ b/tests/Unit/Attribute/ColumnTest.php @@ -161,6 +161,14 @@ public function testValuesOfANonEnumColumnStayAnAttribute(): void Assert::same($column->getAttributes(), ['values' => ['a', 'b']]); } + public function testEnumValuesTakenFromTheCasesOfAnEnumInstance(): void + { + $column = new Column(type: 'enum', values: StringEnum::B); + + Assert::same($column->getType(), 'enum(a,b)'); + Assert::array($column->getAttributes())->doesNotHaveKeys('values'); + } + public function testEnumValuesThatAreNotScalarAreLeftEmpty(): void { $column = new Column(type: 'enum', values: ['a', new StringableObject('b'), 1]); diff --git a/tests/Unit/ConfiguratorTest.php b/tests/Unit/ConfiguratorTest.php index 5c70c968..37ec33ee 100644 --- a/tests/Unit/ConfiguratorTest.php +++ b/tests/Unit/ConfiguratorTest.php @@ -7,19 +7,23 @@ use Cycle\Annotated\Annotation\Column; use Cycle\Annotated\Annotation\Embeddable; use Cycle\Annotated\Annotation\Entity; +use Cycle\Annotated\Annotation\ForeignKey; use Cycle\Annotated\Configurator; use Cycle\Annotated\Exception\AnnotationException; use Cycle\Annotated\Exception\AnnotationWrongTypeArgumentException; use Cycle\Annotated\Tests\Fixtures\Configurator\Address; use Cycle\Annotated\Tests\Fixtures\Configurator\AddressMapper; use Cycle\Annotated\Tests\Fixtures\Configurator\Author; +use Cycle\Annotated\Tests\Fixtures\Configurator\Draft; use Cycle\Annotated\Tests\Fixtures\Configurator\Post; use Cycle\Annotated\Tests\Fixtures\Configurator\Sub\Comments; use Cycle\Annotated\Tests\Fixtures\Configurator\Sub\Typecaster as SubTypecaster; use Cycle\Annotated\Tests\Fixtures\Configurator\Typecaster; +use Cycle\Annotated\Tests\Fixtures\Locator\FailingClassReader; use Cycle\ORM\Schema\GeneratedField; use Cycle\Schema\Definition\Entity as EntitySchema; use Cycle\Schema\Definition\Field; +use Cycle\Schema\Generator\SyncTables; use Cycle\Schema\Table\Column as ColumnOption; use Spiral\Attributes\AttributeReader; use Spiral\Attributes\Reader; @@ -114,6 +118,88 @@ public function keepsTheInnerKeyOfAPropertyForeignKey(): void Assert::same($keys[0]->getInnerColumns(), ['author_ref']); } + public function marksTheSchemaOfAReadonlyEntity(): void + { + $entity = $this->configurator()->initEntity(new Entity(readonlySchema: true), new \ReflectionClass(Post::class)); + + Assert::true($entity->getOptions()->get(SyncTables::READONLY_SCHEMA)); + } + + public function requiresTheTargetOfARelation(): never + { + $entity = new EntitySchema(); + $entity->setClass(Draft::class); + + Expect::exception(AnnotationException::class) + ->withMessage(\sprintf('Relation target definition is required on `%s`.`reviewer`', Draft::class)); + + $this->configurator()->initRelations($entity, new \ReflectionClass(Draft::class)); + } + + public function wrapsAnExceptionOfTheReaderWhileReadingRelations(): never + { + $entity = new EntitySchema(); + $entity->setClass(Post::class); + + Expect::exception(AnnotationException::class)->withMessage('broken')->withCode(7); + + (new Configurator($this->throwingReader(new \RuntimeException('broken', 7)))) + ->initRelations($entity, new \ReflectionClass(Post::class)); + } + + public function takesTheInnerKeyOfAPropertyForeignKeyFromTheProperty(): void + { + $entity = new EntitySchema(); + $entity->setClass(Draft::class); + + $this->configurator()->initForeignKeys(new Entity(), $entity, new \ReflectionClass(Draft::class)); + + $keys = \iterator_to_array($entity->getForeignKeys(), false); + Assert::count($keys, 1); + Assert::same($keys[0]->getInnerColumns(), ['editorId']); + } + + public function requiresTheInnerKeyOfAnEntityForeignKey(): never + { + $entity = new EntitySchema(); + $entity->setClass(Post::class); + + Expect::exception(AnnotationException::class) + ->withMessage(\sprintf('Inner column definition for the foreign key is required on `%s`', Post::class)); + + $this->configurator()->initForeignKeys( + new Entity(foreignKeys: [new ForeignKey(target: Author::class)]), + $entity, + new \ReflectionClass(\stdClass::class), + ); + } + + public function wrapsAnExceptionOfTheReaderWhileReadingClassForeignKeys(): never + { + $entity = new EntitySchema(); + $entity->setClass(Post::class); + + Expect::exception(AnnotationException::class)->withMessage('broken')->withCode(5); + + (new Configurator(new FailingClassReader(new \RuntimeException('broken', 5)))) + ->initForeignKeys(new Entity(), $entity, new \ReflectionClass(Post::class)); + } + + public function wrapsAnExceptionOfTheReaderWhileReadingGeneratedFields(): never + { + Expect::exception(AnnotationException::class)->withMessage('broken')->withCode(3); + + (new Configurator($this->throwingReader(new \RuntimeException('broken', 3)))) + ->initGeneratedFields(new EntitySchema(), new \ReflectionClass(Post::class)); + } + + public function resolvesATypecastWrittenAsClassAndMethod(): void + { + $field = $this->field(new Column(type: 'string', typecast: 'Sub/Typecaster::cast')); + + Assert::same($field->getTypecast(), [SubTypecaster::class, 'cast']); + } + public function makesANullableColumnDefaultToNull(): void { $field = $this->field(new Column(type: 'string', nullable: true)); diff --git a/tests/Unit/EmbeddingsTest.php b/tests/Unit/EmbeddingsTest.php index 443bf8dd..dc0166d4 100644 --- a/tests/Unit/EmbeddingsTest.php +++ b/tests/Unit/EmbeddingsTest.php @@ -4,10 +4,15 @@ namespace Cycle\Annotated\Tests\Unit; +use Cycle\Annotated\Annotation\Embeddable; use Cycle\Annotated\Embeddings; use Cycle\Annotated\Exception\AnnotationException; +use Cycle\Annotated\Locator\Embedding; +use Cycle\Annotated\Locator\EmbeddingLocatorInterface; use Cycle\Annotated\Locator\TokenizerEmbeddingLocator; +use Cycle\Annotated\Tests\Fixtures\Configurator\Address as PostalAddress; use Cycle\Annotated\Tests\Fixtures\Fixtures29\Address; +use Cycle\Annotated\Tests\Fixtures\Locator\FailingPropertyReader; use Cycle\Database\Config\DatabaseConfig; use Cycle\Database\DatabaseManager; use Cycle\Schema\Registry; @@ -29,4 +34,20 @@ public function rejectsARelationInsideAnEmbeddable(): never $embeddings->run(new Registry(new DatabaseManager(new DatabaseConfig()))); } + + public function wrapsAnExceptionOfTheReader(): never + { + $previous = new \RuntimeException('broken', 42); + $locator = new class implements EmbeddingLocatorInterface { + public function getEmbeddings(): array + { + return [new Embedding(new Embeddable(), new \ReflectionClass(PostalAddress::class))]; + } + }; + $embeddings = new Embeddings($locator, new FailingPropertyReader($previous)); + + Expect::exception(AnnotationException::class)->withMessage('broken')->withCode(42)->withPrevious($previous); + + $embeddings->run(new Registry(new DatabaseManager(new DatabaseConfig()))); + } } diff --git a/tests/Unit/EntitiesTest.php b/tests/Unit/EntitiesTest.php new file mode 100644 index 00000000..68e47248 --- /dev/null +++ b/tests/Unit/EntitiesTest.php @@ -0,0 +1,34 @@ +run(new Registry(Memory::manager())); + + $keys = \iterator_to_array($registry->getEntity('order')->getForeignKeys(), false); + Assert::count($keys, 1); + Assert::same($keys[0]->getTarget(), 'customer'); + Assert::same($keys[0]->getInnerColumns(), ['customer_ref']); + Assert::same($keys[0]->getOuterColumns(), ['customer_id']); + } +} diff --git a/tests/Unit/MergeColumnsTest.php b/tests/Unit/MergeColumnsTest.php new file mode 100644 index 00000000..dc7f0e56 --- /dev/null +++ b/tests/Unit/MergeColumnsTest.php @@ -0,0 +1,54 @@ +subject($registry); + $entity->setMapper('Cycle\Annotated\Tests\Fixtures\Fixtures30\MissingMapper'); + $entity->setRepository(SubjectRepository::class); + + (new MergeColumns(new AttributeReader()))->run($registry); + + Assert::same($entity->getFields()->getNames(), ['fromRepository']); + } + + public function wrapsAnExceptionOfTheReader(): never + { + $registry = new Registry(Memory::manager()); + $this->subject($registry); + $previous = new \RuntimeException('broken', 42); + + Expect::exception(AnnotationException::class)->withMessage('broken')->withCode(42)->withPrevious($previous); + + (new MergeColumns(new FailingClassReader($previous)))->run($registry); + } + + private function subject(Registry $registry): Entity + { + $entity = (new Entity())->setRole('subject')->setClass(Subject::class); + $registry->register($entity); + $registry->linkTable($entity, null, 'subjects'); + + return $entity; + } +} diff --git a/tests/Unit/MergeIndexesTest.php b/tests/Unit/MergeIndexesTest.php new file mode 100644 index 00000000..404487d1 --- /dev/null +++ b/tests/Unit/MergeIndexesTest.php @@ -0,0 +1,57 @@ +subject($registry); + $entity->setMapper('Cycle\Annotated\Tests\Fixtures\Fixtures30\MissingMapper'); + $entity->setRepository(SubjectRepository::class); + $registry->getTableSchema($entity)->string('repository_column'); + + (new MergeIndexes(new AttributeReader()))->run($registry); + + $indexes = $registry->getTableSchema($entity)->getIndexes(); + Assert::count($indexes, 1); + Assert::same(\reset($indexes)->getColumns(), ['repository_column']); + } + + public function wrapsAnExceptionOfTheReader(): never + { + $registry = new Registry(Memory::manager()); + $this->subject($registry); + $previous = new \RuntimeException('broken', 42); + + Expect::exception(AnnotationException::class)->withMessage('broken')->withCode(42)->withPrevious($previous); + + (new MergeIndexes(new FailingClassReader($previous)))->run($registry); + } + + private function subject(Registry $registry): Entity + { + $entity = (new Entity())->setRole('subject')->setClass(Subject::class); + $registry->register($entity); + $registry->linkTable($entity, null, 'subjects'); + + return $entity; + } +} diff --git a/tests/Unit/TableInheritanceTest.php b/tests/Unit/TableInheritanceTest.php new file mode 100644 index 00000000..227707fd --- /dev/null +++ b/tests/Unit/TableInheritanceTest.php @@ -0,0 +1,110 @@ +entities(Animal::class, Dog::class); + + (new TableInheritance(new AttributeReader()))->run($registry); + + $id = $registry->getEntity('dog')->getFields()->get('id'); + Assert::same($id->getType(), 'bigInteger'); + Assert::true($id->isPrimary()); + Assert::false($registry->getEntity('dog')->getFields()->has('name')); + } + + public function rejectsAnOuterKeyTheParentDoesNotHave(): never + { + $registry = $this->entities(Animal::class, Cat::class); + + Expect::exception(WrongParentKeyColumnException::class); + + (new TableInheritance(new AttributeReader()))->run($registry); + } + + public function leavesAnUnknownInheritanceTypeToOtherGenerators(): void + { + $registry = $this->entities(Animal::class, Bird::class); + + (new TableInheritance(new AttributeReader()))->run($registry); + + $bird = $registry->getEntity('bird'); + Assert::null($bird->getInheritance()); + Assert::null($registry->getEntity('animal')->getInheritance()); + Assert::same($registry->getTable($bird), 'birds'); + } + + public function dropsFieldsOfASingleTableThatNoEntityOfTheHierarchyOwns(): void + { + $registry = $this->entities(Animal::class, Fish::class); + $animal = $registry->getEntity('animal'); + $animal->getFields()->set('foreign', (new Field())->setType('string')->setColumn('foreign')); + + (new TableInheritance(new AttributeReader()))->run($registry); + + Assert::false($animal->getFields()->has('foreign')); + Assert::true($animal->getFields()->has('name')); + } + + public function failsWhenTheParentEntityIsNotRegistered(): never + { + $registry = new Registry(Memory::manager()); + $animal = (new Entity())->setRole('animal')->setClass(Animal::class); + $registry->register($animal); + $registry->registerChildWithoutMerge($animal, (new Entity())->setRole('puppy')->setClass(Puppy::class)); + + Expect::exception(AnnotationException::class) + ->withMessage(\sprintf('The entity could not be found for the role `%s`.', Dog::class)); + + (new TableInheritance(new AttributeReader()))->run($registry); + } + + public function wrapsAnExceptionOfTheReader(): never + { + $registry = $this->entities(Animal::class, Dog::class); + $previous = new \RuntimeException('broken', 42); + + Expect::exception(AnnotationException::class)->withMessage('broken')->withCode(42)->withPrevious($previous); + + (new TableInheritance(new FailingClassReader($previous)))->run($registry); + } + + /** + * @param class-string ...$classes + */ + private function entities(string ...$classes): Registry + { + $reader = new AttributeReader(); + $registry = new Registry(Memory::manager()); + + return (new Entities(new TokenizerEntityLocator(new ClassList(...$classes), $reader), $reader))->run($registry); + } +}