|
3 | 3 |
|
4 | 4 | namespace App\Model\Table; |
5 | 5 |
|
| 6 | +use ArrayObject; |
| 7 | +use Cake\Event\EventInterface; |
| 8 | +use Cake\ORM\Query\SelectQuery; |
6 | 9 | use Cake\ORM\RulesChecker; |
7 | 10 | use Cake\ORM\Table; |
8 | 11 | use Cake\Validation\Validator; |
@@ -106,4 +109,72 @@ public function buildRules(RulesChecker $rules): RulesChecker |
106 | 109 |
|
107 | 110 | return $rules; |
108 | 111 | } |
| 112 | + |
| 113 | + public function beforeSave(EventInterface $event, $entity, ArrayObject $options) |
| 114 | + { |
| 115 | + if ($entity->tag_string) { |
| 116 | + $entity->tags = $this->_buildTags($entity->tag_string); |
| 117 | + } |
| 118 | + |
| 119 | + // Other code |
| 120 | + } |
| 121 | + |
| 122 | + protected function _buildTags($tagString) |
| 123 | + { |
| 124 | + // Trim tags |
| 125 | + $newTags = array_map('trim', explode(',', $tagString)); |
| 126 | + // Remove all empty tags |
| 127 | + $newTags = array_filter($newTags); |
| 128 | + // Reduce duplicated tags |
| 129 | + $newTags = array_unique($newTags); |
| 130 | + |
| 131 | + $out = []; |
| 132 | + $tags = $this->Tags->find() |
| 133 | + ->where(['Tags.title IN' => $newTags]) |
| 134 | + ->all(); |
| 135 | + |
| 136 | + // Remove existing tags from the list of new tags. |
| 137 | + foreach ($tags->extract('title') as $existing) { |
| 138 | + $index = array_search($existing, $newTags); |
| 139 | + if ($index !== false) { |
| 140 | + unset($newTags[$index]); |
| 141 | + } |
| 142 | + } |
| 143 | + // Add existing tags. |
| 144 | + foreach ($tags as $tag) { |
| 145 | + $out[] = $tag; |
| 146 | + } |
| 147 | + // Add new tags. |
| 148 | + foreach ($newTags as $tag) { |
| 149 | + $out[] = $this->Tags->newEntity(['title' => $tag]); |
| 150 | + } |
| 151 | + return $out; |
| 152 | + } |
| 153 | + |
| 154 | + // The $query argument is a query builder instance. |
| 155 | + // The $options array will contain the 'tags' option we passed |
| 156 | + // to find('tagged') in our controller action. |
| 157 | + public function findTagged(SelectQuery $query, array $tags = []): SelectQuery |
| 158 | + { |
| 159 | + $columns = [ |
| 160 | + 'Articles.id', 'Articles.user_id', 'Articles.title', |
| 161 | + 'Articles.body', 'Articles.published', 'Articles.created', |
| 162 | + 'Articles.slug', |
| 163 | + ]; |
| 164 | + $query = $query |
| 165 | + ->select($columns) |
| 166 | + ->distinct($columns); |
| 167 | + |
| 168 | + if (empty($tags)) { |
| 169 | + // If there are no tags provided, find articles that have no tags. |
| 170 | + $query->leftJoinWith('Tags') |
| 171 | + ->where(['Tags.title IS' => null]); |
| 172 | + } else { |
| 173 | + // Find articles that have one or more of the provided tags. |
| 174 | + $query->innerJoinWith('Tags') |
| 175 | + ->where(['Tags.title IN' => $tags]); |
| 176 | + } |
| 177 | + |
| 178 | + return $query->groupBy(['Articles.id']); |
| 179 | + } |
109 | 180 | } |
0 commit comments