AbstractSortingHandler   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 46
rs 10
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A validateFieldNames() 0 5 2
A getRelationClass() 0 5 1
A validateRelationNames() 0 5 2
A addRelationJoin() 0 5 1
A createOrderBySyntax() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Bugloos\QuerySortingBundle\SortingHandler\Contract;
6
7
use Doctrine\ORM\EntityManagerInterface;
8
use Doctrine\ORM\Mapping\ClassMetadata;
9
10
/**
11
 * @author Milad Ghofrani <[email protected]>
12
 */
13
abstract class AbstractSortingHandler
14
{
15
    protected EntityManagerInterface $entityManager;
16
17
    public function __construct(EntityManagerInterface $entityManager)
18
    {
19
        $this->entityManager = $entityManager;
20
    }
21
22
    abstract public function getSortProperty($rootAlias, $rootClass, $relationsAndFieldName): string;
23
24
    protected function validateFieldNames($field, $class): void
25
    {
26
        if (!\in_array($field, $class->getFieldNames(), true)) {
27
            throw new \InvalidArgumentException(
28
                'You have selected the wrong field for sorting'
29
            );
30
        }
31
    }
32
33
    protected function validateRelationNames($relationProperty, $class): void
34
    {
35
        if (!\in_array($relationProperty, $class->getAssociationNames(), true)) {
36
            throw new \InvalidArgumentException(
37
                'You have selected the wrong relation for sorting'
38
            );
39
        }
40
    }
41
42
    protected function getRelationClass($class, $alias): ClassMetadata
43
    {
44
        $relationEntity = $class->getAssociationMapping($alias)['targetEntity'];
45
46
        return $this->entityManager->getClassMetadata($relationEntity);
47
    }
48
49
    protected function addRelationJoin($relationJoins, $alias, $property)
50
    {
51
        $relationJoins[sprintf('%s.%s', $alias, $property)] = $property;
52
53
        return $relationJoins;
54
    }
55
56
    protected function createOrderBySyntax($alias, $column): string
57
    {
58
        return sprintf('%s.%s', $alias, $column);
59
    }
60
}
61