fix folder name

This commit is contained in:
2021-03-18 13:37:13 +01:00
parent a2f6773f5a
commit eaa0ad925f
1578 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export;
/**
* Interface for Aggregators.
*
* Aggregators gather result of a query. Most of the time, it will add
* a GROUP BY clause.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface AggregatorInterface extends ModifierInterface
{
/**
* give the list of keys the current export added to the queryBuilder in
* self::initiateQuery
*
* Example: if your query builder will contains `SELECT count(id) AS count_id ...`,
* this function will return `array('count_id')`.
*
* @param mixed[] $data the data from the export's form (added by self::buildForm)
*/
public function getQueryKeys($data);
/**
* get a callable which will be able to transform the results into
* viewable and understable string.
*
* The callable will have only one argument: the `value` to translate.
*
* The callable should also be able to return a key `_header`, which
* will contains the header of the column.
*
* The string returned **must** be already translated if necessary,
* **with an exception** for the string returned for `_header`.
*
* Example :
*
* ```
* protected $translator;
*
* public function getLabels($key, array $values, $data)
* {
* return function($value) {
* case $value
* {
* case '_header' :
* return 'my header not translated';
* case true:
* return $this->translator->trans('true');
* case false:
* return $this->translator->trans('false');
* default:
* // this should not happens !
* throw new \LogicException();
* }
* }
* ```
*
* **Note:** Why each string must be translated with an exception for
* the `_header` ? For performance reasons: most of the value will be number
* 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 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`
* @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, $data);
}

View File

@@ -0,0 +1,39 @@
<?php
/*
*
*/
namespace Chill\MainBundle\Export;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Role\Role;
/**
*
*/
interface DirectExportInterface extends ExportElementInterface
{
/**
* get a description, which will be used in UI (and translated)
*
* @return string
*/
public function getDescription();
/**
* Generate the export
*
* @param array $acl
* @param array $data
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function generate(array $acl, array $data = []);
/**
* authorized role
*
* @return \Symfony\Component\Security\Core\Role\Role
*/
public function requiredRole();
}

View File

@@ -0,0 +1,47 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export;
use Symfony\Component\Form\FormBuilderInterface;
/**
* The common methods between different object used to build export (i.e. : ExportInterface,
* FilterInterface, AggregatorInterface)
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ExportElementInterface
{
/**
* get a title, which will be used in UI (and translated)
*
* @return string
*/
public function getTitle();
/**
* Add a form to collect data from the user.
*
* @param FormBuilderInterface $builder
*/
public function buildForm(FormBuilderInterface $builder);
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* Copyright (C) 2017 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/>.
*/
namespace Chill\MainBundle\Export;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Add a validation method to validate data collected by Export Element
*
* Implements this interface on other `ExportElementInterface` to validate
* the form submitted by users.
*
* **note**: When this interface is implemented on filters or aggregators,
* the form is validated **only** if the filter/aggregator is `enabled` by the
* user.
*
* @link http://symfony.com/doc/current/validation/custom_constraint.html#class-constraint-validator Example of building violations
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ExportElementValidatedInterface
{
/**
* validate the form's data and, if required, build a contraint
* violation on the data.
*
* @param mixed $data the data, as returned by the user
* @param ExecutionContextInterface $context
*/
public function validateForm($data, ExecutionContextInterface $context);
}

View File

@@ -0,0 +1,35 @@
<?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/>.
*/
namespace Chill\MainBundle\Export;
/**
* Interface to provide export elements dynamically.
*
* The typical use case is providing exports or aggregators depending on
* dynamic data. Example: providing exports for reports, reports depending
* on data stored in database.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ExportElementsProviderInterface
{
/**
* @return ExportElementInterface[]
*/
public function getExportElements();
}

View File

@@ -0,0 +1,165 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export;
use Doctrine\ORM\QueryBuilder;
/**
* Interface for Export.
*
* An export is a class which will initiate a query for an export.
*
* **Note** : the report implementing this class will be modified by
* both filters **and** aggregators. If the report does not support
* aggregation, use `ListInterface`.
*
* @example Chill\PersonBundle\Export\CountPerson an example of implementation
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ExportInterface extends ExportElementInterface
{
/**
* Return the Export's type. This will inform _on what_ export will apply.
* Most of the type, it will be a string which references an entity.
*
* Example of types : Chill\PersonBundle\Export\Declarations::PERSON_TYPE
*
* @return string
*/
public function getType();
/**
* A description, which will be used in the UI to explain what the export does.
* This description will be translated.
*
* @return string
*/
public function getDescription();
/**
* The initial query, which will be modified by ModifiersInterface
* (i.e. AggregatorInterface, FilterInterface).
*
* This query should take into account the `$acl` and restrict result only to
* what the user is allowed to see. (Do not show personal data the user
* is not allowed to see).
*
* The returned object should be an instance of QueryBuilder or NativeQuery.
*
* @param array $requiredModifiers
* @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 QueryBuilder|\Doctrine\ORM\NativeQuery the query to execute.
*/
public function initiateQuery(array $requiredModifiers, array $acl, array $data = array());
/**
* Inform which ModifiersInterface (i.e. AggregatorInterface, FilterInterface)
* are allowed. The modifiers should be an array of types the _modifier_ apply on
* (@see ModifiersInterface::applyOn()).
*
* @return string[]
*/
public function supportsModifiers();
/**
* Return the required Role to execute the Export.
*
* @return \Symfony\Component\Security\Core\Role\Role
*
*/
public function requiredRole();
/**
* Return which formatter type is allowed for this report.
*
* @return string[]
*/
public function getAllowedFormattersTypes();
/**
* give the list of keys the current export added to the queryBuilder in
* self::initiateQuery
*
* Example: if your query builder will contains `SELECT count(id) AS count_id ...`,
* this function will return `array('count_id')`.
*
* @param mixed[] $data the data from the export's form (added by self::buildForm)
*/
public function getQueryKeys($data);
/**
* Return the results of the query builder.
*
* @param QueryBuilder|\Doctrine\ORM\NativeQuery $query
* @param mixed[] $data the data from the export's fomr (added by self::buildForm)
* @return mixed[] an array of results
*/
public function getResult($query, $data);
/**
* transform the results to viewable and understable string.
*
* The callable will have only one argument: the `value` to translate.
*
* The callable should also be able to return a key `_header`, which
* will contains the header of the column.
*
* The string returned **must** be already translated if necessary,
* **with an exception** for the string returned for `_header`.
*
* Example :
*
* ```
* protected $translator;
*
* public function getLabels($key, array $values, $data)
* {
* return function($value) {
* case $value
* {
* case '_header' :
* return 'my header not translated';
* case true:
* return $this->translator->trans('true');
* case false:
* return $this->translator->trans('false');
* default:
* // this should not happens !
* throw new \LogicException();
* }
* }
* ```
*
* **Note:** Why each string must be translated with an exception for
* the `_header` ? For performance reasons: most of the value will be number
* 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 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`
* @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, $data);
}

View File

@@ -0,0 +1,758 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export;
use Chill\MainBundle\Export\FilterInterface;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Export\ExportInterface;
use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\HttpFoundation\Response;
use Psr\Log\LoggerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Chill\MainBundle\Form\Type\Export\PickCenterType;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Chill\MainBundle\Form\Type\Export\ExportType;
use Chill\MainBundle\Export\ListInterface;
/**
* Collects all agregators, filters and export from
* the installed bundle, and performs the export logic.
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ExportManager
{
/**
* The collected filters, injected by DI
*
* @var FilterInterface[]
*/
private $filters = array();
/**
* The collected aggregators, injected by DI
*
* @var AggregatorInterface[]
*/
private $aggregators = array();
/**
* Collected Exports, injected by DI
*
* @var ExportInterface[]
*/
private $exports = array();
/**
* Collected Formatters, injected by DI
*
* @var FormatterInterface[]
*/
private $formatters = array();
/**
* a logger
*
* @var LoggerInterface
*/
private $logger;
/**
*
* @var EntityManagerInterface
*/
private $em;
/**
*
* @var AuthorizationChecker
*/
private $authorizationChecker;
/**
*
* @var AuthorizationHelper
*/
private $authorizationHelper;
/**
*
* @var \Symfony\Component\Security\Core\User\UserInterface
*/
private $user;
public function __construct(
LoggerInterface $logger,
EntityManagerInterface $em,
AuthorizationCheckerInterface $authorizationChecker,
AuthorizationHelper $authorizationHelper,
TokenStorageInterface $tokenStorage)
{
$this->logger = $logger;
$this->em = $em;
$this->authorizationChecker = $authorizationChecker;
$this->authorizationHelper = $authorizationHelper;
$this->user = $tokenStorage->getToken()->getUser();
}
/**
* add a Filter
*
* @internal Normally used by the dependency injection
*
* @param FilterInterface $filter
* @param string $alias
*/
public function addFilter(FilterInterface $filter, $alias)
{
$this->filters[$alias] = $filter;
}
/**
* add an aggregator
*
* @internal used by DI
*
* @param AggregatorInterface $aggregator
* @param string $alias
*/
public function addAggregator(AggregatorInterface $aggregator, $alias)
{
$this->aggregators[$alias] = $aggregator;
}
/**
* add an export
*
* @internal used by DI
*
* @param ExportInterface|DirectExportInterface $export
* @param type $alias
*/
public function addExport($export, $alias)
{
if ($export instanceof ExportInterface || $export instanceof DirectExportInterface) {
$this->exports[$alias] = $export;
} else {
throw new \InvalidArgumentException(sprintf("The export with alias %s "
. "does not implements %s or %s.", $alias, ExportInterface::class,
DirectExportInterface::class));
}
}
/**
* add a formatter
*
* @internal used by DI
*
* @param FormatterInterface $formatter
* @param type $alias
*/
public function addFormatter(FormatterInterface $formatter, $alias)
{
$this->formatters[$alias] = $formatter;
}
public function addExportElementsProvider(ExportElementsProviderInterface $provider, $prefix)
{
foreach ($provider->getExportElements() as $suffix => $element) {
$alias = $prefix.'_'.$suffix;
if ($element instanceof ExportInterface) {
$this->addExport($element, $alias);
} elseif ($element instanceof FilterInterface) {
$this->addFilter($element, $alias);
} elseif ($element instanceof AggregatorInterface) {
$this->addAggregator($element, $alias);
} elseif ($element instanceof FormatterInterface) {
$this->addFormatter($element, $alias);
} else {
throw new \LogicException("This element ".\get_class($element)." "
. "is not an instance of export element");
}
}
}
/**
*
* @return string[] the existing type for known exports
*/
public function getExistingExportsTypes()
{
$existingTypes = array();
foreach($this->exports as $export) {
if (!in_array($export->getType(), $existingTypes)) {
array_push($existingTypes, $export->getType());
}
}
return $existingTypes;
}
/**
* Return all exports. The exports's alias are the array's keys.
*
* @param boolean $whereUserIsGranted if true (default), restrict to user which are granted the right to execute the export
* @return ExportInterface[] an array where export's alias are keys
*/
public function getExports($whereUserIsGranted = true)
{
foreach ($this->exports as $alias => $export) {
if ($whereUserIsGranted) {
if ($this->isGrantedForElement($export, null, null)) {
yield $alias => $export;
}
} else {
yield $alias => $export;
}
}
}
/**
* Get all exports grouped in an array.
*
* @param bool $whereUserIsGranted
* @return array where keys are the groups's name and value is an array of exports
*/
public function getExportsGrouped($whereUserIsGranted = true): array
{
$groups = [ '_' => [] ];
foreach ($this->getExports($whereUserIsGranted) as $alias => $export) {
if ($export instanceof GroupedExportInterface) {
$groups[$export->getGroup()][$alias] = $export;
} else {
$groups['_'][$alias] = $export;
}
}
return $groups;
}
/**
* Return an export by his alias
*
* @param string $alias
* @return ExportInterface
* @throws \RuntimeException
*/
public function getExport($alias)
{
if (!array_key_exists($alias, $this->exports)) {
throw new \RuntimeException("The export with alias $alias is not known.");
}
return $this->exports[$alias];
}
/**
*
* @param string $alias
* @return FilterInterface
* @throws \RuntimeException if the filter is not known
*/
public function getFilter($alias)
{
if (!array_key_exists($alias, $this->filters)) {
throw new \RuntimeException("The filter with alias $alias is not known.");
}
return $this->filters[$alias];
}
/**
* get all filters
*
* @param \Generator $aliases
*/
public function getFilters(array $aliases)
{
foreach($aliases as $alias) {
yield $alias => $this->getFilter($alias);
}
}
/**
*
* @param string $alias
* @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.");
}
return $this->aggregators[$alias];
}
public function getAggregators(array $aliases)
{
foreach ($aliases as $alias) {
yield $alias => $this->getAggregator($alias);
}
}
public function getFormatter($alias)
{
if (!array_key_exists($alias, $this->formatters)) {
throw new \RuntimeException("The formatter with alias $alias is not known.");
}
return $this->formatters[$alias];
}
/**
* Get all formatters which supports one of the given types.
*
*
* @param array $types
* @return \Generator
*/
public function getFormattersByTypes(array $types)
{
foreach ($this->formatters as $alias => $formatter) {
if (in_array($formatter->getType(), $types)) {
yield $alias => $formatter;
}
}
}
/**
* Return a \Generator containing filter which support type. If `$centers` is
* not null, restrict the given filters to the center the user have access to.
*
* if $centers is null, the function will returns all filters where the user
* has access in every centers he can reach (if the user can use the filter F in
* center A, but not in center B, the filter F will not be returned)
*
* @param \Chill\MainBundle\Entity\Center[] $centers the centers where the user have access to
* @return FilterInterface[] a \Generator that contains filters. The key is the filter's alias
*/
public function &getFiltersApplyingOn(ExportInterface $export, array $centers = null)
{
foreach ($this->filters as $alias => $filter) {
if (in_array($filter->applyOn(), $export->supportsModifiers())
&& $this->isGrantedForElement($filter, $export, $centers)) {
yield $alias => $filter;
}
}
}
/**
* 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.
*
* @param \Chill\MainBundle\Export\ExportElementInterface $element
* @param ExportInterface|DirectExportInterface $export
* @param array|null $centers, if null, the function take into account all the reachables centers for the current user and the role given by element::requiredRole
* @return boolean
*/
public function isGrantedForElement(ExportElementInterface $element, ExportElementInterface $export = NULL, array $centers = null)
{
if ($element instanceof ExportInterface || $element instanceof DirectExportInterface) {
$role = $element->requiredRole();
} elseif ($element instanceof ModifierInterface ) {
if (is_null($element->addRole())) {
if (is_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");
} else {
$role = $export->requiredRole();
}
} else {
$role = $element->addRole();
}
} else {
throw new \LogicException("The element is not an ModifiersInterface or "
. "an ExportInterface.");
}
if ($centers === null) {
$centers = $this->authorizationHelper->getReachableCenters($this->user,
$role);
}
if (count($centers) === 0) {
return false;
}
foreach($centers as $center) {
if ($this->authorizationChecker->isGranted($role->getRole(), $center) === false) {
//debugging
$this->logger->debug('user has no access to element', array(
'method' => __METHOD__,
'type' => get_class($element),
'center' => $center->getName(),
'role' => $role->getRole()
));
return false;
}
}
return true;
}
/**
* Return a \Generator containing aggregators supported by the given export
*
* @internal This class check the interface implemented by export, and, if ´ListInterface´ is used, return an empty array
* @return AggregatorInterface[] a \Generator that contains aggretagors. The key is the filter's alias
*/
public function &getAggregatorsApplyingOn(ExportInterface $export, array $centers = null)
{
if ($export instanceof ListInterface) {
return;
}
foreach ($this->aggregators as $alias => $aggregator) {
if (in_array($aggregator->applyOn(), $export->supportsModifiers()) &&
$this->isGrantedForElement($aggregator, $export, $centers)) {
yield $alias => $aggregator;
}
}
}
/**
* Generate a response which contains the requested data.
*
* @param string $exportAlias
* @param mixed[] $data
* @return Response
*/
public function generate($exportAlias, array $pickedCentersData, array $data, array $formatterData)
{
$export = $this->getExport($exportAlias);
//$qb = $this->em->createQueryBuilder();
$centers = $this->getPickedCenters($pickedCentersData);
if ($export instanceof DirectExportInterface) {
return $export->generate(
$this->buildCenterReachableScopes($centers, $export),
$data[ExportType::EXPORT_KEY]
);
}
$query = $export->initiateQuery(
$this->retrieveUsedModifiers($data),
$this->buildCenterReachableScopes($centers, $export),
$data[ExportType::EXPORT_KEY]
);
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`");
}
} elseif ($query instanceof QueryBuilder) {
//handle filters
$this->handleFilters($export, $query, $data[ExportType::FILTER_KEY], $centers);
//handle aggregators
$this->handleAggregators($export, $query, $data[ExportType::AGGREGATOR_KEY], $centers);
$this->logger->debug('current query is '.$query->getDQL(), array(
'class' => self::class, 'function' => __FUNCTION__
));
} else {
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)
)
);
}
/* @var $formatter FormatterInterface */
$formatter = $this->getFormatter($this->getFormatterAlias($data));
$filtersData = array();
$aggregatorsData = array();
if ($query instanceof QueryBuilder) {
$aggregators = $this->retrieveUsedAggregators($data[ExportType::AGGREGATOR_KEY]);
foreach($aggregators as $alias => $aggregator) {
$aggregatorsData[$alias] = $data[ExportType::AGGREGATOR_KEY][$alias]['form'];
}
}
$filters = $this->retrieveUsedFilters($data[ExportType::FILTER_KEY]);
foreach($filters as $alias => $filter) {
$filtersData[$alias] = $data[ExportType::FILTER_KEY][$alias]['form'];
}
return $formatter->getResponse(
$result,
$formatterData,
$exportAlias,
$data[ExportType::EXPORT_KEY],
$filtersData,
$aggregatorsData);
}
/**
* build the array required for defining centers and circles in the initiate
* queries of ExportElementsInterfaces
*
* @param \Chill\MainBundle\Entity\Center[] $centers
*/
private function buildCenterReachableScopes(array $centers, ExportElementInterface $element) {
$r = array();
foreach($centers as $center) {
$r[] = array(
'center' => $center,
'circles' => $this->authorizationHelper->getReachableScopes($this->user,
$element->requiredRole(), $center)
);
}
return $r;
}
/**
* get the aggregators typse used in the form export data
*
* @param array $data the data from the export form
* @return string[]
*/
public function getUsedAggregatorsAliases(array $data)
{
$aggregators = $this->retrieveUsedAggregators($data[ExportType::AGGREGATOR_KEY]);
return array_keys(iterator_to_array($aggregators));
}
/**
* 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)
{
if (array_key_exists(ExportType::PICK_FORMATTER_KEY, $data)) {
return $data[ExportType::PICK_FORMATTER_KEY]['alias'];
}
return null;
}
/**
* Get the Center picked by the user for this export. The data are
* extracted from the PickCenterType data
*
* @param array $data the data from a PickCenterType
* @return \Chill\MainBundle\Entity\Center[] the picked center
*/
public function getPickedCenters(array $data)
{
return $data;
}
/**
* parse the data to retrieve the used filters and aggregators
*
* @param mixed $data
* @return string[]
*/
private function retrieveUsedModifiers($data)
{
if ($data === null) {
return [];
}
$usedTypes = array_merge(
$this->retrieveUsedFiltersType($data[ExportType::FILTER_KEY]),
$this->retrieveUsedAggregatorsType($data[ExportType::AGGREGATOR_KEY])
);
$this->logger->debug('Required types are '.implode(', ', $usedTypes),
array('class' => self::class, 'function' => __FUNCTION__));
return array_unique($usedTypes);
}
/**
* Retrieve the filter used in this export.
*
* @param mixed $data the data from the `filters` key of the ExportType
* @return array an array with types
*/
private function retrieveUsedFiltersType($data)
{
if ($data === null) {
return [];
}
$usedTypes = array();
foreach($data as $alias => $filterData) {
if ($filterData['enabled'] == true){
$filter = $this->getFilter($alias);
if (!in_array($filter->applyOn(), $usedTypes)) {
array_push($usedTypes, $filter->applyOn());
}
}
}
return $usedTypes;
}
/**
*
* @param mixed $data
* @return string[]
*/
private function retrieveUsedAggregatorsType($data)
{
if ($data === null) {
return [];
}
$usedTypes = array();
foreach($this->retrieveUsedAggregators($data) as $alias => $aggregator) {
if (!in_array($aggregator->applyOn(), $usedTypes)) {
array_push($usedTypes, $aggregator->applyOn());
}
}
return $usedTypes;
}
/**
*
* @param mixed $data
* @return AggregatorInterface[]
*/
private function retrieveUsedAggregators($data)
{
if ($data === null) {
return [];
}
foreach ($data as $alias => $aggregatorData) {
if ($aggregatorData['enabled'] === true){
yield $alias => $this->getAggregator($alias);
}
}
}
/**
*
* @param type $data the data from the filter key of the ExportType
*/
private function retrieveUsedFilters($data)
{
if ($data === null) {
return [];
}
foreach ($data as $alias => $filterData) {
if ($filterData['enabled'] === true) {
yield $alias => $this->getFilter($alias);
}
}
}
/**
* alter the query with selected filters.
*
* This function check the acl.
*
* @param ExportInterface $export
* @param QueryBuilder $qb
* @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(
ExportInterface $export,
QueryBuilder $qb,
$data,
array $centers)
{
$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());
}
$formData = $data[$alias];
$this->logger->debug('alter query by filter '.$alias, array(
'class' => self::class, 'function' => __FUNCTION__
));
$filter->alterQuery($qb, $formData['form']);
}
}
/**
* Alter the query with selected aggregators
*
* Check for acl. If an user is not authorized to see an aggregator, throw an
* UnauthorizedException.
*
* @param ExportInterface $export
* @param QueryBuilder $qb
* @param type $data
* @param \Chill\MainBundle\Entity\Center[] $centers the picked centers
* @throw UnauthorizedHttpException if the user is not authorized
*/
private function handleAggregators(
ExportInterface $export,
QueryBuilder $qb,
$data,
array $center)
{
$aggregators = $this->retrieveUsedAggregators($data);
foreach ($aggregators as $alias => $aggregator) {
$formData = $data[$alias];
$aggregator->alterQuery($qb, $formData['form']);
}
}
}

View File

@@ -0,0 +1,70 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export;
/**
* Interface for filters.
*
* Filter will filter result on the query initiated by Export. Most of the time,
* it will add a `WHERE` clause on this query.
*
* Filters should not add column in `SELECT` clause.
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface FilterInterface extends ModifierInterface
{
const STRING_FORMAT = 'string';
/**
* Describe the filtering action.
*
* The description will be inserted in report to remains to the user the
* filters applyied on this report.
*
* Should return a statement about the filtering action, like :
* "filtering by date: from xxxx-xx-xx to xxxx-xx-xx" or
* "filtering by nationality: only Germany, France"
*
* The format will be determined by the $format. Currently, only 'string' is
* supported, later some 'html' will be added. The filter should always
* implement the 'string' format and fallback to it if other format are used.
*
* If no i18n is necessery, or if the filter translate the string by himself,
* this function should return a string. If the filter does not do any translation,
* the return parameter should be an array, where
*
* - the first element is the string,
* - and the second an array of parameters (may be an empty array)
* - the 3rd the domain (optional)
* - the 4th the locale (optional)
*
* Example: `array('my string with %parameter%', ['%parameter%' => 'good news'], 'mydomain', 'mylocale')`
*
* @param array $data
* @param string $format the format
* @return string|array a string with the data or, if translatable, an array where first element is string, second elements is an array of arguments
*/
public function describeAction($data, $format = 'string');
}

View File

@@ -0,0 +1,463 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export\Formatter;
use Chill\MainBundle\Export\ExportInterface;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// 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
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* @deprecated this formatter is not used any more.
*/
class CSVFormatter implements FormatterInterface
{
/**
*
* @var TranslatorInterface
*/
protected $translator;
protected $result;
protected $formatterData;
protected $export;
protected $aggregators;
protected $exportData;
protected $aggregatorsData;
protected $filtersData;
protected $labels;
/**
*
* @var ExportManager
*/
protected $exportManager;
public function __construct(TranslatorInterface $translator,
ExportManager $manager)
{
$this->translator = $translator;
$this->exportManager = $manager;
}
public function getType()
{
return 'tabular';
}
public function getName()
{
return 'Comma separated values (CSV)';
}
/**
*
* @uses appendAggregatorForm
* @param FormBuilderInterface $builder
* @param type $exportAlias
* @param array $aggregatorAliases
*/
public function buildForm(FormBuilderInterface $builder, $exportAlias, array $aggregatorAliases)
{
$aggregators = $this->exportManager->getAggregators($aggregatorAliases);
$nb = count($aggregatorAliases);
foreach ($aggregators as $alias => $aggregator) {
$builderAggregator = $builder->create($alias, FormType::class, array(
'label' => $aggregator->getTitle(),
'block_name' => '_aggregator_placement_csv_formatter'
));
$this->appendAggregatorForm($builderAggregator, $nb);
$builder->add($builderAggregator);
}
}
/**
* append a form line by aggregator on the formatter form.
*
* This form allow to choose the aggregator position (row or column) and
* the ordering
*
* @param FormBuilderInterface $builder
* @param string $nbAggregators
*/
private function appendAggregatorForm(FormBuilderInterface $builder, $nbAggregators)
{
$builder->add('order', ChoiceType::class, array(
'choices' => array_combine(
range(1, $nbAggregators),
range(1, $nbAggregators)
),
'multiple' => false,
'expanded' => false
));
$builder->add('position', ChoiceType::class, array(
'choices' => array(
'row' => 'r',
'column' => 'c'
),
'multiple' => false,
'expanded' => false
));
}
public function getResponse(
$result,
$formatterData,
$exportAlias,
array $exportData,
array $filtersData,
array $aggregatorsData
) {
$this->result = $result;
$this->orderingHeaders($formatterData);
$this->export = $this->exportManager->getExport($exportAlias);
$this->aggregators = iterator_to_array($this->exportManager
->getAggregators(array_keys($aggregatorsData)));
$this->exportData = $exportData;
$this->aggregatorsData = $aggregatorsData;
$this->labels = $this->gatherLabels();
$this->filtersData = $filtersData;
$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->setContent($this->generateContent());
return $response;
}
/**
* ordering aggregators, preserving key association.
*
* This function do not mind about position.
*
* If two aggregators have the same order, the second given will be placed
* after. This is not significant for the first ordering.
*
* @param type $formatterData
* @return type
*/
protected function orderingHeaders($formatterData)
{
$this->formatterData = $formatterData;
uasort($this->formatterData, function($a, $b) {
return ($a['order'] <= $b['order'] ? -1 : 1);
});
}
protected function generateContent()
{
$rowKeysNb = count($this->getRowHeaders());
$columnKeysNb = count($this->getColumnHeaders());
$resultsKeysNb = count($this->export->getQueryKeys($this->exportData));
$results = $this->getOrderedResults();
/* @var $columnHeaders string[] the column headers associations */
$columnHeaders = array();
/* @var $data string[] the data of the csv file */
$contentData = array();
$content = array();
function findColumnPosition(&$columnHeaders, $columnToFind) {
$i = 0;
foreach($columnHeaders as $set) {
if ($set === $columnToFind) {
return $i;
}
$i++;
}
//we didn't find it, adding the column
$columnHeaders[] = $columnToFind;
return $i++;
}
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
//title
fputcsv($output, array($this->translator->trans($this->export->getTitle())));
//blank line
fputcsv($output, array(""));
// add filtering description
foreach($this->gatherFiltersDescriptions() as $desc) {
fputcsv($output, array($desc));
}
// blank line
fputcsv($output, array(""));
// 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);
//first line : we create line and adding them row headers
if (!isset($line)) {
$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) {
$contentData[] = $line;
$line = array_slice($row, 0, $rowKeysNb);
}
// add the column headers
/* @var $columns string[] the column for this row */
$columns = array_slice($row, $rowKeysNb, $columnKeysNb);
$columnPosition = findColumnPosition($columnHeaders, $columns);
//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);
foreach($resultData as $data) {
$line[] = $data;
}
}
// we add the last line
$contentData[] = $line;
//column title headers
for ($i=0; $i < $columnKeysNb; $i++) {
$line = array_fill(0, $rowKeysNb, '');
foreach($columnHeaders as $set) {
$line[] = $set[$i];
}
$content[] = $line;
}
//row title headers
$headerLine = array();
foreach($this->getRowHeaders() as $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]) ?
$this->labels[$key]['_header'] : '';
}
fputcsv($output, $headerLine);
unset($headerLine); //free memory
//generate CSV
foreach($content as $line) {
fputcsv($output, $line);
}
foreach($contentData as $line) {
fputcsv($output, $line);
}
$text = stream_get_contents($output);
fclose($output);
return $text;
}
private function getOrderedResults()
{
$r = array();
$results = $this->result;
$labels = $this->labels;
$rowKeys = $this->getRowHeaders();
$columnKeys = $this->getColumnHeaders();
$resultsKeys = $this->export->getQueryKeys($this->exportData);
$headers = array_merge($rowKeys, $columnKeys);
foreach ($results as $row) {
$line = array();
foreach ($headers as $key) {
$line[] = call_user_func($labels[$key], $row[$key]);
}
//append result
foreach ($resultsKeys as $key) {
$line[] = call_user_func($labels[$key], $row[$key]);
}
$r[] = $line;
}
array_multisort($r);
return $r;
}
protected function getRowHeaders()
{
return $this->getPositionnalHeaders('r');
}
protected function getColumnHeaders()
{
return $this->getPositionnalHeaders('c');
}
/**
*
* @param string $position may be 'c' (column) or 'r' (row)
* @return string[]
* @throws \RuntimeException
*/
private function getPositionnalHeaders($position)
{
$headers = array();
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");
}
$aggregator = $this->aggregators[$alias];
if ($data['position'] === $position) {
$headers = array_merge($headers, $aggregator->getQueryKeys($this->aggregatorsData[$alias]));
}
}
return $headers;
}
/**
*
* @param mixed $result
* @param \Chill\MainBundle\Export\AggregatorInterface[] $aggregators
*/
protected function gatherLabels()
{
return array_merge(
$this->gatherLabelsFromAggregators(),
$this->gatherLabelsFromExport()
);
}
protected function gatherLabelsFromAggregators()
{
$labels = array();
/* @var $aggretator \Chill\MainBundle\Export\AggregatorInterface */
foreach ($this->aggregators as $alias => $aggregator) {
$keys = $aggregator->getQueryKeys($this->aggregatorsData[$alias]);
// gather data in an array
foreach($keys as $key) {
$values = array_map(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");
}
return $row[$key];
}, $this->result);
$labels[$key] = $aggregator->getLabels($key, array_unique($values),
$this->aggregatorsData[$alias]);
}
}
return $labels;
}
protected function gatherLabelsFromExport()
{
$labels = array();
$export = $this->export;
$keys = $this->export->getQueryKeys($this->exportData);
foreach($keys as $key) {
$values = array_map(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");
}
return $row[$key];
}, $this->result);
$labels[$key] = $this->export->getLabels($key, array_unique($values),
$this->exportData);
}
return $labels;
}
public function gatherFiltersDescriptions()
{
$descriptions = array();
foreach($this->filtersData as $key => $filterData) {
$statement = $this->exportManager
->getFilter($key)
->describeAction($filterData);
if ($statement === null) {
continue;
}
if (is_array($statement)) {
$descriptions[] = $this->translator->trans(
$statement[0],
$statement[1],
isset($statement[2]) ? $statement[2] : null,
isset($statement[3]) ? $statement[3] : null);
} else {
$descriptions[] = $statement;
}
}
return $descriptions;
}
}

View File

@@ -0,0 +1,237 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export\Formatter;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
// 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
/**
* Create a CSV List for the export
*
* @author Champs-Libres <info@champs-libres.coop>
*/
class CSVListFormatter implements FormatterInterface
{
/**
* This variable cache the labels internally
*
* @var string[]
*/
protected $labelsCache = null;
protected $result = null;
protected $exportAlias = null;
protected $exportData = null;
protected $formatterData = null;
/**
*
* @var ExportManager
*/
protected $exportManager;
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct(TranslatorInterface $translatorInterface, ExportManager $exportManager)
{
$this->translator = $translatorInterface;
$this->exportManager = $exportManager;
}
public function getType()
{
return FormatterInterface::TYPE_LIST;
}
public function getName()
{
return 'CSV vertical list';
}
/**
* build a form, which will be used to collect data required for the execution
* of this formatter.
*
* @uses appendAggregatorForm
* @param FormBuilderInterface $builder
* @param type $exportAlias
* @param array $aggregatorAliases
*/
public function buildForm(
FormBuilderInterface $builder,
$exportAlias,
array $aggregatorAliases
){
$builder->add('numerotation', ChoiceType::class, array(
'choices' => array(
'yes' => true,
'no' => false
),
'expanded' => true,
'multiple' => false,
'label' => "Add a number on first column",
'data' => true
));
}
/**
* 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
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/
public function getResponse(
$result,
$formatterData,
$exportAlias,
array $exportData,
array $filtersData,
array $aggregatorsData
) {
$this->result = $result;
$this->exportAlias = $exportAlias;
$this->exportData = $exportData;
$this->formatterData = $formatterData;
$output = fopen('php://output', 'w');
$this->prepareHeaders($output);
$i = 1;
foreach ($result as $row) {
$line = array();
if ($this->formatterData['numerotation'] === true) {
$line[] = $i;
}
foreach ($row as $key => $value) {
$line[] = $this->getLabel($key, $value);
}
fputcsv($output, $line);
$i++;
}
$csvContent = stream_get_contents($output);
fclose($output);
$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->setContent($csvContent);
return $response;
}
/**
* add the headers to the csv file
*
* @param resource $output
*/
protected function prepareHeaders($output)
{
$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] : array();
$header_line = array();
if ($this->formatterData['numerotation'] === true) {
$header_line[] = $this->translator->trans('Number');
}
foreach ($first_row as $key => $value) {
$header_line[] = $this->translator->trans(
$this->getLabel($key, '_header'));
}
if (count($header_line) > 0) {
fputcsv($output, $header_line);
}
}
/**
* Give the label corresponding to the given key and value.
*
* @param string $key
* @param string $value
* @return string
* @throws \LogicException if the label is not found
*/
protected function getLabel($key, $value)
{
if ($this->labelsCache === null) {
$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))));
}
return $this->labelsCache[$key]($value);
}
/**
* Prepare the label cache which will be used by getLabel. This function
* should be called only once in the generation lifecycle.
*/
protected function prepareCacheLabels()
{
$export = $this->exportManager->getExport($this->exportAlias);
$keys = $export->getQueryKeys($this->exportData);
foreach($keys as $key) {
// get an array with all values for this key if possible
$values = \array_map(function ($v) use ($key) { return $v[$key]; }, $this->result);
// store the label in the labelsCache property
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
}
}
}

View File

@@ -0,0 +1,228 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export\Formatter;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
/**
* Create a CSV List for the export where the header are printed on the
* first column, and the result goes from left to right.
*
* @author Champs-Libres <info@champs-libres.coop>
*/
class CSVPivotedListFormatter implements FormatterInterface
{
/**
* This variable cache the labels internally
*
* @var string[]
*/
protected $labelsCache = null;
protected $result = null;
protected $exportAlias = null;
protected $exportData = null;
protected $formatterData = null;
/**
*
* @var ExportManager
*/
protected $exportManager;
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct(TranslatorInterface $translatorInterface, ExportManager $exportManager)
{
$this->translator = $translatorInterface;
$this->exportManager = $exportManager;
}
public function getType()
{
return FormatterInterface::TYPE_LIST;
}
public function getName()
{
return 'CSV horizontal list';
}
/**
* build a form, which will be used to collect data required for the execution
* of this formatter.
*
* @uses appendAggregatorForm
* @param FormBuilderInterface $builder
* @param type $exportAlias
* @param array $aggregatorAliases
*/
public function buildForm(
FormBuilderInterface $builder,
$exportAlias,
array $aggregatorAliases
){
$builder->add('numerotation', ChoiceType::class, array(
'choices' => array(
'yes' => true,
'no' => false
),
'expanded' => true,
'multiple' => false,
'label' => "Add a number on first column",
'data' => true
));
}
/**
* 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
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/
public function getResponse(
$result,
$formatterData,
$exportAlias,
array $exportData,
array $filtersData,
array $aggregatorsData
) {
$this->result = $result;
$this->exportAlias = $exportAlias;
$this->exportData = $exportData;
$this->formatterData = $formatterData;
$output = fopen('php://output', 'w');
$i = 1;
$lines = array();
$this->prepareHeaders($lines);
foreach ($result as $row) {
$j = 0;
if ($this->formatterData['numerotation'] === true) {
$lines[$j][] = $i;
$j++;
}
foreach ($row as $key => $value) {
$lines[$j][] = $this->getLabel($key, $value);
$j++;
}
$i++;
}
//adding the lines to the csv output
foreach($lines as $line) {
fputcsv($output, $line);
}
$csvContent = stream_get_contents($output);
fclose($output);
$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->setContent($csvContent);
return $response;
}
/**
* add the headers to lines array
*
* @param array $lines the lines where the header will be added
*/
protected function prepareHeaders(array &$lines)
{
$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] : array();
$header_line = array();
if ($this->formatterData['numerotation'] === true) {
$lines[] = array($this->translator->trans('Number'));
}
foreach ($first_row as $key => $value) {
$lines[] = array($this->getLabel($key, '_header'));
}
}
/**
* Give the label corresponding to the given key and value.
*
* @param string $key
* @param string $value
* @return string
* @throws \LogicException if the label is not found
*/
protected function getLabel($key, $value)
{
if ($this->labelsCache === null) {
$this->prepareCacheLabels();
}
return $this->labelsCache[$key]($value);
}
/**
* Prepare the label cache which will be used by getLabel. This function
* should be called only once in the generation lifecycle.
*/
protected function prepareCacheLabels()
{
$export = $this->exportManager->getExport($this->exportAlias);
$keys = $export->getQueryKeys($this->exportData);
foreach($keys as $key) {
// get an array with all values for this key if possible
$values = \array_map(function ($v) use ($key) { return $v[$key]; }, $this->result);
// store the label in the labelsCache property
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
}
}
}

View File

@@ -0,0 +1,583 @@
<?php
/*
* Copyright (C) 2017 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/>.
*/
namespace Chill\MainBundle\Export\Formatter;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class SpreadSheetFormatter implements FormatterInterface
{
/**
*
* @var TranslatorInterface
*/
protected $translator;
/**
*
* @var ExportManager
*/
protected $exportManager;
/**
* The result, as returned by the export
*
* replaced when `getResponse` is called.
*
* @var type
*/
protected $result;
/**
*
* replaced when `getResponse` is called.
*
* @var type
*/
protected $formatterData;
/**
* The export
*
* replaced when `getResponse` is called.
*
* @var \Chill\MainBundle\Export\ExportInterface
*/
protected $export;
/**
*
* replaced when `getResponse` is called.
*
* @var type
*/
//protected $aggregators;
/**
* array containing value of export form
*
* replaced when `getResponse` is called.
*
* @var array
*/
protected $exportData;
/**
* an array where keys are the aggregators aliases and
* values are the data
*
* replaced when `getResponse` is called.
*
* @var type
*/
protected $aggregatorsData;
/**
*
* replaced when `getResponse` is called.
*
* @var array
*/
protected $filtersData;
/**
*
* replaced when `getResponse` is called.
*
* @var array
*/
//protected $labels;
/**
* temporary file to store spreadsheet
*
* @var string
*/
protected $tempfile;
/**
* cache for displayable result.
*
* This cache is reset when `getResponse` is called.
*
* The array's keys are the keys in the raw result, and
* values are the callable which will transform the raw result to
* displayable result.
*
* @var array
*/
private $cacheDisplayableResult;
/**
* Whethe `cacheDisplayableResult` is initialized or not.
*
* @var boolean
*/
private $cacheDisplayableResultIsInitialized = false;
public function __construct(TranslatorInterface $translatorInterface, ExportManager $exportManager)
{
$this->translator = $translatorInterface;
$this->exportManager = $exportManager;
}
public function buildForm(
FormBuilderInterface $builder,
$exportAlias,
array $aggregatorAliases
) {
// choosing between formats
$builder->add('format', ChoiceType::class, array(
'choices' => array(
'OpenDocument Format (.ods) (LibreOffice, ...)' => 'ods',
'Microsoft Excel 2007-2013 XML (.xlsx) (Microsoft Excel, LibreOffice)' => 'xlsx',
'Comma separated values (.csv)' => 'csv'
),
'placeholder' => 'Choose the format'
));
// ordering aggregators
$aggregators = $this->exportManager->getAggregators($aggregatorAliases);
$nb = count($aggregatorAliases);
foreach ($aggregators as $alias => $aggregator) {
$builderAggregator = $builder->create($alias, FormType::class, array(
'label' => $aggregator->getTitle(),
'block_name' => '_aggregator_placement_spreadsheet_formatter'
));
$this->appendAggregatorForm($builderAggregator, $nb);
$builder->add($builderAggregator);
}
}
/**
* append a form line by aggregator on the formatter form.
*
* This form allow to choose the aggregator position (row or column) and
* the ordering
*
* @param FormBuilderInterface $builder
* @param string $nbAggregators
*/
private function appendAggregatorForm(FormBuilderInterface $builder, $nbAggregators)
{
$builder->add('order', ChoiceType::class, array(
'choices' => array_combine(
range(1, $nbAggregators),
range(1, $nbAggregators)
),
'multiple' => false,
'expanded' => false
));
}
public function getName()
{
return 'SpreadSheet (xlsx, ods)';
}
public function getResponse(
$result,
$formatterData,
$exportAlias,
array $exportData,
array $filtersData,
array $aggregatorsData
) {
// store all data when the process is initiated
$this->result = $result;
$this->formatterData = $formatterData;
$this->export = $this->exportManager->getExport($exportAlias);
$this->exportData = $exportData;
$this->filtersData = $filtersData;
$this->aggregatorsData = $aggregatorsData;
// reset cache
$this->cacheDisplayableResult = array();
$this->cacheDisplayableResultIsInitialized = false;
$response = new Response();
$response->headers->set('Content-Type',
$this->getContentType($this->formatterData['format']));
$this->tempfile = \tempnam(\sys_get_temp_dir(), '');
$this->generatecontent();
$f = \fopen($this->tempfile, 'r');
$response->setContent(\stream_get_contents($f));
fclose($f);
// remove the temp file from disk
\unlink($this->tempfile);
return $response;
}
/**
* Generate the content and write it to php://temp
*/
protected function generateContent()
{
list($spreadsheet, $worksheet) = $this->createSpreadsheet();
$this->addTitleToWorkSheet($worksheet);
$line = $this->addFiltersDescription($worksheet);
// at this point, we are going to sort retsults for an easier manipulation
list($sortedResult, $exportKeys, $aggregatorKeys, $globalKeys) =
$this->sortResult();
$line = $this->addHeaders($worksheet, $globalKeys, $line);
$line = $this->addContentTable($worksheet, $sortedResult, $line);
switch ($this->formatterData['format'])
{
case 'ods':
$writer = \PhpOffice\PhpSpreadsheet\IOFactory
::createWriter($spreadsheet, 'Ods');
break;
case 'xlsx':
$writer = \PhpOffice\PhpSpreadsheet\IOFactory
::createWriter($spreadsheet, 'Xlsx');
break;
case 'csv':
$writer = \PhpOffice\PhpSpreadsheet\IOFactory
::createWriter($spreadsheet, 'Csv');
break;
default:
// this should not happen
// throw an exception to ensure that the error is catched
throw new \LogicException();
}
$writer->save($this->tempfile);
}
/**
* Create a spreadsheet and a working worksheet
*
* @return array where 1st member is spreadsheet, 2nd is worksheet
*/
protected function createSpreadsheet()
{
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
// setting the worksheet title and code name
$worksheet
->setTitle($this->getTitle())
->setCodeName('result');
return [$spreadsheet, $worksheet];
}
/**
* Add the title to the worksheet and merge the cell containing
* the title
*
* @param Worksheet $worksheet
*/
protected function addTitleToWorkSheet(Worksheet &$worksheet)
{
$worksheet->setCellValue('A1', $this->getTitle());
$worksheet->mergeCells('A1:G1');
}
/**
* Add filter description since line 3.
*
* return the line number after the last description
*
* @param Worksheet $worksheet
* @return int the line number after the last description
*/
protected function addFiltersDescription(Worksheet &$worksheet)
{
$line = 3;
foreach ($this->filtersData as $alias => $data) {
$filter = $this->exportManager->getFilter($alias);
$description = $filter->describeAction($data, 'string');
if (is_array($description)) {
$description = $this->translator
->trans(
$description[0],
isset($description[1]) ? $description[1] : []
);
}
$worksheet->setCellValue('A'.$line, $description);
$line ++;
}
return $line;
}
/**
* sort the results, and return an array where :
* - 0 => sorted results
* - 1 => export keys
* - 2 => aggregator keys
* - 3 => global keys (aggregator keys and export keys)
*
*
* Example, assuming that the result contains two aggregator keys :
*
* array in result :
*
* ```
* array(
* array( //row 1
* 'export_result' => 1,
* 'aggregator_1' => 2,
* 'aggregator_2' => 3
* ),
* array( // row 2
* 'export_result' => 4,
* 'aggregator_1' => 5,
* 'aggregator_2' => 6
* )
* )
* ```
*
* the sorted result will be :
*
* ```
* array(
* array( 2, 3, 1 ),
* array( 5, 6, 4 )
* )
* ```
*
*/
protected function sortResult()
{
// get the keys for each row
$exportKeys = $this->export->getQueryKeys($this->exportData);
$aggregatorKeys = $this->getAggregatorKeysSorted();
$globalKeys = \array_merge($aggregatorKeys, $exportKeys);
$sortedResult = \array_map(function ($row) use ($globalKeys) {
$newRow = array();
foreach ($globalKeys as $key) {
$newRow[] = $this->getDisplayableResult($key, $row[$key]);
}
return $newRow;
}, $this->result);
\array_multisort($sortedResult);
return array($sortedResult, $exportKeys, $aggregatorKeys, $globalKeys);
}
/**
* get an array of aggregator keys. The keys are sorted as asked
* by user in the form.
*
* @return string[] an array containing the keys of aggregators
*/
protected function getAggregatorKeysSorted()
{
// empty array for aggregators keys
$keys = array();
// this association between key and aggregator alias will be used
// during sorting
$aggregatorKeyAssociation = array();
foreach ($this->aggregatorsData as $alias => $data) {
$aggregator = $this->exportManager->getAggregator($alias);
$aggregatorsKeys = $aggregator->getQueryKeys($data);
// append the keys from aggregator to the $keys existing array
$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;
}
}
// sort the result using the form
usort($keys, function ($a, $b) use ($aggregatorKeyAssociation) {
$A = $this->formatterData[$aggregatorKeyAssociation[$a]]['order'];
$B = $this->formatterData[$aggregatorKeyAssociation[$b]]['order'];
if ($A === $B) {
return 0;
} elseif ($A > $B) {
return 1;
} else {
return -1;
}
});
return $keys;
}
/**
* add headers to worksheet
*
* return the line number where the next content (i.e. result) should
* be appended.
*
* @param Worksheet $worksheet
* @param array $aggregatorKeys
* @param array $exportKeys
* @param int $line
* @return int
*/
protected function addHeaders(
Worksheet &$worksheet,
array $globalKeys,
$line
) {
// get the displayable form of headers
$displayables = array();
foreach ($globalKeys as $key) {
$displayables[] = $this->translator->trans(
$this->getDisplayableResult($key, '_header')
);
}
// add headers on worksheet
$worksheet->fromArray(
$displayables,
NULL,
'A'.$line);
return $line + 1;
}
protected function addContentTable(Worksheet $worksheet,
$sortedResults,
$line
) {
$worksheet->fromArray(
$sortedResults,
NULL,
'A'.$line);
return $line + count($sortedResults) + 1;
}
protected function getTitle()
{
return $this->translator->trans($this->export->getTitle());
}
/**
* Get the displayable result.
*
* @param string $key
* @param string $value
* @return string
*/
protected function getDisplayableResult($key, $value)
{
if ($this->cacheDisplayableResultIsInitialized === false) {
$this->initializeCache($key);
}
return call_user_func($this->cacheDisplayableResult[$key], $value);
}
protected function initializeCache($key)
{
/*
* this function follows the following steps :
*
* 1. associate all keys used in result with their export element
* (export or aggregator) and data;
* 2. associate all keys used in result with all the possible values :
* this array will be necessary to call `getLabels`
* 3. store the `callable` in an associative array, in cache
*/
// 1. create an associative array with key and export / aggregator
$keysExportElementAssociation = array();
// keys for export
foreach ($this->export->getQueryKeys($this->exportData) as $key) {
$keysExportElementAssociation[$key] = [$this->export,
$this->exportData];
}
// keys for aggregator
foreach ($this->aggregatorsData as $alias => $data) {
$aggregator = $this->exportManager->getAggregator($alias);
foreach ($aggregator->getQueryKeys($data) as $key) {
$keysExportElementAssociation[$key] = [$aggregator, $data];
}
}
// 2. collect all the keys before iteration
$keys = array_keys($keysExportElementAssociation);
$allValues = array();
// store all the values in an array
foreach ($this->result as $row) {
foreach ($keys as $key) {
$allValues[$key][] = $row[$key];
}
}
// 3. iterate on `keysExportElementAssociation` to store the callable
// in cache
foreach ($keysExportElementAssociation as $key => list($element, $data)) {
$this->cacheDisplayableResult[$key] =
$element->getLabels($key, \array_unique($allValues[$key]), $data);
}
// the cache is initialized !
$this->cacheDisplayableResultIsInitialized = true;
}
protected function getContentType($format)
{
switch ($format)
{
case 'csv':
return 'text/csv';
case 'ods':
return 'application/vnd.oasis.opendocument.spreadsheet';
case 'xlsx':
return 'application/vnd.openxmlformats-officedocument.'
. 'spreadsheetml.sheet';
}
}
public function getType()
{
return 'tabular';
}
}

View File

@@ -0,0 +1,285 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export\Formatter;
use Symfony\Component\HttpFoundation\Response;
use Chill\MainBundle\Export\FormatterInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
// 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
/**
* Create a CSV List for the export
*
* @author Champs-Libres <info@champs-libres.coop>
*/
class SpreadsheetListFormatter implements FormatterInterface
{
/**
* This variable cache the labels internally
*
* @var string[]
*/
protected $labelsCache = null;
protected $result = null;
protected $exportAlias = null;
protected $exportData = null;
protected $formatterData = null;
/**
*
* @var ExportManager
*/
protected $exportManager;
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct(TranslatorInterface $translatorInterface, ExportManager $exportManager)
{
$this->translator = $translatorInterface;
$this->exportManager = $exportManager;
}
public function getType()
{
return FormatterInterface::TYPE_LIST;
}
/**
* build a form, which will be used to collect data required for the execution
* of this formatter.
*
* @uses appendAggregatorForm
* @param FormBuilderInterface $builder
* @param type $exportAlias
* @param array $aggregatorAliases
*/
public function buildForm(
FormBuilderInterface $builder,
$exportAlias,
array $aggregatorAliases
){
$builder
->add('format', ChoiceType::class, array(
'choices' => array(
'OpenDocument Format (.ods) (LibreOffice, ...)' => 'ods',
'Microsoft Excel 2007-2013 XML (.xlsx) (Microsoft Excel, LibreOffice)' => 'xlsx'
),
'placeholder' => 'Choose the format'
))
->add('numerotation', ChoiceType::class, array(
'choices' => array(
'yes' => true,
'no' => false
),
'expanded' => true,
'multiple' => false,
'label' => "Add a number on first column",
'data' => true
));
}
public function getName()
{
return 'Spreadsheet list formatter (.xlsx, .ods)';
}
/**
* 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
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/
public function getResponse(
$result,
$formatterData,
$exportAlias,
array $exportData,
array $filtersData,
array $aggregatorsData
) {
$this->result = $result;
$this->exportAlias = $exportAlias;
$this->exportData = $exportData;
$this->formatterData = $formatterData;
$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();
$this->prepareHeaders($worksheet);
$i = 1;
foreach ($result as $row) {
$line = array();
if ($this->formatterData['numerotation'] === true) {
$worksheet->setCellValue('A'.($i+1), (string) $i);
}
$a = $this->formatterData['numerotation'] ? 'B' : 'A';
foreach ($row as $key => $value) {
$row = $a.($i+1);
if ($value instanceof \DateTimeInterface) {
$worksheet->setCellValue($row, Date::PHPToExcel($value));
$worksheet->getStyle($row)
->getNumberFormat()
->setFormatCode(NumberFormat::FORMAT_DATE_DDMMYYYY);
} else {
$worksheet->setCellValue($row, $this->getLabel($key, $value));
}
$a ++;
}
$i++;
}
switch ($this->formatterData['format'])
{
case 'ods':
$writer = \PhpOffice\PhpSpreadsheet\IOFactory
::createWriter($spreadsheet, 'Ods');
$contentType = "application/vnd.oasis.opendocument.spreadsheet";
break;
case 'xlsx':
$writer = \PhpOffice\PhpSpreadsheet\IOFactory
::createWriter($spreadsheet, 'Xlsx');
$contentType = 'application/vnd.openxmlformats-officedocument.'
. 'spreadsheetml.sheet';
break;
case 'csv':
$writer = \PhpOffice\PhpSpreadsheet\IOFactory
::createWriter($spreadsheet, 'Csv');
$contentType = 'text/csv';
break;
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");
}
$response = new Response();
$response->headers->set('content-type', $contentType);
$tempfile = \tempnam(\sys_get_temp_dir(), '');
$writer->save($tempfile);
$f = \fopen($tempfile, 'r');
$response->setContent(\stream_get_contents($f));
fclose($f);
// remove the temp file from disk
\unlink($tempfile);
return $response;
}
/**
* add the headers to the csv file
*
* @param Worksheet $worksheet
*/
protected function prepareHeaders(Worksheet $worksheet)
{
$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] : array();
$header_line = array();
if ($this->formatterData['numerotation'] === true) {
$header_line[] = $this->translator->trans('Number');
}
foreach ($first_row as $key => $value) {
$header_line[] = $this->translator->trans(
$this->getLabel($key, '_header'));
}
if (count($header_line) > 0) {
$worksheet->fromArray($header_line, NULL, 'A1');
}
}
/**
* Give the label corresponding to the given key and value.
*
* @param string $key
* @param string $value
* @return string
* @throws \LogicException if the label is not found
*/
protected function getLabel($key, $value)
{
if ($this->labelsCache === null) {
$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))));
}
return $this->labelsCache[$key]($value);
}
/**
* Prepare the label cache which will be used by getLabel. This function
* should be called only once in the generation lifecycle.
*/
protected function prepareCacheLabels()
{
$export = $this->exportManager->getExport($this->exportAlias);
$keys = $export->getQueryKeys($this->exportData);
foreach($keys as $key) {
// get an array with all values for this key if possible
$values = \array_map(function ($v) use ($key) { return $v[$key]; }, $this->result);
// store the label in the labelsCache property
$this->labelsCache[$key] = $export->getLabels($key, $values, $this->exportData);
}
}
}

View File

@@ -0,0 +1,71 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export;
use Symfony\Component\Form\FormBuilderInterface;
/**
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface FormatterInterface
{
const TYPE_TABULAR = 'tabular';
const TYPE_LIST = 'list';
public function getType();
public function getName();
/**
* build a form, which will be used to collect data required for the execution
* of this formatter.
*
* @uses appendAggregatorForm
* @param FormBuilderInterface $builder
* @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,
$exportAlias,
array $aggregatorAliases
);
/**
* 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
* @return \Symfony\Component\HttpFoundation\Response The response to be shown
*/
public function getResponse(
$result,
$formatterData,
$exportAlias,
array $exportData,
array $filtersData,
array $aggregatorsData
);
}

View File

@@ -0,0 +1,16 @@
<?php
/*
*
*/
namespace Chill\MainBundle\Export;
/**
* Add a grouping option to exports.
*
* **usage**: the exports will be grouped under the key given by the `getGroup`
* method.
*/
interface GroupedExportInterface
{
public function getGroup(): string;
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Chill\MainBundle\Export;
/**
* Define methods to export list.
*
* This interface is a specification of export interface
* and should be used when the export does not supports aggregators
* (and list does not support aggregation on their data).
*
* When used, the `ExportManager` will not handle aggregator for this class.
*/
interface ListInterface extends ExportInterface
{
}

View File

@@ -0,0 +1,58 @@
<?php
/*
* Copyright (C) 2016 Champs-Libres <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/>.
*/
namespace Chill\MainBundle\Export;
use Doctrine\ORM\QueryBuilder;
/**
* Modifiers modify the export's query.
*
* Known subclasses : AggregatorInterface and FilterInterface
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ModifierInterface extends ExportElementInterface
{
/**
* The role required for executing this Modifier
*
* If null, will used the ExportInterface::requiredRole role from
* the current executing export.
*
* @return NULL|\Symfony\Component\Security\Core\Role\Role A role required to execute this ModifiersInterface
*/
public function addRole();
/**
* On which type of Export this ModifiersInterface may apply.
*
* @return string the type on which the Modifiers apply
*/
public function applyOn();
/**
* 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)
*/
public function alterQuery(QueryBuilder $qb, $data);
}