Returns sum of all duplicated queries

@param $modelData
@return int
@since 2.0.13
170195
public function sumDuplicateQueries($modelData)
    {
        $numDuplicates = 0;
        $duplicates = ArrayHelper::getColumn($modelData, 'duplicate');
        foreach ($duplicates as $duplicate) {
            if ($duplicate > 1) {
                $numDuplicates++;
            }
        }

        return $numDuplicates;
    }
691576
protected function determineMorphModelsForRelationData(ModelRelationData $data)
    {
        // If models were set during analysis, trust them
        if ($data->morphModels && count($data->morphModels)) {
            return $data->morphModels;
        }

        // We do not have access to modelinformation here, so
        // if it cannot be derived from data, the enrichment step must handle this using context info.
        return [];
    }
1362656
protected function mergeMethods($nodeData)/*# : array */
    {
        // no merge
        if (empty($nodeData) || isset($nodeData[0])) {
            return (array) $nodeData;
        }

        // in sections
        $result = [];
        foreach ($nodeData as $data) {
            $result = array_merge($result, $data);
        }
        return $result;
    }
303345
private function checkDatas($yamlData)
    {
        try {
            if ($yamlData === false || !is_array($yamlData) || count($yamlData) > 1) {
                throw new ClassWrapperException('Malformed class content description');
            }

            foreach ($yamlData as $classname => $contentDesc) {
                if ($this->classname != $this->_normalizeVar($this->classname)) {
                    throw new ClassWrapperException("Class Name don't match with the filename");
                }

                if (!is_array($contentDesc)) {
                    throw new ClassWrapperException('None class content description found');
                }

                foreach ($contentDesc as $key => $data) {
                    switch ($key) {
                        case 'extends':
                            $this->extends = $this->_normalizeVar($data, true);
                            if (substr($this->extends, 0, 1) != NAMESPACE_SEPARATOR) {
                                $this->extends = NAMESPACE_SEPARATOR.$this->namespace.
                                    NAMESPACE_SEPARATOR.$this->extends;
                            }

                            break;
                        case 'interfaces':
                            $data = false === is_array($data) ? array($data) : $data;
                            $this->interfaces = array();

                            foreach ($data as $i) {
                                $interface = $i;
                                if (NAMESPACE_SEPARATOR !== substr($i, 0, 1)) {
                                    $interface = NAMESPACE_SEPARATOR.$i;
                                }

                                // add interface only if it exists
                                if (true === interface_exists($interface)) {
                                    $this->interfaces[] = $interface;
                                }
                            }

                            // build up interface use string
                            $str = implode(', ', $this->interfaces);
                            if (0 < count($this->interfaces)) {
                                $this->interfaces = 'implements '.$str;
                            } else {
                                $this->interfaces = '';
                            }

                            break;
                        case 'repository':
                            if (class_exists($data)) {
                                $this->repository = $data;
                            }
                            break;
                        case 'traits':
                            $data = false === is_array($data) ? array($data) : $data;
                            $this->traits = array();

                            foreach ($data as $t) {
                                $trait = $t;
                                if (NAMESPACE_SEPARATOR !== substr($t, 0, 1)) {
                                    $trait = NAMESPACE_SEPARATOR.$t;
                                }

                                // add traits only if it exists
                                if (true === trait_exists($trait)) {
                                    $this->traits[] = $trait;
                                }
                            }

                            // build up trait use string
                            $str = implode(', ', $this->traits);
                            if (0 < count($this->traits)) {
                                $this->traits = 'use '.$str.';';
                            } else {
                                $this->traits = '';
                            }

                            break;
                        case 'elements':
                        case 'parameters':
                        case 'properties':
                            $values = array();
                            $data = (array) $data;
                            foreach ($data as $var => $value) {
                                $values[strtolower($this->_normalizeVar($var))] = $value;
                            }

                            $this->$key = $values;
                            break;
                    }
                }
            }
        } catch (ClassWrapperException $e) {
            throw new ClassWrapperException($e->getMessage(), 0, null, $this->_path);
        }

        return true;
    }
971093
public static function findFirstByName( $modelId, $name ) {

		$query	= self::queryByName( $modelId, $name );

		return $query->one();
	}
518696
protected function getCountCommonCompileLikes(array &$aData)
    {
        $oDb = Factory::service('Database');

        $aLikes = [
            'like'        => 'AND',
            'or_like'     => 'OR',
            'not_like'    => 'AND',
            'or_not_like' => 'OR',
        ];

        $aLikeCompiled = [];

        foreach ($aLikes as $sLikeType => $sLikeGlue) {

            if (!empty($aData[$sLikeType])) {

                $aLikeCompiled[$sLikeType] = [];

                if (is_array($aData[$sLikeType])) {

                    /**
                     * The value is an array. For each element we need to compile as appropriate
                     * and add to $aLikeCompiled.
                     */

                    foreach ($aData[$sLikeType] as $mWhere) {

                        if (is_string($mWhere)) {

                            /**
                             * The value is a straight up string, assume this is a compiled
                             * where string,
                             */

                            $aLikeCompiled[$sLikeType][] = $mWhere;

                        } else {

                            /**
                             * The value is an array, try and determine the various parts
                             * of the query. We use strings which are unlikely to be found
                             * as falsey values (such as null) are perfectly likely.
                             */

                            //  Work out column
                            $mColumn = isset($mWhere['column']) ? $mWhere['column'] : '[NAILS-COL-NOT-FOUND]';

                            if ($mColumn === '[NAILS-COL-NOT-FOUND]') {
                                $mColumn = isset($mWhere[0]) && is_string($mWhere[0]) ? $mWhere[0] : null;
                            }

                            //  Work out value
                            $mVal = isset($mWhere['value']) ? $mWhere['value'] : '[NAILS-VAL-NOT-FOUND]';

                            if ($mVal === '[NAILS-VAL-NOT-FOUND]') {
                                $mVal = isset($mWhere[1]) ? $mWhere[1] : null;
                            }

                            //  Escaped?
                            $bEscape = isset($mWhere['escape']) ? (bool) $mWhere['escape'] : '[NAILS-ESCAPE-NOT-FOUND]';

                            if ($bEscape === '[NAILS-ESCAPE-NOT-FOUND]') {
                                $bEscape = isset($mWhere[2]) ? $mWhere[2] : true;
                            }

                            if ($bEscape) {
                                $mVal = $oDb->escape_like_str($mVal);
                            }

                            //  If the $mColumn is an array then we should concat them together
                            if (is_array($mColumn)) {
                                $mColumn = 'CONCAT_WS(" ", ' . implode(',', $mColumn) . ')';
                            }

                            //  Got something?
                            if ($mColumn) {
                                switch ($sLikeType) {

                                    case 'like' :
                                    case 'or_like' :
                                        $aLikeCompiled[$sLikeType][] = $mColumn . ' LIKE "%' . $mVal . '%"';
                                        break;

                                    case 'not_like' :
                                    case 'or_not_like' :
                                        $aLikeCompiled[$sLikeType][] = $mColumn . ' NOT LIKE "%' . $mVal . '%"';
                                        break;
                                }
                            }
                        }
                    }

                } elseif (is_string($aData[$sLikeType])) {

                    /**
                     * The value is a straight up string, assume this is a compiled
                     * where string,
                     */

                    $aLikeCompiled[$sLikeType][] = $aData[$sLikeType];
                }
            }
        }

        /**
         * Now we need to compile all the conditionals into one big super query.
         * $aWhereStr is an array of the compressed where strings... will make
         * sense shortly...
         */

        if (!empty($aLikeCompiled)) {

            $aWhereStr = [];

            foreach ($aLikeCompiled as $sLikeType => $sValue) {
                $aWhereStr[] = '(' . implode(' ' . $aLikes[$sLikeType] . ' ', $sValue) . ')';
            }

            //  And reduce $aWhereStr to an actual string, like the name suggests
            $aWhereStr = implode(' AND ', $aWhereStr);
            $oDb->where($aWhereStr);
        }
    }
22693
public function getDuplicatedCount()
    {
        $count = 0;
        foreach ($this->getQueries() as $query) {
            if ($query['count'] > 1) {
                $count += $query['count'] - 1;
            }
        }

        return $count;
    }
911967
private function addFields($modelData)
    {
        // Default primary key
        $fields = $this->tab(3) . "\$table->increments('id');" . PHP_EOL . PHP_EOL;

        // Check primary key
        foreach ($modelData->fields as $field)
        {
            if ($field->index == 'primary')
            {
                $fields = '';
                break;
            }
        }

        foreach ($modelData->fields as $field)
        {
            $parsedModifiers = '';

            // Check modifiers
            if (!empty($field->modifiers))
            {
                $modifiersArray = explode(':', $field->modifiers);

                foreach ($modifiersArray as $modifier)
                {
                    $modifierAndValue = explode(',', $modifier);

                    if (count($modifierAndValue) == 2)
                    {
                        $parsedModifiers .= '->' . $modifierAndValue[0] . '(' . $modifierAndValue[1] . ')';
                    }
                    else
                    {
                        $parsedModifiers .= '->' . $modifierAndValue[0] . '()';
                    }
                }
            }

            // Check indexes
            if ($field->index != 'none')
            {
                $fields .= sprintf($this->tab(3) . "\$table->%s('%s')%s->%s();" . PHP_EOL, $field->type->db, $field->name, $parsedModifiers, $field->index);
            }
            else
            {
                $fields .= sprintf($this->tab(3) . "\$table->%s('%s')%s;" . PHP_EOL, $field->type->db, $field->name, $parsedModifiers);
            }

            // Check foreign key
            if (!empty($field->foreignKey))
            {
                $foreignKey = explode(':', $field->foreignKey);
                $fields .= sprintf($this->tab(3) . "\$table->foreign('%s')->references('%s')->on('%s');" . PHP_EOL . PHP_EOL, $field->name, $foreignKey[0], $foreignKey[1]);
            }
        }

        $fields .= PHP_EOL . $this->tab(3) . "\$table->timestamps();" . PHP_EOL;

        $this->stub = str_replace('{{fields}}', $fields, $this->stub);

        return $this;
    }
326491
protected function getCountCommon($data = array())
    {
        parent::getCountCommon($data);

        // --------------------------------------------------------------------------

        $oDb = Factory::service('Database');
        $oDb->select($this->tableAlias . '.*');

        if (!empty($data['include_count'])) {

            $subQuery = '
                SELECT
                    COUNT(DISTINCT post_id)
                FROM ' . NAILS_DB_PREFIX . 'blog_post_category
                WHERE
                category_id = ' . $this->tableAlias . '.id';

            $oDb->select('(' . $subQuery . ') post_count');
        }

        //  Default sort
        if (empty($data['sort'])) {

            $oDb->order_by($this->tableAlias . '.label');
        }
    }
629121
public function getUpcomingAmount(GetUpcomingAmount\RequestData $requestData = null)
    {
        if ($requestData === null) {
            $requestData = new GetUpcomingAmount\RequestData();
        }

        $request = new GetUpcomingAmount\Request($requestData);

        return $this->sendRequest($request, GetUpcomingAmount\ApiResponse::class);
    }
785225
public function addModel(array $modelData)
    {
        // swagger only has locations for requests, so we can safely default to our response serializer.
        $model = $this->createModel($modelData, $this->responseType);
        $modelData = $model->toArray();
        if ($modelData['type'] === 'array' && isset($modelData['name'])) {
            unset($modelData['name']);
        }
        $this->debug('+ adding model %s', $model->getName());
        $this->models[$model->getName()] = $modelData;

        return $model;
    }
268751
public static function count($args = false)
    {
        /* @var ActiveRecord $model */

        $query = null;
        $model = new static();

        if ($args && $args instanceof Query) {
            $query = $args;
            //$query->from = " (SELECT T.".$model->getPkName()." FROM ".$model->getTableName()." T) TEMP";
            if (empty($query->from)) {
                $query->addFrom($model->getTableName().' T');
            }
            $query->select = 'T.'.$model->getPkName();
        } elseif ($args && is_array($args)) {
            if (!isset($args['from'])) {
                $args['from'] = $model->getTableName().' T';
            }
            $query = new Query($args);
            //$query->select = 'COUNT(*)';
            $query->select = 'T.'.$model->getPkName();
        } elseif (!$args) {
            $query = new Query(
                [
                    'from' => $model->getTableName().' T',
                    'select' => 'T.'.$model->getPkName(),
                ]
            );
        } else {
            throw new Exception(translate('Bad arguments'), 500, Exception::BADARGUMENTS);
        }

        $count_query = new Query(
            [
                'select' => 'COUNT(*)',
                'from' => '('.$query->toSql().') TC',
            ]
        );

        $stmt = $model->getDB()->prepare($count_query->toSql());
        $stmt->execute($query->params);
        $records = $stmt->fetchColumn();

        $stmt->closeCursor();

        return $records;
    }
385909
protected function determineMorphModelsForRelationData(ModelRelationData $data)
    {
        if ($data->morphModels && count($data->morphModels)) {
            return $data->morphModels;
        }

        // Use information for other models in the CMS to find (some of) the related models
        $context = $this->enricher->getAllModelInformation();

        // If there is no context, silently ignore it.
        if ( ! $context) {
            // @codeCoverageIgnoreStart
            return [];
            // @codeCoverageIgnoreEnd
        }

        $models = [];

        foreach ($context as $information) {

            // If a relation is related to this model by a reverse morph relation,
            // it is an intended MorphTo targetable model.
            foreach ($information->relations as $relation) {

                if (    $this->info->modelClass() !== $relation->relatedModel
                    ||  ! in_array($relation->type, [ RelationType::MORPH_ONE, RelationType::MORPH_MANY ])
                ) {
                    continue;
                }

                $models[ $information->modelClass() ] = [];
            }
        }

        return $models;
    }
135911
private function count()
    {
        if (!$this->withoutTotalResultCount) {
            $qb = $this->cloneQb($this->queryBuilder);
            $this->resetSqlParts($qb, ['select', 'groupBy', 'orderBy'])
                ->setFirstResult(null)
                ->setMaxResults(null)
                ->select(sprintf('COUNT(DISTINCT %s)', $this->aliasDotPrimary()));
            try {
                $this->totalResultCount = $qb->getQuery()->getSingleScalarResult();
            } catch (NonUniqueResultException $e) {
                $this->totalResultCount = 0;
            } catch (\Exception $e) {
                throw new QueryBuilderException($e->getMessage());
            }
        }

        return $this->totalResultCount;
    }
796285
public function getNumRows($resultSet){
		if($this->unbuffered)
			throw new DriverException('Cannot count rows on unbuffered result.');
		if($resultSet instanceof mysqli_result)
			return $resultSet->num_rows;
		return false;
	}
208101
private function totalRecordsQuery(): int
    {
        return $this->totalIndividualsQuery()
            + $this->totalFamiliesQuery()
            + $this->totalNotesQuery()
            + $this->totalRepositoriesQuery()
            + $this->totalSourcesQuery();
    }
912377
public static function getClassData(&$classData = null) {
		$class = static::getClass();
		if( !isset(static::$knownClassData[$class]) ) {
			static::$knownClassData[$class] = (object)array(
				'sqlAdapter' => null,
			);
		}
		$classData = static::$knownClassData[$class];
		return $classData;
	}