Completed
Pull Request — v2 (#6)
by Guillaume
04:40 queued 02:38
created

filterDataByValidationGroups()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
c 0
b 0
f 0
rs 9.7333
cc 4
nc 3
nop 3
1
<?php
2
3
namespace ETNA\Doctrine\Entity;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Symfony\Component\Validator\Validator\ValidatorInterface;
7
8
abstract class AbstractEntityService
9
{
10
    /** @var EntityManagerInterface L'entity manager */
11
    protected $em;
12
13
    /** @var ValidatorInterface Le service pour la validation des data */
14
    protected $validator;
15
16
    protected function __construct(EntityManagerInterface $em, ValidatorInterface $validator)
17
    {
18
        $this->em        = $em;
19
        $this->validator = $validator;
20
    }
21
22
    /**
23
     * Filtre les champs de $datas qui correspondent à ceux de $entity en se basant sur les groupes de validations.
24
     * Permet de scénariser les modifications d'entités grace aux groupes de validation.
25
     *
26
     * @see https://symfony.com/doc/current/validation/groups.html
27
     *
28
     * @param array          $datas
29
     * @param array          $validation_groups
30
     * @param AbstractEntity $entity
31
     *
32
     * @return array
33
     */
34
    protected function filterDataByValidationGroups(array $datas, array $validation_groups, AbstractEntity $entity)
35
    {
36
        $entity_members_metadatas = $this->validator->getMetadataFor($entity)->members;
37
        $filtered_datas           = [];
38
39
        foreach ($entity_members_metadatas as $field_name => $all_field_metadatas) {
40
            $constraints             = array_shift($all_field_metadatas);
41
            $field_validation_groups = array_keys($constraints->constraintsByGroup);
42
            $is_field_concerned      = !empty(array_intersect($validation_groups, $field_validation_groups));
43
44
            if ($is_field_concerned && isset($datas[$field_name])) {
45
                $filtered_datas[$field_name] = $datas[$field_name];
46
            }
47
        }
48
        return $filtered_datas;
49
    }
50
}
51