Select the model

@param \FreeFW\Core\StorageModel $p_model
@param array                     $p_conditions

@return \FreeFW\Model\ResultSet
506832
public function select(\FreeFW\Core\StorageModel &$p_model, array $p_conditions = [])
    {
        $source     = $p_model::getSource();
        $properties = $p_model::getProperties();
        $values     = [];
        $result     = \FreeFW\DI\DI::get('FreeFW::Model::ResultSet');
        /**
         * @var \FreeFW\Model\Condition $oneCondition
         */
        $where = '';
        foreach ($p_conditions as $idx => $oneCondition) {
            $part = $this->renderCondition($oneCondition);
            if ($where != '') {
                $where = $where . ' AND ';
            }
            $where  = $where . $part['sql'];
            $values = array_merge($values, $part['values']);
        }
        // Build query
        $sql = 'SELECT * FROM ' . $source . ' WHERE ' . $where;
        $this->logger->debug('PDOStorage.select : ' . $sql);
        // I got all, run query...
        try {
            // Get PDO and execute
            $query = $this->provider->prepare($sql, array(\PDO::ATTR_CURSOR => \PDO::CURSOR_FWDONLY));
            if ($query->execute($values)) {
                while ($row = $query->fetch(\PDO::FETCH_OBJ)) {
                    $model = clone($p_model);
                    $model
                        ->init()
                        ->setFromArray($row)
                    ;
                    $result[] = $model;
                }
            } else {
                $this->logger->debug('PDOStorage.select.error : ' . print_r($query->errorInfo(), true));
                $localErr = $query->errorInfo();
                $code     = 0;
                $message  = 'PDOStorage.select.error : ' . print_r($query->errorInfo(), true);
                die($message);
                if (is_array($localErr) && count($localErr) > 1) {
                    $code    = intval($localErr[0]);
                    $message = $localErr[2];
                }
                $p_model->addError($code, $message);
            }
        } catch (\Exception $ex) {
            var_dump($ex);
        }
        return $result;
    }
582866
public static function findByAttributes($attributes, $condition = null, $params = [])
    {
        if (!is_a($condition, '\\mpf\\datasources\\sql\\ModelCondition'))
            $condition = ModelCondition::getFrom($condition, get_called_class());
        /* @var $condition \mpf\datasources\sql\ModelCondition */
        $oldLimit = $condition->limit;
        $condition->limit = 1;
        $models = static::findAllByAttributes($attributes, $condition, $params);
        $condition->limit = $oldLimit;
        return isset($models[0]) ? $models[0] : null;
    }
1204786
public function findOneBy(array $conditions)
    {
        $s = $this->selector()->one();
        foreach ($conditions as $column => $value) {
            $s->where($column, '=', $value);
        }

        return $s->execute();
    }
232145
public function selectPdo($select, $param = null)
    {
        $statement = $this->getAdapter()->query($select, ADT::QUERY_MODE_PREPARE);
        $result = $statement->execute($param);

        $resultSet = clone $this->resultSetPrototype;

        return $resultSet->initialize($result);
    }
505510
public static function find($condition, $params = array())
    {
        if (!is_a($condition, '\\mpf\\datasources\\sql\\ModelCondition'))
            $condition = ModelCondition::getFrom($condition, get_called_class());

        /* @var $condition \mpf\datasources\sql\ModelCondition */
        $oldLimit = $condition->limit;
        $condition->limit = 1;
        $models = static::findAll($condition, $params);
        $condition->limit = $oldLimit;
        return isset($models[0]) ? $models[0] : null;
    }
453131
public function find($condition, $params = NULL, $fields=null, $fetchMode=PDO::FETCH_ASSOC) {
		if (!empty($fields)) $this->driver->field($fields);
		return $this->driver
            ->where($condition, $params)
            ->fetch($fetchMode);
	}
595859
public function finds($condition = NULL, $rows = 0, $start = 0, $order='', $fields = '*', $fetchMode=PDO::FETCH_ASSOC) {
		if (is_array($condition)) {
			$where = $condition[0];
			$params = $condition[1];
		} 
		else {
			$where = $condition;
			$params = null;
		}
		return $this->driver
            ->field($fields)
            ->where($where, $params)
            ->orderby($order)
            ->limit($rows, $start)
            ->fetchAll($fetchMode);
	}
741070
protected function getCondition($condition,$model){
        if(empty($condition)){
            return $condition;
        }
        if(is_array($condition)){
            foreach ($condition as $k=>$v){
                $result[$k]=$this->getCondition($v,$model);
            }
        }else{
            if(preg_match('/{([\w\d_]+):([\w\d_]+)}/',$condition,$match)){
                $result=$model->{$match[2]};
            }else{
                $result=$condition;
            }
        }
        return $result;
    }
516916
protected function _getRelatedRowset(
        Garp_Model $model, Garp_Db_Table_Row $row, Garp_Util_Configuration $options
    ) {
        /**
         * An optional passed SELECT object will be passed by reference after every query.
         * This results in an error when 'clone' is not used, because correlation names will be
         * used twice (since they were set during the first iteration). Using 'clone' makes sure
         * a brand new SELECT object is used every time that hasn't been soiled by a possible
         * previous query.
         */
        $conditions = is_null($options['conditions']) ? null : clone $options['conditions'];
        $otherModel = $options['modelClass'];
        if (!$otherModel instanceof Zend_Db_Table_Abstract) {
            $otherModel = new $otherModel();
        }
        // Bound models should respect the CMS context settings of the root model
        $otherModel->setCmsContext($model->isCmsContext());
        /**
         * Do not cache related queries. The "outside" query should be the only
         * query that's cached.
         */
        $originalCacheQueriesFlag = $otherModel->getCacheQueries();
        $otherModel->setCacheQueries(false);
        $modelName = get_class($otherModel);
        $relatedRowset = null;

        // many to many
        if (!empty($options['bindingModel'])) {
            $relatedRowset = $row->findManyToManyRowset(
                $otherModel,
                $options['bindingModel'],
                $options['rule2'],
                $options['rule'],
                $conditions
            );
        } else {
            /**
             * 'mode' is used to clear ambiguity with homophilic relationships. For example,
             * a Model_Doc can have have child Docs and one parent Doc.
             * The conditionals below can never tell which method to call
             * (findParentRow or findDependentRowset) from the referenceMap.
             *
             * Therefore, we can help the decision-making by passing "mode". This can either be
             * "parent" or "dependent", which will then force a call to
             * findParentRow and findDependentRowset, respectively.
             */
            if (is_null($options['mode'])) {
                // belongs to
                try {
                    $model->getReference($modelName, $options['rule']);
                    $relatedRowset = $row->findParentRow(
                        $otherModel, $options['rule'], $conditions
                    );
                } catch(Exception $e) {
                    if (!Garp_Content_Relation_Manager::isInvalidReferenceException($e)) {
                        throw $e;
                    }
                    try {
                        // one to many - one to one
                        // The following line triggers an exception if no reference is available
                        $otherModel->getReference(get_class($model), $options['rule']);
                        $relatedRowset = $row->findDependentRowset(
                            $otherModel,
                            $options['rule'],
                            $conditions
                        );
                    } catch (Exception $e) {
                        if (!Garp_Content_Relation_Manager::isInvalidReferenceException($e)) {
                            throw $e;
                        }
                        $bindingModel = $model->getBindingModel($modelName);
                        $relatedRowset = $row->findManyToManyRowset(
                            $otherModel,
                            $bindingModel,
                            $options['rule2'],
                            $options['rule'],
                            $conditions
                        );
                    }
                }
            } else {
                switch ($options['mode']) {
                case 'parent':
                    $relatedRowset = $row->findParentRow(
                        $otherModel,
                        $options['rule'],
                        $conditions
                    );
                    break;
                case 'dependent':
                    $relatedRowset = $row->findDependentRowset(
                        $otherModel,
                        $options['rule'],
                        $conditions
                    );
                    break;
                default:
                    throw new Garp_Model_Exception(
                        'Invalid value for "mode" given. Must be either "parent" or ' .
                            '"dependent", but "' . $options['mode'] . '" was given.'
                    );
                    break;
                }
            }
        }
        // Reset the cacheQueries value. It's a static property,
        // so leaving it FALSE will affect all future fetch() calls to this
        // model. Not good.
        $otherModel->setCacheQueries($originalCacheQueriesFlag);
        return $relatedRowset;
    }
306416
public static function deleteByPk($pk, $condition = null, $params = array())
    {
        if (!is_a($condition, '\\mpf\\datasources\\sql\\ModelCondition')) {
            $condition = ModelCondition::getFrom($condition, get_called_class());
        }
        /* @var $condition ModelCondition */
        $condition->compareColumn(static::getDb()->getTablePk(static::getTableName()), $pk);
        return static::deleteAll($condition, $params);
    }
509680
protected function renderCondition(\FreeFW\Model\Condition $p_condition)
    {
        $result = [];
        $left   = $p_condition->getLeftMember();
        $right  = $p_condition->getRightMember();
        $oper   = $p_condition->getOperator();
        switch ($oper) {
            case \FreeFW\Storage\Storage::COND_LOWER:
            case \FreeFW\Storage\Storage::COND_LOWER_EQUAL:
            case \FreeFW\Storage\Storage::COND_GREATER:
            case \FreeFW\Storage\Storage::COND_GREATER_EQUAL:
            case \FreeFW\Storage\Storage::COND_EQUAL:
                if ($left !== null && $right !== null) {
                    $leftDatas  = $this->renderConditionField($left);
                    $rightDatas = $this->renderConditionField($right);
                    $result = [
                        'sql'    => $leftDatas['id'] . ' ' . $oper . ' ' . $rightDatas['id'],
                        'values' => [],
                        'type'   => false
                    ];
                    if ($leftDatas['type'] === false) {
                        $result['values'][$leftDatas['id']] = $leftDatas['value'];
                    } else {
                        $result['type'] = $leftDatas['type'];
                    }
                    if ($rightDatas['type'] === false) {
                        $result['values'][$rightDatas['id']] = $rightDatas['value'];
                    } else {
                        $result['type'] = $rightDatas['type'];
                    }
                } else {
                    throw new \FreeFW\Core\FreeFWStorageException(
                        sprintf('Wrong fields for %s condition', $oper)
                    );
                }
                break;
            default:
                throw new \FreeFW\Core\FreeFWStorageException(
                    sprintf('Unknown condition : %s !', $oper)
                );
                break;
        }
        return $result;
    }
256265
public function getSelector($pkey, array $record)
    {
        if ($pkey !== null && !is_array($pkey))
            throw new InvalidTypeException("Invalid primary key: " . WF::str($pkey));

        // When no primary key is available, we match on all fields
        $is_primary_key = true;
        if ($pkey === null)
        {
            $pkey = array();
            foreach ($record as $k => $v)
                $pkey[$k] = $this->table->getColumn($v);
            $is_primary_key = false;
        }

        // Make sure there are fields to match on
        if (empty($pkey))
            throw new InvalidTypeException("No fields to match on");

        $condition = null;
        foreach ($pkey as $pkey_column => $coldef)
        {
            if ($is_primary_key && (!array_key_exists($pkey_column, $record) || $record[$pkey_column] === null))
                throw new DAOException("Record does not have value for primary key column {$pkey_column}");
            
            $pkey_value = $coldef->beforeInsertFilter($record[$pkey_column]);
            $comparator = new Query\ComparisonOperator("=", $pkey_column, $pkey_value);
            $condition = $condition === null ? $comparator : new Query\BooleanOperator("AND", $condition, $comparator);
        }

        return $condition;
    }
202479
public function getModelHistoryCount(string $model, $foreignKey, array $conditions = [], array $options = []): int
    {
        $conditions = Hash::merge([
            'model' => $model,
            'foreign_key' => $foreignKey
        ], $conditions);
        $options = Hash::merge([
            'includeAssociated' => false
        ], $options);

        if ($options['includeAssociated']) {
            $hashes = $this->find()
                ->select(['save_hash'])
                ->where($conditions);

            $history = $this->find()
                ->where([
                    'save_hash IN' => $hashes
                ]);
        } else {
            $history = $this->find()
                ->where($conditions);
        }

        return $history->count();
    }
1064841
public static function findAllByPk($pk, $condition = null, $params = [])
    {
        $class = get_called_class();
        $condition = ModelCondition::getFrom($condition, $class);
        $condition->compareColumn($class::getDb()->getTablePk($class::getTableName()), $pk);
        return self::findAll($condition, $params);
    }
631590
public function fetchs($condition = NULL, $params = NULL, $fields=null, $order='',$fetchMode=PDO::FETCH_ASSOC) {
		 $this->driver->field($fields)->where($condition, $params);
         $order and $this->orderby($order);
         return  $this->fetchAll($fetchMode);
	}
838378
public function selectOne( $query, $bindings = [ ], $useReadPdo = true, $resultClass = null )
	{
		$records = $this->select( $query, $bindings, $useReadPdo, $resultClass );
		return array_shift( $records );
	}
1260107
public function findBy(array $conditions)
    {
        $s = $this->selector();
        foreach ($conditions as $column => $value) {
            $s->where($column, '=', $value);
        }

        return $s->execute();
    }