Completed
Pull Request — master (#123)
by Damian
03:30 queued 49s
created

TestMailer   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 140
Duplicated Lines 21.43 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 30
loc 140
rs 10
wmc 19
lcom 1
cbo 2

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A sendPlain() 14 15 1
A sendHTML() 16 16 1
A clearEmails() 0 8 2
A findEmail() 0 8 2
D findEmails() 0 32 10
A saveEmail() 0 9 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 SilverStripe\BehatExtension\Utility;
4
5
/**
6
 * Same principle as core TestMailer class,
7
 * but saves emails in {@link TestSessionEnvironment}
8
 * to share the state between PHP calls (CLI vs. browser).
9
 */
10
class TestMailer extends \Mailer
11
{
12
13
    /**
14
     * @var TestSessionEnvironment
15
     */
16
    protected $testSessionEnvironment;
17
18
    public function __construct()
19
    {
20
        $this->testSessionEnvironment = \Injector::inst()->get('TestSessionEnvironment');
21
    }
22
23
    /**
24
     * Send a plain-text email.
25
     * TestMailer will merely record that the email was asked to be sent, without sending anything.
26
     */
27 View Code Duplication
    public function sendPlain($to, $from, $subject, $plainContent, $attachedFiles = false, $customHeaders = false)
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...
28
    {
29
        $this->saveEmail(array(
30
            'Type' => 'plain',
31
            'To' => $to,
32
            'From' => $from,
33
            'Subject' => $subject,
34
            'Content' => $plainContent,
35
            'PlainContent' => $plainContent,
36
            'AttachedFiles' => $attachedFiles,
37
            'CustomHeaders' => $customHeaders,
38
        ));
39
40
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return true; (boolean) is incompatible with the return type of the parent method Mailer::sendPlain of type string[]|false.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
41
    }
42
    
43
    /**
44
     * Send a multi-part HTML email
45
     * TestMailer will merely record that the email was asked to be sent, without sending anything.
46
     */
47 View Code Duplication
    public function sendHTML($to, $from, $subject, $htmlContent, $attachedFiles = false, $customHeaders = false,
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...
48
            $plainContent = false, $inlineImages = false)
0 ignored issues
show
Unused Code introduced by
The parameter $inlineImages 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...
49
    {
50
        $this->saveEmail(array(
51
            'Type' => 'html',
52
            'To' => $to,
53
            'From' => $from,
54
            'Subject' => $subject,
55
            'Content' => $htmlContent,
56
            'PlainContent' => $plainContent,
57
            'AttachedFiles' => $attachedFiles,
58
            'CustomHeaders' => $customHeaders,
59
        ));
60
61
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return true; (boolean) is incompatible with the return type of the parent method Mailer::sendHTML of type string[]|false.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
62
    }
63
    
64
    /**
65
     * Clear the log of emails sent
66
     */
67
    public function clearEmails()
68
    {
69
        $state = $this->testSessionEnvironment->getState();
70
        if (isset($state->emails)) {
71
            unset($state->emails);
72
        }
73
        $this->testSessionEnvironment->applyState($state);
74
    }
75
76
    /**
77
     * Search for an email that was sent.
78
     * All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
79
     * 
80
     * @param $to
81
     * @param $from
82
     * @param $subject
83
     * @param $content
84
     * @return array Contains the keys: 'type', 'to', 'from', 'subject', 'content', 'plainContent', 'attachedFiles',
85
     *               'customHeaders', 'htmlContent', 'inlineImages'
86
     */
87
    public function findEmail($to = null, $from = null, $subject = null, $content = null)
88
    {
89
        $matches = $this->findEmails($to, $from, $subject, $content);
90
                //got the count of matches emails
91
                $emailCount = count($matches);
92
                //get the last(latest) one
93
        return $matches ? $matches[$emailCount-1] : null;
94
    }
95
96
    /**
97
     * Search for all emails.
98
     * All of the parameters can either be a string, or, if they start with "/", a PREG-compatible regular expression.
99
     * 
100
     * @param $to
101
     * @param $from
102
     * @param $subject
103
     * @param $content
104
     * @return array Contains the keys: 'type', 'to', 'from', 'subject', 'content', 'plainContent', 'attachedFiles',
105
     *               'customHeaders', 'htmlContent', 'inlineImages'
106
     */
107
    public function findEmails($to = null, $from = null, $subject = null, $content = null)
0 ignored issues
show
Unused Code introduced by
The parameter $to 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 $from 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 $subject 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 $content 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...
108
    {
109
        $matches = array();
110
        $args = func_get_args();
111
        $state = $this->testSessionEnvironment->getState();
112
        $emails = isset($state->emails) ? $state->emails : array();
113
        foreach ($emails as $email) {
114
            $matched = true;
115
116
            foreach (array('To', 'From', 'Subject', 'Content') as $i => $field) {
117
                if (!isset($email->$field)) {
118
                    continue;
119
                }
120
                $value = (isset($args[$i])) ? $args[$i] : null;
121
                if ($value) {
122
                    if ($value[0] == '/') {
123
                        $matched = preg_match($value, $email->$field);
124
                    } else {
125
                        $matched = ($value == $email->$field);
126
                    }
127
                    if (!$matched) {
128
                        break;
129
                    }
130
                }
131
            }
132
            if ($matched) {
133
                $matches[] = $email;
134
            }
135
        }
136
137
        return $matches;
138
    }
139
140
    protected function saveEmail($data)
141
    {
142
        $state = $this->testSessionEnvironment->getState();
143
        if (!isset($state->emails)) {
144
            $state->emails = array();
145
        }
146
        $state->emails[] = array_filter($data);
147
        $this->testSessionEnvironment->applyState($state);
148
    }
149
}
150