Completed
Pull Request — master (#372)
by Michael
02:28
created

BlogTag::validate()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 20
Code Lines 14

Duplication

Lines 20
Ratio 100 %
Metric Value
dl 20
loc 20
rs 8.8571
cc 6
eloc 14
nc 6
nop 0
1
<?php
2
3
/**
4
 * A blog tag for keyword descriptions of a blog post.
5
 *
6
 * @package silverstripe
7
 * @subpackage blog
8
 *
9
 * @method Blog Blog()
10
 *
11
 * @property string $Title
12
 * @property string $URLSegment
13
 * @property int $BlogID
14
 */
15 View Code Duplication
class BlogTag extends DataObject implements CategorisationObject
0 ignored issues
show
Duplication introduced by
This class 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...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
16
{
17
18
	/**
19
	 * Use an exception code so that attempted writes can continue on
20
	 * duplicate errors. 600 is completely arbitrary.
21
	 *
22
	 * @const int
23
	 */
24
	const DUPLICATE_EXCEPTION = 600;
25
26
    /**
27
     * @var array
28
     */
29
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
30
        'Title' => 'Varchar(255)',
31
    );
32
33
    /**
34
     * @var array
35
     */
36
    private static $has_one = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
37
        'Blog' => 'Blog',
38
    );
39
40
    /**
41
     * @var array
42
     */
43
    private static $belongs_many_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $belongs_many_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
44
        'BlogPosts' => 'BlogPost',
45
    );
46
47
    /**
48
     * @var array
49
     */
50
    private static $extensions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $extensions is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
51
        'URLSegmentExtension',
52
    );
53
54
    /**
55
     * @return DataList
56
     */
57
    public function BlogPosts()
58
    {
59
        $blogPosts = parent::BlogPosts();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DataObject as the method BlogPosts() does only exist in the following sub-classes of DataObject: BlogCategory, BlogTag. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
60
61
        $this->extend("updateGetBlogPosts", $blogPosts);
62
63
        return $blogPosts;
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function getCMSFields()
70
    {
71
        $fields = new FieldList(
72
            TextField::create('Title', _t('BlogTag.Title', 'Title'))
73
        );
74
75
        $this->extend('updateCMSFields', $fields);
76
77
        return $fields;
78
    }
79
80
	/**
81
	 * {@inheritdoc}
82
	 */
83
	protected function validate() {
84
		$validation = parent::validate();
85
		if($validation->valid()) {
86
			// Check for duplicate tags
87
			$blog = $this->Blog();
88
			if($blog && $blog->exists()) {
89
				$existing = $blog->Tags()->filter('Title', $this->Title);
90
				if($this->ID) {
91
					$existing = $existing->exclude('ID', $this->ID);
92
				}
93
				if($existing->count() > 0) {
94
					$validation->error(_t(
95
						'BlogTag.Duplicate', 
96
						'A blog tags already exists with that name'
97
					), BlogTag::DUPLICATE_EXCEPTION);
98
				}
99
			}
100
		}
101
		return $validation;
102
	}
103
104
    /**
105
     * Returns a relative URL for the tag link.
106
     *
107
     * @return string
108
     */
109
    public function getLink()
110
    {
111
        return Controller::join_links($this->Blog()->Link(), 'tag', $this->URLSegment);
112
    }
113
114
    /**
115
     * Inherits from the parent blog or can be overwritten using a DataExtension.
116
     *
117
     * @param null|Member $member
118
     *
119
     * @return bool
120
     */
121
    public function canView($member = null)
122
    {
123
        $extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 121 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
124
125
        if ($extended !== null) {
126
            return $extended;
127
        }
128
129
        return $this->Blog()->canView($member);
130
    }
131
132
    /**
133
     * Inherits from the parent blog or can be overwritten using a DataExtension.
134
     *
135
     * @param null|Member $member
136
     *
137
     * @return bool
138
     */
139
    public function canCreate($member = null)
140
    {
141
        $extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 139 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
142
143
        if ($extended !== null) {
144
            return $extended;
145
        }
146
147
        $permission = Blog::config()->grant_user_permission;
148
149
        return Permission::checkMember($member, $permission);
150
    }
151
152
    /**
153
     * Inherits from the parent blog or can be overwritten using a DataExtension.
154
     *
155
     * @param null|Member $member
156
     *
157
     * @return bool
158
     */
159
    public function canDelete($member = null)
160
    {
161
        $extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 159 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
162
163
        if ($extended !== null) {
164
            return $extended;
165
        }
166
167
        return $this->Blog()->canEdit($member);
168
    }
169
170
    /**
171
     * Inherits from the parent blog or can be overwritten using a DataExtension.
172
     *
173
     * @param null|Member $member
174
     *
175
     * @return bool
176
     */
177
    public function canEdit($member = null)
178
    {
179
        $extended = $this->extendedCan(__FUNCTION__, $member);
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 177 can be null; however, DataObject::extendedCan() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
180
181
        if ($extended !== null) {
182
            return $extended;
183
        }
184
185
        return $this->Blog()->canEdit($member);
186
    }
187
}
188