Fixed PHPstan issues for level 5.

This commit is contained in:
Jan Böhmer 2020-02-01 19:42:28 +01:00
parent a9293b7ceb
commit da72f5b3ec
24 changed files with 87 additions and 49 deletions

View file

@ -1,5 +1,6 @@
parameters:
inferPrivatePropertyTypeFromConstructor: true
treatPhpDocTypesAsCertain: false
symfony:
container_xml_path: '%rootDir%/../../../var/cache/dev/srcApp_KernelDevDebugContainer.xml'

View file

@ -86,7 +86,7 @@ class CleanAttachmentsCommand extends Command
$table = new Table($output);
$table->setHeaders(['Filename', 'MIME Type', 'Last modified date']);
$dateformatter = IntlDateFormatter::create(null, IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
$dateformatter = IntlDateFormatter::create(\Locale::getDefault(), IntlDateFormatter::SHORT, IntlDateFormatter::SHORT);
foreach ($finder as $file) {
//If not attachment object uses this file, print it

View file

@ -64,14 +64,15 @@ class SetPasswordCommand extends Command
/** @var User[] $users */
$users = $this->entityManager->getRepository(User::class)->findBy(['name' => $user_name]);
$user = $users[0];
if (null === $user) {
if (empty($users)) {
$io->error(sprintf('No user with the given username %s found in the database!', $user_name));
return 1;
}
$user = $users[0];
$io->note('User found!');
$proceed = $io->confirm(

View file

@ -130,7 +130,7 @@ abstract class BaseAdminController extends AbstractController
protected function _new(Request $request, EntityManagerInterface $em, EntityImporter $importer)
{
/** @var StructuralDBElement $new_entity */
/** @var StructuralDBElement|User $new_entity */
$new_entity = new $this->entity_class();
$this->denyAccessUnlessGranted('read', $new_entity);

View file

@ -236,9 +236,9 @@ class UserSettingsController extends AbstractController
],
],
'constraints' => [new Length([
'min' => 6,
'max' => 128,
])],
'min' => 6,
'max' => 128,
])],
])
->add('submit', SubmitType::class, ['label' => 'save'])
->getForm();
@ -278,15 +278,13 @@ class UserSettingsController extends AbstractController
return $this->redirectToRoute('user_settings');
}
if ($google_enabled) {
//Remove secret to disable google authenticator
$user->setGoogleAuthenticatorSecret(null);
$backupCodeManager->disableBackupCodesIfUnused($user);
$em->flush();
$this->addFlash('success', 'user.settings.2fa.google.disabled');
//Remove secret to disable google authenticator
$user->setGoogleAuthenticatorSecret(null);
$backupCodeManager->disableBackupCodesIfUnused($user);
$em->flush();
$this->addFlash('success', 'user.settings.2fa.google.disabled');
return $this->redirectToRoute('user_settings');
}
return $this->redirectToRoute('user_settings');
}
$backup_form = $this->get('form.factory')->createNamedBuilder('backup_codes')->add('reset_codes', SubmitType::class, [

View file

@ -57,7 +57,7 @@ class EntityColumn extends AbstractColumn
return $value;
}
public function configureOptions(OptionsResolver $resolver): void
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
@ -69,7 +69,7 @@ class EntityColumn extends AbstractColumn
$resolver->setDefault('render', function (Options $options) {
return function ($value, Part $context) use ($options) {
/** @var DBElement $entity */
/** @var DBElement|null $entity */
$entity = $this->accessor->getValue($context, $options['property']);
if ($entity) {
@ -83,7 +83,10 @@ class EntityColumn extends AbstractColumn
return sprintf('<i>%s</i>', $value);
}
throw new \InvalidArgumentException('$entity must not be null!');
};
});
return $this;
}
}

View file

@ -58,9 +58,10 @@ class LogEntryTargetColumn extends AbstractColumn
return $value;
}
public function configureOptions(OptionsResolver $resolver): void
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
return $this;
}
public function render($value, $context)

View file

@ -91,8 +91,9 @@ class PartAttachmentsColumn extends AbstractColumn
return $tmp;
}
public function configureOptions(OptionsResolver $resolver): void
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
return $this;
}
}

View file

@ -79,7 +79,7 @@ abstract class Attachment extends NamedDBElement
public const ALLOWED_ELEMENT_CLASS = '';
/**
* @var string the original filename the file had, when the user uploaded it
* @var string|null the original filename the file had, when the user uploaded it
* @ORM\Column(type="string", nullable=true)
*/
protected $original_filename;

View file

@ -43,7 +43,7 @@ abstract class AttachmentContainingDBElement extends NamedDBElement
*
* Mapping is done in sub classes like part
*/
protected $attachments = [];
protected $attachments;
public function __construct()
{

View file

@ -58,7 +58,8 @@ use Symfony\Component\Serializer\Annotation\Groups;
*/
abstract class DBElement
{
/** @var int The Identification number for this part. This value is unique for the element in this table.
/** @var int|null The Identification number for this part. This value is unique for the element in this table.
* Null if the element is not saved to DB yet.
* @ORM\Column(type="integer")
* @ORM\Id()
* @ORM\GeneratedValue()

View file

@ -81,10 +81,11 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement
* We can not define the mapping here or we will get an exception. Unfortunately we have to do the mapping in the
* subclasses.
*
* @var StructuralDBElement[]
* @var StructuralDBElement[]|Collection
* @Groups({"include_children"})
*/
protected $children = [];
protected $children;
/**
* @var StructuralDBElement
* @NoneOfItsChildren()
@ -249,7 +250,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement
/**
* Get all sub elements of this element.
*
* @return Collection<static> all subelements as an array of objects (sorted by their full path)
* @return Collection<static>|iterable all subelements as an array of objects (sorted by their full path)
*/
public function getSubelements(): iterable
{
@ -257,7 +258,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement
}
/**
* @return Collection<static>
* @return Collection<static>|iterable
*/
public function getChildren(): iterable
{
@ -311,9 +312,17 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement
return $this;
}
public function setChildren(array $element): self
/**
* @param static[]|Collection $elements
* @return $this
*/
public function setChildren($elements): self
{
$this->children = $element;
if (!is_array($elements) && !$elements instanceof Collection) {
throw new InvalidArgumentException('$elements must be an array or Collection!');
}
$this->children = $elements;
return $this;
}

View file

@ -93,7 +93,7 @@ class Supplier extends Company
protected $default_currency;
/**
* @var float|null the shipping costs that have to be paid, when ordering via this supplier
* @var string|null the shipping costs that have to be paid, when ordering via this supplier
* @ORM\Column(name="shipping_costs", nullable=true, type="decimal", precision=11, scale=5)
* @Assert\PositiveOrZero()
*/

View file

@ -109,7 +109,7 @@ class Pricedetail extends DBElement
protected $manual_input = true;
/**
* @var Orderdetail
* @var Orderdetail|null
* @ORM\ManyToOne(targetEntity="Orderdetail", inversedBy="pricedetails")
* @ORM\JoinColumn(name="orderdetails_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
* @Assert\NotNull()

View file

@ -103,9 +103,10 @@ class U2FKey implements TwoFactorKeyInterface
return $this->keyHandle;
}
public function setKeyHandle($keyHandle): void
public function setKeyHandle($keyHandle): self
{
$this->keyHandle = $keyHandle;
return $this;
}
public function getPublicKey()
@ -113,9 +114,10 @@ class U2FKey implements TwoFactorKeyInterface
return $this->publicKey;
}
public function setPublicKey($publicKey): void
public function setPublicKey($publicKey): self
{
$this->publicKey = $publicKey;
return $this;
}
public function getCertificate()
@ -123,9 +125,10 @@ class U2FKey implements TwoFactorKeyInterface
return $this->certificate;
}
public function setCertificate($certificate): void
public function setCertificate($certificate): self
{
$this->certificate = $certificate;
return $this;
}
public function getCounter()
@ -133,9 +136,10 @@ class U2FKey implements TwoFactorKeyInterface
return $this->counter;
}
public function setCounter($counter): void
public function setCounter($counter): self
{
$this->counter = $counter;
return $this;
}
public function getName()
@ -143,9 +147,10 @@ class U2FKey implements TwoFactorKeyInterface
return $this->name;
}
public function setName($name): void
public function setName($name): self
{
$this->name = $name;
return $this;
}
/**
@ -173,7 +178,7 @@ class U2FKey implements TwoFactorKeyInterface
*
* @return $this
*/
public function setUser(TwoFactorInterface $new_user): self
public function setUser(User $new_user): self
{
$this->user = $new_user;

View file

@ -234,7 +234,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe
*/
protected $attachments;
/** @var DateTime The time when the backup codes were generated
/** @var DateTime|null The time when the backup codes were generated
* @ORM\Column(type="datetime", nullable=true)
*/
protected $backupCodesGenerationDate;
@ -351,9 +351,9 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe
/**
* @see UserInterface
*/
public function getSalt(): void
public function getSalt(): ?string
{
// not needed when using the "bcrypt" algorithm in security.yaml
return null;
}
/**

View file

@ -67,6 +67,6 @@ final class SymfonyDebugToolbarSubscriber implements EventSubscriberInterface
}
$response = $event->getResponse();
$response->headers->set('Symfony-Debug-Toolbar-Replace', 1);
$response->headers->set('Symfony-Debug-Toolbar-Replace', '1');
}
}

View file

@ -25,6 +25,7 @@ declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\UserSystem\U2FKey;
use App\Entity\UserSystem\User;
use Doctrine\ORM\EntityManagerInterface;
use R\U2FTwoFactorBundle\Event\RegisterEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
@ -63,6 +64,10 @@ final class U2FRegistrationSubscriber implements EventSubscriberInterface
//Skip adding of U2F key on demo mode
if (! $this->demo_mode) {
$user = $event->getUser();
if (!$user instanceof User) {
throw new \InvalidArgumentException("Only User objects can be registered for U2F!");
}
$registration = $event->getRegistration();
$newKey = new U2FKey();
$newKey->fromRegistrationData($registration);

View file

@ -26,6 +26,7 @@ namespace App\Helpers\Trees;
use App\Entity\Base\StructuralDBElement;
use ArrayIterator;
use Doctrine\Common\Collections\Collection;
use RecursiveIterator;
final class StructuralDBElementIterator extends ArrayIterator implements RecursiveIterator
@ -48,6 +49,15 @@ final class StructuralDBElementIterator extends ArrayIterator implements Recursi
/** @var StructuralDBElement $element */
$element = $this->current();
return new self($element->getSubelements()->toArray());
$subelements = $element->getSubelements();
if (is_array($subelements)) {
$array = $subelements;
} elseif ($subelements instanceof Collection) {
$array = $subelements->toArray();
} else {
throw new \InvalidArgumentException('Invalid subelements type on $element!');
}
return new self($array);
}
}

View file

@ -91,7 +91,7 @@ class AttachmentReverseSearch
$this->cacheManager->remove($this->attachmentURLGenerator->absolutePathToAssetPath($file->getPathname()));
$fs = new Filesystem();
$fs->remove($file);
$fs->remove($file->getPathname());
return true;
}

View file

@ -25,6 +25,7 @@ declare(strict_types=1);
namespace App\Services;
use App\Entity\Base\StructuralDBElement;
use Symfony\Bundle\MakerBundle\Str;
use function count;
use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
@ -133,7 +134,7 @@ class EntityImporter
$tmp = $this->validator->validate($entity);
//When no validation error occured, persist entity to database (cascade must be set in entity)
if (0 === count($errors)) {
if (empty($tmp)) {
$this->em->persist($entity);
} else { //Log validation errors to global log.
$errors[$entity->getFullPath()] = $tmp;
@ -210,7 +211,7 @@ 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|StructuralDBElement $parent the parent, to which the entity should be set
*/
protected function correctParentEntites(iterable $entities, $parent = null): void
{

View file

@ -96,19 +96,19 @@ class PasswordResetManager
/**
* Sets the new password of the user with the given name, if the token is valid.
*
* @param string $user The name of the user, which password should be reset
* @param string $username The name of the user, which password should be reset
* @param string $token The token that should be used to reset the password
* @param string $new_password The new password that should be applied to user
*
* @return bool Returns true, if the new password was applied. False, if either the username is unknown or the
* token is invalid or expired.
*/
public function setNewPassword(string $user, string $token, string $new_password): bool
public function setNewPassword(string $username, string $token, string $new_password): bool
{
//Try to find the user
$repo = $this->em->getRepository(User::class);
/** @var User $user */
$user = $repo->findOneBy(['name' => $user]);
/** @var User|null $user */
$user = $repo->findOneBy(['name' => $username]);
//If no user matching the name, show an error message
if (null === $user) {

View file

@ -25,6 +25,7 @@ declare(strict_types=1);
namespace App\Services;
use App\Configuration\PermissionsConfiguration;
use App\Entity\UserSystem\Group;
use App\Entity\UserSystem\User;
use App\Security\Interfaces\HasPermissionsInterface;
use Symfony\Component\Config\ConfigCache;
@ -109,6 +110,7 @@ class PermissionResolver
return $allowed;
}
/** @var HasPermissionsInterface $parent */
$parent = $user->getGroup();
while (null !== $parent) { //The top group, has parent == null
//Check if our current element gives a info about disallow/allow

View file

@ -191,7 +191,7 @@ class PricedetailHelper
$val_base = $value;
if (null !== $originCurrency) {
//Without an exchange rate we can not calculate the exchange rate
if (0 === (float) $originCurrency->getExchangeRate()) {
if (0.0 === (float) $originCurrency->getExchangeRate()) {
return null;
}