Completed
Push — master ( a4eb35...650999 )
by Gareth
03:22
created

API::getMailbox()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1.008

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
ccs 4
cts 5
cp 0.8
rs 9.4285
cc 1
eloc 5
nc 1
nop 1
crap 1.008
1
<?php
2
3
namespace garethp\ews;
4
5
use garethp\ews\API\Enumeration\DisposalType;
6
use garethp\ews\API\Enumeration\IndexBasePointType;
7
use garethp\ews\API\ExchangeWebServices;
8
use garethp\ews\API\ItemUpdateBuilder;
9
use garethp\ews\API\Message\GetServerTimeZonesType;
10
use garethp\ews\API\Message\SyncFolderItemsResponseMessageType;
11
use garethp\ews\API\Message\UpdateItemResponseMessageType;
12
use garethp\ews\API\Type;
13
use garethp\ews\CalendarAPI;
14
use garethp\ews\MailAPI;
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 33
    public function __construct(ExchangeWebServices $client = null)
29
    {
30 33
        if ($client) {
31 33
            $this->setClient($client);
32 33
        }
33 33
    }
34
35
    /**
36
     * @return Type\EmailAddressType
37
     */
38 25
    public function getPrimarySmtpMailbox()
39
    {
40 25
        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
        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
        return $mailApi;
75
    }
76
77
    /**
78
     * Set the API client
79
     *
80
     * @param ExchangeWebServices $client
81
     * @return $this
82
     */
83 33
    public function setClient($client)
84
    {
85 33
        $this->client = $client;
86
87 33
        return $this;
88
    }
89
90
    /**
91
     * Get the API client
92
     *
93
     * @return ExchangeWebServices
94
     */
95 32
    public function getClient()
96
    {
97 32
        return $this->client;
98
    }
99
100 32
    public static function withUsernameAndPassword($server, $username, $password, $options = [])
101
    {
102 32
        return new static(ExchangeWebServices::fromUsernameAndPassword(
103 32
            $server,
104 32
            $username,
105 32
            $password,
106 32
            array_replace_recursive(self::$defaultClientOptions, $options)
107 32
        ));
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 4
    public function createItems($items, $options = array())
143
    {
144 4
        if (!is_array($items)) {
145
            $items = array($items);
146
        }
147
148
        $request = array(
149
            'Items' => $items
150 4
        );
151
152 4
        $request = array_replace_recursive($request, $options);
153 4
        $request = Type::buildFromArray($request);
154
155 4
        $response = $this->getClient()->CreateItem($request);
156
157
        return $response;
158
    }
159
160
    public function updateItems($items, $options = array())
161
    {
162
        $request = array(
163
            'ItemChanges' => $items,
164
            'MessageDisposition' => 'SaveOnly',
165
            'ConflictResolution' => 'AlwaysOverwrite'
166
        );
167
168
        $request = array_replace_recursive($request, $options);
169
170
        $request = Type::buildFromArray($request);
171
172
        $response = $this->getClient()->UpdateItem($request);
173
        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
            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
    protected function buildUpdateItemChanges($itemType, $uriType, $changes)
191
    {
192
        return ItemUpdateBuilder::buildUpdateItemChanges($itemType, $uriType, $changes);
193
    }
194
195
    public function createCalendars($names, Type\FolderIdType $parentFolder = null, $options = array())
196
    {
197
        if ($parentFolder == null) {
198
            $parentFolder = $this->getFolderByDistinguishedId('calendar')->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...
199
        }
200
201
        $request = array('Folders' => array('Folder' => array()));
202
        if (!empty($parentFolder)) {
203
            $request['ParentFolderId'] = array('FolderId' => $parentFolder->toArray());
204
        }
205
206
        if (!is_array($names)) {
207
            $names = array($names);
208
        }
209
210
        foreach ($names as $name) {
211
            $request['Folders']['Folder'][] = array(
212
                'DisplayName' => $name,
213
                'FolderClass' => 'IPF.Appointment'
214
            );
215
        }
216
217
        $request = array_merge_recursive($request, $options);
218
219
        $this->client->CreateFolder($request);
220
221
        return true;
222
    }
223
224
    public function createFolders($names, Type\FolderIdType $parentFolder, $options = array())
225
    {
226
        $request = array('Folders' => array('Folder' => array()));
227
        if (!empty($parentFolder)) {
228
            $request['ParentFolderId'] = array('FolderId' => $parentFolder->toArray());
229
        }
230
231
        if (!is_array($names)) {
232
            $names = array($names);
233
        }
234
235
        foreach ($names as $name) {
236
            $request['Folders']['Folder'][] = array(
237
                'DisplayName' => $name
238
            );
239
        }
240
241
        $request = array_merge_recursive($request, $options);
242
243
        $this->client->CreateFolder($request);
244
245
        return true;
246
    }
247
248 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...
249
    {
250
        $request = array(
251
            'DeleteType' => 'HardDelete',
252
            'FolderIds' => array(
253
                'FolderId' => $folderId->toArray()
254
            )
255
        );
256
257
        $request = array_merge_recursive($request, $options);
258
259
        return $this->client->DeleteFolder($request);
260
    }
261
262 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...
263
    {
264
        $request = array(
265
            'ToFolderId' => array('FolderId' => $folderId->toArray()),
266
            'ItemIds' => array('ItemId' => $itemId->toArray())
267
        );
268
269
        $request = array_merge_recursive($request, $options);
270
271
        return $this->client->MoveItem($request);
272
    }
273
274
    /**
275
     * @param        $items Type\ItemIdType|Type\ItemIdType[]
276
     * @param array  $options
277
     * @return bool
278
     */
279
    public function deleteItems($items, $options = array())
280
    {
281
        if (!is_array($items) || Type::arrayIsAssoc($items)) {
282
            $items = array($items);
283
        }
284
285
        $itemIds = array();
286
        foreach ($items as $item) {
287
            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...
288
                $item = $item->toArray();
289
            }
290
            $item = (array)$item;
291
            $itemIds[] = array(
292
                'Id' => $item['Id'],
293
                'ChangeKey' => $item['ChangeKey']
294
            );
295
        }
296
297
        $request = array(
298
            'ItemIds' => array('ItemId' => $itemIds),
299
            'DeleteType' => 'MoveToDeletedItems'
300
        );
301
302
        $request = array_replace_recursive($request, $options);
303
        $request = Type::buildFromArray($request);
304
        $this->getClient()->DeleteItem($request);
305
306
        //If the delete fails, an Exception will be thrown in processResponse before it gets here
307
        return true;
308
    }
309
310
    /**
311
     * @param $identifier
312
     * @return Type\BaseFolderType
313
     */
314 24
    public function getFolder($identifier)
315
    {
316
        $request = array(
317
            'FolderShape' => array(
318 24
                'BaseShape' => array('_' => 'Default')
319 24
            ),
320
            'FolderIds' => $identifier
321 24
        );
322 24
        $request = Type::buildFromArray($request);
323
324 24
        $response = $this->getClient()->GetFolder($request);
325
326
        return $response;
327
    }
328
329
    /**
330
     * Get a folder by it's distinguishedId
331
     *
332
     * @param string $distinguishedId
333
     * @return Type\BaseFolderType
334
     */
335 24
    public function getFolderByDistinguishedId($distinguishedId)
336
    {
337 24
        return $this->getFolder(array(
338
            'DistinguishedFolderId' => array(
339 24
                'Id' => $distinguishedId,
340 24
                'Mailbox' => $this->getPrimarySmtpMailbox()
341 24
            )
342 24
        ));
343
    }
344
345
    /**
346
     * @param $folderId
347
     * @return Type\BaseFolderType
348
     */
349
    public function getFolderByFolderId($folderId)
350
    {
351
        return $this->getFolder(array(
352
            'FolderId' => array('Id' => $folderId, 'Mailbox' => $this->getPrimarySmtpMailbox())
353
        ));
354
    }
355
356
    /**
357
     * @param string|Type\FolderIdType $parentFolderId
358
     * @param array $options
359
     * @return bool|Type\BaseFolderType
360
     */
361 15
    public function getChildrenFolders($parentFolderId = 'root', $options = array())
362
    {
363 15
        if (is_string($parentFolderId)) {
364 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...
365
        }
366
367
        $request = array(
368
            'Traversal' => 'Shallow',
369
            'FolderShape' => array(
370
                'BaseShape' => 'AllProperties'
371
            ),
372
            'ParentFolderIds' => array(
373
                'FolderId' => $parentFolderId->toArray()
374
            )
375
        );
376
377
        $request = array_replace_recursive($request, $options);
378
379
        $request = Type::buildFromArray($request);
380
381
        /** @var \garethp\ews\API\Message\FindFolderResponseMessageType $folders */
382
        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...
383
384
        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...
385
    }
386
387
    /**
388
     * @param string $folderName
389
     * @param string|Type\FolderIdType $parentFolderId
390
     * @param array $options
391
     * @return bool|Type\BaseFolderType
392
     */
393 15
    public function getFolderByDisplayName($folderName, $parentFolderId = 'root', $options = array())
394
    {
395 15
        $folders = $this->getChildrenFolders($parentFolderId, $options);
396
397
        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...
398
            if ($folder->getDisplayName() == $folderName) {
399
                return $folder;
400
            }
401
        }
402
403
        return false;
404
    }
405
406
    /**
407
     * @param $itemId array|Type\ItemIdType
408
     * @param array $options
409
     * @return Type
410
     */
411 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...
412
    {
413
        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...
414
            $itemId = $itemId->toArray();
415
        }
416
417
        $request = array(
418
            'ItemShape' => array('BaseShape' => 'AllProperties'),
419
            'ItemIds' => array('ItemId' => $itemId)
420
        );
421
422
        $request = array_replace_recursive($request, $options);
423
424
        return $this->getClient()->GetItem($request);
425
    }
426
427
    /**
428
     * Get a list of sync changes on a folder
429
     *
430
     * @param Type\FolderIdType $folderId
431
     * @param null $syncState
432
     * @param array $options
433
     * @return SyncFolderItemsResponseMessageType
434
     */
435
    public function listItemChanges($folderId, $syncState = null, $options = array())
436
    {
437
        $request = array(
438
            'ItemShape' => array('BaseShape' => 'IdOnly'),
439
            'SyncFolderId' => array('FolderId' => $folderId->toXmlObject()),
440
            'SyncScope' => 'NormalItems',
441
            'MaxChangesReturned' => '100'
442
        );
443
444
        if ($syncState != null) {
445
            $request['SyncState'] = $syncState;
446
            $request['ItemShape']['BaseShape'] = 'AllProperties';
447
        }
448
449
        $request = array_replace_recursive($request, $options);
450
451
        $request = Type::buildFromArray($request);
452
        $response = $this->getClient()->SyncFolderItems($request);
453
454
        return $response;
455
    }
456
457
    public function getServerTimezones($timezoneIDs = array(), $fullTimezoneData = false)
458
    {
459
        $request = GetServerTimeZonesType::buildFromArray(array(
460
            'returnFullTimeZoneData' => $fullTimezoneData
461
        ));
462
463
        if (!empty($timezoneIDs)) {
464
            $request->setIds($timezoneIDs);
465
        }
466
467
        $timezones = $this->getClient()->GetServerTimeZones($request);
468
        $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...
469
470
        if (!is_array($timezones)) {
471
            $timezones = array($timezones);
472
        }
473
474
        return $timezones;
475
    }
476
477
    /**
478
     * @param Type\ItemIdType $itemId
479
     * @param $fromType
480
     * @param $destinationType
481
     * @param $mailbox
482
     *
483
     * @return Type\ItemIdType
484
     */
485
    public function convertIdFormat(Type\ItemIdType $itemId, $fromType, $destinationType, $mailbox)
486
    {
487
        $result = $this->getClient()->ConvertId(array(
488
            'DestinationFormat' => $destinationType,
489
            'SourceIds' => array(
490
                'AlternateId' => array(
491
                    'Format' => $fromType,
492
                    'Id' => $itemId->getId(),
493
                    'Mailbox' => $mailbox
494
                )
495
            )
496
        ));
497
498
        $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...
499
500
        return $itemId;
501
    }
502
503
    /**
504
     * @param Type\FindItemParentType | Type\FindFolderParentType $result
505
     *
506
     * @return Type\FindItemParentType | Type\FindFolderParentType
507
     */
508
    public function getNextPage($result)
509
    {
510
        if ($result->isIncludesLastItemInRange()) {
511
            return $result;
512
        }
513
514
        $offset = 0;
515
        $maxEntries = count($result);
516
        $basePoint = IndexBasePointType::BEGINNING;
517
518
        $lastRequest = $result->getLastRequest();
519
        if ($lastRequest->getIndexedPageItemView()) {
520
            $indexedView = $lastRequest->getIndexedPageItemView();
521
            /* @var $indexedView \garethp\ews\API\Type\IndexedPageViewType */
522
523
            $offset = $indexedView->getOffset() + $maxEntries;
524
            $basePoint = $indexedView->getBasePoint();
525
        }
526
527
        $lastRequest->setIndexedPageItemView(new Type\IndexedPageViewType($maxEntries, $offset, $basePoint));
528
529
        return $this->getClient()->FindItem($lastRequest);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getClient(...FindItem($lastRequest); (garethp\ews\API\Type) is incompatible with the return type documented by garethp\ews\API::getNextPage of type garethp\ews\API\Type\FindItemParentType.

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...
530
    }
531
532
    protected function getPageViewType($item)
533
    {
534
        if ($item instanceof Type\ContactItemType) {
0 ignored issues
show
Bug introduced by
The class garethp\ews\API\Type\ContactItemType 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...
535
            return "ContactsView";
536
        }
537
538
        return "IndexedPageView";
539
    }
540
}
541