BookingsPull   D
last analyzed

Complexity

Total Complexity 59

Size/Duplication

Total Lines 99
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 76
dl 0
loc 99
ccs 0
cts 76
cp 0
rs 4.08
c 0
b 0
f 0
wmc 59

3 Methods

Rating   Name   Duplication   Size   Complexity  
D createOrUpdateBooking() 0 65 54
A __construct() 0 4 1
A handle() 0 17 4

How to fix   Complexity   

Complex Class

Complex classes like BookingsPull often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BookingsPull, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace IproSync\Jobs\Bookings;
4
5
use Carbon\Carbon;
6
use Illuminate\Bus\Queueable;
7
use Illuminate\Contracts\Queue\ShouldQueue;
8
use Illuminate\Foundation\Bus\Dispatchable;
9
use Illuminate\Queue\InteractsWithQueue;
10
use Illuminate\Queue\SerializesModels;
11
use Illuminate\Support\Str;
12
use IproSync\Ipro\DateTime;
13
use IproSync\Ipro\PullPagination;
0 ignored issues
show
Bug introduced by
The type IproSync\Ipro\PullPagination was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use IproSync\Models\Booking;
15
use LaravelIproSoftwareApi\IproSoftwareFacade;
16
17
class BookingsPull implements ShouldQueue
18
{
19
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
0 ignored issues
show
introduced by
The trait Illuminate\Queue\SerializesModels requires some properties which are not provided by IproSync\Jobs\Bookings\BookingsPull: $collectionClass, $id, $relations, $class, $keyBy
Loading history...
20
21
    protected PullPagination $pagination;
22
    protected array $requestParams;
23
24
    public function __construct(?PullPagination $pagination = null, array $requestParams = [])
25
    {
26
        $this->pagination    = $pagination ?? PullPagination::allPages();
27
        $this->requestParams = $requestParams;
28
    }
29
30
31
    public function handle()
32
    {
33
        $response = IproSoftwareFacade::searchBookings([
34
            'query' => $this->pagination->amendQuery($this->requestParams),
35
        ])->onlySuccessful();
36
37
        $items = $response->json('Items');
38
        $total = $response->json('TotalHits');
39
        foreach ($items as $item) {
40
            if (!empty($item['BookingId'])) {
41
                static::createOrUpdateBooking($item);
42
            }
43
        }
44
45
        if ($nextPagination = $this->pagination->nextPagination($total)) {
46
            static::dispatch($nextPagination, $this->requestParams)
47
                ->onQueue($this->queue);
48
        }
49
    }
50
51
    public static function createOrUpdateBooking(array $item): ?Booking
52
    {
53
        if (isset($item['BookingId'])) {
54
            $contact = Booking::firstOrNew(['id' => $item['BookingId']], )
55
                              ->fill([
56
                                    'external_reservation_id' => !empty($item['ExternalReservationID']) ? (string) $item['ExternalReservationID'] : null,
57
                                    'property_id'             => !empty($item['PropertyId']) ? (int) $item['PropertyId'] : null,
58
                                    'contact_id'              => !empty($item['ContactID']) ? (int) $item['ContactID'] : null,
59
                                    'rep_contact_id'          => !empty($item['RepContactId']) ? (int) $item['RepContactId'] : null,
60
                                    'booking_status_id'       => !empty($item['BookingStatusId']) ? (int) $item['BookingStatusId'] : null,
61
                                    'brand_id'                => !empty($item['BrandId']) ? abs((int) $item['BrandId']) : null,
62
                                    'transaction_id'          => !empty($item['TransactionID']) ? (string) $item['TransactionID'] : null,
63
                                    'order_time'              => !empty($item['OrderTime']) ? DateTime::createFromMultipleFormats(['Y-m-d', 'Y-m-d\TH:i:s'], Str::before((string) $item['OrderTime'], '.'))->format('Y-m-d') : null,
64
                                    'modified_time'           => !empty($item['ModifiedTime']) ? DateTime::createFromMultipleFormats(['Y-m-d', 'Y-m-d\TH:i:s'], Str::before((string) $item['ModifiedTime'], '.'))->format('Y-m-d H:i:s') : null,
65
                                    'check_in'                => !empty($item['CheckIn']) ? Carbon::createFromFormat('Y-m-d', (string) $item['CheckIn'])->format('Y-m-d') : null,
66
                                    'check_out'               => !empty($item['CheckOut']) ? Carbon::createFromFormat('Y-m-d', (string) $item['CheckOut'])->format('Y-m-d') : null,
67
                                    'country'                 => !empty($item['Country']) ? (string) $item['Country'] : null,
68
                                    'currency'                => !empty($item['Currency']) ? (string) $item['Currency'] : null,
69
                                    'renter_amount'           => !empty($item['RenterAmount']) ? round((float) $item['RenterAmount'], 2) : null,
70
                                    'booking_fee'             => !empty($item['BookingFee']) ? round((float) $item['BookingFee'], 2) : null,
71
                                    'booking_fee_vat'         => !empty($item['BookingFeeVAT']) ? round((float) $item['BookingFeeVAT'], 2) : null,
72
                                    'holiday_extras'          => !empty($item['HolidayExtras']) ? round((float) $item['HolidayExtras'], 2) : null,
73
                                    'insurance_total'         => !empty($item['InsuranceTotal']) ? round((float) $item['InsuranceTotal'], 2) : null,
74
                                    'agent_commission'        => !empty($item['AgentCommission']) ? round((float) $item['AgentCommission'], 2) : null,
75
                                    'discount'                => !empty($item['Discount']) ? round((float) $item['Discount'], 2) : null,
76
                                    'payment_charges'         => !empty($item['PaymentCharges']) ? round((float) $item['PaymentCharges'], 2) : null,
77
                                    'compensation'            => !empty($item['Compensation']) ? round((float) $item['Compensation'], 2) : null,
78
                                    'renter_balance'          => !empty($item['RenterBalance']) ? round((float) $item['RenterBalance'], 2) : null,
79
                                    'commission'              => !empty($item['Commission']) ? round((float) $item['Commission'], 2) : null,
80
                                    'commission_vat'          => !empty($item['CommissionVAT']) ? round((float) $item['CommissionVAT'], 2) : null,
81
                                    'security_deposit'        => !empty($item['SecurityDeposit']) ? round((float) $item['SecurityDeposit'], 2) : null,
82
                                    'renter_total'            => !empty($item['RenterTotal']) ? round((float) $item['RenterTotal'], 2) : null,
83
                                    'rate_per_day'            => !empty($item['RatePerDay']) ? round((float) $item['RatePerDay'], 2) : null,
84
                                    'property_types'          => !empty($item['PropertyTypes']) ? (array) $item['PropertyTypes'] : null,
85
                                    'status'                  => !empty($item['Status']) ? (string) $item['Status'] : null,
86
                                    'source'                  => !empty($item['Source']) ? (string) $item['Source'] : null,
87
                                    'booking_tags'            => !empty($item['BookingTags']) ? (array) $item['BookingTags'] : null,
88
                                    'customer_name'           => !empty($item['CustomerName']) ? (string) $item['CustomerName'] : null,
89
                                    'adults'                  => !empty($item['Adults']) ? (int) $item['Adults'] : 0,
90
                                    'children'                => !empty($item['Children']) ? (int) $item['Children'] : 0,
91
                                    'infants'                 => !empty($item['Infants']) ? (int) $item['Infants'] : 0,
92
                                    'pets'                    => !empty($item['Pets']) ? (int) $item['Pets'] : 0,
93
                                    'guests'                  => !empty($item['Guests']) ? (array) $item['Guests'] : null,
94
                                    'holiday_extras_ordered'  => !empty($item['HolidayExtrasOrdered']) ? (array) $item['HolidayExtrasOrdered'] : null,
95
                                    'deposit'                 => !empty($item['Deposit']) ? round((float) $item['Deposit'], 2) : null,
96
                                    'deposit_due_date'        => !empty($item['DepositDueDate']) ? Carbon::createFromFormat('d/m/Y', (string) $item['DepositDueDate'])->format('Y-m-d') : null,
97
                                    'balance'                 => !empty($item['Balance']) ? round((float) $item['Balance'], 2) : null,
98
                                    'balance_due_date'        => !empty($item['BalanceDueDate']) ? Carbon::createFromFormat('d/m/Y', (string) $item['BalanceDueDate'])->format('Y-m-d') : null,
99
                                    'guest_notes'             => !empty($item['GuestNotes']) ? (string) $item['GuestNotes'] : null,
100
                                    'house_keeper_notes'      => !empty($item['HouseKeeperNotes']) ? (string) $item['HouseKeeperNotes'] : null,
101
                                    'internal_notes'          => !empty($item['InternalNotes']) ? (string) $item['InternalNotes'] : null,
102
                                    'payment_schedules'       => !empty($item['PaymentSchedules']) ? (array) $item['PaymentSchedules'] : null,
103
                                    'payments'                => !empty($item['Payments']) ? (array) $item['Payments'] : null,
104
                                    'holiday_notes'           => !empty($item['HolidayNotes']) ? (string) $item['HolidayNotes'] : null,
105
                                    'arrival_notes'           => !empty($item['ArrivalNotes']) ? (string) $item['ArrivalNotes'] : null,
106
                                    'departure_notes'         => !empty($item['DepartureNotes']) ? (string) $item['DepartureNotes'] : null,
107
                                    'bills'                   => !empty($item['Bills']) ? (array) $item['Bills'] : null,
108
                              ])
109
                              ->fillPulled();
110
            $contact->save();
111
112
            return $contact;
113
        }
114
115
        return null;
116
    }
117
}
118