Completed
Push — develop ( 2ce0a7...a053c0 )
by Vladimir
04:14
created

PulseBoard::createPulse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1.0527

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 20
ccs 5
cts 8
cp 0.625
rs 9.4285
cc 1
eloc 13
nc 1
nop 5
crap 1.0527
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
    public function getUrl ()
92
    {
93
        $this->lazyLoad();
94
95
        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
    public function getId ()
108
    {
109
        return $this->id;
110
    }
111
112 15
    /**
113
     * The board's name.
114 15
     *
115
     * @api
116
     *
117
     * @since  0.1.0
118
     *
119
     * @return string
120
     */
121
    public function getName ()
122
    {
123
        $this->lazyLoad();
124
125
        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
    public function getDescription ()
138
    {
139
        $this->lazyLoad();
140
141
        return $this->description;
142
    }
143
144
    /**
145
     * Creation time.
146
     *
147
     * @api
148
     *
149
     * @since  0.1.0
150
     *
151
     * @return \DateTime
152
     */
153
    public function getCreatedAt ()
154
    {
155
        $this->lazyLoad();
156
        self::lazyCast($this->created_at, '\DateTime');
157
158
        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
    public function getUpdatedAt ()
171
    {
172
        $this->lazyLoad();
173
        self::lazyCast($this->updated_at, '\DateTime');
174
175
        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 15
     */
191
    public function getColumns ()
192 15
    {
193 15
        $this->lazyLoad();
194
195 15
        self::lazyInject($this->columns, [
196
            "board_id" => $this->getId()
197 15
        ]);
198
        self::lazyCastAll($this->columns, "PulseColumn");
199
200
        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
    public function createColumn ($title, $type, $labels = array())
255
    {
256
        if ($type !== PulseColumn::Status && !empty($labels))
257
        {
258
            throw new ArgumentMismatchException("No color definitions are required for a non-color column.");
259
        }
260
261
        if ($type === PulseColumn::Status && count($labels) > 0 && max(array_keys($labels)) > 10)
262
        {
263
            throw new InvalidArraySizeException("The range of status can only be from 0-10.");
264
        }
265
266
        $url        = sprintf("%s/%d/columns.json", self::apiEndpoint(), $this->getId());
267
        $postParams = array(
268
            "title" => $title,
269
            "type"  => $type
270
        );
271
272
        self::setIfNotNullOrEmpty($postParams, "labels", $labels);
273
274
        $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
        $this->assignResults();
276
277
        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
    public function getGroups ($showArchived = false)
298
    {
299
        $url    = sprintf("%s/%d/groups.json", self::apiEndpoint(), $this->getId());
300
        $params = [
301
            'show_archived' => StringUtilities::booleanLiteral($showArchived)
302
        ];
303
        $result = self::sendGet($url, $params);
304
305
        self::lazyInject($result, [
306
            'board_id' => $this->getId()
307
        ]);
308
        self::lazyCastAll($result, 'PulseGroup');
309
310
        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
    public function createGroup ($title)
325
    {
326
        $url        = sprintf("%s/%s/groups.json", self::apiEndpoint(), $this->getId());
327
        $postParams = array("title" => $title);
328
329
        // The API doesn't return the board ID, so since we have access to it here: set it manually
330
        $groupResult             = self::sendPost($url, $postParams);
331
        $groupResult["board_id"] = $this->getId();
332
333
        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
    public function deleteGroup ($groupId)
349
    {
350 15
        $url = sprintf("%s/%d/groups/%s.json", self::apiEndpoint(), $this->getId(), $groupId);
351
        $result = self::sendDelete($url);
352 15
353 15
        self::lazyInject($result, [
354 15
            'board_id' => $this->getId()
355
        ]);
356 15
        self::lazyCastAll($result, 'PulseGroup');
357
358 15
        return $result;
359
    }
360 15
361
    // =================================================================================================================
362
    //   Pulse functions
363 15
    // =================================================================================================================
364
365
    /**
366
     * @return Pulse[]
367
     */
368
    public function getPulses ()
369
    {
370
        $url    = sprintf("%s/%d/pulses.json", self::apiEndpoint(), $this->getId());
371
        $data   = self::sendGet($url);
372
        $pulses = array();
373
374
        foreach ($data as $entry)
375
        {
376
            $this->pulseInjection($entry);
377
378
            $pulses[] = new Pulse($entry["pulse"]);
379
        }
380
381
        return $pulses;
382
    }
383
384
    /**
385
     * Create a new Pulse inside of this board
386
     *
387
     * Using the $updateText and $announceToAll parameters is the equivalent of using Pulse::createUpdate() after a
388
     * Pulse has been created but with one less API call.
389
     *
390
     * @api
391
     *
392
     * @param string        $name          The name of the Pulse
393
     * @param PulseUser|int $user          The owner of the Pulse, i.e. who created it
394
     * @param string|null   $groupId       The group to add this Pulse to
395
     * @param string|null   $updateText    The update's text, can contain simple HTML for formatting
396
     * @param bool|null     $announceToAll Determines if the update should be sent to everyone's wall
397
     *
398
     * @throws \InvalidArgumentException if $user is not a valid user by definition
399
     *
400
     * @since 0.3.0 An \InvalidArgumentException may be thrown
401
     * @since 0.1.0
402
     *
403
     * @return Pulse
404
     */
405
    public function createPulse ($name, $user, $groupId = NULL, $updateText = NULL, $announceToAll = NULL)
406
    {
407
        $user       = PulseUser::_castToInt($user);
408
        $url        = sprintf("%s/%d/pulses.json", self::apiEndpoint(), $this->getId());
409 15
        $postParams = array(
410
            "user_id" => $user,
411
            "pulse"   => array(
412 15
                "name" => $name
413 15
            )
414 15
        );
415 15
416
        self::setIfNotNullOrEmpty($postParams, "group_id", $groupId);
417
        self::setIfNotNullOrEmpty($postParams['update'], 'text', $updateText);
418
        self::setIfNotNullOrEmpty($postParams['update'], 'announcement', $announceToAll);
419
420
        $result = self::sendPost($url, $postParams);
421
        $this->pulseInjection($result);
422
423
        return (new Pulse($result["pulse"]));
424
    }
425
426 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...
427
    {
428
        // Inject some information so a Pulse object can survive on its own
429
        $result["pulse"]["group_id"]          = $result["board_meta"]["group_id"];
430
        $result["pulse"]["column_structure"]  = $this->getColumns();
431
        $result["pulse"]["raw_column_values"] = $result["column_values"];
432
    }
433
434
    // =================================================================================================================
435
    //   Board functions
436
    // =================================================================================================================
437
438
    /**
439
     * Archive this board
440
     *
441
     * @since 0.1.0
442
     *
443
     * @throws InvalidObjectException if the object has already been deleted
444
     */
445 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...
446
    {
447
        $this->checkInvalid();
448
449
        $url = sprintf("%s/%s.json", self::apiEndpoint(), $this->getId());
450
        self::sendDelete($url);
451
452
        $this->deletedObject = true;
453
    }
454
455
    /**
456
     * Create a new board
457
     *
458
     * @param  string        $name        The name of the board
459
     * @param  int|PulseUser $user        The owner of the board
460
     * @param  string|null   $description A description of the board
461
     *
462
     * @since  0.3.0 $userId may be a PulseUser object and \InvalidArgumentException is now thrown
463
     * @since  0.1.0
464
     *
465
     * @throws \InvalidArgumentException if $user is not a valid user by definition
466
     *
467
     * @return PulseBoard
468
     */
469
    public static function createBoard ($name, $user, $description = NULL)
470
    {
471
        $user       = PulseUser::_castToInt($user);
472
        $url        = sprintf("%s.json", self::apiEndpoint());
473
        $postParams = array(
474
            "user_id" => $user,
475
            "name"    => $name
476
        );
477
478
        self::setIfNotNullOrEmpty($postParams, "description", $description);
479
480
        $boardResult = self::sendPost($url, $postParams);
481
482
        return (new PulseBoard($boardResult));
483
    }
484
485
    /**
486
     * Get all the account's boards
487
     *
488
     * ```
489
     * array['page']            int  - Page offset to fetch
490
     *      ['per_page']        int  - Number of results to return per page
491
     *      ['offset']          int  - Pad a number of results
492
     *      ['only_globals']    bool - Return only global boards
493
     *      ['order_by_latest'] bool - Order by newest boards
494
     * ```
495
     *
496
     * @param  array $params Parameters to filter the boards (see above)
497
     *
498
     * @since  0.1.0
499
     *
500
     * @return PulseBoard[]
501
     */
502
    public static function getBoards ($params = array())
503
    {
504
        $url = sprintf("%s.json", self::apiEndpoint());
505
506
        return self::fetchAndCastToObjectArray($url, "PulseBoard", $params);
507
    }
508
}