Merge branch 'master' of gitlab.com:Chill-Projet/chill-bundles

This commit is contained in:
Julie Lenaerts 2021-11-11 13:37:11 +01:00
commit f92c500657
38 changed files with 2208 additions and 620 deletions

View File

@ -54,6 +54,9 @@
"doctrine/doctrine-fixtures-bundle": "^3.3", "doctrine/doctrine-fixtures-bundle": "^3.3",
"fakerphp/faker": "^1.13", "fakerphp/faker": "^1.13",
"nelmio/alice": "^3.8", "nelmio/alice": "^3.8",
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan": "^1.0",
"phpstan/phpstan-strict-rules": "^1.0",
"phpunit/phpunit": "^7.0", "phpunit/phpunit": "^7.0",
"symfony/debug-bundle": "^5.1", "symfony/debug-bundle": "^5.1",
"symfony/dotenv": "^5.1", "symfony/dotenv": "^5.1",

1542
phpstan-baseline.neon Normal file

File diff suppressed because it is too large Load Diff

21
phpstan.neon.dist Normal file
View File

@ -0,0 +1,21 @@
parameters:
level: 1
paths:
- src/
excludePaths:
- src/Bundle/*/Tests/*
- src/Bundle/*/Test/*
- src/Bundle/*/config/*
- src/Bundle/*/migrations/*
- src/Bundle/*/translations/*
- src/Bundle/*/Resources/*
- src/Bundle/*/src/Tests/*
- src/Bundle/*/src/Test/*
- src/Bundle/*/src/config/*
- src/Bundle/*/src/migrations/*
- src/Bundle/*/src/translations/*
- src/Bundle/*/src/Resources/*
includes:
- phpstan-baseline.neon

View File

@ -105,12 +105,12 @@ class ActivityTypeAggregator implements AggregatorInterface
return new Role(ActivityStatsVoter::STATS); return new Role(ActivityStatsVoter::STATS);
} }
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data): \Closure
{ {
// for performance reason, we load data from db only once // for performance reason, we load data from db only once
$this->typeRepository->findBy(array('id' => $values)); $this->typeRepository->findBy(array('id' => $values));
return function($value) use ($data) { return function($value): string {
if ($value === '_header') { if ($value === '_header') {
return 'Activity type'; return 'Activity type';
} }
@ -120,12 +120,11 @@ class ActivityTypeAggregator implements AggregatorInterface
return $this->stringHelper->localize($t->getName()); return $this->stringHelper->localize($t->getName());
}; };
} }
public function getQueryKeys($data) public function getQueryKeys($data): array
{ {
return array(self::KEY); return [self::KEY];
} }
} }

View File

@ -19,8 +19,6 @@ final class ChillAsideActivityExtension extends Extension implements PrependExte
{ {
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @phpstan-ignore-next-line
*/ */
public function load(array $configs, ContainerBuilder $container): void public function load(array $configs, ContainerBuilder $container): void
{ {

View File

@ -30,7 +30,9 @@ final class CategoryRender implements ChillEntityRenderInterface
{ {
$options = array_merge(self::DEFAULT_ARGS, $options); $options = array_merge(self::DEFAULT_ARGS, $options);
$titles[] = $this->translatableStringHelper->localize($asideActivityCategory->getTitle()); $titles = [
$this->translatableStringHelper->localize($asideActivityCategory->getTitle()),
];
while ($asideActivityCategory->hasParent()) { while ($asideActivityCategory->hasParent()) {
$asideActivityCategory = $asideActivityCategory->getParent(); $asideActivityCategory = $asideActivityCategory->getParent();

View File

@ -97,9 +97,9 @@ class CalendarController extends AbstractController
'calendarItems' => $calendarItems, 'calendarItems' => $calendarItems,
'user' => $user 'user' => $user
]); ]);
}
} elseif ($accompanyingPeriod instanceof AccompanyingPeriod) { if ($accompanyingPeriod instanceof AccompanyingPeriod) {
$total = $this->calendarRepository->countByAccompanyingPeriod($accompanyingPeriod); $total = $this->calendarRepository->countByAccompanyingPeriod($accompanyingPeriod);
$paginator = $this->paginator->create($total); $paginator = $this->paginator->create($total);
$calendarItems = $this->calendarRepository->findBy( $calendarItems = $this->calendarRepository->findBy(
@ -117,6 +117,8 @@ class CalendarController extends AbstractController
'paginator' => $paginator 'paginator' => $paginator
]); ]);
} }
throw new \Exception('Unable to list actions.');
} }
/** /**

View File

@ -46,7 +46,11 @@ class ChillCustomFieldsExtension extends Extension implements PrependExtensionIn
public function prepend(ContainerBuilder $container) public function prepend(ContainerBuilder $container)
{ {
// add form layout to twig resources // add form layout to twig resources
$twigConfig['form_themes'][] = 'ChillCustomFieldsBundle:Form:fields.html.twig'; $twigConfig = [
'form_themes' => [
'ChillCustomFieldsBundle:Form:fields.html.twig',
],
];
$container->prependExtensionConfig('twig', $twigConfig); $container->prependExtensionConfig('twig', $twigConfig);
//add routes for custom bundle //add routes for custom bundle

View File

@ -145,5 +145,7 @@ class DocGeneratorTemplateController extends AbstractController
} catch (TransferException $e) { } catch (TransferException $e) {
throw $e; throw $e;
} }
throw new \Exception('Unable to generate document.');
} }
} }

View File

@ -1,8 +1,10 @@
<?php <?php
namespace Chill\DocStoreBundle\Repository; declare(strict_types=1);
use App\Entity\AccompanyingCourseDocument; namespace Chill\DocStoreBundle\EntityRepository;
use Chill\DocStoreBundle\Entity\AccompanyingCourseDocument;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\ManagerRegistry;

View File

@ -181,7 +181,7 @@ class ParticipationController extends AbstractController
protected function newMultiple(Request $request) protected function newMultiple(Request $request)
{ {
$participations = $this->handleRequest($request, new Participation(), true); $participations = $this->handleRequest($request, new Participation(), true);
$ignoredParticipations = $newParticipations = [];
foreach ($participations as $i => $participation) { foreach ($participations as $i => $participation) {
// check for authorization // check for authorization
@ -209,7 +209,7 @@ class ParticipationController extends AbstractController
// this is where the function redirect depending on valid participation // this is where the function redirect depending on valid participation
if (!isset($newParticipations)) { if ([] === $newParticipations) {
// if we do not have nay participants, redirect to event view // if we do not have nay participants, redirect to event view
$this->addFlash('error', $this->get('translator')->trans( $this->addFlash('error', $this->get('translator')->trans(
'None of the requested people may participate ' 'None of the requested people may participate '
@ -222,22 +222,27 @@ class ParticipationController extends AbstractController
// if we have multiple participations, show a form with multiple participations // if we have multiple participations, show a form with multiple participations
$form = $this->createCreateFormMultiple($newParticipations); $form = $this->createCreateFormMultiple($newParticipations);
return $this->render('ChillEventBundle:Participation:new-multiple.html.twig', array( return $this->render(
'ChillEventBundle:Participation:new-multiple.html.twig',
[
'form' => $form->createView(), 'form' => $form->createView(),
'participations' => $newParticipations, 'participations' => $newParticipations,
'ignored_participations' => isset($ignoredParticipations) ? $ignoredParticipations : array() 'ignored_participations' => $ignoredParticipations
)); ]
} else { );
}
// if we have only one participation, show the same form than for single participation // if we have only one participation, show the same form than for single participation
$form = $this->createCreateForm($participation); $form = $this->createCreateForm($participation);
return $this->render('ChillEventBundle:Participation:new.html.twig', array( return $this->render(
'ChillEventBundle:Participation:new.html.twig',
[
'form' => $form->createView(), 'form' => $form->createView(),
'participation' => $participation, 'participation' => $participation,
'ignored_participations' => isset($ignoredParticipations) ? $ignoredParticipations : array() 'ignored_participations' => $ignoredParticipations,
)); ]
);
}
} }
/** /**

View File

@ -504,6 +504,8 @@ class ApiController extends AbstractCRUDController
$this->getContextForSerializationPostAlter($action, $request, $_format, $entity, [$postedData]) $this->getContextForSerializationPostAlter($action, $request, $_format, $entity, [$postedData])
); );
} }
throw new \Exception('Unable to handle such request method.');
} }
/** /**

View File

@ -72,6 +72,7 @@ class LoadCountriesCommand extends Command
public static function prepareCountryList($languages) public static function prepareCountryList($languages)
{ {
$regionBundle = Intl::getRegionBundle(); $regionBundle = Intl::getRegionBundle();
$countries = [];
foreach ($languages as $language) { foreach ($languages as $language) {
$countries[$language] = $regionBundle->getCountryNames($language); $countries[$language] = $regionBundle->getCountryNames($language);

View File

@ -63,12 +63,13 @@ class LoadLanguages extends AbstractFixture implements ContainerAwareInterface,
} }
/** /**
* prepare names for languages * Prepare names for languages.
* *
* @param string $languageCode
* @return string[] languages name indexed by available language code * @return string[] languages name indexed by available language code
*/ */
private function prepareName($languageCode) { private function prepareName(string $languageCode): array {
$names = [];
foreach ($this->container->getParameter('chill_main.available_languages') as $lang) { foreach ($this->container->getParameter('chill_main.available_languages') as $lang) {
$names[$lang] = Intl::getLanguageBundle()->getLanguageName($languageCode); $names[$lang] = Intl::getLanguageBundle()->getLanguageName($languageCode);
} }

View File

@ -1,18 +1,15 @@
<?php <?php
/*
*/ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection\CompilerPass; namespace Chill\MainBundle\DependencyInjection\CompilerPass;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Chill\MainBundle\Form\PermissionsGroupType; use Chill\MainBundle\Form\PermissionsGroupType;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
use LogicException;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ACLFlagsCompilerPass implements CompilerPassInterface class ACLFlagsCompilerPass implements CompilerPassInterface
{ {
public function process(ContainerBuilder $container) public function process(ContainerBuilder $container)
@ -29,7 +26,7 @@ class ACLFlagsCompilerPass implements CompilerPassInterface
$permissionGroupType->addMethodCall('addFlagProvider', [ $reference ]); $permissionGroupType->addMethodCall('addFlagProvider', [ $reference ]);
break; break;
default: default:
throw new \LogicalException(sprintf( throw new LogicException(sprintf(
"This tag 'scope' is not implemented: %s, on service with id %s", $tag['scope'], $id) "This tag 'scope' is not implemented: %s, on service with id %s", $tag['scope'], $id)
); );
} }

View File

@ -19,14 +19,11 @@ class Configuration implements ConfigurationInterface
use AddWidgetConfigurationTrait; use AddWidgetConfigurationTrait;
/** private ContainerBuilder $containerBuilder;
*
* @var ContainerBuilder
*/
private $containerBuilder;
public function __construct(array $widgetFactories = array(), public function __construct(
array $widgetFactories,
ContainerBuilder $containerBuilder) ContainerBuilder $containerBuilder)
{ {
$this->setWidgetFactories($widgetFactories); $this->setWidgetFactories($widgetFactories);

View File

@ -124,11 +124,12 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
* @param string $containerWidgetConfigParameterName the key under which we can use the widget configuration * @param string $containerWidgetConfigParameterName the key under which we can use the widget configuration
* @throws \LogicException * @throws \LogicException
* @throws \UnexpectedValueException if the given extension does not implement HasWidgetExtensionInterface * @throws \UnexpectedValueException if the given extension does not implement HasWidgetExtensionInterface
* @throws \InvalidConfigurationException if there are errors in the config
*/ */
public function doProcess(ContainerBuilder $container, $extension, public function doProcess(
$containerWidgetConfigParameterName) ContainerBuilder $container,
{ $extension,
$containerWidgetConfigParameterName
) {
if (!$container->hasDefinition(self::WIDGET_MANAGER)) { if (!$container->hasDefinition(self::WIDGET_MANAGER)) {
throw new \LogicException("the service ".self::WIDGET_MANAGER." should". throw new \LogicException("the service ".self::WIDGET_MANAGER." should".
" be present. It is required by ".self::class); " be present. It is required by ".self::class);
@ -171,7 +172,7 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
// check that the widget is allowed at this place // check that the widget is allowed at this place
if (!$this->isPlaceAllowedForWidget($place, $alias, $container)) { if (!$this->isPlaceAllowedForWidget($place, $alias, $container)) {
throw new \InvalidConfigurationException(sprintf( throw new InvalidConfigurationException(sprintf(
"The widget with alias %s is not allowed at place %s", "The widget with alias %s is not allowed at place %s",
$alias, $alias,
$place $place

View File

@ -4,13 +4,9 @@ namespace Chill\MainBundle\Doctrine\Model;
use \JsonSerializable; use \JsonSerializable;
/**
* Description of Point
*
*/
class Point implements JsonSerializable { class Point implements JsonSerializable {
private ?float $lat = null; private ?float $lat;
private ?float $lon = null; private ?float $lon;
public static string $SRID = '4326'; public static string $SRID = '4326';
private function __construct(?float $lon, ?float $lat) private function __construct(?float $lon, ?float $lat)
@ -22,6 +18,7 @@ class Point implements JsonSerializable {
public function toGeoJson(): string public function toGeoJson(): string
{ {
$array = $this->toArrayGeoJson(); $array = $this->toArrayGeoJson();
return \json_encode($array); return \json_encode($array);
} }
@ -33,60 +30,53 @@ class Point implements JsonSerializable {
public function toArrayGeoJson(): array public function toArrayGeoJson(): array
{ {
return [ return [
"type" => "Point", 'type' => 'Point',
"coordinates" => [ $this->lon, $this->lat ] 'coordinates' => [$this->lon, $this->lat],
]; ];
} }
/**
*
* @return string
*/
public function toWKT(): string public function toWKT(): string
{ {
return 'SRID='.self::$SRID.';POINT('.$this->lon.' '.$this->lat.')'; return sprintf("SRID=%s;POINT(%s %s)", self::$SRID, $this->lon, $this->lat);
} }
/** public static function fromGeoJson(string $geojson): self
*
* @param type $geojson
* @return Point
*/
public static function fromGeoJson(string $geojson): Point
{ {
$a = json_decode($geojson); $a = json_decode($geojson);
//check if the geojson string is correct
if (NULL === $a or !isset($a->type) or !isset($a->coordinates)){ if (null === $a) {
throw PointException::badJsonString($geojson); throw PointException::badJsonString($geojson);
} }
if ($a->type != 'Point'){ if (null === $a->type || null === $a->coordinates) {
throw PointException::badJsonString($geojson);
}
if ($a->type !== 'Point'){
throw PointException::badGeoType(); throw PointException::badGeoType();
} }
$lat = $a->coordinates[1]; [$lon, $lat] = $a->coordinates;
$lon = $a->coordinates[0];
return Point::fromLonLat($lon, $lat); return Point::fromLonLat($lon, $lat);
} }
public static function fromLonLat(float $lon, float $lat): Point public static function fromLonLat(float $lon, float $lat): self
{
if (($lon > -180 && $lon < 180) && ($lat > -90 && $lat < 90))
{ {
if (($lon > -180 && $lon < 180) && ($lat > -90 && $lat < 90)) {
return new Point($lon, $lat); return new Point($lon, $lat);
} else {
throw PointException::badCoordinates($lon, $lat);
}
} }
public static function fromArrayGeoJson(array $array): Point throw PointException::badCoordinates($lon, $lat);
{ }
if ($array['type'] == 'Point' &&
isset($array['coordinates'])) public static function fromArrayGeoJson(array $array): self
{ {
if ($array['type'] === 'Point' && isset($array['coordinates'])) {
return self::fromLonLat($array['coordinates'][0], $array['coordinates'][1]); return self::fromLonLat($array['coordinates'][0], $array['coordinates'][1]);
} }
throw new \Exception('Unable to build a point from input data.');
} }
public function getLat(): float public function getLat(): float

View File

@ -51,8 +51,10 @@ class CenterTransformer implements DataTransformerInterface
} }
} }
$ids = [];
if ($this->multiple) { if ($this->multiple) {
$ids = \explode(',', $id); $ids = explode(',', $id);
} else { } else {
$ids[] = (int) $id; $ids[] = (int) $id;
} }
@ -68,9 +70,9 @@ class CenterTransformer implements DataTransformerInterface
if ($this->multiple) { if ($this->multiple) {
return new ArrayCollection($centers); return new ArrayCollection($centers);
} else {
return $centers[0];
} }
return $centers[0];
} }
public function transform($center) public function transform($center)

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Repository; namespace Chill\MainBundle\Repository;
use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\User; use Chill\MainBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;

View File

@ -139,7 +139,7 @@ class SearchApi
return $nq->getResult(); return $nq->getResult();
} }
private function prepareProviders($rawResults) private function prepareProviders(array $rawResults)
{ {
$metadatas = []; $metadatas = [];
foreach ($rawResults as $r) { foreach ($rawResults as $r) {
@ -156,8 +156,10 @@ class SearchApi
} }
} }
private function buildResults($rawResults) private function buildResults(array $rawResults): array
{ {
$items = [];
foreach ($rawResults as $r) { foreach ($rawResults as $r) {
foreach ($this->providers as $k => $p) { foreach ($this->providers as $k => $p) {
if ($p->supportsResult($r['key'], $r['metadata'])) { if ($p->supportsResult($r['key'], $r['metadata'])) {
@ -170,6 +172,6 @@ class SearchApi
} }
} }
return $items ?? []; return $items;
} }
} }

View File

@ -98,5 +98,7 @@ class PasswordRecoverVoter extends Voter
return true; return true;
} }
return false;
} }
} }

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Chill\MainBundle\Serializer\Normalizer; namespace Chill\MainBundle\Serializer\Normalizer;
use Chill\MainBundle\Entity\Address; use Chill\MainBundle\Entity\Address;
@ -12,31 +14,41 @@ class AddressNormalizer implements NormalizerAwareInterface, NormalizerInterface
{ {
use NormalizerAwareTrait; use NormalizerAwareTrait;
/**
* @param Address $address
*/
public function normalize($address, string $format = null, array $context = []) public function normalize($address, string $format = null, array $context = [])
{ {
/** @var Address $address */ $data = [
$data['address_id'] = $address->getId(); 'address_id' => $address->getId(),
$data['text'] = $address->isNoAddress() ? '' : $address->getStreetNumber().', '.$address->getStreet(); 'text' => $address->isNoAddress() ? '' : $address->getStreetNumber().', '.$address->getStreet(),
$data['street'] = $address->getStreet(); 'street' => $address->getStreet(),
$data['streetNumber'] = $address->getStreetNumber(); 'streetNumber' => $address->getStreetNumber(),
$data['postcode']['id'] = $address->getPostCode()->getId(); 'postcode' => [
$data['postcode']['name'] = $address->getPostCode()->getName(); 'id' => $address->getPostCode()->getId(),
$data['postcode']['code'] = $address->getPostCode()->getCode(); 'name' => $address->getPostCode()->getName(),
$data['country']['id'] = $address->getPostCode()->getCountry()->getId(); 'code' => $address->getPostCode()->getCode(),
$data['country']['name'] = $address->getPostCode()->getCountry()->getName(); ],
$data['country']['code'] = $address->getPostCode()->getCountry()->getCountryCode(); 'country' => [
$data['floor'] = $address->getFloor(); 'id' => $address->getPostCode()->getCountry()->getId(),
$data['corridor'] = $address->getCorridor(); 'name' => $address->getPostCode()->getCountry()->getName(),
$data['steps'] = $address->getSteps(); 'code' => $address->getPostCode()->getCountry()->getCountryCode(),
$data['flat'] = $address->getFlat(); ],
$data['buildingName'] = $address->getBuildingName(); 'floor' => $address->getFloor(),
$data['distribution'] = $address->getDistribution(); 'corridor' => $address->getCorridor(),
$data['extra'] = $address->getExtra(); 'steps' => $address->getSteps(),
$data['validFrom'] = $address->getValidFrom(); 'flat' => $address->getFlat(),
$data['validTo'] = $address->getValidTo(); 'buildingName' => $address->getBuildingName(),
$data['addressReference'] = $this->normalizer->normalize($address->getAddressReference(), $format, [ 'distribution' => $address->getDistribution(),
AbstractNormalizer::GROUPS => ['read'] 'extra' => $address->getExtra(),
]); 'validFrom' => $address->getValidFrom(),
'validTo' => $address->getValidTo(),
'addressReference' => $this->normalizer->normalize(
$address->getAddressReference(),
$format,
[AbstractNormalizer::GROUPS => ['read']]
),
];
return $data; return $data;
} }

View File

@ -11,30 +11,28 @@ class CollectionNormalizer implements NormalizerInterface, NormalizerAwareInterf
{ {
use NormalizerAwareTrait; use NormalizerAwareTrait;
/**
* @param Collection $collection
*/
public function normalize($collection, string $format = null, array $context = [])
{
$paginator = $collection->getPaginator();
return [
'count' => $paginator->getTotalItems(),
'pagination' => [
'first' => $paginator->getCurrentPageFirstItemNumber(),
'items_per_page' => $paginator->getItemsPerPage(),
'next' => $paginator->hasNextPage() ? $paginator->getNextPage()->generateUrl() : null,
'previous' => $paginator->hasPreviousPage() ? $paginator->getPreviousPage()->generateUrl() : null,
'more' => $paginator->hasNextPage(),
],
'results' => $this->normalizer->normalize($collection->getItems(), $format, $context),
];
}
public function supportsNormalization($data, string $format = null): bool public function supportsNormalization($data, string $format = null): bool
{ {
return $data instanceof Collection; return $data instanceof Collection;
} }
public function normalize($collection, string $format = null, array $context = [])
{
/** @var $collection Collection */
$paginator = $collection->getPaginator();
$data['count'] = $paginator->getTotalItems();
$pagination['first'] = $paginator->getCurrentPageFirstItemNumber();
$pagination['items_per_page'] = $paginator->getItemsPerPage();
$pagination['next'] = $paginator->hasNextPage() ?
$paginator->getNextPage()->generateUrl() : null;
$pagination['previous'] = $paginator->hasPreviousPage() ?
$paginator->getPreviousPage()->generateUrl() : null;
$pagination['more'] = $paginator->hasNextPage();
$data['pagination'] = $pagination;
// normalize results
$data['results'] = $this->normalizer->normalize($collection->getItems(),
$format, $context);
return $data;
}
} }

View File

@ -291,11 +291,12 @@ class TimelineBuilder implements ContainerAwareInterface
$entitiesByType[$result['type']][$result['id']], //the entity $entitiesByType[$result['type']][$result['id']], //the entity
$context, $context,
$args); $args);
$timelineEntry['date'] = new \DateTime($result['date']);
$timelineEntry['template'] = $data['template'];
$timelineEntry['template_data'] = $data['template_data'];
$timelineEntries[] = $timelineEntry; $timelineEntries[] = [
'date' => new \DateTime($result['date']),
'template' => $data['template'],
'template_data' => $data['template_data']
];
} }
return $this->container->get('templating') return $this->container->get('templating')

View File

@ -205,7 +205,7 @@ class DateRangeCovering
{ {
if (!$this->computed) { if (!$this->computed) {
throw new \LogicException(sprintf("You cannot call the method %s before ". throw new \LogicException(sprintf("You cannot call the method %s before ".
"'process'", __METHOD)); "'process'", __METHOD__));
} }
return count($this->intersections) > 0; return count($this->intersections) > 0;
@ -215,7 +215,7 @@ class DateRangeCovering
{ {
if (!$this->computed) { if (!$this->computed) {
throw new \LogicException(sprintf("You cannot call the method %s before ". throw new \LogicException(sprintf("You cannot call the method %s before ".
"'process'", __METHOD)); "'process'", __METHOD__));
} }
return $this->intersections; return $this->intersections;

View File

@ -1,20 +1,7 @@
<?php <?php
/*
* Copyright (C) 2016-2019 Champs-Libres <info@champs-libres.coop> declare(strict_types=1);
*
* 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\CRUD\Controller; namespace Chill\PersonBundle\CRUD\Controller;
use Chill\MainBundle\CRUD\Controller\CRUDController; use Chill\MainBundle\CRUD\Controller\CRUDController;
@ -23,11 +10,8 @@ use Chill\PersonBundle\Entity\Person;
use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RedirectResponse;
use BadMethodCallException;
/**
* Controller for entities attached as one-to-on to a person
*
*/
class OneToOneEntityPersonCRUDController extends CRUDController class OneToOneEntityPersonCRUDController extends CRUDController
{ {
protected function getTemplateFor($action, $entity, Request $request) protected function getTemplateFor($action, $entity, Request $request)
@ -83,7 +67,7 @@ class OneToOneEntityPersonCRUDController extends CRUDController
protected function generateRedirectOnCreateRoute($action, Request $request, $entity) protected function generateRedirectOnCreateRoute($action, Request $request, $entity)
{ {
throw new BadMethodCallException("not implemtented yet"); throw new BadMethodCallException('Not implemented yet.');
} }
} }

View File

@ -959,6 +959,8 @@ EOF
$table->setHeaders(array('#', 'label', 'value')); $table->setHeaders(array('#', 'label', 'value'));
$i = 0; $i = 0;
$matchingTableRowAnswer = [];
foreach($answers as $key => $answer) { foreach($answers as $key => $answer) {
$table->addRow(array( $table->addRow(array(
$i, $answer, $key $i, $answer, $key

View File

@ -161,8 +161,10 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
\shuffle($this->personIds); \shuffle($this->personIds);
} }
private function getRandomPersons(int $min, int $max) private function getRandomPersons(int $min, int $max): array
{ {
$persons = [];
$nb = \random_int($min, $max); $nb = \random_int($min, $max);
for ($i=0; $i < $nb; $i++) { for ($i=0; $i < $nb; $i++) {
@ -172,7 +174,7 @@ class LoadHousehold extends Fixture implements DependentFixtureInterface
; ;
} }
return $persons ?? []; return $persons;
} }
public function getDependencies() public function getDependencies()

View File

@ -143,6 +143,8 @@ final class CountryOfBirthAggregator implements AggregatorInterface, ExportEleme
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data)
{ {
$labels = [];
if ($data['group_by_level'] === 'country') { if ($data['group_by_level'] === 'country') {
$qb = $this->countriesRepository->createQueryBuilder('c'); $qb = $this->countriesRepository->createQueryBuilder('c');
@ -153,15 +155,17 @@ final class CountryOfBirthAggregator implements AggregatorInterface, ExportEleme
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR); ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
// initialize array and add blank key for null values // initialize array and add blank key for null values
$labels[''] = $this->translator->trans('without data'); $labels = [
$labels['_header'] = $this->translator->trans('Country of birth'); '' => $this->translator->trans('without data'),
'_header' => $this->translator->trans('Country of birth'),
];
foreach($countries as $row) { foreach($countries as $row) {
$labels[$row['c_countryCode']] = $this->translatableStringHelper->localize($row['c_name']); $labels[$row['c_countryCode']] = $this->translatableStringHelper->localize($row['c_name']);
} }
}
if ($data['group_by_level'] === 'continent') {
} elseif ($data['group_by_level'] === 'continent') {
$labels = array( $labels = array(
'EU' => $this->translator->trans('Europe'), 'EU' => $this->translator->trans('Europe'),
'AS' => $this->translator->trans('Asia'), 'AS' => $this->translator->trans('Asia'),
@ -175,8 +179,7 @@ final class CountryOfBirthAggregator implements AggregatorInterface, ExportEleme
); );
} }
return function(string $value) use ($labels): string {
return function($value) use ($labels) {
return $labels[$value]; return $labels[$value];
}; };

View File

@ -144,6 +144,8 @@ final class NationalityAggregator implements AggregatorInterface, ExportElementV
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data)
{ {
$labels = [];
if ($data['group_by_level'] === 'country') { if ($data['group_by_level'] === 'country') {
$qb = $this->countriesRepository->createQueryBuilder('c'); $qb = $this->countriesRepository->createQueryBuilder('c');
@ -154,15 +156,17 @@ final class NationalityAggregator implements AggregatorInterface, ExportElementV
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR); ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
// initialize array and add blank key for null values // initialize array and add blank key for null values
$labels[''] = $this->translator->trans('without data'); $labels = [
$labels['_header'] = $this->translator->trans('Nationality'); '' => $this->translator->trans('without data'),
'_header' => $this->translator->trans('Nationality'),
];
foreach($countries as $row) { foreach($countries as $row) {
$labels[$row['c_countryCode']] = $this->translatableStringHelper->localize($row['c_name']); $labels[$row['c_countryCode']] = $this->translatableStringHelper->localize($row['c_name']);
} }
}
if ($data['group_by_level'] === 'continent') {
} elseif ($data['group_by_level'] === 'continent') {
$labels = array( $labels = array(
'EU' => $this->translator->trans('Europe'), 'EU' => $this->translator->trans('Europe'),
'AS' => $this->translator->trans('Asia'), 'AS' => $this->translator->trans('Asia'),
@ -176,8 +180,7 @@ final class NationalityAggregator implements AggregatorInterface, ExportElementV
); );
} }
return function(string $value) use ($labels): string {
return function($value) use ($labels) {
return $labels[$value]; return $labels[$value];
}; };

View File

@ -1,8 +1,10 @@
<?php <?php
declare(strict_types=1);
namespace Chill\PersonBundle\Repository\Household; namespace Chill\PersonBundle\Repository\Household;
use Chill\PersonBundle\Entity\Household\HouseholdMembers; use Chill\PersonBundle\Entity\Household\HouseholdMember;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
@ -12,6 +14,6 @@ final class HouseholdMembersRepository
public function __construct(EntityManagerInterface $entityManager) public function __construct(EntityManagerInterface $entityManager)
{ {
$this->repository = $entityManager->getRepository(HouseholdMembers::class); $this->repository = $entityManager->getRepository(HouseholdMember::class);
} }
} }

View File

@ -263,8 +263,9 @@ class PersonSearch extends AbstractSearch implements HasAdvancedSearchFormInterf
public function convertTermsToFormData(array $terms) public function convertTermsToFormData(array $terms)
{ {
foreach(['firstname', 'lastname', 'gender', '_default'] $data = [];
as $key) {
foreach(['firstname', 'lastname', 'gender', '_default'] as $key) {
$data[$key] = $terms[$key] ?? null; $data[$key] = $terms[$key] ?? null;
} }

View File

@ -38,7 +38,7 @@ class SocialActionRender implements ChillEntityRenderInterface
{ {
/** @var $socialAction SocialAction */ /** @var $socialAction SocialAction */
$options = \array_merge(self::DEFAULT_ARGS, $options); $options = \array_merge(self::DEFAULT_ARGS, $options);
$titles[] = $this->translatableStringHelper->localize($socialAction->getTitle()); $titles = [$this->translatableStringHelper->localize($socialAction->getTitle())];
while ($socialAction->hasParent()) { while ($socialAction->hasParent()) {
$socialAction = $socialAction->getParent(); $socialAction = $socialAction->getParent();

View File

@ -38,8 +38,7 @@ final class SocialIssueRender implements ChillEntityRenderInterface
/** @var $socialIssue SocialIssue */ /** @var $socialIssue SocialIssue */
$options = array_merge(self::DEFAULT_ARGS, $options); $options = array_merge(self::DEFAULT_ARGS, $options);
$titles[] = $this->translatableStringHelper $titles = [$this->translatableStringHelper->localize($socialIssue->getTitle())];
->localize($socialIssue->getTitle());
// loop to parent, until root // loop to parent, until root
while ($socialIssue->hasParent()) { while ($socialIssue->hasParent()) {

View File

@ -196,9 +196,8 @@ class ReportList implements ListInterface, ExportElementValidatedInterface
* @param type $key * @param type $key
* @param array $values * @param array $values
* @param type $data * @param type $data
* @return type
*/ */
public function getLabels($key, array $values, $data) public function getLabels($key, array $values, $data): \Closure
{ {
switch ($key) { switch ($key) {
case 'person_birthdate': case 'person_birthdate':
@ -237,12 +236,13 @@ class ReportList implements ListInterface, ExportElementValidatedInterface
; ;
$rows = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY); $rows = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);
$scopes = [];
foreach($rows as $row) { foreach($rows as $row) {
$scopes[$row['id']] = $this->translatableStringHelper $scopes[$row['id']] = $this->translatableStringHelper->localize($row['name']);
->localize($row['name']);
} }
return function($value) use ($scopes) { return function($value) use ($scopes): string {
if ($value === '_header') { if ($value === '_header') {
return 'circle'; return 'circle';
} }
@ -258,11 +258,13 @@ class ReportList implements ListInterface, ExportElementValidatedInterface
; ;
$rows = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY); $rows = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);
$users = [];
foreach($rows as $row) { foreach($rows as $row) {
$users[$row['id']] = $row['username']; $users[$row['id']] = $row['username'];
} }
return function($value) use ($users) { return function($value) use ($users): string {
if ($value === '_header') { if ($value === '_header') {
return 'user'; return 'user';
} }

View File

@ -157,7 +157,7 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
// the parameters // the parameters
$parameters = []; $parameters = $circleIds = [];
// the clause that we will fill // the clause that we will fill
$clause = "{person}.{person_id} = ? AND {task}.{circle} IN ({circle_ids})"; $clause = "{person}.{person_id} = ? AND {task}.{circle} IN ({circle_ids})";

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Chill\ThirdPartyBundle\Serializer\Normalizer; namespace Chill\ThirdPartyBundle\Serializer\Normalizer;
use Chill\ThirdPartyBundle\Entity\ThirdParty; use Chill\ThirdPartyBundle\Entity\ThirdParty;
@ -20,23 +22,24 @@ class ThirdPartyNormalizer implements NormalizerInterface, NormalizerAwareInterf
$this->thirdPartyRender = $thirdPartyRender; $this->thirdPartyRender = $thirdPartyRender;
} }
/**
* @param ThirdParty $thirdParty
*/
public function normalize($thirdParty, string $format = null, array $context = []) public function normalize($thirdParty, string $format = null, array $context = [])
{ {
/** @var $thirdParty ThirdParty */ return [
$data['type'] = 'thirdparty'; 'type' => 'thirdparty',
$data['text'] = $this->thirdPartyRender->renderString($thirdParty, []); 'text' => $this->thirdPartyRender->renderString($thirdParty, []),
$data['id'] = $thirdParty->getId(); 'id' => $thirdParty->getId(),
$data['kind'] = $thirdParty->getKind(); 'kind' => $thirdParty->getKind(),
$data['address'] = $this->normalizer->normalize($thirdParty->getAddress(), $format, 'address' => $this->normalizer->normalize($thirdParty->getAddress(), $format, [ 'address_rendering' => 'short' ]),
[ 'address_rendering' => 'short' ]); 'phonenumber' => $thirdParty->getTelephone(),
$data['phonenumber'] = $thirdParty->getTelephone(); 'email' => $thirdParty->getEmail(),
$data['email'] = $thirdParty->getEmail(); 'isChild' => $thirdParty->isChild(),
$data['isChild'] = $thirdParty->isChild(); 'parent' => $this->normalizer->normalize($thirdParty->getParent(), $format, $context),
$data['parent'] = $this->normalizer->normalize($thirdParty->getParent(), $format, $context); 'civility' => $this->normalizer->normalize($thirdParty->getCivility(), $format, $context),
$data['civility'] = $this->normalizer->normalize($thirdParty->getCivility(), $format, $context); 'contactDataAnonymous' => $thirdParty->isContactDataAnonymous(),
$data['contactDataAnonymous'] = $thirdParty->isContactDataAnonymous(); ];
return $data;
} }
public function supportsNormalization($data, string $format = null) public function supportsNormalization($data, string $format = null)