|
| 1 | +<?php |
| 2 | +namespace App\ServiceCollection\Cms; |
| 3 | + |
| 4 | +use App\Entity\Cms\Tag as TagEntity; |
| 5 | +use App\Service\Cms\TagEditor; |
| 6 | +use App\Service\User; |
| 7 | + |
| 8 | + |
| 9 | +class TagEditorCollection extends TagCollection |
| 10 | +{ |
| 11 | + public function setFromIdsAndTags($arrIdsAndTags, User $author) : static |
| 12 | + { |
| 13 | + $this->clear(); |
| 14 | + |
| 15 | + if( empty($arrIdsAndTags) ) { |
| 16 | + return $this; |
| 17 | + } |
| 18 | + |
| 19 | + $arrIdsToLoad = array_column($arrIdsAndTags, 'id'); |
| 20 | + |
| 21 | + if( empty($arrIdsToLoad) ) { |
| 22 | + return $this; |
| 23 | + } |
| 24 | + |
| 25 | + $arrExistingTagEntities = $this->getRepository()->getById($arrIdsToLoad); |
| 26 | + |
| 27 | + $arrUniqueTagLabels = []; |
| 28 | + foreach($arrIdsAndTags as $item) { |
| 29 | + |
| 30 | + if( !array_key_exists('id', $item) || !array_key_exists('title', $item) ) { |
| 31 | + continue; |
| 32 | + } |
| 33 | + |
| 34 | + $tagId = $item["id"]; |
| 35 | + |
| 36 | + if( !empty($tagId) && array_key_exists($tagId, $this->arrData) ) { |
| 37 | + continue; |
| 38 | + } |
| 39 | + |
| 40 | + $existingTagEntity = $arrExistingTagEntities[$tagId] ?? null; |
| 41 | + |
| 42 | + if( empty($existingTagEntity) ) { |
| 43 | + |
| 44 | + $newTag = |
| 45 | + $this->createService() |
| 46 | + ->setTitle($item["title"]) |
| 47 | + ->addAuthor($author); |
| 48 | + |
| 49 | + if( $this->isTagLabelAlreadyInSet($newTag, $arrUniqueTagLabels) ) { |
| 50 | + continue; |
| 51 | + } |
| 52 | + |
| 53 | + $newTag->save(); |
| 54 | + |
| 55 | + $newTagId = (string)$newTag->getId(); |
| 56 | + $this->arrData[$newTagId] = $newTag; |
| 57 | + |
| 58 | + } else { |
| 59 | + |
| 60 | + $tag = $this->createService($existingTagEntity); |
| 61 | + |
| 62 | + if( $this->isTagLabelAlreadyInSet($tag, $arrUniqueTagLabels) ) { |
| 63 | + continue; |
| 64 | + } |
| 65 | + |
| 66 | + $this->arrData[$tagId] = $tag; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return $this; |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | + protected function isTagLabelAlreadyInSet(TagEditor $tag, array &$arrUniqueTagLabels) : bool |
| 75 | + { |
| 76 | + $title = $tag->getTitleComparable(); |
| 77 | + |
| 78 | + if( in_array($title, $arrUniqueTagLabels) ) { |
| 79 | + return true; |
| 80 | + } |
| 81 | + |
| 82 | + $arrUniqueTagLabels[] = $title; |
| 83 | + |
| 84 | + return false; |
| 85 | + } |
| 86 | + |
| 87 | + |
| 88 | + public function createService(?TagEntity $entity = null) : TagEditor |
| 89 | + { |
| 90 | + return $this->factory->createTagEditor($entity); |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | +} |
0 commit comments