Completed
Push — master ( 79c13f...0bf349 )
by Ariel
03:04
created

VacancyManager::builder()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
ccs 1
cts 1
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 2
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 5
15
    public function __construct(Business $business)
16 5
    {
17 5
        $this->business = $business;
18
    }
19
20
    public function builder()
21
    {
22
        if ($this->builder === null) {
23
            $this->builder = new VacancyTemplateBuilder();
24
        }
25
26
        return $this->builder;
27 2
    }
28
29 2
    /**
30 2
     * Update vacancies from batch statements.
31
     *
32 2
     * @param Business $business
33 2
     * @param array    $parsedStatements
34
     *
35 2
     * @return bool
36 2
     */
37
    public function updateBatch(Business $business, $parsedStatements)
38 2
    {
39
        $changed = false;
40
        $dates = $this->arrayGroupBy('date', $parsedStatements);
41 2
42
        foreach ($dates as $date => $statements) {
43 2
            $services = $this->arrayGroupBy('service', $statements);
44 2
45 2
            $changed |= $this->processServiceStatements($business, $date, $services);
46
        }
47 2
48
        return $changed;
49
    }
50
51
    protected function processServiceStatements($business, $date, $services)
52 1
    {
53
        $changed = false;
54
        foreach ($services as $serviceSlug => $statements) {
55 1
            $service = $business->services()->where('slug', $serviceSlug)->get()->first();
56
57 1
            if ($service === null) {
58 1
59 1
                //  Invalid services are skipped to avoid user frustration.
60
                //  TODO: Still, a user-level WARNING should be raised with no fatal error
61 1
62 2
                continue;
63
            }
64 2
65
            $vacancy = $business->vacancies()->forDate(Carbon::parse($date))->forService($service->id);
66
67 1
            if ($vacancy) {
68
                $vacancy->delete();
69 1
            }
70 1
71 1
            $changed |= $this->processStatements($business, $date, $service, $statements);
72 1
        }
73
74 1
        return $changed;
75
    }
76
77 1
    protected function processStatements($business, $date, $service, $statements)
78
    {
79 1
        $changed = false;
80 1
        foreach ($statements as $statement) {
81 1
            $changed |= $this->publishVacancy($business, $date, $service, $statement);
82
        }
83 1
84 1
        return $changed;
85
    }
86
87 1
    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...
88 1
    {
89 1
        $date = $statement['date'];
90 1
        $startAt = $statement['startAt'];
91 1
        $finishAt = $statement['finishAt'];
92 1
93 1
        $startAt = Carbon::parse("{$date} {$startAt} {$business->timezone}")->timezone('UTC');
94
        $finishAt = Carbon::parse("{$date} {$finishAt} {$business->timezone}")->timezone('UTC');
95 1
96
        $vacancyValues = [
97 1
            'business_id' => $business->id,
98
            'service_id'  => $service->id,
99
            'date'        => $statement['date'],
100 2
            'capacity'    => intval($statement['capacity']),
101
            'start_at'    => $startAt,
102 2
            'finish_at'   => $finishAt,
103 2
            ];
104 2
105 2
        $vacancy = Vacancy::create($vacancyValues);
106 2
107 2
        return $vacancy !== null;
108 2
    }
109
110 2
    protected function arrayGroupBy($key, $array)
111
    {
112
        $grouped = [];
113 1
        foreach ($array as $hash => $item) {
114
            if (!array_key_exists($item[$key], $grouped)) {
115
                $grouped[$item[$key]] = [];
116 1
            }
117 1
            $grouped[$item[$key]][] = $item;
118 1
        }
119 1
120
        return $grouped;
121 1
    }
122 1
123 1
    public function publish($date, Carbon $startAt, Carbon $finishAt, $serviceId, $capacity = 1)
124 1
    {
125
        $vacancyKeys = [
126 1
            'business_id' => $this->business->id,
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Timegridio\Concierge\Models\Business>. 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...
127
            'service_id'  => $serviceId,
128
            'date'        => $date,
129
            ];
130
        $vacancyValues = [
131
            'capacity'    => intval($capacity),
132
            'start_at'    => $startAt->timezone('UTC')->toDateTimeString(),
133
            'finish_at'   => $finishAt->timezone('UTC')->toDateTimeString(),
134
            ];
135
136
        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...
137
    }
138 1
139
    /**
140 1
     * [generateAvailability description].
141 1
     *
142 1
     * @param Illuminate\Database\Eloquent\Collection $vacancies
143 1
     * @param string                                  $startDate
144
     * @param int                                     $futureDays
145 1
     *
146 1
     * @return array
147 1
     */
148 1
    public static function generateAvailability($vacancies, $startDate = 'today', $futureDays = 10)
149 1
    {
150
        $dates = [];
151 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...
152
            $dates[date('Y-m-d', strtotime("$startDate +$i days"))] = [];
153
        }
154
155
        foreach ($vacancies as $vacancy) {
156
            if (array_key_exists($vacancy->date, $dates)) {
157
                $dates[$vacancy->date][$vacancy->service->slug] = $vacancy;
158
            }
159
        }
160
161
        return $dates;
162
    }
163
}
164