Completed
Push — master ( dbda3c...d37ed5 )
by Nicolaas
01:26
created

code/model/PageRaterExtension.php (25 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 *@author nicolaas [at] sunnysideup up .co .nz
5
 * <% loop $PageRatings %>
6
 *
7
 * <% end_loop %>
8
 *
9
 **/
10
11
class PageRaterExtension extends DataExtension
0 ignored issues
show
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...
12
{
13
    private static $db = array(
0 ignored issues
show
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...
14
        'PageRating' => 'Double(4,2)'
15
    );
16
17
    private static $has_many = array(
0 ignored issues
show
The property $has_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...
18
        'PageRatings' => 'PageRating'
19
    );
20
21
    private static $indexes = array(
0 ignored issues
show
The property $indexes 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...
22
        'PageRating' => true
23
    );
24
    /**
25
     * add the default rating to each page ...
26
     * @var boolean
27
     */
28
    private static $add_default_rating = false;
0 ignored issues
show
The property $add_default_rating 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...
29
30
31
    /**
32
     * @var boolean
33
     */
34
    private static $number_of_default_records_to_be_added = 5;
0 ignored issues
show
The property $number_of_default_records_to_be_added 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...
35
36
    public function updateCMSFields(FieldList $fields)
37
    {
38
        if ($this->owner->PageRatings() && $this->owner->PageRatings()->count()) {
39
            $fields->addFieldToTab(
40
                "Root.Ratings",
41
                GridField::create(
42
                    "PageRatings",
43
                    Injector::inst()->get("PageRating")->plural_name(),
44
                    $this->owner->PageRatings(),
45
                    GridFieldConfig_RecordViewer::create()
46
                )
47
            );
48
            $fields->addFieldToTab(
49
                "Root.Ratings",
50
                ReadonlyField::create(
51
                    "PageRating",
52
                    'Average Rating'
53
                )
54
            );
55
        }
56
    }
57
58
59
    public function requireDefaultRecords()
60
    {
61
        parent::requireDefaultRecords();
62
        $step = 50;
63
        if (Config::inst()->get("PageRaterExtension", "add_default_rating")) {
64
            for ($i = 0; $i < 1000000; $i = $i + $step) {
0 ignored issues
show
Comprehensibility Bug introduced by
Loop incrementor ($i, $i) jumbling with inner loop
Loading history...
65
                $pages = SiteTree::get()
66
                    ->leftJoin("PageRating", "\"PageRating\".\"ParentID\" = \"SiteTree\".\"ID\"")
67
                    ->where("\"PageRating\".\"ID\" IS NULL")
68
                    ->limit($step, $i);
69
70
                if ($pages->count()) {
71
                    foreach ($pages as $page) {
72
                        $count = 0;
73
                        $max = PageRating::get_number_of_stars();
74
                        $goingBackTo = ($max / rand(1, $max)) - 1;
75
                        $stepsBack = $max - $goingBackTo;
76
                        $ratings = Config::inst()->get("PageRaterExtension", "number_of_default_records_to_be_added") / $stepsBack;
77
                        for ($i = 1; $i <= $ratings; $i++) {
78
                            for ($j = $max; $j > $goingBackTo; $j--) {
79
                                $PageRating = new PageRating();
80
                                $PageRating->Rating = round(rand(1, $j));
0 ignored issues
show
The property Rating does not seem to exist. Did you mean round_rating?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
81
                                $PageRating->IsDefault = 1;
0 ignored issues
show
The property IsDefault does not exist on object<PageRating>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
82
                                $PageRating->ParentID = $page->ID;
0 ignored issues
show
The property ParentID does not exist on object<PageRating>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
83
                                $PageRating->write();
84
                                $count++;
85
                            }
86
                        }
87
                        DB::alteration_message("Created Initial Ratings for Page with title ".$page->Title.". Ratings created: $count", "created");
88
                    }
89
                } else {
90
                    $i = 1000000;
91
                }
92
            }
93
        }
94
    }
95
96
97
    /**
98
     * return the average rating...
99
     * @return Double
0 ignored issues
show
Should the return type not be integer|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
100
     */
101
    public function StarRating()
102
    {
103
        return $this->getStarRating();
104
    }
105
    /**
106
     *
107
     * @param string $character optional character (e.g. ★,
108
     *                           if supplied and the number of stars is 3
109
     *                           then it will return ★★★)
110
     * @return int|string
111
     */
112
    public function getStarRating($character = '')
113
    {
114
        $ratings = $this->owner->PageRatingResults();
115
        $rating = 0;
116
        if ($ratings->Count() == 1) {
117
            foreach ($ratings as $ratingItem) {
118
                $rating = $ratingItem->Stars;
119
            }
120
        }
121
        if ($character && $rating) {
122
            return str_repeat($character, $rating);
123
        } else {
124
            return $rating;
125
        }
126
    }
127
    /**
128
     *
129
     * @return int
130
     */
131 View Code Duplication
    public function NumberOfPageRatings()
0 ignored issues
show
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...
132
    {
133
        $doSet = new ArrayList();
0 ignored issues
show
$doSet is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
134
        $sqlQuery = new SQLQuery();
0 ignored issues
show
Deprecated Code introduced by
The class SQLQuery has been deprecated with message: since version 4.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
135
        $sqlQuery->setSelect("COUNT(\"PageRating\".\"Rating\") RatingCount");
136
        $sqlQuery->setFrom("\"PageRating\" ");
137
        if ($this->onlyShowApprovedPageRatings()) {
138
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"IsApproved\" = 1");
0 ignored issues
show
The property ID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
139
        } else {
140
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID."");
141
        }
142
        $sqlQuery->setOrderBy("RatingCount ASC");
143
        $sqlQuery->setGroupBy("\"ParentID\"");
144
        $sqlQuery->setLimit(1);
145
        $data = $sqlQuery->execute();
146
        if ($data) {
147
            foreach ($data as $record) {
148
                return $record["RatingCount"];
149
            }
150
        }
151
        return 0;
152
    }
153
154
155
    /**
156
     * rating for this page ...
157
     * @return ArrayList
158
     */
159 View Code Duplication
    public function PageRatingResults()
0 ignored issues
show
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...
160
    {
161
        $sqlQuery = new SQLQuery();
0 ignored issues
show
Deprecated Code introduced by
The class SQLQuery has been deprecated with message: since version 4.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
162
        $sqlQuery->setSelect("AVG(\"PageRating\".\"Rating\") RatingAverage, ParentID");
163
        $sqlQuery->setFrom("\"PageRating\" ");
164
        if ($this->onlyShowApprovedPageRatings()) {
165
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"IsApproved\" = 1");
0 ignored issues
show
The property ID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
166
        } else {
167
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID."");
168
        }
169
        $sqlQuery->setOrderBy("RatingAverage DESC");
170
        $sqlQuery->setGroupby("\"ParentID\"");
171
        $sqlQuery->setLimit(1);
172
        return $this->turnPageRaterSQLIntoArrayList($sqlQuery, "PageRatingResults");
173
    }
174
175
    /**
176
     * rating of this page by this user ...
177
     * @return ArrayList
178
     */
179 View Code Duplication
    public function CurrentUserRating()
0 ignored issues
show
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...
180
    {
181
        $sqlQuery = new SQLQuery();
0 ignored issues
show
Deprecated Code introduced by
The class SQLQuery has been deprecated with message: since version 4.0

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
182
        $sqlQuery->setSelect("AVG(\"PageRating\".\"Rating\") RatingAverage, ParentID");
183
        $sqlQuery->setFrom("\"PageRating\" ");
184
        if ($this->onlyShowApprovedPageRatings()) {
185
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"ID\" = '".Session::get('PageRated'.$this->owner->ID)."' AND \"PageRating\".\"IsApproved\" = 1");
0 ignored issues
show
The property ID does not seem to exist in SS_Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
186
        } else {
187
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"ID\" = '".Session::get('PageRated'.$this->owner->ID)."'");
188
        }
189
190
        $sqlQuery->setOrderBy("RatingAverage DESC");
191
        $sqlQuery->setGroupby("\"ParentID\"");
192
        $sqlQuery->setLimit(1);
193
        return $this->turnPageRaterSQLIntoArrayList($sqlQuery, "CurrentUserRating");
194
    }
195
196
197
    /**
198
     * @param $data $sqlQuery | DataList
0 ignored issues
show
The doc-type $data could not be parsed: Unknown type name "$data" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
There is no parameter named $sqlQuery. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
199
     * @param string $method
200
     *
201
     * @return ArrayList
202
     */
203 View Code Duplication
    public function turnPageRaterSQLIntoArrayList($data, $method = "unknown")
0 ignored issues
show
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...
204
    {
205
        if ($data instanceof SQLQuery) {
206
            $data = $data->execute();
207
        }
208
        $al = new ArrayList();
209
        if ($data) {
210
            foreach ($data as $record) {
211
                if ($record instanceof PageRating) {
212
                    $record->Method = $method;
0 ignored issues
show
The property Method does not seem to exist. Did you mean built_in_methods?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
213
                } else {
214
                    $score = $record["RatingAverage"];
215
                    $parentID = $record["ParentID"];
216
                    $record = PageRating::get_star_details_as_array_data($score, $parentID, $method);
217
                }
218
                $al->push($record);
219
            }
220
        }
221
        return $al;
222
    }
223
224
    public function onlyShowApprovedPageRatings()
225
    {
226
        return Config::inst()->get("PageRaterExtension_Controller", "only_show_approved");
227
    }
228
}
229