Completed
Push — master ( 3cca65...6ffe9e )
by Gabriel
05:45
created

EmailTrait::IsHTML()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
1
<?php
2
3
namespace Nip\MailModule\Models\EmailsTable;
4
5
use ByTIC\MediaLibrary\HasMedia\HasMediaTrait;
6
use Nip\Mail\Models\Mailable\RecordTrait as MailableRecordTrait;
7
use Nip\MailModule\Models\EmailsTable\Traits\MergeTags\MergeTagsRecordTrait;
8
use Nip\Records\AbstractModels\Record;
9
use Nip_File_System;
10
use Swift_Attachment;
11
use Nip\Mail\Mailer;
12
use Nip\Mail\Message;
13
14
/**
15
 * Trait EmailTrait
16
 * @package Nip\Mail\Models\EmailsTable
17
 *
18
 * @property int $id_item
19
 * @property string $type
20
 * @property string $from
21
 * @property string $from_name
22
 * @property string $smtp_host
23
 * @property string $smtp_user
24
 * @property string $smtp_password
25
 * @property string $to
26
 * @property string $subject
27
 * @property string $compiled_subject
28
 * @property string $body
29
 * @property string $compiled_body
30
 * @property string $vars
31
 * @property string $is_html
32
 * @property string $sent
33
 * @property string $date_sent
34
 * @property string $created
35
 */
36
trait EmailTrait
37
{
38
    use MailableRecordTrait;
39
    use HasMediaTrait;
40
    use MergeTagsRecordTrait;
41
42
    public function populateFromConfig()
43
    {
44
        $config = app('config');
45
        $this->from = $config->get('EMAIL.from');
46
        $this->from_name = $config->get('EMAIL.from_name');
47
48
        $this->smtp_host = $config->get('SMTP.host');
49
        $this->smtp_user = $config->get('SMTP.username');
50
        $this->smtp_password = $config->get('SMTP.password');
51
    }
52
53
    /**
54
     * @param Record $item
55
     */
56
    public function populateFromItem($item)
57
    {
58
        $this->id_item = $item->id;
59
        $this->type = inflector()->singularize($item->getManager()->getTable());
60
    }
61
62
    /**
63
     * @inheritdoc
64
     * Used to decode html entities to proper chars
65
     */
66
    public function getFrom()
67
    {
68
        return [$this->from => html_entity_decode($this->from_name, ENT_QUOTES)];
69
    }
70
71
    /**
72
     * @return string
73
     */
74
    public function getPreviewBody()
75
    {
76
        return $this->getBody();
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function getBody()
83
    {
84
        return $this->body;
85
    }
86
87
    /**
88
     * @return string
89
     */
90
    public function getSubject()
91
    {
92
        return $this->subject;
93
    }
94
95
    /**
96
     * @return array
97
     */
98
    public function getTos()
99
    {
100
        $emailsTos = [];
101
        if (preg_match_all('/\s*"?([^><,"]+)"?\s*((?:<[^><,]+>)?)\s*/', $this->to, $matches, PREG_SET_ORDER) > 0) {
102
            foreach ($matches as $m) {
103
                if (!empty($m[2])) {
104
                    $emailsTos[trim($m[2], '<>')] = html_entity_decode($m[1]);
105
                } else {
106
                    $emailsTos[$m[1]] = '';
107
                }
108
            }
109
        }
110
111
        return $emailsTos;
112
    }
113
114
    /**
115
     * @return mixed
116
     */
117 1
    public function insert()
118
    {
119 1
        $this->saveMergeTagsToDbField();
120 1
        $this->created = date('Y-m-d H:i:s');
121
122 1
        return parent::insert();
123
    }
124
125
    public function delete()
126
    {
127
        $this->clearAttachments();
128
        return parent::delete();
129
    }
130
131
    public function clearAttachments()
132
    {
133
        $file = $this->getFiles()->delete();
0 ignored issues
show
Unused Code introduced by
$file is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
134
    }
135
136
137
    /**
138
     * @param Message $message
139
     */
140
    public function buildMailMessageAttachments(&$message)
141
    {
142
        $emailFiles = $this->getFiles();
143
        foreach ($emailFiles as $emailFile) {
144
            $message->attach(
145
                Swift_Attachment::newInstance($emailFile->read(), $emailFile->getName())
146
            );
147
        }
148
    }
149
150
    /**
151
     * @return array|null
152
     */
153
    protected function getCustomArgs()
154
    {
155
        $args = [];
156
        $args['category'] = $this->type;
157
        $args['id_email'] = $this->id;
0 ignored issues
show
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
158
159
        return $args;
160
    }
161
162
    /**
163
     * @param null $value
164
     * @return bool
165
     */
166
    public function IsHTML($value = null)
167
    {
168
        if (is_bool($value)) {
169
            $this->is_html = $value ? 'yes' : 'no';
170
        }
171
172
        return $this->is_html == 'yes';
173
    }
174
175
    /**
176
     * @return mixed
177
     */
178 View Code Duplication
    public function getActivitiesByEmail()
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...
179
    {
180
        if (!$this->getRegistry()->exists('activities-email')) {
0 ignored issues
show
Bug introduced by
It seems like getRegistry() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
181
            $actEmail = [];
182
            $activities = $this->getActivities();
0 ignored issues
show
Bug introduced by
The method getActivities() does not exist on Nip\MailModule\Models\EmailsTable\EmailTrait. Did you maybe mean getActivitiesByEmail()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
183
            foreach ($activities as $activity) {
184
                $actEmail[$activity->email][] = $activity;
185
            }
186
            $this->getRegistry()->set('activities-email', $actEmail);
0 ignored issues
show
Bug introduced by
It seems like getRegistry() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
187
        }
188
189
        return $this->getRegistry()->get('activities-email');
0 ignored issues
show
Bug introduced by
It seems like getRegistry() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
190
    }
191
192
    /**
193
     * @return mixed
194
     */
195 View Code Duplication
    public function getLinksByEmail()
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...
196
    {
197
        if (!$this->getRegistry()->exists('links-email')) {
0 ignored issues
show
Bug introduced by
It seems like getRegistry() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
198
            $linksEmail = [];
0 ignored issues
show
Unused Code introduced by
$linksEmail is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
199
            $links = $this->getLinks();
0 ignored issues
show
Bug introduced by
The method getLinks() does not exist on Nip\MailModule\Models\EmailsTable\EmailTrait. Did you maybe mean getLinksByEmail()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
200
            foreach ($links as $link) {
201
                $actEmail[$link->url][$link->email] = $link;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$actEmail was never initialized. Although not strictly required by PHP, it is generally a good practice to add $actEmail = 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...
202
            }
203
            $this->getRegistry()->set('links-email', $actEmail);
0 ignored issues
show
Bug introduced by
The variable $actEmail 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...
Bug introduced by
It seems like getRegistry() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
204
        }
205
206
        return $this->getRegistry()->get('links-email');
0 ignored issues
show
Bug introduced by
It seems like getRegistry() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
207
    }
208
209
    /**
210
     * @param Mailer $mailer
211
     * @param Message $message
212
     * @param $response
213
     */
214
    protected function afterSend($mailer, $message, $response)
0 ignored issues
show
Unused Code introduced by
The parameter $mailer is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $message is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
215
    {
216
        if ($response > 0) {
217
            $this->sent = 'yes';
218
            $this->smtp_user = '';
219
            $this->smtp_host = '';
220
            $this->smtp_password = '';
221
//            $this->subject = '';
222
//            $this->body = '';
223
            //        $this->vars = '';
224
            $this->date_sent = date(DATE_DB);
225
            $this->update();
0 ignored issues
show
Bug introduced by
It seems like update() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
226
227
            $this->clearAttachments();
228
        }
229
    }
230
}
231