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

@@ -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;
}
}