* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ namespace Chill\PersonBundle\Repository; use Doctrine\ORM\QueryBuilder; /** * PersonRepository * */ class PersonRepository extends \Chill\PersonBundle\Entity\PersonRepository { public function findByPhone( string $phonenumber, $centers, $firstResult, $maxResults, array $only = ['mobile', 'phone'] ) { $qb = $this->createQueryBuilder('p'); $qb->select('p'); $this->addByCenters($qb, $centers); $this->addPhoneNumber($qb, $phonenumber, $only); $qb->setFirstResult($firstResult) ->setMaxResults($maxResults) ; return $qb->getQuery()->getResult(); } public function countByPhone( string $phonenumber, $centers, array $only = ['mobile', 'phone'] ): int { $qb = $this->createQueryBuilder('p'); $qb->select('COUNT(p)'); $this->addByCenters($qb, $centers); $this->addPhoneNumber($qb, $phonenumber, $only); return $qb->getQuery()->getSingleScalarResult(); } protected function addPhoneNumber(QueryBuilder $qb, string $phonenumber, array $only) { if (count($only) === 0) { throw new \Exception("No array field to search"); } $phonenumber = $this->parsePhoneNumber($phonenumber); $orX = $qb->expr()->orX(); if (\in_array('mobile', $only)) { $orX->add($qb->expr()->like("REPLACE(p.mobilenumber, ' ', '')", ':phonenumber')); } if (\in_array('phone', $only)) { $orX->add($qb->expr()->like("REPLACE(p.phonenumber, ' ', '')", ':phonenumber')); } $qb->andWhere($orX); $qb->setParameter('phonenumber', '%'.$phonenumber.'%'); } protected function parsePhoneNumber($phonenumber): string { return \str_replace(' ', '', $phonenumber); } protected function addByCenters(QueryBuilder $qb, array $centers) { if (count($centers) > 0) { $qb->andWhere($qb->expr()->in('p.center', ':centers')); $qb->setParameter('centers', $centers); } } }