1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Helix\Asana\Base\AbstractEntity; |
4
|
|
|
|
5
|
|
|
use Helix\Asana\Api\AsanaError; |
6
|
|
|
use Helix\Asana\Base\AbstractEntity; |
7
|
|
|
use Helix\Asana\Event; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Adds event syncing to entities. |
11
|
|
|
* |
12
|
|
|
* @mixin AbstractEntity |
13
|
|
|
*/ |
14
|
|
|
trait SyncTrait { |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Polls for new events. |
18
|
|
|
* |
19
|
|
|
* > :info: |
20
|
|
|
* > If the given token is `null` then this method catches Asana's `412` and returns an empty array. |
21
|
|
|
* |
22
|
|
|
* @see https://developers.asana.com/docs/get-events-on-a-resource |
23
|
|
|
* |
24
|
|
|
* @param null|string $token Updated to the new token. |
25
|
|
|
* @return Event[] |
26
|
|
|
*/ |
27
|
|
|
public function getEvents (?string &$token) { |
28
|
|
|
try { |
29
|
|
|
/** @var array $remote Asana throws 400 for missing entities. */ |
30
|
|
|
$remote = $this->api->call('GET', 'events?' . http_build_query([ |
31
|
|
|
'resource' => $this->getGid(), |
32
|
|
|
'sync' => $token, |
33
|
|
|
'opt_expand' => 'this' |
34
|
|
|
])); |
35
|
|
|
} |
36
|
|
|
catch (AsanaError $error) { |
37
|
|
|
if ($error->is(412)) { |
38
|
|
|
$remote = $error->asResponse(); |
39
|
|
|
if (!isset($token)) { |
40
|
|
|
// Asana says: "The response will be the same as for an expired sync token." |
41
|
|
|
// The caller knowingly gave a null token, so we don't need to rethrow. |
42
|
|
|
$token = $remote['sync']; |
43
|
|
|
return []; |
44
|
|
|
} |
45
|
|
|
// Token expired. Update and rethrow. |
46
|
|
|
$token = $remote['sync']; |
47
|
|
|
} |
48
|
|
|
throw $error; |
49
|
|
|
} |
50
|
|
|
$token = $remote['sync']; |
51
|
|
|
$events = array_map(function(array $each) { |
52
|
|
|
/** @var AbstractEntity $that */ |
53
|
|
|
$that = $this; |
54
|
|
|
return $this->api->factory($that, Event::class, $each); |
55
|
|
|
}, $remote['data']); |
56
|
|
|
usort($events, function(Event $a, Event $b) { |
57
|
|
|
return $a->getCreatedAt() <=> $b->getCreatedAt(); |
58
|
|
|
}); |
59
|
|
|
return $events; |
60
|
|
|
} |
61
|
|
|
} |