Test Failed
Pull Request — master (#3)
by
unknown
17:36
created

VacancyManager::generateAvailability()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 15

Duplication

Lines 3
Ratio 20 %

Code Coverage

Tests 6
CRAP Score 4.25

Importance

Changes 0
Metric Value
dl 3
loc 15
ccs 6
cts 8
cp 0.75
rs 9.7666
c 0
b 0
f 0
cc 4
nc 6
nop 2
crap 4.25
1
<?php
2
3
namespace Timegridio\Concierge\Vacancy;
4
5
use Carbon\Carbon;
6
use Timegridio\Concierge\Models\Business;
7
use Timegridio\Concierge\Models\Vacancy;
8
9
class VacancyManager
10
{
11
    protected $business;
12
13
    protected $builder;
14
15 9
    public function __construct(Business $business)
16
    {
17 9
        $this->business = $business;
18 9
    }
19
20 1
    public function builder()
21
    {
22 1
        if ($this->builder === null) {
23 1
            $this->builder = new VacancyTemplateBuilder();
24
        }
25
26 1
        return $this->builder;
27
    }
28
29
    /**
30
     * Update vacancies from batch statements.
31
     *
32
     * @param Business $business
33
     * @param array    $parsedStatements
34
     *
35
     * @return bool
36
     */
37 4
    public function updateBatch(Business $business, $parsedStatements)
38
    {
39 4
        $changed = false;
40 4
        $dates = $this->arrayGroupBy('date', $parsedStatements);
41
42 4
        foreach ($dates as $date => $statements) {
43 4
            $services = $this->arrayGroupBy('service', $statements);
44
45 4
            $changed |= $this->processServiceStatements($business, $date, $services);
46
        }
47
48 4
        return $changed;
49
    }
50
51 1
    public function unpublish()
52
    {
53 1
        return $this->business->vacancies()->delete();
54
    }
55
56 4
    protected function processServiceStatements($business, $date, $services)
57
    {
58 4
        $changed = false;
59 4
        foreach ($services as $serviceSlug => $statements) {
60 4
            $service = $business->services()->where('slug', $serviceSlug)->get()->first();
61
62 4
            if ($service === null) {
63
64
                //  Invalid services are skipped to avoid user frustration.
65
                //  TODO: Still, a user-level WARNING should be raised with no fatal error
66
67 2
                continue;
68
            }
69
70 2
            $vacancy = $business->vacancies()->forDate(Carbon::parse($date))->forService($service->id);
71
72 2
            if ($vacancy) {
73 2
                $vacancy->delete();
74
            }
75
76 2
            $changed |= $this->processStatements($business, $date, $service, $statements);
77
        }
78
79 4
        return $changed;
80
    }
81
82 2
    protected function processStatements($business, $date, $service, $statements)
83
    {
84 2
        $changed = false;
85 2
        foreach ($statements as $statement) {
86 2
            $changed |= $this->publishVacancy($business, $date, $service, $statement);
87
        }
88
89 2
        return $changed;
90
    }
91
92 2
    protected function publishVacancy($business, $date, $service, $statement)
0 ignored issues
show
Unused Code introduced by
The parameter $date is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
93
    {
94 2
        $date = $statement['date'];
95 2
        $startAt = $statement['startAt'];
96 2
        $finishAt = $statement['finishAt'];
97
98 2
        $startAt = Carbon::parse("{$date} {$startAt} {$business->timezone}")->timezone('UTC');
99 2
        $finishAt = Carbon::parse("{$date} {$finishAt} {$business->timezone}")->timezone('UTC');
100
101
        $vacancyValues = [
102 2
            'business_id' => $business->id,
103 2
            'service_id'  => $service->id,
104 2
            'date'        => $statement['date'],
105 2
            'start_at'    => $startAt,
106 2
            'finish_at'   => $finishAt,
107
            ];
108
109
        // If capacity is a slug, grab the humanresource
110 2
        if(!is_numeric($statement['capacity']))
111
        {
112 1
            $vacancyValues['humanresource_id'] = $business->humanresources()
113 1
                                                          ->where('slug', $statement['capacity'])
114 1
                                                          ->first()
115 1
                                                          ->id;
116
        }
117
        else
118
        {
119 1
            $vacancyValues['capacity'] = intval($statement['capacity']);
120
        }
121
122 2
        $vacancy = Vacancy::create($vacancyValues);
123
124 2
        return $vacancy !== null;
125
    }
126
127 4
    protected function arrayGroupBy($key, $array)
128
    {
129 4
        $grouped = [];
130 4
        foreach ($array as $hash => $item) {
131 4
            if (!array_key_exists($item[$key], $grouped)) {
132 4
                $grouped[$item[$key]] = [];
133
            }
134 4
            $grouped[$item[$key]][] = $item;
135
        }
136
137 4
        return $grouped;
138
    }
139
140 1
    public function publish($date, Carbon $startAt, Carbon $finishAt, $serviceId, $capacity = 1)
141
    {
142
        $vacancyKeys = [
143 1
            'business_id' => $this->business->id,
144 1
            'service_id'  => $serviceId,
145 1
            'date'        => $date,
146
            ];
147
        $vacancyValues = [
148 1
            'capacity'    => intval($capacity),
149 1
            'start_at'    => $startAt->timezone('UTC')->toDateTimeString(),
150 1
            'finish_at'   => $finishAt->timezone('UTC')->toDateTimeString(),
151
            ];
152
153 1
        return Vacancy::updateOrCreate($vacancyKeys, $vacancyValues);
0 ignored issues
show
Bug introduced by
The method updateOrCreate() does not exist on Timegridio\Concierge\Models\Vacancy. Did you maybe mean create()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
154
    }
155
156
    /**
157
     * [generateAvailability description].
158
     *
159
     * @param Illuminate\Database\Eloquent\Collection $vacancies
0 ignored issues
show
Bug introduced by
There is no parameter named $vacancies. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
160
     * @param string                                  $startDate
161
     * @param int                                     $futureDays
162
     *
163
     * @return array
164
     */
165 1
    public function generateAvailability($startDate = 'today', $futureDays = 10)
166
    {
167 1
        $dates = [];
168 1 View Code Duplication
        for ($i = 0; $i < $futureDays; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
169 1
            $dates[date('Y-m-d', strtotime("$startDate +$i days"))] = [];
170
        }
171
172 1
        foreach ($this->business->vacancies as $vacancy) {
173
            if (array_key_exists($vacancy->date, $dates)) {
174
                $dates[$vacancy->date][$vacancy->service->slug] = $vacancy;
175
            }
176
        }
177
178 1
        return $dates;
179
    }
180
}
181