Completed
Push — master ( 271fbf...1d6cf1 )
by Daniel
02:13
created

BlogTest   B

Complexity

Total Complexity 20

Size/Duplication

Total Lines 381
Duplicated Lines 14.17 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 20
c 5
b 1
f 1
lcom 1
cbo 17
dl 54
loc 381
rs 7.8571

15 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 14 1
A tearDown() 0 7 1
A testGetExcludedSiteTreeClassNames() 0 23 2
B testGetArchivedBlogPosts() 0 27 2
B testArchiveLinks() 0 38 1
A testArchiveYear() 0 7 1
A getStatusOf() 0 4 1
B testRoles() 0 120 1
A testFilteredCategoriesRoot() 10 10 1
A testFilteredCategoriesRSS() 10 10 1
A testFilteredCategoriesTags() 17 17 1
A testFilteredCategoriesArchive() 17 17 1
A testDisabledProfiles() 0 14 2
A requestURL() 0 13 1
A assertIDsEquals() 0 12 3

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\Blog\Tests;
4
5
use SilverStripe\Blog\Model\Blog;
6
use SilverStripe\Blog\Model\BlogController;
7
use SilverStripe\Blog\Model\BlogPost;
8
use SilverStripe\CMS\Controllers\ContentController;
9
use SilverStripe\Control\Controller;
10
use SilverStripe\Control\Director;
11
use SilverStripe\Control\HTTPRequest;
12
use SilverStripe\Control\HTTPResponse_Exception;
13
use SilverStripe\Control\Session;
14
use SilverStripe\Core\Config\Config;
15
use SilverStripe\Dev\SapphireTest;
16
use SilverStripe\ORM\DataModel;
17
use SilverStripe\ORM\FieldType\DBDatetime;
18
use SilverStripe\ORM\SS_List;
19
use SilverStripe\Security\Member;
20
use SilverStripe\Security\Security;
21
22
/**
23
 * @mixin PHPUnit_Framework_TestCase
24
 */
25
class BlogTest extends SapphireTest
26
{
27
    /**
28
     * @var string
29
     */
30
    protected static $fixture_file = 'blog.yml';
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function setUp()
36
    {
37
        parent::setUp();
38
39
        Config::nest();
40
        DBDatetime::set_mock_now('2013-10-10 20:00:00');
41
42
        /**
43
         * @var Blog $blog
44
         */
45
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
46
47
        $blog->publish('Stage', 'Live');
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function tearDown()
54
    {
55
        DBDatetime::clear_mock_now();
56
        Config::unnest();
57
58
        parent::tearDown();
59
    }
60
61
    public function testGetExcludedSiteTreeClassNames()
62
    {
63
        $member = Security::getCurrentUser();
64
65
        if ($member) {
66
            Security::setCurrentUser(null);
67
        }
68
69
        /**
70
         * @var Blog $blog
71
         */
72
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
73
74
        Config::inst()->update(BlogPost::class, 'show_in_sitetree', true);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SilverStripe\Config\Coll...nfigCollectionInterface as the method update() does only exist in the following implementations of said interface: SilverStripe\Config\Coll...s\DeltaConfigCollection, SilverStripe\Config\Coll...\MemoryConfigCollection.

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...
75
        $classes = $blog->getExcludedSiteTreeClassNames();
76
77
        $this->assertNotContains(BlogPost::class, $classes, 'BlogPost class should be hidden.');
78
79
        Config::inst()->update(BlogPost::class, 'show_in_sitetree', false);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SilverStripe\Config\Coll...nfigCollectionInterface as the method update() does only exist in the following implementations of said interface: SilverStripe\Config\Coll...s\DeltaConfigCollection, SilverStripe\Config\Coll...\MemoryConfigCollection.

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...
80
        $classes = $blog->getExcludedSiteTreeClassNames();
81
82
        $this->assertContains(BlogPost::class, $classes, 'BlogPost class should be hidden.');
83
    }
84
85
    public function testGetArchivedBlogPosts()
86
    {
87
        $member = Security::getCurrentUser();
88
89
        if ($member) {
90
            Security::setCurrentUser(null);
91
        }
92
93
        /**
94
         * @var Blog $blog
95
         */
96
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
97
98
        $archive = $blog->getArchivedBlogPosts(2013);
99
100
        $this->assertEquals(2, $archive->count(), 'Incorrect Yearly Archive count for 2013');
101
        $this->assertEquals('First Post', $archive->first()->Title, 'Incorrect First Blog post');
102
        $this->assertEquals('Second Post', $archive->last()->Title, 'Incorrect Last Blog post');
103
104
        $archive = $blog->getArchivedBlogPosts(2013, 10);
105
106
        $this->assertEquals(1, $archive->count(), 'Incorrect monthly archive count.');
107
108
        $archive = $blog->getArchivedBlogPosts(2013, 10, 01);
109
110
        $this->assertEquals(1, $archive->count(), 'Incorrect daily archive count.');
111
    }
112
113
    public function testArchiveLinks()
114
    {
115
        /**
116
         * @var Blog $blog
117
         */
118
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
119
120
        $link = Controller::join_links($blog->Link('archive'), '2013', '10', '01');
121
122
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
123
124
        $link = Controller::join_links($blog->Link('archive'), '2013', '10');
125
126
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
127
128
        $link = Controller::join_links($blog->Link('archive'), '2013');
129
130
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
131
132
        $link = Controller::join_links($blog->Link('archive'), '2011', '10', '01');
133
134
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
135
136
        $link = Controller::join_links($blog->Link('archive'));
137
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
138
139
        $link = Controller::join_links($blog->Link('archive'), 'invalid-year');
140
141
        $this->assertEquals(404, $this->getStatusOf($link), 'HTTP Status should be 404');
142
143
        $link = Controller::join_links($blog->Link('archive'), '2013', '99');
144
145
        $this->assertEquals(404, $this->getStatusOf($link), 'HTTP Status should be 404');
146
147
        $link = Controller::join_links($blog->Link('archive'), '2013', '10', '99');
148
149
        $this->assertEquals(404, $this->getStatusOf($link), 'HTTP Status should be 404');
150
    }
151
152
    /*
153
     * Test archive year
154
     */
155
    public function testArchiveYear()
156
    {
157
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
158
        $controller = new BlogController($blog);
159
        $this->requestURL($controller, 'first-post/archive/');
160
        $this->assertEquals(2013, $controller->getArchiveYear(), 'getArchiveYear should return 2013');
161
    }
162
163
    /**
164
     * @param string $link
165
     *
166
     * @return int
167
     */
168
    protected function getStatusOf($link)
169
    {
170
        return Director::test($link)->getStatusCode();
171
    }
172
173
    public function testRoles()
174
    {
175
        /**
176
         * @var Blog $firstBlog
177
         */
178
        $firstBlog = $this->objFromFixture(Blog::class, 'FirstBlog');
179
180
        /**
181
         * @var Blog $fourthBlog
182
         */
183
        $fourthBlog = $this->objFromFixture(Blog::class, 'FourthBlog');
184
185
        /**
186
         * @var BlogPost $postA
187
         */
188
        $postA = $this->objFromFixture(BlogPost::class, 'PostA');
189
190
        /**
191
         * @var BlogPost $postB
192
         */
193
        $postB = $this->objFromFixture(BlogPost::class, 'PostB');
194
195
        /**
196
         * @var BlogPost $postC
197
         */
198
        $postC = $this->objFromFixture(BlogPost::class, 'PostC');
199
200
        /**
201
         * @var Member $editor
202
         */
203
        $editor = $this->objFromFixture(Member::class, 'BlogEditor');
204
205
        /**
206
         * @var Member $writer
207
         */
208
        $writer = $this->objFromFixture(Member::class, 'Writer');
209
210
        /**
211
         * @var Member $contributor
212
         */
213
        $contributor = $this->objFromFixture(Member::class, 'Contributor');
214
215
        /**
216
         * @var Member $visitor
217
         */
218
        $visitor = $this->objFromFixture(Member::class, 'Visitor');
219
220
        $this->assertEquals('Editor', $fourthBlog->RoleOf($editor));
221
        $this->assertEquals('Contributor', $fourthBlog->RoleOf($contributor));
222
        $this->assertEquals('Writer', $fourthBlog->RoleOf($writer));
223
        $this->assertEmpty($fourthBlog->RoleOf($visitor));
224
        $this->assertEquals('Author', $postA->RoleOf($writer));
225
        $this->assertEquals('Author', $postA->RoleOf($contributor));
226
        $this->assertEquals('Editor', $postA->RoleOf($editor));
227
        $this->assertEmpty($postA->RoleOf($visitor));
228
229
        // Test RoleOf with string values given
230
        $this->assertEquals('Editor', $fourthBlog->RoleOf((string)(int)$editor->ID));
231
        $this->assertEquals('Contributor', $fourthBlog->RoleOf((string)(int)$contributor->ID));
232
        $this->assertEquals('Writer', $fourthBlog->RoleOf((string)(int)$writer->ID));
233
        $this->assertEmpty($fourthBlog->RoleOf((string)(int)$visitor->ID));
234
        $this->assertEquals('Author', $postA->RoleOf((string)(int)$writer->ID));
235
        $this->assertEquals('Author', $postA->RoleOf((string)(int)$contributor->ID));
236
        $this->assertEquals('Editor', $postA->RoleOf((string)(int)$editor->ID));
237
        $this->assertEmpty($postA->RoleOf((string)(int)$visitor->ID));
238
239
        // Test RoleOf with int values given
240
        $this->assertEquals('Editor', $fourthBlog->RoleOf((int)$editor->ID));
241
        $this->assertEquals('Contributor', $fourthBlog->RoleOf((int)$contributor->ID));
242
        $this->assertEquals('Writer', $fourthBlog->RoleOf((int)$writer->ID));
243
        $this->assertEmpty($fourthBlog->RoleOf((int)$visitor->ID));
244
        $this->assertEquals('Author', $postA->RoleOf((int)$writer->ID));
245
        $this->assertEquals('Author', $postA->RoleOf((int)$contributor->ID));
246
        $this->assertEquals('Editor', $postA->RoleOf((int)$editor->ID));
247
        $this->assertEmpty($postA->RoleOf((int)$visitor->ID));
248
249
        $this->assertTrue($fourthBlog->canEdit($editor));
250
        $this->assertFalse($firstBlog->canEdit($editor));
251
        $this->assertTrue($fourthBlog->canAddChildren($editor));
252
        $this->assertFalse($firstBlog->canAddChildren($editor));
253
        $this->assertTrue($postA->canEdit($editor));
254
        $this->assertTrue($postB->canEdit($editor));
255
        $this->assertTrue($postC->canEdit($editor));
256
        $this->assertTrue($postA->canPublish($editor));
257
        $this->assertTrue($postB->canPublish($editor));
258
        $this->assertTrue($postC->canPublish($editor));
259
260
        $this->assertFalse($fourthBlog->canEdit($writer));
261
        $this->assertFalse($firstBlog->canEdit($writer));
262
        $this->assertTrue($fourthBlog->canAddChildren($writer));
263
        $this->assertFalse($firstBlog->canAddChildren($writer));
264
        $this->assertTrue($postA->canEdit($writer));
265
        $this->assertFalse($postB->canEdit($writer));
266
        $this->assertTrue($postC->canEdit($writer));
267
        $this->assertTrue($postA->canPublish($writer));
268
        $this->assertFalse($postB->canPublish($writer));
269
        $this->assertTrue($postC->canPublish($writer));
270
271
        $this->assertFalse($fourthBlog->canEdit($contributor));
272
        $this->assertFalse($firstBlog->canEdit($contributor));
273
        $this->assertTrue($fourthBlog->canAddChildren($contributor));
274
        $this->assertFalse($firstBlog->canAddChildren($contributor));
275
        $this->assertTrue($postA->canEdit($contributor));
276
        $this->assertFalse($postB->canEdit($contributor));
277
        $this->assertTrue($postC->canEdit($contributor));
278
        $this->assertFalse($postA->canPublish($contributor));
279
        $this->assertFalse($postB->canPublish($contributor));
280
        $this->assertFalse($postC->canPublish($contributor));
281
282
        $this->assertFalse($fourthBlog->canEdit($visitor));
283
        $this->assertFalse($firstBlog->canEdit($visitor));
284
        $this->assertFalse($fourthBlog->canAddChildren($visitor));
285
        $this->assertFalse($firstBlog->canAddChildren($visitor));
286
        $this->assertFalse($postA->canEdit($visitor));
287
        $this->assertFalse($postB->canEdit($visitor));
288
        $this->assertFalse($postC->canEdit($visitor));
289
        $this->assertFalse($postA->canPublish($visitor));
290
        $this->assertFalse($postB->canPublish($visitor));
291
        $this->assertFalse($postC->canPublish($visitor));
292
    }
293
294 View Code Duplication
    public function testFilteredCategoriesRoot()
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...
295
    {
296
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
297
        $controller = new BlogController($blog);
298
        $this->requestURL($controller, 'first-post');
299
        $this->assertIDsEquals(
300
            $blog->AllChildren()->column('ID'),
301
            $controller->PaginatedList()->column('ID')
302
        );
303
    }
304
305 View Code Duplication
    public function testFilteredCategoriesRSS()
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...
306
    {
307
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
308
        $controller = new BlogController($blog);
309
        $this->requestURL($controller, 'first-post/rss');
310
        $this->assertIDsEquals(
311
            $blog->AllChildren()->column('ID'),
312
            $controller->PaginatedList()->column('ID')
313
        );
314
    }
315
316 View Code Duplication
    public function testFilteredCategoriesTags()
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...
317
    {
318
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
319
        $controller = new BlogController($blog);
320
321
        // Posts
322
        $firstPostID = $this->idFromFixture(BlogPost::class, 'FirstBlogPost');
323
        $firstFuturePostID = $this->idFromFixture(BlogPost::class, 'FirstFutureBlogPost');
324
        $secondFuturePostID = $this->idFromFixture(BlogPost::class, 'SecondFutureBlogPost');
325
326
        // Request first tag
327
        $this->requestURL($controller, 'first-post/tag/first-tag');
328
        $this->assertIDsEquals(
329
            [$firstPostID, $firstFuturePostID, $secondFuturePostID],
330
            $controller->PaginatedList()
331
        );
332
    }
333
334 View Code Duplication
    public function testFilteredCategoriesArchive()
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...
335
    {
336
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
337
        $controller = new BlogController($blog);
338
339
        // Posts
340
        $firstPostID = $this->idFromFixture(BlogPost::class, 'FirstBlogPost');
341
        $secondPostID = $this->idFromFixture(BlogPost::class, 'SecondBlogPost');
342
        $secondFuturePostID = $this->idFromFixture(BlogPost::class, 'SecondFutureBlogPost');
343
344
        // Request 2013 posts
345
        $this->requestURL($controller, 'first-post/archive/2013');
346
        $this->assertIDsEquals(
347
            [$firstPostID, $secondPostID, $secondFuturePostID],
348
            $controller->PaginatedList()
349
        );
350
    }
351
352
    public function testDisabledProfiles()
353
    {
354
        Config::modify()->set(BlogController::class, 'disable_profiles', true);
355
356
        try {
357
            $controller = BlogController::create();
358
            $controller->setRequest(Controller::curr()->getRequest());
359
            $controller->profile();
360
361
            $this->fail('The "profile" action should throw a HTTPResponse_Exception when disable_profiles is enabled');
362
        } catch (HTTPResponse_Exception $e) {
363
            $this->assertEquals(404, $e->getResponse()->getStatusCode(), 'The response status code should be 404 Not Found');
364
        }
365
    }
366
367
    /**
368
     * Mock a request against a given controller
369
     *
370
     * @param ContentController $controller
371
     * @param string $url
372
     */
373
    protected function requestURL(ContentController $controller, $url)
374
    {
375
        $request = new HTTPRequest('get', $url);
376
        $request->match('$URLSegment//$Action/$ID/$OtherID');
377
        $request->shift();
378
        $session = new Session(null);
379
        $session->start($request);
380
        $request->setSession($session);
381
        $controller->doInit();
382
        $controller->handleRequest($request);
383
        $session->clearAll();
384
        $session->destroy();
385
    }
386
387
    /**
388
     * Assert these id lists match
389
     *
390
     * @param array|SS_List $left
391
     * @param array|SS_List $right
392
     */
393
    protected function assertIDsEquals($left, $right)
394
    {
395
        if ($left instanceof SS_List) {
396
            $left = $left->column('ID');
397
        }
398
        if ($right instanceof SS_List) {
399
            $right = $right->column('ID');
400
        }
401
        asort($left);
402
        asort($right);
403
        $this->assertEquals(array_values($left), array_values($right));
404
    }
405
}
406