Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class RebuildArticleCategoryIndex
- {
- /**
- * Clears the Category Assigment for the Article and rebuilds the Category Assignment Index
- */
- public function rebuildArticleCategories($articleId, array $categoryIds)
- {
- $this->clearArticleCategoryAssignment($articleId);
- foreach ($categoryIds as $categoryId) {
- $this->rebuildArticleCategoryAssignment($articleId, $categoryId);
- }
- }
- /**
- * @param int $articleId
- */
- public function clearArticleCategoryAssignment($articleId)
- {
- $clearQuery = 'DELETE FROM s_articles_categories_ro WHERE `articleID` = ' . $articleId;
- try {
- Shopware()->Models()->getConnection()->executeQuery($clearQuery);
- } catch (DBALException $e) {
- }
- }
- /**
- * Inserts missing assignments in s_articles_categories_ro
- *
- *
- * @param int $articleId
- * @param int $categoryId
- *
- * @return int
- */
- public function rebuildArticleCategoryAssignment($articleId, $categoryId)
- {
- $count = 0;
- $parents = $this->getParentCategoryIds($categoryId);
- if (empty($parents)) {
- return $count;
- }
- $selectSql = '
- SELECT id
- FROM s_articles_categories_ro
- WHERE categoryID = :categoryId
- AND articleID = :articleId
- AND parentCategoryId = :parentCategoryId
- ';
- /** @var \Enlight_Components_Db_Adapter_Pdo_Mysql $db */
- $db = Shopware()->Container()->get('shopware.db');
- $selectStmt = $db->prepare($selectSql);
- $insertSql = 'INSERT INTO s_articles_categories_ro (articleID, categoryID, parentCategoryID) VALUES (:articleId, :categoryId, :parentCategoryId)';
- $insertStmt = $db->prepare($insertSql);
- foreach ($parents as $parentId) {
- $selectStmt->execute([
- ':articleId' => $articleId,
- ':categoryId' => $parentId,
- ':parentCategoryId' => $categoryId,
- ]);
- if ($selectStmt->fetchColumn() === false) {
- ++$count;
- $insertStmt->execute([
- ':articleId' => $articleId,
- ':categoryId' => $parentId,
- ':parentCategoryId' => $categoryId,
- ]);
- }
- }
- return $count;
- }
- /**
- * Returns an array of all categoryIds the given $id has as parent
- *
- * Example:
- * $id = 9
- *
- * <code>
- * Array
- * (
- * [0] => 9
- * [1] => 5
- * [2] => 10
- * [3] => 3
- * )
- * <code>
- *
- * @param int $id
- *
- * @return array
- */
- public function getParentCategoryIds($id)
- {
- /** @var \Enlight_Components_Db_Adapter_Pdo_Mysql $db */
- $db = Shopware()->Container()->get('shopware.db');
- /** @var \PDOStatement $stmt */
- $stmt = $db->prepare('SELECT id, parent FROM s_categories WHERE id = :id AND parent IS NOT NULL');
- $stmt->execute([':id' => $id]);
- $parent = $stmt->fetch(\PDO::FETCH_ASSOC);
- if (!$parent) {
- return [];
- }
- $result = [$parent['id']];
- $parent = $this->getParentCategoryIds($parent['parent']);
- if ($parent) {
- $result = array_merge($result, $parent);
- }
- $cache[$id] = $result;
- return $result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement