Completed
Push — master ( d23403...374141 )
by Rai
03:12
created

BaseRepository::preFlush()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 4
Ratio 100 %

Importance

Changes 0
Metric Value
dl 4
loc 4
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
rs 10
1
<?php
2
3
namespace Bludata\Doctrine\ORM\Repositories;
4
5
use Bludata\Doctrine\Common\Interfaces\BaseEntityInterface;
6
use Bludata\Doctrine\Common\Interfaces\BaseRepositoryInterface;
7
use Doctrine\ORM\EntityRepository;
8
use Symfony\Component\Validator\ValidatorBuilder;
9
10 View Code Duplication
abstract class BaseRepository extends EntityRepository implements BaseRepositoryInterface
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 80 characters; contains 89 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
11
{
12
    /**
13
     * Método executado nos eventos ORM\PrePersist e ORM\PreUpdate.
14
     */
15
    public function preSave(BaseEntityInterface $entity)
16
    {
17
        return $this;
18
    }
19
20
    /**
21
     * Método executado nos eventos ORM\PostPersist e ORM\PostUpdate.
22
     */
23
    public function postSave(BaseEntityInterface $entity)
24
    {
25
        return $this;
26
    }
27
28
    /**
29
     * Método executado no evento ORM\PreFlush.
30
     */
31
    public function preFlush(BaseEntityInterface $entity)
32
    {
33
        return $this;
34
    }
35
36
    public function validate(BaseEntityInterface $entity)
37
    {
38
        $validator = (new ValidatorBuilder())
39
                    ->enableAnnotationMapping()
40
                    ->getValidator();
41
42
        $violations = $validator->validate($entity);
43
44
        $errors = [];
45
46
        if (count($violations)) {
47
            foreach ($violations as $violation) {
48
                $errors[] = $violation->getMessage();
49
            }
50
51
            abort(400, json_encode($errors));
52
        }
53
    }
54
55
    public function getClassMetadata()
56
    {
57
        return parent::getClassMetadata();
58
    }
59
60
    public function getEntityName()
61
    {
62
        return parent::getEntityName();
63
    }
64
65
    public function createEntity()
66
    {
67
        return app($this->getEntityName());
68
    }
69
70
    public function createQueryWorker()
71
    {
72
        return new QueryWorker($this);
73
    }
74
75
    public function query()
76
    {
77
        return $this->createQueryBuilder('t');
78
    }
79
80
    /**
81
     * @return QueryWorker
82
     */
83
    public function findAll()
84
    {
85
        return $this->createQueryWorker();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->createQueryWorker(); (Bludata\Doctrine\ORM\Repositories\QueryWorker) is incompatible with the return type declared by the interface Doctrine\Common\Persiste...jectRepository::findAll of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
86
    }
87
88
    public function findOneBy(array $filters, $abort = true)
89
    {
90
        $entity = parent::findOneBy($filters);
91
92
        if (!$entity && $abort) {
93
            abort(404, $this->getMessageNotFound());
94
        }
95
96
        return $entity;
97
    }
98
99
    public function find($id, $abort = true)
100
    {
101
        return is_object($id) ? $id : $this->findOneBy(['id' => $id], $abort);
102
    }
103
104
    /**
105
     * Inserir ou atualizar um registro.
106
     *
107
     * @param null | string | int | array
108
     *
109
     * @throws InvalidArgumentException Se $input não for null | string | int | array é lançada a exceção
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 80 characters; contains 105 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
110
     */
111
    public function findOrCreate($input)
112
    {
113
        if (is_null($input)) {
114
            return $input;
115
        }
116
117
        if (is_string($input)) {
118
            $input = json_decode($input, true);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $input. This often makes code more readable.
Loading history...
119
        }
120
121
        if (is_numeric($input)) {
122
            return $this->find($input);
123
        }
124
125
        if (is_array($input)) {
126
            if (array_key_exists('id', $input) && $input['id']) {
127
                $object = $this->find($input['id']);
128
            } else {
129
                $object = $this->createEntity();
130
            }
131
132
            $object->setPropertiesEntity($input);
133
134
            return $object;
135
        }
136
137
        throw new InvalidArgumentException('O parâmetro $input pode ser um null | string | int | array');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 80 characters; contains 105 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
138
    }
139
140
    /**
141
     * Marcar um registro como deletado.
142
     *
143
     * @param object | int $target
144
     *
145
     * @throws Symfony\Component\HttpKernel\Exception\NotFoundHttpException Se $target não for encontrado
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 80 characters; contains 105 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
146
     *
147
     * Bludata\Doctrine\Common\Interfaces
148
     */
149
    public function remove($target)
150
    {
151
        $entity = $this->find($target);
152
153
        $this->em()->remove($entity);
0 ignored issues
show
Bug introduced by
It seems like $entity defined by $this->find($target) on line 151 can also be of type null; however, Doctrine\ORM\EntityManager::remove() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
154
155
        return $entity;
156
    }
157
158
    /**
159
     * @param Bludata\Doctrine\Common\Interfaces\BaseEntityInterface $entity
0 ignored issues
show
Documentation introduced by
Should the type for parameter $entity not be BaseEntityInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
160
     *
161
     * @return Bludata\Doctrine\ORM\Repositories\QueryWorker
0 ignored issues
show
Documentation introduced by
Should the return type not be BaseRepository?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
162
     */
163
    public function save(BaseEntityInterface $entity)
164
    {
165
        $this->em()->persist($entity);
166
167
        return $this;
168
    }
169
170
    /**
171
     * @param Bludata\Doctrine\Common\Interfaces\BaseEntityInterface $entity
0 ignored issues
show
Documentation introduced by
Should the type for parameter $entity not be null|BaseEntityInterface?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
172
     *
173
     * @return Bludata\Doctrine\ORM\Repositories\QueryWorker
0 ignored issues
show
Documentation introduced by
Should the return type not be BaseRepository?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
174
     */
175
    public function flush(BaseEntityInterface $entity = null)
176
    {
177
        $this->em()->flush($entity);
178
179
        return $this;
180
    }
181
182
    public function em()
0 ignored issues
show
Coding Style introduced by
This method's name is shorter than the configured minimum length of 3 characters.

Even though PHP does not care about the name of your methods, it is generally a good practice to choose method names which can be easily understood by other human readers.

Loading history...
183
    {
184
        return parent::getEntityManager();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getEntityManager() instead of em()). Are you sure this is correct? If so, you might want to change this to $this->getEntityManager().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
185
    }
186
}
187