I have a trait that checks if a user is logged in or not and number of attempts to a specific location.
This trait I am trying to use inside a FormType in order to display a captcha after a number of attempts.
Inside getIpOrUserId()
I am trying to check if user is logged in $this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')
but it returns an error
Attempted to call an undefined method named "get" of class
.
I don't think that it is possible to create a Trait as a Service so I can inject the security object.
Is there a way to achieve this?
Trait
<?php
Trait CheckAttempts {
public function getTryAttempts()
{
if ($this->getIpOrUserId() == null) {
return false;
} else {
$attempts = $this->getDoctrine()
->getRepository('SiteBundle:LoginAttempts')
->findOneByIpOrUserId($this->getIpOrUserId());
}
return $attempts->getAttempts();
}
protected function getIpOrUserId()
{
//get logged in user
//if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
$ipOrUserId = $this->get('security.token_storage')->getToken()->getUser()->getId();
} else {
$ipOrUserId = $this->container->get('request_stack')->getCurrentRequest()->getClientIp();
}
return $ipOrUserId;
}
FormType
class RegisterType extends AbstractType
{
use FormSendLimitTrait;
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
var_dump($this->getTryAttempts());
$form->add('captcha', 'captcha',
'label' => 'site.captcha'
]);
/*if ($attempts->getAttempts() > 6) {
$form->add('captcha', 'captcha', [
'label' => 'site.captcha'
]);
}*/
})
get
method works only if you extendSymfony\Bundle\FrameworkBundle\Controller\Controller
class, usually it is used inside your controller classes. And it returns only$this->container->get($id)
, nothing else, this means it returnsSymfony\Component\DependencyInjection\Container
class. You should injectsecurity.authorization_checker
service into your class (or other services which you want), or even wholeservice_container
service (but it's not recommended).Example:
services.yml
But in your case you should not use traits like you're doing.