Completed
Push — develop ( dfe314...df0194 )
by
unknown
07:26
created

AbstractSortableStatus::getStates()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license MIT
7
 * @copyright  2013 - 2017 Cross Solution <http://cross-solution.de>
8
 */
9
  
10
/** */
11
namespace Core\Entity\Status;
12
13
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
14
15
/**
16
 * Abstract sortable status.
17
 *
18
 * Defined state are associated to an sortable integer value.
19
 *
20
 * To use this, it must be extended, the available states must be defined in a
21
 * static property called $sortMap. It is recommended to also define class constants
22
 * for ease of use.
23
 *
24
 * <pre>
25
 * // Do not forget the ODM annotations!
26
 *
27
 * class PrioStatus extends AbstractPrioritizedStatus
28
 * {
29
 *      const NEW = 'new';
30
 *      const MODIFIED = 'modified';
31
 *
32
 *      // This must at least be "protected" because this class needs to see it.
33
 *      // Format: string:stateName => int:order
34
 *      //
35
 *      protected static $sortMap = [
36
 *          'state'          => 3
37
 *          static::NEW      => 1,
38
 *          static::MODIFIED => 2,
39
 *
40
 *      ];
41
 * }
42
 * </pre>
43
 *
44
 * getStates() would return <pre>
45
 * [
46
 *      static::NEW,
47
 *      static::MODIFIED,
48
 *      'state'
49
 * ];</pre>
50
 * in above example.
51
 *
52
 * The sort value is only used to be used in database queries and such the usage of
53
 * this class is the same as {@link AbstractStatus}
54
 *
55
 * @ODM\MappedSuperClass
56
 * @author Mathias Gelhausen <[email protected]>
57
 * @since 0.29
58
 */
59
abstract class AbstractSortableStatus extends AbstractStatus
60
{
61
    /**
62
     * The sort value of this status.
63
     *
64
     * @ODM\Field(type="int")
65
     * @var int
66
     */
67
    protected $sort;
68
69
    public static function getStates()
70
    {
71
        $sort = self::getSortMap();
72
        asort($sort, SORT_NUMERIC);
73
74
        return array_keys($sort);
75
    }
76
77
    public function __construct($state)
78
    {
79
        parent::__construct($state);
80
81
        $map        = self::getSortMap();
82
        $this->sort = $map[$state];
83
    }
84
85
    protected static function getSortMap()
86
    {
87
88
        /** @noinspection PhpUndefinedFieldInspection */
89
        if (isset(static::$sortMap)) {
90
91
            /** @noinspection PhpUndefinedFieldInspection */
92
            return static::$sortMap;
93
        }
94
95
        throw new \RuntimeException(sprintf(
96
            'The class %s does not define the static property $sortMap, which is required when extending %s',
97
            static::class, self::class
98
        ));
99
    }
100
}