Completed
Push — master ( 23968f...d87b7b )
by zacksleo
02:12
created

RecentlyViewedBehavior::clearRecentlyViewed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2
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 1
    public function setRecentlyViewed($modelClass, $id)
25
    {
26
        // Create the session index
27 1
        $index = $modelClass . '_recently_viewed';
28
        // Check if the session index exists
29 1
        if (!(Yii::$app->session->has($index))) {
30 1
            $recentlyViewed = [];
0 ignored issues
show
Unused Code introduced by
$recentlyViewed 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...
31
        }
32 1
        $recentlyViewed = Yii::$app->session->get($index, []);
33
        // Remove the id if it is already in the list
34 1
        if (($key = array_search($id, $recentlyViewed)) !== false) {
35 1
            unset($recentlyViewed[$key]);
36
        }
37
        // If a limit is set, and the list is at (or over) the limit, remove oldest item(s)
38 1
        if ($this->limit > 0 && count($recentlyViewed) >= $this->limit) {
39
            $count = count($recentlyViewed) - $this->limit;
40
            $recentlyViewed = array_slice($recentlyViewed, $count);
41
        }
42
        // Add the current item id to the end of the array
43 1
        array_push($recentlyViewed, $id);
44
        // Update the session
45 1
        Yii::$app->session->set($index, $recentlyViewed);
46 1
    }
47
48
    /**
49
     * Retrieves model records from a 'recently viewed items' session object.
50
     * @param string $modelClass the modelClass of the items to retrieve
51
     * @return array|null|static[]
52
     */
53 1
    public function getRecentlyViewed($modelClass)
54
    {
55
        // Create the session index
56 1
        $index = $modelClass . '_recently_viewed';
57 1
        $models = array();
58
        // Check if the session index exists
59 1
        if (isset(Yii::$app->session[$index])) {
60
            /* @var $recentlyViewed \zacksleo\yii2\behaviors\Dictionary */
61 1
            $recentlyViewed = Yii::$app->session[$index];
62
            // Check if a limit is set, and if the list is at (or over) the limit
63 1
            if ($this->limit > 0 && count($recentlyViewed) >= $this->limit) {
64
                $count = count($recentlyViewed) - $this->limit;
65
                // Remove the oldest item(s) (always an index of 0 after each removal)
66
                $recentlyViewed = array_slice($recentlyViewed, $count);
67
            }
68
            // Reverse the array so the most recently added item is first
69 1
            $recentlyViewed = array_reverse($recentlyViewed);
70
            // Create a comma separated list for the db order property
71 1
            $commaSeparated = implode(',', $recentlyViewed);
72
            // Find all of the models with the array of ids recently viewed
73
            // and order the results in the same order as the array
74 1
            $models = $modelClass::find()->where(['id' => $recentlyViewed])->orderBy([new yii\db\Expression("FIELD (id, $commaSeparated)")])->all();
75
        }
76 1
        return $models;
77
    }
78
79 1
    public function clearRecentlyViewed($modelClass)
80
    {
81
        // Create the session index
82 1
        $index = $modelClass . '_recently_viewed';
83
        // Check if the session index exists
84 1
        if (isset(Yii::$app->session[$index])) {
85 1
            unset(Yii::$app->session[$index]);
86
        }
87 1
        echo json_encode([
88 1
            'success' => true
89
        ]);
90 1
    }
91
}
92