Skip to content

Commit

Permalink
Initial implementation for find('path')
Browse files Browse the repository at this point in the history
  • Loading branch information
lorenzo committed Mar 29, 2014
1 parent 932a591 commit 094321f
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/Model/Behavior/TreeBehavior.php
Expand Up @@ -39,6 +39,7 @@ class TreeBehavior extends Behavior {
* @var array
*/
protected static $_defaultConfig = [
'implementedFinders' => ['path' => 'findPath'],
'parent' => 'parent_id',
'left' => 'lft',
'right' => 'rght',
Expand All @@ -56,9 +57,39 @@ public function __construct(Table $table, array $config = []) {
$this->_table = $table;
}

public function beforeSave(Event $event, $entity) {
public function findPath($query, $options) {
if (empty($options['for'])) {
throw new \InvalidArgumentException("The 'for' key is required for find('path')");
}

$config = $this->config();
list($left, $right) = [$config['left'], $config['right']];
$node = $this->_table->get($options['for'], ['fields' => [$left, $right]]);

return $this->_scope($query)
->where([
"$left <=" => $entity->get($left),
"$right >=" => $entity->get($right)
]);
}

protected function _scope($query) {
$config = $this->config();

if (empty($config['scope'])) {
return $query;
}

if (!is_string($config['scope'])) {
return $query->where($config['scope']);
}

$association = $this->_table->association($query['scope']);
if (!$association) {
throw new \InvalidArgumentException("Invalid association name for 'scope'");
}

return $query->matching($association->name());
}

}

0 comments on commit 094321f

Please sign in to comment.