LotRepository   B
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 243
Duplicated Lines 4.53 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 37
lcom 1
cbo 3
dl 11
loc 243
rs 8.6
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A getModel() 0 4 1
A createDraft() 0 7 1
A find() 11 11 2
A statusChange() 0 3 1
A addLot() 0 7 2
A getDraftedLot() 0 11 3
A userLots() 0 20 2
A userLotsPendingComision() 0 20 4
A delete() 0 10 2
A dateToTimestamp() 0 6 1
A reformatDateString() 0 17 2
B save() 0 16 11
A changeCategory() 0 6 1
A checkIfPossibleToChangeCategory() 0 7 2
A getLatestLot() 0 8 1
A getExpireSoon() 0 10 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace App\Repositories;
4
5
use App\Lot;
6
use App\Vendor;
7
use Carbon\Carbon;
8
9
class LotRepository extends Repository
10
{
11
    /**
12
     * @return Lot
13
     */
14
    public function getModel()
15
    {
16
        return new Lot();
17
    }
18
19
    /**
20
     * Create plain lot for attached items to him.
21
     *
22
     * @param Vendor $vendor
23
     * @return mixed
24
     */
25
    public function createDraft(Vendor $vendor)
26
    {
27
        return $this->getModel()
28
            ->create([
29
                'vendor_id' => $vendor->id
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Vendor>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
30
            ]);
31
    }
32
33 View Code Duplication
    public function find($slug)
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...
34
    {
35
        if (is_numeric($slug))
36
            return $this->getModel()
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<App\Lot>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
37
                ->whereId((int) $slug)
38
                ->first();
39
40
        return $this->getModel()
0 ignored issues
show
Documentation Bug introduced by
The method whereSlug does not exist on object<App\Lot>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
41
            ->whereSlug($slug)
42
            ->first();
43
    }
44
45
    public function statusChange(){
46
47
    }
48
49
    /**
50
     * Add empty lot or modify just existed (drafted)..
51
     *
52
     * @param $vendor
53
     * @return Lot|mixed
54
     */
55
    public function addLot($vendor)
56
    {
57
        if($lot = $this->getDraftedLot($vendor))
58
            return $lot;
59
60
        return $this->createDraft($vendor);
61
    }
62
63
    /**
64
     * Get drafted lot
65
     *
66
     * @param $vendor|null
67
     * @return Lot $Lot|null
68
     */
69
    public function getDraftedLot($vendor = null)
70
    {
71
        $query = $this->getModel();
72
73
        if($vendor)
74
            $query = $query->where('vendor_id', $vendor->id);
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Lot>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
75
76
        $lot = $query->drafted()->first();
77
78
        return ($lot) ? $lot : null;
79
    }
80
81
    /**
82
     * Get user's lots.
83
     *
84
     * @param $user
85
     * @param $perPage
86
     * @return \Illuminate\Support\Collection|null
87
     */
88
    public function userLots($user, $perPage = 5)
89
    {
90
        $model = self::getModel();
91
92
        $vendors = [];
93
94
        $user->vendors()->active()->get()
95
            ->each(function($vendor) use (&$vendors){
96
                $vendors[] = $vendor->id;
97
            });
98
99
        $lots = $this->getModel()
0 ignored issues
show
Documentation Bug introduced by
The method whereIn does not exist on object<App\Lot>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
100
            ->whereIn('vendor_id', $vendors)
101
            ->where('status', '!=', $model::STATUS_DELETED)
102
            ->orderBy('expire_date', 'desc')
103
            ->orderBy('status', 'asc')
104
            ->paginate($perPage);
105
106
        return ($lots->count()) ? $lots : null;
107
    }
108
109
    public function userLotsPendingComision($user,$lotId=null)
110
    {
111
112
        $model = self::getModel();
113
114
        $vendors = [];
115
        $user->vendors()->active()->get()
116
            ->each(function($vendor) use (&$vendors){
117
                $vendors[] = $vendor->id;
118
            });
119
        $query = $this->getModel()->where('verify_status', $model::STATUS_VERIFY_PENDING);
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Lot>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
120
        if (!empty($vendors)) {
121
            $query->whereIn('vendor_id', $vendors);
122
        }
123
        if ($lotId != null) {
124
            $query->where('id','!=', $lotId);
125
        }
126
        $sum = $query->sum('comision');
127
        return  $sum ? (int)$sum : 0;
128
    }
129
130
    /**
131
     * Delete lot.
132
     *
133
     * @param $lot
134
     */
135
    public function delete($lot)
136
    {
137
        $model = self::getModel();
138
        if($lot->status !== $model::STATUS_DELETED)
139
        {
140
            $lot->status = $model::STATUS_DELETED;
141
142
            $lot->save();
143
        }
144
    }
145
146
    /**
147
     * Convert string date to \Carbon/Carbon timestamp.
148
     *
149
     * @param $date
150
     * @return static
151
     */
152
    public function dateToTimestamp($date)
153
    {
154
        $dates = $this->reformatDateString($date);
155
156
        return Carbon::createFromDate($dates['y'], $dates['m'], $dates['d']);
157
    }
158
159
    /**
160
     * Reformat date.
161
     *
162
     * @param $date
163
     * @param string $delimiter
164
     * @return mixed
165
     */
166
    public function reformatDateString($date, $delimiter = '.')
167
    {
168
        $datas = explode($delimiter, $date);
169
170
        if(count($datas) == 3) {
171
            $new_date['d'] = $datas[0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$new_date was never initialized. Although not strictly required by PHP, it is generally a good practice to add $new_date = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
172
            $new_date['m'] = $datas[1];
173
            $new_date['y'] = $datas[2];
174
        } else {
175
            $now = Carbon::now();
176
            $new_date['d'] = $now->day;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$new_date was never initialized. Although not strictly required by PHP, it is generally a good practice to add $new_date = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
177
            $new_date['m'] = $now->month;
178
            $new_date['y'] = $now->year;
179
        }
180
181
        return $new_date;
182
    }
183
184
    public function save($lot, array $data)
185
    {
186
        $lot->fill([
187
            'name'                 => isset($data['name']) ? $data['name'] : $lot->present()->renderDraftedName(),
188
            'category_id'          => isset($data['category']) ? $data['category'] : null,
189
            'currency_id'          => isset($data['currency']) ? (int)$data['currency'] : null,
190
            'description'          => isset($data['description']) ? $data['description'] : null,
191
            'yield_amount'         => isset($data['yield_amount']) ? $data['yield_amount'] : null,
192
            'public_date'          => isset($data['public_date']) ? $this->dateToTimestamp($data['public_date']) : Carbon::now()->addDays(1),
193
            'expire_date'          => isset($data['expirate_date']) ? $this->dateToTimestamp($data['expirate_date']) :Carbon::now()->addDays(5),
194
            'comision'             => isset($data['comision']) ? $data['comision'] : 0,
195
            'description_delivery' => isset($data['description_delivery']) ? $data['description_delivery'] : null,
196
            'description_payment'  => isset($data['description_payment']) ? $data['description_payment'] : null,
197
        ])->save();
198
        return $lot;
199
    }
200
201
202
    /**
203
     * Change category.
204
     *
205
     * @param $lot
206
     * @param $category_id
207
     *
208
     * @return void
209
     */
210
    public function changeCategory($lot, $category_id)
211
    {
212
        $lot->fill([
213
            'category_id' => $category_id
214
        ])->save();
215
    }
216
217
    /**
218
     * Check if user can to change category.
219
     *
220
     * @param Lot $lot
221
     * @return bool
222
     */
223
    public function checkIfPossibleToChangeCategory(Lot $lot)
224
    {
225
        if(! count($lot->products))
0 ignored issues
show
Documentation introduced by
The property products does not exist on object<App\Lot>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
226
            return true;
227
228
        return false;
229
    }
230
231
    public function getLatestLot($limit = 10)
232
    {
233
        return self::getModel()
0 ignored issues
show
Documentation Bug introduced by
The method orderBy does not exist on object<App\Lot>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
234
            ->orderBy('id','DESC')
235
            ->active()
236
            ->limit($limit)
237
            ->get();
238
    }
239
240
    public function getExpireSoon($paginate = 10)
241
    {
242
        $query = $this->getModel()
0 ignored issues
show
Documentation Bug introduced by
The method select does not exist on object<App\Lot>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
243
            ->select('lots.*')
244
            ->where('lots.active', 1)
245
            ->where('lots.expire_date', '>', Carbon::now())
246
            ->orderBy('lots.expire_date', self::ASC);
247
248
        return $query->paginate($paginate);
249
    }
250
251
}