File size: 1,993 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
56
57
58
59
60
61
62
63
64
65
<?php

declare(strict_types=1);

namespace Mautic\LeadBundle\Validator;

use Mautic\CoreBundle\Exception\InvalidValueException;
use Mautic\CoreBundle\Exception\RecordNotFoundException;
use Mautic\CoreBundle\Exception\RecordNotPublishedException;
use Mautic\LeadBundle\Entity\LeadField;
use Mautic\LeadBundle\Model\FieldModel;
use Symfony\Contracts\Translation\TranslatorInterface;

class CustomFieldValidator
{
    public function __construct(
        private FieldModel $fieldModel,
        private TranslatorInterface $translator
    ) {
    }

    /**
     * @throws RecordNotFoundException
     * @throws RecordNotPublishedException
     * @throws InvalidValueException
     */
    public function validateFieldType(string $alias, string $fieldType): void
    {
        $field = $this->getPublishedFieldByAlias($alias);

        if ($field->getType() !== $fieldType) {
            throw new InvalidValueException($this->translator->trans('mautic.lead.contact.wrong.field.type', ['%alias%' => $alias, '%fieldType%' => $field->getType(), '%expectedType%' => $fieldType], 'validators'));
        }
    }

    /**
     * @throws RecordNotFoundException
     * @throws RecordNotPublishedException
     */
    private function getPublishedFieldByAlias(string $alias): LeadField
    {
        $field = $this->getFieldByAlias($alias);

        if (!$field->getIsPublished()) {
            throw new RecordNotPublishedException($this->translator->trans('mautic.lead.contact.field.not.published', ['%alias%' => $alias], 'validators'));
        }

        return $field;
    }

    /**
     * @throws RecordNotFoundException
     */
    private function getFieldByAlias(string $alias): LeadField
    {
        $field = $this->fieldModel->getEntityByAlias($alias);

        if (!$field instanceof LeadField) {
            throw new RecordNotFoundException($this->translator->trans('mautic.lead.contact.field.not.found', ['%alias%' => $alias], 'validators'));
        }

        return $field;
    }
}