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

JsonRequestFormatter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 48%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 24
c 1
b 0
f 0
dl 0
loc 35
ccs 12
cts 25
cp 0.48
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getDatas() 0 7 2
A updateDatasForRelationships() 0 24 6
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
}