Completed
Push — master ( 676b2a...efd8f6 )
by Ingo
02:38
created

EmailContext   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 269
Duplicated Lines 20.45 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 8
Bugs 1 Features 2
Metric Value
wmc 40
c 8
b 1
f 2
lcom 1
cbo 7
dl 55
loc 269
rs 8.2609

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getSession() 0 4 1
A before() 0 8 1
A thereIsAnEmailFromTo() 0 12 4
B thereIsAnEmailFromToTitled() 0 23 6
A thereTheEmailContains() 0 20 4
A iGoToInTheEmailTo() 15 15 3
A iGoToInTheEmailToTitled() 14 14 3
A iGoToInTheEmail() 0 15 2
A iClearAllEmails() 0 5 1
B theEmailContainFollowingData() 0 27 6
A thereIsAnEmailTitled() 0 14 2
A theEmailSentFrom() 13 13 3
A theEmailSentTo() 13 13 3

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like EmailContext often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EmailContext, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SilverStripe\BehatExtension\Context;
4
5
use Behat\Behat\Context\ClosuredContextInterface,
6
Behat\Behat\Context\TranslatedContextInterface,
7
Behat\Behat\Context\BehatContext,
8
Behat\Behat\Context\Step,
9
Behat\Behat\Event\FeatureEvent,
10
Behat\Behat\Event\ScenarioEvent,
11
Behat\Behat\Exception\PendingException;
12
use Behat\Gherkin\Node\PyStringNode,
13
Behat\Gherkin\Node\TableNode;
14
use Symfony\Component\DomCrawler\Crawler;
15
16
// PHPUnit
17
require_once 'PHPUnit/Autoload.php';
18
require_once 'PHPUnit/Framework/Assert/Functions.php';
19
20
/**
21
 * Context used to define steps related to email sending.
22
 */
23
class EmailContext extends BehatContext
24
{
25
    protected $context;
26
27
    protected $mailer;
28
29
    /**
30
     * Stored to simplify later assertions
31
     */
32
    protected $lastMatchedEmail;
33
34
    /**
35
     * Initializes context.
36
     * Every scenario gets it's own context object.
37
     *
38
     * @param array $parameters context parameters (set them up through behat.yml)
39
     */
40
    public function __construct(array $parameters)
41
    {
42
        // Initialize your context here
43
        $this->context = $parameters;
44
    }
45
46
    /**
47
     * Get Mink session from MinkContext
48
     */
49
    public function getSession($name = null)
50
    {
51
        return $this->getMainContext()->getSession($name);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Behat\Context\ExtendedContextInterface as the method getSession() does only exist in the following implementations of said interface: Behat\MinkExtension\Context\MinkContext, Behat\MinkExtension\Context\RawMinkContext, SilverStripe\BehatExtension\Context\BasicContext, SilverStripe\BehatExtension\Context\EmailContext, SilverStripe\BehatExtension\Context\FixtureContext, SilverStripe\BehatExtension\Context\LoginContext, SilverStripe\BehatExtens...ext\SilverStripeContext.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
52
    }
53
54
    /**
55
     * @BeforeScenario
56
     */
57
    public function before(ScenarioEvent $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event 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...
58
    {
59
        // Also set through the 'supportbehat' extension
60
        // to ensure its available both in CLI execution and the tested browser session
61
        $this->mailer = new \SilverStripe\BehatExtension\Utility\TestMailer();
62
        \Email::set_mailer($this->mailer);
0 ignored issues
show
Deprecated Code introduced by
The method Email::set_mailer() has been deprecated with message: since version 4.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
63
        \Config::inst()->update("Email","send_all_emails_to", null);
64
    }
65
66
    /**
67
     * @Given /^there should (not |)be an email (to|from) "([^"]*)"$/
68
     */
69
    public function thereIsAnEmailFromTo($negate, $direction, $email)
70
    {
71
        $to = ($direction == 'to') ? $email : null;
72
        $from = ($direction == 'from') ? $email : null;
73
        $match = $this->mailer->findEmail($to, $from);
74
        if(trim($negate)) {
75
            assertNull($match);
76
        } else {
77
            assertNotNull($match);
78
        }
79
        $this->lastMatchedEmail = $match;
80
    }
81
82
    /**
83
     * @Given /^there should (not |)be an email (to|from) "([^"]*)" titled "([^"]*)"$/
84
     */
85
    public function thereIsAnEmailFromToTitled($negate, $direction, $email, $subject)
86
    {
87
        $to = ($direction == 'to') ? $email : null;
88
        $from = ($direction == 'from') ? $email : null;
89
        $match = $this->mailer->findEmail($to, $from, $subject);
90
        $allMails = $this->mailer->findEmails($to, $from);
91
        $allTitles = $allMails ? '"' . implode('","', array_map(function($email) {return $email->Subject;}, $allMails)) . '"' : null;
92
        if(trim($negate)) {
93
            assertNull($match);
94
        } else {
95
            $msg = sprintf(
96
                'Could not find email %s "%s" titled "%s".',
97
                $direction,
98
                $email,
99
                $subject
100
            );
101
            if($allTitles) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $allTitles of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
102
                $msg .= ' Existing emails: ' . $allTitles;
103
            }
104
            assertNotNull($match,$msg);
105
        }
106
        $this->lastMatchedEmail = $match;
107
    }
108
109
    /**
110
     * Example: Given the email should contain "Thank you for registering!".
111
     * Assumes an email has been identified by a previous step,
112
     * e.g. through 'Given there should be an email to "[email protected]"'.
113
     * 
114
	 * @Given /^the email should (not |)contain "([^"]*)"$/
115
	 */
116
	public function thereTheEmailContains($negate, $content)
117
	{
118
		if(!$this->lastMatchedEmail) {
119
			throw new \LogicException('No matched email found from previous step');
120
		}
121
122
		$email = $this->lastMatchedEmail;
123
		$emailContent = null;
0 ignored issues
show
Unused Code introduced by
$emailContent 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...
124
		if($email->Content) {
125
			$emailContent = $email->Content;
126
		} else {
127
			$emailContent = $email->PlainContent;
128
		}
129
130
		if(trim($negate)) {
131
			assertNotContains($content, $emailContent);
132
		} else {
133
			assertContains($content, $emailContent);
134
		}
135
	}
136
137
    /**
138
     * @When /^I click on the "([^"]*)" link in the email (to|from) "([^"]*)"$/
139
     */
140 View Code Duplication
    public function iGoToInTheEmailTo($linkSelector, $direction, $email)
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...
141
    {
142
        $to = ($direction == 'to') ? $email : null;
143
        $from = ($direction == 'from') ? $email : null;
144
        $match = $this->mailer->findEmail($to, $from);
145
        assertNotNull($match);
146
147
        $crawler = new Crawler($match->Content);
148
        $linkEl = $crawler->selectLink($linkSelector);
149
        assertNotNull($linkEl);
150
        $link = $linkEl->attr('href');
151
        assertNotNull($link);
152
        
153
        return new Step\When(sprintf('I go to "%s"', $link));
154
    }
155
156
    /**
157
     * @When /^I click on the "([^"]*)" link in the email (to|from) "([^"]*)" titled "([^"]*)"$/
158
     */
159 View Code Duplication
    public function iGoToInTheEmailToTitled($linkSelector, $direction, $email, $title)
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...
160
    {
161
        $to = ($direction == 'to') ? $email : null;
162
        $from = ($direction == 'from') ? $email : null;
163
        $match = $this->mailer->findEmail($to, $from, $title);
164
        assertNotNull($match);
165
166
        $crawler = new Crawler($match->Content);
167
        $linkEl = $crawler->selectLink($linkSelector);
168
        assertNotNull($linkEl);
169
        $link = $linkEl->attr('href');
170
        assertNotNull($link);
171
        return new Step\When(sprintf('I go to "%s"', $link));
172
    }
173
    
174
    /**
175
     * Assumes an email has been identified by a previous step,
176
     * e.g. through 'Given there should be an email to "[email protected]"'.
177
     * 
178
     * @When /^I click on the "([^"]*)" link in the email"$/
179
     */
180
    public function iGoToInTheEmail($linkSelector)
181
    {
182
        if(!$this->lastMatchedEmail) {
183
            throw new \LogicException('No matched email found from previous step');
184
        }
185
186
        $match = $this->lastMatchedEmail;
187
        $crawler = new Crawler($match->Content);
188
        $linkEl = $crawler->selectLink($linkSelector);
189
        assertNotNull($linkEl);
190
        $link = $linkEl->attr('href');
191
        assertNotNull($link);
192
193
        return new Step\When(sprintf('I go to "%s"', $link));
194
    }
195
196
    /**
197
     * @Given /^I clear all emails$/
198
     */
199
    public function iClearAllEmails()
200
    {
201
        $this->lastMatchedEmail = null;
202
        return $this->mailer->clearEmails();
203
    }
204
205
	/**
206
	 * Example: Then the email should contain the following data:
207
	 * | row1 |
208
	 * | row2 |
209
	 * Assumes an email has been identified by a previous step.
210
	 * @Then /^the email should (not |)contain the following data:$/
211
	 */
212
	public function theEmailContainFollowingData($negate, TableNode $table) {
213
		if(!$this->lastMatchedEmail) {
214
			throw new \LogicException('No matched email found from previous step');
215
		}
216
217
		$email = $this->lastMatchedEmail;
218
		$emailContent = null;
0 ignored issues
show
Unused Code introduced by
$emailContent 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...
219
		if($email->Content) {
220
			$emailContent = $email->Content;
221
		} else {
222
			$emailContent = $email->PlainContent;
223
		}
224
		// Convert html content to plain text
225
		$emailContent = strip_tags($emailContent);
226
		$rows = $table->getRows();
227
		
228
		// For "should not contain"
229
		if(trim($negate)) {
230
			foreach($rows as $row) {
231
				assertNotContains($row[0], $emailContent);
232
			}
233
		} else {
234
			foreach($rows as $row) {
235
				assertContains($row[0], $emailContent);
236
			}
237
		}
238
	}
239
240
	/**
241
	 * @Then /^there should (not |)be an email titled "([^"]*)"$/
242
	 */
243
	public function thereIsAnEmailTitled($negate, $subject)
244
	{
245
		$match = $this->mailer->findEmail(null, null, $subject);
246
		if(trim($negate)) {
247
			assertNull($match);
248
		} else {
249
			$msg = sprintf(
250
				'Could not find email titled "%s".',
251
				$subject
252
			);
253
			assertNotNull($match,$msg);
254
		}
255
		$this->lastMatchedEmail = $match;
256
	}
257
258
	/**
259
	 * @Then /^the email should (not |)be sent from "([^"]*)"$/
260
	 */
261 View Code Duplication
	public function theEmailSentFrom($negate, $from)
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...
262
	{
263
		if(!$this->lastMatchedEmail) {
264
			throw new \LogicException('No matched email found from previous step');
265
		}
266
267
		$match = $this->lastMatchedEmail;
268
		if(trim($negate)) {
269
			assertNotContains($from, $match->From);
270
		} else {
271
			assertContains($from, $match->From);
272
		}
273
	}
274
275
	/**
276
	 * @Then /^the email should (not |)be sent to "([^"]*)"$/
277
	 */
278 View Code Duplication
	public function theEmailSentTo($negate, $to)
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...
279
	{
280
		if(!$this->lastMatchedEmail) {
281
			throw new \LogicException('No matched email found from previous step');
282
		}
283
284
		$match = $this->lastMatchedEmail;
285
		if(trim($negate)) {
286
			assertNotContains($to, $match->To);
287
		} else {
288
			assertContains($to, $match->To);
289
		}
290
	}
291
}
292