Completed
Push — master ( d520d9...2d6225 )
by
unknown
12s
created

BlogTest::testGetArchivedBlogPosts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
3
namespace SilverStripe\Blog\Tests;
4
5
use PHPUnit_Framework_TestCase;
6
use SilverStripe\Blog\Model\Blog;
7
use SilverStripe\Blog\Model\BlogController;
8
use SilverStripe\Blog\Model\BlogPost;
9
use SilverStripe\CMS\Controllers\ContentController;
10
use SilverStripe\Control\Controller;
11
use SilverStripe\Control\Director;
12
use SilverStripe\Control\HTTPRequest;
13
use SilverStripe\Control\Session;
14
use SilverStripe\Core\Config\Config;
15
use SilverStripe\Dev\SapphireTest;
16
use SilverStripe\ORM\FieldType\DBDatetime;
17
use SilverStripe\ORM\SS_List;
18
use SilverStripe\Security\Member;
19
20
/**
21
 * @mixin PHPUnit_Framework_TestCase
22
 */
23
class BlogTest extends SapphireTest
24
{
25
    protected static $fixture_file = 'blog.yml';
26
27
    protected function setUp()
28
    {
29
        parent::setUp();
30
31
        DBDatetime::set_mock_now('2013-10-10 20:00:00');
32
33
        /**
34
         * @var Blog $blog
35
         */
36
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
37
        $blog->publishRecursive();
38
    }
39
40
    protected function tearDown()
41
    {
42
        DBDatetime::clear_mock_now();
43
44
        parent::tearDown();
45
    }
46
47
    public function testGetExcludedSiteTreeClassNames()
48
    {
49
        $this->logOut();
50
51
        /**
52
         * @var Blog $blog
53
         */
54
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
55
56
        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...
57
        $classes = $blog->getExcludedSiteTreeClassNames();
58
59
        $this->assertNotContains(BlogPost::class, $classes, 'BlogPost class should be hidden.');
60
61
        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...
62
        $classes = $blog->getExcludedSiteTreeClassNames();
63
64
        $this->assertContains(BlogPost::class, $classes, 'BlogPost class should be hidden.');
65
    }
66
67
    public function testGetArchivedBlogPosts()
68
    {
69
        $this->logOut();
70
71
        /**
72
         * @var Blog $blog
73
         */
74
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
75
76
        $archive = $blog->getArchivedBlogPosts(2013);
77
78
        $this->assertEquals(2, $archive->count(), 'Incorrect Yearly Archive count for 2013');
79
        $this->assertEquals('First Post', $archive->first()->Title, 'Incorrect First Blog post');
80
        $this->assertEquals('Second Post', $archive->last()->Title, 'Incorrect Last Blog post');
81
82
        $archive = $blog->getArchivedBlogPosts(2013, 10);
83
84
        $this->assertEquals(1, $archive->count(), 'Incorrect monthly archive count.');
85
86
        $archive = $blog->getArchivedBlogPosts(2013, 10, 01);
87
88
        $this->assertEquals(1, $archive->count(), 'Incorrect daily archive count.');
89
    }
90
91
    public function testArchiveLinks()
92
    {
93
        /**
94
         * @var Blog $blog
95
         */
96
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
97
98
        $link = Controller::join_links($blog->Link('archive'), '2013', '10', '01');
99
100
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
101
102
        $link = Controller::join_links($blog->Link('archive'), '2013', '10');
103
104
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
105
106
        $link = Controller::join_links($blog->Link('archive'), '2013');
107
108
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
109
110
        $link = Controller::join_links($blog->Link('archive'), '2011', '10', '01');
111
112
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
113
114
        $link = Controller::join_links($blog->Link('archive'));
115
        $this->assertEquals(200, $this->getStatusOf($link), 'HTTP Status should be 200');
116
117
        $link = Controller::join_links($blog->Link('archive'), 'invalid-year');
118
119
        $this->assertEquals(404, $this->getStatusOf($link), 'HTTP Status should be 404');
120
121
        $link = Controller::join_links($blog->Link('archive'), '2013', '99');
122
123
        $this->assertEquals(404, $this->getStatusOf($link), 'HTTP Status should be 404');
124
125
        $link = Controller::join_links($blog->Link('archive'), '2013', '10', '99');
126
127
        $this->assertEquals(404, $this->getStatusOf($link), 'HTTP Status should be 404');
128
    }
129
130
    /*
131
     * Test archive year
132
     */
133
    public function testArchiveYear()
134
    {
135
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
136
        $controller = new BlogController($blog);
137
        $this->requestURL($controller, 'first-post/archive/');
138
        $this->assertEquals(2013, $controller->getArchiveYear(), 'getArchiveYear should return 2013');
139
    }
140
141
    /**
142
     * @param string $link
143
     *
144
     * @return int
145
     */
146
    protected function getStatusOf($link)
147
    {
148
        return Director::test($link)->getStatusCode();
149
    }
150
151
    public function testRoles()
152
    {
153
        /**
154
         * @var Blog $firstBlog
155
         */
156
        $firstBlog = $this->objFromFixture(Blog::class, 'FirstBlog');
157
158
        /**
159
         * @var Blog $fourthBlog
160
         */
161
        $fourthBlog = $this->objFromFixture(Blog::class, 'FourthBlog');
162
163
        /**
164
         * @var BlogPost $postA
165
         */
166
        $postA = $this->objFromFixture(BlogPost::class, 'PostA');
167
168
        /**
169
         * @var BlogPost $postB
170
         */
171
        $postB = $this->objFromFixture(BlogPost::class, 'PostB');
172
173
        /**
174
         * @var BlogPost $postC
175
         */
176
        $postC = $this->objFromFixture(BlogPost::class, 'PostC');
177
178
        /**
179
         * @var Member $editor
180
         */
181
        $editor = $this->objFromFixture(Member::class, 'BlogEditor');
182
183
        /**
184
         * @var Member $writer
185
         */
186
        $writer = $this->objFromFixture(Member::class, 'Writer');
187
188
        /**
189
         * @var Member $contributor
190
         */
191
        $contributor = $this->objFromFixture(Member::class, 'Contributor');
192
193
        /**
194
         * @var Member $visitor
195
         */
196
        $visitor = $this->objFromFixture(Member::class, 'Visitor');
197
198
        $this->assertEquals('Editor', $fourthBlog->RoleOf($editor));
199
        $this->assertEquals('Contributor', $fourthBlog->RoleOf($contributor));
200
        $this->assertEquals('Writer', $fourthBlog->RoleOf($writer));
201
        $this->assertEmpty($fourthBlog->RoleOf($visitor));
202
        $this->assertEquals('Author', $postA->RoleOf($writer));
203
        $this->assertEquals('Author', $postA->RoleOf($contributor));
204
        $this->assertEquals('Editor', $postA->RoleOf($editor));
205
        $this->assertEmpty($postA->RoleOf($visitor));
206
207
        // Test RoleOf with string values given
208
        $this->assertEquals('Editor', $fourthBlog->RoleOf((string)(int)$editor->ID));
209
        $this->assertEquals('Contributor', $fourthBlog->RoleOf((string)(int)$contributor->ID));
210
        $this->assertEquals('Writer', $fourthBlog->RoleOf((string)(int)$writer->ID));
211
        $this->assertEmpty($fourthBlog->RoleOf((string)(int)$visitor->ID));
212
        $this->assertEquals('Author', $postA->RoleOf((string)(int)$writer->ID));
213
        $this->assertEquals('Author', $postA->RoleOf((string)(int)$contributor->ID));
214
        $this->assertEquals('Editor', $postA->RoleOf((string)(int)$editor->ID));
215
        $this->assertEmpty($postA->RoleOf((string)(int)$visitor->ID));
216
217
        // Test RoleOf with int values given
218
        $this->assertEquals('Editor', $fourthBlog->RoleOf((int)$editor->ID));
219
        $this->assertEquals('Contributor', $fourthBlog->RoleOf((int)$contributor->ID));
220
        $this->assertEquals('Writer', $fourthBlog->RoleOf((int)$writer->ID));
221
        $this->assertEmpty($fourthBlog->RoleOf((int)$visitor->ID));
222
        $this->assertEquals('Author', $postA->RoleOf((int)$writer->ID));
223
        $this->assertEquals('Author', $postA->RoleOf((int)$contributor->ID));
224
        $this->assertEquals('Editor', $postA->RoleOf((int)$editor->ID));
225
        $this->assertEmpty($postA->RoleOf((int)$visitor->ID));
226
227
        $this->assertTrue($fourthBlog->canEdit($editor));
228
        $this->assertFalse($firstBlog->canEdit($editor));
229
        $this->assertTrue($fourthBlog->canAddChildren($editor));
230
        $this->assertFalse($firstBlog->canAddChildren($editor));
231
        $this->assertTrue($postA->canEdit($editor));
232
        $this->assertTrue($postB->canEdit($editor));
233
        $this->assertTrue($postC->canEdit($editor));
234
        $this->assertTrue($postA->canPublish($editor));
235
        $this->assertTrue($postB->canPublish($editor));
236
        $this->assertTrue($postC->canPublish($editor));
237
238
        $this->assertFalse($fourthBlog->canEdit($writer));
239
        $this->assertFalse($firstBlog->canEdit($writer));
240
        $this->assertTrue($fourthBlog->canAddChildren($writer));
241
        $this->assertFalse($firstBlog->canAddChildren($writer));
242
        $this->assertTrue($postA->canEdit($writer));
243
        $this->assertFalse($postB->canEdit($writer));
244
        $this->assertTrue($postC->canEdit($writer));
245
        $this->assertTrue($postA->canPublish($writer));
246
        $this->assertFalse($postB->canPublish($writer));
247
        $this->assertTrue($postC->canPublish($writer));
248
249
        $this->assertFalse($fourthBlog->canEdit($contributor));
250
        $this->assertFalse($firstBlog->canEdit($contributor));
251
        $this->assertTrue($fourthBlog->canAddChildren($contributor));
252
        $this->assertFalse($firstBlog->canAddChildren($contributor));
253
        $this->assertTrue($postA->canEdit($contributor));
254
        $this->assertFalse($postB->canEdit($contributor));
255
        $this->assertTrue($postC->canEdit($contributor));
256
        $this->assertFalse($postA->canPublish($contributor));
257
        $this->assertFalse($postB->canPublish($contributor));
258
        $this->assertFalse($postC->canPublish($contributor));
259
260
        $this->assertFalse($fourthBlog->canEdit($visitor));
261
        $this->assertFalse($firstBlog->canEdit($visitor));
262
        $this->assertFalse($fourthBlog->canAddChildren($visitor));
263
        $this->assertFalse($firstBlog->canAddChildren($visitor));
264
        $this->assertFalse($postA->canEdit($visitor));
265
        $this->assertFalse($postB->canEdit($visitor));
266
        $this->assertFalse($postC->canEdit($visitor));
267
        $this->assertFalse($postA->canPublish($visitor));
268
        $this->assertFalse($postB->canPublish($visitor));
269
        $this->assertFalse($postC->canPublish($visitor));
270
    }
271
272 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...
273
    {
274
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
275
        $controller = new BlogController($blog);
276
        $this->requestURL($controller, 'first-post');
277
        $this->assertIDsEquals(
278
            $blog->AllChildren()->column('ID'),
279
            $controller->PaginatedList()->column('ID')
280
        );
281
    }
282
283 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...
284
    {
285
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
286
        $controller = new BlogController($blog);
287
        $this->requestURL($controller, 'first-post/rss');
288
        $this->assertIDsEquals(
289
            $blog->AllChildren()->column('ID'),
290
            $controller->PaginatedList()->column('ID')
291
        );
292
    }
293
294 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...
295
    {
296
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
297
        $controller = new BlogController($blog);
298
299
        // Posts
300
        $firstPostID = $this->idFromFixture(BlogPost::class, 'FirstBlogPost');
301
        $firstFuturePostID = $this->idFromFixture(BlogPost::class, 'FirstFutureBlogPost');
302
        $secondFuturePostID = $this->idFromFixture(BlogPost::class, 'SecondFutureBlogPost');
303
304
        // Request first tag
305
        $this->requestURL($controller, 'first-post/tag/first-tag');
306
        $this->assertIDsEquals(
307
            [$firstPostID, $firstFuturePostID, $secondFuturePostID],
308
            $controller->PaginatedList()
309
        );
310
    }
311
312 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...
313
    {
314
        $blog = $this->objFromFixture(Blog::class, 'FirstBlog');
315
        $controller = new BlogController($blog);
316
317
        // Posts
318
        $firstPostID = $this->idFromFixture(BlogPost::class, 'FirstBlogPost');
319
        $secondPostID = $this->idFromFixture(BlogPost::class, 'SecondBlogPost');
320
        $secondFuturePostID = $this->idFromFixture(BlogPost::class, 'SecondFutureBlogPost');
321
322
        // Request 2013 posts
323
        $this->requestURL($controller, 'first-post/archive/2013');
324
        $this->assertIDsEquals(
325
            [$firstPostID, $secondPostID, $secondFuturePostID],
326
            $controller->PaginatedList()
327
        );
328
    }
329
330
    /**
331
     * @expectedException \SilverStripe\Control\HTTPResponse_Exception
332
     * @expectedExceptionCode 404
333
     */
334
    public function testDisabledProfiles()
335
    {
336
        Config::modify()->set(BlogController::class, 'disable_profiles', true);
337
338
        $controller = BlogController::create();
339
        $controller->setRequest(Controller::curr()->getRequest());
340
        $controller->profile();
341
    }
342
343
    /**
344
     * Mock a request against a given controller
345
     *
346
     * @param ContentController $controller
347
     * @param string $url
348
     */
349
    protected function requestURL(ContentController $controller, $url)
350
    {
351
        $request = new HTTPRequest('get', $url);
352
        $request->match('$URLSegment//$Action/$ID/$OtherID');
353
        $request->shift();
354
        $session = new Session(null);
355
        $session->start($request);
356
        $request->setSession($session);
357
        $controller->doInit();
358
        $controller->handleRequest($request);
359
        $session->clearAll();
360
        $session->destroy();
361
    }
362
363
    /**
364
     * Assert these id lists match
365
     *
366
     * @param array|SS_List $left
367
     * @param array|SS_List $right
368
     */
369
    protected function assertIDsEquals($left, $right)
370
    {
371
        if ($left instanceof SS_List) {
372
            $left = $left->column('ID');
373
        }
374
        if ($right instanceof SS_List) {
375
            $right = $right->column('ID');
376
        }
377
        asort($left);
378
        asort($right);
379
        $this->assertEquals(array_values($left), array_values($right));
380
    }
381
}
382