Completed
Push — master ( b9f7b1...c05cbd )
by Ariel
09:22
created

Concierge::booking()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 4
nc 2
nop 0
crap 3
1
<?php
2
3
namespace Timegridio\Concierge;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Arr;
7
use Timegridio\Concierge\Booking\BookingManager;
8
use Timegridio\Concierge\Calendar\Calendar;
9
use Timegridio\Concierge\Exceptions\DuplicatedAppointmentException;
10
use Timegridio\Concierge\Models\Appointment;
11
use Timegridio\Concierge\Models\Business;
12
use Timegridio\Concierge\Models\Service;
13
use Timegridio\Concierge\Timetable\Strategies\TimetableStrategy;
14
use Timegridio\Concierge\Vacancy\VacancyManager;
15
16
/*******************************************************************************
17
 * Concierge Service Layer
18
 *     High level booking manager
19
 ******************************************************************************/
20
class Concierge extends Workspace
21
{
22
    protected $timetable = null;
23
24
    protected $calendar = null;
25
26
    protected $booking = null;
27
28
    protected $vacancies = null;
29
30 6
    protected function calendar()
31
    {
32 6
        if ($this->calendar === null) {
33 6
            $this->calendar = new Calendar($this->business->strategy, $this->business->vacancies(), $this->business->timezone);
34 6
        }
35
36 6
        return $this->calendar;
37
    }
38
39 2
    public function timetable()
40
    {
41 2
        if ($this->timetable === null) {
42 2
            $this->timetable = new TimetableStrategy($this->business->strategy);
43 2
        }
44
45 2
        return $this->timetable;
46
    }
47
48
    public function vacancies()
49
    {
50
        if ($this->vacancies === null && $this->business !== null) {
51
            $this->vacancies = new VacancyManager($this->business);
52
        }
53
54
        return $this->vacancies;
55
    }
56
57 3
    public function booking()
58
    {
59 3
        if ($this->booking === null && $this->business !== null) {
60 3
            $this->booking = new BookingManager($this->business);
61 3
        }
62
63 3
        return $this->booking;
64
    }
65
66 6
    public function takeReservation(array $request)
67
    {
68 6
        $issuer = $request['issuer'];
69 6
        $service = $request['service'];
70 6
        $contact = $request['contact'];
71 6
        $comments = $request['comments'];
72
73 6
        $vacancies = $this->calendar()
74 6
                          ->forService($service->id)
75 6
                          ->withDuration($service->duration)
76 6
                          ->forDate($request['date'])
77 6
                          ->atTime($request['time'])
78 6
                          ->find();
79
80 6
        if ($vacancies->count() == 0) {
81
            // TODO: Log failure feedback message / raise exception
82 2
            return false;
83
        }
84
85
//      DEBUG / INCONSISTENT DB RECORDS CHECK
86
//        if ($vacancies->count() > 1) {
87
//            // Log unexpected behavior message / raise exception
88
//            $vacancy = $vacancies->first();
89
//        }
90
91 4
        if ($vacancies->count() == 1) {
92 4
            $vacancy = $vacancies->first();
93 4
        }
94
95 4
        $startAt = $this->makeDateTimeUTC($request['date'], $request['time'], $request['timezone']);
96 4
        $finishAt = $startAt->copy()->addMinutes($service->duration);
97
98 4
        $appointment = $this->generateAppointment(
99 4
            $issuer,
100 4
            $this->business->id,
101 4
            $contact->id,
102 4
            $service->id,
103 4
            $startAt,
104 4
            $finishAt,
105
            $comments
106 4
        );
107
108
        /* Should be moved inside generateAppointment() */
109 4
        if ($appointment->duplicates()) {
110 2
            throw new DuplicatedAppointmentException();
111
        }
112
113
        /* Should be moved inside generateAppointment() */
114 4
        $appointment->vacancy()->associate($vacancy);
0 ignored issues
show
Bug introduced by
The variable $vacancy does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
115 4
        $appointment->save();
116
117 4
        return $appointment;
118
    }
119
120 4
    protected function generateAppointment(
121
        $issuerId,
122
        $businessId,
123
        $contactId,
124
        $serviceId,
125
        Carbon $startAt,
126
        Carbon $finishAt,
127
        $comments = null)
128
    {
129 4
        $appointment = new Appointment();
130
131 4
        $appointment->doReserve();
132 4
        $appointment->setStartAtAttribute($startAt);
133 4
        $appointment->setFinishAtAttribute($finishAt);
134 4
        $appointment->business()->associate($businessId);
135 4
        $appointment->issuer()->associate($issuerId);
136 4
        $appointment->contact()->associate($contactId);
137 4
        $appointment->service()->associate($serviceId);
138 4
        $appointment->comments = $comments;
0 ignored issues
show
Documentation introduced by
The property comments does not exist on object<Timegridio\Concierge\Models\Appointment>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
139 4
        $appointment->doHash();
140
141 4
        return $appointment;
142
    }
143
144
    /**
145
     * Determine if the Business has any published Vacancies available for booking.
146
     *
147
     * @return bool
148
     */
149 2
    public function isBookable($fromDate = 'today', $days = 7)
150
    {
151 2
        $timetable = $this->timetable()->buildTimetable($this->business->vacancies, $fromDate, $days);
152
153 2
        $timetable = Arr::flatten($timetable);
154
155 2
        $sum = array_sum($timetable);
156
157 2
        return $sum > 0;
158
    }
159
160
    //////////////////
161
    // FOR REFACTOR //
162
    //////////////////
163
164
    public function getActiveAppointments()
165
    {
166
        return $this->business
167
            ->bookings()->with('contact')
168
            ->with('business')
169
            ->with('service')
170
            ->active()
171
            ->orderBy('start_at')
172
            ->get();
173
    }
174
175
    public function getUnservedAppointments()
176
    {
177
        return $this->business
178
            ->bookings()->with('contact')
179
            ->with('business')
180
            ->with('service')
181
            ->unserved()
182
            ->orderBy('start_at')
183
            ->get();
184
    }
185
186 4
    protected function makeDateTime($date, $time, $timezone = null)
187
    {
188 4
        return Carbon::parse("{$date} {$time} {$timezone}");
189
    }
190
191 4
    protected function makeDateTimeUTC($date, $time, $timezone = null)
192
    {
193 4
        return $this->makeDateTime($date, $time, $timezone)->timezone('UTC');
194
    }
195
}
196