Completed
Push — master ( cc976a...4af9f1 )
by zacksleo
01:35
created

RecentlyViewedBehavior::clearRecentlyViewed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 6
1
<?php
2
3
namespace zacksleo\yii2\behaviors;
4
5
use yii;
6
use yii\base\Behavior;
7
8
/**
9
 * ERecentlyViewedBehavior is a behavior for managing recently viewed model items.
10
 */
11
class RecentlyViewedBehavior extends Behavior
12
{
13
    /**
14
     * @param integer the limit to the number of items in the recently viewed list.
15
     */
16
    public $limit = 8; // 0 = no limit.
17
18
    /**
19
     * Adds an item id to a 'recently viewed items' session object.
20
     * @var string the modelClass of the item to store
21
     * @param integer the id of the item to store
22
     */
23
24
    public function setRecentlyViewed($modelClass, $id)
25
    {
26
        // Create the session index
27
        $index = $modelClass . '_recently_viewed';
28
        // Check if the session index exists
29
        if (!isset(Yii::$app->session[$index])) {
30
            $recentlyViewed = [];
31
        } else {
32
            $recentlyViewed = Yii::$app->session[$index];
33
            // Remove the id if it is already in the list
34
            if (($key = array_search($id, $recentlyViewed)) !== false) {
35
                unset($recentlyViewed[$key]);
36
            }
37
            // If a limit is set, and the list is at (or over) the limit, remove oldest item(s)
38
            if ($this->limit > 0 && count($recentlyViewed) >= $this->limit) {
39
                $count = count($recentlyViewed) - $this->limit;
40
                $recentlyViewed = array_slice($recentlyViewed, $count);
41
            }
42
        }
43
        // Add the current item id to the end of the array
44
        array_push($recentlyViewed, $id);
45
        // Update the session
46
        if (Yii instanceof yii\web\Application) {
47
            Yii::$app->getSession()->set($index, $recentlyViewed);
0 ignored issues
show
Bug introduced by
The method getSession does only exist in yii\web\Application, but not in yii\console\Application.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
48
        }
49
    }
50
51
    /**
52
     * Retrieves model records from a 'recently viewed items' session object.
53
     * @param string $modelClass the modelClass of the items to retrieve
54
     * @return array|null|static[]
55
     */
56
    public function getRecentlyViewed($modelClass)
57
    {
58
        // Create the session index
59
        $index = $modelClass . '_recently_viewed';
60
        $models = array();
61
        // Check if the session index exists
62
        if (isset(Yii::$app->session[$index])) {
63
            /* @var $recentlyViewed \zacksleo\yii2\behaviors\Dictionary */
64
            $recentlyViewed = Yii::$app->session[$index];
65
            // Check if a limit is set, and if the list is at (or over) the limit
66
            if ($this->limit > 0 && count($recentlyViewed) >= $this->limit) {
67
                $count = count($recentlyViewed) - $this->limit;
68
                // Remove the oldest item(s) (always an index of 0 after each removal)
69
                $recentlyViewed = array_slice($recentlyViewed, $count);
70
            }
71
            // Reverse the array so the most recently added item is first
72
            $recentlyViewed = array_reverse($recentlyViewed);
73
            // Create a comma separated list for the db order property
74
            $commaSeparated = implode(',', $recentlyViewed);
75
            // Find all of the models with the array of ids recently viewed
76
            // and order the results in the same order as the array
77
            $models = $modelClass::find()->where(['id' => $recentlyViewed])->orderBy([new yii\db\Expression("FIELD (id, $commaSeparated)")])->all();
78
        }
79
        return $models;
80
    }
81
82
    public function clearRecentlyViewed($modelClass)
83
    {
84
        // Create the session index
85
        $index = $modelClass . '_recently_viewed';
86
        // Check if the session index exists
87
        if (isset(Yii::$app->session[$index])) {
88
            unset(Yii::$app->session[$index]);
89
        }
90
        echo json_encode([
91
            'success' => true
92
        ]);
93
    }
94
}
95