Completed
Push — master ( c0b10e...49744a )
by Daniel
09:58
created

BlogPostTest   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 104
Duplicated Lines 9.62 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 10
loc 104
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A tearDown() 0 5 1
A testCanView() 0 7 1
B canViewProvider() 0 32 1
A testCandidateAuthors() 0 15 1
A testCanViewFuturePost() 10 10 1
A testGetDate() 0 8 1

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\BlogPost;
6
use SilverStripe\Core\Config\Config;
7
use SilverStripe\Dev\SapphireTest;
8
use SilverStripe\ORM\FieldType\DBDatetime;
9
use SilverStripe\Security\Member;
10
11
class BlogPostTest extends SapphireTest
12
{
13
    /**
14
     * {@inheritDoc}
15
     * @var string
16
     */
17
    protected static $fixture_file = 'blog.yml';
18
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function tearDown()
23
    {
24
        DBDatetime::clear_mock_now();
25
        parent::tearDown();
26
    }
27
28
    /**
29
     * @dataProvider canViewProvider
30
     */
31
    public function testCanView($date, $user, $page, $canView)
32
    {
33
        $userRecord = $this->objFromFixture(Member::class, $user);
34
        $pageRecord = $this->objFromFixture(BlogPost::class, $page);
35
        DBDatetime::set_mock_now($date);
36
        $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 33 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...
37
    }
38
39
    /**
40
     * @return array
41
     */
42
    public function canViewProvider()
43
    {
44
        $someFutureDate = '2013-10-10 20:00:00';
45
        $somePastDate = '2009-10-10 20:00:00';
46
        return [
47
            // Check this post given the date has passed
48
            [$someFutureDate, 'Editor', 'PostA', true],
49
            [$someFutureDate, 'Contributor', 'PostA', true],
50
            [$someFutureDate, 'BlogEditor', 'PostA', true],
51
            [$someFutureDate, 'Writer', 'PostA', true],
52
53
            // Check unpublished pages
54
            [$somePastDate, 'Editor', 'PostA', true],
55
            [$somePastDate, 'Contributor', 'PostA', true],
56
            [$somePastDate, 'BlogEditor', 'PostA', true],
57
            [$somePastDate, 'Writer', 'PostA', true],
58
59
            // Test a page that was authored by another user
60
61
            // Check this post given the date has passed
62
            [$someFutureDate, 'Editor', 'FirstBlogPost', true],
63
            [$someFutureDate, 'Contributor', 'FirstBlogPost', true],
64
            [$someFutureDate, 'BlogEditor', 'FirstBlogPost', true],
65
            [$someFutureDate, 'Writer', 'FirstBlogPost', true],
66
67
            // Check future pages - non-editors shouldn't be able to see this
68
            [$somePastDate, 'Editor', 'FirstBlogPost', true],
69
            [$somePastDate, 'Contributor', 'FirstBlogPost', false],
70
            [$somePastDate, 'BlogEditor', 'FirstBlogPost', false],
71
            [$somePastDate, 'Writer', 'FirstBlogPost', false],
72
        ];
73
    }
74
75
    public function testCandidateAuthors()
76
    {
77
        $blogpost = $this->objFromFixture(BlogPost::class, 'PostC');
78
79
        $this->assertEquals(7, $blogpost->getCandidateAuthors()->count());
80
81
        //Set the group to draw Members from
82
        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...
83
84
        $this->assertEquals(3, $blogpost->getCandidateAuthors()->count());
85
86
        // Test cms field is generated
87
        $fields = $blogpost->getCMSFields();
88
        $this->assertNotEmpty($fields->dataFieldByName('Authors'));
89
    }
90
91 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...
92
    {
93
        $blogPost = $this->objFromFixture(BlogPost::class, 'NullPublishDate');
94
95
        $editor = $this->objFromFixture(Member::class, 'BlogEditor');
96
        $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 95 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...
97
98
        $visitor = $this->objFromFixture(Member::class, 'Visitor');
99
        $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 98 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...
100
    }
101
102
    /**
103
     * The purpose of getDate() is to act as a proxy for PublishDate in the default RSS
104
     * template, rather than copying the entire template.
105
     */
106
    public function testGetDate()
107
    {
108
        $blogPost = $this->objFromFixture(BlogPost::class, 'NullPublishDate');
109
        $this->assertNull($blogPost->getDate());
110
111
        $blogPost = $this->objFromFixture(BlogPost::class, 'PostA');
112
        $this->assertEquals('2012-01-09 15:00:00', $blogPost->getDate());
113
    }
114
}
115