apply more cs rules for php-cs

This commit is contained in:
2023-10-17 13:27:03 +02:00
parent 0b0cbed9db
commit bc2041cbdd
1485 changed files with 8169 additions and 9620 deletions

View File

@@ -38,10 +38,10 @@ class CRUDControllerCompilerPass implements CompilerPassInterface
private function configureCrudController(ContainerBuilder $container, array $crudEntry, string $apiOrCrud): void
{
$controllerClass = $crudEntry['controller'];
$controllerServiceName = 'cs' . $apiOrCrud . '_' . $crudEntry['name'] . '_controller';
$controllerServiceName = 'cs'.$apiOrCrud.'_'.$crudEntry['name'].'_controller';
// create config parameter in container
$param = 'chill_main_' . $apiOrCrud . '_config_' . $crudEntry['name'];
$param = 'chill_main_'.$apiOrCrud.'_config_'.$crudEntry['name'];
$container->setParameter($param, $crudEntry);
if ($container->hasDefinition($controllerClass)) {
@@ -51,7 +51,7 @@ class CRUDControllerCompilerPass implements CompilerPassInterface
// add the "addMethodCall"
$container->getDefinition($controllerClass)
->addMethodCall('setCrudConfig', ['%' . $param . '%']);
->addMethodCall('setCrudConfig', ['%'.$param.'%']);
} else {
$controller = new Definition($controllerClass);
@@ -59,7 +59,7 @@ class CRUDControllerCompilerPass implements CompilerPassInterface
$controller->setAutoconfigured(true);
$controller->setPublic(true);
$controller->addMethodCall('setCrudConfig', ['%' . $param . '%']);
$controller->addMethodCall('setCrudConfig', ['%'.$param.'%']);
$container->setDefinition($controllerServiceName, $controller);
}

View File

@@ -23,8 +23,6 @@ use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_merge;
abstract class AbstractCRUDController extends AbstractController
{
/**
@@ -49,14 +47,12 @@ abstract class AbstractCRUDController extends AbstractController
return $this->crudConfig['base_role'];
}
throw new \RuntimeException(sprintf('the config does not have any role for the ' .
'method %s nor a global role for the whole action. Add those to your ' .
'configuration or override the required method', $request->getMethod()));
throw new \RuntimeException(sprintf('the config does not have any role for the method %s nor a global role for the whole action. Add those to your configuration or override the required method', $request->getMethod()));
}
public static function getSubscribedServices(): array
{
return array_merge(
return \array_merge(
parent::getSubscribedServices(),
[
'chill_main.paginator_factory' => PaginatorFactory::class,
@@ -153,7 +149,7 @@ abstract class AbstractCRUDController extends AbstractController
}
/**
* @return string The crud name.
* @return string the crud name
*/
protected function getCrudName(): string
{

View File

@@ -13,9 +13,6 @@ namespace Chill\MainBundle\CRUD\Controller;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Serializer\Model\Collection;
use Exception;
use LogicException;
use RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
@@ -24,15 +21,11 @@ use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use function array_merge;
use function ucfirst;
class ApiController extends AbstractCRUDController
{
/**
* Base method for handling api action.
*
* @param string $_format
* @return void
*/
public function entityApi(Request $request, mixed $id, ?string $_format = 'json'): Response
@@ -51,8 +44,7 @@ class ApiController extends AbstractCRUDController
$entity = $this->getEntity($action, $id, $request);
if (null === $entity) {
throw $this->createNotFoundException(sprintf('The %s with id %s '
. 'is not found', $this->getCrudName(), $id));
throw $this->createNotFoundException(sprintf('The %s with id %s is not found', $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $request, $_format, $entity);
@@ -119,8 +111,7 @@ class ApiController extends AbstractCRUDController
}
if (null === $entity) {
throw $this->createNotFoundException(sprintf('The %s with id %s '
. 'is not found', $this->getCrudName(), $id));
throw $this->createNotFoundException(sprintf('The %s with id %s is not found', $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $request, $_format, $entity);
@@ -214,10 +205,11 @@ class ApiController extends AbstractCRUDController
*
* @param string action
* @param mixed id
* @param string $property the name of the property. This will be used to make a `add+$property` and `remove+$property` method
* @param string $postedDataType the type of the posted data (the content)
* @param string $property the name of the property. This will be used to make a `add+$property` and `remove+$property` method
* @param string $postedDataType the type of the posted data (the content)
* @param string $postedDataContext a context to deserialize posted data (the content)
* @param bool $forcePersist force to persist the created element (only for POST request)
* @param bool $forcePersist force to persist the created element (only for POST request)
*
* @throw BadRequestException if unable to deserialize the posted data
* @throw BadRequestException if the method is not POST or DELETE
*/
@@ -252,15 +244,14 @@ class ApiController extends AbstractCRUDController
try {
$postedData = $this->getSerializer()->deserialize($request->getContent(), $postedDataType, $_format, $postedDataContext);
} catch (\Symfony\Component\Serializer\Exception\UnexpectedValueException $e) {
throw new BadRequestHttpException(sprintf('Unable to deserialize posted ' .
'data: %s', $e->getMessage()), $e, 0);
throw new BadRequestHttpException(sprintf('Unable to deserialize posted data: %s', $e->getMessage()), $e, 0);
}
match ($request->getMethod()) {
/* @phpstan-ignore-next-line */
Request::METHOD_DELETE => $entity->{'remove' . ucfirst($property)}($postedData),
/* @phpstan-ignore-next-line */
Request::METHOD_POST => $entity->{'add' . ucfirst($property)}($postedData),
/* @phpstan-ignore-next-line */
Request::METHOD_DELETE => $entity->{'remove'.\ucfirst($property)}($postedData),
/* @phpstan-ignore-next-line */
Request::METHOD_POST => $entity->{'add'.\ucfirst($property)}($postedData),
default => throw new BadRequestHttpException('this method is not supported'),
};
@@ -277,7 +268,7 @@ class ApiController extends AbstractCRUDController
return $this->json($errors, 422);
}
if ($forcePersist && $request->getMethod() === Request::METHOD_POST) {
if ($forcePersist && Request::METHOD_POST === $request->getMethod()) {
$this->getDoctrine()->getManager()->persist($postedData);
}
@@ -288,6 +279,7 @@ class ApiController extends AbstractCRUDController
if ($response instanceof Response) {
return $response;
}
return match ($request->getMethod()) {
Request::METHOD_DELETE => $this->json('', Response::HTTP_OK),
Request::METHOD_POST => $this->json(
@@ -296,7 +288,7 @@ class ApiController extends AbstractCRUDController
[],
$this->getContextForSerializationPostAlter($action, $request, $_format, $entity, [$postedData])
),
default => throw new Exception('Unable to handle such request method.'),
default => throw new \Exception('Unable to handle such request method.'),
};
}
@@ -313,7 +305,7 @@ class ApiController extends AbstractCRUDController
$default[AbstractNormalizer::OBJECT_TO_POPULATE] = $entity;
}
$context = array_merge(
$context = \array_merge(
$default,
$this->getContextForSerialization($action, $request, $_format, $entity)
);
@@ -438,7 +430,7 @@ class ApiController extends AbstractCRUDController
return match ($request->getMethod()) {
Request::METHOD_GET => ['groups' => ['read']],
Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_POST => ['groups' => ['write']],
default => throw new LogicException('get context for serialization is not implemented for this method'),
default => throw new \LogicException('get context for serialization is not implemented for this method'),
};
}
@@ -453,7 +445,6 @@ class ApiController extends AbstractCRUDController
return ['groups' => ['read']];
}
protected function getSerializer(): SerializerInterface
{
return $this->get('serializer');

View File

@@ -19,7 +19,6 @@ use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Chill\MainBundle\Templating\Listing\FilterOrderHelperFactoryInterface;
use Doctrine\ORM\QueryBuilder;
use LogicException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormInterface;
@@ -30,9 +29,6 @@ use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
use function array_merge;
class CRUDController extends AbstractController
{
/**
@@ -47,9 +43,6 @@ class CRUDController extends AbstractController
return new Response($parameter);
}
/**
* @param $id
*/
public function delete(Request $request, $id): Response
{
return $this->deleteAction('delete', $request, $id);
@@ -75,7 +68,7 @@ class CRUDController extends AbstractController
public static function getSubscribedServices(): array
{
return array_merge(
return \array_merge(
parent::getSubscribedServices(),
[
'chill_main.paginator_factory' => PaginatorFactory::class,
@@ -178,7 +171,6 @@ class CRUDController extends AbstractController
* Throw an \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException
* if not accessible.
*
*
* @throws \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException
*/
protected function checkACL(string $action, mixed $entity)
@@ -189,7 +181,7 @@ class CRUDController extends AbstractController
/**
* Count the number of entities.
*/
protected function countEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null): int
protected function countEntities(string $action, Request $request, FilterOrderHelper $filterOrder = null): int
{
return $this->buildQueryEntities($action, $request)
->select('COUNT(e)')
@@ -217,10 +209,8 @@ class CRUDController extends AbstractController
*
* It is preferable to override customizeForm instead of overriding
* this method.
*
* @param string $formClass
*/
protected function createFormFor(string $action, mixed $entity, ?string $formClass = null, array $formOptions = []): FormInterface
protected function createFormFor(string $action, mixed $entity, string $formClass = null, array $formOptions = []): FormInterface
{
$formClass ??= $this->getFormClassFor($action);
@@ -239,7 +229,6 @@ class CRUDController extends AbstractController
protected function customizeQuery(string $action, Request $request, $query): void {}
/**
* @param $id
* @param null $formClass
*/
protected function deleteAction(string $action, Request $request, $id, $formClass = null): Response
@@ -255,13 +244,7 @@ class CRUDController extends AbstractController
}
if (null === $entity) {
throw $this->createNotFoundException(
sprintf(
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
throw $this->createNotFoundException(sprintf('The %s with id %s is not found', $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $entity);
@@ -300,7 +283,7 @@ class CRUDController extends AbstractController
return $result;
}
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_view', ['id' => $entity->getId()]);
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_view', ['id' => $entity->getId()]);
}
if ($form->isSubmitted()) {
@@ -321,8 +304,6 @@ class CRUDController extends AbstractController
/**
* Duplicate an entity.
*
* @return mixed
*/
protected function duplicateEntity(string $action, Request $request)
{
@@ -419,7 +400,7 @@ class CRUDController extends AbstractController
return $result;
}
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_view', ['id' => $entity->getId()]);
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_view', ['id' => $entity->getId()]);
}
if ($form->isSubmitted()) {
@@ -475,20 +456,15 @@ class CRUDController extends AbstractController
* The parameters may be personnalized using `generateTemplateParameter`.
*
* @param class-string $formClass
*
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
protected function formEditAction(string $action, Request $request, mixed $id, ?string $formClass = null, array $formOptions = []): Response
protected function formEditAction(string $action, Request $request, mixed $id, string $formClass = null, array $formOptions = []): Response
{
$entity = $this->getEntity($action, $id, $request);
if (null === $entity) {
throw $this->createNotFoundException(
sprintf(
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
throw $this->createNotFoundException(sprintf('The %s with id %s is not found', $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $entity);
@@ -523,7 +499,7 @@ class CRUDController extends AbstractController
return $result;
}
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_index');
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_index');
}
if ($form->isSubmitted()) {
@@ -574,7 +550,6 @@ class CRUDController extends AbstractController
/**
* Customize template parameters.
*
*
* @return array
*/
protected function generateTemplateParameter(
@@ -588,8 +563,6 @@ class CRUDController extends AbstractController
/**
* Include services.
*
* @return mixed
*/
protected function getActionConfig(string $action)
{
@@ -623,8 +596,6 @@ class CRUDController extends AbstractController
* get the instance of the entity with the given id.
*
* @param string $id
*
* @return object
*/
protected function getEntity(mixed $action, $id, Request $request): ?object
{
@@ -679,15 +650,13 @@ class CRUDController extends AbstractController
/**
* Get the result of the query.
*
* @return mixed
*/
protected function getQueryResult(
string $action,
Request $request,
int $totalItems,
PaginatorInterface $paginator,
?FilterOrderHelper $filterOrder = null
FilterOrderHelper $filterOrder = null
) {
$query = $this->queryEntities($action, $request, $paginator, $filterOrder);
@@ -697,7 +666,7 @@ class CRUDController extends AbstractController
/**
* @return \Chill\MainBundle\Entity\Center[]
*/
protected function getReachableCenters(string $role, ?Scope $scope = null)
protected function getReachableCenters(string $role, Scope $scope = null)
{
return $this->getAuthorizationHelper()
->getReachableCenters($this->getUser(), $role, $scope);
@@ -712,7 +681,7 @@ class CRUDController extends AbstractController
*/
protected function getRoleFor($action)
{
if (array_key_exists('role', $this->getActionConfig($action))) {
if (\array_key_exists('role', $this->getActionConfig($action))) {
return $this->getActionConfig($action)['role'];
}
@@ -727,11 +696,11 @@ class CRUDController extends AbstractController
* and view.
*
* @param string $action
* @param mixed $entity the entity for the current request, or an array of entities
*
* @throws LogicException if no template are available
* @param mixed $entity the entity for the current request, or an array of entities
*
* @return string the path to the template
*
* @throws \LogicException if no template are available
*/
protected function getTemplateFor($action, mixed $entity, Request $request)
{
@@ -745,9 +714,7 @@ class CRUDController extends AbstractController
'index' => '@ChillMain/CRUD/index.html.twig',
'view' => '@ChillMain/CRUD/view.html.twig',
'delete' => '@ChillMain/CRUD/delete.html.twig',
default => throw new LogicException("the view for action {$action} is not "
. 'defined. You should override ' . __METHOD__ . ' to add this '
. 'action'),
default => throw new \LogicException("the view for action {$action} is not ".'defined. You should override '.__METHOD__.' to add this action'),
};
}
@@ -756,10 +723,6 @@ class CRUDController extends AbstractController
return $this->container->get('translator');
}
/**
* @param $action
* @param $entity
*/
protected function hasCustomTemplate($action, $entity, Request $request): bool
{
return !empty($this->getActionConfig($action)['template']);
@@ -869,9 +832,9 @@ class CRUDController extends AbstractController
$next = $request->request->get('submit', 'save-and-close');
return match ($next) {
'save-and-close' => $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_index'),
'save-and-new' => $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_new', $request->query->all()),
default => $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_view', [
'save-and-close' => $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_index'),
'save-and-new' => $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_new', $request->query->all()),
default => $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_view', [
'id' => $entity->getId(),
]),
};
@@ -879,27 +842,16 @@ class CRUDController extends AbstractController
protected function onFormValid(string $action, object $entity, FormInterface $form, Request $request) {}
/**
* @param $action
* @param $entity
*/
protected function onPostCheckACL($action, Request $request, $entity): ?Response
{
return null;
}
/**
* @param $action
* @param $entity
*/
protected function onPostFetchEntity($action, Request $request, $entity): ?Response
{
return null;
}
/**
* @param $entity
*/
protected function onPostFlush(string $action, $entity, FormInterface $form, Request $request) {}
/**
@@ -912,21 +864,12 @@ class CRUDController extends AbstractController
*/
protected function onPostIndexFetchQuery(string $action, Request $request, int $totalItems, PaginatorInterface $paginator, mixed $entities) {}
/**
* @param $entity
*/
protected function onPostPersist(string $action, $entity, FormInterface $form, Request $request) {}
/**
* @param $entity
*/
protected function onPostRemove(string $action, $entity, FormInterface $form, Request $request) {}
protected function onPreDelete(string $action, Request $request) {}
/**
* @param $entity
*/
protected function onPreFlush(string $action, $entity, FormInterface $form, Request $request) {}
protected function onPreIndex(string $action, Request $request) {}
@@ -936,14 +879,8 @@ class CRUDController extends AbstractController
*/
protected function onPreIndexBuildQuery(string $action, Request $request, int $totalItems, PaginatorInterface $paginator) {}
/**
* @param $entity
*/
protected function onPrePersist(string $action, $entity, FormInterface $form, Request $request) {}
/**
* @param $entity
*/
protected function onPreRemove(string $action, $entity, FormInterface $form, Request $request) {}
/**
@@ -969,7 +906,7 @@ class CRUDController extends AbstractController
*
* @return type
*/
protected function queryEntities(string $action, Request $request, PaginatorInterface $paginator, ?FilterOrderHelper $filterOrder = null)
protected function queryEntities(string $action, Request $request, PaginatorInterface $paginator, FilterOrderHelper $filterOrder = null)
{
$query = $this->buildQueryEntities($action, $request)
->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber())
@@ -979,9 +916,6 @@ class CRUDController extends AbstractController
return $this->orderQuery($action, $query, $request, $paginator);
}
/**
* @param $entity
*/
protected function removeEntity(string $action, $entity, FormInterface $form, Request $request)
{
$this->getDoctrine()
@@ -1021,13 +955,7 @@ class CRUDController extends AbstractController
}
if (null === $entity) {
throw $this->createNotFoundException(
sprintf(
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
throw $this->createNotFoundException(sprintf('The %s with id %s is not found', $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $entity);

View File

@@ -12,10 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\CRUD\Resolver;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use function array_key_exists;
use function strtoupper;
/**
* Class Resolver.
@@ -65,28 +61,22 @@ class Resolver
}
/**
* @param $crudName
* @param $action
*
* @return string
*/
public function buildDefaultRole($crudName, $action)
{
if (empty($this->crudConfig[$crudName]['base_role'])) {
throw new LogicException(sprintf('the base role is not defined. You must define '
. 'on or override %s or %s methods', __METHOD__, 'getRoleFor'));
throw new \LogicException(sprintf('the base role is not defined. You must define on or override %s or %s methods', __METHOD__, 'getRoleFor'));
}
return strtoupper(
$this->crudConfig[$crudName]['base_role'] .
'_' .
return \strtoupper(
$this->crudConfig[$crudName]['base_role'].
'_'.
$action
);
}
/**
* @param $key
* @param $crudName
* @param null $action
*
* @return string
@@ -102,14 +92,11 @@ class Resolver
}
/**
* @param $crudName
* @param $action
*
* @return bool
*/
public function hasAction($crudName, $action)
{
return array_key_exists(
return \array_key_exists(
$action,
$this->crudConfig[$crudName]['actions']
);

View File

@@ -11,20 +11,11 @@ declare(strict_types=1);
namespace Chill\MainBundle\CRUD\Routing;
use RuntimeException;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use function array_filter;
use function array_keys;
use function array_search;
use function count;
use function in_array;
use const ARRAY_FILTER_USE_BOTH;
class CRUDRoutesLoader extends Loader
{
private const ALL_INDEX_METHODS = [Request::METHOD_GET, Request::METHOD_HEAD];
@@ -46,13 +37,12 @@ class CRUDRoutesLoader extends Loader
/**
* Load routes for CRUD and CRUD Api.
*
* @param mixed $resource
* @param mixed|null $type
*/
public function load($resource, $type = null): RouteCollection
{
if (true === $this->isLoaded) {
throw new RuntimeException('Do not add the "CRUD" loader twice');
throw new \RuntimeException('Do not add the "CRUD" loader twice');
}
$collection = new RouteCollection();
@@ -69,7 +59,6 @@ class CRUDRoutesLoader extends Loader
}
/**
* @param mixed $resource
* @param null $type
*
* @return bool
@@ -81,13 +70,11 @@ class CRUDRoutesLoader extends Loader
/**
* Load routes for api single.
*
* @param $crudConfig
*/
protected function loadApi(array $crudConfig): RouteCollection
{
$collection = new RouteCollection();
$controller = 'csapi_' . $crudConfig['name'] . '_controller';
$controller = 'csapi_'.$crudConfig['name'].'_controller';
foreach ($crudConfig['actions'] as $name => $action) {
// filter only on single actions
@@ -100,40 +87,38 @@ class CRUDRoutesLoader extends Loader
$controllerAction = match ($name) {
'_entity' => 'entityApi',
'_index' => 'indexApi',
default => $name . 'Api',
default => $name.'Api',
};
$defaults = [
'_controller' => $controller . ':' . ($action['controller_action'] ?? $controllerAction),
'_controller' => $controller.':'.($action['controller_action'] ?? $controllerAction),
];
// path are rewritten
// if name === 'default', we rewrite it to nothing :-)
$localName = in_array($name, ['_entity', '_index'], true) ? '' : '/' . $name;
$localName = \in_array($name, ['_entity', '_index'], true) ? '' : '/'.$name;
if ('collection' === $action['single_collection'] || '_index' === $name) {
$localPath = $action['path'] ?? $localName . '.{_format}';
$localPath = $action['path'] ?? $localName.'.{_format}';
} else {
$localPath = $action['path'] ?? '/{id}' . $localName . '.{_format}';
$localPath = $action['path'] ?? '/{id}'.$localName.'.{_format}';
}
$path = $crudConfig['base_path'] . $localPath;
$path = $crudConfig['base_path'].$localPath;
$requirements = $action['requirements'] ?? ['{id}' => '\d+'];
$methods = array_keys(array_filter(
$methods = \array_keys(\array_filter(
$action['methods'],
static fn ($value, $key) => $value,
ARRAY_FILTER_USE_BOTH
\ARRAY_FILTER_USE_BOTH
));
if (count($methods) === 0) {
throw new RuntimeException("The api configuration named \"{$crudConfig['name']}\", action \"{$name}\", " .
'does not have any allowed methods. You should remove this action from the config ' .
'or allow, at least, one method');
if (0 === \count($methods)) {
throw new \RuntimeException("The api configuration named \"{$crudConfig['name']}\", action \"{$name}\", ".'does not have any allowed methods. You should remove this action from the config or allow, at least, one method');
}
if ('_entity' === $name && in_array(Request::METHOD_POST, $methods, true)) {
unset($methods[array_search(Request::METHOD_POST, $methods, true)]);
if ('_entity' === $name && \in_array(Request::METHOD_POST, $methods, true)) {
unset($methods[\array_search(Request::METHOD_POST, $methods, true)]);
$entityPostRoute = $this->createEntityPostRoute(
$name,
$crudConfig,
@@ -146,7 +131,7 @@ class CRUDRoutesLoader extends Loader
);
}
if (count($methods) === 0) {
if (0 === \count($methods)) {
// the only method was POST,
// continue to next
continue;
@@ -155,7 +140,7 @@ class CRUDRoutesLoader extends Loader
$route = new Route($path, $defaults, $requirements);
$route->setMethods($methods);
$collection->add('chill_api_single_' . $crudConfig['name'] . '_' . $name, $route);
$collection->add('chill_api_single_'.$crudConfig['name'].'_'.$name, $route);
}
return $collection;
@@ -163,35 +148,33 @@ class CRUDRoutesLoader extends Loader
/**
* Load routes for CRUD (without api).
*
* @param $crudConfig
*/
protected function loadCrudConfig($crudConfig): RouteCollection
{
$collection = new RouteCollection();
$controller = 'cscrud_' . $crudConfig['name'] . '_controller';
$controller = 'cscrud_'.$crudConfig['name'].'_controller';
foreach ($crudConfig['actions'] as $name => $action) {
// defaults (controller name)
$defaults = [
'_controller' => $controller . ':' . ($action['controller_action'] ?? $name),
'_controller' => $controller.':'.($action['controller_action'] ?? $name),
];
if ('index' === $name) {
$path = '{_locale}' . $crudConfig['base_path'];
$path = '{_locale}'.$crudConfig['base_path'];
$route = new Route($path, $defaults);
} elseif ('new' === $name) {
$path = '{_locale}' . $crudConfig['base_path'] . '/' . $name;
$path = '{_locale}'.$crudConfig['base_path'].'/'.$name;
$route = new Route($path, $defaults);
} else {
$path = '{_locale}' . $crudConfig['base_path'] . ($action['path'] ?? '/{id}/' . $name);
$path = '{_locale}'.$crudConfig['base_path'].($action['path'] ?? '/{id}/'.$name);
$requirements = $action['requirements'] ?? [
'{id}' => '\d+',
];
$route = new Route($path, $defaults, $requirements);
}
$collection->add('chill_crud_' . $crudConfig['name'] . '_' . $name, $route);
$collection->add('chill_crud_'.$crudConfig['name'].'_'.$name, $route);
}
return $collection;
@@ -199,11 +182,11 @@ class CRUDRoutesLoader extends Loader
private function createEntityPostRoute(string $name, $crudConfig, array $action, $controller): Route
{
$localPath = $action['path'] . '.{_format}';
$localPath = $action['path'].'.{_format}';
$defaults = [
'_controller' => $controller . ':' . ($action['controller_action'] ?? 'entityPost'),
'_controller' => $controller.':'.($action['controller_action'] ?? 'entityPost'),
];
$path = $crudConfig['base_path'] . $localPath;
$path = $crudConfig['base_path'].$localPath;
$requirements = $action['requirements'] ?? [];
$route = new Route($path, $defaults, $requirements);
$route->setMethods([Request::METHOD_POST]);

View File

@@ -35,8 +35,6 @@ class TwigCRUDResolver extends AbstractExtension
}
/**
* @param $configKey
* @param $crudName
* @param null $action
*
* @return string
@@ -66,9 +64,6 @@ class TwigCRUDResolver extends AbstractExtension
}
/**
* @param $crudName
* @param $action
*
* @return bool
*/
public function hasAction($crudName, $action)

View File

@@ -15,7 +15,6 @@ use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\CRUD\CompilerPass\CRUDControllerCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\ACLFlagsCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\ExportsCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\GroupingCenterCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\MenuCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\NotificationCounterCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\SearchableServicesCompilerPass;

View File

@@ -17,11 +17,9 @@ use Chill\MainBundle\Entity\PermissionsGroup;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use League\Csv\Reader;
use League\Csv\Writer;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
@@ -33,15 +31,6 @@ use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use function array_key_exists;
use function array_keys;
use function array_merge;
use function bin2hex;
use function count;
use function implode;
use function random_bytes;
use function trim;
class ChillImportUsersCommand extends Command
{
/**
@@ -91,7 +80,7 @@ class ChillImportUsersCommand extends Command
$str[] = $e->getMessage();
}
return implode(';', $str);
return \implode(';', $str);
}
protected function configure()
@@ -107,8 +96,8 @@ class ChillImportUsersCommand extends Command
protected function createOrGetGroupCenter(Center $center, PermissionsGroup $pg): GroupCenter
{
if (array_key_exists($center->getId(), $this->groupCenters)) {
if (array_key_exists($pg->getId(), $this->groupCenters[$center->getId()])) {
if (\array_key_exists($center->getId(), $this->groupCenters)) {
if (\array_key_exists($pg->getId(), $this->groupCenters[$center->getId()])) {
return $this->groupCenters[$center->getId()][$pg->getId()];
}
}
@@ -138,12 +127,12 @@ class ChillImportUsersCommand extends Command
{
$user = new User();
$user
->setEmail(trim((string) $data['email']))
->setUsername(trim((string) $data['username']))
->setEmail(\trim((string) $data['email']))
->setUsername(\trim((string) $data['username']))
->setEnabled(true)
->setPassword($this->passwordEncoder->encodePassword(
$user,
bin2hex(random_bytes(32))
\bin2hex(\random_bytes(32))
));
$errors = $this->validator->validate($user);
@@ -154,8 +143,7 @@ class ChillImportUsersCommand extends Command
$this->tempOutput->writeln(sprintf('%d errors found with user with username "%s" at line %d', $errors->count(), $data['username'], $offset));
$this->tempOutput->writeln($errorMessages);
throw new RuntimeException('Found errors while creating an user. '
. 'Watch messages in command output');
throw new \RuntimeException('Found errors while creating an user. Watch messages in command output');
}
$pgs = $this->getPermissionGroup($data['permission group']);
@@ -215,9 +203,10 @@ class ChillImportUsersCommand extends Command
try {
$this->loadUsers();
} catch (Exception $e) {
} catch (\Exception $e) {
throw $e;
}
return 0;
}
@@ -239,9 +228,9 @@ class ChillImportUsersCommand extends Command
protected function getCenters($name)
{
// sanitize
$name = trim($name);
$name = \trim($name);
if (array_key_exists($name, $this->centers)) {
if (\array_key_exists($name, $this->centers)) {
return $this->centers[$name];
}
@@ -274,8 +263,7 @@ class ChillImportUsersCommand extends Command
$this->tempOutput->writeln(sprintf('%d errors found with center with name "%s"', $errors->count(), $name));
$this->tempOutput->writeln($errorMessages);
throw new RuntimeException('Found errors while creating one center. '
. 'Watch messages in command output');
throw new \RuntimeException('Found errors while creating one center. Watch messages in command output');
}
$this->em->persist($center);
@@ -288,7 +276,7 @@ class ChillImportUsersCommand extends Command
protected function getPermissionGroup($alias)
{
if (array_key_exists($alias, $this->permissionGroups)) {
if (\array_key_exists($alias, $this->permissionGroups)) {
return $this->permissionGroups[$alias];
}
@@ -301,30 +289,29 @@ class ChillImportUsersCommand extends Command
$permissionGroupsByName[$permissionGroup->getName()] = $permissionGroup;
}
if (count($permissionGroupsByName) === 0) {
throw new RuntimeException('no permission groups found. Create them '
. 'before importing users');
if (0 === \count($permissionGroupsByName)) {
throw new \RuntimeException('no permission groups found. Create them before importing users');
}
$question = new ChoiceQuestion(
"To which permission groups associate with \"{$alias}\" ?",
array_keys($permissionGroupsByName)
\array_keys($permissionGroupsByName)
);
$question
->setMultiselect(true)
->setAutocompleterValues(array_keys($permissionGroupsByName))
->setAutocompleterValues(\array_keys($permissionGroupsByName))
->setNormalizer(static function ($value) {
if (null === $value) {
return '';
}
return trim((string) $value);
return \trim((string) $value);
});
$helper = $this->getHelper('question');
$keys = $helper->ask($this->tempInput, $this->tempOutput, $question);
$this->tempOutput->writeln('You have chosen ' . implode(', ', $keys));
$this->tempOutput->writeln('You have chosen '.\implode(', ', $keys));
if (
$helper->ask(
@@ -343,7 +330,7 @@ class ChillImportUsersCommand extends Command
$this->logger->error('Error while responding to a a question');
$this->tempOutput->writeln('Ok, I accept, but I do not know what to do. Please try again.');
throw new RuntimeException('Error while responding to a question');
throw new \RuntimeException('Error while responding to a question');
}
protected function loadUsers()
@@ -358,7 +345,7 @@ class ChillImportUsersCommand extends Command
if ($this->doesUserExists($r)) {
$this->tempOutput->writeln(sprintf("User with username '%s' already "
. 'exists, skipping', $r['username']));
.'exists, skipping', $r['username']));
$this->logger->info('One user already exists, skipping creation', [
'username_in_file' => $r['username'],
@@ -381,7 +368,7 @@ class ChillImportUsersCommand extends Command
foreach ($reader->getRecords() as $r) {
$this->centers[$r['alias']] =
array_merge(
\array_merge(
$this->centers[$r['alias']] ?? [],
$this->getCenters(
$r['center']

View File

@@ -14,10 +14,7 @@ namespace Chill\MainBundle\Command;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Notification\Mailer;
use Chill\MainBundle\Security\PasswordRecover\RecoverPasswordHelper;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use InvalidArgumentException;
use League\Csv\Reader;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
@@ -27,11 +24,6 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use function array_key_exists;
use function array_merge;
use function in_array;
use function trim;
/**
* Class ChillUserSendRenewPasswordCodeCommand.
*/
@@ -115,19 +107,20 @@ class ChillUserSendRenewPasswordCodeCommand extends Command
$this->sendRecoverCode($user);
}
return 0;
}
/**
* @throws Exception
*
* @return Reader
*
* @throws \Exception
*/
protected function getReader()
{
try {
$reader = Reader::createFromPath($this->input->getArgument('csvfile'));
} catch (Exception $e) {
} catch (\Exception $e) {
$this->logger->error('The csv file could not be read', [
'path' => $this->input->getArgument('csvfile'),
]);
@@ -140,11 +133,10 @@ class ChillUserSendRenewPasswordCodeCommand extends Command
$headers = $reader->getHeader();
if (
false === in_array('username', $headers, true)
&& false === in_array('email', $headers, true)
false === \in_array('username', $headers, true)
&& false === \in_array('email', $headers, true)
) {
throw new InvalidArgumentException('The csv file does not have an '
. 'username or email header');
throw new \InvalidArgumentException('The csv file does not have an username or email header');
}
return $reader;
@@ -156,16 +148,16 @@ class ChillUserSendRenewPasswordCodeCommand extends Command
$userRepository = $this->em->getRepository(User::class);
try {
if (array_key_exists('email', $row)) {
return $userRepository->findOneByUsernameOrEmail(trim((string) $row['email']));
if (\array_key_exists('email', $row)) {
return $userRepository->findOneByUsernameOrEmail(\trim((string) $row['email']));
}
} catch (\Doctrine\ORM\NoResultException) {
// continue, we will try username
}
try {
if (array_key_exists('username', $row)) {
return $userRepository->findOneByUsernameOrEmail(trim((string) $row['username']));
if (\array_key_exists('username', $row)) {
return $userRepository->findOneByUsernameOrEmail(\trim((string) $row['username']));
}
} catch (\Doctrine\ORM\NoResultException) {
return null;
@@ -174,7 +166,7 @@ class ChillUserSendRenewPasswordCodeCommand extends Command
protected function onUserNotFound($row, $offset)
{
$this->logger->alert('User not found', array_merge([
$this->logger->alert('User not found', \array_merge([
'offset' => $offset,
], $row));
}
@@ -191,7 +183,7 @@ class ChillUserSendRenewPasswordCodeCommand extends Command
}
$template = $this->input->getOption('template');
$expiration = DateTime::createFromFormat(
$expiration = \DateTime::createFromFormat(
'U',
$this->input->getOption('expiration')
);

View File

@@ -34,7 +34,7 @@ class LoadAddressesFRFromBANOCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): int
{
foreach ($input->getArgument('departementNo') as $departementNo) {
$output->writeln('Import addresses for ' . $departementNo);
$output->writeln('Import addresses for '.$departementNo);
$this->addressReferenceFromBano->import($departementNo);
}

View File

@@ -17,10 +17,7 @@ use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Intl\Intl;
use Symfony\Component\Intl\Languages;
use function in_array;
/*
* Load or update the languages entities command
@@ -41,8 +38,6 @@ class LoadAndUpdateLanguagesCommand extends Command
/**
* LoadCountriesCommand constructor.
*
* @param $availableLanguages
*/
public function __construct(private readonly EntityManager $entityManager, private $availableLanguages)
{
@@ -58,21 +53,21 @@ class LoadAndUpdateLanguagesCommand extends Command
{
$this
->setName('chill:main:languages:populate')
->setDescription('Load or update languages in db. This command does not delete existing ' .
->setDescription('Load or update languages in db. This command does not delete existing '.
'languages, but will update names according to available languages')
->addOption(
self::INCLUDE_REGIONAL_VERSION,
null,
InputOption::VALUE_NONE,
'Include the regional languages. The regional languages are languages with code containing _ excepted '
. implode(',', $this->regionalVersionToInclude) . '.'
.implode(',', $this->regionalVersionToInclude).'.'
)
->addOption(
self::INCLUDE_ANCIENT,
null,
InputOption::VALUE_NONE,
'Include the ancient languages that are languages with code '
. implode(', ', $this->ancientToExclude) . '.'
.implode(', ', $this->ancientToExclude).'.'
);
}
@@ -96,10 +91,10 @@ class LoadAndUpdateLanguagesCommand extends Command
(
!$input->getOption(self::INCLUDE_REGIONAL_VERSION)
&& strpos($code, '_')
&& !in_array($code, $this->regionalVersionToInclude, true)
&& !\in_array($code, $this->regionalVersionToInclude, true)
) || (
!$input->getOption(self::INCLUDE_ANCIENT)
&& in_array($code, $this->ancientToExclude, true)
&& \in_array($code, $this->ancientToExclude, true)
)
);
@@ -125,6 +120,7 @@ class LoadAndUpdateLanguagesCommand extends Command
}
$em->flush();
return 0;
}
}

View File

@@ -17,14 +17,11 @@ use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Intl\Intl;
class LoadCountriesCommand extends Command
{
/**
* LoadCountriesCommand constructor.
*
* @param $availableLanguages
*/
public function __construct(private readonly EntityManager $entityManager, private $availableLanguages)
{
@@ -59,7 +56,7 @@ class LoadCountriesCommand extends Command
protected function configure()
{
$this->setName('chill:main:countries:populate')
->setDescription('Load or update countries in db. This command does not delete existing countries, ' .
->setDescription('Load or update countries in db. This command does not delete existing countries, '.
'but will update names according to available languages');
}
@@ -85,6 +82,7 @@ class LoadCountriesCommand extends Command
}
$em->flush();
return 0;
}
}

View File

@@ -15,8 +15,6 @@ use Chill\MainBundle\Doctrine\Model\Point;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Entity\PostalCode;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use RuntimeException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
@@ -25,9 +23,6 @@ use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use function count;
use function strlen;
class LoadPostalCodesCommand extends Command
{
public function __construct(private readonly EntityManagerInterface $entityManager, private readonly ValidatorInterface $validator)
@@ -40,15 +35,15 @@ class LoadPostalCodesCommand extends Command
$this->setName('chill:main:postal-code:populate')
->setDescription('Add the postal code from a csv file.')
->setHelp('This script will try to avoid existing postal code '
. "using the postal code and name. \n"
. 'The CSV file must have the following columns: '
. 'postal code, label, country code.'
. 'Optionally, the csv file can have the following '
. 'columns after the country code: reference code, latitude, longitude, source. '
. 'The latitude and longitude columns are supposed to be in WGS84 and expressed in decimal degrees. '
. 'The CSV file should not have any header row.')
."using the postal code and name. \n"
.'The CSV file must have the following columns: '
.'postal code, label, country code.'
.'Optionally, the csv file can have the following '
.'columns after the country code: reference code, latitude, longitude, source. '
.'The latitude and longitude columns are supposed to be in WGS84 and expressed in decimal degrees. '
.'The CSV file should not have any header row.')
->addArgument('csv_file', InputArgument::REQUIRED, 'the path to '
. 'the csv file. See the help for specifications.')
.'the csv file. See the help for specifications.')
->addOption(
'delimiter',
'd',
@@ -76,7 +71,7 @@ class LoadPostalCodesCommand extends Command
{
$csv = $this->getCSVResource($input);
if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) {
if (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
$output->writeln('The content of the file is ...');
$output->write(file_get_contents($input->getArgument('csv_file')));
}
@@ -97,28 +92,29 @@ class LoadPostalCodesCommand extends Command
$this->addPostalCode($row, $output);
++$num;
} catch (CountryCodeNotFoundException|ExistingPostalCodeException|PostalCodeNotValidException $ex) {
$output->writeln('<warning> on line ' . $line . ' : ' . $ex->getMessage() . '</warning>');
$output->writeln('<warning> on line '.$line.' : '.$ex->getMessage().'</warning>');
}
++$line;
}
$this->entityManager->flush();
$output->writeln('<info>' . $num . ' were added !</info>');
$output->writeln('<info>'.$num.' were added !</info>');
return 0;
}
private function addPostalCode($row, OutputInterface $output)
{
if ('FR' === $row[2] && strlen((string) $row[0]) === 4) {
if ('FR' === $row[2] && 4 === \strlen((string) $row[0])) {
// CP in FRANCE are on 5 digit
// For CP starting with a zero, the starting zero can be remove if stored as number in a csv
// add a zero if CP from FR and on 4 digit
$row[0] = '0' . $row[0];
$row[0] = '0'.$row[0];
}
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$output->writeln('handling row: ' . $row[0] . ' | ' . $row[1] . ' | ' . $row[2]);
$output->writeln('handling row: '.$row[0].' | '.$row[1].' | '.$row[2]);
}
$em = $this->entityManager;
$country = $em
@@ -126,12 +122,7 @@ class LoadPostalCodesCommand extends Command
->findOneBy(['countryCode' => $row[2]]);
if (null === $country) {
throw new CountryCodeNotFoundException(sprintf(
'The country with code %s is not found. Aborting to insert postal code with %s - %s',
$row[2],
$row[0],
$row[1]
));
throw new CountryCodeNotFoundException(sprintf('The country with code %s is not found. Aborting to insert postal code with %s - %s', $row[2], $row[0], $row[1]));
}
// try to find an existing postal code
@@ -139,12 +130,8 @@ class LoadPostalCodesCommand extends Command
->getRepository(PostalCode::class)
->findBy(['code' => $row[0], 'name' => $row[1]]);
if (count($existingPC) > 0) {
throw new ExistingPostalCodeException(sprintf(
'A postal code with code : %s and name : %s already exists, skipping',
$row[0],
$row[1]
));
if (\count($existingPC) > 0) {
throw new ExistingPostalCodeException(sprintf('A postal code with code : %s and name : %s already exists, skipping', $row[0], $row[1]));
}
$postalCode = (new PostalCode())
@@ -166,13 +153,13 @@ class LoadPostalCodesCommand extends Command
$errors = $this->validator->validate($postalCode);
if ($errors->count() === 0) {
if (0 === $errors->count()) {
$em->persist($postalCode);
} else {
$msg = '';
foreach ($errors as $error) {
$msg .= ' ' . $error->getMessage();
$msg .= ' '.$error->getMessage();
}
throw new PostalCodeNotValidException($msg);
@@ -194,22 +181,21 @@ class LoadPostalCodesCommand extends Command
$filename = $input->getArgument('csv_file');
if (!$fs->exists($filename)) {
throw new RuntimeException('The file does not exists or you do not '
. 'have the right to read it.');
throw new \RuntimeException('The file does not exists or you do not have the right to read it.');
}
$resource = fopen($filename, 'rb');
if (false === $resource) {
throw new RuntimeException("The file '{$filename}' could not be opened.");
throw new \RuntimeException("The file '{$filename}' could not be opened.");
}
return $resource;
}
}
class ExistingPostalCodeException extends Exception {}
class ExistingPostalCodeException extends \Exception {}
class CountryCodeNotFoundException extends Exception {}
class CountryCodeNotFoundException extends \Exception {}
class PostalCodeNotValidException extends Exception {}
class PostalCodeNotValidException extends \Exception {}

View File

@@ -13,7 +13,6 @@ namespace Chill\MainBundle\Command;
use Chill\MainBundle\Entity\User;
use Doctrine\ORM\EntityManager;
use LogicException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
@@ -59,7 +58,7 @@ class SetPasswordCommand extends Command
$this->setName('chill:user:set_password')
->setDescription('set a password to user')
->addArgument('username', InputArgument::REQUIRED, 'the user\'s '
. 'username you want to change password')
.'username you want to change password')
->addArgument('password', InputArgument::OPTIONAL, 'the new password');
}
@@ -68,8 +67,7 @@ class SetPasswordCommand extends Command
$user = $this->_getUser($input->getArgument('username'));
if (null === $user) {
throw new LogicException("The user with username '" .
$input->getArgument('username') . "' is not found");
throw new \LogicException("The user with username '".$input->getArgument('username')."' is not found");
}
$password = $input->getArgument('password');
@@ -77,10 +75,11 @@ class SetPasswordCommand extends Command
if (null === $password) {
$dialog = $this->getHelperSet()->get('dialog');
$password = $dialog->askHiddenResponse($output, '<question>the new password :'
. '</question>');
.'</question>');
}
$this->_setPassword($user, $password);
return 0;
}
}

View File

@@ -24,8 +24,6 @@ use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use function trim;
final class AddressReferenceAPIController extends ApiController
{
public function __construct(private readonly AddressReferenceRepository $addressReferenceRepository, private readonly PaginatorFactory $paginatorFactory) {}
@@ -43,7 +41,7 @@ final class AddressReferenceAPIController extends ApiController
$pattern = $request->query->get('q');
if ('' === trim((string) $pattern)) {
if ('' === \trim((string) $pattern)) {
throw new BadRequestHttpException('the search pattern is empty');
}

View File

@@ -72,22 +72,22 @@ class DefaultController extends AbstractController
],
[
'name' => 'Link 2',
//'link' => "http://localhost",
// 'link' => "http://localhost",
'content' => 'Dui sapien eget mi proin sed libero. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Turpis nunc eget lorem dolor. Phasellus egestas tellus rutrum tellus. Diam sit amet nisl suscipit adipiscing bibendum est ultricies integer. Duis ultricies lacus sed turpis tincidunt id. Nisl suscipit adipiscing bibendum est ultricies integer. Elementum nibh tellus molestie nunc non blandit massa enim. Faucibus in ornare quam viverra orci sagittis eu. Neque volutpat ac tincidunt vitae semper quis lectus nulla. Accumsan sit amet nulla facilisi morbi. Leo vel fringilla est ullamcorper eget nulla facilisi etiam dignissim. Amet est placerat in egestas erat imperdiet sed euismod. Quis auctor elit sed vulputate mi. Mauris nunc congue nisi vitae suscipit tellus mauris a diam. At volutpat diam ut venenatis. Facilisis gravida neque convallis a cras semper.',
],
[
'name' => 'Link 3',
//'link' => "http://localhost",
// 'link' => "http://localhost",
'content' => 'In ornare quam viverra orci sagittis eu volutpat. Ac tincidunt vitae semper quis lectus nulla at volutpat. Placerat duis ultricies lacus sed turpis tincidunt. Augue interdum velit euismod in pellentesque. Felis eget nunc lobortis mattis aliquam. Volutpat lacus laoreet non curabitur gravida arcu. Gravida cum sociis natoque penatibus et magnis dis parturient montes. Nisl pretium fusce id velit ut tortor. Nunc scelerisque viverra mauris in aliquam sem fringilla ut. Magna eget est lorem ipsum dolor sit. Non consectetur a erat nam at lectus urna. Eget est lorem ipsum dolor sit amet consectetur adipiscing elit. Sed velit dignissim sodales ut.',
],
[
'name' => 'Link 4',
'link' => 'http://localhost',
//'content' => "Ut tellus elementum sagittis vitae et. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra. Hendrerit gravida rutrum quisque non tellus orci ac auctor augue. Eleifend quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Dictumst quisque sagittis purus sit. Suspendisse sed nisi lacus sed viverra. Pretium quam vulputate dignissim suspendisse in est ante. Id eu nisl nunc mi ipsum. Ut venenatis tellus in metus vulputate. Ut morbi tincidunt augue interdum velit euismod.",
// 'content' => "Ut tellus elementum sagittis vitae et. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra. Hendrerit gravida rutrum quisque non tellus orci ac auctor augue. Eleifend quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Dictumst quisque sagittis purus sit. Suspendisse sed nisi lacus sed viverra. Pretium quam vulputate dignissim suspendisse in est ante. Id eu nisl nunc mi ipsum. Ut venenatis tellus in metus vulputate. Ut morbi tincidunt augue interdum velit euismod.",
],
[
'name' => 'Link 5',
//'link' => "http://localhost",
// 'link' => "http://localhost",
'content' => 'Vel elit scelerisque mauris pellentesque pulvinar. Ornare suspendisse sed nisi lacus sed viverra tellus. Massa tincidunt dui ut ornare lectus sit. Congue nisi vitae suscipit tellus mauris a diam. At auctor urna nunc id cursus metus aliquam. Viverra accumsan in nisl nisi scelerisque eu ultrices vitae. Mattis aliquam faucibus purus in massa tempor nec feugiat. Et leo duis ut diam quam. Auctor augue mauris augue neque. Purus ut faucibus pulvinar elementum integer enim neque volutpat. Scelerisque felis imperdiet proin fermentum leo. Diam sit amet nisl suscipit adipiscing bibendum est ultricies. Consectetur libero id faucibus nisl tincidunt. Vel fringilla est ullamcorper eget nulla facilisi. Pharetra diam sit amet nisl suscipit adipiscing. Dignissim diam quis enim lobortis. Auctor eu augue ut lectus arcu bibendum at varius.',
],
],

View File

@@ -25,9 +25,7 @@ use Chill\MainBundle\Redis\ChillRedis;
use Chill\MainBundle\Repository\SavedExportRepositoryInterface;
use Chill\MainBundle\Security\Authorization\SavedExportVoter;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Psr\Log\LoggerInterface;
use RedisException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@@ -39,12 +37,8 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
use function serialize;
use function unserialize;
/**
* Class ExportController
@@ -109,6 +103,7 @@ class ExportController extends AbstractController
* @param string $alias
*
* @return \Symfony\Component\HttpFoundation\Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/exports/generate/{alias}", name="chill_main_export_generate", methods={"GET"})
*/
public function generateAction(Request $request, $alias)
@@ -131,7 +126,7 @@ class ExportController extends AbstractController
/**
* @Route("/{_locale}/exports/generate-from-saved/{id}", name="chill_main_export_generate_from_saved")
*
* @throws RedisException
* @throws \RedisException
*/
public function generateFromSavedExport(SavedExport $savedExport): RedirectResponse
{
@@ -139,7 +134,7 @@ class ExportController extends AbstractController
$key = md5(uniqid((string) random_int(0, mt_getrandmax()), false));
$this->redis->setEx($key, 3600, serialize($savedExport->getOptions()));
$this->redis->setEx($key, 3600, \serialize($savedExport->getOptions()));
return $this->redirectToRoute(
'chill_main_export_download',
@@ -153,6 +148,7 @@ class ExportController extends AbstractController
/**
* Render the list of available exports.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/exports/", name="chill_main_export_index")
*/
public function indexAction(): Response
@@ -186,7 +182,7 @@ class ExportController extends AbstractController
$exportManager = $this->exportManager;
$export = $exportManager->getExport($alias);
if ($exportManager->isGrantedForElement($export) === false) {
if (false === $exportManager->isGrantedForElement($export)) {
throw $this->createAccessDeniedException('The user does not have access to this export');
}
@@ -279,7 +275,7 @@ class ExportController extends AbstractController
$options = match ($step) {
'export', 'generate_export' => [
'export_alias' => $alias,
'picked_centers' => $exportManager->getPickedCenters($data['centers'])
'picked_centers' => $exportManager->getPickedCenters($data['centers']),
],
'formatter', 'generate_formatter' => [
'export_alias' => $alias,
@@ -332,7 +328,7 @@ class ExportController extends AbstractController
* When the method is POST, the form is stored if valid, and a redirection
* is done to next step.
*/
private function exportFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, ?SavedExport $savedExport = null): Response
private function exportFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, SavedExport $savedExport = null): Response
{
$exportManager = $this->exportManager;
@@ -350,7 +346,7 @@ class ExportController extends AbstractController
$form = $this->createCreateFormExport($alias, 'export', $data, $savedExport);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -365,11 +361,11 @@ class ExportController extends AbstractController
);
$this->session->set('export_step', $data);
//redirect to next step
// redirect to next step
return $this->redirectToRoute('chill_main_export_new', [
'step' => $this->getNextStep('export', $export),
'alias' => $alias,
'from_saved' => $request->get('from_saved', '')
'from_saved' => $request->get('from_saved', ''),
]);
}
$this->logger->debug('form export is invalid', [
@@ -390,7 +386,7 @@ class ExportController extends AbstractController
* If the form is posted and valid, store the data in session and
* redirect to the next step.
*/
private function formatterFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, ?SavedExport $savedExport = null): Response
private function formatterFormStep(Request $request, DirectExportInterface|ExportInterface $export, string $alias, SavedExport $savedExport = null): Response
{
// check we have data from the previous step (export step)
$data = $this->session->get('export_step', null);
@@ -404,7 +400,7 @@ class ExportController extends AbstractController
$form = $this->createCreateFormExport($alias, 'formatter', $data, $savedExport);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -415,7 +411,7 @@ class ExportController extends AbstractController
$request->request->all()
);
//redirect to next step
// redirect to next step
return $this->redirectToRoute('chill_main_export_new', [
'alias' => $alias,
'step' => $this->getNextStep('formatter', $export),
@@ -440,12 +436,11 @@ class ExportController extends AbstractController
*
* The data from previous steps is removed from session.
*
* @param \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export
* @param string $alias
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
private function forwardToGenerate(Request $request, \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export, $alias, ?SavedExport $savedExport)
private function forwardToGenerate(Request $request, DirectExportInterface|ExportInterface $export, $alias, ?SavedExport $savedExport)
{
$dataCenters = $this->session->get('centers_step_raw', null);
$dataFormatter = $this->session->get('formatter_step_raw', null);
@@ -468,7 +463,7 @@ class ExportController extends AbstractController
unset($parameters['_token']);
$key = md5(uniqid((string) random_int(0, mt_getrandmax()), false));
$this->redis->setEx($key, 3600, serialize($parameters));
$this->redis->setEx($key, 3600, \serialize($parameters));
// remove data from session
$this->session->remove('export_step_raw');
@@ -497,7 +492,7 @@ class ExportController extends AbstractController
$formExport->submit($rawData['export']);
$dataExport = $formExport->getData();
if (count($rawData['formatter']) > 0) {
if (\count($rawData['formatter']) > 0) {
$formFormatter = $this->createCreateFormExport(
$alias,
'generate_formatter',
@@ -513,16 +508,17 @@ class ExportController extends AbstractController
/**
* @param string $alias
*
* @return Response
*/
private function selectCentersStep(Request $request, \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export, $alias, ?SavedExport $savedExport = null)
private function selectCentersStep(Request $request, DirectExportInterface|ExportInterface $export, $alias, SavedExport $savedExport = null)
{
/** @var \Chill\MainBundle\Export\ExportManager $exportManager */
$exportManager = $this->exportManager;
$form = $this->createCreateFormExport($alias, 'centers', [], $savedExport);
if ($request->getMethod() === 'POST') {
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -533,14 +529,13 @@ class ExportController extends AbstractController
// check ACL
if (
$exportManager->isGrantedForElement(
false === $exportManager->isGrantedForElement(
$export,
null,
$exportManager->getPickedCenters($data['centers'])
) === false
)
) {
throw $this->createAccessDeniedException('you do not have '
. 'access to this export for those centers');
throw $this->createAccessDeniedException('you do not have access to this export for those centers');
}
$this->session->set(
@@ -589,20 +584,19 @@ class ExportController extends AbstractController
*
* This method provides a centralized way of handling next/previous step.
*
* @param string $step the current step
* @param \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export
* @param bool $reverse set to true to get the previous step
*
* @throws LogicException if there is no step before or after the given step
* @param string $step the current step
* @param bool $reverse set to true to get the previous step
*
* @return string the next/current step
*
* @throws \LogicException if there is no step before or after the given step
*/
private function getNextStep($step, \Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export, $reverse = false)
private function getNextStep($step, DirectExportInterface|ExportInterface $export, $reverse = false)
{
switch ($step) {
case 'centers':
if (false !== $reverse) {
throw new LogicException("there is no step before 'export'");
throw new \LogicException("there is no step before 'export'");
}
return 'export';
@@ -622,13 +616,13 @@ class ExportController extends AbstractController
case 'generate':
if (false === $reverse) {
throw new LogicException("there is no step after 'generate'");
throw new \LogicException("there is no step after 'generate'");
}
return 'formatter';
default:
throw new LogicException("the step {$step} is not defined.");
throw new \LogicException("the step {$step} is not defined.");
}
}
@@ -638,7 +632,7 @@ class ExportController extends AbstractController
throw $this->createNotFoundException('key does not exists');
}
if ($this->redis->exists($key) !== 1) {
if (1 !== $this->redis->exists($key)) {
$this->addFlash('error', $this->translator->trans('This report is not available any more'));
throw $this->createNotFoundException('key does not exists');
@@ -647,10 +641,10 @@ class ExportController extends AbstractController
$serialized = $this->redis->get($key);
if (false === $serialized) {
throw new LogicException('the key could not be reached from redis');
throw new \LogicException('the key could not be reached from redis');
}
$rawData = unserialize($serialized);
$rawData = \unserialize($serialized);
$this->logger->notice('[export] choices for an export unserialized', [
'key' => $key,
@@ -668,7 +662,7 @@ class ExportController extends AbstractController
};
if (null !== $savedExport && !$this->security->isGranted(SavedExportVoter::EDIT, $savedExport)) {
throw new AccessDeniedHttpException("saved export edition not allowed");
throw new AccessDeniedHttpException('saved export edition not allowed');
}
return $savedExport;

View File

@@ -36,7 +36,6 @@ class LocationApiController extends ApiController
/**
* @param QueryBuilder $query
* @param mixed $_format
*/
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
{

View File

@@ -35,6 +35,7 @@ class LoginController extends AbstractController
* Show a login form.
*
* @return Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/login", name="login")
*/
public function loginAction(Request $request)

View File

@@ -19,14 +19,12 @@ use Chill\MainBundle\Security\Authorization\NotificationVoter;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\MainBundle\Serializer\Model\Counter;
use Doctrine\ORM\EntityManagerInterface;
use RuntimeException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\SerializerInterface;
use UnexpectedValueException;
/**
* @Route("/api/1.0/main/notification")
@@ -91,13 +89,13 @@ class NotificationApiController
$user = $this->security->getUser();
if (!$user instanceof User) {
throw new RuntimeException('not possible to mark as read by this user');
throw new \RuntimeException('not possible to mark as read by this user');
}
match ($target) {
'read' => $notification->markAsReadBy($user),
'unread' => $notification->markAsUnreadBy($user),
default => throw new UnexpectedValueException("target not supported: {$target}"),
default => throw new \UnexpectedValueException("target not supported: {$target}"),
};
$this->entityManager->flush();

View File

@@ -148,7 +148,7 @@ class NotificationController extends AbstractController
throw new AccessDeniedHttpException('You must be authenticated and a user to create a notification');
}
foreach (['accessKey'/*, 'email'*/] as $param) {
foreach (['accessKey'/* , 'email' */] as $param) {
if (!$request->query->has($param)) {
throw new BadRequestHttpException("Missing {$param} parameter");
}
@@ -191,7 +191,7 @@ class NotificationController extends AbstractController
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');
$currentUser = $this->security->getUser();
$notificationsNbr = $this->notificationRepository->countAllForAttendee(($currentUser));
$notificationsNbr = $this->notificationRepository->countAllForAttendee($currentUser);
$paginator = $this->paginatorFactory->create($notificationsNbr);
$notifications = $this->notificationRepository->findAllForAttendee(
@@ -264,7 +264,7 @@ class NotificationController extends AbstractController
return $this->redirectToRoute('chill_main_notification_show', [
'id' => $notification->getId(),
'_fragment' => 'comment-' . $commentId,
'_fragment' => 'comment-'.$commentId,
]);
}

View File

@@ -17,8 +17,6 @@ use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverEvent;
use Chill\MainBundle\Security\PasswordRecover\PasswordRecoverVoter;
use Chill\MainBundle\Security\PasswordRecover\RecoverPasswordHelper;
use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use DateInterval;
use DateTimeImmutable;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
@@ -88,6 +86,7 @@ class PasswordController extends AbstractController
/**
* @return Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/request-changed", name="password_request_recover_changed")
*/
public function changeConfirmedAction()
@@ -96,15 +95,14 @@ class PasswordController extends AbstractController
}
/**
* @return Response|\Symfony\Component\HttpFoundation\RedirectResponse
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/recover", name="password_recover")
*/
public function recoverAction(Request $request): \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
public function recoverAction(Request $request): Response|\Symfony\Component\HttpFoundation\RedirectResponse
{
if (false === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return new Response($this->translator->trans('You are not allowed '
. 'to try to recover password, due to mitigating possible '
. 'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
.'to try to recover password, due to mitigating possible '
.'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
}
$query = $request->query;
@@ -165,15 +163,14 @@ class PasswordController extends AbstractController
* @throws \Doctrine\ORM\NoResultException
* @throws \Doctrine\ORM\NonUniqueResultException
*
* @return Response|\Symfony\Component\HttpFoundation\RedirectResponse
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/request-recover", name="password_request_recover")
*/
public function requestRecoverAction(Request $request): \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
public function requestRecoverAction(Request $request): Response|\Symfony\Component\HttpFoundation\RedirectResponse
{
if (false === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN)) {
return new Response($this->translator->trans('You are not allowed '
. 'to try to recover password, due to mitigating possible '
. 'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
.'to try to recover password, due to mitigating possible '
.'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
}
$form = $this->requestRecoverForm();
@@ -194,17 +191,17 @@ class PasswordController extends AbstractController
if (empty($user->getEmail())) {
$this->addFlash('error', $this->translator->trans('This account does not have an email address. '
. 'Please ask your administrator to renew your password.'));
.'Please ask your administrator to renew your password.'));
} else {
if (false === $this->isGranted(PasswordRecoverVoter::ASK_TOKEN, $user)) {
return new Response($this->translator->trans('You are not allowed '
. 'to try to recover password, due to mitigating possible '
. 'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
.'to try to recover password, due to mitigating possible '
.'attack. Try to contact your system administrator'), Response::HTTP_FORBIDDEN);
}
$this->recoverPasswordHelper->sendRecoverEmail(
$user,
(new DateTimeImmutable('now'))->add(new DateInterval('PT30M'))
(new \DateTimeImmutable('now'))->add(new \DateInterval('PT30M'))
);
// logging for prod
@@ -238,6 +235,7 @@ class PasswordController extends AbstractController
/**
* @return Response
*
* @\Symfony\Component\Routing\Annotation\Route(path="/public/{_locale}/password/request-confirm", name="password_request_recover_confirm")
*/
public function requestRecoverConfirmAction()
@@ -247,6 +245,7 @@ class PasswordController extends AbstractController
/**
* @return Response
*
* @Route("/{_locale}/my/password", name="change_my_password")
*/
public function UserPasswordAction(Request $request)
@@ -310,7 +309,7 @@ class PasswordController extends AbstractController
->orWhere($qb->expr()->eq('u.emailCanonical', 'UNACCENT(LOWER(:pattern))'))
->setParameter('pattern', $pattern);
if ((int) $qb->getQuery()->getSingleScalarResult() !== 1) {
if (1 !== (int) $qb->getQuery()->getSingleScalarResult()) {
$context->addViolation('This username or email does not exists');
}
},

View File

@@ -19,9 +19,6 @@ use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use function array_key_exists;
use function json_decode;
class PermissionApiController extends AbstractController
{
public function __construct(private readonly DenormalizerInterface $denormalizer, private readonly Security $security) {}
@@ -35,21 +32,17 @@ class PermissionApiController extends AbstractController
{
$this->denyAccessUnlessGranted('ROLE_USER');
$data = json_decode($request->getContent(), true);
$data = \json_decode($request->getContent(), true);
if (null === $data) {
throw new BadRequestHttpException(sprintf(
'Could not decode json received, or data invalid: %s, %s',
json_last_error(),
json_last_error_msg()
));
throw new BadRequestHttpException(sprintf('Could not decode json received, or data invalid: %s, %s', json_last_error(), json_last_error_msg()));
}
if (!array_key_exists('object', $data)) {
if (!\array_key_exists('object', $data)) {
throw new BadRequestHttpException('the object key is not present');
}
if (!array_key_exists('class', $data)) {
if (!\array_key_exists('class', $data)) {
throw new BadRequestHttpException('the class key is not present');
}

View File

@@ -21,7 +21,6 @@ use Chill\MainBundle\Repository\RoleScopeRepository;
use Chill\MainBundle\Security\RoleProvider;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityManagerInterface;
use RuntimeException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormInterface;
@@ -31,8 +30,6 @@ use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
/**
* Class PermissionsGroupController.
*/
@@ -75,7 +72,7 @@ final class PermissionsGroupController extends AbstractController
$permissionsGroup->addRoleScope($roleScope);
$violations = $this->validator->validate($permissionsGroup);
if ($violations->count() === 0) {
if (0 === $violations->count()) {
$this->em->flush();
$this->addFlash(
@@ -132,6 +129,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Creates a new PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/create", name="admin_permissionsgroup_create", methods={"POST"})
*/
public function createAction(Request $request): Response
@@ -155,6 +153,7 @@ final class PermissionsGroupController extends AbstractController
/**
* remove an association between permissionsGroup and roleScope.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{pgid}/delete_link_role_scope/{rsid}", name="admin_permissionsgroup_delete_role_scope", methods={"DELETE"})
*/
public function deleteLinkRoleScopeAction(int $pgid, int $rsid): Response
@@ -172,11 +171,11 @@ final class PermissionsGroupController extends AbstractController
try {
$permissionsGroup->removeRoleScope($roleScope);
} catch (RuntimeException) {
} catch (\RuntimeException) {
$this->addFlash(
'notice',
$this->translator->trans("The role '%role%' and circle "
. "'%scope%' is not associated with this permission group", [
."'%scope%' is not associated with this permission group", [
'%role%' => $this->translator->trans($roleScope->getRole()),
'%scope%' => $this->translatableStringHelper
->localize($roleScope->getScope()->getName()),
@@ -188,11 +187,11 @@ final class PermissionsGroupController extends AbstractController
$this->em->flush();
if ($roleScope->getScope() !== null) {
if (null !== $roleScope->getScope()) {
$this->addFlash(
'notice',
$this->translator->trans("The role '%role%' on circle "
. "'%scope%' has been removed", [
."'%scope%' has been removed", [
'%role%' => $this->translator->trans($roleScope->getRole()),
'%scope%' => $this->translatableStringHelper
->localize($roleScope->getScope()->getName()),
@@ -212,6 +211,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Displays a form to edit an existing PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{id}/edit", name="admin_permissionsgroup_edit")
*/
public function editAction(int $id): Response
@@ -259,6 +259,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Lists all PermissionsGroup entities.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/", name="admin_permissionsgroup")
*/
public function indexAction(): Response
@@ -272,6 +273,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Displays a form to create a new PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/new", name="admin_permissionsgroup_new")
*/
public function newAction(): Response
@@ -287,6 +289,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Finds and displays a PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{id}/show", name="admin_permissionsgroup_show")
*/
public function showAction(int $id): Response
@@ -304,11 +307,11 @@ final class PermissionsGroupController extends AbstractController
usort(
$roleScopes,
static function (RoleScope $a, RoleScope $b) use ($translatableStringHelper) {
if ($a->getScope() === null) {
if (null === $a->getScope()) {
return 1;
}
if ($b->getScope() === null) {
if (null === $b->getScope()) {
return +1;
}
@@ -339,6 +342,7 @@ final class PermissionsGroupController extends AbstractController
/**
* Edits an existing PermissionsGroup entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/permissionsgroup/{id}/update", name="admin_permissionsgroup_update", methods={"POST", "PUT"})
*/
public function updateAction(Request $request, int $id): Response
@@ -347,8 +351,7 @@ final class PermissionsGroupController extends AbstractController
->find($id);
if (!$permissionsGroup) {
throw $this->createNotFoundException('Unable to find Permissions'
. 'Group entity.');
throw $this->createNotFoundException('Unable to find PermissionsGroup entity.');
}
$editForm = $this->createEditForm($permissionsGroup);
@@ -396,7 +399,7 @@ final class PermissionsGroupController extends AbstractController
* get a role scope by his parameters. The role scope is persisted if it
* doesn't exist in database.
*/
protected function getPersistentRoleScopeBy(string $role, ?Scope $scope = null): RoleScope
protected function getPersistentRoleScopeBy(string $role, Scope $scope = null): RoleScope
{
$roleScope = $this->roleScopeRepository
->findOneBy(['role' => $role, 'scope' => $scope]);
@@ -487,7 +490,7 @@ final class PermissionsGroupController extends AbstractController
$expandedRoles = [];
foreach ($roleScopes as $roleScope) {
if (!array_key_exists($roleScope->getRole(), $expandedRoles)) {
if (!\array_key_exists($roleScope->getRole(), $expandedRoles)) {
$expandedRoles[$roleScope->getRole()] =
array_map(
static fn ($role) => $role,

View File

@@ -19,8 +19,6 @@ use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use function array_map;
/**
* Class PostalCodeController.
*/
@@ -55,21 +53,21 @@ class PostalCodeController extends AbstractController
->createQuery(
sprintf(
'SELECT p.id AS id, p.name AS name, p.code AS code, '
. 'country.name AS country_name, '
. 'country.countryCode AS country_code '
. 'FROM %s p '
. 'JOIN p.country country '
. 'WHERE LOWER(p.name) LIKE LOWER(:pattern) OR LOWER(p.code) LIKE LOWER(:pattern) '
. 'ORDER BY code',
.'country.name AS country_name, '
.'country.countryCode AS country_code '
.'FROM %s p '
.'JOIN p.country country '
.'WHERE LOWER(p.name) LIKE LOWER(:pattern) OR LOWER(p.code) LIKE LOWER(:pattern) '
.'ORDER BY code',
PostalCode::class
)
)
->setParameter('pattern', '%' . $pattern . '%')
->setParameter('pattern', '%'.$pattern.'%')
->setMaxResults(30);
$results = array_map(function ($row) {
$results = \array_map(function ($row) {
$row['country_name'] = $this->translatableStringHelper->localize($row['country_name']);
$row['text'] = $row['code'] . ' ' . $row['name'] . ' (' . $row['country_name'] . ')';
$row['text'] = $row['code'].' '.$row['name'].' ('.$row['country_name'].')';
return $row;
}, $query->getResult(Query::HYDRATE_ARRAY));

View File

@@ -30,9 +30,7 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
class SavedExportController
{
@@ -139,7 +137,7 @@ class SavedExportController
'@ChillMain/SavedExport/index.html.twig',
[
'grouped_exports' => $exportsGrouped,
'total' => count($exports),
'total' => \count($exports),
]
)
);

View File

@@ -24,6 +24,7 @@ class ScopeController extends AbstractController
{
/**
* Creates a new Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/create", name="admin_scope_create", methods={"POST"})
*/
public function createAction(Request $request)
@@ -48,6 +49,7 @@ class ScopeController extends AbstractController
/**
* Displays a form to edit an existing Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/{id}/edit", name="admin_scope_edit")
*/
public function editAction(mixed $id)
@@ -70,6 +72,7 @@ class ScopeController extends AbstractController
/**
* Lists all Scope entities.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/", name="admin_scope")
*/
public function indexAction()
@@ -85,6 +88,7 @@ class ScopeController extends AbstractController
/**
* Displays a form to create a new Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/new", name="admin_scope_new")
*/
public function newAction()
@@ -118,6 +122,7 @@ class ScopeController extends AbstractController
/**
* Edits an existing Scope entity.
*
* @\Symfony\Component\Routing\Annotation\Route(path="/{_locale}/admin/scope/{id}/update", name="admin_scope_update", methods={"POST", "PUT"})
*/
public function updateAction(Request $request, mixed $id)

View File

@@ -27,10 +27,6 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
use function key;
use function reset;
/**
* Class SearchController.
*/
@@ -50,8 +46,7 @@ class SearchController extends AbstractController
$search = $this->searchProvider
->getHasAdvancedFormByName($name);
} catch (\Chill\MainBundle\Search\UnknowSearchNameException) {
throw $this->createNotFoundException('no advanced search for '
. "{$name}");
throw $this->createNotFoundException('no advanced search for '."{$name}");
}
if ($request->query->has('q')) {
@@ -96,7 +91,7 @@ class SearchController extends AbstractController
$advancedSearchProviders = $searchProvider
->getHasAdvancedFormSearchServices();
if (count($advancedSearchProviders) === 1) {
if (1 === \count($advancedSearchProviders)) {
return $this->redirectToRoute('chill_main_advanced_search', [
'name' => array_key_first($advancedSearchProviders),
]);
@@ -119,7 +114,7 @@ class SearchController extends AbstractController
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('Your search is empty. '
. 'Please provide search terms.'),
.'Please provide search terms.'),
'pattern' => $pattern,
]
);
@@ -138,7 +133,7 @@ class SearchController extends AbstractController
if (null === $name) {
if ('json' === $_format) {
return new JsonResponse('Currently, we still do not aggregate results '
. 'from different providers', JsonResponse::HTTP_BAD_REQUEST);
.'from different providers', JsonResponse::HTTP_BAD_REQUEST);
}
// no specific search selected. Rendering result in "preview" mode
@@ -166,7 +161,7 @@ class SearchController extends AbstractController
), ];
if ('json' === $_format) {
return new JsonResponse(reset($results));
return new JsonResponse(\reset($results));
}
}
} catch (UnknowSearchDomainException $ex) {
@@ -174,18 +169,18 @@ class SearchController extends AbstractController
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('The domain %domain% '
. 'is unknow. Please check your search.', ['%domain%' => $ex->getDomain()]),
.'is unknow. Please check your search.', ['%domain%' => $ex->getDomain()]),
'pattern' => $pattern,
]
);
} catch (UnknowSearchNameException $ex) {
throw $this->createNotFoundException('The name ' . $ex->getName() . ' is not found');
throw $this->createNotFoundException('The name '.$ex->getName().' is not found');
} catch (ParsingException $ex) {
return $this->render(
'@ChillMain/Search/error.html.twig',
[
'message' => $this->translator->trans('Invalid terms') .
': ' . $this->translator->trans($ex->getMessage()),
'message' => $this->translator->trans('Invalid terms').
': '.$this->translator->trans($ex->getMessage()),
'pattern' => $pattern,
]
);
@@ -202,13 +197,12 @@ class SearchController extends AbstractController
*/
public function searchApi(Request $request, mixed $_format): JsonResponse
{
//TODO this is an incomplete implementation
// TODO this is an incomplete implementation
$query = $request->query->get('q', '');
$types = $request->query->get('type', []);
if (count($types) === 0) {
throw new BadRequestHttpException('The request must contains at '
. ' one type');
if (0 === \count($types)) {
throw new BadRequestHttpException('The request must contains at one type');
}
try {

View File

@@ -18,8 +18,6 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use function count;
class TimelineCenterController extends AbstractController
{
public function __construct(protected TimelineBuilder $timelineBuilder, protected PaginatorFactory $paginatorFactory, private readonly Security $security) {}
@@ -40,7 +38,7 @@ class TimelineCenterController extends AbstractController
$centers[] = $group->getCenter();
}
if (0 === count($centers)) {
if (0 === \count($centers)) {
throw $this->createNotFoundException();
}

View File

@@ -68,10 +68,6 @@ class UserApiController extends ApiController
}
}
/**
* @param mixed $query
* @param mixed $_format
*/
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
{
return $query->orderBy('e.label', 'ASC');

View File

@@ -22,7 +22,6 @@ use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Repository\UserRepository;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Form;
@@ -63,11 +62,11 @@ class UserController extends CRUDController
);
$user->addGroupCenter($groupCenter);
if ($this->validator->validate($user)->count() === 0) {
if (0 === $this->validator->validate($user)->count()) {
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('The '
. 'permissions have been successfully added to the user'));
.'permissions have been successfully added to the user'));
$returnPathParams = $request->query->has('returnPath') ?
['returnPath' => $request->query->get('returnPath')] : [];
@@ -115,7 +114,7 @@ class UserController extends CRUDController
try {
$user->removeGroupCenter($groupCenter);
} catch (RuntimeException $ex) {
} catch (\RuntimeException $ex) {
$this->addFlash('error', $this->get('translator')->trans($ex->getMessage()));
return $this->redirectToRoute('chill_crud_admin_user_edit', ['id' => $uid]);
@@ -135,13 +134,7 @@ class UserController extends CRUDController
$entity = $this->getEntity($action, $id, $request);
if (null === $entity) {
throw $this->createNotFoundException(
sprintf(
'The %s with id %s is not found',
$this->getCrudName(),
$id
)
);
throw $this->createNotFoundException(sprintf('The %s with id %s is not found', $this->getCrudName(), $id));
}
$response = $this->checkACL($action, $entity);
@@ -176,7 +169,7 @@ class UserController extends CRUDController
return $result;
}
return $this->redirectToRoute('chill_crud_' . $this->getCrudName() . '_index');
return $this->redirectToRoute('chill_crud_'.$this->getCrudName().'_index');
}
if ($form->isSubmitted()) {
@@ -272,7 +265,7 @@ class UserController extends CRUDController
->build();
}
protected function countEntities(string $action, Request $request, ?FilterOrderHelper $filterOrder = null): int
protected function countEntities(string $action, Request $request, FilterOrderHelper $filterOrder = null): int
{
if (!$filterOrder instanceof FilterOrderHelper) {
return parent::countEntities($action, $request, $filterOrder);
@@ -285,7 +278,7 @@ class UserController extends CRUDController
return $this->userRepository->countByUsernameOrEmail($filterOrder->getQueryString());
}
protected function createFormFor(string $action, $entity, ?string $formClass = null, array $formOptions = []): FormInterface
protected function createFormFor(string $action, $entity, string $formClass = null, array $formOptions = []): FormInterface
{
// for "new", add special config
if ('new' === $action) {
@@ -329,7 +322,7 @@ class UserController extends CRUDController
Request $request,
int $totalItems,
PaginatorInterface $paginator,
?FilterOrderHelper $filterOrder = null
FilterOrderHelper $filterOrder = null
) {
if (0 === $totalItems) {
return [];

View File

@@ -47,7 +47,7 @@ final readonly class UserExportController
$csv = Writer::createFromPath('php://temp', 'r+');
$csv->insertOne(
array_map(
fn (string $e) => $this->translator->trans('admin.users.export.' . $e),
fn (string $e) => $this->translator->trans('admin.users.export.'.$e),
[
'id',
// 'username',
@@ -57,7 +57,7 @@ final readonly class UserExportController
'civility_abbreviation',
'civility_name',
'label',
'mainCenter_id' ,
'mainCenter_id',
'mainCenter_name',
'mainScope_id',
'mainScope_name',
@@ -67,7 +67,7 @@ final readonly class UserExportController
'currentLocation_name',
'mainLocation_id',
'mainLocation_name',
'absenceStart'
'absenceStart',
]
)
);
@@ -94,6 +94,7 @@ final readonly class UserExportController
* @throws \League\Csv\CannotInsertRecord
* @throws \League\Csv\Exception
* @throws \League\Csv\UnavailableStream
*
* @Route("/{_locale}/admin/main/users/export/permissions.{_format}", requirements={"_format": "csv"}, name="chill_main_users_export_permissions")
*/
public function userPermissionsList(string $_format = 'csv'): StreamedResponse
@@ -107,7 +108,7 @@ final readonly class UserExportController
$csv = Writer::createFromPath('php://temp', 'r+');
$csv->insertOne(
array_map(
fn (string $e) => $this->translator->trans('admin.users.export.' . $e),
fn (string $e) => $this->translator->trans('admin.users.export.'.$e),
[
'id',
'username',

View File

@@ -18,7 +18,6 @@ use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\MainBundle\Serializer\Model\Counter;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
@@ -142,12 +141,12 @@ class WorkflowApiController
'final' => match ($action) {
'subscribe' => $entityWorkflow->addSubscriberToFinal($user),
'unsubscribe' => $entityWorkflow->removeSubscriberToFinal($user),
default => throw new LogicException(),
default => throw new \LogicException(),
},
'step' => match ($action) {
'subscribe' => $entityWorkflow->addSubscriberToStep($user),
'unsubscribe' => $entityWorkflow->removeSubscriberToStep($user),
default => throw new LogicException(),
default => throw new \LogicException(),
},
default => throw new BadRequestHttpException('subscribe parameter must be equal to "step" or "final"'),
};

View File

@@ -35,7 +35,6 @@ use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\TransitionBlocker;
use Symfony\Contracts\Translation\TranslatorInterface;
use function count;
class WorkflowController extends AbstractController
{
@@ -67,11 +66,11 @@ class WorkflowController extends AbstractController
$errors = $this->validator->validate($entityWorkflow, null, ['creation']);
if (count($errors) > 0) {
if (\count($errors) > 0) {
$msg = [];
foreach ($errors as $error) {
/** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
/* @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
$msg[] = $error->getMessage();
}
@@ -294,7 +293,7 @@ class WorkflowController extends AbstractController
$workflow = $this->registry->get($entityWorkflow, $entityWorkflow->getWorkflowName());
$errors = [];
if (count($workflow->getEnabledTransitions($entityWorkflow)) > 0) {
if (\count($workflow->getEnabledTransitions($entityWorkflow)) > 0) {
// possible transition
$usersInvolved = $entityWorkflow->getUsersInvolved();
@@ -310,7 +309,7 @@ class WorkflowController extends AbstractController
[
'transition' => true,
'entity_workflow' => $entityWorkflow,
'suggested_users' => $usersInvolved
'suggested_users' => $usersInvolved,
]
);
@@ -324,12 +323,7 @@ class WorkflowController extends AbstractController
$tb->getParameters()
), iterator_to_array($blockers));
throw $this->createAccessDeniedException(
sprintf(
"not allowed to apply transition {$transition}: %s",
implode(', ', $msgs)
)
);
throw $this->createAccessDeniedException(sprintf("not allowed to apply transition {$transition}: %s", implode(', ', $msgs)));
}
// TODO symfony 5: add those "future" on context ($workflow->apply($entityWorkflow, $transition, $context)
@@ -374,7 +368,7 @@ class WorkflowController extends AbstractController
'transition_form' => isset($transitionForm) ? $transitionForm->createView() : null,
'entity_workflow' => $entityWorkflow,
'transition_form_errors' => $errors,
//'comment_form' => $commentForm->createView(),
// 'comment_form' => $commentForm->createView(),
]
);
}

View File

@@ -20,11 +20,12 @@ interface CronJobInterface
public function getKey(): string;
/**
* Execute the cronjob
* Execute the cronjob.
*
* If data is returned, this data is passed as argument on the next execution
*
* @param array $lastExecutionData the data which was returned from the previous execution
*
* @return array|null optionally return an array with the same data than the previous execution
*/
public function run(array $lastExecutionData): null|array;

View File

@@ -13,12 +13,10 @@ namespace Chill\MainBundle\Cron;
use Chill\MainBundle\Entity\CronJobExecution;
use Chill\MainBundle\Repository\CronJobExecutionRepositoryInterface;
use DateTimeImmutable;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Psr\Log\LoggerInterface;
use function array_key_exists;
/**
* Manage cronjob and execute them.
@@ -43,11 +41,11 @@ final readonly class CronManager implements CronManagerInterface
{
private const LOG_PREFIX = '[cron manager] ';
private const UPDATE_AFTER_EXEC = 'UPDATE ' . CronJobExecution::class . ' cr SET cr.lastEnd = :now, cr.lastStatus = :status WHERE cr.key = :key';
private const UPDATE_AFTER_EXEC = 'UPDATE '.CronJobExecution::class.' cr SET cr.lastEnd = :now, cr.lastStatus = :status WHERE cr.key = :key';
private const UPDATE_BEFORE_EXEC = 'UPDATE ' . CronJobExecution::class . ' cr SET cr.lastStart = :now WHERE cr.key = :key';
private const UPDATE_BEFORE_EXEC = 'UPDATE '.CronJobExecution::class.' cr SET cr.lastStart = :now WHERE cr.key = :key';
private const UPDATE_LAST_EXECUTION_DATA = 'UPDATE ' . CronJobExecution::class . ' cr SET cr.lastExecutionData = :data WHERE cr.key = :key';
private const UPDATE_LAST_EXECUTION_DATA = 'UPDATE '.CronJobExecution::class.' cr SET cr.lastExecutionData = :data WHERE cr.key = :key';
/**
* @param CronJobInterface[] $jobs
@@ -59,7 +57,7 @@ final readonly class CronManager implements CronManagerInterface
private LoggerInterface $logger
) {}
public function run(?string $forceJob = null): void
public function run(string $forceJob = null): void
{
if (null !== $forceJob) {
$this->runForce($forceJob);
@@ -71,13 +69,13 @@ final readonly class CronManager implements CronManagerInterface
foreach ($orderedJobs as $job) {
if ($job->canRun($lasts[$job->getKey()] ?? null)) {
if (array_key_exists($job->getKey(), $lasts)) {
if (\array_key_exists($job->getKey(), $lasts)) {
$executionData = $lasts[$job->getKey()]->getLastExecutionData();
$this->entityManager
->createQuery(self::UPDATE_BEFORE_EXEC)
->setParameters([
'now' => new DateTimeImmutable('now'),
'now' => new \DateTimeImmutable('now'),
'key' => $job->getKey(),
])
->execute();
@@ -100,7 +98,7 @@ final readonly class CronManager implements CronManagerInterface
$this->entityManager
->createQuery(self::UPDATE_AFTER_EXEC)
->setParameters([
'now' => new DateTimeImmutable('now'),
'now' => new \DateTimeImmutable('now'),
'status' => CronJobExecution::SUCCESS,
'key' => $job->getKey(),
])
@@ -117,12 +115,12 @@ final readonly class CronManager implements CronManagerInterface
$this->logger->info(sprintf('%sSuccessfully run job', self::LOG_PREFIX), ['job' => $job->getKey()]);
return;
} catch (Exception) {
} catch (\Exception) {
$this->logger->error(sprintf('%sRunning job failed', self::LOG_PREFIX), ['job' => $job->getKey()]);
$this->entityManager
->createQuery(self::UPDATE_AFTER_EXEC)
->setParameters([
'now' => new DateTimeImmutable('now'),
'now' => new \DateTimeImmutable('now'),
'status' => CronJobExecution::FAILURE,
'key' => $job->getKey(),
])
@@ -152,16 +150,16 @@ final readonly class CronManager implements CronManagerInterface
$orderedJobs,
static function (CronJobInterface $a, CronJobInterface $b) use ($lasts): int {
if (
(!array_key_exists($a->getKey(), $lasts) && !array_key_exists($b->getKey(), $lasts))
!\array_key_exists($a->getKey(), $lasts) && !\array_key_exists($b->getKey(), $lasts)
) {
return 0;
}
if (!array_key_exists($a->getKey(), $lasts) && array_key_exists($b->getKey(), $lasts)) {
if (!\array_key_exists($a->getKey(), $lasts) && \array_key_exists($b->getKey(), $lasts)) {
return -1;
}
if (!array_key_exists($b->getKey(), $lasts) && array_key_exists($a->getKey(), $lasts)) {
if (!\array_key_exists($b->getKey(), $lasts) && \array_key_exists($a->getKey(), $lasts)) {
return 1;
}

View File

@@ -16,5 +16,5 @@ interface CronManagerInterface
/**
* Execute one job, with a given priority, or the given job (identified by his key).
*/
public function run(?string $forceJob = null): void;
public function run(string $forceJob = null): void;
}

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DataFixtures\ORM;
use Chill\MainBundle\Entity\Notification;
use DateTimeImmutable;
use Doctrine\Persistence\ObjectManager;
/**
@@ -27,14 +26,14 @@ trait LoadAbstractNotificationsTrait
foreach ($this->notifs as $notif) {
$entityId = $this->getReference($notif['entityRef'])->getId();
echo 'Adding notification for ' . $notif['entityClass'] . '(entity id:' . $entityId . ")\n";
echo 'Adding notification for '.$notif['entityClass'].'(entity id:'.$entityId.")\n";
$newNotif = (new Notification())
->setMessage($notif['message'])
->setSender($this->getReference($notif['sender']))
->setRelatedEntityClass($notif['entityClass'])
->setRelatedEntityId($entityId)
->setDate(new DateTimeImmutable('now'))
->setDate(new \DateTimeImmutable('now'))
->setRead([]);
foreach ($notif['addressees'] as $addressee) {

View File

@@ -50,7 +50,7 @@ class LoadAddressReferences extends AbstractFixture implements ContainerAwareInt
$manager->flush();
}
public function setContainer(?ContainerInterface $container = null)
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}

View File

@@ -43,7 +43,7 @@ class LoadCountries extends AbstractFixture implements ContainerAwareInterface,
$manager->flush();
}
public function setContainer(?ContainerInterface $container = null)
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}

View File

@@ -35,7 +35,7 @@ class LoadGroupCenters extends AbstractFixture implements OrderedFixtureInterfac
$manager->persist($GroupCenter);
$reference = $centerRef . '_' . $permissionGroupRef;
$reference = $centerRef.'_'.$permissionGroupRef;
$this->addReference($reference, $GroupCenter);
static::$refs[] = $reference;
echo "Creating {$reference}... \n";

View File

@@ -17,9 +17,6 @@ use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Intl\Intl;
use function in_array;
/**
* Load languages into database.
@@ -47,8 +44,8 @@ class LoadLanguages extends AbstractFixture implements ContainerAwareInterface,
foreach (\Symfony\Component\Intl\Languages::getNames() as $code => $language) {
if (
!in_array($code, $this->regionalVersionToInclude, true)
&& !in_array($code, $this->ancientToExclude, true)
!\in_array($code, $this->regionalVersionToInclude, true)
&& !\in_array($code, $this->ancientToExclude, true)
) {
$lang = (new Language())
->setId($code)
@@ -60,7 +57,7 @@ class LoadLanguages extends AbstractFixture implements ContainerAwareInterface,
$manager->flush();
}
public function setContainer(?ContainerInterface $container = null)
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}

View File

@@ -65,7 +65,7 @@ class LoadLocationType extends AbstractFixture implements ContainerAwareInterfac
$manager->flush();
}
public function setContainer(?ContainerInterface $container = null)
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}

View File

@@ -63,7 +63,7 @@ class LoadPermissionsGroup extends AbstractFixture implements OrderedFixtureInte
}
$manager->persist($permissionGroup);
$reference = 'permission_group_' . $new['name'];
$reference = 'permission_group_'.$new['name'];
echo "Creating {$reference} \n";
$this->setReference($reference, $permissionGroup);
static::$refs[] = $reference;

View File

@@ -18,9 +18,6 @@ use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use function strtolower;
use function ucwords;
/**
* Description of LoadPostalCodes.
*/
@@ -351,7 +348,7 @@ class LoadPostalCodes extends AbstractFixture implements OrderedFixtureInterface
$c = new PostalCode();
$c->setCountry($country)
->setCode($code[0])
->setName(ucwords(strtolower($code[1])));
->setName(\ucwords(\strtolower($code[1])));
if (null !== ($code[3] ?? null)) {
$c->setRefPostalCodeId($code[3]);
@@ -366,7 +363,7 @@ class LoadPostalCodes extends AbstractFixture implements OrderedFixtureInterface
}
$manager->persist($c);
$ref = 'postal_code_' . $code[0];
$ref = 'postal_code_'.$code[0];
if (!$this->hasReference($ref)) {
$this->addReference($ref, $c);

View File

@@ -56,7 +56,7 @@ class LoadRoleScopes extends AbstractFixture implements OrderedFixtureInterface
$roleScope = new RoleScope();
$roleScope->setRole($key)
->setScope($this->getReference($scopeReference));
$reference = 'role_scope_' . $key . '_' . $this->getReference($scopeReference)->getName()['en'];
$reference = 'role_scope_'.$key.'_'.$this->getReference($scopeReference)->getName()['en'];
echo "Creating {$reference} \n";
$this->addReference($reference, $roleScope);
$manager->persist($roleScope);

View File

@@ -58,7 +58,7 @@ class LoadScopes extends AbstractFixture implements OrderedFixtureInterface
$scope->setName($new['names']);
$manager->persist($scope);
$reference = 'scope_' . $new['names']['en'];
$reference = 'scope_'.$new['names']['en'];
$this->addReference($reference, $scope);
static::$references[] = $reference;
}

View File

@@ -15,14 +15,11 @@ use Chill\MainBundle\Entity\User;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use LogicException;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use function str_replace;
/**
* Load fixtures users into database.
*
@@ -81,13 +78,13 @@ class LoadUsers extends AbstractFixture implements ContainerAwareInterface, Orde
->getEncoder($user)
->encodePassword('password', $user->getSalt())
)
->setEmail(sprintf('%s@chill.social', str_replace(' ', '', (string) $username)));
->setEmail(sprintf('%s@chill.social', \str_replace(' ', '', (string) $username)));
foreach ($params['groupCenterRefs'] as $groupCenterRef) {
$user->addGroupCenter($this->getReference($groupCenterRef));
}
echo 'Creating user ' . $username . "... \n";
echo 'Creating user '.$username."... \n";
$manager->persist($user);
$this->addReference($username, $user);
}
@@ -95,10 +92,10 @@ class LoadUsers extends AbstractFixture implements ContainerAwareInterface, Orde
$manager->flush();
}
public function setContainer(?ContainerInterface $container = null)
public function setContainer(ContainerInterface $container = null)
{
if (null === $container) {
throw new LogicException('$container should not be null');
throw new \LogicException('$container should not be null');
}
$this->container = $container;

View File

@@ -23,8 +23,6 @@ use Chill\MainBundle\Controller\RegroupmentController;
use Chill\MainBundle\Controller\UserController;
use Chill\MainBundle\Controller\UserJobApiController;
use Chill\MainBundle\Controller\UserJobController;
use Chill\MainBundle\Controller\UserJobHistoryController;
use Chill\MainBundle\Controller\UserScopeHistoryController;
use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface;
use Chill\MainBundle\Doctrine\DQL\Age;
use Chill\MainBundle\Doctrine\DQL\Extract;
@@ -59,8 +57,6 @@ use Chill\MainBundle\Entity\Regroupment;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserJob;
use Chill\MainBundle\Form\CenterType;
use Chill\MainBundle\Entity\User\UserJobHistory;
use Chill\MainBundle\Entity\User\UserScopeHistory;
use Chill\MainBundle\Form\CivilityType;
use Chill\MainBundle\Form\CountryType;
use Chill\MainBundle\Form\LanguageType;
@@ -69,7 +65,6 @@ use Chill\MainBundle\Form\LocationTypeType;
use Chill\MainBundle\Form\RegroupmentType;
use Chill\MainBundle\Form\UserJobType;
use Chill\MainBundle\Form\UserType;
use Exception;
use Misd\PhoneNumberBundle\Doctrine\DBAL\Types\PhoneNumberType;
use Ramsey\Uuid\Doctrine\UuidType;
use Symfony\Component\Config\FileLocator;
@@ -79,8 +74,6 @@ use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use function count;
/**
* Class ChillMainExtension
* This class load config for chillMainExtension.
@@ -101,7 +94,7 @@ class ChillMainExtension extends Extension implements
$this->widgetFactories[] = $factory;
}
public function getConfiguration(array $config, ContainerBuilder $container): \Chill\MainBundle\DependencyInjection\Configuration
public function getConfiguration(array $config, ContainerBuilder $container): Configuration
{
return new Configuration($this->widgetFactories, $container);
}
@@ -115,7 +108,7 @@ class ChillMainExtension extends Extension implements
}
/**
* @throws Exception
* @throws \Exception
*/
public function load(array $configs, ContainerBuilder $container)
{
@@ -195,7 +188,7 @@ class ChillMainExtension extends Extension implements
[]
);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../config'));
$loader->load('services.yaml');
$loader->load('services/doctrine.yaml');
$loader->load('services/logger.yaml');
@@ -223,12 +216,12 @@ class ChillMainExtension extends Extension implements
$this->configureCruds($container, $config['cruds'], $config['apis'], $loader);
$container->setParameter('chill_main.short_messages', $config['short_messages']);
//$this->configureSms($config['short_messages'], $container, $loader);
// $this->configureSms($config['short_messages'], $container, $loader);
}
public function prepend(ContainerBuilder $container)
{
//add installation_name and date_format to globals
// add installation_name and date_format to globals
$chillMainConfig = $container->getExtensionConfig($this->getAlias());
$config = $this->processConfiguration($this
->getConfiguration($chillMainConfig, $container), $chillMainConfig);
@@ -243,7 +236,7 @@ class ChillMainExtension extends Extension implements
];
$container->prependExtensionConfig('twig', $twigConfig);
//add DQL function to ORM (default entity_manager)
// add DQL function to ORM (default entity_manager)
$container
->prependExtensionConfig(
'doctrine',
@@ -283,7 +276,7 @@ class ChillMainExtension extends Extension implements
],
);
//add dbal types (default entity_manager)
// add dbal types (default entity_manager)
$container
->prependExtensionConfig(
'doctrine',
@@ -305,7 +298,7 @@ class ChillMainExtension extends Extension implements
]
);
//add current route to chill main
// add current route to chill main
$container->prependExtensionConfig('chill_main', [
'routing' => [
'resources' => [
@@ -314,7 +307,7 @@ class ChillMainExtension extends Extension implements
],
]);
//add a channel to log app events
// add a channel to log app events
$container->prependExtensionConfig('monolog', [
'channels' => ['chill'],
]);
@@ -326,7 +319,7 @@ class ChillMainExtension extends Extension implements
],
]);
//add crud api
// add crud api
$this->prependCruds($container);
}
@@ -339,7 +332,7 @@ class ChillMainExtension extends Extension implements
array $apiConfig,
Loader\YamlFileLoader $loader
): void {
if (count($crudConfig) === 0) {
if (0 === \count($crudConfig)) {
return;
}
@@ -773,7 +766,7 @@ class ChillMainExtension extends Extension implements
],
],
],
]
],
],
]);
}

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection\CompilerPass;
use Chill\MainBundle\Form\PermissionsGroupType;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -29,13 +28,7 @@ class ACLFlagsCompilerPass implements CompilerPassInterface
foreach ($tags as $tag) {
match ($tag['scope']) {
PermissionsGroupType::FLAG_SCOPE => $permissionGroupType->addMethodCall('addFlagProvider', [$reference]),
default => throw new LogicException(
sprintf(
"This tag 'scope' is not implemented: %s, on service with id %s",
$tag['scope'],
$id
)
),
default => throw new \LogicException(sprintf("This tag 'scope' is not implemented: %s, on service with id %s", $tag['scope'], $id)),
};
}
}

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection\CompilerPass;
use Chill\MainBundle\Export\ExportManager;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
@@ -32,8 +31,7 @@ class ExportsCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
if (!$container->has(ExportManager::class)) {
throw new LogicException('service ' . ExportManager::class . ' '
. 'is not defined. It is required by ExportsCompilerPass');
throw new \LogicException('service '.ExportManager::class.' is not defined. It is required by ExportsCompilerPass');
}
$chillManagerDefinition = $container->findDefinition(
@@ -57,13 +55,11 @@ class ExportsCompilerPass implements CompilerPassInterface
foreach ($taggedServices as $id => $tagAttributes) {
foreach ($tagAttributes as $attributes) {
if (!isset($attributes['prefix'])) {
throw new LogicException("the 'prefix' attribute is missing in your " .
"service '{$id}' definition");
throw new \LogicException("the 'prefix' attribute is missing in your service '{$id}' definition");
}
if (array_search($attributes['prefix'], $knownAliases, true)) {
throw new LogicException('There is already a chill.export_elements_provider service with prefix '
. $attributes['prefix'] . '. Choose another prefix.');
throw new \LogicException('There is already a chill.export_elements_provider service with prefix '.$attributes['prefix'].'. Choose another prefix.');
}
$knownAliases[] = $attributes['prefix'];
@@ -88,13 +84,11 @@ class ExportsCompilerPass implements CompilerPassInterface
foreach ($taggedServices as $id => $tagAttributes) {
foreach ($tagAttributes as $attributes) {
if (!isset($attributes['alias'])) {
throw new LogicException("the 'alias' attribute is missing in your " .
"service '{$id}' definition");
throw new \LogicException("the 'alias' attribute is missing in your service '{$id}' definition");
}
if (array_search($attributes['alias'], $knownAliases, true)) {
throw new LogicException('There is already a chill.export_formatter service with alias '
. $attributes['alias'] . '. Choose another alias.');
throw new \LogicException('There is already a chill.export_formatter service with alias '.$attributes['alias'].'. Choose another alias.');
}
$knownAliases[] = $attributes['alias'];

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection\CompilerPass;
use Chill\MainBundle\Routing\MenuComposer;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -22,8 +21,7 @@ class MenuCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('chill.main.menu_composer')) {
throw new LogicException(sprintf('The service %s does not exists in '
. 'container.', MenuComposer::class));
throw new \LogicException(sprintf('The service %s does not exists in container.', MenuComposer::class));
}
$menuComposerDefinition = $container->getDefinition('chill.main.menu_composer');

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection\CompilerPass;
use Chill\MainBundle\Templating\UI\CountNotificationUser;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -22,8 +21,7 @@ class NotificationCounterCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition(CountNotificationUser::class)) {
throw new LogicException('The service ' . CountNotificationUser::class . ' '
. 'should be defined');
throw new \LogicException('The service '.CountNotificationUser::class.' should be defined');
}
$notificationCounterDefinition = $container->getDefinition(CountNotificationUser::class);

View File

@@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection\CompilerPass;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -26,8 +25,7 @@ class SearchableServicesCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('chill_main.search_provider')) {
throw new LogicException('service chill_main.search_provider '
. 'is not defined.');
throw new \LogicException('service chill_main.search_provider is not defined.');
}
$definition = $container->getDefinition(
@@ -43,13 +41,11 @@ class SearchableServicesCompilerPass implements CompilerPassInterface
foreach ($taggedServices as $id => $tagAttributes) {
foreach ($tagAttributes as $attributes) {
if (!isset($attributes['alias'])) {
throw new LogicException("the 'name' attribute is missing in your " .
"service '{$id}' definition");
throw new \LogicException("the 'name' attribute is missing in your service '{$id}' definition");
}
if (array_search($attributes['alias'], $knownAliases, true)) {
throw new LogicException('There is already a chill.search service with alias '
. $attributes['alias'] . '. Choose another alias.');
throw new \LogicException('There is already a chill.search service with alias '.$attributes['alias'].'. Choose another alias.');
}
$knownAliases[] = $attributes['alias'];

View File

@@ -28,7 +28,6 @@ use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use function array_key_exists;
class ShortMessageCompilerPass implements CompilerPassInterface
{
@@ -43,30 +42,28 @@ class ShortMessageCompilerPass implements CompilerPassInterface
if ('null' === $dsn['scheme'] || false === $config['enabled']) {
$defaultTransporter = new Reference(NullShortMessageSender::class);
} elseif ('ovh' === $dsn['scheme']) {
if (!class_exists('\\' . \Ovh\Api::class)) {
if (!class_exists('\\'.\Ovh\Api::class)) {
throw new RuntimeException('Class \\Ovh\\Api not found');
}
foreach (['user', 'host', 'pass'] as $component) {
if (!array_key_exists($component, $dsn)) {
throw new RuntimeException(sprintf('The component %s does not exist in dsn. Please provide a dsn ' .
'like ovh://applicationKey:applicationSecret@endpoint?consumerKey=xxxx&sender=yyyy&service_name=zzzz', $component));
if (!\array_key_exists($component, $dsn)) {
throw new RuntimeException(sprintf('The component %s does not exist in dsn. Please provide a dsn like ovh://applicationKey:applicationSecret@endpoint?consumerKey=xxxx&sender=yyyy&service_name=zzzz', $component));
}
$container->setParameter('chill_main.short_messages.ovh_config_' . $component, $dsn[$component]);
$container->setParameter('chill_main.short_messages.ovh_config_'.$component, $dsn[$component]);
}
foreach (['consumer_key', 'sender', 'service_name'] as $param) {
if (!array_key_exists($param, $dsn['queries'])) {
throw new RuntimeException(sprintf('The parameter %s does not exist in dsn. Please provide a dsn ' .
'like ovh://applicationKey:applicationSecret@endpoint?consumerKey=xxxx&sender=yyyy&service_name=zzzz', $param));
if (!\array_key_exists($param, $dsn['queries'])) {
throw new RuntimeException(sprintf('The parameter %s does not exist in dsn. Please provide a dsn like ovh://applicationKey:applicationSecret@endpoint?consumerKey=xxxx&sender=yyyy&service_name=zzzz', $param));
}
$container->setParameter('chill_main.short_messages.ovh_config_' . $param, $dsn['queries'][$param]);
$container->setParameter('chill_main.short_messages.ovh_config_'.$param, $dsn['queries'][$param]);
}
$ovh = new Definition();
$ovh
->setClass('\\' . \Ovh\Api::class)
->setClass('\\'.\Ovh\Api::class)
->setArgument(0, $dsn['user'])
->setArgument(1, $dsn['pass'])
->setArgument(2, $dsn['host'])

View File

@@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection\CompilerPass;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -25,8 +24,7 @@ class TimelineCompilerClass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('chill_main.timeline_builder')) {
throw new LogicException('service chill_main.timeline_builder '
. 'is not defined.');
throw new \LogicException('service chill_main.timeline_builder is not defined.');
}
$definition = $container->getDefinition(
@@ -40,8 +38,7 @@ class TimelineCompilerClass implements CompilerPassInterface
foreach ($taggedServices as $id => $tagAttributes) {
foreach ($tagAttributes as $attributes) {
if (!isset($attributes['context'])) {
throw new LogicException("the 'context' attribute is missing in your " .
"service '{$id}' definition");
throw new \LogicException("the 'context' attribute is missing in your service '{$id}' definition");
}
$definition->addMethodCall(

View File

@@ -11,13 +11,9 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection;
use LogicException;
use RuntimeException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use function count;
/**
* Description of ConfigConsistencyCompilerPass.
*/
@@ -42,17 +38,14 @@ class ConfigConsistencyCompilerPass implements CompilerPassInterface
}
}
if (count($fallbackLocales) === 0) {
throw new LogicException('the fallback locale are not defined. '
. 'The framework config should not allow this.');
if (0 === \count($fallbackLocales)) {
throw new \LogicException('the fallback locale are not defined. The framework config should not allow this.');
}
$diff = array_diff($fallbackLocales, $availableLanguages);
if (count($diff) > 0) {
throw new RuntimeException(sprintf('The chill_main.available_languages'
. ' parameter does not contains fallback locales. The languages %s'
. ' are missing.', implode(', ', $diff)));
if (\count($diff) > 0) {
throw new \RuntimeException(sprintf('The chill_main.available_languages parameter does not contains fallback locales. The languages %s are missing.', implode(', ', $diff)));
}
}
}

View File

@@ -176,8 +176,8 @@ class Configuration implements ConfigurationInterface
->scalarNode('path')
->defaultNull()
->info('the path that will be **appended** after the base path. Do not forget to add '
. 'arguments for the method. Will be set to the action name, including an `{id}` '
. 'parameter if left empty.')
.'arguments for the method. Will be set to the action name, including an `{id}` '
.'parameter if left empty.')
->example('/{id}/my-action')
->end()
->arrayNode('requirements')
@@ -216,15 +216,15 @@ class Configuration implements ConfigurationInterface
->children()
->scalarNode('controller_action')
->defaultNull()
->info('the method name to call in the controller. Will be set to the concatenation ' .
->info('the method name to call in the controller. Will be set to the concatenation '.
'of action name + \'Api\' if left empty.')
->example('showApi')
->end()
->scalarNode('path')
->defaultNull()
->info('the path that will be **appended** after the base path. Do not forget to add ' .
'arguments for the method. By default, will set to the action name, including an `{id}` ' .
'parameter. A suffix of action name will be appended, except if the action name ' .
->info('the path that will be **appended** after the base path. Do not forget to add '.
'arguments for the method. By default, will set to the action name, including an `{id}` '.
'parameter. A suffix of action name will be appended, except if the action name '.
'is "_entity".')
->example('/{id}/my-action')
->end()
@@ -235,8 +235,8 @@ class Configuration implements ConfigurationInterface
->enumNode('single_collection')
->values(['single', 'collection'])
->defaultValue('single')
->info('indicates if the returned object is a single element or a collection. ' .
'If the action name is `_index`, this value will always be considered as ' .
->info('indicates if the returned object is a single element or a collection. '.
'If the action name is `_index`, this value will always be considered as '.
'`collection`')
->end()
->arrayNode('methods')

View File

@@ -11,12 +11,10 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection;
use Exception;
/**
* Description of MissingBundleException.
*/
class MissingBundleException extends Exception
class MissingBundleException extends \Exception
{
public function __construct($missingBundleName)
{

View File

@@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\DependencyInjection;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -21,8 +20,7 @@ class RoleProvidersCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('chill.main.role_provider')) {
throw new LogicException('service chill.main.role_provider '
. 'is not defined. It is required by RoleProviderCompilerPass');
throw new \LogicException('service chill.main.role_provider is not defined. It is required by RoleProviderCompilerPass');
}
$definition = $container->getDefinition(

View File

@@ -13,20 +13,11 @@ namespace Chill\MainBundle\DependencyInjection\Widget;
use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface;
use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
use LengthException;
use LogicException;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use UnexpectedValueException;
use function array_key_exists;
use function count;
use function get_class;
use function in_array;
use function is_array;
/**
* Compile the configurations and inject required service into container.
@@ -122,11 +113,11 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
/**
* process the configuration and the container to add the widget available.
*
* @param string $extension the extension of your bundle
* @param string $extension the extension of your bundle
* @param string $containerWidgetConfigParameterName the key under which we can use the widget configuration
*
* @throws LogicException
* @throws UnexpectedValueException if the given extension does not implement HasWidgetExtensionInterface
* @throws \LogicException
* @throws \UnexpectedValueException if the given extension does not implement HasWidgetExtensionInterface
*/
public function doProcess(
ContainerBuilder $container,
@@ -134,8 +125,7 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
$containerWidgetConfigParameterName
) {
if (!$container->hasDefinition(self::WIDGET_MANAGER)) {
throw new LogicException('the service ' . self::WIDGET_MANAGER . ' should' .
' be present. It is required by ' . self::class);
throw new \LogicException('the service '.self::WIDGET_MANAGER.' should be present. It is required by '.self::class);
}
$managerDefinition = $container->getDefinition(self::WIDGET_MANAGER);
@@ -145,14 +135,7 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
$extensionClass = $container->getExtension($extension);
// throw an error if extension does not implement HasWidgetFactoriesExtensionInterface
if (!$extensionClass instanceof HasWidgetFactoriesExtensionInterface) {
throw new UnexpectedValueException(sprintf(
'The extension for %s '
. 'do not implements %s. You should implement %s on %s',
$extension,
HasWidgetFactoriesExtensionInterface::class,
HasWidgetFactoriesExtensionInterface::class,
$extensionClass::class
));
throw new \UnexpectedValueException(sprintf('The extension for %s do not implements %s. You should implement %s on %s', $extension, HasWidgetFactoriesExtensionInterface::class, HasWidgetFactoriesExtensionInterface::class, $extensionClass::class));
}
$this->widgetFactories = $extensionClass->getWidgetFactories();
@@ -168,18 +151,13 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
foreach ($widgets as $param) {
$alias = $param[self::WIDGET_CONFIG_ALIAS];
// check that the service exists
if (!array_key_exists($alias, $this->widgetServices)) {
throw new InvalidConfigurationException(sprintf('The alias %s' .
' is not defined.', $alias));
if (!\array_key_exists($alias, $this->widgetServices)) {
throw new InvalidConfigurationException(sprintf('The alias %s is not defined.', $alias));
}
// check that the widget is allowed at this place
if (!$this->isPlaceAllowedForWidget($place, $alias, $container)) {
throw new InvalidConfigurationException(sprintf(
'The widget with alias %s is not allowed at place %s',
$alias,
$place
));
throw new InvalidConfigurationException(sprintf('The widget with alias %s is not allowed at place %s', $alias, $place));
}
// get the order, eventually corrected
@@ -242,23 +220,17 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
foreach ($attrs as $attr) {
// check the alias is set
if (!isset($attr[self::WIDGET_SERVICE_TAG_ALIAS])) {
throw new InvalidConfigurationException('you should add an ' . self::WIDGET_SERVICE_TAG_ALIAS .
' key on the service ' . $id);
throw new InvalidConfigurationException('you should add an '.self::WIDGET_SERVICE_TAG_ALIAS.' key on the service '.$id);
}
// check the place is set
if (!isset($attr[self::WIDGET_SERVICE_TAG_PLACES])) {
throw new InvalidConfigurationException(sprintf(
'You should add a %s key on the service %s',
self::WIDGET_SERVICE_TAG_PLACES,
$id
));
throw new InvalidConfigurationException(sprintf('You should add a %s key on the service %s', self::WIDGET_SERVICE_TAG_PLACES, $id));
}
// check the alias does not exists yet
if (array_key_exists($attr[self::WIDGET_SERVICE_TAG_ALIAS], $this->widgetServices)) {
throw new InvalidArgumentException('a service has already be defined with the ' .
self::WIDGET_SERVICE_TAG_ALIAS . ' ' . $attr[self::WIDGET_SERVICE_TAG_ALIAS]);
if (\array_key_exists($attr[self::WIDGET_SERVICE_TAG_ALIAS], $this->widgetServices)) {
throw new InvalidArgumentException('a service has already be defined with the '.self::WIDGET_SERVICE_TAG_ALIAS.' '.$attr[self::WIDGET_SERVICE_TAG_ALIAS]);
}
// register the service as available
@@ -273,29 +245,21 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
// check the alias is not empty
if (empty($alias)) {
throw new LogicException(sprintf(
'the widget factory %s returns an empty alias',
$factory::class
));
throw new \LogicException(sprintf('the widget factory %s returns an empty alias', $factory::class));
}
// check the places are not empty
if (!is_array($factory->getAllowedPlaces())) {
throw new UnexpectedValueException("the method 'getAllowedPlaces' "
. 'should return a non-empty array. Unexpected value on ' .
$factory::class);
if (!\is_array($factory->getAllowedPlaces())) {
throw new \UnexpectedValueException("the method 'getAllowedPlaces' ".'should return a non-empty array. Unexpected value on '.$factory::class);
}
if (count($factory->getAllowedPlaces()) === 0) {
throw new LengthException("The method 'getAllowedPlaces' should "
. 'return a non-empty array, but returned 0 elements on ' .
$factory::class . '::getAllowedPlaces()');
if (0 === \count($factory->getAllowedPlaces())) {
throw new \LengthException("The method 'getAllowedPlaces' should ".'return a non-empty array, but returned 0 elements on '.$factory::class.'::getAllowedPlaces()');
}
// check the alias does not exists yet
if (array_key_exists($alias, $this->widgetServices)) {
throw new InvalidArgumentException('a service has already be defined with the ' .
self::WIDGET_SERVICE_TAG_ALIAS . ' ' . $alias);
if (\array_key_exists($alias, $this->widgetServices)) {
throw new InvalidArgumentException('a service has already be defined with the '.self::WIDGET_SERVICE_TAG_ALIAS.' '.$alias);
}
// register the factory as available
@@ -307,7 +271,7 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
* register the service into container.
*
* @param string $place
* @param float $order
* @param float $order
*
* @return string the id of the new service
*/
@@ -338,14 +302,14 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
* recursive method.
*
* @param string $place
* @param float $ordering
* @param float $ordering
*
* @return float
*/
private function cacheAndGetOrdering($place, $ordering)
{
// create a key in the cache array if not exists
if (!array_key_exists($place, $this->cacheOrdering)) {
if (!\array_key_exists($place, $this->cacheOrdering)) {
$this->cacheOrdering[$place] = [];
}
@@ -363,14 +327,13 @@ abstract class AbstractWidgetsCompilerPass implements CompilerPassInterface
/**
* get the places where the service is allowed.
*
*
* @return unknown
*/
private function isPlaceAllowedForWidget(mixed $place, mixed $widgetAlias, ContainerBuilder $container)
{
if ($this->widgetServices[$widgetAlias] instanceof WidgetFactoryInterface) {
if (
in_array($place, $this->widgetServices[$widgetAlias]
\in_array($place, $this->widgetServices[$widgetAlias]
->getAllowedPlaces(), true)
) {
return true;

View File

@@ -16,10 +16,6 @@ use Generator;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use function array_key_exists;
use function count;
use function implode;
use function in_array;
/**
* This trait allow to add automatic configuration for widget inside your config.
@@ -141,10 +137,10 @@ trait AddWidgetConfigurationTrait
$treeBuilder = new TreeBuilder($place);
$root = $treeBuilder->getRootNode()
->canBeUnset()
->info('register widgets on place "' . $place . '"');
->info('register widgets on place "'.$place.'"');
// if no childen, return the root
if (count(iterator_to_array($this->filterWidgetByPlace($place))) === 0) {
if (0 === \count(iterator_to_array($this->filterWidgetByPlace($place)))) {
return $root;
}
@@ -162,8 +158,8 @@ trait AddWidgetConfigurationTrait
// is build, the services are avaialble => we add the possible aliases
// in the info.
->info('the widget alias (see your installed bundles config). '
. 'Possible values are (maybe incomplete) : ' .
implode(', ', $this->getWidgetAliasesbyPlace($place, $containerBuilder)))
.'Possible values are (maybe incomplete) : '.
\implode(', ', $this->getWidgetAliasesbyPlace($place, $containerBuilder)))
->isRequired()
->end();
@@ -188,12 +184,12 @@ trait AddWidgetConfigurationTrait
*
* @param string $place
*
* @return Generator a generator containing a widget factory
* @return \Generator a generator containing a widget factory
*/
protected function filterWidgetByPlace($place)
{
foreach ($this->widgetFactories as $factory) {
if (in_array($place, $factory->getAllowedPlaces(), true)) {
if (\in_array($place, $factory->getAllowedPlaces(), true)) {
yield $factory;
}
}
@@ -209,9 +205,9 @@ trait AddWidgetConfigurationTrait
*
* @param type $place
*
* @throws InvalidConfigurationException if a service's tag does not have the "alias" key
*
* @return array
*
* @throws InvalidConfigurationException if a service's tag does not have the "alias" key
*/
protected function getWidgetAliasesbyPlace($place, ContainerBuilder $containerBuilder)
{
@@ -223,16 +219,11 @@ trait AddWidgetConfigurationTrait
// append the aliases added without factory
foreach ($containerBuilder
->findTaggedServiceIds(WidgetsCompilerPass::WIDGET_SERVICE_TAG_NAME)
as $serviceId => $tags) {
->findTaggedServiceIds(WidgetsCompilerPass::WIDGET_SERVICE_TAG_NAME) as $serviceId => $tags) {
foreach ($tags as $tag) {
// throw an error if no alias in definition
if (!array_key_exists(WidgetsCompilerPass::WIDGET_SERVICE_TAG_ALIAS, $tag)) {
throw new InvalidConfigurationException(sprintf(
'The service with id %s does not have any %d key',
$serviceId,
WidgetsCompilerPass::WIDGET_SERVICE_TAG_ALIAS
));
if (!\array_key_exists(WidgetsCompilerPass::WIDGET_SERVICE_TAG_ALIAS, $tag)) {
throw new InvalidConfigurationException(sprintf('The service with id %s does not have any %d key', $serviceId, WidgetsCompilerPass::WIDGET_SERVICE_TAG_ALIAS));
}
// add the key to the possible results
$result[] = $tag[WidgetsCompilerPass::WIDGET_SERVICE_TAG_ALIAS];

View File

@@ -72,7 +72,7 @@ interface WidgetFactoryInterface
* return the service id to build the widget.
*
* @param string $place
* @param float $order
* @param float $order
*
* @return string the service definition
*/

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\DQL;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\PathExpression;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;

View File

@@ -30,9 +30,9 @@ class Extract extends FunctionNode
private string $field;
private null|\Doctrine\ORM\Query\AST\Node|string $value = null;
//private PathExpression $value;
//private FunctionNode $value;
//private DateDiffFunction $value;
// private PathExpression $value;
// private FunctionNode $value;
// private DateDiffFunction $value;
public function getSql(SqlWalker $sqlWalker)
{
@@ -53,7 +53,7 @@ class Extract extends FunctionNode
$parser->match(Lexer::T_FROM);
//$this->value = $parser->ScalarExpression();
// $this->value = $parser->ScalarExpression();
$this->value = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);

View File

@@ -33,7 +33,7 @@ class Greatest extends FunctionNode
public function getSql(SqlWalker $sqlWalker)
{
return 'GREATEST(' . implode(', ', array_map(static fn (Node $expr) => $expr->dispatch($sqlWalker), $this->exprs)) . ')';
return 'GREATEST('.implode(', ', array_map(static fn (Node $expr) => $expr->dispatch($sqlWalker), $this->exprs)).')';
}
public function parse(Parser $parser)

View File

@@ -32,7 +32,7 @@ class JsonBuildObject extends FunctionNode
public function getSql(SqlWalker $sqlWalker)
{
return 'JSONB_BUILD_OBJECT(' . implode(', ', array_map(static fn (Node $expr) => $expr->dispatch($sqlWalker), $this->exprs)) . ')';
return 'JSONB_BUILD_OBJECT('.implode(', ', array_map(static fn (Node $expr) => $expr->dispatch($sqlWalker), $this->exprs)).')';
}
public function parse(Parser $parser)

View File

@@ -33,7 +33,7 @@ class Least extends FunctionNode
public function getSql(SqlWalker $sqlWalker)
{
return 'LEAST(' . implode(', ', array_map(static fn (Node $expr) => $expr->dispatch($sqlWalker), $this->exprs)) . ')';
return 'LEAST('.implode(', ', array_map(static fn (Node $expr) => $expr->dispatch($sqlWalker), $this->exprs)).')';
}
public function parse(Parser $parser)

View File

@@ -15,7 +15,6 @@ use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\PathExpression;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Exception;
/**
* DQL function for OVERLAPS function in postgresql.
@@ -76,7 +75,7 @@ class OverlapsI extends FunctionNode
$p = match ($position) {
'start' => '-infinity',
'end' => 'infinity',
default => throw new Exception('Unexpected position value.'),
default => throw new \Exception('Unexpected position value.'),
};
if ($part instanceof PathExpression) {

View File

@@ -24,12 +24,12 @@ class Replace extends FunctionNode
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker): string
{
return 'REPLACE(' .
$this->string->dispatch($sqlWalker) .
', ' .
$this->from->dispatch($sqlWalker) .
', ' .
$this->to->dispatch($sqlWalker) .
return 'REPLACE('.
$this->string->dispatch($sqlWalker).
', '.
$this->from->dispatch($sqlWalker).
', '.
$this->to->dispatch($sqlWalker).
')';
}

View File

@@ -25,8 +25,8 @@ class STContains extends FunctionNode
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return 'ST_CONTAINS(' . $this->firstPart->dispatch($sqlWalker) .
', ' . $this->secondPart->dispatch($sqlWalker) . ')';
return 'ST_CONTAINS('.$this->firstPart->dispatch($sqlWalker).
', '.$this->secondPart->dispatch($sqlWalker).')';
}
public function parse(\Doctrine\ORM\Query\Parser $parser)

View File

@@ -22,8 +22,8 @@ class Similarity extends FunctionNode
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return 'SIMILARITY(' . $this->firstPart->dispatch($sqlWalker) .
', ' . $this->secondPart->dispatch($sqlWalker) . ')';
return 'SIMILARITY('.$this->firstPart->dispatch($sqlWalker).
', '.$this->secondPart->dispatch($sqlWalker).')';
}
public function parse(\Doctrine\ORM\Query\Parser $parser)

View File

@@ -23,8 +23,8 @@ class StrictWordSimilarityOPS extends \Doctrine\ORM\Query\AST\Functions\Function
public function getSql(SqlWalker $sqlWalker)
{
return $this->firstPart->dispatch($sqlWalker) .
' <<% ' . $this->secondPart->dispatch($sqlWalker);
return $this->firstPart->dispatch($sqlWalker).
' <<% '.$this->secondPart->dispatch($sqlWalker);
}
public function parse(Parser $parser)

View File

@@ -26,7 +26,7 @@ class Unaccent extends FunctionNode
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return 'UNACCENT(' . $this->string->dispatch($sqlWalker) . ')';
return 'UNACCENT('.$this->string->dispatch($sqlWalker).')';
}
public function parse(\Doctrine\ORM\Query\Parser $parser)

View File

@@ -14,7 +14,6 @@ namespace Chill\MainBundle\Doctrine\Event;
use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
@@ -37,7 +36,7 @@ class TrackCreateUpdateSubscriber implements EventSubscriber
$object = $args->getObject();
if ($object instanceof TrackCreationInterface) {
$object->setCreatedAt(new DateTimeImmutable('now'));
$object->setCreatedAt(new \DateTimeImmutable('now'));
if ($this->security->getUser() instanceof User) {
$object->setCreatedBy($this->security->getUser());
@@ -57,7 +56,7 @@ class TrackCreateUpdateSubscriber implements EventSubscriber
protected function onUpdate(object $object): void
{
if ($object instanceof TrackUpdateInterface) {
$object->setUpdatedAt(new DateTimeImmutable('now'));
$object->setUpdatedAt(new \DateTimeImmutable('now'));
if ($this->security->getUser() instanceof User) {
$object->setUpdatedBy($this->security->getUser());

View File

@@ -14,9 +14,6 @@ namespace Chill\MainBundle\Doctrine\Migrations;
use Doctrine\Migrations\Version\Comparator;
use Doctrine\Migrations\Version\Version;
use function explode;
use function strcmp;
/**
* Compare Version classes names from different namespaces and order them.
*
@@ -26,12 +23,12 @@ final class VersionComparator implements Comparator
{
public function compare(Version $a, Version $b): int
{
return strcmp($this->getNumber($a), $this->getNumber($b));
return \strcmp($this->getNumber($a), $this->getNumber($b));
}
private function getNumber(Version $version): string
{
$names = explode('\\', (string) $version);
$names = \explode('\\', (string) $version);
return end($names);
}

View File

@@ -11,12 +11,7 @@ declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\Model;
use Exception;
use JsonSerializable;
use function json_encode;
class Point implements JsonSerializable
class Point implements \JsonSerializable
{
public static string $SRID = '4326';
@@ -28,7 +23,7 @@ class Point implements JsonSerializable
return self::fromLonLat($array['coordinates'][0], $array['coordinates'][1]);
}
throw new Exception('Unable to build a point from input data.');
throw new \Exception('Unable to build a point from input data.');
}
public static function fromGeoJson(string $geojson): self
@@ -88,7 +83,7 @@ class Point implements JsonSerializable
{
$array = $this->toArrayGeoJson();
return json_encode($array, JSON_THROW_ON_ERROR);
return \json_encode($array, JSON_THROW_ON_ERROR);
}
public function toWKT(): string

View File

@@ -11,12 +11,10 @@ declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\Model;
use Exception;
/**
* Description of PointException.
*/
class PointException extends Exception
class PointException extends \Exception
{
public static function badCoordinates($lon, $lat): self
{

View File

@@ -12,11 +12,10 @@ declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\Model;
use Chill\MainBundle\Entity\User;
use DateTimeInterface;
interface TrackCreationInterface
{
public function setCreatedAt(DateTimeInterface $datetime): self;
public function setCreatedAt(\DateTimeInterface $datetime): self;
public function setCreatedBy(User $user): self;
}

View File

@@ -13,8 +13,6 @@ namespace Chill\MainBundle\Doctrine\Model;
use Chill\MainBundle\Entity\User;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer;
@@ -22,18 +20,21 @@ trait TrackCreationTrait
{
/**
* @ORM\Column(type="datetime_immutable", nullable=true, options={"default": NULL})
*
* @Serializer\Groups({"read"})
*/
private ?DateTimeImmutable $createdAt = null;
private ?\DateTimeImmutable $createdAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=true)
*
* @Serializer\Groups({"read"})
*/
private ?User $createdBy = null;
public function getCreatedAt(): ?DateTimeInterface
public function getCreatedAt(): ?\DateTimeInterface
{
return $this->createdAt;
}
@@ -43,9 +44,9 @@ trait TrackCreationTrait
return $this->createdBy;
}
public function setCreatedAt(DateTimeInterface $datetime): self
public function setCreatedAt(\DateTimeInterface $datetime): self
{
$this->createdAt = $datetime instanceof DateTime ? DateTimeImmutable::createFromMutable($datetime) : $datetime;
$this->createdAt = $datetime instanceof \DateTime ? \DateTimeImmutable::createFromMutable($datetime) : $datetime;
return $this;
}

View File

@@ -12,11 +12,10 @@ declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\Model;
use Chill\MainBundle\Entity\User;
use DateTimeInterface;
interface TrackUpdateInterface
{
public function setUpdatedAt(DateTimeInterface $datetime): self;
public function setUpdatedAt(\DateTimeInterface $datetime): self;
public function setUpdatedBy(User $user): self;
}

View File

@@ -13,8 +13,6 @@ namespace Chill\MainBundle\Doctrine\Model;
use Chill\MainBundle\Entity\User;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer;
@@ -22,18 +20,21 @@ trait TrackUpdateTrait
{
/**
* @ORM\Column(type="datetime_immutable", nullable=true, options={"default": NULL})
*
* @Serializer\Groups({"read"})
*/
private ?DateTimeImmutable $updatedAt = null;
private ?\DateTimeImmutable $updatedAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @ORM\JoinColumn(nullable=true)
*
* @Serializer\Groups({"read"})
*/
private ?User $updatedBy = null;
public function getUpdatedAt(): ?DateTimeInterface
public function getUpdatedAt(): ?\DateTimeInterface
{
return $this->updatedAt;
}
@@ -43,9 +44,9 @@ trait TrackUpdateTrait
return $this->updatedBy;
}
public function setUpdatedAt(DateTimeInterface $datetime): self
public function setUpdatedAt(\DateTimeInterface $datetime): self
{
$this->updatedAt = $datetime instanceof DateTime ? DateTimeImmutable::createFromMutable($datetime) : $datetime;
$this->updatedAt = $datetime instanceof \DateTime ? \DateTimeImmutable::createFromMutable($datetime) : $datetime;
return $this;
}

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\ORM\Hydration;
use Doctrine\ORM\Internal\Hydration\ObjectHydrator;
use Generator;
final class FlatHierarchyEntityHydrator extends ObjectHydrator
{
@@ -40,7 +39,7 @@ final class FlatHierarchyEntityHydrator extends ObjectHydrator
);
}
private function flatListGenerator(array $hashMap, ?object $parent = null): Generator
private function flatListGenerator(array $hashMap, object $parent = null): \Generator
{
$parent = null === $parent ? null : spl_object_id($parent);
$hashMap += [$parent => []];

View File

@@ -11,17 +11,9 @@ declare(strict_types=1);
namespace Chill\MainBundle\Doctrine\Type;
use DateInterval;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateIntervalType;
use Exception;
use LogicException;
use function count;
use function current;
use function preg_match;
use function reset;
/**
* Re-declare the date interval to use the implementation of date interval in
@@ -37,7 +29,7 @@ class NativeDateIntervalType extends DateIntervalType
return null;
}
if ($value instanceof DateInterval) {
if ($value instanceof \DateInterval) {
return $value->format(self::FORMAT);
}
@@ -46,25 +38,25 @@ class NativeDateIntervalType extends DateIntervalType
public function convertToPHPValue($value, AbstractPlatform $platform)
{
if (null === $value || $value instanceof DateInterval) {
if (null === $value || $value instanceof \DateInterval) {
return $value;
}
try {
$strings = explode(' ', (string) $value);
if (count($strings) === 0) {
if (1 === count($strings) && ('' === $strings[0])) {
return null;
}
$intervalSpec = 'P';
reset($strings);
\reset($strings);
do {
$intervalSpec .= $this->convertEntry($strings);
} while (next($strings) !== false);
} while (false !== next($strings));
return new DateInterval($intervalSpec);
} catch (Exception $exception) {
return new \DateInterval($intervalSpec);
} catch (\Exception $exception) {
throw $this->createConversionException($value, $exception);
}
}
@@ -86,7 +78,7 @@ class NativeDateIntervalType extends DateIntervalType
private function convertEntry(&$strings)
{
$current = current($strings);
$current = \current($strings);
if (is_numeric($current)) {
$next = next($strings);
@@ -98,19 +90,19 @@ class NativeDateIntervalType extends DateIntervalType
default => throw $this->createConversionException(implode('', $strings)),
};
return $current . $unit;
return $current.$unit;
}
if (preg_match('/([0-9]{2}\:[0-9]{2}:[0-9]{2})/', (string) $current) === 1) {
if (1 === \preg_match('/([0-9]{2}\:[0-9]{2}:[0-9]{2})/', (string) $current)) {
$tExploded = explode(':', (string) $current);
$intervalSpec = 'T';
$intervalSpec .= $tExploded[0] . 'H';
$intervalSpec .= $tExploded[1] . 'M';
$intervalSpec .= $tExploded[2] . 'S';
$intervalSpec .= $tExploded[0].'H';
$intervalSpec .= $tExploded[1].'M';
$intervalSpec .= $tExploded[2].'S';
return $intervalSpec;
}
throw new LogicException();
throw new \LogicException();
}
}

View File

@@ -42,10 +42,7 @@ class PointType extends Type
return $sqlExpr;
}
/**
* @param mixed $value
*/
public function convertToPHPValue($value, AbstractPlatform $platform): ?\Chill\MainBundle\Doctrine\Model\Point
public function convertToPHPValue($value, AbstractPlatform $platform): ?Point
{
if (null === $value) {
return null;
@@ -56,7 +53,7 @@ class PointType extends Type
public function convertToPHPValueSQL($sqlExpr, $platform)
{
return 'ST_AsGeoJSON(' . $sqlExpr . ') ';
return 'ST_AsGeoJSON('.$sqlExpr.') ';
}
public function getName()
@@ -69,6 +66,6 @@ class PointType extends Type
*/
public function getSQLDeclaration(array $column, AbstractPlatform $platform)
{
return 'geometry(POINT,' . Point::$SRID . ')';
return 'geometry(POINT,'.Point::$SRID.')';
}
}

View File

@@ -18,7 +18,6 @@ use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateTrait;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
use DateTime;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@@ -29,7 +28,9 @@ use Symfony\Component\Validator\Context\ExecutionContextInterface;
* Address.
*
* @ORM\Entity
*
* @ORM\Table(name="chill_main_address")
*
* @ORM\HasLifecycleCallbacks
*/
class Address implements TrackCreationInterface, TrackUpdateInterface
@@ -38,68 +39,76 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
use TrackUpdateTrait;
/**
* When an Address does match with the AddressReference
* When an Address does match with the AddressReference.
*/
final public const ADDR_REFERENCE_STATUS_MATCH = 'match';
/**
* When an Address does not match with the AddressReference, and
* is pending for a review
* is pending for a review.
*/
final public const ADDR_REFERENCE_STATUS_TO_REVIEW = 'to_review';
/**
* When an Address does not match with the AddressReference, but
* is reviewed
* is reviewed.
*/
final public const ADDR_REFERENCE_STATUS_REVIEWED = 'reviewed';
/**
* @ORM\ManyToOne(targetEntity=AddressReference::class)
*
* @Groups({"write"})
*/
private ?AddressReference $addressReference = null;
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $buildingName = '';
/**
* @ORM\Column(type="boolean", options={"default": false})
*
* @Groups({"write"})
*/
private bool $confidential = false;
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $corridor = '';
/**
* used for the CEDEX information
* used for the CEDEX information.
*
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $distribution = '';
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $extra = '';
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $flat = '';
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $floor = '';
@@ -111,8 +120,11 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
* on the materialized view.
*
* @var Collection<GeographicalUnit>
*
* @readonly
*
* @ORM\ManyToMany(targetEntity=GeographicalUnit::class)
*
* @ORM\JoinTable(
* name="view_chill_main_address_geographical_unit",
* joinColumns={@ORM\JoinColumn(name="address_id")},
@@ -122,12 +134,14 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
private Collection $geographicalUnits;
/**
* @var int
*
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*
* @Groups({"write"})
*
* @readonly
*/
private ?int $id = null;
@@ -136,6 +150,7 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
* True if the address is a "no address", aka homeless person, ...
*
* @Groups({"write"})
*
* @ORM\Column(type="boolean", options={"default": false})
*/
private bool $isNoAddress = false;
@@ -143,10 +158,10 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
/**
* A ThirdParty reference for person's addresses that are linked to a third party.
*
* @var ThirdParty|null
*
* @ORM\ManyToOne(targetEntity="Chill\ThirdPartyBundle\Entity\ThirdParty")
*
* @Groups({"write"})
*
* @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private ?ThirdParty $linkedToThirdParty = null;
@@ -154,22 +169,24 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
/**
* A geospatial field storing the coordinates of the Address.
*
* @var Point|null
*
* @ORM\Column(type="point", nullable=true)
*
* @Groups({"write"})
*/
private ?Point $point = null;
/**
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode")
*
* @ORM\JoinColumn(nullable=false)
*
* @Groups({"write"})
*/
private ?PostalCode $postcode = null;
/**
* @var self::ADDR_REFERENCE_STATUS_*
*
* @ORM\Column(type="text", nullable=false, options={"default": self::ADDR_REFERENCE_STATUS_MATCH})
*/
private string $refStatus = self::ADDR_REFERENCE_STATUS_MATCH;
@@ -180,22 +197,22 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
private \DateTimeImmutable $refStatusLastUpdate;
/**
*
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $steps = '';
/**
*
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $street = '';
/**
*
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Groups({"write"})
*/
private string $streetNumber = '';
@@ -205,22 +222,24 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
* of address. By default, the current date.
*
* @ORM\Column(type="date")
*
* @Groups({"write"})
*/
private DateTime $validFrom;
private \DateTime $validFrom;
/**
* Indicates when the address ends. Used to build an history
* of address.
*
* @ORM\Column(type="date", nullable=true)
*
* @Groups({"write"})
*/
private ?DateTime $validTo = null;
private ?\DateTime $validTo = null;
public function __construct()
{
$this->validFrom = new DateTime();
$this->validFrom = new \DateTime();
$this->refStatusLastUpdate = new \DateTimeImmutable('now');
$this->geographicalUnits = new ArrayCollection();
}
@@ -376,6 +395,7 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
* Get streetAddress1 (legacy function).
*
* @return string
*
* @deprecated
*/
public function getStreetAddress1()
@@ -387,6 +407,7 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
* Get streetAddress2 (legacy function).
*
* @return string
*
* @deprecated
*/
public function getStreetAddress2()
@@ -399,12 +420,12 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
return $this->streetNumber;
}
public function getValidFrom(): DateTime
public function getValidFrom(): \DateTime
{
return $this->validFrom;
}
public function getValidTo(): ?DateTimeInterface
public function getValidTo(): ?\DateTimeInterface
{
return $this->validTo;
}
@@ -419,7 +440,7 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
return $this->getIsNoAddress();
}
public function setAddressReference(?AddressReference $addressReference = null): Address
public function setAddressReference(AddressReference $addressReference = null): Address
{
$this->addressReference = $addressReference;
@@ -506,11 +527,9 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
/**
* Set postcode.
*
* @param PostalCode $postcode
*
* @return Address
*/
public function setPostcode(?PostalCode $postcode = null)
public function setPostcode(PostalCode $postcode = null)
{
$this->postcode = $postcode;
@@ -518,14 +537,15 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
}
/**
* Update the ref status
* Update the ref status.
*
* <<<<<<< HEAD
*
* @param Address::ADDR_REFERENCE_STATUS_* $refStatus
* @param bool|null $updateLastUpdate Also update the "refStatusLastUpdate"
* =======
* The refstatuslast update is also updated
* >>>>>>> 31152616d (Feature: Provide api endpoint for reviewing addresses)
* @param bool|null $updateLastUpdate Also update the "refStatusLastUpdate"
* =======
* The refstatuslast update is also updated
* >>>>>>> 31152616d (Feature: Provide api endpoint for reviewing addresses)
*/
public function setRefStatus(string $refStatus, ?bool $updateLastUpdate = true): self
{
@@ -562,8 +582,6 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
/**
* Set streetAddress1 (legacy function).
*
* @param string $streetAddress1
*
* @deprecated
*/
public function setStreetAddress1(?string $streetAddress1): self
@@ -576,7 +594,6 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
/**
* Set streetAddress2 (legacy function).
*
* @param string $streetAddress2
* @deprecated
*/
public function setStreetAddress2(?string $streetAddress2): self
@@ -596,14 +613,14 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
/**
* @return Address
*/
public function setValidFrom(DateTime $validFrom)
public function setValidFrom(\DateTime $validFrom)
{
$this->validFrom = $validFrom;
return $this;
}
public function setValidTo(?DateTimeInterface $validTo = null): self
public function setValidTo(\DateTimeInterface $validTo = null): self
{
$this->validTo = $validTo;
@@ -624,7 +641,7 @@ class Address implements TrackCreationInterface, TrackUpdateInterface
*/
public function validate(ExecutionContextInterface $context, $payload)
{
if (!$this->getValidFrom() instanceof DateTime) {
if (!$this->getValidFrom() instanceof \DateTime) {
$context
->buildViolation('address.date-should-be-set')
->atPath('validFrom')

View File

@@ -12,18 +12,21 @@ declare(strict_types=1);
namespace Chill\MainBundle\Entity;
use Chill\MainBundle\Doctrine\Model\Point;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_main_address_reference", indexes={
*
* @ORM\Index(name="address_refid", columns={"refId"})
* },
* uniqueConstraints={
*
* @ORM\UniqueConstraint(name="chill_main_address_reference_unicity", columns={"refId", "source"})
* })
*
* @ORM\HasLifecycleCallbacks
*/
class AddressReference
@@ -39,26 +42,32 @@ class AddressReference
/**
* @ORM\Column(type="datetime_immutable", nullable=true)
*
* @groups({"read"})
*/
private ?DateTimeImmutable $createdAt = null;
private ?\DateTimeImmutable $createdAt = null;
/**
* @ORM\Column(type="datetime_immutable", nullable=true)
*
* @groups({"read"})
*/
private ?DateTimeImmutable $deletedAt = null;
private ?\DateTimeImmutable $deletedAt = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @groups({"read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @groups({"read"})
*/
private string $municipalityCode = '';
@@ -66,57 +75,60 @@ class AddressReference
/**
* A geospatial field storing the coordinates of the Address.
*
* @var Point
*
* @ORM\Column(type="point")
*
* @groups({"read"})
*/
private ?Point $point = null;
/**
* @var PostalCode
*
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode")
*
* @groups({"read"})
*/
private ?PostalCode $postcode = null;
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @groups({"read"})
*/
private string $refId = '';
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @groups({"read"})
*/
private string $source = '';
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @groups({"read"})
*/
private string $street = '';
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @groups({"read"})
*/
private string $streetNumber = '';
/**
* @ORM\Column(type="datetime_immutable", nullable=true)
*
* @groups({"read"})
*/
private ?DateTimeImmutable $updatedAt = null;
private ?\DateTimeImmutable $updatedAt = null;
public function getCreatedAt(): ?DateTimeImmutable
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function getDeletedAt(): ?DateTimeImmutable
public function getDeletedAt(): ?\DateTimeImmutable
{
return $this->deletedAt;
}
@@ -138,8 +150,6 @@ class AddressReference
/**
* Get postcode.
*
* @return PostalCode
*/
public function getPostcode(): ?PostalCode
{
@@ -166,7 +176,7 @@ class AddressReference
return $this->streetNumber;
}
public function getUpdatedAt(): ?DateTimeImmutable
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
@@ -176,14 +186,14 @@ class AddressReference
return null !== $this->getPoint();
}
public function setCreatedAt(?DateTimeImmutable $createdAt): self
public function setCreatedAt(?\DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
public function setDeletedAt(?DateTimeImmutable $deletedAt): self
public function setDeletedAt(?\DateTimeImmutable $deletedAt): self
{
$this->deletedAt = $deletedAt;
@@ -207,11 +217,9 @@ class AddressReference
/**
* Set postcode.
*
* @param PostalCode $postcode
*
* @return Address
*/
public function setPostcode(?PostalCode $postcode = null)
public function setPostcode(PostalCode $postcode = null)
{
$this->postcode = $postcode;
@@ -246,7 +254,7 @@ class AddressReference
return $this;
}
public function setUpdatedAt(?DateTimeImmutable $updatedAt): self
public function setUpdatedAt(?\DateTimeImmutable $updatedAt): self
{
$this->updatedAt = $updatedAt;

View File

@@ -18,6 +18,7 @@ use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Entity
*
* @ORM\Table(name="centers")
*/
class Center implements HasCenterInterface, \Stringable
@@ -33,17 +34,19 @@ class Center implements HasCenterInterface, \Stringable
private Collection $groupCenters;
/**
* @var int
*
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*
* @Serializer\Groups({"docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="string", length=255)
*
* @Serializer\Groups({"docgen:read"})
*/
private string $name = '';
@@ -55,6 +58,7 @@ class Center implements HasCenterInterface, \Stringable
/**
* @var Collection<Regroupment>
*
* @ORM\ManyToMany(targetEntity=Regroupment::class, mappedBy="centers")
*/
private Collection $regroupments;
@@ -68,9 +72,6 @@ class Center implements HasCenterInterface, \Stringable
$this->regroupments = new ArrayCollection();
}
/**
* @return string
*/
public function __toString(): string
{
return $this->getName();
@@ -94,10 +95,7 @@ class Center implements HasCenterInterface, \Stringable
return $this;
}
/**
* @return ArrayCollection|Collection
*/
public function getGroupCenters(): \Doctrine\Common\Collections\ArrayCollection|\Doctrine\Common\Collections\Collection
public function getGroupCenters(): ArrayCollection|Collection
{
return $this->groupCenters;
}
@@ -132,8 +130,6 @@ class Center implements HasCenterInterface, \Stringable
}
/**
* @param $name
*
* @return $this
*/
public function setName($name)

View File

@@ -16,35 +16,45 @@ use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Table(name="chill_main_civility")
*
* @ORM\Entity
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={"chill_main_civility": Civility::class})
*/
class Civility
{
/**
* @ORM\Column(type="json")
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Serializer\Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $abbreviation = [];
/**
* @ORM\Column(type="boolean")
*
* @Serializer\Groups({"read"})
*/
private bool $active = true;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="json")
*
* @Serializer\Groups({"read", "docgen:read"})
*
* @Serializer\Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $name = [];

View File

@@ -19,25 +19,31 @@ use Symfony\Component\Serializer\Annotation\Groups;
* Country.
*
* @ORM\Entity
*
* @ORM\Table(name="country")
*
* @ORM\Cache(usage="READ_ONLY", region="country_cache_region")
*
* @ORM\HasLifecycleCallbacks
*/
class Country
{
/**
* @ORM\Column(type="string", length=3)
*
* @groups({"read", "docgen:read"})
*
* @Context({"is-translatable": true}, groups={"docgen:read"})
*/
private string $countryCode = '';
/**
* @var int
*
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*
* @groups({"read", "docgen:read"})
*/
private ?int $id = null;
@@ -46,7 +52,9 @@ class Country
* @var array<string, string>
*
* @ORM\Column(type="json")
*
* @groups({"read", "docgen:read"})
*
* @Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $name = [];
@@ -63,7 +71,6 @@ class Country
/**
* Get name.
*
*/
public function getName(): array
{

View File

@@ -11,11 +11,11 @@ declare(strict_types=1);
namespace Chill\MainBundle\Entity;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*
* @ORM\Table(name="chill_main_cronjob_execution")
*/
class CronJobExecution
@@ -27,12 +27,12 @@ class CronJobExecution
/**
* @ORM\Column(type="datetime_immutable", nullable=true, options={"default": null})
*/
private ?DateTimeImmutable $lastEnd = null;
private ?\DateTimeImmutable $lastEnd = null;
/**
* @ORM\Column(type="datetime_immutable", nullable=false)
*/
private DateTimeImmutable $lastStart;
private \DateTimeImmutable $lastStart;
/**
* @ORM\Column(type="integer", nullable=true, options={"default": null})
@@ -46,11 +46,12 @@ class CronJobExecution
public function __construct(/**
* @ORM\Column(type="text", nullable=false)
*
* @ORM\Id
*/
private string $key
) {
$this->lastStart = new DateTimeImmutable('now');
$this->lastStart = new \DateTimeImmutable('now');
}
public function getKey(): string
@@ -58,12 +59,12 @@ class CronJobExecution
return $this->key;
}
public function getLastEnd(): DateTimeImmutable
public function getLastEnd(): \DateTimeImmutable
{
return $this->lastEnd;
}
public function getLastStart(): DateTimeImmutable
public function getLastStart(): \DateTimeImmutable
{
return $this->lastStart;
}
@@ -73,14 +74,14 @@ class CronJobExecution
return $this->lastStatus;
}
public function setLastEnd(?DateTimeImmutable $lastEnd): CronJobExecution
public function setLastEnd(?\DateTimeImmutable $lastEnd): CronJobExecution
{
$this->lastEnd = $lastEnd;
return $this;
}
public function setLastStart(DateTimeImmutable $lastStart): CronJobExecution
public function setLastStart(\DateTimeImmutable $lastStart): CronJobExecution
{
$this->lastStart = $lastStart;

View File

@@ -32,7 +32,6 @@ class CommentEmbeddable
/**
* Embeddable does not support associations.
*
* @var int
* @ORM\Column(type="integer", nullable=true)
*/
private ?int $userId = null;
@@ -43,7 +42,7 @@ class CommentEmbeddable
}
/**
* @return DateTime
* @return \DateTime
*/
public function getDate()
{
@@ -65,10 +64,7 @@ class CommentEmbeddable
$this->comment = $comment;
}
/**
* @param DateTime $date
*/
public function setDate(?DateTime $date)
public function setDate(?\DateTime $date)
{
$this->date = $date;
}

View File

@@ -13,7 +13,6 @@ namespace Chill\MainBundle\Entity\Embeddable;
use Chill\MainBundle\Entity\User;
use Doctrine\ORM\Mapping as ORM;
use function array_key_exists;
/**
* @ORM\Embeddable
@@ -39,7 +38,7 @@ class PrivateCommentEmbeddable
public function hasCommentForUser(User $user): bool
{
return array_key_exists($user->getId(), $this->comments)
return \array_key_exists($user->getId(), $this->comments)
&& '' !== $this->comments[$user->getId()];
}

View File

@@ -15,8 +15,10 @@ use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="chill_main_geographical_unit", uniqueConstraints={
*
* @ORM\UniqueConstraint(name="geographical_unit_refid", columns={"layer_id", "unitRefId"})
* })
*
* @ORM\Entity(readOnly=true)
*/
class GeographicalUnit
@@ -28,7 +30,9 @@ class GeographicalUnit
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*/
private ?int $id = null;

View File

@@ -23,25 +23,33 @@ class SimpleGeographicalUnitDTO
public function __construct(
/**
* @readonly
*
* @psalm-readonly
*
* @Serializer\Groups({"read"})
*/
public int $id,
/**
* @readonly
*
* @psalm-readonly
*
* @Serializer\Groups({"read"})
*/
public string $unitName,
/**
* @readonly
*
* @psalm-readonly
*
* @Serializer\Groups({"read"})
*/
public string $unitRefId,
/**
* @readonly
*
* @psalm-readonly
*
* @Serializer\Groups({"read"})
*/
public int $layerId

View File

@@ -18,34 +18,42 @@ use Symfony\Component\Serializer\Annotation as Serializer;
/**
* @ORM\Table(name="chill_main_geographical_unit_layer", uniqueConstraints={
*
* @ORM\UniqueConstraint(name="geographical_unit_layer_refid", columns={"refId"})
* })
*
* @ORM\Entity
*/
class GeographicalUnitLayer
{
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read"})
*/
private ?int $id = null;
/**
* @ORM\Column(type="json", nullable=false, options={"default": "[]"})
*
* @Serializer\Groups({"read"})
*/
private array $name = [];
/**
* @ORM\Column(type="text", nullable=false, options={"default": ""})
*
* @Serializer\Groups({"read"})
*/
private string $refId = '';
/**
* @var Collection<GeographicalUnit>
*
* @ORM\OneToMany(targetEntity=GeographicalUnit::class, mappedBy="layer")
*/
private Collection $units;

View File

@@ -17,27 +17,28 @@ use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*
* @ORM\Table(name="group_centers")
*
* @ORM\Cache(usage="NONSTRICT_READ_WRITE", region="acl_cache_region")
*/
class GroupCenter
{
/**
* @var Center
*
* @ORM\ManyToOne(
* targetEntity="Chill\MainBundle\Entity\Center",
* inversedBy="groupCenters"
* )
*
* @ORM\Cache(usage="NONSTRICT_READ_WRITE")
*/
private ?Center $center = null;
/**
* @var int
*
* @ORM\Id
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\GeneratedValue(strategy="AUTO")
*/
private ?int $id = null;
@@ -46,6 +47,7 @@ class GroupCenter
* @ORM\ManyToOne(
* targetEntity="Chill\MainBundle\Entity\PermissionsGroup",
* inversedBy="groupCenters")
*
* @ORM\Cache(usage="NONSTRICT_READ_WRITE")
*/
private ?PermissionsGroup $permissionsGroup = null;
@@ -55,6 +57,7 @@ class GroupCenter
* targetEntity="Chill\MainBundle\Entity\User",
* mappedBy="groupCenters"
* )
*
* @var Collection<User::class>
*/
private Collection $users;

View File

@@ -18,17 +18,20 @@ use Symfony\Component\Serializer\Annotation as Serializer;
* Language.
*
* @ORM\Entity
*
* @ORM\Table(name="language")
*
* @ORM\Cache(usage="READ_ONLY", region="language_cache_region")
*
* @ORM\HasLifecycleCallbacks
*/
class Language
{
/**
* @var string
*
* @ORM\Id
*
* @ORM\Column(type="string")
*
* @Serializer\Groups({"docgen:read"})
*/
private ?string $id = null;
@@ -37,7 +40,9 @@ class Language
* @var string array
*
* @ORM\Column(type="json")
*
* @Serializer\Groups({"docgen:read"})
*
* @Serializer\Context({"is-translatable": true}, groups={"docgen:read"})
*/
private array $name = [];

View File

@@ -15,8 +15,6 @@ use Chill\MainBundle\Doctrine\Model\TrackCreationInterface;
use Chill\MainBundle\Doctrine\Model\TrackUpdateInterface;
use Chill\MainBundle\Repository\LocationRepository;
use Chill\MainBundle\Validation\Constraint\PhonenumberConstraint;
use DateTimeImmutable;
use DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use libphonenumber\PhoneNumber;
use Symfony\Component\Serializer\Annotation as Serializer;
@@ -24,7 +22,9 @@ use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
/**
* @ORM\Table(name="chill_main_location")
*
* @ORM\Entity(repositoryClass=LocationRepository::class)
*
* @DiscriminatorMap(typeProperty="type", mapping={
* "location": Location::class
* })
@@ -33,84 +33,103 @@ class Location implements TrackCreationInterface, TrackUpdateInterface
{
/**
* @ORM\Column(type="boolean", nullable=true)
*
* @Serializer\Groups({"read"})
*/
private bool $active = true;
/**
* @ORM\ManyToOne(targetEntity=Address::class, cascade={"persist"})
*
* @ORM\JoinColumn(nullable=true)
*
* @Serializer\Groups({"read", "write", "docgen:read"})
*/
private ?Address $address = null;
/**
* @ORM\Column(type="boolean")
*
* @Serializer\Groups({"read"})
*/
private bool $availableForUsers = false;
/**
* @ORM\Column(type="datetime_immutable", nullable=true)
*
* @Serializer\Groups({"read"})
*/
private ?DateTimeImmutable $createdAt = null;
private ?\DateTimeImmutable $createdAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @Serializer\Groups({"read"})
*/
private ?User $createdBy = null;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*
* @Serializer\Groups({"read", "write", "docgen:read"})
*/
private ?string $email = null;
/**
* @ORM\Id
*
* @ORM\GeneratedValue
*
* @ORM\Column(type="integer")
*
* @Serializer\Groups({"read", "docgen:read"})
*/
private ?int $id = null;
/**
* @ORM\ManyToOne(targetEntity=LocationType::class)
*
* @ORM\JoinColumn(nullable=false)
*
* @Serializer\Groups({"read", "write", "docgen:read"})
*/
private ?LocationType $locationType = null;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*
* @Serializer\Groups({"read", "write", "docgen:read"})
*/
private ?string $name = null;
/**
* @ORM\Column(type="phone_number", nullable=true)
*
* @Serializer\Groups({"read", "write", "docgen:read"})
*
* @PhonenumberConstraint(type="any")
*/
private ?PhoneNumber $phonenumber1 = null;
/**
* @ORM\Column(type="phone_number", nullable=true)
*
* @Serializer\Groups({"read", "write", "docgen:read"})
*
* @PhonenumberConstraint(type="any")
*/
private ?PhoneNumber $phonenumber2 = null;
/**
* @ORM\Column(type="datetime_immutable", nullable=true)
*
* @Serializer\Groups({"read"})
*/
private ?DateTimeImmutable $updatedAt = null;
private ?\DateTimeImmutable $updatedAt = null;
/**
* @ORM\ManyToOne(targetEntity=User::class)
*
* @Serializer\Groups({"read"})
*/
private ?User $updatedBy = null;
@@ -130,7 +149,7 @@ class Location implements TrackCreationInterface, TrackUpdateInterface
return $this->availableForUsers;
}
public function getCreatedAt(): ?DateTimeImmutable
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
@@ -170,7 +189,7 @@ class Location implements TrackCreationInterface, TrackUpdateInterface
return $this->phonenumber2;
}
public function getUpdatedAt(): ?DateTimeImmutable
public function getUpdatedAt(): ?\DateTimeImmutable
{
return $this->updatedAt;
}
@@ -206,7 +225,7 @@ class Location implements TrackCreationInterface, TrackUpdateInterface
return $this;
}
public function setCreatedAt(?DateTimeInterface $createdAt): self
public function setCreatedAt(?\DateTimeInterface $createdAt): self
{
$this->createdAt = $createdAt;
@@ -255,7 +274,7 @@ class Location implements TrackCreationInterface, TrackUpdateInterface
return $this;
}
public function setUpdatedAt(?DateTimeInterface $updatedAt): self
public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;

Some files were not shown because too many files have changed in this diff Show More