UrlToHostTransformer   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 7
eloc 10
c 1
b 0
f 1
dl 0
loc 27
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A transform() 0 3 1
A reverseTransform() 0 15 6
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