Completed
Branch master (acab90)
by Nil
03:50
created

EloquentWriteRepository::count()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 11
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 11
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace NilPortugues\Foundation\Infrastructure\Model\Repository\Eloquent;
4
5
use Illuminate\Database\Eloquent\Model;
6
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Filter;
7
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Identity;
8
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\WriteRepository;
9
use NilPortugues\Foundation\Domain\Model\Repository\Filter as DomainFilter;
10
11
class EloquentWriteRepository extends BaseEloquentRepository implements WriteRepository
12
{
13
    /**
14
     * Returns the total amount of elements in the repository given the restrictions provided by the Filter object.
15
     *
16
     * @param Filter|null $filter
17
     *
18
     * @return int
19
     */
20 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...
21
    {
22
        $model = self::$instance;
23
        $query = $model->query();
24
25
        if ($filter) {
26
            EloquentFilter::filter($query, $filter);
27
        }
28
29
        return (int) $query->getQuery()->count();
30
    }
31
32
    /**
33
     * Returns whether an entity with the given id exists.
34
     *
35
     * @param $id
36
     *
37
     * @return bool
38
     */
39
    public function exists(Identity $id)
40
    {
41
        $model = self::$instance;
42
43
        $filter = new DomainFilter();
44
        $filter->must()->equal($model->getKeyName(), $id->id());
45
46
        return $this->count($filter) > 0;
47
    }
48
49
    /**
50
     * Adds a new entity to the storage.
51
     *
52
     * @param Identity|Model $value
53
     *
54
     * @return mixed
55
     */
56
    public function add(Identity $value)
57
    {
58
        $this->guard($value);
59
        $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...
60
61
        return $value;
62
    }
63
64
    /**
65
     * Adds a collections of entities to the storage.
66
     *
67
     * @param array $values
68
     *
69
     * @return mixed
70
     */
71
    public function addAll(array $values)
72
    {
73
        foreach ($values as $value) {
74
            $this->guard($value);
75
            $value->save();
76
        }
77
78
        return $values;
79
    }
80
81
    /**
82
     * Removes the entity with the given id.
83
     *
84
     * @param $id
85
     */
86
    public function remove(Identity $id)
87
    {
88
        $model = self::$instance;
89
90
        $model->query()->find($id->id())->delete();
0 ignored issues
show
Bug introduced by
The method delete does only exist in Illuminate\Database\Eloq...Database\Eloquent\Model, but not in Illuminate\Database\Eloquent\Collection.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
91
    }
92
93
    /**
94
     * Removes all elements in the repository given the restrictions provided by the Filter object.
95
     * If $filter is null, all the repository data will be deleted.
96
     *
97
     * @param Filter $filter
98
     *
99
     * @return bool
100
     */
101 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...
102
    {
103
        $model = self::$instance;
104
        $query = $model->query();
105
106
        if ($filter) {
107
            EloquentFilter::filter($query, $filter);
108
        }
109
110
        $query->delete();
111
    }
112
113
    /**
114
     * Repository data is added or removed as a whole block.
115
     * Must work or fail and rollback any persisted/erased data.
116
     *
117
     * @param callable $transaction
118
     *
119
     * @throws \Exception
120
     */
121
    public function transactional(callable $transaction)
122
    {
123
        $model = $model = self::$instance;
124
125
        try {
126
            $model->getConnection()->beginTransaction();
127
            $transaction();
128
            $model->getConnection()->commit();
129
        } catch (\Exception $e) {
130
            $model->getConnection()->rollback();
131
            throw $e;
132
        }
133
    }
134
}
135