| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* This file is part of the Nette Framework (https://nette.org) |
| 5 |
* Copyright (c) 2004 David Grudl (https://davidgrudl.com) |
| 6 |
*/ |
| 7 |
declare (strict_types=1); |
| 8 |
namespace Packetery\Nette\Schema; |
| 9 |
|
| 10 |
use Packetery\Nette; |
| 11 |
/** |
| 12 |
* Schema validator. |
| 13 |
*/ |
| 14 |
final class Processor |
| 15 |
{ |
| 16 |
use \Packetery\Nette\SmartObject; |
| 17 |
/** @var array */ |
| 18 |
public $onNewContext = []; |
| 19 |
/** @var Context|null */ |
| 20 |
private $context; |
| 21 |
/** @var bool */ |
| 22 |
private $skipDefaults; |
| 23 |
public function skipDefaults(bool $value = \true) |
| 24 |
{ |
| 25 |
$this->skipDefaults = $value; |
| 26 |
} |
| 27 |
/** |
| 28 |
* Normalizes and validates data. Result is a clean completed data. |
| 29 |
* @return mixed |
| 30 |
* @throws ValidationException |
| 31 |
*/ |
| 32 |
public function process(Schema $schema, $data) |
| 33 |
{ |
| 34 |
$this->createContext(); |
| 35 |
$data = $schema->normalize($data, $this->context); |
| 36 |
$this->throwsErrors(); |
| 37 |
$data = $schema->complete($data, $this->context); |
| 38 |
$this->throwsErrors(); |
| 39 |
return $data; |
| 40 |
} |
| 41 |
/** |
| 42 |
* Normalizes and validates and merges multiple data. Result is a clean completed data. |
| 43 |
* @return mixed |
| 44 |
* @throws ValidationException |
| 45 |
*/ |
| 46 |
public function processMultiple(Schema $schema, array $dataset) |
| 47 |
{ |
| 48 |
$this->createContext(); |
| 49 |
$flatten = null; |
| 50 |
$first = \true; |
| 51 |
foreach ($dataset as $data) { |
| 52 |
$data = $schema->normalize($data, $this->context); |
| 53 |
$this->throwsErrors(); |
| 54 |
$flatten = $first ? $data : $schema->merge($data, $flatten); |
| 55 |
$first = \false; |
| 56 |
} |
| 57 |
$data = $schema->complete($flatten, $this->context); |
| 58 |
$this->throwsErrors(); |
| 59 |
return $data; |
| 60 |
} |
| 61 |
/** |
| 62 |
* @return string[] |
| 63 |
*/ |
| 64 |
public function getWarnings() : array |
| 65 |
{ |
| 66 |
$res = []; |
| 67 |
foreach ($this->context->warnings as $message) { |
| 68 |
$res[] = $message->toString(); |
| 69 |
} |
| 70 |
return $res; |
| 71 |
} |
| 72 |
private function throwsErrors() : void |
| 73 |
{ |
| 74 |
if ($this->context->errors) { |
| 75 |
throw new ValidationException(null, $this->context->errors); |
| 76 |
} |
| 77 |
} |
| 78 |
private function createContext() |
| 79 |
{ |
| 80 |
$this->context = new Context(); |
| 81 |
$this->context->skipDefaults = $this->skipDefaults; |
| 82 |
$this->onNewContext($this->context); |
| 83 |
} |
| 84 |
} |
| 85 |
|