Completed
Push — master ( 725043...fc3a8f )
by Vladimir
07:42
created

PulseBoard::createPulse()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 24
c 2
b 0
f 0
rs 8.9713
cc 2
eloc 14
nc 2
nop 5
1
<?php
2
3
/**
4
 * This file contains the PulseBoard class
5
 *
6
 * @copyright 2015 Vladimir Jimenez
7
 * @license   https://github.com/allejo/PhpPulse/blob/master/LICENSE.md MIT
8
 */
9
10
namespace allejo\DaPulse;
11
12
use allejo\DaPulse\Exceptions\ArgumentMismatchException;
13
use allejo\DaPulse\Exceptions\InvalidArraySizeException;
14
use allejo\DaPulse\Objects\SubscribableObject;
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 unique identifier.
45
     *
46
     * @var int
47
     */
48
    protected $id;
49
50
    /**
51
     * The board's name.
52
     *
53
     * @var string
54
     */
55
    protected $name;
56
57
    /**
58
     * The board's description.
59
     *
60
     * @var string
61
     */
62
    protected $description;
63
64
    /**
65
     * The board's visible columns.
66
     *
67
     * @var array
68
     */
69
    protected $columns;
70
71
    /**
72
     * Creation time.
73
     *
74
     * @var \DateTime
75
     */
76
    protected $created_at;
77
78
    /**
79
     * Last update time.
80
     *
81
     * @var \DateTime
82
     */
83
    protected $updated_at;
84
85
    // =================================================================================================================
86
    //   Getter functions
87
    // =================================================================================================================
88
89
    /**
90
     * The resource's URL.
91
     *
92
     * @api
93
     *
94
     * @since  0.1.0
95
     *
96
     * @return string
97
     */
98
    public function getUrl ()
99
    {
100
        return $this->url;
101
    }
102
103
    /**
104
     * The board's unique identifier.
105
     *
106
     * @api
107
     *
108
     * @since  0.1.0
109
     *
110
     * @return int
111
     */
112
    public function getId ()
113
    {
114
        return $this->id;
115
    }
116
117
    /**
118
     * The board's name.
119
     *
120
     * @api
121
     *
122
     * @since  0.1.0
123
     *
124
     * @return string
125
     */
126
    public function getName ()
127
    {
128
        return $this->name;
129
    }
130
131
    /**
132
     * The board's description.
133
     *
134
     * @api
135
     *
136
     * @since  0.1.0
137
     *
138
     * @return string
139
     */
140
    public function getDescription ()
141
    {
142
        return $this->description;
143
    }
144
145
    /**
146
     * Creation time.
147
     *
148
     * @api
149
     *
150
     * @since  0.1.0
151
     *
152
     * @return \DateTime
153
     */
154
    public function getCreatedAt ()
155
    {
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
        self::lazyCast($this->updated_at, '\DateTime');
173
174
        return $this->updated_at;
175
    }
176
177
    // =================================================================================================================
178
    //   Columns functions
179
    // =================================================================================================================
180
181
    /**
182
     * The board's visible columns.
183
     *
184
     * @api
185
     *
186
     * @since  0.1.0
187
     *
188
     * @return PulseColumn[]
189
     */
190
    public function getColumns ()
191
    {
192
        self::lazyInject($this->columns, array(
193
            "board_id" => $this->getId()
194
        ));
195
        self::lazyCastAll($this->columns, "PulseColumn");
196
197
        return $this->columns;
198
    }
199
200
    /**
201
     * Create a new column for the current board.
202
     *
203
     * If you are creating a status column, use the constants available in the **PulseColumnColorValue** class to match
204
     * the colors. Keep in mind this array cannot have a key higher than 11 nor can it be an associative array. Here's
205
     * an example of how to match statuses with specific colors.
206
     *
207
     * ```php
208
     * $labels = array(
209
     *     PulseColumnColorValue::Orange  => "Working on it",
210
     *     PulseColumnColorValue::L_Green => "Done",
211
     *     PulseColumnColorValue::Red     => "Delayed"
212
     * );
213
     * ```
214
     *
215
     * @api
216
     *
217
     * @param string $title  The title of the column. This title will automatically be "slugified" and become the ID
218
     *                       of the column.
219
     * @param string $type   The type of value that this column will use. Either use the available constants in the
220
     *                       PulseColumn class or use the following strings: "date", "person", "status", "text".
221
     * @param array  $labels If the column type will be "status," then this array will be the values for each of the
222
     *                       colors.
223
     *
224
     * @see   PulseColumn::Date    PulseColumn::Date
225
     * @see   PulseColumn::Person  PulseColumn::Person
226
     * @see   PulseColumn::Numeric PulseColumn::Numeric
227
     * @see   PulseColumn::Status  PulseColumn::Status
228
     * @see   PulseColumn::Text    PulseColumn::Text
229
     * @see   PulseColumnStatusValue::Orange  PulseColumnStatusValue::Orange
230
     * @see   PulseColumnStatusValue::L_Green PulseColumnStatusValue::L_Green
231
     * @see   PulseColumnStatusValue::Red     PulseColumnStatusValue::Red
232
     * @see   PulseColumnStatusValue::Blue    PulseColumnStatusValue::Blue
233
     * @see   PulseColumnStatusValue::Purple  PulseColumnStatusValue::Purple
234
     * @see   PulseColumnStatusValue::Grey    PulseColumnStatusValue::Grey
235
     * @see   PulseColumnStatusValue::Green   PulseColumnStatusValue::Green
236
     * @see   PulseColumnStatusValue::L_Blue  PulseColumnStatusValue::L_Blue
237
     * @see   PulseColumnStatusValue::Gold    PulseColumnStatusValue::Gold
238
     * @see   PulseColumnStatusValue::Yellow  PulseColumnStatusValue::Yellow
239
     * @see   PulseColumnStatusValue::Black   PulseColumnStatusValue::Black
240
     *
241
     * @since 0.1.0
242
     *
243
     * @throws ArgumentMismatchException Status definitions were defined yet the type of the column was not a status
244
     *                                   type column
245
     * @throws InvalidArraySizeException The array containing the value of statuses has a key larger than the
246
     *                                   supported 10 indices
247
     *
248
     * @return $this This instance will be updated to have updated information to reflect the new column that was
249
     *               created
250
     */
251
    public function createColumn ($title, $type, $labels = array())
252
    {
253
        if ($type !== PulseColumn::Status && !empty($labels))
254
        {
255
            throw new ArgumentMismatchException("No color definitions are required for a non-color column.");
256
        }
257
258
        if ($type === PulseColumn::Status && count($labels) > 0 && max(array_keys($labels)) > 10)
259
        {
260
            throw new InvalidArraySizeException("The range of status can only be from 0-10.");
261
        }
262
263
        $url        = sprintf("%s/%d/columns.json", self::apiEndpoint(), $this->getId());
264
        $postParams = array(
265
            "title" => $title,
266
            "type"  => $type
267
        );
268
269
        self::setIfNotNullOrEmpty($postParams, "labels", $labels);
270
271
        $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...
272
        $this->assignResults();
273
274
        return $this;
275
    }
276
277
    // =================================================================================================================
278
    //   Group functions
279
    // =================================================================================================================
280
281
    /**
282
     * Get all of the groups belonging to a board.
283
     *
284
     * A group is defined as the colorful headers that split up pulses into categories.
285
     *
286
     * @api
287
     *
288
     * @param bool $showArchived Set to true if you would like to get archived groups in a board as well
0 ignored issues
show
Documentation introduced by
Should the type for parameter $showArchived not be boolean|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...
289
     *
290
     * @since 0.1.0
291
     *
292
     * @return PulseGroup[]
293
     */
294
    public function getGroups ($showArchived = NULL)
295
    {
296
        $url    = sprintf("%s/%d/groups.json", self::apiEndpoint(), $this->getId());
297
        $params = array();
298
299
        self::setIfNotNullOrEmpty($params, "show_archived", $showArchived);
300
301
        return self::fetchAndCastToObjectArray($url, "PulseGroup", $params);
302
    }
303
304
    /**
305
     * Create a new group in a board
306
     *
307
     * @api
308
     *
309
     * @param  string $title The title of the board
310
     *
311
     * @since  0.1.0
312
     *
313
     * @return PulseGroup
314
     */
315
    public function createGroup ($title)
316
    {
317
        $url        = sprintf("%s/%s/groups.json", self::apiEndpoint(), $this->getId());
318
        $postParams = array("title" => $title);
319
320
        // The API doesn't return the board ID, so since we have access to it here: set it manually
321
        $groupResult             = self::sendPost($url, $postParams);
322
        $groupResult["board_id"] = $this->getId();
323
324
        return (new PulseGroup($groupResult));
325
    }
326
327
    /**
328
     * Delete a group from a board
329
     *
330
     * @api
331
     *
332
     * @param string $groupId The group ID to be deleted
333
     *
334
     * @since 0.1.0
335
     */
336
    public function deleteGroup ($groupId)
337
    {
338
        $url = sprintf("%s/%d/groups/%s.json", self::apiEndpoint(), $this->getId(), $groupId);
339
340
        self::sendDelete($url);
341
    }
342
343
    // =================================================================================================================
344
    //   Pulse functions
345
    // =================================================================================================================
346
347
    /**
348
     * @return Pulse[]
349
     */
350
    public function getPulses ()
351
    {
352
        $url    = sprintf("%s/%d/pulses.json", self::apiEndpoint(), $this->getId());
353
        $data   = self::sendGet($url);
354
        $pulses = array();
355
356
        foreach ($data as $entry)
357
        {
358
            $this->pulseInjection($entry);
359
360
            $pulses[] = new Pulse($entry["pulse"]);
361
        }
362
363
        return $pulses;
364
    }
365
366
    /**
367
     * Create a new Pulse inside of this board
368
     *
369
     * Using the $updateText and $announceToAll parameters is the equivalent of using Pulse::createUpdate() after a
370
     * Pulse has been created but with one less API call.
371
     *
372
     * @api
373
     *
374
     * @param string        $name          The name of the Pulse
375
     * @param PulseUser|int $owner         The owner of the Pulse, i.e. who created it
376
     * @param string|null   $groupId       The group to add this Pulse to
377
     * @param string|null   $updateText    The update's text, can contain simple HTML for formatting
378
     * @param bool|null     $announceToAll Determines if the update should be sent to everyone's wall
379
     *
380
     * @since 0.1.0
381
     *
382
     * @return \allejo\DaPulse\Pulse
383
     */
384
    public function createPulse ($name, $owner, $groupId = NULL, $updateText = NULL, $announceToAll = NULL)
385
    {
386
        if ($owner instanceof PulseUser)
387
        {
388
            $owner = $owner->getId();
389
        }
390
391
        $url        = sprintf("%s/%d/pulses.json", self::apiEndpoint(), $this->getId());
392
        $postParams = array(
393
            "user_id" => $owner,
394
            "pulse"   => array(
395
                "name" => $name
396
            )
397
        );
398
399
        self::setIfNotNullOrEmpty($postParams, "group_id", $groupId);
400
        self::setIfNotNullOrEmpty($postParams['update'], 'text', $updateText);
401
        self::setIfNotNullOrEmpty($postParams['update'], 'announcement', $announceToAll);
402
403
        $result = self::sendPost($url, $postParams);
404
        $this->pulseInjection($result);
405
406
        return (new Pulse($result["pulse"]));
407
    }
408
409 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...
410
    {
411
        // Inject some information so a Pulse object can survive on its own
412
        $result["pulse"]["group_id"]          = $result["board_meta"]["group_id"];
413
        $result["pulse"]["column_structure"]  = $this->getColumns();
414
        $result["pulse"]["raw_column_values"] = $result["column_values"];
415
    }
416
417
    // =================================================================================================================
418
    //   Board functions
419
    // =================================================================================================================
420
421 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...
422
    {
423
        $this->checkInvalid();
424
425
        $url = sprintf("%s/%s.json", self::apiEndpoint(), $this->getId());
426
        self::sendDelete($url);
427
428
        $this->deletedObject = true;
429
    }
430
431
    public static function createBoard ($name, $userId, $description = NULL)
432
    {
433
        $url        = sprintf("%s.json", self::apiEndpoint());
434
        $postParams = array(
435
            "user_id" => $userId,
436
            "name"    => $name
437
        );
438
439
        self::setIfNotNullOrEmpty($postParams, "description", $description);
440
441
        $boardResult = self::sendPost($url, $postParams);
442
443
        return (new PulseBoard($boardResult));
444
    }
445
446
    public static function getBoards ($params = array())
447
    {
448
        $url = sprintf("%s.json", self::apiEndpoint());
449
450
        return self::fetchAndCastToObjectArray($url, "PulseBoard", $params);
451
    }
452
}