diff --git a/.php_cs.cache b/.php_cs.cache new file mode 100644 index 00000000..76d211ab --- /dev/null +++ b/.php_cs.cache @@ -0,0 +1 @@ +{"php":"7.3.6","version":"2.16.0:v2.16.0#ceaff36bee1ed3f1bbbedca36d2528c0826c336d","indent":" ","lineEnding":"\n","rules":{"array_syntax":{"syntax":"short"},"binary_operator_spaces":true,"blank_line_after_opening_tag":true,"blank_line_before_statement":{"statements":["return"]},"braces":{"allow_single_line_closure":true},"cast_spaces":true,"class_attributes_separation":{"elements":["method"]},"class_definition":{"single_line":true},"concat_space":true,"declare_equal_normalize":true,"function_typehint_space":true,"include":true,"increment_style":true,"lowercase_cast":true,"lowercase_static_reference":true,"magic_constant_casing":true,"magic_method_casing":true,"method_argument_space":true,"native_function_casing":true,"native_function_type_declaration_casing":true,"new_with_braces":true,"no_blank_lines_after_class_opening":true,"no_blank_lines_after_phpdoc":true,"no_empty_comment":true,"no_empty_phpdoc":true,"no_empty_statement":true,"no_extra_blank_lines":{"tokens":["curly_brace_block","extra","parenthesis_brace_block","square_brace_block","throw","use"]},"no_leading_import_slash":true,"no_leading_namespace_whitespace":true,"no_mixed_echo_print":true,"no_multiline_whitespace_around_double_arrow":true,"no_short_bool_cast":true,"no_singleline_whitespace_before_semicolons":true,"no_spaces_around_offset":true,"no_superfluous_phpdoc_tags":{"allow_mixed":true,"allow_unused_params":true},"no_trailing_comma_in_list_call":true,"no_trailing_comma_in_singleline_array":true,"no_unneeded_control_parentheses":true,"no_unneeded_curly_braces":true,"no_unneeded_final_method":true,"no_unused_imports":true,"no_whitespace_before_comma_in_array":true,"no_whitespace_in_blank_line":true,"normalize_index_brace":true,"object_operator_without_whitespace":true,"ordered_imports":true,"php_unit_fqcn_annotation":true,"phpdoc_align":{"tags":["method","param","property","return","throws","type","var"]},"phpdoc_annotation_without_dot":true,"phpdoc_indent":true,"phpdoc_inline_tag":true,"phpdoc_no_access":true,"phpdoc_no_alias_tag":true,"phpdoc_no_package":true,"phpdoc_no_useless_inheritdoc":true,"phpdoc_return_self_reference":true,"phpdoc_scalar":true,"phpdoc_separation":true,"phpdoc_single_line_var_spacing":true,"phpdoc_summary":true,"phpdoc_to_comment":true,"phpdoc_trim":true,"phpdoc_trim_consecutive_blank_line_separation":true,"phpdoc_types":true,"phpdoc_types_order":{"null_adjustment":"always_last","sort_algorithm":"none"},"phpdoc_var_without_name":true,"return_type_declaration":true,"semicolon_after_instruction":true,"short_scalar_cast":true,"single_blank_line_before_namespace":true,"single_class_element_per_statement":true,"single_line_comment_style":{"comment_types":["hash"]},"single_line_throw":true,"single_quote":true,"single_trait_insert_per_statement":true,"space_after_semicolon":{"remove_in_empty_for_expressions":true},"standardize_increment":true,"standardize_not_equals":true,"ternary_operator_spaces":true,"trailing_comma_in_multiline_array":true,"trim_array_spaces":true,"unary_operator_spaces":true,"whitespace_after_comma_in_array":true,"yoda_style":true,"blank_line_after_namespace":true,"constant_case":true,"elseif":true,"function_declaration":true,"indentation_type":true,"line_ending":true,"lowercase_keywords":true,"no_break_comment":true,"no_closing_tag":true,"no_spaces_after_function_name":true,"no_spaces_inside_parenthesis":true,"no_trailing_whitespace":true,"no_trailing_whitespace_in_comment":true,"single_blank_line_at_eof":true,"single_import_per_statement":true,"single_line_after_imports":true,"switch_case_semicolon_to_colon":true,"switch_case_space":true,"visibility_required":true,"encoding":true,"full_opening_tag":true,"dir_constant":true,"ereg_to_preg":true,"error_suppression":true,"fopen_flag_order":true,"function_to_constant":true,"implode_call":true,"is_null":true,"modernize_types_casting":true,"native_constant_invocation":{"fix_built_in":false,"include":["DIRECTORY_SEPARATOR","PHP_SAPI","PHP_VERSION_ID"],"scope":"namespaced"},"native_function_invocation":{"include":["@compiler_optimized"],"scope":"namespaced","strict":true},"no_alias_functions":true,"no_homoglyph_names":true,"non_printable_character":true,"php_unit_construct":true,"php_unit_mock_short_will_return":true,"psr4":true,"self_accessor":true,"set_type_to_cast":true,"php_unit_dedicate_assert_internal_type":{"target":"7.5"},"php_unit_namespaced":{"target":"6.0"},"php_unit_dedicate_assert":{"target":"5.6"},"php_unit_expectation":{"target":"5.6"},"php_unit_mock":{"target":"5.5"},"php_unit_no_expectation_annotation":{"target":"4.3"},"combine_nested_dirname":true},"hashes":{"src\\Command\\CleanAttachmentsCommand.php":2908442282,"src\\Command\\ConvertBBCodeCommand.php":2987395581,"src\\Command\\SetPasswordCommand.php":2214878570,"src\\Command\\UpdateExchangeRatesCommand.php":2478314487,"src\\Configuration\\PermissionsConfiguration.php":2292703041,"src\\Controller\\AdminPages\\AttachmentTypeController.php":2043735562,"src\\Controller\\AdminPages\\BaseAdminController.php":199943669,"src\\Controller\\AdminPages\\CategoryController.php":2332760319,"src\\Controller\\AdminPages\\CurrencyController.php":1707599961,"src\\Controller\\AdminPages\\DeviceController.php":1643684955,"src\\Controller\\AdminPages\\FootprintController.php":4274611247,"src\\Controller\\AdminPages\\ManufacturerController.php":398603842,"src\\Controller\\AdminPages\\MeasurementUnitController.php":3602410282,"src\\Controller\\AdminPages\\StorelocationController.php":2319716752,"src\\Controller\\AdminPages\\SupplierController.php":981802406,"src\\Controller\\AttachmentFileController.php":1843792477,"src\\Controller\\DebugController.php":1887303631,"src\\Controller\\GroupController.php":2553259838,"src\\Controller\\HomepageController.php":890878176,"src\\Controller\\PartController.php":422633708,"src\\Controller\\PartListsController.php":2203269023,"src\\Controller\\RedirectController.php":3017636547,"src\\Controller\\SecurityController.php":3402949811,"src\\Controller\\TreeController.php":1098072083,"src\\Controller\\TypeaheadController.php":701921162,"src\\Controller\\UserController.php":2302195322,"src\\DataFixtures\\AppFixtures.php":2963967304,"src\\DataFixtures\\DataStructureFixtures.php":431104433,"src\\DataFixtures\\GroupFixtures.php":3858137367,"src\\DataFixtures\\UserFixtures.php":3167825813,"src\\DataTables\\AttachmentDataTable.php":4057506203,"src\\DataTables\\Column\\EntityColumn.php":1510470116,"src\\DataTables\\Column\\LocaleDateTimeColumn.php":908976159,"src\\DataTables\\PartsDataTable.php":190824757,"src\\Entity\\Attachments\\Attachment.php":3179331481,"src\\Entity\\Attachments\\AttachmentContainingDBElement.php":1075739443,"src\\Entity\\Attachments\\AttachmentType.php":2791499020,"src\\Entity\\Attachments\\AttachmentTypeAttachment.php":2485692758,"src\\Entity\\Attachments\\CategoryAttachment.php":2403256637,"src\\Entity\\Attachments\\CurrencyAttachment.php":24135120,"src\\Entity\\Attachments\\DeviceAttachment.php":2324000529,"src\\Entity\\Attachments\\FootprintAttachment.php":2560722039,"src\\Entity\\Attachments\\GroupAttachment.php":3895624202,"src\\Entity\\Attachments\\ManufacturerAttachment.php":515231899,"src\\Entity\\Attachments\\MeasurementUnitAttachment.php":3485510744,"src\\Entity\\Attachments\\PartAttachment.php":4250738841,"src\\Entity\\Attachments\\StorelocationAttachment.php":3453695181,"src\\Entity\\Attachments\\SupplierAttachment.php":3954069882,"src\\Entity\\Attachments\\UserAttachment.php":4186678762,"src\\Entity\\Base\\Company.php":1915616836,"src\\Entity\\Base\\DBElement.php":1101919543,"src\\Entity\\Base\\MasterAttachmentTrait.php":837971824,"src\\Entity\\Base\\NamedDBElement.php":803194601,"src\\Entity\\Base\\PartsContainingDBElement.php":646909351,"src\\Entity\\Base\\StructuralDBElement.php":2044199864,"src\\Entity\\Base\\TimestampTrait.php":2708737647,"src\\Entity\\Devices\\Device.php":1508962504,"src\\Entity\\Devices\\DevicePart.php":35018670,"src\\Entity\\Parts\\Category.php":774843680,"src\\Entity\\Parts\\Footprint.php":3859634492,"src\\Entity\\Parts\\Manufacturer.php":3809823616,"src\\Entity\\Parts\\MeasurementUnit.php":2912156176,"src\\Entity\\Parts\\Part.php":4192739584,"src\\Entity\\Parts\\PartLot.php":2180429772,"src\\Entity\\Parts\\PartTraits\\AdvancedPropertyTrait.php":1202738823,"src\\Entity\\Parts\\PartTraits\\BasicPropertyTrait.php":4185734632,"src\\Entity\\Parts\\PartTraits\\InstockTrait.php":1873097051,"src\\Entity\\Parts\\PartTraits\\ManufacturerTrait.php":3468487154,"src\\Entity\\Parts\\PartTraits\\OrderTrait.php":3932234196,"src\\Entity\\Parts\\Storelocation.php":2765793307,"src\\Entity\\Parts\\Supplier.php":3420235130,"src\\Entity\\PriceInformations\\Currency.php":1085803866,"src\\Entity\\PriceInformations\\Orderdetail.php":2190484276,"src\\Entity\\PriceInformations\\Pricedetail.php":4018021368,"src\\Entity\\UserSystem\\Group.php":403305251,"src\\Entity\\UserSystem\\PermissionsEmbed.php":205366727,"src\\Entity\\UserSystem\\User.php":4200871585,"src\\EntityListeners\\AttachmentDeleteListener.php":3708835753,"src\\EntityListeners\\TreeCacheInvalidationListener.php":4271177067,"src\\EventSubscriber\\LoginSuccessListener.php":3290811941,"src\\EventSubscriber\\LogoutOnDisabledUserListener.php":1379035211,"src\\EventSubscriber\\SymfonyDebugToolbarSubscriber.php":3244347947,"src\\EventSubscriber\\TimezoneListener.php":1719734434,"src\\Exceptions\\AttachmentDownloadException.php":2916573626,"src\\Exceptions\\EntityNotSupportedException.php":2435284975,"src\\Form\\AdminPages\\AttachmentTypeAdminForm.php":2650814797,"src\\Form\\AdminPages\\BaseEntityAdminForm.php":707930465,"src\\Form\\AdminPages\\CategoryAdminForm.php":3496349857,"src\\Form\\AdminPages\\CompanyForm.php":1291902630,"src\\Form\\AdminPages\\CurrencyAdminForm.php":2310942389,"src\\Form\\AdminPages\\FootprintAdminForm.php":3045276981,"src\\Form\\AdminPages\\GroupAdminForm.php":3121051016,"src\\Form\\AdminPages\\ImportType.php":4176723793,"src\\Form\\AdminPages\\MassCreationForm.php":888518718,"src\\Form\\AdminPages\\MeasurementUnitAdminForm.php":3004432840,"src\\Form\\AdminPages\\StorelocationAdminForm.php":2323716743,"src\\Form\\AdminPages\\SupplierForm.php":4018499008,"src\\Form\\AttachmentFormType.php":3210088880,"src\\Form\\Part\\OrderdetailType.php":2662506322,"src\\Form\\Part\\PartBaseType.php":898045911,"src\\Form\\Part\\PartLotType.php":2338377803,"src\\Form\\Part\\PricedetailType.php":1490806012,"src\\Form\\Permissions\\PermissionGroupType.php":2524182940,"src\\Form\\Permissions\\PermissionsMapper.php":1163401752,"src\\Form\\Permissions\\PermissionsType.php":1106564554,"src\\Form\\Permissions\\PermissionType.php":331672534,"src\\Form\\Type\\CurrencyEntityType.php":3759799614,"src\\Form\\Type\\MasterPictureAttachmentType.php":2603681397,"src\\Form\\Type\\SIUnitType.php":2016913257,"src\\Form\\Type\\StructuralEntityType.php":589624973,"src\\Form\\Type\\TriStateCheckboxType.php":1561238730,"src\\Form\\UserAdminForm.php":1522499243,"src\\Form\\UserSettingsType.php":2161828990,"src\\Helpers\\BBCodeToMarkdownConverter.php":96305637,"src\\Helpers\\TreeViewNode.php":4023335168,"src\\Helpers\\TreeViewNodeState.php":1494408863,"src\\Helpers\\UTCDateTimeType.php":2732968354,"src\\Kernel.php":1116622545,"src\\Migrations\\Version1.php":4120408624,"src\\Migrations\\Version20190902140506.php":3292952863,"src\\Migrations\\Version20190913141126.php":2563793341,"src\\Migrations\\Version20190924113252.php":3219990553,"src\\Repository\\PartRepository.php":2577496518,"src\\Repository\\StructuralDBElementRepository.php":677611017,"src\\Repository\\UserRepository.php":3545774539,"src\\Security\\Annotations\\ColumnSecurity.php":566606204,"src\\Security\\EntityListeners\\ElementPermissionListener.php":2460254839,"src\\Security\\Interfaces\\HasPermissionsInterface.php":2020026839,"src\\Security\\UserChecker.php":3891573841,"src\\Security\\Voter\\AttachmentVoter.php":831559087,"src\\Security\\Voter\\ExtendedVoter.php":849288942,"src\\Security\\Voter\\GroupVoter.php":3159044518,"src\\Security\\Voter\\PartVoter.php":44030195,"src\\Security\\Voter\\PermissionVoter.php":3336939541,"src\\Security\\Voter\\StructureVoter.php":2372406494,"src\\Security\\Voter\\UserVoter.php":2043762541,"src\\Services\\AmountFormatter.php":1174463127,"src\\Services\\Attachments\\AttachmentManager.php":1767336959,"src\\Services\\Attachments\\AttachmentPathResolver.php":3903709913,"src\\Services\\Attachments\\AttachmentReverseSearch.php":4106615088,"src\\Services\\Attachments\\AttachmentSubmitHandler.php":214831333,"src\\Services\\Attachments\\AttachmentURLGenerator.php":4159809971,"src\\Services\\Attachments\\BuiltinAttachmentsFinder.php":4197852886,"src\\Services\\Attachments\\FileTypeFilterTools.php":2265205006,"src\\Services\\Attachments\\PartPreviewGenerator.php":3296326077,"src\\Services\\ElementTypeNameGenerator.php":1146150845,"src\\Services\\EntityExporter.php":1214704187,"src\\Services\\EntityImporter.php":852222861,"src\\Services\\EntityURLGenerator.php":2045229148,"src\\Services\\GitVersionInfo.php":2876352447,"src\\Services\\MarkdownParser.php":1800926498,"src\\Services\\MoneyFormatter.php":2556966976,"src\\Services\\PermissionResolver.php":2769642819,"src\\Services\\PricedetailHelper.php":698230535,"src\\Services\\SIFormatter.php":1138826431,"src\\Services\\StructuralElementRecursionHelper.php":350965913,"src\\Services\\TagFinder.php":4108516166,"src\\Services\\ToolsTreeBuilder.php":1079849839,"src\\Services\\TranslationExtractor\\PermissionExtractor.php":2379032323,"src\\Services\\TreeBuilder.php":773475422,"src\\Services\\UserCacheKeyGenerator.php":602924229,"src\\Twig\\AppExtension.php":1446709883,"src\\Validator\\Constraints\\AllowedFileExtension.php":2636718005,"src\\Validator\\Constraints\\AllowedFileExtensionValidator.php":2759618947,"src\\Validator\\Constraints\\NoLockout.php":3624981320,"src\\Validator\\Constraints\\NoLockoutValidator.php":3493345860,"src\\Validator\\Constraints\\NoneOfItsChildren.php":1276347049,"src\\Validator\\Constraints\\NoneOfItsChildrenValidator.php":2211921658,"src\\Validator\\Constraints\\Selectable.php":4202102224,"src\\Validator\\Constraints\\SelectableValidator.php":3834058426,"src\\Validator\\Constraints\\UrlOrBuiltin.php":853948628,"src\\Validator\\Constraints\\UrlOrBuiltinValidator.php":3558280999,"src\\Validator\\Constraints\\ValidFileFilter.php":630385033,"src\\Validator\\Constraints\\ValidFileFilterValidator.php":4287615068,"src\\Validator\\Constraints\\ValidPartLot.php":1207490428,"src\\Validator\\Constraints\\ValidPartLotValidator.php":2590613882,"src\\Validator\\Constraints\\ValidPermission.php":2714384844,"src\\Validator\\Constraints\\ValidPermissionValidator.php":2719956864,"tests\\Controller\\AdminPages\\AbstractAdminControllerTest.php":1062895990,"tests\\Controller\\AdminPages\\AttachmentTypeControllerTest.php":1851572998,"tests\\Controller\\AdminPages\\CategoryControllerTest.php":3055054466,"tests\\Controller\\AdminPages\\DeviceControllerTest.php":298260400,"tests\\Controller\\AdminPages\\FootprintControllerTest.php":3545271305,"tests\\Controller\\AdminPages\\ManufacturerControllerTest.php":3593233112,"tests\\Controller\\AdminPages\\MeasurementUnitControllerTest.php":4008297325,"tests\\Controller\\AdminPages\\StorelocationControllerTest.php":3328115423,"tests\\Controller\\AdminPages\\SupplierControllerTest.php":2990639805,"tests\\Controller\\RedirectControllerTest.php":2162110459,"tests\\Entity\\Attachments\\AttachmentTest.php":4196625113,"tests\\Entity\\Attachments\\AttachmentTypeTest.php":2179722054,"tests\\Entity\\Parts\\PartLotTest.php":3186371808,"tests\\Entity\\Parts\\PartTest.php":2431087462,"tests\\Entity\\PriceSystem\\CurrencyTest.php":3047106740,"tests\\Entity\\PriceSystem\\OrderdetailTest.php":3366114275,"tests\\Entity\\PriceSystem\\PricedetailTest.php":2947791329,"tests\\Entity\\StructuralDBElementTest.php":4091822439,"tests\\Entity\\UserSystem\\PermissionsEmbedTest.php":1625719810,"tests\\Entity\\UserSystem\\UserTest.php":3005477241,"tests\\Helpers\\BBCodeToMarkdownConverterTest.php":722308221,"tests\\Helpers\\TreeViewNodeTest.php":479496228,"tests\\Services\\AmountFormatterTest.php":2220293280,"tests\\Services\\Attachments\\AttachmentPathResolverTest.php":1244829604,"tests\\Services\\Attachments\\AttachmentURLGeneratorTest.php":1468896953,"tests\\Services\\Attachments\\BuiltinAttachmentsFinderTest.php":2778824448,"tests\\Services\\Attachments\\FileTypeFilterToolsTest.php":2163556490,"tests\\Services\\PermissionResolverTest.php":2934090111,"tests\\Services\\PricedetailHelperTest.php":2101366552,"tests\\Services\\SIFormatterTest.php":2424942615,".php_cs.dist":3212446582}} \ No newline at end of file diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 00000000..8cb87fc6 --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,30 @@ +setRules([ + '@Symfony' => true, + '@Symfony:risky' => true, + '@PHPUnit75Migration:risky' => true, + 'php_unit_dedicate_assert' => ['target' => '5.6'], + 'array_syntax' => ['syntax' => 'short'], + 'fopen_flags' => false, + 'protected_to_private' => false, + 'combine_nested_dirname' => true, + ]) + ->setRiskyAllowed(true) + ->setFinder( + PhpCsFixer\Finder::create() + ->in(__DIR__.'/src') + ->in(__DIR__.'/tests') + ->append([__FILE__]) + ) + ; diff --git a/src/Command/CleanAttachmentsCommand.php b/src/Command/CleanAttachmentsCommand.php index 912d9aef..49572f76 100644 --- a/src/Command/CleanAttachmentsCommand.php +++ b/src/Command/CleanAttachmentsCommand.php @@ -1,6 +1,6 @@ pathResolver->getMediaPath(); - $io->note("The media path is " . $mediaPath); + $io->note('The media path is '.$mediaPath); $securePath = $this->pathResolver->getSecurePath(); - $io->note("The secure media path is ". $securePath); + $io->note('The secure media path is '.$securePath); $finder = new Finder(); //We look for files in the media folder only @@ -81,7 +76,7 @@ class CleanAttachmentsCommand extends Command $fs = new Filesystem(); - $file_list = array(); + $file_list = []; $table = new Table($output); $table->setHeaders(['Filename', 'MIME Type', 'Last modified date']); @@ -89,20 +84,20 @@ class CleanAttachmentsCommand extends Command foreach ($finder as $file) { //If not attachment object uses this file, print it - if (count($this->reverseSearch->findAttachmentsByFile($file)) == 0) { + if (0 == \count($this->reverseSearch->findAttachmentsByFile($file))) { $file_list[] = $file; $table->addRow([ $fs->makePathRelative($file->getPathname(), $mediaPath), $this->mimeTypeGuesser->guessMimeType($file->getPathname()), - $dateformatter->format($file->getMTime()) + $dateformatter->format($file->getMTime()), ]); } } - 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 @@ -114,27 +109,26 @@ class CleanAttachmentsCommand extends Command //Delete empty folders: $this->removeEmptySubFolders($mediaPath); - $io->success("All abandoned files were removed."); - + $io->success('All abandoned files were removed.'); } else { - $io->success("No abandoned files found."); + $io->success('No abandoned files found.'); } - - } /** - * This function removes all empty folders inside $path. Taken from https://stackoverflow.com/a/1833681 + * This function removes all empty folders inside $path. Taken from https://stackoverflow.com/a/1833681. + * * @param string $path The path in which the empty folders should be deleted + * * @return bool */ protected function removeEmptySubFolders($path) { - $empty=true; - foreach (glob($path . DIRECTORY_SEPARATOR . "*") as $file) - { + $empty = true; + foreach (glob($path.\DIRECTORY_SEPARATOR.'*') as $file) { $empty &= is_dir($file) && $this->removeEmptySubFolders($file); } + return $empty && rmdir($path); } } diff --git a/src/Command/ConvertBBCodeCommand.php b/src/Command/ConvertBBCodeCommand.php index 7a7f5aa5..4b5870c1 100644 --- a/src/Command/ConvertBBCodeCommand.php +++ b/src/Command/ConvertBBCodeCommand.php @@ -1,6 +1,6 @@ ['description', 'comment'], @@ -120,19 +118,19 @@ class ConvertBBCodeCommand extends Command ->select('e'); //Add fields criteria foreach ($properties as $key => $property) { - $qb->orWhere('e.' . $property . ' LIKE ?' . $key); + $qb->orWhere('e.'.$property.' LIKE ?'.$key); $qb->setParameter($key, static::BBCODE_CRITERIA); } //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) { - /** @var NamedDBElement $result */ + /* @var NamedDBElement $result */ $io->writeln( - 'Convert entity: ' . $result->getName() . ' (' . $result->getIDString() . ')', + 'Convert entity: '.$result->getName().' ('.$result->getIDString().')', OutputInterface::VERBOSITY_VERBOSE ); foreach ($properties as $property) { @@ -144,19 +142,18 @@ class ConvertBBCodeCommand extends Command } $io->writeln( 'BBCode (old): ' - . str_replace('\n', ' ', substr($bbcode, 0, 255)), + .str_replace('\n', ' ', substr($bbcode, 0, 255)), OutputInterface::VERBOSITY_VERY_VERBOSE ); $markdown = $this->converter->convert($bbcode); $io->writeln( 'Markdown (new): ' - . str_replace('\n', ' ', substr($markdown, 0, 255)), + .str_replace('\n', ' ', substr($markdown, 0, 255)), OutputInterface::VERBOSITY_VERY_VERBOSE ); $io->writeln('', OutputInterface::VERBOSITY_VERY_VERBOSE); $this->propertyAccessor->setValue($result, $property, $markdown); } - } } @@ -166,6 +163,4 @@ class ConvertBBCodeCommand extends Command $io->success('Changes saved to DB successfully!'); } } - - -} \ No newline at end of file +} diff --git a/src/Command/SetPasswordCommand.php b/src/Command/SetPasswordCommand.php index 98358f31..986ee857 100644 --- a/src/Command/SetPasswordCommand.php +++ b/src/Command/SetPasswordCommand.php @@ -1,6 +1,6 @@ base_current) !== 3) { - $io->error("Choosen Base current is not valid. Check your settings!"); + if (3 !== \strlen($this->base_current)) { + $io->error('Choosen Base current is not valid. Check your settings!'); + return; } - $io->note('Update currency exchange rates with base currency: ' . $this->base_current); + $io->note('Update currency exchange rates with base currency: '.$this->base_current); $service = $input->getOption('service'); $api_key = $input->getOption('api_key'); @@ -88,7 +86,7 @@ class UpdateExchangeRatesCommand extends Command //Check what currencies we need to update: $iso_code = $input->getArgument('iso_code'); $repo = $this->em->getRepository(Currency::class); - $candidates = array(); + $candidates = []; if (!empty($iso_code)) { $candidates = $repo->findBy(['iso_code' => $iso_code]); @@ -101,22 +99,21 @@ class UpdateExchangeRatesCommand extends Command //Iterate over each candidate and update exchange rate foreach ($candidates as $currency) { try { - $rate = $swap->latest($currency->getIsoCode() . '/' . $this->base_current); + $rate = $swap->latest($currency->getIsoCode().'/'.$this->base_current); $currency->setExchangeRate($rate->getValue()); $io->note(sprintf('Set exchange rate of %s to %f', $currency->getIsoCode(), $currency->getExchangeRate())); $this->em->persist($currency); - $success_counter++; + ++$success_counter; } catch (\Exchanger\Exception\Exception $ex) { $io->warning(sprintf('Error updating %s:', $currency->getIsoCode())); $io->warning($ex->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 ea224878..b3d41011 100644 --- a/src/Configuration/PermissionsConfiguration.php +++ b/src/Configuration/PermissionsConfiguration.php @@ -1,6 +1,6 @@ _delete($request, $entity, $recursionHelper); } - /** * @Route("/{id}/edit", requirements={"id"="\d+"}, name="attachment_type_edit") * @Route("/{id}", requirements={"id"="\d+"}) - * @param AttachmentType $entity - * @param Request $request - * @param EntityManagerInterface $em + * * @return Response */ public function edit(AttachmentType $entity, Request $request, EntityManagerInterface $em) @@ -78,9 +68,6 @@ class AttachmentTypeController extends BaseAdminController * @Route("/new", name="attachment_type_new") * @Route("/") * - * @param Request $request - * @param EntityManagerInterface $em - * @param EntityImporter $importer * @return Response */ public function new(Request $request, EntityManagerInterface $em, EntityImporter $importer) @@ -90,8 +77,7 @@ class AttachmentTypeController extends BaseAdminController /** * @Route("/export", name="attachment_type_export_all") - * @param Request $request - * @param EntityManagerInterface $em + * * @return Response */ public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request) @@ -101,13 +87,11 @@ class AttachmentTypeController extends BaseAdminController /** * @Route("/{id}/export", name="attachment_type_export") - * @param Request $request - * @param AttachmentType $entity + * * @return Response */ public function exportEntity(AttachmentType $entity, EntityExporter $exporter, Request $request) { return $this->_exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/BaseAdminController.php b/src/Controller/AdminPages/BaseAdminController.php index 139d94eb..fe545f1e 100644 --- a/src/Controller/AdminPages/BaseAdminController.php +++ b/src/Controller/AdminPages/BaseAdminController.php @@ -1,6 +1,6 @@ entity_class === '' || $this->form_class === '' || $this->twig_template === '' || $this->route_base === '') { + 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!'); } - if ($this->attachment_class === '') { + if ('' === $this->attachment_class) { throw new \InvalidArgumentException('You have to override the $attachment_class value in your subclass!'); } @@ -78,7 +73,6 @@ abstract class BaseAdminController extends AbstractController protected function _edit(NamedDBElement $entity, Request $request, EntityManagerInterface $em) { - $this->denyAccessUnlessGranted('read', $entity); $form = $this->createForm($this->form_class, $entity, ['attachment_class' => $this->attachment_class]); @@ -99,14 +93,14 @@ abstract class BaseAdminController extends AbstractController /** @var $attachment FormInterface */ $options = [ 'secure_attachment' => $attachment['secureFile']->getData(), - 'download_url' => $attachment['downloadURL']->getData() + 'download_url' => $attachment['downloadURL']->getData(), ]; try { $this->attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); } catch (AttachmentDownloadException $ex) { $this->addFlash( 'error', - $this->translator->trans('attachment.download_failed') . ' ' . $ex->getMessage() + $this->translator->trans('attachment.download_failed').' '.$ex->getMessage() ); } } @@ -118,14 +112,14 @@ abstract class BaseAdminController extends AbstractController //Rebuild form, so it is based on the updated data. Important for the parent field! //We can not use dynamic form events here, because the parent entity list is build from database! $form = $this->createForm($this->form_class, $entity, ['attachment_class' => $this->attachment_class]); - } elseif ($form->isSubmitted() && ! $form->isValid()) { + } elseif ($form->isSubmitted() && !$form->isValid()) { $this->addFlash('error', $this->translator->trans('entity.edit_flash.invalid')); } return $this->render($this->twig_template, [ 'entity' => $entity, 'form' => $form->createView(), - 'attachment_helper' => $this->attachmentHelper + 'attachment_helper' => $this->attachmentHelper, ]); } @@ -155,14 +149,14 @@ abstract class BaseAdminController extends AbstractController /** @var $attachment FormInterface */ $options = [ 'secure_attachment' => $attachment['secureFile']->getData(), - 'download_url' => $attachment['downloadURL']->getData() + 'download_url' => $attachment['downloadURL']->getData(), ]; try { $this->attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); } catch (AttachmentDownloadException $ex) { $this->addFlash( 'error', - $this->translator->trans('attachment.download_failed') . ' ' . $ex->getMessage() + $this->translator->trans('attachment.download_failed').' '.$ex->getMessage() ); } } @@ -171,10 +165,10 @@ abstract class BaseAdminController extends AbstractController $em->flush(); $this->addFlash('success', $this->translator->trans('entity.created_flash')); - return $this->redirectToRoute($this->route_base . '_edit', ['id' => $new_entity->getID()]); + return $this->redirectToRoute($this->route_base.'_edit', ['id' => $new_entity->getID()]); } - if ($form->isSubmitted() && ! $form->isValid()) { + if ($form->isSubmitted() && !$form->isValid()) { $this->addFlash('error', $this->translator->trans('entity.created_flash.invalid')); } @@ -187,14 +181,14 @@ abstract class BaseAdminController extends AbstractController $file = $import_form['file']->getData(); $data = $import_form->getData(); - $options = array('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); foreach ($errors as $name => $error) { - /** @var $error ConstraintViolationList */ - $this->addFlash('error', $name . ':' . $error); + /* @var $error ConstraintViolationList */ + $this->addFlash('error', $name.':'.$error); } } @@ -212,8 +206,8 @@ abstract class BaseAdminController extends AbstractController //Show errors to user: foreach ($errors as $name => $error) { - /** @var $error ConstraintViolationList */ - $this->addFlash('error', $name . ':' . $error); + /* @var $error ConstraintViolationList */ + $this->addFlash('error', $name.':'.$error); } } @@ -222,7 +216,7 @@ abstract class BaseAdminController extends AbstractController 'form' => $form->createView(), 'import_form' => $import_form->createView(), 'mass_creation_form' => $mass_creation_form->createView(), - 'attachment_helper' => $this->attachmentHelper + 'attachment_helper' => $this->attachmentHelper, ]); } @@ -259,7 +253,7 @@ abstract class BaseAdminController extends AbstractController $this->addFlash('error', 'csfr_invalid'); } - return $this->redirectToRoute($this->route_base . '_new'); + return $this->redirectToRoute($this->route_base.'_new'); } protected function _exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request) @@ -270,7 +264,7 @@ abstract class BaseAdminController extends AbstractController $entities = $em->getRepository($this->entity_class)->findAll(); - return $exporter->exportEntityFromRequest($entities,$request); + return $exporter->exportEntityFromRequest($entities, $request); } protected function _exportEntity(NamedDBElement $entity, EntityExporter $exporter, Request $request) @@ -279,4 +273,4 @@ abstract class BaseAdminController extends AbstractController return $exporter->exportEntityFromRequest($entity, $request); } -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/CategoryController.php b/src/Controller/AdminPages/CategoryController.php index e135874b..cb7a0a34 100644 --- a/src/Controller/AdminPages/CategoryController.php +++ b/src/Controller/AdminPages/CategoryController.php @@ -1,6 +1,6 @@ _exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/CurrencyController.php b/src/Controller/AdminPages/CurrencyController.php index bbfb65aa..73ad0a59 100644 --- a/src/Controller/AdminPages/CurrencyController.php +++ b/src/Controller/AdminPages/CurrencyController.php @@ -1,6 +1,6 @@ _exportEntity($entity, $exporter, $request); } -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/DeviceController.php b/src/Controller/AdminPages/DeviceController.php index ac33bc0a..85a7223b 100644 --- a/src/Controller/AdminPages/DeviceController.php +++ b/src/Controller/AdminPages/DeviceController.php @@ -1,6 +1,6 @@ _exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/FootprintController.php b/src/Controller/AdminPages/FootprintController.php index 85c9f875..d7e62953 100644 --- a/src/Controller/AdminPages/FootprintController.php +++ b/src/Controller/AdminPages/FootprintController.php @@ -1,6 +1,6 @@ _delete($request, $entity, $recursionHelper); } - /** * @Route("/{id}/edit", requirements={"id"="\d+"}, name="footprint_edit") * @Route("/{id}", requirements={"id"="\d+"}) @@ -82,9 +75,9 @@ class FootprintController extends BaseAdminController /** * @Route("/export", name="footprint_export_all") - * @param Request $request + * * @param SerializerInterface $serializer - * @param EntityManagerInterface $em + * * @return Response */ public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request) @@ -94,13 +87,11 @@ class FootprintController extends BaseAdminController /** * @Route("/{id}/export", name="footprint_export") - * @param Request $request - * @param AttachmentType $entity + * * @return Response */ public function exportEntity(AttachmentType $entity, EntityExporter $exporter, Request $request) { return $this->_exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/ManufacturerController.php b/src/Controller/AdminPages/ManufacturerController.php index 84315c8d..a1bab71b 100644 --- a/src/Controller/AdminPages/ManufacturerController.php +++ b/src/Controller/AdminPages/ManufacturerController.php @@ -1,6 +1,6 @@ _new($request, $em, $importer); } - - /** * @Route("/export", name="manufacturer_export_all") - * @param Request $request + * * @param SerializerInterface $serializer - * @param EntityManagerInterface $em + * * @return Response */ public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request) @@ -93,13 +87,13 @@ class ManufacturerController extends BaseAdminController /** * @Route("/{id}/export", name="manufacturer_export") - * @param Request $request + * * @param Supplier $entity + * * @return Response */ public function exportEntity(Manufacturer $entity, EntityExporter $exporter, Request $request) { return $this->_exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/MeasurementUnitController.php b/src/Controller/AdminPages/MeasurementUnitController.php index b1406a65..efa3bc88 100644 --- a/src/Controller/AdminPages/MeasurementUnitController.php +++ b/src/Controller/AdminPages/MeasurementUnitController.php @@ -1,6 +1,6 @@ _exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/StorelocationController.php b/src/Controller/AdminPages/StorelocationController.php index 501e06d9..a46cfdd9 100644 --- a/src/Controller/AdminPages/StorelocationController.php +++ b/src/Controller/AdminPages/StorelocationController.php @@ -1,6 +1,6 @@ _delete($request, $entity, $recursionHelper); } - /** * @Route("/{id}/edit", requirements={"id"="\d+"}, name="store_location_edit") * @Route("/{id}", requirements={"id"="\d+"}) @@ -79,9 +74,9 @@ class StorelocationController extends BaseAdminController /** * @Route("/export", name="store_location_export_all") - * @param Request $request + * * @param SerializerInterface $serializer - * @param EntityManagerInterface $em + * * @return Response */ public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request) @@ -91,13 +86,13 @@ class StorelocationController extends BaseAdminController /** * @Route("/{id}/export", name="store_location_export") - * @param Request $request + * * @param AttachmentType $entity + * * @return Response */ public function exportEntity(Storelocation $entity, EntityExporter $exporter, Request $request) { return $this->_exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AdminPages/SupplierController.php b/src/Controller/AdminPages/SupplierController.php index 11f65b04..8e62557a 100644 --- a/src/Controller/AdminPages/SupplierController.php +++ b/src/Controller/AdminPages/SupplierController.php @@ -1,6 +1,6 @@ _new($request, $em, $importer); } - /** * @Route("/export", name="supplier_export_all") - * @param Request $request + * * @param SerializerInterface $serializer - * @param EntityManagerInterface $em + * * @return Response */ public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request) @@ -91,13 +86,11 @@ class SupplierController extends BaseAdminController /** * @Route("/{id}/export", name="supplier_export") - * @param Request $request - * @param Supplier $entity + * * @return Response */ public function exportEntity(Supplier $entity, EntityExporter $exporter, Request $request) { return $this->_exportEntity($entity, $exporter, $request); } - -} \ No newline at end of file +} diff --git a/src/Controller/AttachmentFileController.php b/src/Controller/AttachmentFileController.php index 152595bb..334cdd68 100644 --- a/src/Controller/AttachmentFileController.php +++ b/src/Controller/AttachmentFileController.php @@ -1,6 +1,6 @@ toAbsoluteFilePath($attachment); $response = new BinaryFileResponse($file_path); @@ -70,12 +65,12 @@ class AttachmentFileController extends AbstractController } /** - * View the attachment + * View the attachment. * * @Route("/attachment/{id}/view", name="attachment_view") - * @param Attachment $attachment - * @param AttachmentManager $helper + * * @return BinaryFileResponse + * * @throws \Exception */ public function view(Attachment $attachment, AttachmentManager $helper) @@ -90,7 +85,6 @@ class AttachmentFileController extends AbstractController throw new \RuntimeException('The file associated with the attachment is not existing!'); } - $file_path = $helper->toAbsoluteFilePath($attachment); $response = new BinaryFileResponse($file_path); @@ -102,8 +96,7 @@ class AttachmentFileController extends AbstractController /** * @Route("/attachment/list", name="attachment_list") - * @param DataTableFactory $dataTable - * @param Request $request + * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response */ public function attachmentsTable(DataTableFactory $dataTable, Request $request) @@ -118,8 +111,7 @@ class AttachmentFileController extends AbstractController } return $this->render('attachment_list.html.twig', [ - 'datatable' => $table + 'datatable' => $table, ]); } - -} \ No newline at end of file +} diff --git a/src/Controller/DebugController.php b/src/Controller/DebugController.php index c043c5ef..8b3209ec 100644 --- a/src/Controller/DebugController.php +++ b/src/Controller/DebugController.php @@ -1,6 +1,6 @@ addFlash('testkjfd', 'Blabla. This message type should be not know to template!'); - - return $this->render('base.html.twig'); } @@ -81,6 +78,5 @@ class DebugController extends AbstractController $translator->trans('flash.info'); $translator->trans('validator.noLockout'); - } } diff --git a/src/Controller/GroupController.php b/src/Controller/GroupController.php index db7f20ca..c3bbbabe 100644 --- a/src/Controller/GroupController.php +++ b/src/Controller/GroupController.php @@ -1,6 +1,6 @@ _exportEntity($entity, $exporter, $request); } -} \ No newline at end of file +} diff --git a/src/Controller/HomepageController.php b/src/Controller/HomepageController.php index 597d2c46..73426b9a 100644 --- a/src/Controller/HomepageController.php +++ b/src/Controller/HomepageController.php @@ -1,7 +1,7 @@ kernel = $kernel; } - public function getBanner() : string + public function getBanner(): string { $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); } @@ -64,7 +60,7 @@ class HomepageController extends AbstractController return $this->render('homepage.html.twig', [ 'banner' => $this->getBanner(), 'git_branch' => $versionInfo->getGitBranchName(), - 'git_commit' => $versionInfo->getGitCommitHash() + 'git_commit' => $versionInfo->getGitCommitHash(), ]); } } diff --git a/src/Controller/PartController.php b/src/Controller/PartController.php index 69e01a7d..e97ea200 100644 --- a/src/Controller/PartController.php +++ b/src/Controller/PartController.php @@ -1,7 +1,7 @@ $part, 'attachment_helper' => $attachmentHelper, 'pricedetail_helper' => $pricedetailHelper, - 'pictures' => $previewGenerator->getPreviewAttachments($part) + 'pictures' => $previewGenerator->getPreviewAttachments($part), ] ); } @@ -69,10 +66,6 @@ class PartController extends AbstractController /** * @Route("/{id}/edit", name="part_edit") * - * @param Part $part - * - * @param Request $request - * @param EntityManagerInterface $em * @return \Symfony\Component\HttpFoundation\Response */ public function edit(Part $part, Request $request, EntityManagerInterface $em, TranslatorInterface $translator, @@ -90,25 +83,24 @@ class PartController extends AbstractController /** @var $attachment FormInterface */ $options = [ 'secure_attachment' => $attachment['secureFile']->getData(), - 'download_url' => $attachment['downloadURL']->getData() + 'download_url' => $attachment['downloadURL']->getData(), ]; try { $attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); } catch (AttachmentDownloadException $ex) { $this->addFlash( 'error', - $translator->trans('attachment.download_failed') . ' ' . $ex->getMessage() + $translator->trans('attachment.download_failed').' '.$ex->getMessage() ); } } - $em->persist($part); $em->flush(); $this->addFlash('info', $translator->trans('part.edited_flash')); //Reload form, so the SIUnitType entries use the new part unit $form = $this->createForm(PartBaseType::class, $part); - } elseif ($form->isSubmitted() && ! $form->isValid()) { + } elseif ($form->isSubmitted() && !$form->isValid()) { $this->addFlash('error', $translator->trans('part.edited_flash.invalid')); } @@ -122,15 +114,14 @@ class PartController extends AbstractController /** * @Route("/{id}/delete", name="part_delete", methods={"DELETE"}) - * @param Request $request - * @param Part $part + * * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function delete(Request $request, Part $part) { $this->denyAccessUnlessGranted('delete', $part); - if ($this->isCsrfTokenValid('delete' . $part->getId(), $request->request->get('_token'))) { + if ($this->isCsrfTokenValid('delete'.$part->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); //Remove part @@ -148,9 +139,6 @@ class PartController extends AbstractController /** * @Route("/new", name="part_new") * - * @param Request $request - * @param EntityManagerInterface $em - * @param TranslatorInterface $translator * @return \Symfony\Component\HttpFoundation\Response */ public function new(Request $request, EntityManagerInterface $em, TranslatorInterface $translator, @@ -176,14 +164,14 @@ class PartController extends AbstractController /** @var $attachment FormInterface */ $options = [ 'secure_attachment' => $attachment['secureFile']->getData(), - 'download_url' => $attachment['downloadURL']->getData() + 'download_url' => $attachment['downloadURL']->getData(), ]; try { $attachmentSubmitHandler->handleFormSubmit($attachment->getData(), $attachment['file']->getData(), $options); } catch (AttachmentDownloadException $ex) { $this->addFlash( 'error', - $translator->trans('attachment.download_failed') . ' ' . $ex->getMessage() + $translator->trans('attachment.download_failed').' '.$ex->getMessage() ); } } @@ -195,7 +183,7 @@ class PartController extends AbstractController return $this->redirectToRoute('part_edit', ['id' => $new_part->getID()]); } - if ($form->isSubmitted() && ! $form->isValid()) { + if ($form->isSubmitted() && !$form->isValid()) { $this->addFlash('error', $translator->trans('part.created_flash.invalid')); } @@ -203,16 +191,13 @@ class PartController extends AbstractController [ 'part' => $new_part, 'form' => $form->createView(), - 'attachment_helper' => $attachmentHelper + 'attachment_helper' => $attachmentHelper, ]); } /** * @Route("/{id}/clone", name="part_clone") - * @param Part $part - * @param Request $request - * @param EntityManagerInterface $em - * @param TranslatorInterface $translator + * * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\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 81273428..4c364ca4 100644 --- a/src/Controller/PartListsController.php +++ b/src/Controller/PartListsController.php @@ -1,6 +1,6 @@ render('Parts/lists/category_list.html.twig', [ 'datatable' => $table, - 'entity' => $category + 'entity' => $category, ]); } @@ -75,7 +74,7 @@ class PartListsController extends AbstractController return $this->render('Parts/lists/footprint_list.html.twig', [ 'datatable' => $table, - 'entity' => $footprint + 'entity' => $footprint, ]); } @@ -97,7 +96,7 @@ class PartListsController extends AbstractController return $this->render('Parts/lists/manufacturer_list.html.twig', [ 'datatable' => $table, - 'entity' => $manufacturer + 'entity' => $manufacturer, ]); } @@ -119,7 +118,7 @@ class PartListsController extends AbstractController return $this->render('Parts/lists/store_location_list.html.twig', [ 'datatable' => $table, - 'entity' => $storelocation + 'entity' => $storelocation, ]); } @@ -141,16 +140,13 @@ class PartListsController extends AbstractController return $this->render('Parts/lists/supplier_list.html.twig', [ 'datatable' => $table, - 'entity' => $supplier + 'entity' => $supplier, ]); } - /** * @Route("/parts/by_tag/{tag}", name="part_list_tags") - * @param string $tag - * @param Request $request - * @param DataTableFactory $dataTable + * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response */ public function showTag(string $tag, Request $request, DataTableFactory $dataTable) @@ -164,7 +160,7 @@ class PartListsController extends AbstractController return $this->render('Parts/lists/tags_list.html.twig', [ 'tag' => $tag, - 'datatable' => $table + 'datatable' => $table, ]); } @@ -184,16 +180,13 @@ class PartListsController extends AbstractController return $this->render('Parts/lists/search_list.html.twig', [ 'datatable' => $table, - 'keyword' => $keyword + 'keyword' => $keyword, ]); } /** * @Route("/parts", name="parts_show_all") * - * @param Request $request - * @param DataTableFactory $dataTable - * * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response */ public function showAll(Request $request, DataTableFactory $dataTable) diff --git a/src/Controller/RedirectController.php b/src/Controller/RedirectController.php index 21e87eb0..f5ac3abe 100644 --- a/src/Controller/RedirectController.php +++ b/src/Controller/RedirectController.php @@ -1,6 +1,6 @@ isNeedPwChange()) { $this->session->getFlashBag()->add('warning', $this->translator->trans('flash.password_change_needed')); + return $this->redirectToRoute('user_settings', ['_locale' => $locale]); } //$new_url = str_replace($request->getPathInfo(), '/' . $locale . $request->getPathInfo(), $request->getUri()); - $new_url = $request->getUriForPath('/' . $locale . $request->getPathInfo()); + $new_url = $request->getUriForPath('/'.$locale.$request->getPathInfo()); //If either mod_rewrite is not enabled or the index.php version is enforced, add index.php to the string if (($this->enforce_index_php || !$this->checkIfModRewriteAvailable()) - && strpos($new_url, 'index.php') === false) { + && false === strpos($new_url, 'index.php')) { //Like Request::getUriForPath only with index.php - $new_url = $request->getSchemeAndHttpHost(). $request->getBaseUrl().'/index.php/' . $locale . $request->getPathInfo(); + $new_url = $request->getSchemeAndHttpHost().$request->getBaseUrl().'/index.php/'.$locale.$request->getPathInfo(); } + return $this->redirect($new_url); } /** * Check if mod_rewrite is availabe (URL rewriting is possible). * If this is true, we can redirect to /en, otherwise we have to redirect to index.php/en. - * When the PHP is not used via Apache SAPI, we just assume that URL rewriting is available + * When the PHP is not used via Apache SAPI, we just assume that URL rewriting is available. + * * @return bool */ 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); } -} \ No newline at end of file +} diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php index 6d3e52f8..b0753ceb 100644 --- a/src/Controller/SecurityController.php +++ b/src/Controller/SecurityController.php @@ -1,6 +1,6 @@ elementToTreeNode($category); } else { $tree = $builder->typeToTree(Category::class); } - return $this->json($tree, 200, [], ['skip_null_values' => true]); } @@ -73,13 +69,12 @@ class TreeController extends AbstractController */ public function footprintTree(TreeBuilder $builder, Footprint $footprint = null) { - if ($footprint !== null) { + if (null !== $footprint) { $tree[] = $builder->elementToTreeNode($footprint); } else { $tree = $builder->typeToTree(Footprint::class); } - return $this->json($tree, 200, [], ['skip_null_values' => true]); } @@ -89,13 +84,12 @@ class TreeController extends AbstractController */ public function locationTree(TreeBuilder $builder, Storelocation $location = null) { - if ($location !== null) { + if (null !== $location) { $tree[] = $builder->elementToTreeNode($location); } else { $tree = $builder->typeToTree(Storelocation::class); } - return $this->json($tree, 200, [], ['skip_null_values' => true]); } @@ -105,13 +99,12 @@ class TreeController extends AbstractController */ public function manufacturerTree(TreeBuilder $builder, Manufacturer $manufacturer = null) { - if ($manufacturer !== null) { + if (null !== $manufacturer) { $tree[] = $builder->elementToTreeNode($manufacturer); } else { $tree = $builder->typeToTree(Manufacturer::class); } - return $this->json($tree, 200, [], ['skip_null_values' => true]); } @@ -121,13 +114,12 @@ class TreeController extends AbstractController */ public function supplierTree(TreeBuilder $builder, Supplier $supplier = null) { - if ($supplier !== null) { + if (null !== $supplier) { $tree[] = $builder->elementToTreeNode($supplier); } else { $tree = $builder->typeToTree(Supplier::class); } - return $this->json($tree, 200, [], ['skip_null_values' => true]); } @@ -137,15 +129,12 @@ class TreeController extends AbstractController */ public function deviceTree(TreeBuilder $builder, Device $device = null) { - if ($device !== null) { + if (null !== $device) { $tree[] = $builder->elementToTreeNode($device); } else { $tree = $builder->typeToTree(Device::class, null); } - return $this->json($tree, 200, [], ['skip_null_values' => true]); } - - } diff --git a/src/Controller/TypeaheadController.php b/src/Controller/TypeaheadController.php index 7b1579b0..44324ecd 100644 --- a/src/Controller/TypeaheadController.php +++ b/src/Controller/TypeaheadController.php @@ -1,6 +1,6 @@ find($query); - $normalizers = [ - new ObjectNormalizer() + new ObjectNormalizer(), ]; - $encoders = [ - new JsonEncoder() + $encoders = [ + new JsonEncoder(), ]; $serializer = new Serializer($normalizers, $encoders); $data = $serializer->serialize($array, 'json'); + return new JsonResponse($data, 200, [], true); } @@ -67,13 +65,14 @@ class TypeaheadController extends AbstractController $array = $finder->searchTags($query); $normalizers = [ - new ObjectNormalizer() + new ObjectNormalizer(), ]; - $encoders = [ - new JsonEncoder() + $encoders = [ + new JsonEncoder(), ]; $serializer = new Serializer($normalizers, $encoders); $data = $serializer->serialize($array, 'json'); + return new JsonResponse($data, 200, [], true); } -} \ No newline at end of file +} diff --git a/src/Controller/UserController.php b/src/Controller/UserController.php index 689d95a7..957a217d 100644 --- a/src/Controller/UserController.php +++ b/src/Controller/UserController.php @@ -1,6 +1,6 @@ getID() == User::ID_ANONYMOUS) { + 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'); } + return $this->_delete($request, $entity, $recursionHelper); } /** * @Route("/export", name="user_export_all") - * @param Request $request + * * @param SerializerInterface $serializer - * @param EntityManagerInterface $em + * * @return Response */ public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request) @@ -104,8 +101,9 @@ class UserController extends AdminPages\BaseAdminController /** * @Route("/{id}/export", name="user_export") - * @param Request $request + * * @param AttachmentType $entity + * * @return Response */ public function exportEntity(User $entity, EntityExporter $exporter, Request $request) @@ -113,7 +111,6 @@ class UserController extends AdminPages\BaseAdminController return $this->_exportEntity($entity, $exporter, $request); } - /** * @Route("/info", name="user_info_self") * @Route("/{id}/info") @@ -135,17 +132,17 @@ class UserController extends AdminPages\BaseAdminController } //Show permissions to user - $builder = $this->createFormBuilder()->add('permissions',PermissionsType::class, [ + $builder = $this->createFormBuilder()->add('permissions', PermissionsType::class, [ 'mapped' => false, 'disabled' => true, 'inherit' => true, - 'data' => $user + 'data' => $user, ]); return $this->render('Users/user_info.html.twig', [ 'user' => $user, 'avatar' => $avatar, - 'form' => $builder->getForm()->createView() + 'form' => $builder->getForm()->createView(), ]); } @@ -161,8 +158,8 @@ class UserController extends AdminPages\BaseAdminController $page_need_reload = false; - if(!$user instanceof User) { - return new \RuntimeException("This controller only works only for Part-DB User objects!"); + if (!$user instanceof User) { + return new \RuntimeException('This controller only works only for Part-DB User objects!'); } //When user change its settings, he should be logged in fully. @@ -233,7 +230,7 @@ class UserController extends AdminPages\BaseAdminController return $this->render('Users/user_settings.html.twig', [ 'settings_form' => $form->createView(), 'pw_form' => $pw_form->createView(), - 'page_need_reload' => $page_need_reload + 'page_need_reload' => $page_need_reload, ]); } @@ -250,10 +247,10 @@ class UserController extends AdminPages\BaseAdminController * @return string containing either just a URL or a complete image tag * @source https://gravatar.com/site/implement/images/php/ */ - public function getGravatar(?string $email, int $s = 80, string $d = 'mm', string $r = 'g', bool $img = false, array $atts = array()) + public function getGravatar(?string $email, int $s = 80, string $d = 'mm', string $r = 'g', bool $img = false, array $atts = []) { - if ($email === null) { - return ""; + if (null === $email) { + return ''; } $url = 'https://www.gravatar.com/avatar/'; diff --git a/src/DataFixtures/AppFixtures.php b/src/DataFixtures/AppFixtures.php index 2e33b55d..5a92bd37 100644 --- a/src/DataFixtures/AppFixtures.php +++ b/src/DataFixtures/AppFixtures.php @@ -1,6 +1,6 @@ createNodesForClass($type, $manager); @@ -68,7 +61,8 @@ class DataStructureFixtures extends Fixture /** * Creates a datafixture with serveral nodes for the given class. - * @param string $class The class for which the nodes should be generated (must be a StructuralDBElement child) + * + * @param string $class The class for which the nodes should be generated (must be a StructuralDBElement child) * @param ObjectManager $manager The ObjectManager that should be used to persist the nodes */ public function createNodesForClass(string $class, ObjectManager $manager) @@ -116,4 +110,4 @@ class DataStructureFixtures extends Fixture $manager->persist($node2_1); $manager->persist($node1_1_1); } -} \ No newline at end of file +} diff --git a/src/DataFixtures/GroupFixtures.php b/src/DataFixtures/GroupFixtures.php index 7cd274f6..5f7125cd 100644 --- a/src/DataFixtures/GroupFixtures.php +++ b/src/DataFixtures/GroupFixtures.php @@ -1,6 +1,6 @@ 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', - 'measurement_units' => '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); $manager->persist($admins); @@ -54,15 +53,15 @@ 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', - 'measurement_units' => '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); $manager->persist($readonly); @@ -70,15 +69,15 @@ 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', - 'measurement_units' => '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); $manager->persist($users); diff --git a/src/DataFixtures/UserFixtures.php b/src/DataFixtures/UserFixtures.php index 39e2d4d7..d917e976 100644 --- a/src/DataFixtures/UserFixtures.php +++ b/src/DataFixtures/UserFixtures.php @@ -1,6 +1,6 @@ leftJoin('attachment.element', 'element'); } - /** - * @param DataTable $dataTable - * @param array $options - */ public function configure(DataTable $dataTable, array $options) { $dataTable->add('picture', TextColumn::class, [ @@ -91,7 +82,7 @@ class AttachmentDataTable implements DataTableTypeInterface } return ''; - } + }, ]); $dataTable->add('name', TextColumn::class, [ @@ -115,7 +106,7 @@ class AttachmentDataTable implements DataTableTypeInterface } return $value; - } + }, ]); $dataTable->add('attachment_type', TextColumn::class, [ @@ -126,7 +117,7 @@ class AttachmentDataTable implements DataTableTypeInterface $this->entityURLGenerator->editURL($context->getAttachmentType()), htmlspecialchars($value) ); - } + }, ]); $dataTable->add('element', TextColumn::class, [ @@ -138,11 +129,11 @@ class AttachmentDataTable implements DataTableTypeInterface $this->entityURLGenerator->infoURL($context->getElement()), $this->elementTypeNameGenerator->getTypeNameCombination($context->getElement(), true) ); - } + }, ]); $dataTable->add('filename', TextColumn::class, [ - 'propertyPath' => 'filename' + 'propertyPath' => 'filename', ]); $dataTable->add('filesize', TextColumn::class, [ @@ -151,7 +142,7 @@ class AttachmentDataTable implements DataTableTypeInterface return $this->attachmentHelper->getHumanFileSize($context); } if ($context->isExternal()) { - return '' . $this->translator->trans('attachment.external') . ''; + return ''.$this->translator->trans('attachment.external').''; } return sprintf( @@ -160,17 +151,17 @@ class AttachmentDataTable implements DataTableTypeInterface ', $this->translator->trans('attachment.file_not_found') ); - } + }, ]); $dataTable ->add('addedDate', LocaleDateTimeColumn::class, [ 'label' => $this->translator->trans('part.table.addedDate'), - 'visible' => false + 'visible' => false, ]) ->add('lastModified', LocaleDateTimeColumn::class, [ 'label' => $this->translator->trans('part.table.lastModified'), - 'visible' => false + 'visible' => false, ]); $dataTable->add('show_in_table', BoolColumn::class, [ @@ -178,7 +169,7 @@ class AttachmentDataTable implements DataTableTypeInterface 'trueValue' => $this->translator->trans('true'), 'falseValue' => $this->translator->trans('false'), 'nullValue' => '', - 'visible' => false + 'visible' => false, ]); $dataTable->add('isPicture', BoolColumn::class, [ @@ -187,7 +178,7 @@ class AttachmentDataTable implements DataTableTypeInterface 'falseValue' => $this->translator->trans('false'), 'nullValue' => '', 'visible' => false, - 'propertyPath' => 'picture' + 'propertyPath' => 'picture', ]); $dataTable->add('is3DModel', BoolColumn::class, [ @@ -196,7 +187,7 @@ class AttachmentDataTable implements DataTableTypeInterface 'falseValue' => $this->translator->trans('false'), 'nullValue' => '', 'visible' => false, - 'propertyPath' => '3dmodel' + 'propertyPath' => '3dmodel', ]); $dataTable->add('isBuiltin', BoolColumn::class, [ @@ -205,7 +196,7 @@ class AttachmentDataTable implements DataTableTypeInterface 'falseValue' => $this->translator->trans('false'), 'nullValue' => '', 'visible' => false, - 'propertyPath' => 'builtin' + 'propertyPath' => 'builtin', ]); $dataTable->createAdapter(ORMAdapter::class, [ @@ -215,4 +206,4 @@ class AttachmentDataTable implements DataTableTypeInterface }, ]); } -} \ No newline at end of file +} diff --git a/src/DataTables/Column/EntityColumn.php b/src/DataTables/Column/EntityColumn.php index 2f95b077..3e4aa233 100644 --- a/src/DataTables/Column/EntityColumn.php +++ b/src/DataTables/Column/EntityColumn.php @@ -1,6 +1,6 @@ setRequired('property'); $resolver->setDefault('field', function (Options $option) { - return $option['property'] . '.name'; + return $option['property'].'.name'; }); $resolver->setDefault('render', function (Options $options) { @@ -72,7 +70,7 @@ class EntityColumn extends AbstractColumn $entity = $this->accessor->getValue($context, $options['property']); if ($entity) { - if ($entity->getID() !== null) { + if (null !== $entity->getID()) { return sprintf( '%s', $this->urlGenerator->listPartsURL($entity), @@ -85,4 +83,4 @@ class EntityColumn extends AbstractColumn }; }); } -} \ No newline at end of file +} diff --git a/src/DataTables/Column/LocaleDateTimeColumn.php b/src/DataTables/Column/LocaleDateTimeColumn.php index 3ea30780..1ef0056d 100644 --- a/src/DataTables/Column/LocaleDateTimeColumn.php +++ b/src/DataTables/Column/LocaleDateTimeColumn.php @@ -1,6 +1,6 @@ IntlDateFormatter::NONE, 'short' => IntlDateFormatter::SHORT, 'medium' => IntlDateFormatter::MEDIUM, 'long' => IntlDateFormatter::LONG, 'full' => IntlDateFormatter::FULL, - ); + ]; $formatter = IntlDateFormatter::create( \Locale::getDefault(), @@ -74,11 +71,11 @@ class LocaleDateTimeColumn extends AbstractColumn ->setDefaults([ 'dateFormat' => 'short', 'timeFormat' => 'short', - 'nullValue' => '' + 'nullValue' => '', ]) ->setAllowedTypes('nullValue', 'string') ; return $this; } -} \ No newline at end of file +} diff --git a/src/DataTables/PartsDataTable.php b/src/DataTables/PartsDataTable.php index e683f3dc..d9491378 100644 --- a/src/DataTables/PartsDataTable.php +++ b/src/DataTables/PartsDataTable.php @@ -1,6 +1,6 @@ andWhere('part.tags LIKE :tag')->setParameter('tag', '%' . $options['tag'] . '%'); + $builder->andWhere('part.tags LIKE :tag')->setParameter('tag', '%'.$options['tag'].'%'); } if (isset($options['search'])) { $builder->AndWhere('part.name LIKE :search')->orWhere('part.description LIKE :search')->orWhere('part.comment LIKE :search') - ->setParameter('search', '%' . $options['search'] . '%'); + ->setParameter('search', '%'.$options['search'].'%'); } } - /** - * @param DataTable $dataTable - * @param array $options - */ public function configure(DataTable $dataTable, array $options) { $dataTable @@ -154,7 +145,7 @@ class PartsDataTable implements DataTableTypeInterface 'label' => '', 'render' => function ($value, Part $context) { $preview_attachment = $this->previewGenerator->getTablePreviewAttachment($context); - if ($preview_attachment === null) { + if (null === $preview_attachment) { return ''; } @@ -165,7 +156,7 @@ class PartsDataTable implements DataTableTypeInterface $this->attachmentURLGenerator->getThumbnailURL($preview_attachment, 'thumbnail_md'), 'img-fluid hoverpic' ); - } + }, ]) ->add('name', TextColumn::class, [ 'label' => $this->translator->trans('part.table.name'), @@ -179,7 +170,7 @@ class PartsDataTable implements DataTableTypeInterface ]) ->add('id', TextColumn::class, [ 'label' => $this->translator->trans('part.table.id'), - 'visible' => false + 'visible' => false, ]) ->add('description', TextColumn::class, [ 'label' => $this->translator->trans('part.table.description'), @@ -190,19 +181,19 @@ class PartsDataTable implements DataTableTypeInterface ]) ->add('footprint', EntityColumn::class, [ 'property' => 'footprint', - 'label' => $this->translator->trans('part.table.footprint') + 'label' => $this->translator->trans('part.table.footprint'), ]) ->add('manufacturer', EntityColumn::class, [ 'property' => 'manufacturer', - 'label' => $this->translator->trans('part.table.manufacturer') + 'label' => $this->translator->trans('part.table.manufacturer'), ]) ->add('storelocation', TextColumn::class, [ 'label' => $this->translator->trans('part.table.storeLocations'), 'render' => function ($value, Part $context) { - $tmp = array(); + $tmp = []; foreach ($context->getPartLots() as $lot) { //Ignore lots without storelocation - if ($lot->getStorageLocation() === null) { + if (null === $lot->getStorageLocation()) { continue; } $tmp[] = sprintf( @@ -210,51 +201,52 @@ class PartsDataTable implements DataTableTypeInterface $this->urlGenerator->listPartsURL($lot->getStorageLocation()), $lot->getStorageLocation()->getName() ); - } + return implode('
', $tmp); - } + }, ]) ->add('amount', TextColumn::class, [ 'label' => $this->translator->trans('part.table.amount'), 'render' => function ($value, Part $context) { $amount = $context->getAmountSum(); + return $this->amountFormatter->format($amount, $context->getPartUnit()); - } + }, ]) ->add('minamount', TextColumn::class, [ 'label' => $this->translator->trans('part.table.minamount'), 'visible' => false, 'render' => function ($value, Part $context) { return $this->amountFormatter->format($value, $context->getPartUnit()); - } + }, ]) ->add('partUnit', TextColumn::class, [ 'field' => 'partUnit.name', 'label' => $this->translator->trans('part.table.partUnit'), - 'visible' => false + 'visible' => false, ]) ->add('addedDate', LocaleDateTimeColumn::class, [ 'label' => $this->translator->trans('part.table.addedDate'), - 'visible' => false + 'visible' => false, ]) ->add('lastModified', LocaleDateTimeColumn::class, [ 'label' => $this->translator->trans('part.table.lastModified'), - 'visible' => false + 'visible' => false, ]) ->add('needs_review', BoolColumn::class, [ 'label' => $this->translator->trans('part.table.needsReview'), 'trueValue' => $this->translator->trans('true'), 'falseValue' => $this->translator->trans('false'), 'nullValue' => '', - 'visible' => false + 'visible' => false, ]) ->add('favorite', BoolColumn::class, [ 'label' => $this->translator->trans('part.table.favorite'), 'trueValue' => $this->translator->trans('true'), 'falseValue' => $this->translator->trans('false'), 'nullValue' => '', - 'visible' => false + 'visible' => false, ]) ->add('manufacturing_status', MapColumn::class, [ 'label' => $this->translator->trans('part.table.manufacturingStatus'), @@ -266,25 +258,25 @@ class PartsDataTable implements DataTableTypeInterface 'active' => $this->translator->trans('m_status.active'), 'nrfnd' => $this->translator->trans('m_status.nrfnd'), 'eol' => $this->translator->trans('m_status.eol'), - 'discontinued' => $this->translator->trans('m_status.discontinued') - ] + 'discontinued' => $this->translator->trans('m_status.discontinued'), + ], ]) ->add('manufacturer_product_number', TextColumn::class, [ 'label' => $this->translator->trans('part.table.mpn'), - 'visible' => false + 'visible' => false, ]) ->add('mass', TextColumn::class, [ 'label' => $this->translator->trans('part.table.mass'), - 'visible' => false + 'visible' => false, ]) ->add('tags', TextColumn::class, [ 'label' => $this->translator->trans('part.table.tags'), - 'visible' => false + 'visible' => false, ]) ->addOrderBy('name') ->createAdapter(ORMAdapter::class, [ - 'query' => function(QueryBuilder $builder) { + 'query' => function (QueryBuilder $builder) { $this->getQuery($builder); }, 'entity' => Part::class, @@ -292,8 +284,8 @@ class PartsDataTable implements DataTableTypeInterface function (QueryBuilder $builder) use ($options) { $this->buildCriteria($builder, $options); }, - new SearchCriteriaProvider() - ] + new SearchCriteriaProvider(), + ], ]); } } diff --git a/src/Entity/Attachments/Attachment.php b/src/Entity/Attachments/Attachment.php index caf9559e..4d1f7149 100644 --- a/src/Entity/Attachments/Attachment.php +++ b/src/Entity/Attachments/Attachment.php @@ -1,6 +1,6 @@ getPath(), PATHINFO_EXTENSION); - return in_array(strtolower($extension), static::PICTURE_EXTS, true); + return \in_array(strtolower($extension), static::PICTURE_EXTS, true); } /** * Check if this attachment is a 3D model and therfore can be directly shown to user. * If the attachment is external, false is returned (3D Models must be internal). + * * @return bool */ - public function is3DModel() : bool + public function is3DModel(): bool { //We just assume that 3D Models are internally saved, otherwise we get problems loading them. if ($this->isExternal()) { @@ -171,14 +170,15 @@ 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); } /** - * Checks if the attachment file is externally saved (the database saves an URL) + * Checks if the attachment file is externally saved (the database saves an URL). + * * @return bool true, if the file is saved externally */ - public function isExternal() : bool + public function isExternal(): bool { //When path is empty, this attachment can not be external if (empty($this->path)) { @@ -186,38 +186,40 @@ abstract class Attachment extends NamedDBElement } //After the %PLACEHOLDER% comes a slash, so we can check if we have a placholder via explode - $tmp = explode("/", $this->path); + $tmp = explode('/', $this->path); if (empty($tmp)) { 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); } /** * Check if this attachment is saved in a secure place. * This means that it can not be accessed directly via a web request, but must be viewed via a controller. + * * @return bool True, if the file is secure. */ - public function isSecure() : bool + public function isSecure(): bool { //After the %PLACEHOLDER% comes a slash, so we can check if we have a placholder via explode - $tmp = explode("/", $this->path); + $tmp = explode('/', $this->path); if (empty($tmp)) { return false; } - return $tmp[0] === '%SECURE%'; + return '%SECURE%' === $tmp[0]; } /** * Checks if the attachment file is using a builtin file. (see BUILTIN_PLACEHOLDERS const for possible placeholders) - * If a file is built in, the path is shown to user in url field (no sensitive infos are provided) + * If a file is built in, the path is shown to user in url field (no sensitive infos are provided). + * * @return bool True if the attachment is uning an builtin file. */ - public function isBuiltIn() : bool + public function isBuiltIn(): bool { return static::checkIfBuiltin($this->path); } @@ -232,9 +234,10 @@ abstract class Attachment extends NamedDBElement * Returns the extension of the file referenced via the attachment. * For a path like %BASE/path/foo.bar, bar will be returned. * If this attachment is external null is returned. + * * @return string|null The file extension in lower case. */ - public function getExtension() : ?string + public function getExtension(): ?string { if ($this->isExternal()) { return null; @@ -260,6 +263,7 @@ abstract class Attachment extends NamedDBElement /** * The URL to the external file, or the path to the built in file. * Returns null, if the file is not external (and not builtin). + * * @return string|null */ public function getURL(): ?string @@ -274,6 +278,7 @@ abstract class Attachment extends NamedDBElement /** * Returns the hostname where the external file is stored. * Returns null, if the file is not external. + * * @return string|null */ public function getHost(): ?string @@ -319,16 +324,19 @@ abstract class Attachment extends NamedDBElement /** * Sets the filename that is shown for this attachment. Useful when the internal path is some generated value. + * * @param string|null $new_filename The filename that should be shown. - * Set to null to generate the filename from path. + * Set to null to generate the filename from path. + * * @return Attachment */ - public function setFilename(?string $new_filename): Attachment + public function setFilename(?string $new_filename): self { - if ($new_filename === "") { + if ('' === $new_filename) { $new_filename = null; } $this->original_filename = $new_filename; + return $this; } @@ -347,7 +355,6 @@ abstract class Attachment extends NamedDBElement * Get the type of this attachement. * * @return AttachmentType the type of this attachement - * */ public function getAttachmentType(): ?AttachmentType { @@ -370,8 +377,6 @@ abstract class Attachment extends NamedDBElement ****************************************************************************************************/ /** - * @param bool $show_in_table - * * @return self */ public function setShowInTable(bool $show_in_table): self @@ -381,51 +386,48 @@ abstract class Attachment extends NamedDBElement return $this; } - public function setElement(AttachmentContainingDBElement $element) : Attachment + 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!', - get_class($this), - static::ALLOWED_ELEMENT_CLASS - )); + if (!is_a($element, static::ALLOWED_ELEMENT_CLASS)) { + throw new \InvalidArgumentException(sprintf('The element associated with a %s must be a %s!', \get_class($this), static::ALLOWED_ELEMENT_CLASS)); } $this->element = $element; + return $this; } /** - * @param string $path * @return Attachment */ - public function setPath(string $path): Attachment + public function setPath(string $path): self { $this->path = $path; + return $this; } /** - * @param AttachmentType $attachement_type * @return Attachment */ - public function setAttachmentType(AttachmentType $attachement_type): Attachment + public function setAttachmentType(AttachmentType $attachement_type): self { $this->attachment_type = $attachement_type; + return $this; } /** * Sets the url associated with this attachment. * If the url is empty nothing is changed, to not override the file path. - * @param string|null $url + * * @return Attachment */ - public function setURL(?string $url) : Attachment + public function setURL(?string $url): self { //Only set if the URL is not empty if (!empty($url)) { - if (strpos($url, '%BASE%') !== false || strpos($url, '%MEDIA%') !== false) { + 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!'); } @@ -437,17 +439,18 @@ abstract class Attachment extends NamedDBElement return $this; } - /***************************************************************************************************** * Static functions *****************************************************************************************************/ /** * Checks if the given path is a path to a builtin ressource. + * * @param string $path The path that should be checked + * * @return bool True if the path is pointing to a builtin ressource. */ - public static function checkIfBuiltin(string $path) : bool + public static function checkIfBuiltin(string $path): bool { //After the %PLACEHOLDER% comes a slash, so we can check if we have a placholder via explode $tmp = explode('/', $path); @@ -455,22 +458,25 @@ abstract class Attachment extends NamedDBElement if (empty($tmp)) { return false; } - return in_array($tmp[0], static::BUILTIN_PLACEHOLDER, false); + + return \in_array($tmp[0], static::BUILTIN_PLACEHOLDER, false); } /** * Check if a string is a URL and is valid. + * * @param $string string The string which should be checked. * @param bool $path_required If true, the string must contain a path to be valid. (e.g. foo.bar would be invalid, foo.bar/test.php would be valid). * @param $only_http bool Set this to true, if only HTTPS or HTTP schemata should be allowed. * *Caution: When this is set to false, a attacker could use the file:// schema, to get internal server files, like /etc/passwd.* + * * @return bool True if the string is a valid URL. False, if the string is not an URL or invalid. */ - public static function isURL(string $string, bool $path_required = true, bool $only_http = true) : bool + public static function isURL(string $string, bool $path_required = true, bool $only_http = true): bool { if ($only_http) { //Check if scheme is HTTPS or HTTP $scheme = parse_url($string, PHP_URL_SCHEME); - if ($scheme !== 'http' && $scheme !== 'https') { + if ('http' !== $scheme && 'https' !== $scheme) { return false; //All other schemes are not valid. } } diff --git a/src/Entity/Attachments/AttachmentContainingDBElement.php b/src/Entity/Attachments/AttachmentContainingDBElement.php index fe0d4ee2..31154a53 100644 --- a/src/Entity/Attachments/AttachmentContainingDBElement.php +++ b/src/Entity/Attachments/AttachmentContainingDBElement.php @@ -1,6 +1,6 @@ attachments; } /** - * Adds an attachment to this element + * Adds an attachment to this element. + * * @param Attachment $attachment Attachment + * * @return $this */ - public function addAttachment(Attachment $attachment) : self + public function addAttachment(Attachment $attachment): self { //Attachment must be associated with this element $attachment->setElement($this); $this->attachments->add($attachment); + return $this; } /** - * Removes the given attachment from this element - * @param Attachment $attachment + * Removes the given attachment from this element. + * * @return $this */ - public function removeAttachment(Attachment $attachment) : self + public function removeAttachment(Attachment $attachment): self { $this->attachments->removeElement($attachment); + return $this; } } diff --git a/src/Entity/Attachments/AttachmentType.php b/src/Entity/Attachments/AttachmentType.php index 41a83deb..b0834a8b 100644 --- a/src/Entity/Attachments/AttachmentType.php +++ b/src/Entity/Attachments/AttachmentType.php @@ -1,6 +1,6 @@ accept attribute * (See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers). + * * @return string */ public function getFiletypeFilter(): string @@ -116,12 +116,12 @@ class AttachmentType extends StructuralDBElement } /** - * @param string $filetype_filter * @return AttachmentType */ - public function setFiletypeFilter(string $filetype_filter): AttachmentType + public function setFiletypeFilter(string $filetype_filter): self { $this->filetype_filter = $filetype_filter; + return $this; } @@ -133,6 +133,6 @@ class AttachmentType extends StructuralDBElement */ public function getIDString(): string { - return 'AT' . sprintf('%09d', $this->getID()); + return 'AT'.sprintf('%09d', $this->getID()); } } diff --git a/src/Entity/Attachments/AttachmentTypeAttachment.php b/src/Entity/Attachments/AttachmentTypeAttachment.php index b8c0577a..b92a65fc 100644 --- a/src/Entity/Attachments/AttachmentTypeAttachment.php +++ b/src/Entity/Attachments/AttachmentTypeAttachment.php @@ -1,6 +1,6 @@ master_picture_attachment = $new_master_attachment; + return $this; } - - -} \ No newline at end of file +} diff --git a/src/Entity/Base/NamedDBElement.php b/src/Entity/Base/NamedDBElement.php index 9560b74a..f32cb419 100644 --- a/src/Entity/Base/NamedDBElement.php +++ b/src/Entity/Base/NamedDBElement.php @@ -1,6 +1,6 @@ parts; } diff --git a/src/Entity/Base/StructuralDBElement.php b/src/Entity/Base/StructuralDBElement.php index 74ea8aae..327c3c34 100644 --- a/src/Entity/Base/StructuralDBElement.php +++ b/src/Entity/Base/StructuralDBElement.php @@ -1,6 +1,6 @@ parent === null; + return null === $this->parent; } /****************************************************************************** @@ -180,6 +177,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement /** * Get the comment of the element. + * * @return string the comment */ public function getComment(): ?string @@ -194,21 +192,21 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement * * @return int the level of this element (zero means a most top element * [a subelement of the root node]) - * */ public function getLevel(): int { - /** + /* * Only check for nodes that have a parent. In the other cases zero is correct. */ - if (0 === $this->level && $this->parent !== null) { + if (0 === $this->level && null !== $this->parent) { $element = $this->parent; - while ($element !== null) { + while (null !== $element) { /** @var StructuralDBElement $element */ $element = $element->parent; ++$this->level; } } + return $this->level; } @@ -218,12 +216,11 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement * @param string $delimeter the delimeter of the returned string * * @return string the full path (incl. the name of this element), delimeted by $delimeter - * */ public function getFullPath(string $delimeter = self::PATH_DELIMITER_ARROW): string { if (!\is_array($this->full_path_strings)) { - $this->full_path_strings = array(); + $this->full_path_strings = []; $this->full_path_strings[] = $this->getName(); $element = $this; @@ -233,7 +230,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement $element = $element->parent; $this->full_path_strings[] = $element->getName(); //Decrement to prevent mem overflow. - $overflow--; + --$overflow; } $this->full_path_strings = array_reverse($this->full_path_strings); @@ -242,11 +239,11 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement return implode($delimeter, $this->full_path_strings); } - /** - * Gets the path to this element (including the element itself) + * Gets the path to this element (including the element itself). + * * @return self[] An array with all (recursivily) parent elements (including this one), - * ordered from the lowest levels (root node) first to the highest level (the element itself) + * ordered from the lowest levels (root node) first to the highest level (the element itself) */ public function getPathArray(): array { @@ -254,7 +251,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; } @@ -293,11 +290,13 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement ******************************************************************************/ /** - * Sets the new parent object + * Sets the new parent object. + * * @param self $new_parent The new parent object + * * @return StructuralDBElement */ - public function setParent(?self $new_parent) : self + public function setParent(?self $new_parent): self { /* if ($new_parent->isChildOf($this)) { @@ -311,7 +310,9 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement /** * Set the comment. + * * @param string $new_comment the new comment + * * @return StructuralDBElement */ public function setComment(?string $new_comment): self @@ -321,7 +322,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement return $this; } - public function setChildren(array $element) : self + public function setChildren(array $element): self { $this->children = $element; @@ -329,16 +330,16 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement } /** - * @param bool $not_selectable * @return StructuralDBElement */ - public function setNotSelectable(bool $not_selectable): StructuralDBElement + public function setNotSelectable(bool $not_selectable): self { $this->not_selectable = $not_selectable; + return $this; } - public function clearChildren() : self + public function clearChildren(): self { $this->children = new ArrayCollection(); diff --git a/src/Entity/Base/TimestampTrait.php b/src/Entity/Base/TimestampTrait.php index 6dc26735..892f5e53 100644 --- a/src/Entity/Base/TimestampTrait.php +++ b/src/Entity/Base/TimestampTrait.php @@ -1,6 +1,6 @@ addedDate = new \DateTime('now'); } } -} \ No newline at end of file +} diff --git a/src/Entity/Devices/Device.php b/src/Entity/Devices/Device.php index 0a99cc23..5465d826 100644 --- a/src/Entity/Devices/Device.php +++ b/src/Entity/Devices/Device.php @@ -1,6 +1,6 @@ partname_hint = $partname_hint; + return $this; } @@ -165,12 +163,12 @@ class Category extends PartsContainingDBElement } /** - * @param string $partname_regex * @return Category */ - public function setPartnameRegex(string $partname_regex): Category + public function setPartnameRegex(string $partname_regex): self { $this->partname_regex = $partname_regex; + return $this; } @@ -183,12 +181,12 @@ class Category extends PartsContainingDBElement } /** - * @param bool $disable_footprints * @return Category */ - public function setDisableFootprints(bool $disable_footprints): Category + public function setDisableFootprints(bool $disable_footprints): self { $this->disable_footprints = $disable_footprints; + return $this; } @@ -201,12 +199,12 @@ class Category extends PartsContainingDBElement } /** - * @param bool $disable_manufacturers * @return Category */ - public function setDisableManufacturers(bool $disable_manufacturers): Category + public function setDisableManufacturers(bool $disable_manufacturers): self { $this->disable_manufacturers = $disable_manufacturers; + return $this; } @@ -219,12 +217,12 @@ class Category extends PartsContainingDBElement } /** - * @param bool $disable_autodatasheets * @return Category */ - public function setDisableAutodatasheets(bool $disable_autodatasheets): Category + public function setDisableAutodatasheets(bool $disable_autodatasheets): self { $this->disable_autodatasheets = $disable_autodatasheets; + return $this; } @@ -237,12 +235,12 @@ class Category extends PartsContainingDBElement } /** - * @param bool $disable_properties * @return Category */ - public function setDisableProperties(bool $disable_properties): Category + public function setDisableProperties(bool $disable_properties): self { $this->disable_properties = $disable_properties; + return $this; } @@ -255,12 +253,12 @@ class Category extends PartsContainingDBElement } /** - * @param string $default_description * @return Category */ - public function setDefaultDescription(string $default_description): Category + public function setDefaultDescription(string $default_description): self { $this->default_description = $default_description; + return $this; } @@ -273,14 +271,12 @@ class Category extends PartsContainingDBElement } /** - * @param string $default_comment * @return Category */ - public function setDefaultComment(string $default_comment): Category + public function setDefaultComment(string $default_comment): self { $this->default_comment = $default_comment; + return $this; } - - } diff --git a/src/Entity/Parts/Footprint.php b/src/Entity/Parts/Footprint.php index 81b68b01..e8936268 100644 --- a/src/Entity/Parts/Footprint.php +++ b/src/Entity/Parts/Footprint.php @@ -1,6 +1,6 @@ footprint_3d; } @@ -127,13 +126,13 @@ class Footprint extends PartsContainingDBElement /** * Sets the 3D Model associated with this footprint. - * @param FootprintAttachment|null $new_attachment + * * @return Footprint */ - public function setFootprint3d(?FootprintAttachment $new_attachment) : Footprint + public function setFootprint3d(?FootprintAttachment $new_attachment): self { $this->footprint_3d = $new_attachment; + return $this; } - } diff --git a/src/Entity/Parts/Manufacturer.php b/src/Entity/Parts/Manufacturer.php index b3b34a4c..60c33788 100644 --- a/src/Entity/Parts/Manufacturer.php +++ b/src/Entity/Parts/Manufacturer.php @@ -1,6 +1,6 @@ getID(); + return 'MU'.$this->getID(); } /** @@ -109,11 +103,13 @@ class MeasurementUnit extends PartsContainingDBElement /** * @param string $unit + * * @return MeasurementUnit */ - public function setUnit(?string $unit): MeasurementUnit + public function setUnit(?string $unit): self { $this->unit = $unit; + return $this; } @@ -126,12 +122,12 @@ class MeasurementUnit extends PartsContainingDBElement } /** - * @param bool $isInteger * @return MeasurementUnit */ - public function setIsInteger(bool $isInteger): MeasurementUnit + public function setIsInteger(bool $isInteger): self { $this->is_integer = $isInteger; + return $this; } @@ -144,12 +140,12 @@ class MeasurementUnit extends PartsContainingDBElement } /** - * @param bool $usesSIPrefixes * @return MeasurementUnit */ - public function setUseSIPrefix(bool $usesSIPrefixes): MeasurementUnit + public function setUseSIPrefix(bool $usesSIPrefixes): self { $this->use_si_prefix = $usesSIPrefixes; + return $this; } -} \ No newline at end of file +} diff --git a/src/Entity/Parts/Part.php b/src/Entity/Parts/Part.php index 99c516a1..a266a6fa 100644 --- a/src/Entity/Parts/Part.php +++ b/src/Entity/Parts/Part.php @@ -1,6 +1,6 @@ getID()); + return 'P'.sprintf('%06d', $this->getID()); } /** @@ -152,11 +150,9 @@ class Part extends AttachmentContainingDBElement * @return Device[] * all devices which uses this part as a one-dimensional array of Device objects * (empty array if there are no ones) * * the array is sorted by the devices names - * */ public function getDevices(): array { return $this->devices; } - } diff --git a/src/Entity/Parts/PartLot.php b/src/Entity/Parts/PartLot.php index a9ccaac4..5d200b22 100644 --- a/src/Entity/Parts/PartLot.php +++ b/src/Entity/Parts/PartLot.php @@ -1,6 +1,6 @@ getID(); + return 'PL'.$this->getID(); } /** * Check if the current part lot is expired. * This is the case, if the expiration date is greater the the current date. + * * @return bool|null True, if the part lot is expired. Returns null, if no expiration date was set. */ public function isExpired(): ?bool { - if ($this->expiration_date === null) { + if (null === $this->expiration_date) { return null; } @@ -129,6 +125,7 @@ class PartLot extends DBElement /** * Gets the description of the part lot. Similar to a "name" of the part lot. + * * @return string */ public function getDescription(): string @@ -138,17 +135,19 @@ class PartLot extends DBElement /** * Sets the description of the part lot. - * @param string $description + * * @return PartLot */ - public function setDescription(string $description): PartLot + public function setDescription(string $description): self { $this->description = $description; + return $this; } /** * Gets the comment for this part lot. + * * @return string */ public function getComment(): string @@ -158,17 +157,19 @@ class PartLot extends DBElement /** * Sets the comment for this part lot. - * @param string $comment + * * @return PartLot */ - public function setComment(string $comment): PartLot + public function setComment(string $comment): self { $this->comment = $comment; + return $this; } /** * Gets the expiration date for the part lot. Returns null, if no expiration date was set. + * * @return \DateTime|null */ public function getExpirationDate(): ?\DateTime @@ -178,17 +179,21 @@ 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 + * * @return PartLot */ - public function setExpirationDate(?\DateTime $expiration_date): PartLot + public function setExpirationDate(?\DateTime $expiration_date): self { $this->expiration_date = $expiration_date; + return $this; } /** * Gets the storage locatiion, where this part lot is stored. + * * @return Storelocation|null The store location where this part is stored */ public function getStorageLocation(): ?Storelocation @@ -197,18 +202,20 @@ class PartLot extends DBElement } /** - * Sets the storage location, where this part lot is stored - * @param Storelocation|null $storage_location + * Sets the storage location, where this part lot is stored. + * * @return PartLot */ - public function setStorageLocation(?Storelocation $storage_location): PartLot + public function setStorageLocation(?Storelocation $storage_location): self { $this->storage_location = $storage_location; + return $this; } /** * Return the part that is stored in this part lot. + * * @return Part */ public function getPart(): Part @@ -218,12 +225,15 @@ class PartLot extends DBElement /** * Sets the part that is stored in this part lot. + * * @param Part|InstockTrait $part + * * @return PartLot */ - public function setPart(Part $part): PartLot + public function setPart(Part $part): self { $this->part = $part; + return $this; } @@ -239,12 +249,13 @@ class PartLot extends DBElement /** * Set the unknown instock status of this part lot. - * @param bool $instock_unknown + * * @return PartLot */ - public function setInstockUnknown(bool $instock_unknown): PartLot + public function setInstockUnknown(bool $instock_unknown): self { $this->instock_unknown = $instock_unknown; + return $this; } @@ -256,17 +267,17 @@ class PartLot extends DBElement if ($this->part instanceof Part && !$this->part->useFloatAmount()) { return round($this->amount); } + return (float) $this->amount; } - public function setAmount(float $new_amount): PartLot + public function setAmount(float $new_amount): self { - $this->amount = $new_amount; + $this->amount = $new_amount; + return $this; } - - /** * @return bool */ @@ -276,14 +287,12 @@ class PartLot extends DBElement } /** - * @param bool $needs_refill * @return PartLot */ - public function setNeedsRefill(bool $needs_refill): PartLot + public function setNeedsRefill(bool $needs_refill): self { $this->needs_refill = $needs_refill; + return $this; } - - -} \ No newline at end of file +} diff --git a/src/Entity/Parts/PartTraits/AdvancedPropertyTrait.php b/src/Entity/Parts/PartTraits/AdvancedPropertyTrait.php index dfdd5e89..0cbb1320 100644 --- a/src/Entity/Parts/PartTraits/AdvancedPropertyTrait.php +++ b/src/Entity/Parts/PartTraits/AdvancedPropertyTrait.php @@ -1,6 +1,6 @@ needs_review = $needs_review; + return $this; } - /** - * Gets a comma separated list, of tags, that are assigned to this part + * Gets a comma separated list, of tags, that are assigned to this part. + * * @return string */ public function getTags(): string @@ -86,18 +85,20 @@ trait AdvancedPropertyTrait /** * Sets a comma separated list of tags, that are assigned to this part. - * @param string $tags + * * @return self */ public function setTags(string $tags): self { $this->tags = $tags; + return $this; } /** * Returns the mass of a single part unit. - * Returns null, if the mass is unknown/not set yet + * Returns null, if the mass is unknown/not set yet. + * * @return float|null */ public function getMass(): ?float @@ -108,14 +109,13 @@ trait AdvancedPropertyTrait /** * Sets the mass of a single part unit. * Sett to null, if the mass is unknown. - * @param float|null $mass + * * @return self */ public function setMass(?float $mass): self { $this->mass = $mass; + return $this; } - - -} \ No newline at end of file +} diff --git a/src/Entity/Parts/PartTraits/BasicPropertyTrait.php b/src/Entity/Parts/PartTraits/BasicPropertyTrait.php index e0b482f5..01c23f3e 100644 --- a/src/Entity/Parts/PartTraits/BasicPropertyTrait.php +++ b/src/Entity/Parts/PartTraits/BasicPropertyTrait.php @@ -1,6 +1,6 @@ favorite; } - /** * Get the category of this part (e.g. Resistors). * There is always a category, for each part! + * * @return Category the category of this part */ public function getCategory(): ?Category @@ -129,7 +131,8 @@ trait BasicPropertyTrait } /** - * Gets the Footprint of this part (e.g. DIP8) + * Gets the Footprint of this part (e.g. DIP8). + * * @return Footprint|null The footprint of this part. Null if this part should no have a footprint. */ public function getFootprint(): ?Footprint @@ -139,36 +142,44 @@ trait BasicPropertyTrait /** * Sets the description of this part. + * * @param string $new_description the new description + * * @return self */ public function setDescription(?string $new_description): self { $this->description = $new_description; + return $this; } /** * Sets the comment property of this part. + * * @param string $new_comment the new comment + * * @return self */ public function setComment(string $new_comment): self { $this->comment = $new_comment; + return $this; } - /** * Set the category of this Part. - * The category property is required for every part, so you can not pass null like the other properties (footprints) + * The category property is required for every part, so you can not pass null like the other properties (footprints). + * * @param Category $category The new category of this part + * * @return self */ public function setCategory(Category $category): self { $this->category = $category; + return $this; } @@ -183,6 +194,7 @@ trait BasicPropertyTrait public function setFootprint(?Footprint $new_footprint): self { $this->footprint = $new_footprint; + return $this; } @@ -197,7 +209,7 @@ trait BasicPropertyTrait public function setFavorite(bool $new_favorite_status): self { $this->favorite = $new_favorite_status; + return $this; } - -} \ No newline at end of file +} diff --git a/src/Entity/Parts/PartTraits/InstockTrait.php b/src/Entity/Parts/PartTraits/InstockTrait.php index 29c4de63..1b66c878 100644 --- a/src/Entity/Parts/PartTraits/InstockTrait.php +++ b/src/Entity/Parts/PartTraits/InstockTrait.php @@ -1,6 +1,6 @@ partLots; } @@ -71,30 +69,35 @@ trait InstockTrait /** * Adds the given part lot, to the list of part lots. * The part lot is assigned to this part. - * @param PartLot $lot + * * @return self */ public function addPartLot(PartLot $lot): self { $lot->setPart($this); $this->partLots->add($lot); + return $this; } /** * Removes the given part lot from the list of part lots. + * * @param PartLot $lot The part lot that should be deleted. + * * @return self */ public function removePartLot(PartLot $lot): self { $this->partLots->removeElement($lot); + return $this; } /** * Gets the measurement unit in which the part's amount should be measured. * Returns null if no specific unit was that. That means the parts are measured simply in quantity numbers. + * * @return MeasurementUnit|null */ public function getPartUnit(): ?MeasurementUnit @@ -105,18 +108,19 @@ trait InstockTrait /** * Sets the measurement unit in which the part's amount should be measured. * Set to null, if the part should be measured in quantities. - * @param MeasurementUnit|null $partUnit + * * @return self */ public function setPartUnit(?MeasurementUnit $partUnit): self { $this->partUnit = $partUnit; + return $this; } /** * Get the count of parts which must be in stock at least. - * If a integer-based part unit is selected, the value will be rounded to integers + * If a integer-based part unit is selected, the value will be rounded to integers. * * @return float count of parts which must be in stock at least */ @@ -132,6 +136,7 @@ trait InstockTrait /** * Checks if this part uses the float amount . * This setting is based on the part unit (see MeasurementUnit->isInteger()). + * * @return bool True if the float amount field should be used. False if the integer instock field should be used. */ public function useFloatAmount(): bool @@ -146,10 +151,11 @@ trait InstockTrait /** * Returns the summed amount of this part (over all part lots) - * Part Lots that have unknown value or are expired, are not used for this value + * Part Lots that have unknown value or are expired, are not used for this value. + * * @return float The amount of parts given in partUnit */ - public function getAmountSum() : float + public function getAmountSum(): float { //TODO: Find a method to do this natively in SQL, the current method could be a bit slow $sum = 0; @@ -172,12 +178,15 @@ trait InstockTrait /** * Set the minimum amount of parts that have to be instock. * See getPartUnit() for the associated unit. + * * @param float $new_minamount the new count of parts which should be in stock at least + * * @return self */ public function setMinAmount(float $new_minamount): self { $this->minamount = $new_minamount; + return $this; } } diff --git a/src/Entity/Parts/PartTraits/ManufacturerTrait.php b/src/Entity/Parts/PartTraits/ManufacturerTrait.php index 55d3fa65..afdb12f3 100644 --- a/src/Entity/Parts/PartTraits/ManufacturerTrait.php +++ b/src/Entity/Parts/PartTraits/ManufacturerTrait.php @@ -1,6 +1,6 @@ manufacturing_status = $manufacturing_status; + return $this; } @@ -133,9 +134,9 @@ trait ManufacturerTrait return $this->manufacturer; } - /** * Returns the assigned manufacturer product number (MPN) for this part. + * * @return string */ public function getManufacturerProductNumber(): string @@ -145,19 +146,22 @@ trait ManufacturerTrait /** * Sets the manufacturer product number (MPN) for this part. - * @param string $manufacturer_product_number + * * @return Part */ public function setManufacturerProductNumber(string $manufacturer_product_number): self { $this->manufacturer_product_number = $manufacturer_product_number; + return $this; } /** * Sets the URL to the manufacturer site about this Part. * Set to "" if this part should use the automatically URL based on its manufacturer. + * * @param string $new_url The new url + * * @return self */ public function setManufacturerProductURL(string $new_url): self @@ -181,5 +185,4 @@ trait ManufacturerTrait return $this; } - -} \ No newline at end of file +} diff --git a/src/Entity/Parts/PartTraits/OrderTrait.php b/src/Entity/Parts/PartTraits/OrderTrait.php index db74fc1d..2724c954 100644 --- a/src/Entity/Parts/PartTraits/OrderTrait.php +++ b/src/Entity/Parts/PartTraits/OrderTrait.php @@ -1,6 +1,6 @@ setPart($this); $this->orderdetails->add($orderdetail); + return $this; } /** * Removes the given orderdetail from the list of orderdetails. - * @param Orderdetail $orderdetail + * * @return OrderTrait */ - public function removeOrderdetail(Orderdetail $orderdetail) : self + public function removeOrderdetail(Orderdetail $orderdetail): self { $this->orderdetails->removeElement($orderdetail); + return $this; } /** * Set the "manual_order" attribute. * - * @param bool $new_manual_order the new "manual_order" attribute - * @param int $new_order_quantity the new order quantity + * @param bool $new_manual_order the new "manual_order" attribute + * @param int $new_order_quantity the new order quantity * @param Orderdetail|null $new_order_orderdetail * the ID of the new order orderdetails - * * or Zero for "no order orderdetails" - * * or NULL for automatic order orderdetails - * (if the part has exactly one orderdetails, - * set this orderdetails as order orderdetails. - * Otherwise, set "no order orderdetails") + * * or Zero for "no order orderdetails" + * * or NULL for automatic order orderdetails + * (if the part has exactly one orderdetails, + * set this orderdetails as order orderdetails. + * Otherwise, set "no order orderdetails") * * @return self */ @@ -183,7 +185,7 @@ trait OrderTrait { $all_orderdetails = $this->getOrderdetails(); - if (0 === count($all_orderdetails)) { + if (0 === \count($all_orderdetails)) { return false; } @@ -195,5 +197,4 @@ trait OrderTrait return true; } - -} \ No newline at end of file +} diff --git a/src/Entity/Parts/Storelocation.php b/src/Entity/Parts/Storelocation.php index 23de5c6f..8308dcf5 100644 --- a/src/Entity/Parts/Storelocation.php +++ b/src/Entity/Parts/Storelocation.php @@ -1,6 +1,6 @@ only_single_part = $only_single_part; + return $this; } @@ -168,12 +165,12 @@ class Storelocation extends PartsContainingDBElement } /** - * @param bool $limit_to_existing_parts * @return Storelocation */ - public function setLimitToExistingParts(bool $limit_to_existing_parts): Storelocation + public function setLimitToExistingParts(bool $limit_to_existing_parts): self { $this->limit_to_existing_parts = $limit_to_existing_parts; + return $this; } @@ -186,17 +183,15 @@ class Storelocation extends PartsContainingDBElement } /** - * @param MeasurementUnit|null $storage_type * @return Storelocation */ - public function setStorageType(?MeasurementUnit $storage_type): Storelocation + public function setStorageType(?MeasurementUnit $storage_type): self { $this->storage_type = $storage_type; + return $this; } - - /******************************************************************************** * * Setters @@ -211,9 +206,10 @@ class Storelocation extends PartsContainingDBElement * * @param bool $new_is_full * true means that the storelocation is full * * false means that the storelocation isn't full + * * @return Storelocation */ - public function setIsFull(bool $new_is_full): Storelocation + public function setIsFull(bool $new_is_full): self { $this->is_full = $new_is_full; diff --git a/src/Entity/Parts/Supplier.php b/src/Entity/Parts/Supplier.php index 2d5ec30c..1848e4b3 100644 --- a/src/Entity/Parts/Supplier.php +++ b/src/Entity/Parts/Supplier.php @@ -1,6 +1,6 @@ default_currency; } /** * Sets the default currency. + * * @param ?Currency $default_currency - * @return Supplier */ - public function setDefaultCurrency(?Currency $default_currency) : Supplier + public function setDefaultCurrency(?Currency $default_currency): self { $this->default_currency = $default_currency; + return $this; } /** * Gets the shipping costs for an order with this supplier, given in base currency. + * * @return string|null A bcmath string with the shipping costs */ - public function getShippingCosts() : ?string + public function getShippingCosts(): ?string { return $this->shipping_costs; } /** * Sets the shipping costs for an order with this supplier. - * @param string|null $shipping_costs A bcmath string with the shipping costs. - * @return Supplier + * + * @param string|null $shipping_costs a bcmath string with the shipping costs */ - public function setShippingCosts(?string $shipping_costs) : Supplier + public function setShippingCosts(?string $shipping_costs): self { $this->shipping_costs = $shipping_costs; + return $this; } - /** * 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/PriceInformations/Currency.php b/src/Entity/PriceInformations/Currency.php index c26cc65c..f1546b77 100644 --- a/src/Entity/PriceInformations/Currency.php +++ b/src/Entity/PriceInformations/Currency.php @@ -1,6 +1,6 @@ iso_code = $iso_code; + return $this; } /** - * Returns the inverse exchange rate (how many of the current currency the base unit is worth) + * Returns the inverse exchange rate (how many of the current currency the base unit is worth). + * * @return string|null */ public function getInverseExchangeRate(): ?string { $tmp = $this->getExchangeRate(); - if ($tmp === null || $tmp === "0") { + if (null === $tmp || '0' === $tmp) { return null; } @@ -111,7 +111,8 @@ class Currency extends StructuralDBElement /** * Returns The exchange rate between this currency and the base currency - * (how many base units the current currency is worth) + * (how many base units the current currency is worth). + * * @return string|null */ public function getExchangeRate(): ?string @@ -120,25 +121,23 @@ class Currency extends StructuralDBElement } /** - * @param string|null $exchange_rate * @return Currency */ - public function setExchangeRate(?string $exchange_rate): Currency + public function setExchangeRate(?string $exchange_rate): self { $this->exchange_rate = $exchange_rate; + return $this; } - /** * Returns the ID as an string, defined by the element class. * This should have a form like P000014, for a part with ID 14. * * @return string The ID as a string; - * */ public function getIDString(): string { - return 'C' . $this->getID(); + return 'C'.$this->getID(); } -} \ No newline at end of file +} diff --git a/src/Entity/PriceInformations/Orderdetail.php b/src/Entity/PriceInformations/Orderdetail.php index 526bc8a6..910807bf 100644 --- a/src/Entity/PriceInformations/Orderdetail.php +++ b/src/Entity/PriceInformations/Orderdetail.php @@ -1,6 +1,6 @@ supplier_product_url; } - if ($this->getSupplier() === null) { + if (null === $this->getSupplier()) { return ''; } @@ -204,7 +203,7 @@ class Orderdetail extends DBElement * Get all pricedetails. * * @return Pricedetail[]|Collection all pricedetails as a one-dimensional array of Pricedetails objects, - * sorted by minimum discount quantity + * sorted by minimum discount quantity */ public function getPricedetails(): Collection { @@ -212,36 +211,41 @@ class Orderdetail extends DBElement } /** - * Adds an pricedetail to this orderdetail + * Adds an pricedetail to this orderdetail. + * * @param Pricedetail $pricedetail The pricedetail to add + * * @return Orderdetail */ - public function addPricedetail(Pricedetail $pricedetail) : Orderdetail + public function addPricedetail(Pricedetail $pricedetail): self { $pricedetail->setOrderdetail($this); $this->pricedetails->add($pricedetail); + return $this; } /** - * Removes an pricedetail from this orderdetail - * @param Pricedetail $pricedetail + * Removes an pricedetail from this orderdetail. + * * @return Orderdetail */ - public function removePricedetail(Pricedetail $pricedetail) : Orderdetail + public function removePricedetail(Pricedetail $pricedetail): self { $this->pricedetails->removeElement($pricedetail); + return $this; } /** * Find the pricedetail that is correct for the desired amount (the one with the greatest discount value with a - * minimum order amount of the wished quantity) - * @param float $quantity this is the quantity to choose the correct pricedetails + * minimum order amount of the wished quantity). + * + * @param float $quantity this is the quantity to choose the correct pricedetails * * @return Pricedetail|null: the price as a bcmath string. Null if there are no orderdetails for the given quantity */ - public function findPriceForQty(float $quantity = 1) : ?Pricedetail + public function findPriceForQty(float $quantity = 1): ?Pricedetail { if ($quantity <= 0) { return null; @@ -269,30 +273,34 @@ class Orderdetail extends DBElement *********************************************************************************/ /** - * Sets a new part with which this orderdetail is associated - * @param Part $part + * Sets a new part with which this orderdetail is associated. + * * @return Orderdetail */ - public function setPart(Part $part) : Orderdetail + public function setPart(Part $part): self { $this->part = $part; + return $this; } /** * Sets the new supplier associated with this orderdetail. - * @param Supplier $new_supplier + * * @return Orderdetail */ - public function setSupplier(Supplier $new_supplier) : Orderdetail + public function setSupplier(Supplier $new_supplier): self { $this->supplier = $new_supplier; + return $this; } /** * Set the supplier part-nr. + * * @param string $new_supplierpartnr the new supplier-part-nr + * * @return Orderdetail * @return Orderdetail */ @@ -305,7 +313,9 @@ class Orderdetail extends DBElement /** * Set if the part is obsolete at the supplier of that orderdetails. + * * @param bool $new_obsolete true means that this part is obsolete + * * @return Orderdetail * @return Orderdetail */ @@ -319,10 +329,12 @@ class Orderdetail extends DBElement /** * Sets the custom product supplier URL for this order detail. * Set this to "", if the function getSupplierProductURL should return the automatic generated URL. + * * @param $new_url string The new URL for the supplier URL. + * * @return Orderdetail */ - public function setSupplierProductUrl(string $new_url) : Orderdetail + public function setSupplierProductUrl(string $new_url): self { //Only change the internal URL if it is not the auto generated one if ($new_url === $this->supplier->getAutoProductUrl($this->getSupplierPartNr())) { diff --git a/src/Entity/PriceInformations/Pricedetail.php b/src/Entity/PriceInformations/Pricedetail.php index 89fc74e3..5e998b96 100644 --- a/src/Entity/PriceInformations/Pricedetail.php +++ b/src/Entity/PriceInformations/Pricedetail.php @@ -1,6 +1,6 @@ price; } @@ -152,18 +151,19 @@ class Pricedetail extends DBElement /** * Get the price for a single unit in the currency associated with this price detail. * - * @param float|string $multiplier The returned price (float or string) will be multiplied - * with this multiplier. + * @param float|string $multiplier The returned price (float or string) will be multiplied + * with this multiplier. * * You will get the price for $multiplier parts. If you want the price which is stored * in the database, you have to pass the "price_related_quantity" count as $multiplier. * - * @return string the price as a bcmath string + * @return string the price as a bcmath string */ - public function getPricePerUnit($multiplier = 1.0) : string + public function getPricePerUnit($multiplier = 1.0): string { $multiplier = (string) $multiplier; $tmp = bcmul($this->price, $multiplier, static::PRICE_PRECISION); + return bcdiv($tmp, (string) $this->price_related_quantity, static::PRICE_PRECISION); //return ($this->price * $multiplier) / $this->price_related_quantity; } @@ -180,10 +180,12 @@ class Pricedetail extends DBElement */ public function getPriceRelatedQuantity(): float { - if ($this->orderdetail && $this->orderdetail->getPart() && !$this->orderdetail->getPart()->useFloatAmount()) { + if ($this->orderdetail && $this->orderdetail->getPart() && !$this->orderdetail->getPart()->useFloatAmount()) { $tmp = round($this->price_related_quantity); + return $tmp < 1 ? 1 : $tmp; } + return $this->price_related_quantity; } @@ -203,6 +205,7 @@ class Pricedetail extends DBElement { if ($this->orderdetail && $this->orderdetail->getPart() && !$this->orderdetail->getPart()->useFloatAmount()) { $tmp = round($this->min_discount_quantity); + return $tmp < 1 ? 1 : $tmp; } @@ -212,6 +215,7 @@ class Pricedetail extends DBElement /** * Returns the currency associated with this price information. * Returns null, if no specific currency is selected and the global base currency should be assumed. + * * @return Currency|null */ public function getCurrency(): ?Currency @@ -227,24 +231,26 @@ class Pricedetail extends DBElement /** * Sets the orderdetail to which this pricedetail belongs to. - * @param Orderdetail $orderdetail + * * @return $this */ - public function setOrderdetail(Orderdetail $orderdetail) : self + public function setOrderdetail(Orderdetail $orderdetail): self { $this->orderdetail = $orderdetail; + return $this; } /** * Sets the currency associated with the price informations. * Set to null, to use the global base currency. - * @param Currency|null $currency + * * @return Pricedetail */ - public function setCurrency(?Currency $currency): Pricedetail + public function setCurrency(?Currency $currency): self { $this->currency = $currency; + return $this; } @@ -259,7 +265,7 @@ class Pricedetail extends DBElement * * @return self */ - public function setPrice(string $new_price): Pricedetail + public function setPrice(string $new_price): self { //Assert::natural($new_price, 'The new price must be positive! Got %s!'); @@ -322,6 +328,6 @@ class Pricedetail extends DBElement */ public function getIDString(): string { - return 'PD' . sprintf('%06d', $this->getID()); + return 'PD'.sprintf('%06d', $this->getID()); } } diff --git a/src/Entity/UserSystem/Group.php b/src/Entity/UserSystem/Group.php index f8ea955d..903fd359 100644 --- a/src/Entity/UserSystem/Group.php +++ b/src/Entity/UserSystem/Group.php @@ -1,6 +1,6 @@ $permission_name); } @@ -304,8 +305,8 @@ class PermissionsEmbed /** * Returns the bit pair value of the given permission. * - * @param string $permission_name The name of the permission, for which the bit pair should be returned. - * @param int $bit_n The (lower) bit number of the bit pair, which should be read. + * @param string $permission_name the name of the permission, for which the bit pair should be returned + * @param int $bit_n the (lower) bit number of the bit pair, which should be read * * @return int The value of the bit pair. Compare to the INHERIT, ALLOW, and DISALLOW consts in this class. */ @@ -323,8 +324,8 @@ class PermissionsEmbed /** * Returns the value of the operation for the given permission. * - * @param string $permission_name The name of the permission, for which the operation should be returned. - * @param int $bit_n The (lower) bit number of the bit pair for the operation. + * @param string $permission_name the name of the permission, for which the operation should be returned + * @param int $bit_n the (lower) bit number of the bit pair for the operation * * @return bool|null The value of the operation. True, if the given operation is allowed, false if disallowed * and null if it should inherit from parent. @@ -345,19 +346,21 @@ class PermissionsEmbed /** * Sets the value of the given permission and operation. - * @param string $permission_name The name of the permission, for which the bit pair should be written. - * @param int $bit_n The (lower) bit number of the bit pair, which should be written. - * @param bool|null $new_value The new value for the operation: - * True, if the given operation is allowed, false if disallowed - * and null if it should inherit from parent. - * @return PermissionsEmbed The instance itself. + * + * @param string $permission_name the name of the permission, for which the bit pair should be written + * @param int $bit_n the (lower) bit number of the bit pair, which should be written + * @param bool|null $new_value the new value for the operation: + * True, if the given operation is allowed, false if disallowed + * and null if it should inherit from parent + * + * @return PermissionsEmbed the instance itself */ - public function setPermissionValue(string $permission_name, int $bit_n, ?bool $new_value) : self + public function setPermissionValue(string $permission_name, int $bit_n, ?bool $new_value): self { //Determine which bit value the given value is. - if ($new_value === true) { + if (true === $new_value) { $bit_value = static::ALLOW; - } elseif ($new_value === false) { + } elseif (false === $new_value) { $bit_value = static::DISALLOW; } else { $bit_value = static::INHERIT; @@ -370,12 +373,14 @@ class PermissionsEmbed /** * Sets the bit value of the given permission and operation. - * @param string $permission_name The name of the permission, for which the bit pair should be written. - * @param int $bit_n The (lower) bit number of the bit pair, which should be written. - * @param int $new_value The new (bit) value of the bit pair, which should be written. - * @return PermissionsEmbed The instance itself. + * + * @param string $permission_name the name of the permission, for which the bit pair should be written + * @param int $bit_n the (lower) bit number of the bit pair, which should be written + * @param int $new_value the new (bit) value of the bit pair, which should be written + * + * @return PermissionsEmbed the instance itself */ - public function setBitValue(string $permission_name, int $bit_n, int $new_value) : self + 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!'); @@ -387,12 +392,14 @@ class PermissionsEmbed } /** - * Returns the given permission as raw int (all bit at once) + * Returns the given permission as raw int (all bit at once). + * * @param string $permission_name The name of the permission, which should be retrieved. - * If this is not existing an exception is thrown. - * @return int The raw permission value. + * If this is not existing an exception is thrown. + * + * @return int the raw permission value */ - public function getRawPermissionValue(string $permission_name) : int + public function getRawPermissionValue(string $permission_name): int { if (!$this->isValidPermissionName($permission_name)) { throw new \InvalidArgumentException('No permission with the given name is existing!'); @@ -403,30 +410,33 @@ class PermissionsEmbed /** * Sets the given permission to the value. - * @param string $permission_name The name of the permission to that should be set. - * @param int $value The new value of the permsission + * + * @param string $permission_name the name of the permission to that should be set + * @param int $value The new value of the permsission + * * @return $this */ - public function setRawPermissionValue(string $permission_name, int $value) : self + 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; + return $this; } /** * Sets multiple permissions at once. - * @param array $values An array in the form ['perm_name' => $value], containing the new data - * @param array|null $values2 If this array is not null, the first array will treated of list of perm names, - * and this array as an array of new values. + * + * @param array $values An array in the form ['perm_name' => $value], containing the new data + * @param array|null $values2 if this array is not null, the first array will treated of list of perm names, + * and this array as an array of new values + * * @return $this */ - public function setRawPermissionValues(array $values, array $values2 = null) : self + public function setRawPermissionValues(array $values, array $values2 = null): self { if (!empty($values2)) { $values = array_combine($values, $values2); @@ -435,16 +445,17 @@ class PermissionsEmbed foreach ($values as $key => $value) { $this->setRawPermissionValue($key, $value); } + return $this; } /** * Reads a bit pair from $data. * - * @param $data int The data from where the bits should be extracted from. + * @param $data int The data from where the bits should be extracted from * @param $n int The number of the lower bit (of the pair) that should be read. Starting from zero. * - * @return int The value of the bit pair. + * @return int the value of the bit pair */ final protected static function readBitPair(int $data, int $n): int { @@ -460,11 +471,11 @@ class PermissionsEmbed /** * Writes a bit pair in the given $data and returns it. * - * @param $data int The data which should be modified. - * @param $n int The number of the lower bit of the pair which should be written. - * @param $new int The new value of the pair. + * @param $data int The data which should be modified + * @param $n int The number of the lower bit of the pair which should be written + * @param $new int The new value of the pair * - * @return int The new data with the modified pair. + * @return int the new data with the modified pair */ final protected static function writeBitPair(int $data, int $n, int $new): int { diff --git a/src/Entity/UserSystem/User.php b/src/Entity/UserSystem/User.php index 5db0f661..4ad602c2 100644 --- a/src/Entity/UserSystem/User.php +++ b/src/Entity/UserSystem/User.php @@ -1,6 +1,6 @@ currency = $currency; + return $this; } /** * Checks if this user is disabled (user cannot login any more). + * * @return bool True, if the user is disabled. */ public function isDisabled(): bool @@ -343,17 +341,18 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe /** * Sets the status if a user is disabled. + * * @param bool $disabled True if the user should be disabled. + * * @return User */ - public function setDisabled(bool $disabled): User + public function setDisabled(bool $disabled): self { $this->disabled = $disabled; + return $this; } - - /** * Returns the ID as an string, defined by the element class. * This should have a form like P000014, for a part with ID 14. @@ -371,7 +370,8 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe } /** - * Check if the user needs a password change + * Check if the user needs a password change. + * * @return bool */ public function isNeedPwChange(): bool @@ -381,12 +381,13 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe /** * Set the status, if the user needs a password change. - * @param bool $need_pw_change + * * @return User */ - public function setNeedPwChange(bool $need_pw_change): User + public function setNeedPwChange(bool $need_pw_change): self { $this->need_pw_change = $need_pw_change; + return $this; } @@ -394,8 +395,6 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * Getters ************************************************/ - - /** * Returns the full name in the format FIRSTNAME LASTNAME [(USERNAME)]. * Example: Max Muster (m.muster). @@ -436,7 +435,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setFirstName(?string $first_name): User + public function setFirstName(?string $first_name): self { $this->first_name = $first_name; @@ -456,7 +455,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setLastName(?string $last_name): User + public function setLastName(?string $last_name): self { $this->last_name = $last_name; @@ -476,7 +475,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setDepartment(?string $department): User + public function setDepartment(?string $department): self { $this->department = $department; @@ -496,7 +495,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setEmail(?string $email): User + public function setEmail(?string $email): self { $this->email = $email; @@ -516,7 +515,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setLanguage(?string $language): User + public function setLanguage(?string $language): self { $this->language = $language; @@ -536,7 +535,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setTimezone(?string $timezone): User + public function setTimezone(?string $timezone): self { $this->timezone = $timezone; @@ -556,7 +555,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe * * @return User */ - public function setTheme(?string $theme): User + public function setTheme(?string $theme): self { $this->theme = $theme; @@ -578,6 +577,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe public function __toString() { $tmp = $this->isDisabled() ? ' [DISABLED]' : ''; - return $this->getFullName(true) . $tmp; + + return $this->getFullName(true).$tmp; } } diff --git a/src/EntityListeners/AttachmentDeleteListener.php b/src/EntityListeners/AttachmentDeleteListener.php index 3400cd9d..363653e0 100644 --- a/src/EntityListeners/AttachmentDeleteListener.php +++ b/src/EntityListeners/AttachmentDeleteListener.php @@ -1,6 +1,6 @@ attachmentHelper->attachmentToFile($attachment); //Only delete if the attachment has a valid file. - if ($file !== null) { + if (null !== $file) { $this->attachmentReverseSearch->deleteIfNotUsed($file); } } - -} \ No newline at end of file +} diff --git a/src/EntityListeners/TreeCacheInvalidationListener.php b/src/EntityListeners/TreeCacheInvalidationListener.php index 9244c9cc..eae8b023 100644 --- a/src/EntityListeners/TreeCacheInvalidationListener.php +++ b/src/EntityListeners/TreeCacheInvalidationListener.php @@ -1,6 +1,6 @@ cache->invalidateTags([$secure_class_name]); } @@ -69,10 +62,9 @@ class TreeCacheInvalidationListener /* If any group change, then invalidate all cached trees. Users Permissions can be inherited from groups, so a change in any group can cause big permisssion changes for users. So to be sure, invalidate all trees */ - if($element instanceof Group) { - $tag = "groups"; + if ($element instanceof Group) { + $tag = 'groups'; $this->cache->invalidateTags([$tag]); } - } -} \ No newline at end of file +} diff --git a/src/EventSubscriber/LoginSuccessListener.php b/src/EventSubscriber/LoginSuccessListener.php index 9f81864b..db576047 100644 --- a/src/EventSubscriber/LoginSuccessListener.php +++ b/src/EventSubscriber/LoginSuccessListener.php @@ -1,6 +1,6 @@ 'onLogin']; } -} \ No newline at end of file +} diff --git a/src/EventSubscriber/LogoutOnDisabledUserListener.php b/src/EventSubscriber/LogoutOnDisabledUserListener.php index 78ab77f1..da4be4ca 100644 --- a/src/EventSubscriber/LogoutOnDisabledUserListener.php +++ b/src/EventSubscriber/LogoutOnDisabledUserListener.php @@ -1,6 +1,6 @@ 'onRequest']; } -} \ No newline at end of file +} diff --git a/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php b/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php index 592f97a7..dcc07a05 100644 --- a/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php +++ b/src/EventSubscriber/SymfonyDebugToolbarSubscriber.php @@ -1,6 +1,6 @@ 'onKernelResponse']; } - public function onKernelResponse(FilterResponseEvent $event) { if (!$this->kernel->getParameter('kernel.debug')) { @@ -70,5 +66,4 @@ class SymfonyDebugToolbarSubscriber implements EventSubscriberInterface $response = $event->getResponse(); $response->headers->set('Symfony-Debug-Toolbar-Replace', 1); } - -} \ No newline at end of file +} diff --git a/src/EventSubscriber/TimezoneListener.php b/src/EventSubscriber/TimezoneListener.php index c6794048..eb44bdda 100644 --- a/src/EventSubscriber/TimezoneListener.php +++ b/src/EventSubscriber/TimezoneListener.php @@ -1,6 +1,6 @@ default_timezone)) { + if (null === $timezone && !empty($this->default_timezone)) { $timezone = $this->default_timezone; } //If timezone was configured anywhere set it, otherwise just use the one from php.ini - if ($timezone !== null) { + if (null !== $timezone) { date_default_timezone_set($timezone); - } } @@ -89,7 +84,7 @@ class TimezoneListener implements EventSubscriberInterface { //Set the timezone shortly before executing the controller return [ - KernelEvents::CONTROLLER => 'setTimeZone' + KernelEvents::CONTROLLER => 'setTimeZone', ]; } -} \ No newline at end of file +} diff --git a/src/Exceptions/AttachmentDownloadException.php b/src/Exceptions/AttachmentDownloadException.php index 89bdf457..4d5ab139 100644 --- a/src/Exceptions/AttachmentDownloadException.php +++ b/src/Exceptions/AttachmentDownloadException.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder->add('filetype_filter', TextType::class, ['required' => false, - 'label' => $this->trans->trans('attachment_type.edit.filetype_filter'), - 'help' => $this->trans->trans('attachment_type.edit.filetype_filter.help'), + 'label' => $this->trans->trans('attachment_type.edit.filetype_filter'), + 'help' => $this->trans->trans('attachment_type.edit.filetype_filter.help'), 'attr' => ['placeholder' => $this->trans->trans('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( @@ -65,4 +61,4 @@ class AttachmentTypeAdminForm extends BaseEntityAdminForm } )); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/BaseEntityAdminForm.php b/src/Form/AdminPages/BaseEntityAdminForm.php index 78ce3896..c03956ba 100644 --- a/src/Form/AdminPages/BaseEntityAdminForm.php +++ b/src/Form/AdminPages/BaseEntityAdminForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder ->add('name', TextType::class, ['empty_data' => '', 'label' => $this->trans->trans('name.label'), 'attr' => ['placeholder' => $this->trans->trans('part.name.placeholder')], 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]) - ->add('parent', StructuralEntityType::class, ['class' => get_class($entity), - 'required' => false, 'label' => $this->trans->trans('parent.label'), + ->add('parent', StructuralEntityType::class, ['class' => \get_class($entity), + 'required' => false, 'label' => $this->trans->trans('parent.label'), 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity), ]) ->add('not_selectable', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('entity.edit.not_selectable'), - 'help' => $this->trans->trans('entity.edit.not_selectable.help'), + 'label' => $this->trans->trans('entity.edit.not_selectable'), + 'help' => $this->trans->trans('entity.edit.not_selectable.help'), 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity) ]) + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]) ->add('comment', CKEditorType::class, ['required' => false, 'empty_data' => '', - 'label' => $this->trans->trans('comment.label'), - 'attr' => ['rows' => 4], 'help' => $this->trans->trans('bbcode.hint'), - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'label' => $this->trans->trans('comment.label'), + 'attr' => ['rows' => 4], 'help' => $this->trans->trans('bbcode.hint'), + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $this->additionalFormElements($builder, $options, $entity); @@ -106,27 +97,27 @@ class BaseEntityAdminForm extends AbstractType 'entry_options' => [ 'data_class' => $options['attachment_class'], ], - 'by_reference' => false + 'by_reference' => false, ]); $builder->add('master_picture_attachment', MasterPictureAttachmentType::class, [ 'required' => false, 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), 'label' => $this->trans->trans('part.edit.master_attachment'), - 'entity' => $entity + 'entity' => $entity, ]); //Buttons $builder->add('save', SubmitType::class, [ - 'label' => $is_new ? $this->trans->trans('entity.create') : $this->trans->trans('entity.edit.save'), + 'label' => $is_new ? $this->trans->trans('entity.create') : $this->trans->trans('entity.edit.save'), 'attr' => ['class' => $is_new ? 'btn-success' : ''], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]) + '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)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); } protected function additionalFormElements(FormBuilderInterface $builder, array $options, NamedDBElement $entity) { //Empty for Base } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/CategoryAdminForm.php b/src/Form/AdminPages/CategoryAdminForm.php index a5598bd3..0b302437 100644 --- a/src/Form/AdminPages/CategoryAdminForm.php +++ b/src/Form/AdminPages/CategoryAdminForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder->add('disable_footprints', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('category.edit.disable_footprints'), - 'help' => $this->trans->trans('category.edit.disable_footprints.help'), + 'label' => $this->trans->trans('category.edit.disable_footprints'), + 'help' => $this->trans->trans('category.edit.disable_footprints.help'), 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('disable_manufacturers', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('category.edit.disable_manufacturers'), - 'help' => $this->trans->trans('category.edit.disable_manufacturers.help'), - 'label_attr'=> ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'label' => $this->trans->trans('category.edit.disable_manufacturers'), + 'help' => $this->trans->trans('category.edit.disable_manufacturers.help'), + 'label_attr' => ['class' => 'checkbox-custom'], + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('disable_autodatasheets', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('category.edit.disable_autodatasheets'), - 'help' => $this->trans->trans('category.edit.disable_autodatasheets.help'), - 'label_attr'=> ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'label' => $this->trans->trans('category.edit.disable_autodatasheets'), + 'help' => $this->trans->trans('category.edit.disable_autodatasheets.help'), + 'label_attr' => ['class' => 'checkbox-custom'], + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('disable_properties', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('category.edit.disable_properties'), - 'help' => $this->trans->trans('category.edit.disable_properties.help'), - 'label_attr'=> ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'label' => $this->trans->trans('category.edit.disable_properties'), + 'help' => $this->trans->trans('category.edit.disable_properties.help'), + 'label_attr' => ['class' => 'checkbox-custom'], + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('partname_hint', TextType::class, ['required' => false, 'empty_data' => '', - 'label' => $this->trans->trans('category.edit.partname_hint'), - 'attr' => ['placeholder' => $this->trans->trans('category.edit.partname_hint.placeholder')], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'label' => $this->trans->trans('category.edit.partname_hint'), + 'attr' => ['placeholder' => $this->trans->trans('category.edit.partname_hint.placeholder')], + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('partname_regex', TextType::class, ['required' => false, 'empty_data' => '', 'label' => $this->trans->trans('category.edit.partname_regex'), 'attr' => ['placeholder' => 'category.edit.partname_regex.placeholder'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('default_description', TextType::class, ['required' => false, 'empty_data' => '', - 'label' => $this->trans->trans('category.edit.default_description'), + 'label' => $this->trans->trans('category.edit.default_description'), 'attr' => ['placeholder' => $this->trans->trans('category.edit.default_description.placeholder')], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('default_comment', TextType::class, ['required' => false, 'empty_data' => '', 'label' => $this->trans->trans('category.edit.default_comment'), 'attr' => ['placeholder' => $this->trans->trans('category.edit.default_comment.placeholder')], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/CompanyForm.php b/src/Form/AdminPages/CompanyForm.php index ec6df50c..f9f3fe82 100644 --- a/src/Form/AdminPages/CompanyForm.php +++ b/src/Form/AdminPages/CompanyForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder->add('address', TextareaType::class, [ 'label' => $this->trans->trans('company.edit.address'), 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), 'attr' => ['placeholder' => $this->trans->trans('company.edit.address.placeholder')], 'required' => false, - 'empty_data' => '' + 'empty_data' => '', ]); $builder->add('phone_number', TelType::class, [ @@ -51,28 +46,28 @@ class CompanyForm extends BaseEntityAdminForm 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), 'attr' => ['placeholder' => $this->trans->trans('company.edit.phone_number.placeholder')], 'required' => false, - 'empty_data' => '' + 'empty_data' => '', ]); $builder->add('fax_number', TelType::class, [ 'label' => $this->trans->trans('company.edit.fax_number'), 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), 'attr' => ['placeholder' => 'company.fax_number.placeholder'], 'required' => false, - 'empty_data' => '' + 'empty_data' => '', ]); $builder->add('email_address', EmailType::class, [ 'label' => $this->trans->trans('company.edit.email'), 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), 'attr' => ['placeholder' => $this->trans->trans('company.edit.email.placeholder')], 'required' => false, - 'empty_data' => '' + 'empty_data' => '', ]); $builder->add('website', UrlType::class, [ 'label' => $this->trans->trans('company.edit.website'), 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), 'attr' => ['placeholder' => $this->trans->trans('company.edit.website.placeholder')], 'required' => false, - 'empty_data' => '' + 'empty_data' => '', ]); $builder->add('auto_product_url', UrlType::class, [ @@ -81,7 +76,7 @@ class CompanyForm extends BaseEntityAdminForm 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), 'attr' => ['placeholder' => $this->trans->trans('company.edit.auto_product_url.placeholder')], 'required' => false, - 'empty_data' => '' + 'empty_data' => '', ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/CurrencyAdminForm.php b/src/Form/AdminPages/CurrencyAdminForm.php index 5e8db9b3..d1d022d7 100644 --- a/src/Form/AdminPages/CurrencyAdminForm.php +++ b/src/Form/AdminPages/CurrencyAdminForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder->add('iso_code', CurrencyType::class, [ 'required' => false, 'label' => $this->trans->trans('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)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('exchange_rate', MoneyType::class, [ 'required' => false, 'label' => $this->trans->trans('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), ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/FootprintAdminForm.php b/src/Form/AdminPages/FootprintAdminForm.php index 720c0d14..efcedf93 100644 --- a/src/Form/AdminPages/FootprintAdminForm.php +++ b/src/Form/AdminPages/FootprintAdminForm.php @@ -1,6 +1,6 @@ add('footprint_3d', MasterPictureAttachmentType::class, [ 'required' => false, - 'disabled' => !$this->security->isGranted($entity->getID() === null ? 'create' : 'edit', $entity), + 'disabled' => !$this->security->isGranted(null === $entity->getID() ? 'create' : 'edit', $entity), 'label' => $this->trans->trans('footprint.edit.3d_model'), 'filter' => '3d_model', - 'entity' => $entity + 'entity' => $entity, ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/GroupAdminForm.php b/src/Form/AdminPages/GroupAdminForm.php index 89385f2e..095c2383 100644 --- a/src/Form/AdminPages/GroupAdminForm.php +++ b/src/Form/AdminPages/GroupAdminForm.php @@ -1,6 +1,6 @@ add('permissions', PermissionsType::class, [ 'mapped' => false, 'data' => $builder->getData(), - 'disabled' => !$this->security->isGranted('edit_permissions', $entity) + 'disabled' => !$this->security->isGranted('edit_permissions', $entity), ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/ImportType.php b/src/Form/AdminPages/ImportType.php index 210e42db..a344f417 100644 --- a/src/Form/AdminPages/ImportType.php +++ b/src/Form/AdminPages/ImportType.php @@ -1,6 +1,6 @@ security->isGranted($perm_name, $entity); + $perm_name = 'create'; + $disabled = !$this->security->isGranted($perm_name, $entity); $builder ->add('format', ChoiceType::class, [ - 'choices' => ['JSON' => 'json', 'XML' => 'xml','CSV' => 'csv' ,'YAML' => 'yaml'], + 'choices' => ['JSON' => 'json', 'XML' => 'xml', 'CSV' => 'csv', 'YAML' => 'yaml'], 'label' => $this->trans->trans('export.format'), - 'disabled' => $disabled]) + 'disabled' => $disabled, ]) ->add('csv_separator', TextType::class, ['data' => ';', 'label' => $this->trans->trans('import.csv_separator'), - 'disabled' => $disabled]); + 'disabled' => $disabled, ]); if ($entity instanceof StructuralDBElement) { $builder->add('parent', StructuralEntityType::class, [ 'class' => $data['entity_class'], 'required' => false, 'label' => $this->trans->trans('parent.label'), - 'disabled' => $disabled + 'disabled' => $disabled, ]); } $builder->add('file', FileType::class, [ 'label' => $this->trans->trans('import.file'), 'attr' => ['class' => 'file', 'data-show-preview' => 'false', 'data-show-upload' => 'false'], - 'disabled' => $disabled + 'disabled' => $disabled, ]) ->add('preserve_children', CheckboxType::class, ['data' => true, 'required' => false, 'label' => $this->trans->trans('import.preserve_children'), - 'label_attr' => ['class' => 'checkbox-custom'], 'disabled' => $disabled]) + 'label_attr' => ['class' => 'checkbox-custom'], 'disabled' => $disabled, ]) ->add('abort_on_validation_error', CheckboxType::class, ['data' => true, 'required' => false, 'label' => $this->trans->trans('import.abort_on_validation'), 'help' => $this->trans->trans('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]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/MassCreationForm.php b/src/Form/AdminPages/MassCreationForm.php index 46e8d1da..012f49cf 100644 --- a/src/Form/AdminPages/MassCreationForm.php +++ b/src/Form/AdminPages/MassCreationForm.php @@ -1,6 +1,6 @@ security->isGranted($perm_name, $entity); + $perm_name = 'create'; + $disabled = !$this->security->isGranted($perm_name, $entity); $builder ->add('lines', TextareaType::class, ['data' => '', @@ -64,21 +56,21 @@ class MassCreationForm extends AbstractType 'disabled' => $disabled, 'required' => true, 'attr' => [ 'placeholder' => $this->translator->trans('mass_creation.lines.placeholder'), - 'rows' => 10 - ] + 'rows' => 10, + ], ]); if ($entity instanceof StructuralDBElement) { $builder->add('parent', StructuralEntityType::class, [ 'class' => $data['entity_class'], 'required' => false, 'label' => $this->translator->trans('parent.label'), - 'disabled' => $disabled]); + 'disabled' => $disabled, ]); } //Buttons $builder->add('create', SubmitType::class, [ 'label' => $this->translator->trans('entity.mass_creation.btn'), - 'disabled' => $disabled + 'disabled' => $disabled, ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/MeasurementUnitAdminForm.php b/src/Form/AdminPages/MeasurementUnitAdminForm.php index b0c874c6..09413a1f 100644 --- a/src/Form/AdminPages/MeasurementUnitAdminForm.php +++ b/src/Form/AdminPages/MeasurementUnitAdminForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder->add('is_integer', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('measurement_unit.edit.is_integer'), + 'label' => $this->trans->trans('measurement_unit.edit.is_integer'), 'help' => $this->trans->trans('measurement_unit.edit.is_integer.help'), 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('use_si_prefix', CheckboxType::class, ['required' => false, 'label' => $this->trans->trans('measurement_unit.edit.use_si_prefix'), 'help' => $this->trans->trans('measurement_unit.edit.use_si_prefix.help'), 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); $builder->add('unit', TextType::class, ['required' => false, 'label' => $this->trans->trans('measurement_unit.edit.unit_symbol'), 'attr' => ['placeholder' => $this->trans->trans('measurement_unit.edit.unit_symbol.placeholder')], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'edit', $entity), ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/StorelocationAdminForm.php b/src/Form/AdminPages/StorelocationAdminForm.php index e0ba7c1b..e284cadb 100644 --- a/src/Form/AdminPages/StorelocationAdminForm.php +++ b/src/Form/AdminPages/StorelocationAdminForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder->add('is_full', CheckboxType::class, [ 'required' => false, 'label' => $this->trans->trans('storelocation.edit.is_full.label'), 'help' => $this->trans->trans('storelocation.edit.is_full.help'), 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); $builder->add('limit_to_existing_parts', CheckboxType::class, [ 'required' => false, 'label' => $this->trans->trans('storelocation.limit_to_existing.label'), 'help' => $this->trans->trans('storelocation.limit_to_existing.help'), 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); $builder->add('only_single_part', CheckboxType::class, [ 'required' => false, 'label' => $this->trans->trans('storelocation.only_single_part.label'), 'help' => $this->trans->trans('storelocation.only_single_part.help'), 'label_attr' => ['class' => 'checkbox-custom'], - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity)]); + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); $builder->add('storage_type', StructuralEntityType::class, [ 'required' => false, 'label' => $this->trans->trans('storelocation.storage_type.label'), 'help' => $this->trans->trans('storelocation.storage_type.help'), 'class' => MeasurementUnit::class, 'disable_not_selectable' => true, - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity)]); - + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); } -} \ No newline at end of file +} diff --git a/src/Form/AdminPages/SupplierForm.php b/src/Form/AdminPages/SupplierForm.php index 1ad6c8ea..327e72dd 100644 --- a/src/Form/AdminPages/SupplierForm.php +++ b/src/Form/AdminPages/SupplierForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); - parent::additionalFormElements($builder, $options, $entity); + parent::additionalFormElements($builder, $options, $entity); $builder->add('default_currency', StructuralEntityType::class, [ 'class' => Currency::class, @@ -58,7 +47,7 @@ class SupplierForm extends CompanyForm 'currency' => $this->params->get('default_currency'), 'scale' => 3, 'label' => $this->trans->trans('supplier.shipping_costs.label'), - 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity) + 'disabled' => !$this->security->isGranted($is_new ? 'create' : 'move', $entity), ]); } -} \ No newline at end of file +} diff --git a/src/Form/AttachmentFormType.php b/src/Form/AttachmentFormType.php index 870b48b7..477a8c4a 100644 --- a/src/Form/AttachmentFormType.php +++ b/src/Form/AttachmentFormType.php @@ -1,6 +1,6 @@ add('name', TextType::class, [ - 'label' => $this->trans->trans('attachment.edit.name') + 'label' => $this->trans->trans('attachment.edit.name'), ]) ->add('attachment_type', StructuralEntityType::class, [ - 'label' => $this->trans->trans('attachment.edit.attachment_type'), + 'label' => $this->trans->trans('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, - 'label' => $this->trans->trans('attachment.edit.show_in_table'), + 'label' => $this->trans->trans('attachment.edit.show_in_table'), 'attr' => ['class' => 'form-control-sm'], - 'label_attr' => ['class' => 'checkbox-custom']]); + 'label_attr' => ['class' => 'checkbox-custom'], ]); $builder->add('secureFile', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('attachment.edit.secure_file'), + 'label' => $this->trans->trans('attachment.edit.secure_file'), 'mapped' => false, 'attr' => ['class' => 'form-control-sm'], 'help' => $this->trans->trans('attachment.edit.secure_file.help'), - 'label_attr' => ['class' => 'checkbox-custom']]); + 'label_attr' => ['class' => 'checkbox-custom'], ]); $builder->add('url', TextType::class, [ - 'label' => $this->trans->trans('attachment.edit.url'), + 'label' => $this->trans->trans('attachment.edit.url'), 'required' => false, 'attr' => [ 'data-autocomplete' => $this->urlGenerator->generate('typeahead_builtInRessources', ['query' => 'QUERY']), //Disable browser autocomplete - 'autocomplete' => 'off' + 'autocomplete' => 'off', ], 'help' => $this->trans->trans('attachment.edit.url.help'), 'constraints' => [ - $options['allow_builtins'] ? new UrlOrBuiltin() : new Url() - ] + $options['allow_builtins'] ? new UrlOrBuiltin() : new Url(), + ], ]); $builder->add('downloadURL', CheckboxType::class, ['required' => false, - 'label' => $this->trans->trans('attachment.edit.download_url'), + 'label' => $this->trans->trans('attachment.edit.download_url'), 'mapped' => false, 'disabled' => !$this->allow_attachments_download, 'attr' => ['class' => 'form-control-sm'], - 'label_attr' => ['class' => 'checkbox-custom']]); - + 'label_attr' => ['class' => 'checkbox-custom'], ]); $builder->add('file', FileType::class, [ - 'label' => $this->trans->trans('attachment.edit.file'), + 'label' => $this->trans->trans('attachment.edit.file'), 'mapped' => false, 'required' => false, 'attr' => ['class' => 'file', 'data-show-preview' => 'false', 'data-show-upload' => 'false'], 'constraints' => [ new AllowedFileExtension(), new File([ - 'maxSize' => $options['max_file_size'] + 'maxSize' => $options['max_file_size'], ]), - ] + ], ]); //Check the secure file checkbox, if file is in securefile location @@ -137,8 +131,7 @@ class AttachmentFormType extends AbstractType $resolver->setDefaults([ 'data_class' => Attachment::class, 'max_file_size' => '16M', - 'allow_builtins' => true + 'allow_builtins' => true, ]); - } -} \ No newline at end of file +} diff --git a/src/Form/Part/OrderdetailType.php b/src/Form/Part/OrderdetailType.php index 7f1835f1..2d1bbfaf 100644 --- a/src/Form/Part/OrderdetailType.php +++ b/src/Form/Part/OrderdetailType.php @@ -1,6 +1,6 @@ add('supplierpartnr', TextType::class, [ 'label' => $this->trans->trans('orderdetails.edit.supplierpartnr'), - 'attr' => ['placeholder' => $this->trans->trans('orderdetails.edit.supplierpartnr.placeholder')], + 'attr' => ['placeholder' => $this->trans->trans('orderdetails.edit.supplierpartnr.placeholder')], 'required' => false, - 'empty_data' => "" + 'empty_data' => '', ]); $builder->add('supplier', StructuralEntityType::class, [ 'class' => Supplier::class, 'disable_not_selectable' => true, - 'label' => $this->trans->trans('orderdetails.edit.supplier') + 'label' => $this->trans->trans('orderdetails.edit.supplier'), ]); $builder->add('supplier_product_url', UrlType::class, [ 'required' => false, - 'empty_data' => "", - 'label' => $this->trans->trans('orderdetails.edit.url') + 'empty_data' => '', + 'label' => $this->trans->trans('orderdetails.edit.url'), ]); $builder->add('obsolete', CheckboxType::class, [ 'required' => false, 'label_attr' => ['class' => 'checkbox-custom'], - 'label' => $this->trans->trans('orderdetails.edit.obsolete') + 'label' => $this->trans->trans('orderdetails.edit.obsolete'), ]); - //Add pricedetails after we know the data, so we can set the default currency $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) { /** @var Orderdetail $orderdetail */ $orderdetail = $event->getData(); $dummy_pricedetail = new Pricedetail(); - if ($orderdetail !== null && $orderdetail->getSupplier() !== null) { + if (null !== $orderdetail && null !== $orderdetail->getSupplier()) { $dummy_pricedetail->setCurrency($orderdetail->getSupplier()->getDefaultCurrency()); } @@ -101,10 +98,9 @@ class OrderdetailType extends AbstractType 'by_reference' => false, 'entry_options' => [ 'disabled' => !$this->security->isGranted('@parts_prices.edit'), - 'measurement_unit' => $options['measurement_unit'] - ] + 'measurement_unit' => $options['measurement_unit'], + ], ]); - }); } @@ -118,4 +114,4 @@ class OrderdetailType extends AbstractType $resolver->setRequired('measurement_unit'); $resolver->setAllowedTypes('measurement_unit', [MeasurementUnit::class, 'null']); } -} \ No newline at end of file +} diff --git a/src/Form/Part/PartBaseType.php b/src/Form/Part/PartBaseType.php index e257e3d0..e549be04 100644 --- a/src/Form/Part/PartBaseType.php +++ b/src/Form/Part/PartBaseType.php @@ -1,6 +1,6 @@ getData(); $status_choices = [ - $this->trans->trans("m_status.unknown") => '', + $this->trans->trans('m_status.unknown') => '', $this->trans->trans('m_status.announced') => 'announced', $this->trans->trans('m_status.active') => 'active', $this->trans->trans('m_status.nrfnd') => 'nrfnd', $this->trans->trans('m_status.eol') => 'eol', - $this->trans->trans('m_status.discontinued') => 'discontinued' + $this->trans->trans('m_status.discontinued') => 'discontinued', ]; //Common section $builder ->add('name', TextType::class, [ 'empty_data' => '', - 'label' => $this->trans->trans('part.edit.name'), + 'label' => $this->trans->trans('part.edit.name'), 'attr' => ['placeholder' => $this->trans->trans('part.edit.name.placeholder')], 'disabled' => !$this->security->isGranted('name.edit', $part), ]) @@ -97,7 +89,7 @@ class PartBaseType extends AbstractType 'label' => $this->trans->trans('part.edit.description'), 'config_name' => 'description_config', 'attr' => ['placeholder' => $this->trans->trans('part.edit.description.placeholder'), 'rows' => 2], - 'disabled' => !$this->security->isGranted('description.edit', $part) + 'disabled' => !$this->security->isGranted('description.edit', $part), ]) ->add('minAmount', SIUnitType::class, [ 'attr' => ['min' => 0, 'placeholder' => $this->trans->trans('part.editmininstock.placeholder')], @@ -121,11 +113,11 @@ class PartBaseType extends AbstractType ->add('tags', TextType::class, [ 'required' => false, 'label' => $this->trans->trans('part.edit.tags'), - 'empty_data' => "", + 'empty_data' => '', 'attr' => [ 'class' => 'tagsinput', - 'data-autocomplete' => $this->urlGenerator->generate('typeahead_tags', ['query' => 'QUERY']),], - 'disabled' => !$this->security->isGranted('tags.edit', $part) + 'data-autocomplete' => $this->urlGenerator->generate('typeahead_tags', ['query' => 'QUERY']), ], + 'disabled' => !$this->security->isGranted('tags.edit', $part), ]); //Manufacturer section @@ -134,7 +126,7 @@ class PartBaseType extends AbstractType 'required' => false, 'label' => $this->trans->trans('part.edit.manufacturer.label'), 'disable_not_selectable' => true, - 'disabled' => !$this->security->isGranted('manufacturer.edit', $part) + 'disabled' => !$this->security->isGranted('manufacturer.edit', $part), ]) ->add('manufacturer_product_url', UrlType::class, [ 'required' => false, @@ -146,12 +138,12 @@ class PartBaseType extends AbstractType 'required' => false, 'empty_data' => '', 'label' => $this->trans->trans('part.edit.mpn'), - 'disabled' => !$this->security->isGranted('mpn.edit', $part)]) + 'disabled' => !$this->security->isGranted('mpn.edit', $part), ]) ->add('manufacturing_status', ChoiceType::class, [ 'label' => $this->trans->trans('part.edit.manufacturing_status'), 'choices' => $status_choices, 'required' => false, - 'disabled' => !$this->security->isGranted('status.edit', $part) + 'disabled' => !$this->security->isGranted('status.edit', $part), ]); //Advanced section @@ -159,35 +151,34 @@ class PartBaseType extends AbstractType 'label_attr' => ['class' => 'checkbox-custom'], 'required' => false, 'label' => $this->trans->trans('part.edit.needs_review'), - 'disabled' => !$this->security->isGranted('edit', $part) + 'disabled' => !$this->security->isGranted('edit', $part), ]) ->add('favorite', CheckboxType::class, [ 'label_attr' => ['class' => 'checkbox-custom'], 'required' => false, 'label' => $this->trans->trans('part.edit.is_favorite'), - 'disabled' => !$this->security->isGranted('change_favorite', $part) + 'disabled' => !$this->security->isGranted('change_favorite', $part), ]) ->add('mass', SIUnitType::class, [ 'unit' => 'g', 'label' => $this->trans->trans('part.edit.mass'), 'required' => false, - 'disabled' => !$this->security->isGranted('mass.edit', $part) + 'disabled' => !$this->security->isGranted('mass.edit', $part), ]) ->add('partUnit', StructuralEntityType::class, [ 'class' => MeasurementUnit::class, 'required' => false, 'disable_not_selectable' => true, 'label' => $this->trans->trans('part.edit.partUnit'), - 'disabled' => !$this->security->isGranted('unit.edit', $part) + 'disabled' => !$this->security->isGranted('unit.edit', $part), ]); - //Comment section $builder->add('comment', CKEditorType::class, [ 'required' => false, 'label' => $this->trans->trans('part.edit.comment'), 'attr' => ['rows' => 4], - 'disabled' => !$this->security->isGranted('comment.edit', $part), 'empty_data' => '' + 'disabled' => !$this->security->isGranted('comment.edit', $part), 'empty_data' => '', ]); //Part Lots section @@ -200,7 +191,7 @@ class PartBaseType extends AbstractType 'measurement_unit' => $part->getPartUnit(), 'disabled' => !$this->security->isGranted('lots.edit', $part), ], - 'by_reference' => false + 'by_reference' => false, ]); //Attachment section @@ -213,14 +204,14 @@ class PartBaseType extends AbstractType 'data_class' => PartAttachment::class, 'disabled' => !$this->security->isGranted('attachments.edit', $part), ], - 'by_reference' => false + 'by_reference' => false, ]); $builder->add('master_picture_attachment', MasterPictureAttachmentType::class, [ 'required' => false, 'disabled' => !$this->security->isGranted('attachments.edit', $part), 'label' => $this->trans->trans('part.edit.master_attachment'), - 'entity' => $part + 'entity' => $part, ]); //Orderdetails section @@ -234,7 +225,7 @@ class PartBaseType extends AbstractType 'entry_options' => [ 'measurement_unit' => $part->getPartUnit(), 'disabled' => !$this->security->isGranted('orderdetails.edit', $part), - ] + ], ]); $builder diff --git a/src/Form/Part/PartLotType.php b/src/Form/Part/PartLotType.php index b80cb6d9..d2b2cdbc 100644 --- a/src/Form/Part/PartLotType.php +++ b/src/Form/Part/PartLotType.php @@ -1,6 +1,6 @@ add('description', TextType::class, [ 'label' => $this->trans->trans('part_lot.edit.description'), 'required' => false, - 'empty_data' => "", - 'attr' => ['class' => 'form-control-sm'] + 'empty_data' => '', + 'attr' => ['class' => 'form-control-sm'], ]); $builder->add('storage_location', StructuralEntityType::class, ['class' => Storelocation::class, 'label' => $this->trans->trans('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' => $this->trans->trans('part_lot.edit.amount'), - 'attr' => ['class' => 'form-control-sm'] + 'attr' => ['class' => 'form-control-sm'], ]); $builder->add('instock_unknown', CheckboxType::class, ['required' => false, 'label' => $this->trans->trans('part_lot.edit.instock_unknown'), 'attr' => ['class' => 'form-control-sm'], - 'label_attr' => ['class' => 'checkbox-custom'] + 'label_attr' => ['class' => 'checkbox-custom'], ]); $builder->add('needs_refill', CheckboxType::class, ['label_attr' => ['class' => 'checkbox-custom'], 'label' => $this->trans->trans('part_lot.edit.needs_refill'), 'attr' => ['class' => 'form-control-sm'], - 'required' => false + 'required' => false, ]); $builder->add('expirationDate', DateTimeType::class, [ 'label' => $this->trans->trans('part_lot.edit.expiration_date'), 'attr' => [], - 'required' => false]); + 'required' => false, ]); $builder->add('comment', TextType::class, [ 'label' => $this->trans->trans('part_lot.edit.comment'), 'attr' => ['class' => 'form-control-sm'], - 'required' => false, 'empty_data' => "" + 'required' => false, 'empty_data' => '', ]); } - public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -114,4 +101,4 @@ class PartLotType extends AbstractType $resolver->setRequired('measurement_unit'); $resolver->setAllowedTypes('measurement_unit', [MeasurementUnit::class, 'null']); } -} \ No newline at end of file +} diff --git a/src/Form/Part/PricedetailType.php b/src/Form/Part/PricedetailType.php index cb47235e..d81a772d 100644 --- a/src/Form/Part/PricedetailType.php +++ b/src/Form/Part/PricedetailType.php @@ -1,6 +1,6 @@ add("min_discount_quantity", SIUnitType::class, [ + $builder->add('min_discount_quantity', SIUnitType::class, [ 'measurement_unit' => $options['measurement_unit'], - 'attr' => ['class' => 'form-control-sm'] + 'attr' => ['class' => 'form-control-sm'], ]); - $builder->add("price_related_quantity", SIUnitType::class, [ + $builder->add('price_related_quantity', SIUnitType::class, [ 'measurement_unit' => $options['measurement_unit'], - 'attr' => ['class' => 'form-control-sm'] + 'attr' => ['class' => 'form-control-sm'], ]); - $builder->add("price", NumberType::class, [ + $builder->add('price', NumberType::class, [ 'scale' => 5, 'html5' => true, - 'attr' => ['min' => 0, 'step' => "any"] + 'attr' => ['min' => 0, 'step' => 'any'], ]); - $builder->add("currency", CurrencyEntityType::class, ['required' => false]); + $builder->add('currency', CurrencyEntityType::class, ['required' => false]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Pricedetail::class, - 'error_bubbling' => false + 'error_bubbling' => false, ]); $resolver->setRequired('measurement_unit'); $resolver->setAllowedTypes('measurement_unit', [MeasurementUnit::class, 'null']); } -} \ No newline at end of file +} diff --git a/src/Form/Permissions/PermissionGroupType.php b/src/Form/Permissions/PermissionGroupType.php index 71ae5a68..e0ce75ac 100644 --- a/src/Form/Permissions/PermissionGroupType.php +++ b/src/Form/Permissions/PermissionGroupType.php @@ -1,6 +1,6 @@ false, 'data' => $builder->getData(), 'disabled' => $options['disabled'], - 'inherit' => $options['inherit'] + 'inherit' => $options['inherit'], ]); } } @@ -86,4 +84,4 @@ class PermissionGroupType extends AbstractType return $options['name']; }); } -} \ No newline at end of file +} diff --git a/src/Form/Permissions/PermissionType.php b/src/Form/Permissions/PermissionType.php index 2e657754..2b06c806 100644 --- a/src/Form/Permissions/PermissionType.php +++ b/src/Form/Permissions/PermissionType.php @@ -1,6 +1,6 @@ setDefaults([ - 'inherit' => false + 'inherit' => false, ]); } @@ -80,7 +75,7 @@ class PermissionType extends AbstractType 'required' => false, 'mapped' => false, 'label' => $operation['label'] ?? null, - 'disabled' => $options['disabled'] + 'disabled' => $options['disabled'], ]); } @@ -91,4 +86,4 @@ class PermissionType extends AbstractType { $view->vars['multi_checkbox'] = $options['multi_checkbox']; } -} \ No newline at end of file +} diff --git a/src/Form/Permissions/PermissionsMapper.php b/src/Form/Permissions/PermissionsMapper.php index 366eadb4..7d98bf07 100644 --- a/src/Form/Permissions/PermissionsMapper.php +++ b/src/Form/Permissions/PermissionsMapper.php @@ -1,6 +1,6 @@ perm_structure = $resolver->getPermissionStructure(); } - public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ @@ -52,12 +49,11 @@ class PermissionsType extends AbstractType if (!$options['disabled']) { return [new NoLockout()]; } + return []; }, 'inherit' => false, ]); - - } public function buildView(FormView $view, FormInterface $form, array $options) @@ -70,12 +66,12 @@ class PermissionsType extends AbstractType $groups = $this->perm_structure['groups']; foreach ($groups as $key => $group) { - $builder->add($key,PermissionGroupType::class, [ + $builder->add($key, PermissionGroupType::class, [ 'group_name' => $key, 'mapped' => false, 'data' => $builder->getData(), 'disabled' => $options['disabled'], - 'inherit' => $options['inherit'] + 'inherit' => $options['inherit'], ]); } @@ -85,7 +81,7 @@ class PermissionsType extends AbstractType 'mapped' => false, 'data' => $builder->getData(), 'disabled' => $options['disabled'], - 'inherit' => $options['inherit'] + 'inherit' => $options['inherit'], ]); } -} \ No newline at end of file +} diff --git a/src/Form/Type/CurrencyEntityType.php b/src/Form/Type/CurrencyEntityType.php index bd0cfe2e..0f3ff6f7 100644 --- a/src/Form/Type/CurrencyEntityType.php +++ b/src/Form/Type/CurrencyEntityType.php @@ -1,6 +1,6 @@ getLevel(); //If our base entity is not the root level, we need to change the level, to get zero position - if ($this->options['subentities_of'] !== null) { + if (null !== $this->options['subentities_of']) { $level -= $parent->getLevel() - 1; } - $tmp = str_repeat('   ', $choice->getLevel()); //Use 3 spaces for intendation if (empty($choice->getIsoCode())) { $tmp .= htmlspecialchars($choice->getName()); } else { $tmp .= Currencies::getSymbol($choice->getIsoCode()); } + return $tmp; } - protected function generateChoiceAttr(StructuralDBElement $choice, $key, $value) : array + protected function generateChoiceAttr(StructuralDBElement $choice, $key, $value): array { /** @var Currency $choice */ - - $tmp = array(); + $tmp = []; if (!empty($choice->getIsoCode())) { //Show the name of the currency @@ -104,6 +100,7 @@ class CurrencyEntityType extends StructuralEntityType if ($this->options['disable_not_selectable'] && $choice->isNotSelectable()) { $tmp += ['disabled' => 'disabled']; } + return $tmp; } -} \ No newline at end of file +} diff --git a/src/Form/Type/MasterPictureAttachmentType.php b/src/Form/Type/MasterPictureAttachmentType.php index edb4a445..25ebb117 100644 --- a/src/Form/Type/MasterPictureAttachmentType.php +++ b/src/Form/Type/MasterPictureAttachmentType.php @@ -1,6 +1,6 @@ setRequired('entity'); @@ -47,9 +44,9 @@ class MasterPictureAttachmentType extends AbstractType /** @var Attachment $choice */ $tmp = ['data-subtext' => $choice->getFilename() ?? 'URL']; - if ($options['filter'] === 'picture' && !$choice->isPicture()) { + if ('picture' === $options['filter'] && !$choice->isPicture()) { $tmp += ['disabled' => 'disabled']; - } elseif ($options['filter'] === '3d_model' && !$choice->is3DModel()) { + } elseif ('3d_model' === $options['filter'] && !$choice->is3DModel()) { $tmp += ['disabled' => 'disabled']; } @@ -60,22 +57,23 @@ class MasterPictureAttachmentType extends AbstractType 'class' => function (Options $options) { $short_class_name = (new \ReflectionClass($options['entity']))->getShortName(); //Category becomes CategoryAttachment - return 'App\\Entity\\Attachments\\' . $short_class_name . 'Attachment'; + return 'App\\Entity\\Attachments\\'.$short_class_name.'Attachment'; }, 'query_builder' => function (Options $options) { return function (EntityRepository $er) use ($options) { $entity = $options['entity']; - if ($entity->getID() === null) { + if (null === $entity->getID()) { //This query is always false, so we get empty results return $er->createQueryBuilder('u')->where('0 = 2'); } + return $er->createQueryBuilder('u') ->where('u.element = ?1') ->andWhere("u.path <> ''") ->orderBy('u.name', 'ASC') ->setParameter(1, $entity); }; - } + }, ]); $resolver->setAllowedValues('filter', ['', 'picture', '3d_model']); @@ -85,4 +83,4 @@ class MasterPictureAttachmentType extends AbstractType { return EntityType::class; } -} \ No newline at end of file +} diff --git a/src/Form/Type/SIUnitType.php b/src/Form/Type/SIUnitType.php index 4ba28e54..2e3b22c9 100644 --- a/src/Form/Type/SIUnitType.php +++ b/src/Form/Type/SIUnitType.php @@ -1,6 +1,6 @@ setDefaults([ 'measurement_unit' => null, 'show_prefix' => function (Options $options) { - if ($options['measurement_unit'] !== null) { + if (null !== $options['measurement_unit']) { /** @var MeasurementUnit $unit */ $unit = $options['measurement_unit']; + return $unit->isUseSIPrefix(); } + return false; }, 'is_integer' => function (Options $options) { - if ($options['measurement_unit'] !== null) { + if (null !== $options['measurement_unit']) { /** @var MeasurementUnit $unit */ $unit = $options['measurement_unit']; + return $unit->isInteger(); } + return false; }, 'unit' => function (Options $options) { - if ($options['measurement_unit'] !== null) { + if (null !== $options['measurement_unit']) { /** @var MeasurementUnit $unit */ $unit = $options['measurement_unit']; + return $unit->getUnit(); } + return null; }, - 'error_mapping' => [ '.' => 'value'] + 'error_mapping' => ['.' => 'value'], ]); $resolver->setAllowedTypes('measurement_unit', [MeasurementUnit::class, 'null']); @@ -84,13 +88,13 @@ class SIUnitType extends AbstractType implements DataMapperInterface 'min' => 0, 'max' => '', 'step' => function (Options $options) { - if ($options['is_integer'] === true) { + if (true === $options['is_integer']) { return 1; } - return "any"; + return 'any'; }, - 'html5' => true + 'html5' => true, ]); } @@ -102,13 +106,13 @@ class SIUnitType extends AbstractType implements DataMapperInterface 'attr' => [ 'min' => (string) $options['min'], 'max' => (string) $options['max'], - 'step' => (string) $options['step'] - ] + 'step' => (string) $options['step'], + ], ]); if ($options['show_prefix']) { $builder->add('prefix', ChoiceType::class, [ - 'choices' => ['M' => 6, 'k' => 3, '' => 0, 'm' => -3, 'µ' => -6 ] + 'choices' => ['M' => 6, 'k' => 3, '' => 0, 'm' => -3, 'µ' => -6], ]); } @@ -121,7 +125,7 @@ class SIUnitType extends AbstractType implements DataMapperInterface //Check if we need to make this thing small if (isset($options['attr']['class'])) { - $view->vars['sm'] = (strpos($options['attr']['class'], 'form-control-sm') !== false); + $view->vars['sm'] = (false !== strpos($options['attr']['class'], 'form-control-sm')); } $view->vars['unit'] = $options['unit']; @@ -134,8 +138,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 */ @@ -143,7 +147,7 @@ class SIUnitType extends AbstractType implements DataMapperInterface { $forms = iterator_to_array($forms); - if ($viewData === null) { + if (null === $viewData) { if (isset($forms['prefix'])) { $forms['prefix']->setData(0); } @@ -154,7 +158,7 @@ class SIUnitType extends AbstractType implements DataMapperInterface $data = $this->si_formatter->convertValue($viewData); if (isset($forms['prefix'])) { - $forms['value']->setData($data["value"]); + $forms['value']->setData($data['value']); $forms['prefix']->setData($data['prefix_magnitude']); } else { $forms['value']->setData($viewData); @@ -184,8 +188,8 @@ 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 + * @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 @@ -203,4 +207,4 @@ class SIUnitType extends AbstractType implements DataMapperInterface $viewData *= 10 ** $multiplier; } } -} \ No newline at end of file +} diff --git a/src/Form/Type/StructuralEntityType.php b/src/Form/Type/StructuralEntityType.php index c0111486..a5742ce6 100644 --- a/src/Form/Type/StructuralEntityType.php +++ b/src/Form/Type/StructuralEntityType.php @@ -1,6 +1,6 @@ addModelTransformer(new CallbackTransformer( - function ($value) use ($options){ + function ($value) use ($options) { return $this->transform($value, $options); }, function ($value) use ($options) { - return $this->reverseTransform($value, $options); - })); + return $this->reverseTransform($value, $options); + })); } public function configureOptions(OptionsResolver $resolver) @@ -89,25 +82,26 @@ class StructuralEntityType extends AbstractType return $this->generateChoiceLabels($choice, $key, $value); }, 'choice_attr' => function ($choice, $key, $value) { return $this->generateChoiceAttr($choice, $key, $value); - } + }, ]); $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']; } + return $tmp; }); } - protected function generateChoiceAttr(StructuralDBElement $choice, $key, $value) : array + protected function generateChoiceAttr(StructuralDBElement $choice, $key, $value): array { - $tmp = array(); + $tmp = []; - if ($this->options['show_fullpath_in_subtext'] && $choice->getParent() != null) { + if ($this->options['show_fullpath_in_subtext'] && null != $choice->getParent()) { $tmp += ['data-subtext' => $choice->getParent()->getFullPath()]; } @@ -123,7 +117,7 @@ class StructuralEntityType extends AbstractType return $tmp; } - protected function generateChoiceLabels(StructuralDBElement $choice, $key, $value) : string + protected function generateChoiceLabels(StructuralDBElement $choice, $key, $value): string { /** @var StructuralDBElement|null $parent */ $parent = $this->options['subentities_of']; @@ -131,34 +125,33 @@ class StructuralEntityType extends AbstractType /*** @var StructuralDBElement $choice */ $level = $choice->getLevel(); //If our base entity is not the root level, we need to change the level, to get zero position - if ($this->options['subentities_of'] !== null) { + if (null !== $this->options['subentities_of']) { $level -= $parent->getLevel() - 1; } - $tmp = str_repeat('   ', $choice->getLevel()); //Use 3 spaces for intendation - $tmp .= htmlspecialchars($choice->getName()); + $tmp .= htmlspecialchars($choice->getName()); + return $tmp; } /** - * Gets the entries from database and return an array of them - * @param Options $options + * Gets the entries from database and return an array of them. + * * @return array */ - public function getEntries(Options $options) : array + public function getEntries(Options $options): array { $this->options = $options; $choices = $this->builder->typeToNodesList($options['class'], null); - /** @var StructuralDBElementRepository $repo */ + /* @var StructuralDBElementRepository $repo */ /*$repo = $this->em->getRepository($options['class']); $choices = $repo->toNodesList(null); */ return $choices; } - public function buildView(FormView $view, FormInterface $form, array $options) { //Allow HTML in labels. You must override the 'choice_widget_options' block, so that can work @@ -254,10 +247,10 @@ class StructuralEntityType extends AbstractType The performance impact of this should be very small in comparison of the boost, caused by the caching. */ - if ($value === null) { + if (null === $value) { return null; } return $this->em->find($options['class'], $value->getID()); } -} \ No newline at end of file +} diff --git a/src/Form/Type/TriStateCheckboxType.php b/src/Form/Type/TriStateCheckboxType.php index 6c023a2e..c6989766 100644 --- a/src/Form/Type/TriStateCheckboxType.php +++ b/src/Form/Type/TriStateCheckboxType.php @@ -1,6 +1,6 @@ addViewTransformer($this); } @@ -44,7 +41,7 @@ class TriStateCheckboxType extends AbstractType implements DataTransformerInterf $resolver->setDefaults([ 'label_attr' => ['class' => 'checkbox-custom checkbox-inline'], 'attr' => ['class' => 'tristate'], - 'compound' => false + 'compound' => false, ]); } @@ -61,7 +58,7 @@ class TriStateCheckboxType extends AbstractType implements DataTransformerInterf $view->vars = array_replace($view->vars, [ 'value' => $form->getViewData(), 'checked' => true === $form->getData(), - 'indeterminate' => null === $form->getData() + 'indeterminate' => null === $form->getData(), ]); } @@ -106,19 +103,19 @@ class TriStateCheckboxType extends AbstractType implements DataTransformerInterf */ public function transform($value) { - if ($value === true) { - return "true"; + if (true === $value) { + return 'true'; } - if ($value === false) { - return "false"; + if (false === $value) { + return 'false'; } - if ($value === null) { - return "indeterminate"; + if (null === $value) { + return 'indeterminate'; } - throw new \InvalidArgumentException('Invalid value encountered!: ' . $value); + throw new \InvalidArgumentException('Invalid value encountered!: '.$value); } /** @@ -151,15 +148,15 @@ class TriStateCheckboxType extends AbstractType implements DataTransformerInterf public function reverseTransform($value) { switch ($value) { - case "true": + case 'true': return true; - case "false": + case 'false': case '': return false; - case "indeterminate": + case 'indeterminate': return null; default: - throw new \InvalidArgumentException('Invalid value encountered!: ' . $value); + throw new \InvalidArgumentException('Invalid value encountered!: '.$value); } } -} \ No newline at end of file +} diff --git a/src/Form/UserAdminForm.php b/src/Form/UserAdminForm.php index 24358cc3..f9514dac 100644 --- a/src/Form/UserAdminForm.php +++ b/src/Form/UserAdminForm.php @@ -1,6 +1,6 @@ getID() === null; + $is_new = null === $entity->getID(); $builder ->add('name', TextType::class, [ 'empty_data' => '', - 'label' => $this->trans->trans('user.username.label'), + 'label' => $this->trans->trans('user.username.label'), 'attr' => ['placeholder' => $this->trans->trans('user.username.placeholder')], 'disabled' => !$this->security->isGranted('edit_username', $entity), ]) @@ -111,7 +106,6 @@ class UserAdminForm extends AbstractType 'required' => false, 'disabled' => !$this->security->isGranted('edit_infos', $entity), ]) - ->add('department', TextType::class, [ 'empty_data' => '', 'label' => $this->trans->trans('user.department.label'), @@ -120,7 +114,6 @@ class UserAdminForm extends AbstractType 'disabled' => !$this->security->isGranted('edit_infos', $entity), ]) - //Config section ->add('language', LanguageType::class, [ 'required' => false, @@ -128,7 +121,7 @@ class UserAdminForm extends AbstractType 'placeholder' => $this->trans->trans('user_settings.language.placeholder'), 'label' => $this->trans->trans('user.language_select'), 'preferred_choices' => ['en', 'de'], - 'disabled' => !$this->security->isGranted('change_user_settings', $entity) + 'disabled' => !$this->security->isGranted('change_user_settings', $entity), ]) ->add('timezone', TimezoneType::class, [ 'required' => false, @@ -136,7 +129,7 @@ class UserAdminForm extends AbstractType 'placeholder' => $this->trans->trans('user_settings.timezone.placeholder'), 'label' => $this->trans->trans('user.timezone.label'), 'preferred_choices' => ['Europe/Berlin'], - 'disabled' => !$this->security->isGranted('change_user_settings', $entity) + 'disabled' => !$this->security->isGranted('change_user_settings', $entity), ]) ->add('theme', ChoiceType::class, [ 'required' => false, @@ -147,12 +140,12 @@ class UserAdminForm extends AbstractType 'attr' => ['class' => 'selectpicker'], 'placeholder' => $this->trans->trans('user_settings.theme.placeholder'), 'label' => $this->trans->trans('user.theme.label'), - 'disabled' => !$this->security->isGranted('change_user_settings', $entity) + 'disabled' => !$this->security->isGranted('change_user_settings', $entity), ]) ->add('currency', CurrencyEntityType::class, [ 'required' => false, 'label' => $this->trans->trans('user.currency.label'), - 'disabled' => !$this->security->isGranted('change_user_settings', $entity) + 'disabled' => !$this->security->isGranted('change_user_settings', $entity), ]) ->add('new_password', RepeatedType::class, [ @@ -166,14 +159,14 @@ class UserAdminForm extends AbstractType 'constraints' => [new Length([ 'min' => 6, 'max' => 128, - ])] + ])], ]) ->add('need_pw_change', CheckboxType::class, [ 'required' => false, 'label_attr' => ['class' => 'checkbox-custom'], 'label' => $this->trans->trans('user.edit.needs_pw_change'), - 'disabled' => !$this->security->isGranted('set_password', $entity) + 'disabled' => !$this->security->isGranted('set_password', $entity), ]) ->add('disabled', CheckboxType::class, [ @@ -181,15 +174,14 @@ class UserAdminForm extends AbstractType 'label_attr' => ['class' => 'checkbox-custom'], 'label' => $this->trans->trans('user.edit.user_disabled'), 'disabled' => !$this->security->isGranted('set_password', $entity) - || $entity === $this->security->getUser() - + || $entity === $this->security->getUser(), ]) //Permission section ->add('permissions', PermissionsType::class, [ 'mapped' => false, 'data' => $builder->getData(), - 'disabled' => !$this->security->isGranted('edit_permissions', $entity) + 'disabled' => !$this->security->isGranted('edit_permissions', $entity), ]) ; /*->add('comment', CKEditorType::class, ['required' => false, @@ -213,11 +205,11 @@ class UserAdminForm extends AbstractType //Buttons $builder->add('save', SubmitType::class, [ - 'label' => $is_new ? $this->trans->trans('user.create') : $this->trans->trans('user.edit.save'), - 'attr' => ['class' => $is_new ? 'btn-success' : ''] + 'label' => $is_new ? $this->trans->trans('user.create') : $this->trans->trans('user.edit.save'), + 'attr' => ['class' => $is_new ? 'btn-success' : ''], ]) ->add('reset', ResetType::class, [ - 'label' => $this->trans->trans('entity.edit.reset') + 'label' => $this->trans->trans('entity.edit.reset'), ]); } @@ -225,4 +217,4 @@ class UserAdminForm extends AbstractType { //Empty for Base } -} \ No newline at end of file +} diff --git a/src/Form/UserSettingsType.php b/src/Form/UserSettingsType.php index eaa6b35d..e6f4dfe0 100644 --- a/src/Form/UserSettingsType.php +++ b/src/Form/UserSettingsType.php @@ -1,6 +1,6 @@ ['class' => 'selectpicker', 'data-live-search' => true], 'placeholder' => $this->trans->trans('user_settings.language.placeholder'), 'label' => $this->trans->trans('user.language_select'), - 'preferred_choices' => ['en', 'de'] + 'preferred_choices' => ['en', 'de'], ]) ->add('timezone', TimezoneType::class, [ 'disabled' => $this->demo_mode, @@ -98,7 +92,7 @@ class UserSettingsType extends AbstractType 'attr' => ['class' => 'selectpicker', 'data-live-search' => true], 'placeholder' => $this->trans->trans('user_settings.timezone.placeholder'), 'label' => $this->trans->trans('user.timezone.label'), - 'preferred_choices' => ['Europe/Berlin'] + 'preferred_choices' => ['Europe/Berlin'], ]) ->add('theme', ChoiceType::class, [ 'disabled' => $this->demo_mode, @@ -114,7 +108,7 @@ class UserSettingsType extends AbstractType ->add('currency', CurrencyEntityType::class, [ 'disabled' => $this->demo_mode, 'required' => false, - 'label' => $this->trans->trans('user.currency.label') + 'label' => $this->trans->trans('user.currency.label'), ]) //Buttons diff --git a/src/Helpers/BBCodeToMarkdownConverter.php b/src/Helpers/BBCodeToMarkdownConverter.php index 5a84ba0e..6841e05d 100644 --- a/src/Helpers/BBCodeToMarkdownConverter.php +++ b/src/Helpers/BBCodeToMarkdownConverter.php @@ -1,6 +1,6 @@ html_to_markdown->convert($html); } -} \ No newline at end of file +} diff --git a/src/Helpers/TreeViewNode.php b/src/Helpers/TreeViewNode.php index 49c055ab..32722bab 100644 --- a/src/Helpers/TreeViewNode.php +++ b/src/Helpers/TreeViewNode.php @@ -1,6 +1,6 @@ text = $text; + return $this; } /** * Returns the href link. + * * @return string|null */ public function getHref(): ?string @@ -85,17 +89,21 @@ class TreeViewNode /** * Sets the href link. + * * @param string|null $href The new href link. + * * @return TreeViewNode */ public function setHref(?string $href): self { $this->href = $href; + return $this; } /** * Returns the children nodes of this node. + * * @return array|null */ public function getNodes(): ?array @@ -105,30 +113,34 @@ class TreeViewNode /** * Sets the children nodes. + * * @param array|null $nodes The new children nodes + * * @return TreeViewNode */ public function setNodes(?array $nodes): self { $this->nodes = $nodes; + return $this; } - public function getState() : ?TreeViewNodeState + public function getState(): ?TreeViewNodeState { return $this->state; } - public function setState(TreeViewNodeState $state) : self + public function setState(TreeViewNodeState $state): self { $this->state = $state; + return $this; } - public function setDisabled(?bool $disabled) : self + public function setDisabled(?bool $disabled): self { //Lazy loading of state, so it does not need to get serialized and transfered, when it is empty. - if ($this->state == null) { + if (null == $this->state) { $this->state = new TreeViewNodeState(); } @@ -137,10 +149,10 @@ class TreeViewNode return $this; } - public function setSelected(?bool $selected) : self + public function setSelected(?bool $selected): self { //Lazy loading of state, so it does not need to get serialized and transfered, when it is empty. - if ($this->state == null) { + if (null == $this->state) { $this->state = new TreeViewNodeState(); } @@ -149,21 +161,20 @@ class TreeViewNode return $this; } - public function getTags() : ?array + public function getTags(): ?array { return $this->tags; } - public function addTag(string $new_tag) : self + public function addTag(string $new_tag): self { //Lazy loading tags - if ($this->tags == null) { - $this->tags = array(); + if (null == $this->tags) { + $this->tags = []; } $this->tags[] = $new_tag; return $this; } - } diff --git a/src/Helpers/TreeViewNodeState.php b/src/Helpers/TreeViewNodeState.php index 5d634ba0..c31907e1 100644 --- a/src/Helpers/TreeViewNodeState.php +++ b/src/Helpers/TreeViewNodeState.php @@ -1,6 +1,6 @@ disabled; } - /** - * @param bool|null $disabled - */ public function setDisabled(?bool $disabled): void { $this->disabled = $disabled; @@ -61,9 +56,6 @@ class TreeViewNodeState return $this->expanded; } - /** - * @param bool|null $expanded - */ public function setExpanded(?bool $expanded): void { $this->expanded = $expanded; @@ -77,13 +69,8 @@ class TreeViewNodeState return $this->selected; } - /** - * @param bool|null $selected - */ public function setSelected(?bool $selected): void { $this->selected = $selected; } - - -} \ No newline at end of file +} diff --git a/src/Helpers/UTCDateTimeType.php b/src/Helpers/UTCDateTimeType.php index d5776740..92074367 100644 --- a/src/Helpers/UTCDateTimeType.php +++ b/src/Helpers/UTCDateTimeType.php @@ -1,6 +1,6 @@ getName(), - $platform->getDateTimeFormatString() - ); + if (!$converted) { + throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString()); } return $converted; } -} \ No newline at end of file +} diff --git a/src/Kernel.php b/src/Kernel.php index f607bccf..4aed333e 100644 --- a/src/Kernel.php +++ b/src/Kernel.php @@ -1,6 +1,6 @@ connection->fetchColumn("SELECT keyValue AS version FROM `internal` WHERE `keyName` = 'dbVersion'"); - $this->skipIf(true, "Old Part-DB Database detected! Continue with upgrade..."); + $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) { //when the table was not found, we can proceed, because we have an empty DB! } - // this up() migration is auto-generated, please modify it to your needs - $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE `attachment_types` (id INT AUTO_INCREMENT NOT NULL, parent_id INT DEFAULT NULL, filetype_filter LONGTEXT NOT NULL, comment LONGTEXT NOT NULL, not_selectable TINYINT(1) NOT NULL, name VARCHAR(255) NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, INDEX IDX_EFAED719727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE `categories` (id INT AUTO_INCREMENT NOT NULL, parent_id INT DEFAULT NULL, partname_hint LONGTEXT NOT NULL, partname_regex LONGTEXT NOT NULL, disable_footprints TINYINT(1) NOT NULL, disable_manufacturers TINYINT(1) NOT NULL, disable_autodatasheets TINYINT(1) NOT NULL, disable_properties TINYINT(1) NOT NULL, default_description LONGTEXT NOT NULL, default_comment LONGTEXT NOT NULL, comment LONGTEXT NOT NULL, not_selectable TINYINT(1) NOT NULL, name VARCHAR(255) NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, INDEX IDX_3AF34668727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); @@ -105,16 +103,16 @@ final class Version1 extends AbstractMigration */ //Create table for user logs: - $sql = $updateSteps[] = "CREATE TABLE `log` ". - "( `id` INT NOT NULL AUTO_INCREMENT , `datetime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP() ,". - " `id_user` INT NOT NULL ,". - " `level` TINYINT NOT NULL ,". - " `type` SMALLINT NOT NULL ,". - " `target_id` INT NOT NULL ,". - " `target_type` SMALLINT NOT NULL ,". - " `extra` MEDIUMTEXT NOT NULL ,". - " PRIMARY KEY (`id`),". - " INDEX (`id_user`)) ENGINE = InnoDB;"; + $sql = $updateSteps[] = 'CREATE TABLE `log` '. + '( `id` INT NOT NULL AUTO_INCREMENT , `datetime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP() ,'. + ' `id_user` INT NOT NULL ,'. + ' `level` TINYINT NOT NULL ,'. + ' `type` SMALLINT NOT NULL ,'. + ' `target_id` INT NOT NULL ,'. + ' `target_type` SMALLINT NOT NULL ,'. + ' `extra` MEDIUMTEXT NOT NULL ,'. + ' PRIMARY KEY (`id`),'. + ' INDEX (`id_user`)) ENGINE = InnoDB;'; $this->addSql($sql); //Create first groups and users: //Add needed groups. @@ -145,7 +143,7 @@ final class Version1 extends AbstractMigration 5461, 5461, 1365, 1365); EOD; $this->addSql($sql); - $admin_pw = "$2y$10$36AnqCBS.YnHlVdM4UQ0oOCV7BjU7NmE0qnAVEex65AyZw1cbcEjq"; + $admin_pw = '$2y$10$36AnqCBS.YnHlVdM4UQ0oOCV7BjU7NmE0qnAVEex65AyZw1cbcEjq'; $sql = <<addSql("UPDATE `groups` SET `perms_labels` = '85' WHERE `groups`.`id` = 1;"); $this->addSql("UPDATE `groups` SET `perms_labels` = '165' WHERE `groups`.`id` = 2;"); $this->addSql("UPDATE `groups` SET `perms_labels` = '85' WHERE `groups`.`id` = 3;"); - } - public function down(Schema $schema) : void + public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs - $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE `attachment_types` DROP FOREIGN KEY FK_EFAED719727ACA70'); $this->addSql('ALTER TABLE `attachments` DROP FOREIGN KEY FK_47C4FAD6C54C8C93'); diff --git a/src/Migrations/Version20190902140506.php b/src/Migrations/Version20190902140506.php index 48ee4574..ac0b6d82 100644 --- a/src/Migrations/Version20190902140506.php +++ b/src/Migrations/Version20190902140506.php @@ -1,6 +1,6 @@ abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); try { //Check if we can use this migration method: - $version = (int)$this->connection->fetchColumn("SELECT keyValue AS version FROM `internal` WHERE `keyName` = 'dbVersion'"); - $this->abortIf($version !== 26, "This database migration can only be used if the database version is 26! Install Part-DB 0.5.6 and update database there!"); + $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) { //when the table was not found, then you can not use this migration - $this->skipIf(true, "Empty database detected. Skip migration."); + $this->skipIf(true, 'Empty database detected. Skip migration.'); } - //Deactive SQL Modes (especially NO_ZERO_DATE, which prevents updating) $this->addSql("SET sql_mode = ''"); @@ -64,17 +62,17 @@ final class Version20190902140506 extends AbstractMigration $this->addSql('CREATE TABLE `measurement_units` (id INT AUTO_INCREMENT NOT NULL, parent_id INT DEFAULT NULL, unit VARCHAR(255) DEFAULT NULL, is_integer TINYINT(1) NOT NULL, use_si_prefix TINYINT(1) NOT NULL, comment LONGTEXT NOT NULL, not_selectable TINYINT(1) NOT NULL, name VARCHAR(255) NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, INDEX IDX_F5AF83CF727ACA70 (parent_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE part_lots (id INT AUTO_INCREMENT NOT NULL, id_store_location INT DEFAULT NULL, id_part INT NOT NULL, description LONGTEXT NOT NULL, comment LONGTEXT NOT NULL, expiration_date DATETIME DEFAULT NULL, instock_unknown TINYINT(1) NOT NULL, amount DOUBLE PRECISION NOT NULL, needs_refill TINYINT(1) NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, datetime_added DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL, INDEX IDX_EBC8F9435D8F4B37 (id_store_location), INDEX IDX_EBC8F943C22F6CC4 (id_part), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); - /** Migrate the part locations for parts with known instock */ + /* Migrate the part locations for parts with known instock */ $this->addSql( - 'INSERT IGNORE INTO part_lots (id_part, id_store_location, amount, instock_unknown, last_modified, datetime_added) ' . - 'SELECT parts.id, parts.id_storelocation, parts.instock, 0, NOW(), NOW() FROM parts ' . + 'INSERT IGNORE INTO part_lots (id_part, id_store_location, amount, instock_unknown, last_modified, datetime_added) '. + 'SELECT parts.id, parts.id_storelocation, parts.instock, 0, NOW(), NOW() FROM parts '. 'WHERE parts.instock >= 0' ); //Migrate part locations for parts with unknown instock $this->addSql( - 'INSERT IGNORE INTO part_lots (id_part, id_store_location, amount, instock_unknown, last_modified, datetime_added) ' . - 'SELECT parts.id, parts.id_storelocation, 0, 1, NOW(), NOW() FROM parts ' . + 'INSERT IGNORE INTO part_lots (id_part, id_store_location, amount, instock_unknown, last_modified, datetime_added) '. + 'SELECT parts.id, parts.id_storelocation, 0, 1, NOW(), NOW() FROM parts '. 'WHERE parts.instock = -2' ); @@ -183,8 +181,8 @@ final class Version20190902140506 extends AbstractMigration $this->addSql('CREATE INDEX IDX_F06D3970727ACA70 ON groups (parent_id)'); //Fill empty timestamps with current date - $tables = ["attachments", "attachment_types", "categories", "devices", "footprints", "manufacturers", - "orderdetails", "pricedetails", "storelocations", "suppliers"]; + $tables = ['attachments', 'attachment_types', 'categories', 'devices', 'footprints', 'manufacturers', + 'orderdetails', 'pricedetails', 'storelocations', 'suppliers', ]; foreach ($tables as $table) { $this->addSql("UPDATE $table SET datetime_added = NOW() WHERE datetime_added = '0000-00-00 00:00:00'"); @@ -195,10 +193,10 @@ final class Version20190902140506 extends AbstractMigration $this->addSql("UPDATE `internal` SET `keyValue` = '99' WHERE `internal`.`keyName` = 'dbVersion'"); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs - $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE currencies DROP FOREIGN KEY FK_37C44693727ACA70'); $this->addSql('ALTER TABLE `suppliers` DROP FOREIGN KEY FK_AC28B95CECD792C0'); diff --git a/src/Migrations/Version20190913141126.php b/src/Migrations/Version20190913141126.php index 8a46692f..82f00fc6 100644 --- a/src/Migrations/Version20190913141126.php +++ b/src/Migrations/Version20190913141126.php @@ -1,6 +1,6 @@ abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE `groups` ADD perms_parts_category SMALLINT NOT NULL, ADD perms_parts_minamount SMALLINT NOT NULL, ADD perms_parts_lots SMALLINT NOT NULL, ADD perms_parts_tags SMALLINT NOT NULL, ADD perms_parts_unit SMALLINT NOT NULL, ADD perms_parts_mass SMALLINT NOT NULL, ADD perms_parts_status SMALLINT NOT NULL, ADD perms_parts_mpn SMALLINT NOT NULL, ADD perms_currencies INT NOT NULL, ADD perms_measurement_units INT NOT NULL, DROP perms_parts_instock, DROP perms_parts_mininstock, DROP perms_parts_storelocation'); $this->addSql('ALTER TABLE users ADD currency_id INT DEFAULT NULL, ADD settings LONGTEXT NOT NULL COMMENT \'(DC2Type:json)\', ADD perms_parts_category SMALLINT NOT NULL, ADD perms_parts_minamount SMALLINT NOT NULL, ADD perms_parts_lots SMALLINT NOT NULL, ADD perms_parts_tags SMALLINT NOT NULL, ADD perms_parts_unit SMALLINT NOT NULL, ADD perms_parts_mass SMALLINT NOT NULL, ADD perms_parts_status SMALLINT NOT NULL, ADD perms_parts_mpn SMALLINT NOT NULL, ADD perms_currencies INT NOT NULL, ADD perms_measurement_units INT NOT NULL, DROP config_currency, DROP perms_parts_instock, DROP perms_parts_mininstock, DROP perms_parts_storelocation'); @@ -70,10 +69,10 @@ final class Version20190913141126 extends AbstractMigration $this->write('[!!!] Permissions were updated! Please check if they fit your expectations!'); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs - $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE `groups` ADD perms_parts_instock SMALLINT NOT NULL, ADD perms_parts_mininstock SMALLINT NOT NULL, ADD perms_parts_storelocation SMALLINT NOT NULL, DROP perms_parts_category, DROP perms_parts_minamount, DROP perms_parts_lots, DROP perms_parts_tags, DROP perms_parts_unit, DROP perms_parts_mass, DROP perms_parts_status, DROP perms_parts_mpn, DROP perms_currencies, DROP perms_measurement_units'); $this->addSql('ALTER TABLE `users` DROP FOREIGN KEY FK_1483A5E938248176'); diff --git a/src/Migrations/Version20190924113252.php b/src/Migrations/Version20190924113252.php index e45d3f92..5f7f1f8e 100644 --- a/src/Migrations/Version20190924113252.php +++ b/src/Migrations/Version20190924113252.php @@ -1,6 +1,6 @@ abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE users ADD id_preview_attachement INT DEFAULT NULL, ADD pw_reset_token VARCHAR(255) DEFAULT NULL, ADD pw_reset_expires DATETIME DEFAULT NULL, ADD disabled TINYINT(1) NOT NULL, DROP config_image_path'); $this->addSql('ALTER TABLE users ADD CONSTRAINT FK_1483A5E96DEDCEC2 FOREIGN KEY (id_preview_attachement) REFERENCES `attachments` (id)'); @@ -70,15 +69,15 @@ final class Version20190924113252 extends AbstractMigration //Add a attachment for each footprint attachment $this->addSql( - 'INSERT IGNORE INTO attachments (element_id, type_id, name, class_name, path, last_modified, datetime_added) ' . - "SELECT footprints.id, 1000, 'Footprint', 'Footprint', REPLACE(footprints.filename, '%BASE%/img/footprints', '%FOOTPRINTS%' ), NOW(), NOW() FROM footprints " . + 'INSERT IGNORE INTO attachments (element_id, type_id, name, class_name, path, last_modified, datetime_added) '. + "SELECT footprints.id, 1000, 'Footprint', 'Footprint', REPLACE(footprints.filename, '%BASE%/img/footprints', '%FOOTPRINTS%' ), NOW(), NOW() FROM footprints ". "WHERE footprints.filename <> ''" ); //Do the same for 3D Footprints $this->addSql( - 'INSERT IGNORE INTO attachments (element_id, type_id, name, class_name, path, last_modified, datetime_added) ' . - "SELECT footprints.id, 1001, 'Footprint 3D', 'Footprint', REPLACE(footprints.filename_3d, '%BASE%/models', '%FOOTPRINTS3D%' ), NOW(), NOW() FROM footprints " . + 'INSERT IGNORE INTO attachments (element_id, type_id, name, class_name, path, last_modified, datetime_added) '. + "SELECT footprints.id, 1001, 'Footprint 3D', 'Footprint', REPLACE(footprints.filename_3d, '%BASE%/models', '%FOOTPRINTS3D%' ), NOW(), NOW() FROM footprints ". "WHERE footprints.filename_3d <> ''" ); @@ -123,10 +122,10 @@ final class Version20190924113252 extends AbstractMigration $this->addSql('CREATE INDEX IDX_6940A7FE6DEDCEC2 ON parts (id_preview_attachement)'); } - public function down(Schema $schema) : void + public function down(Schema $schema): void { // this down() migration is auto-generated, please modify it to your needs - $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); + $this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE `attachment_types` DROP FOREIGN KEY FK_EFAED7196DEDCEC2'); $this->addSql('DROP INDEX IDX_EFAED7196DEDCEC2 ON `attachment_types`'); diff --git a/src/Repository/PartRepository.php b/src/Repository/PartRepository.php index f13d80db..e5a8370d 100644 --- a/src/Repository/PartRepository.php +++ b/src/Repository/PartRepository.php @@ -1,7 +1,7 @@ findBy(['parent' => null], ['name' => 'ASC']); } /** * Gets a flattened hierachical tree. Useful for generating option lists. + * * @param StructuralDBElement|null $parent This entity will be used as root element. Set to null, to use global root + * * @return StructuralDBElement[] A flattened list containing the tree elements. */ public function toNodesList(?StructuralDBElement $parent = null): array { - $result = array(); + $result = []; $entities = $this->findBy(['parent' => $parent], ['name' => 'ASC']); - /** + /* * I think it is very difficult to replace this recursive array_merge, * so if you want to change it you should have a better idea than adding each list to $result array * and do an array_merge(...$result) at the end. */ foreach ($entities as $entity) { - /** @var StructuralDBElement $entity */ + /* @var StructuralDBElement $entity */ $result[] = $entity; $result = array_merge($result, $this->toNodesList($entity)); } return $result; } - -} \ No newline at end of file +} diff --git a/src/Repository/UserRepository.php b/src/Repository/UserRepository.php index 7ee8fe31..f48e036e 100644 --- a/src/Repository/UserRepository.php +++ b/src/Repository/UserRepository.php @@ -1,6 +1,6 @@ findOneBy([ - 'id' => User::ID_ANONYMOUS + 'id' => User::ID_ANONYMOUS, ]); } diff --git a/src/Security/Annotations/ColumnSecurity.php b/src/Security/Annotations/ColumnSecurity.php index b40fd320..381e62a7 100644 --- a/src/Security/Annotations/ColumnSecurity.php +++ b/src/Security/Annotations/ColumnSecurity.php @@ -1,6 +1,6 @@ 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); } $object->setName('???'); } + return $object; } - if (null === $this->placeholder) { switch ($this->type) { case 'integer': @@ -113,6 +112,7 @@ class ColumnSecurity return false; case 'datetime': $date = new \DateTime(); + return $date->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 4e3033b5..ff5b4c70 100644 --- a/src/Security/EntityListeners/ElementPermissionListener.php +++ b/src/Security/EntityListeners/ElementPermissionListener.php @@ -1,6 +1,6 @@ 0) { + if (empty($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['HTTP_USER_AGENT']) && \count($_SERVER['argv']) > 0) { return true; } @@ -163,7 +159,6 @@ class ElementPermissionListener $property->setValue($element, $old_data[$property->getName()]); $changed = true; } - } if ($changed) { diff --git a/src/Security/Interfaces/HasPermissionsInterface.php b/src/Security/Interfaces/HasPermissionsInterface.php index eaf6b322..9e533ca9 100644 --- a/src/Security/Interfaces/HasPermissionsInterface.php +++ b/src/Security/Interfaces/HasPermissionsInterface.php @@ -1,6 +1,6 @@ resolver->listOperationsForPermission('parts_attachments'), false); + return \in_array($attribute, $this->resolver->listOperationsForPermission('parts_attachments'), false); } return false; } -} \ No newline at end of file +} diff --git a/src/Security/Voter/ExtendedVoter.php b/src/Security/Voter/ExtendedVoter.php index 3639acca..63b2efbb 100644 --- a/src/Security/Voter/ExtendedVoter.php +++ b/src/Security/Voter/ExtendedVoter.php @@ -1,6 +1,6 @@ getUser(); //An allowed user is not allowed to do anything... - if($user instanceof User && $user->isDisabled()) { + if ($user instanceof User && $user->isDisabled()) { return false; } @@ -72,9 +71,6 @@ abstract class ExtendedVoter extends Voter * * @param $attribute * @param $subject - * @param User $user - * - * @return bool */ abstract protected function voteOnUser($attribute, $subject, User $user): bool; } diff --git a/src/Security/Voter/GroupVoter.php b/src/Security/Voter/GroupVoter.php index 264537bf..07488940 100644 --- a/src/Security/Voter/GroupVoter.php +++ b/src/Security/Voter/GroupVoter.php @@ -1,6 +1,6 @@ resolver->inherit($user,'groups', $attribute) ?? false; + return $this->resolver->inherit($user, 'groups', $attribute) ?? false; } return false; @@ -52,7 +48,7 @@ class GroupVoter extends ExtendedVoter * Determines if the attribute and subject are supported by this voter. * * @param string $attribute An attribute - * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type + * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type * * @return bool True if the attribute and subject are supported, false otherwise */ @@ -64,4 +60,4 @@ class GroupVoter extends ExtendedVoter return false; } -} \ No newline at end of file +} diff --git a/src/Security/Voter/PartVoter.php b/src/Security/Voter/PartVoter.php index ea339778..47092463 100644 --- a/src/Security/Voter/PartVoter.php +++ b/src/Security/Voter/PartVoter.php @@ -1,6 +1,6 @@ resolver->isValidOperation('parts_' . $perm, $op); + return $this->resolver->isValidOperation('parts_'.$perm, $op); } return $this->resolver->isValidOperation('parts', $attribute); diff --git a/src/Security/Voter/PermissionVoter.php b/src/Security/Voter/PermissionVoter.php index 85c99a78..5ab14cab 100644 --- a/src/Security/Voter/PermissionVoter.php +++ b/src/Security/Voter/PermissionVoter.php @@ -1,6 +1,6 @@ resolver->inherit($user, $perm, $op); } @@ -54,7 +50,7 @@ class PermissionVoter extends ExtendedVoter * Determines if the attribute and subject are supported by this voter. * * @param string $attribute An attribute - * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type + * @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type * * @return bool True if the attribute and subject are supported, false otherwise */ @@ -64,9 +60,10 @@ class PermissionVoter extends ExtendedVoter if (preg_match('/^@\\w+\\.\\w+$/', $attribute)) { $attribute = ltrim($attribute, '@'); [$perm, $op] = explode('.', $attribute); + return $this->resolver->isValidOperation($perm, $op); } return false; } -} \ No newline at end of file +} diff --git a/src/Security/Voter/StructureVoter.php b/src/Security/Voter/StructureVoter.php index 98508de8..34276672 100644 --- a/src/Security/Voter/StructureVoter.php +++ b/src/Security/Voter/StructureVoter.php @@ -1,6 +1,6 @@ instanceToPermissionName($subject); //If permission name is null, then the subject is not supported - return ($permission_name !== null) && $this->resolver->isValidOperation($permission_name, $attribute); + return (null !== $permission_name) && $this->resolver->isValidOperation($permission_name, $attribute); } - } /** * Maps a instance type to the permission name. + * * @param $subject mixed The subject for which the permission name should be generated. + * * @return string|null The name of the permission for the subject's type or null, if the subject is not supported. */ - protected function instanceToPermissionName($subject) : ?string + protected function instanceToPermissionName($subject): ?string { - $class_name = get_class($subject); + $class_name = \get_class($subject); switch ($class_name) { case AttachmentType::class: return 'attachment_types'; @@ -93,7 +91,6 @@ class StructureVoter extends ExtendedVoter * * @param $attribute * @param $subject - * @param User $user * * @return bool */ @@ -103,6 +100,4 @@ class StructureVoter extends ExtendedVoter //Just resolve the permission return $this->resolver->inherit($user, $permission_name, $attribute) ?? false; } - - -} \ No newline at end of file +} diff --git a/src/Security/Voter/UserVoter.php b/src/Security/Voter/UserVoter.php index b3d46f78..698b1186 100644 --- a/src/Security/Voter/UserVoter.php +++ b/src/Security/Voter/UserVoter.php @@ -1,6 +1,6 @@ resolver->listOperationsForPermission('users'), $this->resolver->listOperationsForPermission('self')), false @@ -53,9 +52,6 @@ class UserVoter extends ExtendedVoter * * @param $attribute * @param $subject - * @param User $user - * - * @return bool */ protected function voteOnUser($attribute, $subject, User $user): bool { diff --git a/src/Services/AmountFormatter.php b/src/Services/AmountFormatter.php index feeb30ce..a45952d2 100644 --- a/src/Services/AmountFormatter.php +++ b/src/Services/AmountFormatter.php @@ -1,6 +1,6 @@ setDefaults([ 'show_prefix' => function (Options $options) { - if ($options['measurement_unit'] !== null) { + if (null !== $options['measurement_unit']) { /** @var MeasurementUnit $unit */ $unit = $options['measurement_unit']; + return $unit->isUseSIPrefix(); } + return false; }, 'is_integer' => function (Options $options) { - if ($options['measurement_unit'] !== null) { + if (null !== $options['measurement_unit']) { /** @var MeasurementUnit $unit */ $unit = $options['measurement_unit']; + return $unit->isInteger(); } + return true; }, 'unit' => function (Options $options) { - if ($options['measurement_unit'] !== null) { + if (null !== $options['measurement_unit']) { /** @var MeasurementUnit $unit */ $unit = $options['measurement_unit']; + return $unit->getUnit(); } + return ''; }, 'decimals' => 2, - 'error_mapping' => [ '.' => 'value'] + 'error_mapping' => ['.' => 'value'], ]); $resolver->setAllowedTypes('decimals', 'int'); @@ -78,17 +81,20 @@ class AmountFormatter if ($options['is_integer']) { return 0; } + return $value; }); } /** * Formats the given value using the measurement unit and options. + * * @param $value float|int The value that should be formatted. Must be numeric. * @param MeasurementUnit|null $unit The measurement unit, whose unit symbol should be used for formatting. - * If set to null, it is assumed that the part amount is measured in pieces. - * @param array $options + * If set to null, it is assumed that the part amount is measured in pieces. + * * @return string The formatted string + * * @throws \InvalidArgumentException Thrown if $value is not numeric. */ public function format($value, ?MeasurementUnit $unit = null, array $options = []) @@ -116,10 +122,11 @@ class AmountFormatter //Otherwise just output it if (!empty($options['unit'])) { - $format_string = '%.' . $options['decimals'] . 'f ' . $options['unit']; + $format_string = '%.'.$options['decimals'].'f '.$options['unit']; } else { //Dont add space after number if no unit was specified - $format_string = '%.' . $options['decimals'] . 'f'; + $format_string = '%.'.$options['decimals'].'f'; } + return sprintf($format_string, $value); } -} \ No newline at end of file +} diff --git a/src/Services/Attachments/AttachmentManager.php b/src/Services/Attachments/AttachmentManager.php index 7fe5b02a..52037864 100644 --- a/src/Services/Attachments/AttachmentManager.php +++ b/src/Services/Attachments/AttachmentManager.php @@ -1,6 +1,6 @@ isExternal() || !$this->isFileExisting($attachment)) { return null; @@ -77,7 +59,9 @@ class AttachmentManager /** * Returns the absolute filepath of the attachment. Null is returned, if the attachment is externally saved, * or is not existing. + * * @param Attachment $attachment The attachment for which the filepath should be determined + * * @return string|null */ public function toAbsoluteFilePath(Attachment $attachment): ?string @@ -93,15 +77,16 @@ class AttachmentManager $path = $this->pathResolver->placeholderToRealPath($attachment->getPath()); //realpath does not work with null as argument - if ($path === null) { + if (null === $path) { return null; } $tmp = realpath($path); //If path is not existing realpath returns false. - if ($tmp === false) { + if (false === $tmp) { return null; } + return $tmp; } @@ -127,6 +112,7 @@ class AttachmentManager * For external attachments or not existing attachments, null is returned. * * @param Attachment $attachment The filesize for which the filesize should be calculated. + * * @return int|null */ public function getFileSize(Attachment $attachment): ?int @@ -140,22 +126,23 @@ class AttachmentManager } $tmp = filesize($this->toAbsoluteFilePath($attachment)); - return $tmp !== false ? $tmp : null; + + return false !== $tmp ? $tmp : null; } /** * Returns a human readable version of the attachment file size. * For external attachments, null is returned. * - * @param Attachment $attachment * @param int $decimals The number of decimals numbers that should be printed + * * @return string|null A string like 1.3M */ public function getHumanFileSize(Attachment $attachment, $decimals = 2): ?string { $bytes = $this->getFileSize($attachment); - if ($bytes == null) { + if (null == $bytes) { return null; } @@ -163,7 +150,8 @@ 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); - return sprintf("%.{$decimals}f", $bytes / 1024 ** $factor) . @$sz[$factor]; + $factor = (int) floor((\strlen($bytes) - 1) / 3); + + return sprintf("%.{$decimals}f", $bytes / 1024 ** $factor).@$sz[$factor]; } -} \ No newline at end of file +} diff --git a/src/Services/Attachments/AttachmentPathResolver.php b/src/Services/Attachments/AttachmentPathResolver.php index f82e9016..0882a6e1 100644 --- a/src/Services/Attachments/AttachmentPathResolver.php +++ b/src/Services/Attachments/AttachmentPathResolver.php @@ -1,6 +1,6 @@ pathes as $key => $path) { - if ($path === null) { + if (null === $path) { unset($this->placeholders[$key], $this->pathes[$key]); } } @@ -82,13 +79,16 @@ class AttachmentPathResolver /** * Converts a path passed by parameter from services.yaml (which can be an absolute path or relative to project dir) * to an absolute path. When a relative path is passed, the directory must exist or null is returned. + * * @internal + * * @param string|null $param_path The parameter value that should be converted to a absolute path + * * @return string|null */ - public function parameterToAbsolutePath(?string $param_path) : ?string + public function parameterToAbsolutePath(?string $param_path): ?string { - if ($param_path === null) { + if (null === $param_path) { return null; } @@ -97,17 +97,18 @@ class AttachmentPathResolver if ($fs->isAbsolutePath($param_path)) { $tmp = realpath($param_path); //Disable ressource if path is not existing - if ($tmp === false) { + if (false === $tmp) { return null; } + return $tmp; } //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 ($tmp === false) { + if (false === $tmp) { return null; } @@ -119,38 +120,39 @@ class AttachmentPathResolver * Create an array usable for preg_replace out of an array of placeholders or pathes. * Slashes and other chars become escaped. * For example: '%TEST%' becomes '/^%TEST%/'. - * @param array $array + * * @return array */ - protected function arrayToRegexArray(array $array) : array + protected function arrayToRegexArray(array $array): array { $ret = []; foreach ($array as $item) { $item = str_replace(['\\'], ['/'], $item); - $ret[] = '/' . preg_quote($item, '/') . '/'; + $ret[] = '/'.preg_quote($item, '/').'/'; } return $ret; } - /** * Converts an relative placeholder filepath (with %MEDIA% or older %BASE%) to an absolute filepath on disk. - * The directory separator is always /. Relative pathes are not realy possible (.. is striped) + * The directory separator is always /. Relative pathes are not realy possible (.. is striped). + * * @param string $placeholder_path The filepath with placeholder for which the real path should be determined. + * * @return string|null The absolute real path of the file, or null if the placeholder path is invalid */ - public function placeholderToRealPath(string $placeholder_path) : ?string + public function placeholderToRealPath(string $placeholder_path): ?string { //The new attachments use %MEDIA% as placeholders, which is the directory set in media_directory //Older path entries are given via %BASE% which was the project root $count = 0; - $placeholder_path = preg_replace($this->placeholders_regex, $this->pathes, $placeholder_path,-1,$count); + $placeholder_path = preg_replace($this->placeholders_regex, $this->pathes, $placeholder_path, -1, $count); //A valid placeholder can have only one - if ($count !== 1) { + if (1 !== $count) { return null; } @@ -160,7 +162,7 @@ class AttachmentPathResolver } //Path is invalid if path is directory traversal - if (strpos($placeholder_path, '..') !== false) { + if (false !== strpos($placeholder_path, '..')) { return null; } @@ -172,12 +174,14 @@ class AttachmentPathResolver /** * Converts an real absolute filepath to a placeholder version. - * @param string $real_path The absolute path, for which the placeholder version should be generated. - * @param bool $old_version By default the %MEDIA% placeholder is used, which is directly replaced with the - * media directory. If set to true, the old version with %BASE% will be used, which is the project directory. + * + * @param string $real_path The absolute path, for which the placeholder version should be generated. + * @param bool $old_version By default the %MEDIA% placeholder is used, which is directly replaced with the + * media directory. If set to true, the old version with %BASE% will be used, which is the project directory. + * * @return string The placeholder version of the filepath */ - public function realPathToPlaceholder(string $real_path, bool $old_version = false) : ?string + public function realPathToPlaceholder(string $real_path, bool $old_version = false): ?string { $count = 0; @@ -194,7 +198,7 @@ class AttachmentPathResolver $real_path = preg_replace($this->pathes_regex, $this->placeholders, $real_path, -1, $count); } - if ($count !== 1) { + if (1 !== $count) { return null; } @@ -208,9 +212,10 @@ class AttachmentPathResolver /** * The path where uploaded attachments is stored. + * * @return string The absolute path to the media folder. */ - public function getMediaPath() : string + public function getMediaPath(): string { return $this->media_path; } @@ -218,28 +223,31 @@ class AttachmentPathResolver /** * The path where secured attachments are stored. Must not be located in public/ folder, so it can only be accessed * via the attachment controller. + * * @return string The absolute path to the secure path. */ - public function getSecurePath() : string + public function getSecurePath(): string { return $this->secure_path; } /** - * The string where the builtin footprints are stored + * The string where the builtin footprints are stored. + * * @return string|null The absolute path to the footprints folder. Null if built footprints were disabled. */ - public function getFootprintsPath() : ?string + public function getFootprintsPath(): ?string { return $this->footprints_path; } /** - * The string where the builtin 3D models are stored + * The string where the builtin 3D models are stored. + * * @return string|null The absolute path to the models folder. Null if builtin models were disabled. */ - public function getModelsPath() : ?string + public function getModelsPath(): ?string { return $this->models_path; } -} \ No newline at end of file +} diff --git a/src/Services/Attachments/AttachmentReverseSearch.php b/src/Services/Attachments/AttachmentReverseSearch.php index 509c36d2..9ca18f15 100644 --- a/src/Services/Attachments/AttachmentReverseSearch.php +++ b/src/Services/Attachments/AttachmentReverseSearch.php @@ -1,6 +1,6 @@ pathResolver->realPathToPlaceholder($file->getPathname()); @@ -63,20 +61,22 @@ class AttachmentReverseSearch $relative_path_old = $this->pathResolver->realPathToPlaceholder($file->getPathname(), true); $repo = $this->em->getRepository(Attachment::class); + 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. + * 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. + * * @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; } @@ -86,8 +86,6 @@ class AttachmentReverseSearch $fs = new Filesystem(); $fs->remove($file); - - return true; } -} \ No newline at end of file +} diff --git a/src/Services/Attachments/AttachmentSubmitHandler.php b/src/Services/Attachments/AttachmentSubmitHandler.php index a49f7b2b..b26c0919 100644 --- a/src/Services/Attachments/AttachmentSubmitHandler.php +++ b/src/Services/Attachments/AttachmentSubmitHandler.php @@ -1,6 +1,6 @@ pathResolver = $pathResolver; @@ -77,10 +68,10 @@ class AttachmentSubmitHandler 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']; + SupplierAttachment::class => 'supplier', UserAttachment::class => 'user', ]; } - protected function configureOptions(OptionsResolver $resolver) : void + protected function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ //If no preview image was set yet, the new uploaded file will become the preview image @@ -94,11 +85,13 @@ class AttachmentSubmitHandler /** * Generates a filename for the given attachment and extension. * The filename contains a random id, so every time this function is called you get an unique name. + * * @param Attachment $attachment The attachment that should be used for generating an attachment - * @param string $extension The extension that the new file should have (must only contain chars allowed in pathes) + * @param string $extension The extension that the new file should have (must only contain chars allowed in pathes) + * * @return string The new filename. */ - public function generateAttachmentFilename(Attachment $attachment, string $extension) : string + public function generateAttachmentFilename(Attachment $attachment, string $extension): string { //Normalize extension $extension = transliterator_transliterate( @@ -112,16 +105,18 @@ class AttachmentSubmitHandler $attachment->getName() ); - return $safeName . '-' . uniqid('', false) . '.' . $extension; + return $safeName.'-'.uniqid('', false).'.'.$extension; } /** * Generates an (absolute) path to a folder where the given attachment should be stored. - * @param Attachment $attachment The attachment that should be used for - * @param bool $secure_upload True if the file path should be located in a safe location + * + * @param Attachment $attachment The attachment that should be used for + * @param bool $secure_upload True if the file path should be located in a safe location + * * @return string The absolute path for the attachment folder. */ - public function generateAttachmentPath(Attachment $attachment, bool $secure_upload = false) : string + public function generateAttachmentPath(Attachment $attachment, bool $secure_upload = false): string { if ($secure_upload) { $base_path = $this->pathResolver->getSecurePath(); @@ -130,34 +125,32 @@ 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 ($attachment->getElement() === null) { - throw new \InvalidArgumentException( - 'The given attachment is not assigned to an element! An element is needed to generate a path!' - ); + if (null === $attachment->getElement()) { + 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(); } /** * Handle the submit of an attachment form. * This function will move the uploaded file or download the URL file to server, if needed. - * @param Attachment $attachment The attachment that should be used for handling. - * @param UploadedFile|null $file If given, that file will be moved to the right location - * @param array $options The options to use with the upload. Here you can specify that an URL should be downloaded, - * or an file should be moved to a secure location. + * + * @param Attachment $attachment The attachment that should be used for handling. + * @param UploadedFile|null $file If given, that file will be moved to the right location + * @param array $options The options to use with the upload. Here you can specify that an URL should be downloaded, + * or an file should be moved to a secure location. + * * @return Attachment The attachment with the new filename (same instance as passed $attachment) */ - public function handleFormSubmit(Attachment $attachment, ?UploadedFile $file, array $options = []) : Attachment + public function handleFormSubmit(Attachment $attachment, ?UploadedFile $file, array $options = []): Attachment { $resolver = new OptionsResolver(); $this->configureOptions($resolver); @@ -175,9 +168,9 @@ class AttachmentSubmitHandler //Check if we should assign this attachment to master picture //this is only possible if the attachment is new (not yet persisted to DB) - if ($options['become_preview_if_empty'] && $attachment->getID() === null && $attachment->isPicture()) { + if ($options['become_preview_if_empty'] && null === $attachment->getID() && $attachment->isPicture()) { $element = $attachment->getElement(); - if ($element instanceof AttachmentContainingDBElement && $element->getMasterPictureAttachment() === null) { + if ($element instanceof AttachmentContainingDBElement && null === $element->getMasterPictureAttachment()) { $element->setMasterPictureAttachment($attachment); } } @@ -187,11 +180,13 @@ class AttachmentSubmitHandler /** * Move the given attachment to secure location (or back to public folder) if needed. - * @param Attachment $attachment The attachment for which the file should be moved. - * @param bool $secure_location This value determines, if the attachment is moved to the secure or public folder. + * + * @param Attachment $attachment The attachment for which the file should be moved. + * @param bool $secure_location This value determines, if the attachment is moved to the secure or public folder. + * * @return Attachment The attachment with the updated filepath */ - protected function moveFile(Attachment $attachment, bool $secure_location) : Attachment + protected function moveFile(Attachment $attachment, bool $secure_location): Attachment { //We can not do anything on builtins or external ressources if ($attachment->isBuiltIn() || $attachment->isExternal()) { @@ -218,7 +213,7 @@ class AttachmentSubmitHandler $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(); @@ -232,12 +227,13 @@ class AttachmentSubmitHandler } /** - * Download the URL set in the attachment and save it on the server - * @param Attachment $attachment + * Download the URL set in the attachment and save it on the server. + * * @param array $options The options from the handleFormSubmit function + * * @return Attachment The attachment with the new filepath */ - protected function downloadURL(Attachment $attachment, array $options) : Attachment + protected function downloadURL(Attachment $attachment, array $options): Attachment { //Check if we are allowed to download files if (!$this->allow_attachments_downloads) { @@ -248,7 +244,7 @@ class AttachmentSubmitHandler $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, [ @@ -256,7 +252,7 @@ class AttachmentSubmitHandler ]); if (200 !== $response->getStatusCode()) { - throw new AttachmentDownloadException('Status code: ' . $response->getStatusCode()); + throw new AttachmentDownloadException('Status code: '.$response->getStatusCode()); } //Open a temporary file in the attachment folder @@ -271,7 +267,7 @@ class AttachmentSubmitHandler //File download should be finished here, so determine the new filename and extension $headers = $response->getHeaders(); //Try to determine an filename - $filename = ""; + $filename = ''; //If an content disposition header was set try to extract the filename out of it if (isset($headers['content-disposition'])) { @@ -281,7 +277,7 @@ class AttachmentSubmitHandler } //If we dont know filename yet, try to determine it out of url - if ($filename === "") { + if ('' === $filename) { $filename = basename(parse_url($url, PHP_URL_PATH)); } @@ -297,14 +293,13 @@ 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) { throw new AttachmentDownloadException('Transport error!'); } @@ -313,13 +308,15 @@ class AttachmentSubmitHandler } /** - * Moves the given uploaded file to a permanent place and saves it into the attachment - * @param Attachment $attachment The attachment in which the file should be saved - * @param UploadedFile $file The file which was uploaded - * @param array $options The options from the handleFormSubmit function + * Moves the given uploaded file to a permanent place and saves it into the attachment. + * + * @param Attachment $attachment The attachment in which the file should be saved + * @param UploadedFile $file The file which was uploaded + * @param array $options The options from the handleFormSubmit function + * * @return Attachment The attachment with the new filepath */ - protected function upload(Attachment $attachment, UploadedFile $file, array $options) : Attachment + protected function upload(Attachment $attachment, UploadedFile $file, array $options): Attachment { //Move our temporay attachment to its final location $file_path = $file->move( @@ -336,4 +333,4 @@ class AttachmentSubmitHandler return $attachment; } -} \ No newline at end of file +} diff --git a/src/Services/Attachments/AttachmentURLGenerator.php b/src/Services/Attachments/AttachmentURLGenerator.php index c597ebfc..bfbaeb1f 100644 --- a/src/Services/Attachments/AttachmentURLGenerator.php +++ b/src/Services/Attachments/AttachmentURLGenerator.php @@ -1,6 +1,6 @@ attachmentHelper = $attachmentHelper; $this->filterService = $filterService; - //Determine a normalized path to the public folder (assets are relative to this folder) $this->public_path = $this->pathResolver->parameterToAbsolutePath('public'); } @@ -57,46 +52,46 @@ class AttachmentURLGenerator /** * Converts the absolute file path to a version relative to the public folder, that can be passed to asset * Asset Component functions. - * @param string $absolute_path The absolute path that should be converted. - * @param string|null $public_path The public path to which the relative pathes should be created. - * The path must NOT have a trailing slash! - * If this is set to null, the global public/ folder is used. + * + * @param string $absolute_path The absolute path that should be converted. + * @param string|null $public_path The public path to which the relative pathes should be created. + * The path must NOT have a trailing slash! + * If this is set to null, the global public/ folder is used. + * * @return string|null The relative version of the string. Null if the absolute path was not a child folder - * of public path + * of public path */ - public function absolutePathToAssetPath(string $absolute_path, ?string $public_path = null) : ?string + public function absolutePathToAssetPath(string $absolute_path, ?string $public_path = null): ?string { - if ($public_path === null) { + if (null === $public_path) { $public_path = $this->public_path; } //Our absolute path must begin with public path or we can not use it for asset pathes. - if (strpos($absolute_path, $public_path) !== 0) { + if (0 !== strpos($absolute_path, $public_path)) { return null; } //Return the part relative after public path. - return substr($absolute_path, strlen($public_path) + 1); + return substr($absolute_path, \strlen($public_path) + 1); } /** * Returns a URL under which the attachment file can be viewed. - * @param Attachment $attachment + * * @return string */ - public function getViewURL(Attachment $attachment) : string + public function getViewURL(Attachment $attachment): string { $absolute_path = $this->attachmentHelper->toAbsoluteFilePath($attachment); - if ($absolute_path === null) { - 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!' - ); + 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! + Use Attachment::getURL() to get the external URL!'); } $asset_path = $this->absolutePathToAssetPath($absolute_path); //If path is not relative to public path or marked as secure, serve it via controller - if ($asset_path === null || $attachment->isSecure()) { + if (null === $asset_path || $attachment->isSecure()) { return $this->urlGenerator->generate('attachment_view', ['id' => $attachment->getID()]); } @@ -106,11 +101,10 @@ class AttachmentURLGenerator /** * Returns a URL to an thumbnail of the attachment file. - * @param Attachment $attachment - * @param string $filter_name + * * @return string */ - public function getThumbnailURL(Attachment $attachment, string $filter_name = 'thumbnail_sm') : string + public function getThumbnailURL(Attachment $attachment, string $filter_name = 'thumbnail_sm'): string { if (!$attachment->isPicture()) { throw new \InvalidArgumentException('Thumbnail creation only works for picture attachments!'); @@ -121,21 +115,19 @@ class AttachmentURLGenerator } $absolute_path = $this->attachmentHelper->toAbsoluteFilePath($attachment); - if ($absolute_path === null) { - throw new \RuntimeException( - 'The given attachment is external or has no valid file, so no URL can get generated for it!' - ); + 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!'); } $asset_path = $this->absolutePathToAssetPath($absolute_path); //If path is not relative to public path or marked as secure, serve it via controller - if ($asset_path === null || $attachment->isSecure()) { + if (null === $asset_path || $attachment->isSecure()) { return $this->urlGenerator->generate('attachment_view', ['id' => $attachment->getID()]); } //For builtin ressources it is not useful to create a thumbnail //because the footprints images are small and highly optimized already. - if ($filter_name === 'thumbnail_md' && $attachment->isBuiltIn()) { + if ('thumbnail_md' === $filter_name && $attachment->isBuiltIn()) { return $this->assets->getUrl($asset_path); } @@ -144,13 +136,13 @@ class AttachmentURLGenerator } /** - * Returns a download link to the file associated with the attachment - * @param Attachment $attachment + * Returns a download link to the file associated with the attachment. + * * @return string */ - public function getDownloadURL(Attachment $attachment) : string + public function getDownloadURL(Attachment $attachment): string { //Redirect always to download controller, which sets the correct headers for downloading: return $this->urlGenerator->generate('attachment_download', ['id' => $attachment->getID()]); } -} \ No newline at end of file +} diff --git a/src/Services/Attachments/BuiltinAttachmentsFinder.php b/src/Services/Attachments/BuiltinAttachmentsFinder.php index 3d23f6b8..929ce858 100644 --- a/src/Services/Attachments/BuiltinAttachmentsFinder.php +++ b/src/Services/Attachments/BuiltinAttachmentsFinder.php @@ -1,6 +1,6 @@ 15, //Given only 15 entries //'allowed_extensions' => [], //Filter the filenames. For example ['jpg', 'jpeg'] to only get jpegs. //'placeholders' => Attachment::BUILTIN_PLACEHOLDER, //By default use all builtin ressources, - 'empty_returns_all' => false //Return the whole list of ressources when empty keyword is given + 'empty_returns_all' => false, //Return the whole list of ressources when empty keyword is given ]); } @@ -58,9 +54,10 @@ class BuiltinAttachmentsFinder * Returns a list of all builtin ressources. * The array is a list of the relative filenames using the %PLACEHOLDERS%. * The list contains the files from all configured valid ressoureces. + * * @return array The list of the ressources, or an empty array if an error happened. */ - public function getListOfRessources() : array + public function getListOfRessources(): array { try { return $this->cache->get('attachment_builtin_ressources', function () { @@ -73,7 +70,7 @@ class BuiltinAttachmentsFinder foreach (Attachment::BUILTIN_PLACEHOLDER as $placeholder) { $tmp = $this->pathResolver->placeholderToRealPath($placeholder); //Ignore invalid/deactivated placeholders: - if ($tmp !== null) { + if (null !== $tmp) { $finder->in($tmp); } } @@ -93,13 +90,15 @@ class BuiltinAttachmentsFinder } /** - * Find all ressources which are matching the given keyword and the specified options - * @param string $keyword The keyword you want to search for. - * @param array $options Here you can specify some options (see configureOptions for list of options) + * Find all ressources which are matching the given keyword and the specified options. + * + * @param string $keyword The keyword you want to search for. + * @param array $options Here you can specify some options (see configureOptions for list of options) * @param array|null $base_list The list from which should be used as base for filtering. + * * @return array The list of the results matching the specified keyword and options */ - public function find(string $keyword, array $options = [], ?array $base_list = []) : array + public function find(string $keyword, array $options = [], ?array $base_list = []): array { if (empty($base_list)) { $base_list = $this->getListOfRessources(); @@ -109,14 +108,12 @@ class BuiltinAttachmentsFinder $this->configureOptions($resolver); $options = $resolver->resolve($options); - - /* if (empty($options['placeholders'])) { return []; } */ - if ($keyword === '') { + if ('' === $keyword) { if ($options['empty_returns_all']) { $keyword = '.*'; } else { @@ -127,7 +124,7 @@ class BuiltinAttachmentsFinder $keyword = preg_quote($keyword, '/'); } - /*TODO: Implement placheolder and extension filter */ + /*TODO: Implement placheolder and extension filter */ /* if (!empty($options['allowed_extensions'])) { $keyword .= "\.("; foreach ($options['allowed_extensions'] as $extension) { @@ -137,9 +134,8 @@ class BuiltinAttachmentsFinder } */ //Ignore case - $regex = '/.*' . $keyword . '.*/i'; + $regex = '/.*'.$keyword.'.*/i'; return preg_grep($regex, $base_list); } - -} \ No newline at end of file +} diff --git a/src/Services/Attachments/FileTypeFilterTools.php b/src/Services/Attachments/FileTypeFilterTools.php index b009f276..e0b90df3 100644 --- a/src/Services/Attachments/FileTypeFilterTools.php +++ b/src/Services/Attachments/FileTypeFilterTools.php @@ -1,6 +1,6 @@ accept uses. * See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Unique_file_type_specifiers for * more details. - * @package App\Services\Attachments */ class FileTypeFilterTools { - //The file extensions that will be used for the 'video/*', 'image/*', 'audio/*' placeholders //These file formats can be directly played in common browesers //Source: https://www.chromium.org/audio-video @@ -53,17 +50,18 @@ class FileTypeFilterTools $this->cache = $cache; } - /** * Check if a filetype filter string is valid. + * * @param string $filter The filter string that should be validated. + * * @return bool Returns true, if the string is valid. */ - public function validateFilterString(string $filter) : bool + public function validateFilterString(string $filter): bool { $filter = trim($filter); //An empty filter is valid (means no filter applied) - if ($filter === '') { + if ('' === $filter) { return true; } @@ -73,7 +71,7 @@ class FileTypeFilterTools $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 + && !\in_array($element, static::ALLOWED_MIME_PLACEHOLDERS, false)) { //image/* is allowed return false; } } @@ -85,10 +83,12 @@ class FileTypeFilterTools /** * Normalize a filter string. All extensions are converted to lowercase, too much whitespaces are removed. * The filter string is not validated. + * * @param string $filter The filter string that should be normalized. + * * @return string The normalized filter string */ - public function normalizeFilterString(string $filter) : string + public function normalizeFilterString(string $filter): string { $filter = trim($filter); //Replace other separators, with , so we can split it properly @@ -101,75 +101,80 @@ class FileTypeFilterTools foreach ($elements as $key => &$element) { $element = trim($element); //Remove empty elements - if ($element === '') { + if ('' === $element) { unset($elements[$key]); } //Convert *.jpg to .jpg - if (strpos($element, '*.') === 0) { + if (0 === strpos($element, '*.')) { $element = str_replace('*.', '.', $element); } //Convert image to image/* - if ($element === 'image' || $element === 'image/') { + if ('image' === $element || 'image/' === $element) { $element = 'image/*'; - } elseif ($element === 'video' || $element === 'video/') { + } elseif ('video' === $element || 'video/' === $element) { $element = 'video/*'; - } elseif ($element === 'audio' || $element === 'audio/') { + } elseif ('audio' === $element || 'audio/' === $element) { $element = 'audio/*'; - } elseif (!preg_match('/^[-\w.]+\/[-\w.*]+/', $element) && strpos($element, '.') !== 0) { + } elseif (!preg_match('/^[-\w.]+\/[-\w.*]+/', $element) && 0 !== strpos($element, '.')) { //Convert jpg to .jpg - $element = '.' . $element; + $element = '.'.$element; } - } $elements = array_unique($elements); - return implode($elements, ','); + return implode(',', $elements); } /** - * Get a list of all file extensions that matches the given filter string + * Get a list of all file extensions that matches the given filter string. + * * @param string $filter A valid filetype filter string. + * * @return string[] An array of allowed extensions ['txt', 'csv', 'gif'] */ - public function resolveFileExtensions(string $filter) : array + public function resolveFileExtensions(string $filter): array { $filter = trim($filter); - return $this->cache->get('filter_exts_' . md5($filter), function (ItemInterface $item) use ($filter) { + return $this->cache->get('filter_exts_'.md5($filter), function (ItemInterface $item) use ($filter) { $elements = explode(',', $filter); $extensions = []; foreach ($elements as $element) { $element = trim($element); - if (strpos($element, '.') === 0) { + if (0 === strpos($element, '.')) { //We found an explicit specified file extension -> add it to list $extensions[] = substr($element, 1); - } elseif ($element === 'image/*') { + } elseif ('image/*' === $element) { $extensions = array_merge($extensions, static::IMAGE_EXTS); - } elseif ($element === 'audio/*') { + } elseif ('audio/*' === $element) { $extensions = array_merge($extensions, static::AUDIO_EXTS); - } elseif ($element === 'image/*') { + } elseif ('image/*' === $element) { $extensions = array_merge($extensions, static::VIDEO_EXTS); } elseif (preg_match('/^[-\w.]+\/[-\w.*]+/', $element)) { $extensions = array_merge($extensions, $this->mimeTypes->getExtensions($element)); } } + return array_unique($extensions); }); } /** * Check if the given extension matches the filter. - * @param string $filter The filter which should be used for checking. + * + * @param string $filter The filter which should be used for checking. * @param string $extension The extension that should be checked. + * * @return bool Returns true, if the extension is allowed with the given filter. */ - public function isExtensionAllowed(string $filter, string $extension) : bool + public function isExtensionAllowed(string $filter, string $extension): bool { $extension = strtolower($extension); - return empty($filter) || in_array($extension, $this->resolveFileExtensions($filter), false); + + return empty($filter) || \in_array($extension, $this->resolveFileExtensions($filter), false); } -} \ No newline at end of file +} diff --git a/src/Services/Attachments/PartPreviewGenerator.php b/src/Services/Attachments/PartPreviewGenerator.php index a9f036c8..286d467d 100644 --- a/src/Services/Attachments/PartPreviewGenerator.php +++ b/src/Services/Attachments/PartPreviewGenerator.php @@ -1,6 +1,6 @@ Footprint MasterAttachment -> Category MasterAttachment - * -> Storelocation Attachment -> MeasurementUnit Attachment -> ManufacturerAttachment + * -> Storelocation Attachment -> MeasurementUnit Attachment -> ManufacturerAttachment. + * * @param Part $part The part for which the attachments should be determined. + * * @return Attachment[] */ - public function getPreviewAttachments(Part $part) : array + public function getPreviewAttachments(Part $part): array { $list = []; @@ -56,14 +52,14 @@ class PartPreviewGenerator $list[] = $attachment; } - if ($part->getFootprint() !== null) { + if (null !== $part->getFootprint()) { $attachment = $part->getFootprint()->getMasterPictureAttachment(); if ($this->isAttachmentValidPicture($attachment)) { $list[] = $attachment; } } - if ($part->getCategory() !== null) { + if (null !== $part->getCategory()) { $attachment = $part->getCategory()->getMasterPictureAttachment(); if ($this->isAttachmentValidPicture($attachment)) { $list[] = $attachment; @@ -71,7 +67,7 @@ class PartPreviewGenerator } foreach ($part->getPartLots() as $lot) { - if ($lot->getStorageLocation() !== null) { + if (null !== $lot->getStorageLocation()) { $attachment = $lot->getStorageLocation()->getMasterPictureAttachment(); if ($this->isAttachmentValidPicture($attachment)) { $list[] = $attachment; @@ -79,14 +75,14 @@ class PartPreviewGenerator } } - if ($part->getPartUnit() !== null) { + if (null !== $part->getPartUnit()) { $attachment = $part->getPartUnit()->getMasterPictureAttachment(); if ($this->isAttachmentValidPicture($attachment)) { $list[] = $attachment; } } - if ($part->getManufacturer() !== null) { + if (null !== $part->getManufacturer()) { $attachment = $part->getManufacturer()->getMasterPictureAttachment(); if ($this->isAttachmentValidPicture($attachment)) { $list[] = $attachment; @@ -99,10 +95,12 @@ class PartPreviewGenerator /** * Determines what attachment should be used for previewing a part (especially in part table). * The returned attachment is guaranteed to be existing and be a picture. + * * @param Part $part The part for which the attachment should be determined + * * @return Attachment|null */ - public function getTablePreviewAttachment(Part $part) : ?Attachment + public function getTablePreviewAttachment(Part $part): ?Attachment { //First of all we check if the master attachment of the part is set (and a picture) $attachment = $part->getMasterPictureAttachment(); @@ -111,7 +109,7 @@ class PartPreviewGenerator } //Otherwise check if the part has a footprint with a valid masterattachment - if ($part->getFootprint() !== null) { + if (null !== $part->getFootprint()) { $attachment = $part->getFootprint()->getMasterPictureAttachment(); if ($this->isAttachmentValidPicture($attachment)) { return $attachment; @@ -124,13 +122,15 @@ class PartPreviewGenerator /** * Checks if a attachment is exising and a valid picture. + * * @param Attachment|null $attachment The attachment that should be checked. + * * @return bool True if the attachment is valid. */ - protected function isAttachmentValidPicture(?Attachment $attachment) : bool + protected function isAttachmentValidPicture(?Attachment $attachment): bool { - return $attachment !== null + return null !== $attachment && $attachment->isPicture() && $this->attachmentHelper->isFileExisting($attachment); } -} \ No newline at end of file +} diff --git a/src/Services/ElementTypeNameGenerator.php b/src/Services/ElementTypeNameGenerator.php index 22949605..fba29366 100644 --- a/src/Services/ElementTypeNameGenerator.php +++ b/src/Services/ElementTypeNameGenerator.php @@ -1,6 +1,6 @@ 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) @@ -99,25 +99,26 @@ 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))); } /** * Returns a string like in the format ElementType: ElementName. * For example this could be something like: "Part: BC547". * It uses getLocalizedLabel to determine the type. - * @param NamedDBElement $entity The entity for which the string should be generated. - * @param bool $use_html If set to true, a html string is returned, where the type is set italic + * + * @param NamedDBElement $entity The entity for which the string should be generated. + * @param bool $use_html If set to true, a html string is returned, where the type is set italic + * * @return string The localized string */ - public function getTypeNameCombination(NamedDBElement $entity, bool $use_html = false) : string + public function getTypeNameCombination(NamedDBElement $entity, bool $use_html = false): string { $type = $this->getLocalizedTypeLabel($entity); if ($use_html) { - return '' . $type . ': ' . $entity->getName(); + return ''.$type.': '.$entity->getName(); } - return $type . ": " . htmlspecialchars($entity->getName()); + + return $type.': '.htmlspecialchars($entity->getName()); } -} \ No newline at end of file +} diff --git a/src/Services/EntityExporter.php b/src/Services/EntityExporter.php index 4211c077..56ea0e91 100644 --- a/src/Services/EntityExporter.php +++ b/src/Services/EntityExporter.php @@ -1,6 +1,6 @@ get('format') ?? "json"; + $format = $request->get('format') ?? 'json'; //Check if we have one of the supported formats - if (!in_array($format, ['json', 'csv', 'yaml', 'xml'])) { - throw new \InvalidArgumentException("Given format is not supported!"); + if (!\in_array($format, ['json', 'csv', 'yaml', 'xml'])) { + throw new \InvalidArgumentException('Given format is not supported!'); } //Check export verbosity level $level = $request->get('level') ?? 'extended'; - if (!in_array($level, ['simple', 'extended', 'full'])) { + if (!\in_array($level, ['simple', 'extended', 'full'])) { throw new \InvalidArgumentException('Given level is not supported!'); } @@ -69,26 +68,26 @@ class EntityExporter $include_children = $request->get('include_children') ?? false; //Check which groups we need to export, based on level and include_children - $groups = array($level); + $groups = [$level]; if ($include_children) { $groups[] = 'include_children'; } //Plain text should work for all types - $content_type = "text/plain"; + $content_type = 'text/plain'; //Try to use better content types based on the format switch ($format) { case 'xml': - $content_type = "application/xml"; + $content_type = 'application/xml'; break; case 'json': - $content_type = "application/json"; + $content_type = 'application/json'; break; } //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]; @@ -99,7 +98,7 @@ class EntityExporter 'groups' => $groups, 'as_collection' => true, 'csv_delimiter' => ';', //Better for Excel - 'xml_root_node_name' => 'PartDBExport' + 'xml_root_node_name' => 'PartDBExport', ])); $response->headers->set('Content-Type', $content_type); @@ -108,7 +107,7 @@ 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!'); } @@ -120,8 +119,7 @@ class EntityExporter throw new \InvalidArgumentException('$entity type is not supported!'); } - - $filename = "export_" . $entity_name . "_" . $level . "." . $format; + $filename = 'export_'.$entity_name.'_'.$level.'.'.$format; // Create the disposition of the file $disposition = $response->headers->makeDisposition( @@ -134,4 +132,4 @@ class EntityExporter return $response; } -} \ No newline at end of file +} diff --git a/src/Services/EntityImporter.php b/src/Services/EntityImporter.php index 1dd2c084..a12b958a 100644 --- a/src/Services/EntityImporter.php +++ b/src/Services/EntityImporter.php @@ -1,6 +1,6 @@ 'json', 'preserve_children' => true, 'parent' => null, - 'abort_on_validation_error' => true + 'abort_on_validation_error' => true, ]); } /** * Creates many entries at once, based on a (text) list of names. * - * @param string $lines The list of names seperated by \n - * @param string $class_name The name of the class for which the entities should be created - * @param StructuralDBElement|null $parent The element which will be used as parent element for new elements. + * @param string $lines The list of names seperated by \n + * @param string $class_name The name of the class for which the entities should be created + * @param StructuralDBElement|null $parent The element which will be used as parent element for new elements. + * * @return array An associative array containing an ConstraintViolationList and the entity name as key are returned, - * if an error happened during validation. When everything was successfull, the array should be empty. + * if an error happened during validation. When everything was successfull, the array should be empty. */ - public function massCreation(string $lines, string $class_name, ?StructuralDBElement $parent) : array + public function massCreation(string $lines, string $class_name, ?StructuralDBElement $parent): array { //Expand every line to a single entry: $names = explode("\n", $lines); - $errors = array(); + $errors = []; foreach ($names as $name) { $name = trim($name); @@ -84,7 +80,7 @@ class EntityImporter //Validate entity $tmp = $this->validator->validate($entity); //If no error occured, write entry to DB: - if (count($tmp) === 0) { + if (0 === \count($tmp)) { $this->em->persist($entity); } else { //Otherwise log error dump($tmp); @@ -101,27 +97,28 @@ class EntityImporter /** * This methods deserializes the given file and saves it database. * The imported elements will be checked (validated) before written to database. - * @param File $file The file that should be used for importing. + * + * @param File $file The file that should be used for importing. * @param string $class_name The class name of the enitity that should be imported. - * @param array $options Options for the import process. + * @param array $options Options for the import process. + * * @return array An associative array containing an ConstraintViolationList and the entity name as key are returned, - * if an error happened during validation. When everything was successfull, the array should be empty. + * if an error happened during validation. When everything was successfull, the array should be empty. */ - public function fileToDBEntities(File $file, string $class_name, array $options = []) : array + public function fileToDBEntities(File $file, string $class_name, array $options = []): array { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $options = $resolver->resolve($options); - $entities = $this->fileToEntityArray($file, $class_name, $options); - $errors = array(); + $errors = []; //Iterate over each $entity write it to DB. foreach ($entities as $entity) { - /** @var StructuralDBElement $entity */ + /* @var StructuralDBElement $entity */ //Move every imported entity to the selected parent $entity->setParent($options['parent']); @@ -129,7 +126,7 @@ class EntityImporter $tmp = $this->validator->validate($entity); //When no validation error occured, persist entity to database (cascade must be set in entity) - if (count($errors) === 0) { + if (0 === \count($errors)) { $this->em->persist($entity); } else { //Log validation errors to global log. $errors[$entity->getFullPath()] = $tmp; @@ -137,7 +134,7 @@ class EntityImporter } //Save changes to database, when no error happened, or we should continue on error. - if (empty($errors) || $options['abort_on_validation_error'] == false) { + if (empty($errors) || false == $options['abort_on_validation_error']) { $this->em->flush(); } @@ -148,12 +145,14 @@ class EntityImporter * This method converts (deserialize) a (uploaded) file to an array of entities with the given class. * * The imported elements will NOT be validated. If you want to use the result array, you have to validate it by yourself. - * @param File $file The file that should be used for importing. + * + * @param File $file The file that should be used for importing. * @param string $class_name The class name of the enitity that should be imported. - * @param array $options Options for the import process. + * @param array $options Options for the import process. + * * @return array An array containing the deserialized elements. */ - public function fileToEntityArray(File $file, string $class_name, array $options = []) : array + public function fileToEntityArray(File $file, string $class_name, array $options = []): array { $resolver = new OptionsResolver(); $this->configureOptions($resolver); @@ -170,11 +169,11 @@ class EntityImporter } //The [] behind class_name denotes that we expect an array. - $entities = $this->serializer->deserialize($content, $class_name . '[]', $options['format'], + $entities = $this->serializer->deserialize($content, $class_name.'[]', $options['format'], ['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]; } @@ -188,16 +187,17 @@ class EntityImporter /** * This functions corrects the parent setting based on the children value of the parent. + * * @param iterable $entities The list of entities that should be fixed. - * @param null $parent The parent, to which the entity should be set. + * @param null $parent The parent, to which the entity should be set. */ protected function correctParentEntites(iterable $entities, $parent = null) { foreach ($entities as $entity) { - /** @var $entity StructuralDBElement */ + /* @var $entity StructuralDBElement */ $entity->setParent($parent); //Do the same for the children of entity $this->correctParentEntites($entity->getChildren(), $entity); } } -} \ No newline at end of file +} diff --git a/src/Services/EntityURLGenerator.php b/src/Services/EntityURLGenerator.php index e4535220..ddc1299c 100644 --- a/src/Services/EntityURLGenerator.php +++ b/src/Services/EntityURLGenerator.php @@ -1,6 +1,6 @@ $value) { if (is_a($entity, $key)) { @@ -83,10 +82,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]; @@ -99,9 +95,11 @@ class EntityURLGenerator * * @param $entity mixed The element for which the page should be generated. * @param string $type The page type. Currently supported: 'info', 'edit', 'create', 'clone', 'list'/'list_parts' + * * @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) { @@ -148,21 +146,21 @@ class EntityURLGenerator if ($entity->isExternal()) { //For external attachments, return the link to external path return $entity->getURL(); } + return $this->attachmentURLGenerator->getDownloadURL($entity); } //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))); } /** * Generates an URL to a page, where info about this entity can be viewed. * * @param $entity mixed The entity for which the info should be generated. + * * @return string The URL to the info page + * * @throws EntityNotSupportedException If the method is not supported for the given Entity */ public function infoURL(DBElement $entity): string @@ -181,7 +179,7 @@ class EntityURLGenerator User::class => 'user_edit', Currency::class => 'currency_edit', MeasurementUnit::class => 'measurement_unit_edit', - Group::class => 'group_edit' + Group::class => 'group_edit', ]; return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]); @@ -191,7 +189,9 @@ class EntityURLGenerator * Generates an URL to a page, where this entity can be edited. * * @param $entity mixed The entity for which the edit link should be generated. + * * @return string The URL to the edit page. + * * @throws EntityNotSupportedException If the method is not supported for the given Entity */ public function editURL($entity): string @@ -208,7 +208,7 @@ class EntityURLGenerator User::class => 'user_edit', Currency::class => 'currency_edit', MeasurementUnit::class => 'measurement_unit_edit', - Group::class => 'group_edit' + Group::class => 'group_edit', ]; return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]); @@ -218,7 +218,9 @@ class EntityURLGenerator * Generates an URL to a page, where a entity of this type can be created. * * @param $entity mixed The entity for which the link should be generated. + * * @return string The URL to the page. + * * @throws EntityNotSupportedException If the method is not supported for the given Entity */ public function createURL($entity): string @@ -235,7 +237,7 @@ class EntityURLGenerator User::class => 'user_new', Currency::class => 'currency_new', MeasurementUnit::class => 'measurement_unit_new', - Group::class => 'group_new' + Group::class => 'group_new', ]; return $this->urlGenerator->generate($this->mapToController($map, $entity)); @@ -243,16 +245,18 @@ class EntityURLGenerator /** * Generates an URL to a page, where a new entity can be created, that has the same informations as the - * given entity (element cloning) + * given entity (element cloning). * * @param $entity mixed The entity for which the link should be generated. + * * @return string The URL to the page. + * * @throws EntityNotSupportedException If the method is not supported for the given Entity */ public function cloneURL(DBElement $entity): string { $map = [ - Part::class => 'part_clone' + Part::class => 'part_clone', ]; return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]); @@ -262,7 +266,9 @@ class EntityURLGenerator * Generates an URL to a page, where all parts are listed, which are contained in the given element. * * @param $entity mixed The entity for which the link should be generated. + * * @return string The URL to the page. + * * @throws EntityNotSupportedException If the method is not supported for the given Entity */ public function listPartsURL(DBElement $entity): string @@ -272,7 +278,7 @@ class EntityURLGenerator Footprint::class => 'part_list_footprint', Manufacturer::class => 'part_list_manufacturer', Supplier::class => 'part_list_supplier', - Storelocation::class => 'part_list_store_location' + Storelocation::class => 'part_list_store_location', ]; return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]); @@ -292,7 +298,7 @@ class EntityURLGenerator User::class => 'user_delete', Currency::class => 'currency_delete', MeasurementUnit::class => 'measurement_unit_delete', - Group::class => 'group_delete' + Group::class => 'group_delete', ]; return $this->urlGenerator->generate($this->mapToController($map, $entity), ['id' => $entity->getID()]); diff --git a/src/Services/GitVersionInfo.php b/src/Services/GitVersionInfo.php index 08000a19..ddc0a0c5 100644 --- a/src/Services/GitVersionInfo.php +++ b/src/Services/GitVersionInfo.php @@ -1,6 +1,6 @@ project_dir . '/.git/HEAD')) { - $git = file($this->project_dir . '/.git/HEAD'); + if (file_exists($this->project_dir.'/.git/HEAD')) { + $git = file($this->project_dir.'/.git/HEAD'); $head = explode('/', $git[0], 3); + return trim($head[2]); } + return null; // this is not a Git installation } /** - * Get hash of the last git commit (on remote "origin"!) + * Get hash of the last git commit (on remote "origin"!). + * * @note If this method does not work, try to make a "git pull" first! - * @param integer $length if this is smaller than 40, only the first $length characters will be returned - * @return string|null The hash of the last commit, null If this is no Git installation + * + * @param int $length if this is smaller than 40, only the first $length characters will be returned + * + * @return string|null The hash of the last commit, null If this is no Git installation */ public function getGitCommitHash(int $length = 7) { - $filename = $this->project_dir . '/.git/refs/remotes/origin/' . $this->getGitBranchName(); + $filename = $this->project_dir.'/.git/refs/remotes/origin/'.$this->getGitBranchName(); if (file_exists($filename)) { $head = file($filename); $hash = $head[0]; + return substr($hash, 0, $length); } + return null; // this is not a Git installation } -} \ No newline at end of file +} diff --git a/src/Services/MarkdownParser.php b/src/Services/MarkdownParser.php index c683a58f..ec05621e 100644 --- a/src/Services/MarkdownParser.php +++ b/src/Services/MarkdownParser.php @@ -1,6 +1,6 @@ %s', @@ -52,4 +52,4 @@ class MarkdownParser $this->translator->trans('markdown.loading') ); } -} \ No newline at end of file +} diff --git a/src/Services/MoneyFormatter.php b/src/Services/MoneyFormatter.php index 01c4188e..62f5040d 100644 --- a/src/Services/MoneyFormatter.php +++ b/src/Services/MoneyFormatter.php @@ -1,6 +1,6 @@ base_currency; - if ($currency !== null && !empty($currency->getIsoCode())) { + if (null !== $currency && !empty($currency->getIsoCode())) { $iso_code = $currency->getIsoCode(); } @@ -62,5 +61,4 @@ class MoneyFormatter return $number_formatter->formatCurrency((float) $value, $iso_code); } - -} \ No newline at end of file +} diff --git a/src/Services/PermissionResolver.php b/src/Services/PermissionResolver.php index c591ab2c..e047d630 100644 --- a/src/Services/PermissionResolver.php +++ b/src/Services/PermissionResolver.php @@ -1,6 +1,6 @@ cache_file = $cache_dir.'/permissions.php.cache'; $this->is_debug = $container->getParameter('kernel.debug'); - - $this->permission_structure = $this->generatePermissionStructure(); //dump($this->permission_structure); } - public function getPermissionStructure() : array + public function getPermissionStructure(): array { return $this->permission_structure; } protected function generatePermissionStructure() { - $cache = new ConfigCache($this->cache_file, $this->is_debug); //Check if the cache is fresh, else regenerate it. @@ -88,7 +82,7 @@ class PermissionResolver ); //Permission file is our file resource (it is used to invalidate cache) - $resources = array(); + $resources = []; $resources[] = new FileResource($permission_file); //Var export the structure and write it to cache file. @@ -101,7 +95,6 @@ class PermissionResolver return require $this->cache_file; } - /** * Check if a user/group is allowed to do the specified operation for the permission. * @@ -165,13 +158,14 @@ class PermissionResolver } /** - * Sets the new value for the operation - * @param HasPermissionsInterface $user The user or group for which the value should be changed. - * @param string $permission The name of the permission that should be changed. - * @param string $operation The name of the operation that should be changed. - * @param bool|null $new_val The new value for the permission. true = ALLOW, false = DISALLOW, null = INHERIT + * Sets the new value for the operation. + * + * @param HasPermissionsInterface $user The user or group for which the value should be changed. + * @param string $permission The name of the permission that should be changed. + * @param string $operation The name of the operation that should be changed. + * @param bool|null $new_val The new value for the permission. true = ALLOW, false = DISALLOW, null = INHERIT */ - public function setPermission(HasPermissionsInterface $user, string $permission, string $operation, ?bool $new_val) : void + public function setPermission(HasPermissionsInterface $user, string $permission, string $operation, ?bool $new_val): void { //Get the permissions from the user $perm_list = $user->getPermissions(); @@ -195,12 +189,11 @@ class PermissionResolver */ public function listOperationsForPermission(string $permission): array { - if(!$this->isValidPermission($permission)) { + if (!$this->isValidPermission($permission)) { throw new \InvalidArgumentException(sprintf('A permission with that name is not existing! Got %s.', $permission)); } $operations = $this->permission_structure['perms'][$permission]['operations']; - return array_keys($operations); } diff --git a/src/Services/PricedetailHelper.php b/src/Services/PricedetailHelper.php index a9374a33..c617c400 100644 --- a/src/Services/PricedetailHelper.php +++ b/src/Services/PricedetailHelper.php @@ -1,6 +1,6 @@ getOrderdetails(true); @@ -55,7 +53,7 @@ class PricedetailHelper foreach ($orderdetails as $orderdetail) { $pricedetails = $orderdetail->getPricedetails(); //The orderdetail must have pricedetails, otherwise this will not work! - if (count($pricedetails) === 0) { + if (0 === \count($pricedetails)) { continue; } @@ -74,7 +72,6 @@ class PricedetailHelper $max_amount = end($array); } - if ($max_amount > $max) { $max = $max_amount; } @@ -88,11 +85,13 @@ class PricedetailHelper } /** - * Determines the minimum amount of the part that can be ordered + * Determines the minimum amount of the part that can be ordered. + * * @param Part $part The part for which the minimum order amount should be determined. + * * @return float */ - public function getMinOrderAmount(Part $part) : ?float + public function getMinOrderAmount(Part $part): ?float { $orderdetails = $part->getOrderdetails(true); @@ -101,7 +100,7 @@ class PricedetailHelper foreach ($orderdetails as $orderdetail) { $pricedetails = $orderdetail->getPricedetails(); //The orderdetail must have pricedetails, otherwise this will not work! - if (count($pricedetails) === 0) { + if (0 === \count($pricedetails)) { continue; } @@ -123,26 +122,28 @@ class PricedetailHelper /** * Calculates the average price of a part, when ordering the amount $amount. - * @param Part $part The part for which the average price should be calculated. - * @param float $amount The order amount for which the average price should be calculated. - * If set to null, the mininmum order amount for the part is used. + * + * @param Part $part The part for which the average price should be calculated. + * @param float $amount The order amount for which the average price should be calculated. + * If set to null, the mininmum order amount for the part is used. * @param Currency|null $currency The currency in which the average price should be calculated + * * @return string|null The Average price as bcmath string. Returns null, if it was not possible to calculate the - * price for the given + * price for the given */ - public function calculateAvgPrice(Part $part, ?float $amount = null, ?Currency $currency = null) : ?string + public function calculateAvgPrice(Part $part, ?float $amount = null, ?Currency $currency = null): ?string { - if ($amount === null) { + if (null === $amount) { $amount = $this->getMinOrderAmount($part); } - if ($amount === null) { + if (null === $amount) { return null; } $orderdetails = $part->getOrderdetails(true); - $avg = "0"; + $avg = '0'; $count = 0; //Find the price for the amount, for the given @@ -150,15 +151,15 @@ class PricedetailHelper $pricedetail = $orderdetail->findPriceForQty($amount); //When we dont have informations about this amount, ignore it - if ($pricedetail === null) { + if (null === $pricedetail) { continue; } $avg = bcadd($avg, $this->convertMoneyToCurrency($pricedetail->getPricePerUnit(), $pricedetail->getCurrency(), $currency), Pricedetail::PRICE_PRECISION); - $count++; + ++$count; } - if ($count === 0) { + if (0 === $count) { return null; } @@ -166,16 +167,18 @@ class PricedetailHelper } /** - * Converts the given value in origin currency to the choosen target currency + * Converts the given value in origin currency to the choosen target currency. + * * @param $value float|string The value that should be converted * @param Currency|null $originCurrency The currency the $value is given in. - * Set to null, to use global base currency. + * Set to null, to use global base currency. * @param Currency|null $targetCurrency The target currency, to which $value should be converted. - * Set to null, to use global base currency. + * Set to null, to use global base currency. + * * @return string|null The value in $targetCurrency given as bcmath string. - * Returns null, if it was not possible to convert between both values (e.g. when the exchange rates are missing) + * Returns null, if it was not possible to convert between both values (e.g. when the exchange rates are missing) */ - public function convertMoneyToCurrency($value, ?Currency $originCurrency = null, ?Currency $targetCurrency = null) : ?string + public function convertMoneyToCurrency($value, ?Currency $originCurrency = null, ?Currency $targetCurrency = null): ?string { //Skip conversion, if both currencies are same if ($originCurrency === $targetCurrency) { @@ -186,9 +189,9 @@ class PricedetailHelper //Convert value to base currency $val_base = $value; - if ($originCurrency !== null) { + if (null !== $originCurrency) { //Without an exchange rate we can not calculate the exchange rate - if ((float) $originCurrency->getExchangeRate() === 0) { + if (0 === (float) $originCurrency->getExchangeRate()) { return null; } @@ -197,9 +200,9 @@ class PricedetailHelper //Convert value in base currency to target currency $val_target = $val_base; - if ($targetCurrency !== null) { + if (null !== $targetCurrency) { //Without an exchange rate we can not calculate the exchange rate - if ($targetCurrency->getExchangeRate() === null) { + if (null === $targetCurrency->getExchangeRate()) { return null; } @@ -208,4 +211,4 @@ class PricedetailHelper return $val_target; } -} \ No newline at end of file +} diff --git a/src/Services/SIFormatter.php b/src/Services/SIFormatter.php index e4977043..7322c6dc 100644 --- a/src/Services/SIFormatter.php +++ b/src/Services/SIFormatter.php @@ -1,6 +1,6 @@ = 0) { $nearest = (int) floor(abs($magnitude) / 3); @@ -65,43 +67,42 @@ class SIFormatter } /** - * - * @param float $value * @return array */ - public function convertValue(float $value) : array + public function convertValue(float $value): array { //Choose the prefix to use $tmp = $this->getPrefixByMagnitude($this->getMagnitude($value)); - $ret = array( + $ret = [ 'value' => $value / $tmp[0], 'prefix_magnitude' => log10($tmp[0]), - 'prefix' => $tmp[1] - ); + 'prefix' => $tmp[1], + ]; return $ret; } /** - * Formats the given value to a string, using the given options - * @param float $value The value that should be converted - * @param string $unit The unit that should be appended after the prefix - * @param int $decimals The number of decimals (after decimal dot) that should be outputed. + * Formats the given value to a string, using the given options. + * + * @param float $value The value that should be converted + * @param string $unit The unit that should be appended after the prefix + * @param int $decimals The number of decimals (after decimal dot) that should be outputed. + * * @return string */ - public function format(float $value, string $unit = '', int $decimals = 2) : string + public function format(float $value, string $unit = '', int $decimals = 2): string { [$divisor, $symbol] = $this->getPrefixByMagnitude($this->getMagnitude($value)); $value /= $divisor; //Build the format string, e.g.: %.2d km - if ($unit !== '' || $symbol !== '') { - $format_string = '%.' . $decimals . 'f ' . $symbol . $unit; + if ('' !== $unit || '' !== $symbol) { + $format_string = '%.'.$decimals.'f '.$symbol.$unit; } else { - $format_string = '%.' . $decimals . 'f'; + $format_string = '%.'.$decimals.'f'; } return sprintf($format_string, $value); } - -} \ No newline at end of file +} diff --git a/src/Services/StructuralElementRecursionHelper.php b/src/Services/StructuralElementRecursionHelper.php index f5f4436d..209b7cd9 100644 --- a/src/Services/StructuralElementRecursionHelper.php +++ b/src/Services/StructuralElementRecursionHelper.php @@ -1,6 +1,6 @@ em; - $this->execute($element, static function(StructuralDBElement $element) use ($em) { + $this->execute($element, static function (StructuralDBElement $element) use ($em) { $em->remove($element); }); - if($flush) { + if ($flush) { $em->flush(); } } -} \ No newline at end of file +} diff --git a/src/Services/TagFinder.php b/src/Services/TagFinder.php index 8098e1b2..1b0b1615 100644 --- a/src/Services/TagFinder.php +++ b/src/Services/TagFinder.php @@ -1,6 +1,6 @@ setDefaults([ 'query_limit' => 75, 'return_limit' => 25, - 'min_keyword_length' => 3 + 'min_keyword_length' => 3, ]); } /** * Search tags that begins with the certain keyword. + * * @param string $keyword The keyword the tag must begin with - * @param array $options Some options specifying the search behavior. See configureOptions for possible options. + * @param array $options Some options specifying the search behavior. See configureOptions for possible options. + * * @return string[] An array containing the tags that match the given keyword. */ public function searchTags(string $keyword, array $options = []) { $results = []; - $keyword_regex = '/^' . preg_quote($keyword, '/') . '/'; + $keyword_regex = '/^'.preg_quote($keyword, '/').'/'; $resolver = new OptionsResolver(); $this->configureOptions($resolver); @@ -75,10 +74,10 @@ class TagFinder $qb->select('p.tags') ->from(Part::class, 'p') - ->where("p.tags LIKE ?1") + ->where('p.tags LIKE ?1') ->setMaxResults($options['query_limit']) //->orderBy('RAND()') - ->setParameter(1, '%' . $keyword . '%'); + ->setParameter(1, '%'.$keyword.'%'); $possible_tags = $qb->getQuery()->getArrayResult(); @@ -90,6 +89,6 @@ class TagFinder $results = array_unique($results); //Limit the returned tag count to specified value. - return array_slice($results, 0, $options['return_limit']); + return \array_slice($results, 0, $options['return_limit']); } -} \ No newline at end of file +} diff --git a/src/Services/ToolsTreeBuilder.php b/src/Services/ToolsTreeBuilder.php index 0a98e2fc..b882c330 100644 --- a/src/Services/ToolsTreeBuilder.php +++ b/src/Services/ToolsTreeBuilder.php @@ -1,6 +1,6 @@ keyGenerator->generateKey(); + $key = 'tree_tools_'.$this->keyGenerator->generateKey(); return $this->cache->get($key, function (ItemInterface $item) { //Invalidate tree, whenever group or the user changes - $item->tag(["tree_tools", "groups", $this->keyGenerator->generateKey()]); + $item->tag(['tree_tools', 'groups', $this->keyGenerator->generateKey()]); - $tree = array(); + $tree = []; $tree[] = new TreeViewNode($this->translator->trans('tree.tools.edit'), null, $this->getEditNodes()); $tree[] = new TreeViewNode($this->translator->trans('tree.tools.show'), null, $this->getShowNodes()); $tree[] = new TreeViewNode($this->translator->trans('tree.tools.system'), null, $this->getSystemNodes()); + return $tree; }); } /** - * This functions creates a tree entries for the "edit" node of the tool's tree + * This functions creates a tree entries for the "edit" node of the tool's tree. + * * @return TreeViewNode[] */ - protected function getEditNodes() : array + protected function getEditNodes(): array { - $nodes = array(); + $nodes = []; if ($this->security->isGranted('read', new AttachmentType())) { $nodes[] = new TreeViewNode( @@ -164,12 +164,13 @@ class ToolsTreeBuilder } /** - * This function creates the tree entries for the "show" node of the tools tree + * This function creates the tree entries for the "show" node of the tools tree. + * * @return TreeViewNode[] */ - protected function getShowNodes() : array + protected function getShowNodes(): array { - $show_nodes = array(); + $show_nodes = []; $show_nodes[] = new TreeViewNode( $this->translator->trans('tree.tools.show.all_parts'), $this->urlGenerator->generate('parts_show_all') @@ -187,16 +188,17 @@ class ToolsTreeBuilder /** * This function creates the tree entries for the "system" node of the tools tree. + * * @return array */ - protected function getSystemNodes() : array + protected function getSystemNodes(): array { - $nodes = array(); + $nodes = []; if ($this->security->isGranted('read', new User())) { $nodes[] = new TreeViewNode( $this->translator->trans('tree.tools.system.users'), - $this->urlGenerator->generate("user_new") + $this->urlGenerator->generate('user_new') ); } if ($this->security->isGranted('read', new Group())) { diff --git a/src/Services/TranslationExtractor/PermissionExtractor.php b/src/Services/TranslationExtractor/PermissionExtractor.php index de733446..8abecab5 100644 --- a/src/Services/TranslationExtractor/PermissionExtractor.php +++ b/src/Services/TranslationExtractor/PermissionExtractor.php @@ -1,6 +1,6 @@ permission_structure['groups'] as $group) { if (isset($group['label'])) { $catalogue->add([ - $group['label'] => '__' . $group['label'] + $group['label'] => '__'.$group['label'], ]); } } @@ -64,7 +61,7 @@ class PermissionExtractor implements ExtractorInterface foreach ($this->permission_structure['perms'] as $perm) { if (isset($perm['label'])) { $catalogue->add([ - $perm['label'] => '__' . $perm['label'] + $perm['label'] => '__'.$perm['label'], ]); } @@ -72,13 +69,12 @@ class PermissionExtractor implements ExtractorInterface foreach ($perm['operations'] as $op) { if (isset($op['label'])) { $catalogue->add([ - $op['label'] => '__' . $op['label'] + $op['label'] => '__'.$op['label'], ]); } } } - $this->finished = true; } } @@ -92,4 +88,4 @@ class PermissionExtractor implements ExtractorInterface { return ''; } -} \ No newline at end of file +} diff --git a/src/Services/TreeBuilder.php b/src/Services/TreeBuilder.php index 3ba76956..d12a49c7 100644 --- a/src/Services/TreeBuilder.php +++ b/src/Services/TreeBuilder.php @@ -1,6 +1,6 @@ __toString(), $href, $children_nodes); - if($children_nodes != null) { - $tree_node->addTag((string) count($children_nodes)); + if (null != $children_nodes) { + $tree_node->addTag((string) \count($children_nodes)); } //Check if we need to select the current part - if ($selectedElement !== null && $element->getID() === $selectedElement->getID()) { + if (null !== $selectedElement && $element->getID() === $selectedElement->getID()) { $tree_node->setSelected(true); } @@ -106,20 +98,23 @@ class TreeBuilder } /** - * Generates a tree for all elements of the given type - * @param StructuralDBElement $class_name The class name of the StructuralDBElement class for which the tree should - * be generated. - * @param string $href_type The type of the links that should be used for the links. Set to null, to disable links. - * See EntityURLGenerator::getURL for possible types. - * @param DBElement|null $selectedElement When a element is given here, its tree node will be marked as selected in - * the resulting tree. When $selectedElement is not existing in the tree, then nothing happens. + * Generates a tree for all elements of the given type. + * + * @param StructuralDBElement $class_name The class name of the StructuralDBElement class for which the tree should + * be generated. + * @param string $href_type The type of the links that should be used for the links. Set to null, to disable links. + * See EntityURLGenerator::getURL for possible types. + * @param DBElement|null $selectedElement When a element is given here, its tree node will be marked as selected in + * the resulting tree. When $selectedElement is not existing in the tree, then nothing happens. + * * @return TreeViewNode[] Returns an array, containing all nodes. It is empty if the given class has no elements. + * * @throws \App\Exceptions\EntityNotSupportedException */ - public function typeToTree(string $class_name, ?string $href_type = 'list_parts', DBElement $selectedElement = null) : array + public function typeToTree(string $class_name, ?string $href_type = 'list_parts', DBElement $selectedElement = null): array { /** - * @var $repo StructuralDBElementRepository + * @var StructuralDBElementRepository */ $repo = $this->em->getRepository($class_name); @@ -129,15 +124,15 @@ class TreeBuilder $root_nodes = $repo->findAll(); } - $array = array(); + $array = []; //When we use the newEdit type, add the New Element node. - if ($href_type === 'newEdit') { + if ('newEdit' === $href_type) { //Generate the url for the new node $href = $this->url_generator->createURL(new $class_name()); $new_node = new TreeViewNode($this->translator->trans('entity.tree.new'), $href); //When the id of the selected element is null, then we have a new element, and we need to select "new" node - if ($selectedElement != null && $selectedElement->getID() == null) { + if (null != $selectedElement && null == $selectedElement->getID()) { $new_node->setSelected(true); } $array[] = $new_node; @@ -145,7 +140,7 @@ class TreeBuilder $array[] = (new TreeViewNode(''))->setDisabled(true); //Every other treeNode will be used for edit - $href_type = "edit"; + $href_type = 'edit'; } foreach ($root_nodes as $node) { @@ -158,22 +153,24 @@ class TreeBuilder /** * Gets a flattened hierachical tree. Useful for generating option lists. * In difference to the Repository Function, the results here are cached. - * @param string $class_name The class name of the entity you want to retrieve. - * @param StructuralDBElement|null $parent This entity will be used as root element. Set to null, to use global root + * + * @param string $class_name The class name of the entity you want to retrieve. + * @param StructuralDBElement|null $parent This entity will be used as root element. Set to null, to use global root + * * @return StructuralDBElement[] A flattened list containing the tree elements. */ public function typeToNodesList(string $class_name, ?StructuralDBElement $parent = null): array { - $parent_id = $parent != null ? $parent->getID() : "0"; + $parent_id = null != $parent ? $parent->getID() : '0'; // Backslashes are not allowed in cache keys - $secure_class_name = str_replace("\\", '_', $class_name); - $key = "list_" . $this->keyGenerator->generateKey() . "_" . $secure_class_name . $parent_id; + $secure_class_name = str_replace('\\', '_', $class_name); + $key = 'list_'.$this->keyGenerator->generateKey().'_'.$secure_class_name.$parent_id; $ret = $this->cache->get($key, function (ItemInterface $item) use ($class_name, $parent, $secure_class_name) { // Invalidate when groups, a element with the class or the user changes $item->tag(['groups', 'tree_list', $this->keyGenerator->generateKey(), $secure_class_name]); /** - * @var $repo StructuralDBElementRepository + * @var StructuralDBElementRepository */ $repo = $this->em->getRepository($class_name); diff --git a/src/Services/UserCacheKeyGenerator.php b/src/Services/UserCacheKeyGenerator.php index 7b884cda..7f7fa4e4 100644 --- a/src/Services/UserCacheKeyGenerator.php +++ b/src/Services/UserCacheKeyGenerator.php @@ -1,6 +1,6 @@ security->getUser(); } //If the user is null, then treat it as anonymous user. //When the anonymous user is passed as user then use this path too. - if ($user === null || $user->getID() === User::ID_ANONYMOUS) { - return 'user$_' . User::ID_ANONYMOUS; + if (null === $user || User::ID_ANONYMOUS === $user->getID()) { + return 'user$_'.User::ID_ANONYMOUS; } //In the most cases we can just use the username (its unique) - return "user_" . $user->getUsername() . '_' . $locale; + return 'user_'.$user->getUsername().'_'.$locale; } -} \ No newline at end of file +} diff --git a/src/Twig/AppExtension.php b/src/Twig/AppExtension.php index 1f938a96..8023f067 100644 --- a/src/Twig/AppExtension.php +++ b/src/Twig/AppExtension.php @@ -1,6 +1,6 @@ attachmentURLGenerator, 'getThumbnailURL']) + new TwigFunction('attachment_thumbnail', [$this->attachmentURLGenerator, 'getThumbnailURL']), ]; } - public function treeData(DBElement $element, string $type = 'newEdit') : string + public function treeData(DBElement $element, string $type = 'newEdit'): string { - $tree = $this->treeBuilder->typeToTree(get_class($element), $type, $element); + $tree = $this->treeBuilder->typeToTree(\get_class($element), $type, $element); + return $this->serializer->serialize($tree, 'json', ['skip_null_values' => true]); } /** - * This function/filter generates an path - * @param string $path + * This function/filter generates an path. + * * @return string */ - public function loginPath(string $path) : string + public function loginPath(string $path): string { - $parts = explode("/" ,$path); + $parts = explode('/', $path); //Remove the part with unset($parts[1]); - return implode("/", $parts); + + return implode('/', $parts); } public function generateEntityURL(DBElement $entity, string $method = 'info'): string diff --git a/src/Validator/Constraints/AllowedFileExtension.php b/src/Validator/Constraints/AllowedFileExtension.php index fbccaf31..f28084b7 100644 --- a/src/Validator/Constraints/AllowedFileExtension.php +++ b/src/Validator/Constraints/AllowedFileExtension.php @@ -1,6 +1,6 @@ getAttachmentType(); //Only validate if the attachment type has specified an filetype filter: - if ($attachment_type === null || empty($attachment_type->getFiletypeFilter())) { + if (null === $attachment_type || empty($attachment_type->getFiletypeFilter())) { return; } @@ -76,7 +73,6 @@ class AllowedFileExtensionValidator extends ConstraintValidator )) { $this->context->buildViolation('validator.file_ext_not_allowed')->addViolation(); } - } } -} \ No newline at end of file +} diff --git a/src/Validator/Constraints/NoLockout.php b/src/Validator/Constraints/NoLockout.php index b41968cf..33cb9ba5 100644 --- a/src/Validator/Constraints/NoLockout.php +++ b/src/Validator/Constraints/NoLockout.php @@ -1,6 +1,6 @@ security->getUser(); - if ($user === null) { + if (null === $user) { $user = $this->entityManager->getRepository(User::class)->getAnonymousUser(); } if ($user instanceof User) { //Check if we the change_permission permission has changed from allow to disallow - if (($this->resolver->inherit($user, 'users', 'edit_permissions') ?? false) === false) { + if (false === ($this->resolver->inherit($user, 'users', 'edit_permissions') ?? false)) { $this->context->addViolation($constraint->message); } } } } -} \ No newline at end of file +} diff --git a/src/Validator/Constraints/NoneOfItsChildren.php b/src/Validator/Constraints/NoneOfItsChildren.php index e222b3e4..1631b4e0 100644 --- a/src/Validator/Constraints/NoneOfItsChildren.php +++ b/src/Validator/Constraints/NoneOfItsChildren.php @@ -1,6 +1,6 @@ getID(); - if ($entity_id !== null && $entity_id === $value->getID()) { + if (null !== $entity_id && $entity_id === $value->getID()) { //Set the entity to a valid state $entity->setParent(null); $this->context->buildViolation($constraint->self_message)->addViolation(); @@ -80,7 +75,8 @@ class NoneOfItsChildrenValidator extends ConstraintValidator //Set the entity to a valid state $entity->setParent(null); $this->context->buildViolation($constraint->children_message)->addViolation(); + return; } } -} \ No newline at end of file +} diff --git a/src/Validator/Constraints/Selectable.php b/src/Validator/Constraints/Selectable.php index 92d600ea..9b41aea0 100644 --- a/src/Validator/Constraints/Selectable.php +++ b/src/Validator/Constraints/Selectable.php @@ -1,6 +1,6 @@ addViolation(); } } -} \ No newline at end of file +} diff --git a/src/Validator/Constraints/UrlOrBuiltin.php b/src/Validator/Constraints/UrlOrBuiltin.php index 308149b1..84f55107 100644 --- a/src/Validator/Constraints/UrlOrBuiltin.php +++ b/src/Validator/Constraints/UrlOrBuiltin.php @@ -1,6 +1,6 @@ allowed_placeholders, false)) { + if (!empty($tmp) && \in_array($tmp[0], $constraint->allowed_placeholders, false)) { return; } parent::validate($value, $constraint); // TODO: Change the autogenerated stub } - - -} \ No newline at end of file +} diff --git a/src/Validator/Constraints/ValidFileFilter.php b/src/Validator/Constraints/ValidFileFilter.php index 7b1aa026..01525376 100644 --- a/src/Validator/Constraints/ValidFileFilter.php +++ b/src/Validator/Constraints/ValidFileFilter.php @@ -1,6 +1,6 @@ addViolation(); } } -} \ No newline at end of file +} diff --git a/src/Validator/Constraints/ValidPartLot.php b/src/Validator/Constraints/ValidPartLot.php index a6b35328..a6003c3d 100644 --- a/src/Validator/Constraints/ValidPartLot.php +++ b/src/Validator/Constraints/ValidPartLot.php @@ -1,6 +1,6 @@ getStorageLocation()->isLimitToExistingParts()) { if (!$parts->contains($value->getPart())) { @@ -95,4 +91,4 @@ class ValidPartLotValidator extends ConstraintValidator } } } -} \ No newline at end of file +} diff --git a/src/Validator/Constraints/ValidPermission.php b/src/Validator/Constraints/ValidPermission.php index 235005dc..16556433 100644 --- a/src/Validator/Constraints/ValidPermission.php +++ b/src/Validator/Constraints/ValidPermission.php @@ -1,6 +1,6 @@ perm_structure['perms'] as $perm_key => $permission) { foreach ($permission['operations'] as $op_key => $op) { if (!empty($op['alsoSet']) && - $this->resolver->dontInherit($perm_holder, $perm_key, $op_key) === true) { + true === $this->resolver->dontInherit($perm_holder, $perm_key, $op_key)) { //Set every op listed in also Set foreach ($op['alsoSet'] as $set_also) { $this->resolver->setPermission($perm_holder, $perm_key, $set_also, true); @@ -71,4 +66,4 @@ class ValidPermissionValidator extends ConstraintValidator } } } -} \ No newline at end of file +} diff --git a/tests/Controller/AdminPages/AbstractAdminControllerTest.php b/tests/Controller/AdminPages/AbstractAdminControllerTest.php index f25535b7..0f19f804 100644 --- a/tests/Controller/AdminPages/AbstractAdminControllerTest.php +++ b/tests/Controller/AdminPages/AbstractAdminControllerTest.php @@ -1,6 +1,6 @@ $user, - 'PHP_AUTH_PW' => 'test', + 'PHP_AUTH_PW' => 'test', ]); - if ($read == false) { + if (false == $read) { $this->expectException(AccessDeniedException::class); } $client->catchExceptions(false); //Test read/list access by access /new overview page - $crawler = $client->request('GET', static::$base_path . '/new'); + $crawler = $client->request('GET', static::$base_path.'/new'); $this->assertFalse($client->getResponse()->isRedirect()); - $this->assertEquals($read, $client->getResponse()->isSuccessful(), "Controller was not successful!"); - $this->assertEquals($read, !$client->getResponse()->isForbidden(), "Permission Checking not working!"); + $this->assertEquals($read, $client->getResponse()->isSuccessful(), 'Controller was not successful!'); + $this->assertEquals($read, !$client->getResponse()->isForbidden(), 'Permission Checking not working!'); } /** @@ -92,19 +84,19 @@ abstract class AbstractAdminControllerTest extends WebTestCase //Test read access $client = static::createClient([], [ 'PHP_AUTH_USER' => $user, - 'PHP_AUTH_PW' => 'test', + 'PHP_AUTH_PW' => 'test', ]); $client->catchExceptions(false); - if ($read == false) { + if (false == $read) { $this->expectException(AccessDeniedException::class); } //Test read/list access by access /new overview page - $crawler = $client->request('GET', static::$base_path . '/1'); + $crawler = $client->request('GET', static::$base_path.'/1'); $this->assertFalse($client->getResponse()->isRedirect()); - $this->assertEquals($read, $client->getResponse()->isSuccessful(), "Controller was not successful!"); - $this->assertEquals($read, !$client->getResponse()->isForbidden(), "Permission Checking not working!"); + $this->assertEquals($read, $client->getResponse()->isSuccessful(), 'Controller was not successful!'); + $this->assertEquals($read, !$client->getResponse()->isForbidden(), 'Permission Checking not working!'); } public function deleteDataProvider() @@ -113,12 +105,13 @@ abstract class AbstractAdminControllerTest extends WebTestCase ['noread', false], ['anonymous', false], ['user', true], - ['admin', true] + ['admin', true], ]; } /** * Tests if deleting an entity is working. + * * @group slow * @dataProvider deleteDataProvider */ @@ -127,20 +120,19 @@ abstract class AbstractAdminControllerTest extends WebTestCase //Test read access $client = static::createClient([], [ 'PHP_AUTH_USER' => $user, - 'PHP_AUTH_PW' => 'test', + 'PHP_AUTH_PW' => 'test', ]); $client->catchExceptions(false); - if ($delete == false) { - $this->expectException(AccessDeniedException::class); + if (false == $delete) { + $this->expectException(AccessDeniedException::class); } //Test read/list access by access /new overview page - $crawler = $client->request('DELETE', static::$base_path . '/7'); + $crawler = $client->request('DELETE', static::$base_path.'/7'); //Page is redirected to '/new', when delete was successful - $this->assertEquals($delete, $client->getResponse()->isRedirect(static::$base_path . '/new')); - $this->assertEquals($delete, !$client->getResponse()->isForbidden(), "Permission Checking not working!"); + $this->assertEquals($delete, $client->getResponse()->isRedirect(static::$base_path.'/new')); + $this->assertEquals($delete, !$client->getResponse()->isForbidden(), 'Permission Checking not working!'); } - -} \ No newline at end of file +} diff --git a/tests/Controller/AdminPages/AttachmentTypeControllerTest.php b/tests/Controller/AdminPages/AttachmentTypeControllerTest.php index 18dc1002..d7cfd48c 100644 --- a/tests/Controller/AdminPages/AttachmentTypeControllerTest.php +++ b/tests/Controller/AdminPages/AttachmentTypeControllerTest.php @@ -1,6 +1,6 @@ request('GET', $url); $response = $client->getResponse(); - if($expect_redirect) { + if ($expect_redirect) { $this->assertEquals(302, $response->getStatusCode()); } $this->assertEquals($expect_redirect, $response->isRedirect()); @@ -90,9 +88,11 @@ class RedirectControllerTest extends WebTestCase /** * Test if the user is redirected to the localized version of a page, based on his settings. + * * @dataProvider urlAddLocaleDataProvider * @group slow * @depends testUrlMatch + * * @param $user_locale * @param $input_path * @param $redirect_path @@ -100,7 +100,7 @@ class RedirectControllerTest extends WebTestCase public function testAddLocale($user_locale, $input_path, $redirect_path) { //Redirect path is absolute - $redirect_path = 'http://localhost' . $redirect_path; + $redirect_path = 'http://localhost'.$redirect_path; /** @var User $user */ $user = $this->userRepo->findOneBy(['name' => 'user']); @@ -110,7 +110,7 @@ class RedirectControllerTest extends WebTestCase $client = static::createClient([], [ 'PHP_AUTH_USER' => 'user', - 'PHP_AUTH_PW' => 'test', + 'PHP_AUTH_PW' => 'test', ]); $client->followRedirects(false); @@ -119,7 +119,8 @@ class RedirectControllerTest extends WebTestCase } /** - * Test if the user is redirected to password change page if he should do that + * Test if the user is redirected to password change page if he should do that. + * * @depends testAddLocale * @group slow * @testWith ["de"] @@ -137,13 +138,11 @@ class RedirectControllerTest extends WebTestCase $client = static::createClient([], [ 'PHP_AUTH_USER' => 'user', - 'PHP_AUTH_PW' => 'test', + 'PHP_AUTH_PW' => 'test', ]); $client->followRedirects(false); $client->request('GET', '/part/3'); $this->assertEquals("/$locale/user/settings", $client->getResponse()->headers->get('Location')); - - } -} \ No newline at end of file +} diff --git a/tests/Entity/Attachments/AttachmentTest.php b/tests/Entity/Attachments/AttachmentTest.php index 1a908758..b39e1f62 100644 --- a/tests/Entity/Attachments/AttachmentTest.php +++ b/tests/Entity/Attachments/AttachmentTest.php @@ -1,6 +1,6 @@ assertEmpty($attachment->getFilename()); } - public function subClassesDataProvider() : array + public function subClassesDataProvider(): array { return [ [AttachmentTypeAttachment::class, AttachmentType::class], @@ -87,16 +84,14 @@ class AttachmentTest extends TestCase [PartAttachment::class, Part::class], [StorelocationAttachment::class, Storelocation::class], [SupplierAttachment::class, Supplier::class], - [UserAttachment::class, User::class] + [UserAttachment::class, User::class], ]; } /** * @dataProvider subClassesDataProvider - * @param string $attachment_class - * @param string $allowed_class */ - public function testSetElement(string $attachment_class, string $allowed_class) : void + public function testSetElement(string $attachment_class, string $allowed_class): void { /** @var Attachment $attachment */ $attachment = new $attachment_class(); @@ -110,16 +105,17 @@ class AttachmentTest extends TestCase /** * Test that all attachment subclasses like PartAttachment or similar returns an exception, when an not allowed * element is passed. + * * @dataProvider subClassesDataProvider * @depends testSetElement */ - public function testSetElementExceptionOnSubClasses(string $attachment_class, string $allowed_class) : void + public function testSetElementExceptionOnSubClasses(string $attachment_class, string $allowed_class): void { $this->expectException(\InvalidArgumentException::class); /** @var Attachment $attachment */ $attachment = new $attachment_class(); - if ($allowed_class !== Device::class) { + if (Device::class !== $allowed_class) { $element = new Device(); } else { $element = new Category(); @@ -138,7 +134,7 @@ class AttachmentTest extends TestCase ['%SECURE%/test.txt', false], ['%test%/foo/bar.ghp', true], ['foo%MEDIA%/foo.jpg', true], - ['foo%MEDIA%/%BASE%foo.jpg', true] + ['foo%MEDIA%/%BASE%foo.jpg', true], ]; } @@ -211,7 +207,7 @@ class AttachmentTest extends TestCase ['%BASE%/foo/bar.txt', false], ['/', false], ['https://google.de', false], - ['%FOOTPRINTS%/foo/bar.txt', true] + ['%FOOTPRINTS%/foo/bar.txt', true], ]; } @@ -249,7 +245,7 @@ class AttachmentTest extends TestCase return [ ['%MEDIA%/foo/bar.txt', null, 'bar.txt'], ['%MEDIA%/foo/bar.JPeg', 'test.txt', 'test.txt'], - ['https://www.google.de/test.txt', null, null] + ['https://www.google.de/test.txt', null, null], ]; } @@ -278,11 +274,11 @@ class AttachmentTest extends TestCase } /** - * Sets a protected property on a given object via reflection + * Sets a protected property on a given object via reflection. * - * @param object $object - instance in which protected value is being modified + * @param object $object - instance in which protected value is being modified * @param string $property - property on instance being modified - * @param mixed $value - new value of the property being modified + * @param mixed $value - new value of the property being modified * * @return void */ @@ -293,5 +289,4 @@ class AttachmentTest extends TestCase $reflection_property->setAccessible(true); $reflection_property->setValue($object, $value); } - -} \ No newline at end of file +} diff --git a/tests/Entity/Attachments/AttachmentTypeTest.php b/tests/Entity/Attachments/AttachmentTypeTest.php index ecdbf9af..1754cb3f 100644 --- a/tests/Entity/Attachments/AttachmentTypeTest.php +++ b/tests/Entity/Attachments/AttachmentTypeTest.php @@ -1,6 +1,6 @@ assertInstanceOf(Collection::class, $attachment_type->getAttachmentsForType()); $this->assertEmpty($attachment_type->getFiletypeFilter()); } -} \ No newline at end of file +} diff --git a/tests/Entity/Parts/PartLotTest.php b/tests/Entity/Parts/PartLotTest.php index ed6b9acd..84fe5f62 100644 --- a/tests/Entity/Parts/PartLotTest.php +++ b/tests/Entity/Parts/PartLotTest.php @@ -1,6 +1,6 @@ setExpirationDate($datetime->setTimestamp(strtotime('now -1 hour'))); $this->assertTrue($lot->isExpired(), 'Lot with expiration date in the past must be expired!'); } -} \ No newline at end of file +} diff --git a/tests/Entity/Parts/PartTest.php b/tests/Entity/Parts/PartTest.php index dd522b6f..6842ee3b 100644 --- a/tests/Entity/Parts/PartTest.php +++ b/tests/Entity/Parts/PartTest.php @@ -1,6 +1,6 @@ setIsInteger(true); $this->assertEquals(1000000013, $part->getAmountSum()); } -} \ No newline at end of file +} diff --git a/tests/Entity/PriceSystem/CurrencyTest.php b/tests/Entity/PriceSystem/CurrencyTest.php index e5895a33..46540581 100644 --- a/tests/Entity/PriceSystem/CurrencyTest.php +++ b/tests/Entity/PriceSystem/CurrencyTest.php @@ -1,6 +1,6 @@ setExchangeRate('0'); $this->assertNull($currency->getInverseExchangeRate()); - $currency->setExchangeRate("1.45643"); - $this->assertEquals("0.68661", $currency->getInverseExchangeRate()); + $currency->setExchangeRate('1.45643'); + $this->assertEquals('0.68661', $currency->getInverseExchangeRate()); } -} \ No newline at end of file +} diff --git a/tests/Entity/PriceSystem/OrderdetailTest.php b/tests/Entity/PriceSystem/OrderdetailTest.php index 41bae66c..d9ae8666 100644 --- a/tests/Entity/PriceSystem/OrderdetailTest.php +++ b/tests/Entity/PriceSystem/OrderdetailTest.php @@ -1,6 +1,6 @@ assertEquals($price5, $orderdetail->findPriceForQty(5.3)); $this->assertEquals($price5, $orderdetail->findPriceForQty(10000)); } -} \ No newline at end of file +} diff --git a/tests/Entity/PriceSystem/PricedetailTest.php b/tests/Entity/PriceSystem/PricedetailTest.php index 0af86e10..860fc48a 100644 --- a/tests/Entity/PriceSystem/PricedetailTest.php +++ b/tests/Entity/PriceSystem/PricedetailTest.php @@ -1,6 +1,6 @@ assertEquals('43.58000', $pricedetail->getPricePerUnit()); $this->assertEquals('139.45600', $pricedetail->getPricePerUnit('3.2')); - $pricedetail->setPrice('10000000.2345'); //Ten million $pricedetail->setPriceRelatedQuantity(1.234e9); //100 billion $this->assertEquals('0.00810', $pricedetail->getPricePerUnit()); @@ -61,7 +57,6 @@ class PricedetailTest extends TestCase $orderdetail2 = $this->createMock(Orderdetail::class); $orderdetail2->method('getPart')->willReturn($part2); - //By default a price detail returns 1 $this->assertEquals(1, $pricedetail->getPriceRelatedQuantity()); @@ -90,7 +85,6 @@ class PricedetailTest extends TestCase $orderdetail2 = $this->createMock(Orderdetail::class); $orderdetail2->method('getPart')->willReturn($part2); - //By default a price detail returns 1 $this->assertEquals(1, $pricedetail->getMinDiscountQuantity()); @@ -105,4 +99,4 @@ class PricedetailTest extends TestCase $pricedetail->setOrderdetail($orderdetail2); $this->assertEquals(0.23, $pricedetail->getMinDiscountQuantity()); } -} \ No newline at end of file +} diff --git a/tests/Entity/StructuralDBElementTest.php b/tests/Entity/StructuralDBElementTest.php index a86ab11b..eef6cb2a 100644 --- a/tests/Entity/StructuralDBElementTest.php +++ b/tests/Entity/StructuralDBElementTest.php @@ -1,6 +1,6 @@ setParent($this->root); $this->assertTrue($inheritance->isChildOf($this->root)); $this->assertFalse($this->root->isChildOf($inheritance)); @@ -119,5 +117,4 @@ class StructuralDBElementTest extends TestCase $this->assertEquals([$this->root, $this->child1], $this->child1->getPathArray()); $this->assertEquals([$this->root], $this->root->getPathArray()); } - -} \ No newline at end of file +} diff --git a/tests/Entity/UserSystem/PermissionsEmbedTest.php b/tests/Entity/UserSystem/PermissionsEmbedTest.php index 3a53cd83..936be474 100644 --- a/tests/Entity/UserSystem/PermissionsEmbedTest.php +++ b/tests/Entity/UserSystem/PermissionsEmbedTest.php @@ -1,6 +1,6 @@ null //Test both normal name and constants - $this->assertNull( $embed->getPermissionValue(PermissionsEmbed::PARTS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::CONFIG, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::ATTACHMENT_TYPES, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::CATEGORIES, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::DATABASE, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::DEVICE_PARTS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::DEVICES, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::FOOTRPINTS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::GROUPS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::DATABASE, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::LABELS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::MANUFACTURERS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_ATTACHMENTS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_COMMENT, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_DESCRIPTION, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_FOOTPRINT, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_MANUFACTURER, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_MINAMOUNT, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_NAME, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_ORDER, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::PARTS_ORDERDETAILS, 0)); - $this->assertEquals(null, $embed->getPermissionValue(PermissionsEmbed::USERS, 0)); - + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::CONFIG, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::ATTACHMENT_TYPES, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::CATEGORIES, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::DATABASE, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::DEVICE_PARTS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::DEVICES, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::FOOTRPINTS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::GROUPS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::DATABASE, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::LABELS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::MANUFACTURERS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_ATTACHMENTS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_COMMENT, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_DESCRIPTION, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_FOOTPRINT, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_MANUFACTURER, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_MINAMOUNT, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_NAME, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_ORDER, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS_ORDERDETAILS, 0)); + $this->assertNull($embed->getPermissionValue(PermissionsEmbed::USERS, 0)); //Set a value for testing to the part property $reflection = new \ReflectionClass($embed); @@ -77,13 +74,10 @@ class PermissionsEmbedTest extends TestCase $this->assertTrue($embed->getPermissionValue(PermissionsEmbed::PARTS, 4)); // 11 is reserved, but it should be also treat as INHERIT. $this->assertNull($embed->getPermissionValue(PermissionsEmbed::PARTS, 6)); - - } public function testGetBitValue() { - $embed = new PermissionsEmbed(); //Set a value for testing to the part property @@ -94,11 +88,11 @@ class PermissionsEmbedTest extends TestCase $property->setValue($embed, 0b11011000); // 11 01 10 00 //Test if function is working correctly - $this->assertEquals(PermissionsEmbed::INHERIT ,$embed->getBitValue(PermissionsEmbed::PARTS, 0)); - $this->assertEquals(PermissionsEmbed::DISALLOW ,$embed->getBitValue(PermissionsEmbed::PARTS, 2)); - $this->assertEquals(PermissionsEmbed::ALLOW ,$embed->getBitValue(PermissionsEmbed::PARTS, 4)); + $this->assertEquals(PermissionsEmbed::INHERIT, $embed->getBitValue(PermissionsEmbed::PARTS, 0)); + $this->assertEquals(PermissionsEmbed::DISALLOW, $embed->getBitValue(PermissionsEmbed::PARTS, 2)); + $this->assertEquals(PermissionsEmbed::ALLOW, $embed->getBitValue(PermissionsEmbed::PARTS, 4)); // 11 is reserved, but it should be also treat as INHERIT. - $this->assertEquals(0b11 ,$embed->getBitValue(PermissionsEmbed::PARTS, 6)); + $this->assertEquals(0b11, $embed->getBitValue(PermissionsEmbed::PARTS, 6)); } public function testInvalidPermissionName() @@ -139,7 +133,7 @@ class PermissionsEmbedTest extends TestCase 'ALLOW' => [PermissionsEmbed::ALLOW], 'DISALLOW' => [PermissionsEmbed::DISALLOW], 'INHERIT' => [PermissionsEmbed::INHERIT], - '0b11' => [0b11] + '0b11' => [0b11], ]; } @@ -149,7 +143,7 @@ class PermissionsEmbedTest extends TestCase 'ALLOW' => [true], 'DISALLOW' => [false], 'INHERIT' => [null], - '0b11' => [null] + '0b11' => [null], ]; } @@ -188,7 +182,7 @@ class PermissionsEmbedTest extends TestCase $embed->setRawPermissionValues([ PermissionsEmbed::PARTS => 0, PermissionsEmbed::USERS => 100, - PermissionsEmbed::CATEGORIES => 1304 + PermissionsEmbed::CATEGORIES => 1304, ]); $this->assertEquals(0, $embed->getRawPermissionValue(PermissionsEmbed::PARTS)); @@ -204,7 +198,5 @@ class PermissionsEmbedTest extends TestCase $this->assertEquals(0, $embed->getRawPermissionValue(PermissionsEmbed::PARTS)); $this->assertEquals(100, $embed->getRawPermissionValue(PermissionsEmbed::USERS)); $this->assertEquals(1304, $embed->getRawPermissionValue(PermissionsEmbed::CATEGORIES)); - } - } diff --git a/tests/Entity/UserSystem/UserTest.php b/tests/Entity/UserSystem/UserTest.php index 99c6ed35..0ed8fdf2 100644 --- a/tests/Entity/UserSystem/UserTest.php +++ b/tests/Entity/UserSystem/UserTest.php @@ -1,6 +1,6 @@ assertEquals('John Doe', $user->getFullName(false)); $this->assertEquals('John Doe (username)', $user->getFullName(true)); } -} \ No newline at end of file +} diff --git a/tests/Helpers/BBCodeToMarkdownConverterTest.php b/tests/Helpers/BBCodeToMarkdownConverterTest.php index a2064c94..34cfbfef 100644 --- a/tests/Helpers/BBCodeToMarkdownConverterTest.php +++ b/tests/Helpers/BBCodeToMarkdownConverterTest.php @@ -1,6 +1,6 @@ assertEquals($expected, $this->converter->convert($bbcode)); } -} \ No newline at end of file +} diff --git a/tests/Helpers/TreeViewNodeTest.php b/tests/Helpers/TreeViewNodeTest.php index 4506809f..d3fda45a 100644 --- a/tests/Helpers/TreeViewNodeTest.php +++ b/tests/Helpers/TreeViewNodeTest.php @@ -1,6 +1,6 @@ node1 = new TreeViewNode('Name'); //Node 2 gets values for all arguments $this->node2 = new TreeViewNode('Name', 'www.foo.bar', $sub_nodes); - } public function testConstructor() @@ -62,10 +58,8 @@ class TreeViewNodeTest extends TestCase $this->assertEquals('Name', $this->node1->getText()); //The second node must have the given things as properties. - $this->assertEquals('Name',$this->node2->getText()); + $this->assertEquals('Name', $this->node2->getText()); $this->assertEquals('www.foo.bar', $this->node2->getHref()); $this->assertNotEmpty($this->node2->getNodes()); } - - -} \ No newline at end of file +} diff --git a/tests/Services/AmountFormatterTest.php b/tests/Services/AmountFormatterTest.php index 840a633d..cb2db8ea 100644 --- a/tests/Services/AmountFormatterTest.php +++ b/tests/Services/AmountFormatterTest.php @@ -1,6 +1,6 @@ assertEquals("2", $this->service->format(2.321)); - $this->assertEquals("1002", $this->service->format(1002.356)); - $this->assertEquals("1000454", $this->service->format(1000454.0)); - $this->assertEquals("0", $this->service->format(0.01)); - $this->assertEquals("0", $this->service->format(0)); + $this->assertEquals('2', $this->service->format(2.321)); + $this->assertEquals('1002', $this->service->format(1002.356)); + $this->assertEquals('1000454', $this->service->format(1000454.0)); + $this->assertEquals('0', $this->service->format(0.01)); + $this->assertEquals('0', $this->service->format(0)); } public function testInvalidInput() { $this->expectException(\InvalidArgumentException::class); - $this->service->format("test"); + $this->service->format('test'); } public function testFormatUnitWithoutSI() { $meters = new MeasurementUnit(); - $meters->setIsInteger(false)->setUseSIPrefix(false)->setUnit("m"); + $meters->setIsInteger(false)->setUseSIPrefix(false)->setUnit('m'); $this->assertEquals('0.32 m', $this->service->format(0.3245, $meters)); $this->assertEquals('10003.56 m', $this->service->format(10003.556, $meters)); @@ -96,4 +93,4 @@ class AmountFormatterTest extends WebTestCase $this->assertEquals('12002.32 m', $this->service->format(12002.32, $meters, ['show_prefix' => false])); $this->assertEquals('123 m', $this->service->format(123.234, $meters, ['is_integer' => true])); } -} \ No newline at end of file +} diff --git a/tests/Services/Attachments/AttachmentPathResolverTest.php b/tests/Services/Attachments/AttachmentPathResolverTest.php index a800df80..0c5227f7 100644 --- a/tests/Services/Attachments/AttachmentPathResolverTest.php +++ b/tests/Services/Attachments/AttachmentPathResolverTest.php @@ -1,6 +1,6 @@ getProjectDir()); self::$projectDir = str_replace('\\', '/', self::$projectDir_orig); - self::$media_path = self::$projectDir . '/public/media'; - self::$footprint_path = self::$projectDir . '/public/img/footprints'; + self::$media_path = self::$projectDir.'/public/media'; + self::$footprint_path = self::$projectDir.'/public/img/footprints'; } public static function setUpBeforeClass() @@ -69,8 +66,8 @@ class AttachmentPathResolverTest extends WebTestCase $this->assertEquals(self::$projectDir_orig, self::$service->parameterToAbsolutePath(self::$projectDir)); //Relative pathes should be resolved - $this->assertEquals(self::$projectDir_orig . DIRECTORY_SEPARATOR . 'src', self::$service->parameterToAbsolutePath('src')); - $this->assertEquals(self::$projectDir_orig . DIRECTORY_SEPARATOR . 'src', self::$service->parameterToAbsolutePath('./src')); + $this->assertEquals(self::$projectDir_orig.\DIRECTORY_SEPARATOR.'src', self::$service->parameterToAbsolutePath('src')); + $this->assertEquals(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')); @@ -80,9 +77,9 @@ class AttachmentPathResolverTest extends WebTestCase public function placeholderDataProvider() { return [ - ['%FOOTPRINTS%/test/test.jpg', self::$footprint_path . '/test/test.jpg'], - ['%FOOTPRINTS%/test/', self::$footprint_path . '/test/'], - ['%MEDIA%/test', self::$media_path . '/test'], + ['%FOOTPRINTS%/test/test.jpg', self::$footprint_path.'/test/test.jpg'], + ['%FOOTPRINTS%/test/', self::$footprint_path.'/test/'], + ['%MEDIA%/test', self::$media_path.'/test'], ['%MEDIA%', self::$media_path], ['%FOOTPRINTS%', self::$footprint_path], //Footprints 3D are disabled @@ -95,24 +92,24 @@ class AttachmentPathResolverTest extends WebTestCase ['%FOOTPRINTS%/%MEDIA%', null], //No more than one placholder ['%FOOTPRINTS%/%FOOTPRINTS%', null], ['%FOOTPRINTS%/../../etc/passwd', null], - ['%FOOTPRINTS%/0\..\test', null] + ['%FOOTPRINTS%/0\..\test', null], ]; } public function realPathDataProvider() { return [ - [self::$media_path . '/test/img.jpg', '%MEDIA%/test/img.jpg'], - [self::$media_path . '/test/img.jpg', '%BASE%/data/media/test/img.jpg', true], - [self::$footprint_path . '/foo.jpg', '%FOOTPRINTS%/foo.jpg'], - [self::$footprint_path . '/foo.jpg', '%FOOTPRINTS%/foo.jpg', true], + [self::$media_path.'/test/img.jpg', '%MEDIA%/test/img.jpg'], + [self::$media_path.'/test/img.jpg', '%BASE%/data/media/test/img.jpg', true], + [self::$footprint_path.'/foo.jpg', '%FOOTPRINTS%/foo.jpg'], + [self::$footprint_path.'/foo.jpg', '%FOOTPRINTS%/foo.jpg', true], //Every kind of absolute path, that is not based with our placeholder dirs must be invald ['/etc/passwd', null], ['C:\\not\\existing.txt', null], //More then one placeholder is not allowed - [self::$footprint_path . '/test/' . self::$footprint_path, null], + [self::$footprint_path.'/test/'.self::$footprint_path, null], //Path must begin with path - ['/not/root' . self::$footprint_path, null] + ['/not/root'.self::$footprint_path, null], ]; } @@ -131,4 +128,4 @@ class AttachmentPathResolverTest extends WebTestCase { $this->assertEquals($expected, self::$service->realPathToPlaceholder($param, $old_method)); } -} \ No newline at end of file +} diff --git a/tests/Services/Attachments/AttachmentURLGeneratorTest.php b/tests/Services/Attachments/AttachmentURLGeneratorTest.php index af61eeac..7cc1d4f2 100644 --- a/tests/Services/Attachments/AttachmentURLGeneratorTest.php +++ b/tests/Services/Attachments/AttachmentURLGeneratorTest.php @@ -1,6 +1,6 @@ assertEquals($expected, static::$service->absolutePathToAssetPath($input, static::PUBLIC_DIR)); } -} \ No newline at end of file +} diff --git a/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php b/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php index e75aaf34..da0b79e8 100644 --- a/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php +++ b/tests/Services/Attachments/BuiltinAttachmentsFinderTest.php @@ -1,6 +1,6 @@ ['jpeg', 'jpg']], ['%FOOTPRINTS%/test/test.jpg', '%FOOTPRINTS%/123.jpeg', '%FOOTPRINTS_3D%/test.jpg']], //['test.jpg', ['allowed_extensions' => ['jpeg', 'jpg']], ['%FOOTPRINTS%/test/test.jpg', '%FOOTPRINTS_3D%/test.jpg']] - ]; } @@ -69,4 +67,4 @@ class BuiltinAttachmentsFinderTest extends WebTestCase $this->assertEquals([], array_diff($value, $expected), 'Additional'); $this->assertEquals([], array_diff($expected, $value), 'Missing:'); } -} \ No newline at end of file +} diff --git a/tests/Services/Attachments/FileTypeFilterToolsTest.php b/tests/Services/Attachments/FileTypeFilterToolsTest.php index ba62f82c..c673753b 100644 --- a/tests/Services/Attachments/FileTypeFilterToolsTest.php +++ b/tests/Services/Attachments/FileTypeFilterToolsTest.php @@ -1,6 +1,6 @@ get(FileTypeFilterTools::class); } - public function validateDataProvider() : array + public function validateDataProvider(): array { return [ ['', true], //Empty string is valid @@ -47,11 +46,11 @@ class FileTypeFilterToolsTest extends WebTestCase ['test.png', false], //No full filename ['application/*', false], //Only certain placeholders are allowed ['.png;.png,.jpg', false], //Wrong separator - ['.png .jpg .gif', false] + ['.png .jpg .gif', false], ]; } - public function normalizeDataProvider() : array + public function normalizeDataProvider(): array { return [ ['', ''], @@ -67,7 +66,7 @@ class FileTypeFilterToolsTest extends WebTestCase ]; } - public function extensionAllowedDataProvider() : array + public function extensionAllowedDataProvider(): array { return [ ['', 'txt', true], @@ -88,10 +87,9 @@ class FileTypeFilterToolsTest extends WebTestCase } /** - * Test the validateFilterString method + * Test the validateFilterString method. + * * @dataProvider validateDataProvider - * @param string $filter - * @param bool $expected */ public function testValidateFilterString(string $filter, bool $expected) { @@ -100,8 +98,6 @@ class FileTypeFilterToolsTest extends WebTestCase /** * @dataProvider normalizeDataProvider - * @param string $filter - * @param string $expected */ public function testNormalizeFilterString(string $filter, string $expected) { @@ -115,4 +111,4 @@ class FileTypeFilterToolsTest extends WebTestCase { $this->assertEquals($expected, self::$service->isExtensionAllowed($filter, $extension), $expected); } -} \ No newline at end of file +} diff --git a/tests/Services/PermissionResolverTest.php b/tests/Services/PermissionResolverTest.php index de16dbb8..3e514014 100644 --- a/tests/Services/PermissionResolverTest.php +++ b/tests/Services/PermissionResolverTest.php @@ -1,6 +1,6 @@ group->method('getParent')->willReturn($parent_group); } - public function getPermissionNames() { //List all possible operation names. @@ -116,7 +112,7 @@ class PermissionResolverTest extends WebTestCase [PermissionsEmbed::CATEGORIES], [PermissionsEmbed::PARTS_PRICES], [PermissionsEmbed::ATTACHMENT_TYPES], - [PermissionsEmbed::CONFIG] + [PermissionsEmbed::CONFIG], ]; } @@ -196,5 +192,4 @@ class PermissionResolverTest extends WebTestCase $this->assertNull($this->service->inherit($this->user_withoutGroup, 'parts', 'show_history')); $this->assertNull($this->service->inherit($this->user_withoutGroup, 'parts', 'delete')); } - -} \ No newline at end of file +} diff --git a/tests/Services/PricedetailHelperTest.php b/tests/Services/PricedetailHelperTest.php index 947fbfb3..50b95c1a 100644 --- a/tests/Services/PricedetailHelperTest.php +++ b/tests/Services/PricedetailHelperTest.php @@ -1,6 +1,6 @@ assertEquals($expected_result, $this->service->getMaxDiscountAmount($part), $message); } -} \ No newline at end of file +} diff --git a/tests/Services/SIFormatterTest.php b/tests/Services/SIFormatterTest.php index 9a39e2f0..daea7612 100644 --- a/tests/Services/SIFormatterTest.php +++ b/tests/Services/SIFormatterTest.php @@ -1,6 +1,6 @@ assertSame(0, $this->service->getMagnitude(-1.0)); $this->assertSame(0, $this->service->getMagnitude(-9.9)); - $this->assertSame(3, $this->service->getMagnitude(9999.99)); $this->assertSame(3, $this->service->getMagnitude(1000.0)); $this->assertSame(3, $this->service->getMagnitude(-9999.99)); @@ -59,7 +57,7 @@ class SIFormatterTest extends WebTestCase $this->assertSame(-1, $this->service->getMagnitude(0.1)); $this->assertSame(-1, $this->service->getMagnitude(-0.9999)); - $this->assertSame(-25, $this->service->getMagnitude(- 1.246e-25)); + $this->assertSame(-25, $this->service->getMagnitude(-1.246e-25)); $this->assertSame(12, $this->service->getMagnitude(9.99e12)); } @@ -78,9 +76,9 @@ class SIFormatterTest extends WebTestCase public function testFormat() { - $this->assertSame("2.32 km", $this->service->format(2321, 'm')); - $this->assertEquals("230.45 km", $this->service->format(230450.3, 'm')); - $this->assertSame("-98.20 mg", $this->service->format(-0.0982, 'g')); + $this->assertSame('2.32 km', $this->service->format(2321, 'm')); + $this->assertEquals('230.45 km', $this->service->format(230450.3, 'm')); + $this->assertSame('-98.20 mg', $this->service->format(-0.0982, 'g')); $this->assertSame('-0.23 g', $this->service->format(-0.23, 'g')); } -} \ No newline at end of file +}