Passed
Push — master ( 133a7b...2b5dda )
by Malte
02:34
created

Query::getMessageByMsgn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 2
1
<?php
2
/*
3
* File:     Query.php
4
* Category: -
5
* Author:   M. Goldenbaum
6
* Created:  21.07.18 18:54
7
* Updated:  -
8
*
9
* Description:
10
*  -
11
*/
12
13
namespace Webklex\PHPIMAP\Query;
14
15
use Carbon\Carbon;
16
use Exception;
17
use Illuminate\Pagination\LengthAwarePaginator;
18
use Illuminate\Support\Collection;
19
use ReflectionException;
20
use Webklex\PHPIMAP\Client;
21
use Webklex\PHPIMAP\ClientManager;
22
use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
23
use Webklex\PHPIMAP\Exceptions\EventNotFoundException;
24
use Webklex\PHPIMAP\Exceptions\GetMessagesFailedException;
25
use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException;
26
use Webklex\PHPIMAP\Exceptions\MessageContentFetchingException;
27
use Webklex\PHPIMAP\Exceptions\MessageFlagException;
28
use Webklex\PHPIMAP\Exceptions\MessageHeaderFetchingException;
29
use Webklex\PHPIMAP\Exceptions\MessageNotFoundException;
30
use Webklex\PHPIMAP\Exceptions\MessageSearchValidationException;
31
use Webklex\PHPIMAP\Exceptions\RuntimeException;
32
use Webklex\PHPIMAP\IMAP;
33
use Webklex\PHPIMAP\Message;
34
use Webklex\PHPIMAP\Support\MessageCollection;
35
36
/**
37
 * Class Query
38
 *
39
 * @package Webklex\PHPIMAP\Query
40
 */
41
class Query {
42
43
    /** @var Collection $query */
44
    protected $query;
45
46
    /** @var string $raw_query */
47
    protected $raw_query;
48
49
    /** @var string[] $extensions */
50
    protected $extensions;
51
52
    /** @var Client $client */
53
    protected $client;
54
55
    /** @var int $limit */
56
    protected $limit = null;
57
58
    /** @var int $page */
59
    protected $page = 1;
60
61
    /** @var int $fetch_options */
62
    protected $fetch_options = null;
63
64
    /** @var int $fetch_body */
65
    protected $fetch_body = true;
66
67
    /** @var int $fetch_flags */
68
    protected $fetch_flags = true;
69
70
    /** @var int|string $sequence */
71
    protected $sequence = IMAP::NIL;
72
73
    /** @var string $fetch_order */
74
    protected $fetch_order;
75
76
    /** @var string $date_format */
77
    protected $date_format;
78
79
    /** @var bool $soft_fail */
80
    protected $soft_fail = false;
81
82
    /** @var array $errors */
83
    protected $errors = [];
84
85
    /**
86
     * Query constructor.
87
     * @param Client $client
88
     * @param string[] $extensions
89
     */
90
    public function __construct(Client $client, $extensions = []) {
91
        $this->setClient($client);
92
93
        $this->sequence = ClientManager::get('options.sequence', IMAP::ST_MSGN);
94
        if (ClientManager::get('options.fetch') === IMAP::FT_PEEK) $this->leaveUnread();
95
96
        if (ClientManager::get('options.fetch_order') === 'desc') {
97
            $this->fetch_order = 'desc';
98
        } else {
99
            $this->fetch_order = 'asc';
100
        }
101
102
        $this->date_format = ClientManager::get('date_format', 'd M y');
103
        $this->soft_fail = ClientManager::get('options.soft_fail', false);
104
105
        $this->setExtensions($extensions);
106
        $this->query = new Collection();
107
        $this->boot();
108
    }
109
110
    /**
111
     * Instance boot method for additional functionality
112
     */
113
    protected function boot() {
114
    }
115
116
    /**
117
     * Parse a given value
118
     * @param mixed $value
119
     *
120
     * @return string
121
     */
122
    protected function parse_value($value) {
123
        switch (true) {
124
            case $value instanceof Carbon:
125
                $value = $value->format($this->date_format);
126
                break;
127
        }
128
129
        return (string)$value;
130
    }
131
132
    /**
133
     * Check if a given date is a valid carbon object and if not try to convert it
134
     * @param string|Carbon $date
135
     *
136
     * @return Carbon
137
     * @throws MessageSearchValidationException
138
     */
139
    protected function parse_date($date) {
140
        if ($date instanceof Carbon) return $date;
141
142
        try {
143
            $date = Carbon::parse($date);
144
        } catch (Exception $e) {
145
            throw new MessageSearchValidationException();
146
        }
147
148
        return $date;
149
    }
150
151
    /**
152
     * Get the raw IMAP search query
153
     *
154
     * @return string
155
     */
156
    public function generate_query() {
157
        $query = '';
158
        $this->query->each(function($statement) use (&$query) {
159
            if (count($statement) == 1) {
160
                $query .= $statement[0];
161
            } else {
162
                if ($statement[1] === null) {
163
                    $query .= $statement[0];
164
                } else {
165
                    if (is_numeric($statement[1])) {
166
                        $query .= $statement[0] . ' ' . $statement[1];
167
                    } else {
168
                        $query .= $statement[0] . ' "' . $statement[1] . '"';
169
                    }
170
                }
171
            }
172
            $query .= ' ';
173
174
        });
175
176
        $this->raw_query = trim($query);
177
178
        return $this->raw_query;
179
    }
180
181
    /**
182
     * Perform an imap search request
183
     *
184
     * @return Collection
185
     * @throws GetMessagesFailedException
186
     */
187
    protected function search() {
188
        $this->generate_query();
189
190
        try {
191
            $available_messages = $this->client->getConnection()->search([$this->getRawQuery()], $this->sequence);
192
            return $available_messages !== false ? new Collection($available_messages) : new Collection();
0 ignored issues
show
introduced by
The condition $available_messages !== false is always true.
Loading history...
193
        } catch (RuntimeException $e) {
194
            throw new GetMessagesFailedException("failed to fetch messages", 0, $e);
195
        } catch (ConnectionFailedException $e) {
196
            throw new GetMessagesFailedException("failed to fetch messages", 0, $e);
197
        }
198
    }
199
200
    /**
201
     * Count all available messages matching the current search criteria
202
     *
203
     * @return int
204
     * @throws GetMessagesFailedException
205
     */
206
    public function count() {
207
        return $this->search()->count();
208
    }
209
210
    /**
211
     * Fetch a given id collection
212
     * @param Collection $available_messages
213
     *
214
     * @return array
215
     * @throws ConnectionFailedException
216
     * @throws RuntimeException
217
     */
218
    protected function fetch($available_messages) {
219
        if ($this->fetch_order === 'desc') {
220
            $available_messages = $available_messages->reverse();
221
        }
222
223
        $uids = $available_messages->forPage($this->page, $this->limit)->toArray();
224
        $extensions = [];
225
        if (empty($this->getExtensions()) === false) {
226
            $extensions = $this->client->getConnection()->fetch($this->getExtensions(), $uids, null, $this->sequence);
0 ignored issues
show
Bug introduced by
The method fetch() does not exist on Webklex\PHPIMAP\Connecti...ocols\ProtocolInterface. It seems like you code against a sub-type of Webklex\PHPIMAP\Connecti...ocols\ProtocolInterface such as Webklex\PHPIMAP\Connection\Protocols\ImapProtocol. ( Ignorable by Annotation )

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

226
            $extensions = $this->client->getConnection()->/** @scrutinizer ignore-call */ fetch($this->getExtensions(), $uids, null, $this->sequence);
Loading history...
Bug introduced by
The method fetch() does not exist on Webklex\PHPIMAP\Connection\Protocols\Protocol. It seems like you code against a sub-type of Webklex\PHPIMAP\Connection\Protocols\Protocol such as Webklex\PHPIMAP\Connection\Protocols\ImapProtocol. ( Ignorable by Annotation )

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

226
            $extensions = $this->client->getConnection()->/** @scrutinizer ignore-call */ fetch($this->getExtensions(), $uids, null, $this->sequence);
Loading history...
227
        }
228
        $flags = $this->client->getConnection()->flags($uids, $this->sequence);
229
        $headers = $this->client->getConnection()->headers($uids, "RFC822", $this->sequence);
230
231
        $contents = [];
232
        if ($this->getFetchBody()) {
233
            $contents = $this->client->getConnection()->content($uids, "RFC822", $this->sequence);
234
        }
235
236
        return [
237
            "uids"       => $uids,
238
            "flags"      => $flags,
239
            "headers"    => $headers,
240
            "contents"   => $contents,
241
            "extensions" => $extensions,
242
        ];
243
    }
244
245
    /**
246
     * Make a new message from given raw components
247
     * @param integer $uid
248
     * @param integer $msglist
249
     * @param string $header
250
     * @param string $content
251
     * @param array $flags
252
     *
253
     * @return Message|null
254
     * @throws ConnectionFailedException
255
     * @throws EventNotFoundException
256
     * @throws GetMessagesFailedException
257
     * @throws ReflectionException
258
     */
259
    protected function make($uid, $msglist, $header, $content, $flags) {
260
        try {
261
            return Message::make($uid, $msglist, $this->getClient(), $header, $content, $flags, $this->getFetchOptions(), $this->sequence);
262
        } catch (MessageNotFoundException $e) {
263
            $this->setError($uid, $e);
264
        } catch (RuntimeException $e) {
265
            $this->setError($uid, $e);
266
        } catch (MessageFlagException $e) {
267
            $this->setError($uid, $e);
268
        } catch (InvalidMessageDateException $e) {
269
            $this->setError($uid, $e);
270
        } catch (MessageContentFetchingException $e) {
271
            $this->setError($uid, $e);
272
        }
273
274
        $this->handleException($uid);
275
276
        return null;
277
    }
278
279
    /**
280
     * Get the message key for a given message
281
     * @param string $message_key
282
     * @param integer $msglist
283
     * @param Message $message
284
     *
285
     * @return string
286
     */
287
    protected function getMessageKey($message_key, $msglist, $message) {
288
        switch ($message_key) {
289
            case 'number':
290
                $key = $message->getMessageNo();
291
                break;
292
            case 'list':
293
                $key = $msglist;
294
                break;
295
            case 'uid':
296
                $key = $message->getUid();
297
                break;
298
            default:
299
                $key = $message->getMessageId();
300
                break;
301
        }
302
        return (string)$key;
303
    }
304
305
    /**
306
     * Populate a given id collection and receive a fully fetched message collection
307
     * @param Collection $available_messages
308
     *
309
     * @return MessageCollection
310
     * @throws ConnectionFailedException
311
     * @throws EventNotFoundException
312
     * @throws GetMessagesFailedException
313
     * @throws ReflectionException
314
     * @throws RuntimeException
315
     */
316
    protected function populate($available_messages) {
317
        $messages = MessageCollection::make([]);
318
319
        $messages->total($available_messages->count());
320
321
        $message_key = ClientManager::get('options.message_key');
322
323
        $raw_messages = $this->fetch($available_messages);
324
325
        $msglist = 0;
326
        foreach ($raw_messages["headers"] as $uid => $header) {
327
            $content = isset($raw_messages["contents"][$uid]) ? $raw_messages["contents"][$uid] : "";
328
            $flag = isset($raw_messages["flags"][$uid]) ? $raw_messages["flags"][$uid] : [];
329
            $extensions = isset($raw_messages["extensions"][$uid]) ? $raw_messages["extensions"][$uid] : [];
330
331
            $message = $this->make($uid, $msglist, $header, $content, $flag);
332
            foreach($extensions as $key => $extension) {
333
                $message->getHeader()->set($key, $extension);
334
            }
335
            if ($message !== null) {
336
                $key = $this->getMessageKey($message_key, $msglist, $message);
337
                $messages->put("$key", $message);
338
            }
339
            $msglist++;
340
        }
341
342
        return $messages;
343
    }
344
345
    /**
346
     * Fetch the current query and return all found messages
347
     *
348
     * @return MessageCollection
349
     * @throws GetMessagesFailedException
350
     */
351
    public function get() {
352
        $available_messages = $this->search();
353
354
        try {
355
            if ($available_messages->count() > 0) {
356
                return $this->populate($available_messages);
357
            }
358
            return MessageCollection::make([]);
359
        } catch (Exception $e) {
360
            throw new GetMessagesFailedException($e->getMessage(), 0, $e);
361
        }
362
    }
363
364
    /**
365
     * Fetch the current query as chunked requests
366
     * @param callable $callback
367
     * @param int $chunk_size
368
     * @param int $start_chunk
369
     *
370
     * @throws ConnectionFailedException
371
     * @throws EventNotFoundException
372
     * @throws GetMessagesFailedException
373
     * @throws ReflectionException
374
     * @throws RuntimeException
375
     */
376
    public function chunked($callback, $chunk_size = 10, $start_chunk = 1) {
377
        $available_messages = $this->search();
378
        if (($available_messages_count = $available_messages->count()) > 0) {
379
            $old_limit = $this->limit;
380
            $old_page = $this->page;
381
382
            $this->limit = $chunk_size;
383
            $this->page = $start_chunk;
384
            do {
385
                $messages = $this->populate($available_messages);
386
                $callback($messages, $this->page);
387
                $this->page++;
388
            } while ($this->limit * $this->page <= $available_messages_count);
389
            $this->limit = $old_limit;
390
            $this->page = $old_page;
391
        }
392
    }
393
394
    /**
395
     * Paginate the current query
396
     * @param int $per_page Results you which to receive per page
397
     * @param int|null $page The current page you are on (e.g. 0, 1, 2, ...) use `null` to enable auto mode
398
     * @param string $page_name The page name / uri parameter used for the generated links and the auto mode
399
     *
400
     * @return LengthAwarePaginator
401
     * @throws GetMessagesFailedException
402
     */
403
    public function paginate($per_page = 5, $page = null, $page_name = 'imap_page') {
404
        if (
405
            $page === null
406
            && isset($_GET[$page_name])
407
            && $_GET[$page_name] > 0
408
        ) {
409
            $this->page = intval($_GET[$page_name]);
410
        } elseif ($page > 0) {
411
            $this->page = $page;
412
        }
413
414
        $this->limit = $per_page;
415
416
        return $this->get()->paginate($per_page, $this->page, $page_name, true);
417
    }
418
419
    /**
420
     * Get a new Message instance
421
     * @param int $uid
422
     * @param int|null $msglist
423
     * @param int|string|null $sequence
424
     *
425
     * @return Message
426
     * @throws ConnectionFailedException
427
     * @throws RuntimeException
428
     * @throws InvalidMessageDateException
429
     * @throws MessageContentFetchingException
430
     * @throws MessageHeaderFetchingException
431
     * @throws EventNotFoundException
432
     * @throws MessageFlagException
433
     * @throws MessageNotFoundException
434
     */
435
    public function getMessage($uid, $msglist = null, $sequence = null) {
436
        return new Message($uid, $msglist, $this->getClient(), $this->getFetchOptions(), $this->getFetchBody(), $this->getFetchFlags(), $sequence ? $sequence : $this->sequence);
0 ignored issues
show
Bug introduced by
$this->getFetchFlags() of type integer is incompatible with the type boolean expected by parameter $fetch_flags of Webklex\PHPIMAP\Message::__construct(). ( Ignorable by Annotation )

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

436
        return new Message($uid, $msglist, $this->getClient(), $this->getFetchOptions(), $this->getFetchBody(), /** @scrutinizer ignore-type */ $this->getFetchFlags(), $sequence ? $sequence : $this->sequence);
Loading history...
Bug introduced by
It seems like $sequence ? $sequence : $this->sequence can also be of type string; however, parameter $sequence of Webklex\PHPIMAP\Message::__construct() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

436
        return new Message($uid, $msglist, $this->getClient(), $this->getFetchOptions(), $this->getFetchBody(), $this->getFetchFlags(), /** @scrutinizer ignore-type */ $sequence ? $sequence : $this->sequence);
Loading history...
437
    }
438
439
    /**
440
     * Get a message by its message number
441
     * @param $msgn
442
     * @param int|null $msglist
443
     *
444
     * @return Message
445
     * @throws ConnectionFailedException
446
     * @throws InvalidMessageDateException
447
     * @throws MessageContentFetchingException
448
     * @throws MessageHeaderFetchingException
449
     * @throws RuntimeException
450
     * @throws EventNotFoundException
451
     * @throws MessageFlagException
452
     * @throws MessageNotFoundException
453
     */
454
    public function getMessageByMsgn($msgn, $msglist = null) {
455
        return $this->getMessage($msgn, $msglist, IMAP::ST_MSGN);
456
    }
457
458
    /**
459
     * Get a message by its uid
460
     * @param $uid
461
     *
462
     * @return Message
463
     * @throws ConnectionFailedException
464
     * @throws InvalidMessageDateException
465
     * @throws MessageContentFetchingException
466
     * @throws MessageHeaderFetchingException
467
     * @throws RuntimeException
468
     * @throws EventNotFoundException
469
     * @throws MessageFlagException
470
     * @throws MessageNotFoundException
471
     */
472
    public function getMessageByUid($uid) {
473
        return $this->getMessage($uid, null, IMAP::ST_UID);
474
    }
475
476
    /**
477
     * Don't mark messages as read when fetching
478
     *
479
     * @return $this
480
     */
481
    public function leaveUnread() {
482
        $this->setFetchOptions(IMAP::FT_PEEK);
0 ignored issues
show
Bug introduced by
Webklex\PHPIMAP\IMAP::FT_PEEK of type integer is incompatible with the type boolean expected by parameter $fetch_options of Webklex\PHPIMAP\Query\Query::setFetchOptions(). ( Ignorable by Annotation )

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

482
        $this->setFetchOptions(/** @scrutinizer ignore-type */ IMAP::FT_PEEK);
Loading history...
483
484
        return $this;
485
    }
486
487
    /**
488
     * Mark all messages as read when fetching
489
     *
490
     * @return $this
491
     */
492
    public function markAsRead() {
493
        $this->setFetchOptions(IMAP::FT_UID);
0 ignored issues
show
Bug introduced by
Webklex\PHPIMAP\IMAP::FT_UID of type integer is incompatible with the type boolean expected by parameter $fetch_options of Webklex\PHPIMAP\Query\Query::setFetchOptions(). ( Ignorable by Annotation )

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

493
        $this->setFetchOptions(/** @scrutinizer ignore-type */ IMAP::FT_UID);
Loading history...
494
495
        return $this;
496
    }
497
498
    /**
499
     * Set the sequence type
500
     * @param int $sequence
501
     *
502
     * @return $this
503
     */
504
    public function setSequence($sequence) {
505
        $this->sequence = $sequence;
506
507
        return $this;
508
    }
509
510
    /**
511
     * Get the sequence type
512
     *
513
     * @return int|string
514
     */
515
    public function getSequence() {
516
        return $this->sequence;
517
    }
518
519
    /**
520
     * @return Client
521
     * @throws ConnectionFailedException
522
     */
523
    public function getClient() {
524
        $this->client->checkConnection();
525
        return $this->client;
526
    }
527
528
    /**
529
     * Set the limit and page for the current query
530
     * @param int $limit
531
     * @param int $page
532
     *
533
     * @return $this
534
     */
535
    public function limit($limit, $page = 1) {
536
        if ($page >= 1) $this->page = $page;
537
        $this->limit = $limit;
538
539
        return $this;
540
    }
541
542
    /**
543
     * @return Collection
544
     */
545
    public function getQuery() {
546
        return $this->query;
547
    }
548
549
    /**
550
     * @param array $query
551
     * @return Query
552
     */
553
    public function setQuery($query) {
554
        $this->query = new Collection($query);
555
        return $this;
556
    }
557
558
    /**
559
     * @return string
560
     */
561
    public function getRawQuery() {
562
        return $this->raw_query;
563
    }
564
565
    /**
566
     * @param string $raw_query
567
     * @return Query
568
     */
569
    public function setRawQuery($raw_query) {
570
        $this->raw_query = $raw_query;
571
        return $this;
572
    }
573
574
    /**
575
     * @return string[]
576
     */
577
    public function getExtensions() {
578
        return $this->extensions;
579
    }
580
581
    /**
582
     * @param string[] $extensions
583
     * @return Query
584
     */
585
    public function setExtensions($extensions) {
586
        $this->extensions = $extensions;
587
        if (count($this->extensions) > 0) {
588
            if (in_array("UID", $this->extensions) === false) {
589
                $this->extensions[] = "UID";
590
            }
591
        }
592
        return $this;
593
    }
594
595
    /**
596
     * @param Client $client
597
     * @return Query
598
     */
599
    public function setClient(Client $client) {
600
        $this->client = $client;
601
        return $this;
602
    }
603
604
    /**
605
     * @return int
606
     */
607
    public function getLimit() {
608
        return $this->limit;
609
    }
610
611
    /**
612
     * @param int $limit
613
     * @return Query
614
     */
615
    public function setLimit($limit) {
616
        $this->limit = $limit <= 0 ? null : $limit;
617
        return $this;
618
    }
619
620
    /**
621
     * @return int
622
     */
623
    public function getPage() {
624
        return $this->page;
625
    }
626
627
    /**
628
     * @param int $page
629
     * @return Query
630
     */
631
    public function setPage($page) {
632
        $this->page = $page;
633
        return $this;
634
    }
635
636
    /**
637
     * @param boolean $fetch_options
638
     * @return Query
639
     */
640
    public function setFetchOptions($fetch_options) {
641
        $this->fetch_options = $fetch_options;
0 ignored issues
show
Documentation Bug introduced by
The property $fetch_options was declared of type integer, but $fetch_options is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
642
        return $this;
643
    }
644
645
    /**
646
     * @param boolean $fetch_options
647
     * @return Query
648
     */
649
    public function fetchOptions($fetch_options) {
650
        return $this->setFetchOptions($fetch_options);
651
    }
652
653
    /**
654
     * @return int
655
     */
656
    public function getFetchOptions() {
657
        return $this->fetch_options;
658
    }
659
660
    /**
661
     * @return boolean
662
     */
663
    public function getFetchBody() {
664
        return $this->fetch_body;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->fetch_body returns the type integer which is incompatible with the documented return type boolean.
Loading history...
665
    }
666
667
    /**
668
     * @param boolean $fetch_body
669
     * @return Query
670
     */
671
    public function setFetchBody($fetch_body) {
672
        $this->fetch_body = $fetch_body;
0 ignored issues
show
Documentation Bug introduced by
The property $fetch_body was declared of type integer, but $fetch_body is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
673
        return $this;
674
    }
675
676
    /**
677
     * @param boolean $fetch_body
678
     * @return Query
679
     */
680
    public function fetchBody($fetch_body) {
681
        return $this->setFetchBody($fetch_body);
682
    }
683
684
    /**
685
     * @return int
686
     */
687
    public function getFetchFlags() {
688
        return $this->fetch_flags;
689
    }
690
691
    /**
692
     * @param int $fetch_flags
693
     * @return Query
694
     */
695
    public function setFetchFlags($fetch_flags) {
696
        $this->fetch_flags = $fetch_flags;
697
        return $this;
698
    }
699
700
    /**
701
     * @param string $fetch_order
702
     * @return Query
703
     */
704
    public function setFetchOrder($fetch_order) {
705
        $fetch_order = strtolower($fetch_order);
706
707
        if (in_array($fetch_order, ['asc', 'desc'])) {
708
            $this->fetch_order = $fetch_order;
709
        }
710
711
        return $this;
712
    }
713
714
    /**
715
     * @param string $fetch_order
716
     * @return Query
717
     */
718
    public function fetchOrder($fetch_order) {
719
        return $this->setFetchOrder($fetch_order);
720
    }
721
722
    /**
723
     * @return string
724
     */
725
    public function getFetchOrder() {
726
        return $this->fetch_order;
727
    }
728
729
    /**
730
     * @return Query
731
     */
732
    public function setFetchOrderAsc() {
733
        return $this->setFetchOrder('asc');
734
    }
735
736
    /**
737
     * @return Query
738
     */
739
    public function fetchOrderAsc() {
740
        return $this->setFetchOrderAsc();
741
    }
742
743
    /**
744
     * @return Query
745
     */
746
    public function setFetchOrderDesc() {
747
        return $this->setFetchOrder('desc');
748
    }
749
750
    /**
751
     * @return Query
752
     */
753
    public function fetchOrderDesc() {
754
        return $this->setFetchOrderDesc();
755
    }
756
757
    /**
758
     * @return Query
759
     * @var boolean $state
760
     *
761
     */
762
    public function softFail($state = true) {
763
        return $this->setSoftFail($state);
764
    }
765
766
    /**
767
     * @return Query
768
     * @var boolean $state
769
     *
770
     */
771
    public function setSoftFail($state = true) {
772
        $this->soft_fail = $state;
773
774
        return $this;
775
    }
776
777
    /**
778
     * @return boolean
779
     */
780
    public function getSoftFail() {
781
        return $this->soft_fail;
782
    }
783
784
    /**
785
     * Handle the exception for a given uid
786
     * @param integer $uid
787
     *
788
     * @throws GetMessagesFailedException
789
     */
790
    protected function handleException($uid) {
791
        if ($this->soft_fail === false && $this->hasError($uid)) {
792
            $error = $this->getError($uid);
793
            throw new GetMessagesFailedException($error->getMessage(), 0, $error);
794
        }
795
    }
796
797
    /**
798
     * Add a new error to the error holder
799
     * @param integer $uid
800
     * @param Exception $error
801
     */
802
    protected function setError($uid, $error) {
803
        $this->errors[$uid] = $error;
804
    }
805
806
    /**
807
     * Check if there are any errors / exceptions present
808
     * @return boolean
809
     * @var integer|null $uid
810
     *
811
     */
812
    public function hasErrors($uid = null) {
813
        if ($uid !== null) {
814
            return $this->hasError($uid);
815
        }
816
        return count($this->errors) > 0;
817
    }
818
819
    /**
820
     * Check if there is an error / exception present
821
     * @return boolean
822
     * @var integer $uid
823
     *
824
     */
825
    public function hasError($uid) {
826
        return isset($this->errors[$uid]);
827
    }
828
829
    /**
830
     * Get all available errors / exceptions
831
     *
832
     * @return array
833
     */
834
    public function errors() {
835
        return $this->getErrors();
836
    }
837
838
    /**
839
     * Get all available errors / exceptions
840
     *
841
     * @return array
842
     */
843
    public function getErrors() {
844
        return $this->errors;
845
    }
846
847
    /**
848
     * Get a specific error / exception
849
     * @return Exception|null
850
     * @var integer $uid
851
     *
852
     */
853
    public function error($uid) {
854
        return $this->getError($uid);
855
    }
856
857
    /**
858
     * Get a specific error / exception
859
     * @return Exception|null
860
     * @var integer $uid
861
     *
862
     */
863
    public function getError($uid) {
864
        if ($this->hasError($uid)) {
865
            return $this->errors[$uid];
866
        }
867
        return null;
868
    }
869
}
870