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

feat: column type by ReflectionProperty #51

Open
wants to merge 4 commits into
base: 3.x
Choose a base branch
from
Open
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
16 changes: 13 additions & 3 deletions src/Annotation/Column.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
final class Column
{
private bool $hasDefault = false;
private bool $hasNullable = false;

/**
* @param non-empty-string $type Column type. {@see \Cycle\Database\Schema\AbstractColumn::$mapping}
Expand All @@ -41,18 +42,22 @@ public function __construct(
'string', 'text', 'tinyText', 'longText', 'double', 'float', 'decimal', 'datetime', 'date', 'time',
'timestamp', 'binary', 'tinyBinary', 'longBinary', 'json',
])]
private string $type,
private ?string $type = null,
private ?string $name = null,
private ?string $property = null,
private bool $primary = false,
private bool $nullable = false,
private ?bool $nullable = null,
private mixed $default = null,
private mixed $typecast = null,
private bool $castDefault = false,
) {
if ($default !== null) {
$this->hasDefault = true;
}

if ($this->nullable !== null) {
$this->hasNullable = true;
}
}

public function getType(): ?string
Expand All @@ -72,7 +77,7 @@ public function getProperty(): ?string

public function isNullable(): bool
{
return $this->nullable;
return $this->nullable === true;
}

public function isPrimary(): bool
Expand All @@ -85,6 +90,11 @@ public function hasDefault(): bool
return $this->hasDefault;
}

public function hasNullable(): bool
{
return $this->hasNullable;
}

public function getDefault(): mixed
{
return $this->default;
Expand Down
54 changes: 42 additions & 12 deletions src/Configurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Doctrine\Inflector\Rules\English\InflectorFactory;
use Exception;
use Spiral\Attributes\ReaderInterface;
use function is_subclass_of;

final class Configurator
{
Expand Down Expand Up @@ -101,7 +102,7 @@ public function initFields(EntitySchema $entity, \ReflectionClass $class, string
continue;
}

$field = $this->initField($property->getName(), $column, $class, $columnPrefix);
$field = $this->initField($property, $column, $class, $columnPrefix);
$field->setEntityClass($property->getDeclaringClass()->getName());
$entity->getFields()->set($property->getName(), $field);
}
Expand Down Expand Up @@ -208,35 +209,64 @@ public function initColumns(EntitySchema $entity, array $columns, \ReflectionCla
);
}

if ($column->getType() === null) {
throw new AnnotationException(
"Column type definition is required on `{$entity->getClass()}`.`{$columnName}`"
);
}

$field = $this->initField($columnName, $column, $class, '');
$field->setEntityClass($entity->getClass());
$entity->getFields()->set($propertyName, $field);
}
}

public function initField(string $name, Column $column, \ReflectionClass $class, string $columnPrefix): Field
public function initField(string|\ReflectionProperty $nameOrProperty, Column $column, \ReflectionClass $class, string $columnPrefix): Field
{
$type = $column->getType();
$isNullable = $column->hasNullable() ? $column->isNullable() : null;
$hasDefault = $column->hasDefault();
$default = $column->getDefault();

if ($nameOrProperty instanceof \ReflectionProperty) {
$name = ($property = $nameOrProperty)->getName();
$propertyType = $property->getType();

if ($property->hasDefaultValue() && !$hasDefault) {
$hasDefault = true;
$default = $property->getDefaultValue();
}

if ($propertyType instanceof \ReflectionType) {
$isNullable ??= $propertyType->allowsNull();

if ($propertyType instanceof \ReflectionNamedType) {
if ($propertyType->isBuiltin()) {
$type ??= $propertyType->getName();
} elseif (is_subclass_of($propertyType->getName(), \DateTimeInterface::class)) {
$type = 'datetime';
}
}
}
} else {
$name = $nameOrProperty;
}

if ($type === null) {
throw new AnnotationException(
"Column type definition is required on `{$class->getName()}`.`{$name}`"
);
}

$field = new Field();

$field->setType($column->getType());
$field->setType($type);
$field->setColumn($columnPrefix . ($column->getColumn() ?? $this->inflector->tableize($name)));
$field->setPrimary($column->isPrimary());

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

if ($column->isNullable()) {
if ($isNullable) {
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_NULLABLE, true);
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_DEFAULT, null);
}

if ($column->hasDefault()) {
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_DEFAULT, $column->getDefault());
if ($hasDefault) {
$field->getOptions()->set(\Cycle\Schema\Table\Column::OPT_DEFAULT, $default);
}

if ($column->castDefault()) {
Expand Down
33 changes: 33 additions & 0 deletions tests/Annotated/Fixtures/Fixtures1/SomeEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Fixtures\Fixtures1;

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

/** * @Entity(table="SomeEntity") */
#[Entity(table: "SomeEntity")]
class SomeEntity implements LabelledInterface
{
/** @Column(type="primary") */
#[Column(type: "primary")]
public $id;

/** @Column */
#[Column]
public int $idificator;

/** @Column */
#[Column]
public ?string $nullableString;

/** @Column */
#[Column]
public ?string $nullableStringWithDefault = "123";

/** @Column */
#[Column]
public \DateTimeImmutable $dateTime;
}
17 changes: 17 additions & 0 deletions tests/Annotated/Fixtures/Fixtures1/WithColumnInEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Cycle\Annotated\Tests\Fixtures\Fixtures1;

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

/** * @Entity(table="WithColumnInEntity", columns={@Column(name="columnDeclaredInEntity", type="integer")}) */
class WithColumnInEntity implements LabelledInterface
{
/** @Column(type="primary") */
public $id;

public $columnDeclaredInEntity = 123;
}
39 changes: 39 additions & 0 deletions tests/Annotated/Functional/Driver/Common/GeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@
use Cycle\Annotated\Tests\Fixtures\Fixtures1\Constrain\SomeConstrain;
use Cycle\Annotated\Tests\Fixtures\Fixtures1\Repository\CompleteRepository;
use Cycle\Annotated\Tests\Fixtures\Fixtures1\Simple;
use Cycle\Annotated\Tests\Fixtures\Fixtures1\SomeEntity;
use Cycle\Annotated\Tests\Fixtures\Fixtures1\Source\TestSource;
use Cycle\Annotated\Tests\Fixtures\Fixtures1\WithColumnInEntity;
use Cycle\Annotated\Tests\Fixtures\Fixtures1\WithTable;
use Cycle\Schema\Generator\RenderTables;
use Cycle\Schema\Generator\SyncTables;
use Cycle\Schema\Registry;
use Cycle\Schema\Table\Column;
use Doctrine\Common\Annotations\AnnotationReader as DoctrineAnnotationReader;
use Spiral\Attributes\AnnotationReader;
use Spiral\Attributes\AttributeReader;
Expand Down Expand Up @@ -151,4 +154,40 @@ public function testCompleteSchema(ReaderInterface $reader): void

$this->assertFalse($r->getEntity('eComplete')->getFields()->has('ignored'));
}

/**
* @dataProvider allReadersProvider
*/
public function testSimpleReferredSchema(ReaderInterface $reader): void
{
$r = new Registry($this->dbal);
(new Entities($this->locator, $reader))->run($r);

$fields = $r->getEntity(SomeEntity::class)->getFields();

$this->assertSame('int', $fields->get('idificator')->getType());
$this->assertFalse($fields->get('idificator')->getOptions()->has(Column::OPT_NULLABLE));
$this->assertFalse($fields->get('idificator')->getOptions()->has(Column::OPT_DEFAULT));

$this->assertSame('string', $fields->get('nullableString')->getType());
$this->assertSame(true, $fields->get('nullableString')->getOptions()->get(Column::OPT_NULLABLE));
$this->assertSame(null, $fields->get('nullableString')->getOptions()->get(Column::OPT_DEFAULT));

$this->assertSame('string', $fields->get('nullableStringWithDefault')->getType());
$this->assertSame(true, $fields->get('nullableStringWithDefault')->getOptions()->get(Column::OPT_NULLABLE));
$this->assertSame('123', $fields->get('nullableStringWithDefault')->getOptions()->get(Column::OPT_DEFAULT));

$this->assertSame('datetime', $fields->get('dateTime')->getType());
}

public function testSimpleReferredSchemaWithColumnInEntity(): void
{
$reader = new AnnotationReader();
$r = new Registry($this->dbal);
(new Entities($this->locator, $reader))->run($r);

$fields = $r->getEntity(WithColumnInEntity::class)->getFields();

$this->assertFalse($fields->get('columnDeclaredInEntity')->getOptions()->has(Column::OPT_DEFAULT));
}
}
2 changes: 1 addition & 1 deletion tests/Annotated/Functional/Driver/Common/InvalidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function testNotDefinedColumnTypeShouldThrowAnException(ReaderInterface $
{
$this->expectException(AnnotationException::class);
$this->expectErrorMessage(
'Some of required arguments [`type`] is missed on `Cycle\Annotated\Tests\Fixtures\Fixtures4\User.id.`'
'Column type definition is required on `Cycle\Annotated\Tests\Fixtures\Fixtures4\User`.`id`'
);

$tokenizer = new Tokenizer(new TokenizerConfig([
Expand Down