EloquentWriteRepository::exists()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace NilPortugues\Foundation\Infrastructure\Model\Repository\EloquentMongoDB;
4
5
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Filter;
6
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Identity;
7
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\WriteRepository;
8
9
class EloquentWriteRepository extends BaseEloquentRepository implements WriteRepository
10
{
11
    /**
12
     * Returns the total amount of elements in the repository given the restrictions provided by the Filter object.
13
     *
14
     * @param Filter|null $filter
15
     *
16
     * @return int
17
     */
18 View Code Duplication
    public function count(Filter $filter = null)
0 ignored issues
show
Duplication introduced by
This method 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...
19
    {
20
        $model = self::$instance;
21
        $query = $model->query();
22
23
        if ($filter) {
24
            EloquentFilter::filter($query, $filter);
0 ignored issues
show
Compatibility introduced by
$query of type object<Illuminate\Database\Eloquent\Builder> is not a sub-type of object<Jenssegers\Mongodb\Eloquent\Builder>. It seems like you assume a child class of the class Illuminate\Database\Eloquent\Builder to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
25
        }
26
27
        return (int) $query->getQuery()->count();
28
    }
29
30
    /**
31
     * Returns whether an entity with the given id exists.
32
     *
33
     * @param $id
34
     *
35
     * @return bool
36
     */
37
    public function exists(Identity $id)
38
    {
39
        $model = self::$instance;
40
        $result = $model->query()->where($model->getKeyName(), '=', $id->id())->first();
41
42
        return null !== $result;
43
    }
44
45
    /**
46
     * Adds a new entity to the storage.
47
     *
48
     * @param Identity $value
49
     *
50
     * @return mixed
51
     */
52
    public function add(Identity $value)
53
    {
54
        $this->guard($value);
55
        $value->save();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface NilPortugues\Foundation\...tory\Contracts\Identity as the method save() does only exist in the following implementations of said interface: NilPortugues\Example\Persistence\Eloquent\User.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
56
57
        return $value;
58
    }
59
60
    /**
61
     * Adds a collections of entities to the storage.
62
     *
63
     * @param array $values
64
     *
65
     * @return mixed
66
     *
67
     * @throws \Exception
68
     */
69
    public function addAll(array $values)
70
    {
71
        $model = self::$instance;
72
        $ids = [];
73
        try {
74
            foreach ($values as $value) {
75
                $this->guard($value);
76
                $value->save();
77
                $ids[] = $value->getIdAttribute('_id');
78
            }
79
        } catch (\Exception $e) {
80
            $model->destroy($ids);
81
            throw $e;
82
        }
83
    }
84
85
    /**
86
     * Removes the entity with the given id.
87
     *
88
     * @param $id
89
     *
90
     * @return bool
91
     */
92
    public function remove(Identity $id)
93
    {
94
        $model = self::$instance;
95
96
        return (bool) $model->query()->find($id->id())->delete();
97
    }
98
99
    /**
100
     * Removes all elements in the repository given the restrictions provided by the Filter object.
101
     * If $filter is null, all the repository data will be deleted.
102
     *
103
     * @param Filter $filter
104
     *
105
     * @return bool
106
     */
107 View Code Duplication
    public function removeAll(Filter $filter = null)
0 ignored issues
show
Duplication introduced by
This method 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...
108
    {
109
        $model = self::$instance;
110
        $query = $model->query();
111
112
        if ($filter) {
113
            EloquentFilter::filter($query, $filter);
0 ignored issues
show
Compatibility introduced by
$query of type object<Illuminate\Database\Eloquent\Builder> is not a sub-type of object<Jenssegers\Mongodb\Eloquent\Builder>. It seems like you assume a child class of the class Illuminate\Database\Eloquent\Builder to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
114
        }
115
116
        return $query->delete();
117
    }
118
119
    /**
120
     * Repository data is added or removed as a whole block.
121
     * Must work or fail and rollback any persisted/erased data.
122
     *
123
     * @param callable $transaction
124
     *
125
     * @throws \Exception
126
     */
127
    public function transactional(callable $transaction)
128
    {
129
        try {
130
            $transaction();
131
        } catch (\Exception $e) {
132
            throw $e;
133
        }
134
    }
135
}
136