I need to validate the fields of user sent by an API. All works fine but the only one problem is that I don't like the solution is not an OOP solution. In the controller I call the service created by me:
$userValidatorService = $this->get(UserValidatorService::class);
And the service:
class UserValidatorService
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var LoggerInterface;
*/
private $logger;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var UserManagerInterface
*/
private $userManager;
/**
* @var array
*/
private $locales;
/**
* @var User
*/
private $user;
/**
* @var array
*/
private $userFormData;
/**
* UserValidatorService constructor.
* @param EntityManagerInterface $entityManager
* @param LoggerInterface $logger
* @param TranslatorInterface $translator
* @param UserManagerInterface $userManager
*/
public function __construct(
EntityManagerInterface $entityManager,
LoggerInterface $logger,
TranslatorInterface $translator,
UserManagerInterface $userManager
)
{
$this->entityManager = $entityManager;
$this->logger = $logger;
$this->translator = $translator;
$this->userManager = $userManager;
}
/**
* @return array
*/
public function updateUser()
{
$messages = [];
if( '' !== $errorMessage = $this->validateEmail()){
$messages['email'] = $errorMessage;
}
if( '' !== $errorMessage = $this->validateLocale()){
$messages['locale'] = $errorMessage;
// and all fields are validated like that
}
/**
* @return string
*/
private function validateEmail()
{
if(isset($this->userFormData['email'])){
if(!filter_var($this->userFormData['email'], FILTER_VALIDATE_EMAIL)){
return $this->translator->trans('error.message');
}
return '';
}
return $this->translator->trans('error.message');
}
/**
* @return string
*/
private function validateLocale()
{
if(isset($this->userFormData['locale'])){
if(!in_array($this->userFormData['locale'], $this->locales)){
return $this->translator->trans('error.message');
}
return '';
}
return $this->translator->trans('error.message');
}
The question exists as a pattern to use to avoid this duplication and to do more OOP (I repeat that this code works just fine). I want to do that by myself without using Symfony validators.
$this->logger
get used? And when does$this->locales
have values pushed into or assigned to it? \$\endgroup\$