Completed
Push — master ( 070c71...411399 )
by Rudie
02:07
created

IMAPMailbox::message()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace rdx\imap;
4
5
class IMAPMailbox {
6
7
	protected $server = '';
8
	protected $username = '';
9
	protected $password = '';
10
	protected $mailbox = '';
11
	protected $flags = [];
12
13
	protected $imap; // imap_open() resource
14
15
	public function __construct( $server, $username, $password, $mailbox = null, $flags = [] ) {
16
		$this->server = $server;
17
		$this->username = $username;
18
		$this->password = $password;
19
		$this->mailbox = $mailbox ?: 'INBOX';
20
		$this->flags = $flags;
21
	}
22
23
	public function connect() {
24
		if ( !$this->imap ) {
25
			$server = $this->server;
26
			if ( !empty($this->flags) ) {
27
				$server .= '/' . implode('/', $this->flags);
28
			}
29
30
			$mailbox = '{' . $server . '}' . $this->mailbox;
31
			$this->imap = imap_open($mailbox, $this->username, $this->password);
32
		}
33
34
		return $this->imap;
35
	}
36
37
	public function imap() {
38
		return $this->imap;
39
	}
40
41
	public function headers( $newestFirst = true ) {
42
		$this->connect();
43
44
		$headers = imap_headers($this->imap());
45
46
		if ( $newestFirst ) {
47
			$headers = array_reverse($headers);
48
		}
49
50
		return $headers;
51
	}
52
53
	public function message( $msgNum ) {
54
		$this->connect();
55
56
		return new IMAPMessage($this, $msgNum);
57
	}
58
59
	public function messages( array $options = [] ) {
60
		$options += [
61
			'offset' => 0,
62
			'limit' => 0,
63
			'seen' => null,
64
			'newestFirst' => true,
65
		];
66
67
		$headers = $this->headers($options['newestFirst']);
68
69
		$messages = [];
70
		$eligibles = 0;
71
		foreach ( $headers AS $n => $header ) {
72
			if ( preg_match('/([UN]?)\s+(\d+)\)/', $header, $match) ) {
73
				$unseen = (bool) trim($match[1]);
74
				$msgNum = (int) $match[2];
75
76
				$eligible = $options['seen'] === null || $unseen != $options['seen'];
77
				if ( $eligible ) {
78
					$eligibles++;
79
80
					if ( $eligibles > $options['offset'] ) {
81
						$messages[] = new IMAPMessage($this, $msgNum, $unseen);
82
					}
83
				}
84
85
				if ( $options['limit'] && isset($messages[$options['limit']-1]) ) {
86
					break;
87
				}
88
			}
89
		}
90
91
		return $messages;
92
	}
93
94
}
95