GetTrait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 0
loc 70
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
find() 0 1 ?
findOneBy() 0 1 ?
getClassMetadata() 0 1 ?
A assertIsEntity() 0 13 4
A get() 0 7 1
A getOneBy() 0 7 1
1
<?php
2
3
namespace steevanb\EntityUtils\Repository;
4
5
use Doctrine\ORM\EntityNotFoundException;
6
use Doctrine\ORM\Mapping\ClassMetadata;
7
8
trait GetTrait
9
{
10
    /**
11
     * @param mixed $id
12
     * @param int|null $lockMode
13
     * @param int|null $lockVersion
14
     * @return object
15
     */
16
    abstract public function find($id, $lockMode = null, $lockVersion = null);
17
18
    /**
19
     * @param array $criteria
20
     * @param array|null $orderBy
21
     * @return object
22
     */
23
    abstract public function findOneBy(array $criteria, array $orderBy = null);
24
25
    /**
26
     * @return ClassMetadata
27
     */
28
    abstract protected function getClassMetadata();
29
30
    /**
31
     * @param mixed $entity
32
     * @param array $criteria
33
     * @throws EntityNotFoundException
34
     */
35
    protected function assertIsEntity($entity, array $criteria)
36
    {
37
        if (is_object($entity) === false) {
38
            $message = 'Entity of type "' . $this->getClassMetadata()->getName() . '"';
39
            $criteriaForMessage = [];
40
            foreach ($criteria as $name => $value) {
41
                $criteriaForMessage[] = $name . ' = ' . $value;
42
            }
43
            $message .= ' was not found with ' . (count($criteriaForMessage) > 1 ? ' criteria' : 'criterion');
44
            $message .= ' : ' . implode(', ', $criteriaForMessage);
45
            throw new EntityNotFoundException($message);
46
        }
47
    }
48
49
    /**
50
     * @param mixed $id
51
     * @param int|null $lockMode
52
     * @param int|null $lockVersion
53
     * @return object
54
     * @throws EntityNotFoundException
55
     */
56
    public function get($id, $lockMode = null, $lockVersion = null)
57
    {
58
        $entity = $this->find($id, $lockMode, $lockVersion);
59
        $this->assertIsEntity($entity, array('id' => $id));
60
61
        return $entity;
62
    }
63
64
    /**
65
     * @param array $criteria
66
     * @param array|null $orderBy
67
     * @return object
68
     * @throws EntityNotFoundException
69
     */
70
    public function getOneBy(array $criteria, array $orderBy = null)
71
    {
72
        $entity = $this->findOneBy($criteria, $orderBy);
73
        $this->assertIsEntity($entity, $criteria);
74
75
        return $entity;
76
    }
77
}
78