From ccaf1fc5bc38b57c9097c7bf3e097434e83063b6 Mon Sep 17 00:00:00 2001 From: Aldarien Date: Tue, 21 Jan 2020 12:05:21 -0300 Subject: [PATCH] Relationships --- common/Alias/Model.php | 6 ++++++ src/Relationship.php | 38 ++++++++++++++++++++++++++++++++------ 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/common/Alias/Model.php b/common/Alias/Model.php index db14079..29f1da7 100644 --- a/common/Alias/Model.php +++ b/common/Alias/Model.php @@ -143,4 +143,10 @@ abstract class Model extends BaseModel implements ModelInterface { public function jsonSerialize() { return $this->toArray(); } + + public function setRelationship(string $class_name): Relationship { + return (new Relationship) + ->setFactory($this->container->get('model')) + ->setStart($class_name); + } } diff --git a/src/Relationship.php b/src/Relationship.php index 707025c..740cfa3 100644 --- a/src/Relationship.php +++ b/src/Relationship.php @@ -8,26 +8,52 @@ class Relationship { protected $start; protected $nodes; - public function __construct(string $class_name) { - $this->setStart($class_name); + public function __construct(string $class_name = '') { + if ($class_name != '') { + $this->setStart($class_name); + } } - public function setStart(string $class_name) { + public function setStart(string $class_name): Relationship { $this->start = (object) [ 'class' => $class_name, 'table' => Model::getTable($class_name) ]; + return $this; } - public function addNode(RelationNode $node) { + protected $factory; + public function setFactory(ModelFactory $factory): Relationship { + $this->factory = $factory; + return $this; + } + public function with(string $from_class, string $from_key, string $to_class, string $to_key): Relationship { + $node = (new RelationNode()) + ->setSource($from_class, $from_key) + ->setDestination($to_class, $to_key); if ($this->nodes === null) { $this->nodes = []; } $this->nodes []= $node; + return $this; } - public function build(ModelFactory $factory): ModelFactory { + protected $condition; + public function setCondition(string $class_name, string $key, $value): Relationship { + $this->condition = (object) [ + 'class' => $class_name, + 'table' => Model::getTable($class_name), + 'key' => $key, + 'value' => $value + ]; + return $this; + } + public function build(): ModelFactory { $output = $factory->find($this->start->class); foreach ($this->nodes as $node) { - $output = $node->build($factory); + $output = $node->build($output); } + $output = $output->where([ + implode('.', [$this->condition->table, $this->condition->key]), + $this->condition->value + ]); return $output; } }