ulmus/src/Migration/FieldDefinition.php

131 lines
3.4 KiB
PHP

<?php
namespace Ulmus\Migration;
use Notes\Common\ReflectedProperty;
use Ulmus\Adapter\AdapterInterface;
use Ulmus\Annotation\Property\Field;
use Ulmus\Attribute;
use Ulmus\Entity;
class FieldDefinition {
public bool $nullable;
public bool $builtIn;
public string $name;
public string $type;
public array $tags;
public mixed $default;
public ? int $precision;
public null|int|string $length;
public ? string $update;
public AdapterInterface $adapter;
public function __construct(AdapterInterface $adapter, ReflectedProperty $data)
{
$this->adapter = $adapter;
# Patch coming soon
$type = $data->getTypes()[0];
$this->name = $data->name;
$this->builtIn = $type->builtIn;
$this->tags = $data->getAttributes();
if (isset($data->value)) {
$this->default = $data->value;
}
$field = $this->getFieldTag();
$adapter->whitelistAttributes($field->attributes);
$this->type = $field->type ?? $type->type;
$this->length = $field->length ?? null;
$this->precision = $field->precision ?? null;
$this->nullable = $data->allowsNull() ?: $field->nullable;
$this->update = $field->attributes['update'] ?? null;
}
public function getSqlName() : string
{
return $this->getColumnName();
}
public function getSqlType(bool $typeOnly = false) : string
{
return $this->adapter->mapFieldType($this, $typeOnly);
}
public function getSqlParams() : string
{
$default = $this->getDefault();
$syntax = $this->adapter->tableSyntax();
return implode(' ', array_filter([
$this->isUnsigned() ? $syntax['unsigned'] : null,
$this->nullable ? "NULL" : "NOT NULL",
$this->update ? "ON UPDATE {$this->update}" : null,
$default !== null ? "DEFAULT $default" : null,
$this->isPrimaryKey() ? $syntax['pk'] : null,
$this->isAutoIncrement() ? $syntax['ai'] : null,
]));
}
public function getFieldTag() : Attribute\Property\Field|null
{
$field = array_filter($this->tags, fn($item) => $item->object instanceof Attribute\Property\Field);
return array_pop($field)->object;
}
public function getColumnName() : ? string
{
return $this->getFieldTag()->name ?? $this->name;
}
public function getDefault() : mixed
{
if (isset($this->default)) {
$value = $this->adapter->writableValue($this->default);
if (is_string($value) ) {
$value = $this->adapter->escapeIdentifier($value, AdapterInterface::IDENTIFIER_VALUE);
}
return $value;
}
# Fallback on attribute's default value
return $this->getFieldTag()->default ?? ( $this->nullable ? "NULL" : null ) ;
}
public function isPrimaryKey() : bool
{
return $this->getFieldTag()->attributes['primary_key'] ?? false;
}
public function isAutoIncrement() : bool
{
return $this->getFieldTag()->attributes['auto_increment'] ?? false;
}
public function isUnique() : bool
{
return $this->getFieldTag()->attributes['unique'] ?? false;
}
public function isUnsigned() : bool
{
return $this->getFieldTag()->attributes['unsigned'] ?? false;
}
}