Passed
Branch master (84f592)
by Jean-Christophe
11:35
created

JsonRequestFormatter::getDatas()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 7
ccs 5
cts 6
cp 0.8333
rs 10
cc 2
nc 2
nop 1
crap 2.0185
1
<?php
2
3
namespace Ubiquity\controllers\rest\formatters;
4
5
use Ubiquity\orm\OrmUtils;
6
use Ubiquity\utils\http\URequest;
7
8
/**
9
 * Ubiquity\controllers\rest\formatters$JsonRequestFormatter
10
 * This class is part of Ubiquity
11
 *
12
 * @author jc
13
 * @version 1.0.0
14
 *
15
 */
16
class JsonRequestFormatter extends RequestFormatter {
17
18 1
	public function getDatas(?string $model = null): array {
19 1
		$datas = URequest::getRealInput ();
20 1
		if (\count ( $datas ) > 0) {
21 1
			$datas = \current ( \array_keys ( $datas ) );
22 1
			return $this->updateDatasForRelationships ( \json_decode ( $datas, true ), $model );
23
		}
24
		return [ ];
25
	}
26
27 1
	protected function updateDatasForRelationships($datas, $model) {
28 1
		$metas = OrmUtils::getModelMetadata ( $model );
29 1
		$joinColumns = $metas ['#joinColumn'] ?? [ ];
30 1
		$manyToManys = $metas ['#manyToMany'] ?? [ ];
31 1
		foreach ( $joinColumns as $column => $infos ) {
32
			if(isset($datas [$column])) {
33
				$datas [$infos ['name']] = $datas [$column];
34
				unset ($datas [$column]);
35
			}
36
		}
37 1
		foreach ( $manyToManys as $manyColumn => $manyColumnInfos ) {
38
			$targetEntity = $manyColumnInfos ['targetEntity'];
39
			$idField = OrmUtils::getFirstKey ( $targetEntity );
40
			$v = $datas [$manyColumn] ?? [];
41
			$ids = [ ];
42
			foreach ( $v as $values ) {
43
				if (isset ( $values [$idField] )) {
44
					$ids [] = $values [$idField];
45
				}
46
			}
47
			$datas [$manyColumn . 'Ids'] = \implode ( ',', $ids );
48
			unset ( $datas [$manyColumn] );
49
		}
50 1
		return $datas;
51
	}
52
}