Completed
Push — master ( a7d441...9e9528 )
by Gareth
03:30
created

API::getClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace garethp\ews;
4
5
use garethp\ews\API\Exception\ExchangeException;
6
use garethp\ews\API\ExchangeWebServices;
7
use garethp\ews\API\ItemUpdateBuilder;
8
use garethp\ews\API\Message\GetServerTimeZonesType;
9
use garethp\ews\API\Message\SyncFolderItemsResponseMessageType;
10
use garethp\ews\API\Message\UpdateItemResponseMessageType;
11
use garethp\ews\API\Type;
12
use garethp\ews\Calendar\CalendarAPI;
13
use garethp\ews\Mail\MailAPI;
14
use garethp\ews\API\FieldURIManager;
15
16
/**
17
 * A base class for APIs
18
 *
19
 * Class BaseAPI
20
 * @package garethp\ews
21
 */
22
class API
23
{
24
    protected static $defaultClientOptions = array(
25
        'version' => ExchangeWebServices::VERSION_2010
26
    );
27
28 31
    public function __construct(ExchangeWebServices $client = null)
29
    {
30 31
        if ($client) {
31 31
            $this->setClient($client);
32 31
        }
33 31
    }
34
35
    /**
36
     * @return Type\EmailAddressType
37
     */
38 23
    public function getPrimarySmtpMailbox()
39
    {
40 23
        return $this->getClient()->getPrimarySmtpMailbox();
41
    }
42
43
    /**
44
     * Storing the API client
45
     * @var ExchangeWebServices
46
     */
47
    private $client;
48
49
    /**
50
     * Get a calendar item
51
     *
52
     * @param string $name
53
     * @return CalendarAPI
54
     */
55 6
    public function getCalendar($name = null)
56
    {
57 6
        $calendar = new CalendarAPI();
58 6
        $calendar->setClient($this->getClient());
59 6
        $calendar->pickCalendar($name);
60
61 6
        return $calendar;
62
    }
63
64
    /**
65
     * @param string $folderName
66
     * @return MailAPI
67
     */
68 6
    public function getMailbox($folderName = null)
69
    {
70 6
        $mailApi = new MailAPI();
71 6
        $mailApi->setClient($this->getClient());
72 6
        $mailApi->pickMailFolder($folderName);
73
74 6
        return $mailApi;
75
    }
76
77
    /**
78
     * Set the API client
79
     *
80
     * @param ExchangeWebServices $client
81
     * @return $this
82
     */
83 31
    public function setClient($client)
84
    {
85 31
        $this->client = $client;
86
87 31
        return $this;
88
    }
89
90
    /**
91
     * Get the API client
92
     *
93
     * @return ExchangeWebServices
94
     */
95 30
    public function getClient()
96
    {
97 30
        return $this->client;
98
    }
99
100 30
    public static function withUsernameAndPassword($server, $username, $password, $options = [])
101
    {
102 30
        return new static(ExchangeWebServices::fromUsernameAndPassword(
103 30
            $server,
104 30
            $username,
105 30
            $password,
106 30
            array_replace_recursive(self::$defaultClientOptions, $options)
107 30
        ));
108
    }
109
110 1
    public static function withCallbackToken($server, $token, $options = [])
111
    {
112 1
        return new static(ExchangeWebServices::fromCallbackToken(
113 1
            $server,
114 1
            $token,
115 1
            array_replace_recursive(self::$defaultClientOptions, $options)
116 1
        ));
117
    }
118
119 1
    public function getPrimarySmptEmailAddress()
120
    {
121 1
        if ($this->getPrimarySmtpMailbox() == null) {
122 1
            return null;
123
        }
124
125 1
        return $this->getPrimarySmtpMailbox()->getEmailAddress();
126
    }
127
128 1
    public function setPrimarySmtpEmailAddress($emailAddress)
129
    {
130 1
        $this->getClient()->setPrimarySmtpEmailAddress($emailAddress);
131
132 1
        return $this;
133
    }
134
135
    /**
136
     * Create items through the API client
137
     *
138
     * @param $items
139
     * @param array $options
140
     * @return Type
141
     */
142 15
    public function createItems($items, $options = array())
143
    {
144 15
        if (!is_array($items)) {
145
            $items = array($items);
146
        }
147
148
        $request = array(
149
            'Items' => $items
150 15
        );
151
152 15
        $request = array_replace_recursive($request, $options);
153 15
        $request = Type::buildFromArray($request);
154
155 15
        $response = $this->getClient()->CreateItem($request);
156
157 15
        return $response;
158
    }
159
160 4
    public function updateItems($items, $options = array())
161
    {
162
        $request = array(
163 4
            'ItemChanges' => $items,
164 4
            'MessageDisposition' => 'SaveOnly',
165
            'ConflictResolution' => 'AlwaysOverwrite'
166 4
        );
167
168 4
        $request = array_replace_recursive($request, $options);
169
170 4
        $request = Type::buildFromArray($request);
171
172 4
        $response = $this->getClient()->UpdateItem($request);
173 4
        if ($response instanceof UpdateItemResponseMessageType) {
0 ignored issues
show
Bug introduced by
The class garethp\ews\API\Message\...ItemResponseMessageType does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
174 4
            return $response->getItems();
175
        }
176
177
        if (!is_array($response)) {
178
            $response = array($response);
179
        }
180
181
        return $response;
182
    }
183
184
    /**
185
     * @param string $itemType
186
     * @param string $uriType
187
     * @param array $changes
188
     * @return array
189
     */
190 4
    protected function buildUpdateItemChanges($itemType, $uriType, $changes)
191
    {
192 4
        return ItemUpdateBuilder::buildUpdateItemChanges($itemType, $uriType, $changes);
193
    }
194
195 2
    public function createFolders($names, Type\FolderIdType $parentFolder, $options = array())
196
    {
197 2
        $request = array('Folders' => array('Folder' => array()));
198 2
        if (!empty($parentFolder)) {
199 2
            $request['ParentFolderId'] = array('FolderId' => $parentFolder->toArray());
200 2
        }
201
202 2
        if (!is_array($names)) {
203 2
            $names = array($names);
204 2
        }
205
206 2
        foreach ($names as $name) {
207 2
            $request['Folders']['Folder'][] = array(
208
                'DisplayName' => $name
209 2
            );
210 2
        }
211
212 2
        $request = array_merge_recursive($request, $options);
213
214 2
        $this->client->CreateFolder($request);
215
216 2
        return true;
217
    }
218
219 2 View Code Duplication
    public function deleteFolder(Type\FolderIdType $folderId, $options = array())
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...
220
    {
221
        $request = array(
222 2
            'DeleteType' => 'HardDelete',
223
            'FolderIds' => array(
224 2
                'FolderId' => $folderId->toArray()
225 2
            )
226 2
        );
227
228 2
        $request = array_merge_recursive($request, $options);
229
230 2
        return $this->client->DeleteFolder($request);
231
    }
232
233 View Code Duplication
    public function moveItem(Type\ItemIdType $itemId, Type\FolderIdType $folderId, $options = array())
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...
234
    {
235
        $request = array(
236
            'ToFolderId' => array('FolderId' => $folderId->toArray()),
237
            'ItemIds' => array('ItemId' => $itemId->toArray())
238
        );
239
240
        $request = array_merge_recursive($request, $options);
241
242
        return $this->client->MoveItem($request);
243
    }
244
245
    /**
246
     * @param $items Type\ItemIdType|Type\ItemIdType[]
247
     * @param array $options
248
     * @return bool
249
     */
250 15
    public function deleteItems($items, $options = array())
251
    {
252 15
        if (!is_array($items) || Type::arrayIsAssoc($items)) {
253 15
            $items = array($items);
254 15
        }
255
256 15
        $itemIds = array();
257 15
        foreach ($items as $item) {
258 15
            if ($item instanceof Type\ItemIdType) {
0 ignored issues
show
Bug introduced by
The class garethp\ews\API\Type\ItemIdType does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
259 14
                $item = $item->toArray();
260 14
            }
261 15
            $item = (array)$item;
262 15
            $itemIds[] = array(
263 15
                'Id' => $item['Id'],
264 15
                'ChangeKey' => $item['ChangeKey']
265 15
            );
266 15
        }
267
268
        $request = array(
269 15
            'ItemIds' => array('ItemId' => $itemIds),
270
            'DeleteType' => 'MoveToDeletedItems'
271 15
        );
272
273 15
        $request = array_replace_recursive($request, $options);
274 15
        $request = Type::buildFromArray($request);
275 15
        $this->getClient()->DeleteItem($request);
276
277
        //If the delete fails, an Exception will be thrown in processResponse before it gets here
278 15
        return true;
279
    }
280
281
    /**
282
     * @param $identifier
283
     * @return Type\BaseFolderType
284
     */
285 22
    public function getFolder($identifier)
286
    {
287
        $request = array(
288
            'FolderShape' => array(
289 22
                'BaseShape' => array('_' => 'Default')
290 22
            ),
291
            'FolderIds' => $identifier
292 22
        );
293 22
        $request = Type::buildFromArray($request);
294
295 22
        $response = $this->getClient()->GetFolder($request);
296
297 22
        return $response;
298
    }
299
300
    /**
301
     * Get a folder by it's distinguishedId
302
     *
303
     * @param string $distinguishedId
304
     * @return Type\BaseFolderType
305
     */
306 22
    public function getFolderByDistinguishedId($distinguishedId)
307
    {
308 22
        return $this->getFolder(array(
309
            'DistinguishedFolderId' => array(
310 22
                'Id' => $distinguishedId,
311 22
                'Mailbox' => $this->getPrimarySmtpMailbox()
312 22
            )
313 22
        ));
314
    }
315
316
    /**
317
     * @param $folderId
318
     * @return Type\BaseFolderType
319
     */
320 4
    public function getFolderByFolderId($folderId)
321
    {
322 4
        return $this->getFolder(array(
323 4
            'FolderId' => array('Id' => $folderId, 'Mailbox' => $this->getPrimarySmtpMailbox())
324 4
        ));
325
    }
326
327
    /**
328
     * @param string|Type\FolderIdType $parentFolderId
329
     * @param array $options
330
     * @return bool|Type\BaseFolderType
331
     */
332 21
    public function getChildrenFolders($parentFolderId = 'root', $options = array())
333
    {
334 21
        if (is_string($parentFolderId)) {
335 15
            $parentFolderId = $this->getFolderByDistinguishedId($parentFolderId)->getFolderId();
0 ignored issues
show
Documentation Bug introduced by
The method getFolderId does not exist on object<garethp\ews\API\Type>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
336 15
        }
337
338
        $request = array(
339 21
            'Traversal' => 'Shallow',
340
            'FolderShape' => array(
341
                'BaseShape' => 'AllProperties'
342 21
            ),
343
            'ParentFolderIds' => array(
344 21
                'FolderId' => $parentFolderId->toArray()
345 21
            )
346 21
        );
347
348 21
        $request = array_replace_recursive($request, $options);
349
350 21
        $request = Type::buildFromArray($request);
351
352
        /** @var \garethp\ews\API\Message\FindFolderResponseMessageType $folders */
353 21
        return $this->getClient()->FindFolder($request);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getClient()->FindFolder($request); (garethp\ews\API\Type) is incompatible with the return type documented by garethp\ews\API::getChildrenFolders of type boolean|garethp\ews\API\Type\BaseFolderType.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
354
355
        return $folders->getFolders();
0 ignored issues
show
Unused Code introduced by
return $folders->getFolders(); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
356
    }
357
358
    /**
359
     * @param string $folderName
360
     * @param string|Type\FolderIdType $parentFolderId
361
     * @param array $options
362
     * @return bool|Type\BaseFolderType
363
     */
364 21
    public function getFolderByDisplayName($folderName, $parentFolderId = 'root', $options = array())
365
    {
366 21
        $folders = $this->getChildrenFolders($parentFolderId, $options);
367
368 21
        foreach ($folders as $folder) {
0 ignored issues
show
Bug introduced by
The expression $folders of type boolean|object<garethp\e...PI\Type\BaseFolderType> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
369 21
            if ($folder->getDisplayName() == $folderName) {
370 20
                return $folder;
371
            }
372 15
        }
373
374 3
        return false;
375
    }
376
377
    /**
378
     * @param $itemId array|Type\ItemIdType
379
     * @param array $options
380
     * @return Type
381
     */
382 5 View Code Duplication
    public function getItem($itemId, $options = array())
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...
383
    {
384 5
        if ($itemId instanceof Type\ItemIdType) {
0 ignored issues
show
Bug introduced by
The class garethp\ews\API\Type\ItemIdType does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
385 4
            $itemId = $itemId->toArray();
386 4
        }
387
388
        $request = array(
389 5
            'ItemShape' => array('BaseShape' => 'AllProperties'),
390 5
            'ItemIds' => array('ItemId' => $itemId)
391 5
        );
392
393 5
        $request = array_replace_recursive($request, $options);
394
395 5
        return $this->getClient()->GetItem($request);
396
    }
397
398
    /**
399
     * Get a list of sync changes on a folder
400
     *
401
     * @param Type\FolderIdType $folderId
402
     * @param null $syncState
403
     * @param array $options
404
     * @return SyncFolderItemsResponseMessageType
405
     */
406 2
    public function listItemChanges($folderId, $syncState = null, $options = array())
407
    {
408
        $request = array(
409 2
            'ItemShape' => array('BaseShape' => 'IdOnly'),
410 2
            'SyncFolderId' => array('FolderId' => $folderId->toXmlObject()),
411 2
            'SyncScope' => 'NormalItems',
412
            'MaxChangesReturned' => '10'
413 2
        );
414
415 2
        if ($syncState != null) {
416 1
            $request['SyncState'] = $syncState;
417 1
            $request['ItemShape']['BaseShape'] = 'AllProperties';
418 1
        }
419
420 2
        $request = array_replace_recursive($request, $options);
421
422 2
        switch ($this->getClient()->getVersion()) {
423 2
            case ExchangeWebServices::VERSION_2007:
424 2
            case ExchangeWebServices::VERSION_2007_SP1:
425 2
            case ExchangeWebServices::VERSION_2007_SP2:
426 2
            case ExchangeWebServices::VERSION_2007_SP3:
427
                unset($request['SyncScope']);
428 2
        }
429
430 2
        $request = Type::buildFromArray($request);
431 2
        $response = $this->getClient()->SyncFolderItems($request);
432
433 2
        return $response;
434
    }
435
436
    public function getServerTimezones($timezoneIDs = array(), $fullTimezoneData = false)
437
    {
438
        $request = GetServerTimeZonesType::buildFromArray(array(
439
            'returnFullTimeZoneData' => $fullTimezoneData
440
        ));
441
442
        if (!empty($timezoneIDs)) {
443
            $request->setIds($timezoneIDs);
444
        }
445
446
        $timezones = $this->getClient()->GetServerTimeZones($request);
447
        $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...
448
449
        if (!is_array($timezones)) {
450
            $timezones = array($timezones);
451
        }
452
453
        return $timezones;
454
    }
455
456
    /**
457
     * @param Type\ItemIdType $itemId
458
     * @param $fromType
459
     * @param $destinationType
460
     * @param $mailbox
461
     *
462
     * @return Type\ItemIdType
463
     */
464
    public function convertIdFormat(Type\ItemIdType $itemId, $fromType, $destinationType, $mailbox)
465
    {
466
        $result = $this->getClient()->ConvertId(array(
467
            'DestinationFormat' => $destinationType,
468
            'SourceIds' => array(
469
                'AlternateId' => array(
470
                    'Format' => $fromType,
471
                    'Id' => $itemId->getId(),
472
                    'Mailbox' => $mailbox
473
                )
474
            )
475
        ));
476
477
        $itemId->setId($result->getId());
0 ignored issues
show
Documentation Bug introduced by
The method getId does not exist on object<garethp\ews\API\Type>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
478
479
        return $itemId;
480
    }
481
}
482