Completed
Push — master ( a5af43...5fe077 )
by
unknown
12s
created

BlogPostTest::monthlyArchiveLinkProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace SilverStripe\Blog\Tests;
4
5
use SilverStripe\Blog\Model\BlogPost;
6
use SilverStripe\Core\Config\Config;
7
use SilverStripe\Dev\SapphireTest;
8
use SilverStripe\ORM\FieldType\DBDatetime;
9
use SilverStripe\Security\Member;
10
use SilverStripe\Versioned\Versioned;
11
12
class BlogPostTest extends SapphireTest
13
{
14
    protected static $fixture_file = 'blog.yml';
15
16
    protected function tearDown()
17
    {
18
        DBDatetime::clear_mock_now();
19
        parent::tearDown();
20
    }
21
22
    /**
23
     * @dataProvider canViewProvider
24
     */
25
    public function testCanView($date, $user, $page, $canView, $stage)
26
    {
27
        $userRecord = $this->objFromFixture(Member::class, $user);
28
        $pageRecord = $this->objFromFixture(BlogPost::class, $page);
29
        DBDatetime::set_mock_now($date);
30
        if ($stage === 'Live') {
31
            $pageRecord->publishSingle();
32
        }
33
34
        Versioned::set_stage($stage);
35
        $this->assertEquals($canView, $pageRecord->canView($userRecord));
0 ignored issues
show
Bug introduced by
It seems like $userRecord defined by $this->objFromFixture(\S...y\Member::class, $user) on line 27 can also be of type object<SilverStripe\ORM\DataObject>; however, SilverStripe\ORM\DataObject::canView() does only seem to accept object<SilverStripe\Security\Member>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
36
    }
37
38
    /**
39
     * @return array Format:
40
     *  - mock now date
41
     *  - user role (see fixture)
42
     *  - blog post fixture ID
43
     *  - expected result
44
     *  - versioned stage
45
     */
46
    public function canViewProvider()
47
    {
48
        $someFutureDate = '2013-10-10 20:00:00';
49
        $somePastDate = '2009-10-10 20:00:00';
50
        return [
51
            // Check this post given the date has passed
52
            [$someFutureDate, 'Editor', 'PostA', true, 'Stage'],
53
            [$someFutureDate, 'Contributor', 'PostA', true, 'Stage'],
54
            [$someFutureDate, 'BlogEditor', 'PostA', true, 'Stage'],
55
            [$someFutureDate, 'Writer', 'PostA', true, 'Stage'],
56
57
            // Check unpublished pages
58
            [$somePastDate, 'Editor', 'PostA', true, 'Stage'],
59
            [$somePastDate, 'Contributor', 'PostA', true, 'Stage'],
60
            [$somePastDate, 'BlogEditor', 'PostA', true, 'Stage'],
61
            [$somePastDate, 'Writer', 'PostA', true, 'Stage'],
62
63
64
            // Test a page that was authored by another user
65
66
            // Check this post given the date has passed
67
            [$someFutureDate, 'Editor', 'FirstBlogPost', true, 'Stage'],
68
            [$someFutureDate, 'Contributor', 'FirstBlogPost', true, 'Stage'],
69
            [$someFutureDate, 'BlogEditor', 'FirstBlogPost', true, 'Stage'],
70
            [$someFutureDate, 'Writer', 'FirstBlogPost', true, 'Stage'],
71
72
            // Check future pages in draft stage - users with "view draft pages" permission should
73
            // be able to see this, but visitors should not
74
            [$somePastDate, 'Editor', 'FirstBlogPost', true, 'Stage'],
75
            [$somePastDate, 'Contributor', 'FirstBlogPost', true, 'Stage'],
76
            [$somePastDate, 'BlogEditor', 'FirstBlogPost', true, 'Stage'],
77
            [$somePastDate, 'Writer', 'FirstBlogPost', true, 'Stage'],
78
            [$somePastDate, 'Visitor', 'FirstBlogPost', false, 'Stage'],
79
80
            // No future pages in live stage should be visible, even to users that can edit them (in draft)
81
            [$somePastDate, 'Editor', 'FirstBlogPost', false, 'Live'],
82
            [$somePastDate, 'Contributor', 'FirstBlogPost', false, 'Live'],
83
            [$somePastDate, 'BlogEditor', 'FirstBlogPost', false, 'Live'],
84
            [$somePastDate, 'Writer', 'FirstBlogPost', false, 'Live'],
85
            [$somePastDate, 'Visitor', 'FirstBlogPost', false, 'Live'],
86
        ];
87
    }
88
89
    public function testCandidateAuthors()
90
    {
91
        $blogpost = $this->objFromFixture(BlogPost::class, 'PostC');
92
93
        $this->assertEquals(7, $blogpost->getCandidateAuthors()->count());
94
95
        //Set the group to draw Members from
96
        Config::inst()->update(BlogPost::class, 'restrict_authors_to_group', 'blogusers');
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...
97
98
        $this->assertEquals(3, $blogpost->getCandidateAuthors()->count());
99
100
        // Test cms field is generated
101
        $fields = $blogpost->getCMSFields();
102
        $this->assertNotEmpty($fields->dataFieldByName('Authors'));
103
    }
104
105 View Code Duplication
    public function testCanViewFuturePost()
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...
106
    {
107
        $blogPost = $this->objFromFixture(BlogPost::class, 'NullPublishDate');
108
109
        $editor = $this->objFromFixture(Member::class, 'BlogEditor');
110
        $this->assertTrue($blogPost->canView($editor));
0 ignored issues
show
Bug introduced by
It seems like $editor defined by $this->objFromFixture(\S...r::class, 'BlogEditor') on line 109 can also be of type object<SilverStripe\ORM\DataObject>; however, SilverStripe\ORM\DataObject::canView() does only seem to accept object<SilverStripe\Security\Member>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
111
112
        $visitor = $this->objFromFixture(Member::class, 'Visitor');
113
        $this->assertFalse($blogPost->canView($visitor));
0 ignored issues
show
Bug introduced by
It seems like $visitor defined by $this->objFromFixture(\S...mber::class, 'Visitor') on line 112 can also be of type object<SilverStripe\ORM\DataObject>; however, SilverStripe\ORM\DataObject::canView() does only seem to accept object<SilverStripe\Security\Member>|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
114
    }
115
116
    /**
117
     * The purpose of getDate() is to act as a proxy for PublishDate in the default RSS
118
     * template, rather than copying the entire template.
119
     */
120
    public function testGetDate()
121
    {
122
        $blogPost = $this->objFromFixture(BlogPost::class, 'NullPublishDate');
123
        $this->assertNull($blogPost->getDate());
124
125
        $blogPost = $this->objFromFixture(BlogPost::class, 'PostA');
126
        $this->assertEquals('2012-01-09 15:00:00', $blogPost->getDate());
127
    }
128
129
    public function testMinutesToRead()
130
    {
131
        /** @var BlogPost $blogPost */
132
        $blogPost = $this->objFromFixture(BlogPost::class, 'FirstBlogPost');
133
134
        // over 400 words, should take slightly longer than 2 minutes
135
        $this->assertEquals(2, $blogPost->MinutesToRead());
136
137
        $blogPost = $this->objFromFixture(BlogPost::class, 'SecondBlogPost');
138
139
        // over 200 words, should take slighter longer than 1 minute
140
        $this->assertEquals(1, $blogPost->MinutesToRead());
141
142
        $blogPost = $this->objFromFixture(BlogPost::class, 'ThirdBlogPost');
143
        // less than 200 words, should take less than a minute thus return an integer of 0 (zero)
144
        $this->assertEquals(0, $blogPost->MinutesToRead());
145
146
        $this->expectException(\InvalidArgumentException::class);
147
        $blogPost->MinutesToRead('not-a-number');
148
    }
149
150
    /**
151
     * @param string $type
152
     * @param string $expected
153
     * @dataProvider monthlyArchiveLinkProvider
154
     * @group wip
155
     */
156 View Code Duplication
    public function testGetMonthlyArchiveLink($type, $expected)
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...
157
    {
158
        /** @var BlogPost $blogPost */
159
        $blogPost = $this->objFromFixture(BlogPost::class, 'FirstBlogPost');
160
161
        $archiveLink = $blogPost->getMonthlyArchiveLink($type);
162
        $this->assertContains('archive/', $archiveLink);
163
        $this->assertStringEndsWith($expected, $archiveLink);
164
    }
165
166
    /**
167
     * @return array[]
168
     */
169
    public function monthlyArchiveLinkProvider()
170
    {
171
        return [
172
            ['day', '/2013/10/1'],
173
            ['month', '/2013/10'],
174
            ['year', '/2013'],
175
        ];
176
    }
177
178 View Code Duplication
    public function testGetYearlyArchiveLink()
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...
179
    {
180
        /** @var BlogPost $blogPost */
181
        $blogPost = $this->objFromFixture(BlogPost::class, 'FirstBlogPost');
182
183
        $archiveLink = $blogPost->getYearlyArchiveLink();
184
        $this->assertContains('archive/', $archiveLink);
185
        $this->assertStringEndsWith('/2013', $archiveLink);
186
    }
187
}
188