Completed
Push — master ( 0c22ef...9291be )
by
unknown
03:25
created

Envelope::__construct()   C

Complexity

Conditions 10
Paths 257

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 6
cc 10
eloc 12
nc 257
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Email\Envelope
5
 *
6
 * Wraps and compile a MIME Email envelope.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2016 - http://caffeina.com
11
 */
12
13
namespace Email;
14
15
class Envelope {
0 ignored issues
show
Coding Style introduced by
The property $compiled_head is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
Coding Style introduced by
The property $compiled_body is not named in camelCase.

This check marks property names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
16
17
  protected  $uid,
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
18
             $to,
19
             $from,
20
             $cc,
21
             $bcc,
22
             $replyTo,
23
             $subject,
24
             $message,
25
             $contentType = 'text/html; charset="utf-8"',
26
             $attachments,
27
             $compiled_head,
28
             $compiled_body;
29
30
  public function __construct($email=null){
31
    if ($email) {
32
      $email = (object)$email;
33
      if(isset($email->to))           $this->to($email->to);
34
      if(isset($email->from))         $this->from($email->from);
35
      if(isset($email->cc))           $this->cc($email->cc);
36
      if(isset($email->bcc))          $this->bcc($email->bcc);
37
      if(isset($email->replyTo))      $this->replyTo($email->replyTo);
38
      if(isset($email->subject))      $this->subject($email->subject);
39
      if(isset($email->message))      $this->message($email->message);
40
      if(isset($email->attachments))  $this->attach($email->attachments);
41
    }
42
    $this->uid  = '_CORE_'.md5(uniqid(time()));
43
44
  }
45
46
  protected function add_emails(&$pool, $emails, $append=true){
47
    $this->compiled_head = null;
48
    foreach ((array)$emails as $values) {
49
      foreach(preg_split('/\s*,\s*/',$values) as $value) {
50
        if(strpos($value,'<')!==false){
51
          $value   = str_replace('>','',$value);
52
          $parts   = explode('<',$value,2);
53
          $name    = trim(current($parts));
54
          $email   = trim(end($parts));
55
          $address = "$name <{$email}>";
56
        } else {
57
          $address = $value;
58
        }
59
        if ($append) $pool[] = $address; else $pool = $address;
60
      }
61
    }
62
  }
63
64
  public function from($value=null){
65
    if ($value!==null && $value) {
66
      $this->add_emails($this->from, $value, false);
67
    } else if ($value===false) $this->from = '';
68
    return $this->from;
69
  }
70
71
  public function to($value=null){
72 View Code Duplication
    if ($value!==null && $value) {
73
      $this->add_emails($this->to, $value);
74
    } else if ($value===false) $this->to = [];
75
    return $this->to;
76
  }
77
78
  public function cc($value=null){
79 View Code Duplication
    if ($value!==null && $value) {
80
      $this->add_emails($this->cc, $value);
81
    } else if ($value===false) $this->cc = [];
82
    return $this->cc;
83
  }
84
85
  public function bcc($value=null){
86 View Code Duplication
    if ($value!==null && $value) {
87
      $this->add_emails($this->bcc, $value);
88
    } else if ($value===false) $this->bcc = [];
89
    return $this->bcc;
90
  }
91
92
  public function replyTo($value=null){
93 View Code Duplication
    if ($value!==null && $value) {
94
      $this->add_emails($this->replyTo, $value, false);
95
    } else if ($value===false) $this->replyTo = '';
96
    return $this->replyTo;
97
  }
98
99
  public function subject($value=null){
100
    if ($value!==null && $value) {
101
      $this->compiled_head = null;
102
      $this->subject = $value;
103
    } else if ($value===false) $this->subject = '';
104
    return $this->subject;
105
  }
106
107 View Code Duplication
  public function contentType($value=null){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
    if ($value!==null && $value) {
109
      $this->compiled_body = null;
110
      $this->contentType = $value;
111
    } else if ($value===false) $this->contentType = '';
112
    return $this->contentType;
113
  }
114
115 View Code Duplication
  public function message($value=null){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
    if ($value!==null && $value) {
117
      $this->compiled_body = null;
118
      $this->message = $value;
119
    } else if ($value===false) $this->message = '';
120
    return $this->message;
121
  }
122
123
  public function attach($file){
124
    $this->compiled_body = null;
125
    if (isset($file->content) || isset($file['content'])) {
126
      $this->attachments[] = $file;
127
    } else foreach ((array)$file as $curfile) {
128
      $this->attachments[] = $curfile;
129
    }
130
  }
131
132
  public function head($recompile = false){
133
    if ($recompile || (null === $this->compiled_head)){
134
      $head   = [];
135
      $head[] = "Subject: {$this->subject}";
136
      if($this->from)                        $head[] = "From: {$this->from}";
137
      if(is_array($this->to)  && !empty($this->to))  $head[] = "To: "  . implode(', ',$this->to);
138 View Code Duplication
      if(is_array($this->cc)  && !empty($this->cc))  $head[] = "Cc: "  . implode(', ',$this->cc);
139 View Code Duplication
      if(is_array($this->bcc) && !empty($this->bcc)) $head[] = "Bcc: " . implode(', ',$this->bcc);
140
      if($this->replyTo)                     $head[] = "Reply-To: {$this->replyTo}";
141
      $head[] = 'MIME-Version: 1.0';
142
      if (!empty($this->attachments)) $head[] = "Content-Type: multipart/mixed; boundary=\"{$this->uid}\"";
143
      $this->compiled_head = implode("\r\n", $head);
144
    }
145
    return \Filter::with( 'core.email.source.head', $this->compiled_head);
146
  }
147
148
  public function body($recompile = false){
149
    if ($recompile || (null === $this->compiled_body)){
150
      if (!empty($this->attachments)) $body[] = "--{$this->uid}";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$body was never initialized. Although not strictly required by PHP, it is generally a good practice to add $body = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
151
      $body[] = "Content-Type: {$this->contentType}";
0 ignored issues
show
Bug introduced by
The variable $body does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
152
      $body[] = "Content-Transfer-Encoding: quoted-printable";
153
      $body[] = '';
154
      $body[] = quoted_printable_encode($this->message);
155
      $body[] = '';
156
157
      if (!empty($this->attachments)) foreach ((array)$this->attachments as $file) {
158
159
        if (is_string($file)) {
160
          $name = basename($file);
161
          $data = file_get_contents($file);
162
        } else {
163
          $name = isset($file['name'])    ? $file['name']    : 'untitled';
164
          $data = isset($file['content']) ? $file['content'] : '';
165
        }
166
167
        $body[] = "--{$this->uid}";
168
        $body[] = "Content-Type: application/octet-stream; name=\"{$name}\"";
169
        $body[] = "Content-Transfer-Encoding: base64";
170
        $body[] = "Content-Disposition: attachment; filename=\"{$name}\"";
171
        $body[] = '';
172
        $body[] = chunk_split(base64_encode($data));
173
        $body[] = '';
174
        $body[] = "--{$this->uid}--";
175
      }
176
177
      $this->compiled_body = implode("\r\n", $body);
178
    }
179
    return \Filter::with( 'core.email.source.body', $this->compiled_body);
180
  }
181
182
  public function build(){
183
    return \Filter::with( 'core.email.source', $this->head() . "\r\n" . $this->body() );
184
  }
185
186
}
187