Applied code style rules to src/

This commit is contained in:
Jan Böhmer 2020-01-05 15:46:58 +01:00
parent 700c049d26
commit f861de791f
186 changed files with 1462 additions and 1059 deletions

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -37,7 +40,50 @@ class AmountFormatter
$this->siFormatter = $siFormatter;
}
protected function configureOptions(OptionsResolver $resolver)
/**
* Formats the given value using the measurement unit and options.
*
* @param MeasurementUnit|null $unit The measurement unit, whose unit symbol should be used for formatting.
* If set to null, it is assumed that the part amount is measured in pieces.
*
* @return string The formatted string
*
* @throws \InvalidArgumentException thrown if $value is not numeric
*/
public function format($value, ?MeasurementUnit $unit = null, array $options = [])
{
if (! is_numeric($value)) {
throw new \InvalidArgumentException('$value must be an numeric value!');
}
$value = (float) $value;
//Find out what options to use
$resolver = new OptionsResolver();
$resolver->setDefault('measurement_unit', $unit);
$this->configureOptions($resolver);
$options = $resolver->resolve($options);
if ($options['is_integer']) {
$value = round($value);
}
//If the measurement unit uses a SI prefix format it that way.
if ($options['show_prefix']) {
return $this->siFormatter->format($value, $options['unit'], $options['decimals']);
}
//Otherwise just output it
if (! empty($options['unit'])) {
$format_string = '%.'.$options['decimals'].'f '.$options['unit'];
} else { //Dont add space after number if no unit was specified
$format_string = '%.'.$options['decimals'].'f';
}
return sprintf($format_string, $value);
}
protected function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'show_prefix' => function (Options $options) {
@ -85,48 +131,4 @@ class AmountFormatter
return $value;
});
}
/**
* Formats the given value using the measurement unit and options.
*
* @param $value float|int The value that should be formatted. Must be numeric.
* @param MeasurementUnit|null $unit The measurement unit, whose unit symbol should be used for formatting.
* If set to null, it is assumed that the part amount is measured in pieces.
*
* @return string The formatted string
*
* @throws \InvalidArgumentException thrown if $value is not numeric
*/
public function format($value, ?MeasurementUnit $unit = null, array $options = [])
{
if (!is_numeric($value)) {
throw new \InvalidArgumentException('$value must be an numeric value!');
}
$value = (float) $value;
//Find out what options to use
$resolver = new OptionsResolver();
$resolver->setDefault('measurement_unit', $unit);
$this->configureOptions($resolver);
$options = $resolver->resolve($options);
if ($options['is_integer']) {
$value = round($value);
}
//If the measurement unit uses a SI prefix format it that way.
if ($options['show_prefix']) {
return $this->siFormatter->format($value, $options['unit'], $options['decimals']);
}
//Otherwise just output it
if (!empty($options['unit'])) {
$format_string = '%.'.$options['decimals'].'f '.$options['unit'];
} else { //Dont add space after number if no unit was specified
$format_string = '%.'.$options['decimals'].'f';
}
return sprintf($format_string, $value);
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -49,7 +52,7 @@ class AttachmentManager
*/
public function attachmentToFile(Attachment $attachment): ?\SplFileInfo
{
if ($attachment->isExternal() || !$this->isFileExisting($attachment)) {
if ($attachment->isExternal() || ! $this->isFileExisting($attachment)) {
return null;
}
@ -117,7 +120,7 @@ class AttachmentManager
return null;
}
if (!$this->isFileExisting($attachment)) {
if (! $this->isFileExisting($attachment)) {
return null;
}
@ -138,7 +141,7 @@ class AttachmentManager
{
$bytes = $this->getFileSize($attachment);
if (null == $bytes) {
if (null === $bytes) {
return null;
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -114,23 +117,6 @@ class AttachmentPathResolver
return $tmp;
}
/**
* Create an array usable for preg_replace out of an array of placeholders or pathes.
* Slashes and other chars become escaped.
* For example: '%TEST%' becomes '/^%TEST%/'.
*/
protected function arrayToRegexArray(array $array): array
{
$ret = [];
foreach ($array as $item) {
$item = str_replace(['\\'], ['/'], $item);
$ret[] = '/'.preg_quote($item, '/').'/';
}
return $ret;
}
/**
* Converts an relative placeholder filepath (with %MEDIA% or older %BASE%) to an absolute filepath on disk.
* The directory separator is always /. Relative pathes are not realy possible (.. is striped).
@ -163,9 +149,7 @@ class AttachmentPathResolver
}
//Normalize path and remove .. (to prevent directory traversal attack)
$placeholder_path = str_replace(['\\'], ['/'], $placeholder_path);
return $placeholder_path;
return str_replace(['\\'], ['/'], $placeholder_path);
}
/**
@ -199,7 +183,7 @@ class AttachmentPathResolver
}
//If the new string does not begin with a placeholder, it is invalid
if (!preg_match('/^%\w+%/', $real_path)) {
if (! preg_match('/^%\w+%/', $real_path)) {
return null;
}
@ -246,4 +230,21 @@ class AttachmentPathResolver
{
return $this->models_path;
}
/**
* Create an array usable for preg_replace out of an array of placeholders or pathes.
* Slashes and other chars become escaped.
* For example: '%TEST%' becomes '/^%TEST%/'.
*/
protected function arrayToRegexArray(array $array): array
{
$ret = [];
foreach ($array as $item) {
$item = str_replace(['\\'], ['/'], $item);
$ret[] = '/'.preg_quote($item, '/').'/';
}
return $ret;
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -71,17 +74,6 @@ class AttachmentSubmitHandler
SupplierAttachment::class => 'supplier', UserAttachment::class => 'user', ];
}
protected function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
//If no preview image was set yet, the new uploaded file will become the preview image
'become_preview_if_empty' => true,
//When an URL is given download the URL
'download_url' => false,
'secure_attachment' => false,
]);
}
/**
* Generates a filename for the given attachment and extension.
* The filename contains a random id, so every time this function is called you get an unique name.
@ -125,7 +117,7 @@ class AttachmentSubmitHandler
}
//Ensure the given attachment class is known to mapping
if (!isset($this->folder_mapping[\get_class($attachment)])) {
if (! isset($this->folder_mapping[\get_class($attachment)])) {
throw new \InvalidArgumentException('The given attachment class is not known! The passed class was: '.\get_class($attachment));
}
//Ensure the attachment has an assigned element
@ -178,6 +170,17 @@ class AttachmentSubmitHandler
return $attachment;
}
protected function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
//If no preview image was set yet, the new uploaded file will become the preview image
'become_preview_if_empty' => true,
//When an URL is given download the URL
'download_url' => false,
'secure_attachment' => false,
]);
}
/**
* Move the given attachment to secure location (or back to public folder) if needed.
*
@ -200,13 +203,13 @@ class AttachmentSubmitHandler
//Determine the old filepath
$old_path = $this->pathResolver->placeholderToRealPath($attachment->getPath());
if (!file_exists($old_path)) {
if (! file_exists($old_path)) {
return $attachment;
}
$filename = basename($old_path);
//If the basename is not one of the new unique on, we have to save the old filename
if (!preg_match('/\w+-\w{13}\./', $filename)) {
if (! preg_match('/\w+-\w{13}\./', $filename)) {
//Save filename to attachment field
$attachment->setFilename($attachment->getFilename());
}
@ -236,7 +239,7 @@ class AttachmentSubmitHandler
protected function downloadURL(Attachment $attachment, array $options): Attachment
{
//Check if we are allowed to download files
if (!$this->allow_attachments_downloads) {
if (! $this->allow_attachments_downloads) {
throw new \RuntimeException('Download of attachments is not allowed!');
}
@ -286,7 +289,7 @@ class AttachmentSubmitHandler
//Check if we have a extension given
$pathinfo = pathinfo($filename);
if (!empty($pathinfo['extension'])) {
if (! empty($pathinfo['extension'])) {
$new_ext = $pathinfo['extension'];
} else { //Otherwise we have to guess the extension for the new file, based on its content
$new_ext = $this->mimeTypes->getExtensions($this->mimeTypes->guessMimeType($tmp_path))[0] ?? 'tmp';

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -102,7 +105,7 @@ class AttachmentURLGenerator
*/
public function getThumbnailURL(Attachment $attachment, string $filter_name = 'thumbnail_sm'): string
{
if (!$attachment->isPicture()) {
if (! $attachment->isPicture()) {
throw new \InvalidArgumentException('Thumbnail creation only works for picture attachments!');
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -40,16 +43,6 @@ class BuiltinAttachmentsFinder
$this->cache = $cache;
}
protected function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'limit' => 15, //Given only 15 entries
//'allowed_extensions' => [], //Filter the filenames. For example ['jpg', 'jpeg'] to only get jpegs.
//'placeholders' => Attachment::BUILTIN_PLACEHOLDER, //By default use all builtin ressources,
'empty_returns_all' => false, //Return the whole list of ressources when empty keyword is given
]);
}
/**
* Returns a list of all builtin ressources.
* The array is a list of the relative filenames using the %PLACEHOLDERS%.
@ -138,4 +131,14 @@ class BuiltinAttachmentsFinder
return preg_grep($regex, $base_list);
}
protected function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'limit' => 15, //Given only 15 entries
//'allowed_extensions' => [], //Filter the filenames. For example ['jpg', 'jpeg'] to only get jpegs.
//'placeholders' => Attachment::BUILTIN_PLACEHOLDER, //By default use all builtin ressources,
'empty_returns_all' => false, //Return the whole list of ressources when empty keyword is given
]);
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -39,9 +42,9 @@ class FileTypeFilterTools
protected const IMAGE_EXTS = Attachment::PICTURE_EXTS;
protected const VIDEO_EXTS = ['mp4', 'ogv', 'ogg', 'webm'];
protected const AUDIO_EXTS = ['mp3', 'flac', 'ogg', 'oga', 'wav', 'm4a', 'opus'];
protected const ALLOWED_MIME_PLACEHOLDERS = ['image/*', 'audio/*', 'video/*'];
protected $mimeTypes;
protected const ALLOWED_MIME_PLACEHOLDERS = ['image/*', 'audio/*', 'video/*'];
protected $cache;
public function __construct(MimeTypesInterface $mimeTypes, CacheInterface $cache)
@ -69,9 +72,9 @@ class FileTypeFilterTools
//Check for each element if it is valid:
foreach ($elements as $element) {
$element = trim($element);
if (!preg_match('/^\.\w+$/', $element) // .ext is allowed
&& !preg_match('/^[-\w.]+\/[-\w.]+/', $element) //Explicit MIME type is allowed
&& !\in_array($element, static::ALLOWED_MIME_PLACEHOLDERS, false)) { //image/* is allowed
if (! preg_match('/^\.\w+$/', $element) // .ext is allowed
&& ! preg_match('/^[-\w.]+\/[-\w.]+/', $element) //Explicit MIME type is allowed
&& ! \in_array($element, static::ALLOWED_MIME_PLACEHOLDERS, false)) { //image/* is allowed
return false;
}
}
@ -117,7 +120,7 @@ class FileTypeFilterTools
$element = 'video/*';
} elseif ('audio' === $element || 'audio/' === $element) {
$element = 'audio/*';
} elseif (!preg_match('/^[-\w.]+\/[-\w.*]+/', $element) && 0 !== strpos($element, '.')) {
} elseif (! preg_match('/^[-\w.]+\/[-\w.*]+/', $element) && 0 !== strpos($element, '.')) {
//Convert jpg to .jpg
$element = '.'.$element;
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -26,25 +29,19 @@ use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
class CustomEnvVarProcessor implements EnvVarProcessorInterface
{
/**
* {@inheritdoc}
*/
public function getEnv($prefix, $name, \Closure $getEnv)
{
if ('validMailDSN' === $prefix) {
try {
$env = $getEnv($name);
return !empty($env) && 'null://null' !== $env;
return ! empty($env) && 'null://null' !== $env;
} catch (EnvNotFoundException $exception) {
return false;
}
}
}
/**
* {@inheritdoc}
*/
public static function getProvidedTypes()
{
return [

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -42,7 +45,6 @@ class EntityExporter
/**
* Exports an Entity or an array of entities to multiple file formats.
*
* @param $entity NamedDBElement|NamedDBElement[] The element/elements[] that should be exported
* @param Request $request the request that should be used for option resolving
*
* @return Response the generated response containing the exported data
@ -54,13 +56,13 @@ class EntityExporter
$format = $request->get('format') ?? 'json';
//Check if we have one of the supported formats
if (!\in_array($format, ['json', 'csv', 'yaml', 'xml'])) {
if (! \in_array($format, ['json', 'csv', 'yaml', 'xml'], true)) {
throw new \InvalidArgumentException('Given format is not supported!');
}
//Check export verbosity level
$level = $request->get('level') ?? 'extended';
if (!\in_array($level, ['simple', 'extended', 'full'])) {
if (! \in_array($level, ['simple', 'extended', 'full'], true)) {
throw new \InvalidArgumentException('Given level is not supported!');
}
@ -80,9 +82,11 @@ class EntityExporter
switch ($format) {
case 'xml':
$content_type = 'application/xml';
break;
case 'json':
$content_type = 'application/json';
break;
}
@ -104,7 +108,7 @@ class EntityExporter
$response->headers->set('Content-Type', $content_type);
//If view option is not specified, then download the file.
if (!$request->get('view')) {
if (! $request->get('view')) {
if ($entity instanceof NamedDBElement) {
$entity_name = $entity->getName();
} elseif (\is_array($entity)) {

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -41,17 +44,6 @@ class EntityImporter
$this->validator = $validator;
}
protected function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'csv_separator' => ';',
'format' => 'json',
'preserve_children' => true,
'parent' => null,
'abort_on_validation_error' => true,
]);
}
/**
* Creates many entries at once, based on a (text) list of name.
* The created enties are not persisted to database yet, so you have to do it yourself.
@ -68,10 +60,10 @@ class EntityImporter
//Expand every line to a single entry:
$names = explode("\n", $lines);
if (!is_a($class_name, StructuralDBElement::class, true)) {
if (! is_a($class_name, StructuralDBElement::class, true)) {
throw new \InvalidArgumentException('$class_name must be a StructuralDBElement type!');
}
if (null !== $parent && !is_a($parent, $class_name)) {
if (null !== $parent && ! is_a($parent, $class_name)) {
throw new \InvalidArgumentException('$parent must have the same type as specified in $class_name!');
}
@ -84,7 +76,7 @@ class EntityImporter
//Skip empty lines (StrucuralDBElements must have a name)
continue;
}
/** @var $entity StructuralDBElement */
/** @var StructuralDBElement $entity */
//Create new element with given name
$entity = new $class_name();
$entity->setName($name);
@ -127,7 +119,7 @@ class EntityImporter
//Iterate over each $entity write it to DB.
foreach ($entities as $entity) {
/* @var StructuralDBElement $entity */
/** @var StructuralDBElement $entity */
//Move every imported entity to the selected parent
$entity->setParent($options['parent']);
@ -143,7 +135,7 @@ class EntityImporter
}
//Save changes to database, when no error happened, or we should continue on error.
if (empty($errors) || false == $options['abort_on_validation_error']) {
if (empty($errors) || false === $options['abort_on_validation_error']) {
$this->em->flush();
}
@ -182,7 +174,7 @@ class EntityImporter
['groups' => $groups, 'csv_delimiter' => $options['csv_separator']]);
//Ensure we have an array of entitity elements.
if (!\is_array($entities)) {
if (! \is_array($entities)) {
$entities = [$entities];
}
@ -194,16 +186,27 @@ class EntityImporter
return $entities;
}
protected function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'csv_separator' => ';',
'format' => 'json',
'preserve_children' => true,
'parent' => null,
'abort_on_validation_error' => true,
]);
}
/**
* This functions corrects the parent setting based on the children value of the parent.
*
* @param iterable $entities the list of entities that should be fixed
* @param null $parent the parent, to which the entity should be set
*/
protected function correctParentEntites(iterable $entities, $parent = null)
protected function correctParentEntites(iterable $entities, $parent = null): void
{
foreach ($entities as $entity) {
/* @var $entity StructuralDBElement */
/** @var StructuralDBElement $entity */
$entity->setParent($parent);
//Do the same for the children of entity
$this->correctParentEntites($entity->getChildren(), $entity);

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -58,43 +61,13 @@ class EntityURLGenerator
$this->attachmentURLGenerator = $attachmentURLGenerator;
}
/**
* Finds the controller name for the class of the entity using the given map.
* Throws an exception if the entity class is not known to the map.
*
* @param array $map The map that should be used for determing the controller
* @param $entity mixed The entity for which the controller name should be determined
*
* @return string The name of the controller fitting the entity class
*
* @throws EntityNotSupportedException
*/
protected function mapToController(array $map, $entity): string
{
$class = \get_class($entity);
//Check if we have an direct mapping for the given class
if (!\array_key_exists($class, $map)) {
//Check if we need to check inheritance by looping through our map
foreach ($map as $key => $value) {
if (is_a($entity, $key)) {
return $map[$key];
}
}
throw new EntityNotSupportedException(sprintf('The given entity is not supported yet! Passed class type: %s', \get_class($entity)));
}
return $map[$class];
}
/**
* Generates an URL to the page using the given page type and element.
* For the given types, the [type]URL() functions are called (e.g. infoURL()).
* Not all entity class and $type combinations are supported.
*
* @param $entity mixed The element for which the page should be generated
* @param string $type The page type. Currently supported: 'info', 'edit', 'create', 'clone', 'list'/'list_parts'
* @param mixed $entity The element for which the page should be generated
* @param string $type The page type. Currently supported: 'info', 'edit', 'create', 'clone', 'list'/'list_parts'
*
* @return string the link to the desired page
*
@ -157,7 +130,7 @@ class EntityURLGenerator
/**
* Generates an URL to a page, where info about this entity can be viewed.
*
* @param $entity mixed The entity for which the info should be generated
* @param mixed $entity The entity for which the info should be generated
*
* @return string The URL to the info page
*
@ -188,7 +161,7 @@ class EntityURLGenerator
/**
* Generates an URL to a page, where this entity can be edited.
*
* @param $entity mixed The entity for which the edit link should be generated
* @param mixed $entity The entity for which the edit link should be generated
*
* @return string the URL to the edit page
*
@ -217,7 +190,7 @@ class EntityURLGenerator
/**
* Generates an URL to a page, where a entity of this type can be created.
*
* @param $entity mixed The entity for which the link should be generated
* @param mixed $entity The entity for which the link should be generated
*
* @return string the URL to the page
*
@ -247,7 +220,7 @@ class EntityURLGenerator
* Generates an URL to a page, where a new entity can be created, that has the same informations as the
* given entity (element cloning).
*
* @param $entity mixed The entity for which the link should be generated
* @param mixed $entity The entity for which the link should be generated
*
* @return string the URL to the page
*
@ -265,7 +238,7 @@ class EntityURLGenerator
/**
* Generates an URL to a page, where all parts are listed, which are contained in the given element.
*
* @param $entity mixed The entity for which the link should be generated
* @param mixed $entity The entity for which the link should be generated
*
* @return string the URL to the page
*
@ -303,4 +276,34 @@ class EntityURLGenerator
return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]);
}
/**
* Finds the controller name for the class of the entity using the given map.
* Throws an exception if the entity class is not known to the map.
*
* @param array $map The map that should be used for determing the controller
* @param mixed $entity The entity for which the controller name should be determined
*
* @return string The name of the controller fitting the entity class
*
* @throws EntityNotSupportedException
*/
protected function mapToController(array $map, $entity): string
{
$class = \get_class($entity);
//Check if we have an direct mapping for the given class
if (! \array_key_exists($class, $map)) {
//Check if we need to check inheritance by looping through our map
foreach ($map as $key => $value) {
if (is_a($entity, $key)) {
return $map[$key];
}
}
throw new EntityNotSupportedException(sprintf('The given entity is not supported yet! Passed class type: %s', \get_class($entity)));
}
return $map[$class];
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -48,7 +51,7 @@ class MoneyFormatter
public function format($value, ?Currency $currency = null, $decimals = 5, bool $show_all_digits = false)
{
$iso_code = $this->base_currency;
if (null !== $currency && !empty($currency->getIsoCode())) {
if (null !== $currency && ! empty($currency->getIsoCode())) {
$iso_code = $currency->getIsoCode();
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -45,7 +48,7 @@ class PasswordResetManager
{
$this->em = $em;
$this->mailer = $mailer;
/* @var PasswordEncoderInterface passwordEncoder */
/** @var PasswordEncoderInterface passwordEncoder */
$this->passwordEncoder = $encoderFactory->getEncoder(User::class);
$this->translator = $translator;
$this->userPasswordEncoder = $userPasswordEncoder;
@ -70,7 +73,7 @@ class PasswordResetManager
$expiration_date->add(date_interval_create_from_date_string('1 day'));
$user->setPwResetExpires($expiration_date);
if (!empty($user->getEmail())) {
if (! empty($user->getEmail())) {
$address = new Address($user->getEmail(), $user->getFullName());
$mail = new TemplatedEmail();
$mail->to($address);
@ -118,7 +121,7 @@ class PasswordResetManager
}
//Check if token is valid
if (!$this->passwordEncoder->isPasswordValid($user->getPwResetToken(), $token, null)) {
if (! $this->passwordEncoder->isPasswordValid($user->getPwResetToken(), $token, null)) {
return false;
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -58,43 +61,6 @@ class PermissionResolver
return $this->permission_structure;
}
protected function generatePermissionStructure()
{
$cache = new ConfigCache($this->cache_file, $this->is_debug);
//Check if the cache is fresh, else regenerate it.
if (!$cache->isFresh()) {
$permission_file = __DIR__.'/../../config/permissions.yaml';
//Read the permission config file...
$config = Yaml::parse(
file_get_contents($permission_file)
);
$configs = [$config];
//... And parse it
$processor = new Processor();
$databaseConfiguration = new PermissionsConfiguration();
$processedConfiguration = $processor->processConfiguration(
$databaseConfiguration,
$configs
);
//Permission file is our file resource (it is used to invalidate cache)
$resources = [];
$resources[] = new FileResource($permission_file);
//Var export the structure and write it to cache file.
$cache->write(
sprintf('<?php return %s;', var_export($processedConfiguration, true)),
$resources);
}
//In the most cases we just need to dump the cached PHP file.
return require $this->cache_file;
}
/**
* Check if a user/group is allowed to do the specified operation for the permission.
*
@ -144,7 +110,7 @@ class PermissionResolver
}
$parent = $user->getGroup();
while (null != $parent) { //The top group, has parent == null
while (null !== $parent) { //The top group, has parent == null
//Check if our current element gives a info about disallow/allow
$allowed = $this->dontInherit($parent, $permission, $operation);
if (null !== $allowed) {
@ -189,7 +155,7 @@ class PermissionResolver
*/
public function listOperationsForPermission(string $permission): array
{
if (!$this->isValidPermission($permission)) {
if (! $this->isValidPermission($permission)) {
throw new \InvalidArgumentException(sprintf('A permission with that name is not existing! Got %s.', $permission));
}
$operations = $this->permission_structure['perms'][$permission]['operations'];
@ -222,4 +188,41 @@ class PermissionResolver
return $this->isValidPermission($permission) &&
isset($this->permission_structure['perms'][$permission]['operations'][$operation]);
}
protected function generatePermissionStructure()
{
$cache = new ConfigCache($this->cache_file, $this->is_debug);
//Check if the cache is fresh, else regenerate it.
if (! $cache->isFresh()) {
$permission_file = __DIR__.'/../../config/permissions.yaml';
//Read the permission config file...
$config = Yaml::parse(
file_get_contents($permission_file)
);
$configs = [$config];
//... And parse it
$processor = new Processor();
$databaseConfiguration = new PermissionsConfiguration();
$processedConfiguration = $processor->processConfiguration(
$databaseConfiguration,
$configs
);
//Permission file is our file resource (it is used to invalidate cache)
$resources = [];
$resources[] = new FileResource($permission_file);
//Var export the structure and write it to cache file.
$cache->write(
sprintf('<?php return %s;', var_export($processedConfiguration, true)),
$resources);
}
//In the most cases we just need to dump the cached PHP file.
return require $this->cache_file;
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -167,7 +170,6 @@ class PricedetailHelper
/**
* Converts the given value in origin currency to the choosen target currency.
*
* @param $value float|string The value that should be converted
* @param Currency|null $originCurrency The currency the $value is given in.
* Set to null, to use global base currency.
* @param Currency|null $targetCurrency The target currency, to which $value should be converted.

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -71,13 +74,11 @@ class SIFormatter
//Choose the prefix to use
$tmp = $this->getPrefixByMagnitude($this->getMagnitude($value));
$ret = [
return [
'value' => $value / $tmp[0],
'prefix_magnitude' => log10($tmp[0]),
'prefix' => $tmp[1],
];
return $ret;
}
/**

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -47,7 +50,7 @@ class StructuralElementRecursionHelper
public function execute(StructuralDBElement $element, callable $func, int $max_depth = -1, $call_from_bottom = true): void
{
//Cancel if we reached our maximal allowed level. Must be zero because -1 is infinity levels
if (0 == $max_depth) {
if (0 === $max_depth) {
return;
}
@ -55,7 +58,7 @@ class StructuralElementRecursionHelper
$children = $element->getChildren();
//If we should call from top we execute the func here.
if (!$call_from_bottom) {
if (! $call_from_bottom) {
$func($element);
}
@ -80,7 +83,7 @@ class StructuralElementRecursionHelper
{
$em = $this->em;
$this->execute($element, static function (StructuralDBElement $element) use ($em) {
$this->execute($element, static function (StructuralDBElement $element) use ($em): void {
$em->remove($element);
});

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -39,7 +42,7 @@ class BackupCodeManager
* Enable backup codes for the given user, by generating a set of backup codes.
* If the backup codes were already enabled before, they a.
*/
public function enableBackupCodes(User $user)
public function enableBackupCodes(User $user): void
{
if (empty($user->getBackupCodes())) {
$this->regenerateBackupCodes($user);
@ -49,7 +52,7 @@ class BackupCodeManager
/**
* Disable (remove) the backup codes when no other 2 factor authentication methods are enabled.
*/
public function disableBackupCodesIfUnused(User $user)
public function disableBackupCodesIfUnused(User $user): void
{
if ($user->isGoogleAuthenticatorEnabled()) {
return;
@ -64,7 +67,7 @@ class BackupCodeManager
*
* @param User $user The user for which the backup codes should be regenerated
*/
public function regenerateBackupCodes(User $user)
public function regenerateBackupCodes(User $user): void
{
$codes = $this->backupCodeGenerator->generateCodeSet();
$user->setBackupCodes($codes);

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -37,15 +40,6 @@ class TagFinder
$this->em = $entityManager;
}
protected function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'query_limit' => 75,
'return_limit' => 25,
'min_keyword_length' => 3,
]);
}
/**
* Search tags that begins with the certain keyword.
*
@ -91,4 +85,13 @@ class TagFinder
//Limit the returned tag count to specified value.
return \array_slice($results, 0, $options['return_limit']);
}
protected function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'query_limit' => 75,
'return_limit' => 25,
'min_keyword_length' => 3,
]);
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -45,9 +48,9 @@ class PermissionExtractor implements ExtractorInterface
* @param string|array $resource Files, a file or a directory
* @param MessageCatalogue $catalogue The catalogue
*/
public function extract($resource, MessageCatalogue $catalogue)
public function extract($resource, MessageCatalogue $catalogue): void
{
if (!$this->finished) {
if (! $this->finished) {
//Extract for every group...
foreach ($this->permission_structure['groups'] as $group) {
if (isset($group['label'])) {

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -55,22 +58,18 @@ class NodesListBuilder
*/
public function typeToNodesList(string $class_name, ?StructuralDBElement $parent = null): array
{
$parent_id = null != $parent ? $parent->getID() : '0';
$parent_id = null !== $parent ? $parent->getID() : '0';
// Backslashes are not allowed in cache keys
$secure_class_name = str_replace('\\', '_', $class_name);
$key = 'list_'.$this->keyGenerator->generateKey().'_'.$secure_class_name.$parent_id;
$ret = $this->cache->get($key, function (ItemInterface $item) use ($class_name, $parent, $secure_class_name) {
return $this->cache->get($key, function (ItemInterface $item) use ($class_name, $parent, $secure_class_name) {
// Invalidate when groups, a element with the class or the user changes
$item->tag(['groups', 'tree_list', $this->keyGenerator->generateKey(), $secure_class_name]);
/**
* @var StructuralDBElementRepository
*/
/** @var StructuralDBElementRepository */
$repo = $this->em->getRepository($class_name);
return $repo->toNodesList($parent);
});
return $ret;
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -63,7 +66,7 @@ class TreeViewGenerator
*
* @return TreeViewNode[] An array of TreeViewNode[] elements of the root elements.
*/
public function getTreeView(string $class, ?StructuralDBElement $parent = null, string $href_type = 'list_parts', DBElement $selectedElement = null): array
public function getTreeView(string $class, ?StructuralDBElement $parent = null, string $href_type = 'list_parts', ?DBElement $selectedElement = null): array
{
$head = [];
@ -73,7 +76,7 @@ class TreeViewGenerator
$href = $this->urlGenerator->createURL(new $class());
$new_node = new TreeViewNode($this->translator->trans('entity.tree.new'), $href);
//When the id of the selected element is null, then we have a new element, and we need to select "new" node
if (null == $selectedElement || null == $selectedElement->getID()) {
if (null === $selectedElement || null === $selectedElement->getID()) {
$new_node->setSelected(true);
}
$head[] = $new_node;
@ -88,16 +91,16 @@ class TreeViewGenerator
$treeIterator = new TreeViewNodeIterator($generic);
$recursiveIterator = new \RecursiveIteratorIterator($treeIterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($recursiveIterator as $item) {
/** @var $item TreeViewNode */
/** @var TreeViewNode $item */
if (null !== $selectedElement && $item->getId() === $selectedElement->getID()) {
$item->setSelected(true);
}
if (!empty($item->getNodes())) {
if (! empty($item->getNodes())) {
$item->addTag((string) \count($item->getNodes()));
}
if (!empty($href_type)) {
if (! empty($href_type)) {
$entity = $this->em->getPartialReference($class, $item->getId());
$item->setHref($this->urlGenerator->getURL($entity, $href_type));
}
@ -118,10 +121,10 @@ class TreeViewGenerator
*/
public function getGenericTree(string $class, ?StructuralDBElement $parent = null): array
{
if (!is_a($class, NamedDBElement::class, true)) {
if (! is_a($class, NamedDBElement::class, true)) {
throw new \InvalidArgumentException('$class must be a class string that implements StructuralDBElement or NamedDBElement!');
}
if (null !== $parent && !is_a($parent, $class)) {
if (null !== $parent && ! is_a($parent, $class)) {
throw new \InvalidArgumentException('$parent must be of the type $class!');
}
@ -136,13 +139,11 @@ class TreeViewGenerator
$secure_class_name = str_replace('\\', '_', $class);
$key = 'treeview_'.$this->keyGenerator->generateKey().'_'.$secure_class_name;
$ret = $this->cache->get($key, function (ItemInterface $item) use ($repo, $parent, $secure_class_name) {
return $this->cache->get($key, function (ItemInterface $item) use ($repo, $parent, $secure_class_name) {
// Invalidate when groups, a element with the class or the user changes
$item->tag(['groups', 'tree_treeview', $this->keyGenerator->generateKey(), $secure_class_name]);
return $repo->getGenericNodeTree($parent);
});
return $ret;
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -42,7 +45,7 @@ class UserCacheKeyGenerator
* @param User|null $user The user for which the key should be generated. When set to null, the currently logged in
* user is used.
*/
public function generateKey(User $user = null): string
public function generateKey(?User $user = null): string
{
$locale = \Locale::getDefault();