/** * @param $data * @param $entity * @param $primaryId * @return QueryBuilder */ public function getQueryBuilderForEntity($data, $entity, $primaryId) { $metaData = $this->modelManager->getClassMetadata($entity); $table = $metaData->table['name']; $builder = $this->getQueryBuilder(); if ($primaryId) { $id = $builder->createNamedParameter($primaryId, \PDO::PARAM_INT); $builder->update($table); //update article id in case we don't have any field for update $builder->set('id', $id); $builder->where('id = ' . $id); } else { $builder->insert($table); } foreach ($data as $field => $value) { if (!array_key_exists($field, $metaData->fieldMappings)) { continue; } $key = $this->connection->quoteIdentifier($metaData->fieldMappings[$field]['columnName']); $value = $this->getNamedParameter($value, $field, $metaData, $builder); if ($primaryId) { $builder->set($key, $value); } else { $builder->setValue($key, $value); } } return $builder; }
/** * @inheritdoc */ public function exportProfile($profileId) { $profileRepository = $this->modelManager->getRepository(Profile::class); $profile = $profileRepository->findOneBy(['id' => $profileId]); $profileDataStruct = new ProfileDataStruct($profile); return $profileDataStruct; }
/** * initialises the bootstrapPath variable * * @param $em * @param $soapApi * @param $config */ public function __construct(ModelManager $em, SoapApi $soapApi, Config $config) { $this->db = $em->getConnection(); $this->tsSoapApi = $soapApi; $this->tsConfig = $config; /** @var Repository $shopRepository */ $shopRepository = $em->getRepository('Shopware\\Models\\Shop\\Shop'); $this->shops = $shopRepository->getActiveShops(AbstractQuery::HYDRATE_ARRAY); }
/** * Resolve username/realm to password/hash/etc. * * @param string $username Username * @param string $realm Authentication Realm * @return string|false User's shared secret, if the user is found in the * realm, false otherwise. */ public function resolve($username, $realm) { $repository = $this->modelManager->getRepository('Shopware\\Models\\User\\User'); $user = $repository->findOneBy(array('username' => $username, 'active' => true)); if (!$user) { return false; } if ($user->getApiKey() === null) { return false; } $apiKey = $user->getApiKey(); return md5($username . ':' . $realm . ':' . $apiKey); }
/** * @inheritdoc */ public function write($messages, $status, Session $session) { $loggerModel = new LoggerEntity(); if (!is_array($messages)) { $messages = [$messages]; } $messages = implode(';', $messages); $loggerModel->setSession($session); $loggerModel->setMessage($messages); $loggerModel->setCreatedAt('now'); $loggerModel->setStatus($status); $this->modelManager->persist($loggerModel); $this->modelManager->flush(); }
private function importNewsletterDemoData() { $this->modelManager = Shopware()->Container()->get('models'); $newsletterGroup = $this->modelManager->find(Group::class, 1); for ($addressAmount = 0; $addressAmount < 25; $addressAmount++) { $address = new Address(); $address->setEmail('test_' . $addressAmount . '@example.com'); $address->setAdded(new \DateTime()); $address->setNewsletterGroup($newsletterGroup); $address->setIsCustomer(false); $this->modelManager->persist($address); } $this->modelManager->flush(); }
/** * @inheritdoc */ public function getListByCategory($products, Struct\ShopContextInterface $context) { if (!$this->config->offsetExists('similarLimit') || $this->config->get('similarLimit') <= 0) { return []; } $ids = []; foreach ($products as $product) { $ids[] = $product->getId(); } $ids = array_unique($ids); $categoryId = 1; if ($context->getShop() && $context->getShop()->getCategory()) { $categoryId = $context->getShop()->getCategory()->getId(); } $query = $this->connection->createQueryBuilder(); $query->select(['main.articleID', "GROUP_CONCAT(subVariant.ordernumber SEPARATOR '|') as similar"]); $query->from('s_articles_categories', 'main'); $query->innerJoin('main', 's_articles_categories', 'sub', 'sub.categoryID = main.categoryID AND sub.articleID != main.articleID'); $query->innerJoin('sub', 's_articles_details', 'subVariant', 'subVariant.articleID = sub.articleID AND subVariant.kind = 1'); $query->innerJoin('main', 's_categories', 'category', 'category.id = sub.categoryID AND category.id = main.categoryID'); $query->where('main.articleID IN (:ids)')->andWhere('category.path LIKE :path'); $query->setParameter(':ids', $ids, Connection::PARAM_INT_ARRAY)->setParameter(':path', '%|' . (int) $categoryId . '|'); $query->groupBy('main.articleID'); $statement = $query->execute(); $data = $statement->fetchAll(\PDO::FETCH_ASSOC); $limit = (int) $this->config->get('similarLimit'); $result = []; foreach ($data as $row) { $similar = explode('|', $row['similar']); $result[$row['articleID']] = array_slice($similar, 0, $limit); } return $result; }
/** * Given a category id, returns the category path * * @param int $categoryId Id of the category * @return array Array containing the path parts */ public function sCategoryPath($categoryId) { $parts = $this->modelManager->getRepository('Shopware\\Models\\Category\\Category')->getPathById($categoryId, 'name'); $level = Shopware()->Shop()->getCategory()->getLevel(); $parts = array_slice($parts, $level); return $parts; }
/** * @param int $articleID * @return bool */ private function deleteDownloads($articleID) { /* @var ArticleRepository $articleRepository */ $articleRepository = $this->getArticleRepository(); $article = $articleRepository->find($articleID); if (!$article instanceof Article) { return false; } $downloads = $article->getDownloads(); foreach ($downloads as $downloadModel) { $filename = $downloadModel->getFile(); $this->em->remove($downloadModel); /* @var MediaRepository $mediaRepository */ $mediaRepository = $this->getMediaRepository(); $mediaList = $mediaRepository->findBy(['path' => $filename]); foreach ($mediaList as $mediaModel) { $this->em->remove($mediaModel); } } $sql = 'SELECT id FROM s_articles_downloads WHERE articleID = ' . $articleID; $downloads = $this->db->fetchCol($sql); if (!empty($downloads)) { $this->deleteTranslation('download', $downloads); } $this->em->flush(); return true; }
/** * @return \Doctrine\ORM\QueryBuilder */ public function getElementBuilder() { $repository = $this->modelManager->getRepository(Element::class); $builder = $repository->createQueryBuilder('attribute'); $builder->andWhere('attribute.translatable = 1'); $builder->orderBy('attribute.position'); return $builder; }
/** * @param Category $category * @throws AdapterException */ private function validateCategoryModel($category) { $violations = $this->modelManager->validate($category); if ($violations->count() > 0) { $message = SnippetsHelper::getNamespace()->get('adapters/category/no_valid_category_entity', 'No valid category entity for category %s'); throw new AdapterException(sprintf($message, $category->getName())); } }
/** * @param EventArgs $arguments */ public function preRemoveCategory(EventArgs $arguments) { $categoryModel = $arguments->get('entity'); $categoryId = $categoryModel->getId(); $builder = $this->em->getDBALQueryBuilder(); $builder->delete('s_articles_sort')->where('categoryId = :categoryId')->setParameter('categoryId', $categoryId); $builder->execute(); }
/** * Helper function that queries all sub shops (including language sub shops). * @return array */ private function getData() { /** @var \Shopware\Models\Shop\Repository $repository */ $repository = $this->models->getRepository('Shopware\\Models\\Shop\\Shop'); $builder = $repository->getActiveQueryBuilder(); $builder->orderBy('shop.id'); return $builder->getQuery()->getArrayResult(); }
/** * Returns all config elements of the passed template. * * @param \Shopware\Models\Shop\Template $template * @return ArrayCollection */ private function getElements(Shop\Template $template) { $builder = $this->entityManager->createQueryBuilder(); $builder->select('elements')->from('Shopware\\Models\\Shop\\TemplateConfig\\Element', 'elements')->where('elements.templateId = :templateId')->setParameter('templateId', $template->getId()); $elements = $builder->getQuery()->getResult(); $elements = $this->eventManager->filter('Theme_Configurator_Elements_Loaded', $elements, array('template' => $template)); return new ArrayCollection($elements); }
/** * @return \Shopware\Components\Model\DatabaseDriver */ private function getDatabaseDriver() { $platform = $this->em->getConnection()->getDatabasePlatform(); $platform->registerDoctrineTypeMapping('enum', 'string'); $driver = new \Shopware\Components\Model\DatabaseDriver( $this->em->getConnection()->getSchemaManager() ); return $driver; }
/** * Removes the import files on update to version 1.2.2 */ private function removeImportFilesAlbum() { $repo = $this->modelManager->getRepository(Album::class); $album = $repo->findOneBy(['name' => 'ImportFiles']); if ($album) { $this->modelManager->remove($album); $this->modelManager->flush(); } }
/** * Returns the Trusted Shops config used in the frontend * * @param $shopId * @return array */ public function getTrustedShopBasicConfig($shopId) { $config = $this->getSettings($shopId); $sql = "SELECT id, description\n\t\t\t\tFROM s_core_states\n\t\t\t\tWHERE description LIKE 'TS - Antrag%'\n\t\t\t\tORDER BY id"; $states = $this->em->getConnection()->fetchAll($sql); //set trusted shop parameters $trustedShop = array('id' => $config['trustedShopsId'], 'rating_active' => $config['trustedShopsShowRatingWidget'], 'rating_buttons' => $config['trustedShopsShowRatingsButtons'], 'rating_link' => $this->getRatingLink($config['trustedShopsId']), 'rate_later_days' => $config['trustedShopsRateLaterDays'], 'user' => $config['trustedShopsUser'], 'pw' => $config['trustedShopsPassword'], 'trustBadgeCode' => $config['trustedShopsTrustBadgeCode'], 'stateWaiting' => $states[0], 'stateSuccess' => $states[1], 'stateError' => $states[2]); return $trustedShop; }
/** * @param Menu|null $menuItem * @param string $menuLabel */ private function createMenuItemIfItDoesNotExist($menuItem, $menuLabel) { if ($menuItem instanceof Menu) { return; } $menu = new Menu(); $menu->setLabel($menuLabel); $this->modelManger->persist($menu); $this->modelManger->flush(); }
/** * creates the DB tables on base of the Trusted Shops CustomModel */ private function createSchema() { $this->registerCustomModels(); $tool = new SchemaTool($this->em); $classes = array($this->em->getClassMetadata('Shopware\\CustomModels\\TrustedShops\\TrustedShops')); try { $tool->createSchema($classes); } catch (Exception $e) { } }
private function removePriceGroup() { $ids = $this->db->fetchCol("SELECT id FROM s_core_pricegroups WHERE description = 'TEST-GROUP'"); foreach ($ids as $id) { $group = $this->entityManager->find('Shopware\\Models\\Price\\Group', $id); $this->entityManager->remove($group); $this->entityManager->flush(); $this->entityManager->clear(); } }
/** * Try to get the Tax object * * @return bool|Tax * @throws ORMException * @throws OptimisticLockException * @throws TransactionRequiredException */ private function getTax() { $taxId = $this->getTaxId(); /** @var Tax $tax */ $tax = $this->em->find('Shopware\\Models\\Tax\\Tax', $taxId); if (!$tax instanceof Tax) { echo json_encode(array("success" => false, "message" => "Tax with id: {$taxId} does not exist!")); return false; } return $tax; }
/** * Returns the query builder object to select the theme configuration for the * current shop. * * @param \Shopware\Models\Shop\Template $template * @param boolean $lessCompatible * @return \Doctrine\ORM\QueryBuilder|\Shopware\Components\Model\QueryBuilder * @throws \Enlight_Event_Exception */ private function getShopConfigQuery(Shop\Template $template, $lessCompatible) { $builder = $this->entityManager->createQueryBuilder(); $builder->select(array('element.name', 'values.value', 'element.defaultValue', 'element.type')); $builder->from('Shopware\\Models\\Shop\\TemplateConfig\\Element', 'element')->leftJoin('element.values', 'values', 'WITH', 'values.shopId = :shopId')->where('element.templateId = :templateId'); if ($lessCompatible) { $builder->andWhere('element.lessCompatible = 1'); } $this->eventManager->notify('Theme_Inheritance_Shop_Query_Built', array('builder' => $builder, 'template' => $template)); return $builder; }
/** * @param $type * @return Profile * @throws \Exception */ public function loadHiddenProfile($type) { /** @var Repository $profileRepository */ $profileRepository = $this->modelManager->getRepository(ProfileEntity::class); $profileEntity = $profileRepository->findOneBy(['type' => $type, 'hidden' => 1]); if (!$profileEntity) { $data = ['name' => $type . 'Shopware', 'type' => $type, 'hidden' => 1]; $profileEntity = $this->createProfileModel($data); } return new Profile($profileEntity); }
/** * Helper function to read the landing pages urls * * @return array */ private function readLandingPageUrls() { $categoryId = $this->contextService->getShopContext()->getShop()->getCategory()->getId(); $emotionRepository = $this->em->getRepository('Shopware\\Models\\Emotion\\Emotion'); $builder = $emotionRepository->getCampaignsByCategoryId($categoryId); $campaigns = $builder->getQuery()->getArrayResult(); foreach ($campaigns as &$campaign) { $campaign['show'] = $this->filterCampaign($campaign[0]['validFrom'], $campaign[0]['validTo']); $campaign['urlParams'] = array('sViewport' => 'campaign', 'emotionId' => $campaign[0]['id'], 'sCategory' => $campaign['categoryId']); } return $campaigns; }
/** * @param string $profileType * @param string $profileName */ private function createProfile($profileType, $profileName) { $defaultTree = TreeHelper::getDefaultTreeByProfileType($profileType); $profile = new Profile(); $profile->setHidden(0); $profile->setName($profileName); $profile->setType($profileType); $profile->setTree($defaultTree); $this->modelManager->persist($profile); $this->modelManager->flush(); $this->profileIds[$profileType] = $profile->getId(); }
/** * Generates and inserts static page urls * * @param $offset * @param $limit */ private function insertStaticPageUrls($offset, $limit) { $shopId = Shopware()->Shop()->getId(); $sitesData = $this->modelManager->getRepository('Shopware\\Models\\Site\\Site')->getSitesWithoutLinkQuery($shopId, $offset, $limit)->getArrayResult(); foreach ($sitesData as $site) { $org_path = 'sViewport=custom&sCustom=' . $site['id']; $this->data->assign('site', $site); $path = $this->template->fetch('string:' . $this->config->get('seoCustomSiteRouteTemplate'), $this->data); $path = $this->sCleanupPath($path, false); $this->sInsertUrl($org_path, $path); } }
/** * gets the old data of the Trusted Shops core integration and the Trusted Shops Excellence plugin * and fills them into the new DB table of this plugin * * @param $pluginId */ public function migrateData($pluginId) { $tsValues = $this->getTsClassicData(); $tsExcValues = $this->getTsExcellenceData($pluginId); /** @var Repository $shopRepository */ $shopRepository = $this->em->getRepository('Shopware\\Models\\Shop\\Shop'); $shops = $shopRepository->getActiveShops(); /** @var Shop $shop */ foreach ($shops as $shop) { if (!$shop) { continue; } $shopId = $shop->getId(); $oldTsId = $tsValues[$shopId]; $oldTsEID = $tsExcValues['tsEID'][$shopId]; $oldTsWebServiceUser = $tsExcValues['tsWebServiceUser'][$shopId]; $oldTsWebServicePassword = $tsExcValues['tsWebServicePassword'][$shopId]; $tsExcValues['testSystemActive'][$shopId] ? $oldTestSystemActive = $tsExcValues['testSystemActive'][$shopId] : ($oldTestSystemActive = 0); $tsExcValues['ratingActive'][$shopId] ? $oldRatingActive = $tsExcValues['ratingActive'][$shopId] : ($oldRatingActive = 1); /* @var TrustedShops $trustedShopsModel */ $trustedShopsModel = $this->em->getRepository('Shopware\\CustomModels\\TrustedShops\\TrustedShops')->findOneBy(array('shopId' => $shopId)); if (!$oldTsId && !$oldTsEID) { continue; } if (!$trustedShopsModel) { $trustedShopsModel = new TrustedShops(); $trustedShopsModel->setShopId($shopId); $oldTsEID ? $trustedShopsModel->setTrustedShopsId($oldTsEID) : $trustedShopsModel->setTrustedShopsId($oldTsId); $trustedShopsModel->setTrustedShopsUser($oldTsWebServiceUser); $trustedShopsModel->setTrustedShopsPassword($oldTsWebServicePassword); $trustedShopsModel->setTrustedShopsTestSystem($oldTestSystemActive); $trustedShopsModel->setTrustedShopsShowRatingWidget($oldRatingActive); $trustedShopsModel->setTrustedShopsShowRatingsButtons(0); $trustedShopsModel->setTrustedShopsRateLaterDays(7); } $this->em->persist($trustedShopsModel); $this->em->flush(); } $this->deactivateOldTsComponents(); }
/** * @param array $category * @return bool|int */ public function import(array $category) { $category = $this->prepareCategoryData($category); // Try to find an existing category by name and parent $model = null; if (isset($category['parent']) && isset($category['name'])) { $model = $this->repository->findOneBy(['parent' => $category['parent'], 'name' => $category['name']]); } if (!$model instanceof Category) { $model = new Category(); } $parentModel = null; if (isset($category['parent'])) { $parentModel = $this->repository->find((int) $category['parent']); if (!$parentModel instanceof Category) { $this->logger->error("Parent category {$category['parent']} not found!"); return false; } } $model->fromArray($category); $model->setParent($parentModel); $this->em->persist($model); $this->em->flush(); // Set category attributes $attributes = $this->prepareCategoryAttributesData($category); unset($category); $categoryId = $model->getId(); if (!empty($attributes)) { $attributeID = $this->db->fetchOne("SELECT id FROM s_categories_attributes WHERE categoryID = ?", [$categoryId]); if ($attributeID === false) { $attributes['categoryID'] = $categoryId; $this->db->insert('s_categories_attributes', $attributes); } else { $this->db->update('s_categories_attributes', $attributes, ['categoryID = ?' => $categoryId]); } } return $categoryId; }
/** * Returns the sort mode for the passed value ids. * If the value ids contains more than one property set, the * global fallback sort mode is used. * * @param array $valueIds * @return int */ private function getSortMode(array $valueIds) { $query = $this->connection->createQueryBuilder(); $query->select('DISTINCT propertySet.sortmode')->from('s_filter', 'propertySet'); $query->innerJoin('propertySet', 's_filter_relations', 'relations', 'relations.groupID = propertySet.id'); $query->innerJoin('relations', 's_filter_values', 'propertyOption', 'relations.optionID = propertyOption.optionID'); $query->where('propertyOption.id IN (:ids)')->setParameter(':ids', $valueIds, Connection::PARAM_INT_ARRAY); /**@var $statement \Doctrine\DBAL\Driver\ResultStatement */ $statement = $query->execute(); $rows = $statement->fetchAll(\PDO::FETCH_COLUMN); if (count($rows) == 1) { return $rows[0]; } else { return $this->config->get('defaultFilterSort', self::FILTERS_SORT_POSITION); } }
/** * Helper function which resolves the theme parent for each * passed theme * * @param array $themes * @throws \Exception */ private function setParents(array $themes) { /**@var $theme Theme */ foreach ($themes as $theme) { if ($theme->getExtend() === null) { continue; } $template = $this->repository->findOneBy(array('template' => $theme->getTemplate())); $parent = $this->repository->findOneBy(array('template' => $theme->getExtend())); if (!$parent instanceof Shop\Template) { throw new \Exception(sprintf("Parent %s of theme %s not found", $theme->getExtend(), $theme->getTemplate())); } $template->setParent($parent); $this->entityManager->flush(); } }