Passed
Pull Request — master (#249)
by
unknown
08:39
created

API::getFolderByDisplayName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3

Importance

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

509
        $itemId->setId($result->/** @scrutinizer ignore-call */ getId());
Loading history...
510
511
        return $itemId;
512
    }
513
514
    /**
515
     * @param Type\FindItemParentType|Type\FindFolderParentType $result
516
     *
517
     * @return Type\FindItemParentType|Type\FindFolderParentType
518
     */
519
    public function getNextPage($result)
520
    {
521
        if ($result->isIncludesLastItemInRange()) {
522
            return $result;
523
        }
524
525
        $currentPage = $result->getCurrentPage();
526
        $currentPage->setOffset($result->getIndexedPagingOffset());
527
528
        $lastRequest = $result->getLastRequest();
529
        $lastRequest->setIndexedPage($currentPage);
530
531 18
        if ($result instanceof Type\FindFolderParentType) {
532
            return $this->getClient()->FindFolder($lastRequest);
533 18
        }
534
535
        return $this->getClient()->FindItem($lastRequest);
536 18
    }
537
538
    /**
539
     * @param BaseFolderIdType $folderId
540
     * @param string $deleteType
541
     * @param bool $deleteSubFolders
542
     * @param array $options
543
     * @return EmptyFolderResponseType
544
     */
545
    public function emptyFolder(
546
        BaseFolderIdType $folderId,
547
        $deleteType = 'SoftDelete',
548
        $deleteSubFolders = false,
549
        array $options = []
550
    ) {
551
        $request = [
552
            'DeleteType' => $deleteType,
553
            'DeleteSubFolders' => $deleteSubFolders,
554
            'FolderIds' => $folderId->toArray(true)
555
        ];
556
557
        $request = array_merge_recursive($request, $options);
558
559
        return $this->getClient()->EmptyFolder($request);
560
    }
561
562
    protected function getDistinguishedFolderId($id = null, $changeKey = null)
563
    {
564
        return new Type\DistinguishedFolderIdType(
565
            $id,
566
            $changeKey,
567
            $this->getPrimarySmtpMailbox()
568
        );
569
    }
570
}
571