StringElement::toHttp()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Bdf\Form\Leaf;
4
5
use TypeError;
6
use function Webmozart\Assert\Tests\StaticAnalysis\string;
0 ignored issues
show
introduced by
The function Webmozart\Assert\Tests\StaticAnalysis\string was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
7
8
/**
9
 * Element for a simple string field
10
 *
11
 * @see StringElementBuilder for build the element
12
 *
13
 * @extends LeafElement<string>
14
 */
15
class StringElement extends LeafElement
16
{
17
    /**
18
     * {@inheritdoc}
19
     *
20
     * @return string|null
21
     */
22 186
    protected function toPhp($httpValue): ?string
23
    {
24 186
        if (!is_scalar($httpValue)) {
25 28
            return null;
26
        }
27
28 162
        return (string) $httpValue;
0 ignored issues
show
Bug Best Practice introduced by
The expression return (string)$httpValue returns the type string which is incompatible with the return type mandated by Bdf\Form\Leaf\LeafElement::toPhp() of Bdf\Form\Leaf\T|null.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 38
    protected function toHttp($phpValue): ?string
35
    {
36 38
        return $phpValue;
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     *
42
     * @return string|null
43
     */
44 82
    protected function tryCast($value): ?string
45
    {
46 82
        if ($value === null) {
47 7
            return null;
48
        }
49
50 80
        if (!is_scalar($value) && (!is_object($value) || !method_exists($value, '__toString'))) {
51 3
            throw new TypeError('The import()\'ed value of a '.static::class.' must be stringable or null');
52
        }
53
54 77
        return (string) $value;
55
    }
56
}
57