Skip to content

Commit 8f5bdd3

Browse files
committed
ISSUE-345: validate that template has placeholder
1 parent 4f67858 commit 8f5bdd3

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

config/services/validators.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,6 @@ services:
2626
PhpList\RestBundle\Validator\TemplateImageValidator:
2727
autowire: true
2828
autoconfigure: true
29+
30+
PhpList\RestBundle\Validator\ContainsPlaceholderValidator:
31+
tags: ['validator.constraint_validator']

src/Entity/Request/CreateTemplateRequest.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Symfony\Component\HttpFoundation\File\UploadedFile;
88
use Symfony\Component\Validator\Constraints as Assert;
9+
use PhpList\RestBundle\Validator as CustomAssert;
910

1011
class CreateTemplateRequest
1112
{
@@ -14,8 +15,10 @@ class CreateTemplateRequest
1415
public string $title;
1516

1617
#[Assert\NotBlank]
18+
#[CustomAssert\ContainsPlaceholder]
1719
public string $content;
1820

21+
#[CustomAssert\ContainsPlaceholder]
1922
public ?string $text = null;
2023

2124
public ?UploadedFile $file = null;
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace PhpList\RestBundle\Validator;
6+
7+
use Symfony\Component\Validator\Constraint;
8+
9+
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
10+
class ContainsPlaceholder extends Constraint
11+
{
12+
public string $placeholder = '[CONTENT]';
13+
public string $message = 'The content must include at least one "{{ placeholder }}" placeholder.';
14+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace PhpList\RestBundle\Validator;
6+
7+
use InvalidArgumentException;
8+
use Symfony\Component\Validator\Constraint;
9+
use Symfony\Component\Validator\ConstraintValidator;
10+
11+
class ContainsPlaceholderValidator extends ConstraintValidator
12+
{
13+
public function validate($value, Constraint $constraint): void
14+
{
15+
if (!$constraint instanceof ContainsPlaceholder) {
16+
throw new InvalidArgumentException(sprintf('%s expects %s.', __CLASS__, ContainsPlaceholder::class));
17+
}
18+
19+
if (null === $value || '' === $value) {
20+
return;
21+
}
22+
23+
if (!str_contains($value, $constraint->placeholder)) {
24+
$this->context->buildViolation($constraint->message)
25+
->setParameter('{{ placeholder }}', $constraint->placeholder)
26+
->addViolation();
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)