PulseBoard::createColumn()   B
last analyzed

Complexity

Conditions 6
Paths 3

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 25
c 0
b 0
f 0
ccs 12
cts 12
cp 1
rs 8.8977
cc 6
nc 3
nop 3
crap 6
1
<?php
2
3
/**
4
 * @copyright 2017 Vladimir Jimenez
5
 * @license   https://github.com/allejo/PhpPulse/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\DaPulse;
9
10
use allejo\DaPulse\Exceptions\ArgumentMismatchException;
11
use allejo\DaPulse\Exceptions\InvalidArraySizeException;
12
use allejo\DaPulse\Exceptions\InvalidObjectException;
13
use allejo\DaPulse\Objects\SubscribableObject;
14
use allejo\DaPulse\Utilities\StringUtilities;
15
16
/**
17
 * This class contains all of the respective functionality for working a board on DaPulse
18
 *
19
 * @api
20
 * @package allejo\DaPulse
21
 * @since   0.1.0
22
 */
23
class PulseBoard extends SubscribableObject
24
{
25
    /**
26
     * The suffix that is appended to the URL to access functionality for certain objects
27
     *
28
     * @internal
29
     */
30
    const API_PREFIX = "boards";
31
32
    // =================================================================================================================
33
    //   Instance Variables
34
    // =================================================================================================================
35
36
    /**
37
     * The resource's URL.
38
     *
39
     * @var string
40
     */
41
    protected $url;
42
43
    /**
44
     * The board's name.
45
     *
46
     * @var string
47
     */
48
    protected $name;
49
50
    /**
51
     * The board's description.
52
     *
53
     * @var string
54
     */
55
    protected $description;
56
57
    /**
58
     * The board's visible columns.
59
     *
60
     * @var array
61
     */
62
    protected $columns;
63
64
    /**
65
     * Creation time.
66
     *
67
     * @var \DateTime
68
     */
69
    protected $created_at;
70
71
    /**
72
     * Last update time.
73
     *
74
     * @var \DateTime
75
     */
76
    protected $updated_at;
77
78
    // =================================================================================================================
79
    //   Getter functions
80
    // =================================================================================================================
81
82
    /**
83
     * The resource's URL.
84
     *
85
     * @api
86
     *
87
     * @since  0.1.0
88
     *
89
     * @return string
90
     */
91 1
    public function getUrl ()
92
    {
93 1
        $this->lazyLoad();
94
95 1
        return $this->url;
96
    }
97
98
    /**
99
     * The board's unique identifier.
100
     *
101
     * @api
102
     *
103
     * @since  0.1.0
104
     *
105
     * @return int
106
     */
107 43
    public function getId ()
108
    {
109 43
        return $this->id;
110
    }
111
112
    /**
113
     * The board's name.
114
     *
115
     * @api
116
     *
117
     * @since  0.1.0
118
     *
119
     * @return string
120
     */
121 2
    public function getName ()
122
    {
123 2
        $this->lazyLoad();
124
125 2
        return $this->name;
126
    }
127
128
    /**
129
     * The board's description.
130
     *
131
     * @api
132
     *
133
     * @since  0.1.0
134
     *
135
     * @return string
136
     */
137 2
    public function getDescription ()
138
    {
139 2
        $this->lazyLoad();
140
141 2
        return $this->description;
142
    }
143
144
    /**
145
     * Creation time.
146
     *
147
     * @api
148
     *
149
     * @since  0.1.0
150
     *
151
     * @return \DateTime
152
     */
153 1
    public function getCreatedAt ()
154
    {
155 1
        $this->lazyLoad();
156 1
        self::lazyCast($this->created_at, '\DateTime');
157
158 1
        return $this->created_at;
159
    }
160
161
    /**
162
     * Last update time.
163
     *
164
     * @api
165
     *
166
     * @since  0.1.0
167
     *
168
     * @return \DateTime
169
     */
170 1
    public function getUpdatedAt ()
171
    {
172 1
        $this->lazyLoad();
173 1
        self::lazyCast($this->updated_at, '\DateTime');
174
175 1
        return $this->updated_at;
176
    }
177
178
    // =================================================================================================================
179
    //   Columns functions
180
    // =================================================================================================================
181
182
    /**
183
     * The board's visible columns.
184
     *
185
     * @api
186
     *
187
     * @since  0.1.0
188
     *
189
     * @return PulseColumn[]
190
     */
191 40
    public function getColumns ()
192
    {
193 40
        $this->lazyLoad();
194
195 40
        self::lazyInject($this->columns, [
196 40
            "board_id" => $this->getId()
197
        ]);
198 40
        self::lazyCastAll($this->columns, "PulseColumn");
199
200 40
        return $this->columns;
201
    }
202
203
    /**
204
     * Create a new column for the current board.
205
     *
206
     * If you are creating a status column, use the constants available in the **PulseColumnColorValue** class to match
207
     * the colors. Keep in mind this array cannot have a key higher than 11 nor can it be an associative array. Here's
208
     * an example of how to match statuses with specific colors.
209
     *
210
     * ```php
211
     * $labels = array(
212
     *     PulseColumnColorValue::Orange  => "Working on it",
213
     *     PulseColumnColorValue::L_Green => "Done",
214
     *     PulseColumnColorValue::Red     => "Delayed"
215
     * );
216
     * ```
217
     *
218
     * @api
219
     *
220
     * @param string $title  The title of the column. This title will automatically be "slugified" and become the ID
221
     *                       of the column.
222
     * @param string $type   The type of value that this column will use. Either use the available constants in the
223
     *                       PulseColumn class or use the following strings: "date", "person", "status", "text".
224
     * @param array  $labels If the column type will be "status," then this array will be the values for each of the
225
     *                       colors.
226
     *
227
     * @see   PulseColumn::Date    PulseColumn::Date
228
     * @see   PulseColumn::Person  PulseColumn::Person
229
     * @see   PulseColumn::Numeric PulseColumn::Numeric
230
     * @see   PulseColumn::Status  PulseColumn::Status
231
     * @see   PulseColumn::Text    PulseColumn::Text
232
     * @see   PulseColumnStatusValue::Orange  PulseColumnStatusValue::Orange
233
     * @see   PulseColumnStatusValue::L_Green PulseColumnStatusValue::L_Green
234
     * @see   PulseColumnStatusValue::Red     PulseColumnStatusValue::Red
235
     * @see   PulseColumnStatusValue::Blue    PulseColumnStatusValue::Blue
236
     * @see   PulseColumnStatusValue::Purple  PulseColumnStatusValue::Purple
237
     * @see   PulseColumnStatusValue::Grey    PulseColumnStatusValue::Grey
238
     * @see   PulseColumnStatusValue::Green   PulseColumnStatusValue::Green
239
     * @see   PulseColumnStatusValue::L_Blue  PulseColumnStatusValue::L_Blue
240
     * @see   PulseColumnStatusValue::Gold    PulseColumnStatusValue::Gold
241
     * @see   PulseColumnStatusValue::Yellow  PulseColumnStatusValue::Yellow
242
     * @see   PulseColumnStatusValue::Black   PulseColumnStatusValue::Black
243
     *
244
     * @since 0.1.0
245
     *
246
     * @throws ArgumentMismatchException Status definitions were defined yet the type of the column was not a status
247
     *                                   type column
248
     * @throws InvalidArraySizeException The array containing the value of statuses has a key larger than the
249
     *                                   supported 10 indices
250
     *
251
     * @return $this This instance will be updated to have updated information to reflect the new column that was
252
     *               created
253
     */
254 3
    public function createColumn ($title, $type, $labels = [])
255
    {
256 3
        if ($type !== PulseColumn::Status && !empty($labels))
257
        {
258 1
            throw new ArgumentMismatchException("No color definitions are required for a non-color column.");
259
        }
260
261 2
        if ($type === PulseColumn::Status && count($labels) > 0 && max(array_keys($labels)) > 10)
262
        {
263 1
            throw new InvalidArraySizeException("The range of status can only be from 0-10.");
264
        }
265
266 1
        $url        = sprintf("%s/%d/columns.json", self::apiEndpoint(), $this->getId());
267
        $postParams = [
268 1
            "title" => $title,
269 1
            "type"  => $type
270
        ];
271
272 1
        self::setIfNotNullOrEmpty($postParams, "labels", $labels);
273
274 1
        $this->jsonResponse = self::sendPost($url, $postParams);
0 ignored issues
show
Documentation Bug introduced by
It seems like self::sendPost($url, $postParams) of type * is incompatible with the declared type array of property $jsonResponse.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
275 1
        $this->assignResults();
276
277 1
        return $this;
278
    }
279
280
    // =================================================================================================================
281
    //   Group functions
282
    // =================================================================================================================
283
284
    /**
285
     * Get all of the groups belonging to a board.
286
     *
287
     * A group is defined as the colorful headers that split up pulses into categories.
288
     *
289
     * @api
290
     *
291
     * @param bool $showArchived Set to true if you would like to get archived groups in a board as well
292
     *
293
     * @since 0.1.0
294
     *
295
     * @return PulseGroup[]
296
     */
297 3
    public function getGroups ($showArchived = false)
298
    {
299 3
        $url    = sprintf("%s/%d/groups.json", self::apiEndpoint(), $this->getId());
300
        $params = [
301 3
            'show_archived' => StringUtilities::booleanLiteral($showArchived)
302
        ];
303 3
        $result = self::sendGet($url, $params);
304
305 3
        self::lazyInject($result, [
306 3
            'board_id' => $this->getId()
307
        ]);
308 3
        self::lazyCastAll($result, 'PulseGroup');
309
310 3
        return $result;
311
    }
312
313
    /**
314
     * Create a new group in a board
315
     *
316
     * @api
317
     *
318
     * @param  string $title The title of the board
319
     *
320
     * @since  0.1.0
321
     *
322
     * @return PulseGroup
323
     */
324 1
    public function createGroup ($title)
325
    {
326 1
        $url        = sprintf("%s/%s/groups.json", self::apiEndpoint(), $this->getId());
327 1
        $postParams = ["title" => $title];
328
329
        // The API doesn't return the board ID, so since we have access to it here: set it manually
330 1
        $groupResult             = self::sendPost($url, $postParams);
331 1
        $groupResult["board_id"] = $this->getId();
332
333 1
        return (new PulseGroup($groupResult));
334
    }
335
336
    /**
337
     * Delete a group from a board
338
     *
339
     * @api
340
     *
341
     * @param string $groupId The group ID to be deleted
342
     *
343
     * @since 0.3.0 An array of PulseGroup objects representing the current groups in this board and their states
344
     * @since 0.1.0
345
     *
346
     * @return PulseGroup[] An array containing the remaining groups available on the board
347
     */
348 1
    public function deleteGroup ($groupId)
349
    {
350 1
        $url    = sprintf("%s/%d/groups/%s.json", self::apiEndpoint(), $this->getId(), $groupId);
351 1
        $result = self::sendDelete($url);
352
353 1
        self::lazyInject($result, [
354 1
            'board_id' => $this->getId()
355
        ]);
356 1
        self::lazyCastAll($result, 'PulseGroup');
357
358 1
        return $result;
359
    }
360
361
    // =================================================================================================================
362
    //   Pulse functions
363
    // =================================================================================================================
364
365
    /**
366
     * Get all of the Pulses belonging to this board
367
     *
368
     * @api
369
     *
370
     * @since  0.1.0
371
     *
372
     * @param int $perPage  default: 15, max: 25
0 ignored issues
show
Documentation introduced by
Should the type for parameter $perPage not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
373
     * @param int $page     default: 1
0 ignored issues
show
Documentation introduced by
Should the type for parameter $page not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
374
     * @return Pulse[]
375
     */
376 40
    public function getPulses ($perPage = null, $page = null)
377
    {
378 40
        $url    = sprintf("%s/%d/pulses.json", self::apiEndpoint(), $this->getId());
379 40
        $params = [];
380
        
381 40
        self::setIfNotNullOrEmpty($params, 'per_page', $perPage);
382 40
        self::setIfNotNullOrEmpty($params, 'page', $page);
383
384 40
        $data   = self::sendGet($url, $params);
385 40
        $pulses = [];
386
387 40
        foreach ($data as $entry)
388
        {
389 40
            $this->pulseInjection($entry);
390
391 40
            $pulses[] = new Pulse($entry["pulse"]);
392
        }
393
394 40
        return $pulses;
395
    }
396
397
    /**
398
     * Create a new Pulse inside of this board
399
     *
400
     * Using the $updateText and $announceToAll parameters is the equivalent of using Pulse::createUpdate() after a
401
     * Pulse has been created but with one less API call.
402
     *
403
     * @api
404
     *
405
     * @param string        $name          The name of the Pulse
406
     * @param PulseUser|int $user          The owner of the Pulse, i.e. who created it
407
     * @param string|null   $groupId       The group to add this Pulse to
408
     * @param string|null   $updateText    The update's text, can contain simple HTML for formatting
409
     * @param bool|null     $announceToAll Determines if the update should be sent to everyone's wall
410
     *
411
     * @throws \InvalidArgumentException if $user is not a valid user by definition
412
     *
413
     * @since 0.3.0 An \InvalidArgumentException may be thrown
414
     * @since 0.1.0
415
     *
416
     * @return Pulse
417
     */
418 1
    public function createPulse ($name, $user, $groupId = null, $updateText = null, $announceToAll = null)
419
    {
420 1
        $user       = PulseUser::_castToInt($user);
421 1
        $url        = sprintf("%s/%d/pulses.json", self::apiEndpoint(), $this->getId());
422
        $postParams = [
423 1
            "user_id" => $user,
424
            "pulse"   => [
425 1
                "name" => $name
426
            ]
427
        ];
428
429 1
        self::setIfNotNullOrEmpty($postParams, "group_id", $groupId);
430 1
        self::setIfNotNullOrEmpty($postParams['update'], 'text', $updateText);
431 1
        self::setIfNotNullOrEmpty($postParams['update'], 'announcement', $announceToAll);
432
433 1
        $result = self::sendPost($url, $postParams);
434 1
        $this->pulseInjection($result);
435
436 1
        return (new Pulse($result["pulse"]));
437
    }
438
439 40 View Code Duplication
    private function pulseInjection (&$result)
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...
440
    {
441
        // Inject some information so a Pulse object can survive on its own
442 40
        $result["pulse"]["group_id"]          = $result["board_meta"]["group_id"];
443 40
        $result["pulse"]["column_structure"]  = $this->getColumns();
444 40
        $result["pulse"]["raw_column_values"] = $result["column_values"];
445 40
    }
446
447
    // =================================================================================================================
448
    //   Board functions
449
    // =================================================================================================================
450
451
    /**
452
     * Archive this board
453
     *
454
     * @api
455
     *
456
     * @since 0.1.0
457
     *
458
     * @throws InvalidObjectException if the object has already been deleted
459
     */
460 1 View Code Duplication
    public function archiveBoard ()
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...
461
    {
462 1
        $this->checkInvalid();
463
464 1
        $url = sprintf("%s/%s.json", self::apiEndpoint(), $this->getId());
465 1
        self::sendDelete($url);
466
467 1
        $this->deletedObject = true;
468 1
    }
469
470
    /**
471
     * Create a new board
472
     *
473
     * @api
474
     *
475
     * @param  string        $name        The name of the board
476
     * @param  int|PulseUser $user        The owner of the board
477
     * @param  string|null   $description A description of the board
478
     *
479
     * @since  0.3.0 $userId may be a PulseUser object and \InvalidArgumentException is now thrown
480
     * @since  0.1.0
481
     *
482
     * @throws \InvalidArgumentException if $user is not a valid user by definition
483
     *
484
     * @return PulseBoard
485
     */
486 1
    public static function createBoard ($name, $user, $description = null)
487
    {
488 1
        $user       = PulseUser::_castToInt($user);
489 1
        $url        = sprintf("%s.json", self::apiEndpoint());
490
        $postParams = [
491 1
            "user_id" => $user,
492 1
            "name"    => $name
493
        ];
494
495 1
        self::setIfNotNullOrEmpty($postParams, "description", $description);
496
497 1
        $boardResult = self::sendPost($url, $postParams);
498
499 1
        return (new PulseBoard($boardResult));
500
    }
501
502
    /**
503
     * Get all the account's boards
504
     *
505
     * ```
506
     * array['page']            int  - Page offset to fetch
507
     *      ['per_page']        int  - Number of results to return per page
508
     *      ['offset']          int  - Pad a number of results
509
     *      ['only_globals']    bool - Return only global boards
510
     *      ['order_by_latest'] bool - Order by newest boards
511
     * ```
512
     *
513
     * @api
514
     *
515
     * @param  array $params Parameters to filter the boards (see above)
516
     *
517
     * @since  0.1.0
518
     *
519
     * @return PulseBoard[]
520
     */
521 1
    public static function getBoards ($params = [])
522
    {
523 1
        $url = sprintf("%s.json", self::apiEndpoint());
524
525 1
        return self::fetchAndCastToObjectArray($url, "PulseBoard", $params);
526
    }
527
}