Api   B
last analyzed

Complexity

Total Complexity 44

Size/Duplication

Total Lines 412
Duplicated Lines 6.07 %

Coupling/Cohesion

Components 2
Dependencies 9

Test Coverage

Coverage 85.07%

Importance

Changes 0
Metric Value
wmc 44
lcom 2
cbo 9
dl 25
loc 412
ccs 114
cts 134
cp 0.8507
rs 8.8798
c 0
b 0
f 0

31 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A reset() 0 6 1
A setSpreadsheetId() 0 6 1
A addBatchRequests() 0 9 3
A sendBatchRequests() 0 15 1
A frozenRowRequest() 0 14 1
A frozenColumnRequest() 0 14 1
A styleArea() 0 22 1
A fixedColumnWidthRequest() 0 17 1
A setSheetTitle() 12 12 1
A setTabColor() 0 12 1
A setSheetPropertiesRequest() 13 13 1
A addSheetRequest() 0 16 2
A addBlankSheet() 0 5 2
A clearSheetRequest() 0 11 1
A protectRangeRequest() 0 16 1
A writeCells() 0 14 1
A readCells() 0 8 1
A getSheetRowCount() 0 6 1
A getSheet() 0 12 3
A getSheetByTitle() 0 12 3
A getSheets() 0 11 2
A forgetSheets() 0 6 1
A freshSheets() 0 6 1
A firstSheetId() 0 4 1
A getSheetProtectedRanges() 0 17 4
A deleteColumnsFrom() 0 12 1
A deleteRowsFrom() 0 12 1
A deleteProtectedRange() 0 8 1
A deleteSheetRequest() 0 8 1
A fractalColors() 0 14 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Api 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 Api, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Nikaia\TranslationSheet\Client;
4
5
use Google_Service_Sheets;
6
use Google_Service_Sheets_BatchUpdateSpreadsheetRequest;
7
use Google_Service_Sheets_BatchUpdateValuesRequest;
8
use Google_Service_Sheets_Request;
9
use Illuminate\Support\Collection;
10
11
class Api
12
{
13
    /** @var Collection */
14
    protected $requests;
15
16
    /** @var Client */
17
    protected $client;
18
19
    /** @var string */
20
    protected $spreadsheetId;
21
22
    /** @var array */
23
    protected $cachedSheets = [];
24
25
    /**
26
     * SheetService constructor.
27 20
     *
28
     * @param Client $client
29 20
     */
30 20
    public function __construct(Client $client)
31 20
    {
32
        $this->client = $client;
33
        $this->requests = new Collection([]);
34
    }
35
36
    /**
37
     * Empty the requests collection.
38
     */
39 2
    public function reset()
40
    {
41 2
        $this->requests = new Collection([]);
42
43 2
        return $this;
44
    }
45
46 1
    /**
47
     * Set the service speadsheet ID.
48 1
     *
49 1
     * @param string $spreadsheetId
50 1
     * @return $this
51
     */
52
    public function setSpreadsheetId($spreadsheetId)
53 1
    {
54
        $this->spreadsheetId = $spreadsheetId;
55
56 1
        return $this;
57
    }
58 1
59
    public function addBatchRequests($requests)
60 1
    {
61 1
        $requests = is_array($requests) ? $requests : [$requests];
62 1
        foreach ($requests as $request) {
63 1
            $this->requests->push($request);
64
        }
65
66
        return $this;
67 1
    }
68
69 1
    public function sendBatchRequests()
70
    {
71
        $sheets = new Google_Service_Sheets($this->client);
72 1
73
        $sheets->spreadsheets->batchUpdate(
74 1
            $this->spreadsheetId,
75
            new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([
76
                'requests' => $this->requests->toArray(),
77 1
            ])
78
        );
79 1
80
        $this->requests = new Collection([]);
81
82 1
        return $this;
83
    }
84
85
    public function frozenRowRequest($sheetId, $frozonRowCount = 1)
86
    {
87 1
        return new Google_Service_Sheets_Request([
88
            'updateSheetProperties' => [
89 1
                'properties' => [
90
                    'sheetId' => $sheetId,
91
                    'gridProperties' => [
92 1
                        'frozenRowCount' => $frozonRowCount,
93
                    ],
94 1
                ],
95
                'fields' => 'gridProperties.frozenRowCount',
96
            ],
97 1
        ]);
98
    }
99
100
    public function frozenColumnRequest($sheetId, $frozonColumnCount = 1)
101
    {
102 1
        return new Google_Service_Sheets_Request([
103
            'updateSheetProperties' => [
104 1
                'properties' => [
105
                    'sheetId' => $sheetId,
106 1
                    'gridProperties' => [
107
                        'frozenColumnCount' => $frozonColumnCount,
108
                    ],
109 1
                ],
110 1
                'fields' => 'gridProperties.frozenColumnCount',
111 1
            ],
112
        ]);
113 1
    }
114 1
115 1
    public function styleArea($range, $styles)
116 1
    {
117
        return new Google_Service_Sheets_Request([
118
            'repeatCell' => [
119
                'range' => $range,
120 1
                'cell' => [
121
                    'userEnteredFormat' => [
122
                        'backgroundColor' => $this->fractalColors($styles['backgroundColor']),
123
                        'horizontalAlignment' => $styles['horizontalAlignment'],
124
                        'verticalAlignment' => $styles['verticalAlignment'],
125 1
                        'textFormat' => [
126
                            'foregroundColor' => $this->fractalColors($styles['foregroundColor']),
127 1
                            'fontSize' => $styles['fontSize'],
128
                            'fontFamily' => $styles['fontFamily'],
129
                            'bold' => $styles['bold'],
130 1
                        ],
131 1
                    ],
132 1
                ],
133 1
                'fields' => 'userEnteredFormat(backgroundColor,textFormat,horizontalAlignment)',
134
            ],
135
        ]);
136 1
    }
137
138 1
    public function fixedColumnWidthRequest($sheetId, $startIndex, $endIndex, $width)
139
    {
140
        return new Google_Service_Sheets_Request([
141
            'updateDimensionProperties' => [
142
                'range' => [
143 1
                    'sheetId' => $sheetId,
144
                    'dimension' => 'COLUMNS',
145 1
                    'startIndex' => $startIndex,
146
                    'endIndex' => $endIndex,
147
                ],
148 1
                'properties' => [
149 1
                    'pixelSize' => $width,
150 1
                ],
151
                'fields' => 'pixelSize',
152 1
            ],
153
        ]);
154
    }
155
156 View Code Duplication
    public function setSheetTitle($sheetId, $title)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
157 1
    {
158
        return new Google_Service_Sheets_Request([
159
            'updateSheetProperties' => [
160 1
                'properties' => [
161
                    'sheetId' => $sheetId,
162 1
                    'title' => $title,
163 1
                ],
164
                'fields' => 'title',
165
            ],
166
        ]);
167 1
    }
168 1
169
    public function setTabColor($sheetId, $tabColor)
170
    {
171 1
        return new Google_Service_Sheets_Request([
172
            'updateSheetProperties' => [
173
                'properties' => [
174 1
                    'sheetId' => $sheetId,
175
                    'tabColor' => $this->fractalColors($tabColor),
176 1
                ],
177 1
                'fields' => 'tabColor',
178
            ],
179
        ]);
180
    }
181
182
    // @todo: remove if not used any more.
183 View Code Duplication
    public function setSheetPropertiesRequest($sheetId, $title, $tabColor)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
184
    {
185
        return new Google_Service_Sheets_Request([
186
            'updateSheetProperties' => [
187
                'properties' => [
188
                    'sheetId' => $sheetId,
189
                    'title' => $title,
190
                    'tabColor' => $this->fractalColors($tabColor),
191
                ],
192 1
                'fields' => 'title,tabColor',
193
            ],
194 1
        ]);
195
    }
196
197 1
    public function addSheetRequest($title, $rowCount, $columnCount, $tabColor = null)
198 1
    {
199
        $properties = [
200
            'title' => $title,
201 1
            'gridProperties' => [
202
                'rowCount' => $rowCount,
203
                'columnCount' => $columnCount,
204
            ],
205
        ];
206
207
        if (!is_null($tabColor)) {
208
            $properties['tabColor'] = $this->fractalColors($tabColor);
209 1
        }
210
211 1
        return new Google_Service_Sheets_Request(['addSheet' => ['properties' => $properties]]);
212
    }
213 1
214 1
    public function addBlankSheet($title = null)
215 1
    {
216 1
        $properties = $title ? ['title' => $title] : [];
217 1
        return new Google_Service_Sheets_Request(['addSheet' => ['properties' => $properties]]);
218 1
    }
219
220
    public function clearSheetRequest($sheetId)
221 1
    {
222 1
        return new Google_Service_Sheets_Request([
223
            'updateCells' => [
224
                'range' => [
225
                    'sheetId' => $sheetId,
226
                ],
227
                'fields' => 'userEnteredValue',
228
            ],
229
        ]);
230
    }
231
232
    public function protectRangeRequest($range, $description)
233
    {
234
        return new Google_Service_Sheets_Request([
235
            'addProtectedRange' => [
236
                'protectedRange' => [
237
                    'range' => $range,
238
                    'description' => $description,
239
                    'warningOnly' => false,
240 1
                    'editors' => [
241
                        'users' => [config('translation_sheet.serviceAccountEmail')],
242 1
                    ],
243
                ],
244 1
            ],
245 1
246 1
        ]);
247
    }
248
249
    public function writeCells($shortRange, $values)
250
    {
251 2
        $sheets = new \Google_Service_Sheets($this->client);
252
253 2
        $request = new Google_Service_Sheets_BatchUpdateValuesRequest();
254
        $request->setValueInputOption('RAW');
255 2
        $request->setData([
256
            'range' => $shortRange,
257
            'majorDimension' => 'ROWS',
258 2
            'values' => $values,
259
        ]);
260 2
261
        $sheets->spreadsheets_values->batchUpdate($this->spreadsheetId, $request);
262
    }
263 1
264
    public function readCells($sheetId, $range)
265 1
    {
266
        $range .= $this->getSheetRowCount($sheetId);
267 1
268 1
        $sheets = new \Google_Service_Sheets($this->client);
269
270
        return $sheets->spreadsheets_values->get($this->spreadsheetId, $range)->values;
271
    }
272
273
    public function getSheetRowCount($sheetId)
274
    {
275
        $sheet = $this->getSheet($sheetId);
276
277
        return $sheet['properties']['gridProperties']['rowCount'];
278
    }
279
280
    public function getSheet($sheetId)
281 1
    {
282
        $sheets = $this->getSheets();
283 1
284
        foreach ($sheets as $sheet) {
285
            if ($sheet['properties']['sheetId'] === $sheetId) {
286 1
                return $sheet;
287 1
            }
288 1
        }
289
290
        return null;
291
    }
292
293
    public function getSheetByTitle($title)
294 1
    {
295
        $sheets = $this->getSheets();
296 1
297
        foreach ($sheets as $sheet) {
298
            if (strtolower($sheet['properties']['title']) === strtolower($title)) {
299 1
                return $sheet;
300 1
            }
301 1
        }
302
303
        return null;
304
    }
305
306
    public function getSheets()
307
    {
308
        if (empty($this->cachedSheets)) {
309
            $this->cachedSheets = (new \Google_Service_Sheets($this->client))
310
                ->spreadsheets
311
                ->get($this->spreadsheetId)
312
                ->getSheets();
313
        }
314
315
        return $this->cachedSheets;
316 1
    }
317
318 1
    public function forgetSheets()
319
    {
320 1
        $this->cachedSheets = [];
321
322
        return $this;
323
    }
324
325
    public function freshSheets()
326
    {
327
        $this->forgetSheets();
328
329
        return $this->getSheets();
330
    }
331
332 1
    public function firstSheetId()
333
    {
334 1
        return data_get(collect($this->getSheets())->first(), 'properties.sheetId');
335 1
    }
336
337 1
    public function getSheetProtectedRanges($sheetId, $description = null)
338
    {
339
        $sheet = $this->getSheet($sheetId);
340
341 1
        if (is_null($description)) {
342 1
            return $sheet['protectedRanges'];
343 1
        }
344
345
        $ranges = [];
346
        foreach ($sheet['protectedRanges'] as $range) {
347
            if ($range->description === $description) {
348
                $ranges[] = $range;
349
            }
350
        }
351
352
        return $ranges;
353
    }
354
355
    public function deleteColumnsFrom($sheetId, $fromColumnIndex)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
356
    {
357
        return new Google_Service_Sheets_Request([
358
            'deleteDimension' => [
359
                'range' => [
360
                    'sheetId' => $sheetId,
361
                    'dimension' => 'COLUMNS',
362
                    'startIndex' => $fromColumnIndex,
363
                ],
364
            ],
365
        ]);
366
    }
367
368
    public function deleteRowsFrom($sheetId, $fromRowIndex)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
369
    {
370
        return new Google_Service_Sheets_Request([
371
            'deleteDimension' => [
372
                'range' => [
373
                    'sheetId' => $sheetId,
374
                    'dimension' => 'ROWS',
375
                    'startIndex' => $fromRowIndex,
376
                ],
377
            ],
378
        ]);
379
    }
380
381
    public function deleteProtectedRange($protectedRangeId)
382
    {
383
        return new Google_Service_Sheets_Request([
384
            'deleteProtectedRange' => [
385
                'protectedRangeId' => $protectedRangeId,
386
            ],
387
        ]);
388
    }
389
390
    public function deleteSheetRequest($sheetId)
391
    {
392
        return new Google_Service_Sheets_Request([
393
            'deleteSheet' => [
394
                'sheetId' => $sheetId,
395
            ],
396
        ]);
397
    }
398
399
    /**
400
     * Return Fractal RGB color array with r,g,b between 0 and 1.
401
     *
402
     * @param mixed $color array of RGB color ([255, 255, 255]) or hex string (#FFFFFF)
403
     *
404
     * @return array
405
     */
406
    protected function fractalColors($color)
407
    {
408
        if (is_array($color)) {
409
            list($red, $green, $blue) = $color;
410
        } else {
411
            list($red, $green, $blue) = sscanf($color, '#%02x%02x%02x');
412
        }
413
414
        return [
415
            'red' => round($red / 255, 1),
416
            'green' => round($green / 255, 1),
417
            'blue' => round($blue / 255, 1),
418
        ];
419
    }
420
421
422
}
423