├── phpstan.neon ├── ecs.php ├── src ├── translations │ └── en │ │ └── similar.php ├── behaviors │ └── CountBehavior.php ├── variables │ └── SimilarVariable.php ├── services │ ├── ServicesTrait.php │ └── Similar.php ├── icon.svg └── Similar.php ├── Makefile ├── LICENSE.md ├── CHANGELOG.md ├── composer.json └── README.md /phpstan.neon: -------------------------------------------------------------------------------- 1 | includes: 2 | - %currentWorkingDirectory%/vendor/craftcms/phpstan/phpstan.neon 3 | 4 | parameters: 5 | level: 5 6 | paths: 7 | - src 8 | -------------------------------------------------------------------------------- /ecs.php: -------------------------------------------------------------------------------- 1 | paths([ 8 | __DIR__ . '/src', 9 | __FILE__, 10 | ]); 11 | $ecsConfig->parallel(); 12 | $ecsConfig->sets([SetList::CRAFT_CMS_4]); 13 | }; 14 | -------------------------------------------------------------------------------- /src/translations/en/similar.php: -------------------------------------------------------------------------------- 1 | '{name} plugin loaded', 18 | ]; 19 | -------------------------------------------------------------------------------- /src/behaviors/CountBehavior.php: -------------------------------------------------------------------------------- 1 | similar->find($data); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) nystudio107.com 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Similar Changelog 2 | 3 | ## 5.0.4 - UNRELEASED 4 | ### Fixed 5 | * Fix `limit` being added to the element query *before* it has been sorted by `count`, fixes #57 ([#58](https://github.com/nystudio107/craft-similar/pull/58)) 6 | 7 | ## 5.0.3 - 2025.10.09 8 | ### Fixed 9 | * Fixed an issue where having empty elements or empty tags could cause an exception to be thrown, seemingly due to a change in Craft CMS ([#55](https://github.com/nystudio107/craft-similar/issues/55)) 10 | 11 | ## 5.0.2 - 2024.06.20 12 | ### Fixed 13 | * Fixed an issue where `toArray()` was done recursively on the passed in `$critera`, which turned objects into sub-arrays in `orderBy` and other properties, causing a DB error ([#51](https://github.com/nystudio107/craft-similar/issues/51)) ([#50](https://github.com/nystudio107/craft-similar/issues/50)) 14 | 15 | ## 5.0.1 - 2024.06.19 16 | ### Fixed 17 | * Filter out `OrderByPlaceholderExpression` expressions from the `orderBy` clause in the `ElementQuery` to prevent invalid SQL from being generated ([#51](https://github.com/nystudio107/craft-similar/issues/51)) ([#52](https://github.com/nystudio107/craft-similar/issues/52)) 18 | * Fixed a `SQLSTATE[42S22]: Column not found: 1054 Unknown column 'content.id' in 'group statement'` error on Craft 5 ([#51](https://github.com/nystudio107/craft-similar/issues/51)) 19 | 20 | ## 5.0.0 - 2024.04.28 21 | ### Added 22 | * Stable release for Craft CMS 5 23 | -------------------------------------------------------------------------------- /src/services/ServicesTrait.php: -------------------------------------------------------------------------------- 1 | [ 36 | 'similar' => SimilarService::class, 37 | ], 38 | ]; 39 | } 40 | 41 | // Public Methods 42 | // ========================================================================= 43 | 44 | /** 45 | * Returns the similar service 46 | * 47 | * @return SimilarService The similar service 48 | * @throws InvalidConfigException 49 | */ 50 | public function getSimilar(): SimilarService 51 | { 52 | return $this->get('similar'); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nystudio107/craft-similar", 3 | "description": "Similar for Craft lets you find elements, Entries, Categories, Commerce Products, etc, that are similar, based on... other related elements.", 4 | "type": "craft-plugin", 5 | "version": "5.0.4", 6 | "keywords": [ 7 | "craft", 8 | "cms", 9 | "craftcms", 10 | "craft-plugin", 11 | "elements", 12 | "relations", 13 | "similar" 14 | ], 15 | "support": { 16 | "docs": "https://nystudio107.com/docs/similar/", 17 | "issues": "https://nystudio107.com/plugins/similar/support", 18 | "source": "https://github.com/nystudio107/craft-similar" 19 | }, 20 | "license": "MIT", 21 | "authors": [ 22 | { 23 | "name": "nystudio107.com", 24 | "homepage": "https://nystudio107.com/" 25 | } 26 | ], 27 | "require": { 28 | "php": "^8.2", 29 | "craftcms/cms": "^5.0.0" 30 | }, 31 | "require-dev": { 32 | "craftcms/ecs": "dev-main", 33 | "craftcms/phpstan": "dev-main", 34 | "craftcms/rector": "dev-main" 35 | }, 36 | "scripts": { 37 | "phpstan": "phpstan --ansi --memory-limit=1G", 38 | "check-cs": "ecs check --ansi", 39 | "fix-cs": "ecs check --fix --ansi" 40 | }, 41 | "config": { 42 | "allow-plugins": { 43 | "craftcms/plugin-installer": true, 44 | "yiisoft/yii2-composer": true 45 | }, 46 | "optimize-autoloader": true, 47 | "sort-packages": true 48 | }, 49 | "autoload": { 50 | "psr-4": { 51 | "nystudio107\\similar\\": "src/" 52 | } 53 | }, 54 | "extra": { 55 | "class": "nystudio107\\similar\\Similar", 56 | "handle": "similar", 57 | "name": "Similar" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/nystudio107/craft-similar/badges/quality-score.png?b=v5)](https://scrutinizer-ci.com/g/nystudio107/craft-similar/?branch=v5) [![Code Coverage](https://scrutinizer-ci.com/g/nystudio107/craft-similar/badges/coverage.png?b=v5)](https://scrutinizer-ci.com/g/nystudio107/craft-similar/?branch=v5) [![Build Status](https://scrutinizer-ci.com/g/nystudio107/craft-similar/badges/build.png?b=v5)](https://scrutinizer-ci.com/g/nystudio107/craft-similar/build-status/v5) [![Code Intelligence Status](https://scrutinizer-ci.com/g/nystudio107/craft-similar/badges/code-intelligence.svg?b=v5)](https://scrutinizer-ci.com/code-intelligence) 2 | 3 | # Similar plugin for Craft CMS 5.x 4 | 5 | Similar for Craft lets you find elements, Entries, Categories, Commerce Products, etc, that are similar, based on... other related elements. 6 | 7 | ![Screenshot](./docs/docs/resources/img/plugin-logo.png) 8 | 9 | ## Requirements 10 | 11 | This plugin requires Craft CMS 5.0.0 or later. 12 | 13 | ## Installation 14 | 15 | To install the plugin, follow these instructions. 16 | 17 | 1. Open your terminal and go to your Craft project: 18 | 19 | cd /path/to/project 20 | 21 | 2. Then tell Composer to load the plugin: 22 | 23 | composer require nystudio107/craft-similar 24 | 25 | 3. Install the plugin via `./craft install/plugin similar` via the CLI, or in the Control Panel, go to Settings → Plugins and click the “Install” button for Similar. 26 | 27 | You can also install Similar via the **Plugin Store** in the Craft AdminCP. 28 | 29 | ## Documentation 30 | 31 | Click here -> [Similar Documentation](https://nystudio107.com/plugins/similar/documentation) 32 | 33 | ## Similar Roadmap 34 | 35 | Some things to do, and ideas for potential features: 36 | 37 | * Release it 38 | 39 | Brought to you by [nystudio107.com](https://nystudio107.com/) 40 | -------------------------------------------------------------------------------- /src/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 12 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/Similar.php: -------------------------------------------------------------------------------- 1 | sender; 80 | $variable->set('similar', SimilarVariable::class); 81 | } 82 | ); 83 | Event::on( 84 | ElementQuery::class, 85 | ElementQuery::EVENT_AFTER_POPULATE_ELEMENT, 86 | static function(PopulateElementEvent $event): void { 87 | /** @var Element $element */ 88 | $element = $event->element; 89 | $element->attachBehavior('myCountBehavior', CountBehavior::class); 90 | }); 91 | 92 | Craft::info( 93 | Craft::t( 94 | 'similar', 95 | '{name} plugin loaded', 96 | ['name' => $this->name] 97 | ), 98 | __METHOD__ 99 | ); 100 | } 101 | 102 | // Protected Methods 103 | // ========================================================================= 104 | } 105 | -------------------------------------------------------------------------------- /src/services/Similar.php: -------------------------------------------------------------------------------- 1 | toArray([], [], false); 80 | } 81 | 82 | // Get an ElementQuery for this Element 83 | $elementClass = is_object($element) ? $element::class : $element; 84 | 85 | // Stash limit and remove from criteria 86 | if (isset($criteria['limit'])) { 87 | $this->limit = $criteria['limit']; 88 | $criteria['limit'] = null; 89 | } 90 | 91 | /** @var EntryQuery $query */ 92 | $query = $this->getElementQuery($elementClass, $criteria); 93 | 94 | // Stash any orderBy directives from the $query for our anonymous function 95 | $this->preOrder = $query->orderBy ?? []; 96 | 97 | // Extract the $tagIds from the $context 98 | if (is_array($context)) { 99 | $tagIds = $context; 100 | } else { 101 | /** @var ElementQueryInterface $context */ 102 | $tagIds = $context->ids(); 103 | } 104 | 105 | $this->targetElements = $tagIds; 106 | 107 | // We need to modify the actual craft\db\Query after the ElementQuery has been prepared 108 | $query->on(ElementQuery::EVENT_AFTER_PREPARE, fn(CancelableEvent $event) => $this->eventAfterPrepareHandler($event)); 109 | // Return the data as an array, and only fetch the `id` and `siteId` 110 | $query->asArray(true); 111 | $query->select(['elements.id', 'elements_sites.siteId']); 112 | $query->andWhere(['not', ['elements.id' => $element->getId()]]); 113 | 114 | // Unless site criteria is provided, force the element's site. 115 | if (empty($criteria['siteId']) && empty($criteria['site'])) { 116 | $query->andWhere(['elements_sites.siteId' => $element->siteId]); 117 | } 118 | 119 | // If no tags are provided, skip this and assume all elements are similar 120 | if ($tagIds) { 121 | $query->andWhere(['in', 'relations.targetId', $tagIds]); 122 | } 123 | 124 | $query->leftJoin(['relations' => Table::RELATIONS], '[[elements.id]] = [[relations.sourceId]]'); 125 | 126 | $results = $query->all(); 127 | 128 | 129 | // Fetch the elements based on the returned `id` and `siteId` 130 | $queryConditions = []; 131 | $similarCounts = []; 132 | 133 | // Build the query conditions for a new element query. 134 | // The reason we have to do it in two steps is because the `count` property is added by a behavior after element creation 135 | // So if we just try to tack that on in the original query, it will throw an error on element creation 136 | foreach ($results as $config) { 137 | $siteId = $config['siteId']; 138 | $elementId = $config['id']; 139 | 140 | if ($elementId && $siteId) { 141 | if (empty($queryConditions[$siteId])) { 142 | $queryConditions[$siteId] = []; 143 | } 144 | 145 | // Write down elements per site and similar counts 146 | $queryConditions[$siteId][] = $elementId; 147 | $key = $siteId . '-' . $elementId; 148 | $similarCounts[$key] = $config['count']; 149 | } 150 | } 151 | 152 | if (empty($results)) { 153 | return []; 154 | } 155 | 156 | // Fetch all the elements in one fell swoop, including any preset eager-loaded conditions 157 | $query = $this->getElementQuery($elementClass, $criteria); 158 | 159 | // Make sure we fetch the elements that are similar only 160 | $query->on(ElementQuery::EVENT_AFTER_PREPARE, function(CancelableEvent $event) use ($queryConditions): void { 161 | /** @var ElementQuery $query */ 162 | $query = $event->sender; 163 | $first = true; 164 | 165 | foreach ($queryConditions as $siteId => $elementIds) { 166 | $method = $first ? 'where' : 'orWhere'; 167 | $first = false; 168 | $query->subQuery->$method(['and', [ 169 | 'elements_sites.siteId' => $siteId, 170 | 'elements.id' => $elementIds, ], 171 | ]); 172 | } 173 | }); 174 | 175 | $elements = $query->all(); 176 | 177 | 178 | /** @var Element $element */ 179 | foreach ($elements as $element) { 180 | // The `count` property is added dynamically by our CountBehavior behavior 181 | $key = $element->siteId . '-' . $element->id; 182 | if (!empty($similarCounts[$key])) { 183 | /** @phpstan-ignore-next-line */ 184 | $element->count = $similarCounts[$key]; 185 | } 186 | } 187 | 188 | if (empty($criteria['orderBy'])) { 189 | /** @phpstan-ignore-next-line */ 190 | usort($elements, static fn($a, $b) => $a->count < $b->count ? 1 : ($a->count == $b->count ? 0 : -1)); 191 | } 192 | if ($this->limit) { 193 | $elements = array_slice($elements, 0, $this->limit); 194 | } 195 | 196 | return $elements; 197 | } 198 | 199 | protected function eventAfterPrepareHandler(CancelableEvent $event): void 200 | { 201 | /** @var ElementQuery $query */ 202 | $query = $event->sender; 203 | // Add in the `count` param so we know how many were fetched 204 | $query->query->addSelect(['COUNT(*) as count']); 205 | if (is_array($this->preOrder)) { 206 | $this->preOrder = array_filter($this->preOrder, fn($value) => !$value instanceof OrderByPlaceholderExpression); 207 | $query->query->orderBy(array_merge([ 208 | 'count' => 'DESC', 209 | ], $this->preOrder)); 210 | } elseif (is_string($this->preOrder)) { 211 | $query->query->orderBy('count DESC, ' . str_replace('`', '', $this->preOrder)); 212 | } 213 | 214 | $query->query->groupBy(['relations.sourceId', 'elements.id', 'elements_sites.siteId']); 215 | 216 | // If targetElements are provided, filter by them, otherwise get anything that matches criteria 217 | if ($this->targetElements) { 218 | $query->query->andWhere(['in', 'relations.targetId', $this->targetElements]); 219 | } 220 | 221 | $query->subQuery->limit(null); // inner limit to null -> fetch all possible entries, sort them afterwards 222 | 223 | $query->subQuery->groupBy(['elements.id', 'elements_sites.id']); 224 | 225 | if ($query instanceof EntryQuery) { 226 | $query->subQuery->addGroupBy(['entries.postDate']); 227 | } 228 | 229 | if ($query->withStructure || ($query->withStructure !== false && $query->structureId)) { 230 | $query->subQuery->addGroupBy(['structureelements.structureId', 'structureelements.lft']); 231 | } 232 | 233 | $event->isValid = true; 234 | } 235 | 236 | /** 237 | * Returns the element query based on $elementType and $criteria 238 | * 239 | * @param string|ElementInterface $elementType 240 | * @param array $criteria 241 | * @return ElementQueryInterface 242 | */ 243 | protected function getElementQuery(string|ElementInterface $elementType, array $criteria): ElementQueryInterface 244 | { 245 | /** @var string|ElementInterface $elementType */ 246 | $query = $elementType::find(); 247 | Craft::configure($query, $criteria); 248 | 249 | return $query; 250 | } 251 | } 252 | --------------------------------------------------------------------------------