Concierge::generateAppointment()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 13
cts 13
cp 1
rs 9.52
c 0
b 0
f 0
cc 1
nc 1
nop 8
crap 1

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
namespace Timegridio\Concierge;
4
5
use Carbon\Carbon;
6
use Timegridio\Concierge\Booking\BookingManager;
7
use Timegridio\Concierge\Calendar\Calendar;
8
use Timegridio\Concierge\Exceptions\DuplicatedAppointmentException;
9
use Timegridio\Concierge\Models\Appointment;
10
use Timegridio\Concierge\Models\Business;
11
use Timegridio\Concierge\Models\Service;
12
use Timegridio\Concierge\Timetable\Strategies\TimetableStrategy;
13
use Timegridio\Concierge\Vacancy\VacancyManager;
14
15
/*******************************************************************************
16
 * Concierge Service Layer
17
 *     High level booking manager
18
 ******************************************************************************/
19
class Concierge extends Workspace
20
{
21
    protected $timetable = null;
22
23
    protected $calendar = null;
24
25
    protected $booking = null;
26
27
    protected $vacancies = null;
28
29
    protected $appointment = null;
30
31 6
    protected function calendar()
32
    {
33 6
        if ($this->calendar === null) {
34 6
            $this->calendar = new Calendar($this->business->strategy, $this->business->vacancies(), $this->business->timezone);
35
        }
36
37 6
        return $this->calendar;
38
    }
39
40
    public function timetable()
41
    {
42
        if ($this->timetable === null) {
43
            $this->timetable = new TimetableStrategy($this->business->strategy);
44
        }
45
46
        return $this->timetable;
47
    }
48
49 1
    public function vacancies()
50
    {
51 1
        if ($this->vacancies === null && $this->business !== null) {
52 1
            $this->vacancies = new VacancyManager($this->business);
53
        }
54
55 1
        return $this->vacancies;
56
    }
57
58 3
    public function booking()
59
    {
60 3
        if ($this->booking === null && $this->business !== null) {
61 3
            $this->booking = new BookingManager($this->business);
62
        }
63
64 3
        return $this->booking;
65
    }
66
67 6
    public function takeReservation(array $request)
68
    {
69 6
        $issuer = $request['issuer'];
70 6
        $service = $request['service'];
71 6
        $contact = $request['contact'];
72 6
        $comments = $request['comments'];
73
74 6
        $vacancies = $this->calendar()
75 6
                          ->forService($service->id)
76 6
                          ->withDuration($service->duration)
77 6
                          ->forDate($request['date'])
78 6
                          ->atTime($request['time'], $request['timezone'])
79 6
                          ->find();
80
81 6
        if ($vacancies->count() == 0) {
82
            // TODO: Log failure feedback message / raise exception
83 2
            logger()->debug('NO VACANCIES FOUND!');
84 2
            return false;
85
        }
86
87 4
        if ($vacancies->count() > 1) {
88
            // Log unexpected behavior message / raise exception
89
            $vacancy = $vacancies->first();
90
        }
91
92 4
        if ($vacancies->count() == 1) {
93 4
            $vacancy = $vacancies->first();
94
        }
95
96 4
        $humanresourceId = $vacancy->humanresource ? $vacancy->humanresource->id : null;
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...
97
98 4
        $startAt = $this->makeDateTimeUTC($request['date'], $request['time'], $request['timezone']);
99 4
        $finishAt = $startAt->copy()->addMinutes($service->duration);
100
101 4
        $appointment = $this->generateAppointment(
102 4
            $issuer,
103 4
            $this->business->id,
104 4
            $contact->id,
105 4
            $service->id,
106 4
            $startAt,
107 4
            $finishAt,
108 4
            $comments,
109 4
            $humanresourceId
110
        );
111
112
        /* Should be moved inside generateAppointment() */
113 4
        if ($appointment->duplicates()) {
114 2
            $this->appointment = $appointment;
115
116 2
            throw new DuplicatedAppointmentException($appointment->code);
117
        }
118
119 4
        $appointment->vacancy()->associate($vacancy);
120 4
        $appointment->save();
121
122 4
        return $appointment;
123
    }
124
125 4
    protected function generateAppointment(
126
        $issuerId,
127
        $businessId,
128
        $contactId,
129
        $serviceId,
130
        Carbon $startAt,
131
        Carbon $finishAt,
132
        $comments = null,
133
        $humanresourceId = null)
134
    {
135 4
        $appointment = new Appointment();
136
137 4
        $appointment->doReserve();
138 4
        $appointment->setStartAtAttribute($startAt);
139 4
        $appointment->setFinishAtAttribute($finishAt);
140 4
        $appointment->business()->associate($businessId);
141 4
        $appointment->issuer()->associate($issuerId);
142 4
        $appointment->contact()->associate($contactId);
143 4
        $appointment->service()->associate($serviceId);
144 4
        $appointment->humanresource()->associate($humanresourceId);
145 4
        $appointment->comments = $comments;
146 4
        $appointment->doHash();
147
148 4
        return $appointment;
149
    }
150
151
    /**
152
     * Determine if the Business has any published Vacancies available for booking.
153
     *
154
     * @param string $fromDate
155
     * @param int $days
156
     *
157
     * @return bool
158
     */
159 2
    public function isBookable($fromDate = 'now', $days = 7)
160
    {
161 2
        $fromDate = Carbon::parse($fromDate)->timezone($this->business->timezone);
162
163 2
        $count = $this->business
164 2
                      ->vacancies()
165 2
                      ->future($fromDate)
166 2
                      ->until($fromDate->addDays($days))
167 2
                      ->count();
168
169 2
        return $count > 0;
170
    }
171
172
    //////////////////
173
    // FOR REFACTOR //
174
    //////////////////
175
176 2
    public function getActiveAppointments()
177
    {
178 2
        return $this->business
179 2
            ->bookings()->with('contact')
180 2
            ->with('business')
181 2
            ->with('service')
182 2
            ->active()
183 2
            ->orderBy('start_at')
184 2
            ->get();
185
    }
186
187
    public function getUnservedAppointments()
188
    {
189
        return $this->business
190
            ->bookings()->with('contact')
191
            ->with('business')
192
            ->with('service')
193
            ->unserved()
194
            ->orderBy('start_at')
195
            ->get();
196
    }
197
198 1
    public function getUnarchivedAppointments()
199
    {
200 1
        return $this->business
201 1
            ->bookings()->with('contact')
202 1
            ->with('business')
203 1
            ->with('service')
204 1
            ->unarchived()
205 1
            ->orderBy('start_at')
206 1
            ->get();
207
    }
208
209 4
    protected function makeDateTime($date, $time, $timezone = null)
210
    {
211 4
        return Carbon::parse("{$date} {$time} {$timezone}");
212
    }
213
214 4
    protected function makeDateTimeUTC($date, $time, $timezone = null)
215
    {
216 4
        return $this->makeDateTime($date, $time, $timezone)->timezone('UTC');
217
    }
218
219
    public function appointment()
220
    {
221
        return $this->appointment;
222
    }
223
}
224