UniquePriorityQueue   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 57
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A count() 0 4 1
A getIterator() 0 7 1
A getUnique() 0 11 3
A getKey() 0 11 3
1
<?php
2
3
/**
4
 * Phoole (PHP7.2+)
5
 *
6
 * @category  Library
7
 * @package   Phoole\Base
8
 * @copyright Copyright (c) 2019 Hong Zhang
9
 */
10
declare(strict_types=1);
11
12
namespace Phoole\Base\Queue;
13
14
/**
15
 * UniquePriorityQueue
16
 *
17
 * Make sure items in the queue are unique
18
 *
19
 * @package Phoole\Base
20
 */
21
class UniquePriorityQueue extends PriorityQueue
22
{
23
    /**
24
     * {@inheritDoc}
25
     */
26
    public function count()
27
    {
28
        return count($this->getUnique(array_column($this->queue, 'data')));
29
    }
30
31
    /**
32
     * {@inheritDoc}
33
     */
34
    public function getIterator()
35
    {
36
        $this->sortQueue();
37
        return new \ArrayIterator(
38
            $this->getUnique(array_column($this->queue, 'data'))
39
        );
40
    }
41
42
    /**
43
     * Remove duplicated items
44
     *
45
     * @param  mixed[] $input
46
     * @return mixed[]
47
     */
48
    protected function getUnique(array $input): array
49
    {
50
        $result = [];
51
        foreach ($input as $val) {
52
            $key = $this->getKey($val);
53
            if (!isset($result[$key])) {
54
                $result[$key] = $val;
55
            }
56
        }
57
        return \array_values($result);
58
    }
59
60
    /**
61
     * Generate related key base on value
62
     *
63
     * @param  mixed $val
64
     * @return string
65
     */
66
    protected function getKey($val): string
67
    {
68
        if (is_object($val)) {
69
            $key = \spl_object_hash($val);
70
        } elseif (is_scalar($val)) {
71
            $key = (string) $val;
72
        } else {
73
            $key = md5(\serialize($val));
74
        }
75
        return $key;
76
    }
77
}