Completed
Push — master ( c3f0f6...0c6e4d )
by Tomáš
02:30
created

HierarchyContainer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 85.71%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 22
c 1
b 0
f 0
dl 0
loc 53
ccs 18
cts 21
cp 0.8571
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getLevelType() 0 2 1
A insert() 0 11 4
A getHierarchyLevel() 0 15 5
1
<?php
2
3
4
namespace TournamentGenerator\Containers;
5
6
use InvalidArgumentException;
7
use TournamentGenerator\Base;
8
9
/**
10
 * Class HierarchyContainer
11
 *
12
 * HierarchyContainer is a special type of container specifically for creating hierarchies on Tournament->Category->Round->Group.
13
 *
14
 * @package TournamentGenerator\Containers
15
 * @author  Tomáš Vojík <[email protected]>
16
 */
17
class HierarchyContainer extends BaseContainer
18
{
19
20
	/** @var HierarchyContainer[] Direct child containers */
21
	protected array $children = [];
22
	/** @var Base[] Any value that the container holds */
23
	protected array   $values = [];
24
	protected ?string $type   = null;
25
26 64
	public function insert(...$values) : BaseContainer {
27 64
		if (is_null($this->type)) {
28 64
			$this->type = get_class($values[0]);
29
		}
30 64
		foreach ($values as $obj) {
31 64
			if (!$obj instanceof $this->type) {
32 1
				throw new InvalidArgumentException('HierarchyContainer allows only one class type per level.');
33
			}
34
		}
35 64
		parent::insert(...$values);
36 64
		return $this;
37
	}
38
39
	/**
40
	 * Returns a hierarchy level of objects that contains the given classes
41
	 *
42
	 * @param $class
43
	 *
44
	 * @return Base[]
45
	 */
46 47
	public function getHierarchyLevel($class) : array {
47 47
		if (!class_exists($class)) {
48
			throw new InvalidArgumentException(sprintf('Class %s does not exist.', $class));
49
		}
50 47
		if ($this->type === $class) {
51 45
			return $this->values;
52
		}
53 8
		if (count($this->children) > 0) {
54 6
			$values = [];
55 6
			foreach ($this->children as $child) {
56 6
				$values[] = $child->getHierarchyLevel($class);
57
			}
58 6
			return array_merge(...$values);
59
		}
60 2
		return [];
61
	}
62
63
	/**
64
	 * Get current level's type
65
	 *
66
	 * @return string|null
67
	 */
68
	public function getLevelType() : ?string {
69
		return $this->type;
70
	}
71
72
}