EmailsToArrayTransformer::reverseTransform()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 10
rs 9.6111
c 0
b 0
f 0
cc 5
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Setono\SyliusStockMovementPlugin\Form\DataTransformer;
6
7
use const PREG_SPLIT_NO_EMPTY;
8
use Safe\Exceptions\PcreException;
9
use Safe\Exceptions\StringsException;
10
use function Safe\preg_split;
11
use function Safe\sprintf;
12
use Symfony\Component\Form\DataTransformerInterface;
13
use Symfony\Component\Form\Exception\TransformationFailedException;
14
15
final class EmailsToArrayTransformer implements DataTransformerInterface
16
{
17
    /**
18
     * Transforms an array of emails into a string like '[email protected],[email protected]'
19
     */
20
    public function transform($arr): string
21
    {
22
        if (!is_array($arr)) {
23
            return '';
24
        }
25
26
        return implode(',', $arr);
27
    }
28
29
    /**
30
     * Transforms a string of emails into an array of emails
31
     *
32
     * @throws StringsException
33
     * @throws TransformationFailedException
34
     */
35
    public function reverseTransform($str): array
36
    {
37
        if (null === $str || '' === $str || !is_string($str)) {
38
            return [];
39
        }
40
41
        try {
42
            return preg_split('/[ ,]+/', $str, -1, PREG_SPLIT_NO_EMPTY);
43
        } catch (PcreException $e) {
44
            throw new TransformationFailedException(sprintf('It was not possible to convert the string "%s" to an array of emails', $str), 0, $e);
45
        }
46
    }
47
}
48