cs: Fix code style (safe rules only).

This commit is contained in:
Pol Dellaiera
2021-11-23 14:06:38 +01:00
parent 149d7ce991
commit 8f96a1121d
1223 changed files with 65199 additions and 64625 deletions

View File

@@ -1,41 +1,57 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\PersonBundle\Search;
use Chill\MainBundle\Form\Type\ChillDateType;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Search\AbstractSearch;
use Chill\MainBundle\Search\HasAdvancedSearchFormInterface;
use Chill\MainBundle\Search\ParsingException;
use Chill\MainBundle\Search\SearchInterface;
use Chill\MainBundle\Search\Utils\ExtractDateFromPattern;
use Chill\MainBundle\Search\Utils\ExtractPhonenumberFromPattern;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Form\Type\GenderType;
use Chill\PersonBundle\Repository\PersonACLAwareRepositoryInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Search\SearchInterface;
use Chill\MainBundle\Search\ParsingException;
use Chill\MainBundle\Pagination\PaginatorFactory;
use DateTime;
use Exception;
use Symfony\Component\Form\Extension\Core\Type\TelType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Chill\MainBundle\Form\Type\ChillDateType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Search\HasAdvancedSearchFormInterface;
use Symfony\Component\Templating\EngineInterface;
use function array_fill_keys;
use function array_filter;
use function array_key_exists;
use function array_merge;
class PersonSearch extends AbstractSearch implements HasAdvancedSearchFormInterface
{
private EngineInterface $templating;
private PaginatorFactory $paginatorFactory;
private PersonACLAwareRepositoryInterface $personACLAwareRepository;
private ExtractDateFromPattern $extractDateFromPattern;
private ExtractPhonenumberFromPattern $extractPhonenumberFromPattern;
public const NAME = "person_regular";
public const NAME = 'person_regular';
private const POSSIBLE_KEYS = [
'_default', 'firstname', 'lastname', 'birthdate', 'birthdate-before',
'birthdate-after', 'gender', 'nationality', 'phonenumber', 'city'
'birthdate-after', 'gender', 'nationality', 'phonenumber', 'city',
];
private ExtractDateFromPattern $extractDateFromPattern;
private ExtractPhonenumberFromPattern $extractPhonenumberFromPattern;
private PaginatorFactory $paginatorFactory;
private PersonACLAwareRepositoryInterface $personACLAwareRepository;
private EngineInterface $templating;
public function __construct(
EngineInterface $templating,
ExtractDateFromPattern $extractDateFromPattern,
@@ -50,6 +66,106 @@ class PersonSearch extends AbstractSearch implements HasAdvancedSearchFormInterf
$this->personACLAwareRepository = $personACLAwareRepository;
}
public function buildForm(FormBuilderInterface $builder)
{
$builder
->add('_default', TextType::class, [
'label' => 'First name or Last name',
'required' => false,
])
->add('firstname', TextType::class, [
'label' => 'First name',
'required' => false,
])
->add('lastname', TextType::class, [
'label' => 'Last name',
'required' => false,
])
->add('birthdate-after', ChillDateType::class, [
'label' => 'Birthdate after',
'required' => false,
])
->add('birthdate', ChillDateType::class, [
'label' => 'Birthdate',
'required' => false,
])
->add('birthdate-before', ChillDateType::class, [
'label' => 'Birthdate before',
'required' => false,
])
->add('phonenumber', TelType::class, [
'required' => false,
'label' => 'Part of the phonenumber',
])
->add('gender', GenderType::class, [
'label' => 'Gender',
'required' => false,
'expanded' => false,
'placeholder' => 'All genders',
])
->add('city', TextType::class, [
'required' => false,
'label' => 'City or postal code',
]);
}
public function convertFormDataToQuery(array $data)
{
$string = '@person ';
$string .= empty($data['_default']) ? '' : $data['_default'] . ' ';
foreach (['firstname', 'lastname', 'gender', 'phonenumber', 'city'] as $key) {
$string .= empty($data[$key]) ? '' : $key . ':' .
// add quote if contains spaces
(strpos($data[$key], ' ') !== false ? '"' . $data[$key] . '"' : $data[$key])
. ' ';
}
foreach (['birthdate', 'birthdate-before', 'birthdate-after'] as $key) {
$string .= empty($data[$key]) ?
''
:
$key . ':' . $data[$key]->format('Y-m-d') . ' ';
}
return $string;
}
public function convertTermsToFormData(array $terms)
{
$data = [];
foreach (['firstname', 'lastname', 'gender', '_default', 'phonenumber', 'city'] as $key) {
$data[$key] = $terms[$key] ?? null;
}
// parse dates
foreach (['birthdate', 'birthdate-before', 'birthdate-after'] as $key) {
if (array_key_exists($key, $terms)) {
try {
$date = new DateTime($terms[$key]);
} catch (Exception $ex) {
throw new ParsingException("The date for {$key} is "
. 'not parsable', 0, $ex);
}
}
$data[$key] = $date ?? null;
}
return $data;
}
public function getAdvancedSearchTitle()
{
return 'Search within persons';
}
public static function getAlias(): string
{
return self::NAME;
}
/*
* (non-PHPdoc)
* @see \Chill\MainBundle\Search\SearchInterface::getOrder()
@@ -68,66 +184,89 @@ class PersonSearch extends AbstractSearch implements HasAdvancedSearchFormInterf
return true;
}
public function supports($domain, $format)
{
return 'person' === $domain;
}
/*
* (non-PHPdoc)
* @see \Chill\MainBundle\Search\SearchInterface::renderResult()
*/
public function renderResult(array $terms, $start = 0, $limit = 50, array $options = array(), $format = 'html')
public function renderResult(array $terms, $start = 0, $limit = 50, array $options = [], $format = 'html')
{
$terms = $this->findAdditionnalInDefault($terms);
$total = $this->count($terms);
$paginator = $this->paginatorFactory->create($total);
if ($format === 'html') {
return $this->templating->render('@ChillPerson/Person/list_with_period.html.twig',
array(
'persons' => $this->search($terms, $start, $limit, $options),
'pattern' => $this->recomposePattern(
$terms,
\array_filter(self::POSSIBLE_KEYS, fn($item) => $item !== '_default'),
$terms['_domain']
),
'total' => $total,
'start' => $start,
'search_name' => self::NAME,
'preview' => $options[SearchInterface::SEARCH_PREVIEW_OPTION],
'paginator' => $paginator
));
if ('html' === $format) {
return $this->templating->render(
'@ChillPerson/Person/list_with_period.html.twig',
[
'persons' => $this->search($terms, $start, $limit, $options),
'pattern' => $this->recomposePattern(
$terms,
array_filter(self::POSSIBLE_KEYS, fn ($item) => '_default' !== $item),
$terms['_domain']
),
'total' => $total,
'start' => $start,
'search_name' => self::NAME,
'preview' => $options[SearchInterface::SEARCH_PREVIEW_OPTION],
'paginator' => $paginator,
]
);
}
if ($format === 'json') {
if ('json' === $format) {
return [
'results' => $this->search($terms, $start, $limit, \array_merge($options, [ 'simplify' => true ])),
'results' => $this->search($terms, $start, $limit, array_merge($options, ['simplify' => true])),
'pagination' => [
'more' => $paginator->hasNextPage()
]
'more' => $paginator->hasNextPage(),
],
];
}
}
private function findAdditionnalInDefault(array $terms): array
public function supports($domain, $format)
{
// chaining some extractor
$datesResults = $this->extractDateFromPattern->extractDates($terms['_default']);
$phoneResults = $this->extractPhonenumberFromPattern->extractPhonenumber($datesResults->getFilteredSubject());
$terms['_default'] = $phoneResults->getFilteredSubject();
return 'person' === $domain;
}
if ($datesResults->hasResult() && (!\array_key_exists('birthdate', $terms)
|| NULL !== $terms['birthdate'])) {
$terms['birthdate'] = $datesResults->getFound()[0]->format('Y-m-d');
protected function count(array $terms): int
{
[
'_default' => $default,
'firstname' => $firstname,
'lastname' => $lastname,
'birthdate' => $birthdate,
'birthdate-before' => $birthdateBefore,
'birthdate-after' => $birthdateAfter,
'gender' => $gender,
'nationality' => $countryCode,
'phonenumber' => $phonenumber,
'city' => $city,
] = $terms + array_fill_keys(self::POSSIBLE_KEYS, null);
foreach (['birthdateBefore', 'birthdateAfter', 'birthdate'] as $v) {
if (null !== ${$v}) {
try {
${$v} = new DateTime(${$v});
} catch (Exception $e) {
throw new ParsingException('The date is '
. 'not parsable', 0, $e);
}
}
}
if ($phoneResults->hasResult() && (!\array_key_exists('phonenumber', $terms)
|| NULL !== $terms['phonenumber'])) {
$terms['phonenumber'] = $phoneResults->getFound()[0];
}
return $terms;
return $this->personACLAwareRepository
->countBySearchCriteria(
$default,
$firstname,
$lastname,
$birthdate,
$birthdateBefore,
$birthdateAfter,
$gender,
$countryCode,
$phonenumber,
$city
);
}
/**
@@ -146,13 +285,13 @@ class PersonSearch extends AbstractSearch implements HasAdvancedSearchFormInterf
'nationality' => $countryCode,
'phonenumber' => $phonenumber,
'city' => $city,
] = $terms + \array_fill_keys(self::POSSIBLE_KEYS, null);
] = $terms + array_fill_keys(self::POSSIBLE_KEYS, null);
foreach (['birthdateBefore', 'birthdateAfter', 'birthdate'] as $v) {
if (NULL !== ${$v}) {
if (null !== ${$v}) {
try {
${$v} = new \DateTime(${$v});
} catch (\Exception $e) {
${$v} = new DateTime(${$v});
} catch (Exception $e) {
throw new ParsingException('The date is '
. 'not parsable', 0, $e);
}
@@ -177,146 +316,23 @@ class PersonSearch extends AbstractSearch implements HasAdvancedSearchFormInterf
);
}
protected function count(array $terms): int
private function findAdditionnalInDefault(array $terms): array
{
[
'_default' => $default,
'firstname' => $firstname,
'lastname' => $lastname,
'birthdate' => $birthdate,
'birthdate-before' => $birthdateBefore,
'birthdate-after' => $birthdateAfter,
'gender' => $gender,
'nationality' => $countryCode,
'phonenumber' => $phonenumber,
'city' => $city,
] = $terms + \array_fill_keys(self::POSSIBLE_KEYS, null);
// chaining some extractor
$datesResults = $this->extractDateFromPattern->extractDates($terms['_default']);
$phoneResults = $this->extractPhonenumberFromPattern->extractPhonenumber($datesResults->getFilteredSubject());
$terms['_default'] = $phoneResults->getFilteredSubject();
foreach (['birthdateBefore', 'birthdateAfter', 'birthdate'] as $v) {
if (NULL !== ${$v}) {
try {
${$v} = new \DateTime(${$v});
} catch (\Exception $e) {
throw new ParsingException('The date is '
. 'not parsable', 0, $e);
}
}
if ($datesResults->hasResult() && (!array_key_exists('birthdate', $terms)
|| null !== $terms['birthdate'])) {
$terms['birthdate'] = $datesResults->getFound()[0]->format('Y-m-d');
}
return $this->personACLAwareRepository
->countBySearchCriteria(
$default,
$firstname,
$lastname,
$birthdate,
$birthdateBefore,
$birthdateAfter,
$gender,
$countryCode,
$phonenumber,
$city
);
}
public function buildForm(FormBuilderInterface $builder)
{
$builder
->add('_default', TextType::class, [
'label' => 'First name or Last name',
'required' => false
])
->add('firstname', TextType::class, [
'label' => 'First name',
'required' => false
])
->add('lastname', TextType::class, [
'label' => 'Last name',
'required' => false
])
->add('birthdate-after', ChillDateType::class, [
'label' => 'Birthdate after',
'required' => false
])
->add('birthdate', ChillDateType::class, [
'label' => 'Birthdate',
'required' => false
])
->add('birthdate-before', ChillDateType::class, [
'label' => 'Birthdate before',
'required' => false
])
->add('phonenumber', TelType::class, [
'required' => false,
'label' => 'Part of the phonenumber'
])
->add('gender', GenderType::class, [
'label' => 'Gender',
'required' => false,
'expanded' => false,
'placeholder' => 'All genders'
])
->add('city', TextType::class, [
'required' => false,
'label' => 'City or postal code'
])
;
}
public function convertFormDataToQuery(array $data)
{
$string = '@person ';
$string .= empty($data['_default']) ? '' : $data['_default'].' ';
foreach(['firstname', 'lastname', 'gender', 'phonenumber', 'city'] as $key) {
$string .= empty($data[$key]) ? '' : $key.':'.
// add quote if contains spaces
(strpos($data[$key], ' ') !== false ? '"'.$data[$key].'"': $data[$key])
.' ';
if ($phoneResults->hasResult() && (!array_key_exists('phonenumber', $terms)
|| null !== $terms['phonenumber'])) {
$terms['phonenumber'] = $phoneResults->getFound()[0];
}
foreach (['birthdate', 'birthdate-before', 'birthdate-after'] as $key) {
$string .= empty($data[$key]) ?
''
:
$key.':'.$data[$key]->format('Y-m-d').' '
;
}
return $string;
}
public function convertTermsToFormData(array $terms)
{
$data = [];
foreach(['firstname', 'lastname', 'gender', '_default', 'phonenumber', 'city'] as $key) {
$data[$key] = $terms[$key] ?? null;
}
// parse dates
foreach (['birthdate', 'birthdate-before', 'birthdate-after'] as $key) {
if (\array_key_exists($key, $terms)) {
try {
$date = new \DateTime($terms[$key]);
} catch (\Exception $ex) {
throw new ParsingException("The date for $key is "
. 'not parsable', 0, $ex);
}
}
$data[$key] = $date ?? null;
}
return $data;
}
public function getAdvancedSearchTitle()
{
return 'Search within persons';
}
public static function getAlias(): string
{
return self::NAME;
return $terms;
}
}

View File

@@ -1,25 +1,39 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Search;
use Chill\MainBundle\Search\SearchApiInterface;
use Chill\MainBundle\Search\SearchApiQuery;
use Chill\MainBundle\Search\Utils\ExtractDateFromPattern;
use Chill\MainBundle\Search\Utils\ExtractPhonenumberFromPattern;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface;
use Chill\PersonBundle\Repository\PersonACLAwareRepositoryInterface;
use Chill\PersonBundle\Repository\PersonRepository;
use Chill\MainBundle\Search\SearchApiQuery;
use Chill\MainBundle\Search\SearchApiInterface;
use Symfony\Component\Security\Core\Security;
use function array_map;
use function in_array;
class SearchPersonApiProvider implements SearchApiInterface
{
private PersonRepository $personRepository;
private Security $security;
private AuthorizationHelperInterface $authorizationHelper;
private ExtractDateFromPattern $extractDateFromPattern;
private PersonACLAwareRepositoryInterface $personACLAwareRepository;
private ExtractPhonenumberFromPattern $extractPhonenumberFromPattern;
private PersonACLAwareRepositoryInterface $personACLAwareRepository;
private PersonRepository $personRepository;
private Security $security;
public function __construct(
PersonRepository $personRepository,
PersonACLAwareRepositoryInterface $personACLAwareRepository,
@@ -36,6 +50,18 @@ class SearchPersonApiProvider implements SearchApiInterface
$this->extractPhonenumberFromPattern = $extractPhonenumberFromPattern;
}
public function getResult(string $key, array $metadata, float $pertinence)
{
return $this->personRepository->find($metadata['id']);
}
public function prepare(array $metadatas): void
{
$ids = array_map(fn ($m) => $m['id'], $metadatas);
$this->personRepository->findByIds($ids);
}
public function provideQuery(string $pattern, array $parameters): SearchApiQuery
{
$datesResult = $this->extractDateFromPattern->extractDates($pattern);
@@ -43,40 +69,27 @@ class SearchPersonApiProvider implements SearchApiInterface
$filtered = $phoneResult->getFilteredSubject();
return $this->personACLAwareRepository->buildAuthorizedQuery(
$filtered,
null,
null,
count($datesResult->getFound()) > 0 ? $datesResult->getFound()[0] : null,
null,
null,
null,
null,
count($phoneResult->getFound()) > 0 ? $phoneResult->getFound()[0] : null
)
->setSelectKey("person")
$filtered,
null,
null,
count($datesResult->getFound()) > 0 ? $datesResult->getFound()[0] : null,
null,
null,
null,
null,
count($phoneResult->getFound()) > 0 ? $phoneResult->getFound()[0] : null
)
->setSelectKey('person')
->setSelectJsonbMetadata("jsonb_build_object('id', person.id)");
}
public function supportsTypes(string $pattern, array $types, array $parameters): bool
{
return \in_array('person', $types);
}
public function prepare(array $metadatas): void
{
$ids = \array_map(fn($m) => $m['id'], $metadatas);
$this->personRepository->findByIds($ids);
}
public function supportsResult(string $key, array $metadatas): bool
{
return $key === 'person';
return 'person' === $key;
}
public function getResult(string $key, array $metadata, float $pertinence)
public function supportsTypes(string $pattern, array $types, array $parameters): bool
{
return $this->personRepository->find($metadata['id']);
return in_array('person', $types);
}
}

View File

@@ -1,48 +1,28 @@
<?php
/*
*
* Copyright (C) 2018, Champs Libres Cooperative SCRLFS, <http://www.champs-libres.coop>
*
* 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 <http://www.gnu.org/licenses/>.
*/
namespace Chill\PersonBundle\Search;
use Chill\PersonBundle\Entity\PersonNotDuplicate;
use Chill\PersonBundle\Templating\Entity\PersonRender;
use Doctrine\ORM\EntityManagerInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Repository\PersonNotDuplicateRepository;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
/**
* Chill is a software for social workers
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\PersonBundle\Search;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Repository\PersonNotDuplicateRepository;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\PersonBundle\Templating\Entity\PersonRender;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role;
class SimilarPersonMatcher
{
CONST SIMILAR_SEARCH_ORDER_BY_ALPHABETICAL = 'alphabetical';
public const SIMILAR_SEARCH_ORDER_BY_ALPHABETICAL = 'alphabetical';
CONST SIMILAR_SEARCH_ORDER_BY_SIMILARITY = 'similarity';
/**
* @var EntityManagerInterface
*/
protected $em;
public const SIMILAR_SEARCH_ORDER_BY_SIMILARITY = 'similarity';
/**
* @var AuthorizationHelper
@@ -50,14 +30,19 @@ class SimilarPersonMatcher
protected $authorizationHelper;
/**
* @var TokenStorageInterface
* @var EntityManagerInterface
*/
protected $tokenStorage;
protected $em;
protected PersonNotDuplicateRepository $personNotDuplicateRepository;
protected PersonRender $personRender;
/**
* @var TokenStorageInterface
*/
protected $tokenStorage;
public function __construct(
EntityManagerInterface $em,
AuthorizationHelper $authorizationHelper,
@@ -88,11 +73,9 @@ class SimilarPersonMatcher
. ' WHERE ('
. ' SIMILARITY(p.fullnameCanonical, UNACCENT(LOWER(:fullName))) >= :precision '
. ' ) '
. ' AND p.center IN (:centers)'
. ' AND p.center IN (:centers)';
;
if ($person->getId() !== NULL) {
if ($person->getId() !== null) {
$dql .= ' AND p.id != :personId ';
$notDuplicatePersons = $this->personNotDuplicateRepository->findNotDuplicatePerson($person);
@@ -107,9 +90,11 @@ class SimilarPersonMatcher
switch ($orderBy) {
case self::SIMILAR_SEARCH_ORDER_BY_ALPHABETICAL:
$dql .= ' ORDER BY p.fullnameCanonical ASC ';
break;
case self::SIMILAR_SEARCH_ORDER_BY_SIMILARITY:
default :
default:
$dql .= ' ORDER BY SIMILARITY(p.fullnameCanonical, UNACCENT(LOWER(:fullName))) DESC ';
}
@@ -117,8 +102,7 @@ class SimilarPersonMatcher
->setDQL($dql)
->setParameter('fullName', $this->personRender->renderString($person, []))
->setParameter('centers', $centers)
->setParameter('precision', $precision)
;
->setParameter('precision', $precision);
return $query->getResult();
}