creates and caches related mapper objects
@param string $model
@param array $relConf
@param string $key
@param bool $pushFilter
@return Cortex
184801
protected function getRelInstance($model=null, $relConf=null, $key='', $pushFilter=false) {
		if (!$model && !$relConf)
			trigger_error(self::E_MISSING_REL_CONF,E_USER_ERROR);
		$relConf = $model ? $model::resolveConfiguration() : $relConf;
		$relName = ($model?:'Cortex').'\\'.$relConf['db']->uuid().
			'\\'.$relConf['table'].'\\'.$key;
		if (\Registry::exists($relName)) {
			$rel = \Registry::get($relName);
			$rel->reset();
		} else {
			$rel = $model ? new $model : new Cortex($relConf['db'], $relConf['table']);
			if (!$rel instanceof Cortex)
				trigger_error(self::E_WRONG_RELATION_CLASS,E_USER_ERROR);
			\Registry::set($relName, $rel);
		}
		// restrict fields of related mapper
		if(!empty($key) && isset($this->relWhitelist[$key])) {
			if (isset($this->relWhitelist[$key][0]))
				$rel->fields($this->relWhitelist[$key][0],false);
			if (isset($this->relWhitelist[$key][1]))
				$rel->fields($this->relWhitelist[$key][1],true);
		}
		if ($pushFilter && !empty($key)) {
			if (isset($this->relFilter[$key.'.'])) {
				foreach($this->relFilter[$key.'.'] as $fkey=>$conf)
					$rel->filter($fkey,$conf[0],$conf[1]);
			}
			if (isset($this->hasCond[$key.'.'])) {
				foreach($this->hasCond[$key.'.'] as $fkey=>$conf)
					$rel->has($fkey,$conf[0],$conf[1]);
			}
		}
		return $rel;
	}
963074
public function relatedKey($key, $model = false)
    {
        if (!$model) {
            $model = $this->model;
        }

        if (($methodBreaker = strpos($key, '.')) !== false) {
            $method = substr($key, 0, $methodBreaker);
            if (method_exists($model, $method)) {
                if (method_exists($model->$method, $submethod = str_replace($method.'.', '', $key))) {
                    return $model->$method->$submethod();
                }

                if (isset($model->$method->$submethod)) {
                    return $model->$method->$submethod;
                }

                return $model->getRelationValue($method);
            }
        }

        return false;
    }
238852
public function fromModel(string $model, string $name, string $key = null): self
    {
        $key = $key ?? (new $model())->getModel()->getKeyName();

        $this->set('relationModel', Crypt::encryptString($model));
        $this->set('relationName', Crypt::encryptString($name));
        $this->set('relationKey', Crypt::encryptString($key));

        $this->addBeforeRender(function () use ($name, $key) {
            $value = $this->get('value');

            if (! is_countable($value)) {
                $value = Arr::wrap($value);
            }

            $value = collect($value)
                ->map(function ($item) use ($name, $key) {
                    return [
                        'id'   => $item->$key,
                        'text' => $item->$name,
                    ];
                })->toJson();

            $this->set('value', $value);
        });

        return $this;
    }
1341870
public static function getModelKeys($model, $includePrimary = true)
    {
        $keys = array_map(function ($foreignKey) {
            array_shift($foreignKey);
            return array_keys($foreignKey);
        }, $model->getTableSchema()->foreignKeys);
        if ($includePrimary) {
            $keys[] = $model->primaryKey();
        }
        return call_user_func_array('array_merge', $keys);
    }
857291
public function create(Model $model)
    {
        $metadata = $model->getMetadata();
        $insert = $this->createInsertObj($model);
        $this->getQuery()->executeInsert($metadata, $insert);
        return $model;
    }
213926
private function _buildTreeArrayRecursive(Tree $model, $filter)
    {
        $is_filter_set = !empty($filter);

        if ($model->isNewRecord) {
            $childs = static::findRoots()->all();
        } else {
            $childs = $model->children;
        }


        foreach ($childs as $child) {
            $level = $child->level;
            $id = $child->id;
            if (!$is_filter_set || in_array($id, $filter)) {
                $name = $child->name;
                if ($level == 0) {
                    $name = "[" . $child->site->name . "] " . $child->name;
                }

                $child->name = str_repeat($this->repeat, $level) . $name;
                $this->_tmpResult[$id] = $child;
            }
            $this->_buildTreeArrayRecursive($child, $filter);
        }

        return $this->_tmpResult;
    }
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;
	}
302072
public function actionSchedulerLog($model, $pk)
    {
        return new ActiveDataProvider([
            'query' => Scheduler::find()->where(['model_class' => $model, 'primary_key' => $pk]),
            'sort'=> ['defaultOrder' => ['schedule_timestamp' => SORT_ASC]],
            'pagination' => false,
        ]);
    }
685927
public function relatedToMany(
        string $otherClass,
        array $fieldsMap,
        bool $applySetters = false
    ) {
        $thisValues = array_intersect_key($this->data, $fieldsMap);

        $filterFn = function (Query $query) use (&$thisValues, &$fieldsMap) {
            $query->where(function (WhereClause $where) use (&$query, &$thisValues, &$fieldsMap) {
                foreach ($fieldsMap as $thisKey => $thatKey) {
                    $where->and($thatKey, '=', '?');
                    $query->bind($thisValues[$thisKey]);
                }
            });
        };

        /* @var $otherClass Model */
        return $otherClass::find($filterFn, $applySetters);
    }
1148177
public static function buildResult($model, $params = [])
    {
        $pk = $model->primaryKey;
        $id = $model->{$pk};
        $fields = array_get($params, ApiOptions::FIELDS, $pk);
        $related = array_get($params, ApiOptions::RELATED);

        if ($pk === $fields && empty($related)) {
            return [$pk => $id];
        }

        $fieldsArray = explode(',', $fields);

        $result = static::selectById($id, $params, $fieldsArray);

        return $result;
    }
945453
public function getByKey(string $key, AbstractFilter $filter = null)
    {
        return $this->children->getByKey($key, $filter);
    }
987545
public function updateDataMeta( $model, $key, $value ) {

		$model->updateDataMeta( $key, $value );

		$model->refresh();

		return $model;
	}
1128061
public function generatePush(Array $parameters, $label, $pushCallback, $pushClass = "\BIPBOP\Client\Push") {
        $reflection = new \ReflectionClass($pushClass);
        $query = sprintf("SELECT FROM '%s'.'%s'", $this->database->name(), $this->domNode->getAttribute("name"));
        $instance = $reflection->newInstance($this->ws);
        $this->validateParameters($parameters);
        /* @var $instance \BIPBOP\Push */
        return $instance->create($label, $pushCallback, $query, $parameters);
    }
412883
public function add_filter_by_key( FilterInterface $filter, $key ) {

		if ( ! is_scalar( $key ) ) {
			throw new Exception\InvalidArgumentException( 'key should be a scalar value.' );
		}

		$key = (string) $key;

		if ( ! isset ( $this->filters_by_key[ $key ] ) ) {
			$this->filters_by_key[ $key ] = [ ];
		}

		$this->filters_by_key[ $key ][] = $filter;

		return $this;
	}
529420
public function addFilter($key, $filter)
    {
        if (false === isset($this->filters[$key])) {
            $this->filters[$key] = [];
        }

        $this->filters[$key][] = $filter;

        return $this;
    }
866723
public function push(Model $model)
    {
        $this->models[$model->getType()][$model->getId()] = $model;
        return $this;
    }
533054
protected static function mapSchemaDataToModelData(
        iterable $captures,
        string $schemaClass,
        ModelSchemaInfoInterface $schemaInfo
    ): array {
        static::assertClassImplements($schemaClass, SchemaInterface::class);

        /** @var SchemaInterface $schemaClass */
        static::assertClassImplements($modelClass = $schemaClass::MODEL, ModelInterface::class);

        $index         = null;
        $fields        = [];
        $toManyIndexes = [];
        foreach ($captures as $name => $value) {
            assert(is_string($name) === true);
            if ($name === DI::KEYWORD_ID) {
                $index = $value;
            } elseif ($schemaClass::hasAttributeMapping($name) === true) {
                $fieldName          = $schemaClass::getAttributeMapping($name);
                $fields[$fieldName] = $value;
            } elseif ($schemaClass::hasRelationshipMapping($name) === true) {
                $modelRelName = $schemaClass::getRelationshipMapping($name);
                $relType      = $schemaInfo->getRelationshipType($modelClass, $modelRelName);
                if ($relType === RelationshipTypes::BELONGS_TO) {
                    $fkName          = $schemaInfo->getForeignKey($modelClass, $modelRelName);
                    $fields[$fkName] = $value;
                } elseif ($relType === RelationshipTypes::BELONGS_TO_MANY) {
                    $toManyIndexes[$modelRelName] = $value;
                }
            }
        }

        $result = [$index, $fields, $toManyIndexes];

        return $result;
    }