Completed
Push — feature/more-metadata-values ( 150bb6...480338 )
by Daan van
13:28 queued 10:55
created

Assertion   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 6
c 1
b 0
f 1
lcom 1
cbo 1
dl 0
loc 54
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A nonEmptyString() 0 13 3
A validRegularExpression() 0 22 3
1
<?php
2
3
namespace OpenConext\Value\Assert;
4
5
use Assert\Assertion as BaseAssertion;
6
7
/**
8
 * @method static void nullOrNonEmptyString($value, $message = null, $propertyPath = null)
9
 * @method static void allNonEmptyString($value, $message = null, $propertyPath = null)
10
 * @method static void allValidRegularExpression($value, $message = null, $propertyPath = null)
11
 */
12
class Assertion extends BaseAssertion
13
{
14
    const INVALID_NON_EMPTY_STRING   = 501;
15
    const INVALID_REGULAR_EXPRESSION = 502;
16
17
    protected static $exceptionClass = 'OpenConext\Value\Exception\InvalidArgumentException';
18
19
    /**
20
     * @param string $value
21
     * @param string $propertyPath
22
     * @return void
23
     */
24
    public static function nonEmptyString($value, $propertyPath)
25
    {
26
        if (!is_string($value) || trim($value) === '') {
27
            $message = 'Expected non-empty string for "%s", "%s" given';
28
29
            throw static::createException(
30
                $value,
31
                sprintf($message, $propertyPath, static::stringify($value)),
32
                static::INVALID_NON_EMPTY_STRING,
33
                $propertyPath
34
            );
35
        }
36
    }
37
38
    /**
39
     * @param $regularExpression
40
     * @param $propertyPath
41
     * @return void
42
     */
43
    public static function validRegularExpression($regularExpression, $propertyPath)
44
    {
45
        $pregMatchErrored = false;
46
        set_error_handler(
47
            function () use (&$pregMatchErrored) {
48
                $pregMatchErrored = true;
49
            }
50
        );
51
52
        preg_match($regularExpression, 'some test string');
53
54
        restore_error_handler();
55
56
        if ($pregMatchErrored || preg_last_error()) {
57
            throw static::createException(
58
                $regularExpression,
59
                sprintf('The pattern "%s" is not a valid regular expression', self::stringify($regularExpression)),
60
                static::INVALID_REGULAR_EXPRESSION,
61
                $propertyPath
62
            );
63
        }
64
    }
65
}
66