From 388e847b17e6241e28fc921cf405f624d7a2dfb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20B=C3=B6hmer?= Date: Sun, 5 Jan 2020 22:49:00 +0100 Subject: [PATCH] Applied symplify rules to codebase. --- ecs.yaml | 8 +- src/Command/CleanAttachmentsCommand.php | 13 +- src/Command/ConvertBBCodeCommand.php | 11 +- src/Command/UpdateExchangeRatesCommand.php | 11 +- .../PermissionsConfiguration.php | 4 +- .../AdminPages/AttachmentTypeController.php | 3 +- .../AdminPages/BaseAdminController.php | 21 +- .../AdminPages/CategoryController.php | 3 +- .../AdminPages/CurrencyController.php | 3 +- .../AdminPages/DeviceController.php | 3 +- src/Controller/AttachmentFileController.php | 16 +- src/Controller/GroupController.php | 3 +- src/Controller/HomepageController.php | 3 +- src/Controller/PartController.php | 20 +- src/Controller/PartListsController.php | 16 +- src/Controller/RedirectController.php | 9 +- src/Controller/SecurityController.php | 16 +- src/Controller/UserController.php | 3 +- src/Controller/UserSettingsController.php | 53 ++-- src/DataFixtures/DataStructureFixtures.php | 3 +- src/DataFixtures/GroupFixtures.php | 129 ++++++++-- src/DataTables/Adapter/CustomORMAdapter.php | 5 +- src/DataTables/AttachmentDataTable.php | 2 +- .../Column/LocaleDateTimeColumn.php | 9 +- .../Column/PartAttachmentsColumn.php | 3 +- src/DataTables/PartsDataTable.php | 10 +- src/Entity/Attachments/Attachment.php | 39 +-- .../AttachmentContainingDBElement.php | 2 +- src/Entity/Attachments/AttachmentType.php | 23 +- src/Entity/Base/Company.php | 3 +- src/Entity/Base/StructuralDBElement.php | 49 ++-- src/Entity/Base/TimestampTrait.php | 17 +- src/Entity/Devices/Device.php | 20 +- src/Entity/Devices/DevicePart.php | 23 +- src/Entity/Parts/Category.php | 11 +- src/Entity/Parts/Footprint.php | 17 +- src/Entity/Parts/Manufacturer.php | 17 +- src/Entity/Parts/MeasurementUnit.php | 11 +- src/Entity/Parts/Part.php | 21 +- src/Entity/Parts/PartLot.php | 34 +-- src/Entity/Parts/PartTraits/OrderTrait.php | 3 +- src/Entity/Parts/Storelocation.php | 39 ++- src/Entity/Parts/Supplier.php | 11 +- src/Entity/PriceInformations/Currency.php | 22 +- src/Entity/PriceInformations/Orderdetail.php | 30 +-- src/Entity/PriceInformations/Pricedetail.php | 17 +- src/Entity/UserSystem/Group.php | 23 +- src/Entity/UserSystem/PermissionsEmbed.php | 15 +- src/Entity/UserSystem/U2FKey.php | 14 +- src/Entity/UserSystem/User.php | 238 +++++++++--------- .../AttachmentDeleteListener.php | 3 +- .../TreeCacheInvalidationListener.php | 3 +- src/EventSubscriber/LoginSuccessListener.php | 2 +- .../LogoutOnDisabledUserListener.php | 2 +- src/EventSubscriber/MailFromListener.php | 2 +- .../PasswordChangeNeededSubscriber.php | 6 +- .../SymfonyDebugToolbarSubscriber.php | 2 +- src/EventSubscriber/TimezoneListener.php | 2 +- .../U2FRegistrationSubscriber.php | 10 +- .../AttachmentDownloadException.php | 4 +- .../EntityNotSupportedException.php | 4 +- .../AdminPages/AttachmentTypeAdminForm.php | 10 +- src/Form/AdminPages/BaseEntityAdminForm.php | 56 +++-- src/Form/AdminPages/CategoryAdminForm.php | 84 +++++-- src/Form/AdminPages/CompanyForm.php | 28 ++- src/Form/AdminPages/CurrencyAdminForm.php | 11 +- src/Form/AdminPages/GroupAdminForm.php | 7 +- src/Form/AdminPages/ImportType.php | 47 +++- src/Form/AdminPages/MassCreationForm.php | 9 +- .../AdminPages/MeasurementUnitAdminForm.php | 30 ++- .../AdminPages/StorelocationAdminForm.php | 27 +- src/Form/AdminPages/SupplierForm.php | 3 +- src/Form/AttachmentFormType.php | 46 +++- src/Form/Part/OrderdetailType.php | 11 +- src/Form/Part/PartBaseType.php | 35 ++- src/Form/Part/PartLotType.php | 46 +++- src/Form/Part/PricedetailType.php | 13 +- src/Form/Permissions/PermissionsMapper.php | 16 +- src/Form/TFAGoogleSettingsType.php | 11 +- src/Form/Type/MasterPictureAttachmentType.php | 7 +- src/Form/Type/SIUnitType.php | 25 +- src/Form/Type/StructuralEntityType.php | 15 +- src/Form/Type/TriStateCheckboxType.php | 15 +- src/Form/UserAdminForm.php | 61 +++-- src/Form/UserSettingsType.php | 14 +- .../Trees/StructuralDBElementIterator.php | 4 +- src/Helpers/Trees/TreeViewNode.php | 4 +- src/Helpers/Trees/TreeViewNodeIterator.php | 5 +- src/Helpers/Trees/TreeViewNodeState.php | 20 +- src/Helpers/UTCDateTimeType.php | 12 +- src/Migrations/Version1.php | 2 +- src/Migrations/Version20190902140506.php | 2 +- .../StructuralDBElementRepository.php | 3 +- src/Repository/UserRepository.php | 9 +- src/Security/Annotations/ColumnSecurity.php | 6 +- .../ElementPermissionListener.php | 13 +- src/Security/UserChecker.php | 2 +- src/Security/Voter/AttachmentVoter.php | 3 +- src/Security/Voter/ExtendedVoter.php | 3 +- src/Security/Voter/PermissionVoter.php | 2 +- src/Security/Voter/StructureVoter.php | 6 +- src/Security/Voter/UserVoter.php | 3 +- src/Services/AmountFormatter.php | 9 +- .../Attachments/AttachmentManager.php | 14 +- .../Attachments/AttachmentPathResolver.php | 7 +- .../Attachments/AttachmentReverseSearch.php | 18 +- .../Attachments/AttachmentSubmitHandler.php | 46 ++-- .../Attachments/AttachmentURLGenerator.php | 11 +- .../Attachments/BuiltinAttachmentsFinder.php | 3 +- .../Attachments/FileTypeFilterTools.php | 13 +- src/Services/CustomEnvVarProcessor.php | 7 +- src/Services/ElementTypeNameGenerator.php | 7 +- src/Services/EntityExporter.php | 25 +- src/Services/EntityImporter.php | 23 +- src/Services/EntityURLGenerator.php | 17 +- src/Services/FAIconGenerator.php | 6 +- src/Services/MoneyFormatter.php | 3 +- .../PermissionExtractor.php | 2 +- src/Twig/AppExtension.php | 5 +- .../Constraints/NoneOfItsChildren.php | 8 +- src/Validator/Constraints/UrlOrBuiltin.php | 4 +- tests/Entity/Attachments/AttachmentTest.php | 3 +- tests/Entity/Parts/PartLotTest.php | 3 +- tests/Entity/Parts/PartTest.php | 3 +- tests/Entity/StructuralDBElementTest.php | 3 +- .../UserSystem/PermissionsEmbedTest.php | 14 +- tests/Entity/UserSystem/UserTest.php | 3 +- .../NamedDBElementRepositoryTest.php | 4 +- .../StructuralDBElementRepositoryTest.php | 4 +- tests/Services/AmountFormatterTest.php | 13 +- .../AttachmentPathResolverTest.php | 9 +- .../BuiltinAttachmentsFinderTest.php | 7 +- tests/Services/PermissionResolverTest.php | 11 +- .../Services/TFA/BackupCodeGeneratorTest.php | 5 +- tests/Services/Trees/NodesListBuilderTest.php | 2 +- .../Services/Trees/TreeViewGeneratorTest.php | 2 +- 136 files changed, 1370 insertions(+), 789 deletions(-) diff --git a/ecs.yaml b/ecs.yaml index 28ea9362..78da12eb 100644 --- a/ecs.yaml +++ b/ecs.yaml @@ -6,5 +6,9 @@ parameters: - "clean-code" - "common" # very nice to have ↓ - #- "symplify" - - "symfony" \ No newline at end of file + - "symplify" + - "symfony" + + skip: + Symplify\CodingStandard\Fixer\Naming\PropertyNameMatchingTypeFixer: ~ + Symplify\CodingStandard\Fixer\LineLength\LineLengthFixer: ~ \ No newline at end of file diff --git a/src/Command/CleanAttachmentsCommand.php b/src/Command/CleanAttachmentsCommand.php index 0f4f6128..80f2957c 100644 --- a/src/Command/CleanAttachmentsCommand.php +++ b/src/Command/CleanAttachmentsCommand.php @@ -27,6 +27,9 @@ namespace App\Command; use App\Services\Attachments\AttachmentManager; use App\Services\Attachments\AttachmentPathResolver; use App\Services\Attachments\AttachmentReverseSearch; +use function count; +use const DIRECTORY_SEPARATOR; +use IntlDateFormatter; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; @@ -83,11 +86,11 @@ class CleanAttachmentsCommand extends Command $table = new Table($output); $table->setHeaders(['Filename', 'MIME Type', 'Last modified date']); - $dateformatter = \IntlDateFormatter::create(null, \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT); + $dateformatter = IntlDateFormatter::create(null, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT); foreach ($finder as $file) { //If not attachment object uses this file, print it - if (0 === \count($this->reverseSearch->findAttachmentsByFile($file))) { + if (0 === count($this->reverseSearch->findAttachmentsByFile($file))) { $file_list[] = $file; $table->addRow([ $fs->makePathRelative($file->getPathname(), $mediaPath), @@ -97,10 +100,10 @@ class CleanAttachmentsCommand extends Command } } - if (\count($file_list) > 0) { + if (count($file_list) > 0) { $table->render(); - $continue = $io->confirm(sprintf('Found %d abandoned files. Do you want to delete them? This can not be undone!', \count($file_list)), false); + $continue = $io->confirm(sprintf('Found %d abandoned files. Do you want to delete them? This can not be undone!', count($file_list)), false); if (! $continue) { //We are finished here, when no files should be deleted @@ -128,7 +131,7 @@ class CleanAttachmentsCommand extends Command protected function removeEmptySubFolders($path) { $empty = true; - foreach (glob($path.\DIRECTORY_SEPARATOR.'*') as $file) { + foreach (glob($path.DIRECTORY_SEPARATOR.'*') as $file) { $empty &= is_dir($file) && $this->removeEmptySubFolders($file); } diff --git a/src/Command/ConvertBBCodeCommand.php b/src/Command/ConvertBBCodeCommand.php index cdb7c072..6a93f3fa 100644 --- a/src/Command/ConvertBBCodeCommand.php +++ b/src/Command/ConvertBBCodeCommand.php @@ -36,6 +36,7 @@ use App\Entity\Parts\Supplier; use App\Entity\PriceInformations\Currency; use App\Entity\UserSystem\Group; use App\Helpers\BBCodeToMarkdownConverter; +use function count; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityRepository; use Symfony\Component\Console\Command\Command; @@ -49,9 +50,13 @@ use Symfony\Component\PropertyAccess\PropertyAccessorInterface; */ class ConvertBBCodeCommand extends Command { - /** @var string The LIKE criteria used to detect on SQL server if a entry contains BBCode */ + /** + * @var string The LIKE criteria used to detect on SQL server if a entry contains BBCode + */ protected const BBCODE_CRITERIA = '%[%]%[/%]%'; - /** @var string The regex (performed in PHP) used to check if a property really contains BBCODE */ + /** + * @var string The regex (performed in PHP) used to check if a property really contains BBCODE + */ protected const BBCODE_REGEX = '/\\[.+\\].*\\[\\/.+\\]/'; protected static $defaultName = 'app:convert-bbcode'; @@ -125,7 +130,7 @@ class ConvertBBCodeCommand extends Command //Fetch resulting classes $results = $qb->getQuery()->getResult(); - $io->note(sprintf('Found %d entities, that need to be converted!', \count($results))); + $io->note(sprintf('Found %d entities, that need to be converted!', count($results))); //In verbose mode print the names of the entities foreach ($results as $result) { diff --git a/src/Command/UpdateExchangeRatesCommand.php b/src/Command/UpdateExchangeRatesCommand.php index 721bbecc..4db05244 100644 --- a/src/Command/UpdateExchangeRatesCommand.php +++ b/src/Command/UpdateExchangeRatesCommand.php @@ -25,7 +25,10 @@ declare(strict_types=1); namespace App\Command; use App\Entity\PriceInformations\Currency; +use function count; use Doctrine\ORM\EntityManagerInterface; +use Exchanger\Exception\Exception; +use function strlen; use Swap\Builder; use Swap\Swap; use Symfony\Component\Console\Command\Command; @@ -70,7 +73,7 @@ class UpdateExchangeRatesCommand extends Command $io = new SymfonyStyle($input, $output); //Check for valid base current - if (3 !== \strlen($this->base_current)) { + if (3 !== strlen($this->base_current)) { $io->error('Choosen Base current is not valid. Check your settings!'); return; @@ -108,15 +111,15 @@ class UpdateExchangeRatesCommand extends Command $this->em->persist($currency); ++$success_counter; - } catch (\Exchanger\Exception\Exception $ex) { + } catch (Exception $exception) { $io->warning(sprintf('Error updating %s:', $currency->getIsoCode())); - $io->warning($ex->getMessage()); + $io->warning($exception->getMessage()); } } //Save to database $this->em->flush(); - $io->success(sprintf('%d (of %d) currency exchange rates were updated.', $success_counter, \count($candidates))); + $io->success(sprintf('%d (of %d) currency exchange rates were updated.', $success_counter, count($candidates))); } } diff --git a/src/Configuration/PermissionsConfiguration.php b/src/Configuration/PermissionsConfiguration.php index 99269353..edf84579 100644 --- a/src/Configuration/PermissionsConfiguration.php +++ b/src/Configuration/PermissionsConfiguration.php @@ -27,12 +27,12 @@ namespace App\Configuration; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; -class PermissionsConfiguration implements ConfigurationInterface +final class PermissionsConfiguration implements ConfigurationInterface { /** * Generates the configuration tree builder. * - * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder + * @return TreeBuilder The tree builder */ public function getConfigTreeBuilder() { diff --git a/src/Controller/AdminPages/AttachmentTypeController.php b/src/Controller/AdminPages/AttachmentTypeController.php index aa00a8a4..949bd89a 100644 --- a/src/Controller/AdminPages/AttachmentTypeController.php +++ b/src/Controller/AdminPages/AttachmentTypeController.php @@ -31,6 +31,7 @@ use App\Services\EntityExporter; use App\Services\EntityImporter; use App\Services\StructuralElementRecursionHelper; use Doctrine\ORM\EntityManagerInterface; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; @@ -49,7 +50,7 @@ class AttachmentTypeController extends BaseAdminController /** * @Route("/{id}", name="attachment_type_delete", methods={"DELETE"}) * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function delete(Request $request, AttachmentType $entity, StructuralElementRecursionHelper $recursionHelper) { diff --git a/src/Controller/AdminPages/BaseAdminController.php b/src/Controller/AdminPages/BaseAdminController.php index 6e4177cb..b5f5ed31 100644 --- a/src/Controller/AdminPages/BaseAdminController.php +++ b/src/Controller/AdminPages/BaseAdminController.php @@ -36,6 +36,7 @@ use App\Services\EntityExporter; use App\Services\EntityImporter; use App\Services\StructuralElementRecursionHelper; use Doctrine\ORM\EntityManagerInterface; +use InvalidArgumentException; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\File\UploadedFile; @@ -61,11 +62,11 @@ abstract class BaseAdminController extends AbstractController AttachmentManager $attachmentHelper, AttachmentSubmitHandler $attachmentSubmitHandler) { if ('' === $this->entity_class || '' === $this->form_class || '' === $this->twig_template || '' === $this->route_base) { - throw new \InvalidArgumentException('You have to override the $entity_class, $form_class, $route_base and $twig_template value in your subclasss!'); + throw new InvalidArgumentException('You have to override the $entity_class, $form_class, $route_base and $twig_template value in your subclasss!'); } if ('' === $this->attachment_class) { - throw new \InvalidArgumentException('You have to override the $attachment_class value in your subclass!'); + throw new InvalidArgumentException('You have to override the $attachment_class value in your subclass!'); } $this->translator = $translator; @@ -101,10 +102,10 @@ abstract class BaseAdminController extends AbstractController try { $this->attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); - } catch (AttachmentDownloadException $ex) { + } catch (AttachmentDownloadException $attachmentDownloadException) { $this->addFlash( 'error', - $this->translator->trans('attachment.download_failed').' '.$ex->getMessage() + $this->translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage() ); } } @@ -158,10 +159,10 @@ abstract class BaseAdminController extends AbstractController try { $this->attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); - } catch (AttachmentDownloadException $ex) { + } catch (AttachmentDownloadException $attachmentDownloadException) { $this->addFlash( 'error', - $this->translator->trans('attachment.download_failed').' '.$ex->getMessage() + $this->translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage() ); } } @@ -186,8 +187,12 @@ abstract class BaseAdminController extends AbstractController $file = $import_form['file']->getData(); $data = $import_form->getData(); - $options = ['parent' => $data['parent'], 'preserve_children' => $data['preserve_children'], - 'format' => $data['format'], 'csv_separator' => $data['csv_separator'], ]; + $options = [ + 'parent' => $data['parent'], + 'preserve_children' => $data['preserve_children'], + 'format' => $data['format'], + 'csv_separator' => $data['csv_separator'], + ]; $errors = $importer->fileToDBEntities($file, $this->entity_class, $options); diff --git a/src/Controller/AdminPages/CategoryController.php b/src/Controller/AdminPages/CategoryController.php index 04fe4e86..4582a6eb 100644 --- a/src/Controller/AdminPages/CategoryController.php +++ b/src/Controller/AdminPages/CategoryController.php @@ -31,6 +31,7 @@ use App\Services\EntityExporter; use App\Services\EntityImporter; use App\Services\StructuralElementRecursionHelper; use Doctrine\ORM\EntityManagerInterface; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; @@ -49,7 +50,7 @@ class CategoryController extends BaseAdminController /** * @Route("/{id}", name="category_delete", methods={"DELETE"}) * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function delete(Request $request, Category $entity, StructuralElementRecursionHelper $recursionHelper) { diff --git a/src/Controller/AdminPages/CurrencyController.php b/src/Controller/AdminPages/CurrencyController.php index b365cc5f..42d61cf8 100644 --- a/src/Controller/AdminPages/CurrencyController.php +++ b/src/Controller/AdminPages/CurrencyController.php @@ -31,6 +31,7 @@ use App\Services\EntityExporter; use App\Services\EntityImporter; use App\Services\StructuralElementRecursionHelper; use Doctrine\ORM\EntityManagerInterface; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; @@ -51,7 +52,7 @@ class CurrencyController extends BaseAdminController /** * @Route("/{id}", name="currency_delete", methods={"DELETE"}) * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function delete(Request $request, Currency $entity, StructuralElementRecursionHelper $recursionHelper) { diff --git a/src/Controller/AdminPages/DeviceController.php b/src/Controller/AdminPages/DeviceController.php index 5b66265c..5afcad08 100644 --- a/src/Controller/AdminPages/DeviceController.php +++ b/src/Controller/AdminPages/DeviceController.php @@ -31,6 +31,7 @@ use App\Services\EntityExporter; use App\Services\EntityImporter; use App\Services\StructuralElementRecursionHelper; use Doctrine\ORM\EntityManagerInterface; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; @@ -49,7 +50,7 @@ class DeviceController extends BaseAdminController /** * @Route("/{id}", name="device_delete", methods={"DELETE"}) * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function delete(Request $request, Device $entity, StructuralElementRecursionHelper $recursionHelper) { diff --git a/src/Controller/AttachmentFileController.php b/src/Controller/AttachmentFileController.php index 93d5898f..6ed81cd7 100644 --- a/src/Controller/AttachmentFileController.php +++ b/src/Controller/AttachmentFileController.php @@ -28,10 +28,14 @@ use App\DataTables\AttachmentDataTable; use App\Entity\Attachments\Attachment; use App\Entity\Attachments\PartAttachment; use App\Services\Attachments\AttachmentManager; +use Exception; use Omines\DataTablesBundle\DataTableFactory; +use RuntimeException; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\BinaryFileResponse; +use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\Routing\Annotation\Route; @@ -49,11 +53,11 @@ class AttachmentFileController extends AbstractController $this->denyAccessUnlessGranted('read', $attachment); if ($attachment->isExternal()) { - throw new \RuntimeException('You can not download external attachments!'); + throw new RuntimeException('You can not download external attachments!'); } if (! $helper->isFileExisting($attachment)) { - throw new \RuntimeException('The file associated with the attachment is not existing!'); + throw new RuntimeException('The file associated with the attachment is not existing!'); } $file_path = $helper->toAbsoluteFilePath($attachment); @@ -72,18 +76,18 @@ class AttachmentFileController extends AbstractController * * @return BinaryFileResponse * - * @throws \Exception + * @throws Exception */ public function view(Attachment $attachment, AttachmentManager $helper) { $this->denyAccessUnlessGranted('read', $attachment); if ($attachment->isExternal()) { - throw new \RuntimeException('You can not download external attachments!'); + throw new RuntimeException('You can not download external attachments!'); } if (! $helper->isFileExisting($attachment)) { - throw new \RuntimeException('The file associated with the attachment is not existing!'); + throw new RuntimeException('The file associated with the attachment is not existing!'); } $file_path = $helper->toAbsoluteFilePath($attachment); @@ -98,7 +102,7 @@ class AttachmentFileController extends AbstractController /** * @Route("/attachment/list", name="attachment_list") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function attachmentsTable(DataTableFactory $dataTable, Request $request) { diff --git a/src/Controller/GroupController.php b/src/Controller/GroupController.php index a998ea78..1215d273 100644 --- a/src/Controller/GroupController.php +++ b/src/Controller/GroupController.php @@ -32,6 +32,7 @@ use App\Services\EntityExporter; use App\Services\EntityImporter; use App\Services\StructuralElementRecursionHelper; use Doctrine\ORM\EntityManagerInterface; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; @@ -72,7 +73,7 @@ class GroupController extends BaseAdminController /** * @Route("/{id}", name="group_delete", methods={"DELETE"}) * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function delete(Request $request, Group $entity, StructuralElementRecursionHelper $recursionHelper) { diff --git a/src/Controller/HomepageController.php b/src/Controller/HomepageController.php index ab71d316..96b2a34f 100644 --- a/src/Controller/HomepageController.php +++ b/src/Controller/HomepageController.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace App\Controller; use App\Services\GitVersionInfo; +use const DIRECTORY_SEPARATOR; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Routing\Annotation\Route; @@ -46,7 +47,7 @@ class HomepageController extends AbstractController $banner = $this->getParameter('banner'); if (empty($banner)) { $banner_path = $this->kernel->getProjectDir() - .\DIRECTORY_SEPARATOR.'config'.\DIRECTORY_SEPARATOR.'banner.md'; + .DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'banner.md'; return file_get_contents($banner_path); } diff --git a/src/Controller/PartController.php b/src/Controller/PartController.php index 95d3353a..26585075 100644 --- a/src/Controller/PartController.php +++ b/src/Controller/PartController.php @@ -35,7 +35,9 @@ use App\Services\PricedetailHelper; use Doctrine\ORM\EntityManagerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\FormInterface; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Contracts\Translation\TranslatorInterface; @@ -48,7 +50,7 @@ class PartController extends AbstractController * @Route("/{id}/info", name="part_info") * @Route("/{id}", requirements={"id"="\d+"}) * - * @return \Symfony\Component\HttpFoundation\Response + * @return Response */ public function show(Part $part, AttachmentManager $attachmentHelper, PricedetailHelper $pricedetailHelper, PartPreviewGenerator $previewGenerator) { @@ -68,7 +70,7 @@ class PartController extends AbstractController /** * @Route("/{id}/edit", name="part_edit") * - * @return \Symfony\Component\HttpFoundation\Response + * @return Response */ public function edit(Part $part, Request $request, EntityManagerInterface $em, TranslatorInterface $translator, AttachmentManager $attachmentHelper, AttachmentSubmitHandler $attachmentSubmitHandler) @@ -90,10 +92,10 @@ class PartController extends AbstractController try { $attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); - } catch (AttachmentDownloadException $ex) { + } catch (AttachmentDownloadException $attachmentDownloadException) { $this->addFlash( 'error', - $translator->trans('attachment.download_failed').' '.$ex->getMessage() + $translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage() ); } } @@ -118,7 +120,7 @@ class PartController extends AbstractController /** * @Route("/{id}/delete", name="part_delete", methods={"DELETE"}) * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function delete(Request $request, Part $part) { @@ -142,7 +144,7 @@ class PartController extends AbstractController /** * @Route("/new", name="part_new") * - * @return \Symfony\Component\HttpFoundation\Response + * @return Response */ public function new(Request $request, EntityManagerInterface $em, TranslatorInterface $translator, AttachmentManager $attachmentHelper, AttachmentSubmitHandler $attachmentSubmitHandler) @@ -174,10 +176,10 @@ class PartController extends AbstractController try { $attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); - } catch (AttachmentDownloadException $ex) { + } catch (AttachmentDownloadException $attachmentDownloadException) { $this->addFlash( 'error', - $translator->trans('attachment.download_failed').' '.$ex->getMessage() + $translator->trans('attachment.download_failed').' '.$attachmentDownloadException->getMessage() ); } } @@ -204,7 +206,7 @@ class PartController extends AbstractController /** * @Route("/{id}/clone", name="part_clone") * - * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response + * @return RedirectResponse|Response */ public function clone(Part $part, Request $request, EntityManagerInterface $em, TranslatorInterface $translator) { diff --git a/src/Controller/PartListsController.php b/src/Controller/PartListsController.php index 695843de..bdf3c9fc 100644 --- a/src/Controller/PartListsController.php +++ b/src/Controller/PartListsController.php @@ -32,7 +32,9 @@ use App\Entity\Parts\Storelocation; use App\Entity\Parts\Supplier; use Omines\DataTablesBundle\DataTableFactory; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class PartListsController extends AbstractController @@ -40,7 +42,7 @@ class PartListsController extends AbstractController /** * @Route("/category/{id}/parts", name="part_list_category") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function showCategory(Category $category, Request $request, DataTableFactory $dataTable) { @@ -60,7 +62,7 @@ class PartListsController extends AbstractController /** * @Route("/footprint/{id}/parts", name="part_list_footprint") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function showFootprint(Footprint $footprint, Request $request, DataTableFactory $dataTable) { @@ -80,7 +82,7 @@ class PartListsController extends AbstractController /** * @Route("/manufacturer/{id}/parts", name="part_list_manufacturer") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function showManufacturer(Manufacturer $manufacturer, Request $request, DataTableFactory $dataTable) { @@ -100,7 +102,7 @@ class PartListsController extends AbstractController /** * @Route("/store_location/{id}/parts", name="part_list_store_location") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function showStorelocation(Storelocation $storelocation, Request $request, DataTableFactory $dataTable) { @@ -120,7 +122,7 @@ class PartListsController extends AbstractController /** * @Route("/supplier/{id}/parts", name="part_list_supplier") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function showSupplier(Supplier $supplier, Request $request, DataTableFactory $dataTable) { @@ -140,7 +142,7 @@ class PartListsController extends AbstractController /** * @Route("/parts/by_tag/{tag}", name="part_list_tags") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function showTag(string $tag, Request $request, DataTableFactory $dataTable) { @@ -180,7 +182,7 @@ class PartListsController extends AbstractController /** * @Route("/parts", name="parts_show_all") * - * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response + * @return JsonResponse|Response */ public function showAll(Request $request, DataTableFactory $dataTable) { diff --git a/src/Controller/RedirectController.php b/src/Controller/RedirectController.php index 76ba53e3..18160deb 100644 --- a/src/Controller/RedirectController.php +++ b/src/Controller/RedirectController.php @@ -25,7 +25,10 @@ declare(strict_types=1); namespace App\Controller; use App\Entity\UserSystem\User; +use function function_exists; +use function in_array; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Contracts\Translation\TranslatorInterface; @@ -49,7 +52,7 @@ class RedirectController extends AbstractController * This function is called whenever a route was not matching the localized routes. * The purpose is to redirect the user to the localized version of the page. * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function addLocalePart(Request $request) { @@ -84,13 +87,13 @@ class RedirectController extends AbstractController */ public function checkIfModRewriteAvailable() { - if (! \function_exists('apache_get_modules')) { + if (! function_exists('apache_get_modules')) { //If we can not check for apache modules, we just hope for the best and assume url rewriting is available //If you want to enforce index.php versions of the url, you can override this via ENV vars. return true; } //Check if the mod_rewrite module is loaded - return \in_array('mod_rewrite', apache_get_modules(), false); + return in_array('mod_rewrite', apache_get_modules(), false); } } diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php index ecbae653..566b31de 100644 --- a/src/Controller/SecurityController.php +++ b/src/Controller/SecurityController.php @@ -26,6 +26,7 @@ namespace App\Controller; use App\Services\PasswordResetManager; use Gregwar\CaptchaBundle\Type\CaptchaType; +use RuntimeException; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\RepeatedType; @@ -122,7 +123,10 @@ class SecurityController extends AbstractController throw new AccessDeniedHttpException('You are already logged in, so you can not reset your password!'); } - $data = ['username' => $user, 'token' => $token]; + $data = [ + 'username' => $user, + 'token' => $token, + ]; $builder = $this->createFormBuilder($data); $builder->add('username', TextType::class, [ 'label' => $this->translator->trans('pw_reset.username'), @@ -132,8 +136,12 @@ class SecurityController extends AbstractController ]); $builder->add('new_password', RepeatedType::class, [ 'type' => PasswordType::class, - 'first_options' => ['label' => 'user.settings.pw_new.label'], - 'second_options' => ['label' => 'user.settings.pw_confirm.label'], + 'first_options' => [ + 'label' => 'user.settings.pw_new.label', + ], + 'second_options' => [ + 'label' => 'user.settings.pw_confirm.label', + ], 'invalid_message' => 'password_must_match', 'constraints' => [new Length([ 'min' => 6, @@ -171,6 +179,6 @@ class SecurityController extends AbstractController */ public function logout(): void { - throw new \RuntimeException('Will be intercepted before getting here'); + throw new RuntimeException('Will be intercepted before getting here'); } } diff --git a/src/Controller/UserController.php b/src/Controller/UserController.php index 31b95a13..b1a99fc1 100644 --- a/src/Controller/UserController.php +++ b/src/Controller/UserController.php @@ -33,6 +33,7 @@ use App\Services\EntityExporter; use App\Services\EntityImporter; use App\Services\StructuralElementRecursionHelper; use Doctrine\ORM\EntityManagerInterface; +use InvalidArgumentException; use Symfony\Component\Asset\Packages; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -99,7 +100,7 @@ class UserController extends AdminPages\BaseAdminController public function delete(Request $request, User $entity, StructuralElementRecursionHelper $recursionHelper) { if (User::ID_ANONYMOUS === $entity->getID()) { - throw new \InvalidArgumentException('You can not delete the anonymous user! It is needed for permission checking without a logged in user'); + throw new InvalidArgumentException('You can not delete the anonymous user! It is needed for permission checking without a logged in user'); } return $this->_delete($request, $entity, $recursionHelper); diff --git a/src/Controller/UserSettingsController.php b/src/Controller/UserSettingsController.php index 3e1cea83..1338d02f 100644 --- a/src/Controller/UserSettingsController.php +++ b/src/Controller/UserSettingsController.php @@ -30,12 +30,14 @@ use App\Form\TFAGoogleSettingsType; use App\Form\UserSettingsType; use App\Services\TFA\BackupCodeManager; use Doctrine\ORM\EntityManagerInterface; +use RuntimeException; use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Google\GoogleAuthenticator; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\RepeatedType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; @@ -65,13 +67,13 @@ class UserSettingsController extends AbstractController $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); if (! $user instanceof User) { - return new \RuntimeException('This controller only works only for Part-DB User objects!'); + return new RuntimeException('This controller only works only for Part-DB User objects!'); } if (empty($user->getBackupCodes())) { $this->addFlash('error', 'tfa_backup.no_codes_enabled'); - throw new \RuntimeException('You do not have any backup codes enabled, therefore you can not view them!'); + throw new RuntimeException('You do not have any backup codes enabled, therefore you can not view them!'); } return $this->render('Users/backup_codes.html.twig', [ @@ -82,12 +84,12 @@ class UserSettingsController extends AbstractController /** * @Route("/u2f_delete", name="u2f_delete", methods={"DELETE"}) * - * @return \Symfony\Component\HttpFoundation\RedirectResponse + * @return RedirectResponse */ public function removeU2FToken(Request $request, EntityManagerInterface $entityManager, BackupCodeManager $backupCodeManager) { if ($this->demo_mode) { - throw new \RuntimeException('You can not do 2FA things in demo mode'); + throw new RuntimeException('You can not do 2FA things in demo mode'); } $user = $this->getUser(); @@ -96,7 +98,7 @@ class UserSettingsController extends AbstractController $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); if (! $user instanceof User) { - throw new \RuntimeException('This controller only works only for Part-DB User objects!'); + throw new RuntimeException('This controller only works only for Part-DB User objects!'); } if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) { @@ -108,14 +110,14 @@ class UserSettingsController extends AbstractController if (null === $u2f) { $this->addFlash('danger', 'tfa_u2f.u2f_delete.not_existing'); - throw new \RuntimeException('Key not existing!'); + throw new RuntimeException('Key not existing!'); } //User can only delete its own U2F keys if ($u2f->getUser() !== $user) { $this->addFlash('danger', 'tfa_u2f.u2f_delete.access_denied'); - throw new \RuntimeException('You can only delete your own U2F keys!'); + throw new RuntimeException('You can only delete your own U2F keys!'); } $backupCodeManager->disableBackupCodesIfUnused($user); @@ -136,7 +138,7 @@ class UserSettingsController extends AbstractController public function resetTrustedDevices(Request $request, EntityManagerInterface $entityManager) { if ($this->demo_mode) { - throw new \RuntimeException('You can not do 2FA things in demo mode'); + throw new RuntimeException('You can not do 2FA things in demo mode'); } $user = $this->getUser(); @@ -145,7 +147,7 @@ class UserSettingsController extends AbstractController $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); if (! $user instanceof User) { - return new \RuntimeException('This controller only works only for Part-DB User objects!'); + return new RuntimeException('This controller only works only for Part-DB User objects!'); } if ($this->isCsrfTokenValid('devices_reset'.$user->getId(), $request->request->get('_token'))) { @@ -173,7 +175,7 @@ class UserSettingsController extends AbstractController $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); if (! $user instanceof User) { - throw new \RuntimeException('This controller only works only for Part-DB User objects!'); + throw new RuntimeException('This controller only works only for Part-DB User objects!'); } /*************************** @@ -202,23 +204,36 @@ class UserSettingsController extends AbstractController //Username field for autocomplete ->add('username', TextType::class, [ 'data' => $user->getName(), - 'attr' => ['autocomplete' => 'username'], + 'attr' => [ + 'autocomplete' => 'username', + ], 'disabled' => true, - 'row_attr' => ['class' => 'd-none'], + 'row_attr' => [ + 'class' => 'd-none', + ], ]) ->add('old_password', PasswordType::class, [ 'label' => 'user.settings.pw_old.label', 'disabled' => $this->demo_mode, - 'attr' => ['autocomplete' => 'current-password'], - 'constraints' => [new UserPassword()], ]) //This constraint checks, if the current user pw was inputted. + 'attr' => [ + 'autocomplete' => 'current-password', + ], + 'constraints' => [new UserPassword()], + ]) //This constraint checks, if the current user pw was inputted. ->add('new_password', RepeatedType::class, [ 'disabled' => $this->demo_mode, 'type' => PasswordType::class, - 'first_options' => ['label' => 'user.settings.pw_new.label'], - 'second_options' => ['label' => 'user.settings.pw_confirm.label'], + 'first_options' => [ + 'label' => 'user.settings.pw_new.label', + ], + 'second_options' => [ + 'label' => 'user.settings.pw_confirm.label', + ], 'invalid_message' => 'password_must_match', 'options' => [ - 'attr' => ['autocomplete' => 'new-password'], + 'attr' => [ + 'autocomplete' => 'new-password', + ], ], 'constraints' => [new Length([ 'min' => 6, @@ -276,7 +291,9 @@ class UserSettingsController extends AbstractController $backup_form = $this->get('form.factory')->createNamedBuilder('backup_codes')->add('reset_codes', SubmitType::class, [ 'label' => 'tfa_backup.regenerate_codes', - 'attr' => ['class' => 'btn-danger'], + 'attr' => [ + 'class' => 'btn-danger', + ], 'disabled' => empty($user->getBackupCodes()), ])->getForm(); diff --git a/src/DataFixtures/DataStructureFixtures.php b/src/DataFixtures/DataStructureFixtures.php index b5815554..119a0f57 100644 --- a/src/DataFixtures/DataStructureFixtures.php +++ b/src/DataFixtures/DataStructureFixtures.php @@ -36,6 +36,7 @@ use App\Entity\Parts\Supplier; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\ORM\EntityManagerInterface; +use InvalidArgumentException; class DataStructureFixtures extends Fixture { @@ -71,7 +72,7 @@ class DataStructureFixtures extends Fixture public function createNodesForClass(string $class, ObjectManager $manager): void { if (! new $class() instanceof StructuralDBElement) { - throw new \InvalidArgumentException('$class must be a StructuralDBElement!'); + throw new InvalidArgumentException('$class must be a StructuralDBElement!'); } $table_name = $this->em->getClassMetadata($class)->getTableName(); diff --git a/src/DataFixtures/GroupFixtures.php b/src/DataFixtures/GroupFixtures.php index 02895987..fd3cf729 100644 --- a/src/DataFixtures/GroupFixtures.php +++ b/src/DataFixtures/GroupFixtures.php @@ -40,14 +40,41 @@ class GroupFixtures extends Fixture $admins->setName('admins'); //Perm values taken from Version 1 $admins->getPermissions()->setRawPermissionValues([ - 'system' => 21, 'groups' => 1365, 'users' => 87381, 'self' => 85, 'config' => 85, - 'database' => 21, 'parts' => 1431655765, 'parts_name' => 5, 'parts_description' => 5, - 'parts_footprint' => 5, 'parts_manufacturer' => 5, 'parts_comment' => 5, 'parts_order' => 5, - 'parts_orderdetails' => 341, 'parts_prices' => 341, 'parts_attachments' => 341, 'devices' => 5461, - 'devices_parts' => 325, 'storelocations' => 5461, 'footprints' => 5461, 'categories' => 5461, - 'suppliers' => 5461, 'manufacturers' => 5461, 'attachment_types' => 1365, 'tools' => 1365, - 'labels' => 21, 'parts_category' => 5, 'parts_minamount' => 5, 'parts_lots' => 85, 'parts_tags' => 5, - 'parts_unit' => 5, 'parts_mass' => 5, 'parts_status' => 5, 'parts_mpn' => 5, 'currencies' => 5461, + 'system' => 21, + 'groups' => 1365, + 'users' => 87381, + 'self' => 85, + 'config' => 85, + 'database' => 21, + 'parts' => 1431655765, + 'parts_name' => 5, + 'parts_description' => 5, + 'parts_footprint' => 5, + 'parts_manufacturer' => 5, + 'parts_comment' => 5, + 'parts_order' => 5, + 'parts_orderdetails' => 341, + 'parts_prices' => 341, + 'parts_attachments' => 341, + 'devices' => 5461, + 'devices_parts' => 325, + 'storelocations' => 5461, + 'footprints' => 5461, + 'categories' => 5461, + 'suppliers' => 5461, + 'manufacturers' => 5461, + 'attachment_types' => 1365, + 'tools' => 1365, + 'labels' => 21, + 'parts_category' => 5, + 'parts_minamount' => 5, + 'parts_lots' => 85, + 'parts_tags' => 5, + 'parts_unit' => 5, + 'parts_mass' => 5, + 'parts_status' => 5, + 'parts_mpn' => 5, + 'currencies' => 5461, 'measurement_units' => 5461, ]); $this->setReference(self::ADMINS, $admins); @@ -56,14 +83,41 @@ class GroupFixtures extends Fixture $readonly = new Group(); $readonly->setName('readonly'); $readonly->getPermissions()->setRawPermissionValues([ - 'system' => 2, 'groups' => 2730, 'users' => 43690, 'self' => 25, 'config' => 170, - 'database' => 42, 'parts' => 2778027689, 'parts_name' => 9, 'parts_description' => 9, - 'parts_footprint' => 9, 'parts_manufacturer' => 9, 'parts_comment' => 9, 'parts_order' => 9, - 'parts_orderdetails' => 681, 'parts_prices' => 681, 'parts_attachments' => 681, 'devices' => 1705, - 'devices_parts' => 649, 'storelocations' => 1705, 'footprints' => 1705, 'categories' => 1705, - 'suppliers' => 1705, 'manufacturers' => 1705, 'attachment_types' => 681, 'tools' => 1366, - 'labels' => 165, 'parts_category' => 9, 'parts_minamount' => 9, 'parts_lots' => 169, 'parts_tags' => 9, - 'parts_unit' => 9, 'parts_mass' => 9, 'parts_status' => 9, 'parts_mpn' => 9, 'currencies' => 9897, + 'system' => 2, + 'groups' => 2730, + 'users' => 43690, + 'self' => 25, + 'config' => 170, + 'database' => 42, + 'parts' => 2778027689, + 'parts_name' => 9, + 'parts_description' => 9, + 'parts_footprint' => 9, + 'parts_manufacturer' => 9, + 'parts_comment' => 9, + 'parts_order' => 9, + 'parts_orderdetails' => 681, + 'parts_prices' => 681, + 'parts_attachments' => 681, + 'devices' => 1705, + 'devices_parts' => 649, + 'storelocations' => 1705, + 'footprints' => 1705, + 'categories' => 1705, + 'suppliers' => 1705, + 'manufacturers' => 1705, + 'attachment_types' => 681, + 'tools' => 1366, + 'labels' => 165, + 'parts_category' => 9, + 'parts_minamount' => 9, + 'parts_lots' => 169, + 'parts_tags' => 9, + 'parts_unit' => 9, + 'parts_mass' => 9, + 'parts_status' => 9, + 'parts_mpn' => 9, + 'currencies' => 9897, 'measurement_units' => 9897, ]); $this->setReference(self::READONLY, $readonly); @@ -72,14 +126,41 @@ class GroupFixtures extends Fixture $users = new Group(); $users->setName('users'); $users->getPermissions()->setRawPermissionValues([ - 'system' => 42, 'groups' => 2730, 'users' => 43690, 'self' => 89, 'config' => 105, - 'database' => 41, 'parts' => 1431655765, 'parts_name' => 5, 'parts_description' => 5, - 'parts_footprint' => 5, 'parts_manufacturer' => 5, 'parts_comment' => 5, 'parts_order' => 5, - 'parts_orderdetails' => 341, 'parts_prices' => 341, 'parts_attachments' => 341, 'devices' => 5461, - 'devices_parts' => 325, 'storelocations' => 5461, 'footprints' => 5461, 'categories' => 5461, - 'suppliers' => 5461, 'manufacturers' => 5461, 'attachment_types' => 1365, 'tools' => 1365, - 'labels' => 85, 'parts_category' => 5, 'parts_minamount' => 5, 'parts_lots' => 85, 'parts_tags' => 5, - 'parts_unit' => 5, 'parts_mass' => 5, 'parts_status' => 5, 'parts_mpn' => 5, 'currencies' => 5461, + 'system' => 42, + 'groups' => 2730, + 'users' => 43690, + 'self' => 89, + 'config' => 105, + 'database' => 41, + 'parts' => 1431655765, + 'parts_name' => 5, + 'parts_description' => 5, + 'parts_footprint' => 5, + 'parts_manufacturer' => 5, + 'parts_comment' => 5, + 'parts_order' => 5, + 'parts_orderdetails' => 341, + 'parts_prices' => 341, + 'parts_attachments' => 341, + 'devices' => 5461, + 'devices_parts' => 325, + 'storelocations' => 5461, + 'footprints' => 5461, + 'categories' => 5461, + 'suppliers' => 5461, + 'manufacturers' => 5461, + 'attachment_types' => 1365, + 'tools' => 1365, + 'labels' => 85, + 'parts_category' => 5, + 'parts_minamount' => 5, + 'parts_lots' => 85, + 'parts_tags' => 5, + 'parts_unit' => 5, + 'parts_mass' => 5, + 'parts_status' => 5, + 'parts_mpn' => 5, + 'currencies' => 5461, 'measurement_units' => 5461, ]); $this->setReference(self::USERS, $users); diff --git a/src/DataTables/Adapter/CustomORMAdapter.php b/src/DataTables/Adapter/CustomORMAdapter.php index 764a4088..9aa565cc 100644 --- a/src/DataTables/Adapter/CustomORMAdapter.php +++ b/src/DataTables/Adapter/CustomORMAdapter.php @@ -29,6 +29,7 @@ use Doctrine\ORM\QueryBuilder; use Omines\DataTablesBundle\Adapter\AdapterQuery; use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter; use Omines\DataTablesBundle\Column\AbstractColumn; +use Traversable; /** * Override default ORM Adapter, to allow fetch joins (allow addSelect with ManyToOne Collections). @@ -52,9 +53,9 @@ class CustomORMAdapter extends ORMAdapter } /** - * @return \Traversable + * @return Traversable */ - protected function getResults(AdapterQuery $query): \Traversable + protected function getResults(AdapterQuery $query): Traversable { /** @var QueryBuilder $builder */ $builder = $query->get('qb'); diff --git a/src/DataTables/AttachmentDataTable.php b/src/DataTables/AttachmentDataTable.php index 8e741a68..14bdd9ab 100644 --- a/src/DataTables/AttachmentDataTable.php +++ b/src/DataTables/AttachmentDataTable.php @@ -38,7 +38,7 @@ use Omines\DataTablesBundle\DataTable; use Omines\DataTablesBundle\DataTableTypeInterface; use Symfony\Contracts\Translation\TranslatorInterface; -class AttachmentDataTable implements DataTableTypeInterface +final class AttachmentDataTable implements DataTableTypeInterface { protected $translator; protected $entityURLGenerator; diff --git a/src/DataTables/Column/LocaleDateTimeColumn.php b/src/DataTables/Column/LocaleDateTimeColumn.php index d01e2c3d..c0dc8599 100644 --- a/src/DataTables/Column/LocaleDateTimeColumn.php +++ b/src/DataTables/Column/LocaleDateTimeColumn.php @@ -24,7 +24,10 @@ declare(strict_types=1); namespace App\DataTables\Column; +use DateTime; +use DateTimeInterface; use IntlDateFormatter; +use Locale; use Omines\DataTablesBundle\Column\AbstractColumn; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -38,8 +41,8 @@ class LocaleDateTimeColumn extends AbstractColumn { if (null === $value) { return $this->options['nullValue']; - } elseif (! $value instanceof \DateTimeInterface) { - $value = new \DateTime((string) $value); + } elseif (! $value instanceof DateTimeInterface) { + $value = new DateTime((string) $value); } $formatValues = [ @@ -51,7 +54,7 @@ class LocaleDateTimeColumn extends AbstractColumn ]; $formatter = IntlDateFormatter::create( - \Locale::getDefault(), + Locale::getDefault(), $formatValues[$this->options['dateFormat']], $formatValues[$this->options['timeFormat']], $value->getTimezone() diff --git a/src/DataTables/Column/PartAttachmentsColumn.php b/src/DataTables/Column/PartAttachmentsColumn.php index 303da5a7..a4530741 100644 --- a/src/DataTables/Column/PartAttachmentsColumn.php +++ b/src/DataTables/Column/PartAttachmentsColumn.php @@ -30,6 +30,7 @@ use App\Services\Attachments\AttachmentManager; use App\Services\EntityURLGenerator; use App\Services\FAIconGenerator; use Omines\DataTablesBundle\Column\AbstractColumn; +use RuntimeException; use Symfony\Component\OptionsResolver\OptionsResolver; class PartAttachmentsColumn extends AbstractColumn @@ -60,7 +61,7 @@ class PartAttachmentsColumn extends AbstractColumn public function render($value, $context) { if (! $context instanceof Part) { - throw new \RuntimeException('$context must be a Part object!'); + throw new RuntimeException('$context must be a Part object!'); } $tmp = ''; $attachments = $context->getAttachments()->filter(function (Attachment $attachment) { diff --git a/src/DataTables/PartsDataTable.php b/src/DataTables/PartsDataTable.php index 861e38e8..e9ed9b2e 100644 --- a/src/DataTables/PartsDataTable.php +++ b/src/DataTables/PartsDataTable.php @@ -50,17 +50,17 @@ use Omines\DataTablesBundle\DataTable; use Omines\DataTablesBundle\DataTableTypeInterface; use Symfony\Contracts\Translation\TranslatorInterface; -class PartsDataTable implements DataTableTypeInterface +final class PartsDataTable implements DataTableTypeInterface { - /** - * @var EntityURLGenerator - */ - protected $urlGenerator; protected $translator; protected $treeBuilder; protected $amountFormatter; protected $previewGenerator; protected $attachmentURLGenerator; + /** + * @var EntityURLGenerator + */ + protected $urlGenerator; public function __construct(EntityURLGenerator $urlGenerator, TranslatorInterface $translator, NodesListBuilder $treeBuilder, AmountFormatter $amountFormatter, diff --git a/src/Entity/Attachments/Attachment.php b/src/Entity/Attachments/Attachment.php index 4c1da00c..0288c416 100644 --- a/src/Entity/Attachments/Attachment.php +++ b/src/Entity/Attachments/Attachment.php @@ -26,6 +26,9 @@ namespace App\Entity\Attachments; use App\Entity\Base\NamedDBElement; use App\Validator\Constraints\Selectable; use Doctrine\ORM\Mapping as ORM; +use function in_array; +use InvalidArgumentException; +use LogicException; /** * Class Attachment. @@ -65,7 +68,9 @@ abstract class Attachment extends NamedDBElement */ public const INTERNAL_PLACEHOLDER = ['%BASE%', '%MEDIA%', '%SECURE%']; - /** @var array Placeholders for attachments which using built in files. */ + /** + * @var array Placeholders for attachments which using built in files. + */ public const BUILTIN_PLACEHOLDER = ['%FOOTPRINTS%', '%FOOTPRINTS3D%']; /** @@ -74,10 +79,10 @@ abstract class Attachment extends NamedDBElement public const ALLOWED_ELEMENT_CLASS = ''; /** - * @var bool - * @ORM\Column(type="boolean") + * @var string the original filename the file had, when the user uploaded it + * @ORM\Column(type="string", nullable=true) */ - protected $show_in_table = false; + protected $original_filename; /** * @var string The path to the file relative to a placeholder path like %MEDIA% @@ -85,17 +90,17 @@ abstract class Attachment extends NamedDBElement */ protected $path = ''; - /** - * @var string the original filename the file had, when the user uploaded it - * @ORM\Column(type="string", nullable=true) - */ - protected $original_filename; - /** * ORM mapping is done in sub classes (like PartAttachment). */ protected $element; + /** + * @var bool + * @ORM\Column(type="boolean") + */ + protected $show_in_table = false; + /** * @var AttachmentType * @ORM\ManyToOne(targetEntity="AttachmentType", inversedBy="attachments_with_type") @@ -108,7 +113,7 @@ abstract class Attachment extends NamedDBElement { //parent::__construct(); if ('' === static::ALLOWED_ELEMENT_CLASS) { - throw new \LogicException('An *Attachment class must override the ALLOWED_ELEMENT_CLASS const!'); + throw new LogicException('An *Attachment class must override the ALLOWED_ELEMENT_CLASS const!'); } } @@ -132,7 +137,7 @@ abstract class Attachment extends NamedDBElement $extension = pathinfo($this->getPath(), PATHINFO_EXTENSION); - return \in_array(strtolower($extension), static::PICTURE_EXTS, true); + return in_array(strtolower($extension), static::PICTURE_EXTS, true); } /** @@ -148,7 +153,7 @@ abstract class Attachment extends NamedDBElement $extension = pathinfo($this->getPath(), PATHINFO_EXTENSION); - return \in_array(strtolower($extension), static::MODEL_EXTS, true); + return in_array(strtolower($extension), static::MODEL_EXTS, true); } /** @@ -170,7 +175,7 @@ abstract class Attachment extends NamedDBElement return true; } - return ! \in_array($tmp[0], array_merge(static::INTERNAL_PLACEHOLDER, static::BUILTIN_PLACEHOLDER), false); + return ! in_array($tmp[0], array_merge(static::INTERNAL_PLACEHOLDER, static::BUILTIN_PLACEHOLDER), false); } /** @@ -363,7 +368,7 @@ abstract class Attachment extends NamedDBElement public function setElement(AttachmentContainingDBElement $element): self { if (! is_a($element, static::ALLOWED_ELEMENT_CLASS)) { - throw new \InvalidArgumentException(sprintf('The element associated with a %s must be a %s!', static::class, static::ALLOWED_ELEMENT_CLASS)); + throw new InvalidArgumentException(sprintf('The element associated with a %s must be a %s!', static::class, static::ALLOWED_ELEMENT_CLASS)); } $this->element = $element; @@ -406,7 +411,7 @@ abstract class Attachment extends NamedDBElement //Only set if the URL is not empty if (! empty($url)) { if (false !== strpos($url, '%BASE%') || false !== strpos($url, '%MEDIA%')) { - throw new \InvalidArgumentException('You can not reference internal files via the url field! But nice try!'); + throw new InvalidArgumentException('You can not reference internal files via the url field! But nice try!'); } $this->path = $url; @@ -437,7 +442,7 @@ abstract class Attachment extends NamedDBElement return false; } - return \in_array($tmp[0], static::BUILTIN_PLACEHOLDER, false); + return in_array($tmp[0], static::BUILTIN_PLACEHOLDER, false); } /** diff --git a/src/Entity/Attachments/AttachmentContainingDBElement.php b/src/Entity/Attachments/AttachmentContainingDBElement.php index dbce1c92..1a1c9736 100644 --- a/src/Entity/Attachments/AttachmentContainingDBElement.php +++ b/src/Entity/Attachments/AttachmentContainingDBElement.php @@ -43,7 +43,7 @@ abstract class AttachmentContainingDBElement extends NamedDBElement * * Mapping is done in sub classes like part */ - protected $attachments; + protected $attachments = []; public function __construct() { diff --git a/src/Entity/Attachments/AttachmentType.php b/src/Entity/Attachments/AttachmentType.php index 42156553..da4c4c05 100644 --- a/src/Entity/Attachments/AttachmentType.php +++ b/src/Entity/Attachments/AttachmentType.php @@ -37,18 +37,6 @@ use Doctrine\ORM\Mapping as ORM; */ class AttachmentType extends StructuralDBElement { - /** - * @var Collection|AttachmentTypeAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\AttachmentTypeAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - - /** - * @var Collection|Attachment[] - * @ORM\OneToMany(targetEntity="Attachment", mappedBy="attachment_type") - */ - protected $attachments_with_type; - /** * @ORM\OneToMany(targetEntity="AttachmentType", mappedBy="parent", cascade={"persist"}) */ @@ -66,6 +54,17 @@ class AttachmentType extends StructuralDBElement * @ValidFileFilter */ protected $filetype_filter = ''; + /** + * @var Collection|AttachmentTypeAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\AttachmentTypeAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; + + /** + * @var Collection|Attachment[] + * @ORM\OneToMany(targetEntity="Attachment", mappedBy="attachment_type") + */ + protected $attachments_with_type; public function __construct() { diff --git a/src/Entity/Base/Company.php b/src/Entity/Base/Company.php index 368374e9..711695c6 100644 --- a/src/Entity/Base/Company.php +++ b/src/Entity/Base/Company.php @@ -44,6 +44,7 @@ declare(strict_types=1); namespace App\Entity\Base; use Doctrine\ORM\Mapping as ORM; +use function is_string; use Symfony\Component\Validator\Constraints as Assert; /** @@ -157,7 +158,7 @@ abstract class Company extends PartsContainingDBElement */ public function getAutoProductUrl($partnr = null): string { - if (\is_string($partnr)) { + if (is_string($partnr)) { return str_replace('%PARTNUMBER%', $partnr, $this->auto_product_url); } diff --git a/src/Entity/Base/StructuralDBElement.php b/src/Entity/Base/StructuralDBElement.php index dc795083..6a74ff9e 100644 --- a/src/Entity/Base/StructuralDBElement.php +++ b/src/Entity/Base/StructuralDBElement.php @@ -25,9 +25,13 @@ namespace App\Entity\Base; use App\Entity\Attachments\AttachmentContainingDBElement; use App\Validator\Constraints\NoneOfItsChildren; +use function count; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; +use function get_class; +use InvalidArgumentException; +use function is_array; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Serializer\Annotation\Groups; @@ -50,23 +54,11 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement { public const ID_ROOT_ELEMENT = 0; - /** This is a not standard character, so build a const, so a dev can easily use it */ + /** + * This is a not standard character, so build a const, so a dev can easily use it + */ public const PATH_DELIMITER_ARROW = ' → '; - /** - * We can not define the mapping here or we will get an exception. Unfortunately we have to do the mapping in the - * subclasses - * @var StructuralDBElement[] - * @Groups({"include_children"}) - */ - protected $children; - /** - * @var StructuralDBElement - * @NoneOfItsChildren() - * @Groups({"include_parents"}) - */ - protected $parent; - /** * @var string The comment info for this element * @ORM\Column(type="text") @@ -86,10 +78,25 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement */ protected $level = 0; + /** + * We can not define the mapping here or we will get an exception. Unfortunately we have to do the mapping in the + * subclasses. + * + * @var StructuralDBElement[] + * @Groups({"include_children"}) + */ + protected $children = []; + /** + * @var StructuralDBElement + * @NoneOfItsChildren() + * @Groups({"include_parents"}) + */ + protected $parent; + /** @var string[] all names of all parent elements as a array of strings, * the last array element is the name of the element itself */ - private $full_path_strings; + private $full_path_strings = []; public function __construct() { @@ -109,7 +116,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement * * @return bool True, if this element is child of $another_element. * - * @throws \InvalidArgumentException if there was an error + * @throws InvalidArgumentException if there was an error */ public function isChildOf(self $another_element): bool { @@ -117,8 +124,8 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement //Check if both elements compared, are from the same type // (we have to check inheritance, or we get exceptions when using doctrine entities (they have a proxy type): - if (! is_a($another_element, $class_name) && ! is_a($this, \get_class($another_element))) { - throw new \InvalidArgumentException('isChildOf() only works for objects of the same type!'); + if (! is_a($another_element, $class_name) && ! is_a($this, get_class($another_element))) { + throw new InvalidArgumentException('isChildOf() only works for objects of the same type!'); } if (null === $this->getParent()) { // this is the root node @@ -201,7 +208,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement */ public function getFullPath(string $delimiter = self::PATH_DELIMITER_ARROW): string { - if (! \is_array($this->full_path_strings)) { + if (empty($this->full_path_strings)) { $this->full_path_strings = []; $this->full_path_strings[] = $this->getName(); $element = $this; @@ -233,7 +240,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement $tmp[] = $this; //We only allow 20 levels depth - while (! end($tmp)->isRoot() && \count($tmp) < 20) { + while (! end($tmp)->isRoot() && count($tmp) < 20) { $tmp[] = end($tmp)->parent; } diff --git a/src/Entity/Base/TimestampTrait.php b/src/Entity/Base/TimestampTrait.php index aa3ebf71..c94c26e7 100644 --- a/src/Entity/Base/TimestampTrait.php +++ b/src/Entity/Base/TimestampTrait.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace App\Entity\Base; +use DateTime; use Symfony\Component\Serializer\Annotation\Groups; /** @@ -32,14 +33,14 @@ use Symfony\Component\Serializer\Annotation\Groups; trait TimestampTrait { /** - * @var \DateTime the date when this element was modified the last time + * @var DateTime the date when this element was modified the last time * @ORM\Column(type="datetime", name="last_modified", options={"default"="CURRENT_TIMESTAMP"}) * @Groups({"extended", "full"}) */ protected $lastModified; /** - * @var \DateTime the date when this element was created + * @var DateTime the date when this element was created * @ORM\Column(type="datetime", name="datetime_added", options={"default"="CURRENT_TIMESTAMP"}) * @Groups({"extended", "full"}) */ @@ -49,9 +50,9 @@ trait TimestampTrait * Returns the last time when the element was modified. * Returns null if the element was not yet saved to DB yet. * - * @return \DateTime|null the time of the last edit + * @return DateTime|null the time of the last edit */ - public function getLastModified(): ?\DateTime + public function getLastModified(): ?DateTime { return $this->lastModified; } @@ -60,9 +61,9 @@ trait TimestampTrait * Returns the date/time when the element was created. * Returns null if the element was not yet saved to DB yet. * - * @return \DateTime|null the creation time of the part + * @return DateTime|null the creation time of the part */ - public function getAddedDate(): ?\DateTime + public function getAddedDate(): ?DateTime { return $this->addedDate; } @@ -75,9 +76,9 @@ trait TimestampTrait */ public function updatedTimestamps(): void { - $this->lastModified = new \DateTime('now'); + $this->lastModified = new DateTime('now'); if (null === $this->addedDate) { - $this->addedDate = new \DateTime('now'); + $this->addedDate = new DateTime('now'); } } } diff --git a/src/Entity/Devices/Device.php b/src/Entity/Devices/Device.php index 56cd360f..928b4c4c 100644 --- a/src/Entity/Devices/Device.php +++ b/src/Entity/Devices/Device.php @@ -55,6 +55,7 @@ use App\Entity\Attachments\DeviceAttachment; use App\Entity\Base\PartsContainingDBElement; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; +use InvalidArgumentException; /** * Class AttachmentType. @@ -64,12 +65,6 @@ use Doctrine\ORM\Mapping as ORM; */ class Device extends PartsContainingDBElement { - /** - * @var Collection|DeviceAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\DeviceAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - /** * @ORM\OneToMany(targetEntity="Device", mappedBy="parent") */ @@ -81,6 +76,11 @@ class Device extends PartsContainingDBElement */ protected $parent; + /** + * @ORM\OneToMany(targetEntity="DevicePart", mappedBy="device") + */ + protected $parts; + /** * @var int * @ORM\Column(type="integer") @@ -92,11 +92,11 @@ class Device extends PartsContainingDBElement * @ORM\Column(type="boolean") */ protected $order_only_missing_parts = false; - /** - * @ORM\OneToMany(targetEntity="DevicePart", mappedBy="device") + * @var Collection|DeviceAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\DeviceAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) */ - protected $parts; + protected $attachments; /******************************************************************************** * @@ -140,7 +140,7 @@ class Device extends PartsContainingDBElement public function setOrderQuantity(int $new_order_quantity): self { if ($new_order_quantity < 0) { - throw new \InvalidArgumentException('The new order quantity must not be negative!'); + throw new InvalidArgumentException('The new order quantity must not be negative!'); } $this->order_quantity = $new_order_quantity; diff --git a/src/Entity/Devices/DevicePart.php b/src/Entity/Devices/DevicePart.php index 85cb4264..3bbcbbb1 100644 --- a/src/Entity/Devices/DevicePart.php +++ b/src/Entity/Devices/DevicePart.php @@ -63,6 +63,17 @@ use Doctrine\ORM\Mapping as ORM; */ class DevicePart extends DBElement { + /** + * @var int + * @ORM\Column(type="integer", name="quantity") + */ + protected $quantity; + + /** + * @var string + * @ORM\Column(type="text", name="mountnames") + */ + protected $mountnames; /** * @var Device * @ORM\ManyToOne(targetEntity="Device", inversedBy="parts") @@ -77,18 +88,6 @@ class DevicePart extends DBElement */ protected $part; - /** - * @var int - * @ORM\Column(type="integer", name="quantity") - */ - protected $quantity; - - /** - * @var string - * @ORM\Column(type="text", name="mountnames") - */ - protected $mountnames; - /** * Returns the ID as an string, defined by the element class. * This should have a form like P000014, for a part with ID 14. diff --git a/src/Entity/Parts/Category.php b/src/Entity/Parts/Category.php index aeab05bb..094bbe4b 100644 --- a/src/Entity/Parts/Category.php +++ b/src/Entity/Parts/Category.php @@ -36,12 +36,6 @@ use Doctrine\ORM\Mapping as ORM; */ class Category extends PartsContainingDBElement { - /** - * @var Collection|CategoryAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\CategoryAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - /** * @ORM\OneToMany(targetEntity="Category", mappedBy="parent") */ @@ -105,6 +99,11 @@ class Category extends PartsContainingDBElement * @ORM\Column(type="text") */ protected $default_comment = ''; + /** + * @var Collection|CategoryAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\CategoryAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; /** * Returns the ID as an string, defined by the element class. diff --git a/src/Entity/Parts/Footprint.php b/src/Entity/Parts/Footprint.php index c508a832..b63cbf22 100644 --- a/src/Entity/Parts/Footprint.php +++ b/src/Entity/Parts/Footprint.php @@ -65,26 +65,25 @@ use Doctrine\ORM\Mapping as ORM; class Footprint extends PartsContainingDBElement { /** - * @var Collection|FootprintAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\FootprintAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + * @ORM\ManyToOne(targetEntity="Footprint", inversedBy="children") + * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") */ - protected $attachments; + protected $parent; /** * @ORM\OneToMany(targetEntity="Footprint", mappedBy="parent") */ protected $children; - /** - * @ORM\ManyToOne(targetEntity="Footprint", inversedBy="children") - * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") - */ - protected $parent; - /** * @ORM\OneToMany(targetEntity="Part", mappedBy="footprint", fetch="EXTRA_LAZY") */ protected $parts; + /** + * @var Collection|FootprintAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\FootprintAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; /** * @var FootprintAttachment|null diff --git a/src/Entity/Parts/Manufacturer.php b/src/Entity/Parts/Manufacturer.php index 60c33788..45dcdc6c 100644 --- a/src/Entity/Parts/Manufacturer.php +++ b/src/Entity/Parts/Manufacturer.php @@ -65,26 +65,25 @@ use Doctrine\ORM\Mapping as ORM; class Manufacturer extends Company { /** - * @var Collection|ManufacturerAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\ManufacturerAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + * @ORM\ManyToOne(targetEntity="Manufacturer", inversedBy="children") + * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") */ - protected $attachments; + protected $parent; /** * @ORM\OneToMany(targetEntity="Manufacturer", mappedBy="parent") */ protected $children; - /** - * @ORM\ManyToOne(targetEntity="Manufacturer", inversedBy="children") - * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") - */ - protected $parent; - /** * @ORM\OneToMany(targetEntity="Part", mappedBy="manufacturer", fetch="EXTRA_LAZY") */ protected $parts; + /** + * @var Collection|ManufacturerAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\ManufacturerAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; /** * Returns the ID as an string, defined by the element class. diff --git a/src/Entity/Parts/MeasurementUnit.php b/src/Entity/Parts/MeasurementUnit.php index 741a7085..761ae8ba 100644 --- a/src/Entity/Parts/MeasurementUnit.php +++ b/src/Entity/Parts/MeasurementUnit.php @@ -41,12 +41,6 @@ use Symfony\Component\Validator\Constraints as Assert; */ class MeasurementUnit extends PartsContainingDBElement { - /** - * @var Collection|MeasurementUnitAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\MeasurementUnitAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - /** * @var string The unit symbol that should be used for the Unit. This could be something like "", g (for grams) * or m (for meters). @@ -84,6 +78,11 @@ class MeasurementUnit extends PartsContainingDBElement * @ORM\OneToMany(targetEntity="Part", mappedBy="partUnit", fetch="EXTRA_LAZY") */ protected $parts; + /** + * @var Collection|MeasurementUnitAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\MeasurementUnitAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; /** * Returns the ID as an string, defined by the element class. diff --git a/src/Entity/Parts/Part.php b/src/Entity/Parts/Part.php index 885c75cc..ae8dfa65 100644 --- a/src/Entity/Parts/Part.php +++ b/src/Entity/Parts/Part.php @@ -60,6 +60,7 @@ use App\Entity\Parts\PartTraits\InstockTrait; use App\Entity\Parts\PartTraits\ManufacturerTrait; use App\Entity\Parts\PartTraits\OrderTrait; use App\Security\Annotations\ColumnSecurity; +use DateTime; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; @@ -82,7 +83,9 @@ class Part extends AttachmentContainingDBElement use ManufacturerTrait; use OrderTrait; - /** TODO */ + /** + * TODO + */ protected $devices; /** @@ -91,16 +94,9 @@ class Part extends AttachmentContainingDBElement */ protected $addedDate; - /** - * @var \DateTime the date when this element was modified the last time - * @ColumnSecurity(type="datetime") - * @ORM\Column(type="datetime", name="last_modified", options={"default"="CURRENT_TIMESTAMP"}) - */ - protected $lastModified; - /** ************************************************************* * Overridden properties - * (They are defined here and not in a trait, to avoid conflicts) + * (They are defined here and not in a trait, to avoid conflicts). ****************************************************************/ /** @@ -117,6 +113,13 @@ class Part extends AttachmentContainingDBElement */ protected $attachments; + /** + * @var DateTime the date when this element was modified the last time + * @ColumnSecurity(type="datetime") + * @ORM\Column(type="datetime", name="last_modified", options={"default"="CURRENT_TIMESTAMP"}) + */ + protected $lastModified; + /** * @var Attachment * @ORM\ManyToOne(targetEntity="App\Entity\Attachments\Attachment") diff --git a/src/Entity/Parts/PartLot.php b/src/Entity/Parts/PartLot.php index c80f7c90..6538d782 100644 --- a/src/Entity/Parts/PartLot.php +++ b/src/Entity/Parts/PartLot.php @@ -29,7 +29,9 @@ use App\Entity\Base\TimestampTrait; use App\Entity\Parts\PartTraits\InstockTrait; use App\Validator\Constraints\Selectable; use App\Validator\Constraints\ValidPartLot; +use DateTime; use Doctrine\ORM\Mapping as ORM; +use Exception; use Symfony\Component\Validator\Constraints as Assert; /** @@ -58,8 +60,8 @@ class PartLot extends DBElement protected $comment = ''; /** - * @var ?\DateTime Set a time until when the lot must be used. - * Set to null, if the lot can be used indefinitely. + * @var ?DateTime Set a time until when the lot must be used. + * Set to null, if the lot can be used indefinitely. * @ORM\Column(type="datetime", name="expiration_date", nullable=true) */ protected $expiration_date; @@ -72,14 +74,6 @@ class PartLot extends DBElement */ protected $storage_location; - /** - * @var Part The part that is stored in this lot - * @ORM\ManyToOne(targetEntity="Part", inversedBy="partLots") - * @ORM\JoinColumn(name="id_part", referencedColumnName="id", nullable=false, onDelete="CASCADE") - * @Assert\NotNull() - */ - protected $part; - /** * @var bool If this is set to true, the instock amount is marked as not known * @ORM\Column(type="boolean") @@ -99,6 +93,14 @@ class PartLot extends DBElement */ protected $needs_refill = false; + /** + * @var Part The part that is stored in this lot + * @ORM\ManyToOne(targetEntity="Part", inversedBy="partLots") + * @ORM\JoinColumn(name="id_part", referencedColumnName="id", nullable=false, onDelete="CASCADE") + * @Assert\NotNull() + */ + protected $part; + /** * Returns the ID as an string, defined by the element class. * This should have a form like P000014, for a part with ID 14. @@ -116,7 +118,7 @@ class PartLot extends DBElement * * @return bool|null True, if the part lot is expired. Returns null, if no expiration date was set. * - * @throws \Exception If an error with the DateTime occurs + * @throws Exception If an error with the DateTime occurs */ public function isExpired(): ?bool { @@ -125,7 +127,7 @@ class PartLot extends DBElement } //Check if the expiration date is bigger then current time - return $this->expiration_date < new \DateTime('now'); + return $this->expiration_date < new DateTime('now'); } /** @@ -175,9 +177,9 @@ class PartLot extends DBElement /** * Gets the expiration date for the part lot. Returns null, if no expiration date was set. * - * @return \DateTime|null + * @return DateTime|null */ - public function getExpirationDate(): ?\DateTime + public function getExpirationDate(): ?DateTime { return $this->expiration_date; } @@ -185,11 +187,11 @@ class PartLot extends DBElement /** * Sets the expiration date for the part lot. Set to null, if the part lot does not expires. * - * @param \DateTime $expiration_date + * @param DateTime $expiration_date * * @return PartLot */ - public function setExpirationDate(?\DateTime $expiration_date): self + public function setExpirationDate(?DateTime $expiration_date): self { $this->expiration_date = $expiration_date; diff --git a/src/Entity/Parts/PartTraits/OrderTrait.php b/src/Entity/Parts/PartTraits/OrderTrait.php index eabb32e8..f99ed9bc 100644 --- a/src/Entity/Parts/PartTraits/OrderTrait.php +++ b/src/Entity/Parts/PartTraits/OrderTrait.php @@ -26,6 +26,7 @@ namespace App\Entity\Parts\PartTraits; use App\Entity\PriceInformations\Orderdetail; use App\Security\Annotations\ColumnSecurity; +use function count; use Doctrine\Common\Collections\Collection; /** @@ -183,7 +184,7 @@ trait OrderTrait { $all_orderdetails = $this->getOrderdetails(); - if (0 === \count($all_orderdetails)) { + if (0 === count($all_orderdetails)) { return false; } diff --git a/src/Entity/Parts/Storelocation.php b/src/Entity/Parts/Storelocation.php index 224aeaad..7fcf083d 100644 --- a/src/Entity/Parts/Storelocation.php +++ b/src/Entity/Parts/Storelocation.php @@ -64,12 +64,6 @@ use Doctrine\ORM\Mapping as ORM; */ class Storelocation extends PartsContainingDBElement { - /** - * @var Collection|StorelocationAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\StorelocationAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - /** * @ORM\OneToMany(targetEntity="Storelocation", mappedBy="parent") */ @@ -81,6 +75,22 @@ class Storelocation extends PartsContainingDBElement */ protected $parent; + /** + * @var MeasurementUnit|null The measurement unit, which parts can be stored in here + * @ORM\ManyToOne(targetEntity="MeasurementUnit") + * @ORM\JoinColumn(name="storage_type_id", referencedColumnName="id") + */ + protected $storage_type; + + /** + * @ORM\ManyToMany(targetEntity="Part", fetch="EXTRA_LAZY") + * @ORM\JoinTable(name="part_lots", + * joinColumns={@ORM\JoinColumn(name="id_store_location", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="id_part", referencedColumnName="id")} + * ) + */ + protected $parts; + /** * @var bool * @ORM\Column(type="boolean") @@ -98,22 +108,11 @@ class Storelocation extends PartsContainingDBElement * @ORM\Column(type="boolean") */ protected $limit_to_existing_parts = false; - /** - * @var MeasurementUnit|null The measurement unit, which parts can be stored in here - * @ORM\ManyToOne(targetEntity="MeasurementUnit") - * @ORM\JoinColumn(name="storage_type_id", referencedColumnName="id") + * @var Collection|StorelocationAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\StorelocationAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) */ - protected $storage_type; - - /** - * @ORM\ManyToMany(targetEntity="Part", fetch="EXTRA_LAZY") - * @ORM\JoinTable(name="part_lots", - * joinColumns={@ORM\JoinColumn(name="id_store_location", referencedColumnName="id")}, - * inverseJoinColumns={@ORM\JoinColumn(name="id_part", referencedColumnName="id")} - * ) - */ - protected $parts; + protected $attachments; /******************************************************************************** * diff --git a/src/Entity/Parts/Supplier.php b/src/Entity/Parts/Supplier.php index 1475e007..9c8da03f 100644 --- a/src/Entity/Parts/Supplier.php +++ b/src/Entity/Parts/Supplier.php @@ -67,12 +67,6 @@ use Symfony\Component\Validator\Constraints as Assert; */ class Supplier extends Company { - /** - * @var Collection|SupplierAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\SupplierAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - /** * @ORM\OneToMany(targetEntity="Supplier", mappedBy="parent") */ @@ -113,6 +107,11 @@ class Supplier extends Company * ) */ protected $parts; + /** + * @var Collection|SupplierAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\SupplierAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; /** * Gets the currency that should be used by default, when creating a orderdetail with this supplier. diff --git a/src/Entity/PriceInformations/Currency.php b/src/Entity/PriceInformations/Currency.php index e7818a82..860aa4a6 100644 --- a/src/Entity/PriceInformations/Currency.php +++ b/src/Entity/PriceInformations/Currency.php @@ -43,10 +43,12 @@ class Currency extends StructuralDBElement public const PRICE_SCALE = 5; /** - * @var Collection|CurrencyAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\CurrencyAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + * @var string|null The exchange rate between this currency and the base currency + * (how many base units the current currency is worth) + * @ORM\Column(type="decimal", precision=11, scale=5, nullable=true) + * @Assert\Positive() */ - protected $attachments; + protected $exchange_rate; /** * @var string the 3 letter ISO code of the currency @@ -55,14 +57,6 @@ class Currency extends StructuralDBElement */ protected $iso_code; - /** - * @var string|null The exchange rate between this currency and the base currency - * (how many base units the current currency is worth) - * @ORM\Column(type="decimal", precision=11, scale=5, nullable=true) - * @Assert\Positive() - */ - protected $exchange_rate; - /** * @ORM\OneToMany(targetEntity="Currency", mappedBy="parent", cascade={"persist"}) */ @@ -74,6 +68,12 @@ class Currency extends StructuralDBElement */ protected $parent; + /** + * @var Collection|CurrencyAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\CurrencyAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; + /** * Returns the 3 letter ISO code of this currency. * diff --git a/src/Entity/PriceInformations/Orderdetail.php b/src/Entity/PriceInformations/Orderdetail.php index d73e79f7..39823ea6 100644 --- a/src/Entity/PriceInformations/Orderdetail.php +++ b/src/Entity/PriceInformations/Orderdetail.php @@ -71,21 +71,6 @@ class Orderdetail extends DBElement { use TimestampTrait; - /** - * @var Part - * @ORM\ManyToOne(targetEntity="App\Entity\Parts\Part", inversedBy="orderdetails") - * @ORM\JoinColumn(name="part_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") - * @Assert\NotNull() - */ - protected $part; - - /** - * @var Supplier - * @ORM\ManyToOne(targetEntity="App\Entity\Parts\Supplier", inversedBy="orderdetails") - * @ORM\JoinColumn(name="id_supplier", referencedColumnName="id") - */ - protected $supplier; - /** * @ORM\OneToMany(targetEntity="Pricedetail", mappedBy="orderdetail", cascade={"persist", "remove"}, orphanRemoval=true) * @Assert\Valid() @@ -112,6 +97,21 @@ class Orderdetail extends DBElement */ protected $supplier_product_url = ''; + /** + * @var Part + * @ORM\ManyToOne(targetEntity="App\Entity\Parts\Part", inversedBy="orderdetails") + * @ORM\JoinColumn(name="part_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") + * @Assert\NotNull() + */ + protected $part; + + /** + * @var Supplier + * @ORM\ManyToOne(targetEntity="App\Entity\Parts\Supplier", inversedBy="orderdetails") + * @ORM\JoinColumn(name="id_supplier", referencedColumnName="id") + */ + protected $supplier; + public function __construct() { $this->pricedetails = new ArrayCollection(); diff --git a/src/Entity/PriceInformations/Pricedetail.php b/src/Entity/PriceInformations/Pricedetail.php index be5d4276..133c5acb 100644 --- a/src/Entity/PriceInformations/Pricedetail.php +++ b/src/Entity/PriceInformations/Pricedetail.php @@ -72,14 +72,6 @@ class Pricedetail extends DBElement public const PRICE_PRECISION = 5; - /** - * @var Orderdetail - * @ORM\ManyToOne(targetEntity="Orderdetail", inversedBy="pricedetails") - * @ORM\JoinColumn(name="orderdetails_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") - * @Assert\NotNull() - */ - protected $orderdetail; - /** * @var string The price related to the detail. (Given in the selected currency) * @ORM\Column(type="decimal", precision=11, scale=5) @@ -116,6 +108,14 @@ class Pricedetail extends DBElement */ protected $manual_input = true; + /** + * @var Orderdetail + * @ORM\ManyToOne(targetEntity="Orderdetail", inversedBy="pricedetails") + * @ORM\JoinColumn(name="orderdetails_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") + * @Assert\NotNull() + */ + protected $orderdetail; + public function __construct() { bcscale(static::PRICE_PRECISION); @@ -280,6 +280,7 @@ class Pricedetail extends DBElement * quantity to 100. The single price (20$/100 = 0.2$) will be calculated automatically. * * @param float $new_price_related_quantity the price related quantity + * * @return $this */ public function setPriceRelatedQuantity(float $new_price_related_quantity): self diff --git a/src/Entity/UserSystem/Group.php b/src/Entity/UserSystem/Group.php index b209d02f..1e8fee0b 100644 --- a/src/Entity/UserSystem/Group.php +++ b/src/Entity/UserSystem/Group.php @@ -39,12 +39,6 @@ use Doctrine\ORM\Mapping as ORM; */ class Group extends StructuralDBElement implements HasPermissionsInterface { - /** - * @var Collection|GroupAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\ManufacturerAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - /** * @ORM\OneToMany(targetEntity="Group", mappedBy="parent") */ @@ -61,17 +55,22 @@ class Group extends StructuralDBElement implements HasPermissionsInterface */ protected $users; - /** @var PermissionsEmbed - * @ORM\Embedded(class="PermissionsEmbed", columnPrefix="perms_") - * @ValidPermission() - */ - protected $permissions; - /** * @var bool If true all users associated with this group must have enabled some kind of 2 factor authentication * @ORM\Column(type="boolean", name="enforce_2fa") */ protected $enforce2FA = false; + /** + * @var Collection|GroupAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\ManufacturerAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; + + /** @var PermissionsEmbed + * @ORM\Embedded(class="PermissionsEmbed", columnPrefix="perms_") + * @ValidPermission() + */ + protected $permissions; public function __construct() { diff --git a/src/Entity/UserSystem/PermissionsEmbed.php b/src/Entity/UserSystem/PermissionsEmbed.php index 1b4f39bc..3980b737 100644 --- a/src/Entity/UserSystem/PermissionsEmbed.php +++ b/src/Entity/UserSystem/PermissionsEmbed.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace App\Entity\UserSystem; use Doctrine\ORM\Mapping as ORM; +use InvalidArgumentException; use Webmozart\Assert\Assert; /** @@ -316,7 +317,7 @@ class PermissionsEmbed public function getBitValue(string $permission_name, int $bit_n): int { if (! $this->isValidPermissionName($permission_name)) { - throw new \InvalidArgumentException(sprintf('No permission with the name "%s" is existing!', $permission_name)); + throw new InvalidArgumentException(sprintf('No permission with the name "%s" is existing!', $permission_name)); } $perm_int = (int) $this->{$permission_name}; @@ -386,7 +387,7 @@ class PermissionsEmbed public function setBitValue(string $permission_name, int $bit_n, int $new_value): self { if (! $this->isValidPermissionName($permission_name)) { - throw new \InvalidArgumentException('No permission with the given name is existing!'); + throw new InvalidArgumentException('No permission with the given name is existing!'); } $this->{$permission_name} = static::writeBitPair($this->{$permission_name}, $bit_n, $new_value); @@ -405,7 +406,7 @@ class PermissionsEmbed public function getRawPermissionValue(string $permission_name): int { if (! $this->isValidPermissionName($permission_name)) { - throw new \InvalidArgumentException('No permission with the given name is existing!'); + throw new InvalidArgumentException('No permission with the given name is existing!'); } return $this->{$permission_name}; @@ -422,7 +423,7 @@ class PermissionsEmbed public function setRawPermissionValue(string $permission_name, int $value): self { if (! $this->isValidPermissionName($permission_name)) { - throw new \InvalidArgumentException(sprintf('No permission with the given name %s is existing!', $permission_name)); + throw new InvalidArgumentException(sprintf('No permission with the given name %s is existing!', $permission_name)); } $this->{$permission_name} = $value; @@ -456,7 +457,7 @@ class PermissionsEmbed * Reads a bit pair from $data. * * @param int|string $data The data from where the bits should be extracted from - * @param int $n The number of the lower bit (of the pair) that should be read. Starting from zero. + * @param int $n The number of the lower bit (of the pair) that should be read. Starting from zero. * * @return int the value of the bit pair */ @@ -464,7 +465,7 @@ class PermissionsEmbed { Assert::lessThanEq($n, 31, '$n must be smaller than 32, because only a 32bit int is used! Got %s.'); if (0 !== $n % 2) { - throw new \InvalidArgumentException('$n must be dividable by 2, because we address bit pairs here!'); + throw new InvalidArgumentException('$n must be dividable by 2, because we address bit pairs here!'); } $mask = 0b11 << $n; //Create a mask for the data @@ -487,7 +488,7 @@ class PermissionsEmbed Assert::greaterThanEq($new, 0, '$new must not be negative, because a bit pair is written! Got %s.'); if (0 !== $n % 2) { - throw new \InvalidArgumentException('$n must be dividable by 2, because we address bit pairs here!'); + throw new InvalidArgumentException('$n must be dividable by 2, because we address bit pairs here!'); } $mask = 0b11 << $n; //Mask all bits that should be written diff --git a/src/Entity/UserSystem/U2FKey.php b/src/Entity/UserSystem/U2FKey.php index 36eff11e..446692f5 100644 --- a/src/Entity/UserSystem/U2FKey.php +++ b/src/Entity/UserSystem/U2FKey.php @@ -76,13 +76,6 @@ class U2FKey implements TwoFactorKeyInterface */ protected $id; - /** - * @ORM\ManyToOne(targetEntity="App\Entity\UserSystem\User", inversedBy="u2fKeys") - * - * @var User - **/ - protected $user; - /** * @ORM\Column(type="string") * @@ -90,6 +83,13 @@ class U2FKey implements TwoFactorKeyInterface **/ protected $name; + /** + * @ORM\ManyToOne(targetEntity="App\Entity\UserSystem\User", inversedBy="u2fKeys") + * + * @var User + **/ + protected $user; + public function fromRegistrationData(Registration $data): void { $this->keyHandle = $data->keyHandle; diff --git a/src/Entity/UserSystem/User.php b/src/Entity/UserSystem/User.php index b77dee82..fe490d80 100644 --- a/src/Entity/UserSystem/User.php +++ b/src/Entity/UserSystem/User.php @@ -59,9 +59,13 @@ use App\Entity\PriceInformations\Currency; use App\Security\Interfaces\HasPermissionsInterface; use App\Validator\Constraints\Selectable; use App\Validator\Constraints\ValidPermission; +use function count; +use DateTime; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; +use Exception; +use function in_array; use R\U2FTwoFactorBundle\Model\U2F\TwoFactorInterface as U2FTwoFactorInterface; use R\U2FTwoFactorBundle\Model\U2F\TwoFactorKeyInterface; use Scheb\TwoFactorBundle\Model\BackupCodeInterface; @@ -84,7 +88,9 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe { use MasterAttachmentTrait; - /** The User id of the anonymous user */ + /** + * The User id of the anonymous user + */ public const ID_ANONYMOUS = 1; public const AVAILABLE_THEMES = ['bootstrap', 'cerulean', 'cosmo', 'cyborg', 'darkly', 'flatly', 'journal', @@ -92,79 +98,10 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe 'spacelab', 'united', 'yeti', ]; /** - * @var Collection|UserAttachment[] - * @ORM\OneToMany(targetEntity="App\Entity\Attachments\UserAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) - */ - protected $attachments; - - /** - * @ORM\Id() - * @ORM\GeneratedValue() - * @ORM\Column(type="integer") - */ - protected $id; - - /** - * @ORM\Column(type="string", length=180, unique=true) - * @Assert\NotBlank - */ - protected $name = ''; - - /** - * //@ORM\Column(type="json"). - */ - //protected $roles = []; - - /** - * @var string|null The hashed password - * @ORM\Column(type="string", nullable=true) - */ - protected $password; - - /** - * @var bool True if the user needs to change password after log in + * @var bool Determines if the user is disabled (user can not log in) * @ORM\Column(type="boolean") */ - protected $need_pw_change = true; - - /** - * @var string|null The first name of the User - * @ORM\Column(type="string", length=255, nullable=true) - */ - protected $first_name = ''; - - /** - * @var string|null The last name of the User - * @ORM\Column(type="string", length=255, nullable=true) - */ - protected $last_name = ''; - - /** - * @var string|null The department the user is working - * @ORM\Column(type="string", length=255, nullable=true) - */ - protected $department = ''; - - /** - * @var string|null The email address of the user - * @ORM\Column(type="string", length=255, nullable=true) - * @Assert\Email() - */ - protected $email = ''; - - /** - * @var string|null The language/locale the user prefers - * @ORM\Column(type="string", name="config_language", nullable=true) - * @Assert\Language() - */ - protected $language = ''; - - /** - * @var string|null The timezone the user prefers - * @ORM\Column(type="string", name="config_timezone", nullable=true) - * @Assert\Timezone() - */ - protected $timezone = ''; + protected $disabled = false; /** * @var string|null The theme @@ -173,6 +110,40 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe */ protected $theme = ''; + /** + * @var string|null The hash of a token the user must provide when he wants to reset his password. + * @ORM\Column(type="string", nullable=true) + */ + protected $pw_reset_token = null; + + /** + * @ORM\Column(type="text", name="config_instock_comment_a") + */ + protected $instock_comment_a = ''; + + /** + * @ORM\Column(type="text", name="config_instock_comment_w") + */ + protected $instock_comment_w = ''; + + /** @var int The version of the trusted device cookie. Used to invalidate all trusted device cookies at once. + * @ORM\Column(type="integer") + */ + protected $trustedDeviceCookieVersion = 0; + + /** + * @var string[]|null A list of backup codes that can be used, if the user has no access to its Google Authenticator device + * @ORM\Column(type="json") + */ + protected $backupCodes = []; + + /** + * @ORM\Id() + * @ORM\GeneratedValue() + * @ORM\Column(type="integer") + */ + protected $id; + /** * @var Group|null the group this user belongs to * @ORM\ManyToOne(targetEntity="Group", inversedBy="users", fetch="EAGER") @@ -188,25 +159,66 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe protected $googleAuthenticatorSecret; /** - * @var string[]|null A list of backup codes that can be used, if the user has no access to its Google Authenticator device - * @ORM\Column(type="json") + * @var string|null The timezone the user prefers + * @ORM\Column(type="string", name="config_timezone", nullable=true) + * @Assert\Timezone() */ - protected $backupCodes = []; + protected $timezone = ''; - /** @var \DateTime The time when the backup codes were generated - * @ORM\Column(type="datetime", nullable=true) + /** + * @var string|null The language/locale the user prefers + * @ORM\Column(type="string", name="config_language", nullable=true) + * @Assert\Language() */ - protected $backupCodesGenerationDate; + protected $language = ''; - /** @var int The version of the trusted device cookie. Used to invalidate all trusted device cookies at once. - * @ORM\Column(type="integer") + /** + * @var string|null The email address of the user + * @ORM\Column(type="string", length=255, nullable=true) + * @Assert\Email() */ - protected $trustedDeviceCookieVersion = 0; + protected $email = ''; - /** @var Collection - * @ORM\OneToMany(targetEntity="App\Entity\UserSystem\U2FKey", mappedBy="user", cascade={"REMOVE"}, orphanRemoval=true) + /** + * @var string|null The department the user is working + * @ORM\Column(type="string", length=255, nullable=true) */ - protected $u2fKeys; + protected $department = ''; + + /** + * @var string|null The last name of the User + * @ORM\Column(type="string", length=255, nullable=true) + */ + protected $last_name = ''; + + /** + * @var string|null The first name of the User + * @ORM\Column(type="string", length=255, nullable=true) + */ + protected $first_name = ''; + + /** + * @var bool True if the user needs to change password after log in + * @ORM\Column(type="boolean") + */ + protected $need_pw_change = true; + + /** + * //@ORM\Column(type="json"). + */ + //protected $roles = []; + + /** + * @var string|null The hashed password + * @ORM\Column(type="string", nullable=true) + */ + protected $password; + + /** + * @ORM\Column(type="string", length=180, unique=true) + * @Assert\NotBlank + */ + protected $name = ''; /** * @var array @@ -214,6 +226,22 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe */ protected $settings = []; + /** + * @var Collection|UserAttachment[] + * @ORM\OneToMany(targetEntity="App\Entity\Attachments\UserAttachment", mappedBy="element", cascade={"persist", "remove"}, orphanRemoval=true) + */ + protected $attachments; + + /** @var DateTime The time when the backup codes were generated + * @ORM\Column(type="datetime", nullable=true) + */ + protected $backupCodesGenerationDate; + + /** @var Collection + * @ORM\OneToMany(targetEntity="App\Entity\UserSystem\U2FKey", mappedBy="user", cascade={"REMOVE"}, orphanRemoval=true) + */ + protected $u2fKeys; + /** * @var Currency|null The currency the user wants to see prices in. * Dont use fetch=EAGER here, this will cause problems with setting the currency setting. @@ -232,33 +260,11 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe protected $permissions; /** - * @ORM\Column(type="text", name="config_instock_comment_w") - */ - protected $instock_comment_w = ''; - - /** - * @ORM\Column(type="text", name="config_instock_comment_a") - */ - protected $instock_comment_a = ''; - - /** - * @var string|null The hash of a token the user must provide when he wants to reset his password. - * @ORM\Column(type="string", nullable=true) - */ - protected $pw_reset_token = null; - - /** - * @var \DateTime The time until the password reset token is valid. + * @var DateTime The time until the password reset token is valid. * @ORM\Column(type="datetime", nullable=true) */ protected $pw_reset_expires = null; - /** - * @var bool Determines if the user is disabled (user can not log in) - * @ORM\Column(type="boolean") - */ - protected $disabled = false; - public function __construct() { parent::__construct(); @@ -466,9 +472,9 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe /** * Gets the datetime when the password reset token expires. * - * @return \DateTime + * @return DateTime */ - public function getPwResetExpires(): \DateTime + public function getPwResetExpires(): DateTime { return $this->pw_reset_expires; } @@ -478,7 +484,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setPwResetExpires(\DateTime $pw_reset_expires): self + public function setPwResetExpires(DateTime $pw_reset_expires): self { $this->pw_reset_expires = $pw_reset_expires; @@ -769,7 +775,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe */ public function isBackupCode(string $code): bool { - return \in_array($code, $this->backupCodes, true); + return in_array($code, $this->backupCodes, true); } /** @@ -802,7 +808,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return $this * - * @throws \Exception If an error with the datetime occurs + * @throws Exception If an error with the datetime occurs */ public function setBackupCodes(array $codes): self { @@ -810,7 +816,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe if (empty($codes)) { $this->backupCodesGenerationDate = null; } else { - $this->backupCodesGenerationDate = new \DateTime(); + $this->backupCodesGenerationDate = new DateTime(); } return $this; @@ -819,9 +825,9 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe /** * Return the date when the backup codes were generated. * - * @return \DateTime|null + * @return DateTime|null */ - public function getBackupCodesGenerationDate(): ?\DateTime + public function getBackupCodesGenerationDate(): ?DateTime { return $this->backupCodesGenerationDate; } @@ -852,7 +858,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe */ public function isU2FAuthEnabled(): bool { - return \count($this->u2fKeys) > 0; + return count($this->u2fKeys) > 0; } /** diff --git a/src/EntityListeners/AttachmentDeleteListener.php b/src/EntityListeners/AttachmentDeleteListener.php index 459db6f9..e8c240d5 100644 --- a/src/EntityListeners/AttachmentDeleteListener.php +++ b/src/EntityListeners/AttachmentDeleteListener.php @@ -32,6 +32,7 @@ use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Event\PreUpdateEventArgs; use Doctrine\ORM\Mapping\PostRemove; use Doctrine\ORM\Mapping\PreUpdate; +use SplFileInfo; /** * This listener watches for changes on attachments and deletes the files associated with an attachment, that are not @@ -63,7 +64,7 @@ class AttachmentDeleteListener return; } - $file = new \SplFileInfo($this->pathResolver->placeholderToRealPath($event->getOldValue('path'))); + $file = new SplFileInfo($this->pathResolver->placeholderToRealPath($event->getOldValue('path'))); $this->attachmentReverseSearch->deleteIfNotUsed($file); } } diff --git a/src/EntityListeners/TreeCacheInvalidationListener.php b/src/EntityListeners/TreeCacheInvalidationListener.php index 764c5961..813029ef 100644 --- a/src/EntityListeners/TreeCacheInvalidationListener.php +++ b/src/EntityListeners/TreeCacheInvalidationListener.php @@ -31,6 +31,7 @@ use App\Entity\UserSystem\User; use App\Services\UserCacheKeyGenerator; use Doctrine\ORM\Event\LifecycleEventArgs; use Doctrine\ORM\Mapping as ORM; +use function get_class; use Symfony\Contracts\Cache\TagAwareCacheInterface; class TreeCacheInvalidationListener @@ -53,7 +54,7 @@ class TreeCacheInvalidationListener { //If an element was changed, then invalidate all cached trees with this element class if ($element instanceof StructuralDBElement) { - $secure_class_name = str_replace('\\', '_', \get_class($element)); + $secure_class_name = str_replace('\\', '_', get_class($element)); $this->cache->invalidateTags([$secure_class_name]); } diff --git a/src/EventSubscriber/LoginSuccessListener.php b/src/EventSubscriber/LoginSuccessListener.php index b1f4ac4b..3aa57029 100644 --- a/src/EventSubscriber/LoginSuccessListener.php +++ b/src/EventSubscriber/LoginSuccessListener.php @@ -33,7 +33,7 @@ use Symfony\Contracts\Translation\TranslatorInterface; /** * This event listener shows an login successful flash to the user after login. */ -class LoginSuccessListener implements EventSubscriberInterface +final class LoginSuccessListener implements EventSubscriberInterface { protected $translator; protected $flashBag; diff --git a/src/EventSubscriber/LogoutOnDisabledUserListener.php b/src/EventSubscriber/LogoutOnDisabledUserListener.php index 73cb8949..81b152a4 100644 --- a/src/EventSubscriber/LogoutOnDisabledUserListener.php +++ b/src/EventSubscriber/LogoutOnDisabledUserListener.php @@ -32,7 +32,7 @@ use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Security\Core\Security; -class LogoutOnDisabledUserListener implements EventSubscriberInterface +final class LogoutOnDisabledUserListener implements EventSubscriberInterface { protected $security; protected $translator; diff --git a/src/EventSubscriber/MailFromListener.php b/src/EventSubscriber/MailFromListener.php index 3843b3eb..b8021219 100644 --- a/src/EventSubscriber/MailFromListener.php +++ b/src/EventSubscriber/MailFromListener.php @@ -29,7 +29,7 @@ use Symfony\Component\Mailer\Event\MessageEvent; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; -class MailFromListener implements EventSubscriberInterface +final class MailFromListener implements EventSubscriberInterface { protected $email; protected $name; diff --git a/src/EventSubscriber/PasswordChangeNeededSubscriber.php b/src/EventSubscriber/PasswordChangeNeededSubscriber.php index 9dfcfcc7..52b8b735 100644 --- a/src/EventSubscriber/PasswordChangeNeededSubscriber.php +++ b/src/EventSubscriber/PasswordChangeNeededSubscriber.php @@ -37,7 +37,7 @@ use Symfony\Component\Security\Http\HttpUtils; * to setup a 2FA method (enforcement can be set per group). * In this cases the user is unable to access sites other than the whitelisted (see ALLOWED_ROUTES). */ -class PasswordChangeNeededSubscriber implements EventSubscriberInterface +final class PasswordChangeNeededSubscriber implements EventSubscriberInterface { /** * @var string[] The routes the user is allowed to access without being redirected. @@ -51,7 +51,9 @@ class PasswordChangeNeededSubscriber implements EventSubscriberInterface 'logout', ]; - /** @var string The route the user will redirected to, if he needs to change this password */ + /** + * @var string The route the user will redirected to, if he needs to change this password + */ public const REDIRECT_TARGET = 'user_settings'; protected $security; protected $flashBag; diff --git a/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php b/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php index 0797bbfb..12a5f979 100644 --- a/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php +++ b/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php @@ -28,7 +28,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; -class SymfonyDebugToolbarSubscriber implements EventSubscriberInterface +final class SymfonyDebugToolbarSubscriber implements EventSubscriberInterface { protected $kernel; diff --git a/src/EventSubscriber/TimezoneListener.php b/src/EventSubscriber/TimezoneListener.php index 9a237351..d5abb465 100644 --- a/src/EventSubscriber/TimezoneListener.php +++ b/src/EventSubscriber/TimezoneListener.php @@ -33,7 +33,7 @@ use Symfony\Component\Security\Core\Security; /** * The purpose of this event listener is to set the timezone to the one preferred by the user. */ -class TimezoneListener implements EventSubscriberInterface +final class TimezoneListener implements EventSubscriberInterface { protected $default_timezone; protected $security; diff --git a/src/EventSubscriber/U2FRegistrationSubscriber.php b/src/EventSubscriber/U2FRegistrationSubscriber.php index 263e1093..2748fe47 100644 --- a/src/EventSubscriber/U2FRegistrationSubscriber.php +++ b/src/EventSubscriber/U2FRegistrationSubscriber.php @@ -32,13 +32,15 @@ use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -class U2FRegistrationSubscriber implements EventSubscriberInterface +final class U2FRegistrationSubscriber implements EventSubscriberInterface { protected $em; protected $demo_mode; protected $flashBag; - /** @var UrlGeneratorInterface */ + /** + * @var UrlGeneratorInterface + */ private $router; public function __construct(UrlGeneratorInterface $router, EntityManagerInterface $entityManager, FlashBagInterface $flashBag, bool $demo_mode) @@ -49,7 +51,9 @@ class U2FRegistrationSubscriber implements EventSubscriberInterface $this->flashBag = $flashBag; } - /** @return string[] **/ + /** + * + */ public static function getSubscribedEvents(): array { return [ diff --git a/src/Exceptions/AttachmentDownloadException.php b/src/Exceptions/AttachmentDownloadException.php index f29f94d7..4c681f04 100644 --- a/src/Exceptions/AttachmentDownloadException.php +++ b/src/Exceptions/AttachmentDownloadException.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace App\Exceptions; -class AttachmentDownloadException extends \RuntimeException +use RuntimeException; + +class AttachmentDownloadException extends RuntimeException { } diff --git a/src/Exceptions/EntityNotSupportedException.php b/src/Exceptions/EntityNotSupportedException.php index 2875ee31..3e5b3dea 100644 --- a/src/Exceptions/EntityNotSupportedException.php +++ b/src/Exceptions/EntityNotSupportedException.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace App\Exceptions; -class EntityNotSupportedException extends \InvalidArgumentException +use InvalidArgumentException; + +class EntityNotSupportedException extends InvalidArgumentException { } diff --git a/src/Form/AdminPages/AttachmentTypeAdminForm.php b/src/Form/AdminPages/AttachmentTypeAdminForm.php index 622efea7..14c6d91c 100644 --- a/src/Form/AdminPages/AttachmentTypeAdminForm.php +++ b/src/Form/AdminPages/AttachmentTypeAdminForm.php @@ -46,12 +46,16 @@ class AttachmentTypeAdminForm extends BaseEntityAdminForm { $is_new = null === $entity->getID(); - $builder->add('filetype_filter', TextType::class, ['required' => false, + $builder->add('filetype_filter', TextType::class, [ + 'required' => false, 'label' => 'attachment_type.edit.filetype_filter', 'help' => 'attachment_type.edit.filetype_filter.help', - 'attr' => ['placeholder' => 'attachment_type.edit.filetype_filter.placeholder'], + 'attr' => [ + 'placeholder' => 'attachment_type.edit.filetype_filter.placeholder', + ], 'empty_data' => '', - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); //Normalize data before writing it to database $builder->get('filetype_filter')->addViewTransformer(new CallbackTransformer( diff --git a/src/Form/AdminPages/BaseEntityAdminForm.php b/src/Form/AdminPages/BaseEntityAdminForm.php index 79bfeda8..feff6641 100644 --- a/src/Form/AdminPages/BaseEntityAdminForm.php +++ b/src/Form/AdminPages/BaseEntityAdminForm.php @@ -31,6 +31,7 @@ use App\Form\AttachmentFormType; use App\Form\Type\MasterPictureAttachmentType; use App\Form\Type\StructuralEntityType; use FOS\CKEditorBundle\Form\Type\CKEditorType; +use function get_class; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; @@ -66,24 +67,42 @@ class BaseEntityAdminForm extends AbstractType $is_new = null === $entity->getID(); $builder - ->add('name', TextType::class, ['empty_data' => '', 'label' => 'name.label', - 'attr' => ['placeholder' => 'part.name.placeholder'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]) + ->add('name', TextType::class, [ + 'empty_data' => '', + 'label' => 'name.label', + 'attr' => [ + 'placeholder' => 'part.name.placeholder', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]) - ->add('parent', StructuralEntityType::class, ['class' => \get_class($entity), - 'required' => false, 'label' => 'parent.label', - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), ]) + ->add('parent', StructuralEntityType::class, [ + 'class' => get_class($entity), + 'required' => false, + 'label' => 'parent.label', + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), + ]) - ->add('not_selectable', CheckboxType::class, ['required' => false, + ->add('not_selectable', CheckboxType::class, [ + 'required' => false, 'label' => 'entity.edit.not_selectable', 'help' => 'entity.edit.not_selectable.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]) + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]) - ->add('comment', CKEditorType::class, ['required' => false, 'empty_data' => '', + ->add('comment', CKEditorType::class, [ + 'required' => false, + 'empty_data' => '', 'label' => 'comment.label', - 'attr' => ['rows' => 4], 'help' => 'bbcode.hint', - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'rows' => 4, + ], + 'help' => 'bbcode.hint', + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); $this->additionalFormElements($builder, $options, $entity); @@ -110,10 +129,15 @@ class BaseEntityAdminForm extends AbstractType //Buttons $builder->add('save', SubmitType::class, [ 'label' => $is_new ? 'entity.create' : 'entity.edit.save', - 'attr' => ['class' => $is_new ? 'btn-success' : ''], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]) - ->add('reset', ResetType::class, ['label' => 'entity.edit.reset', - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'class' => $is_new ? 'btn-success' : '', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]) + ->add('reset', ResetType::class, [ + 'label' => 'entity.edit.reset', + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); } protected function additionalFormElements(FormBuilderInterface $builder, array $options, NamedDBElement $entity): void diff --git a/src/Form/AdminPages/CategoryAdminForm.php b/src/Form/AdminPages/CategoryAdminForm.php index 873c07ed..1327ea56 100644 --- a/src/Form/AdminPages/CategoryAdminForm.php +++ b/src/Form/AdminPages/CategoryAdminForm.php @@ -35,48 +35,84 @@ class CategoryAdminForm extends BaseEntityAdminForm { $is_new = null === $entity->getID(); - $builder->add('disable_footprints', CheckboxType::class, ['required' => false, + $builder->add('disable_footprints', CheckboxType::class, [ + 'required' => false, 'label' => 'category.edit.disable_footprints', 'help' => 'category.edit.disable_footprints.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('disable_manufacturers', CheckboxType::class, ['required' => false, + $builder->add('disable_manufacturers', CheckboxType::class, [ + 'required' => false, 'label' => 'category.edit.disable_manufacturers', 'help' => 'category.edit.disable_manufacturers.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('disable_autodatasheets', CheckboxType::class, ['required' => false, + $builder->add('disable_autodatasheets', CheckboxType::class, [ + 'required' => false, 'label' => 'category.edit.disable_autodatasheets', 'help' => 'category.edit.disable_autodatasheets.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('disable_properties', CheckboxType::class, ['required' => false, + $builder->add('disable_properties', CheckboxType::class, [ + 'required' => false, 'label' => 'category.edit.disable_properties', 'help' => 'category.edit.disable_properties.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('partname_hint', TextType::class, ['required' => false, 'empty_data' => '', + $builder->add('partname_hint', TextType::class, [ + 'required' => false, + 'empty_data' => '', 'label' => 'category.edit.partname_hint', - 'attr' => ['placeholder' => 'category.edit.partname_hint.placeholder'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'placeholder' => 'category.edit.partname_hint.placeholder', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('partname_regex', TextType::class, ['required' => false, 'empty_data' => '', + $builder->add('partname_regex', TextType::class, [ + 'required' => false, + 'empty_data' => '', 'label' => 'category.edit.partname_regex', - 'attr' => ['placeholder' => 'category.edit.partname_regex.placeholder'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'placeholder' => 'category.edit.partname_regex.placeholder', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('default_description', TextType::class, ['required' => false, 'empty_data' => '', + $builder->add('default_description', TextType::class, [ + 'required' => false, + 'empty_data' => '', 'label' => 'category.edit.default_description', - 'attr' => ['placeholder' => 'category.edit.default_description.placeholder'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'placeholder' => 'category.edit.default_description.placeholder', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('default_comment', TextType::class, ['required' => false, 'empty_data' => '', + $builder->add('default_comment', TextType::class, [ + 'required' => false, + 'empty_data' => '', 'label' => 'category.edit.default_comment', - 'attr' => ['placeholder' => 'category.edit.default_comment.placeholder'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'placeholder' => 'category.edit.default_comment.placeholder', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); } } diff --git a/src/Form/AdminPages/CompanyForm.php b/src/Form/AdminPages/CompanyForm.php index adc3ddac..cd568f43 100644 --- a/src/Form/AdminPages/CompanyForm.php +++ b/src/Form/AdminPages/CompanyForm.php @@ -40,14 +40,19 @@ class CompanyForm extends BaseEntityAdminForm $builder->add('address', TextareaType::class, [ 'label' => 'company.edit.address', 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), - 'attr' => ['placeholder' => 'company.edit.address.placeholder'], 'required' => false, + 'attr' => [ + 'placeholder' => 'company.edit.address.placeholder', + ], + 'required' => false, 'empty_data' => '', ]); $builder->add('phone_number', TelType::class, [ 'label' => 'company.edit.phone_number', 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), - 'attr' => ['placeholder' => 'company.edit.phone_number.placeholder'], + 'attr' => [ + 'placeholder' => 'company.edit.phone_number.placeholder', + ], 'required' => false, 'empty_data' => '', ]); @@ -55,21 +60,30 @@ class CompanyForm extends BaseEntityAdminForm $builder->add('fax_number', TelType::class, [ 'label' => 'company.edit.fax_number', 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), - 'attr' => ['placeholder' => 'company.fax_number.placeholder'], 'required' => false, + 'attr' => [ + 'placeholder' => 'company.fax_number.placeholder', + ], + 'required' => false, 'empty_data' => '', ]); $builder->add('email_address', EmailType::class, [ 'label' => 'company.edit.email', 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), - 'attr' => ['placeholder' => 'company.edit.email.placeholder'], 'required' => false, + 'attr' => [ + 'placeholder' => 'company.edit.email.placeholder', + ], + 'required' => false, 'empty_data' => '', ]); $builder->add('website', UrlType::class, [ 'label' => 'company.edit.website', 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), - 'attr' => ['placeholder' => 'company.edit.website.placeholder'], 'required' => false, + 'attr' => [ + 'placeholder' => 'company.edit.website.placeholder', + ], + 'required' => false, 'empty_data' => '', ]); @@ -77,7 +91,9 @@ class CompanyForm extends BaseEntityAdminForm 'label' => 'company.edit.auto_product_url', 'help' => 'company.edit.auto_product_url.help', 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), - 'attr' => ['placeholder' => 'company.edit.auto_product_url.placeholder'], + 'attr' => [ + 'placeholder' => 'company.edit.auto_product_url.placeholder', + ], 'required' => false, 'empty_data' => '', ]); diff --git a/src/Form/AdminPages/CurrencyAdminForm.php b/src/Form/AdminPages/CurrencyAdminForm.php index 5cd5353b..a8c47d7a 100644 --- a/src/Form/AdminPages/CurrencyAdminForm.php +++ b/src/Form/AdminPages/CurrencyAdminForm.php @@ -39,14 +39,19 @@ class CurrencyAdminForm extends BaseEntityAdminForm 'required' => false, 'label' => 'currency.edit.iso_code', 'preferred_choices' => ['EUR', 'USD', 'GBP', 'JPY', 'CNY'], - 'attr' => ['class' => 'selectpicker', 'data-live-search' => true], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'class' => 'selectpicker', + 'data-live-search' => true, + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); $builder->add('exchange_rate', MoneyType::class, [ 'required' => false, 'label' => 'currency.edit.exchange_rate', 'currency' => $this->params->get('default_currency'), 'scale' => 6, - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); } } diff --git a/src/Form/AdminPages/GroupAdminForm.php b/src/Form/AdminPages/GroupAdminForm.php index a489d2f9..6a3a2f31 100644 --- a/src/Form/AdminPages/GroupAdminForm.php +++ b/src/Form/AdminPages/GroupAdminForm.php @@ -35,10 +35,13 @@ class GroupAdminForm extends BaseEntityAdminForm { $is_new = null === $entity->getID(); - $builder->add('enforce2FA', CheckboxType::class, ['required' => false, + $builder->add('enforce2FA', CheckboxType::class, [ + 'required' => false, 'label' => 'group.edit.enforce_2fa', 'help' => 'entity.edit.enforce_2fa.help', - 'label_attr' => ['class' => 'checkbox-custom'], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); diff --git a/src/Form/AdminPages/ImportType.php b/src/Form/AdminPages/ImportType.php index 3f6e7bd7..27f8c99a 100644 --- a/src/Form/AdminPages/ImportType.php +++ b/src/Form/AdminPages/ImportType.php @@ -56,12 +56,20 @@ class ImportType extends AbstractType $builder ->add('format', ChoiceType::class, [ - 'choices' => ['JSON' => 'json', 'XML' => 'xml', 'CSV' => 'csv', 'YAML' => 'yaml'], + 'choices' => [ + 'JSON' => 'json', + 'XML' => 'xml', + 'CSV' => 'csv', + 'YAML' => 'yaml', + ], 'label' => 'export.format', - 'disabled' => $disabled, ]) - ->add('csv_separator', TextType::class, ['data' => ';', + 'disabled' => $disabled, + ]) + ->add('csv_separator', TextType::class, [ + 'data' => ';', 'label' => 'import.csv_separator', - 'disabled' => $disabled, ]); + 'disabled' => $disabled, + ]); if ($entity instanceof StructuralDBElement) { $builder->add('parent', StructuralEntityType::class, [ @@ -74,19 +82,38 @@ class ImportType extends AbstractType $builder->add('file', FileType::class, [ 'label' => 'import.file', - 'attr' => ['class' => 'file', 'data-show-preview' => 'false', 'data-show-upload' => 'false'], + 'attr' => [ + 'class' => 'file', + 'data-show-preview' => 'false', + 'data-show-upload' => 'false', + ], 'disabled' => $disabled, ]) - ->add('preserve_children', CheckboxType::class, ['data' => true, 'required' => false, + ->add('preserve_children', CheckboxType::class, [ + 'data' => true, + 'required' => false, 'label' => 'import.preserve_children', - 'label_attr' => ['class' => 'checkbox-custom'], 'disabled' => $disabled, ]) - ->add('abort_on_validation_error', CheckboxType::class, ['data' => true, 'required' => false, + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => $disabled, + ]) + ->add('abort_on_validation_error', CheckboxType::class, [ + 'data' => true, + 'required' => false, 'label' => 'import.abort_on_validation', 'help' => 'import.abort_on_validation.help', - 'label_attr' => ['class' => 'checkbox-custom'], 'disabled' => $disabled, ]) + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => $disabled, + ]) //Buttons - ->add('import', SubmitType::class, ['label' => 'import.btn', 'disabled' => $disabled]); + ->add('import', SubmitType::class, [ + 'label' => 'import.btn', + 'disabled' => $disabled, + ]); } } diff --git a/src/Form/AdminPages/MassCreationForm.php b/src/Form/AdminPages/MassCreationForm.php index 06a54912..076773ef 100644 --- a/src/Form/AdminPages/MassCreationForm.php +++ b/src/Form/AdminPages/MassCreationForm.php @@ -51,9 +51,11 @@ class MassCreationForm extends AbstractType $disabled = ! $this->security->isGranted($perm_name, $entity); $builder - ->add('lines', TextareaType::class, ['data' => '', + ->add('lines', TextareaType::class, [ + 'data' => '', 'label' => 'mass_creation.lines', - 'disabled' => $disabled, 'required' => true, + 'disabled' => $disabled, + 'required' => true, 'attr' => [ 'placeholder' => 'mass_creation.lines.placeholder', 'rows' => 10, @@ -64,7 +66,8 @@ class MassCreationForm extends AbstractType 'class' => $data['entity_class'], 'required' => false, 'label' => 'parent.label', - 'disabled' => $disabled, ]); + 'disabled' => $disabled, + ]); } //Buttons diff --git a/src/Form/AdminPages/MeasurementUnitAdminForm.php b/src/Form/AdminPages/MeasurementUnitAdminForm.php index 61e42c7d..affabe18 100644 --- a/src/Form/AdminPages/MeasurementUnitAdminForm.php +++ b/src/Form/AdminPages/MeasurementUnitAdminForm.php @@ -35,21 +35,33 @@ class MeasurementUnitAdminForm extends BaseEntityAdminForm { $is_new = null === $entity->getID(); - $builder->add('is_integer', CheckboxType::class, ['required' => false, + $builder->add('is_integer', CheckboxType::class, [ + 'required' => false, 'label' => 'measurement_unit.edit.is_integer', 'help' => 'measurement_unit.edit.is_integer.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('use_si_prefix', CheckboxType::class, ['required' => false, + $builder->add('use_si_prefix', CheckboxType::class, [ + 'required' => false, 'label' => 'measurement_unit.edit.use_si_prefix', 'help' => 'measurement_unit.edit.use_si_prefix.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); - $builder->add('unit', TextType::class, ['required' => false, + $builder->add('unit', TextType::class, [ + 'required' => false, 'label' => 'measurement_unit.edit.unit_symbol', - 'attr' => ['placeholder' => 'measurement_unit.edit.unit_symbol.placeholder'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); + 'attr' => [ + 'placeholder' => 'measurement_unit.edit.unit_symbol.placeholder', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'edit', $entity), + ]); } } diff --git a/src/Form/AdminPages/StorelocationAdminForm.php b/src/Form/AdminPages/StorelocationAdminForm.php index 19c67d81..29f1b420 100644 --- a/src/Form/AdminPages/StorelocationAdminForm.php +++ b/src/Form/AdminPages/StorelocationAdminForm.php @@ -40,28 +40,39 @@ class StorelocationAdminForm extends BaseEntityAdminForm 'required' => false, 'label' => 'storelocation.edit.is_full.label', 'help' => 'storelocation.edit.is_full.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), + ]); $builder->add('limit_to_existing_parts', CheckboxType::class, [ 'required' => false, 'label' => 'storelocation.limit_to_existing.label', 'help' => 'storelocation.limit_to_existing.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), + ]); $builder->add('only_single_part', CheckboxType::class, [ 'required' => false, 'label' => 'storelocation.only_single_part.label', 'help' => 'storelocation.only_single_part.help', - 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), + ]); $builder->add('storage_type', StructuralEntityType::class, [ 'required' => false, 'label' => 'storelocation.storage_type.label', 'help' => 'storelocation.storage_type.help', - 'class' => MeasurementUnit::class, 'disable_not_selectable' => true, - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); + 'class' => MeasurementUnit::class, + 'disable_not_selectable' => true, + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), + ]); } } diff --git a/src/Form/AdminPages/SupplierForm.php b/src/Form/AdminPages/SupplierForm.php index d56006f8..2210e7c6 100644 --- a/src/Form/AdminPages/SupplierForm.php +++ b/src/Form/AdminPages/SupplierForm.php @@ -43,7 +43,8 @@ class SupplierForm extends CompanyForm 'required' => false, 'label' => 'supplier.edit.default_currency', 'disable_not_selectable' => true, - 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); + 'disabled' => ! $this->security->isGranted($is_new ? 'create' : 'move', $entity), + ]); $builder->add('shipping_costs', MoneyType::class, [ 'required' => false, diff --git a/src/Form/AttachmentFormType.php b/src/Form/AttachmentFormType.php index f1547a00..df9ca8ca 100644 --- a/src/Form/AttachmentFormType.php +++ b/src/Form/AttachmentFormType.php @@ -65,20 +65,34 @@ class AttachmentFormType extends AbstractType 'label' => 'attachment.edit.attachment_type', 'class' => AttachmentType::class, 'disable_not_selectable' => true, - 'attr' => ['class' => 'attachment_type_selector'], + 'attr' => [ + 'class' => 'attachment_type_selector', + ], ]); - $builder->add('showInTable', CheckboxType::class, ['required' => false, + $builder->add('showInTable', CheckboxType::class, [ + 'required' => false, 'label' => 'attachment.edit.show_in_table', - 'attr' => ['class' => 'form-control-sm'], - 'label_attr' => ['class' => 'checkbox-custom'], ]); + 'attr' => [ + 'class' => 'form-control-sm', + ], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + ]); - $builder->add('secureFile', CheckboxType::class, ['required' => false, + $builder->add('secureFile', CheckboxType::class, [ + 'required' => false, 'label' => 'attachment.edit.secure_file', 'mapped' => false, - 'attr' => ['class' => 'form-control-sm'], + 'attr' => [ + 'class' => 'form-control-sm', + ], 'help' => 'attachment.edit.secure_file.help', - 'label_attr' => ['class' => 'checkbox-custom'], ]); + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + ]); $builder->add('url', TextType::class, [ 'label' => 'attachment.edit.url', @@ -94,18 +108,28 @@ class AttachmentFormType extends AbstractType ], ]); - $builder->add('downloadURL', CheckboxType::class, ['required' => false, + $builder->add('downloadURL', CheckboxType::class, [ + 'required' => false, 'label' => 'attachment.edit.download_url', 'mapped' => false, 'disabled' => ! $this->allow_attachments_download, - 'attr' => ['class' => 'form-control-sm'], - 'label_attr' => ['class' => 'checkbox-custom'], ]); + 'attr' => [ + 'class' => 'form-control-sm', + ], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], + ]); $builder->add('file', FileType::class, [ 'label' => 'attachment.edit.file', 'mapped' => false, 'required' => false, - 'attr' => ['class' => 'file', 'data-show-preview' => 'false', 'data-show-upload' => 'false'], + 'attr' => [ + 'class' => 'file', + 'data-show-preview' => 'false', + 'data-show-upload' => 'false', + ], 'constraints' => [ new AllowedFileExtension(), new File([ diff --git a/src/Form/Part/OrderdetailType.php b/src/Form/Part/OrderdetailType.php index e2db6890..757c3983 100644 --- a/src/Form/Part/OrderdetailType.php +++ b/src/Form/Part/OrderdetailType.php @@ -56,13 +56,16 @@ class OrderdetailType extends AbstractType $builder->add('supplierpartnr', TextType::class, [ 'label' => 'orderdetails.edit.supplierpartnr', - 'attr' => ['placeholder' => 'orderdetails.edit.supplierpartnr.placeholder'], + 'attr' => [ + 'placeholder' => 'orderdetails.edit.supplierpartnr.placeholder', + ], 'required' => false, 'empty_data' => '', ]); $builder->add('supplier', StructuralEntityType::class, [ - 'class' => Supplier::class, 'disable_not_selectable' => true, + 'class' => Supplier::class, + 'disable_not_selectable' => true, 'label' => 'orderdetails.edit.supplier', ]); @@ -74,7 +77,9 @@ class OrderdetailType extends AbstractType $builder->add('obsolete', CheckboxType::class, [ 'required' => false, - 'label_attr' => ['class' => 'checkbox-custom'], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], 'label' => 'orderdetails.edit.obsolete', ]); diff --git a/src/Form/Part/PartBaseType.php b/src/Form/Part/PartBaseType.php index 7e7908aa..652cb33f 100644 --- a/src/Form/Part/PartBaseType.php +++ b/src/Form/Part/PartBaseType.php @@ -81,7 +81,9 @@ class PartBaseType extends AbstractType ->add('name', TextType::class, [ 'empty_data' => '', 'label' => 'part.edit.name', - 'attr' => ['placeholder' => 'part.edit.name.placeholder'], + 'attr' => [ + 'placeholder' => 'part.edit.name.placeholder', + ], 'disabled' => ! $this->security->isGranted('name.edit', $part), ]) ->add('description', CKEditorType::class, [ @@ -89,11 +91,17 @@ class PartBaseType extends AbstractType 'empty_data' => '', 'label' => 'part.edit.description', 'config_name' => 'description_config', - 'attr' => ['placeholder' => 'part.edit.description.placeholder', 'rows' => 2], + 'attr' => [ + 'placeholder' => 'part.edit.description.placeholder', + 'rows' => 2, + ], 'disabled' => ! $this->security->isGranted('description.edit', $part), ]) ->add('minAmount', SIUnitType::class, [ - 'attr' => ['min' => 0, 'placeholder' => 'part.editmininstock.placeholder'], + 'attr' => [ + 'min' => 0, + 'placeholder' => 'part.editmininstock.placeholder', + ], 'label' => 'part.edit.mininstock', 'measurement_unit' => $part->getPartUnit(), 'disabled' => ! $this->security->isGranted('minamount.edit', $part), @@ -117,7 +125,8 @@ class PartBaseType extends AbstractType 'empty_data' => '', 'attr' => [ 'class' => 'tagsinput', - 'data-autocomplete' => $this->urlGenerator->generate('typeahead_tags', ['query' => 'QUERY']), ], + 'data-autocomplete' => $this->urlGenerator->generate('typeahead_tags', ['query' => 'QUERY']), + ], 'disabled' => ! $this->security->isGranted('tags.edit', $part), ]); @@ -139,7 +148,8 @@ class PartBaseType extends AbstractType 'required' => false, 'empty_data' => '', 'label' => 'part.edit.mpn', - 'disabled' => ! $this->security->isGranted('mpn.edit', $part), ]) + 'disabled' => ! $this->security->isGranted('mpn.edit', $part), + ]) ->add('manufacturing_status', ChoiceType::class, [ 'label' => 'part.edit.manufacturing_status', 'choices' => $status_choices, @@ -149,13 +159,17 @@ class PartBaseType extends AbstractType //Advanced section $builder->add('needsReview', CheckboxType::class, [ - 'label_attr' => ['class' => 'checkbox-custom'], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], 'required' => false, 'label' => 'part.edit.needs_review', 'disabled' => ! $this->security->isGranted('edit', $part), ]) ->add('favorite', CheckboxType::class, [ - 'label_attr' => ['class' => 'checkbox-custom'], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], 'required' => false, 'label' => 'part.edit.is_favorite', 'disabled' => ! $this->security->isGranted('change_favorite', $part), @@ -178,8 +192,11 @@ class PartBaseType extends AbstractType $builder->add('comment', CKEditorType::class, [ 'required' => false, 'label' => 'part.edit.comment', - 'attr' => ['rows' => 4], - 'disabled' => ! $this->security->isGranted('comment.edit', $part), 'empty_data' => '', + 'attr' => [ + 'rows' => 4, + ], + 'disabled' => ! $this->security->isGranted('comment.edit', $part), + 'empty_data' => '', ]); //Part Lots section diff --git a/src/Form/Part/PartLotType.php b/src/Form/Part/PartLotType.php index 229c600b..a395bca6 100644 --- a/src/Form/Part/PartLotType.php +++ b/src/Form/Part/PartLotType.php @@ -52,43 +52,65 @@ class PartLotType extends AbstractType 'label' => 'part_lot.edit.description', 'required' => false, 'empty_data' => '', - 'attr' => ['class' => 'form-control-sm'], + 'attr' => [ + 'class' => 'form-control-sm', + ], ]); - $builder->add('storage_location', StructuralEntityType::class, ['class' => Storelocation::class, + $builder->add('storage_location', StructuralEntityType::class, [ + 'class' => Storelocation::class, 'label' => 'part_lot.edit.location', 'required' => false, 'disable_not_selectable' => true, - 'attr' => ['class' => 'selectpicker form-control-sm', 'data-live-search' => true], + 'attr' => [ + 'class' => 'selectpicker form-control-sm', + 'data-live-search' => true, + ], ]); $builder->add('amount', SIUnitType::class, [ 'measurement_unit' => $options['measurement_unit'], 'label' => 'part_lot.edit.amount', - 'attr' => ['class' => 'form-control-sm'], + 'attr' => [ + 'class' => 'form-control-sm', + ], ]); - $builder->add('instock_unknown', CheckboxType::class, ['required' => false, + $builder->add('instock_unknown', CheckboxType::class, [ + 'required' => false, 'label' => 'part_lot.edit.instock_unknown', - 'attr' => ['class' => 'form-control-sm'], - 'label_attr' => ['class' => 'checkbox-custom'], + 'attr' => [ + 'class' => 'form-control-sm', + ], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], ]); - $builder->add('needs_refill', CheckboxType::class, ['label_attr' => ['class' => 'checkbox-custom'], + $builder->add('needs_refill', CheckboxType::class, [ + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], 'label' => 'part_lot.edit.needs_refill', - 'attr' => ['class' => 'form-control-sm'], + 'attr' => [ + 'class' => 'form-control-sm', + ], 'required' => false, ]); $builder->add('expirationDate', DateTimeType::class, [ 'label' => 'part_lot.edit.expiration_date', 'attr' => [], - 'required' => false, ]); + 'required' => false, + ]); $builder->add('comment', TextType::class, [ 'label' => 'part_lot.edit.comment', - 'attr' => ['class' => 'form-control-sm'], - 'required' => false, 'empty_data' => '', + 'attr' => [ + 'class' => 'form-control-sm', + ], + 'required' => false, + 'empty_data' => '', ]); } diff --git a/src/Form/Part/PricedetailType.php b/src/Form/Part/PricedetailType.php index 57c89445..58052e18 100644 --- a/src/Form/Part/PricedetailType.php +++ b/src/Form/Part/PricedetailType.php @@ -41,18 +41,25 @@ class PricedetailType extends AbstractType $builder->add('min_discount_quantity', SIUnitType::class, [ 'label' => false, 'measurement_unit' => $options['measurement_unit'], - 'attr' => ['class' => 'form-control-sm'], + 'attr' => [ + 'class' => 'form-control-sm', + ], ]); $builder->add('price_related_quantity', SIUnitType::class, [ 'label' => false, 'measurement_unit' => $options['measurement_unit'], - 'attr' => ['class' => 'form-control-sm'], + 'attr' => [ + 'class' => 'form-control-sm', + ], ]); $builder->add('price', NumberType::class, [ 'label' => false, 'scale' => 5, 'html5' => true, - 'attr' => ['min' => 0, 'step' => 'any'], + 'attr' => [ + 'min' => 0, + 'step' => 'any', + ], ]); $builder->add('currency', CurrencyEntityType::class, [ 'required' => false, diff --git a/src/Form/Permissions/PermissionsMapper.php b/src/Form/Permissions/PermissionsMapper.php index 91b2157b..f77beceb 100644 --- a/src/Form/Permissions/PermissionsMapper.php +++ b/src/Form/Permissions/PermissionsMapper.php @@ -25,14 +25,16 @@ declare(strict_types=1); namespace App\Form\Permissions; use App\Services\PermissionResolver; +use RuntimeException; use Symfony\Component\Form\DataMapperInterface; use Symfony\Component\Form\FormInterface; +use Traversable; /** * This class is a data mapper that maps the permission data from DB (accessed via a PermissionResolver), * to TristateCheckboxes and vice versa. */ -class PermissionsMapper implements DataMapperInterface +final class PermissionsMapper implements DataMapperInterface { protected $resolver; protected $inherit; @@ -49,8 +51,8 @@ class PermissionsMapper implements DataMapperInterface * The method is responsible for calling {@link FormInterface::setData()} * on the children of compound forms, defining their underlying model data. * - * @param mixed $viewData View data of the compound form being initialized - * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances + * @param mixed $viewData View data of the compound form being initialized + * @param FormInterface[]|Traversable $forms A list of {@link FormInterface} instances */ public function mapDataToForms($viewData, $forms): void { @@ -95,14 +97,14 @@ class PermissionsMapper implements DataMapperInterface * The model data can be an array or an object, so this second argument is always passed * by reference. * - * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances - * @param mixed $viewData The compound form's view data that get mapped - * its children model data + * @param FormInterface[]|Traversable $forms A list of {@link FormInterface} instances + * @param mixed $viewData The compound form's view data that get mapped + * its children model data */ public function mapFormsToData($forms, &$viewData): void { if ($this->inherit) { - throw new \RuntimeException('The permission type is readonly when it is showing read only data!'); + throw new RuntimeException('The permission type is readonly when it is showing read only data!'); } foreach ($forms as $form) { diff --git a/src/Form/TFAGoogleSettingsType.php b/src/Form/TFAGoogleSettingsType.php index 518e90e1..7cd60af9 100644 --- a/src/Form/TFAGoogleSettingsType.php +++ b/src/Form/TFAGoogleSettingsType.php @@ -58,7 +58,12 @@ class TFAGoogleSettingsType extends AbstractType TextType::class, [ 'mapped' => false, - 'attr' => ['maxlength' => '6', 'minlength' => '6', 'pattern' => '\d*', 'autocomplete' => 'off'], + 'attr' => [ + 'maxlength' => '6', + 'minlength' => '6', + 'pattern' => '\d*', + 'autocomplete' => 'off', + ], 'constraints' => [new ValidGoogleAuthCode()], ] ); @@ -77,7 +82,9 @@ class TFAGoogleSettingsType extends AbstractType } else { $form->add('submit', SubmitType::class, [ 'label' => 'tfa_google.disable', - 'attr' => ['class' => 'btn-danger'], + 'attr' => [ + 'class' => 'btn-danger', + ], ]); } }); diff --git a/src/Form/Type/MasterPictureAttachmentType.php b/src/Form/Type/MasterPictureAttachmentType.php index 5e8446d8..fdeee5e9 100644 --- a/src/Form/Type/MasterPictureAttachmentType.php +++ b/src/Form/Type/MasterPictureAttachmentType.php @@ -27,6 +27,7 @@ namespace App\Form\Type; use App\Entity\Attachments\Attachment; use App\Entity\Attachments\AttachmentContainingDBElement; use Doctrine\ORM\EntityRepository; +use ReflectionClass; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\OptionsResolver\Options; @@ -41,7 +42,9 @@ class MasterPictureAttachmentType extends AbstractType $resolver->setDefaults([ 'filter' => 'picture', - 'attr' => ['class' => 'selectpicker'], + 'attr' => [ + 'class' => 'selectpicker', + ], 'choice_attr' => function (Options $options) { return function ($choice, $key, $value) use ($options) { /** @var Attachment $choice */ @@ -58,7 +61,7 @@ class MasterPictureAttachmentType extends AbstractType }, 'choice_label' => 'name', 'class' => function (Options $options) { - $short_class_name = (new \ReflectionClass($options['entity']))->getShortName(); + $short_class_name = (new ReflectionClass($options['entity']))->getShortName(); //Category becomes CategoryAttachment return 'App\\Entity\\Attachments\\'.$short_class_name.'Attachment'; }, diff --git a/src/Form/Type/SIUnitType.php b/src/Form/Type/SIUnitType.php index a22ba234..30002b7c 100644 --- a/src/Form/Type/SIUnitType.php +++ b/src/Form/Type/SIUnitType.php @@ -36,8 +36,9 @@ use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; +use Traversable; -class SIUnitType extends AbstractType implements DataMapperInterface +final class SIUnitType extends AbstractType implements DataMapperInterface { protected $si_formatter; @@ -80,7 +81,9 @@ class SIUnitType extends AbstractType implements DataMapperInterface return null; }, - 'error_mapping' => ['.' => 'value'], + 'error_mapping' => [ + '.' => 'value', + ], ]); $resolver->setAllowedTypes('measurement_unit', [MeasurementUnit::class, 'null']); @@ -117,7 +120,13 @@ class SIUnitType extends AbstractType implements DataMapperInterface if ($options['show_prefix']) { $builder->add('prefix', ChoiceType::class, [ 'label' => 'false', - 'choices' => ['M' => 6, 'k' => 3, '' => 0, 'm' => -3, 'µ' => -6], + 'choices' => [ + 'M' => 6, + 'k' => 3, + '' => 0, + 'm' => -3, + 'µ' => -6, + ], ]); } @@ -143,8 +152,8 @@ class SIUnitType extends AbstractType implements DataMapperInterface * The method is responsible for calling {@link FormInterface::setData()} * on the children of compound forms, defining their underlying model data. * - * @param mixed $viewData View data of the compound form being initialized - * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances + * @param mixed $viewData View data of the compound form being initialized + * @param FormInterface[]|Traversable $forms A list of {@link FormInterface} instances * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ @@ -193,9 +202,9 @@ class SIUnitType extends AbstractType implements DataMapperInterface * The model data can be an array or an object, so this second argument is always passed * by reference. * - * @param FormInterface[]|\Traversable $forms A list of {@link FormInterface} instances - * @param mixed $viewData The compound form's view data that get mapped - * its children model data + * @param FormInterface[]|Traversable $forms A list of {@link FormInterface} instances + * @param mixed $viewData The compound form's view data that get mapped + * its children model data * * @throws Exception\UnexpectedTypeException if the type of the data parameter is not supported */ diff --git a/src/Form/Type/StructuralEntityType.php b/src/Form/Type/StructuralEntityType.php index b3a0ae8e..5e1b9d27 100644 --- a/src/Form/Type/StructuralEntityType.php +++ b/src/Form/Type/StructuralEntityType.php @@ -50,7 +50,9 @@ class StructuralEntityType extends AbstractType { protected $em; protected $options; - /** @var NodesListBuilder */ + /** + * @var NodesListBuilder + */ protected $builder; public function __construct(EntityManagerInterface $em, NodesListBuilder $builder) @@ -81,9 +83,11 @@ class StructuralEntityType extends AbstractType return new CallbackChoiceLoader(function () use ($options) { return $this->getEntries($options); }); - }, 'choice_label' => function ($choice, $key, $value) { + }, + 'choice_label' => function ($choice, $key, $value) { return $this->generateChoiceLabels($choice, $key, $value); - }, 'choice_attr' => function ($choice, $key, $value) { + }, + 'choice_attr' => function ($choice, $key, $value) { return $this->generateChoiceAttr($choice, $key, $value); }, ]); @@ -91,7 +95,10 @@ class StructuralEntityType extends AbstractType $resolver->setDefault('empty_message', null); $resolver->setDefault('attr', function (Options $options) { - $tmp = ['class' => 'selectpicker', 'data-live-search' => true]; + $tmp = [ + 'class' => 'selectpicker', + 'data-live-search' => true, + ]; if ($options['empty_message']) { $tmp['data-none-Selected-Text'] = $options['empty_message']; } diff --git a/src/Form/Type/TriStateCheckboxType.php b/src/Form/Type/TriStateCheckboxType.php index 37aff40c..f4ed2432 100644 --- a/src/Form/Type/TriStateCheckboxType.php +++ b/src/Form/Type/TriStateCheckboxType.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace App\Form\Type; +use InvalidArgumentException; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; @@ -32,7 +33,7 @@ use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormView; use Symfony\Component\OptionsResolver\OptionsResolver; -class TriStateCheckboxType extends AbstractType implements DataTransformerInterface +final class TriStateCheckboxType extends AbstractType implements DataTransformerInterface { public function buildForm(FormBuilderInterface $builder, array $options): void { @@ -42,8 +43,12 @@ class TriStateCheckboxType extends AbstractType implements DataTransformerInterf public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ - 'label_attr' => ['class' => 'checkbox-custom checkbox-inline'], - 'attr' => ['class' => 'tristate'], + 'label_attr' => [ + 'class' => 'checkbox-custom checkbox-inline', + ], + 'attr' => [ + 'class' => 'tristate', + ], 'compound' => false, ]); } @@ -115,7 +120,7 @@ class TriStateCheckboxType extends AbstractType implements DataTransformerInterf return 'indeterminate'; } - throw new \InvalidArgumentException('Invalid value encountered!: '.$value); + throw new InvalidArgumentException('Invalid value encountered!: '.$value); } /** @@ -156,7 +161,7 @@ class TriStateCheckboxType extends AbstractType implements DataTransformerInterf case 'indeterminate': return null; default: - throw new \InvalidArgumentException('Invalid value encountered!: '.$value); + throw new InvalidArgumentException('Invalid value encountered!: '.$value); } } } diff --git a/src/Form/UserAdminForm.php b/src/Form/UserAdminForm.php index cff3812e..9cc0ebbe 100644 --- a/src/Form/UserAdminForm.php +++ b/src/Form/UserAdminForm.php @@ -73,7 +73,9 @@ class UserAdminForm extends AbstractType ->add('name', TextType::class, [ 'empty_data' => '', 'label' => 'user.username.label', - 'attr' => ['placeholder' => 'user.username.placeholder'], + 'attr' => [ + 'placeholder' => 'user.username.placeholder', + ], 'disabled' => ! $this->security->isGranted('edit_username', $entity), ]) @@ -82,19 +84,25 @@ class UserAdminForm extends AbstractType 'required' => false, 'label' => 'group.label', 'disable_not_selectable' => true, - 'disabled' => ! $this->security->isGranted('change_group', $entity), ]) + 'disabled' => ! $this->security->isGranted('change_group', $entity), + ]) ->add('first_name', TextType::class, [ 'empty_data' => '', 'label' => 'user.firstName.label', - 'attr' => ['placeholder' => 'user.firstName.placeholder'], 'required' => false, + 'attr' => [ + 'placeholder' => 'user.firstName.placeholder', + ], + 'required' => false, 'disabled' => ! $this->security->isGranted('edit_infos', $entity), ]) ->add('last_name', TextType::class, [ 'empty_data' => '', 'label' => 'user.lastName.label', - 'attr' => ['placeholder' => 'user.lastName.placeholder'], + 'attr' => [ + 'placeholder' => 'user.lastName.placeholder', + ], 'required' => false, 'disabled' => ! $this->security->isGranted('edit_infos', $entity), ]) @@ -102,14 +110,19 @@ class UserAdminForm extends AbstractType ->add('email', TextType::class, [ 'empty_data' => '', 'label' => 'user.email.label', - 'attr' => ['placeholder' => 'user.email.placeholder'], + 'attr' => [ + 'placeholder' => 'user.email.placeholder', + ], 'required' => false, - 'disabled' => ! $this->security->isGranted('edit_infos', $entity), ]) + 'disabled' => ! $this->security->isGranted('edit_infos', $entity), + ]) ->add('department', TextType::class, [ 'empty_data' => '', 'label' => 'user.department.label', - 'attr' => ['placeholder' => 'user.department.placeholder'], + 'attr' => [ + 'placeholder' => 'user.department.placeholder', + ], 'required' => false, 'disabled' => ! $this->security->isGranted('edit_infos', $entity), ]) @@ -117,7 +130,10 @@ class UserAdminForm extends AbstractType //Config section ->add('language', LanguageType::class, [ 'required' => false, - 'attr' => ['class' => 'selectpicker', 'data-live-search' => true], + 'attr' => [ + 'class' => 'selectpicker', + 'data-live-search' => true, + ], 'placeholder' => 'user_settings.language.placeholder', 'label' => 'user.language_select', 'preferred_choices' => ['en', 'de'], @@ -125,7 +141,10 @@ class UserAdminForm extends AbstractType ]) ->add('timezone', TimezoneType::class, [ 'required' => false, - 'attr' => ['class' => 'selectpicker', 'data-live-search' => true], + 'attr' => [ + 'class' => 'selectpicker', + 'data-live-search' => true, + ], 'placeholder' => 'user_settings.timezone.placeholder', 'label' => 'user.timezone.label', 'preferred_choices' => ['Europe/Berlin'], @@ -137,7 +156,9 @@ class UserAdminForm extends AbstractType 'choice_label' => function ($entity, $key, $value) { return $value; }, - 'attr' => ['class' => 'selectpicker'], + 'attr' => [ + 'class' => 'selectpicker', + ], 'placeholder' => 'user_settings.theme.placeholder', 'label' => 'user.theme.label', 'disabled' => ! $this->security->isGranted('change_user_settings', $entity), @@ -150,8 +171,12 @@ class UserAdminForm extends AbstractType ->add('new_password', RepeatedType::class, [ 'type' => PasswordType::class, - 'first_options' => ['label' => 'user.settings.pw_new.label'], - 'second_options' => ['label' => 'user.settings.pw_confirm.label'], + 'first_options' => [ + 'label' => 'user.settings.pw_new.label', + ], + 'second_options' => [ + 'label' => 'user.settings.pw_confirm.label', + ], 'invalid_message' => 'password_must_match', 'required' => false, 'mapped' => false, @@ -164,14 +189,18 @@ class UserAdminForm extends AbstractType ->add('need_pw_change', CheckboxType::class, [ 'required' => false, - 'label_attr' => ['class' => 'checkbox-custom'], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], 'label' => 'user.edit.needs_pw_change', 'disabled' => ! $this->security->isGranted('set_password', $entity), ]) ->add('disabled', CheckboxType::class, [ 'required' => false, - 'label_attr' => ['class' => 'checkbox-custom'], + 'label_attr' => [ + 'class' => 'checkbox-custom', + ], 'label' => 'user.edit.user_disabled', 'disabled' => ! $this->security->isGranted('set_password', $entity) || $entity === $this->security->getUser(), @@ -206,7 +235,9 @@ class UserAdminForm extends AbstractType //Buttons $builder->add('save', SubmitType::class, [ 'label' => $is_new ? 'user.create' : 'user.edit.save', - 'attr' => ['class' => $is_new ? 'btn-success' : ''], + 'attr' => [ + 'class' => $is_new ? 'btn-success' : '', + ], ]) ->add('reset', ResetType::class, [ 'label' => 'entity.edit.reset', diff --git a/src/Form/UserSettingsType.php b/src/Form/UserSettingsType.php index a73be03b..18df6556 100644 --- a/src/Form/UserSettingsType.php +++ b/src/Form/UserSettingsType.php @@ -79,7 +79,10 @@ class UserSettingsType extends AbstractType ->add('language', LanguageType::class, [ 'disabled' => $this->demo_mode, 'required' => false, - 'attr' => ['class' => 'selectpicker', 'data-live-search' => true], + 'attr' => [ + 'class' => 'selectpicker', + 'data-live-search' => true, + ], 'placeholder' => 'user_settings.language.placeholder', 'label' => 'user.language_select', 'preferred_choices' => ['en', 'de'], @@ -87,7 +90,10 @@ class UserSettingsType extends AbstractType ->add('timezone', TimezoneType::class, [ 'disabled' => $this->demo_mode, 'required' => false, - 'attr' => ['class' => 'selectpicker', 'data-live-search' => true], + 'attr' => [ + 'class' => 'selectpicker', + 'data-live-search' => true, + ], 'placeholder' => 'user_settings.timezone.placeholder', 'label' => 'user.timezone.label', 'preferred_choices' => ['Europe/Berlin'], @@ -95,7 +101,9 @@ class UserSettingsType extends AbstractType ->add('theme', ChoiceType::class, [ 'disabled' => $this->demo_mode, 'required' => false, - 'attr' => ['class' => 'selectpicker'], + 'attr' => [ + 'class' => 'selectpicker', + ], 'choices' => User::AVAILABLE_THEMES, 'choice_label' => function ($entity, $key, $value) { return $value; diff --git a/src/Helpers/Trees/StructuralDBElementIterator.php b/src/Helpers/Trees/StructuralDBElementIterator.php index bc2c5e70..285213b0 100644 --- a/src/Helpers/Trees/StructuralDBElementIterator.php +++ b/src/Helpers/Trees/StructuralDBElementIterator.php @@ -25,8 +25,10 @@ declare(strict_types=1); namespace App\Helpers\Trees; use App\Entity\Base\StructuralDBElement; +use ArrayIterator; +use RecursiveIterator; -class StructuralDBElementIterator extends \ArrayIterator implements \RecursiveIterator +final class StructuralDBElementIterator extends ArrayIterator implements RecursiveIterator { public function __construct($nodes) { diff --git a/src/Helpers/Trees/TreeViewNode.php b/src/Helpers/Trees/TreeViewNode.php index b00647e1..bf97e686 100644 --- a/src/Helpers/Trees/TreeViewNode.php +++ b/src/Helpers/Trees/TreeViewNode.php @@ -24,11 +24,13 @@ declare(strict_types=1); namespace App\Helpers\Trees; +use JsonSerializable; + /** * This class represents a node for the bootstrap treeview node. * When you serialize an array of these objects to JSON, you can use the serialized data in data for the treeview. */ -class TreeViewNode implements \JsonSerializable +final class TreeViewNode implements JsonSerializable { protected $text; protected $href; diff --git a/src/Helpers/Trees/TreeViewNodeIterator.php b/src/Helpers/Trees/TreeViewNodeIterator.php index ffd7c260..4063735d 100644 --- a/src/Helpers/Trees/TreeViewNodeIterator.php +++ b/src/Helpers/Trees/TreeViewNodeIterator.php @@ -24,7 +24,10 @@ declare(strict_types=1); namespace App\Helpers\Trees; -class TreeViewNodeIterator extends \ArrayIterator implements \RecursiveIterator +use ArrayIterator; +use RecursiveIterator; + +final class TreeViewNodeIterator extends ArrayIterator implements RecursiveIterator { /** * @param TreeViewNode[] $nodes diff --git a/src/Helpers/Trees/TreeViewNodeState.php b/src/Helpers/Trees/TreeViewNodeState.php index 1f0affdf..29eac313 100644 --- a/src/Helpers/Trees/TreeViewNodeState.php +++ b/src/Helpers/Trees/TreeViewNodeState.php @@ -24,18 +24,28 @@ declare(strict_types=1); namespace App\Helpers\Trees; -class TreeViewNodeState implements \JsonSerializable +use JsonSerializable; + +final class TreeViewNodeState implements JsonSerializable { - /** @var bool|null */ + /** + * @var bool|null + */ protected $checked = null; - /** @var bool|null */ + /** + * @var bool|null + */ protected $disabled = null; - /** @var bool|null */ + /** + * @var bool|null + */ protected $expanded = null; - /** @var bool|null */ + /** + * @var bool|null + */ protected $selected = null; /** diff --git a/src/Helpers/UTCDateTimeType.php b/src/Helpers/UTCDateTimeType.php index 6d564d5f..9e4c9d33 100644 --- a/src/Helpers/UTCDateTimeType.php +++ b/src/Helpers/UTCDateTimeType.php @@ -24,6 +24,8 @@ declare(strict_types=1); namespace App\Helpers; +use DateTime; +use DateTimeZone; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Types\ConversionException; use Doctrine\DBAL\Types\DateTimeType; @@ -39,10 +41,10 @@ class UTCDateTimeType extends DateTimeType public function convertToDatabaseValue($value, AbstractPlatform $platform) { if (! self::$utc_timezone) { - self::$utc_timezone = new \DateTimeZone('UTC'); + self::$utc_timezone = new DateTimeZone('UTC'); } - if ($value instanceof \DateTime) { + if ($value instanceof DateTime) { $value->setTimezone(self::$utc_timezone); } @@ -52,14 +54,14 @@ class UTCDateTimeType extends DateTimeType public function convertToPHPValue($value, AbstractPlatform $platform) { if (! self::$utc_timezone) { - self::$utc_timezone = new \DateTimeZone('UTC'); + self::$utc_timezone = new DateTimeZone('UTC'); } - if (null === $value || $value instanceof \DateTime) { + if (null === $value || $value instanceof DateTime) { return $value; } - $converted = \DateTime::createFromFormat( + $converted = DateTime::createFromFormat( $platform->getDateTimeFormatString(), $value, self::$utc_timezone diff --git a/src/Migrations/Version1.php b/src/Migrations/Version1.php index aa8020b0..14e6b12d 100644 --- a/src/Migrations/Version1.php +++ b/src/Migrations/Version1.php @@ -43,7 +43,7 @@ final class Version1 extends AbstractMigration //Check if we can use this migration method: $version = (int) $this->connection->fetchColumn("SELECT keyValue AS version FROM `internal` WHERE `keyName` = 'dbVersion'"); $this->skipIf(true, 'Old Part-DB Database detected! Continue with upgrade...'); - } catch (DBALException $ex) { + } catch (DBALException $dBALException) { //when the table was not found, we can proceed, because we have an empty DB! } diff --git a/src/Migrations/Version20190902140506.php b/src/Migrations/Version20190902140506.php index d0e47752..18b2ed24 100644 --- a/src/Migrations/Version20190902140506.php +++ b/src/Migrations/Version20190902140506.php @@ -46,7 +46,7 @@ final class Version20190902140506 extends AbstractMigration //Check if we can use this migration method: $version = (int) $this->connection->fetchColumn("SELECT keyValue AS version FROM `internal` WHERE `keyName` = 'dbVersion'"); $this->abortIf(26 !== $version, 'This database migration can only be used if the database version is 26! Install Part-DB 0.5.6 and update database there!'); - } catch (DBALException $ex) { + } catch (DBALException $dBALException) { //when the table was not found, then you can not use this migration $this->skipIf(true, 'Empty database detected. Skip migration.'); } diff --git a/src/Repository/StructuralDBElementRepository.php b/src/Repository/StructuralDBElementRepository.php index dbd3543d..6e7f9b8c 100644 --- a/src/Repository/StructuralDBElementRepository.php +++ b/src/Repository/StructuralDBElementRepository.php @@ -27,6 +27,7 @@ namespace App\Repository; use App\Entity\Base\StructuralDBElement; use App\Helpers\Trees\StructuralDBElementIterator; use App\Helpers\Trees\TreeViewNode; +use RecursiveIteratorIterator; class StructuralDBElementRepository extends NamedDBElementRepository { @@ -80,7 +81,7 @@ class StructuralDBElementRepository extends NamedDBElementRepository $entities = $this->findBy(['parent' => $parent], ['name' => 'ASC']); $elementIterator = new StructuralDBElementIterator($entities); - $recursiveIterator = new \RecursiveIteratorIterator($elementIterator, \RecursiveIteratorIterator::SELF_FIRST); + $recursiveIterator = new RecursiveIteratorIterator($elementIterator, RecursiveIteratorIterator::SELF_FIRST); //$result = iterator_to_array($recursiveIterator); //We can not use iterator_to_array here or we get only the parent elements diff --git a/src/Repository/UserRepository.php b/src/Repository/UserRepository.php index b4367bb5..a2d97a86 100644 --- a/src/Repository/UserRepository.php +++ b/src/Repository/UserRepository.php @@ -35,7 +35,7 @@ use Symfony\Component\Security\Core\User\UserInterface; * @method User[] findAll() * @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ -class UserRepository extends NamedDBElementRepository implements PasswordUpgraderInterface +final class UserRepository extends NamedDBElementRepository implements PasswordUpgraderInterface { protected $anonymous_user; @@ -74,11 +74,14 @@ class UserRepository extends NamedDBElementRepository implements PasswordUpgrade ->where('u.name = (:name)') ->orWhere('u.email = (:email)'); - $qb->setParameters(['email' => $name_or_password, 'name' => $name_or_password]); + $qb->setParameters([ + 'email' => $name_or_password, + 'name' => $name_or_password, + ]); try { return $qb->getQuery()->getOneOrNullResult(); - } catch (NonUniqueResultException $exception) { + } catch (NonUniqueResultException $nonUniqueResultException) { return null; } } diff --git a/src/Security/Annotations/ColumnSecurity.php b/src/Security/Annotations/ColumnSecurity.php index 78f5dc06..bd16c11d 100644 --- a/src/Security/Annotations/ColumnSecurity.php +++ b/src/Security/Annotations/ColumnSecurity.php @@ -25,9 +25,11 @@ declare(strict_types=1); namespace App\Security\Annotations; use App\Entity\Base\NamedDBElement; +use DateTime; use Doctrine\Common\Annotations\Annotation; use Doctrine\Common\Collections\ArrayCollection; use InvalidArgumentException; +use function is_string; /** * @Annotation @@ -90,7 +92,7 @@ class ColumnSecurity if (class_exists($this->type)) { $object = new $this->type(); if ($object instanceof NamedDBElement) { - if (\is_string($this->placeholder) && '' !== $this->placeholder) { + if (is_string($this->placeholder) && '' !== $this->placeholder) { $object->setName($this->placeholder); } else { $object->setName('???'); @@ -117,7 +119,7 @@ class ColumnSecurity case 'bool': return false; case 'datetime': - return (new \DateTime())->setTimestamp(0); + return (new DateTime())->setTimestamp(0); default: throw new InvalidArgumentException('Unknown type! You have to specify a placeholder!'); } diff --git a/src/Security/EntityListeners/ElementPermissionListener.php b/src/Security/EntityListeners/ElementPermissionListener.php index a91baa1c..07794080 100644 --- a/src/Security/EntityListeners/ElementPermissionListener.php +++ b/src/Security/EntityListeners/ElementPermissionListener.php @@ -27,6 +27,7 @@ namespace App\Security\EntityListeners; use App\Entity\Base\DBElement; use App\Entity\UserSystem\User; use App\Security\Annotations\ColumnSecurity; +use function count; use Doctrine\Common\Annotations\Reader; use Doctrine\Common\Persistence\Event\LifecycleEventArgs; use Doctrine\ORM\EntityManagerInterface; @@ -34,6 +35,8 @@ use Doctrine\ORM\Event\PreFlushEventArgs; use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping\PostLoad; use Doctrine\ORM\Mapping\PreUpdate; +use function get_class; +use InvalidArgumentException; use ReflectionClass; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Security\Core\Security; @@ -167,7 +170,7 @@ class ElementPermissionListener */ protected function isRunningFromCLI() { - if (empty($_SERVER['REMOTE_ADDR']) && ! isset($_SERVER['HTTP_USER_AGENT']) && \count($_SERVER['argv']) > 0) { + if (empty($_SERVER['REMOTE_ADDR']) && ! isset($_SERVER['HTTP_USER_AGENT']) && count($_SERVER['argv']) > 0) { return true; } @@ -191,7 +194,7 @@ class ElementPermissionListener } elseif ('edit' === $mode) { $operation = $annotation->getEditOperationName(); } else { - throw new \InvalidArgumentException('$mode must be either "read" or "edit"!'); + throw new InvalidArgumentException('$mode must be either "read" or "edit"!'); } //Users must always be checked, because its return value can differ if it is the user itself or something else @@ -200,10 +203,10 @@ class ElementPermissionListener } //Check if we have already have saved the permission, otherwise save it to cache - if (! isset($this->perm_cache[$mode][\get_class($element)][$operation])) { - $this->perm_cache[$mode][\get_class($element)][$operation] = $this->security->isGranted($operation, $element); + if (! isset($this->perm_cache[$mode][get_class($element)][$operation])) { + $this->perm_cache[$mode][get_class($element)][$operation] = $this->security->isGranted($operation, $element); } - return $this->perm_cache[$mode][\get_class($element)][$operation]; + return $this->perm_cache[$mode][get_class($element)][$operation]; } } diff --git a/src/Security/UserChecker.php b/src/Security/UserChecker.php index d25f936c..22e3b10a 100644 --- a/src/Security/UserChecker.php +++ b/src/Security/UserChecker.php @@ -30,7 +30,7 @@ use Symfony\Component\Security\Core\Exception\DisabledException; use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Core\User\UserInterface; -class UserChecker implements UserCheckerInterface +final class UserChecker implements UserCheckerInterface { public function __construct() { diff --git a/src/Security/Voter/AttachmentVoter.php b/src/Security/Voter/AttachmentVoter.php index bb91cc99..6c84c08e 100644 --- a/src/Security/Voter/AttachmentVoter.php +++ b/src/Security/Voter/AttachmentVoter.php @@ -26,6 +26,7 @@ namespace App\Security\Voter; use App\Entity\Attachments\Attachment; use App\Entity\UserSystem\User; +use function in_array; class AttachmentVoter extends ExtendedVoter { @@ -54,7 +55,7 @@ class AttachmentVoter extends ExtendedVoter protected function supports($attribute, $subject) { if ($subject instanceof Attachment) { - return \in_array($attribute, $this->resolver->listOperationsForPermission('parts_attachments'), false); + return in_array($attribute, $this->resolver->listOperationsForPermission('parts_attachments'), false); } return false; diff --git a/src/Security/Voter/ExtendedVoter.php b/src/Security/Voter/ExtendedVoter.php index 8920dcfa..dd4b435e 100644 --- a/src/Security/Voter/ExtendedVoter.php +++ b/src/Security/Voter/ExtendedVoter.php @@ -35,13 +35,12 @@ use Symfony\Component\Security\Core\Authorization\Voter\Voter; */ abstract class ExtendedVoter extends Voter { + protected $entityManager; /** * @var PermissionResolver */ protected $resolver; - protected $entityManager; - public function __construct(PermissionResolver $resolver, EntityManagerInterface $entityManager) { $this->resolver = $resolver; diff --git a/src/Security/Voter/PermissionVoter.php b/src/Security/Voter/PermissionVoter.php index a983774d..bd708e39 100644 --- a/src/Security/Voter/PermissionVoter.php +++ b/src/Security/Voter/PermissionVoter.php @@ -58,7 +58,7 @@ class PermissionVoter extends ExtendedVoter protected function supports($attribute, $subject) { //Check if the attribute has the form @permission.operation - if (preg_match('/^@\\w+\\.\\w+$/', $attribute)) { + if (preg_match('#^@\\w+\\.\\w+$#', $attribute)) { $attribute = ltrim($attribute, '@'); [$perm, $op] = explode('.', $attribute); diff --git a/src/Security/Voter/StructureVoter.php b/src/Security/Voter/StructureVoter.php index 1bf94c40..8e54e930 100644 --- a/src/Security/Voter/StructureVoter.php +++ b/src/Security/Voter/StructureVoter.php @@ -34,6 +34,8 @@ use App\Entity\Parts\Storelocation; use App\Entity\Parts\Supplier; use App\Entity\PriceInformations\Currency; use App\Entity\UserSystem\User; +use function get_class; +use function is_object; class StructureVoter extends ExtendedVoter { @@ -47,7 +49,7 @@ class StructureVoter extends ExtendedVoter */ protected function supports($attribute, $subject) { - if (\is_object($subject)) { + if (is_object($subject)) { $permission_name = $this->instanceToPermissionName($subject); //If permission name is null, then the subject is not supported return (null !== $permission_name) && $this->resolver->isValidOperation($permission_name, $attribute); @@ -63,7 +65,7 @@ class StructureVoter extends ExtendedVoter */ protected function instanceToPermissionName($subject): ?string { - $class_name = \get_class($subject); + $class_name = get_class($subject); switch ($class_name) { case AttachmentType::class: return 'attachment_types'; diff --git a/src/Security/Voter/UserVoter.php b/src/Security/Voter/UserVoter.php index 978ce91e..378993a8 100644 --- a/src/Security/Voter/UserVoter.php +++ b/src/Security/Voter/UserVoter.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace App\Security\Voter; use App\Entity\UserSystem\User; +use function in_array; class UserVoter extends ExtendedVoter { @@ -39,7 +40,7 @@ class UserVoter extends ExtendedVoter protected function supports($attribute, $subject) { if ($subject instanceof User) { - return \in_array($attribute, array_merge( + return in_array($attribute, array_merge( $this->resolver->listOperationsForPermission('users'), $this->resolver->listOperationsForPermission('self')), false diff --git a/src/Services/AmountFormatter.php b/src/Services/AmountFormatter.php index e080e22a..9df01914 100644 --- a/src/Services/AmountFormatter.php +++ b/src/Services/AmountFormatter.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace App\Services; use App\Entity\Parts\MeasurementUnit; +use InvalidArgumentException; use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -48,12 +49,12 @@ class AmountFormatter * * @return string The formatted string * - * @throws \InvalidArgumentException thrown if $value is not numeric + * @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!'); + throw new InvalidArgumentException('$value must be an numeric value!'); } $value = (float) $value; @@ -117,7 +118,9 @@ class AmountFormatter return ''; }, 'decimals' => 2, - 'error_mapping' => ['.' => 'value'], + 'error_mapping' => [ + '.' => 'value', + ], ]); $resolver->setAllowedTypes('decimals', 'int'); diff --git a/src/Services/Attachments/AttachmentManager.php b/src/Services/Attachments/AttachmentManager.php index ffaac0d5..2d43721e 100644 --- a/src/Services/Attachments/AttachmentManager.php +++ b/src/Services/Attachments/AttachmentManager.php @@ -25,6 +25,8 @@ declare(strict_types=1); namespace App\Services\Attachments; use App\Entity\Attachments\Attachment; +use SplFileInfo; +use function strlen; /** * This service contains basic commonly used functions to work with attachments. @@ -47,16 +49,16 @@ class AttachmentManager * * @param Attachment $attachment The attachment for which the file should be generated * - * @return \SplFileInfo|null The fileinfo for the attachment file. Null, if the attachment is external or has - * invalid file. + * @return SplFileInfo|null The fileinfo for the attachment file. Null, if the attachment is external or has + * invalid file. */ - public function attachmentToFile(Attachment $attachment): ?\SplFileInfo + public function attachmentToFile(Attachment $attachment): ?SplFileInfo { if ($attachment->isExternal() || ! $this->isFileExisting($attachment)) { return null; } - return new \SplFileInfo($this->toAbsoluteFilePath($attachment)); + return new SplFileInfo($this->toAbsoluteFilePath($attachment)); } /** @@ -107,7 +109,7 @@ class AttachmentManager $absolute_path = $this->toAbsoluteFilePath($attachment); - if ($absolute_path === null) { + if (null === $absolute_path) { return false; } @@ -155,7 +157,7 @@ class AttachmentManager //Taken from: https://www.php.net/manual/de/function.filesize.php#106569 and slightly modified $sz = 'BKMGTP'; - $factor = (int) floor((\strlen($bytes) - 1) / 3); + $factor = (int) floor((strlen($bytes) - 1) / 3); return sprintf("%.{$decimals}f", $bytes / 1024 ** $factor).@$sz[$factor]; } diff --git a/src/Services/Attachments/AttachmentPathResolver.php b/src/Services/Attachments/AttachmentPathResolver.php index c76eba0b..c20f3bc2 100644 --- a/src/Services/Attachments/AttachmentPathResolver.php +++ b/src/Services/Attachments/AttachmentPathResolver.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace App\Services\Attachments; +use const DIRECTORY_SEPARATOR; use Symfony\Component\Filesystem\Filesystem; /** @@ -106,7 +107,7 @@ class AttachmentPathResolver } //Otherwise prepend the project path - $tmp = realpath($this->project_dir.\DIRECTORY_SEPARATOR.$param_path); + $tmp = realpath($this->project_dir.DIRECTORY_SEPARATOR.$param_path); //If path does not exist then disable the placeholder if (false === $tmp) { @@ -139,7 +140,7 @@ class AttachmentPathResolver } //If we have now have a placeholder left, the string is invalid: - if (preg_match('/%\w+%/', $placeholder_path)) { + if (preg_match('#%\w+%#', $placeholder_path)) { return null; } @@ -183,7 +184,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; } diff --git a/src/Services/Attachments/AttachmentReverseSearch.php b/src/Services/Attachments/AttachmentReverseSearch.php index 0e95e5bc..ab3a7d18 100644 --- a/src/Services/Attachments/AttachmentReverseSearch.php +++ b/src/Services/Attachments/AttachmentReverseSearch.php @@ -25,8 +25,10 @@ declare(strict_types=1); namespace App\Services\Attachments; use App\Entity\Attachments\Attachment; +use function count; use Doctrine\ORM\EntityManagerInterface; use Liip\ImagineBundle\Imagine\Cache\CacheManager; +use SplFileInfo; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\File; @@ -52,11 +54,11 @@ class AttachmentReverseSearch /** * Find all attachments that use the given file. * - * @param \SplFileInfo $file The file for which is searched + * @param SplFileInfo $file The file for which is searched * * @return Attachment[] an list of attachments that use the given file */ - public function findAttachmentsByFile(\SplFileInfo $file): array + public function findAttachmentsByFile(SplFileInfo $file): array { //Path with %MEDIA% $relative_path_new = $this->pathResolver->realPathToPlaceholder($file->getPathname()); @@ -65,21 +67,23 @@ class AttachmentReverseSearch $repo = $this->em->getRepository(Attachment::class); - return $repo->findBy(['path' => [$relative_path_new, $relative_path_old]]); + return $repo->findBy([ + 'path' => [$relative_path_new, $relative_path_old], + ]); } /** * Deletes the given file if it is not used by more than $threshold attachments. * - * @param \SplFileInfo $file The file that should be removed - * @param int $threshold the threshold used, to determine if a file should be deleted or not + * @param SplFileInfo $file The file that should be removed + * @param int $threshold the threshold used, to determine if a file should be deleted or not * * @return bool True, if the file was delete. False if not. */ - public function deleteIfNotUsed(\SplFileInfo $file, int $threshold = 1): bool + public function deleteIfNotUsed(SplFileInfo $file, int $threshold = 1): bool { /* When the file is used more then $threshold times, don't delete it */ - if (\count($this->findAttachmentsByFile($file)) > $threshold) { + if (count($this->findAttachmentsByFile($file)) > $threshold) { return false; } diff --git a/src/Services/Attachments/AttachmentSubmitHandler.php b/src/Services/Attachments/AttachmentSubmitHandler.php index 43646a11..d4867eaf 100644 --- a/src/Services/Attachments/AttachmentSubmitHandler.php +++ b/src/Services/Attachments/AttachmentSubmitHandler.php @@ -39,6 +39,10 @@ use App\Entity\Attachments\StorelocationAttachment; use App\Entity\Attachments\SupplierAttachment; use App\Entity\Attachments\UserAttachment; use App\Exceptions\AttachmentDownloadException; +use const DIRECTORY_SEPARATOR; +use function get_class; +use InvalidArgumentException; +use RuntimeException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Mime\MimeTypesInterface; @@ -66,12 +70,20 @@ class AttachmentSubmitHandler $this->mimeTypes = $mimeTypes; //The mapping used to determine which folder will be used for an attachment type - $this->folder_mapping = [PartAttachment::class => 'part', AttachmentTypeAttachment::class => 'attachment_type', - CategoryAttachment::class => 'category', CurrencyAttachment::class => 'currency', - DeviceAttachment::class => 'device', FootprintAttachment::class => 'footprint', - GroupAttachment::class => 'group', ManufacturerAttachment::class => 'manufacturer', - MeasurementUnitAttachment::class => 'measurement_unit', StorelocationAttachment::class => 'storelocation', - SupplierAttachment::class => 'supplier', UserAttachment::class => 'user', ]; + $this->folder_mapping = [ + PartAttachment::class => 'part', + AttachmentTypeAttachment::class => 'attachment_type', + CategoryAttachment::class => 'category', + CurrencyAttachment::class => 'currency', + DeviceAttachment::class => 'device', + FootprintAttachment::class => 'footprint', + GroupAttachment::class => 'group', + ManufacturerAttachment::class => 'manufacturer', + MeasurementUnitAttachment::class => 'measurement_unit', + StorelocationAttachment::class => 'storelocation', + SupplierAttachment::class => 'supplier', + UserAttachment::class => 'user', + ]; } /** @@ -117,18 +129,18 @@ class AttachmentSubmitHandler } //Ensure the given attachment class is known to mapping - 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)); + 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 if (null === $attachment->getElement()) { - throw new \InvalidArgumentException('The given attachment is not assigned to an element! An element is needed to generate a path!'); + throw new InvalidArgumentException('The given attachment is not assigned to an element! An element is needed to generate a path!'); } //Build path return - $base_path.\DIRECTORY_SEPARATOR //Base path - .$this->folder_mapping[\get_class($attachment)].\DIRECTORY_SEPARATOR.$attachment->getElement()->getID(); + $base_path.DIRECTORY_SEPARATOR //Base path + .$this->folder_mapping[get_class($attachment)].DIRECTORY_SEPARATOR.$attachment->getElement()->getID(); } /** @@ -209,14 +221,14 @@ class AttachmentSubmitHandler $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()); } $ext = pathinfo($filename, PATHINFO_EXTENSION); $new_path = $this->generateAttachmentPath($attachment, $secure_location) - .\DIRECTORY_SEPARATOR.$this->generateAttachmentFilename($attachment, $ext); + .DIRECTORY_SEPARATOR.$this->generateAttachmentFilename($attachment, $ext); //Move file to new directory $fs = new Filesystem(); @@ -240,14 +252,14 @@ class AttachmentSubmitHandler { //Check if we are allowed to download files if (! $this->allow_attachments_downloads) { - throw new \RuntimeException('Download of attachments is not allowed!'); + throw new RuntimeException('Download of attachments is not allowed!'); } $url = $attachment->getURL(); $fs = new Filesystem(); $attachment_folder = $this->generateAttachmentPath($attachment, $options['secure_attachment']); - $tmp_path = $attachment_folder.\DIRECTORY_SEPARATOR.$this->generateAttachmentFilename($attachment, 'tmp'); + $tmp_path = $attachment_folder.DIRECTORY_SEPARATOR.$this->generateAttachmentFilename($attachment, 'tmp'); try { $response = $this->httpClient->request('GET', $url, [ @@ -296,14 +308,14 @@ class AttachmentSubmitHandler } //Rename the file to its new name and save path to attachment entity - $new_path = $attachment_folder.\DIRECTORY_SEPARATOR.$this->generateAttachmentFilename($attachment, $new_ext); + $new_path = $attachment_folder.DIRECTORY_SEPARATOR.$this->generateAttachmentFilename($attachment, $new_ext); $fs->rename($tmp_path, $new_path); //Make our file path relative to %BASE% $new_path = $this->pathResolver->realPathToPlaceholder($new_path); //Save the path to the attachment $attachment->setPath($new_path); - } catch (TransportExceptionInterface $exception) { + } catch (TransportExceptionInterface $transportExceptionInterface) { throw new AttachmentDownloadException('Transport error!'); } diff --git a/src/Services/Attachments/AttachmentURLGenerator.php b/src/Services/Attachments/AttachmentURLGenerator.php index e29ab08f..f07f2f9d 100644 --- a/src/Services/Attachments/AttachmentURLGenerator.php +++ b/src/Services/Attachments/AttachmentURLGenerator.php @@ -25,7 +25,10 @@ declare(strict_types=1); namespace App\Services\Attachments; use App\Entity\Attachments\Attachment; +use InvalidArgumentException; use Liip\ImagineBundle\Service\FilterService; +use RuntimeException; +use function strlen; use Symfony\Component\Asset\Packages; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; @@ -76,7 +79,7 @@ class AttachmentURLGenerator } //Return the part relative after public path. - return substr($absolute_path, \strlen($public_path) + 1); + return substr($absolute_path, strlen($public_path) + 1); } /** @@ -86,7 +89,7 @@ class AttachmentURLGenerator { $absolute_path = $this->attachmentHelper->toAbsoluteFilePath($attachment); if (null === $absolute_path) { - throw new \RuntimeException('The given attachment is external or has no valid file, so no URL can get generated for it! + throw new RuntimeException('The given attachment is external or has no valid file, so no URL can get generated for it! Use Attachment::getURL() to get the external URL!'); } @@ -106,7 +109,7 @@ class AttachmentURLGenerator public function getThumbnailURL(Attachment $attachment, string $filter_name = 'thumbnail_sm'): string { if (! $attachment->isPicture()) { - throw new \InvalidArgumentException('Thumbnail creation only works for picture attachments!'); + throw new InvalidArgumentException('Thumbnail creation only works for picture attachments!'); } if ($attachment->isExternal()) { @@ -115,7 +118,7 @@ class AttachmentURLGenerator $absolute_path = $this->attachmentHelper->toAbsoluteFilePath($attachment); if (null === $absolute_path) { - throw new \RuntimeException('The given attachment is external or has no valid file, so no URL can get generated for it!'); + throw new RuntimeException('The given attachment is external or has no valid file, so no URL can get generated for it!'); } $asset_path = $this->absolutePathToAssetPath($absolute_path); diff --git a/src/Services/Attachments/BuiltinAttachmentsFinder.php b/src/Services/Attachments/BuiltinAttachmentsFinder.php index 3e7b2fb0..1a232de9 100644 --- a/src/Services/Attachments/BuiltinAttachmentsFinder.php +++ b/src/Services/Attachments/BuiltinAttachmentsFinder.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace App\Services\Attachments; use App\Entity\Attachments\Attachment; +use Psr\Cache\InvalidArgumentException; use Symfony\Component\Finder\Finder; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Contracts\Cache\CacheInterface; @@ -77,7 +78,7 @@ class BuiltinAttachmentsFinder return $results; }); - } catch (\Psr\Cache\InvalidArgumentException $ex) { + } catch (InvalidArgumentException $invalidArgumentException) { return []; } } diff --git a/src/Services/Attachments/FileTypeFilterTools.php b/src/Services/Attachments/FileTypeFilterTools.php index 12391031..ff67c3bf 100644 --- a/src/Services/Attachments/FileTypeFilterTools.php +++ b/src/Services/Attachments/FileTypeFilterTools.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace App\Services\Attachments; use App\Entity\Attachments\Attachment; +use function in_array; use Symfony\Component\Mime\MimeTypesInterface; use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\ItemInterface; @@ -72,9 +73,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; } } @@ -120,7 +121,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; } @@ -157,7 +158,7 @@ class FileTypeFilterTools $extensions = array_merge($extensions, static::AUDIO_EXTS); } elseif ('image/*' === $element) { $extensions = array_merge($extensions, static::VIDEO_EXTS); - } elseif (preg_match('/^[-\w.]+\/[-\w.*]+/', $element)) { + } elseif (preg_match('#^[-\w.]+\/[-\w.*]+#', $element)) { $extensions = array_merge($extensions, $this->mimeTypes->getExtensions($element)); } } @@ -178,6 +179,6 @@ class FileTypeFilterTools { $extension = strtolower($extension); - return empty($filter) || \in_array($extension, $this->resolveFileExtensions($filter), false); + return empty($filter) || in_array($extension, $this->resolveFileExtensions($filter), false); } } diff --git a/src/Services/CustomEnvVarProcessor.php b/src/Services/CustomEnvVarProcessor.php index 224e92d8..cdcc2b55 100644 --- a/src/Services/CustomEnvVarProcessor.php +++ b/src/Services/CustomEnvVarProcessor.php @@ -24,19 +24,20 @@ declare(strict_types=1); namespace App\Services; +use Closure; use Symfony\Component\DependencyInjection\EnvVarProcessorInterface; use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException; -class CustomEnvVarProcessor implements EnvVarProcessorInterface +final class CustomEnvVarProcessor implements EnvVarProcessorInterface { - public function getEnv($prefix, $name, \Closure $getEnv) + public function getEnv($prefix, $name, Closure $getEnv) { if ('validMailDSN' === $prefix) { try { $env = $getEnv($name); return ! empty($env) && 'null://null' !== $env; - } catch (EnvNotFoundException $exception) { + } catch (EnvNotFoundException $envNotFoundException) { return false; } } diff --git a/src/Services/ElementTypeNameGenerator.php b/src/Services/ElementTypeNameGenerator.php index eebef078..f2338053 100644 --- a/src/Services/ElementTypeNameGenerator.php +++ b/src/Services/ElementTypeNameGenerator.php @@ -42,6 +42,7 @@ use App\Entity\PriceInformations\Pricedetail; use App\Entity\UserSystem\Group; use App\Entity\UserSystem\User; use App\Exceptions\EntityNotSupportedException; +use function get_class; use Proxies\__CG__\App\Entity\Parts\Supplier; use Symfony\Contracts\Translation\TranslatorInterface; @@ -90,8 +91,8 @@ class ElementTypeNameGenerator public function getLocalizedTypeLabel(DBElement $entity): string { //Check if we have an direct array entry for our entity class, then we can use it - if (isset($this->mapping[\get_class($entity)])) { - return $this->mapping[\get_class($entity)]; + if (isset($this->mapping[get_class($entity)])) { + return $this->mapping[get_class($entity)]; } //Otherwise iterate over array and check for inheritance (needed when the proxy element from doctrine are passed) @@ -102,7 +103,7 @@ class ElementTypeNameGenerator } //When nothing was found throw an exception - throw new EntityNotSupportedException(sprintf('No localized label for the element with type %s was found!', \get_class($entity))); + throw new EntityNotSupportedException(sprintf('No localized label for the element with type %s was found!', get_class($entity))); } /** diff --git a/src/Services/EntityExporter.php b/src/Services/EntityExporter.php index 255d4137..0cf63c45 100644 --- a/src/Services/EntityExporter.php +++ b/src/Services/EntityExporter.php @@ -25,6 +25,11 @@ declare(strict_types=1); namespace App\Services; use App\Entity\Base\NamedDBElement; +use function in_array; +use InvalidArgumentException; +use function is_array; +use ReflectionClass; +use ReflectionException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; @@ -49,21 +54,21 @@ class EntityExporter * * @return Response the generated response containing the exported data * - * @throws \ReflectionException + * @throws ReflectionException */ public function exportEntityFromRequest($entity, Request $request): Response { $format = $request->get('format') ?? 'json'; //Check if we have one of the supported formats - if (! \in_array($format, ['json', 'csv', 'yaml', 'xml'], true)) { - throw new \InvalidArgumentException('Given format is not supported!'); + 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'], true)) { - throw new \InvalidArgumentException('Given level is not supported!'); + if (! in_array($level, ['simple', 'extended', 'full'], true)) { + throw new InvalidArgumentException('Given level is not supported!'); } //Check for include children option @@ -91,7 +96,7 @@ class EntityExporter } //Ensure that we always serialize an array. This makes it easier to import the data again. - if (\is_array($entity)) { + if (is_array($entity)) { $entity_array = $entity; } else { $entity_array = [$entity]; @@ -111,16 +116,16 @@ class EntityExporter if (! $request->get('view')) { if ($entity instanceof NamedDBElement) { $entity_name = $entity->getName(); - } elseif (\is_array($entity)) { + } elseif (is_array($entity)) { if (empty($entity)) { - throw new \InvalidArgumentException('$entity must not be empty!'); + throw new InvalidArgumentException('$entity must not be empty!'); } //Use the class name of the first element for the filename - $reflection = new \ReflectionClass($entity[0]); + $reflection = new ReflectionClass($entity[0]); $entity_name = $reflection->getShortName(); } else { - throw new \InvalidArgumentException('$entity type is not supported!'); + throw new InvalidArgumentException('$entity type is not supported!'); } $filename = 'export_'.$entity_name.'_'.$level.'.'.$format; diff --git a/src/Services/EntityImporter.php b/src/Services/EntityImporter.php index b992ebc4..5c6a4955 100644 --- a/src/Services/EntityImporter.php +++ b/src/Services/EntityImporter.php @@ -25,7 +25,10 @@ declare(strict_types=1); namespace App\Services; use App\Entity\Base\StructuralDBElement; +use function count; use Doctrine\ORM\EntityManagerInterface; +use InvalidArgumentException; +use function is_array; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Serializer\SerializerInterface; @@ -61,10 +64,10 @@ class EntityImporter $names = explode("\n", $lines); if (! is_a($class_name, StructuralDBElement::class, true)) { - throw new \InvalidArgumentException('$class_name must be a StructuralDBElement type!'); + throw new InvalidArgumentException('$class_name must be a StructuralDBElement type!'); } if (null !== $parent && ! is_a($parent, $class_name)) { - throw new \InvalidArgumentException('$parent must have the same type as specified in $class_name!'); + throw new InvalidArgumentException('$parent must have the same type as specified in $class_name!'); } $errors = []; @@ -85,10 +88,13 @@ class EntityImporter //Validate entity $tmp = $this->validator->validate($entity); //If no error occured, write entry to DB: - if (0 === \count($tmp)) { + if (0 === count($tmp)) { $valid_entities[] = $entity; } else { //Otherwise log error - $errors[] = ['entity' => $entity, 'violations' => $tmp]; + $errors[] = [ + 'entity' => $entity, + 'violations' => $tmp, + ]; } } @@ -127,7 +133,7 @@ class EntityImporter $tmp = $this->validator->validate($entity); //When no validation error occured, persist entity to database (cascade must be set in entity) - if (0 === \count($errors)) { + if (0 === count($errors)) { $this->em->persist($entity); } else { //Log validation errors to global log. $errors[$entity->getFullPath()] = $tmp; @@ -171,10 +177,13 @@ class EntityImporter //The [] behind class_name denotes that we expect an array. $entities = $this->serializer->deserialize($content, $class_name.'[]', $options['format'], - ['groups' => $groups, 'csv_delimiter' => $options['csv_separator']]); + [ + '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]; } diff --git a/src/Services/EntityURLGenerator.php b/src/Services/EntityURLGenerator.php index 2dccb348..104232b4 100644 --- a/src/Services/EntityURLGenerator.php +++ b/src/Services/EntityURLGenerator.php @@ -40,6 +40,9 @@ use App\Entity\UserSystem\Group; use App\Entity\UserSystem\User; use App\Exceptions\EntityNotSupportedException; use App\Services\Attachments\AttachmentURLGenerator; +use function array_key_exists; +use function get_class; +use InvalidArgumentException; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; /** @@ -49,11 +52,11 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface; */ class EntityURLGenerator { + protected $attachmentURLGenerator; /** * @var UrlGeneratorInterface */ protected $urlGenerator; - protected $attachmentURLGenerator; public function __construct(UrlGeneratorInterface $urlGenerator, AttachmentURLGenerator $attachmentURLGenerator) { @@ -72,7 +75,7 @@ class EntityURLGenerator * @return string the link to the desired page * * @throws EntityNotSupportedException thrown if the entity is not supported for the given type - * @throws \InvalidArgumentException thrown if the givent type is not existing + * @throws InvalidArgumentException thrown if the givent type is not existing */ public function getURL($entity, string $type) { @@ -96,7 +99,7 @@ class EntityURLGenerator return $this->viewURL($entity); } - throw new \InvalidArgumentException('Method is not supported!'); + throw new InvalidArgumentException('Method is not supported!'); } public function viewURL($entity): string @@ -124,7 +127,7 @@ class EntityURLGenerator } //Otherwise throw an error - throw new EntityNotSupportedException(sprintf('The given entity is not supported yet! Passed class type: %s', \get_class($entity))); + throw new EntityNotSupportedException(sprintf('The given entity is not supported yet! Passed class type: %s', get_class($entity))); } /** @@ -290,10 +293,10 @@ class EntityURLGenerator */ protected function mapToController(array $map, $entity): string { - $class = \get_class($entity); + $class = get_class($entity); //Check if we have an direct mapping for the given class - if (! \array_key_exists($class, $map)) { + 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)) { @@ -301,7 +304,7 @@ class EntityURLGenerator } } - throw new EntityNotSupportedException(sprintf('The given entity is not supported yet! Passed class type: %s', \get_class($entity))); + throw new EntityNotSupportedException(sprintf('The given entity is not supported yet! Passed class type: %s', get_class($entity))); } return $map[$class]; diff --git a/src/Services/FAIconGenerator.php b/src/Services/FAIconGenerator.php index 80b8e944..dd2a3c08 100644 --- a/src/Services/FAIconGenerator.php +++ b/src/Services/FAIconGenerator.php @@ -25,6 +25,8 @@ declare(strict_types=1); namespace App\Services; use App\Entity\Attachments\Attachment; +use function in_array; +use InvalidArgumentException; class FAIconGenerator { @@ -53,12 +55,12 @@ class FAIconGenerator public function fileExtensionToFAType(string $extension): string { if ('' === $extension) { - throw new \InvalidArgumentException('You must specify an extension!'); + throw new InvalidArgumentException('You must specify an extension!'); } //Normalize file extension $extension = strtolower($extension); foreach (self::EXT_MAPPING as $fa => $exts) { - if (\in_array($extension, $exts, true)) { + if (in_array($extension, $exts, true)) { return $fa; } } diff --git a/src/Services/MoneyFormatter.php b/src/Services/MoneyFormatter.php index ab5e9937..f977767e 100644 --- a/src/Services/MoneyFormatter.php +++ b/src/Services/MoneyFormatter.php @@ -26,6 +26,7 @@ namespace App\Services; use App\Entity\PriceInformations\Currency; use Locale; +use NumberFormatter; class MoneyFormatter { @@ -55,7 +56,7 @@ class MoneyFormatter $iso_code = $currency->getIsoCode(); } - $number_formatter = new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY); + $number_formatter = new NumberFormatter($this->locale, NumberFormatter::CURRENCY); if ($show_all_digits) { $number_formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $decimals); } else { diff --git a/src/Services/TranslationExtractor/PermissionExtractor.php b/src/Services/TranslationExtractor/PermissionExtractor.php index d890cef0..daba6c08 100644 --- a/src/Services/TranslationExtractor/PermissionExtractor.php +++ b/src/Services/TranslationExtractor/PermissionExtractor.php @@ -32,7 +32,7 @@ use Symfony\Component\Translation\MessageCatalogue; * The purpose of this class is to extract label attributes out of our permissions.yaml structure, * so they can be translated. */ -class PermissionExtractor implements ExtractorInterface +final class PermissionExtractor implements ExtractorInterface { protected $permission_structure; protected $finished = false; diff --git a/src/Twig/AppExtension.php b/src/Twig/AppExtension.php index 6d6c7b04..4db01dca 100644 --- a/src/Twig/AppExtension.php +++ b/src/Twig/AppExtension.php @@ -78,7 +78,10 @@ class AppExtension extends AbstractExtension { return [ new TwigFilter('entityURL', [$this, 'generateEntityURL']), - new TwigFilter('markdown', [$this->markdownParser, 'markForRendering'], ['pre_escape' => 'html', 'is_safe' => ['html']]), + new TwigFilter('markdown', [$this->markdownParser, 'markForRendering'], [ + 'pre_escape' => 'html', + 'is_safe' => ['html'], + ]), new TwigFilter('moneyFormat', [$this, 'formatCurrency']), new TwigFilter('siFormat', [$this, 'siFormat']), new TwigFilter('amountFormat', [$this, 'amountFormat']), diff --git a/src/Validator/Constraints/NoneOfItsChildren.php b/src/Validator/Constraints/NoneOfItsChildren.php index ed844cf0..ad3eb4f4 100644 --- a/src/Validator/Constraints/NoneOfItsChildren.php +++ b/src/Validator/Constraints/NoneOfItsChildren.php @@ -34,9 +34,13 @@ use Symfony\Component\Validator\Constraint; */ class NoneOfItsChildren extends Constraint { - /** @var string The message used if it is tried to assign a object as its own parent */ + /** + * @var string The message used if it is tried to assign a object as its own parent + */ public $self_message = 'validator.noneofitschild.self'; - /** @var string The message used if it is tried to use one of the children for as parent */ + /** + * @var string The message used if it is tried to use one of the children for as parent + */ public $children_message = 'validator.noneofitschild.children'; public function validatedBy() diff --git a/src/Validator/Constraints/UrlOrBuiltin.php b/src/Validator/Constraints/UrlOrBuiltin.php index 61c02b7b..8aeff7ab 100644 --- a/src/Validator/Constraints/UrlOrBuiltin.php +++ b/src/Validator/Constraints/UrlOrBuiltin.php @@ -34,6 +34,8 @@ use Symfony\Component\Validator\Constraints\Url; */ class UrlOrBuiltin extends Url { - /** @var array A list of the placeholders that are treated as builtin */ + /** + * @var array A list of the placeholders that are treated as builtin + */ public $allowed_placeholders = Attachment::BUILTIN_PLACEHOLDER; } diff --git a/tests/Entity/Attachments/AttachmentTest.php b/tests/Entity/Attachments/AttachmentTest.php index 1fd2ec98..21696088 100644 --- a/tests/Entity/Attachments/AttachmentTest.php +++ b/tests/Entity/Attachments/AttachmentTest.php @@ -49,6 +49,7 @@ use App\Entity\Parts\Supplier; use App\Entity\PriceInformations\Currency; use App\Entity\UserSystem\Group; use App\Entity\UserSystem\User; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; use ReflectionClass; @@ -114,7 +115,7 @@ class AttachmentTest extends TestCase */ public function testSetElementExceptionOnSubClasses(string $attachment_class, string $allowed_class): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); /** @var Attachment $attachment */ $attachment = new $attachment_class(); diff --git a/tests/Entity/Parts/PartLotTest.php b/tests/Entity/Parts/PartLotTest.php index d5ed40c8..a78f3473 100644 --- a/tests/Entity/Parts/PartLotTest.php +++ b/tests/Entity/Parts/PartLotTest.php @@ -25,6 +25,7 @@ declare(strict_types=1); namespace App\Tests\Entity\Parts; use App\Entity\Parts\PartLot; +use DateTime; use PHPUnit\Framework\TestCase; class PartLotTest extends TestCase @@ -34,7 +35,7 @@ class PartLotTest extends TestCase $lot = new PartLot(); $this->assertNull($lot->isExpired(), 'Lot must be return null when no Expiration date is set!'); - $datetime = new \DateTime(); + $datetime = new DateTime(); $lot->setExpirationDate($datetime->setTimestamp(strtotime('now +1 hour'))); $this->assertFalse($lot->isExpired(), 'Lot with expiration date in the future must not be expired!'); diff --git a/tests/Entity/Parts/PartTest.php b/tests/Entity/Parts/PartTest.php index c3f7d1cf..71c56df6 100644 --- a/tests/Entity/Parts/PartTest.php +++ b/tests/Entity/Parts/PartTest.php @@ -27,6 +27,7 @@ namespace App\Tests\Entity\Parts; use App\Entity\Parts\MeasurementUnit; use App\Entity\Parts\Part; use App\Entity\Parts\PartLot; +use DateTime; use Doctrine\Common\Collections\Collection; use PHPUnit\Framework\TestCase; @@ -86,7 +87,7 @@ class PartTest extends TestCase { $part = new Part(); $measurement_unit = new MeasurementUnit(); - $datetime = new \DateTime(); + $datetime = new DateTime(); $this->assertSame(0.0, $part->getAmountSum()); diff --git a/tests/Entity/StructuralDBElementTest.php b/tests/Entity/StructuralDBElementTest.php index 3125e3c9..f56aa84e 100644 --- a/tests/Entity/StructuralDBElementTest.php +++ b/tests/Entity/StructuralDBElementTest.php @@ -26,6 +26,7 @@ namespace App\Tests\Entity; use App\Entity\Attachments\AttachmentType; use App\Entity\Parts\Category; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; use Symfony\Component\Yaml\Tests\A; @@ -84,7 +85,7 @@ class StructuralDBElementTest extends TestCase public function testChildOfDifferentClasses(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $category = new Category(); $this->root->isChildOf($category); } diff --git a/tests/Entity/UserSystem/PermissionsEmbedTest.php b/tests/Entity/UserSystem/PermissionsEmbedTest.php index fa7b308d..14b3ebeb 100644 --- a/tests/Entity/UserSystem/PermissionsEmbedTest.php +++ b/tests/Entity/UserSystem/PermissionsEmbedTest.php @@ -26,7 +26,9 @@ namespace App\Tests\Entity\UserSystem; use App\Entity\UserSystem\PermissionsEmbed; use Doctrine\ORM\Mapping\Embedded; +use InvalidArgumentException; use PHPUnit\Framework\TestCase; +use ReflectionClass; class PermissionsEmbedTest extends TestCase { @@ -60,7 +62,7 @@ class PermissionsEmbedTest extends TestCase $this->assertNull($embed->getPermissionValue(PermissionsEmbed::USERS, 0)); //Set a value for testing to the part property - $reflection = new \ReflectionClass($embed); + $reflection = new ReflectionClass($embed); $property = $reflection->getProperty('parts'); $property->setAccessible(true); @@ -79,7 +81,7 @@ class PermissionsEmbedTest extends TestCase $embed = new PermissionsEmbed(); //Set a value for testing to the part property - $reflection = new \ReflectionClass($embed); + $reflection = new ReflectionClass($embed); $property = $reflection->getProperty('parts'); $property->setAccessible(true); @@ -97,7 +99,7 @@ class PermissionsEmbedTest extends TestCase { $embed = new PermissionsEmbed(); //When encoutering an unknown permission name the class must throw an exception - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $embed->getPermissionValue('invalid', 0); } @@ -105,7 +107,7 @@ class PermissionsEmbedTest extends TestCase { $embed = new PermissionsEmbed(); //When encoutering an negative bit the class must throw an exception - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $embed->getPermissionValue('parts', -1); } @@ -113,7 +115,7 @@ class PermissionsEmbedTest extends TestCase { $embed = new PermissionsEmbed(); //When encoutering an odd bit number it must throw an error. - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $embed->getPermissionValue('parts', 1); } @@ -121,7 +123,7 @@ class PermissionsEmbedTest extends TestCase { $embed = new PermissionsEmbed(); //When encoutering an too high bit number it must throw an error. - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $embed->getPermissionValue('parts', 32); } diff --git a/tests/Entity/UserSystem/UserTest.php b/tests/Entity/UserSystem/UserTest.php index e82f2840..5e7c432d 100644 --- a/tests/Entity/UserSystem/UserTest.php +++ b/tests/Entity/UserSystem/UserTest.php @@ -26,6 +26,7 @@ namespace App\Tests\Entity\UserSystem; use App\Entity\UserSystem\U2FKey; use App\Entity\UserSystem\User; +use DateTime; use PHPUnit\Framework\TestCase; class UserTest extends TestCase @@ -69,7 +70,7 @@ class UserTest extends TestCase $codes = ['test', 'invalid', 'test']; $user->setBackupCodes($codes); // Backup Codes generation date must be changed! - $this->assertEqualsWithDelta(new \DateTime(), $user->getBackupCodesGenerationDate(), 0.1); + $this->assertEqualsWithDelta(new DateTime(), $user->getBackupCodesGenerationDate(), 0.1); $this->assertSame($codes, $user->getBackupCodes()); //Test what happens if we delete the backup keys diff --git a/tests/Repository/NamedDBElementRepositoryTest.php b/tests/Repository/NamedDBElementRepositoryTest.php index 0487c9d1..3a849161 100644 --- a/tests/Repository/NamedDBElementRepositoryTest.php +++ b/tests/Repository/NamedDBElementRepositoryTest.php @@ -35,7 +35,9 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class NamedDBElementRepositoryTest extends WebTestCase { private $entityManager; - /** @var StructuralDBElementRepository */ + /** + * @var StructuralDBElementRepository + */ private $repo; protected function setUp(): void diff --git a/tests/Repository/StructuralDBElementRepositoryTest.php b/tests/Repository/StructuralDBElementRepositoryTest.php index e3157abc..7d7b38a8 100644 --- a/tests/Repository/StructuralDBElementRepositoryTest.php +++ b/tests/Repository/StructuralDBElementRepositoryTest.php @@ -35,7 +35,9 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class StructuralDBElementRepositoryTest extends WebTestCase { private $entityManager; - /** @var StructuralDBElementRepository */ + /** + * @var StructuralDBElementRepository + */ private $repo; protected function setUp(): void diff --git a/tests/Services/AmountFormatterTest.php b/tests/Services/AmountFormatterTest.php index 85dee35f..d15dd48a 100644 --- a/tests/Services/AmountFormatterTest.php +++ b/tests/Services/AmountFormatterTest.php @@ -26,6 +26,7 @@ namespace App\Tests\Services; use App\Entity\Parts\MeasurementUnit; use App\Services\AmountFormatter; +use InvalidArgumentException; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class AmountFormatterTest extends WebTestCase @@ -55,7 +56,7 @@ class AmountFormatterTest extends WebTestCase public function testInvalidInput(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->service->format('test'); } @@ -83,8 +84,14 @@ class AmountFormatterTest extends WebTestCase public function testFormatMoreDigits(): void { - $this->assertSame('12.12345', $this->service->format(12.1234532, null, ['is_integer' => false, 'decimals' => 5])); - $this->assertSame('12.1', $this->service->format(12.1234532, null, ['is_integer' => false, 'decimals' => 1])); + $this->assertSame('12.12345', $this->service->format(12.1234532, null, [ + 'is_integer' => false, + 'decimals' => 5, + ])); + $this->assertSame('12.1', $this->service->format(12.1234532, null, [ + 'is_integer' => false, + 'decimals' => 1, + ])); } public function testFormatOptionsOverride(): void diff --git a/tests/Services/Attachments/AttachmentPathResolverTest.php b/tests/Services/Attachments/AttachmentPathResolverTest.php index 26be1b19..c69ebdc0 100644 --- a/tests/Services/Attachments/AttachmentPathResolverTest.php +++ b/tests/Services/Attachments/AttachmentPathResolverTest.php @@ -26,18 +26,19 @@ namespace App\Tests\Services\Attachments; use App\Services\AmountFormatter; use App\Services\Attachments\AttachmentPathResolver; +use const DIRECTORY_SEPARATOR; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class AttachmentPathResolverTest extends WebTestCase { public static $media_path; public static $footprint_path; + protected static $projectDir_orig; + protected static $projectDir; /** * @var AmountFormatter */ protected static $service; - protected static $projectDir_orig; - protected static $projectDir; public function __construct($name = null, array $data = [], $dataName = '') { @@ -68,8 +69,8 @@ class AttachmentPathResolverTest extends WebTestCase $this->assertSame(self::$projectDir_orig, self::$service->parameterToAbsolutePath(self::$projectDir)); //Relative pathes should be resolved - $this->assertSame(self::$projectDir_orig.\DIRECTORY_SEPARATOR.'src', self::$service->parameterToAbsolutePath('src')); - $this->assertSame(self::$projectDir_orig.\DIRECTORY_SEPARATOR.'src', self::$service->parameterToAbsolutePath('./src')); + $this->assertSame(self::$projectDir_orig.DIRECTORY_SEPARATOR.'src', self::$service->parameterToAbsolutePath('src')); + $this->assertSame(self::$projectDir_orig.DIRECTORY_SEPARATOR.'src', self::$service->parameterToAbsolutePath('./src')); //Invalid pathes should return null $this->assertNull(self::$service->parameterToAbsolutePath('/this/path/does/not/exist')); diff --git a/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php b/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php index 04b37d74..cdaa83ce 100644 --- a/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php +++ b/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php @@ -29,13 +29,14 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class BuiltinAttachmentsFinderTest extends WebTestCase { - /** @var BuiltinAttachmentsFinder */ - protected static $service; - protected static $mock_list = [ '%FOOTPRINTS%/test/test.jpg', '%FOOTPRINTS%/test/test.png', '%FOOTPRINTS%/123.jpg', '%FOOTPRINTS%/123.jpeg', '%FOOTPRINTS_3D%/test.jpg', '%FOOTPRINTS_3D%/hallo.txt', ]; + /** + * @var BuiltinAttachmentsFinder + */ + protected static $service; public static function setUpBeforeClass(): void { diff --git a/tests/Services/PermissionResolverTest.php b/tests/Services/PermissionResolverTest.php index 09461d82..002eed9a 100644 --- a/tests/Services/PermissionResolverTest.php +++ b/tests/Services/PermissionResolverTest.php @@ -28,19 +28,20 @@ use App\Entity\UserSystem\Group; use App\Entity\UserSystem\PermissionsEmbed; use App\Entity\UserSystem\User; use App\Services\PermissionResolver; +use InvalidArgumentException; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class PermissionResolverTest extends WebTestCase { + protected $user_withoutGroup; + + protected $user; + protected $group; /** * @var PermissionResolver */ protected $service; - protected $user; - protected $user_withoutGroup; - protected $group; - protected function setUp(): void { parent::setUp(); // TODO: Change the autogenerated stub @@ -132,7 +133,7 @@ class PermissionResolverTest extends WebTestCase public function testInvalidListOperationsForPermission(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); //Must throw an exception $this->service->listOperationsForPermission('invalid'); } diff --git a/tests/Services/TFA/BackupCodeGeneratorTest.php b/tests/Services/TFA/BackupCodeGeneratorTest.php index 87e2320a..04f1bcc4 100644 --- a/tests/Services/TFA/BackupCodeGeneratorTest.php +++ b/tests/Services/TFA/BackupCodeGeneratorTest.php @@ -26,6 +26,7 @@ namespace App\Tests\Services\TFA; use App\Services\TFA\BackupCodeGenerator; use PHPUnit\Framework\TestCase; +use RuntimeException; class BackupCodeGeneratorTest extends TestCase { @@ -34,7 +35,7 @@ class BackupCodeGeneratorTest extends TestCase */ public function testLengthUpperLimit(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); new BackupCodeGenerator(33, 10); } @@ -43,7 +44,7 @@ class BackupCodeGeneratorTest extends TestCase */ public function testLengthLowerLimit(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); new BackupCodeGenerator(4, 10); } diff --git a/tests/Services/Trees/NodesListBuilderTest.php b/tests/Services/Trees/NodesListBuilderTest.php index 37e963e0..3458cfdd 100644 --- a/tests/Services/Trees/NodesListBuilderTest.php +++ b/tests/Services/Trees/NodesListBuilderTest.php @@ -34,11 +34,11 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; */ class NodesListBuilderTest extends WebTestCase { + protected $em; /** * @var NodesListBuilder */ protected $service; - protected $em; protected function setUp(): void { diff --git a/tests/Services/Trees/TreeViewGeneratorTest.php b/tests/Services/Trees/TreeViewGeneratorTest.php index 74c1c521..1cd36ca7 100644 --- a/tests/Services/Trees/TreeViewGeneratorTest.php +++ b/tests/Services/Trees/TreeViewGeneratorTest.php @@ -36,11 +36,11 @@ use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; */ class TreeViewGeneratorTest extends WebTestCase { + protected $em; /** * @var TreeViewGenerator */ protected $service; - protected $em; protected function setUp(): void {