Completed
Push — master ( 534a14...506297 )
by Ariel
22:51
created

Concierge::takeReservation()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 52
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 4

Importance

Changes 11
Bugs 1 Features 2
Metric Value
c 11
b 1
f 2
dl 0
loc 52
ccs 30
cts 30
cp 1
rs 8.9408
cc 4
eloc 29
nc 5
nop 1
crap 4

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Timegridio\Concierge;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Arr;
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
14
/*******************************************************************************
15
 * Concierge Service Layer
16
 *     High level booking manager
17
 ******************************************************************************/
18
class Concierge extends Workspace
19
{
20
    protected $timetable = null;
21
22
    protected $calendar = null;
23
24
    protected $booking = null;
25
26 7
    protected function calendar()
27
    {
28 7
        if ($this->calendar === null) {
29 6
            $this->calendar = new Calendar($this->business->strategy, $this->business->vacancies(), $this->business->timezone);
30 6
        }
31
32 6
        return $this->calendar;
33
    }
34
35 2
    protected function timetable()
36
    {
37 2
        if ($this->timetable === null) {
38 2
            $this->timetable = new TimetableStrategy($this->business->strategy);
39 2
        }
40
41 2
        return $this->timetable;
42
    }
43
44 6
    public function takeReservation(array $request)
45
    {
46 6
        $issuer = $request['issuer'];
47 6
        $service = $request['service'];
48 6
        $contact = $request['contact'];
49 6
        $comments = $request['comments'];
50
51 6
        $vacancies = $this->calendar()
52 6
                          ->forService($service->id)
53 6
                          ->forDate($request['date'])
54 6
                          ->atTime($request['time'])
55 6
                          ->find();
56
57 6
        if ($vacancies->count() == 0) {
58
            // TODO: Log failure feedback message / raise exception
59 2
            return false;
60
        }
61
62
//      DEBUG / INCONSISTENT DB RECORDS CHECK
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
63
//        if ($vacancies->count() > 1) {
64
//            // Log unexpected behavior message / raise exception
65
//            $vacancy = $vacancies->first();
66
//        }
67
68 4
        if ($vacancies->count() == 1) {
69 4
            $vacancy = $vacancies->first();
70 4
        }
71
72 4
        $startAt = $this->makeDateTimeUTC($request['date'], $request['time'], $request['timezone']);
73 4
        $finishAt = $startAt->copy()->addMinutes($service->duration);
74
75 4
        $appointment = $this->generateAppointment(
76 4
            $issuer,
77 4
            $this->business->id,
78 4
            $contact->id,
79 4
            $service->id,
80 4
            $startAt,
81 4
            $finishAt,
82
            $comments
83 4
        );
84
85
        /* Should be moved inside generateAppointment() */
86 4
        if ($appointment->duplicates()) {
87 2
            throw new DuplicatedAppointmentException();
88
        }
89
90
        /* Should be moved inside generateAppointment() */
91 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...
92 4
        $appointment->save();
93
94 4
        return $appointment;
95
    }
96
97 4
    protected function generateAppointment(
98
        $issuerId,
99
        $businessId,
100
        $contactId,
101
        $serviceId,
102
        Carbon $startAt,
103
        Carbon $finishAt,
104
        $comments = null)
105
    {
106 4
        $appointment = new Appointment();
107
108 4
        $appointment->doReserve();
109 4
        $appointment->setStartAtAttribute($startAt);
110 4
        $appointment->setFinishAtAttribute($finishAt);
111 4
        $appointment->business()->associate($businessId);
112 4
        $appointment->issuer()->associate($issuerId);
113 4
        $appointment->contact()->associate($contactId);
114 4
        $appointment->service()->associate($serviceId);
115 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...
116 4
        $appointment->doHash();
117
118 4
        return $appointment;
119
    }
120
121
    /**
122
     * Determine if the Business has any published Vacancies available for booking.
123
     * 
124
     * @return boolean
125
     */
126 2
    public function isBookable()
127
    {
128 2
        $timetable = $this->timetable()->buildTimetable($this->business->vacancies);
129
130 2
        $timetable = Arr::flatten($timetable);
131
132 2
        $sum = array_sum($timetable);
133
134 2
        return $sum > 0;
135
    }
136
137 4
    protected function makeDateTime($date, $time, $timezone = null)
138
    {
139 4
        return Carbon::parse("{$date} {$time} {$timezone}");
140
    }
141
142 4
    protected function makeDateTimeUTC($date, $time, $timezone = null)
143
    {
144 4
        return $this->makeDateTime($date, $time, $timezone)->timezone('UTC');
145
    }
146
}
147