UrlToHostTransformer::reverseTransform()   A
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 9
c 1
b 0
f 1
dl 0
loc 15
rs 9.2222
cc 6
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Setono\SyliusStockMovementPlugin\Form\DataTransformer;
6
7
use const PHP_URL_HOST;
8
use Safe\Exceptions\StringsException;
9
use Safe\Exceptions\UrlException;
10
use function Safe\parse_url;
11
use Symfony\Component\Form\DataTransformerInterface;
12
use Symfony\Component\Form\Exception\TransformationFailedException;
13
14
final class UrlToHostTransformer implements DataTransformerInterface
15
{
16
    public function transform($host): ?string
17
    {
18
        return $host;
19
    }
20
21
    /**
22
     * Transforms an url to it's host
23
     *
24
     * @throws StringsException
25
     */
26
    public function reverseTransform($url): ?string
27
    {
28
        if (null === $url || '' === $url || !is_string($url)) {
29
            return null;
30
        }
31
32
        try {
33
            $res = parse_url($url, PHP_URL_HOST);
34
            if (null === $res) {
35
                return $url;
36
            }
37
38
            return $res;
39
        } catch (UrlException $e) {
40
            throw new TransformationFailedException(\Safe\sprintf('It was not possible to extract the host from the url: "%s"', $url), 0, $e);
41
        }
42
    }
43
}
44