ulmus/src/EntityTrait.php

83 lines
2.1 KiB
PHP
Raw Normal View History

2019-08-21 20:13:00 +00:00
<?php
namespace Ulmus;
use Ulmus\Repository,
Ulmus\Common\EntityResolver,
Ulmus\Common\EntityField;
use Ulmus\Annotation\Classes\{ Method, Table, Collation as Test, };
use Ulmus\Annotation\Property\{ Field, Relation, OrderBy, Where, };
use Ulmus\Annotation\Property\Field\{ Id, ForeignKey, CreatedAt, UpdatedAt, };
trait EntityTrait {
public function entityFillFromDataset($dataset) : self
{
$fields = Ulmus::resolveEntity(static::class);
foreach($dataset as $key => $value) {
if ( null === $field = $fields->field($key, EntityResolver::KEY_COLUMN_NAME) ?? null ) {
throw new \Exception("Field `$key` can not be found within your entity ".static::class);
}
if ( is_null($value) ) {
$this->{$field['name']} = null;
}
elseif ( $field['type'] === 'array' ) {
$this->{$field['name']} = substr($value, 0, 1) === "a" ? unserialize($value) : json_decode($value, true);
}
elseif ( EntityField::isScalarType($field['type']) ) {
$this->{$field['name']} = $value;
}
elseif ( EntityField::isObjectType($field['type']) ) {
$this->{$field['name']} = new $field['type']();
}
}
return $this;
}
/**
* @Ignore
*/
public static function repository() : Repository
{
return Ulmus::repository(static::class);
}
/**
* @Ignore
*/
public static function queryBuilder() : QueryBuilder
{
return Ulmus::queryBuilder(static::class);
}
/**
* @Ignore
*/
public static function field($name, ? string $alias = null)
{
return new EntityField(static::class, $name, $alias ?: Repository::DEFAULT_ALIAS);
}
/**
* @Ignore
*/
public static function fields(...$fields)
{
return implode(', ', array_map(function($name) {
return static::field($name);
}, $fields));
}
/**
* @Ignore
*/
public static function table()
{
return "REFLECT TABLE";
}
}