Serialize entity.

@param \Railken\Lem\Contracts\EntityContract $entity
@param Collection                            $select

@return \Railken\Bag
772125
public function serialize(EntityContract $entity, Collection $select = null)
    {
        $bag = new Bag($entity->toArray());

        foreach ($this->getManager()->getAttributes() as $attribute) {
            $attribute->pushReadable($entity, $bag);
        }

        if ($select) {
            $bag = $bag->only($select->toArray());
        }
                
        return $bag;
    }
1342239
private function forEachChunk(ObjectManager $objectManager, array $entities, $operation)
    {
        $batch = [];
        foreach (array_chunk($entities, $this->configuration['batchSize']) as $chunk) {
            $searchableEntitiesChunk = [];
            foreach ($chunk as $entity) {
                $entityClassName = ClassUtils::getClass($entity);

                $searchableEntitiesChunk[] = new SearchableEntity(
                    $this->getFullIndexName($entityClassName),
                    $entity,
                    $objectManager->getClassMetadata($entityClassName),
                    $this->normalizer,
                    ['useSerializerGroup' => $this->canUseSerializerGroup($entityClassName)]
                );
            }

            $batch[] = $operation($searchableEntitiesChunk);
        }

        return $this->formatBatchResponse($batch);
    }
1236661
public function embed(&$collection, $options = [])
    {
        $indexes = $this->_index($collection, $this->keys('from'));
        $related = $this->_find(array_keys($indexes), $options);

        $name = $this->name();

        $this->_cleanup($collection);

        foreach ($related as $index => $entity) {
            if (is_object($entity)) {
                $value = (string) $entity->{$this->keys('to')};
                if (isset($indexes[$value])) {
                    $source = $collection[$indexes[$value]];
                    $source->{$name} = $entity;
                }
            } else {
                $value = $entity[$this->keys('to')];
                if (isset($indexes[$value])) {
                    $collection[$indexes[$value]][$name] = &$related[$index];
                }
            }
        }
        return $related;
    }
613543
private function mergeCollectionSqlSelectWithAnotherCollection(EntityRepository $collection): self
    {
        $select_fields = $collection->getSelectFields();
        foreach ($select_fields as $select_field) {
            $this->sql_select_fields[] = $select_field;
        }

        $where_fields = $collection->getWhereFields();
        foreach ($where_fields as $where_field) {
            $this->sql_where_fields[] = $where_field;
        }

        $group_fields = $collection->getGroupByField();
        foreach ($group_fields as $group_field) {
            $this->group_by_fields[] = $group_field;
        }

        $having_fields = $collection->getHavingFields();
        foreach ($having_fields as $having_field) {
            $this->having_fields[] = $having_field;
        }

        $order_fields = $collection->getOrderFields();
        foreach ($order_fields as $order_field) {
            $this->order_fields[] = $order_field;
        }

        $translation_fields = $collection->getTranslationFields();
        foreach ($translation_fields as $translation_field) {
            $this->translation_fields[] = $translation_field;
        }

        $join_tables = $collection->getJoinTables();
        foreach ($join_tables as $join_table) {
            $this->addJoinTable([$join_table['table'], $join_table['alias']], $join_table['left'], $join_table['right'], $join_table['type'], $join_table['right_table']);
        }

        return $this;
    }
722791
public function getData(Entity $entity)
    {
        $column = $this->analyzer->listColumns();
        $data = array();

        foreach ($column as $key => $value) {
            $method = 'get' . Utils::capitalize($key);
            $data[$key] = $entity->$method();
            if (is_null($data[$key])) $data[$key] = array();
            if ($data[$key] instanceof ArrayCollection) $data[$key] = $data[$key]->toArray();
        }

        $data['objectclass'] = $entity->getObjectClass()->toArray();

        return $data;
    }
817664
public function updateSelectQuery($select)
    {
        $p = null;
        if (!empty($this->owner->relations)) {
            $p = $this->owner->table_alias ?: $this->owner->table;
        }

        if ($this->relation) {
            $select->field($this->actual_field ?: $this->short_name, $this->relation->short_name, $this->short_name);
        } elseif (!(is_null($this->actual_field)) && $this->actual_field != $this->short_name) {
            $select->field($this->actual_field, $p, $this->short_name);

            return $this;
        } else {
            $select->field($this->short_name, $p);
        }

        return $this;
    }
864328
protected function fetchResult(Select $select, AbstractResultSet $resultSet = null)
    {
        $resultSet = $resultSet ?: $this->getResultSet();
        $resultSet->buffer();

        if ($this->usePaginator()) {
            $this->setUsePaginator(false);
            $resultSet = $this->paginate($select, $resultSet);
        } else {
            $statement = $this->getSql()->prepareStatementForSqlObject($select);
            $result = $statement->execute();
            $resultSet->initialize($result);
        }

        return $resultSet;
    }
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);
    }
18317
protected function visitSirelNodeSelectStatement(Node\SelectStatement $select)
    {
        return join(" ", array_filter(array(
            "SELECT",

            ($select->distinct ? "DISTINCT" : null),

            ($select->projections
                ? join(", ", $this->visitEach($select->projections))
                : '*'),

            // FROM
            $this->visit($select->source),

            // WHERE
            ($select->restrictions 
                ? "WHERE " . join(" AND ", $this->visitEach($select->restrictions))
                : null
            ),

            // ORDER BY
            ($select->orders
                ? "ORDER BY " . join(", ", $this->visitEach($select->orders))
                : null),

            // GROUP BY
            ($select->groups
                ? "GROUP BY " . join(', ', $this->visitEach($select->groups))
                : null),

            // LIMIT
            ($select->limit ? $this->visit($select->limit) : null),

            // OFFSET 
            ($select->offset ? $this->visit($select->offset) : null)
        ))) . ';';
    }
864176
public function validate(EntityContract $entity, Bag $parameters)
    {
        $errors = new Collection();

        $value = $parameters->get($this->getRelationName());

        if ($this->required && !$entity->exists && !$parameters->exists($this->getRelationName())) {
            $errors->push($this->newException(Tokens::NOT_DEFINED, $parameters->get($this->getName())));
        }

        if ($this->unique && $parameters->exists($this->getRelationName()) && $this->isUnique($entity, $value)) {
            $errors->push($this->newException(Tokens::NOT_UNIQUE, $parameters->get($this->getName())));
        }

        if ($parameters->exists($this->getRelationName()) && ($value !== null || $this->required) && !$this->valid($entity, $value)) {
            $errors->push($this->newException(Tokens::NOT_VALID, $parameters->get($this->getName())));
        }

        return $errors;
    }
631461
public function validate(EntityContract $entity, Bag $parameters)
    {
        $errors = new Collection();

        $this->callMethods('validate', [$entity, $parameters], function ($return) use (&$errors) {
            $errors = $errors->merge($return);
        });

        return $errors;
    }
112105
public function valid(EntityContract $entity, $value)
    {
        try {
            $country = (new \League\ISO3166\ISO3166())->alpha2($entity->country);

            return Collection::make($country['currency'])->contains($value);
        } catch (\Exception $e) {
            return false;
        }
    }
1245685
protected function createSelectQuery(array $fields = [], array $criteria = [], array $orderBy = [], $distinct = true)
	{
		if ($this->objectManager instanceof \Doctrine\ORM\EntityManager) {
			/** @var \Doctrine\ORM\QueryBuilder $builder */
			$builder = $this->objectManager->createQueryBuilder();
			$builder->select(empty($fields) ? 'p' : 'p.' . implode(', p.', $fields));
			
			if (true === $distinct) {
				$builder->distinct();
			}
			
			$builder->from($this->className, 'p')
					->setFirstResult($this->getItemOffset())
					->setMaxResults($this->itemPerPage);
			
			foreach ($orderBy as $key => $value) {
				$builder->orderBy(sprintf('p.%s', $key), $value);
			}
		} elseif ($this->objectManager instanceof \Doctrine\ODM\MongoDB\DocumentManager) {
			/** @var \Doctrine\ODM\MongoDB\Query\Builder $builder */
			$builder = $this->objectManager->createQueryBuilder($this->className);
			
			if (false === empty($fields)) {
				$builder->select($fields);
			}
			
			$builder->skip($this->getItemOffset())
					->limit($this->itemPerPage);
			
			foreach ($orderBy as $key => $value) {
				$builder->sort($key, $value);
			}
		} else {
			throw new ObjectManagerNotSupportedException(sprintf('Doctrine object manager class "%s" is not supported.', get_class($this->objectManager)));
		}
		
		$this->qbHandler->applyExprFromArray($builder, 'p', $criteria);
		
		return $builder->getQuery();
	}
546477
public function load(Entity $entity)
    {
        /** @var \Slick\Orm\Sql\Select $sql */
        $sql = call_user_func_array(
            array($this->getRelatedEntity(), 'find'),
            []
        );
        $pmk = $this->getEntity()->getPrimaryKey();
        $table = Entity\Manager::getInstance()->get($this->getRelatedEntity())
            ->getEntity()->getTableName();
        $sql->where(
            [
                "{$table}.{$this->getForeignKey()} = :id" => [
                    ':id' => $this->getEntity()->$pmk
                ]
            ]
        );
        return $sql->first();
    }
107538
public function filterRelationParameters(EntityContract $entity, Bag $parameters): Bag
    {
        $m = $this->getRelationManager($entity);

        $unique_keys = $m->getAttributes()->filter(function ($attribute) {
            return $attribute->getUnique();
        })->keys()->toArray();

        return (new Bag($parameters))->only($unique_keys);
    }
238423
public static function select(Collection $data, $selected = 0, $options = [], $htmlOptions = [])
    {
        if (empty($options['valueColumn']))
            $options['valueColumn'] = Model::PK;
        if (empty($options['titleColumn']))
            $options['titleColumn'] = 'title';
        if (is_array($selected))
            $selected = $selected[$options['valueColumn']];
        if ($selected instanceof Model) {
            $selected = $selected->{$options['valueColumn']};
        }
        if (empty($options['disabled']))
            $options['disabled'] = [];

        if ($options instanceof Std) {
            $options = $options->getData();
        }

        $htmlOptionsText = [];
        foreach ($htmlOptions as $key => $value) {
            if (is_numeric($key)) {
                $htmlOptionsText[] = $value;
            } else {
                $htmlOptionsText[] = $key . '="' . $value . '"';
            }
        }
        $htmlOptionsText = implode(' ', $htmlOptionsText);

        $html = '<select ' . $htmlOptionsText . '>' . "\n";
        if (
            isset($options['null']) && $options['null']
            &&
            $data->first()[$options['valueColumn']] !== 0 && $data->first()[$options['titleColumn']] !== '---'
        ) {
            $data->prepend([$options['valueColumn'] => 0, $options['titleColumn'] => '---']);
        }
        foreach ($data as $item) {
            $html .=
                '<option
                    value="' . $item[$options['valueColumn']] . '"' .
                ($item[$options['valueColumn']] == $selected ? ' selected="selected"' : '') .
                (in_array($item[$options['valueColumn']], $options['disabled']) ? ' disabled="disabled"' : '') .
                '>' .
                (
                    in_array('tree', $options) && isset($options['treeLevelColumn']) && isset($item[$options['treeLevelColumn']])
                        ? str_repeat(self::TREE_LEVEL_SYMBOL, (int)$item[$options['treeLevelColumn']])
                        : ''
                ) . ' ' .
                $item[$options['titleColumn']] .
                '</option>' . "\n";
        }
        $html .= '</select>';
        return $html;
    }
292799
public function save(EntityContract $entity)
    {
        $result = new Result();

        $saving = $entity->save();

        foreach ($this->getAttributes() as $attribute) {
            $result->addErrors($attribute->save($entity));
        }

        return $result;
    }