Models example


    private function checkIfProductIsInBasket($productId$orderNumber$sessionId)
    {
        $builder = Shopware()->Models()->getConnection()->createQueryBuilder();

        $builder->select('basket.id', 'basket.quantity')
            ->from('s_order_basket', 'basket')
            ->where('basket.articleID = :articleId')
            ->andWhere('basket.sessionID = :sessionId')
            ->andWhere('basket.ordernumber = :ordernumber')
            ->andWhere('basket.modus != 1')
            ->setParameter('articleId', $productId)
            ->setParameter('sessionId', $sessionId)
            ->setParameter('ordernumber', $orderNumber);

        

    private function overwriteBillingAddress(array $userData): array
    {
        // Temporarily overwrite billing address         if (!$this->session->offsetGet('checkoutBillingAddressId')
            || \strtolower(Shopware()->Front()->Request()->getControllerName()) !== 'checkout'
        ) {
            return $userData;
        }

        $addressRepository = Shopware()->Models()->getRepository(Address::class);
        $addressId = $this->session->offsetGet('checkoutBillingAddressId');

        try {
            $legacyAddress = $this->convertToLegacyAddressArray(
                $addressRepository->getOneByUser($addressId$this->session->offsetGet('sUserId'))
            );

            $userData['billingaddress'] = array_merge($userData['billingaddress']$legacyAddress);
            $userData = $this->completeUserCountryData($userData);
        } catch (Exception $ex) {
            // No need to overwrite default billing address
public function getCurrentPaymentDataAsArray($userId)
    {
        // nothing to do, array expected         return [];
    }

    /** * {@inheritdoc} */
    public function createPaymentInstance($orderId$userId$paymentId)
    {
        $orderAmount = Shopware()->Models()->createQueryBuilder()
            ->select('orders.invoiceAmount')
            ->from(Order::class, 'orders')
            ->where('orders.id = ?1')
            ->setParameter(1, $orderId)
            ->getQuery()
            ->getSingleScalarResult();

        $addressData = Shopware()->Models()->getRepository(Customer::class)
            ->find($userId)->getDefaultBillingAddress();

        $date = new DateTime();
        

    public function refreshArticleImpression($request)
    {
        $articleId = $request->getParam('articleId');
        $deviceType = $request->getDeviceType();
        if (empty($articleId)) {
            return;
        }
        $shopId = Shopware()->Shop()->getId();
        $repository = Shopware()->Models()->getRepository(ArticleImpression::class);
        $articleImpressionQuery = $repository->getArticleImpressionQuery($articleId$shopId, null, $deviceType);
        $articleImpression = $articleImpressionQuery->getOneOrNullResult();

        // If no Entry for this day exists - create a new one         if ($articleImpression === null) {
            $articleImpression = new ArticleImpression($articleId$shopId, null, 1, $deviceType);
            Shopware()->Models()->persist($articleImpression);
        } else {
            $articleImpression->increaseImpressions();
        }
        Shopware()->Models()->flush();
    }

    public function getList($offset$limit)
    {
        /** @var Query<array<string, mixed>> $query */
        $query = $this->getDqlHelper()->getEntityManager()->getRepository(BackupModel::class)
            ->getBackupListQuery($offset$limit);
        $query->setHydrationMode(AbstractQuery::HYDRATE_ARRAY);
        $paginator = Shopware()->Models()->createPaginator($query);
        $totalCount = $paginator->count();

        $backups = iterator_to_array($paginator);

        return [
            'totalCount' => $totalCount,
            'data' => $backups,
        ];
    }

    /** * Will create a backup for $detailIds. The columns and tables to backup will be generated from $operations * Depending on $newBackup a existing file will be appended or overwritten. The name of the backup is chosen * depending on $id. * * @param int[] $detailIds * @param array $operations * @param bool $newBackup * @param int $id */
return $builder;
    }

    /** * @param Query<Detail> $query * * @return array{0: array<int>, 1: int} */
    public function getPaginatedResult($query)
    {
        $paginator = Shopware()->Models()->createPaginator($query);
        $paginator->setUseOutputWalkers(true);

        $totalCount = $paginator->count();

        $result = array_map(
            function D$item) {
                return $item->getId();
            },
            iterator_to_array($paginator)
        );

        

        $this->translationComponent = Shopware()->Container()->get(Shopware_Components_Translation::class);
    }

    /** * @throws Exception */
    protected function setOrder(Shopware_Models_Document_Order $order)
    {
        $this->_order = $order;

        $repository = Shopware()->Models()->getRepository(Shop::class);
        // "language" actually refers to a language-shop and not to a locale         $shop = $repository->getById($this->_order->order->language);
        if ($shop === null) {
            throw new ModelNotFoundException(Shop::class$this->_order->order->language);
        }

        if (!empty($this->_order->order->currencyID)) {
            $repository = Shopware()->Models()->getRepository(Currency::class);
            $currency = $repository->find($this->_order->order->currencyID);
            if ($currency === null) {
                throw new ModelNotFoundException(Currency::class$this->_order->order->currencyID);
            }
return true;
        }

        $shops = Shopware()->Db()->fetchCol('SELECT id FROM s_core_shops WHERE active = 1');

        $currentTime = new DateTime();

        $this->SeoIndex()->registerShop($shops[0]);
        $this->RewriteTable()->sCreateRewriteTableCleanup();

        foreach ($shops as $shopId) {
            $repository = Shopware()->Models()->getRepository(Shop::class);
            $shop = $repository->getActiveById($shopId);
            if ($shop === null) {
                throw new Exception('No valid shop id passed');
            }

            $this->get(ShopRegistrationServiceInterface::class)->registerShop($shop);
            Shopware()->Modules()->Categories()->baseId = $shop->getCategory()->getId();

            [$elementId$shopId] = $this->SeoIndex()->getCachedTime();
            $this->SeoIndex()->setCachedTime($currentTime->format('Y-m-d H:i:s')$elementId$shopId);

            

    public function sGetSupplierById($id)
    {
        trigger_error(sprintf('%s:%s is deprecated since Shopware 5.6 and will be removed with 5.8. Will be removed without replacement.', __CLASS__, __METHOD__), E_USER_DEPRECATED);

        $id = (int) $id;
        $categoryId = (int) $this->frontController->Request()->getQuery('sCategory');

        $supplier = Shopware()->Models()->getRepository(Supplier::class)->find($id);
        if (!($supplier instanceof Supplier)) {
            return [];
        }
        $supplier = Shopware()->Models()->toArray($supplier);
        if (!Shopware()->Shop()->getDefault()) {
            $supplier = $this->sGetTranslation($supplier$supplier['id'], 'supplier');
        }
        $supplier['link'] = $this->config['sBASEFILE'];
        $supplier['link'] .= '?sViewport=cat&sCategory=' . $categoryId . '&sPage=1&sSupplier=0';

        return $supplier;
    }
if (!isset($params['name'])) {
            throw new CustomValidationException('A name is required');
        }

        // In order to have a consistent interface within the REST Api, one might want         // to set the parent category by using 'parentId' instead of 'parent'         if (isset($params['parentId']) && !isset($params['parent'])) {
            $params['parent'] = $params['parentId'];
        }

        if (!empty($params['parent'])) {
            $params['parent'] = Shopware()->Models()->getRepository(CategoryModel::class)->find($params['parent']);
            if (!$params['parent']) {
                throw new CustomValidationException(sprintf('Parent by id %s not found', $params['parent']));
            }
        } else {
            unset($params['parent']);
        }

        if (!empty($params['attribute'])) {
            foreach ($params['attribute'] as $key => $value) {
                if (is_numeric($key)) {
                    $params['attribute']['attribute' . $key] = $value;
                    
 ArrayObject::ARRAY_AS_PROPS);
    }

    /** * Get all information from a certain order (model) * * @return void */
    public function processOrder()
    {
        $snippetManager = Shopware()->Snippets();
        $modelManager = Shopware()->Models();
        $orderLocale = null;

        if ($modelManager !== null) {
            $orderLocale = $modelManager->find(
                ShopLocale::class,
                $this->_order['language']
            );
        }

        if ($orderLocale !== null) {
            $snippetManager->setLocale($orderLocale);
        }
try {
                $result = $result->rowCount();
            } catch (Zend_Db_Exception $e) {
                continue;
            }

            if (empty($result)) {
                continue;
            }

            $repository = Shopware()->Models()->getRepository(Shop::class);
            $shopId = is_numeric($user['language']) ? $user['language'] : $user['subshopID'];
            $shop = $repository->getActiveById($shopId);
            $this->get(ShopRegistrationServiceInterface::class)->registerShop($shop);

            // language subshopID             $context = [
                'sUser' => $user,
                'sVoucher' => $voucher,
                'sData' => $job['data'],
            ];

            
$results = [];
        foreach ($data as $key => $datum) {
            $id = $this->getIdByData($datum);

            try {
                $results[$key] = [
                    'success' => true,
                    'operation' => 'delete',
                    'data' => $this->delete($id),
                ];
                if ($this->getResultMode() === self::HYDRATE_ARRAY) {
                    $results[$key]['data'] = Shopware()->Models()->toArray(
                        $results[$key]['data']
                    );
                }
            } catch (Exception $e) {
                if (!$this->getManager()->isOpen()) {
                    $this->resetEntityManager();
                }
                $message = $e->getMessage();
                if ($e instanceof ValidationException && $e->getViolations() instanceof ConstraintViolationList) {
                    $message = implode("\n", $e->getViolations()->getIterator()->getArrayCopy());
                }

                

    public function onUpdate()
    {
        if (!empty($this->rawPassword)) {
            $this->hashPassword = $this->rawPassword;
        } elseif (!empty($this->password)) {
            $this->encoderName = Shopware()->PasswordEncoder()->getDefaultPasswordEncoderName();
            $this->hashPassword = Shopware()->PasswordEncoder()->encodePassword($this->password, $this->encoderName);
        }

        $changeSet = Shopware()->Models()->getUnitOfWork()->getEntityChangeSet($this);

        $passwordChanged = isset($changeSet['hashPassword']) && $changeSet['hashPassword'][0] !== $changeSet['hashPassword'][1];

        if ($passwordChanged) {
            $this->passwordChangeDate = new DateTime();
        }
    }

    /** * @return CustomerAttribute|null */
    
return [];
    }

    /** * {@inheritdoc} */
    public function savePaymentData($userId, Enlight_Controller_Request_Request $request)
    {
        $lastPayment = $this->getCurrentPaymentDataAsArray($userId);

        $paymentMean = Shopware()->Models()->getRepository(Payment::class)->
            getActivePaymentsQuery(['name' => 'debit'])->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);

        $data = [
            'account_number' => $request->getParam('sDebitAccount'),
            'bank_code' => $request->getParam('sDebitBankcode'),
            'bankname' => $request->getParam('sDebitBankName'),
            'account_holder' => $request->getParam('sDebitBankHolder'),
        ];

        if (!$lastPayment) {
            $date = new DateTime();
            
Home | Imprint | This part of the site doesn't use cookies.