HierarchyContainer   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
dl 0
loc 67
ccs 25
cts 25
cp 1
rs 10
c 1
b 0
f 0
wmc 11

4 Methods

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