Data::sort()   B
last analyzed

Complexity

Conditions 5
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 12
rs 8.8571
cc 5
eloc 7
nc 1
nop 2
1
<?php
2
3
namespace stojg\recommend;
4
5
/**
6
 * This class contains behaviour for finding recommendations.
7
 */
8
class Data
9
{
10
    /**
11
     * This the.
12
     *
13
     * @var array
14
     */
15
    protected $item = '';
16
17
    /**
18
     * This is the full dataset.
19
     *
20
     * @var array
21
     */
22
    protected $set = [];
23
24
    /**
25
     * @param array $set - The full dataset
26
     */
27
    public function __construct($set)
28
    {
29
        $this->set = $set;
30
    }
31
32
    /**
33
     * Return a list of recommendations.
34
     *
35
     * @param string $for      - the item we want recommendations for
36
     * @param object $strategy
37
     *
38
     * @return array
39
     */
40
    public function recommend($for, $strategy)
41
    {
42
        $nearest = $this->findNearest($for, $strategy);
43
        if ($nearest === false) {
44
            return [];
45
        }
46
        $recommendations = [];
47
        foreach ($this->set[$nearest] as $item => $rating) {
48
            // The item has been already been rated
49
            if (isset($this->set[$for][$item])) {
50
                continue;
51
            }
52
            $recommendations[] = ['key' => $item, 'value' => $rating];
53
        }
54
        $this->sort($recommendations, false);
55
56
        return $recommendations;
57
    }
58
59
    /**
60
     * Find the nearest key that matching is closest to the item in the set.
61
     *
62
     * @return string
63
     */
64
    public function findNearest($for, $strategy)
65
    {
66
        $distances = [];
67
        foreach ($this->set as $key => $itemData) {
68
            if ($key == $for) {
69
                continue;
70
            }
71
            $distance = $strategy->run($itemData, $this->set[$for]);
72
            if ($distance === false) {
73
                continue;
74
            }
75
            $distances[] = ['key' => $key, 'value' => $distance];
76
        }
77
        if (!count($distances)) {
78
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by stojg\recommend\Data::findNearest of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
79
        }
80
        $this->sort($distances, true);
81
82
        return $distances[0]['key'];
83
    }
84
85
    /**
86
     * sort an nested array that have a value attribute.
87
     *
88
     * i.e [ 0 => [ 'value' => 5 ], 1 => [ 'value' => 2 ] ]
89
     *
90
     * @param array $distances
91
     * @param bool  $ascending
92
     */
93
    protected function sort(&$distances, $ascending = true)
94
    {
95
        usort($distances, function ($first, $second) use ($ascending) {
96
            if ($first['value'] > $second['value']) {
97
                return ($ascending) ? 1 : -1;
98
            } elseif ($first['value'] < $second['value']) {
99
                return ($ascending) ? -1 : 1;
100
            }
101
102
            return 0;
103
        });
104
    }
105
}
106