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

@@ -27,5 +27,4 @@ final readonly class AccompanyingCourseExportHelper
return $qb;
}
}

View File

@@ -11,7 +11,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\Export;
use Closure;
use Symfony\Component\Form\FormBuilderInterface;
/**
@@ -28,7 +27,7 @@ interface AggregatorInterface extends ModifierInterface
public function buildForm(FormBuilderInterface $builder);
/**
* Get the default data, that can be use as "data" for the form
* Get the default data, that can be use as "data" for the form.
*/
public function getFormDefaultData(): array;
@@ -72,11 +71,11 @@ interface AggregatorInterface extends ModifierInterface
* which do not need to be translated, or value already translated in
* database. But the header must be, in every case, translated.
*
* @param string $key The column key, as added in the query
* @param string $key The column key, as added in the query
* @param mixed[] $values The values from the result. if there are duplicates, those might be given twice. Example: array('FR', 'BE', 'CZ', 'FR', 'BE', 'FR')
* @param mixed $data The data from the export's form (as defined in `buildForm`
* @param mixed $data The data from the export's form (as defined in `buildForm`
*
* @return Closure where the first argument is the value, and the function should return the label to show in the formatted file. Example : `function($countryCode) use ($countries) { return $countries[$countryCode]->getName(); }`
* @return \Closure where the first argument is the value, and the function should return the label to show in the formatted file. Example : `function($countryCode) use ($countries) { return $countries[$countryCode]->getName(); }`
*/
public function getLabels($key, array $values, mixed $data);

View File

@@ -22,7 +22,7 @@ interface DirectExportInterface extends ExportElementInterface
public function buildForm(FormBuilderInterface $builder);
/**
* Get the default data, that can be use as "data" for the form
* Get the default data, that can be use as "data" for the form.
*/
public function getFormDefaultData(): array;

View File

@@ -11,8 +11,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\Export;
use Symfony\Component\Form\FormBuilderInterface;
/**
* The common methods between different object used to build export (i.e. : ExportInterface,
* FilterInterface, AggregatorInterface).

View File

@@ -34,7 +34,7 @@ final readonly class ExportFormHelper
'centers', 'generate_centers' => ['centers' => $this->authorizationHelper->getReachableCenters($export->requiredRole())],
'export', 'generate_export' => ['export' => $this->getDefaultDataStepExport($export, $options)],
'formatter', 'generate_formatter' => ['formatter' => $this->getDefaultDataStepFormatter($options)],
default => throw new \LogicException("step not allowed : " . $step),
default => throw new \LogicException('step not allowed : '.$step),
};
}
@@ -58,7 +58,7 @@ final readonly class ExportFormHelper
foreach ($filters as $alias => $filter) {
$data[ExportType::FILTER_KEY][$alias] = [
FilterType::ENABLED_FIELD => false,
'form' => $filter->getFormDefaultData()
'form' => $filter->getFormDefaultData(),
];
}
@@ -99,7 +99,7 @@ final readonly class ExportFormHelper
'centers', 'generate_centers' => $this->savedExportDataToFormDataStepCenter($savedExport),
'export', 'generate_export' => $this->savedExportDataToFormDataStepExport($savedExport, $formOptions),
'formatter', 'generate_formatter' => $this->savedExportDataToFormDataStepFormatter($savedExport, $formOptions),
default => throw new \LogicException("this step is not allowed: " . $step),
default => throw new \LogicException('this step is not allowed: '.$step),
};
}
@@ -138,7 +138,7 @@ final readonly class ExportFormHelper
);
$builder->add('export', ExportType::class, [
'export_alias' => $savedExport->getExportAlias(), ...$formOptions
'export_alias' => $savedExport->getExportAlias(), ...$formOptions,
]);
$form = $builder->getForm();
$form->submit($savedExport->getOptions()['export']);
@@ -160,7 +160,7 @@ final readonly class ExportFormHelper
);
$builder->add('formatter', FormatterType::class, [
'export_alias' => $savedExport->getExportAlias(), ...$formOptions
'export_alias' => $savedExport->getExportAlias(), ...$formOptions,
]);
$form = $builder->getForm();
$form->submit($savedExport->getOptions()['formatter']);

View File

@@ -25,6 +25,7 @@ use Symfony\Component\Form\FormBuilderInterface;
* aggregation, use `ListInterface`.
*
* @example Chill\PersonBundle\Export\CountPerson an example of implementation
*
* @template Q of QueryBuilder|NativeQuery
*/
interface ExportInterface extends ExportElementInterface
@@ -35,7 +36,7 @@ interface ExportInterface extends ExportElementInterface
public function buildForm(FormBuilderInterface $builder);
/**
* Get the default data, that can be use as "data" for the form
* Get the default data, that can be use as "data" for the form.
*/
public function getFormDefaultData(): array;
@@ -93,11 +94,11 @@ interface ExportInterface extends ExportElementInterface
* which do not need to be translated, or value already translated in
* database. But the header must be, in every case, translated.
*
* @param string $key The column key, as added in the query
* @param string $key The column key, as added in the query
* @param mixed[] $values The values from the result. if there are duplicates, those might be given twice. Example: array('FR', 'BE', 'CZ', 'FR', 'BE', 'FR')
* @param mixed $data The data from the export's form (as defined in `buildForm`)
* @param mixed $data The data from the export's form (as defined in `buildForm`)
*
* @return (callable(null|string|int|float|'_header' $value): string|int|\DateTimeInterface) where the first argument is the value, and the function should return the label to show in the formatted file. Example : `function($countryCode) use ($countries) { return $countries[$countryCode]->getName(); }`
* @return (callable(string|int|float|'_header'|null $value): string|int|\DateTimeInterface) where the first argument is the value, and the function should return the label to show in the formatted file. Example : `function($countryCode) use ($countries) { return $countries[$countryCode]->getName(); }`
*/
public function getLabels($key, array $values, mixed $data);
@@ -115,8 +116,8 @@ interface ExportInterface extends ExportElementInterface
/**
* Return the results of the query builder.
*
* @param Q $query
* @param mixed[] $data the data from the export's fomr (added by self::buildForm)
* @param Q $query
* @param mixed[] $data the data from the export's fomr (added by self::buildForm)
*
* @return mixed[] an array of results
*/
@@ -142,10 +143,10 @@ interface ExportInterface extends ExportElementInterface
*
* The returned object should be an instance of QueryBuilder or NativeQuery.
*
* @param array $acl an array where each row has a `center` key containing the Chill\MainBundle\Entity\Center, and `circles` keys containing the reachable circles. Example: `array( array('center' => $centerA, 'circles' => array($circleA, $circleB) ) )`
* @param array $acl an array where each row has a `center` key containing the Chill\MainBundle\Entity\Center, and `circles` keys containing the reachable circles. Example: `array( array('center' => $centerA, 'circles' => array($circleA, $circleB) ) )`
* @param array $data the data from the form, if any
*
* @return Q the query to execute.
* @return Q the query to execute
*/
public function initiateQuery(array $requiredModifiers, array $acl, array $data = []);

View File

@@ -14,21 +14,11 @@ namespace Chill\MainBundle\Export;
use Chill\MainBundle\Form\Type\Export\ExportType;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface;
use Doctrine\ORM\QueryBuilder;
use Generator;
use LogicException;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use UnexpectedValueException;
use function array_key_exists;
use function count;
use function get_class;
use function gettype;
use function in_array;
/**
* Collects all agregators, filters and export from
@@ -74,19 +64,19 @@ class ExportManager
iterable $exports,
iterable $aggregators,
iterable $filters
//iterable $formatters,
//iterable $exportElementProvider
// iterable $formatters,
// iterable $exportElementProvider
) {
$this->user = $tokenStorage->getToken()->getUser();
$this->exports = iterator_to_array($exports);
$this->aggregators = iterator_to_array($aggregators);
$this->filters = iterator_to_array($filters);
// NOTE: PHP crashes on the next line (exit error code 11). This is desactivated until further investigation
//$this->formatters = iterator_to_array($formatters);
// $this->formatters = iterator_to_array($formatters);
//foreach ($exportElementProvider as $prefix => $provider) {
// foreach ($exportElementProvider as $prefix => $provider) {
// $this->addExportElementsProvider($provider, $prefix);
//}
// }
}
/**
@@ -101,7 +91,7 @@ class ExportManager
*
* @return FilterInterface[] a \Generator that contains filters. The key is the filter's alias
*/
public function &getFiltersApplyingOn(DirectExportInterface|ExportInterface $export, ?array $centers = null): iterable
public function &getFiltersApplyingOn(DirectExportInterface|ExportInterface $export, array $centers = null): iterable
{
if ($export instanceof DirectExportInterface) {
return;
@@ -109,7 +99,7 @@ class ExportManager
foreach ($this->filters as $alias => $filter) {
if (
in_array($filter->applyOn(), $export->supportsModifiers(), true)
\in_array($filter->applyOn(), $export->supportsModifiers(), true)
&& $this->isGrantedForElement($filter, $export, $centers)
) {
yield $alias => $filter;
@@ -122,9 +112,9 @@ class ExportManager
*
* @internal This class check the interface implemented by export, and, if ´ListInterface´ is used, return an empty array
*
* @return null|iterable<string, AggregatorInterface> a \Generator that contains aggretagors. The key is the filter's alias
* @return iterable<string, AggregatorInterface>|null a \Generator that contains aggretagors. The key is the filter's alias
*/
public function &getAggregatorsApplyingOn(DirectExportInterface|ExportInterface $export, ?array $centers = null): ?iterable
public function &getAggregatorsApplyingOn(DirectExportInterface|ExportInterface $export, array $centers = null): ?iterable
{
if ($export instanceof ListInterface || $export instanceof DirectExportInterface) {
return;
@@ -132,7 +122,7 @@ class ExportManager
foreach ($this->aggregators as $alias => $aggregator) {
if (
in_array($aggregator->applyOn(), $export->supportsModifiers(), true)
\in_array($aggregator->applyOn(), $export->supportsModifiers(), true)
&& $this->isGrantedForElement($aggregator, $export, $centers)
) {
yield $alias => $aggregator;
@@ -143,7 +133,7 @@ class ExportManager
public function addExportElementsProvider(ExportElementsProviderInterface $provider, string $prefix): void
{
foreach ($provider->getExportElements() as $suffix => $element) {
$alias = $prefix . '_' . $suffix;
$alias = $prefix.'_'.$suffix;
if ($element instanceof ExportInterface) {
$this->exports[$alias] = $element;
@@ -154,8 +144,7 @@ class ExportManager
} elseif ($element instanceof FormatterInterface) {
$this->addFormatter($element, $alias);
} else {
throw new LogicException('This element ' . $element::class . ' '
. 'is not an instance of export element');
throw new \LogicException('This element '.$element::class.' is not an instance of export element');
}
}
}
@@ -194,37 +183,27 @@ class ExportManager
if ($query instanceof \Doctrine\ORM\NativeQuery) {
// throw an error if the export require other modifier, which is
// not allowed when the export return a `NativeQuery`
if (count($export->supportsModifiers()) > 0) {
throw new LogicException("The export with alias `{$exportAlias}` return "
. 'a `\\Doctrine\\ORM\\NativeQuery` and supports modifiers, which is not '
. 'allowed. Either the method `supportsModifiers` should return an empty '
. 'array, or return a `Doctrine\\ORM\\QueryBuilder`');
if (\count($export->supportsModifiers()) > 0) {
throw new \LogicException("The export with alias `{$exportAlias}` return ".'a `\\Doctrine\\ORM\\NativeQuery` and supports modifiers, which is not allowed. Either the method `supportsModifiers` should return an empty array, or return a `Doctrine\\ORM\\QueryBuilder`');
}
} elseif ($query instanceof QueryBuilder) {
//handle filters
// handle filters
$this->handleFilters($export, $query, $data[ExportType::FILTER_KEY], $centers);
//handle aggregators
// handle aggregators
$this->handleAggregators($export, $query, $data[ExportType::AGGREGATOR_KEY], $centers);
$this->logger->notice('[export] will execute this qb in export', [
'dql' => $query->getDQL(),
]);
} else {
throw new UnexpectedValueException('The method `intiateQuery` should return '
. 'a `\\Doctrine\\ORM\\NativeQuery` or a `Doctrine\\ORM\\QueryBuilder` '
. 'object.');
throw new \UnexpectedValueException('The method `intiateQuery` should return a `\\Doctrine\\ORM\\NativeQuery` or a `Doctrine\\ORM\\QueryBuilder` object.');
}
$result = $export->getResult($query, $data[ExportType::EXPORT_KEY]);
if (!is_iterable($result)) {
throw new UnexpectedValueException(
sprintf(
'The result of the export should be an iterable, %s given',
gettype($result)
)
);
throw new \UnexpectedValueException(sprintf('The result of the export should be an iterable, %s given', \gettype($result)));
}
/** @var FormatterInterface $formatter */
@@ -259,14 +238,14 @@ class ExportManager
/**
* @param string $alias
*
* @throws RuntimeException if the aggregator is not known
*
* @return AggregatorInterface
*
* @throws \RuntimeException if the aggregator is not known
*/
public function getAggregator($alias)
{
if (!array_key_exists($alias, $this->aggregators)) {
throw new RuntimeException("The aggregator with alias {$alias} is not known.");
if (!\array_key_exists($alias, $this->aggregators)) {
throw new \RuntimeException("The aggregator with alias {$alias} is not known.");
}
return $this->aggregators[$alias];
@@ -283,7 +262,7 @@ class ExportManager
}
/**
* Get the types for known exports
* Get the types for known exports.
*
* @return list<string> the existing type for known exports
*/
@@ -292,7 +271,7 @@ class ExportManager
$existingTypes = [];
foreach ($this->exports as $export) {
if (!in_array($export->getType(), $existingTypes, true)) {
if (!\in_array($export->getType(), $existingTypes, true)) {
$existingTypes[] = $export->getType();
}
}
@@ -305,12 +284,12 @@ class ExportManager
*
* @param string $alias
*
* @throws RuntimeException
* @throws \RuntimeException
*/
public function getExport($alias): DirectExportInterface|ExportInterface
{
if (!array_key_exists($alias, $this->exports)) {
throw new RuntimeException("The export with alias {$alias} is not known.");
if (!\array_key_exists($alias, $this->exports)) {
throw new \RuntimeException("The export with alias {$alias} is not known.");
}
return $this->exports[$alias];
@@ -339,7 +318,6 @@ class ExportManager
/**
* Get all exports grouped in an array.
*
*
* @return array<string, array<string, ExportInterface|DirectExportInterface>> where keys are the groups's name and value is an array of exports
*/
public function getExportsGrouped(bool $whereUserIsGranted = true): array
@@ -358,12 +336,12 @@ class ExportManager
}
/**
* @throws RuntimeException if the filter is not known
* @throws \RuntimeException if the filter is not known
*/
public function getFilter(string $alias): FilterInterface
{
if (!array_key_exists($alias, $this->filters)) {
throw new RuntimeException("The filter with alias {$alias} is not known.");
if (!\array_key_exists($alias, $this->filters)) {
throw new \RuntimeException("The filter with alias {$alias} is not known.");
}
return $this->filters[$alias];
@@ -373,6 +351,7 @@ class ExportManager
* get all filters.
*
* @param array<string> $aliases
*
* @return iterable<string, FilterInterface> $aliases
*/
public function getFilters(array $aliases): iterable
@@ -384,8 +363,8 @@ class ExportManager
public function getFormatter(string $alias): FormatterInterface
{
if (!array_key_exists($alias, $this->formatters)) {
throw new RuntimeException("The formatter with alias {$alias} is not known.");
if (!\array_key_exists($alias, $this->formatters)) {
throw new \RuntimeException("The formatter with alias {$alias} is not known.");
}
return $this->formatters[$alias];
@@ -395,11 +374,12 @@ class ExportManager
* get the formatter alias from the form export data.
*
* @param array $data the data from the export form
*
* @string the formatter alias|null
*/
public function getFormatterAlias(array $data): ?string
{
if (array_key_exists(ExportType::PICK_FORMATTER_KEY, $data)) {
if (\array_key_exists(ExportType::PICK_FORMATTER_KEY, $data)) {
return $data[ExportType::PICK_FORMATTER_KEY]['alias'];
}
@@ -414,7 +394,7 @@ class ExportManager
public function getFormattersByTypes(array $types): iterable
{
foreach ($this->formatters as $alias => $formatter) {
if (in_array($formatter->getType(), $types, true)) {
if (\in_array($formatter->getType(), $types, true)) {
yield $alias => $formatter;
}
}
@@ -450,21 +430,18 @@ class ExportManager
/**
* Return true if the current user has access to the ExportElement for every
* center, false if the user hasn't access to element for at least one center.
*
*/
public function isGrantedForElement(
DirectExportInterface|ExportInterface|ModifierInterface $element,
\Chill\MainBundle\Export\DirectExportInterface|\Chill\MainBundle\Export\ExportInterface $export = null,
?array $centers = null
DirectExportInterface|ExportInterface $export = null,
array $centers = null
): bool {
if ($element instanceof ExportInterface || $element instanceof DirectExportInterface) {
$role = $element->requiredRole();
} else {
if (null === $element->addRole()) {
if (null === $export) {
throw new LogicException('The export should not be null: as the '
. 'ModifierInstance element is not an export, we should '
. 'be aware of the export to determine which role is required');
throw new \LogicException('The export should not be null: as the ModifierInstance element is not an export, we should be aware of the export to determine which role is required');
}
$role = $export->requiredRole();
} else {
@@ -482,7 +459,7 @@ class ExportManager
foreach ($centers as $center) {
if (false === $this->authorizationChecker->isGranted($role, $center)) {
//debugging
// debugging
$this->logger->debug('user has no access to element', [
'method' => __METHOD__,
'type' => $element::class,
@@ -538,9 +515,8 @@ class ExportManager
$aggregators = $this->retrieveUsedAggregators($data);
foreach ($aggregators as $alias => $aggregator) {
if ($this->isGrantedForElement($aggregator, $export, $center) === false) {
throw new UnauthorizedHttpException('You are not authorized to '
. 'use the aggregator' . $aggregator->getTitle());
if (false === $this->isGrantedForElement($aggregator, $export, $center)) {
throw new UnauthorizedHttpException('You are not authorized to use the aggregator'.$aggregator->getTitle());
}
$formData = $data[$alias];
@@ -553,8 +529,9 @@ class ExportManager
*
* This function check the acl.
*
* @param mixed $data the data under the initial 'filters' data
* @param mixed $data the data under the initial 'filters' data
* @param \Chill\MainBundle\Entity\Center[] $centers the picked centers
*
* @throw UnauthorizedHttpException if the user is not authorized
*/
private function handleFilters(
@@ -566,14 +543,13 @@ class ExportManager
$filters = $this->retrieveUsedFilters($data);
foreach ($filters as $alias => $filter) {
if ($this->isGrantedForElement($filter, $export, $centers) === false) {
throw new UnauthorizedHttpException('You are not authorized to '
. 'use the filter ' . $filter->getTitle());
if (false === $this->isGrantedForElement($filter, $export, $centers)) {
throw new UnauthorizedHttpException('You are not authorized to use the filter '.$filter->getTitle());
}
$formData = $data[$alias];
$this->logger->debug('alter query by filter ' . $alias, [
$this->logger->debug('alter query by filter '.$alias, [
'class' => self::class, 'function' => __FUNCTION__,
]);
$filter->alterQuery($qb, $formData['form']);
@@ -608,7 +584,7 @@ class ExportManager
$usedTypes = [];
foreach ($this->retrieveUsedAggregators($data) as $alias => $aggregator) {
if (!in_array($aggregator->applyOn(), $usedTypes, true)) {
if (!\in_array($aggregator->applyOn(), $usedTypes, true)) {
$usedTypes[] = $aggregator->applyOn();
}
}
@@ -651,7 +627,7 @@ class ExportManager
if (true === $filterData['enabled']) {
$filter = $this->getFilter($alias);
if (!in_array($filter->applyOn(), $usedTypes, true)) {
if (!\in_array($filter->applyOn(), $usedTypes, true)) {
$usedTypes[] = $filter->applyOn();
}
}
@@ -663,7 +639,6 @@ class ExportManager
/**
* parse the data to retrieve the used filters and aggregators.
*
*
* @return string[]
*/
private function retrieveUsedModifiers(mixed $data)
@@ -678,7 +653,7 @@ class ExportManager
);
$this->logger->debug(
'Required types are ' . implode(', ', $usedTypes),
'Required types are '.implode(', ', $usedTypes),
['class' => self::class, 'function' => __FUNCTION__]
);

View File

@@ -31,7 +31,7 @@ interface FilterInterface extends ModifierInterface
public function buildForm(FormBuilderInterface $builder);
/**
* Get the default data, that can be use as "data" for the form
* Get the default data, that can be use as "data" for the form.
*/
public function getFormDefaultData(): array;
@@ -60,7 +60,7 @@ interface FilterInterface extends ModifierInterface
*
* Example: `array('my string with %parameter%', ['%parameter%' => 'good news'], 'mydomain', 'mylocale')`
*
* @param array $data
* @param array $data
* @param string $format the format
*
* @return array|string a string with the data or, if translatable, an array where first element is string, second elements is an array of arguments

View File

@@ -13,25 +13,18 @@ namespace Chill\MainBundle\Export\Formatter;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Export\FormatterInterface;
use LogicException;
use RuntimeException;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
use function array_slice;
use function call_user_func;
use function count;
use function is_array;
/**
* Command to get the report with curl:
* curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff.
*
* @deprecated this formatter is not used any more.
* @deprecated this formatter is not used any more
*/
class CSVFormatter implements FormatterInterface
{
@@ -65,13 +58,11 @@ class CSVFormatter implements FormatterInterface
/**
* @uses appendAggregatorForm
*
* @param mixed $exportAlias
*/
public function buildForm(FormBuilderInterface $builder, $exportAlias, array $aggregatorAliases)
{
$aggregators = $this->exportManager->getAggregators($aggregatorAliases);
$nb = count($aggregatorAliases);
$nb = \count($aggregatorAliases);
foreach ($aggregators as $alias => $aggregator) {
$builderAggregator = $builder->create($alias, FormType::class, [
@@ -101,7 +92,7 @@ class CSVFormatter implements FormatterInterface
continue;
}
if (is_array($statement)) {
if (\is_array($statement)) {
$descriptions[] = $this->translator->trans(
$statement[0],
$statement[1],
@@ -142,7 +133,7 @@ class CSVFormatter implements FormatterInterface
$response = new Response();
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
//$response->headers->set('Content-Disposition','attachment; filename="export.csv"');
// $response->headers->set('Content-Disposition','attachment; filename="export.csv"');
$response->setContent($this->generateContent());
@@ -172,10 +163,8 @@ class CSVFormatter implements FormatterInterface
// gather data in an array
foreach ($keys as $key) {
$values = array_map(static function ($row) use ($key, $alias) {
if (!array_key_exists($key, $row)) {
throw new LogicException("the key '" . $key . "' is declared by "
. "the aggregator with alias '" . $alias . "' but is not "
. 'present in results');
if (!\array_key_exists($key, $row)) {
throw new \LogicException("the key '".$key."' is declared by the aggregator with alias '".$alias."' but is not ".'present in results');
}
return $row[$key];
@@ -199,10 +188,8 @@ class CSVFormatter implements FormatterInterface
foreach ($keys as $key) {
$values = array_map(static function ($row) use ($key, $export) {
if (!array_key_exists($key, $row)) {
throw new LogicException("the key '" . $key . "' is declared by "
. "the export with title '" . $export->getTitle() . "' but is not "
. 'present in results');
if (!\array_key_exists($key, $row)) {
throw new \LogicException("the key '".$key."' is declared by the export with title '".$export->getTitle()."' but is not ".'present in results');
}
return $row[$key];
@@ -220,9 +207,9 @@ class CSVFormatter implements FormatterInterface
protected function generateContent()
{
$line = null;
$rowKeysNb = count($this->getRowHeaders());
$columnKeysNb = count($this->getColumnHeaders());
$resultsKeysNb = count($this->export->getQueryKeys($this->exportData));
$rowKeysNb = \count($this->getRowHeaders());
$columnKeysNb = \count($this->getColumnHeaders());
$resultsKeysNb = \count($this->export->getQueryKeys($this->exportData));
$results = $this->getOrderedResults();
/** @var string[] $columnHeaders the column headers associations */
$columnHeaders = [];
@@ -233,9 +220,9 @@ class CSVFormatter implements FormatterInterface
// create a file pointer connected to the output stream
$output = fopen('php://output', 'wb');
//title
// title
fputcsv($output, [$this->translator->trans($this->export->getTitle())]);
//blank line
// blank line
fputcsv($output, ['']);
// add filtering description
@@ -247,32 +234,32 @@ class CSVFormatter implements FormatterInterface
// iterate on result to : 1. populate row headers, 2. populate column headers, 3. add result
foreach ($results as $row) {
$rowHeaders = array_slice($row, 0, $rowKeysNb);
$rowHeaders = \array_slice($row, 0, $rowKeysNb);
//first line : we create line and adding them row headers
// first line : we create line and adding them row headers
if (!isset($line)) {
$line = array_slice($row, 0, $rowKeysNb);
$line = \array_slice($row, 0, $rowKeysNb);
}
// do we have to create a new line ? if the rows are equals, continue on the line, else create a next line
if (array_slice($line, 0, $rowKeysNb) !== $rowHeaders) {
if (\array_slice($line, 0, $rowKeysNb) !== $rowHeaders) {
$contentData[] = $line;
$line = array_slice($row, 0, $rowKeysNb);
$line = \array_slice($row, 0, $rowKeysNb);
}
// add the column headers
/** @var string[] $columns the column for this row */
$columns = array_slice($row, $rowKeysNb, $columnKeysNb);
$columns = \array_slice($row, $rowKeysNb, $columnKeysNb);
$columnPosition = $this->findColumnPosition($columnHeaders, $columns);
//fill with blank at the position given by the columnPosition + nbRowHeaders
// fill with blank at the position given by the columnPosition + nbRowHeaders
for ($i = 0; $i < $columnPosition; ++$i) {
if (!isset($line[$rowKeysNb + $i])) {
$line[$rowKeysNb + $i] = '';
}
}
$resultData = array_slice($row, $resultsKeysNb * -1);
$resultData = \array_slice($row, $resultsKeysNb * -1);
foreach ($resultData as $data) {
$line[] = $data;
@@ -282,7 +269,7 @@ class CSVFormatter implements FormatterInterface
// we add the last line
$contentData[] = $line;
//column title headers
// column title headers
for ($i = 0; $i < $columnKeysNb; ++$i) {
$line = array_fill(0, $rowKeysNb, '');
@@ -293,22 +280,22 @@ class CSVFormatter implements FormatterInterface
$content[] = $line;
}
//row title headers
// row title headers
$headerLine = [];
foreach ($this->getRowHeaders() as $headerKey) {
$headerLine[] = array_key_exists('_header', $this->labels[$headerKey]) ?
$headerLine[] = \array_key_exists('_header', $this->labels[$headerKey]) ?
$this->labels[$headerKey]['_header'] : '';
}
foreach ($this->export->getQueryKeys($this->exportData) as $key) {
$headerLine[] = array_key_exists('_header', $this->labels[$key]) ?
$headerLine[] = \array_key_exists('_header', $this->labels[$key]) ?
$this->labels[$key]['_header'] : '';
}
fputcsv($output, $headerLine);
unset($headerLine); //free memory
unset($headerLine); // free memory
//generate CSV
// generate CSV
foreach ($content as $line) {
fputcsv($output, $line);
}
@@ -390,7 +377,7 @@ class CSVFormatter implements FormatterInterface
++$i;
}
//we didn't find it, adding the column
// we didn't find it, adding the column
$columnHeaders[] = $columnToFind;
return $i++;
@@ -410,12 +397,12 @@ class CSVFormatter implements FormatterInterface
$line = [];
foreach ($headers as $key) {
$line[] = call_user_func($labels[$key], $row[$key]);
$line[] = \call_user_func($labels[$key], $row[$key]);
}
//append result
// append result
foreach ($resultsKeys as $key) {
$line[] = call_user_func($labels[$key], $row[$key]);
$line[] = \call_user_func($labels[$key], $row[$key]);
}
$r[] = $line;
@@ -429,19 +416,17 @@ class CSVFormatter implements FormatterInterface
/**
* @param string $position may be 'c' (column) or 'r' (row)
*
* @throws RuntimeException
*
* @return string[]
*
* @throws \RuntimeException
*/
private function getPositionnalHeaders($position)
{
$headers = [];
foreach ($this->formatterData as $alias => $data) {
if (!array_key_exists($alias, $this->aggregatorsData)) {
throw new RuntimeException('the formatter wants to use the '
. "aggregator with alias {$alias}, but the export do not "
. 'contains data about it');
if (!\array_key_exists($alias, $this->aggregatorsData)) {
throw new \RuntimeException('the formatter wants to use the '."aggregator with alias {$alias}, but the export do not ".'contains data about it');
}
$aggregator = $this->aggregators[$alias];

View File

@@ -13,18 +13,11 @@ namespace Chill\MainBundle\Export\Formatter;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Export\FormatterInterface;
use LogicException;
use OutOfBoundsException;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
use function array_keys;
use function array_map;
use function count;
use function implode;
// command to get the report with curl : curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff
@@ -101,11 +94,11 @@ class CSVListFormatter implements FormatterInterface
/**
* Generate a response from the data collected on differents ExportElementInterface.
*
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
*
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/
@@ -150,7 +143,7 @@ class CSVListFormatter implements FormatterInterface
$response = new Response();
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
//$response->headers->set('Content-Disposition','attachment; filename="export.csv"');
// $response->headers->set('Content-Disposition','attachment; filename="export.csv"');
$response->setContent($csvContent);
@@ -168,9 +161,9 @@ class CSVListFormatter implements FormatterInterface
* @param string $key
* @param string $value
*
* @throws LogicException if the label is not found
*
* @return string
*
* @throws \LogicException if the label is not found
*/
protected function getLabel($key, $value)
{
@@ -178,15 +171,8 @@ class CSVListFormatter implements FormatterInterface
$this->prepareCacheLabels();
}
if (!array_key_exists($key, $this->labelsCache)) {
throw new OutOfBoundsException(sprintf(
'The key "%s" '
. 'is not present in the list of keys handled by '
. 'this query. Check your `getKeys` and `getLabels` '
. 'methods. Available keys are %s.',
$key,
implode(', ', array_keys($this->labelsCache))
));
if (!\array_key_exists($key, $this->labelsCache)) {
throw new \OutOfBoundsException(sprintf('The key "%s" is not present in the list of keys handled by this query. Check your `getKeys` and `getLabels` methods. Available keys are %s.', $key, \implode(', ', \array_keys($this->labelsCache))));
}
return $this->labelsCache[$key]($value);
@@ -203,7 +189,7 @@ class CSVListFormatter implements FormatterInterface
foreach ($keys as $key) {
// get an array with all values for this key if possible
$values = array_map(static fn ($v) => $v[$key], $this->result);
$values = \array_map(static fn ($v) => $v[$key], $this->result);
// store the label in the labelsCache property
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
}
@@ -218,7 +204,7 @@ class CSVListFormatter implements FormatterInterface
{
$keys = $this->exportManager->getExport($this->exportAlias)->getQueryKeys($this->exportData);
// we want to keep the order of the first row. So we will iterate on the first row of the results
$first_row = count($this->result) > 0 ? $this->result[0] : [];
$first_row = \count($this->result) > 0 ? $this->result[0] : [];
$header_line = [];
if (true === $this->formatterData['numerotation']) {
@@ -231,7 +217,7 @@ class CSVListFormatter implements FormatterInterface
);
}
if (count($header_line) > 0) {
if (\count($header_line) > 0) {
fputcsv($output, $header_line);
}
}

View File

@@ -13,15 +13,11 @@ namespace Chill\MainBundle\Export\Formatter;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Export\FormatterInterface;
use LogicException;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_map;
use function count;
/**
* Create a CSV List for the export where the header are printed on the
* first column, and the result goes from left to right.
@@ -97,11 +93,11 @@ class CSVPivotedListFormatter implements FormatterInterface
/**
* Generate a response from the data collected on differents ExportElementInterface.
*
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
*
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/
@@ -139,7 +135,7 @@ class CSVPivotedListFormatter implements FormatterInterface
++$i;
}
//adding the lines to the csv output
// adding the lines to the csv output
foreach ($lines as $line) {
fputcsv($output, $line);
}
@@ -168,9 +164,9 @@ class CSVPivotedListFormatter implements FormatterInterface
* @param string $key
* @param string $value
*
* @throws LogicException if the label is not found
*
* @return string
*
* @throws \LogicException if the label is not found
*/
protected function getLabel($key, $value)
{
@@ -192,7 +188,7 @@ class CSVPivotedListFormatter implements FormatterInterface
foreach ($keys as $key) {
// get an array with all values for this key if possible
$values = array_map(static fn ($v) => $v[$key], $this->result);
$values = \array_map(static fn ($v) => $v[$key], $this->result);
// store the label in the labelsCache property
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
}
@@ -207,7 +203,7 @@ class CSVPivotedListFormatter implements FormatterInterface
{
$keys = $this->exportManager->getExport($this->exportAlias)->getQueryKeys($this->exportData);
// we want to keep the order of the first row. So we will iterate on the first row of the results
$first_row = count($this->result) > 0 ? $this->result[0] : [];
$first_row = \count($this->result) > 0 ? $this->result[0] : [];
$header_line = [];
if (true === $this->formatterData['numerotation']) {

View File

@@ -13,7 +13,6 @@ namespace Chill\MainBundle\Export\Formatter;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Export\FormatterInterface;
use LogicException;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
@@ -21,19 +20,6 @@ use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_map;
use function array_merge;
use function array_multisort;
use function array_unique;
use function call_user_func;
use function count;
use function fopen;
use function is_array;
use function stream_get_contents;
use function sys_get_temp_dir;
use function tempnam;
use function unlink;
class SpreadSheetFormatter implements FormatterInterface
{
/**
@@ -60,7 +46,7 @@ class SpreadSheetFormatter implements FormatterInterface
*
* @var type
*/
//protected $aggregators;
// protected $aggregators;
/**
* array containing value of export form.
@@ -104,7 +90,7 @@ class SpreadSheetFormatter implements FormatterInterface
*
* @var array
*/
//protected $labels;
// protected $labels;
/**
* temporary file to store spreadsheet.
@@ -157,7 +143,7 @@ class SpreadSheetFormatter implements FormatterInterface
// ordering aggregators
$aggregators = $this->exportManager->getAggregators($aggregatorAliases);
$nb = count($aggregatorAliases);
$nb = \count($aggregatorAliases);
foreach ($aggregators as $alias => $aggregator) {
$builderAggregator = $builder->create($alias, FormType::class, [
@@ -212,15 +198,15 @@ class SpreadSheetFormatter implements FormatterInterface
$this->getContentType($this->formatterData['format'])
);
$this->tempfile = tempnam(sys_get_temp_dir(), '');
$this->tempfile = \tempnam(\sys_get_temp_dir(), '');
$this->generateContent();
$f = fopen($this->tempfile, 'rb');
$response->setContent(stream_get_contents($f));
$f = \fopen($this->tempfile, 'rb');
$response->setContent(\stream_get_contents($f));
fclose($f);
// remove the temp file from disk
unlink($this->tempfile);
\unlink($this->tempfile);
return $response;
}
@@ -238,11 +224,11 @@ class SpreadSheetFormatter implements FormatterInterface
$worksheet->fromArray(
$sortedResults,
null,
'A' . $line,
'A'.$line,
true
);
return $line + count($sortedResults) + 1;
return $line + \count($sortedResults) + 1;
}
/**
@@ -260,7 +246,7 @@ class SpreadSheetFormatter implements FormatterInterface
$filter = $this->exportManager->getFilter($alias);
$description = $filter->describeAction($data, 'string');
if (is_array($description)) {
if (\is_array($description)) {
$description = $this->translator
->trans(
$description[0],
@@ -268,7 +254,7 @@ class SpreadSheetFormatter implements FormatterInterface
);
}
$worksheet->setCellValue('A' . $line, $description);
$worksheet->setCellValue('A'.$line, $description);
++$line;
}
@@ -303,7 +289,7 @@ class SpreadSheetFormatter implements FormatterInterface
$worksheet->fromArray(
$displayables,
null,
'A' . $line
'A'.$line
);
return $line + 1;
@@ -359,7 +345,7 @@ class SpreadSheetFormatter implements FormatterInterface
'ods' => \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Ods'),
'xlsx' => \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'),
'csv' => \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Csv'),
default => throw new LogicException(),
default => throw new \LogicException(),
};
$writer->save($this->tempfile);
@@ -383,7 +369,7 @@ class SpreadSheetFormatter implements FormatterInterface
$aggregator = $this->exportManager->getAggregator($alias);
$aggregatorsKeys = $aggregator->getQueryKeys($data);
// append the keys from aggregator to the $keys existing array
$keys = array_merge($keys, $aggregatorsKeys);
$keys = \array_merge($keys, $aggregatorsKeys);
// append the key with the alias, which will be use later for sorting
foreach ($aggregatorsKeys as $key) {
$aggregatorKeyAssociation[$key] = $alias;
@@ -420,7 +406,7 @@ class SpreadSheetFormatter implements FormatterInterface
case 'xlsx':
return 'application/vnd.openxmlformats-officedocument.'
. 'spreadsheetml.sheet';
.'spreadsheetml.sheet';
}
}
@@ -439,7 +425,7 @@ class SpreadSheetFormatter implements FormatterInterface
$value ??= '';
return call_user_func($this->cacheDisplayableResult[$key], $value);
return \call_user_func($this->cacheDisplayableResult[$key], $value);
}
protected function getTitle()
@@ -447,7 +433,7 @@ class SpreadSheetFormatter implements FormatterInterface
$title = $this->translator->trans($this->export->getTitle());
if (30 < strlen($title)) {
return substr($title, 0, 30) . '…';
return substr($title, 0, 30).'…';
}
return $title;
@@ -499,7 +485,7 @@ class SpreadSheetFormatter implements FormatterInterface
$this->cacheDisplayableResult[$key] = $element->getLabels($key, ['_header'], $data);
} else {
$this->cacheDisplayableResult[$key] =
$element->getLabels($key, array_unique($allValues[$key]), $data);
$element->getLabels($key, \array_unique($allValues[$key]), $data);
}
}
@@ -548,9 +534,9 @@ class SpreadSheetFormatter implements FormatterInterface
$exportKeys = $this->export->getQueryKeys($this->exportData);
$aggregatorKeys = $this->getAggregatorKeysSorted();
$globalKeys = array_merge($aggregatorKeys, $exportKeys);
$globalKeys = \array_merge($aggregatorKeys, $exportKeys);
$sortedResult = array_map(function ($row) use ($globalKeys) {
$sortedResult = \array_map(function ($row) use ($globalKeys) {
$newRow = [];
foreach ($globalKeys as $key) {
@@ -560,7 +546,7 @@ class SpreadSheetFormatter implements FormatterInterface
return $newRow;
}, $this->result);
array_multisort($sortedResult);
\array_multisort($sortedResult);
return [$sortedResult, $exportKeys, $aggregatorKeys, $globalKeys];
}

View File

@@ -13,29 +13,15 @@ namespace Chill\MainBundle\Export\Formatter;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Export\FormatterInterface;
use DateTimeInterface;
use LogicException;
use OutOfBoundsException;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use RuntimeException;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
use function array_keys;
use function array_map;
use function count;
use function fopen;
use function implode;
use function stream_get_contents;
use function sys_get_temp_dir;
use function tempnam;
use function unlink;
// command to get the report with curl : curl --user "center a_social:password" "http://localhost:8000/fr/exports/generate/count_person?export[filters][person_gender_filter][enabled]=&export[filters][person_nationality_filter][enabled]=&export[filters][person_nationality_filter][form][nationalities]=&export[aggregators][person_nationality_aggregator][order]=1&export[aggregators][person_nationality_aggregator][form][group_by_level]=country&export[submit]=&export[_token]=RHpjHl389GrK-bd6iY5NsEqrD5UKOTHH40QKE9J1edU" --globoff
@@ -120,11 +106,11 @@ class SpreadsheetListFormatter implements FormatterInterface
/**
* Generate a response from the data collected on differents ExportElementInterface.
*
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
*
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/
@@ -150,20 +136,20 @@ class SpreadsheetListFormatter implements FormatterInterface
foreach ($result as $row) {
if (true === $this->formatterData['numerotation']) {
$worksheet->setCellValue('A' . ($i + 1), (string) $i);
$worksheet->setCellValue('A'.($i + 1), (string) $i);
}
$a = $this->formatterData['numerotation'] ? 'B' : 'A';
foreach ($row as $key => $value) {
$row = $a . ($i + 1);
$row = $a.($i + 1);
$formattedValue = $this->getLabel($key, $value);
if ($formattedValue instanceof DateTimeInterface) {
if ($formattedValue instanceof \DateTimeInterface) {
$worksheet->setCellValue($row, Date::PHPToExcel($formattedValue));
if ($formattedValue->format('His') === '000000') {
if ('000000' === $formattedValue->format('His')) {
$worksheet->getStyle($row)
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
@@ -191,7 +177,7 @@ class SpreadsheetListFormatter implements FormatterInterface
case 'xlsx':
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$contentType = 'application/vnd.openxmlformats-officedocument.'
. 'spreadsheetml.sheet';
.'spreadsheetml.sheet';
break;
@@ -204,22 +190,21 @@ class SpreadsheetListFormatter implements FormatterInterface
default:
// this should not happen
// throw an exception to ensure that the error is catched
throw new OutOfBoundsException('The format ' . $this->formatterData['format'] .
' is not supported');
throw new \OutOfBoundsException('The format '.$this->formatterData['format'].' is not supported');
}
$response = new Response();
$response->headers->set('content-type', $contentType);
$tempfile = tempnam(sys_get_temp_dir(), '');
$tempfile = \tempnam(\sys_get_temp_dir(), '');
$writer->save($tempfile);
$f = fopen($tempfile, 'rb');
$response->setContent(stream_get_contents($f));
$f = \fopen($tempfile, 'rb');
$response->setContent(\stream_get_contents($f));
fclose($f);
// remove the temp file from disk
unlink($tempfile);
\unlink($tempfile);
return $response;
}
@@ -235,9 +220,9 @@ class SpreadsheetListFormatter implements FormatterInterface
* @param string $key
* @param string $value
*
* @throws LogicException if the label is not found
*
* @return string
*
* @throws \LogicException if the label is not found
*/
protected function getLabel($key, $value)
{
@@ -245,15 +230,8 @@ class SpreadsheetListFormatter implements FormatterInterface
$this->prepareCacheLabels();
}
if (!array_key_exists($key, $this->labelsCache)) {
throw new OutOfBoundsException(sprintf(
'The key "%s" '
. 'is not present in the list of keys handled by '
. 'this query. Check your `getKeys` and `getLabels` '
. 'methods. Available keys are %s.',
$key,
implode(', ', array_keys($this->labelsCache))
));
if (!\array_key_exists($key, $this->labelsCache)) {
throw new \OutOfBoundsException(sprintf('The key "%s" is not present in the list of keys handled by this query. Check your `getKeys` and `getLabels` methods. Available keys are %s.', $key, \implode(', ', \array_keys($this->labelsCache))));
}
return $this->labelsCache[$key]($value);
@@ -270,9 +248,9 @@ class SpreadsheetListFormatter implements FormatterInterface
foreach ($keys as $key) {
// get an array with all values for this key if possible
$values = array_map(static function ($v) use ($key) {
if (!array_key_exists($key, $v)) {
throw new RuntimeException(sprintf('This key does not exists: %s. Available keys are %s', $key, implode(', ', array_keys($v))));
$values = \array_map(static function ($v) use ($key) {
if (!\array_key_exists($key, $v)) {
throw new \RuntimeException(sprintf('This key does not exists: %s. Available keys are %s', $key, \implode(', ', \array_keys($v))));
}
return $v[$key];
@@ -289,7 +267,7 @@ class SpreadsheetListFormatter implements FormatterInterface
{
$keys = $this->exportManager->getExport($this->exportAlias)->getQueryKeys($this->exportData);
// we want to keep the order of the first row. So we will iterate on the first row of the results
$first_row = count($this->result) > 0 ? $this->result[0] : [];
$first_row = \count($this->result) > 0 ? $this->result[0] : [];
$header_line = [];
if (true === $this->formatterData['numerotation']) {
@@ -302,7 +280,7 @@ class SpreadsheetListFormatter implements FormatterInterface
);
}
if (count($header_line) > 0) {
if (\count($header_line) > 0) {
$worksheet->fromArray($header_line, null, 'A1');
}
}

View File

@@ -25,8 +25,8 @@ interface FormatterInterface
*
* @uses appendAggregatorForm
*
* @param string $exportAlias Alias of the export which is being executed. An export gets the data and implements the \Chill\MainBundle\Export\ExportInterface
* @param Array(String) $aggregatorAliases Array of the aliases of the aggregators. An aggregator do the "group by" on the data. $aggregatorAliases
* @param string $exportAlias Alias of the export which is being executed. An export gets the data and implements the \Chill\MainBundle\Export\ExportInterface
* @param array<string> $aggregatorAliases Array of the aliases of the aggregators. An aggregator do the "group by" on the data. $aggregatorAliases
*/
public function buildForm(
FormBuilderInterface $builder,
@@ -35,7 +35,7 @@ interface FormatterInterface
);
/**
* get the default data for the form build by buildForm
* get the default data for the form build by buildForm.
*/
public function getFormDefaultData(array $aggregatorAliases): array;
@@ -44,11 +44,11 @@ interface FormatterInterface
/**
* Generate a response from the data collected on differents ExportElementInterface.
*
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
* @param mixed[] $result The result, as given by the ExportInterface
* @param mixed[] $formatterData collected from the current form
* @param string $exportAlias the id of the current export
* @param array $filtersData an array containing the filters data. The key are the filters id, and the value are the data
* @param array $aggregatorsData an array containing the aggregators data. The key are the filters id, and the value are the data
*
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/

View File

@@ -11,9 +11,6 @@ declare(strict_types=1);
namespace Chill\MainBundle\Export\Helper;
use DateTime;
use DateTimeInterface;
use Exception;
use Symfony\Contracts\Translation\TranslatorInterface;
class DateTimeHelper
@@ -31,23 +28,22 @@ class DateTimeHelper
return '';
}
if ($value instanceof DateTimeInterface) {
if ($value instanceof \DateTimeInterface) {
return $value;
}
// warning: won't work with DateTimeImmutable as we reset time a few lines later
$date = DateTime::createFromFormat('Y-m-d', $value);
$date = \DateTime::createFromFormat('Y-m-d', $value);
$hasTime = false;
if (false === $date) {
$date = DateTime::createFromFormat('Y-m-d H:i:s', $value);
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $value);
$hasTime = true;
}
// check that the creation could occurs.
if (false === $date) {
throw new Exception(sprintf('The value %s could '
. 'not be converted to %s', $value, DateTime::class));
throw new \Exception(sprintf('The value %s could not be converted to %s', $value, \DateTime::class));
}
if (!$hasTime) {

View File

@@ -18,11 +18,6 @@ use Chill\MainBundle\Repository\GeographicalUnitLayerRepositoryInterface;
use Chill\MainBundle\Templating\Entity\AddressRender;
use Chill\MainBundle\Templating\TranslatableStringHelperInterface;
use Doctrine\ORM\QueryBuilder;
use LogicException;
use function array_key_exists;
use function count;
use function in_array;
use function strlen;
/**
* Helps to load addresses and format them in list.
@@ -116,8 +111,8 @@ class ExportAddressHelper
case 'postcode_code':
$postCodeAlias = sprintf('%spostcode_t', $prefix);
if (!in_array($postCodeAlias, $queryBuilder->getAllAliases(), true)) {
$queryBuilder->leftJoin($entityName . '.postcode', $postCodeAlias);
if (!\in_array($postCodeAlias, $queryBuilder->getAllAliases(), true)) {
$queryBuilder->leftJoin($entityName.'.postcode', $postCodeAlias);
}
if ('postcode_name' === $field) {
@@ -134,7 +129,7 @@ class ExportAddressHelper
$countryAlias = sprintf('%scountry_t', $prefix);
if (!in_array($countryAlias, $queryBuilder->getAllAliases(), true)) {
if (!\in_array($countryAlias, $queryBuilder->getAllAliases(), true)) {
$queryBuilder->leftJoin(sprintf('%s.country', $postCodeAlias), $countryAlias);
}
@@ -211,7 +206,7 @@ class ExportAddressHelper
break;
default:
throw new LogicException(sprintf('This key is not supported: %s, field %s', $key, $field));
throw new \LogicException(sprintf('This key is not supported: %s, field %s', $key, $field));
}
}
}
@@ -239,7 +234,7 @@ class ExportAddressHelper
$prefixes = array_merge(
$prefixes,
array_map(
static fn ($item) => $prefix . $item,
static fn ($item) => $prefix.$item,
self::COLUMN_MAPPING[$key]
)
);
@@ -251,7 +246,7 @@ class ExportAddressHelper
public function getLabel($key, array $values, $data, string $prefix = '', string $translationPrefix = 'export.address_helper.'): callable
{
$sanitizedKey = substr((string) $key, strlen($prefix));
$sanitizedKey = substr((string) $key, \strlen($prefix));
switch ($sanitizedKey) {
case 'id':
@@ -270,7 +265,7 @@ class ExportAddressHelper
case 'postcode_name':
return static function ($value) use ($sanitizedKey, $translationPrefix) {
if ('_header' === $value) {
return $translationPrefix . $sanitizedKey;
return $translationPrefix.$sanitizedKey;
}
if (null === $value) {
@@ -283,7 +278,7 @@ class ExportAddressHelper
case 'country':
return function ($value) use ($sanitizedKey, $translationPrefix) {
if ('_header' === $value) {
return $translationPrefix . $sanitizedKey;
return $translationPrefix.$sanitizedKey;
}
if (null === $value) {
@@ -297,7 +292,7 @@ class ExportAddressHelper
case 'confidential':
return static function ($value) use ($sanitizedKey, $translationPrefix) {
if ('_header' === $value) {
return $translationPrefix . $sanitizedKey;
return $translationPrefix.$sanitizedKey;
}
switch ($value) {
@@ -311,14 +306,14 @@ class ExportAddressHelper
return 0;
default:
throw new LogicException('this value is not supported for ' . $sanitizedKey . ': ' . $value);
throw new \LogicException('this value is not supported for '.$sanitizedKey.': '.$value);
}
};
case '_as_string':
return function ($value) use ($sanitizedKey, $translationPrefix) {
if ('_header' === $value) {
return $translationPrefix . $sanitizedKey;
return $translationPrefix.$sanitizedKey;
}
if (null === $value) {
@@ -333,7 +328,7 @@ class ExportAddressHelper
default:
$layerNamesKeys = [...$this->generateKeysForUnitsNames($prefix), ...$this->generateKeysForUnitsRefs($prefix)];
if (array_key_exists($key, $layerNamesKeys)) {
if (\array_key_exists($key, $layerNamesKeys)) {
return function ($value) use ($key, $layerNamesKeys) {
if ('_header' === $value) {
$header = $this->translatableStringHelper->localize($layerNamesKeys[$key]->getName());
@@ -351,7 +346,7 @@ class ExportAddressHelper
$decodedValues = json_decode((string) $value, true, 512, JSON_THROW_ON_ERROR);
return match (count($decodedValues)) {
return match (\count($decodedValues)) {
0 => '',
1 => $decodedValues[0],
default => implode('|', $decodedValues),
@@ -359,7 +354,7 @@ class ExportAddressHelper
};
}
throw new LogicException('this key is not supported: ' . $sanitizedKey);
throw new \LogicException('this key is not supported: '.$sanitizedKey);
}
}
@@ -368,14 +363,14 @@ class ExportAddressHelper
*/
private function generateKeysForUnitsNames(string $prefix): array
{
if (array_key_exists($prefix, $this->unitNamesKeysCache)) {
if (\array_key_exists($prefix, $this->unitNamesKeysCache)) {
return $this->unitNamesKeysCache[$prefix];
}
$keys = [];
foreach ($this->geographicalUnitLayerRepository->findAllHavingUnits() as $layer) {
$keys[$prefix . 'unit_names_' . $layer->getId()] = $layer;
$keys[$prefix.'unit_names_'.$layer->getId()] = $layer;
}
return $this->unitNamesKeysCache[$prefix] = $keys;
@@ -386,14 +381,14 @@ class ExportAddressHelper
*/
private function generateKeysForUnitsRefs(string $prefix): array
{
if (array_key_exists($prefix, $this->unitRefsKeysCache)) {
if (\array_key_exists($prefix, $this->unitRefsKeysCache)) {
return $this->unitRefsKeysCache[$prefix];
}
$keys = [];
foreach ($this->geographicalUnitLayerRepository->findAllHavingUnits() as $layer) {
$keys[$prefix . 'unit_refs_' . $layer->getId()] = $layer;
$keys[$prefix.'unit_refs_'.$layer->getId()] = $layer;
}
return $this->unitRefsKeysCache[$prefix] = $keys;

View File

@@ -13,23 +13,21 @@ namespace Chill\MainBundle\Export\Helper;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use Chill\MainBundle\Templating\Entity\UserRender;
use function count;
use const SORT_NUMERIC;
class UserHelper
{
public function __construct(private readonly UserRender $userRender, private readonly UserRepositoryInterface $userRepository) {}
/**
* Return a callable that will transform a value into a string representing a user
* Return a callable that will transform a value into a string representing a user.
*
* The callable may receive as argument:
*
* - an int or a string, the id of the user;
* - a string containing a json which will be decoded, and will have this structure: array{uid: int, d: string}. The job and scopes will be shown at this date
*
* @param string $key the key of the content
* @param array $values the list of values
* @param string $key the key of the content
* @param array $values the list of values
* @param string $header the header's content
*/
public function getLabel($key, array $values, string $header): callable
@@ -66,17 +64,15 @@ class UserHelper
}
/**
* Return a callable that will transform a value into a string representing a user
* Return a callable that will transform a value into a string representing a user.
*
* The callable may receive as argument:
*
* - an int or a string, the id of the user;
* - a string containing a json which will be decoded, and will have this structure: array{uid: int, d: string}. The job and scopes will be shown at this date * @param $key
*
* @param string $key the key of the element
* @param array $values a list of values
* @param string $key the key of the element
* @param array $values a list of values
* @param string $header the header's content
* @return callable
*/
public function getLabelMulti($key, array $values, string $header): callable
{
@@ -91,7 +87,7 @@ class UserHelper
$decoded = json_decode((string) $value, true, 512, JSON_THROW_ON_ERROR);
if (0 === count($decoded)) {
if (0 === \count($decoded)) {
return '';
}
$asStrings = [];

View File

@@ -34,8 +34,8 @@ interface ModifierInterface extends ExportElementInterface
* Alter the query initiated by the export, to add the required statements
* (`GROUP BY`, `SELECT`, `WHERE`).
*
* @param QueryBuilder $qb the QueryBuilder initiated by the Export (and eventually modified by other Modifiers)
* @param mixed[] $data the data from the Form (builded by buildForm)
* @param QueryBuilder $qb the QueryBuilder initiated by the Export (and eventually modified by other Modifiers)
* @param mixed[] $data the data from the Form (builded by buildForm)
*/
public function alterQuery(QueryBuilder $qb, $data);