@param QueryBuilder $builder
@param string       $modelClass

@return array

@throws DBALException

@SuppressWarnings(PHPMD.ElseExpression)
492205
private function fetchResourceCollection(QueryBuilder $builder, string $modelClass): array
    {
        $statement = $builder->execute();

        $models           = [];
        $counter          = 0;
        $hasMoreThanLimit = false;
        $limit            = $builder->getMaxResults() !== null ? $builder->getMaxResults() - 1 : null;

        if ($this->isFetchTyped() === true) {
            $platform  = $builder->getConnection()->getDatabasePlatform();
            $typeNames = $this->getModelSchemas()->getAttributeTypes($modelClass);
            $statement->setFetchMode(PDOConnection::FETCH_ASSOC);
            while (($attributes = $statement->fetch()) !== false) {
                $counter++;
                if ($limit !== null && $counter > $limit) {
                    $hasMoreThanLimit = true;
                    break;
                }
                $models[] = $this->readResourceFromAssoc($modelClass, $attributes, $typeNames, $platform);
            }
        } else {
            $statement->setFetchMode(PDOConnection::FETCH_CLASS, $modelClass);
            while (($fetched = $statement->fetch()) !== false) {
                $counter++;
                if ($limit !== null && $counter > $limit) {
                    $hasMoreThanLimit = true;
                    break;
                }
                $models[] = $fetched;
            }
        }

        return [$models, $hasMoreThanLimit, $limit, $builder->getFirstResult()];
    }
477506
protected function getQueryBuilderForModelClass($modelClass)
    {
        if ( ! is_a($modelClass, Model::class, true)) {
            throw new UnexpectedValueException("{$modelClass} is not an Eloquent model.");
        }

        // If the targeted model is a CMS model, we can default back to its reference data
        // if not specifics are given, otherwise, a custom fallback reference must be used.
        if ($info = $this->getCmsModelInformation($modelClass)) {

            // Get model records, filtered as necessary
            $repository = $this->getModelRepositoryForInformation($info);

            /** @var Model[] $models */
            return $repository->query();
        }

        // The model is not part of the CMS
        return $this->getQueryBuilderForNonCmsModelClass($modelClass);
    }
260117
private function _getRelatedFks($data, $relation, $modelClass)
    {
        $fks = [];
        if (is_array($data)) {
            // Get the right link definition
            if ($relation->via instanceof BaseActiveRecord) {
                $link = $relation->via->link;
            } elseif (is_array($relation->via)) {
                list($viaName, $viaQuery) = $relation->via;
                $link = $viaQuery->link;
            } else {
                $link = $relation->link;
            }
            // search PK
            foreach ($modelClass::primaryKey() as $modelAttribute) {
                if (isset($data[$modelAttribute])) {
                    $fks[$modelAttribute] = $data[$modelAttribute];
                } elseif ($relation->multiple && !$relation->via) {
                    foreach ($link as $relatedAttribute => $relatedModelAttribute) {
                        if (!isset($data[$relatedAttribute]) && in_array($relatedAttribute, $modelClass::primaryKey())) {
                            $fks[$relatedAttribute] = $this->owner->{$relatedModelAttribute};
                        }
                    }
                } else {
                    $fks = [];
                    break;
                }
            }
            if (empty($fks)) {
                foreach ($link as $relatedAttribute => $modelAttribute) {
                    if (isset($data[$modelAttribute])) {
                        $fks[$modelAttribute] = $data[$modelAttribute];
                    }
                }
            }
        } else {
            $fks = $data;
        }
        return $fks;
    }
1279797
public static function modelIdsQueryAtOnce($modelClass, $values)
    {
        $q = (new Query())
            ->select('model_id')
            ->from($modelClass::tableInheritanceTable());

        foreach ($values as $key => $vals) {
            $q->andWhere(['or', $key, $vals]);
        };

            $q->groupBy('model_id');
        return $q;
    }
1063370
protected function parseBuilder($builder)
    {
        if ($builder instanceof EloquentBuilder) {
            return $this->createHandler($builder->getQuery(), $builder);
        }
        if (is_subclass_of($builder, Model::class)) {
            return $this->createHandler($builder->getQuery(), $builder->newQuery());
        }
        if ($builder instanceof QueryBuilder) {
            return $this->createHandler($builder, $builder);
        }
    }
878757
public function find(Driver $driver, $modelClass, $id)
    {
        $this->managerFactory->setModelClass($modelClass);

        return $this->managerFactory->getManager($driver)->find($id);
    }
821691
public function analyze($modelClass)
    {
        $information = new ModelInformation;

        $information->model          = $modelClass;
        $information->original_model = $modelClass;

        $this->makeModelInstance($modelClass);

        foreach ($this->getSteps() as $stepClass) {

            /** @var AnalyzerStepInterface $step */
            $step = app($stepClass);

            $information = $step->setAnalyzer($this)->analyze($information);
        }

        return $information;
    }
455148
public function fetchColumn(QueryBuilder $builder, string $modelClass, string $columnName): iterable
    {
        $statement = $builder->execute();
        $statement->setFetchMode(PDOConnection::FETCH_ASSOC);

        if ($this->isFetchTyped() === true) {
            $platform = $builder->getConnection()->getDatabasePlatform();
            $typeName = $this->getModelSchemas()->getAttributeTypes($modelClass)[$columnName];
            $type     = Type::getType($typeName);
            while (($attributes = $statement->fetch()) !== false) {
                $value     = $attributes[$columnName];
                $converted = $type->convertToPHPValue($value, $platform);

                yield $converted;
            }
        } else {
            while (($attributes = $statement->fetch()) !== false) {
                $value = $attributes[$columnName];

                yield $value;
            }
        }

        $this->clearFetchParameters();
    }
159415
public function setModelClass($model_class): Repository
	{
		if ( !is_subclass_of($model_class, Model::class)) {
			throw new InvalidArgumentException('Specified model class must be an instance of ' . Model::class);
		}

		$this->model_class = $model_class;

		/** @var \Illuminate\Database\Eloquent\Model|\Fuzz\MagicBox\Contracts\MagicBoxResource $instance */
		$instance = new $model_class;

		// @todo use set methods
		$this->setFillable($instance->getRepositoryFillable());
		$this->setIncludable($instance->getRepositoryIncludable());
		$this->setFilterable($instance->getRepositoryFilterable());

		$this->key_name = $instance->getKeyName();

		return $this;
	}
294283
public function batchDelete($class, ProxyQueryInterface $queryProxy)
    {
        try {
            $i = 0;
            $res = $queryProxy->execute();
            foreach ($res as $object) {
                $this->dm->remove($object);

                if (0 == (++$i % 20)) {
                    $this->dm->flush();
                    $this->dm->clear();
                }
            }

            $this->dm->flush();
            $this->dm->clear();
        } catch (\Exception $e) {
            throw new ModelManagerException('', 0, $e);
        }
    }
701319
public function queryMethods(QueryBuilder $builder)
    {
        $script = '';
        $script .= $this->addArchive($builder);
        if ($this->behavior->isArchiveOnUpdate()) {
            $script .= $this->addSetArchiveOnUpdate($builder);
            $script .= $this->addUpdateWithoutArchive($builder);
        }
        if ($this->behavior->isArchiveOnDelete()) {
            $script .= $this->addSetArchiveOnDelete($builder);
            $script .= $this->addDeleteWithoutArchive($builder);
        }

        return $script;
    }
1369082
public function findModelClassObject($modelClass, $id, $relationContext)
    {
        $keys = $modelClass::primaryKey();
        if (count($keys) > 1) {
            $values = explode(',', $id);
            if (count($keys) === count($values)) {
                return $this->findModelFromCondition(array_combine($keys, $values), $keys, $modelClass, $relationContext);
            }
        } elseif ($id !== null) {
            return $this->findModelFromCondition($id, $keys, $modelClass, $relationContext);
        }

        return false;
    }
1020445
protected function getModelColumns($class)
    {
        $attributes = [];

        $classNamespace = $this->getModelNamespace($class);

        if ($class) {
            if (class_exists($classNamespace)) {
                $model = new \ReflectionClass($classNamespace);

                if ($model->isSubclassOf('Illuminate\Database\Eloquent\Model')) {
                    $mdl = $this->app->make($classNamespace);
                    $table = $mdl->getTable();

                    if (is_array($table)) {
                        $table = array_first($table);
                    }

                    $table = $mdl->getConnection()->getTablePrefix().$table;
                    $schema = $mdl->getConnection()->getDoctrineSchemaManager($table);

                    $database = null;
                    if (strpos($table, '.')) {
                        list($database, $table) = explode('.', $table);
                    }

                    $columns = Arr::except($schema->listTableColumns($table, $database), $mdl->getHidden());

                    foreach ($columns as $column) {
                        if ($column->getType() instanceof \Doctrine\DBAL\Types\JsonArrayType) {
                            continue;
                        }

                        $castTo = $this->getCasting($column->getType());

                        $attributes[] = ['column' => $column->getName(), 'casts' => $castTo];
                    }

                    return $attributes;
                }
            } else {
                $this->error("Your model {$class} was not found in {$this->config->get('fractal.model_namespace')}\\ \r\nIf this is the first time you get this message, try to update /config/fractal.php to make changes to model_namespace accordingly.");
                exit();
            }
        }

        // use as a default attribute
        return [
            ['column' => 'id', 'casts' => null],
        ];
    }
598060
public static  function createQuery($modelClass, $ignore=[])
    {
        $model = $modelClass::find();
        $wheres = ['and'];
        $filter_fields = self::getQueryParams($ignore);
        $condition_transform_functions = self::conditionTransformFunctions();

        foreach($filter_fields as $key => $value){
            if($value == '' || in_array($key,self::$exclude_field))
                continue;
            $field_key = $key;
            if(!strpos($key,'.')){
                $field_key =  $modelClass::tableName().'.'.$key ;
            }else{
                $relation_model = substr($field_key,0,strrpos($key,'.'));
                $model->joinWith($relation_model);
                if(strpos($relation_model,'.')){
                    $temp = substr($field_key,strrpos($field_key,'.'));
                    $field_key = substr($relation_model,strrpos($relation_model,'.')+1).$temp;
                    $field_key = str_replace($relation_model, $relation_model::tableName(), $field_key);
                } else {
                    // Build the relation's tale name
                    $baseModel = new $modelClass;
                    $relationModel = $baseModel->getRelation($relation_model);
                    $relationModel = new $relationModel->modelClass;
                    $field_key = str_replace($relation_model . '.', $relationModel->tableName() . '.', $field_key);
                }
            }

            $type = 'EQUAL';
            if(preg_match("/^[A-Z]+_/",$value, $matches) && array_key_exists(trim($matches[0],'_'),$condition_transform_functions)){
                $type = trim($matches[0],'_');
                $value = str_replace($matches[0],'',$value);
            }

            $wheres = ArrayHelper::merge($wheres, [$condition_transform_functions[$type]($field_key,$value)]);
        }

        if(count($wheres) > 1) {
            $model->andWhere($wheres);
        }

        return $model;
    }
485724
public function getClassMetadata(Driver $driver, $modelClass)
    {
        $manager = $this->managerFactory->getManager($driver);
        $manager->setModelClass($modelClass);

        return $manager->getClassMetadata();
    }
200735
public function build(string $modelClass): IEntityService
    {
        if (!isset($this->sharedInstances[$modelClass]) || $this->sharedInstances[$modelClass] === null) {
            $this->sharedInstances[$modelClass] = $this->buildEntityService($modelClass);
        }
        return $this->sharedInstances[$modelClass];
    }
350916
public function apply(Builder $builder, Model $model) {
    $subclassTypes = array_keys($model->getSingleTableTypeMap());

    if (!empty($subclassTypes) ) {
      $builder->whereIn($model->getQualifiedSingleTableTypeColumn(), $subclassTypes);
    }
  }