Step::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license.
17
 */
18
19
namespace KawaiiGherkin\Formatter;
20
21
use Behat\Gherkin\Node\ArgumentInterface;
22
use Behat\Gherkin\Node\StepNode;
23
24
/**
25
 * @author  Jefersson Nathan  <[email protected]>
26
 * @license MIT
27
 */
28
final class Step extends AbstractFormatter
29
{
30
    const ALIGN_TO_LEFT  = 'left';
31
    const ALIGN_TO_RIGHT = 'right';
32
33
    /**
34
     * @var string
35
     */
36
    private $align;
37
38
    /**
39
     * @param string $align
40
     */
41 3
    public function __construct($align = self::ALIGN_TO_RIGHT)
42
    {
43 3
        $this->align = $align;
44 3
    }
45
46
    /**
47
     * @param \Behat\Gherkin\Node\StepNode[] $steps
48
     *
49
     * @return string
50
     */
51 3
    public function format(array $steps)
52
    {
53 3
        return implode(
54 3
            array_map(
55
                function (StepNode $step) {
56 3
                    return $this->getStepText($step) . $this->getArguments($step);
57 3
                },
58 3
                $steps
59
            )
60
        );
61
    }
62
63
    /**
64
     * @param string $keyword
65
     *
66
     * @return int
67
     */
68 3
    private function computeIndentationSpaces($keyword)
69
    {
70 3
        if ($this->align === self::ALIGN_TO_RIGHT) {
71 1
            return (self::INDENTATION * 2) - strlen(trim($keyword)) + 1;
72
        }
73
74 2
        return self::INDENTATION;
75
    }
76
77
    /**
78
     * @param StepNode $step
79
     *
80
     * @return string
81
     */
82 3
    private function getStepText(StepNode $step)
83
    {
84 3
        $spacesQuantity = $this->computeIndentationSpaces($step->getKeyword());
85
86 3
        return rtrim(sprintf(
87 3
            '%s%s %s',
88 3
            $this->indent($spacesQuantity + self::INDENTATION),
89 3
            trim($step->getKeyword()),
90 3
            trim($step->getText())
91 3
        )) . "\n";
92
93
    }
94
95
    /**
96
     * @param StepNode $step
97
     *
98
     * @return string
99
     */
100 3
    private function getArguments(StepNode $step)
101
    {
102 3
        if (! $step->hasArguments()) {
103 3
            return;
104
        }
105
106 3
        return implode(
107 3
            array_map(
108
                function (ArgumentInterface $argument) {
109 3
                    if (in_array($argument->getNodeType(), ['Table', 'ExampleTable'])) {
110 2
                        return implode(
111 2
                            array_map(
112
                                function ($arguments) {
113 2
                                    return $this->indent(self::INDENTATION * 2 + 4) . trim($arguments) . "\n";
114 2
                                },
115 2
                                explode("\n", $argument->getTableAsString())
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Gherkin\Node\ArgumentInterface as the method getTableAsString() does only exist in the following implementations of said interface: Behat\Gherkin\Node\ExampleTableNode, Behat\Gherkin\Node\TableNode.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
116
                            )
117
                        );
118
                    }
119
120 1
                    if ('PyString' === $argument->getNodeType()) {
121 1
                        return $this->encapsulateAsPyString(
122 1
                            implode(
123 1
                                array_map(
124 1
                                    function ($arguments) {
125 1
                                        return rtrim($this->indent(self::INDENTATION * 2 + 2) . trim($arguments)) . "\n";
126 1
                                    },
127 1
                                    $argument->getStrings()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Behat\Gherkin\Node\ArgumentInterface as the method getStrings() does only exist in the following implementations of said interface: Behat\Gherkin\Node\PyStringNode.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
128
                                )
129
                            )
130
                        );
131
                    }
132 3
                },
133 3
                $step->getArguments()
134
            )
135
        );
136
    }
137
138
    /**
139
     * @param string $string
140
     *
141
     * @return string
142
     */
143 1
    private function encapsulateAsPyString($string)
144
    {
145 1
        return sprintf('%s%s%1$s', $this->indent(8) . '"""' . "\n", $string);
146
    }
147
}
148