· 8 years ago · May 16, 2018, 11:32 AM
1<?php
2namespace AppModel;
3
4use DoctrineORMMapping as ORM;
5use SymfonyComponentValidatorConstraints as Assert;
6
7/**
8 * User
9 *
10 * @ORMHasLifecycleCallbacks
11 * @ORMTable(name="users", uniqueConstraints={@ORMUniqueConstraint(name="id_UNIQUE", columns={"id"}), @ORMUniqueConstraint(name="username_UNIQUE", columns={"username"})})
12 * @ORMEntity(repositoryClass="AppRepositoryUserRepository")
13 */
14class User extends AbstractEntity
15{
16 /**
17 * @ORMPreUpdate
18 * @ORMPrePersist
19 */
20 public function validate()
21 {
22 // how do I retrieve the validator?
23
24 // $validator->validate($this);
25 }
26
27 /**
28 * @var string
29 *
30 * @ORMColumn(name="username", type="string", length=45, nullable=false)
31 * @AssertLength(min=3, max=45)
32 */
33 protected $username;
34
35 /** ... */
36}
37
38use SymfonyComponentValidatorValidation;
39use SymfonyComponentValidatorConstraints as Assert;
40
41class User
42{
43 /**
44 * @AssertLength(min = 3)
45 * @AssertNotBlank
46 */
47 private $name;
48
49 /**
50 * @AssertEmail
51 * @AssertNotBlank
52 */
53 private $email;
54
55 public function __construct($name, $email)
56 {
57 $this->name = $name;
58 $this->email = $email;
59 }
60
61 /**
62 * @AssertTrue(message = "The user should have a Google Mail account")
63 */
64 public function isGmailUser()
65 {
66 return false !== strpos($this->email, '@gmail.com');
67 }
68}
69
70$validator = Validation::createValidatorBuilder()
71 ->enableAnnotationMapping()
72 ->getValidator();
73
74$user = new User('John Doe', 'john@example.com');
75
76$violations = $validator->validate($user);