Completed
Branch develop (2b04dd)
by Mariano
03:37
created

FirstErrorRequestParser::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 7
Bugs 3 Features 4
Metric Value
c 7
b 3
f 4
dl 0
loc 16
ccs 11
cts 11
cp 1
rs 9.4285
cc 3
eloc 11
nc 3
nop 1
crap 3
1
<?php
2
/**
3
 * This file is part of php-simple-request.
4
 *
5
 * php-simple-request is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * php-simple-request is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with php-simple-request.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
namespace Mcustiel\SimpleRequest;
19
20
use Mcustiel\SimpleRequest\Exception\InvalidValueException;
21
use Mcustiel\SimpleRequest\Exception\InvalidRequestException;
22
23
/**
24
 * Parser object that stops on first invalid property and returns only that error.
25
 *
26
 * @author mcustiel
27
 */
28
class FirstErrorRequestParser extends RequestParser
29
{
30
    /**
31
     * Parses a request and returns the object obtained.
32
     *
33
     * @param array|\stdClass $request
34
     *
35
     * @return object
36
     */
37 5
    public function parse($request)
38
    {
39 5
        $object = clone $this->requestObject;
40 5
        foreach ($this->propertyParsers as $propertyParser) {
41
            try {
42 5
                $this->setProperty($request, $object, $propertyParser);
43 5
            } catch (InvalidValueException $e) {
44 1
                $propertyName = $propertyParser->getName();
45 1
                $exception = new InvalidRequestException($propertyName . ': ' . $e->getMessage());
46 1
                $exception->setErrors([$propertyName => $e->getMessage()]);
47 1
                throw $exception;
48
            }
49 4
        }
50
51 4
        return clone $object;
52
    }
53
}
54