fix: SA: Fix "...an unused use..." rule.

Also fix a critical bug in `ListPerson.php`.

SA stands for Static Analysis.
This commit is contained in:
Pol Dellaiera 2021-11-16 15:06:43 +01:00
parent 8bebe1f904
commit 7462babbeb
No known key found for this signature in database
GPG Key ID: D476DFE9C67467CA
4 changed files with 83 additions and 268 deletions

View File

@ -10,11 +10,6 @@ parameters:
count: 1
path: src/Bundle/ChillCustomFieldsBundle/Controller/CustomFieldsGroupController.php
-
message: "#^Anonymous function has an unused use \\$entries\\.$#"
count: 1
path: src/Bundle/ChillCustomFieldsBundle/CustomFields/CustomFieldLongChoice.php
-
message: "#^Instantiated class PhpOffice\\\\PhpWord\\\\TemplateProcessor not found\\.$#"
count: 1
@ -145,41 +140,6 @@ parameters:
count: 1
path: src/Bundle/ChillPersonBundle/DataFixtures/ORM/LoadSocialWorkMetadata.php
-
message: "#^Anonymous function has an unused use \\$key\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Switch condition type \\(Chill\\\\PersonBundle\\\\Export\\\\Export\\\\type\\) does not match case condition 'address_country_name' \\(string\\)\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Switch condition type \\(Chill\\\\PersonBundle\\\\Export\\\\Export\\\\type\\) does not match case condition 'address_isnoaddress' \\(string\\)\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Switch condition type \\(Chill\\\\PersonBundle\\\\Export\\\\Export\\\\type\\) does not match case condition 'birthdate' \\(string\\)\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Switch condition type \\(Chill\\\\PersonBundle\\\\Export\\\\Export\\\\type\\) does not match case condition 'countryOfBirth' \\(string\\)\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Switch condition type \\(Chill\\\\PersonBundle\\\\Export\\\\Export\\\\type\\) does not match case condition 'gender' \\(string\\)\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Switch condition type \\(Chill\\\\PersonBundle\\\\Export\\\\Export\\\\type\\) does not match case condition 'nationality' \\(string\\)\\.$#"
count: 1
path: src/Bundle/ChillPersonBundle/Export/Export/ListPerson.php
-
message: "#^Foreach overwrites \\$value with its value variable\\.$#"
count: 1
@ -245,11 +205,6 @@ parameters:
count: 1
path: src/Bundle/ChillTaskBundle/Entity/RecurringTask.php
-
message: "#^Constructor of class Chill\\\\TaskBundle\\\\Security\\\\Authorization\\\\TaskVoter has an unused parameter \\$voterHelperFactory\\.$#"
count: 1
path: src/Bundle/ChillTaskBundle/Security/Authorization/TaskVoter.php
-
message: "#^Foreach overwrites \\$value with its value variable\\.$#"
count: 1

View File

@ -1,21 +1,6 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Chill\CustomFieldsBundle\CustomFields;
@ -29,36 +14,21 @@ use Symfony\Bridge\Twig\TwigEngine;
use Chill\MainBundle\Form\Type\Select2ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class CustomFieldLongChoice extends AbstractCustomField
{
/**
*
* @var OptionRepository
*/
private $optionRepository;
private OptionRepository $optionRepository;
/**
*
* @var TranslatableStringHelper
*/
private $translatableStringHelper;
private TranslatableStringHelper $translatableStringHelper;
/**
* @var TwigEngine
*/
private $templating;
private TwigEngine $templating;
const KEY = 'key';
public const KEY = 'key';
public function __construct(OptionRepository $optionRepository,
public function __construct(
OptionRepository $optionRepository,
TranslatableStringHelper $translatableStringHelper,
TwigEngine $twigEngine)
{
TwigEngine $twigEngine
) {
$this->optionRepository = $optionRepository;
$this->translatableStringHelper = $translatableStringHelper;
$this->templating = $twigEngine;
@ -76,12 +46,7 @@ class CustomFieldLongChoice extends AbstractCustomField
'choice_label' => function(Option $option) use ($translatableStringHelper) {
return $translatableStringHelper->localize($option->getText());
},
'choice_value' => function ($key) use ($entries) {
if ($key === NULL) {
return null;
}
return $key->getId();
},
'choice_value' => static fn (Option $key): ?int => $key === null ? null : $key->getId(),
'multiple' => false,
'expanded' => false,
'required' => $customField->isRequired(),
@ -89,15 +54,16 @@ class CustomFieldLongChoice extends AbstractCustomField
'group_by' => function(Option $option) use ($translatableStringHelper) {
if ($option->hasParent()) {
return $translatableStringHelper->localize($option->getParent()->getText());
} else {
return $translatableStringHelper->localize($option->getText());
}
return $translatableStringHelper->localize($option->getText());
},
'label' => $translatableStringHelper->localize($customField->getName())
));
$builder->get($customField->getSlug())
->addModelTransformer(new CustomFieldDataTransformer($this, $customField));
$builder
->get($customField->getSlug())
->addModelTransformer(new CustomFieldDataTransformer($this, $customField));
}
public function buildOptionsForm(FormBuilderInterface $builder)

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace Chill\PersonBundle\Export\Export;
use Chill\MainBundle\Export\ListInterface;
@ -24,44 +26,26 @@ use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Chill\CustomFieldsBundle\CustomFields\CustomFieldChoice;
/**
* Render a list of peoples
*
* @author julien
* Render a list of people.
*/
class ListPerson implements ListInterface, ExportElementValidatedInterface
{
/**
*
* @var EntityManagerInterface
*/
protected $entityManager;
protected EntityManagerInterface $entityManager;
/**
*
* @var TranslatorInterface
*/
protected $translator;
protected TranslatorInterface $translator;
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
protected TranslatableStringHelper $translatableStringHelper;
/**
*
* @var CustomFieldProvider
*/
protected $customFieldProvider;
protected CustomFieldProvider $customFieldProvider;
protected $fields = array(
protected array $fields = [
'id', 'firstName', 'lastName', 'birthdate',
'placeOfBirth', 'gender', 'memo', 'email', 'phonenumber',
'mobilenumber', 'contactInfo', 'countryOfBirth', 'nationality',
'address_street_address_1', 'address_street_address_2',
'address_valid_from', 'address_postcode_label', 'address_postcode_code',
'address_country_name', 'address_country_code', 'address_isnoaddress'
);
];
private $slugs = [];
@ -77,11 +61,6 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
$this->customFieldProvider = $customFieldProvider;
}
/**
* {@inheritDoc}
*
* @param FormBuilderInterface $builder
*/
public function buildForm(FormBuilderInterface $builder)
{
$choices = array_combine($this->fields, $this->fields);
@ -99,13 +78,13 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
'expanded' => true,
'choices' => $choices,
'label' => 'Fields to include in export',
'choice_attr' => function($val, $key, $index) {
'choice_attr' => static function(string $val): array {
// add a 'data-display-target' for address fields
if (substr($val, 0, 8) === 'address_') {
return ['data-display-target' => 'address_date'];
} else {
return [];
}
return [];
},
'constraints' => [new Callback(array(
'callback' => function($selected, ExecutionContextInterface $context) {
@ -133,9 +112,10 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
public function validateForm($data, ExecutionContextInterface $context)
{
// get the field starting with address_
$addressFields = array_filter(function($el) {
return substr($el, 0, 8) === 'address_';
}, $this->fields);
$addressFields = array_filter(
$this->fields,
static fn(string $el): bool => substr($el, 0, 8) === 'address_'
);
// check if there is one field starting with address in data
if (count(array_intersect($data['fields'], $addressFields)) > 0) {
@ -168,41 +148,23 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
->getResult();
}
/**
* {@inheritDoc}
*
* @return type
*/
public function getAllowedFormattersTypes()
{
return array(FormatterInterface::TYPE_LIST);
}
/**
* {@inheritDoc}
*
* @return string
*/
public function getDescription()
{
return "Create a list of people according to various filters.";
}
/**
* {@inheritDoc}
*
* @param type $key
* @param array $values
* @param type $data
* @return type
*/
public function getLabels($key, array $values, $data)
{
switch ($key) {
case 'birthdate':
// for birthdate, we have to transform the string into a date
// to format the date correctly.
return function($value) {
return static function($value) {
if ($value === '_header') { return 'birthdate'; }
if (empty($value))
@ -257,27 +219,29 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
return $this->translatableStringHelper->localize(json_decode($value, true));
};
case 'address_isnoaddress':
return function($value) use ($key) {
if ($value === '_header') { return 'address.address_homeless'; }
if ($value) {
return 'X';
} else {
return '';
return static function(?string $value): string {
if ($value === '_header') {
return 'address.address_homeless';
}
if (null !== $value) {
return 'X';
}
return '';
};
default:
// for fields which are associated with person
if (in_array($key, $this->fields)) {
return function($value) use ($key) {
return static function($value) use ($key) {
if ($value === '_header') { return \strtolower($key); }
return $value;
};
} else {
return $this->getLabelForCustomField($key, $values, $data);
}
return $this->getLabelForCustomField($key, $values, $data);
}
}
@ -315,22 +279,16 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
if ($slugChoice === '_other' and $cfType->isChecked($cf, $choiceSlug, $decoded)) {
return $cfType->extractOtherValue($cf, $decoded);
} else {
return $cfType->isChecked($cf, $slugChoice, $decoded);
}
return $cfType->isChecked($cf, $slugChoice, $decoded);
};
} else {
return $defaultFunction;
}
return $defaultFunction;
}
/**
* {@inheritDoc}
*
* @param type $data
* @return type
*/
public function getQueryKeys($data)
{
$fields = array();
@ -346,15 +304,11 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
}
/**
* clean a slug to be usable by DQL
*
* @param string $slugsanitize
* @param string $type the type of the customfield, if required (currently only for choices)
* @return string
* Clean a slug to be usable by DQL.
*/
private function slugToDQL($slug, $type = "default", array $additionalInfos = [])
private function slugToDQL(string $slug, string $type = "default", array $additionalInfos = []): string
{
$uid = 'slug_'.\uniqid();
$uid = 'slug_' . \uniqid('', true);
$this->slugs[$uid] = [
'slug' => $slug,
@ -371,47 +325,28 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
}
/**
*
* @param type $cleanedSlug
* @return an array with keys = 'slug', 'type', 'additionnalInfo'
* @return array An array with keys = 'slug', 'type', 'additionnalInfo'
*/
private function extractInfosFromSlug($slug)
private function extractInfosFromSlug($slug): array
{
return $this->slugs[$slug];
}
/**
* {@inheritDoc}
*
*/
public function getResult($query, $data)
{
return $query->getQuery()->getResult(Query::HYDRATE_SCALAR);
}
/**
* {@inheritDoc}
*
* @return string
*/
public function getTitle()
{
return "List peoples";
}
/**
* {@inheritDoc}
*
*/
public function getType()
{
return Declarations::PERSON_TYPE;
}
/**
* {@inheritDoc}
*
*/
public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
{
$centers = array_map(function($el) { return $el['center']; }, $acl);
@ -483,19 +418,11 @@ class ListPerson implements ListInterface, ExportElementValidatedInterface
return $qb;
}
/**
*
* {@inheritDoc}
*/
public function requiredRole()
{
return new Role(PersonVoter::LISTS);
}
/**
*
* {@inheritDoc}
*/
public function supportsModifiers()
{
return array(Declarations::PERSON_TYPE, Declarations::PERSON_IMPLIED_IN);

View File

@ -1,26 +1,13 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace Chill\TaskBundle\Security\Authorization;
use Chill\EventBundle\Entity\Event;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Security\Authorization\AbstractChillVoter;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface;
use Chill\MainBundle\Security\Authorization\VoterHelperFactoryInterface;
use Chill\MainBundle\Security\Authorization\VoterHelperInterface;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
@ -41,13 +28,13 @@ use Chill\TaskBundle\Security\Authorization\AuthorizationEvent;
final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchyInterface
{
const CREATE_COURSE = 'CHILL_TASK_TASK_CREATE_FOR_COURSE';
const CREATE_PERSON = 'CHILL_TASK_TASK_CREATE_FOR_PERSON';
const DELETE = 'CHILL_TASK_TASK_DELETE';
const SHOW = 'CHILL_TASK_TASK_SHOW';
const UPDATE = 'CHILL_TASK_TASK_UPDATE';
public const CREATE_COURSE = 'CHILL_TASK_TASK_CREATE_FOR_COURSE';
public const CREATE_PERSON = 'CHILL_TASK_TASK_CREATE_FOR_PERSON';
public const DELETE = 'CHILL_TASK_TASK_DELETE';
public const SHOW = 'CHILL_TASK_TASK_SHOW';
public const UPDATE = 'CHILL_TASK_TASK_UPDATE';
const ROLES = [
public const ROLES = [
self::CREATE_COURSE,
self::CREATE_PERSON,
self::DELETE,
@ -55,33 +42,23 @@ final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchy
self::UPDATE,
];
protected AuthorizationHelper $authorizationHelper;
private AccessDecisionManagerInterface $accessDecisionManager;
protected AccessDecisionManagerInterface $accessDecisionManager;
private LoggerInterface $logger;
protected LoggerInterface $logger;
protected EventDispatcherInterface $eventDispatcher;
protected CenterResolverDispatcher $centerResolverDispatcher;
protected VoterHelperInterface $voter;
private EventDispatcherInterface $eventDispatcher;
private VoterHelperInterface $voter;
public function __construct(
VoterHelperFactoryInterface $voterHelperFactory,
AccessDecisionManagerInterface $accessDecisionManager,
AuthorizationHelper $authorizationHelper,
EventDispatcherInterface $eventDispatcher,
LoggerInterface $logger,
CenterResolverDispatcher $centerResolverDispatcher,
VoterHelperFactoryInterface $voterFactory
) {
$this->accessDecisionManager = $accessDecisionManager;
$this->authorizationHelper = $authorizationHelper;
$this->eventDispatcher = $eventDispatcher;
$this->logger = $logger;
$this->centerResolverDispatcher = $centerResolverDispatcher;
$this->voter = $voterFactory
->generate(AbstractTask::class)
@ -89,8 +66,7 @@ final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchy
->addCheckFor(Person::class, [self::SHOW, self::CREATE_PERSON])
->addCheckFor(AccompanyingPeriod::class, [self::SHOW, self::CREATE_COURSE])
->addCheckFor(null, [self::SHOW])
->build()
;
->build();
}
public function supports($attribute, $subject)
@ -98,13 +74,6 @@ final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchy
return $this->voter->supports($attribute, $subject);
}
/**
*
* @param string $attribute
* @param AbstractTask $subject
* @param TokenInterface $token
* @return boolean
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$this->logger->debug(sprintf("Voting from %s class", self::class));
@ -118,7 +87,6 @@ final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchy
$this->eventDispatcher->dispatch(AuthorizationEvent::VOTE, $event);
if ($event->hasVote()) {
$this->logger->debug("The TaskVoter is overriding by "
.AuthorizationEvent::VOTE, [
'vote' => $event->getVote(),
@ -167,5 +135,4 @@ final class TaskVoter extends AbstractChillVoter implements ProvideRoleHierarchy
{
return [];
}
}