fix (ECS) apply coding standard

This commit is contained in:
Olaf 2020-01-03 00:12:44 +01:00
parent 2ed4f74954
commit 478c64633e
6 changed files with 80 additions and 67 deletions

View File

@ -10,7 +10,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
/** /**
* Generates a captcha via a URL * Generates a captcha via a URL.
* *
* @author Jeremy Livingston <jeremy.j.livingston@gmail.com> * @author Jeremy Livingston <jeremy.j.livingston@gmail.com>
*/ */

View File

@ -11,15 +11,16 @@ use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\FileLocator;
/** /**
* Extension used to load the configuration, set parameters, and initialize the captcha view * Extension used to load the configuration, set parameters, and initialize the captcha view.
* *
* @author Gregwar <g.passault@gmail.com> * @author Gregwar <g.passault@gmail.com>
*/ */
class GregwarCaptchaExtension extends Extension class GregwarCaptchaExtension extends Extension
{ {
/** /**
* @param array $configs * @param array $configs
* @param ContainerBuilder $container * @param ContainerBuilder $container
*
* @throws Exception * @throws Exception
*/ */
public function load(array $configs, ContainerBuilder $container): void public function load(array $configs, ContainerBuilder $container): void

View File

@ -7,12 +7,11 @@ namespace Gregwar\CaptchaBundle\Generator;
use Gregwar\Captcha\CaptchaBuilder; use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder; use Gregwar\Captcha\PhraseBuilder;
use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Routing\RouterInterface;
use Gregwar\Captcha\CaptchaBuilderInterface; use Gregwar\Captcha\CaptchaBuilderInterface;
use Gregwar\Captcha\PhraseBuilderInterface; use Gregwar\Captcha\PhraseBuilderInterface;
/** /**
* Uses configuration parameters to call the services that generate captcha images * Uses configuration parameters to call the services that generate captcha images.
* *
* @author Gregwar <g.passault@gmail.com> * @author Gregwar <g.passault@gmail.com>
* @author Jeremy Livingston <jeremy.j.livingston@gmail.com> * @author Jeremy Livingston <jeremy.j.livingston@gmail.com>
@ -32,10 +31,10 @@ class CaptchaGenerator
protected $imageFileHandler; protected $imageFileHandler;
/** /**
* @param RouterInterface $router * @param RouterInterface $router
* @param CaptchaBuilderInterface $builder * @param CaptchaBuilderInterface $builder
* @param PhraseBuilderInterface $phraseBuilder * @param PhraseBuilderInterface $phraseBuilder
* @param ImageFileHandler $imageFileHandler * @param ImageFileHandler $imageFileHandler
*/ */
public function __construct( public function __construct(
RouterInterface $router, RouterInterface $router,
@ -43,9 +42,9 @@ class CaptchaGenerator
PhraseBuilderInterface $phraseBuilder, PhraseBuilderInterface $phraseBuilder,
ImageFileHandler $imageFileHandler ImageFileHandler $imageFileHandler
) { ) {
$this->router = $router; $this->router = $router;
$this->builder = $builder; $this->builder = $builder;
$this->phraseBuilder = $phraseBuilder; $this->phraseBuilder = $phraseBuilder;
$this->imageFileHandler = $imageFileHandler; $this->imageFileHandler = $imageFileHandler;
} }
@ -62,11 +61,13 @@ class CaptchaGenerator
// Returns the image generation URL // Returns the image generation URL
if ($options['as_url']) { if ($options['as_url']) {
return $this->router->generate('gregwar_captcha.generate_captcha', return $this->router->generate(
array('key' => $options['session_key'], 'n' => md5(microtime(true).mt_rand()))); 'gregwar_captcha.generate_captcha',
array('key' => $options['session_key'], 'n' => md5(microtime(true).mt_rand()))
);
} }
return 'data:image/jpeg;base64,' . base64_encode($this->generate($options)); return 'data:image/jpeg;base64,'.base64_encode($this->generate($options));
} }
public function setPhrase(string $phrase): void public function setPhrase(string $phrase): void
@ -82,7 +83,7 @@ class CaptchaGenerator
$this->builder->setMaxBehindLines($options['max_behind_lines']); $this->builder->setMaxBehindLines($options['max_behind_lines']);
if (isset($options['text_color']) && $options['text_color']) { if (isset($options['text_color']) && $options['text_color']) {
if (count($options['text_color']) !== 3) { if (3 !== count($options['text_color'])) {
throw new \RuntimeException('text_color should be an array of r, g and b'); throw new \RuntimeException('text_color should be an array of r, g and b');
} }
@ -91,7 +92,7 @@ class CaptchaGenerator
} }
if (isset($options['background_color']) && $options['background_color']) { if (isset($options['background_color']) && $options['background_color']) {
if (count($options['background_color']) !== 3) { if (3 !== count($options['background_color'])) {
throw new \RuntimeException('background_color should be an array of r, g and b'); throw new \RuntimeException('background_color should be an array of r, g and b');
} }

View File

@ -7,7 +7,7 @@ namespace Gregwar\CaptchaBundle\Generator;
use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\Finder;
/** /**
* Handles actions related to captcha image files including saving and garbage collection * Handles actions related to captcha image files including saving and garbage collection.
* *
* @author Gregwar <g.passault@gmail.com> * @author Gregwar <g.passault@gmail.com>
* @author Jeremy Livingston <jeremy@quizzle.com> * @author Jeremy Livingston <jeremy@quizzle.com>
@ -15,25 +15,29 @@ use Symfony\Component\Finder\Finder;
class ImageFileHandler class ImageFileHandler
{ {
/** /**
* Name of folder for captcha images * Name of folder for captcha images.
*
* @var string * @var string
*/ */
protected $imageFolder; protected $imageFolder;
/** /**
* Absolute path to public web folder * Absolute path to public web folder.
*
* @var string * @var string
*/ */
protected $webPath; protected $webPath;
/** /**
* Frequency of garbage collection in fractions of 1 * Frequency of garbage collection in fractions of 1.
*
* @var int * @var int
*/ */
protected $gcFreq; protected $gcFreq;
/** /**
* Maximum age of images in minutes * Maximum age of images in minutes.
*
* @var int * @var int
*/ */
protected $expiration; protected $expiration;
@ -47,25 +51,25 @@ class ImageFileHandler
public function __construct(string $imageFolder, string $webPath, string $gcFreq, string $expiration) public function __construct(string $imageFolder, string $webPath, string $gcFreq, string $expiration)
{ {
$this->imageFolder = $imageFolder; $this->imageFolder = $imageFolder;
$this->webPath= $webPath; $this->webPath = $webPath;
$this->gcFreq = $gcFreq; $this->gcFreq = $gcFreq;
$this->expiration = $expiration; $this->expiration = $expiration;
} }
public function saveAsFile($contents):string public function saveAsFile($contents): string
{ {
$this->createFolderIfMissing(); $this->createFolderIfMissing();
$filename = md5(uniqid()) . '.jpg'; $filename = md5(uniqid()).'.jpg';
$filePath = $this->webPath . '/' . $this->imageFolder . '/' . $filename; $filePath = $this->webPath.'/'.$this->imageFolder.'/'.$filename;
imagejpeg($contents, $filePath, 15); imagejpeg($contents, $filePath, 15);
return '/' . $this->imageFolder . '/' . $filename; return '/'.$this->imageFolder.'/'.$filename;
} }
public function collectGarbage(): bool public function collectGarbage(): bool
{ {
if (!mt_rand(1, $this->gcFreq) == 1) { if (1 == !mt_rand(1, $this->gcFreq)) {
return false; return false;
} }
@ -73,10 +77,10 @@ class ImageFileHandler
$finder = new Finder(); $finder = new Finder();
$criteria = sprintf('<= now - %s minutes', $this->expiration); $criteria = sprintf('<= now - %s minutes', $this->expiration);
$finder->in($this->webPath . '/' . $this->imageFolder) $finder->in($this->webPath.'/'.$this->imageFolder)
->date($criteria); ->date($criteria);
foreach($finder->files() as $file) { foreach ($finder->files() as $file) {
unlink($file->getPathname()); unlink($file->getPathname());
} }
@ -85,8 +89,8 @@ class ImageFileHandler
protected function createFolderIfMissing(): void protected function createFolderIfMissing(): void
{ {
if (!file_exists($this->webPath . '/' . $this->imageFolder)) { if (!file_exists($this->webPath.'/'.$this->imageFolder)) {
mkdir($this->webPath . '/' . $this->imageFolder, 0755); mkdir($this->webPath.'/'.$this->imageFolder, 0755);
} }
} }
} }

View File

@ -17,7 +17,7 @@ use Gregwar\CaptchaBundle\Validator\CaptchaValidator;
use Gregwar\CaptchaBundle\Generator\CaptchaGenerator; use Gregwar\CaptchaBundle\Generator\CaptchaGenerator;
/** /**
* Captcha type * Captcha type.
* *
* @author Gregwar <g.passault@gmail.com> * @author Gregwar <g.passault@gmail.com>
*/ */
@ -78,7 +78,7 @@ class CaptchaType extends AbstractType
} }
$sessionKey = sprintf('%s%s', self::SESSION_KEY_PREFIX, $options['session_key']); $sessionKey = sprintf('%s%s', self::SESSION_KEY_PREFIX, $options['session_key']);
$isHuman = false; $isHuman = false;
if ($options['humanity'] > 0) { if ($options['humanity'] > 0) {
$humanityKey = sprintf('%s_humanity', $sessionKey); $humanityKey = sprintf('%s_humanity', $sessionKey);
@ -97,18 +97,18 @@ class CaptchaType extends AbstractType
} }
$view->vars = array_merge($view->vars, array( $view->vars = array_merge($view->vars, array(
'captcha_width' => $options['width'], 'captcha_width' => $options['width'],
'captcha_height' => $options['height'], 'captcha_height' => $options['height'],
'reload' => $options['reload'], 'reload' => $options['reload'],
'image_id' => uniqid('captcha_'), 'image_id' => uniqid('captcha_'),
'captcha_code' => $this->generator->getCaptchaCode($options), 'captcha_code' => $this->generator->getCaptchaCode($options),
'value' => '', 'value' => '',
'is_human' => $isHuman 'is_human' => $isHuman,
)); ));
$persistOptions = array(); $persistOptions = array();
foreach (array('phrase', 'width', 'height', 'distortion', 'length', foreach (array('phrase', 'width', 'height', 'distortion', 'length',
'quality', 'background_color', 'background_images', 'text_color') as $key) { 'quality', 'background_color', 'background_images', 'text_color', ) as $key) {
$persistOptions[$key] = $options[$key]; $persistOptions[$key] = $options[$key];
} }

View File

@ -10,7 +10,7 @@ use Symfony\Component\Form\FormEvent;
use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface;
/** /**
* Captcha validator * Captcha validator.
* *
* @author Gregwar <g.passault@gmail.com> * @author Gregwar <g.passault@gmail.com>
*/ */
@ -20,31 +20,36 @@ class CaptchaValidator
private $session; private $session;
/** /**
* Session key to store the code * Session key to store the code.
*
* @var string * @var string
*/ */
private $key; private $key;
/** /**
* Error message text for non-matching submissions * Error message text for non-matching submissions.
*
* @var string * @var string
*/ */
private $invalidMessage; private $invalidMessage;
/** /**
* Configuration parameter used to bypass a required code match * Configuration parameter used to bypass a required code match.
*
* @var string * @var string
*/ */
private $bypassCode; private $bypassCode;
/** /**
* Number of form that the user can submit without captcha * Number of form that the user can submit without captcha.
*
* @var int * @var int
*/ */
private $humanity; private $humanity;
/** /**
* Translator * Translator.
*
* @var TranslatorInterface * @var TranslatorInterface
*/ */
private $translator; private $translator;
@ -57,12 +62,12 @@ class CaptchaValidator
?string $bypassCode, ?string $bypassCode,
int $humanity int $humanity
) { ) {
$this->translator = $translator; $this->translator = $translator;
$this->session = $session; $this->session = $session;
$this->key = $key; $this->key = $key;
$this->invalidMessage = $invalidMessage; $this->invalidMessage = $invalidMessage;
$this->bypassCode = $bypassCode; $this->bypassCode = $bypassCode;
$this->humanity = $humanity; $this->humanity = $humanity;
} }
public function validate(FormEvent $event): void public function validate(FormEvent $event): void
@ -75,12 +80,13 @@ class CaptchaValidator
if ($this->humanity > 0) { if ($this->humanity > 0) {
$humanity = $this->getHumanity(); $humanity = $this->getHumanity();
if ($humanity > 0) { if ($humanity > 0) {
$this->updateHumanity($humanity-1); $this->updateHumanity($humanity - 1);
return; return;
} }
} }
if (!($code !== null && is_string($code) && ($this->compare($code, $expectedCode) || $this->compare($code, $this->bypassCode)))) { if (!(null !== $code && is_string($code) && ($this->compare($code, $expectedCode) || $this->compare($code, $this->bypassCode)))) {
$form->addError(new FormError($this->translator->trans($this->invalidMessage, array(), 'validators'))); $form->addError(new FormError($this->translator->trans($this->invalidMessage, array(), 'validators')));
} else { } else {
if ($this->humanity > 0) { if ($this->humanity > 0) {
@ -90,13 +96,13 @@ class CaptchaValidator
$this->session->remove($this->key); $this->session->remove($this->key);
if ($this->session->has($this->key . '_fingerprint')) { if ($this->session->has($this->key.'_fingerprint')) {
$this->session->remove($this->key . '_fingerprint'); $this->session->remove($this->key.'_fingerprint');
} }
} }
/** /**
* Retrieve the expected CAPTCHA code * Retrieve the expected CAPTCHA code.
* *
* @return mixed|null * @return mixed|null
*/ */
@ -112,21 +118,21 @@ class CaptchaValidator
} }
/** /**
* Retrieve the humanity * Retrieve the humanity.
* *
* @return mixed|null * @return mixed|null
*/ */
protected function getHumanity() protected function getHumanity()
{ {
return $this->session->get($this->key . '_humanity', 0); return $this->session->get($this->key.'_humanity', 0);
} }
protected function updateHumanity(int $newValue): void protected function updateHumanity(int $newValue): void
{ {
if ($newValue > 0) { if ($newValue > 0) {
$this->session->set($this->key . '_humanity', $newValue); $this->session->set($this->key.'_humanity', $newValue);
} else { } else {
$this->session->remove($this->key . '_humanity'); $this->session->remove($this->key.'_humanity');
} }
} }
@ -136,14 +142,15 @@ class CaptchaValidator
} }
/** /**
* Run a match comparison on the provided code and the expected code * Run a match comparison on the provided code and the expected code.
* *
* @param string $code * @param string $code
* @param string|null $expectedCode * @param string|null $expectedCode
*
* @return bool * @return bool
*/ */
protected function compare($code, $expectedCode): bool protected function compare($code, $expectedCode): bool
{ {
return ($expectedCode !== null && is_string($expectedCode) && $this->niceize($code) == $this->niceize($expectedCode)); return null !== $expectedCode && is_string($expectedCode) && $this->niceize($code) == $this->niceize($expectedCode);
} }
} }