Passed
Push — master ( a62b41...518ca5 )
by Oliver
03:36
created

HasOpeningHours::setOpeningHoursAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 13
cts 13
cp 1
rs 9.0856
c 0
b 0
f 0
cc 2
eloc 13
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Webfactor\Laravel\OpeningHours\Traits;
4
5
use Webfactor\Laravel\OpeningHours\Entities\OpeningHours;
6
use Webfactor\Laravel\OpeningHours\Entities\OpeningHoursForDay;
7
use Webfactor\Laravel\OpeningHours\Entities\TimeRange;
8
use Webfactor\Laravel\OpeningHours\Models\DayOpenTimeRange;
9
10
11
/** @property OpeningHours opening_hours */
12
trait HasOpeningHours
13
{
14
    use OpeningHoursRelations;
15
16
17 4
    public function getOpeningHoursAttribute()
18
    {
19 4
        $hours = $this->dayOpenTimeRanges
0 ignored issues
show
Bug introduced by
The property dayOpenTimeRanges does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
20
            ->groupBy('day')->map(function($day) {
21 2
                return $day->map(function (DayOpenTimeRange $range) {
22 2
                    return $range->start.'-'.$range->end;
23 2
                });
24 4
            });
25
26 4
        return OpeningHours::create($hours->toArray());
27
    }
28
29 2
    public function setOpeningHoursAttribute($data)
30
    {
31
        // clear previous open times
32 2
        $this->dayOpenTimeRanges()->delete();
33
34 2
        if ($data == null) {
35 1
            return;
36
        }
37
38
        $rangesArray = collect($data->flatMap(function (OpeningHoursForDay $openingHoursForDay, string $day) {
39 1
            return $openingHoursForDay->map(function (TimeRange $timeRange) use ($day) {
40
                return [
41 1
                    'day' => $day,
42 1
                    'start' => $timeRange->start(),
43 1
                    'end' => $timeRange->end()
44
                ];
45 1
            });
46
        }))->map(function ($range) {
47 1
            return new DayOpenTimeRange($range);
48 1
        });
49
50 1
        $this->dayOpenTimeRanges()->saveMany($rangesArray);
51
    }
52
}