Test Failed
Push — master ( 8cf703...3d752b )
by eXeCUT
04:39
created

Receiver::getMails()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 12
ccs 8
cts 8
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 3
nop 0
crap 4
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
    public function getSearchCriteria() {
33
        if ($this->searchCriteria === null) {
34
            return 'UNSEEN SINCE "' . $this->getNow() . '"';
35
        }
36
37
        return $this->searchCriteria;
38
    }
39
40
    protected function getNow() {
41
        if ($this->now !== null) {
42
            return $this->now;
43
        }
44
        return date('d F Y', time() - 3600 * 24 * 10);
45
    }
46
47
    protected function _getMails() {
48
        $mailsIds = $this->imap->searchMailBox($this->getSearchCriteria());
49
        $mails = [];
50
        foreach ($mailsIds as $id) {
51
            $mails[] = self::createMailFromImap($this->imap->getMail($id, false));
52
        }
53
54
        return $mails;
55
    }
56
57
    /**
58
     * @return Mail[];
59
     */
60 2
    public function getMails() {
61 2
        $mails = $this->_getMails();
62 2
        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 2
        return $mails;
72
    }
73
74 1
    public static function createMailFromImap(IncomingMail $imapMail) {
75 1
        $attachments = [];
76 1
        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 1
        return new Mail([
85 1
            'id' => $imapMail->id,
86 1
            'sender' => $imapMail->fromAddress,
87 1
            'subject' => $imapMail->subject,
88 1
            'attachments' => $attachments,
89
        ]);
90
    }
91
}