Completed
Pull Request — master (#23)
by
unknown
03:09
created

AllOfType::getItem()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 5
nop 1
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
1
<?php
2
3
namespace SwaggerGen\Swagger\Type;
4
5
/**
6
 * allOf compound type
7
 *
8
 * @package    SwaggerGen
9
 * @author     Bruce Weirdan <[email protected]>
10
 * @copyright  2014-2015 Martijn van der Lee
11
 * @license    https://opensource.org/licenses/MIT MIT
12
 */
13
class AllOfType extends AbstractType
14
{
15
	private $allOfItems = array();
16
	private $mostRecentItem;
17
	protected function parseDefinition($definition)
18
	{
19
		$pattern = self::REGEX_START . 'allOf' . self::REGEX_CONTENT . self::REGEX_END;
20
		$inlineDef = '';
21
		if (preg_match($pattern, $definition, $matches)) {
22
			if (isset($matches[1])) {
23
				$inlineDef = $matches[1];
24
			}
25
		}
26
		if ($inlineDef) {
27
			foreach ($this->parseList($inlineDef) as $item) {
28
				$this->handleCommand('item', $item);
29
			}
30
		}
31
	}
32
33
	/**
34
	 * @param string $list
35
	 * @return string
36
	 * @todo remove duplication between this method and ObjectType::extract_property()
37
	 */
38
	private function getItem(&$list)
39
	{
40
		static $openingBraces = array('(', '[', '{', '<',);
41
		static $closingBraces = array(')', ']', '}', '>');
42
43
		$depth = 0;
44
		$index = 0;
45
		$item = '';
46
47
		while ($index < strlen($list)) {
48
			$c = $list{$index};
49
			$index++;
50
			if (in_array($c, $openingBraces)) {
51
				$depth++;
52
			} elseif (in_array($c, $closingBraces)) {
53
				$depth--;
54
			} elseif ($c === ',' && !$depth) {
55
				break;
56
			}
57
			$item .= $c;
58
		}
59
		$list = substr($list, $index);
60
		return $item;
61
	}
62
63
	/**
64
	 * @param string $list
65
	 * @return array
66
	 */
67
	private function parseList($list)
68
	{
69
		$ret = array();
70
		while ($item = $this->getItem($list)) {
71
			$ret[] = $item;
72
		}
73
		return $ret;
74
	}
75
76
	public function handleCommand($command, $data = null)
77
	{
78
		switch ($command) {
79
			case 'ref':
80
			case 'inline':
81
			case 'item':
82
				$this->mostRecentItem = self::typeFactory($this, $data);
83
				$this->allOfItems[] = $this->mostRecentItem;
84
				return $this;
85
		}
86
		if (isset($this->mostRecentItem)) {
87
			if ($this->mostRecentItem->handleCommand($command, $data)) {
88
				return $this;
89
			}
90
		}
91
		return parent::handleCommand($command, $data);
92
	}
93
94
	public function toArray()
95
	{
96
		$allOf = array();
97
		foreach ($this->allOfItems as $item) {
98
			$allOf[] = $item->toArray();
99
		}
100
		return self::arrayFilterNull(array_merge(array(
101
			'allOf' => $allOf,
102
		), parent::toArray()));
103
	}
104
}
105