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

@@ -29,7 +29,6 @@ use Chill\TaskBundle\Repository\SingleTaskAclAwareRepositoryInterface;
use Chill\TaskBundle\Repository\SingleTaskRepository;
use Chill\TaskBundle\Repository\SingleTaskStateRepository;
use Chill\TaskBundle\Security\Authorization\TaskVoter;
use LogicException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
@@ -41,12 +40,8 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_map;
use function array_merge;
final class SingleTaskController extends AbstractController
{
public function __construct(
@@ -78,7 +73,7 @@ final class SingleTaskController extends AbstractController
throw $this->createNotFoundException('Unable to find Task entity.');
}
if ($task->getPerson() !== null) {
if (null !== $task->getPerson()) {
$personId = $task->getPerson()->getId();
if (null === $personId) {
@@ -115,7 +110,7 @@ final class SingleTaskController extends AbstractController
$form = $this->createDeleteForm($id);
if ($request->getMethod() === Request::METHOD_DELETE) {
if (Request::METHOD_DELETE === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
@@ -174,7 +169,7 @@ final class SingleTaskController extends AbstractController
Request $request
) {
$this->denyAccessUnlessGranted(TaskVoter::UPDATE, $task, 'You are not '
. 'allowed to edit this task');
.'allowed to edit this task');
$event = (new UIEvent('single-task', $task))
->setForm($this->setCreateForm($task, TaskVoter::UPDATE));
@@ -275,9 +270,9 @@ final class SingleTaskController extends AbstractController
$filteredUsers = $filterOrder->getUserPickerData('userPicker');
$flags = array_merge(
$flags = \array_merge(
$filterOrder->getCheckboxData('status'),
array_map(static fn ($i) => 'state_' . $i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
\array_map(static fn ($i) => 'state_'.$i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
);
if ($showMissionTypeFilter) {
@@ -329,9 +324,9 @@ final class SingleTaskController extends AbstractController
$this->denyAccessUnlessGranted(TaskVoter::SHOW, $course);
$filterOrder = $this->buildFilterOrder();
$flags = array_merge(
$flags = \array_merge(
$filterOrder->getCheckboxData('status'),
array_map(static fn ($i) => 'state_' . $i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
\array_map(static fn ($i) => 'state_'.$i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
);
$nb = $this->singleTaskAclAwareRepository->countByCourse(
$course,
@@ -378,9 +373,9 @@ final class SingleTaskController extends AbstractController
$this->denyAccessUnlessGranted(TaskVoter::SHOW, $person);
$filterOrder = $this->buildFilterOrder();
$flags = array_merge(
$flags = \array_merge(
$filterOrder->getCheckboxData('status'),
array_map(static fn ($i) => 'state_' . $i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
\array_map(static fn ($i) => 'state_'.$i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
);
$nb = $this->singleTaskAclAwareRepository->countByPerson(
$person,
@@ -418,6 +413,7 @@ final class SingleTaskController extends AbstractController
/**
* @return Response
*
* @Route(
* "/{_locale}/task/single-task/list/my",
* name="chill_task_singletask_my_tasks",
@@ -433,9 +429,9 @@ final class SingleTaskController extends AbstractController
$this->denyAccessUnlessGranted('ROLE_USER');
$filterOrder = $this->buildFilterOrder(false);
$flags = array_merge(
$flags = \array_merge(
$filterOrder->getCheckboxData('status'),
array_map(static fn ($i) => 'state_' . $i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
\array_map(static fn ($i) => 'state_'.$i, $filterOrder->hasCheckboxData('states') ? $filterOrder->getCheckboxData('states') : [])
);
$nb = $this->singleTaskAclAwareRepository->countByCurrentUsersTasks(
$filterOrder->getQueryString(),
@@ -541,7 +537,7 @@ final class SingleTaskController extends AbstractController
}
$this->denyAccessUnlessGranted($role, $task, 'You are not '
. 'allowed to create this task');
.'allowed to create this task');
$form = $this->setCreateForm($task, $role);
@@ -589,7 +585,7 @@ final class SingleTaskController extends AbstractController
'task' => $task,
'accompanyingCourse' => $task->getCourse(),
]),
default => throw new LogicException('entity context not supported'),
default => throw new \LogicException('entity context not supported'),
};
}
@@ -673,7 +669,7 @@ final class SingleTaskController extends AbstractController
if ($includeMissionType) {
$filterBuilder->addCheckbox(
'missionTypePicker',
array_map(
\array_map(
fn ($row) => $row['type'],
$this->singleTaskRepository->findAllTaskDistinctTypes()
)

View File

@@ -25,7 +25,6 @@ use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\Transition;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_filter;
use function array_values;
@@ -43,7 +42,7 @@ class TaskController extends AbstractController
* )
*
* @param string $kind
* @param int $taskId
* @param int $taskId
* @param string $transition
*
* @return Response
@@ -70,7 +69,7 @@ class TaskController extends AbstractController
'list_params' => $request->query->get('list_params', []),
]
);
$task->getCourse() === null ? $defaultTemplate = '@ChillTask/SingleTask/Person/transition.html.twig' : $defaultTemplate = '@ChillTask/SingleTask/AccompanyingCourse/transition.html.twig';
null === $task->getCourse() ? $defaultTemplate = '@ChillTask/SingleTask/Person/transition.html.twig' : $defaultTemplate = '@ChillTask/SingleTask/AccompanyingCourse/transition.html.twig';
break;
@@ -82,8 +81,7 @@ class TaskController extends AbstractController
}
if (null === $task) {
throw $this->createNotFoundException("task with id '{$taskId}' and type "
. "'{$kind}' does not exists");
throw $this->createNotFoundException("task with id '{$taskId}' and type '{$kind}' does not exists");
}
$workflow = $registry->get($task);
@@ -91,8 +89,8 @@ class TaskController extends AbstractController
if (!$workflow->can($task, $transition)) {
throw $this->createAccessDeniedException('You are not allowed to apply this transition');
}
$transitionInstance = array_values( // array_values needed to reset keys (array_filter preserves keys)
array_filter(
$transitionInstance = \array_values( // array_values needed to reset keys (array_filter preserves keys)
\array_filter(
$workflow->getEnabledTransitions($task),
static fn (Transition $t) => $t->getName() === $transition
)

View File

@@ -19,8 +19,6 @@ use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use function in_array;
/**
* Add a role UPDATE & CREATE for all groups except administrative,
* and a role SEE for administrative.
@@ -39,10 +37,10 @@ class LoadTaskACL extends AbstractFixture implements OrderedFixtureInterface
foreach (LoadScopes::$references as $scopeRef) {
$scope = $this->getReference($scopeRef);
//create permission group
// create permission group
switch ($permissionsGroup->getName()) {
case 'social':
if ($scope->getName()['en'] === 'administrative') {
if ('administrative' === $scope->getName()['en']) {
break 2; // we do not want any power on administrative
}
@@ -50,7 +48,7 @@ class LoadTaskACL extends AbstractFixture implements OrderedFixtureInterface
case 'administrative':
case 'direction':
if (in_array($scope->getName()['en'], ['administrative', 'social'], true)) {
if (\in_array($scope->getName()['en'], ['administrative', 'social'], true)) {
break 2; // we do not want any power on social or administrative
}
@@ -59,7 +57,7 @@ class LoadTaskACL extends AbstractFixture implements OrderedFixtureInterface
printf(
'Adding CHILL_TASK_TASK_UPDATE & CHILL_TASK_TASK_CREATE & Chill_TASK_TASK_DELETE permissions to %s '
. "permission group, scope '%s' \n",
."permission group, scope '%s' \n",
$permissionsGroup->getName(),
$scope->getName()['en']
);

View File

@@ -31,7 +31,7 @@ class ChillTaskExtension extends Extension implements PrependExtensionInterface
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../config'));
$loader->load('services/controller.yaml');
$loader->load('services/security.yaml');
$loader->load('services/repositories.yaml');
@@ -64,7 +64,7 @@ class ChillTaskExtension extends Extension implements PrependExtensionInterface
protected function prependRoute(ContainerBuilder $container)
{
//declare routes for task bundle
// declare routes for task bundle
$container->prependExtensionConfig('chill_main', [
'routing' => [
'resources' => [

View File

@@ -14,7 +14,6 @@ namespace Chill\TaskBundle\DependencyInjection\Compiler;
use Chill\TaskBundle\Event\Lifecycle\TaskLifecycleEvent;
use Chill\TaskBundle\Templating\UI\CountNotificationTask;
use Chill\TaskBundle\Workflow\TaskWorkflowManager;
use LogicException;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
@@ -24,8 +23,7 @@ class TaskWorkflowDefinitionCompilerPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition(TaskWorkflowManager::class)) {
throw new LogicException('The service ' . TaskWorkflowManager::class . ' is '
. 'not registered');
throw new \LogicException('The service '.TaskWorkflowManager::class.' is not registered');
}
$workflowManagerDefinition = $container->getDefinition(TaskWorkflowManager::class);

View File

@@ -21,13 +21,11 @@ use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;
use function array_fill_keys;
use function array_keys;
/**
* AbstractTask.
*
* @ORM\MappedSuperclass
*
* @Serializer\DiscriminatorMap(typeProperty="type", mapping={
* "single_task": SingleTask::class
* })
@@ -38,6 +36,7 @@ abstract class AbstractTask implements HasCenterInterface, HasScopeInterface
* @ORM\ManyToOne(
* targetEntity="\Chill\MainBundle\Entity\User"
* )
*
* @Serializer\Groups({"read"})
*/
private ?\Chill\MainBundle\Entity\User $assignee = null;
@@ -51,25 +50,28 @@ abstract class AbstractTask implements HasCenterInterface, HasScopeInterface
/**
* @ORM\Column(name="closed", type="boolean", options={ "default": false })
*
* @Serializer\Groups({"read"})
*/
private bool $closed = false;
/**
* @ORM\ManyToOne(targetEntity="\Chill\PersonBundle\Entity\AccompanyingPeriod")
*
* @Serializer\Groups({"read"})
*/
private ?\Chill\PersonBundle\Entity\AccompanyingPeriod $course = null;
/**
* @ORM\Column(name="current_states", type="json", options={"jsonb"=true, "default"="[]"})
*
* @Serializer\Groups({"read"})
*/
private array $currentStates = [];
/**
*
* @ORM\Column(name="description", type="text")
*
* @Serializer\Groups({"read"})
*/
private string $description = '';
@@ -78,21 +80,23 @@ abstract class AbstractTask implements HasCenterInterface, HasScopeInterface
* @ORM\ManyToOne(
* targetEntity="\Chill\PersonBundle\Entity\Person"
* )
*
* @Serializer\Groups({"read"})
*/
private ?\Chill\PersonBundle\Entity\Person $person = null;
/**
*
* @ORM\Column(name="title", type="text")
*
* @Assert\NotBlank
*
* @Serializer\Groups({"read"})
*/
private string $title = '';
/**
*
* @ORM\Column(name="type", type="string", length=255)
*
* @Serializer\Groups({"read"})
*/
private ?string $type = null;
@@ -137,7 +141,7 @@ abstract class AbstractTask implements HasCenterInterface, HasScopeInterface
*/
public function getCurrentStates()
{
return array_fill_keys($this->currentStates, 1);
return \array_fill_keys($this->currentStates, 1);
}
/**
@@ -185,7 +189,7 @@ abstract class AbstractTask implements HasCenterInterface, HasScopeInterface
return $this->closed;
}
public function setAssignee(?User $assignee = null)
public function setAssignee(User $assignee = null)
{
$this->assignee = $assignee;
@@ -216,13 +220,11 @@ abstract class AbstractTask implements HasCenterInterface, HasScopeInterface
*
* The current states are sorted in a single array, non associative.
*
* @param $currentStates
*
* @return AbstractTask
*/
public function setCurrentStates($currentStates)
{
$this->currentStates = array_keys($currentStates);
$this->currentStates = \array_keys($currentStates);
return $this;
}

View File

@@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\TaskBundle\Entity;
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@@ -20,6 +19,7 @@ use Doctrine\ORM\Mapping as ORM;
* RecurringTask.
*
* @ORM\Table(name="chill_task.recurring_task")
*
* @ORM\Entity(repositoryClass="Chill\TaskBundle\Repository\RecurringTaskRepository")
*/
class RecurringTask extends AbstractTask
@@ -30,10 +30,10 @@ class RecurringTask extends AbstractTask
private ?\DateTime $firstOccurenceEndDate = null;
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\Id
*
* @ORM\GeneratedValue(strategy="AUTO")
*/
private ?int $id = null;
@@ -44,20 +44,16 @@ class RecurringTask extends AbstractTask
private ?\DateTime $lastOccurenceEndDate = null;
/**
* @var string
*
* @ORM\Column(name="occurence_frequency", type="string", length=255)
*/
private ?string $occurenceFrequency = null;
/**
*
* @ORM\Column(name="occurence_start_date", type="dateinterval")
*/
private $occurenceStartDate;
/**
*
* @ORM\Column(name="occurence_warning_interval", type="dateinterval", nullable=true)
*/
private $occurenceWarningInterval;
@@ -80,7 +76,7 @@ class RecurringTask extends AbstractTask
/**
* Get firstOccurenceEndDate.
*
* @return DateTime
* @return \DateTime
*/
public function getFirstOccurenceEndDate()
{
@@ -100,7 +96,7 @@ class RecurringTask extends AbstractTask
/**
* Get lastOccurenceEndDate.
*
* @return DateTime
* @return \DateTime
*/
public function getLastOccurenceEndDate()
{
@@ -119,7 +115,6 @@ class RecurringTask extends AbstractTask
/**
* Get occurenceStartDate.
*
*/
public function getOccurenceStartDate()
{
@@ -128,7 +123,6 @@ class RecurringTask extends AbstractTask
/**
* Get occurenceWarningInterval.
*
*/
public function getOccurenceWarningInterval()
{
@@ -138,7 +132,7 @@ class RecurringTask extends AbstractTask
/**
* Set firstOccurenceEndDate.
*
* @param DateTime $firstOccurenceEndDate
* @param \DateTime $firstOccurenceEndDate
*
* @return RecurringTask
*/
@@ -152,7 +146,7 @@ class RecurringTask extends AbstractTask
/**
* Set lastOccurenceEndDate.
*
* @param DateTime $lastOccurenceEndDate
* @param \DateTime $lastOccurenceEndDate
*
* @return RecurringTask
*/
@@ -180,7 +174,6 @@ class RecurringTask extends AbstractTask
/**
* Set occurenceStartDate.
*
*
* @return RecurringTask
*/
public function setOccurenceStartDate(mixed $occurenceStartDate)
@@ -193,7 +186,6 @@ class RecurringTask extends AbstractTask
/**
* Set occurenceWarningInterval.
*
*
* @return RecurringTask
*/
public function setOccurenceWarningInterval(mixed $occurenceWarningInterval)

View File

@@ -13,8 +13,6 @@ namespace Chill\TaskBundle\Entity;
use Chill\TaskBundle\Entity\Task\SingleTaskPlaceEvent;
use DateInterval;
use DateTime;
use DateTimeImmutable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
@@ -27,6 +25,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* @ORM\Table(
* name="chill_task.single_task",
* indexes={
*
* @ORM\Index(
* name="by_type",
* columns={ "type" }
@@ -41,23 +40,27 @@ use Symfony\Component\Validator\Constraints as Assert;
* )
* }
* )
*
* @ORM\Entity(repositoryClass="Chill\TaskBundle\Repository\SingleTaskRepository")
*/
class SingleTask extends AbstractTask
{
/**
* @ORM\Column(name="end_date", type="date", nullable=true)
*
* @Assert\Date
*
* @Serializer\Groups({"read"})
*/
private ?\DateTime $endDate = null;
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
*
* @ORM\Id
*
* @ORM\GeneratedValue(strategy="AUTO")
*
* @Serializer\Groups({"read"})
*/
private ?int $id = null;
@@ -71,16 +74,16 @@ class SingleTask extends AbstractTask
private ?\Chill\TaskBundle\Entity\RecurringTask $recurringTask = null;
/**
*
* @ORM\Column(name="start_date", type="date", nullable=true)
*
* @Serializer\Groups({"read"})
*
* @Assert\Date
*
* @Assert\Expression(
* "value === null or this.getEndDate() === null or value < this.getEndDate()",
* message="The start date must be before the end date"
* )
*
* @Assert\Expression(
* "value === null or this.getWarningDate() === null or this.getWarningDate() > this.getStartDate()",
* message="The start date must be before warning date"
@@ -90,6 +93,7 @@ class SingleTask extends AbstractTask
/**
* @var Collection<SingleTaskPlaceEvent>
*
* @ORM\OneToMany(
* targetEntity="\Chill\TaskBundle\Entity\Task\SingleTaskPlaceEvent",
* mappedBy="task",
@@ -99,10 +103,11 @@ class SingleTask extends AbstractTask
private Collection $taskPlaceEvents;
/**
* @var DateInterval
* and this.getEndDate() === null
* @var \DateInterval
* and this.getEndDate() === null
*
* @ORM\Column(name="warning_interval", type="dateinterval", nullable=true)
*
* @Serializer\Groups({"read"})
*
* @Assert\Expression(
@@ -110,7 +115,7 @@ class SingleTask extends AbstractTask
* message="An end date is required if a warning interval is set"
* )
*/
private $warningInterval;
private null|\DateInterval $warningInterval = null;
public function __construct()
{
@@ -119,10 +124,8 @@ class SingleTask extends AbstractTask
/**
* Get endDate.
*
* @return DateTime
*/
public function getEndDate()
public function getEndDate(): null|\DateTime
{
return $this->endDate;
}
@@ -145,7 +148,7 @@ class SingleTask extends AbstractTask
/**
* Get startDate.
*
* @return DateTime
* @return \DateTime
*/
public function getStartDate()
{
@@ -163,29 +166,28 @@ class SingleTask extends AbstractTask
*
* Return null if warningDate or endDate is null
*
* @return DateTimeImmutable
* @return \DateTimeImmutable
*
* @Serializer\Groups({"read"})
*/
public function getWarningDate()
{
if ($this->getWarningInterval() === null) {
if (null === $this->getWarningInterval()) {
return null;
}
if ($this->getEndDate() === null) {
if (null === $this->getEndDate()) {
return null;
}
return DateTimeImmutable::createFromMutable($this->getEndDate())
return \DateTimeImmutable::createFromMutable($this->getEndDate())
->sub($this->getWarningInterval());
}
/**
* Get warningInterval.
*
* @return DateInterval
*/
public function getWarningInterval()
public function getWarningInterval(): null|\DateInterval
{
return $this->warningInterval;
}
@@ -193,7 +195,7 @@ class SingleTask extends AbstractTask
/**
* Set endDate.
*
* @param DateTime $endDate
* @param \DateTime $endDate
*
* @return SingleTask
*/
@@ -212,7 +214,7 @@ class SingleTask extends AbstractTask
/**
* Set startDate.
*
* @param DateTime $startDate
* @param \DateTime $startDate
*
* @return SingleTask
*/
@@ -233,11 +235,9 @@ class SingleTask extends AbstractTask
/**
* Set warningInterval.
*
* @param string $warningInterval
*
* @return SingleTask
*/
public function setWarningInterval($warningInterval)
public function setWarningInterval(null|\DateInterval $warningInterval)
{
$this->warningInterval = $warningInterval;

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\TaskBundle\Entity\Task;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
/**
@@ -48,7 +47,7 @@ class AbstractTaskPlaceEvent
public function __construct()
{
$this->datetime = new DateTimeImmutable('now');
$this->datetime = new \DateTimeImmutable('now');
}
public function getAuthor(): User

View File

@@ -18,6 +18,7 @@ use Doctrine\ORM\Mapping as ORM;
* @ORM\Table(
* name="chill_task.single_task_place_event",
* indexes={
*
* @ORM\Index(
* name="transition_task_date",
* columns={"task_id", "transition", "datetime"}
@@ -27,19 +28,21 @@ use Doctrine\ORM\Mapping as ORM;
* columns={"task_id", "transition"}
* )
* })
*
* @ORM\Entity
*/
class SingleTaskPlaceEvent extends AbstractTaskPlaceEvent
{
/**
* @ORM\Column(name="id", type="integer")
*
* @ORM\Id
*
* @ORM\GeneratedValue(strategy="AUTO")
*/
private ?int $id = null;
/**
* @var SingleTask
* @ORM\ManyToOne(
* targetEntity="\Chill\TaskBundle\Entity\SingleTask",
* inversedBy="taskPlaceEvents"

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\TaskBundle\Event;
use Chill\TaskBundle\Entity\AbstractTask;
use Symfony\Component\EventDispatcher\Event;
class TaskEvent extends \Symfony\Contracts\EventDispatcher\Event
{

View File

@@ -12,7 +12,6 @@ declare(strict_types=1);
namespace Chill\TaskBundle\Event\UI;
use Chill\TaskBundle\Entity\AbstractTask;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Workflow\Transition;
@@ -53,7 +52,7 @@ class UIEvent extends \Symfony\Contracts\EventDispatcher\Event
$this->task = $task;
}
public function getForm(): ?\Symfony\Component\Form\FormInterface
public function getForm(): ?FormInterface
{
return $this->form;
}

View File

@@ -28,11 +28,6 @@ use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Role\Role;
use function array_combine;
use function array_map;
use function count;
class SingleTaskListType extends AbstractType
{
@@ -99,7 +94,7 @@ class SingleTaskListType extends AbstractType
if ($options['add_type']) {
$types = $this->getTaskTypesChoices($options);
if (count($types) > 0) {
if (\count($types) > 0) {
$builder->add('types', ChoiceType::class, [
'choices' => $types,
'required' => false,
@@ -123,7 +118,7 @@ class SingleTaskListType extends AbstractType
]);
$reachablesCenters = $this->getReachablesCenters();
if (count($reachablesCenters) > 1) {
if (\count($reachablesCenters) > 1) {
$builder
->add('center_id', EntityType::class, [
'class' => \Chill\MainBundle\Entity\Center::class,
@@ -182,16 +177,16 @@ class SingleTaskListType extends AbstractType
foreach ($centers as $center) {
$circles = $this->authorizationHelper->getReachableCircles($user, $role, $center);
if (count($circles) > 0) {
if (\count($circles) > 0) {
$andX = $qb->expr()->andX();
$andX
->add($qb->expr()->eq('person.center', ':center_' . $i))
->add($qb->expr()->in('task.circle', ':circles_' . $i));
->add($qb->expr()->eq('person.center', ':center_'.$i))
->add($qb->expr()->in('task.circle', ':circles_'.$i));
$orCenters->add($andX);
$qb
->setParameter('center_' . $i, $center)
->setParameter('circles_' . $i, $circles);
->setParameter('center_'.$i, $center)
->setParameter('circles_'.$i, $circles);
++$i;
}
}
@@ -216,11 +211,11 @@ class SingleTaskListType extends AbstractType
protected function getUserChoices($options)
{
$users = $this->getUsersAssigneedToTask($options);
$choices = array_combine(
$choices = \array_combine(
// get usernames
array_map(static fn (User $user) => $user->getUsername(), $users),
\array_map(static fn (User $user) => $user->getUsername(), $users),
// get ids
array_map(static fn (User $user) => $user->getId(), $users)
\array_map(static fn (User $user) => $user->getId(), $users)
);
$choices['Unassigned'] = '_unassigned';
@@ -230,7 +225,6 @@ class SingleTaskListType extends AbstractType
/**
* Return a list of user having a task assigned.
*
*
* @return User[]
*/
protected function getUsersAssigneedToTask(mixed $options)
@@ -260,12 +254,12 @@ class SingleTaskListType extends AbstractType
// add condition about person and circle
$circleCenterCond->add(
$qb->expr()->andX()
->add($qb->expr()->eq('person.center', ':center_' . $i))
->add($qb->expr()->in('task.circle', ':circles_' . $i))
->add($qb->expr()->eq('person.center', ':center_'.$i))
->add($qb->expr()->in('task.circle', ':circles_'.$i))
);
$qb->setParameter('center_' . $i, $center)
->setParameter('circles_' . $i, $circles);
$qb->setParameter('center_'.$i, $center)
->setParameter('circles_'.$i, $circles);
// increase counter
++$i;
}

View File

@@ -24,7 +24,6 @@ use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Role\Role;
class SingleTaskType extends AbstractType
{

View File

@@ -15,7 +15,6 @@ use Chill\MainBundle\Routing\LocalMenuBuilderInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\TaskBundle\Security\Authorization\TaskVoter;
use Knp\Menu\MenuItem;
use LogicException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
@@ -63,13 +62,13 @@ class MenuBuilder implements LocalMenuBuilderInterface
'person' => $this->buildPersonMenu($menu, $parameters),
'accompanyingCourse' => $this->buildAccompanyingCourseMenu($menu, $parameters),
'section' => $menu->setExtras('icons'),
default => throw new LogicException("this menuid {$menuId} is not implemented"),
default => throw new \LogicException("this menuid {$menuId} is not implemented"),
};
}
public function buildPersonMenu($menu, $parameters)
{
//var $person \Chill\PersonBundle\Entity\Person */
// var $person \Chill\PersonBundle\Entity\Person */
$person = $parameters['person'] ?? null;
if ($this->authorizationChecker->isGranted(TaskVoter::SHOW, $person)) {

View File

@@ -103,7 +103,7 @@ class UserMenuBuilder implements LocalMenuBuilderInterface
{
if (0 < $number) {
$menu->addChild(
$this->translator->trans($message, $number),
$this->translator->trans($message, ['nb' => $number]),
[
'route' => 'chill_task_singletask_my_tasks',
'routeParameters' => [

View File

@@ -17,22 +17,16 @@ use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use Chill\TaskBundle\Entity\SingleTask;
use Chill\TaskBundle\Security\Authorization\TaskVoter;
use DateInterval;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use LogicException;
use Symfony\Component\Security\Core\Security;
use function count;
use function substr;
final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareRepositoryInterface
{
public function __construct(private CenterResolverManagerInterface $centerResolverDispatcher, private EntityManagerInterface $em, private Security $security, private AuthorizationHelperInterface $authorizationHelper) {}
public function buildBaseQuery(
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?array $types = [],
?array $users = []
@@ -43,18 +37,18 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
if (null !== $pattern && '' !== $pattern) {
$qb->andWhere($qb->expr()->like('LOWER(UNACCENT(t.title))', 'LOWER(UNACCENT(:pattern))'))
->setParameter('pattern', '%' . $pattern . '%');
->setParameter('pattern', '%'.$pattern.'%');
}
if (null !== $users && count($users) > 0) {
if (null !== $users && \count($users) > 0) {
$orXUser = $qb->expr()->orX();
foreach ($users as $key => $user) {
$orXUser->add(
$qb->expr()->eq('t.assignee', ':user_' . $key)
$qb->expr()->eq('t.assignee', ':user_'.$key)
);
$qb->setParameter('user_' . $key, $user);
$qb->setParameter('user_'.$key, $user);
}
if ($orXUser->count() > 0) {
@@ -62,16 +56,16 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
}
}
if (null !== $types && count($types) > 0) {
if (null !== $types && \count($types) > 0) {
$qb->andWhere($qb->expr()->in('t.type', ':types'));
$qb->setParameter('types', $types);
}
if (null !== $flags && count($flags) > 0) {
if (null !== $flags && \count($flags) > 0) {
$orXDate = $qb->expr()->orX();
$orXState = $qb->expr()->orX();
$now = new DateTime();
$now = new \DateTime();
foreach ($flags as $key => $flag) {
switch ($flag) {
@@ -84,7 +78,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
)
);
$qb
->setParameter('intervalBlank', new DateInterval('P0D'))
->setParameter('intervalBlank', new \DateInterval('P0D'))
->setParameter('now', $now);
break;
@@ -126,7 +120,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
break;
case str_starts_with((string) $flag, 'state_'):
$state = substr((string) $flag, 6);
$state = \substr((string) $flag, 6);
$orXState
->add(
"JSONB_EXISTS_IN_ARRAY(t.currentStates, :state_{$key}) = 'TRUE'"
@@ -136,7 +130,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
break;
default:
throw new LogicException("this flag is not supported: {$flag}");
throw new \LogicException("this flag is not supported: {$flag}");
}
}
@@ -154,7 +148,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
public function buildQueryByCourse(
AccompanyingPeriod $course,
?string $pattern = null,
string $pattern = null,
?array $flags = []
): QueryBuilder {
$qb = $this->buildBaseQuery($pattern, $flags);
@@ -166,7 +160,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
public function buildQueryByPerson(
Person $person,
?string $pattern = null,
string $pattern = null,
?array $flags = []
): QueryBuilder {
$qb = $this->buildBaseQuery($pattern, $flags);
@@ -177,7 +171,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
}
public function buildQueryMyTasks(
?string $pattern = null,
string $pattern = null,
?array $flags = []
): QueryBuilder {
$qb = $this->buildBaseQuery($pattern, $flags);
@@ -188,7 +182,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
}
public function countByAllViewable(
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?array $types = [],
?array $users = []
@@ -203,7 +197,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
public function countByCourse(
AccompanyingPeriod $course,
?string $pattern = null,
string $pattern = null,
?array $flags = []
): int {
$qb = $this->buildQueryByCourse($course, $pattern, $flags);
@@ -215,7 +209,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
}
public function countByCurrentUsersTasks(
?string $pattern = null,
string $pattern = null,
?array $flags = []
): int {
return $this->buildQueryMyTasks($pattern, $flags)
@@ -225,7 +219,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
public function countByPerson(
Person $person,
?string $pattern = null,
string $pattern = null,
?array $flags = []
): int {
$qb = $this->buildQueryByPerson($person, $pattern, $flags);
@@ -237,7 +231,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
}
public function findByAllViewable(
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?array $types = [],
?array $users = [],
@@ -253,7 +247,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
public function findByCourse(
AccompanyingPeriod $course,
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?int $start = 0,
?int $limit = 50,
@@ -266,7 +260,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
}
public function findByCurrentUsersTasks(
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?int $start = 0,
?int $limit = 50,
@@ -279,7 +273,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
public function findByPerson(
Person $person,
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?int $start = 0,
?int $limit = 50,
@@ -304,7 +298,7 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
->setMaxResults($limit);
foreach ($orderBy as $field => $direction) {
$qb->addOrderBy('t.' . $field, $direction);
$qb->addOrderBy('t.'.$field, $direction);
}
return $qb->getQuery()->getResult();
@@ -360,14 +354,14 @@ final readonly class SingleTaskAclAwareRepository implements SingleTaskAclAwareR
$and = $qb->expr()->andX(
$qb->expr()->orX(
$qb->expr()->eq('center_current_person.center', ':center_' . $k),
$qb->expr()->eq('center_current_participation.center', ':center_' . $k)
$qb->expr()->eq('center_current_person.center', ':center_'.$k),
$qb->expr()->eq('center_current_participation.center', ':center_'.$k)
),
$qb->expr()->in('t.circle', ':scopes_' . $k)
$qb->expr()->in('t.circle', ':scopes_'.$k)
);
$qb
->setParameter('center_' . $k, $center)
->setParameter('scopes_' . $k, $allowedScopes);
->setParameter('center_'.$k, $center)
->setParameter('scopes_'.$k, $allowedScopes);
$orX->add($and);
++$k;

View File

@@ -17,7 +17,7 @@ use Chill\PersonBundle\Entity\Person;
interface SingleTaskAclAwareRepositoryInterface
{
public function countByAllViewable(
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?array $types = [],
?array $users = []
@@ -25,20 +25,20 @@ interface SingleTaskAclAwareRepositoryInterface
public function countByCourse(
AccompanyingPeriod $course,
?string $pattern = null,
string $pattern = null,
?array $flags = []
): int;
public function countByCurrentUsersTasks(?string $pattern = null, ?array $flags = []): int;
public function countByCurrentUsersTasks(string $pattern = null, ?array $flags = []): int;
public function countByPerson(
Person $person,
?string $pattern = null,
string $pattern = null,
?array $flags = []
): int;
public function findByAllViewable(
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?array $types = [],
?array $users = [],
@@ -49,18 +49,18 @@ interface SingleTaskAclAwareRepositoryInterface
public function findByCourse(
AccompanyingPeriod $course,
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?int $start = 0,
?int $limit = 50,
?array $orderBy = []
): array;
public function findByCurrentUsersTasks(?string $pattern = null, ?array $flags = [], ?int $start = 0, ?int $limit = 50, ?array $orderBy = []): array;
public function findByCurrentUsersTasks(string $pattern = null, ?array $flags = [], ?int $start = 0, ?int $limit = 50, ?array $orderBy = []): array;
public function findByPerson(
Person $person,
?string $pattern = null,
string $pattern = null,
?array $flags = [],
?int $start = 0,
?int $limit = 50,

View File

@@ -15,15 +15,9 @@ use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\TaskBundle\Security\Authorization\TaskVoter;
use DateTime;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use LogicException;
use Symfony\Component\Security\Core\Role\Role;
use UnexpectedValueException;
use function array_key_exists;
use function count;
/**
@@ -59,11 +53,10 @@ class SingleTaskRepository extends EntityRepository
* @see SingleTaskRepository::filterByParameters
*
* @param array $params
* @param User $currentUser
*
* @return int
*/
public function countByParameters($params, ?User $currentUser = null)
public function countByParameters($params, User $currentUser = null)
{
$qb = $this->createQueryBuilder('st')
->select('COUNT(st)');
@@ -146,17 +139,14 @@ class SingleTaskRepository extends EntityRepository
->add($this->buildNowIsAfterWarningDate($qb, true))
->add($this->buildNowIsAfterStartDate($qb, true));
}
$qb->setParameter('now', new DateTime('today'), Types::DATE_MUTABLE);
$qb->setParameter('now', new \DateTime('today'), Types::DATE_MUTABLE);
$qb->andWhere($andWhere);
}
protected function buildACLQuery(QueryBuilder $qb, User $currentUser)
{
if (null === $this->authorizationHelper) {
throw new LogicException('Injecting the authorization helper is '
. 'required to run this query. Please use dependency injection '
. 'to initialize this repository or use the method '
. '`setAuthorizationHelper`');
throw new \LogicException('Injecting the authorization helper is required to run this query. Please use dependency injection to initialize this repository or use the method `setAuthorizationHelper`');
}
$role = TaskVoter::SHOW;
@@ -174,10 +164,10 @@ class SingleTaskRepository extends EntityRepository
$centerWhere = $qb->expr()->andX();
$centerWhere->add($qb->expr()->eq('p.center', ':center_' . $i));
$qb->setParameter('center_' . $i, $center);
$centerWhere->add($qb->expr()->in('st.circle', ':circles_' . $i));
$qb->setParameter('circles_' . $i, $circles);
$centerWhere->add($qb->expr()->eq('p.center', ':center_'.$i));
$qb->setParameter('center_'.$i, $center);
$centerWhere->add($qb->expr()->in('st.circle', ':circles_'.$i));
$qb->setParameter('circles_'.$i, $circles);
$where->add($centerWhere);
++$i;
}
@@ -185,56 +175,55 @@ class SingleTaskRepository extends EntityRepository
$qb->where($where);
}
protected function buildQuery(QueryBuilder $qb, $params, ?User $currentUser = null)
protected function buildQuery(QueryBuilder $qb, $params, User $currentUser = null)
{
if (null !== $currentUser) {
$this->buildACLQuery($qb, $currentUser);
}
if (array_key_exists('person', $params) && !empty($params['person'])) {
if (\array_key_exists('person', $params) && !empty($params['person'])) {
$qb->andWhere($qb->expr()->eq('st.person', ':person'));
$qb->setParameter('person', $params['person']);
} elseif (array_key_exists('center', $params)) {
} elseif (\array_key_exists('center', $params)) {
if ($params['center'] instanceof Center) {
$qb->join('st.person', 'person');
$qb->andWhere($qb->expr()->eq('person.center', ':center'));
$qb->setParameter('center', $params['center']);
} else {
throw new UnexpectedValueException("params 'center' should be an instance of " . Center::class);
throw new \UnexpectedValueException("params 'center' should be an instance of ".Center::class);
}
}
if (array_key_exists('unassigned', $params) && true === $params['unassigned']) {
if (array_key_exists('user', $params) && !empty($params['user'])) {
throw new UnexpectedValueException('You should not require for '
. 'unassigned tasks and tasks assigned to some user.');
if (\array_key_exists('unassigned', $params) && true === $params['unassigned']) {
if (\array_key_exists('user', $params) && !empty($params['user'])) {
throw new \UnexpectedValueException('You should not require for unassigned tasks and tasks assigned to some user.');
}
$qb->andWhere($qb->expr()->isNull('st.assignee'));
}
if (array_key_exists('user', $params) && !empty($params['user'])) {
if (\array_key_exists('user', $params) && !empty($params['user'])) {
$qb->andWhere($qb->expr()->eq('st.assignee', ':user'));
$qb->setParameter('user', $params['user']);
}
if (array_key_exists('scope', $params) && !empty($params['scope'])) {
if (\array_key_exists('scope', $params) && !empty($params['scope'])) {
$qb->andWhere($qb->expr()->eq('st.circle', ':scope'));
$qb->setParameter('scope', $params['scope']);
}
if (array_key_exists('types', $params) && null !== $params['types']) {
if (count($params['types']) > 0) {
if (\array_key_exists('types', $params) && null !== $params['types']) {
if (\count($params['types']) > 0) {
$qb->andWhere($qb->expr()->in('st.type', ':types'));
$qb->setParameter('types', $params['types']);
}
}
if (array_key_exists('date_status', $params) && !empty($params['date_status'])) {
if (\array_key_exists('date_status', $params) && !empty($params['date_status'])) {
$this->addTypeFilter($qb, $params);
}
if (array_key_exists('is_closed', $params)) {
if (\array_key_exists('is_closed', $params)) {
$qb->andWhere($this->buildIsClosed($qb, !$params['is_closed']));
}
}

View File

@@ -25,9 +25,10 @@ class SingleTaskStateRepository
) {}
/**
* Return a list of all states associated to at least one single task in the database
* Return a list of all states associated to at least one single task in the database.
*
* @return list<string>
*
* @throws Exception
*/
public function findAllExistingStates(): array

View File

@@ -14,7 +14,6 @@ namespace Chill\TaskBundle\Security\Authorization;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use Chill\TaskBundle\Entity\AbstractTask;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class AuthorizationEvent extends \Symfony\Contracts\EventDispatcher\Event

View File

@@ -26,8 +26,6 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use function in_array;
final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
public const CREATE_COURSE = 'CHILL_TASK_TASK_CREATE_FOR_COURSE';
@@ -99,7 +97,7 @@ final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchy
if ($event->hasVote()) {
$this->logger->debug('The TaskVoter is overriding by '
. AuthorizationEvent::VOTE, [
.AuthorizationEvent::VOTE, [
'vote' => $event->getVote(),
'task_id' => $subject->getId(),
]);
@@ -128,7 +126,7 @@ final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchy
if ($subject instanceof AccompanyingPeriod) {
if (AccompanyingPeriod::STEP_CLOSED === $subject->getStep()) {
if (in_array($attribute, [self::UPDATE, self::CREATE_COURSE, self::DELETE], true)) {
if (\in_array($attribute, [self::UPDATE, self::CREATE_COURSE, self::DELETE], true)) {
return false;
}
}

View File

@@ -39,7 +39,7 @@ class TaskTwigExtension extends AbstractExtension
AbstractTask $task,
string $key,
$metadataSubject = null,
?string $name = null
string $name = null
) {
return $this->taskWorkflowManager->getWorkflowMetadata($task, $key, $metadataSubject, $name);
}

View File

@@ -18,8 +18,6 @@ use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Workflow\Event\Event;
use function array_merge;
class CountNotificationTask implements NotificationCounterInterface
{
final public const CACHE_KEY = 'chill_task.count_notifications.user.%d.%s';

View File

@@ -15,11 +15,10 @@ use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Tests\TestHelper;
use Faker;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use function array_filter;
use function array_rand;
/**
* @internal
*
* @coversNothing
*/
final class SingleTaskControllerTest extends WebTestCase
@@ -58,7 +57,7 @@ final class SingleTaskControllerTest extends WebTestCase
$client->submit($form, [
'title' => $title,
'circle' => $circles[array_rand($circles)],
'circle' => $circles[\array_rand($circles)],
]);
$this->assertTrue($client->getResponse()->isRedirect(sprintf(
@@ -88,7 +87,7 @@ final class SingleTaskControllerTest extends WebTestCase
->getRepository(Center::class)
->findAll();
$center = array_filter(
$center = \array_filter(
$centers,
static fn (Center $c) => $c->getName() === $centerName
)[0];
@@ -96,12 +95,12 @@ final class SingleTaskControllerTest extends WebTestCase
$ids = $em
->createQuery(
'SELECT p.id FROM ChillPersonBundle:Person p '
. 'WHERE p.center = :center'
.'WHERE p.center = :center'
)
->setParameter('center', $center)
->getResult();
$id = $ids[array_rand($ids)];
$id = $ids[\array_rand($ids)];
return self::$kernel
->getContainer()

View File

@@ -15,6 +15,7 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
/**
* @internal
*
* @coversNothing
*/
final class TaskControllerTest extends WebTestCase {}

View File

@@ -28,10 +28,10 @@ use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Security\Core\Security;
use function count;
/**
* @internal
*
* @coversNothing
*/
final class SingleTaskACLAwareRepositoryTest extends KernelTestCase
@@ -152,7 +152,7 @@ final class SingleTaskACLAwareRepositoryTest extends KernelTestCase
$tasks = $repository->findByAllViewable(null, []);
$this->assertGreaterThanOrEqual(0, count($tasks));
$this->assertGreaterThanOrEqual(0, \count($tasks));
}
public function testFindByCourse(): void
@@ -162,7 +162,7 @@ final class SingleTaskACLAwareRepositoryTest extends KernelTestCase
$scopes = $this->scopeRepository->findAll();
/** @var Person $person */
$person = $this->em->createQuery(
'SELECT p FROM ' . Person::class . ' p JOIN p.centerCurrent cc
'SELECT p FROM '.Person::class.' p JOIN p.centerCurrent cc
WHERE SIZE(p.accompanyingPeriodParticipations) > 0
AND cc.center = :center'
)
@@ -191,7 +191,7 @@ final class SingleTaskACLAwareRepositoryTest extends KernelTestCase
$tasks = $repository->findByCourse($period);
$this->assertGreaterThanOrEqual(0, count($tasks));
$this->assertGreaterThanOrEqual(0, \count($tasks));
}
public function testFindByPerson(): void
@@ -221,6 +221,6 @@ final class SingleTaskACLAwareRepositoryTest extends KernelTestCase
$tasks = $repository->findByPerson($person, null, []);
$this->assertGreaterThanOrEqual(0, count($tasks));
$this->assertGreaterThanOrEqual(0, \count($tasks));
}
}

View File

@@ -16,13 +16,9 @@ use Chill\MainBundle\Timeline\TimelineSingleQuery;
use Chill\TaskBundle\Entity\SingleTask;
use Chill\TaskBundle\Entity\Task\SingleTaskPlaceEvent;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\Workflow;
use function array_combine;
use function array_map;
/**
* Provide timeline elements related to tasks, in tasks context.
*/
@@ -49,8 +45,7 @@ class SingleTaskTaskLifeCycleEventTimelineProvider implements TimelineProviderIn
public function fetchQuery($context, $args)
{
if ('task' !== $context) {
throw new LogicException(sprintf('%s is not able '
. 'to render context %s', self::class, $context));
throw new \LogicException(sprintf('%s is not able to render context %s', self::class, $context));
}
$metadata = $this->em
@@ -85,8 +80,8 @@ class SingleTaskTaskLifeCycleEventTimelineProvider implements TimelineProviderIn
->getRepository(SingleTaskPlaceEvent::class)
->findBy(['id' => $ids]);
return array_combine(
array_map(static fn ($e) => $e->getId(), $events),
return \array_combine(
\array_map(static fn ($e) => $e->getId(), $events),
$events
);
}

View File

@@ -19,19 +19,9 @@ use Chill\PersonBundle\Entity\Person;
use Chill\TaskBundle\Entity\SingleTask;
use Chill\TaskBundle\Entity\Task\SingleTaskPlaceEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\Workflow\Workflow;
use UnexpectedValueException;
use function array_combine;
use function array_fill;
use function array_map;
use function count;
use function implode;
use function in_array;
use function strtr;
/**
* Provide element for timeline for 'person' and 'center' context.
@@ -47,10 +37,10 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
$metadata = $this->em
->getClassMetadata(SingleTaskPlaceEvent::class);
[ $where, $parameters ] = match ($context) {
[$where, $parameters] = match ($context) {
'person' => $this->getWhereClauseForPerson($args['person']),
'center' => $this->getWhereClauseForCenter($args['centers']),
default => throw new UnexpectedValueException("context {$context} is not supported"),
default => throw new \UnexpectedValueException("context {$context} is not supported"),
};
return TimelineSingleQuery::fromArray([
@@ -69,8 +59,8 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
->getRepository(SingleTaskPlaceEvent::class)
->findBy(['id' => $ids]);
return array_combine(
array_map(static fn ($e) => $e->getId(), $events),
return \array_combine(
\array_map(static fn ($e) => $e->getId(), $events),
$events
);
}
@@ -127,11 +117,11 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
$taskFkPerson = $singleTask->getAssociationMapping('person')['joinColumns'][0]['name'];
$personPk = $singleTask->getAssociationMapping('person')['joinColumns'][0]['referencedColumnName'];
$from = '{single_task_event} ' .
'JOIN {single_task} ON {single_task}.{task_pk} = {single_task_event}.{event_fk_task} ' .
$from = '{single_task_event} '.
'JOIN {single_task} ON {single_task}.{task_pk} = {single_task_event}.{event_fk_task} '.
'JOIN {person} ON {single_task}.{task_person_fk} = {person}.{person_pk}';
return strtr(
return \strtr(
$from,
[
'{single_task}' => sprintf('%s.%s', $singleTask->getSchemaName(), $singleTask->getTableName()),
@@ -169,7 +159,7 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
ActivityVoter::SEE_DETAILS
) as $center
) {
if (false === in_array($center, $centers, true)) {
if (false === \in_array($center, $centers, true)) {
continue;
}
@@ -188,24 +178,24 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
$parameters[] = $circleIds[] = $circle->getId();
}
$clauses[] = strtr(
$clauses[] = \strtr(
$clause,
[
'{person}' => $person->getTableName(),
'{center_id}' => $personFkCenter,
'{task}' => $singleTask->getSchemaName() . '.' . $singleTask->getTableName(),
'{task}' => $singleTask->getSchemaName().'.'.$singleTask->getTableName(),
'{circle}' => $taskFkCircle,
'{circle_ids}' => implode(', ', array_fill(0, count($circleIds), '?')),
'{circle_ids}' => \implode(', ', \array_fill(0, \count($circleIds), '?')),
]
);
}
if (0 === count($clauses)) {
if (0 === \count($clauses)) {
return ['FALSE = TRUE', []];
}
return [
implode(' OR ', $clauses),
\implode(' OR ', $clauses),
$parameters,
];
}
@@ -236,7 +226,7 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
$personArg->getCenter()
);
if (0 === count($circles)) {
if (0 === \count($circles)) {
// go fast to block access to every tasks
return ['FALSE = TRUE', []];
}
@@ -246,14 +236,14 @@ class TaskLifeCycleEventTimelineProvider implements TimelineProviderInterface
}
return [
strtr(
\strtr(
$clause,
[
'{person}' => $person->getTableName(),
'{person_id}' => $person->getColumnName('id'),
'{task}' => $singleTask->getSchemaName() . '.' . $singleTask->getTableName(),
'{task}' => $singleTask->getSchemaName().'.'.$singleTask->getTableName(),
'{circle}' => $taskFkCircle,
'{circle_ids}' => implode(', ', array_fill(0, count($circleIds), '?')),
'{circle_ids}' => \implode(', ', \array_fill(0, \count($circleIds), '?')),
]
),
$parameters,

View File

@@ -13,14 +13,8 @@ namespace Chill\TaskBundle\Workflow\Definition;
use Chill\TaskBundle\Entity\AbstractTask;
use Chill\TaskBundle\Entity\SingleTask;
use LogicException;
use Symfony\Component\Workflow\Transition;
use function array_key_exists;
use function array_slice;
use function explode;
use function implode;
class DefaultTaskDefinition implements \Chill\TaskBundle\Workflow\TaskWorkflowDefinition
{
final public const DEFINITION_METADATA = [
@@ -61,15 +55,15 @@ class DefaultTaskDefinition implements \Chill\TaskBundle\Workflow\TaskWorkflowDe
string $key,
$metadataSubject = null
) {
$keys = explode('.', $key);
$keys = \explode('.', $key);
switch ($keys[0]) {
case 'transition':
if (!$metadataSubject instanceof Transition) {
throw new LogicException('You must give a transition as metadatasubject');
throw new \LogicException('You must give a transition as metadatasubject');
}
return $this->getTransitionMetadata(implode('.', array_slice($keys, 1)), $metadataSubject);
return $this->getTransitionMetadata(\implode('.', \array_slice($keys, 1)), $metadataSubject);
case 'definition':
return self::DEFINITION_METADATA[$keys[1]] ?? $key;
@@ -81,23 +75,23 @@ class DefaultTaskDefinition implements \Chill\TaskBundle\Workflow\TaskWorkflowDe
public function isClosed(AbstractTask $task)
{
return array_key_exists('closed', $task->getCurrentStates())
|| array_key_exists('canceled', $task->getCurrentStates());
return \array_key_exists('closed', $task->getCurrentStates())
|| \array_key_exists('canceled', $task->getCurrentStates());
}
public function supports(AbstractTask $task)
{
return $task instanceof SingleTask
&& $task->getType() === 'task_default';
&& 'task_default' === $task->getType();
}
protected function getTransitionMetadata($key, Transition $transition)
{
if (!array_key_exists($transition->getName(), self::TRANSITION_METADATA)) {
if (!\array_key_exists($transition->getName(), self::TRANSITION_METADATA)) {
return $key;
}
if (!array_key_exists($key, self::TRANSITION_METADATA[$transition->getName()])) {
if (!\array_key_exists($key, self::TRANSITION_METADATA[$transition->getName()])) {
return $key;
}

View File

@@ -12,14 +12,10 @@ declare(strict_types=1);
namespace Chill\TaskBundle\Workflow;
use Chill\TaskBundle\Entity\AbstractTask;
use LogicException;
use Symfony\Component\Workflow\Event\Event;
use Symfony\Component\Workflow\SupportStrategy\WorkflowSupportStrategyInterface;
use Symfony\Component\Workflow\WorkflowInterface;
use function count;
use function sprintf;
class TaskWorkflowManager implements WorkflowSupportStrategyInterface
{
/**
@@ -33,9 +29,9 @@ class TaskWorkflowManager implements WorkflowSupportStrategyInterface
}
/**
* @throws LogicException
*
* @return TaskWorkflowDefinition
*
* @throws \LogicException
*/
public function getTaskWorkflowDefinition(AbstractTask $task)
{
@@ -47,21 +43,20 @@ class TaskWorkflowManager implements WorkflowSupportStrategyInterface
}
}
$count = count($definitions);
$count = \count($definitions);
if (1 < $count) {
throw new LogicException('More than one TaskWorkflowDefinition supports '
. 'this task. This should not happens.');
throw new \LogicException('More than one TaskWorkflowDefinition supports this task. This should not happens.');
}
if (0 === $count) {
throw new LogicException(sprintf('No taskWorkflowDefinition supports this task type: %s (task id: %s).', $task->getType(), $task->getId()));
throw new \LogicException(\sprintf('No taskWorkflowDefinition supports this task type: %s (task id: %s).', $task->getType(), $task->getId()));
}
return $definitions[0];
}
public function getWorkflowMetadata(AbstractTask $task, string $key, $metadataSubject = null, ?string $name = null)
public function getWorkflowMetadata(AbstractTask $task, string $key, $metadataSubject = null, string $name = null)
{
return $this->getTaskWorkflowDefinition($task)
->getWorkflowMetadata($task, $key, $metadataSubject);

View File

@@ -21,14 +21,14 @@ class Version20180413135614 extends AbstractMigration
{
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('DROP SCHEMA chill_task CASCADE');
}
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('CREATE SCHEMA chill_task');
$this->addSql('CREATE SEQUENCE chill_task.single_task_id_seq INCREMENT BY 1 MINVALUE 1 START 1');

View File

@@ -21,7 +21,7 @@ class Version20180413201023 extends AbstractMigration
{
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_task.single_task DROP CONSTRAINT FK_194CB3D840868C31');
$this->addSql('DROP SEQUENCE chill_task.recurring_task_id_seq CASCADE');
@@ -32,7 +32,7 @@ class Version20180413201023 extends AbstractMigration
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('CREATE SEQUENCE chill_task.recurring_task_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE chill_task.recurring_task (id INT NOT NULL, assignee_id INT DEFAULT NULL, person_id INT DEFAULT NULL, circle_id INT DEFAULT NULL, type VARCHAR(255) NOT NULL, current_states JSONB NOT NULL, title TEXT NOT NULL, description TEXT NOT NULL, first_occurence_end_date DATE NOT NULL, last_occurence_end_date DATE NOT NULL, occurence_frequency VARCHAR(255) NOT NULL, occurence_start_date INTERVAL NOT NULL, occurence_warning_interval INTERVAL DEFAULT NULL, PRIMARY KEY(id))');

View File

@@ -21,7 +21,7 @@ class Version20180426093011 extends AbstractMigration
{
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_task.recurring_task DROP closed');
$this->addSql('ALTER TABLE chill_task.single_task DROP closed');
@@ -29,7 +29,7 @@ class Version20180426093011 extends AbstractMigration
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('ALTER TABLE chill_task.single_task ADD closed BOOLEAN DEFAULT \'false\' NOT NULL');
$this->addSql('ALTER TABLE chill_task.recurring_task ADD closed BOOLEAN DEFAULT \'false\' NOT NULL');

View File

@@ -21,7 +21,7 @@ class Version20180502194119 extends AbstractMigration
{
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('DROP SEQUENCE chill_task.single_task_place_event_id_seq CASCADE');
$this->addSql('DROP TABLE chill_task.single_task_place_event');
@@ -29,7 +29,7 @@ class Version20180502194119 extends AbstractMigration
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('CREATE SEQUENCE chill_task.single_task_place_event_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
$this->addSql('CREATE TABLE chill_task.single_task_place_event (id INT NOT NULL, author_id INT DEFAULT NULL, task_id INT DEFAULT NULL, datetime TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, transition VARCHAR(255) NOT NULL, data JSONB NOT NULL, PRIMARY KEY(id))');

View File

@@ -21,7 +21,7 @@ final class Version20181113161925 extends AbstractMigration
{
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('DROP INDEX transition_task_date');
$this->addSql('DROP INDEX transition_task');
@@ -29,7 +29,7 @@ final class Version20181113161925 extends AbstractMigration
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('CREATE INDEX transition_task_date ON chill_task.single_task_place_event (task_id, transition, datetime)');
$this->addSql('CREATE INDEX transition_task ON chill_task.single_task_place_event (task_id, transition)');

View File

@@ -21,7 +21,7 @@ final class Version20181113164108 extends AbstractMigration
{
public function down(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('DROP INDEX by_type');
$this->addSql('DROP INDEX by_current_state');
@@ -29,7 +29,7 @@ final class Version20181113164108 extends AbstractMigration
public function up(Schema $schema): void
{
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
$this->abortIf('postgresql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'postgresql\'.');
$this->addSql('CREATE INDEX by_type ON chill_task.single_task (type)');
$this->addSql('CREATE INDEX by_current_state ON chill_task.single_task USING GIN (current_states)');