Saves and returns category article count into cache

@param array  $aCache    Category cache data
@param string $sCatId    Unique category identifier
@param string $sActIdent ID

@return int
167480
public function setCatArticleCount($aCache, $sCatId, $sActIdent)
    {
        $oArticle = oxNew(\OxidEsales\Eshop\Application\Model\Article::class);
        $sTable = $oArticle->getViewName();
        $sO2CView = getViewName('oxobject2category');
        $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        // we use distinct if article is assigned to category twice
        $sQ = "SELECT COUNT( DISTINCT $sTable.`oxid` )
               FROM $sO2CView
                   INNER JOIN $sTable ON $sO2CView.`oxobjectid` = $sTable.`oxid` AND $sTable.`oxparentid` = ''
               WHERE $sO2CView.`oxcatnid` = " . $oDb->quote($sCatId) . " AND " . $oArticle->getSqlActiveSnippet();

        $aCache[$sCatId][$sActIdent] = $oDb->getOne($sQ);

        $this->_setCatCache($aCache);

        return $aCache[$sCatId][$sActIdent];
    }
789741
public function countByType($viewableType): int
    {
        if ($viewableType instanceof ViewableContract) {
            $viewableType = $viewableType->getMorphClass();
        }

        $cacheKey = Key::createForType($viewableType, $this->period ?? Period::create(), $this->unique);

        // Return cached views count if it exists
        if ($this->shouldCache) {
            $cachedViewsCount = $this->cache->get($cacheKey);

            if ($cachedViewsCount !== null) {
                return (int) $cachedViewsCount;
            }
        }

        $query = app(ViewContract::class)->where('viewable_type', $viewableType);

        if ($period = $this->period) {
            $query->withinPeriod($period);
        }

        if ($this->unique) {
            $viewsCount = $query->uniqueVisitor()->count('visitor');
        } else {
            $viewsCount = $query->count();
        }

        if ($this->shouldCache) {
            $this->cache->put($cacheKey, $viewsCount, $this->cacheLifetime);
        }

        return $viewsCount;
    }
1020676
public function setLangCache($sCacheName, $aLangCache)
    {
        $sCache = "<?php\n\$aLangCache = " . var_export($aLangCache, true) . ";\n?>";
        $sFileName = $this->getCacheFilePath($sCacheName);
        $cacheDirectory = \OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('sCompileDir');

        $tmpFile = $cacheDirectory . basename($sFileName) . uniqid('.temp', true) . '.txt';
        $blRes = file_put_contents($tmpFile, $sCache, LOCK_EX);

        rename($tmpFile, $sFileName);

        return $blRes;
    }
702693
public static function getCategoriesCount($filter = array())
    {
        $filter = Filter::create($filter);
        return self::getCount('/categories/count' . $filter->toQuery());
    }
370882
public static function setMostReadCache()
    {
        // check if a article has been read
        if(Cache::has("most_read_articles_ids")) {
            // current date and time
            $currentDate = new DateTime();

            // use to refresh the cache "most_read_articles_ids", removes posts that are older then 2 days
            $mostReadIDs = [];

            // used to make a new array with postID as key end the count (how many times is the post read) as value
            $postByCount = [];

            // get the cached post
            $currentMostReadIDs = Cache::get("most_read_articles_ids");
            foreach($currentMostReadIDs as $key => $post){
                $diff = (int) $currentDate->diff($post['date'])->format("%d");
                if($diff <= 2) {
                    $mostReadIDs[$key] = $post;
                    $postByCount[$key] = $post['count'];
                }
            }

            // save most read id
            Cache::forever("most_read_articles_ids", $mostReadIDs);

            // @TODO cache duhet em u gjeneru prej cron-it, jo çdo here sa te hapet nje artikull me ba kete query
            if(false && $postByCount) {
                // sort posts by count DESC
                arsort($postByCount);

                // get only the 10 most read posts IDs
                $mostReadPostIDs = array_slice(array_keys($postByCount), 0, 10);

                // get post from db
                $post = new Post();
                $post->setTable("post_articles");
                $posts = $post->whereIn("postID", $mostReadPostIDs)->get()->keyBy("postID");

                // make array for cache and arrange the posts with the most read
                $mosReadPosts = [];
                foreach ($mostReadPostIDs as $id) {
                    if (isset($posts[$id])) {
                        $mosReadPosts[$id] = $posts[$id];
                    }
                }

                Cache::forever("most_read_articles", $mosReadPosts);
            }
        }
    }
683139
public function getManufacturerArticleCount($sManufacturerId)
    {
        // current category unique ident
        $sActIdent = $this->_getUserViewId();

        // loading from cache
        $aManufacturerData = $this->_getManufacturerCache();
        if (!$aManufacturerData || !isset($aManufacturerData[$sManufacturerId][$sActIdent])) {
            $iCnt = $this->setManufacturerArticleCount($aManufacturerData, $sManufacturerId, $sActIdent);
        } else {
            $iCnt = $aManufacturerData[$sManufacturerId][$sActIdent];
        }

        return $iCnt;
    }
1142125
public function countKstruktursRelatedBySkillId(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
    {
        $partial = $this->collKstruktursRelatedBySkillIdPartial && !$this->isNew();
        if (null === $this->collKstruktursRelatedBySkillId || null !== $criteria || $partial) {
            if ($this->isNew() && null === $this->collKstruktursRelatedBySkillId) {
                return 0;
            }

            if ($partial && !$criteria) {
                return count($this->getKstruktursRelatedBySkillId());
            }

            $query = ChildKstrukturQuery::create(null, $criteria);
            if ($distinct) {
                $query->distinct();
            }

            return $query
                ->filterBySkillRelatedBySkillId($this)
                ->count($con);
        }

        return count($this->collKstruktursRelatedBySkillId);
    }
160660
public function track($key, $decayMinutes = 1)
    {
        $this->cache->add($key, 1, $decayMinutes);

        return (int) $this->cache->increment($key);
    }
862012
protected function _getCategoryCacheLifetime(\Cms\Orm\CmsCategoryRecord $category)
    {
        //czas buforowania (na podstawie typu kategorii i pojedynczej kategorii
        $cacheLifetime = (null !== $category->cacheLifetime) ? $category->cacheLifetime : ((null !== $category->getJoined('cms_category_type')->cacheLifetime) ? $category->getJoined('cms_category_type')->cacheLifetime : Orm\CmsCategoryRecord::DEFAULT_CACHE_LIFETIME);
        //jeśli bufor wyłączony (na poziomie typu kategorii, lub pojedynczej kategorii)
        if (0 == $cacheLifetime) {
            //brak bufora
            return 0;
        }
        //iteracja po widgetach
        foreach ($category->getWidgetModel()->getWidgetRelations() as $widgetRelation) {
            //bufor wyłączony przez widget
            if (0 == $widgetCacheLifetime = $widgetRelation->getWidgetRecord()->cacheLifetime) {
                //brak bufora
                return 0;
            }
            //wpływ widgeta na czas buforowania kategorii
            $cacheLifetime = ($cacheLifetime > $widgetCacheLifetime) ? $widgetCacheLifetime : $cacheLifetime;
        }
        //zwrot długości bufora
        return $cacheLifetime;
    }
179279
public function inPriceCategory($sCatNid)
    {
        $blIn = false;
        if (($oParent = $this->getParent())) {
            $blIn = $oParent->inPriceCategory($sCatNid);
        }

        return $blIn;
    }
967233
@Override
	public int countByCPOptionCategoryId(long CPOptionCategoryId) {
		FinderPath finderPath = FINDER_PATH_COUNT_BY_CPOPTIONCATEGORYID;

		Object[] finderArgs = new Object[] { CPOptionCategoryId };

		Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_CPSPECIFICATIONOPTION_WHERE);

			query.append(_FINDER_COLUMN_CPOPTIONCATEGORYID_CPOPTIONCATEGORYID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(CPOptionCategoryId);

				count = (Long)q.uniqueResult();

				finderCache.putResult(finderPath, finderArgs, count);
			}
			catch (Exception e) {
				finderCache.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}
526022
public function getRatingCount($sObjectId, $sType, $aIncludedObjectsIds = null)
    {
        $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        $sQuerySnipet = " AND `oxobjectid` = " . $oDb->quote($sObjectId);
        if (is_array($aIncludedObjectsIds) && count($aIncludedObjectsIds) > 0) {
            $sQuerySnipet = " AND ( `oxobjectid` = " . $oDb->quote($sObjectId) . " OR `oxobjectid` in ('" . implode("', '", $aIncludedObjectsIds) . "') )";
        }

        $sSelect = "
            SELECT
                COUNT(*)
            FROM `oxreviews`
            WHERE `oxrating` > 0
                AND `oxtype` = " . $oDb->quote($sType)
                   . $sQuerySnipet . "
            LIMIT 1";

        // We force reading from master to prevent issues with slow replications or open transactions (see ESDEV-3804).
        $masterDb = \OxidEsales\Eshop\Core\DatabaseProvider::getMaster();
        $iCount = $masterDb->getOne($sSelect);

        return $iCount;
    }
555897
protected function _insertArticles($sHeapTable, $sCatAdd)
    {
        $oDB = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();

        $iExpLang = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("iExportLanguage");
        if (!isset($iExpLang)) {
            $iExpLang = \OxidEsales\Eshop\Core\Registry::getSession()->getVariable("iExportLanguage");
        }

        $oArticle = oxNew(\OxidEsales\Eshop\Application\Model\Article::class);
        $oArticle->setLanguage($iExpLang);

        $sO2CView = getViewName('oxobject2category', $iExpLang);
        $sArticleTable = getViewName("oxarticles", $iExpLang);

        $insertQuery = "insert into {$sHeapTable} select {$sArticleTable}.oxid from {$sArticleTable}, {$sO2CView} as oxobject2category where ";
        $insertQuery .= $oArticle->getSqlActiveSnippet();

        if (!\OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("blExportVars")) {
            $insertQuery .= " and {$sArticleTable}.oxid = oxobject2category.oxobjectid and {$sArticleTable}.oxparentid = '' ";
        } else {
            $insertQuery .= " and ( {$sArticleTable}.oxid = oxobject2category.oxobjectid or {$sArticleTable}.oxparentid = oxobject2category.oxobjectid ) ";
        }

        $sSearchString = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("search");
        if (isset($sSearchString)) {
            $insertQuery .= "and ( {$sArticleTable}.OXTITLE like " . $oDB->quote("%{$sSearchString}%");
            $insertQuery .= " or {$sArticleTable}.OXSHORTDESC like " . $oDB->quote("%$sSearchString%");
            $insertQuery .= " or {$sArticleTable}.oxsearchkeys like " . $oDB->quote("%$sSearchString%") . " ) ";
        }

        if ($sCatAdd) {
            $insertQuery .= $sCatAdd;
        }

        // add minimum stock value
        if (\OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('blUseStock') && ($dMinStock = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("sExportMinStock"))) {
            $dMinStock = str_replace([";", " ", "/", "'"], "", $dMinStock);
            $insertQuery .= " and {$sArticleTable}.oxstock >= " . $oDB->quote($dMinStock);
        }

        $insertQuery .= " group by {$sArticleTable}.oxid";

        return $oDB->execute($insertQuery) ? true : false;
    }
563862
static function fetchCountByVatType( $vatID )
    {
        $rows = eZPersistentObject::fetchObjectList( eZVatRule::definition(),
                                                     array(),
                                                     array( 'vat_type' => (int) $vatID ),
                                                     false,
                                                     null,
                                                     false,
                                                     false,
                                                     array( array( 'operation' => 'count( * )',
                                                                   'name' => 'count' ) ) );
        return $rows[0]['count'];
    }
72216
public function GetCategoryPathAsString($sSeparator = '/')
    {
        $sKey = 'sCatPathCache'.$sSeparator;

        $sPath = $this->GetFromInternalCache($sKey);
        if (is_null($sPath)) {
            $sPath = '';
            $oParent = &$this->GetParent();
            if ($oParent) {
                $sPath = $oParent->GetCategoryPathAsString($sSeparator);
            }
            if (!empty($sPath)) {
                $sPath .= $sSeparator;
            }
            $sPath .= $this->GetName();
            $this->SetInternalCache($sKey, $sPath);
        }

        return $sPath;
    }
865220
public function AddArticle($sArticleId, $dAmount = 1, $sComment = null)
    {
        $dNewAmount = 0;
        $aItemData = array();
        $oItem = TdbPkgShopWishlistArticle::GetNewInstance();
        /** @var $oItem TdbPkgShopWishlistArticle */
        if ($oItem->LoadFromFields(array('pkg_shop_wishlist_id' => $this->id, 'shop_article_id' => $sArticleId))) {
            $aItemData = $oItem->sqlData;
            $aItemData['amount'] += $dAmount;
        } else {
            $aItemData['pkg_shop_wishlist_id'] = $this->id;
            $aItemData['shop_article_id'] = $sArticleId;
            $aItemData['amount'] = $dAmount;
            $aItemData['datecreated'] = date('Y-m-d H:i:s');
        }
        if (!is_null($sComment)) {
            $aItemData['comment'] = $oItem->LoadFromRow($aItemData);
        }
        $oItem->LoadFromRow($aItemData);
        $oItem->AllowEditByAll(true);
        $oItem->Save();
        $dNewAmount = $aItemData['amount'];

        return $dNewAmount;
    }
132067
protected function getIdCategoryByKey(string $categoryKey): int
    {
        if (!isset($this->idCategoryCache[$categoryKey])) {
            /** @var \Orm\Zed\Category\Persistence\SpyCategoryQuery $categoryQuery */
            $categoryQuery = SpyCategoryQuery::create()
                ->select(SpyCategoryTableMap::COL_ID_CATEGORY);

            /** @var int|null $idCategory */
            $idCategory = $categoryQuery->findOneByCategoryKey($categoryKey);

            if (!$idCategory) {
                throw new EntityNotFoundException(sprintf('Could not find Category by key "%s"', $categoryKey));
            }
            $this->idCategoryCache[$categoryKey] = $idCategory;
        }

        return $this->idCategoryCache[$categoryKey];
    }