Completed
Push — master ( 2bbd99...96882f )
by Nicolaas
05:57
created

PageRaterExtension::onlyShowApprovedPageRatings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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 $has_many = array(
0 ignored issues
show
Unused Code introduced by
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...
14
        'PageRatings' => 'PageRating'
15
    );
16
17
    /**
18
     * add the default rating to each page ...
19
     * @var boolean
20
     */
21
    private static $add_default_rating = false;
0 ignored issues
show
Unused Code introduced by
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...
22
23
24
    /**
25
     * @var boolean
26
     */
27
    private static $number_of_default_records_to_be_added = 5;
0 ignored issues
show
Unused Code introduced by
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...
28
29
    public function updateCMSFields(FieldList $fields)
30
    {
31
        if ($this->owner->PageRatings() && $this->owner->PageRatings()->count()) {
32
            $fields->addFieldToTab(
33
                "Root.Ratings",
34
                GridField::create(
35
                    "PageRatings",
36
                    Injector::inst()->get("PageRating")->plural_name(),
37
                    $this->owner->PageRatings(),
38
                    GridFieldConfig_RecordViewer::create()
39
                )
40
            );
41
        }
42
    }
43
44
45
    public function requireDefaultRecords()
46
    {
47
        parent::requireDefaultRecords();
48
        $step = 50;
49
        if (Config::inst()->get("PageRaterExtension", "add_default_rating")) {
50
            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...
51
                $pages = SiteTree::get()
52
                    ->leftJoin("PageRating", "\"PageRating\".\"ParentID\" = \"SiteTree\".\"ID\"")
53
                    ->where("\"PageRating\".\"ID\" IS NULL")
54
                    ->limit($step, $i);
55
56
                if ($pages->count()) {
57
                    foreach ($pages as $page) {
58
                        $count = 0;
59
                        $max = PageRating::get_number_of_stars();
60
                        $goingBackTo = ($max / rand(1, $max)) - 1;
61
                        $stepsBack = $max - $goingBackTo;
62
                        $ratings = Config::inst()->get("PageRaterExtension", "number_of_default_records_to_be_added") / $stepsBack;
63
                        for ($i = 1; $i <= $ratings; $i++) {
64
                            for ($j = $max; $j > $goingBackTo; $j--) {
65
                                $PageRating = new PageRating();
66
                                $PageRating->Rating = round(rand(1, $j));
0 ignored issues
show
Bug introduced by
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...
67
                                $PageRating->IsDefault = 1;
0 ignored issues
show
Documentation introduced by
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...
68
                                $PageRating->ParentID = $page->ID;
0 ignored issues
show
Documentation introduced by
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...
69
                                $PageRating->write();
70
                                $count++;
71
                            }
72
                        }
73
                        DB::alteration_message("Created Initial Ratings for Page with title ".$page->Title.". Ratings created: $count", "created");
74
                    }
75
                } else {
76
                    $i = 1000000;
77
                }
78
            }
79
        }
80
    }
81
82
83
    /**
84
     * return the average rating...
85
     * @return Double
86
     */
87
    public function StarRating()
88
    {
89
        return $this->getStarRating();
90
    }
91
    public function getStarRating()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
92
    {
93
        $ratings = $this->owner->PageRatingResults();
94
        $rating = 0;
95
        if ($ratings->Count() == 1) {
96
            foreach ($ratings as $ratingItem) {
97
                $rating = $ratingItem->Stars;
98
            }
99
        }
100
        return $rating;
101
    }
102
    /**
103
     *
104
     * @return int
105
     */
106
    public function NumberOfPageRatings()
107
    {
108
        $doSet = new ArrayList();
0 ignored issues
show
Unused Code introduced by
$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...
109
        $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...
110
        $sqlQuery->setSelect("COUNT(\"PageRating\".\"Rating\") RatingCount");
111
        $sqlQuery->setFrom("\"PageRating\" ");
112 View Code Duplication
        if ($this->onlyShowApprovedPageRatings()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
113
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"IsApproved\" = 1");
114
        } else {
115
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID."");
116
        }
117
        $sqlQuery->setOrderBy("RatingCount ASC");
118
        $sqlQuery->setGroupBy("\"ParentID\"");
119
        $sqlQuery->setLimit(1);
120
        $data = $sqlQuery->execute();
121
        if ($data) {
122
            foreach ($data as $record) {
123
                return $record["RatingCount"];
124
            }
125
        }
126
        return 0;
127
    }
128
129
130
    /**
131
     * rating for this page ...
132
     * @return ArrayList
133
     */
134
    public function PageRatingResults()
135
    {
136
        $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...
137
        $sqlQuery->setSelect("AVG(\"PageRating\".\"Rating\") RatingAverage, ParentID");
138
        $sqlQuery->setFrom("\"PageRating\" ");
139 View Code Duplication
        if ($this->onlyShowApprovedPageRatings()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
140
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"IsApproved\" = 1");
141
        } else {
142
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID."");
143
        }
144
        $sqlQuery->setOrderBy("RatingAverage DESC");
145
        $sqlQuery->setGroupby("\"ParentID\"");
146
        $sqlQuery->setLimit(1);
147
        return $this->turnPageRaterSQLIntoArrayList($sqlQuery, "PageRatingResults");
148
    }
149
150
    /**
151
     * rating of this page by this user ...
152
     * @return ArrayList
153
     */
154
    public function CurrentUserRating()
155
    {
156
        $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...
157
        $sqlQuery->setSelect("AVG(\"PageRating\".\"Rating\") RatingAverage, ParentID");
158
        $sqlQuery->setFrom("\"PageRating\" ");
159
        if ($this->onlyShowApprovedPageRatings()) {
160
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"ID\" = '".Session::get('PageRated'.$this->owner->ID)."' AND \"PageRating\".\"IsApproved\" = 1");
161
        } else {
162
            $sqlQuery->setWhere("\"ParentID\" = ".$this->owner->ID." AND \"PageRating\".\"ID\" = '".Session::get('PageRated'.$this->owner->ID)."'");
163
        }
164
165
        $sqlQuery->setOrderBy("RatingAverage DESC");
166
        $sqlQuery->setGroupby("\"ParentID\"");
167
        $sqlQuery->setLimit(1);
168
        return $this->turnPageRaterSQLIntoArrayList($sqlQuery, "CurrentUserRating");
169
    }
170
171
172
    /**
173
     * @param $data $sqlQuery | DataList
0 ignored issues
show
Documentation introduced by
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...
Bug introduced by
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...
174
     * @param string $method
175
     *
176
     * @return ArrayList
177
     */
178
    protected function turnPageRaterSQLIntoArrayList($data, $method = "unknown")
179
    {
180
        if ($data instanceof SQLQuery) {
181
            $data = $data->execute();
182
        }
183
        $al = new ArrayList();
184
        if ($data) {
185
            foreach ($data as $record) {
186
                if ($record instanceof PageRating) {
187
                    $record->Method = $method;
0 ignored issues
show
Bug introduced by
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...
188
                //do nothing
189
                } else {
190
                    $score = $record["RatingAverage"];
191
                    $parentID = $record["ParentID"];
192
                    $record = PageRating::get_star_details_as_array_data($score, $parentID, $method);
193
                }
194
                $al->push($record);
195
            }
196
        }
197
        return $al;
198
    }
199
200
    protected function onlyShowApprovedPageRatings()
201
    {
202
        return Config::inst()->get("PageRaterExtension_Controller", "only_show_approved");
203
    }
204
205
}
206