2fb05358522ce563449eaa4a80bdd6475b4ee0e2
[yaffs-website] / vendor / behat / behat / src / Behat / Testwork / Argument / PregMatchArgumentOrganiser.php
1 <?php
2
3 /*
4  * This file is part of the Behat Testwork.
5  * (c) Konstantin Kudryashov <ever.zet@gmail.com>
6  *
7  * For the full copyright and license information, please view the LICENSE
8  * file that was distributed with this source code.
9  */
10
11 namespace Behat\Testwork\Argument;
12
13 use ReflectionFunctionAbstract;
14
15 /**
16  * Organises arguments coming from preg_match results.
17  *
18  * @author Konstantin Kudryashov <ever.zet@gmail.com>
19  */
20 final class PregMatchArgumentOrganiser implements ArgumentOrganiser
21 {
22     /**
23      * @var ArgumentOrganiser
24      */
25     private $baseOrganiser;
26
27     /**
28      * Initialises organiser.
29      *
30      * @param ArgumentOrganiser $organiser
31      */
32     public function __construct(ArgumentOrganiser $organiser)
33     {
34         $this->baseOrganiser = $organiser;
35     }
36
37     /**
38      * {@inheritdoc}
39      */
40     public function organiseArguments(ReflectionFunctionAbstract $function, array $match)
41     {
42         $arguments = $this->cleanupMatchDuplicates($match);
43
44         return $this->baseOrganiser->organiseArguments($function, $arguments);
45     }
46
47     /**
48      * Cleans up provided preg_match match into a list of arguments.
49      *
50      * `preg_match` matches named arguments with named indexes and also
51      * represents all arguments with numbered indexes. This method removes
52      * duplication and also drops the first full match element from the
53      * array.
54      *
55      * @param array $match
56      *
57      * @return mixed[]
58      */
59     private function cleanupMatchDuplicates(array $match)
60     {
61         $cleanMatch = array_slice($match, 1);
62         $arguments = array();
63
64         $keys = array_keys($cleanMatch);
65         for ($keyIndex = 0; $keyIndex < count($keys); $keyIndex++) {
66             $key = $keys[$keyIndex];
67
68             $arguments[$key] = $cleanMatch[$key];
69
70             if ($this->isKeyAStringAndNexOneIsAnInteger($keyIndex, $keys)) {
71                 $keyIndex += 1;
72             }
73         }
74
75         return $arguments;
76     }
77
78     /**
79      * Checks if key at provided index is a string and next key in the array is an integer.
80      *
81      * @param integer $keyIndex
82      * @param mixed[] $keys
83      *
84      * @return Boolean
85      */
86     private function isKeyAStringAndNexOneIsAnInteger($keyIndex, array $keys)
87     {
88         $keyIsAString = is_string($keys[$keyIndex]);
89         $nextKeyIsAnInteger = isset($keys[$keyIndex + 1]) && is_integer($keys[$keyIndex + 1]);
90
91         return $keyIsAString && $nextKeyIsAnInteger;
92     }
93 }