@param BaseProduct $product
@param             $event
@param             $trackingKey

@return array|ProductStat[]
509205
public function retrievedStatForProduct(BaseProduct $product, $event, $trackingKey)
    {
        $qb = $this->createQueryBuilder('s')
            ->select('s')
            ->where('s.product = :product and s.type = :event and s.trackingKey = :key and s.createdAt between :start and :end')
            ->setParameters(array(
                'product' => $product,
                'event' => $event,
                'key' => $trackingKey,
                'start' => new \DateTime('today'),
                'end' => new \DateTime('tomorrow'),
            ))
        ;

        return $qb->getQuery()->getResult();
    }
1155898
private function retrieveProductTypeIdByKey($key)
    {
        if (!isset($this->productTypesMap[$key])) {
            return null;
        }

        return intval($this->productTypesMap[$key]);
    }
4980
public function getProductsByBarcode(string $barCode, int $siteId) : array
    {
        Assert::that($barCode)->minLength(1, 'The length of $barCode has to be > 0');
        Assert::that($siteId)->greaterThan(0, 'The $siteId has to be positive');

        return (array)$this->master->doRequest(
            'GET',
            sprintf('/admin/WEBAPI/Endpoints/v1_0/ProductService/{KEY}/ByBarcode/%s/%d', rawurlencode($barCode), $siteId)
        );
    }
543246
public function newAction()
    {
        $entity = new Product();

        $entity = $this->addProductItemFieldData($entity);


        $form = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form' => $form->createView(),
        );
    }
715061
public static function productName($project, $location, $product)
    {
        return self::getProductNameTemplate()->render([
            'project' => $project,
            'location' => $location,
            'product' => $product,
        ]);
    }
579698
public function addProductAction(Product $product, $quantity, Request $request)
    {
        // Find OrderCollection
        $orderCollection = $this->getCurrentCart();

        $quantity = array_key_exists('quantity', $_POST) ? (int) $_POST['quantity'] : $quantity;

        try
        {
            if ('-' == $request->get('remove'))
            {
                $quantity = -1 * $quantity;
            }

            // Add Product to OrderCollection
            $lineItem = $orderCollection->addProduct($product, $quantity);

            // Persisting cascades to Order and OrderCollection
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($lineItem);
            $em->flush();

            if ($quantity > 0) {
                $notice = 'Added '.$quantity.' '
                    .$product->getUnitForNumber($quantity).' of '
                    .$product->getName().' to your cart';
            } else {
                $quantity = abs($quantity);
                $notice = 'Removed '.$quantity.' '
                    .$product->getUnitForNumber($quantity).' of '
                    .$product->getName().' from your cart';
            }

            // Set flash message
            $this->get('session')->getFlashBag()->add('notice', $notice);

            // Save the OrderCollection to the session
            $this->getRequest()->getSession()->set('cart_id', $orderCollection->getId());
        }
        catch (\Exception $e)
        {
            // could not add Product to cart
        }

        $last_route = $request->get('referer');

        if (in_array($last_route, array('_welcome')))
        {
            return $this->redirect($this->generateUrl($last_route));
        }

        return $this->redirect($this->generateUrl('Profile_product_show', array(
            'product_slug' => $product->getSlug(),
            'slug'         => $product->getSeller()->getSlug(),
        )));
    }
160485
private function getItemsData($quoteItem, $_product, $_parentProduct)
    {
        $totalPrice = (!isset($_parentProduct) ? $quoteItem->getBaseRowTotalInclTax() : $quoteItem->getParentItem()->getBaseRowTotalInclTax());
        $inStock = ($_product->isInStock())
            ? 'In Stock'
            : 'Out of stock';
        $total = $this->priceHelper->currency(
            $totalPrice,
            true,
            false
        );

        $productUrl = (isset($_parentProduct) ? $this->urlFinder->fetchFor($_parentProduct) : $this->urlFinder->fetchFor($_product));
        $grandTotal = $this->priceHelper->currency(
            $this->getGrandTotal(),
            true,
            false
        );
        $itemsData = [
            'grandTotal' => $grandTotal,
            'total' => $total,
            'inStock' => $inStock,
            'productUrl' => $productUrl,
            'product' => (isset($_parentProduct) ? $_parentProduct : $_product),
            'qty' => isset($_parentProduct) ? $quoteItem->getParentItem()->getQty() : $quoteItem->getQty(),
            'product_details' => $_product
        ];

        return $itemsData;
    }
687996
public function getAllRoutesOfProduct(ProductInterface $product)
    {
        $urls = [];
        /** @var ProductTranslation $productTranslation */
        foreach ($product->getTranslations() as $productTranslation) {
            if ($productTranslation->getRoute()) {
                $urls[$productTranslation->getLocale()] = $productTranslation->getRoute()->getPath();
            }
        }

        return $urls;
    }
126907
public function selectCombination(array $product, array $field_value_ids)
    {
        $result = array();
        $this->hook->attach('sku.select.combination.before', $product, $field_value_ids, $result, $this);

        if (!empty($result)) {
            return (array) $result;
        }

        $access = !empty($product['stock']) || empty($product['subtract']);

        $result = array(
            'modal' => '',
            'severity' => '',
            'cart_access' => $access,
            'combination' => array(),
            'sku' => $product['sku'],
            'price' => $product['price'],
            'currency' => $product['currency'],
            'message' => $access ? '' : $this->translation->text('Out of stock')
        );

        if (empty($field_value_ids)) {
            $this->hook->attach('sku.select.combination.after', $product, $field_value_ids, $result, $this);
            return (array) $result;
        }

        if (empty($product['status'])) {
            $result['severity'] = 'danger';
            $result['message'] = $this->translation->text('Unavailable');

            $this->hook->attach('sku.select.combination.after', $product, $field_value_ids, $result, $this);
            return (array) $result;
        }

        $combination_id = $this->getCombinationId($field_value_ids, $product['product_id']);

        if (empty($product['combination'][$combination_id]['status'])) {

            $result['not_matched'] = true;
            $result['cart_access'] = false;

            $result['severity'] = 'danger';
            $result['message'] = $this->translation->text('Unavailable');
            $result['related'] = $this->getRelatedFieldValues($product, $field_value_ids);

            $this->hook->attach('sku.select.combination.after', $product, $field_value_ids, $result, $this);
            return (array) $result;
        }

        $result['combination'] = $product['combination'][$combination_id];
        $result['combination']['currency'] = $product['currency'];

        $result['sku'] = $result['combination']['sku'];
        $result['price'] = $result['combination']['price'];

        if (empty($result['combination']['stock']) && $product['subtract']) {
            $result['cart_access'] = false;
            $result['severity'] = 'warning';
            $result['message'] = $this->translation->text('Out of stock');
        }

        $this->hook->attach('sku.select.combination.after', $product, $field_value_ids, $result, $this);
        return (array) $result;
    }
855450
protected function prepareProductInformation($addProductId, $productInfo)
    {
        $return = [];

        $return['id'] = isset($productInfo['aid']) ? $productInfo['aid'] : $addProductId;
        $return['amount'] = isset($productInfo['am']) ? $productInfo['am'] : 0;
        $return['selectList'] = isset($productInfo['sel']) ? $productInfo['sel'] : null;

        $return['persistentParameters'] = $this->getPersistedParameters($productInfo['persparam']);
        $return['override'] = isset($productInfo['override']) ? $productInfo['override'] : null;
        $return['bundle'] = isset($productInfo['bundle']) ? true : false;
        $return['oldBasketItemId'] = isset($productInfo['basketitemid']) ? $productInfo['basketitemid'] : null;

        return $return;
    }
1192311
public function getProductStats(Product $product, $start, $end)
    {
        $em = $this->getEntityManager();
        $repository = $em->getRepository('EcommerceBundle:ProductStats');
        $query = $repository->createQueryBuilder('s')
            ->select("s.id, p.id product, s.day, sum(s.visits) as visits")
            ->leftJoin('s.product', 'p')
            ->where('s.product = :product')
            ->andWhere('s.day >= :start')
            ->andWhere('s.day <= :end')
            ->setParameters(array(
                'product' => $product, 
                'start' => $start, 
                'end' => $end
                ))
            ->groupBy('s.day')   
            ->orderBy('s.id', 'ASC') 
            ->getQuery();

        $stats = $query->getResult();
        $arr = new \Doctrine\Common\Collections\ArrayCollection();
        foreach ($stats as $stat) {
            $arr->add($stat);
        }
        if(count($arr)==0){
            $element = array('product' => $product->getId(), 'day' => date('Y-m-d'), 'visits' => 0);
            $arr->add($element);
        }
        return $arr;
    }
989024
public function update(ProductUpdateEvent $event)
    {
        if (null !== $product = ProductQuery::create()->findPk($event->getProductId())) {
            $con = Propel::getWriteConnection(ProductTableMap::DATABASE_NAME);
            $con->beginTransaction();

            try {
                $prevRef = $product->getRef();

                $product
                    ->setDispatcher($this->eventDispatcher)
                    ->setRef($event->getRef())
                    ->setLocale($event->getLocale())
                    ->setTitle($event->getTitle())
                    ->setDescription($event->getDescription())
                    ->setChapo($event->getChapo())
                    ->setPostscriptum($event->getPostscriptum())
                    ->setVisible($event->getVisible() ? 1 : 0)
                    ->setVirtual($event->getVirtual() ? 1 : 0)
                    ->setBrandId($event->getBrandId() <= 0 ? null : $event->getBrandId())

                    ->save($con)
                ;

                // Update default PSE (if product has no attributes and the product's ref change)
                $defaultPseRefChange = $prevRef !== $product->getRef()
                    && 0 === $product->getDefaultSaleElements()->countAttributeCombinations();
                if ($defaultPseRefChange) {
                    $defaultPse = $product->getDefaultSaleElements();
                    $defaultPse->setRef($product->getRef())->save();
                }

                // Update default category (if required)
                $product->setDefaultCategory($event->getDefaultCategory());

                $event->setProduct($product);
                $con->commit();
            } catch (PropelException $e) {
                $con->rollBack();
                throw $e;
            }
        }
    }
532115
public function actionGetProductCombination($values, $productId, $currencyFormatting = false) {
        /** @var CartComponent $cart */
        $cart = \Yii::$app->cart;

        $values = Json::decode($values);
        $combination = $cart->getCombination($values, $productId);
        if (!empty($combination)) {
            $oldPrice = $combination->price->oldPrice ?? '';
            $newPrice = $combination->price->discountPrice ?? '';
            if ($currencyFormatting) {
                $oldPrice = Yii::$app->formatter->asCurrency($oldPrice);
                $newPrice = Yii::$app->formatter->asCurrency($newPrice);
            }

            $availability = $combination->combinationAvailability->translation->title
                ?? $combination->product->productAvailability->translation->title ?? '';
            $description = (!empty($combination->translation->description))
                ? $combination->translation->description
                : $combination->product->translation->full_text ?? '';

            $array = [
                'image' => $combination->images[0]->productImage->thumb ?? '',
                'images' => $combination->getImagesArray() ?? '',
                'oldPrice' => $oldPrice,
                'newPrice' => $newPrice,
                'sku' => $combination->sku ?? '',
                'availability' => $availability,
                'description' => $description,
                'prices' => $combination->combinationPrices
            ];
        }
        else return 0;

        return Json::encode($array);
    }
115892
public function update(ProductSaleElementUpdateEvent $event)
    {
        $salesElement = ProductSaleElementsQuery::create()->findPk($event->getProductSaleElementId());

        $con = Propel::getWriteConnection(ProductSaleElementsTableMap::DATABASE_NAME);

        $con->beginTransaction();

        try {
            // Update the product's tax rule
            $event->getProduct()->setTaxRuleId($event->getTaxRuleId())->save($con);

            // If product sale element is not defined, create it.
            if ($salesElement == null) {
                $salesElement = new ProductSaleElements();

                $salesElement->setProduct($event->getProduct());
            }

            $defaultStatus = $event->getIsDefault();

            // If this PSE will become the default one, be sure to have *only one* default for this product
            if ($defaultStatus) {
                ProductSaleElementsQuery::create()
                    ->filterByProduct($event->getProduct())
                    ->filterByIsDefault(true)
                    ->filterById($event->getProductSaleElementId(), Criteria::NOT_EQUAL)
                    ->update(['IsDefault' => false], $con)
                ;
            } else {
                // We will not allow the default PSE to become non default if no other default PSE exists for this product.
                if ($salesElement->getIsDefault() && ProductSaleElementsQuery::create()
                        ->filterByProduct($event->getProduct())
                        ->filterByIsDefault(true)
                        ->filterById($salesElement->getId(), Criteria::NOT_EQUAL)
                        ->count() === 0) {
                    // Prevent setting the only default PSE to non-default
                    $defaultStatus = true;
                }
            }

            // Update sale element
            $salesElement
                ->setRef($event->getReference())
                ->setQuantity($event->getQuantity())
                ->setPromo($event->getOnsale())
                ->setNewness($event->getIsnew())
                ->setWeight($event->getWeight())
                ->setIsDefault($defaultStatus)
                ->setEanCode($event->getEanCode())
                ->save()
            ;

            // Update/create price for current currency
            $productPrice = ProductPriceQuery::create()
                ->filterByCurrencyId($event->getCurrencyId())
                ->filterByProductSaleElementsId($salesElement->getId())
                ->findOne($con);

            // If price is not defined, create it.
            if ($productPrice == null) {
                $productPrice = new ProductPrice();

                $productPrice
                    ->setProductSaleElements($salesElement)
                    ->setCurrencyId($event->getCurrencyId())
                ;
            }

            // Check if we have to store the price
            $productPrice->setFromDefaultCurrency($event->getFromDefaultCurrency());

            if ($event->getFromDefaultCurrency() == 0) {
                // Store the price
                $productPrice
                    ->setPromoPrice($event->getSalePrice())
                    ->setPrice($event->getPrice())
                ;
            } else {
                // Do not store the price.
                $productPrice
                    ->setPromoPrice(0)
                    ->setPrice(0)
                ;
            }

            $productPrice->save($con);

            // Store all the stuff !
            $con->commit();
        } catch (\Exception $ex) {
            $con->rollback();

            throw $ex;
        }
    }
1192342
public function sendNewProductToManagerAndOwner(Product $product)
    {
        $productOwner = $product->productOwner;
        $mailVars = [
            '{productId}' => $product->id,
            '{title}' => $product->translation->title,
            '{ownerId}' => $productOwner->id,
            '{ownerEmail}' => $productOwner->email,
            '{owner}' => !(empty($productOwner->profile->name . ' ' . $productOwner->profile->surname)) ?
                $productOwner->profile->name . ' ' . $productOwner->profile->surname : $productOwner->profile->info,
            '{link}' => Html::a(
                $product->translation->title,
                Url::toRoute('/shop/product/save?id=' . $product->id . '&languageId=' . Language::getCurrent()->id, true)),

        ];

        //Send mail to manager
        $mailTemplate = $this->createMailTemplate('new-product-to-manager', $mailVars);
        $partnerManagerEmail = \Yii::$app->getModule('shop')->partnerManagerEmail;

        if (!empty($mailTemplate) && !empty($partnerManagerEmail)) {
            $subject = $mailTemplate->getSubject();
            $bodyParams = ['bodyContent' => $mailTemplate->getBody()];

            $sendFrom = [\Yii::$app->get('shopMailer')->transport->getUsername() => \Yii::$app->name ?? parse_url(Url::base(true), PHP_URL_HOST)];

            $this->sendMessage($sendFrom, $partnerManagerEmail, $subject, $bodyParams);
        }

        //Send mail to partner
        $mailTemplate = $this->createMailTemplate('new-product-to-partner', $mailVars);
        if (!empty($mailTemplate) && !empty($productOwner->email)) {
            $subject = $mailTemplate->getSubject();
            $bodyParams = ['bodyContent' => $mailTemplate->getBody()];

            $sendFrom = [\Yii::$app->get('shopMailer')->transport->getUsername() => \Yii::$app->name ?? parse_url(Url::base(true), PHP_URL_HOST)];

            $this->sendMessage($sendFrom, $productOwner->email, $subject, $bodyParams);
        }
    }
1323248
public function banProductReview($eventObject) {
        if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) {
            $patterns = array();
            /* @var $review \Mage_Review_Model_Review*/
            $review = $eventObject->getObject();

            /* @var $productCollection \Mage_Review_Model_Resource_Review_Product_Collection*/
            $productCollection = $review->getProductCollection();

            $products = $productCollection->addEntityFilter((int) $review->getEntityPkValue())->getItems();

            $productIds = array_unique(array_map(
                create_function('$p', 'return $p->getEntityId();'),
                $products ));
            $patterns[] = sprintf('/review/product/list/id/(?:%s)/category/',
                implode('|', array_unique($productIds)));
            $patterns[] = sprintf('/review/product/view/id/%d/',
                $review->getEntityId());
            $productPatterns = array();
            foreach ($products as $p) {
                $urlKey = $p->getUrlModel()->formatUrlKey($p->getName());
                if ($urlKey) {
                    $productPatterns[] = $urlKey;
                }
            }
            if ( ! empty($productPatterns)) {
                $productPatterns = array_unique($productPatterns);
                $patterns[] = sprintf('(?:%s)', implode('|', $productPatterns));
            }
            $urlPattern = implode('|', $patterns);

            $result = $this->_getVarnishAdmin()->flushUrl($urlPattern);
            return $this->_checkResult($result);
        }
    }
1003243
private function loadSimpleVariation(Product $parentProduct, array $filterArray)
    {
        $childProduct = $this->swatchHelperData->loadVariationByFallback($parentProduct, $filterArray);
        if ($childProduct && !$childProduct->getImage()) {
            $childProduct = $this->swatchHelperData->loadFirstVariationWithImage($parentProduct, $filterArray);
        }
        if (!$childProduct) {
            $childProduct = $parentProduct;
        }

        return $childProduct;
    }