*/ abstract class AbstractRepository extends EntityRepository { /** * Create a query with filter. * * @param QueryBuilder $qb * @param array $fields * @param array $filters * @return Query */ protected function createQueryFilter($qb, $fields, $filters = array()) { $apply = array(); foreach ($fields as $field) { $apply[] = $field." like :query"; } $qb->andWhere((implode(' OR ',$apply))); if (isset($filters['query'])){ $qb->setParameter('query', "%".$filters['query']."%"); } else { $qb->setParameter('query', '%%'); } $qb->setFirstResult(isset($filters['start']) ? $filters['start'] : 0)-> setMaxResults(isset($filters['limit']) ? $filters['limit'] : 200); // @todo: add sort return $qb->getQuery(); } /** * Merge an array with the entity. * * @todo rewrite this method * @param array $data */ public function fromArray($data) { // get the entity metadata $metadata = $this->_em->getClassMetadata($this->_entityName); // instantiate the entity $entity = $this->getEntityInstance($data); // set the property value foreach ($data as $property => $value) { // the field exists in field list if ($metadata->hasField($property)) { // get the method name $method = 'set'.ucfirst($property); // check if the method is callable if (is_callable(array($entity, $method))) { $entity->$method($value); } // if the field not exists in field list } else { // try call fromArray recursively if ($metadata->hasAssociation($property) && (is_array($value) || is_object($value))) { $assoc = $metadata->getAssociationMapping($property); // define the method name $method = (is_array($value) ? 'add' : 'set').$this->getSingleEntityName($assoc['targetEntity']); // check if the method is callable if (is_callable(array($entity, $method))) { $repo = $this->_em->getRepository($assoc['targetEntity']); if (is_callable(array($repo, 'fromArray'))) { if (is_array($value)) { foreach ($value as $item) { $item[$assoc['mappedBy']] = $entity; $entity->$method($repo->fromArray($item, $entity)); } } else { $entity->$method($value); } } } } } } return $entity; } /** * Get the single name of entity. * * @param string $namespaced Full qualified class name * @return string */ private function getSingleEntityName($namespaced) { $parts = explode('\\',$namespaced); return end($parts); } /** * Retrieves or create an entity instance. * * @param array $data * @return Entity */ private function getEntityInstance($data) { $entity = null; // if the id is defined if (isset($data['id']) && $data['id'] > 0){ // instantiate the entity based on it id $entity = $this->find($data['id']); // clear id reference unset($data['id']); } else { // create a new entity instance $entity = new $this->_entityName(); } return $entity; } }