Returns the number of aliases that link to the given stored_file

Aliases in user draft areas are not counted.

@param stored_file $storedfile
@return int
19774
public function get_references_count_by_storedfile(stored_file $storedfile) {
        global $DB;

        $params = array();
        $params['contextid'] = $storedfile->get_contextid();
        $params['component'] = $storedfile->get_component();
        $params['filearea']  = $storedfile->get_filearea();
        $params['itemid']    = $storedfile->get_itemid();
        $params['filename']  = $storedfile->get_filename();
        $params['filepath']  = $storedfile->get_filepath();

        return $this->search_references_count(self::pack_reference($params));
    }
644935
public function countPersonTeamLinks(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
    {
        $partial = $this->collPersonTeamLinksPartial && !$this->isNew();
        if (null === $this->collPersonTeamLinks || null !== $criteria || $partial) {
            if ($this->isNew() && null === $this->collPersonTeamLinks) {
                return 0;
            }

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

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

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

        return count($this->collPersonTeamLinks);
    }
982704
public function countSkillsRelatedByEndPositionId(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
    {
        $partial = $this->collSkillsRelatedByEndPositionIdPartial && !$this->isNew();
        if (null === $this->collSkillsRelatedByEndPositionId || null !== $criteria || $partial) {
            if ($this->isNew() && null === $this->collSkillsRelatedByEndPositionId) {
                return 0;
            }

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

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

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

        return count($this->collSkillsRelatedByEndPositionId);
    }
513092
protected function _getCountQuery($identifier) {
		return $this->Table
			->find()
			->where([
				$this->Table->alias() . '.model' => $identifier
			]);
	}
1353133
private function exist(File $aFile)
    {
        $count = $this->execute(
            'SELECT COUNT(*) FROM file WHERE id = :id', [':id' => $aFile->id()->id()]
        )->fetchColumn();

        return $count === 1;
    }
1340192
public function getMixedCountsForFile($file_path)
    {
        if (!isset($this->mixed_counts[$file_path])) {
            $this->mixed_counts[$file_path] = [0, 0];
        }

        return $this->mixed_counts[$file_path];
    }
126876
public function countImageReferences($uri)
    {
        $path = $this->redecorator->redecorateFromSource($uri);

        $connection = $this->getConnection();

        $selectQuery = $connection->createSelectQuery();
        $selectQuery->select(
            $selectQuery->expr->count(
                $connection->quoteColumn('id')
            )
        )->from(
            $connection->quoteTable('ezimagefile')
        )->where(
            $selectQuery->expr->like(
                $connection->quoteColumn('filepath'),
                $selectQuery->bindValue($path . '%')
            )
        );

        $statement = $selectQuery->prepare();
        $statement->execute();

        return (int)$statement->fetchColumn();
    }
799928
protected function getLastNonDefaultArgumentIndex(File $phpcsFile, int $startIndex, int $endIndex): ?int
    {
        $tokens = $phpcsFile->getTokens();

        for ($i = $endIndex - 1; $i > $startIndex; --$i) {
            $token = $tokens[$i];

            if ($this->isGivenKind(T_EQUAL, $token)) {
                $i = (int)$phpcsFile->findPrevious(T_VARIABLE, $i - 1) ?: null;
                $i = (int)$phpcsFile->findPrevious(Tokens::$emptyTokens, $i, $startIndex - 1, true) ?: null;
                continue;
            }

            if ($this->isGivenKind(T_VARIABLE, $token) && !$this->isEllipsis($phpcsFile, $i)) {
                return $i;
            }
        }

        return null;
    }
712564
public function selectCount(string $column = '*', string $alias = null): string
    {
        return 'SELECT ' . $this->count($column, $alias);
    }
1144865
protected function getUseStatements(File $phpcsFile): array
    {
        $tokens = $phpcsFile->getTokens();

        $statements = [];
        foreach ($tokens as $index => $token) {
            if ($token['code'] !== T_USE || $token['level'] > 0) {
                continue;
            }

            $useStatementStartIndex = $phpcsFile->findNext(Tokens::$emptyTokens, $index + 1, null, true);

            // Ignore function () use ($foo) {}
            if ($tokens[$useStatementStartIndex]['content'] === '(') {
                continue;
            }

            $semicolonIndex = $phpcsFile->findNext(T_SEMICOLON, $useStatementStartIndex + 1);
            $useStatementEndIndex = $phpcsFile->findPrevious(Tokens::$emptyTokens, $semicolonIndex - 1, null, true);

            $statement = '';
            for ($i = $useStatementStartIndex; $i <= $useStatementEndIndex; $i++) {
                $statement .= $tokens[$i]['content'];
            }

            if ($this->isMultipleUseStatement($statement)) {
                continue;
            }

            $statementParts = preg_split('/\s+as\s+/i', $statement);

            if (count($statementParts) === 1) {
                $fullName = $statement;
                $statementParts = explode('\\', $fullName);
                $shortName = end($statementParts);
                $alias = null;
            } else {
                $fullName = $statementParts[0];
                $alias = $statementParts[1];
                $statementParts = explode('\\', $fullName);
                $shortName = end($statementParts);
            }

            $shortName = trim($shortName);
            $fullName = trim($fullName);
            $key = $alias ?: $shortName;

            $statements[$key] = [
                'alias' => $alias,
                'end' => $semicolonIndex,
                'fullName' => ltrim($fullName, '\\'),
                'shortName' => $shortName,
                'start' => $index,
            ];
        }

        return $statements;
    }
1199859
public function cache_file_by_reference($reference, $storedfile) {
        try {
            $this->import_external_file_contents($storedfile, $this->max_cache_bytes());
        } catch (Exception $e) {
            // Cache failure should not cause a fatal error. This is only a nice-to-have feature.
        }
    }
212537
private function determineCount($items, &$count, $idList)
    {
        $usedOptionsIdList = \array_unique(\array_filter(\array_map(
            function ($item) {
                /** @var IItem $item */
                return $item->get('id');
            },
            \iterator_to_array($items)
        )));

        if (empty($usedOptionsIdList)) {
            return;
        }

        $valueCol = $this->getColName();
        $query    = $this->connection->createQueryBuilder()
            ->select($this->getColName())
            ->addSelect(\sprintf('COUNT(%s) AS count', $this->getColName()))
            ->from($this->getMetaModel()->getTableName())
            ->where($this->getColName() . ' IN (:ids)')
            ->groupBy($this->getColName())
            ->setParameter('ids', $usedOptionsIdList, Connection::PARAM_STR_ARRAY);
        if ($idList !== null && !empty($idList)) {
            $query
                ->andWhere('id IN (:idList)')
                ->setParameter('idList', $idList, Connection::PARAM_STR_ARRAY);
        }
        $query = $query->execute();

        while ($row = $query->fetch(\PDO::FETCH_ASSOC)) {
            $count[$row->{$valueCol}] = $row->count;
        }
    }
240792
function count($filter=NULL,array $options=NULL,$ttl=0) {
		if (!($subquery_mode=($options && !empty($options['group']))))
			$this->adhoc['_rows']=['expr'=>'COUNT(*)','value'=>NULL];
		$adhoc=[];
		foreach ($this->adhoc as $key=>$field)
			// Add all adhoc fields
			// (make them available for grouping, sorting, having)
			$adhoc[]=$field['expr'].' AS '.$this->db->quotekey($key);
		$fields=implode(',',$adhoc);
		if ($subquery_mode) {
			if (empty($fields))
				// Select at least one field, ideally the grouping fields
				// or sqlsrv fails
				$fields=preg_replace('/HAVING.+$/i','',$options['group']);
			if (preg_match('/mssql|dblib|sqlsrv/',$this->engine))
				$fields='TOP 100 PERCENT '.$fields;
		}
		list($sql,$args)=$this->stringify($fields,$filter,$options);
		if ($subquery_mode)
			$sql='SELECT COUNT(*) AS '.$this->db->quotekey('_rows').' '.
				'FROM ('.$sql.') AS '.$this->db->quotekey('_temp');
		$result=$this->db->exec($sql,$args,$ttl);
		unset($this->adhoc['_rows']);
		return (int)$result[0]['_rows'];
	}
490195
public function getFileLineCount($file)
    {
        $count = 0;

        try {
            if (false === strpos($file, $this->container->getParameter('kernel.project_dir'))) {
                $file = $this->container->getParameter('kernel.project_dir').$file;
            }

            $handle = fopen($file, 'r');
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }

        while (!feof($handle)) {
            $line = fgets($handle);
            ++$count;
        }

        fclose($handle);

        return $count;
    }
620802
private function _count()
    {
        if ($this->group_id)
            $join = " LEFT JOIN " . $this->db->table_name($this->db_groupmembers, true) . " AS m".
                " ON (m.`contact_id` = c.`".$this->primary_key."`)";

        // count contacts for this user
        $sql_result = $this->db->query(
            "SELECT COUNT(c.`contact_id`) AS cnt".
            " FROM " . $this->db->table_name($this->db_name, true) . " AS c".
                $join.
            " WHERE c.`del` <> 1".
            " AND c.`user_id` = ?".
            ($this->group_id ? " AND m.`contactgroup_id` = ?" : "").
            ($this->filter ? " AND (".$this->filter.")" : ""),
            $this->user_id,
            $this->group_id
        );

        $sql_arr = $this->db->fetch_assoc($sql_result);

        $this->cache['count'] = (int) $sql_arr['cnt'];

        return $this->cache['count'];
    }
808282
public function countRel($key, $alias=null, $filter=null, $option=null) {
		if (!$alias)
			$alias = 'count_'.$key;
		$filter_bak = null;
		if ($filter || $option) {
			$filter_bak = isset($this->relFilter[$key]) ? $this->relFilter[$key] : false;
			$this->filter($key,$filter,$option);
		}
		if (isset($this->fieldConf[$key])){
			// one-to-one, one-to-many
			if ($this->fieldConf[$key]['relType'] == 'belongs-to-one') {
				if ($this->dbsType == 'sql') {
					$this->mapper->set($alias,'count('.$this->db->quotekey($key).')');
					$this->grp_stack=(!$this->grp_stack)?$key:$this->grp_stack.','.$key;
					if ($this->whitelist && !in_array($alias,$this->whitelist))
						$this->whitelist[] = $alias;
				} elseif ($this->dbsType == 'mongo')
					$this->_mongo_addGroup(array(
						'keys'=>array($key=>1),
						'reduce' => 'prev.'.$alias.'++;',
						"initial" => array($alias => 0)
					));
				else
					trigger_error('Cannot add direct relational counter.',E_USER_ERROR);
			} elseif($this->fieldConf[$key]['relType'] == 'has-many') {
				$relConf=$this->fieldConf[$key]['has-many'];
				if ($relConf['hasRel']=='has-many') {
					// many-to-many
					if ($this->dbsType == 'sql') {
						$mmTable = $this->mmTable($relConf,$key);
						$filter = array($mmTable.'.'.$relConf['relField']
							.' = '.$this->table.'.'.$this->primary);
						$from = $this->db->quotekey($mmTable);
						if (array_key_exists($key, $this->relFilter) &&
							!empty($this->relFilter[$key][0])) {
							$options=array();
							$from = $this->db->quotekey($mmTable).' '.
								$this->_sql_left_join($key,$mmTable,$relConf['relPK'],$relConf['relTable']);
							$relFilter = $this->relFilter[$key];
							$this->_sql_mergeRelCondition($relFilter,$relConf['relTable'],
								$filter,$options);
						}
						$filter = $this->queryParser->prepareFilter($filter,
							$this->dbsType, $this->db, $this->fieldConf);
						$crit = array_shift($filter);
						if (count($filter)>0)
							$this->preBinds=array_merge($this->preBinds,$filter);
						$this->mapper->set($alias,
							'(select count('.$this->db->quotekey($mmTable.'.'.$relConf['relField']).')'.
							' from '.$from.' where '.$crit.
							' group by '.$this->db->quotekey($mmTable.'.'.$relConf['relField']).')');
						if ($this->whitelist && !in_array($alias,$this->whitelist))
							$this->whitelist[] = $alias;
					} else {
						// count rel
						$this->countFields[]=$key;
					}
				} elseif($this->fieldConf[$key]['has-many']['hasRel']=='belongs-to-one') {
					// many-to-one
					if ($this->dbsType == 'sql') {
						$fConf=$relConf[0]::resolveConfiguration();
						$fTable=$fConf['table'];
						$fAlias=$fTable.'__count';
						$rKey=$relConf[1];
						$crit = $fAlias.'.'.$rKey.' = '.$this->table.'.'.$relConf['relField'];
						$filter = $this->mergeWithRelFilter($key,array($crit));
						$filter[0] = $this->queryParser->sql_prependTableToFields($filter[0],$fAlias);
						$filter = $this->queryParser->prepareFilter($filter,
							$this->dbsType, $this->db, $this->fieldConf);
						$crit = array_shift($filter);
						if (count($filter)>0)
							$this->preBinds=array_merge($this->preBinds,$filter);
						$this->mapper->set($alias,
							'(select count('.$this->db->quotekey($fAlias.'.'.$fConf['primary']).') from '.
							$this->db->quotekey($fTable).' AS '.$this->db->quotekey($fAlias).' where '.
							$crit.' group by '.$this->db->quotekey($fAlias.'.'.$rKey).')');
						if ($this->whitelist && !in_array($alias,$this->whitelist))
							$this->whitelist[] = $alias;
					} else {
						// count rel
						$this->countFields[]=$key;
					}
				}
			}
		}
		if ($filter_bak!==null) {
			if ($filter_bak)
				$this->relFilter[$key] = $filter_bak;
			else
				$this->clearFilter($key);
		}
	}
826320
public function findFirstOnLine(File $phpcsFile, $start)
    {
        $tokens = $phpcsFile->getTokens();

        for ($i = $start; $i >= 0; $i--) {
            if ($tokens[$i]['line'] === $tokens[$start]['line']) {
                continue;
            }

            return ($i + 1);
        }

        return false;
    }