Fixed coding style.

This commit is contained in:
Jan Böhmer 2020-05-10 21:39:31 +02:00
parent e9493e52ec
commit f5d685dfd4
71 changed files with 619 additions and 531 deletions

View file

@ -62,9 +62,9 @@ class AmountFormatter
/**
* Formats the given value using the measurement unit and options.
*
* @param float|string|int $value
* @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.
* @param float|string|int $value
* @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
*

View file

@ -242,7 +242,7 @@ class EntityURLGenerator
Currency::class => 'currency_edit',
MeasurementUnit::class => 'measurement_unit_edit',
Group::class => 'group_edit',
LabelProfile::class => 'label_profile_edit'
LabelProfile::class => 'label_profile_edit',
];
return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]);
@ -272,7 +272,7 @@ class EntityURLGenerator
Currency::class => 'currency_edit',
MeasurementUnit::class => 'measurement_unit_edit',
Group::class => 'group_edit',
LabelProfile::class => 'label_profile_edit'
LabelProfile::class => 'label_profile_edit',
];
return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]);
@ -302,7 +302,7 @@ class EntityURLGenerator
Currency::class => 'currency_new',
MeasurementUnit::class => 'measurement_unit_new',
Group::class => 'group_new',
LabelProfile::class => 'label_profile_new'
LabelProfile::class => 'label_profile_new',
];
return $this->urlGenerator->generate($this->mapToController($map, $entity));
@ -333,7 +333,7 @@ class EntityURLGenerator
Currency::class => 'currency_clone',
MeasurementUnit::class => 'measurement_unit_clone',
Group::class => 'group_clone',
LabelProfile::class => 'label_profile_clone'
LabelProfile::class => 'label_profile_clone',
];
return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]);
@ -376,7 +376,7 @@ class EntityURLGenerator
Currency::class => 'currency_delete',
MeasurementUnit::class => 'measurement_unit_delete',
Group::class => 'group_delete',
LabelProfile::class => 'label_profile_delete'
LabelProfile::class => 'label_profile_delete',
];
return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]);

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,18 +43,23 @@ final class BarcodeGenerator
switch ($options->getBarcodeType()) {
case 'qr':
$type = 'QRCODE';
break;
case 'datamatrix':
$type = 'DATAMATRIX';
break;
case 'code39':
$type = 'C39';
break;
case 'code93':
$type = 'C93';
break;
case 'code128':
$type = 'C128A';
break;
case 'none':
return null;
@ -80,5 +88,4 @@ final class BarcodeGenerator
throw new \InvalidArgumentException('Unknown label type!');
}
}
}
}

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).
*
@ -20,24 +23,18 @@
namespace App\Services\LabelSystem\Barcodes;
use App\Entity\Base\AbstractDBElement;
use App\Entity\Parts\Manufacturer;
use App\Entity\Parts\Part;
use App\Entity\Parts\PartLot;
use App\Entity\Parts\Storelocation;
use App\Entity\Parts\Supplier;
use App\Exceptions\EntityNotSupportedException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
final class BarcodeContentGenerator
{
private $urlGenerator;
public const PREFIX_MAP = [
Part::class => 'P',
PartLot::class => 'L',
Storelocation::class => 'S'
Storelocation::class => 'S',
];
private const URL_MAP = [
@ -45,6 +42,7 @@ final class BarcodeContentGenerator
PartLot::class => 'lot',
Storelocation::class => 'location',
];
private $urlGenerator;
public function __construct(UrlGeneratorInterface $urlGenerator)
{
@ -53,7 +51,7 @@ final class BarcodeContentGenerator
/**
* Generates a fixed URL to the given Element that can be embedded in a 2D code (e.g. QR code).
* @param AbstractDBElement $target
*
* @return string
*/
public function getURLContent(AbstractDBElement $target): string
@ -69,15 +67,16 @@ final class BarcodeContentGenerator
/**
* Returns a Code that can be used in a 1D barcode.
* The return value has a format of "L0123"
* @param AbstractDBElement $target
* The return value has a format of "L0123".
*
* @return string
*/
public function get1DBarcodeContent(AbstractDBElement $target): string
{
$prefix = $this->classToString(self::PREFIX_MAP, $target);
$id = sprintf('%04d', $target->getID() ?? 0);
return $prefix . $id;
return $prefix.$id;
}
private function classToString(array $map, object $target): string
@ -87,12 +86,12 @@ final class BarcodeContentGenerator
return $map[$class];
}
foreach($map as $class => $string) {
foreach ($map as $class => $string) {
if (is_a($target, $class)) {
return $string;
}
}
throw new \InvalidArgumentException('Unknown object class ' . get_class($target));
throw new \InvalidArgumentException('Unknown object class '.get_class($target));
}
}
}

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).
*
@ -44,39 +47,6 @@ final class BarcodeExampleElementsGenerator
}
}
private function getStorelocation(): Storelocation
{
$storelocation = new Storelocation();
$storelocation->setName('Location 1');
$storelocation->setComment('Example comment');
$storelocation->updatedTimestamps();
$parent = new Storelocation();
$parent->setName('Parent');
$storelocation->setParent($parent);
return $storelocation;
}
private function getStructuralData(string $class): AbstractStructuralDBElement
{
if (!is_a($class, AbstractStructuralDBElement::class, true)) {
throw new \InvalidArgumentException('$class must be an child of AbstractStructuralDBElement');
}
/** @var AbstractStructuralDBElement $parent */
$parent = new $class();
$parent->setName('Example');
/** @var AbstractStructuralDBElement $child */
$child = new $class();
$child->setName((new \ReflectionClass($class))->getShortName());
$child->setParent($parent);
return $child;
}
public function getExamplePart(): Part
{
$part = new Part();
@ -98,7 +68,6 @@ final class BarcodeExampleElementsGenerator
$part->setMinAmount(100);
$part->setNeedsReview(true);
return $part;
}
@ -115,4 +84,37 @@ final class BarcodeExampleElementsGenerator
return $lot;
}
}
private function getStorelocation(): Storelocation
{
$storelocation = new Storelocation();
$storelocation->setName('Location 1');
$storelocation->setComment('Example comment');
$storelocation->updatedTimestamps();
$parent = new Storelocation();
$parent->setName('Parent');
$storelocation->setParent($parent);
return $storelocation;
}
private function getStructuralData(string $class): AbstractStructuralDBElement
{
if (! is_a($class, AbstractStructuralDBElement::class, true)) {
throw new \InvalidArgumentException('$class must be an child of AbstractStructuralDBElement');
}
/** @var AbstractStructuralDBElement $parent */
$parent = new $class();
$parent->setName('Example');
/** @var AbstractStructuralDBElement $child */
$child = new $class();
$child->setName((new \ReflectionClass($class))->getShortName());
$child->setParent($parent);
return $child;
}
}

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).
*
@ -20,7 +23,6 @@
namespace App\Services\LabelSystem\Barcodes;
final class BarcodeNormalizer
{
private const PREFIX_TYPE_MAP = [
@ -31,8 +33,8 @@ final class BarcodeNormalizer
/**
* Parses barcode content and normalizes it.
* Returns an array in the format ['part', 1]: First entry contains element type, second the ID of the element
* @param string $input
* Returns an array in the format ['part', 1]: First entry contains element type, second the ID of the element.
*
* @return array
*/
public function normalizeBarcodeContent(string $input): array
@ -53,9 +55,10 @@ final class BarcodeNormalizer
$prefix = $matches[1];
$id = (int) $matches[2];
if (!isset(self::PREFIX_TYPE_MAP[$prefix])) {
throw new \InvalidArgumentException('Unknown prefix ' . $prefix);
if (! isset(self::PREFIX_TYPE_MAP[$prefix])) {
throw new \InvalidArgumentException('Unknown prefix '.$prefix);
}
return [self::PREFIX_TYPE_MAP[$prefix], $id];
}
@ -64,9 +67,10 @@ final class BarcodeNormalizer
$prefix = $matches[1];
$id = (int) $matches[2];
if (!isset(self::PREFIX_TYPE_MAP[$prefix])) {
throw new \InvalidArgumentException('Unknown prefix ' . $prefix);
if (! isset(self::PREFIX_TYPE_MAP[$prefix])) {
throw new \InvalidArgumentException('Unknown prefix '.$prefix);
}
return [self::PREFIX_TYPE_MAP[$prefix], $id];
}
@ -80,7 +84,6 @@ final class BarcodeNormalizer
return ['part', (int) $matches[1]];
}
throw new \InvalidArgumentException('Unknown barcode format!');
}
}
}

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).
*
@ -20,7 +23,6 @@
namespace App\Services\LabelSystem\Barcodes;
use App\Entity\Parts\PartLot;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityNotFoundException;
@ -31,7 +33,6 @@ final class BarcodeRedirector
private $urlGenerator;
private $em;
public function __construct(UrlGeneratorInterface $urlGenerator, EntityManagerInterface $entityManager)
{
$this->urlGenerator = $urlGenerator;
@ -39,10 +40,13 @@ final class BarcodeRedirector
}
/**
* Determines the URL to which the user should be redirected, when scanning a QR code
* @param string $type The type of the element that was scanned (e.g. 'part', 'lot', etc.)
* @param int $id The ID of the element that was scanned
* Determines the URL to which the user should be redirected, when scanning a QR code.
*
* @param string $type The type of the element that was scanned (e.g. 'part', 'lot', etc.)
* @param int $id The ID of the element that was scanned
*
* @return string The URL to which should be redirected.
*
* @throws EntityNotFoundException
*/
public function getRedirectURL(string $type, int $id): string
@ -53,7 +57,7 @@ final class BarcodeRedirector
case 'lot':
//Try to determine the part to the given lot
$lot = $this->em->find(PartLot::class, $id);
if ($lot === null) {
if (null === $lot) {
throw new EntityNotFoundException();
}
@ -63,7 +67,7 @@ final class BarcodeRedirector
return $this->urlGenerator->generate('part_list_store_location', ['id' => $id]);
default:
throw new \InvalidArgumentException('Unknown $type: ' . $type);
throw new \InvalidArgumentException('Unknown $type: '.$type);
}
}
}
}

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).
*
@ -20,15 +23,11 @@
namespace App\Services\LabelSystem;
use App\Entity\Contracts\NamedElementInterface;
use App\Entity\LabelSystem\LabelOptions;
use App\Entity\Parts\Part;
use App\Entity\Parts\PartLot;
use App\Entity\Parts\Storelocation;
use App\Services\ElementTypeNameGenerator;
use Dompdf\Dompdf;
use Twig\Environment;
final class LabelGenerator
{
@ -48,44 +47,43 @@ final class LabelGenerator
}
/**
* @param LabelOptions $options
* @param object|object[] $elements An element or an array of elements for which labels should be generated
* @param object|object[] $elements An element or an array of elements for which labels should be generated
*
* @return string
*/
public function generateLabel(LabelOptions $options, $elements): string
{
if (!is_array($elements) && !is_object($elements)) {
if (! is_array($elements) && ! is_object($elements)) {
throw new \InvalidArgumentException('$element must be an object or an array of objects!');
}
if (!is_array($elements)) {
if (! is_array($elements)) {
$elements = [$elements];
}
foreach ($elements as $element) {
if (!$this->supports($options, $element)) {
if (! $this->supports($options, $element)) {
throw new \InvalidArgumentException('The given options are not compatible with the given element!');
}
}
$dompdf = new Dompdf();
$dompdf->setPaper($this->mmToPointsArray($options->getWidth(), $options->getHeight()));
$dompdf->loadHtml($this->labelHTMLGenerator->getLabelHTML($options, $elements));
$dompdf->render();
return $dompdf->output();
}
/**
* Check if the given LabelOptions can be used with $element.
* @param LabelOptions $options
* @param object $element
*
* @return bool
*/
public function supports(LabelOptions $options, object $element)
{
$supported_type = $options->getSupportedElement();
if (!isset(static::CLASS_SUPPORT_MAPPING[$supported_type])) {
if (! isset(static::CLASS_SUPPORT_MAPPING[$supported_type])) {
throw new \InvalidArgumentException('Supported type name of the Label options not known!');
}
@ -93,13 +91,15 @@ final class LabelGenerator
}
/**
* Converts width and height given in mm to an size array, that can be used by DOMPDF for page size
* @param float $width The width of the paper
* @param float $height The height of the paper
* Converts width and height given in mm to an size array, that can be used by DOMPDF for page size.
*
* @param float $width The width of the paper
* @param float $height The height of the paper
*
* @return float[]
*/
public function mmToPointsArray(float $width, float $height): array
{
return [0.0, 0.0, $width * self::MM_TO_POINTS_FACTOR, $height * self::MM_TO_POINTS_FACTOR];
}
}
}

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).
*
@ -24,11 +27,9 @@ use App\Entity\Contracts\NamedElementInterface;
use App\Entity\LabelSystem\LabelOptions;
use App\Exceptions\TwigModeException;
use App\Services\ElementTypeNameGenerator;
use App\Services\LabelSystem\Barcodes\BarcodeContentGenerator;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;
use Twig\Error\Error;
use Twig\Error\SyntaxError;
final class LabelHTMLGenerator
{
@ -60,14 +61,14 @@ final class LabelHTMLGenerator
$twig_elements = [];
if ($options->getLinesMode() === 'twig') {
if ('twig' === $options->getLinesMode()) {
$sandboxed_twig = $this->sandboxedTwigProvider->getTwig($options);
$current_user = $this->security->getUser();
}
$page = 1;
foreach ($elements as $element) {
if ($options->getLinesMode() === 'twig' && isset($sandboxed_twig) && isset($current_user)) {
if ('twig' === $options->getLinesMode() && isset($sandboxed_twig) && isset($current_user)) {
try {
$lines = $sandboxed_twig->render(
'lines',
@ -92,10 +93,9 @@ final class LabelHTMLGenerator
'barcode_content' => $this->barcodeGenerator->getContent($options, $element),
];
$page++;
++$page;
}
return $this->twig->render('LabelSystem/labels/base_label.html.twig', [
'meta_title' => $this->getPDFTitle($options, $elements[0]),
'elements' => $twig_elements,
@ -103,8 +103,7 @@ final class LabelHTMLGenerator
]);
}
protected function getPDFTitle(LabelOptions $options, object $element)
private function getPDFTitle(LabelOptions $options, object $element)
{
if ($element instanceof NamedElementInterface) {
return $this->elementTypeNameGenerator->getTypeNameCombination($element, false);
@ -112,4 +111,4 @@ final class LabelHTMLGenerator
return 'Part-DB 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).
*
@ -20,7 +23,6 @@
namespace App\Services\LabelSystem;
use App\Entity\LabelSystem\LabelProfile;
use App\Repository\LabelProfileRepository;
use App\Services\UserCacheKeyGenerator;
@ -44,7 +46,7 @@ final class LabelProfileDropdownHelper
public function getDropdownProfiles(string $type): array
{
$secure_class_name = str_replace('\\', '_', LabelProfile::class);
$key = 'profile_dropdown_'.$this->keyGenerator->generateKey().'_'.$secure_class_name . '_' . $type;
$key = 'profile_dropdown_'.$this->keyGenerator->generateKey().'_'.$secure_class_name.'_'.$type;
/** @var LabelProfileRepository $repo */
$repo = $this->entityManager->getRepository(LabelProfile::class);
@ -56,4 +58,4 @@ final class LabelProfileDropdownHelper
return $repo->getDropdownProfiles($type);
});
}
}
}

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).
*
@ -25,7 +28,6 @@ use App\Services\LabelSystem\PlaceholderProviders\PlaceholderProviderInterface;
/**
* This service replaces the Placeholders of the user provided lines with the proper informations.
* It uses the PlaceholderProviders provided by PlaceholderProviderInterface classes.
* @package App\Services\LabelSystem
*/
final class LabelTextReplacer
{
@ -39,16 +41,18 @@ final class LabelTextReplacer
/**
* Determine the replacement for a single placeholder. It is iterated over all Replacement Providers.
* If the given string is not a placeholder or the placeholder is not known, it will be returned unchanged.
* @param string $placeholder The placeholder that should be replaced. (e.g. '%%PLACEHOLDER%%')
* @param object $target The object that should be used for the placeholder info source.
* @return string If the placeholder was valid, the replaced info. Otherwise the passed string.
*
* @param string $placeholder The placeholder that should be replaced. (e.g. '%%PLACEHOLDER%%')
* @param object $target The object that should be used for the placeholder info source.
*
* @return string If the placeholder was valid, the replaced info. Otherwise the passed string.
*/
public function handlePlaceholder(string $placeholder, object $target): string
{
foreach ($this->providers as $provider) {
/** @var PlaceholderProviderInterface $provider */
$ret = $provider->replace($placeholder, $target);
if ($ret !== null) {
if (null !== $ret) {
return $ret;
}
}
@ -58,8 +62,10 @@ final class LabelTextReplacer
/**
* Replaces all placeholders in the input lines.
* @param string $lines The input lines that should be replaced
* @param object $target The object that should be used as source for the informations.
*
* @param string $lines The input lines that should be replaced
* @param object $target The object that should be used as source for the informations.
*
* @return string The Lines with replaced informations.
*/
public function replace(string $lines, object $target): string
@ -72,4 +78,4 @@ final class LabelTextReplacer
return preg_replace_callback_array($patterns, $lines);
}
}
}

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).
*
@ -20,7 +23,6 @@
namespace App\Services\LabelSystem\PlaceholderProviders;
use App\Entity\Base\AbstractDBElement;
use App\Services\ElementTypeNameGenerator;
@ -33,23 +35,18 @@ final class AbstractDBElementProvider implements PlaceholderProviderInterface
$this->elementTypeNameGenerator = $elementTypeNameGenerator;
}
/**
* @inheritDoc
*/
public function replace(string $placeholder, object $label_target, array $options = []): ?string
{
if ($label_target instanceof AbstractDBElement) {
if ($placeholder === '[[TYPE]]') {
if ('[[TYPE]]' === $placeholder) {
return $this->elementTypeNameGenerator->getLocalizedTypeLabel($label_target);
}
if ($placeholder === '[[ID]]') {
if ('[[ID]]' === $placeholder) {
return (string) ($label_target->getID() ?? 'unknown');
}
}
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).
*
@ -20,7 +23,6 @@
namespace App\Services\LabelSystem\PlaceholderProviders;
use App\Entity\UserSystem\User;
use IntlDateFormatter;
use Locale;
@ -28,11 +30,9 @@ use Symfony\Component\Security\Core\Security;
/**
* Provides Placeholders for infos about global infos like Installation name or datetimes.
* @package App\Services\LabelSystem\PlaceholderProviders
*/
final class GlobalProviders implements PlaceholderProviderInterface
{
private $partdb_title;
private $security;
@ -42,34 +42,32 @@ final class GlobalProviders implements PlaceholderProviderInterface
$this->security = $security;
}
/**
* @inheritDoc
*/
public function replace(string $placeholder, object $label_target, array $options = []): ?string
{
if ($placeholder === "[[INSTALL_NAME]]") {
if ('[[INSTALL_NAME]]' === $placeholder) {
return $this->partdb_title;
}
$user = $this->security->getUser();
if ($placeholder === "[[USERNAME]]") {
if ('[[USERNAME]]' === $placeholder) {
if ($user instanceof User) {
return $user->getName();
}
return 'anonymous';
}
if ($placeholder === "[[USERNAME_FULL]]") {
if ('[[USERNAME_FULL]]' === $placeholder) {
if ($user instanceof User) {
return $user->getFullName(true);
}
return 'anonymous';
}
$now = new \DateTime();
if ($placeholder === '[[DATETIME]]') {
if ('[[DATETIME]]' === $placeholder) {
$formatter = IntlDateFormatter::create(
Locale::getDefault(),
IntlDateFormatter::SHORT,
@ -80,7 +78,7 @@ final class GlobalProviders implements PlaceholderProviderInterface
return $formatter->format($now);
}
if ($placeholder === '[[DATE]]') {
if ('[[DATE]]' === $placeholder) {
$formatter = IntlDateFormatter::create(
Locale::getDefault(),
IntlDateFormatter::SHORT,
@ -91,7 +89,7 @@ final class GlobalProviders implements PlaceholderProviderInterface
return $formatter->format($now);
}
if ($placeholder === '[[TIME]]') {
if ('[[TIME]]' === $placeholder) {
$formatter = IntlDateFormatter::create(
Locale::getDefault(),
IntlDateFormatter::NONE,
@ -104,4 +102,4 @@ final class GlobalProviders implements PlaceholderProviderInterface
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).
*
@ -20,21 +23,16 @@
namespace App\Services\LabelSystem\PlaceholderProviders;
use App\Entity\Contracts\NamedElementInterface;
final class NamedElementProvider implements PlaceholderProviderInterface
{
/**
* @inheritDoc
*/
public function replace(string $placeholder, object $label_target, array $options = []): ?string
{
if ($label_target instanceof NamedElementInterface && $placeholder === '[[NAME]]') {
if ($label_target instanceof NamedElementInterface && '[[NAME]]' === $placeholder) {
return $label_target->getName();
}
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).
*
@ -20,7 +23,6 @@
namespace App\Services\LabelSystem\PlaceholderProviders;
use App\Entity\Parts\PartLot;
use App\Services\AmountFormatter;
use App\Services\LabelSystem\LabelTextReplacer;
@ -41,20 +43,20 @@ final class PartLotProvider implements PlaceholderProviderInterface
public function replace(string $placeholder, object $label_target, array $options = []): ?string
{
if ($label_target instanceof PartLot) {
if ($placeholder === '[[LOT_ID]]') {
if ('[[LOT_ID]]' === $placeholder) {
return $label_target->getID() ?? 'unknown';
}
if ($placeholder === '[[LOT_NAME]]') {
if ('[[LOT_NAME]]' === $placeholder) {
return $label_target->getName();
}
if ($placeholder === '[[LOT_COMMENT]]') {
if ('[[LOT_COMMENT]]' === $placeholder) {
return $label_target->getComment();
}
if ($placeholder === '[[EXPIRATION_DATE]]') {
if ($label_target->getExpirationDate() === null) {
if ('[[EXPIRATION_DATE]]' === $placeholder) {
if (null === $label_target->getExpirationDate()) {
return '';
}
$formatter = IntlDateFormatter::create(
@ -67,25 +69,25 @@ final class PartLotProvider implements PlaceholderProviderInterface
return $formatter->format($label_target->getExpirationDate());
}
if ($placeholder === '[[AMOUNT]]') {
if ('[[AMOUNT]]' === $placeholder) {
if ($label_target->isInstockUnknown()) {
return '?';
}
return $this->amountFormatter->format($label_target->getAmount(), $label_target->getPart()->getPartUnit());
}
if ($placeholder === '[[LOCATION]]') {
if ('[[LOCATION]]' === $placeholder) {
return $label_target->getStorageLocation() ? $label_target->getStorageLocation()->getName() : '';
}
if ($placeholder === '[[LOCATION_FULL]]') {
if ('[[LOCATION_FULL]]' === $placeholder) {
return $label_target->getStorageLocation() ? $label_target->getStorageLocation()->getFullPath() : '';
}
return $this->labelTextReplacer->handlePlaceholder($placeholder, $label_target->getPart());
}
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).
*
@ -20,14 +23,12 @@
namespace App\Services\LabelSystem\PlaceholderProviders;
use App\Entity\Parts\Part;
use App\Services\SIFormatter;
use Symfony\Contracts\Translation\TranslatorInterface;
final class PartProvider implements PlaceholderProviderInterface
{
private $siFormatter;
private $translator;
@ -37,76 +38,74 @@ final class PartProvider implements PlaceholderProviderInterface
$this->translator = $translator;
}
/**
* @inheritDoc
*/
public function replace(string $placeholder, object $part, array $options = []): ?string
{
if (!$part instanceof Part) {
if (! $part instanceof Part) {
return null;
}
if ($placeholder === '[[CATEGORY]]') {
if ('[[CATEGORY]]' === $placeholder) {
return $part->getCategory() ? $part->getCategory()->getName() : '';
}
if ($placeholder === '[[CATEGORY_FULL]]') {
if ('[[CATEGORY_FULL]]' === $placeholder) {
return $part->getCategory() ? $part->getCategory()->getFullPath() : '';
}
if ($placeholder === '[[MANUFACTURER]]') {
if ('[[MANUFACTURER]]' === $placeholder) {
return $part->getManufacturer() ? $part->getManufacturer()->getName() : '';
}
if ($placeholder === '[[MANUFACTURER_FULL]]') {
if ('[[MANUFACTURER_FULL]]' === $placeholder) {
return $part->getManufacturer() ? $part->getManufacturer()->getFullPath() : '';
}
if ($placeholder === '[[FOOTPRINT]]') {
if ('[[FOOTPRINT]]' === $placeholder) {
return $part->getFootprint() ? $part->getFootprint()->getName() : '';
}
if ($placeholder === '[[FOOTPRINT_FULL]]') {
if ('[[FOOTPRINT_FULL]]' === $placeholder) {
return $part->getFootprint() ? $part->getFootprint()->getFullPath() : '';
}
if ($placeholder === '[[MASS]]') {
if ('[[MASS]]' === $placeholder) {
return $part->getMass() ? $this->siFormatter->format($part->getMass(), 'g', 1) : '';
}
if ($placeholder === '[[MPN]]') {
if ('[[MPN]]' === $placeholder) {
return $part->getManufacturerProductNumber();
}
if ($placeholder === '[[TAGS]]') {
if ('[[TAGS]]' === $placeholder) {
return $part->getTags();
}
if ($placeholder === '[[M_STATUS]]') {
if ($part->getManufacturingStatus() === '') {
if ('[[M_STATUS]]' === $placeholder) {
if ('' === $part->getManufacturingStatus()) {
return '';
}
return $this->translator->trans('m_status.' . $part->getManufacturingStatus());
return $this->translator->trans('m_status.'.$part->getManufacturingStatus());
}
$parsedown = new \Parsedown();
if ($placeholder === '[[DESCRIPTION]]') {
if ('[[DESCRIPTION]]' === $placeholder) {
return $parsedown->line($part->getDescription());
}
if ($placeholder === '[[DESCRIPTION_T]]') {
if ('[[DESCRIPTION_T]]' === $placeholder) {
return strip_tags($parsedown->line($part->getDescription()));
}
if ($placeholder === '[[COMMENT]]') {
if ('[[COMMENT]]' === $placeholder) {
return $parsedown->line($part->getComment());
}
if ($placeholder === '[[COMMENT_T]]') {
if ('[[COMMENT_T]]' === $placeholder) {
return strip_tags($parsedown->line($part->getComment()));
}
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).
*
@ -20,17 +23,17 @@
namespace App\Services\LabelSystem\PlaceholderProviders;
interface PlaceholderProviderInterface
{
/**
* Determines the real value of this placeholder.
* If the placeholder is not supported, null must be returned.
* @param string $placeholder The placeholder (e.g. "%%PLACEHOLDER%%") that should be replaced
* @param object $label_target The object that is targeted by the label
* @param array $options A list of options that can be used to specify the generated output further.
*
* @param string $placeholder The placeholder (e.g. "%%PLACEHOLDER%%") that should be replaced
* @param object $label_target The object that is targeted by the label
* @param array $options A list of options that can be used to specify the generated output further.
*
* @return string|null The real value of this placeholder, null if not supported.
*/
public function replace(string $placeholder, object $label_target, array $options = []): ?string;
}
}

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).
*
@ -20,33 +23,30 @@
namespace App\Services\LabelSystem\PlaceholderProviders;
use App\Entity\Base\AbstractDBElement;
use App\Entity\Base\AbstractStructuralDBElement;
final class StructuralDBElementProvider implements PlaceholderProviderInterface
{
public function replace(string $placeholder, object $label_target, array $options = []): ?string
{
if ($label_target instanceof AbstractStructuralDBElement) {
if ($placeholder === '[[COMMENT]]') {
if ('[[COMMENT]]' === $placeholder) {
return $label_target->getComment();
}
if ($placeholder === '[[COMMENT_T]]') {
if ('[[COMMENT_T]]' === $placeholder) {
return strip_tags($label_target->getComment());
}
if ($placeholder === '[[FULL_PATH]]') {
if ('[[FULL_PATH]]' === $placeholder) {
return $label_target->getFullPath();
}
if ($placeholder === '[[PARENT]]') {
if ('[[PARENT]]' === $placeholder) {
return $label_target->getParent() ? $label_target->getParent()->getName() : '';
}
if ($placeholder === '[[PARENT_FULL_PATH]]') {
if ('[[PARENT_FULL_PATH]]' === $placeholder) {
return $label_target->getParent() ? $label_target->getParent()->getFullPath() : '';
}
}
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).
*
@ -26,23 +29,18 @@ use Locale;
final class TimestampableElementProvider implements PlaceholderProviderInterface
{
/**
* @inheritDoc
*/
public function replace(string $placeholder, object $label_target, array $options = []): ?string
{
if ($label_target instanceof TimeStampableInterface) {
if ($placeholder === '[[LAST_MODIFIED]]') {
if ('[[LAST_MODIFIED]]' === $placeholder) {
return IntlDateFormatter::formatObject($label_target->getLastModified() ?? new \DateTime(), IntlDateFormatter::SHORT, Locale::getDefault());
}
if ($placeholder === '[[CREATION_DATE]]') {
if ('[[CREATION_DATE]]' === $placeholder) {
return IntlDateFormatter::formatObject($label_target->getAddedDate() ?? new \DateTime(), IntlDateFormatter::SHORT, Locale::getDefault());
}
}
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).
*
@ -20,12 +23,10 @@
namespace App\Services\LabelSystem;
use App\Entity\Attachments\Attachment;
use App\Entity\Attachments\AttachmentContainingDBElement;
use App\Entity\Base\AbstractCompany;
use App\Entity\Base\AbstractDBElement;
use App\Entity\Base\AbstractNamedDBElement;
use App\Entity\Base\AbstractStructuralDBElement;
use App\Entity\Contracts\NamedElementInterface;
use App\Entity\Contracts\TimeStampableInterface;
@ -45,7 +46,6 @@ use App\Twig\Sandbox\InheritanceSecurityPolicy;
use Twig\Environment;
use Twig\Extension\SandboxExtension;
use Twig\Extra\Intl\IntlExtension;
use Twig\Sandbox\SecurityPolicy;
use Twig\Sandbox\SecurityPolicyInterface;
final class SandboxedTwigProvider
@ -58,7 +58,7 @@ final class SandboxedTwigProvider
'reduce', 'replace', 'reverse', 'slice', 'sort', 'spaceless', 'split', 'striptags', 'timezone_name', 'title',
'trim', 'upper', 'url_encode',
//Part-DB specific filters:
'moneyFormat', 'siFormat', 'amountFormat'];
'moneyFormat', 'siFormat', 'amountFormat', ];
private const ALLOWED_FUNCTIONS = ['date', 'html_classes', 'max', 'min', 'random', 'range'];
@ -67,31 +67,30 @@ final class SandboxedTwigProvider
AbstractDBElement::class => ['getID', '__toString'],
TimeStampableInterface::class => ['getLastModified', 'getAddedDate'],
AbstractStructuralDBElement::class => ['isChildOf', 'isRoot', 'getParent', 'getComment', 'getLevel',
'getFullPath', 'getPathArray', 'getChildren', 'isNotSelectable'],
'getFullPath', 'getPathArray', 'getChildren', 'isNotSelectable', ],
AbstractCompany::class => ['getAddress', 'getPhoneNumber', 'getFaxNumber', 'getEmailAddress', 'getWebsite'],
AttachmentContainingDBElement::class => ['getAttachments', 'getMasterPictureAttachment'],
Attachment::class => ['isPicture', 'is3DModel', 'isExternal', 'isSecure', 'isBuiltIn', 'getExtension',
'getElement', 'getURL', 'getFilename', 'getAttachmentType', 'getShowInTable'],
'getElement', 'getURL', 'getFilename', 'getAttachmentType', 'getShowInTable', ],
AbstractParameter::class => ['getFormattedValue', 'getGroup', 'getSymbol', 'getValueMin', 'getValueMax',
'getValueTypical', 'getUnit', 'getValueText'],
'getValueTypical', 'getUnit', 'getValueText', ],
MeasurementUnit::class => ['getUnit', 'isInteger', 'useSIPrefix'],
PartLot::class => ['isExpired', 'getDescription', 'getComment', 'getExpirationDate', 'getStorageLocation',
'getPart', 'isInstockUnknown', 'getAmount', 'getNeedsRefill'],
'getPart', 'isInstockUnknown', 'getAmount', 'getNeedsRefill', ],
Storelocation::class => ['isFull', 'isOnlySinglePart', 'isLimitToExistingParts', 'getStorageType'],
Supplier::class => ['getShippingCosts', 'getDefaultCurrency'],
Part::class => ['isNeedsReview', 'getTags', 'getMass', 'getDescription', 'isFavorite', 'getCategory',
'getFootprint', 'getPartLots', 'getPartUnit', 'useFloatAmount', 'getMinAmount', 'getAmountSum',
'getManufacturerProductUrl', 'getCustomProductURL', 'getManufacturingStatus', 'getManufacturer',
'getManufacturerProductNumber', 'getOrderdetails', 'isObsolete'],
'getManufacturerProductNumber', 'getOrderdetails', 'isObsolete', ],
Currency::class => ['getIsoCode', 'getInverseExchangeRate', 'getExchangeRate'],
Orderdetail::class => ['getPart', 'getSupplier', 'getSupplierPartNr', 'getObsolete',
'getPricedetails', 'findPriceForQty', ],
Pricedetail::class => ['getOrderdetail', 'getPrice', 'getPricePerUnit', 'getPriceRelatedQuantity',
'getMinDiscountQuantity', 'getCurrency'],
'getMinDiscountQuantity', 'getCurrency', ],
//Only allow very little information about users...
User::class => ['isAnonymousUser', 'getUsername', 'getFullName', 'getFirstName', 'getLastName',
'getDepartment', 'getEmail']
'getDepartment', 'getEmail', ],
];
private const ALLOWED_PROPERTIES = [];
@ -104,14 +103,13 @@ final class SandboxedTwigProvider
public function getTwig(LabelOptions $options): Environment
{
if ($options->getLinesMode() !== 'twig') {
if ('twig' !== $options->getLinesMode()) {
throw new \InvalidArgumentException('The LabelOptions must explicitly allow twig via lines_mode = "twig"!');
}
$loader = new \Twig\Loader\ArrayLoader([
'lines' => $options->getLines(),
]);
'lines' => $options->getLines(),
]);
$twig = new Environment($loader);
//Second argument activate sandbox globally.
@ -127,7 +125,7 @@ final class SandboxedTwigProvider
return $twig;
}
protected function getSecurityPolicy(): SecurityPolicyInterface
private function getSecurityPolicy(): SecurityPolicyInterface
{
return new InheritanceSecurityPolicy(
self::ALLOWED_TAGS,
@ -137,4 +135,4 @@ final class SandboxedTwigProvider
self::ALLOWED_FUNCTIONS
);
}
}
}

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).
*
@ -21,13 +24,15 @@
namespace App\Services\Misc;
/**
* This Parser allows to parse number ranges like 1-3, 4, 5
* This Parser allows to parse number ranges like 1-3, 4, 5.
*/
class RangeParser
{
/**
* Converts the given range string to an array of all numbers in the given range.
* @param string $range_str A range string like '1-3, 5, 6'
*
* @param string $range_str A range string like '1-3, 5, 6'
*
* @return int[] An array with all numbers from the range (e.g. [1, 2, 3, 5, 6]
*/
public function parse(string $range_str): array
@ -48,7 +53,7 @@ class RangeParser
} elseif (empty($number)) { //Allow empty tokens
continue;
} else {
throw new \InvalidArgumentException('Invalid range encoutered: ' . $number);
throw new \InvalidArgumentException('Invalid range encoutered: '.$number);
}
}
@ -58,13 +63,16 @@ class RangeParser
/**
* Checks if the given string is a valid range.
* @param string $range_str The string that should be checked
*
* @param string $range_str The string that should be checked
*
* @return bool True if the string is valid, false if not.
*/
public function isValidRange(string $range_str): bool
{
try {
$this->parse($range_str);
return true;
} catch (\InvalidArgumentException $exception) {
return false;
@ -86,9 +94,9 @@ class RangeParser
$tmp = [];
while ($min <= $max) {
$tmp[] = $min;
$min++;
};
++$min;
}
return $tmp;
}
}
}

View file

@ -105,6 +105,7 @@ class SIFormatter
* @param float $value The value that should be converted
* @param string $unit The unit that should be appended after the prefix
* @param int $decimals the number of decimals (after decimal dot) that should be outputed
*
* @return string The formatted value
*/
public function format(float $value, string $unit = '', int $decimals = 2): string

View file

@ -211,7 +211,6 @@ class ToolsTreeBuilder
);
}
return $nodes;
}

View file

@ -118,13 +118,13 @@ class TreeViewGenerator
$item->addTag((string) \count($item->getNodes()));
}
if (! empty($href_type) && $item->getId() !== null) {
if (! empty($href_type) && null !== $item->getId()) {
$entity = $this->em->getPartialReference($class, $item->getId());
$item->setHref($this->urlGenerator->getURL($entity, $href_type));
}
//Translate text if text starts with $$
if (substr($item->getText(), 0, 2) === '$$') {
if ('$$' === substr($item->getText(), 0, 2)) {
$item->setText($this->translator->trans(substr($item->getText(), 2)));
}
}