Completed
Push — master ( 95cc27...d32772 )
by Vladimir
05:08 queued 03:05
created

PulseBoard::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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