Applied rector suggestions

This commit is contained in:
Jan Böhmer 2024-06-22 00:31:43 +02:00
parent 4106bcef5f
commit 20f32c7f12
170 changed files with 808 additions and 761 deletions

View file

@ -139,12 +139,12 @@ class AttachmentPathResolver
}
//If we have now have a placeholder left, the string is invalid:
if (preg_match('#%\w+%#', $placeholder_path)) {
if (preg_match('#%\w+%#', (string) $placeholder_path)) {
return null;
}
//Path is invalid if path is directory traversal
if (str_contains($placeholder_path, '..')) {
if (str_contains((string) $placeholder_path, '..')) {
return null;
}
@ -183,7 +183,7 @@ class AttachmentPathResolver
}
//If the new string does not begin with a placeholder, it is invalid
if (!preg_match('#^%\w+%#', $real_path)) {
if (!preg_match('#^%\w+%#', (string) $real_path)) {
return null;
}

View file

@ -300,7 +300,7 @@ class AttachmentSubmitHandler
return $attachment;
}
$filename = basename($old_path);
$filename = basename((string) $old_path);
//If the basename is not one of the new unique on, we have to save the old filename
if (!preg_match('#\w+-\w{13}\.#', $filename)) {
//Save filename to attachment field
@ -378,7 +378,7 @@ class AttachmentSubmitHandler
//If we don't know filename yet, try to determine it out of url
if ('' === $filename) {
$filename = basename(parse_url($url, PHP_URL_PATH));
$filename = basename(parse_url((string) $url, PHP_URL_PATH));
}
//Set original file

View file

@ -46,11 +46,10 @@ class ElementCacheTagGenerator
{
//Ensure that the given element is a class name
if (is_object($element)) {
$element = get_class($element);
} else { //And that the class exists
if (!class_exists($element)) {
throw new \InvalidArgumentException("The given class '$element' does not exist!");
}
$element = $element::class;
} elseif (!class_exists($element)) {
//And that the class exists
throw new \InvalidArgumentException("The given class '$element' does not exist!");
}
//Check if the tag is already cached

View file

@ -134,7 +134,7 @@ class KiCadHelper
if ($this->category_depth >= 0) {
//Ensure that the category is set
if (!$category) {
if ($category === null) {
throw new NotFoundHttpException('Category must be set, if category_depth is greater than 1!');
}
@ -196,25 +196,25 @@ class KiCadHelper
//Add basic fields
$result["fields"]["description"] = $this->createField($part->getDescription());
if ($part->getCategory()) {
if ($part->getCategory() !== null) {
$result["fields"]["Category"] = $this->createField($part->getCategory()->getFullPath('/'));
}
if ($part->getManufacturer()) {
if ($part->getManufacturer() !== null) {
$result["fields"]["Manufacturer"] = $this->createField($part->getManufacturer()->getName());
}
if ($part->getManufacturerProductNumber() !== "") {
$result['fields']["MPN"] = $this->createField($part->getManufacturerProductNumber());
}
if ($part->getManufacturingStatus()) {
if ($part->getManufacturingStatus() !== null) {
$result["fields"]["Manufacturing Status"] = $this->createField(
//Always use the english translation
$this->translator->trans($part->getManufacturingStatus()->toTranslationKey(), locale: 'en')
);
}
if ($part->getFootprint()) {
if ($part->getFootprint() !== null) {
$result["fields"]["Part-DB Footprint"] = $this->createField($part->getFootprint()->getName());
}
if ($part->getPartUnit()) {
if ($part->getPartUnit() !== null) {
$unit = $part->getPartUnit()->getName();
if ($part->getPartUnit()->getUnit() !== "") {
$unit .= ' ('.$part->getPartUnit()->getUnit().')';
@ -225,7 +225,7 @@ class KiCadHelper
$result["fields"]["Mass"] = $this->createField($part->getMass() . ' g');
}
$result["fields"]["Part-DB ID"] = $this->createField($part->getId());
if (!empty($part->getIpn())) {
if ($part->getIpn() !== null && $part->getIpn() !== '' && $part->getIpn() !== '0') {
$result["fields"]["Part-DB IPN"] = $this->createField($part->getIpn());
}
@ -308,14 +308,9 @@ class KiCadHelper
)) {
return true;
}
//And on the footprint
if ($part->getFootprint() && $part->getFootprint()->getEdaInfo()->getKicadFootprint() !== null) {
return true;
}
//Otherwise the part should be not visible
return false;
return $part->getFootprint() && $part->getFootprint()->getEdaInfo()->getKicadFootprint() !== null;
}
/**

View file

@ -69,7 +69,7 @@ class EntityMerger
{
$merger = $this->findMergerForObject($target, $other, $context);
if ($merger === null) {
throw new \RuntimeException('No merger found for merging '.get_class($other).' into '.get_class($target));
throw new \RuntimeException('No merger found for merging '.$other::class.' into '.$target::class);
}
return $merger->merge($target, $other, $context);
}

View file

@ -85,9 +85,7 @@ trait EntityMergerHelperTrait
protected function useOtherValueIfNotNull(object $target, object $other, string $field): object
{
return $this->useCallback(
function ($target_value, $other_value) {
return $target_value ?? $other_value;
},
fn($target_value, $other_value) => $target_value ?? $other_value,
$target,
$other,
$field
@ -106,9 +104,7 @@ trait EntityMergerHelperTrait
protected function useOtherValueIfNotEmtpy(object $target, object $other, string $field): object
{
return $this->useCallback(
function ($target_value, $other_value) {
return empty($target_value) ? $other_value : $target_value;
},
fn($target_value, $other_value) => empty($target_value) ? $other_value : $target_value,
$target,
$other,
$field
@ -126,9 +122,7 @@ trait EntityMergerHelperTrait
protected function useLargerValue(object $target, object $other, string $field): object
{
return $this->useCallback(
function ($target_value, $other_value) {
return max($target_value, $other_value);
},
fn($target_value, $other_value) => max($target_value, $other_value),
$target,
$other,
$field
@ -146,9 +140,7 @@ trait EntityMergerHelperTrait
protected function useSmallerValue(object $target, object $other, string $field): object
{
return $this->useCallback(
function ($target_value, $other_value) {
return min($target_value, $other_value);
},
fn($target_value, $other_value) => min($target_value, $other_value),
$target,
$other,
$field
@ -166,9 +158,7 @@ trait EntityMergerHelperTrait
protected function useTrueValue(object $target, object $other, string $field): object
{
return $this->useCallback(
function (bool $target_value, bool $other_value): bool {
return $target_value || $other_value;
},
fn(bool $target_value, bool $other_value): bool => $target_value || $other_value,
$target,
$other,
$field
@ -232,10 +222,8 @@ trait EntityMergerHelperTrait
continue 2;
}
}
} else {
if ($target_collection->contains($item)) {
continue;
}
} elseif ($target_collection->contains($item)) {
continue;
}
$clones[] = clone $item;
@ -257,11 +245,9 @@ trait EntityMergerHelperTrait
*/
protected function mergeAttachments(AttachmentContainingDBElement $target, AttachmentContainingDBElement $other): object
{
return $this->mergeCollections($target, $other, 'attachments', function (Attachment $t, Attachment $o): bool {
return $t->getName() === $o->getName()
&& $t->getAttachmentType() === $o->getAttachmentType()
&& $t->getPath() === $o->getPath();
});
return $this->mergeCollections($target, $other, 'attachments', fn(Attachment $t, Attachment $o): bool => $t->getName() === $o->getName()
&& $t->getAttachmentType() === $o->getAttachmentType()
&& $t->getPath() === $o->getPath());
}
/**
@ -272,16 +258,14 @@ trait EntityMergerHelperTrait
*/
protected function mergeParameters(AbstractStructuralDBElement|Part $target, AbstractStructuralDBElement|Part $other): object
{
return $this->mergeCollections($target, $other, 'parameters', function (AbstractParameter $t, AbstractParameter $o): bool {
return $t->getName() === $o->getName()
&& $t->getSymbol() === $o->getSymbol()
&& $t->getUnit() === $o->getUnit()
&& $t->getValueMax() === $o->getValueMax()
&& $t->getValueMin() === $o->getValueMin()
&& $t->getValueTypical() === $o->getValueTypical()
&& $t->getValueText() === $o->getValueText()
&& $t->getGroup() === $o->getGroup();
});
return $this->mergeCollections($target, $other, 'parameters', fn(AbstractParameter $t, AbstractParameter $o): bool => $t->getName() === $o->getName()
&& $t->getSymbol() === $o->getSymbol()
&& $t->getUnit() === $o->getUnit()
&& $t->getValueMax() === $o->getValueMax()
&& $t->getValueMin() === $o->getValueMin()
&& $t->getValueTypical() === $o->getValueTypical()
&& $t->getValueText() === $o->getValueText()
&& $t->getGroup() === $o->getGroup());
}
/**

View file

@ -33,6 +33,7 @@ use App\Entity\PriceInformations\Orderdetail;
* This class merges two parts together.
*
* @implements EntityMergerInterface<Part>
* @see \App\Tests\Services\EntityMergers\Mergers\PartMergerTest
*/
class PartMerger implements EntityMergerInterface
{
@ -99,7 +100,7 @@ class PartMerger implements EntityMergerInterface
return $target;
}
private static function comparePartAssociations(PartAssociation $t, PartAssociation $o): bool {
private function comparePartAssociations(PartAssociation $t, PartAssociation $o): bool {
//We compare the translation keys, as it contains info about the type and other type info
return $t->getOther() === $o->getOther()
&& $t->getTypeTranslationKey() === $o->getTypeTranslationKey();
@ -117,7 +118,7 @@ class PartMerger implements EntityMergerInterface
$this->mergeParameters($target, $other);
//Merge the associations
$this->mergeCollections($target, $other, 'associated_parts_as_owner', self::comparePartAssociations(...));
$this->mergeCollections($target, $other, 'associated_parts_as_owner', $this->comparePartAssociations(...));
//We have to recreate the associations towards the other part, as they are not created by the merger
foreach ($other->getAssociatedPartsAsOther() as $association) {
@ -131,7 +132,7 @@ class PartMerger implements EntityMergerInterface
}
//Ensure that the association is not already present
foreach ($owner->getAssociatedPartsAsOwner() as $existing_association) {
if (self::comparePartAssociations($existing_association, $clone)) {
if ($this->comparePartAssociations($existing_association, $clone)) {
continue 2;
}
}

View file

@ -360,11 +360,7 @@ class EntityURLGenerator
*/
protected function mapToController(array $map, string|AbstractDBElement $entity): string
{
if (is_string($entity)) { //If a class name was already passed, then use it directly
$class = $entity;
} else { //Otherwise get the class name from the entity
$class = $entity::class;
}
$class = is_string($entity) ? $entity : $entity::class;
//Check if we have an direct mapping for the given class
if (!array_key_exists($class, $map)) {

View file

@ -116,7 +116,7 @@ class PKOptionalImporter
//All imported users get assigned to the "PartKeepr Users" group
$group_users = $this->em->find(Group::class, 3);
$group = $this->em->getRepository(Group::class)->findOneBy(['name' => 'PartKeepr Users', 'parent' => $group_users]);
if (!$group) {
if ($group === null) {
$group = new Group();
$group->setName('PartKeepr Users');
$group->setParent($group_users);

View file

@ -218,7 +218,7 @@ class PKPartImporter
'iso_code' => $currency_iso_code,
]);
if (!$currency) {
if ($currency === null) {
$currency = new Currency();
$currency->setIsoCode($currency_iso_code);
$currency->setName(Currencies::getName($currency_iso_code));
@ -265,7 +265,7 @@ class PKPartImporter
]);
//When no orderdetail exists, create one
if (!$orderdetail) {
if ($orderdetail === null) {
$orderdetail = new Orderdetail();
$orderdetail->setSupplier($supplier);
$orderdetail->setSupplierpartnr($spn);

View file

@ -26,6 +26,7 @@ namespace App\Services\InfoProviderSystem\DTOs;
/**
* This DTO represents a file that can be downloaded from a URL.
* This could be a datasheet, a 3D model, a picture or similar.
* @see \App\Tests\Services\InfoProviderSystem\DTOs\FileDTOTest
*/
class FileDTO
{

View file

@ -26,6 +26,7 @@ namespace App\Services\InfoProviderSystem\DTOs;
/**
* This DTO represents a parameter of a part (similar to the AbstractParameter entity).
* This could be a voltage, a current, a temperature or similar.
* @see \App\Tests\Services\InfoProviderSystem\DTOs\ParameterDTOTest
*/
class ParameterDTO
{
@ -76,7 +77,7 @@ class ParameterDTO
$parts = preg_split('/\s*(\.{3}|~)\s*/', $value);
if (count($parts) === 2) {
//Try to extract number and unit from value (allow leading +)
if (empty($unit)) {
if ($unit === null || trim($unit) === '') {
[$number, $unit] = self::splitIntoValueAndUnit(ltrim($parts[0], " +")) ?? [$parts[0], null];
} else {
$number = $parts[0];

View file

@ -25,6 +25,7 @@ namespace App\Services\InfoProviderSystem\DTOs;
/**
* This DTO represents a purchase information for a part (supplier name, order number and prices).
* @see \App\Tests\Services\InfoProviderSystem\DTOs\PurchaseInfoDTOTest
*/
class PurchaseInfoDTO
{

View file

@ -27,6 +27,7 @@ use App\Entity\Parts\ManufacturingStatus;
/**
* This DTO represents a search result for a part.
* @see \App\Tests\Services\InfoProviderSystem\DTOs\SearchResultDTOTest
*/
class SearchResultDTO
{

View file

@ -45,6 +45,7 @@ use Doctrine\ORM\EntityManagerInterface;
/**
* This class converts DTOs to entities which can be persisted in the DB
* @see \App\Tests\Services\InfoProviderSystem\DTOtoEntityConverterTest
*/
final class DTOtoEntityConverter
{
@ -127,7 +128,7 @@ final class DTOtoEntityConverter
$entity->setAttachmentType($type);
//If no name is given, try to extract the name from the URL
if (empty($dto->name)) {
if ($dto->name === null || $dto->name === '' || $dto->name === '0') {
$entity->setName($this->getAttachmentNameFromURL($dto->url));
} else {
$entity->setName($dto->name);

View file

@ -27,6 +27,7 @@ use App\Services\InfoProviderSystem\Providers\InfoProviderInterface;
/**
* This class keeps track of all registered info providers and allows to find them by their key
* @see \App\Tests\Services\InfoProviderSystem\ProviderRegistryTest
*/
final class ProviderRegistry
{

View file

@ -93,7 +93,7 @@ class DigikeyProvider implements InfoProviderInterface
public function isActive(): bool
{
//The client ID has to be set and a token has to be available (user clicked connect)
return !empty($this->clientId) && $this->authTokenManager->hasToken(self::OAUTH_APP_NAME);
return $this->clientId !== '' && $this->authTokenManager->hasToken(self::OAUTH_APP_NAME);
}
public function searchByKeyword(string $keyword): array
@ -210,7 +210,7 @@ class DigikeyProvider implements InfoProviderInterface
$footprint_name = $parameter['Value'];
}
if (in_array(trim($parameter['Value']), array('', '-'), true)) {
if (in_array(trim((string) $parameter['Value']), ['', '-'], true)) {
continue;
}

View file

@ -65,7 +65,7 @@ class Element14Provider implements InfoProviderInterface
public function isActive(): bool
{
return !empty($this->api_key);
return $this->api_key !== '';
}
/**

View file

@ -96,7 +96,7 @@ class LCSCProvider implements InfoProviderInterface
*/
private function getRealDatasheetUrl(?string $url): string
{
if (!empty($url) && preg_match("/^https:\/\/(datasheet\.lcsc\.com|www\.lcsc\.com\/datasheet)\/.*(C\d+)\.pdf$/", $url, $matches) > 0) {
if ($url !== null && trim($url) !== '' && preg_match("/^https:\/\/(datasheet\.lcsc\.com|www\.lcsc\.com\/datasheet)\/.*(C\d+)\.pdf$/", $url, $matches) > 0) {
$response = $this->lcscClient->request('GET', $url, [
'headers' => [
'Referer' => 'https://www.lcsc.com/product-detail/_' . $matches[2] . '.html'
@ -139,7 +139,7 @@ class LCSCProvider implements InfoProviderInterface
// LCSC does not display LCSC codes in the search, instead taking you directly to the
// detailed product listing. It does so utilizing a product tip field.
// If product tip exists and there are no products in the product list try a detail query
if (count($products) === 0 && !($tipProductCode === null)) {
if (count($products) === 0 && $tipProductCode !== null) {
$result[] = $this->queryDetail($tipProductCode);
}
@ -174,11 +174,11 @@ class LCSCProvider implements InfoProviderInterface
{
// Get product images in advance
$product_images = $this->getProductImages($product['productImages'] ?? null);
$product['productImageUrl'] = $product['productImageUrl'] ?? null;
$product['productImageUrl'] ??= null;
// If the product does not have a product image but otherwise has attached images, use the first one.
if (count($product_images) > 0) {
$product['productImageUrl'] = $product['productImageUrl'] ?? $product_images[0]->url;
$product['productImageUrl'] ??= $product_images[0]->url;
}
// LCSC puts HTML in footprints and descriptions sometimes randomly
@ -321,7 +321,7 @@ class LCSCProvider implements InfoProviderInterface
foreach ($attributes as $attribute) {
//Skip this attribute if it's empty
if (in_array(trim($attribute['paramValueEn']), array('', '-'), true)) {
if (in_array(trim((string) $attribute['paramValueEn']), ['', '-'], true)) {
continue;
}

View file

@ -74,7 +74,7 @@ class MouserProvider implements InfoProviderInterface
public function isActive(): bool
{
return !empty($this->api_key);
return $this->api_key !== '';
}
public function searchByKeyword(string $keyword): array
@ -247,7 +247,7 @@ class MouserProvider implements InfoProviderInterface
private function parseDataSheets(?string $sheetUrl, ?string $sheetName): ?array
{
if (empty($sheetUrl)) {
if ($sheetUrl === null || $sheetUrl === '' || $sheetUrl === '0') {
return null;
}
$result = [];

View file

@ -183,7 +183,7 @@ class OctopartProvider implements InfoProviderInterface
{
//The client ID has to be set and a token has to be available (user clicked connect)
//return /*!empty($this->clientId) && */ $this->authTokenManager->hasToken(self::OAUTH_APP_NAME);
return !empty($this->clientId) && !empty($this->secret);
return $this->clientId !== '' && $this->secret !== '';
}
private function mapLifeCycleStatus(?string $value): ?ManufacturingStatus
@ -243,11 +243,14 @@ class OctopartProvider implements InfoProviderInterface
//If we encounter the mass spec, we save it for later
if ($spec['attribute']['shortname'] === "weight") {
$mass = (float) $spec['siValue'];
} else if ($spec['attribute']['shortname'] === "case_package") { //Package
} elseif ($spec['attribute']['shortname'] === "case_package") {
//Package
$package = $spec['value'];
} else if ($spec['attribute']['shortname'] === "numberofpins") { //Pin Count
} elseif ($spec['attribute']['shortname'] === "numberofpins") {
//Pin Count
$pinCount = $spec['value'];
} else if ($spec['attribute']['shortname'] === "lifecyclestatus") { //LifeCycleStatus
} elseif ($spec['attribute']['shortname'] === "lifecyclestatus") {
//LifeCycleStatus
$mStatus = $this->mapLifeCycleStatus($spec['value']);
}
@ -295,7 +298,7 @@ class OctopartProvider implements InfoProviderInterface
$category = null;
if (!empty($part['category']['name'])) {
$category = implode(' -> ', array_map(static fn($c) => $c['name'], $part['category']['ancestors'] ?? []));
if (!empty($category)) {
if ($category !== '' && $category !== '0') {
$category .= ' -> ';
}
$category .= $part['category']['name'];

View file

@ -47,7 +47,7 @@ class TMEClient
public function isUsable(): bool
{
return !($this->token === '' || $this->secret === '');
return $this->token !== '' && $this->secret !== '';
}

View file

@ -80,7 +80,7 @@ class TMEProvider implements InfoProviderInterface
$result[] = new SearchResultDTO(
provider_key: $this->getProviderKey(),
provider_id: $product['Symbol'],
name: !empty($product['OriginalSymbol']) ? $product['OriginalSymbol'] : $product['Symbol'],
name: empty($product['OriginalSymbol']) ? $product['Symbol'] : $product['OriginalSymbol'],
description: $product['Description'],
category: $product['Category'],
manufacturer: $product['Producer'],
@ -116,7 +116,7 @@ class TMEProvider implements InfoProviderInterface
return new PartDetailDTO(
provider_key: $this->getProviderKey(),
provider_id: $product['Symbol'],
name: !empty($product['OriginalSymbol']) ? $product['OriginalSymbol'] : $product['Symbol'],
name: empty($product['OriginalSymbol']) ? $product['Symbol'] : $product['OriginalSymbol'],
description: $product['Description'],
category: $product['Category'],
manufacturer: $product['Producer'],

View file

@ -28,6 +28,7 @@ use Com\Tecnick\Barcode\Barcode;
/**
* This function is used to generate barcodes of various types using arbitrary (text) content.
* @see \App\Tests\Services\LabelSystem\Barcodes\BarcodeHelperTest
*/
class BarcodeHelper
{
@ -66,7 +67,7 @@ class BarcodeHelper
{
$svg = $this->barcodeAsSVG($content, $type);
$base64 = $this->dataUri($svg, 'image/svg+xml');
$alt_text = $alt_text ?? $content;
$alt_text ??= $content;
return '<img src="'.$base64.'" width="'.$width.'" style="min-height: 25px;" alt="'.$alt_text.'"/>';
}

View file

@ -48,7 +48,7 @@ use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
/**
* @see \App\Tests\Services\LabelSystem\Barcodes\BarcodeNormalizerTest
* @see \App\Tests\Services\LabelSystem\Barcodes\BarcodeScanHelperTest
*/
final class BarcodeScanHelper
{

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -17,7 +20,6 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Services\LabelSystem;
use Dompdf\Dompdf;
@ -36,10 +38,8 @@ class DompdfFactory implements DompdfFactoryInterface
private function createDirectoryIfNotExisting(string $path): void
{
if (!is_dir($path)) {
if (!mkdir($concurrentDirectory = $path, 0777, true) && !is_dir($concurrentDirectory)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
}
if (!is_dir($path) && (!mkdir($concurrentDirectory = $path, 0777, true) && !is_dir($concurrentDirectory))) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
}
}
@ -51,4 +51,4 @@ class DompdfFactory implements DompdfFactoryInterface
'tempDir' => $this->tmpDirectory,
]);
}
}
}

View file

@ -49,7 +49,7 @@ use App\Services\LabelSystem\Barcodes\BarcodeHelper;
use InvalidArgumentException;
/**
* @see \App\Tests\Services\LabelSystem\BarcodeGeneratorTest
* @see \App\Tests\Services\LabelSystem\LabelBarcodeGeneratorTest
*/
final class LabelBarcodeGenerator
{

View file

@ -119,7 +119,7 @@ final class PartProvider implements PlaceholderProviderInterface
}
if ('[[DESCRIPTION_T]]' === $placeholder) {
return strip_tags($parsedown->line($part->getDescription()));
return strip_tags((string) $parsedown->line($part->getDescription()));
}
if ('[[COMMENT]]' === $placeholder) {
@ -127,7 +127,7 @@ final class PartProvider implements PlaceholderProviderInterface
}
if ('[[COMMENT_T]]' === $placeholder) {
return strip_tags($parsedown->line($part->getComment()));
return strip_tags((string) $parsedown->line($part->getComment()));
}
return null;

View file

@ -52,7 +52,7 @@ final class StructuralDBElementProvider implements PlaceholderProviderInterface
return $label_target->getComment();
}
if ('[[COMMENT_T]]' === $placeholder) {
return strip_tags($label_target->getComment());
return strip_tags((string) $label_target->getComment());
}
if ('[[FULL_PATH]]' === $placeholder) {
return $label_target->getFullPath();

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -17,7 +20,6 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Services\LogSystem;
use InvalidArgumentException;

View file

@ -135,7 +135,7 @@ class LogEntryExtraFormatter
}
if ($context instanceof LogWithCommentInterface && $context->hasComment()) {
$array[] = htmlspecialchars($context->getComment());
$array[] = htmlspecialchars((string) $context->getComment());
}
if ($context instanceof ElementCreatedLogEntry && $context->hasCreationInstockValue()) {
@ -193,7 +193,7 @@ class LogEntryExtraFormatter
htmlspecialchars($this->elementTypeNameGenerator->getLocalizedTypeLabel(PartLot::class))
.' ' . $context->getMoveToTargetID();
}
if ($context->getActionTimestamp()) {
if ($context->getActionTimestamp() !== null) {
$formatter = new \IntlDateFormatter($this->translator->getLocale(), \IntlDateFormatter::SHORT, \IntlDateFormatter::SHORT);
$array['log.part_stock_changed.timestamp'] = $formatter->format($context->getActionTimestamp());
}

View file

@ -47,7 +47,7 @@ final class OAuthTokenManager
$tokenEntity = $this->entityManager->getRepository(OAuthToken::class)->findOneBy(['name' => $app_name]);
//If the token was already existing, we just replace it with the new one
if ($tokenEntity) {
if ($tokenEntity !== null) {
$tokenEntity->replaceWithNewToken($token);
$this->entityManager->flush();
@ -96,7 +96,7 @@ final class OAuthTokenManager
{
$token = $this->getToken($app_name);
if (!$token) {
if ($token === null) {
throw new \RuntimeException('No token was saved yet for '.$app_name);
}
@ -128,7 +128,7 @@ final class OAuthTokenManager
$token = $this->getToken($app_name);
//If the token is not existing, we return null
if (!$token) {
if ($token === null) {
return null;
}

View file

@ -43,7 +43,7 @@ class BannerHelper
if (!is_string($banner)) {
throw new \RuntimeException('The parameter "partdb.banner" must be a string.');
}
if (empty($banner)) {
if ($banner === '') {
$banner_path = $this->project_dir
.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'banner.md';

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/*
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -17,7 +20,6 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace App\Services\UserSystem\TFA;
use Scheb\TwoFactorBundle\Model\Google\TwoFactorInterface;
@ -67,4 +69,4 @@ class DecoratedGoogleAuthenticator implements GoogleAuthenticatorInterface
{
return $this->inner->generateSecret();
}
}
}

View file

@ -29,6 +29,9 @@ use App\Security\ApiTokenAuthenticatedToken;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* @see \App\Tests\Services\UserSystem\VoterHelperTest
*/
final class VoterHelper
{
private readonly UserRepository $userRepository;