Passed
Push — master ( ba41b4...cc2322 )
by Gabriel
19:31
created

EmailTrait   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 191
Duplicated Lines 13.61 %

Coupling/Cohesion

Components 7
Dependencies 8

Test Coverage

Coverage 5.26%

Importance

Changes 0
Metric Value
wmc 27
lcom 7
cbo 8
dl 26
loc 191
ccs 4
cts 76
cp 0.0526
rs 10
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A populateFromConfig() 0 6 1
A populateFromItem() 0 5 1
A getFrom() 0 4 1
A getPreviewBody() 0 4 1
A getBody() 0 4 1
A getSubject() 0 4 1
A getTos() 0 15 4
A insert() 0 7 1
A delete() 0 5 1
A clearAttachments() 0 4 1
A buildMailMessageAttachments() 0 9 2
A getCustomArgs() 0 8 1
A IsHTML() 0 8 3
A getActivitiesByEmail() 13 13 3
A getLinksByEmail() 13 13 3
A afterSend() 0 16 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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('mail.from.address');
46
        $this->from_name = $config->get('mail.from.address');
47
    }
48
49
    /**
50
     * @param Record $item
51
     */
52
    public function populateFromItem($item)
53
    {
54
        $this->id_item = $item->id;
55
        $this->type = inflector()->singularize($item->getManager()->getTable());
56
    }
57
58
    /**
59
     * @inheritdoc
60
     * Used to decode html entities to proper chars
61
     */
62
    public function getFrom()
63
    {
64
        return [$this->from => html_entity_decode($this->from_name, ENT_QUOTES)];
65
    }
66
67
    /**
68
     * @return string
69
     */
70
    public function getPreviewBody()
71
    {
72
        return $this->getBody();
73
    }
74
75
    /**
76
     * @return string
77
     */
78
    public function getBody()
79
    {
80
        return $this->body;
81
    }
82
83
    /**
84
     * @return string
85
     */
86
    public function getSubject()
87
    {
88
        return $this->subject;
89
    }
90
91
    /**
92
     * @return array
93
     */
94
    public function getTos()
95
    {
96
        $emailsTos = [];
97
        if (preg_match_all('/\s*"?([^><,"]+)"?\s*((?:<[^><,]+>)?)\s*/', $this->to, $matches, PREG_SET_ORDER) > 0) {
98
            foreach ($matches as $m) {
99
                if (!empty($m[2])) {
100
                    $emailsTos[trim($m[2], '<>')] = html_entity_decode($m[1]);
101
                } else {
102
                    $emailsTos[$m[1]] = '';
103
                }
104
            }
105
        }
106
107
        return $emailsTos;
108
    }
109
110
    /**
111
     * @return mixed
112
     */
113 1
    public function insert()
114
    {
115 1
        $this->saveMergeTagsToDbField();
116 1
        $this->created = date('Y-m-d H:i:s');
117
118 1
        return parent::insert();
119
    }
120
121
    public function delete()
122
    {
123
        $this->clearAttachments();
124
        return parent::delete();
125
    }
126
127
    public function clearAttachments()
128
    {
129
        $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...
130
    }
131
132
133
    /**
134
     * @param Message $message
135
     */
136
    public function buildMailMessageAttachments(&$message)
137
    {
138
        $emailFiles = $this->getFiles();
139
        foreach ($emailFiles as $emailFile) {
140
            $message->attach(
141
                Swift_Attachment::newInstance($emailFile->read(), $emailFile->getName())
142
            );
143
        }
144
    }
145
146
    /**
147
     * @return array|null
148
     */
149
    protected function getCustomArgs()
150
    {
151
        $args = [];
152
        $args['category'] = $this->type;
153
        $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...
154
155
        return $args;
156
    }
157
158
    /**
159
     * @param null $value
160
     * @return bool
161
     */
162
    public function IsHTML($value = null)
163
    {
164
        if (is_bool($value)) {
165
            $this->is_html = $value ? 'yes' : 'no';
166
        }
167
168
        return $this->is_html == 'yes';
169
    }
170
171
    /**
172
     * @return mixed
173
     */
174 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...
175
    {
176
        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...
177
            $actEmail = [];
178
            $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...
179
            foreach ($activities as $activity) {
180
                $actEmail[$activity->email][] = $activity;
181
            }
182
            $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...
183
        }
184
185
        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...
186
    }
187
188
    /**
189
     * @return mixed
190
     */
191 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...
192
    {
193
        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...
194
            $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...
195
            $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...
196
            foreach ($links as $link) {
197
                $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...
198
            }
199
            $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...
200
        }
201
202
        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...
203
    }
204
205
    /**
206
     * @param Mailer $mailer
207
     * @param Message $message
208
     * @param $response
209
     */
210
    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...
211
    {
212
        if ($response > 0) {
213
            $this->sent = 'yes';
214
            $this->smtp_user = '';
215
            $this->smtp_host = '';
216
            $this->smtp_password = '';
217
//            $this->subject = '';
218
//            $this->body = '';
219
            //        $this->vars = '';
220
            $this->date_sent = date(DATE_DB);
221
            $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...
222
223
            $this->clearAttachments();
224
        }
225
    }
226
}
227