Skip to content

Commit

Permalink
Better handling for model types
Browse files Browse the repository at this point in the history
  • Loading branch information
ronanchilvers committed Oct 11, 2019
1 parent 121d216 commit 5c33609
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/Features/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Ronanchilvers\Orm\Features\Type\ArrayHandler;
use Ronanchilvers\Orm\Features\Type\DateTimeHandler;
use Ronanchilvers\Orm\Features\Type\HandlerInterface;
use Ronanchilvers\Orm\Features\Type\ModelHandler;
use Ronanchilvers\Utility\Str;

/**
Expand Down Expand Up @@ -240,9 +241,12 @@ protected function getTypeHandler($type)
* @param string $attribute
* @author Ronan Chilvers <[email protected]>
*/
public function addType($type, $attribute)
public function addType($type, $attribute, array $options = [])
{
$this->types[$attribute] = $type;
$this->types[$attribute] = [
'type' => $type,
'options' => $options,
];
}

/**
Expand All @@ -257,7 +261,7 @@ protected function hasType($attribute)
if (!isset($this->types[$attribute])) {
return false;
}
$type = $this->types[$attribute];
$type = $this->types[$attribute]['type'];
if (!isset(self::$typeHandlers[$type])) {
return false;
}
Expand All @@ -279,10 +283,11 @@ protected function getAttributeToType(
if (is_null($value)) {
return $value;
}
$handler = self::getTypeHandler($this->types[$attribute]);
$handler = self::getTypeHandler($this->types[$attribute]['type']);

return $handler->toType(
$value
$value,
$this->types[$attribute]['options']
);
}

Expand All @@ -301,10 +306,11 @@ protected function getAttributeToRaw(
if (is_null($value)) {
return $value;
}
$handler = self::getTypeHandler($this->types[$attribute]);
$handler = self::getTypeHandler($this->types[$attribute]['type']);

return $handler->toRaw(
$value
$value,
$this->types[$attribute]['options']
);
}

Expand Down
14 changes: 14 additions & 0 deletions src/Features/Type/ModelHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ class ModelHandler implements HandlerInterface
*/
public function toType($raw, array $options = [])
{
if (array_key_exists('class', $options)) {
$class = $options['class'];
$finder = Orm::finder($class);

return $finder->one($raw);
}

return $raw;
}

Expand All @@ -32,6 +39,13 @@ public function toRaw($typeData, array $options = [])
if (!$typeData instanceof Model) {
return $typeData;
}
if (array_key_exists('class', $options)) {
$class = $options['class'];
} else {
$reflection = new ReflectionClass($typeData);
$class = $reflection->getName();
}
$primaryKey = $class::primaryKey();

return $typeData->getAttribute(
$typeData->primaryKey()
Expand Down

0 comments on commit 5c33609

Please sign in to comment.