Completed
Push — master ( 0c6133...5ed276 )
by
unknown
02:28
created

Email::clear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * Email
5
 *
6
 * Send messages via Email services.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2015 - http://caffeina.it
11
 */
12
13
14
class Email {
15
  use Module;
16
17
  protected static $driver;
18
  protected static $options;
19
  protected static $driver_name;
20
21
  protected static function instance(){
22
    return static::$driver;
23
  }
24
25
  public static function using($driver, $options = null){
26
    $class = '\\Email\\'.ucfirst(strtolower($driver));
27
    if ( ! class_exists($class) ) throw new \Exception("[Core.Email] : $driver driver not found.");
28
    static::$driver_name = $driver;
29
    static::$options = $options;
30
    static::$driver = new $class($options);
31
  }
32
33
  public static function clear(){
34
    static::using( static::$driver_name, static::$options );
35
  }
36
37
  protected static function get_email_parts($value){
38
    if(strpos($value,'<')!==false){
39
      $value = str_replace('>','',$value);
40
      $parts = explode('<',$value,2);
41
      $name  = trim(current($parts));
42
      $email = trim(end($parts));
43
      return (object) [
44
        'name'  => $name,
45
        'email' => $email,
46
      ];
47
    } else {
48
      return (object) [
49
        'name'  => '',
50
        'email' => $value,
51
      ];
52
    }
53
  }
54
55
  public static function send(array $options){
56
    $mail = static::instance();
57
58
    $options = array_merge([
59
      'to'          => '',
60
      'from'        => '',
61
      'replyTo'     => '',
62
      'subject'     => '',
63
      'message'     => '',
64
      'attachments' => [],
65
    ],$options);
66
67
    // To
68
    foreach((array)$options['to'] as $value){
69
      $to = static::get_email_parts($value);
70
      empty($to->name)
71
        ? $mail->addAddress($to->email)
72
        : $mail->addAddress($to->email,$to->name);
73
    }
74
75
    // From
76
    $from = static::get_email_parts($options['from']);
77
    empty($from->name)
78
      ? $mail->from($from->email)
79
      : $mail->from($from->email,$from->name);
80
81
    // Reply
82
    $replyTo = static::get_email_parts($options['replyTo']);
83
    empty($replyTo->name)
84
      ? $mail->replyTo($replyTo->email)
85
      : $mail->replyTo($replyTo->email,$replyTo->name);
86
87
    // Subjects
88
    $mail->subject($options['subject']);
89
90
    // Message
91
    $mail->message($options['message']);
92
93
    // Attachments
94
    foreach((array)$options['attachments'] as $value){
95
      $mail->addAttachment($value);
96
    }
97
98
    return $mail->send();
99
  }
100
}
101
102
Email::using('native');
103