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,59 @@
<?php
/*
* Copyright (C) 2019 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\PersonBundle\Export;
use Doctrine\ORM\QueryBuilder;
/**
*
*
*/
class AbstractAccompanyingPeriodExportElement
{
/**
* Return true if "accompanying_period" alias is present in the query alises.
*
* @param QueryBuilder $query
* @return bool
*/
protected function havingAccompanyingPeriodInJoin(QueryBuilder $query): bool
{
$joins = $query->getDQLPart('join') ?? [];
return (\in_array('accompanying_period', $query->getAllAliases()));
}
/**
* Add the accompanying period alias to the query
*
* @param QueryBuilder $query
* @return void
* @throws \LogicException if the "person" alias is not present and attaching accompanying period is not possible
*/
protected function addJoinAccompanyingPeriod(QueryBuilder $query): void
{
if (FALSE === $this->havingAccompanyingPeriodInJoin($query)) {
if (FALSE === \in_array('person', $query->getAllAliases())) {
throw new \LogicException("the alias 'person' does not exists in "
. "query builder");
}
$query->join('person.accompanyingPeriods', 'accompanying_period');
}
}
}

View File

@@ -0,0 +1,112 @@
<?php
/*
* Copyright (C) 2017 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\PersonBundle\Export\Aggregator;
use Chill\MainBundle\Export\AggregatorInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Translation\TranslatorInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class AgeAggregator implements AggregatorInterface,
ExportElementValidatedInterface
{
/**
*
* @var
*/
protected $translator;
public function __construct($translator)
{
$this->translator = $translator;
}
public function addRole()
{
return null;
}
public function alterQuery(QueryBuilder $qb, $data)
{
$qb->addSelect('DATE_DIFF(:date_age_calculation, person.birthdate)/365 as person_age');
$qb->setParameter('date_age_calculation', $data['date_age_calculation']);
$qb->addGroupBy('person_age');
}
public function applyOn()
{
return 'person';
}
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder)
{
$builder->add('date_age_calculation', DateType::class, array(
'label' => "Calculate age in relation to this date",
'data' => new \DateTime(),
'attr' => array('class' => 'datepicker'),
'widget'=> 'single_text',
'format' => 'dd-MM-yyyy'
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
if ($data['date_age_calculation'] === null) {
$context->buildViolation("The date should not be empty")
->addViolation();
}
}
public function getLabels($key, array $values, $data)
{
return function($value) {
if ($value === '_header') {
return "Age";
}
if ($value === NULL) {
return $this->translator->trans("without data");
}
return $value;
};
}
public function getQueryKeys($data)
{
return array(
'person_age'
);
}
public function getTitle()
{
return "Aggregate by age";
}
}

View File

@@ -0,0 +1,202 @@
<?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\PersonBundle\Export\Aggregator;
use Chill\MainBundle\Export\AggregatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Translation\TranslatorInterface;
use Chill\MainBundle\Util\CountriesInfo;
use Symfony\Component\Security\Core\Role\Role;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class CountryOfBirthAggregator implements AggregatorInterface,
ExportElementValidatedInterface
{
/**
*
* @var EntityRepository
*/
protected $countriesRepository;
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct(EntityRepository $countriesRepository,
TranslatableStringHelper $translatableStringHelper,
TranslatorInterface $translator)
{
$this->countriesRepository = $countriesRepository;
$this->translatableStringHelper = $translatableStringHelper;
$this->translator = $translator;
}
public function applyOn()
{
return 'person';
}
public function buildForm(FormBuilderInterface $builder)
{
$builder->add('group_by_level', ChoiceType::class, array(
'choices' => array(
'Group by continents' => 'continent',
'Group by country' => 'country'
),
'expanded' => true,
'multiple' => false
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
if ($data['group_by_level'] === null) {
$context->buildViolation("You should select an option")
->addViolation();
}
}
public function alterQuery(QueryBuilder $qb, $data)
{
// add a clause in select part
if ($data['group_by_level'] === 'country') {
$qb->addSelect('countryOfBirth.countryCode as country_of_birth_aggregator');
} elseif ($data['group_by_level'] === 'continent') {
$clause = 'CASE '
. 'WHEN countryOfBirth.countryCode IN(:cob_africa_codes) THEN \'AF\' '
. 'WHEN countryOfBirth.countryCode IN(:cob_asia_codes) THEN \'AS\' '
. 'WHEN countryOfBirth.countryCode IN(:cob_europe_codes) THEN \'EU\' '
. 'WHEN countryOfBirth.countryCode IN(:cob_north_america_codes) THEN \'NA\' '
. 'WHEN countryOfBirth.countryCode IN(:cob_south_america_codes) THEN \'SA\' '
. 'WHEN countryOfBirth.countryCode IN(:cob_oceania_codes) THEN \'OC\' '
. 'WHEN countryOfBirth.countryCode IN(:cob_antartica_codes) THEN \'AN\' '
. 'ELSE \'\' '
. 'END as country_of_birth_aggregator ';
$qb->addSelect($clause);
$params =
array(
'cob_africa_codes' => CountriesInfo::getCountriesCodeByContinent('AF'),
'cob_asia_codes' => CountriesInfo::getCountriesCodeByContinent('AS'),
'cob_europe_codes' => CountriesInfo::getCountriesCodeByContinent('EU'),
'cob_north_america_codes' => CountriesInfo::getCountriesCodeByContinent('NA'),
'cob_south_america_codes' => CountriesInfo::getCountriesCodeByContinent('SA'),
'cob_oceania_codes' => CountriesInfo::getCountriesCodeByContinent('OC'),
'cob_antartica_codes' => CountriesInfo::getCountriesCodeByContinent('AN')
);
foreach ($params as $k => $v) {
$qb->setParameter($k, $v);
}
} else {
throw new \LogicException("The group_by_level '".$data['group_by_level']
." is not known.");
}
$qb->leftJoin('person.countryOfBirth', 'countryOfBirth');
// add group by
$groupBy = $qb->getDQLPart('groupBy');
if (!empty($groupBy)) {
$qb->addGroupBy('country_of_birth_aggregator');
} else {
$qb->groupBy('country_of_birth_aggregator');
}
}
public function getTitle()
{
return "Group people by country of birth";
}
public function getQueryKeys($data)
{
return array('country_of_birth_aggregator');
}
public function addRole()
{
return NULL;
}
public function getLabels($key, array $values, $data)
{
if ($data['group_by_level'] === 'country') {
$qb = $this->countriesRepository->createQueryBuilder('c');
$countries = $qb
->andWhere($qb->expr()->in('c.countryCode', ':countries'))
->setParameter('countries', $values)
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
// initialize array and add blank key for null values
$labels[''] = $this->translator->trans('without data');
$labels['_header'] = $this->translator->trans('Country of birth');
foreach($countries as $row) {
$labels[$row['c_countryCode']] = $this->translatableStringHelper->localize($row['c_name']);
}
} elseif ($data['group_by_level'] === 'continent') {
$labels = array(
'EU' => $this->translator->trans('Europe'),
'AS' => $this->translator->trans('Asia'),
'AN' => $this->translator->trans('Antartica'),
'AF' => $this->translator->trans('Africa'),
'SA' => $this->translator->trans('South America'),
'NA' => $this->translator->trans('North America'),
'OC' => $this->translator->trans('Oceania'),
'' => $this->translator->trans('without data'),
'_header' => $this->translator->trans('Continent of birth')
);
}
return function($value) use ($labels) {
return $labels[$value];
};
}
}

View File

@@ -0,0 +1,103 @@
<?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\PersonBundle\Export\Aggregator;
use Chill\MainBundle\Export\AggregatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Translation\TranslatorInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Export\Declarations;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class GenderAggregator implements AggregatorInterface
{
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
public function applyOn()
{
return Declarations::PERSON_TYPE;
}
public function buildForm(FormBuilderInterface $builder)
{
}
public function alterQuery(QueryBuilder $qb, $data)
{
$qb->addSelect('person.gender as gender');
$qb->addGroupBy('gender');
}
public function getTitle()
{
return "Group people by gender";
}
public function getQueryKeys($data)
{
return array('gender');
}
public function getLabels($key, array $values, $data)
{
return function($value) {
switch ($value) {
case Person::FEMALE_GENDER :
return $this->translator->trans('woman');
case Person::MALE_GENDER :
return $this->translator->trans('man');
case Person::BOTH_GENDER:
return $this->translator->trans('both');
case null:
return $this->translator->trans('Not given');
case '_header' :
return $this->translator->trans('Gender');
default:
throw new \LogicException(sprintf("The value %s is not valid", $value));
}
};
}
public function addRole()
{
return NULL;
}
}

View File

@@ -0,0 +1,201 @@
<?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\PersonBundle\Export\Aggregator;
use Chill\MainBundle\Export\AggregatorInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Symfony\Component\Translation\TranslatorInterface;
use Chill\MainBundle\Util\CountriesInfo;
use Symfony\Component\Security\Core\Role\Role;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class NationalityAggregator implements AggregatorInterface,
ExportElementValidatedInterface
{
/**
*
* @var EntityRepository
*/
protected $countriesRepository;
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
*
* @var TranslatorInterface
*/
protected $translator;
public function __construct(EntityRepository $countriesRepository,
TranslatableStringHelper $translatableStringHelper,
TranslatorInterface $translator)
{
$this->countriesRepository = $countriesRepository;
$this->translatableStringHelper = $translatableStringHelper;
$this->translator = $translator;
}
public function applyOn()
{
return 'person';
}
public function buildForm(FormBuilderInterface $builder)
{
$builder->add('group_by_level', ChoiceType::class, array(
'choices' => array(
'Group by continents' => 'continent',
'Group by country' => 'country'
),
'expanded' => true,
'multiple' => false
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
if ($data['group_by_level'] === null) {
$context->buildViolation("You should select an option")
->addViolation();
}
}
public function alterQuery(QueryBuilder $qb, $data)
{
// add a clause in select part
if ($data['group_by_level'] === 'country') {
$qb->addSelect('nationality.countryCode as nationality_aggregator');
} elseif ($data['group_by_level'] === 'continent') {
$clause = 'CASE '
. 'WHEN nationality.countryCode IN(:africa_codes) THEN \'AF\' '
. 'WHEN nationality.countryCode IN(:asia_codes) THEN \'AS\' '
. 'WHEN nationality.countryCode IN(:europe_codes) THEN \'EU\' '
. 'WHEN nationality.countryCode IN(:north_america_codes) THEN \'NA\' '
. 'WHEN nationality.countryCode IN(:south_america_codes) THEN \'SA\' '
. 'WHEN nationality.countryCode IN(:oceania_codes) THEN \'OC\' '
. 'WHEN nationality.countryCode IN(:antartica_codes) THEN \'AN\' '
. 'ELSE \'\' '
. 'END as nationality_aggregator ';
$qb->addSelect($clause);
$params =
array(
'africa_codes' => CountriesInfo::getCountriesCodeByContinent('AF'),
'asia_codes' => CountriesInfo::getCountriesCodeByContinent('AS'),
'europe_codes' => CountriesInfo::getCountriesCodeByContinent('EU'),
'north_america_codes' => CountriesInfo::getCountriesCodeByContinent('NA'),
'south_america_codes' => CountriesInfo::getCountriesCodeByContinent('SA'),
'oceania_codes' => CountriesInfo::getCountriesCodeByContinent('OC'),
'antartica_codes' => CountriesInfo::getCountriesCodeByContinent('AN')
);
foreach ($params as $k => $v) {
$qb->setParameter($k, $v);
}
} else {
throw new \LogicException("The group_by_level '".$data['group_by_level']
." is not known.");
}
$qb->leftJoin('person.nationality', 'nationality');
// add group by
$groupBy = $qb->getDQLPart('groupBy');
if (!empty($groupBy)) {
$qb->addGroupBy('nationality_aggregator');
} else {
$qb->groupBy('nationality_aggregator');
}
}
public function getTitle()
{
return "Group people by nationality";
}
public function getQueryKeys($data)
{
return array('nationality_aggregator');
}
public function addRole()
{
return NULL;
}
public function getLabels($key, array $values, $data)
{
if ($data['group_by_level'] === 'country') {
$qb = $this->countriesRepository->createQueryBuilder('c');
$countries = $qb
->andWhere($qb->expr()->in('c.countryCode', ':countries'))
->setParameter('countries', $values)
->getQuery()
->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
// initialize array and add blank key for null values
$labels[''] = $this->translator->trans('without data');
$labels['_header'] = $this->translator->trans('Nationality');
foreach($countries as $row) {
$labels[$row['c_countryCode']] = $this->translatableStringHelper->localize($row['c_name']);
}
} elseif ($data['group_by_level'] === 'continent') {
$labels = array(
'EU' => $this->translator->trans('Europe'),
'AS' => $this->translator->trans('Asia'),
'AN' => $this->translator->trans('Antartica'),
'AF' => $this->translator->trans('Africa'),
'SA' => $this->translator->trans('South America'),
'NA' => $this->translator->trans('North America'),
'OC' => $this->translator->trans('Oceania'),
'' => $this->translator->trans('without data'),
'_header' => $this->translator->trans('Continent')
);
}
return function($value) use ($labels) {
return $labels[$value];
};
}
}

View File

@@ -0,0 +1,32 @@
<?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\PersonBundle\Export;
/**
* This class declare constants used for the export framework.
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
abstract class Declarations
{
CONST PERSON_TYPE = 'person';
CONST PERSON_IMPLIED_IN = 'person_implied_in';
}

View File

@@ -0,0 +1,136 @@
<?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\PersonBundle\Export\Export;
use Chill\MainBundle\Export\ExportInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\Query;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Component\Security\Core\Role\Role;
use Chill\PersonBundle\Export\Declarations;
use Chill\MainBundle\Export\FormatterInterface;
use Doctrine\ORM\EntityManagerInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class CountPerson implements ExportInterface
{
/**
*
* @var EntityManagerInterface
*/
protected $entityManager;
public function __construct(
EntityManagerInterface $em
)
{
$this->entityManager = $em;
}
/**
*
*/
public function getType()
{
return Declarations::PERSON_TYPE;
}
public function getDescription()
{
return "Count peoples by various parameters.";
}
public function getTitle()
{
return "Count peoples";
}
public function requiredRole()
{
return new Role(PersonVoter::STATS);
}
/**
* Initiate the query
*
* @param QueryBuilder $qb
* @return QueryBuilder
*/
public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
{
$centers = array_map(function($el) { return $el['center']; }, $acl);
$qb = $this->entityManager->createQueryBuilder();
$qb->select('COUNT(person.id) AS export_result')
->from('ChillPersonBundle:Person', 'person')
->join('person.center', 'center')
->andWhere('center IN (:authorized_centers)')
->setParameter('authorized_centers', $centers);
;
return $qb;
}
public function getResult($qb, $data)
{
return $qb->getQuery()->getResult(Query::HYDRATE_SCALAR);
}
public function getQueryKeys($data)
{
return array('export_result');
}
public function getLabels($key, array $values, $data)
{
if ($key !== 'export_result') {
throw new \LogicException("the key $key is not used by this export");
}
$labels = array_combine($values, $values);
$labels['_header'] = $this->getTitle();
return function($value) use ($labels) {
return $labels[$value];
};
}
public function getAllowedFormattersTypes()
{
return array(FormatterInterface::TYPE_TABULAR);
}
public function buildForm(FormBuilderInterface $builder) {
}
public function supportsModifiers()
{
return array(Declarations::PERSON_TYPE, Declarations::PERSON_IMPLIED_IN);
}
}

View File

@@ -0,0 +1,503 @@
<?php
namespace Chill\PersonBundle\Export\Export;
use Chill\MainBundle\Export\ListInterface;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\Query;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Component\Security\Core\Role\Role;
use Chill\PersonBundle\Export\Declarations;
use Chill\MainBundle\Export\FormatterInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Chill\PersonBundle\Entity\Person;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\CustomFieldsBundle\Service\CustomFieldProvider;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Chill\CustomFieldsBundle\CustomFields\CustomFieldChoice;
/**
* Render a list of peoples
*
* @author julien
*/
class ListPerson implements ListInterface, ExportElementValidatedInterface
{
/**
*
* @var EntityManagerInterface
*/
protected $entityManager;
/**
*
* @var TranslatorInterface
*/
protected $translator;
/**
*
* @var TranslatableStringHelper
*/
protected $translatableStringHelper;
/**
*
* @var CustomFieldProvider
*/
protected $customFieldProvider;
protected $fields = array(
'id', 'firstName', 'lastName', 'birthdate',
'placeOfBirth', 'gender', 'memo', 'email', 'phonenumber',
'mobilenumber', 'contactInfo', 'countryOfBirth', 'nationality',
'address_street_address_1', 'address_street_address_2',
'address_valid_from', 'address_postcode_label', 'address_postcode_code',
'address_country_name', 'address_country_code', 'address_isnoaddress'
);
private $slugs = [];
public function __construct(
EntityManagerInterface $em,
TranslatorInterface $translator,
TranslatableStringHelper $translatableStringHelper,
CustomFieldProvider $customFieldProvider
) {
$this->entityManager = $em;
$this->translator = $translator;
$this->translatableStringHelper = $translatableStringHelper;
$this->customFieldProvider = $customFieldProvider;
}
/**
* {@inheritDoc}
*
* @param FormBuilderInterface $builder
*/
public function buildForm(FormBuilderInterface $builder)
{
$choices = array_combine($this->fields, $this->fields);
foreach ($this->getCustomFields() as $cf) {
$choices
[$this->translatableStringHelper->localize($cf->getName())]
=
$cf->getSlug();
}
// Add a checkbox to select fields
$builder->add('fields', ChoiceType::class, array(
'multiple' => true,
'expanded' => true,
'choices' => $choices,
'label' => 'Fields to include in export',
'choice_attr' => function($val, $key, $index) {
// add a 'data-display-target' for address fields
if (substr($val, 0, 8) === 'address_') {
return ['data-display-target' => 'address_date'];
} else {
return [];
}
},
'constraints' => [new Callback(array(
'callback' => function($selected, ExecutionContextInterface $context) {
if (count($selected) === 0) {
$context->buildViolation('You must select at least one element')
->atPath('fields')
->addViolation();
}
}
))]
));
// add a date field for addresses
$builder->add('address_date', DateType::class, array(
'label' => "Address valid at this date",
'data' => new \DateTime(),
'attr' => array( 'class' => 'datepicker'),
'widget'=> 'single_text',
'format' => 'dd-MM-yyyy',
'required' => false,
'block_name' => 'list_export_form_address_date'
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
// get the field starting with address_
$addressFields = array_filter(function($el) {
return substr($el, 0, 8) === 'address_';
}, $this->fields);
// check if there is one field starting with address in data
if (count(array_intersect($data['fields'], $addressFields)) > 0) {
// if a field address is checked, the date must not be empty
if (empty($data['address_date'])) {
$context
->buildViolation("You must set this date if an address is checked")
->atPath('address_date')
->addViolation();
}
}
}
/**
* Get custom fields associated with person
*
* @return CustomField[]
*/
private function getCustomFields()
{
return $this->entityManager
->createQuery("SELECT cf "
. "FROM ChillCustomFieldsBundle:CustomField cf "
. "JOIN cf.customFieldGroup g "
. "WHERE cf.type != :title AND g.entity LIKE :entity")
->setParameters(array(
'title' => 'title',
'entity' => \addcslashes(Person::class, "\\")
))
->getResult();
}
/**
* {@inheritDoc}
*
* @return type
*/
public function getAllowedFormattersTypes()
{
return array(FormatterInterface::TYPE_LIST);
}
/**
* {@inheritDoc}
*
* @return string
*/
public function getDescription()
{
return "Create a list of people according to various filters.";
}
/**
* {@inheritDoc}
*
* @param type $key
* @param array $values
* @param type $data
* @return type
*/
public function getLabels($key, array $values, $data)
{
switch ($key) {
case 'birthdate':
// for birthdate, we have to transform the string into a date
// to format the date correctly.
return function($value) {
if ($value === '_header') { return 'birthdate'; }
if (empty($value))
{
return "";
}
$date = \DateTime::createFromFormat('Y-m-d', $value);
// check that the creation could occurs.
if ($date === false) {
throw new \Exception(sprintf("The value %s could "
. "not be converted to %s", $value, \DateTime::class));
}
return $date->format('d-m-Y');
};
case 'gender' :
// for gender, we have to translate men/women statement
return function($value) {
if ($value === '_header') { return 'gender'; }
return $this->translator->trans($value);
};
case 'countryOfBirth':
case 'nationality':
$countryRepository = $this->entityManager
->getRepository('ChillMainBundle:Country');
// load all countries in a single query
$countryRepository->findBy(array('countryCode' => $values));
return function($value) use ($key, $countryRepository) {
if ($value === '_header') { return \strtolower($key); }
if ($value === NULL) {
return $this->translator->trans('no data');
}
$country = $countryRepository->find($value);
return $this->translatableStringHelper->localize(
$country->getName());
};
case 'address_country_name':
return function($value) use ($key) {
if ($value === '_header') { return \strtolower($key); }
if ($value === NULL) {
return '';
}
return $this->translatableStringHelper->localize(json_decode($value, true));
};
case 'address_isnoaddress':
return function($value) use ($key) {
if ($value === '_header') { return 'address.address_homeless'; }
if ($value) {
return 'X';
} else {
return '';
}
};
default:
// for fields which are associated with person
if (in_array($key, $this->fields)) {
return function($value) use ($key) {
if ($value === '_header') { return \strtolower($key); }
return $value;
};
} else {
return $this->getLabelForCustomField($key, $values, $data);
}
}
}
private function getLabelForCustomField($key, array $values, $data)
{
// for fields which are custom fields
/* @var $cf CustomField */
$cf = $this->entityManager
->getRepository(CustomField::class)
->findOneBy(array('slug' => $this->DQLToSlug($key)));
$cfType = $this->customFieldProvider->getCustomFieldByType($cf->getType());
$defaultFunction = function($value) use ($cf) {
if ($value === '_header') {
return $this->translatableStringHelper->localize($cf->getName());
}
return $this->customFieldProvider
->getCustomFieldByType($cf->getType())
->render(json_decode($value, true), $cf, 'csv');
};
if ($cfType instanceof CustomFieldChoice and $cfType->isMultiple($cf)) {
return function($value) use ($cf, $cfType, $key) {
$slugChoice = $this->extractInfosFromSlug($key)['additionnalInfos']['choiceSlug'];
$decoded = \json_decode($value, true);
if ($value === '_header') {
$label = $cfType->getChoices($cf)[$slugChoice];
return $this->translatableStringHelper->localize($cf->getName())
.' | '.$label;
}
if ($slugChoice === '_other' and $cfType->isChecked($cf, $choiceSlug, $decoded)) {
return $cfType->extractOtherValue($cf, $decoded);
} else {
return $cfType->isChecked($cf, $slugChoice, $decoded);
}
};
} else {
return $defaultFunction;
}
}
/**
* {@inheritDoc}
*
* @param type $data
* @return type
*/
public function getQueryKeys($data)
{
$fields = array();
foreach ($data['fields'] as $key) {
if (in_array($key, $this->fields)) {
$fields[] = $key;
}
}
// add the key from slugs and return
return \array_merge($fields, \array_keys($this->slugs));
}
/**
* clean a slug to be usable by DQL
*
* @param string $slugsanitize
* @param string $type the type of the customfield, if required (currently only for choices)
* @return string
*/
private function slugToDQL($slug, $type = "default", array $additionalInfos = [])
{
$uid = 'slug_'.\uniqid();
$this->slugs[$uid] = [
'slug' => $slug,
'type' => $type,
'additionnalInfos' => $additionalInfos
];
return $uid;
}
private function DQLToSlug($cleanedSlug)
{
return $this->slugs[$cleanedSlug]['slug'];
}
/**
*
* @param type $cleanedSlug
* @return an array with keys = 'slug', 'type', 'additionnalInfo'
*/
private function extractInfosFromSlug($slug)
{
return $this->slugs[$slug];
}
/**
* {@inheritDoc}
*
*/
public function getResult($query, $data)
{
return $query->getQuery()->getResult(Query::HYDRATE_SCALAR);
}
/**
* {@inheritDoc}
*
* @return string
*/
public function getTitle()
{
return "List peoples";
}
/**
* {@inheritDoc}
*
*/
public function getType()
{
return Declarations::PERSON_TYPE;
}
/**
* {@inheritDoc}
*
*/
public function initiateQuery(array $requiredModifiers, array $acl, array $data = array())
{
$centers = array_map(function($el) { return $el['center']; }, $acl);
// throw an error if any fields are present
if (!\array_key_exists('fields', $data)) {
throw new \Doctrine\DBAL\Exception\InvalidArgumentException("any fields "
. "have been checked");
}
$qb = $this->entityManager->createQueryBuilder();
foreach ($this->fields as $f) {
if (in_array($f, $data['fields'])) {
switch ($f) {
case 'countryOfBirth':
case 'nationality':
$qb->addSelect(sprintf('IDENTITY(person.%s) as %s', $f, $f));
break;
case 'address_street_address_1':
case 'address_street_address_2':
case 'address_valid_from':
case 'address_postcode_label':
case 'address_postcode_code':
case 'address_country_name':
case 'address_country_code':
case 'address_isnoaddress':
$qb->addSelect(sprintf(
'GET_PERSON_ADDRESS_%s(person.id, :address_date) AS %s',
// get the part after address_
strtoupper(substr($f, 8)),
$f));
$qb->setParameter('address_date', $data['address_date']);
break;
default:
$qb->addSelect(sprintf('person.%s as %s', $f, $f));
}
}
}
foreach ($this->getCustomFields() as $cf) {
$cfType = $this->customFieldProvider->getCustomFieldByType($cf->getType());
if ($cfType instanceof CustomFieldChoice and $cfType->isMultiple($cf)) {
foreach($cfType->getChoices($cf) as $choiceSlug => $label) {
$slug = $this->slugToDQL($cf->getSlug(), 'choice', [ 'choiceSlug' => $choiceSlug ]);
$qb->addSelect(
sprintf('GET_JSON_FIELD_BY_KEY(person.cFData, :slug%s) AS %s',
$slug, $slug));
$qb->setParameter(sprintf('slug%s', $slug), $cf->getSlug());
}
} else {
$slug = $this->slugToDQL($cf->getSlug());
$qb->addSelect(
sprintf('GET_JSON_FIELD_BY_KEY(person.cFData, :slug%s) AS %s',
$slug, $slug));
$qb->setParameter(sprintf('slug%s', $slug), $cf->getSlug());
}
}
$qb
->from('ChillPersonBundle:Person', 'person')
->join('person.center', 'center')
->andWhere('center IN (:authorized_centers)')
->setParameter('authorized_centers', $centers);
;
return $qb;
}
/**
*
* {@inheritDoc}
*/
public function requiredRole()
{
return new Role(PersonVoter::LISTS);
}
/**
*
* {@inheritDoc}
*/
public function supportsModifiers()
{
return array(Declarations::PERSON_TYPE, Declarations::PERSON_IMPLIED_IN);
}
}

View File

@@ -0,0 +1,85 @@
<?php
/*
* Copyright (C) 2019 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\PersonBundle\Export\Filter;
use Chill\MainBundle\Export\FilterInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Form\Type\ChillDateType;
use Doctrine\DBAL\Types\Type;
use Chill\PersonBundle\Export\AbstractAccompanyingPeriodExportElement;
/**
*
*
*/
class AccompanyingPeriodClosingFilter extends AbstractAccompanyingPeriodExportElement implements FilterInterface
{
public function addRole()
{
return null;
}
public function alterQuery(QueryBuilder $qb, $data)
{
$this->addJoinAccompanyingPeriod($qb);
$clause = $qb->expr()->andX(
$qb->expr()->lte('accompanying_period.closingDate', ':date_to'),
$qb->expr()->gte('accompanying_period.closingDate', ':date_from'));
$qb->andWhere($clause);
$qb->setParameter('date_from', $data['date_from'], Type::DATE);
$qb->setParameter('date_to', $data['date_to'], Type::DATE);
}
public function applyOn(): string
{
return 'person';
}
public function buildForm(FormBuilderInterface $builder)
{
$builder->add('date_from', ChillDateType::class, array(
'label' => "Having an accompanying period closed after this date",
'data' => new \DateTime("-1 month"),
));
$builder->add('date_to', ChillDateType::class, array(
'label' => "Having an accompanying period closed before this date",
'data' => new \DateTime(),
));
}
public function describeAction($data, $format = 'string')
{
return [
"Filtered by accompanying period: persons having an accompanying period"
. " closed between the %date_from% and %date_to%",
[
'%date_from%' => $data['date_from']->format('d-m-Y'),
'%date_to%' => $data['date_to']->format('d-m-Y')
]
];
}
public function getTitle(): string
{
return "Filter by accompanying period: closed between two dates";
}
}

View File

@@ -0,0 +1,95 @@
<?php
/*
* Copyright (C) 2019 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\PersonBundle\Export\Filter;
use Chill\MainBundle\Export\FilterInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Form\Type\ChillDateType;
use Doctrine\DBAL\Types\Type;
use Chill\PersonBundle\Export\AbstractAccompanyingPeriodExportElement;
/**
*
*
*/
class AccompanyingPeriodFilter extends AbstractAccompanyingPeriodExportElement implements FilterInterface
{
public function addRole()
{
return null;
}
public function alterQuery(QueryBuilder $qb, $data)
{
$this->addJoinAccompanyingPeriod($qb);
$clause = $qb->expr()->andX();
$clause->add(
$qb->expr()->lte('accompanying_period.openingDate', ':date_to')
);
$clause->add(
$qb->expr()->orX(
$qb->expr()->gte('accompanying_period.closingDate', ':date_from'),
$qb->expr()->isNull('accompanying_period.closingDate')
)
);
$qb->andWhere($clause);
$qb->setParameter('date_from', $data['date_from'], Type::DATE);
$qb->setParameter('date_to', $data['date_to'], Type::DATE);
}
public function applyOn(): string
{
return 'person';
}
public function buildForm(FormBuilderInterface $builder)
{
$builder->add('date_from', ChillDateType::class, array(
'label' => "Having an accompanying period opened after this date",
'data' => new \DateTime("-1 month"),
));
$builder->add('date_to', ChillDateType::class, array(
'label' => "Having an accompanying period ending before this date, or "
. "still opened at this date",
'data' => new \DateTime(),
));
}
public function describeAction($data, $format = 'string')
{
return [
"Filtered by accompanying period: persons having an accompanying period"
. " opened after the %date_from% and closed before the %date_to% (or still opened "
. "at the %date_to%)",
[
'%date_from%' => $data['date_from']->format('d-m-Y'),
'%date_to%' => $data['date_to']->format('d-m-Y')
]
];
}
public function getTitle(): string
{
return "Filter by accompanying period: active period";
}
}

View File

@@ -0,0 +1,85 @@
<?php
/*
* Copyright (C) 2019 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\PersonBundle\Export\Filter;
use Chill\MainBundle\Export\FilterInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Form\Type\ChillDateType;
use Doctrine\DBAL\Types\Type;
use Chill\PersonBundle\Export\AbstractAccompanyingPeriodExportElement;
/**
*
*
*/
class AccompanyingPeriodOpeningFilter extends AbstractAccompanyingPeriodExportElement implements FilterInterface
{
public function addRole()
{
return null;
}
public function alterQuery(QueryBuilder $qb, $data)
{
$this->addJoinAccompanyingPeriod($qb);
$clause = $qb->expr()->andX(
$qb->expr()->lte('accompanying_period.openingDate', ':date_to'),
$qb->expr()->gte('accompanying_period.openingDate', ':date_from'));
$qb->andWhere($clause);
$qb->setParameter('date_from', $data['date_from'], Type::DATE);
$qb->setParameter('date_to', $data['date_to'], Type::DATE);
}
public function applyOn(): string
{
return 'person';
}
public function buildForm(FormBuilderInterface $builder)
{
$builder->add('date_from', ChillDateType::class, array(
'label' => "Having an accompanying period opened after this date",
'data' => new \DateTime("-1 month"),
));
$builder->add('date_to', ChillDateType::class, array(
'label' => "Having an accompanying period opened before this date",
'data' => new \DateTime(),
));
}
public function describeAction($data, $format = 'string')
{
return [
"Filtered by accompanying period: persons having an accompanying period"
. " opened between the %date_from% and %date_to%",
[
'%date_from%' => $data['date_from']->format('d-m-Y'),
'%date_to%' => $data['date_to']->format('d-m-Y')
]
];
}
public function getTitle(): string
{
return "Filter by accompanying period: starting between two dates";
}
}

View File

@@ -0,0 +1,130 @@
<?php
/*
* Copyright (C) 2017 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\PersonBundle\Export\Filter;
use Chill\MainBundle\Export\FilterInterface;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Doctrine\ORM\Query\Expr;
use Chill\MainBundle\Form\Type\Export\FilterType;
use Symfony\Component\Form\FormError;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class BirthdateFilter implements FilterInterface, ExportElementValidatedInterface
{
public function addRole()
{
return null;
}
public function alterQuery(\Doctrine\ORM\QueryBuilder $qb, $data)
{
$where = $qb->getDQLPart('where');
$clause = $qb->expr()->between('person.birthdate', ':date_from',
':date_to');
if ($where instanceof Expr\Andx) {
$where->add($clause);
} else {
$where = $qb->expr()->andX($clause);
}
$qb->add('where', $where);
$qb->setParameter('date_from', $data['date_from']);
$qb->setParameter('date_to', $data['date_to']);
}
public function applyOn()
{
return 'person';
}
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder)
{
$builder->add('date_from', DateType::class, array(
'label' => "Born after this date",
'data' => new \DateTime(),
'attr' => array('class' => 'datepicker'),
'widget'=> 'single_text',
'format' => 'dd-MM-yyyy',
));
$builder->add('date_to', DateType::class, array(
'label' => "Born before this date",
'data' => new \DateTime(),
'attr' => array('class' => 'datepicker'),
'widget'=> 'single_text',
'format' => 'dd-MM-yyyy',
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
$date_from = $data['date_from'];
$date_to = $data['date_to'];
if ($date_from === null) {
$context->buildViolation('The "date from" should not be empty')
//->atPath('date_from')
->addViolation();
}
if ($date_to === null) {
$context->buildViolation('The "date to" should not be empty')
//->atPath('date_to')
->addViolation();
}
if (
($date_from !== null && $date_to !== null)
&&
$date_from >= $date_to
) {
$context->buildViolation('The date "date to" should be after the '
. 'date given in "date from" field')
->addViolation();
}
}
public function describeAction($data, $format = 'string')
{
return array('Filtered by person\'s birtdate: '
. 'between %date_from% and %date_to%', array(
'%date_from%' => $data['date_from']->format('d-m-Y'),
'%date_to%' => $data['date_to']->format('d-m-Y')
));
}
public function getTitle()
{
return 'Filter by person\'s birthdate';
}
}

View File

@@ -0,0 +1,139 @@
<?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\PersonBundle\Export\Filter;
use Chill\MainBundle\Export\FilterInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query\Expr;
use Symfony\Component\Security\Core\Role\Role;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Translation\TranslatorInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class GenderFilter implements FilterInterface,
ExportElementValidatedInterface
{
/**
*
* @var TranslatorInterface
*/
protected $translator;
function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
public function applyOn()
{
return 'person';
}
/**
*
*/
public function buildForm(FormBuilderInterface $builder)
{
$builder->add('accepted_genders', ChoiceType::class, array(
'choices' => array(
'Woman' => Person::FEMALE_GENDER,
'Man' => Person::MALE_GENDER,
'Both' => Person::BOTH_GENDER,
'Not given' => 'null'
),
'multiple' => true,
'expanded' => true
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
if (!is_array($data['accepted_genders']) || count($data['accepted_genders']) === 0 ) {
$context->buildViolation("You should select an option")
->addViolation();
}
}
public function alterQuery(QueryBuilder $qb, $data)
{
$where = $qb->getDQLPart('where');
$isIn = $qb->expr()->in('person.gender', ':person_gender');
if (!\in_array('null', $data['accepted_genders'])) {
$clause = $isIn;
} else {
$clause = $qb->expr()->orX($isIn, $qb->expr()->isNull('person.gender'));
}
if ($where instanceof Expr\Andx) {
$where->add($clause);
} else {
$where = $qb->expr()->andX($clause);
}
$qb->add('where', $where);
$qb->setParameter('person_gender', \array_filter(
$data['accepted_genders'],
function($el) {
return $el !== 'null';
}));
}
/**
* A title which will be used in the label for the form
*
* @return string
*/
public function getTitle()
{
return 'Filter by person gender';
}
public function addRole()
{
return NULL;
}
public function describeAction($data, $format = 'string')
{
$genders = [];
foreach ($data['accepted_genders'] as $g) {
if ('null' === $g) {
$genders[] = $this->translator->trans('Not given');
} else {
$genders[] = $this->translator->trans($g);
}
}
return [
"Filtering by genders: only %genders%",
[ "%genders%" => \implode(", ", $genders)]
];
}
}

View File

@@ -0,0 +1,111 @@
<?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\PersonBundle\Export\Filter;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\QueryBuilder;
use Chill\MainBundle\Export\FilterInterface;
use Doctrine\ORM\Query\Expr;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Doctrine\ORM\EntityRepository;
use Chill\MainBundle\Entity\Country;
use Chill\MainBundle\Export\ExportElementValidatedInterface;
use Chill\MainBundle\Form\Type\Select2CountryType;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class NationalityFilter implements FilterInterface,
ExportElementValidatedInterface
{
/**
*
* @var TranslatableStringHelper
*/
private $translatableStringHelper;
public function __construct(TranslatableStringHelper $helper)
{
$this->translatableStringHelper = $helper;
}
public function applyOn()
{
return 'person';
}
public function buildForm(FormBuilderInterface $builder)
{
$builder->add('nationalities', Select2CountryType::class, array(
'placeholder' => 'Choose countries'
));
}
public function validateForm($data, ExecutionContextInterface $context)
{
if ($data['nationalities'] === null) {
$context->buildViolation("A nationality must be selected")
->addViolation();
}
}
public function alterQuery(QueryBuilder $qb, $data)
{
$where = $qb->getDQLPart('where');
$clause = $qb->expr()->in('person.nationality', ':person_nationality');
if ($where instanceof Expr\Andx) {
$where->add($clause);
} else {
$where = $qb->expr()->andX($clause);
}
$qb->add('where', $where);
$qb->setParameter('person_nationality', array($data['nationalities']));
}
public function getTitle()
{
return "Filter by person's nationality";
}
public function addRole()
{
return NULL;
}
public function describeAction($data, $format = 'string')
{
$countries = $data['nationalities'];
$names = array_map(function(Country $c) {
return $this->translatableStringHelper->localize($c->getName());
}, array($countries));
return array(
"Filtered by nationality : %nationalities%",
array('%nationalities%' => implode(", ", $names))
);
}
}