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

Add support for generated fields #95

Merged
merged 6 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
],
"require": {
"php": ">=8.1",
"cycle/orm": "^2.2.0",
"cycle/schema-builder": "^2.6",
"cycle/orm": "^2.7",
"cycle/schema-builder": "^2.8",
"spiral/attributes": "^2.8|^3.0",
"spiral/tokenizer": "^2.8|^3.0",
"doctrine/inflector": "^2.0"
Expand Down
30 changes: 30 additions & 0 deletions src/Annotation/Generated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Annotation;

use Cycle\Annotated\Enum\GeneratedType;
use Spiral\Attributes\NamedArgumentConstructor;

#[\Attribute(\Attribute::TARGET_PROPERTY)]
#[NamedArgumentConstructor]
class Generated
{
protected int $type = 0;

/**
* @param GeneratedType|int ...$type Generating type {@see GeneratedType}.
*/
public function __construct(GeneratedType|int ...$type)
{
foreach ($type as $value) {
$this->type |= $value instanceof GeneratedType ? $value->value : $value;
}
}

public function getType(): int
{
return $this->type;
}
}
30 changes: 29 additions & 1 deletion src/Configurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@
use Cycle\Annotated\Annotation\Embeddable;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\ForeignKey;
use Cycle\Annotated\Annotation\Generated;
use Cycle\Annotated\Annotation\Relation as RelationAnnotation;
use Cycle\Annotated\Enum\GeneratedType;
use Cycle\Annotated\Exception\AnnotationException;
use Cycle\Annotated\Exception\AnnotationRequiredArgumentsException;
use Cycle\Annotated\Exception\AnnotationWrongTypeArgumentException;
use Cycle\Annotated\Utils\EntityUtils;
use Cycle\Schema\Definition\Entity as EntitySchema;
use Cycle\Schema\Definition\ForeignKey as ForeignKeySchema;
use Cycle\Schema\Definition\Field;
use Cycle\Schema\Definition\ForeignKey as ForeignKeySchema;
use Cycle\Schema\Definition\Relation;
use Cycle\Schema\Generator\SyncTables;
use Cycle\Schema\SchemaModifierInterface;
Expand Down Expand Up @@ -232,6 +234,9 @@ public function initField(string $name, Column $column, \ReflectionClass $class,
$field->setColumn($columnName);

$field->setPrimary($column->isPrimary());
if ($this->isDbGeneratedField($field)) {
$field->setGenerated(GeneratedType::Db->value);
}

$field->setTypecast($this->resolveTypecast($column->getTypecast(), $class));

Expand Down Expand Up @@ -297,6 +302,20 @@ public function initForeignKeys(Entity $ann, EntitySchema $entity, \ReflectionCl
}
}

public function initGeneratedFields(EntitySchema $entity, \ReflectionClass $class): void
{
foreach ($class->getProperties() as $property) {
try {
$generated = $this->reader->firstPropertyMetadata($property, Generated::class);
if ($generated !== null) {
$entity->getFields()->get($property->getName())->setGenerated($generated->getType());
}
} catch (\Throwable $e) {
throw new AnnotationException($e->getMessage(), (int) $e->getCode(), $e);
}
}
}

/**
* Resolve class or role name relative to the current class.
*
Expand Down Expand Up @@ -386,4 +405,13 @@ private function getPropertyMetadata(\ReflectionProperty $property, string $name
throw new AnnotationException($e->getMessage(), (int) $e->getCode(), $e);
}
}

private function isDbGeneratedField(Field $field): bool
{
return $field->isPrimary()
|| $field->getType() === 'serial'
|| $field->getType() === 'smallserial'
|| $field->getType() === 'serial'
|| $field->getType() === 'bigserial';
roxblnfk marked this conversation as resolved.
Show resolved Hide resolved
}
}
3 changes: 3 additions & 0 deletions src/Entities.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ public function run(Registry $registry): Registry
continue;
}

// generated fields
$this->generator->initGeneratedFields($e, $entity->class);

// register entity (OR find parent)
$registry->register($e);

Expand Down
12 changes: 12 additions & 0 deletions src/Enum/GeneratedType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Enum;

enum GeneratedType: int
{
case Db = 1;
case PhpInsert = 2;
case PhpUpdate = 4;
}
29 changes: 29 additions & 0 deletions tests/Annotated/Fixtures/Fixtures25/Php82/WithGenerated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Fixtures\Fixtures25\Php82;

use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Generated;
use Cycle\Annotated\Enum\GeneratedType;

#[Entity(role: 'generatedFieldsEnumValue', table: 'generated_fields_enum_value')]
class WithGenerated
{
#[Column(type: 'primary')]
public int $id;

#[
Column(type: 'datetime', name: 'created_at'),
Generated(type: GeneratedType::PhpInsert->value)
]
public \DateTimeImmutable $createdAt;

#[
Column(type: 'datetime', name: 'updated_at'),
Generated(type: GeneratedType::PhpInsert->value | GeneratedType::PhpUpdate->value)
]
public \DateTimeImmutable $updatedAt;
}
24 changes: 24 additions & 0 deletions tests/Annotated/Fixtures/Fixtures25/PostgreSQL/WithSerial.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Fixtures\Fixtures25\PostgreSQL;

use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;

#[Entity(role: 'generatedFieldsSerial', table: 'generated_fields_serial')]
class WithSerial
{
#[Column(type: 'primary')]
public int $id;

#[Column(type: 'smallserial', name: 'small_serial')]
public int $smallSerial;

#[Column(type: 'serial')]
public int $serial;

#[Column(type: 'bigserial', name: 'big_serial')]
public int $bigSerial;
}
29 changes: 29 additions & 0 deletions tests/Annotated/Fixtures/Fixtures25/WithGeneratedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Fixtures\Fixtures25;

use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Generated;
use Cycle\Annotated\Enum\GeneratedType;

#[Entity(role: 'generatedFieldsEnum', table: 'generated_fields_enum')]
class WithGeneratedEnum
{
#[Column(type: 'primary')]
public int $id;

#[
Column(type: 'datetime', name: 'created_at'),
Generated(type: GeneratedType::PhpInsert)
]
public \DateTimeImmutable $createdAt;

#[
Column(type: 'datetime', name: 'updated_at'),
Generated(GeneratedType::PhpInsert, GeneratedType::PhpUpdate)
]
public \DateTimeImmutable $updatedAt;
}
28 changes: 28 additions & 0 deletions tests/Annotated/Fixtures/Fixtures25/WithGeneratedInt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Fixtures\Fixtures25;

use Cycle\Annotated\Annotation\Column;
use Cycle\Annotated\Annotation\Entity;
use Cycle\Annotated\Annotation\Generated;

#[Entity(role: 'generatedFieldsInt', table: 'generated_fields_int')]
class WithGeneratedInt
{
#[Column(type: 'primary')]
public int $id;

#[
Column(type: 'datetime', name: 'created_at'),
Generated(type: 2)
]
public \DateTimeImmutable $createdAt;

#[
Column(type: 'datetime', name: 'updated_at'),
Generated(type: 2 | 4)
]
public \DateTimeImmutable $updatedAt;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Functional\Driver\Common;

use Cycle\Annotated\Entities;
use Cycle\Annotated\Locator\TokenizerEntityLocator;
use Cycle\ORM\SchemaInterface;
use Cycle\Schema\Compiler;
use Cycle\Schema\Registry;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhp;
use Spiral\Attributes\AttributeReader;
use Spiral\Attributes\ReaderInterface;
use Spiral\Tokenizer\Config\TokenizerConfig;
use Spiral\Tokenizer\Tokenizer;

abstract class GeneratedFieldsTestCase extends BaseTestCase
{
protected readonly ReaderInterface $reader;

public function setUp(): void
{
$this->reader = new AttributeReader();

parent::setUp();
}

#[DataProvider('generatedFieldsDataProvider')]
public function testGeneratedFields(string $role): void
{
$tokenizer = new Tokenizer(new TokenizerConfig([
'directories' => [__DIR__ . '/../../../Fixtures/Fixtures25'],
'exclude' => ['Php82', 'PostgreSQL'],
]));

$locator = $tokenizer->classLocator();

$r = new Registry($this->dbal);
$schema = (new Compiler())->compile($r, [
new Entities(new TokenizerEntityLocator($locator, $this->reader), $this->reader),
]);

$this->assertSame(
[
'id' => SchemaInterface::GENERATED_DB,
'createdAt' => SchemaInterface::GENERATED_PHP_INSERT,
'updatedAt' => SchemaInterface::GENERATED_PHP_INSERT | SchemaInterface::GENERATED_PHP_UPDATE,
],
$schema[$role][SchemaInterface::GENERATED_FIELDS]
);
}

#[RequiresPhp('^8.2')]
public function testGeneratedFieldsEnumValues(): void
{
$tokenizer = new Tokenizer(new TokenizerConfig([
'directories' => [__DIR__ . '/../../../Fixtures/Fixtures25/Php82'],
'exclude' => [],
]));

$locator = $tokenizer->classLocator();

$r = new Registry($this->dbal);

$schema = (new Compiler())->compile($r, [
new Entities(new TokenizerEntityLocator($locator, $this->reader), $this->reader),
]);

$this->assertSame(
[
'id' => SchemaInterface::GENERATED_DB,
'createdAt' => SchemaInterface::GENERATED_PHP_INSERT,
'updatedAt' => SchemaInterface::GENERATED_PHP_INSERT | SchemaInterface::GENERATED_PHP_UPDATE,
],
$schema['generatedFieldsEnumValue'][SchemaInterface::GENERATED_FIELDS]
);
}

public static function generatedFieldsDataProvider(): \Traversable
{
yield ['generatedFieldsEnum'];
yield ['generatedFieldsInt'];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,9 @@ public function testSingleTableInheritanceWithDifferentColumnDeclaration(
],
SchemaInterface::SCHEMA => [],
SchemaInterface::TYPECAST_HANDLER => null,
SchemaInterface::GENERATED_FIELDS => [
'id' => SchemaInterface::GENERATED_DB,
],
],
$schema['comment']
);
Expand Down
16 changes: 16 additions & 0 deletions tests/Annotated/Functional/Driver/MySQL/GeneratedFieldsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Functional\Driver\MySQL;

// phpcs:ignore
use Cycle\Annotated\Tests\Functional\Driver\Common\GeneratedFieldsTestCase;
use PHPUnit\Framework\Attributes\Group;

#[Group('driver')]
#[Group('driver-mysql')]
final class GeneratedFieldsTest extends GeneratedFieldsTestCase
{
public const DRIVER = 'mysql';
}
Loading
Loading