File tree 3 files changed +91
-0
lines changed
3 files changed +91
-0
lines changed Original file line number Diff line number Diff line change @@ -70,6 +70,7 @@ Currently the following types are supported:
70
70
* Object
71
71
* List
72
72
* Datetime
73
+ * Regex
73
74
74
75
There are some open issues with ideas for more types. Feel free to send pull requests.
75
76
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace spec \StructureCheck \Type ;
4
+
5
+ use PhpSpec \ObjectBehavior ;
6
+ use StructureCheck \Type \RegexType ;
7
+
8
+ class RegexTypeSpec extends ObjectBehavior
9
+ {
10
+
11
+ function it_is_initializable ()
12
+ {
13
+ $ this ->beConstructedWith ('/^def/ ' );
14
+
15
+ $ this ->shouldHaveType (RegexType::class);
16
+ }
17
+
18
+ function it_should_return_valid_for_matching_strings ()
19
+ {
20
+ $ this ->beConstructedWith ('/^def/ ' );
21
+
22
+ $ this ->check ('definitive ' )->isValid ()->shouldBe (true );
23
+ }
24
+
25
+ function it_should_return_invalid_for_not_matching_strings ()
26
+ {
27
+ $ this ->beConstructedWith ('/^def/ ' );
28
+
29
+ $ this ->check ('developers ' )->isValid ()->shouldBe (false );
30
+ }
31
+
32
+ function it_should_return_invalid_for_others ()
33
+ {
34
+ $ this ->beConstructedWith ('/^def/ ' );
35
+
36
+ $ this ->check (null )->isValid ()->shouldBe (false );
37
+ $ this ->check (12.3 )->isValid ()->shouldBe (false );
38
+ $ this ->check ([])->isValid ()->shouldBe (false );
39
+ $ this ->check (-1 )->isValid ()->shouldBe (false );
40
+ $ this ->check (true )->isValid ()->shouldBe (false );
41
+ }
42
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace StructureCheck \Type ;
4
+
5
+ use StructureCheck \Result ;
6
+ use StructureCheck \ResultInterface ;
7
+
8
+ /**
9
+ * Class RegexType
10
+ * @package StructureCheck\Type
11
+ */
12
+ class RegexType
13
+ {
14
+ /**
15
+ * @var string
16
+ */
17
+ private static $ errorMessage = 'The value %s does not match the regex %s ' ;
18
+
19
+ /**
20
+ * @var string
21
+ */
22
+ private $ regex ;
23
+
24
+ /**
25
+ * RegexType constructor.
26
+ *
27
+ * @param string $regex
28
+ */
29
+ public function __construct ($ regex )
30
+ {
31
+ $ this ->regex = $ regex ;
32
+ }
33
+
34
+ /**
35
+ * @param mixed $value
36
+ *
37
+ * @return ResultInterface
38
+ */
39
+ public function check ($ value )
40
+ {
41
+ $ checkResult = is_string ($ value ) && preg_match ($ this ->regex , $ value ) === 1 ;
42
+
43
+ return new Result (
44
+ $ checkResult ,
45
+ !$ checkResult ? [sprintf (self ::$ errorMessage , json_encode ($ value ), $ this ->regex )] : []
46
+ );
47
+ }
48
+ }
You can’t perform that action at this time.
0 commit comments