Passed
Push — master ( 3d752b...8294c3 )
by eXeCUT
07:01 queued 02:57
created

Receiver::_getMails()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: execut
5
 * Date: 9/27/16
6
 * Time: 2:26 PM
7
 */
8
9
namespace execut\import\components\source\adapter\email;
10
11
12
use execut\import\components\source\File;
13
use roopz\imap\Imap;
14
use roopz\imap\IncomingMail;
15
use yii\base\Component;
16
17
class Receiver extends Component
18
{
19
    public $filter = null;
20
    /**
21
     * @var Imap
22
     */
23
    public $imap = null;
24
    public $now = null;
25
    protected $searchCriteria = null;
26
    protected $mails;
27
28
    public function setSearchCriteria($criteria) {
29
        $this->searchCriteria = $criteria;
30
    }
31
32 1
    public function getSearchCriteria() {
33 1
        if ($this->searchCriteria === null) {
34 1
            return 'UNSEEN SINCE "' . $this->getNow() . '"';
35
        }
36
37
        return $this->searchCriteria;
38
    }
39
40 1
    protected function getNow() {
41 1
        if ($this->now !== null) {
42 1
            return $this->now;
43
        }
44
        return date('d F Y', time() - 3600 * 24 * 10);
45
    }
46
47 1
    protected function _getMails() {
48 1
        $mailsIds = $this->imap->searchMailBox($this->getSearchCriteria());
49 1
        $mails = [];
50 1
        foreach ($mailsIds as $id) {
51 1
            $mails[] = self::createMailFromImap($this->imap->getMail($id, false));
52
        }
53
54 1
        return $mails;
55
    }
56
57
    /**
58
     * @return Mail[];
59
     */
60 3
    public function getMails() {
61 3
        $mails = $this->_getMails();
62 3
        if ($this->filter) {
63 1
            $mails = $this->filter->filtrate($mails);
64 1
            if ($this->imap !== null) {
65 1
                foreach ($mails as $mail) {
66 1
                    $this->imap->markMailAsRead($mail->id);
67
                }
68
            }
69
        }
70
71 3
        return $mails;
72
    }
73
74 2
    public static function createMailFromImap(IncomingMail $imapMail) {
75 2
        $attachments = [];
76 2
        foreach ($imapMail->getAttachments() as $imapAttachment) {
77 1
            $attachment = new File([
78 1
                'fileName' => $imapAttachment->name,
79 1
                'filePath' => $imapAttachment->filePath,
80
            ]);
81 1
            $attachments[] = $attachment;
82
        }
83
84 2
        return new Mail([
85 2
            'id' => $imapMail->id,
86 2
            'sender' => $imapMail->fromAddress,
87 2
            'subject' => $imapMail->subject,
88 2
            'attachments' => $attachments,
89
        ]);
90
    }
91
}