Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
8
declare(strict_types=1);
9
 
10
namespace Nette\Schema;
11
 
12
use Nette;
13
 
14
 
15
/**
16
 * Schema validator.
17
 */
18
final class Processor
19
{
20
	use Nette\SmartObject;
21
 
22
	/** @var array */
23
	public $onNewContext = [];
24
 
25
	/** @var Context|null */
26
	private $context;
27
 
28
	/** @var bool */
29
	private $skipDefaults;
30
 
31
 
32
	public function skipDefaults(bool $value = true)
33
	{
34
		$this->skipDefaults = $value;
35
	}
36
 
37
 
38
	/**
39
	 * Normalizes and validates data. Result is a clean completed data.
40
	 * @return mixed
41
	 * @throws ValidationException
42
	 */
43
	public function process(Schema $schema, $data)
44
	{
45
		$this->createContext();
46
		$data = $schema->normalize($data, $this->context);
47
		$this->throwsErrors();
48
		$data = $schema->complete($data, $this->context);
49
		$this->throwsErrors();
50
		return $data;
51
	}
52
 
53
 
54
	/**
55
	 * Normalizes and validates and merges multiple data. Result is a clean completed data.
56
	 * @return mixed
57
	 * @throws ValidationException
58
	 */
59
	public function processMultiple(Schema $schema, array $dataset)
60
	{
61
		$this->createContext();
62
		$flatten = null;
63
		$first = true;
64
		foreach ($dataset as $data) {
65
			$data = $schema->normalize($data, $this->context);
66
			$this->throwsErrors();
67
			$flatten = $first ? $data : $schema->merge($data, $flatten);
68
			$first = false;
69
		}
70
 
71
		$data = $schema->complete($flatten, $this->context);
72
		$this->throwsErrors();
73
		return $data;
74
	}
75
 
76
 
77
	/**
78
	 * @return string[]
79
	 */
80
	public function getWarnings(): array
81
	{
82
		$res = [];
83
		foreach ($this->context->warnings as $message) {
84
			$res[] = $message->toString();
85
		}
86
 
87
		return $res;
88
	}
89
 
90
 
91
	private function throwsErrors(): void
92
	{
93
		if ($this->context->errors) {
94
			throw new ValidationException(null, $this->context->errors);
95
		}
96
	}
97
 
98
 
99
	private function createContext()
100
	{
101
		$this->context = new Context;
102
		$this->context->skipDefaults = $this->skipDefaults;
103
		$this->onNewContext($this->context);
104
	}
105
}