diff --git a/src/Model/Behavior/TagBehavior.php b/src/Model/Behavior/TagBehavior.php index 2fe49cd..a48320c 100644 --- a/src/Model/Behavior/TagBehavior.php +++ b/src/Model/Behavior/TagBehavior.php @@ -5,6 +5,7 @@ use Cake\Event\Event; use Cake\ORM\Behavior; use Cake\ORM\Entity; +use Cake\ORM\Query; use Cake\ORM\Table; use Cake\ORM\TableRegistry; use Cake\Utility\Inflector; @@ -21,6 +22,7 @@ class TagBehavior extends Behavior 'delimiter' => ',', 'separator' => ':', 'namespace' => null, + 'finderField' => 'tag', 'tagsAlias' => 'Tags', 'tagsAssoc' => [ 'className' => 'Muffin/Tags.Tags', @@ -37,11 +39,14 @@ class TagBehavior extends Behavior 'taggedCounter' => ['tag_count' => [ 'conditions' => [] ]], + 'implementedFinders' => [ + 'tagged' => 'findByTag' + ], 'implementedEvents' => [ - 'Model.beforeMarshal' => 'beforeMarshal', + 'Model.beforeMarshal' => 'beforeMarshal' ], 'implementedMethods' => [ - 'normalizeTags' => 'normalizeTags', + 'normalizeTags' => 'normalizeTags' ], 'fkTableField' => 'fk_table' ]; @@ -87,6 +92,29 @@ public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $opti } } + /** + * Finder method + * usage $query->find('tagged', ['{finderField}' => 'example_tag' ] ); + * + * @param Query $query + * @param array $options + */ + public function findByTag(Query $query, array $options){ + + if(!empty($options[$this->config('finderField')])){ + $query->matching($this->config('tagsAlias'), function ($q) use ($options) { + return $q->where([ + 'OR' => [ + $this->config('tagsAlias').'.slug' => $options[$this->config('finderField')], + $this->config('tagsAlias').'.label' => $options[$this->config('finderField')] + ] + ] + ); + }); + } + + } + /** * Binds all required associations if an association of the same name has * not already been configured.