Completed
Push — master ( e11a9c...c41b0b )
by Gareth
02:56
created

API::getChildrenFolders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 12

Duplication

Lines 23
Ratio 100 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 23
loc 23
ccs 12
cts 12
cp 1
rs 9.0856
cc 2
eloc 12
nc 2
nop 2
crap 2
1
<?php
2
3
namespace garethp\ews;
4
5
use garethp\ews\API\ExchangeWebServices;
6
use garethp\ews\API\Message\EmptyFolderResponseType;
7
use garethp\ews\API\Message\GetServerTimeZonesType;
8
use garethp\ews\API\Message\SyncFolderItemsResponseMessageType;
9
use garethp\ews\API\Message\UpdateItemResponseMessageType;
10
use garethp\ews\API\Type;
11
12
/**
13
 * A base class for APIs
14
 *
15
 * Class BaseAPI
16
 * @package garethp\ews
17
 */
18
class API
19
{
20
    protected static $defaultClientOptions = array(
21
        'version' => ExchangeWebServices::VERSION_2010
22
    );
23
24 34
    public function __construct(ExchangeWebServices $client = null)
25
    {
26 34
        if ($client) {
27 34
            $this->setClient($client);
28 34
        }
29 34
    }
30
31
    /**
32
     * @return Type\EmailAddressType
33
     */
34 26
    public function getPrimarySmtpMailbox()
35
    {
36 26
        return $this->getClient()->getPrimarySmtpMailbox();
37
    }
38
39
    /**
40
     * Storing the API client
41
     * @var ExchangeWebServices
42
     */
43
    private $client;
44
45
    /**
46
     * Get a calendar item
47
     *
48
     * @param string $name
49
     * @return CalendarAPI
50
     */
51 6
    public function getCalendar($name = null)
52
    {
53 6
        $calendar = new CalendarAPI();
54 6
        $calendar->setClient($this->getClient());
55 6
        $calendar->pickCalendar($name);
56
57 6
        return $calendar;
58
    }
59
60
    /**
61
     * @param string $folderName
62
     * @return MailAPI
63
     */
64 6
    public function getMailbox($folderName = null)
65
    {
66 6
        $mailApi = new MailAPI();
67 6
        $mailApi->setClient($this->getClient());
68 6
        $mailApi->pickMailFolder($folderName);
69
70 6
        return $mailApi;
71
    }
72
73
    /**
74
     * Set the API client
75
     *
76
     * @param ExchangeWebServices $client
77
     * @return $this
78
     */
79 34
    public function setClient($client)
80
    {
81 34
        $this->client = $client;
82
83 34
        return $this;
84
    }
85
86
    /**
87
     * Get the API client
88
     *
89
     * @return ExchangeWebServices
90
     */
91 33
    public function getClient()
92
    {
93 33
        return $this->client;
94
    }
95
96 33
    public static function withUsernameAndPassword($server, $username, $password, $options = [])
97
    {
98 33
        return new static(ExchangeWebServices::fromUsernameAndPassword(
99 33
            $server,
100 33
            $username,
101 33
            $password,
102 33
            array_replace_recursive(self::$defaultClientOptions, $options)
103 33
        ));
104
    }
105
106 1
    public static function withCallbackToken($server, $token, $options = [])
107
    {
108 1
        return new static(ExchangeWebServices::fromCallbackToken(
109 1
            $server,
110 1
            $token,
111 1
            array_replace_recursive(self::$defaultClientOptions, $options)
112 1
        ));
113
    }
114
115 1
    public function getPrimarySmptEmailAddress()
116
    {
117 1
        if ($this->getPrimarySmtpMailbox() == null) {
118 1
            return null;
119
        }
120
121 1
        return $this->getPrimarySmtpMailbox()->getEmailAddress();
122
    }
123
124 1
    public function setPrimarySmtpEmailAddress($emailAddress)
125
    {
126 1
        $this->getClient()->setPrimarySmtpEmailAddress($emailAddress);
127
128 1
        return $this;
129
    }
130
131
    /**
132
     * Create items through the API client
133
     *
134
     * @param $items
135
     * @param array $options
136
     * @return Type
137
     */
138 16
    public function createItems($items, $options = array())
139
    {
140 16
        $items = Utilities\ensureIsArray($items);
141
        $request = array(
142
            'Items' => $items
143 16
        );
144
145 16
        $request = array_replace_recursive($request, $options);
146 16
        $request = Type::buildFromArray($request);
147
148 16
        $response = $this->getClient()->CreateItem($request);
149
150 16
        return $response;
151
    }
152
153 4
    public function updateItems($items, $options = array())
154
    {
155
        $request = array(
156 4
            'ItemChanges' => $items,
157 4
            'MessageDisposition' => 'SaveOnly',
158
            'ConflictResolution' => 'AlwaysOverwrite'
159 4
        );
160
161 4
        $request = array_replace_recursive($request, $options);
162
163 4
        $request = Type::buildFromArray($request);
164
165 4
        $response = $this->getClient()->UpdateItem($request);
166 4
        if ($response instanceof UpdateItemResponseMessageType) {
167 4
            return $response->getItems();
168
        }
169
170
        return Utilities\ensureIsArray($response);
171
    }
172
173 1 View Code Duplication
    public function createCalendars($names, Type\FolderIdType $parentFolder = null, $options = array())
174
    {
175 1
        if ($parentFolder == null) {
176 1
            $parentFolder = $this->getFolderByDistinguishedId('calendar')->getFolderId();
177 1
        }
178
179 1
        $names = Utilities\ensureIsArray($names);
180
181
        $names = array_map(function ($name) {
182
            return array(
183 1
                'DisplayName' => $name,
184
                'FolderClass' => 'IPF.Appointment'
185 1
            );
186 1
        }, $names);
187
188
        $request = [
189 1
            'Folders' => ['Folder' => $names],
190 1
            'ParentFolderId' => ['FolderId' => $parentFolder->toArray()]
191 1
        ];
192
193 1
        $request = array_merge_recursive($request, $options);
194
195 1
        $this->client->CreateFolder($request);
196 1
        return true;
197
    }
198
    
199 View Code Duplication
    public function createContactsFolder($names, Type\FolderIdType $parentFolder = null, $options = array())
200
    {
201
        if ($parentFolder == null) {
202
            $parentFolder = $this->getFolderByDistinguishedId('contacts')->getFolderId();
203
        }
204
205
        $names = Utilities\ensureIsArray($names);
206
        $names = array_map(function ($name) {
207
            return array(
208
                'DisplayName' => $name,
209
                'FolderClass' => 'IPF.Contact'
210
            );
211
        }, $names);
212
213
        $request = [
214
            'Folders' => ['Folder' => $names],
215
            'ParentFolderId' => ['FolderId' => $parentFolder->toArray()]
216
        ];
217
218
        $request = array_merge_recursive($request, $options);
219
220
        $this->client->CreateFolder($request);
221
        return true;
222
    }
223
224 3
    public function createFolders($names, Type\FolderIdType $parentFolder, $options = array())
225
    {
226 3
        $names = Utilities\ensureIsArray($names);
227
        $names = array_map(function ($name) {
228 3
            return ['DisplayName' => $name];
229 3
        }, $names);
230
231
        $request = [
232 3
            'Folders' => ['Folder' => $names]
233 3
        ];
234
235 3
        if (!empty($parentFolder)) {
236 3
            $request['ParentFolderId'] = array('FolderId' => $parentFolder->toArray());
237 3
        }
238
239 3
        $request = array_merge_recursive($request, $options);
240
241 3
        $this->client->CreateFolder($request);
242
243 3
        return true;
244
    }
245
246
    /**
247
     * @deprecated Please use API::deleteFolders() instead
248
     *
249
     * @param Type\FolderIdType $folderId
250
     * @param array $options
251
     * @return Type
252
     */
253
    public function deleteFolder(Type\FolderIdType $folderId, $options = array())
254
    {
255
        return $this->deleteFolders($folderId, $options);
256
    }
257
258 4
    public function deleteFolders($folders, $options = array())
259
    {
260 4
        $folders = Utilities\ensureIsArray($folders);
261
262
        $folderIds = array_map(function ($folderId) {
263 4
            return $folderId->toArray();
264 4
        }, $folders);
265
266
        $request = [
267 4
            'DeleteType' => 'HardDelete',
268
            'FolderIds' => array(
269
                'FolderId' => $folderIds
270 4
            )
271 4
        ];
272
273 4
        $request = array_merge_recursive($request, $options);
274 4
        return $this->client->DeleteFolder($request);
275
    }
276
277
    public function moveItem(Type\ItemIdType $itemId, Type\FolderIdType $folderId, $options = array())
278
    {
279
        $request = array(
280
            'ToFolderId' => array('FolderId' => $folderId->toArray()),
281
            'ItemIds' => array('ItemId' => $itemId->toArray())
282
        );
283
284
        $request = array_merge_recursive($request, $options);
285
286
        return $this->client->MoveItem($request);
287
    }
288
289
    /**
290
     * @param $items Type\ItemIdType|Type\ItemIdType[]
291
     * @param array $options
292
     * @return bool
293
     */
294 16
    public function deleteItems($items, $options = array())
295
    {
296 16
        $items = Utilities\ensureIsArray($items);
297
298 16
        $items = array_map(function ($item) {
299 16
            $item = Type\ItemIdType::buildFromArray($item);
300
301 16
            return $item->toArray();
302 16
        }, $items);
303
304
        $request = array(
305 16
            'ItemIds' => array('ItemId' => $items),
306
            'DeleteType' => 'MoveToDeletedItems'
307 16
        );
308
309 16
        $request = array_replace_recursive($request, $options);
310 16
        $request = Type::buildFromArray($request);
311 16
        $this->getClient()->DeleteItem($request);
312
313
        //If the delete fails, an Exception will be thrown in processResponse before it gets here
314 16
        return true;
315
    }
316
317
    /**
318
     * @param $identifier
319
     * @return Type\BaseFolderType
320
     */
321 25
    public function getFolder($identifier)
322
    {
323
        $request = array(
324
            'FolderShape' => array(
325 25
                'BaseShape' => array('_' => 'Default')
326 25
            ),
327
            'FolderIds' => $identifier
328 25
        );
329 25
        $request = Type::buildFromArray($request);
330
331 25
        $response = $this->getClient()->GetFolder($request);
332
333 25
        return $response;
334
    }
335
336
    /**
337
     * Get a folder by it's distinguishedId
338
     *
339
     * @param string $distinguishedId
340
     * @return Type\BaseFolderType
341
     */
342 25
    public function getFolderByDistinguishedId($distinguishedId)
343
    {
344 25
        return $this->getFolder(array(
345
            'DistinguishedFolderId' => array(
346 25
                'Id' => $distinguishedId,
347 25
                'Mailbox' => $this->getPrimarySmtpMailbox()
348 25
            )
349 25
        ));
350
    }
351
352
    /**
353
     * @param $folderId
354
     * @return Type\BaseFolderType
355
     */
356 4
    public function getFolderByFolderId($folderId)
357
    {
358 4
        return $this->getFolder(array(
359 4
            'FolderId' => array('Id' => $folderId, 'Mailbox' => $this->getPrimarySmtpMailbox())
360 4
        ));
361
    }
362
363
    /**
364
     * @param string|Type\FolderIdType $parentFolderId
365
     * @param array $options
366
     * @return Type\BaseFolderType[]
367
     */
368 24 View Code Duplication
    public function getChildrenFolders($parentFolderId = 'root', $options = array())
369
    {
370 24
        if (is_string($parentFolderId)) {
371 16
            $parentFolderId = $this->getFolderByDistinguishedId($parentFolderId)->getFolderId();
372 16
        }
373
374
        $request = array(
375 24
            'Traversal' => 'Shallow',
376
            'FolderShape' => array(
377
                'BaseShape' => 'AllProperties'
378 24
            ),
379
            'ParentFolderIds' => array(
380 24
                'FolderId' => $parentFolderId->toArray()
381 24
            )
382 24
        );
383
384 24
        $request = array_replace_recursive($request, $options);
385
386 24
        $request = Type::buildFromArray($request);
387
388
        /** @var \garethp\ews\API\Message\FindFolderResponseMessageType $folders */
389 24
        return $this->getClient()->FindFolder($request);
390
    }
391
392
    /**
393
     * @param string $folderName
394
     * @param string|Type\FolderIdType $parentFolderId
395
     * @param array $options
396
     * @return bool|Type\BaseFolderType
397
     */
398 24
    public function getFolderByDisplayName($folderName, $parentFolderId = 'root', $options = array())
399
    {
400 24
        $folders = $this->getChildrenFolders($parentFolderId, $options);
401
402 24
        foreach ($folders as $folder) {
0 ignored issues
show
Bug introduced by
The expression $folders of type object<garethp\ews\API\Type> is not traversable.
Loading history...
403 24
            if ($folder->getDisplayName() == $folderName) {
404 23
                return $folder;
405
            }
406 17
        }
407
408 4
        return false;
409
    }
410
411
    /**
412
     * @param $itemId array|Type\ItemIdType
413
     * @param array $options
414
     * @return Type
415
     */
416 5 View Code Duplication
    public function getItem($itemId, $options = array())
417
    {
418 5
        if ($itemId instanceof Type\ItemIdType) {
419 4
            $itemId = $itemId->toArray();
420 4
        }
421
422
        $request = array(
423 5
            'ItemShape' => array('BaseShape' => 'AllProperties'),
424 5
            'ItemIds' => array('ItemId' => $itemId)
425 5
        );
426
427 5
        $request = array_replace_recursive($request, $options);
428
429 5
        return $this->getClient()->GetItem($request);
430
    }
431
432
    /**
433
     * Get a list of sync changes on a folder
434
     *
435
     * @param Type\FolderIdType $folderId
436
     * @param null $syncState
437
     * @param array $options
438
     * @return SyncFolderItemsResponseMessageType
439
     */
440 2
    public function listItemChanges($folderId, $syncState = null, $options = array())
441
    {
442
        $request = array(
443 2
            'ItemShape' => array('BaseShape' => 'AllProperties'),
444 2
            'SyncFolderId' => array('FolderId' => $folderId->toXmlObject()),
445 2
            'SyncScope' => 'NormalItems',
446
            'MaxChangesReturned' => '100'
447 2
        );
448
449 2
        if ($syncState != null) {
450 1
            $request['SyncState'] = $syncState;
451 1
            $request['ItemShape']['BaseShape'] = 'AllProperties';
452 1
        }
453
454 2
        $request = array_replace_recursive($request, $options);
455
456 2
        $request = Type::buildFromArray($request);
457 2
        $response = $this->getClient()->SyncFolderItems($request);
458
459 2
        return $response;
460
    }
461
462
    public function getServerTimezones($timezoneIDs = array(), $fullTimezoneData = false)
463
    {
464
        $request = GetServerTimeZonesType::buildFromArray(array(
465
            'returnFullTimeZoneData' => $fullTimezoneData
466
        ));
467
468
        if (!empty($timezoneIDs)) {
469
            $request->setIds($timezoneIDs);
470
        }
471
472
        $timezones = $this->getClient()->GetServerTimeZones($request);
473
        $timezones = $timezones->TimeZoneDefinition;
0 ignored issues
show
Documentation introduced by
The property TimeZoneDefinition does not exist on object<garethp\ews\API\Type>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
474
475
        return Utilities\ensureIsArray($timezones);
476
    }
477
478
    /**
479
     * @param Type\ItemIdType $itemId
480
     * @param $fromType
481
     * @param $destinationType
482
     * @param $mailbox
483
     *
484
     * @return Type\ItemIdType
485
     */
486
    public function convertIdFormat(Type\ItemIdType $itemId, $fromType, $destinationType, $mailbox)
487
    {
488
        $result = $this->getClient()->ConvertId(array(
489
            'DestinationFormat' => $destinationType,
490
            'SourceIds' => array(
491
                'AlternateId' => array(
492
                    'Format' => $fromType,
493
                    'Id' => $itemId->getId(),
494
                    'Mailbox' => $mailbox
495
                )
496
            )
497
        ));
498
499
        $itemId->setId($result->getId());
500
501
        return $itemId;
502
    }
503
504
    /**
505
     * @param Type\FindItemParentType|Type\FindFolderParentType $result
506
     *
507
     * @return Type\FindItemParentType|Type\FindFolderParentType
508
     */
509 2
    public function getNextPage($result)
510
    {
511 2
        if ($result->isIncludesLastItemInRange()) {
512
            return $result;
513
        }
514
515 2
        $currentPage = $result->getCurrentPage();
516 2
        $currentPage->setOffset($result->getIndexedPagingOffset());
517
518 2
        $lastRequest = $result->getLastRequest();
519 2
        $lastRequest->setIndexedPage($currentPage);
520
521 2
        if ($result instanceof Type\FindFolderParentType) {
522 1
            return $this->getClient()->FindFolder($lastRequest);
523
        }
524
525 1
        return $this->getClient()->FindItem($lastRequest);
526
    }
527
528
    /**
529
     * @param Type\FolderIdType $folderId
530
     * @param string $deleteType
531
     * @param bool $deleteSubFolders
532
     * @param array $options
533
     * @return EmptyFolderResponseType
534
     */
535
    public function emptyFolder(
536
        Type\FolderIdType $folderId,
537
        $deleteType = 'SoftDelete',
538
        $deleteSubFolders = false,
539
        array $options = []
540
    ) {
541
        $request = [
542
            'DeleteType' => $deleteType,
543
            'DeleteSubFolders' => $deleteSubFolders,
544
            'FolderIds' => ['FolderId' => $folderId->toArray()]
545
        ];
546
547
        $request = array_merge_recursive($request, $options);
548
549
        return $this->getClient()->EmptyFolder($request);
550
    }
551
}
552