File size: 1,746 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php

declare(strict_types=1);

namespace Mautic\EmailBundle\Validator;

use Mautic\EmailBundle\Mailer\Transport\TransportFactory;
use Mautic\EmailBundle\Validator\Dsn as DsnConstraint;
use Symfony\Component\Mailer\Exception\ExceptionInterface;
use Symfony\Component\Mailer\Exception\InvalidArgumentException;
use Symfony\Component\Mailer\Exception\UnsupportedSchemeException;
use Symfony\Component\Mailer\Transport\Dsn as MailerDsn;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class DsnValidator extends ConstraintValidator
{
    public function __construct(
        private TransportFactory $transportFactory
    ) {
    }

    public function validate($value, Constraint $constraint): void
    {
        if (!is_string($value)) {
            throw new UnexpectedTypeException($value, 'string');
        }

        if (!$constraint instanceof DsnConstraint) {
            throw new UnexpectedTypeException($constraint, DsnConstraint::class);
        }

        if (!$value) {
            return;
        }

        try {
            $dsn = MailerDsn::fromString($value);
        } catch (InvalidArgumentException $e) {
            $this->context->addViolation($e->getMessage() ?: 'mautic.email.dsn.invalid_dsn');

            return;
        }

        try {
            $this->transportFactory->fromDsnObject($dsn);
        } catch (UnsupportedSchemeException $e) {
            $this->context->addViolation($e->getMessage() ?: 'mautic.email.dsn.unsupported_scheme');
        } catch (ExceptionInterface $e) {
            $this->context->addViolation($e->getMessage() ?: 'mautic.email.dsn.invalid_dsn');
        }
    }
}