chill-bundles/Export/Aggregator/AgeAggregator.php

113 lines
3.0 KiB
PHP

<?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";
}
}