Skip to content

Validator service #567

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion app/config/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ services:
markdown:
class: AppBundle\Utils\Markdown

# These are the Twig extensions that create new filters and functions for
app.validator:
class: AppBundle\Utils\Validator

# These are the Twig extensions that create new filters and functions for
# using them in the templates
app.twig.app_extension:
public: false
Expand Down
68 changes: 11 additions & 57 deletions src/AppBundle/Command/AddUserCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ protected function interact(InputInterface $input, OutputInterface $output)
return;
}

$validator = $this->getContainer()->get('app.validator');

// multi-line messages can be displayed this way...
$output->writeln('');
$output->writeln('Add User Command Interactive Wizard');
Expand Down Expand Up @@ -125,13 +127,7 @@ protected function interact(InputInterface $input, OutputInterface $output)
$username = $input->getArgument('username');
if (null === $username) {
$question = new Question(' > <info>Username</info>: ');
$question->setValidator(function ($answer) {
if (empty($answer)) {
throw new \RuntimeException('The username cannot be empty');
}

return $answer;
});
$question->setValidator([$validator, 'username']);
$question->setMaxAttempts(self::MAX_ATTEMPTS);

$username = $console->ask($input, $output, $question);
Expand All @@ -144,7 +140,7 @@ protected function interact(InputInterface $input, OutputInterface $output)
$password = $input->getArgument('password');
if (null === $password) {
$question = new Question(' > <info>Password</info> (your type will be hidden): ');
$question->setValidator([$this, 'passwordValidator']);
$question->setValidator([$validator, 'password']);
$question->setHidden(true);
$question->setMaxAttempts(self::MAX_ATTEMPTS);

Expand All @@ -158,7 +154,7 @@ protected function interact(InputInterface $input, OutputInterface $output)
$email = $input->getArgument('email');
if (null === $email) {
$question = new Question(' > <info>Email</info>: ');
$question->setValidator([$this, 'emailValidator']);
$question->setValidator([$validator, 'email']);
$question->setMaxAttempts(self::MAX_ATTEMPTS);

$email = $console->ask($input, $output, $question);
Expand All @@ -171,7 +167,7 @@ protected function interact(InputInterface $input, OutputInterface $output)
$fullName = $input->getArgument('full-name');
if (null === $fullName) {
$question = new Question(' > <info>Full Name</info>: ');
$question->setValidator([$this, 'fullNameValidator']);
$question->setValidator([$validator, 'fullName']);
$question->setMaxAttempts(self::MAX_ATTEMPTS);

$fullName = $console->ask($input, $output, $question);
Expand Down Expand Up @@ -224,50 +220,6 @@ protected function execute(InputInterface $input, OutputInterface $output)
}
}

/**
* @internal
*/
public function passwordValidator($plainPassword)
{
if (empty($plainPassword)) {
throw new \Exception('The password can not be empty.');
}

if (mb_strlen(trim($plainPassword)) < 6) {
throw new \Exception('The password must be at least 6 characters long.');
}

return $plainPassword;
}

/**
* @internal
*/
public function emailValidator($email)
{
if (empty($email)) {
throw new \Exception('The email can not be empty.');
}

if (false === mb_strpos($email, '@')) {
throw new \Exception('The email should look like a real email.');
}

return $email;
}

/**
* @internal
*/
public function fullNameValidator($fullName)
{
if (empty($fullName)) {
throw new \Exception('The full name can not be empty.');
}

return $fullName;
}

private function validateUserData($username, $plainPassword, $email, $fullName)
{
$userRepository = $this->entityManager->getRepository(User::class);
Expand All @@ -280,9 +232,11 @@ private function validateUserData($username, $plainPassword, $email, $fullName)
}

// validate password and email if is not this input means interactive.
$this->passwordValidator($plainPassword);
$this->emailValidator($email);
$this->fullNameValidator($fullName);
$validator = $this->getContainer()->get('app.validator');

$validator->password($plainPassword);
$validator->email($email);
$validator->fullName($fullName);

// check if a user with the same email already exists.
$existingEmail = $userRepository->findOneBy(['email' => $email]);
Expand Down
25 changes: 3 additions & 22 deletions src/AppBundle/Command/DeleteUserCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ protected function interact(InputInterface $input, OutputInterface $output)
$helper = $this->getHelper('question');

$question = new Question(' > <info>Username</info>: ');
$question->setValidator([$this, 'usernameValidator']);
$question->setValidator([$this->getContainer()->get('app.validator'), 'username']);
$question->setMaxAttempts(self::MAX_ATTEMPTS);

$username = $helper->ask($input, $output, $question);
Expand All @@ -109,8 +109,8 @@ protected function interact(InputInterface $input, OutputInterface $output)

protected function execute(InputInterface $input, OutputInterface $output)
{
$username = $input->getArgument('username');
$this->usernameValidator($username);
$validator = $this->getContainer()->get('app.validator');
$username = $validator->username($input->getArgument('username'));

$repository = $this->entityManager->getRepository(User::class);
/** @var User $user */
Expand All @@ -131,23 +131,4 @@ protected function execute(InputInterface $input, OutputInterface $output)
$output->writeln('');
$output->writeln(sprintf('[OK] User "%s" (ID: %d, email: %s) was successfully deleted.', $user->getUsername(), $userId, $user->getEmail()));
}

/**
* This internal method should be private, but it's declared public to
* maintain PHP 5.3 compatibility when using it in a callback.
*
* @internal
*/
public function usernameValidator($username)
{
if (empty($username)) {
throw new \Exception('The username can not be empty.');
}

if (1 !== preg_match('/^[a-z_]+$/', $username)) {
throw new \Exception('The username must contain only lowercase latin characters and underscores.');
}

return $username;
}
}
63 changes: 63 additions & 0 deletions src/AppBundle/Utils/Validator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace AppBundle\Utils;

class Validator
{
public function username($username)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe the name could be: usernameValidation?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validateUsername

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding the "right" name has always been the hardest part in software design 😉

Copy link
Contributor

@voronkovich voronkovich May 28, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@elkuku, You're right, but a method name in most cases should be beginning with a verb. :)

{
if (empty($username)) {
throw new \Exception('The username can not be empty.');
}

if (1 !== preg_match('/^[a-z_]+$/', $username)) {
throw new \Exception('The username must contain only lowercase latin characters and underscores.');
}

return $username;
}

public function password($plainPassword)
{
if (empty($plainPassword)) {
throw new \Exception('The password can not be empty.');
}

if (mb_strlen(trim($plainPassword)) < 6) {
throw new \Exception('The password must be at least 6 characters long.');
}

return $plainPassword;
}

public function email($email)
{
if (empty($email)) {
throw new \Exception('The email can not be empty.');
}

if (false === mb_strpos($email, '@')) {
throw new \Exception('The email should look like a real email.');
}

return $email;
}

public function fullName($fullName)
{
if (empty($fullName)) {
throw new \Exception('The full name can not be empty.');
}

return $fullName;
}
}