Enum::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Deltatag\Enum;
4
5
use Deltatag\Enum\Exceptions\EnumDefaultNotDefinedException;
6
use Deltatag\Enum\Exceptions\EnumValueNotAllowedException;
7
8
/**
9
 * Class EnumBaseClass
10
 *
11
 * @package Deltatag\Enum
12
 */
13
abstract class Enum implements IEnum
0 ignored issues
show
Coding Style introduced by
Enum does not seem to conform to the naming convention (^Abstract|Factory$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
14
{
15
	use ConstantsTrait;
16
17
	/**
18
	 * @var mixed
19
	 */
20
	private $value;
21
22
	/**
23
	 * EnumBaseClass constructor.
24
	 *
25
	 * @param mixed $value If no value is defined the default value (if defined) will be used.
26
	 * @throws EnumDefaultNotDefinedException
27
	 * @throws EnumValueNotAllowedException
28
	 */
29
	public function __construct($value = null)
30
	{
31
		if (is_null($value)) {
32
			if(!array_key_exists('__default', self::getConstants())) {
33
				throw new EnumDefaultNotDefinedException();
34
			} else {
35
				$value = self::getConstants()['__default'];
36
			}
37
		}
38
		if (!self::isValid($value)) {
39
			throw new EnumValueNotAllowedException();
40
		}
41
		$this->value = $value;
42
	}
43
44
	/**
45
	 * @return string
46
	 */
47
	public function __toString(): string
48
	{
49
		return strval($this->value);
50
	}
51
52
	/**
53
	 * Return current value
54
	 *
55
	 * @return mixed
56
	 */
57
	public function getValue()
58
	{
59
		return $this->value;
60
	}
61
62
	/**
63
	 * Fetch default value of enum
64
	 *
65
	 * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use integer|double|string|boolean.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
66
	 * @throws EnumDefaultNotDefinedException
67
	 */
68
	public static function getDefault()
69
	{
70
		if (array_key_exists('__default', self::getConstants())) {
71
			return self::getConstants()['__default'];
72
		}
73
		throw new EnumDefaultNotDefinedException();
74
	}
75
76
	/**
77
	 * Compare instance of enum to another enum instance and comparing values
78
	 *
79
	 * @param IEnum $enumCompare
80
	 * @return bool
81
	 */
82
	public function isEqual(IEnum $enumCompare): bool
83
	{
84
		/** @noinspection PhpNonStrictObjectEqualityInspection */
85
		return $this == $enumCompare;
86
	}
87
}