Fixed coding style.

This commit is contained in:
Jan Böhmer 2020-02-01 16:17:20 +01:00
parent 0a94689d98
commit f2ff77a8b3
44 changed files with 435 additions and 387 deletions

View file

@ -6,7 +6,7 @@ parameters:
- "clean-code" - "clean-code"
- "common" - "common"
# very nice to have ↓ # very nice to have ↓
- "symplify" # - "symplify"
- "symfony" - "symfony"
skip: skip:

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,7 +24,6 @@
namespace App\Command; namespace App\Command;
use App\Entity\Base\NamedDBElement; use App\Entity\Base\NamedDBElement;
use App\Entity\LogSystem\AbstractLogEntry; use App\Entity\LogSystem\AbstractLogEntry;
use App\Services\ElementTypeNameGenerator; use App\Services\ElementTypeNameGenerator;
@ -56,18 +58,6 @@ class ShowEventLogCommand extends Command
parent::__construct(); parent::__construct();
} }
protected function configure()
{
$this
->setDescription('List the last event log entries.')
->addOption('count', 'c', InputOption::VALUE_REQUIRED, 'How many log entries should be shown per page.', 50 )
->addOption('oldest_first', null, InputOption::VALUE_NONE,'Show older entries first.')
->addOption('page', 'p', InputOption::VALUE_REQUIRED, 'Which page should be shown?', 1)
->addOption('onePage', null, InputOption::VALUE_NONE, 'Show only one page (dont ask to go to next).')
->addOption('showExtra', 'x', InputOption::VALUE_NONE, 'Show a column with the extra data.');
;
}
public function execute(InputInterface $input, OutputInterface $output) public function execute(InputInterface $input, OutputInterface $output)
{ {
$io = new SymfonyStyle($input, $output); $io = new SymfonyStyle($input, $output);
@ -83,11 +73,12 @@ class ShowEventLogCommand extends Command
$max_page = ceil($total_count / $limit); $max_page = ceil($total_count / $limit);
if ($page > $max_page) { if ($page > $max_page) {
$io->error("There is no page $page! The maximum page is $max_page."); $io->error("There is no page ${page}! The maximum page is ${max_page}.");
return 1; return 1;
} }
$io->note("There are a total of $total_count log entries in the DB."); $io->note("There are a total of ${total_count} log entries in the DB.");
$continue = true; $continue = true;
while ($continue && $page <= $max_page) { while ($continue && $page <= $max_page) {
@ -98,12 +89,23 @@ class ShowEventLogCommand extends Command
} }
$continue = $io->confirm('Do you want to show the next page?'); $continue = $io->confirm('Do you want to show the next page?');
$page++; ++$page;
} }
return 0; return 0;
} }
protected function configure(): void
{
$this
->setDescription('List the last event log entries.')
->addOption('count', 'c', InputOption::VALUE_REQUIRED, 'How many log entries should be shown per page.', 50)
->addOption('oldest_first', null, InputOption::VALUE_NONE, 'Show older entries first.')
->addOption('page', 'p', InputOption::VALUE_REQUIRED, 'Which page should be shown?', 1)
->addOption('onePage', null, InputOption::VALUE_NONE, 'Show only one page (dont ask to go to next).')
->addOption('showExtra', 'x', InputOption::VALUE_NONE, 'Show a column with the extra data.');
}
protected function showPage(OutputInterface $output, bool $desc, int $limit, int $page, int $max_page, bool $showExtra): void protected function showPage(OutputInterface $output, bool $desc, int $limit, int $page, int $max_page, bool $showExtra): void
{ {
$sorting = $desc ? 'ASC' : 'DESC'; $sorting = $desc ? 'ASC' : 'DESC';
@ -113,7 +115,7 @@ class ShowEventLogCommand extends Command
$entries = $this->repo->getLogsOrderedByTimestamp($sorting, $limit, $offset); $entries = $this->repo->getLogsOrderedByTimestamp($sorting, $limit, $offset);
$table = new Table($output); $table = new Table($output);
$table->setHeaderTitle("Page $page / $max_page"); $table->setHeaderTitle("Page ${page} / ${max_page}");
$headers = ['ID', 'Timestamp', 'Type', 'User', 'Target Type', 'Target']; $headers = ['ID', 'Timestamp', 'Type', 'User', 'Target Type', 'Target'];
if ($showExtra) { if ($showExtra) {
$headers[] = 'Extra data'; $headers[] = 'Extra data';
@ -130,15 +132,15 @@ class ShowEventLogCommand extends Command
protected function addTableRow(Table $table, AbstractLogEntry $entry, bool $showExtra): void protected function addTableRow(Table $table, AbstractLogEntry $entry, bool $showExtra): void
{ {
$target = $this->repo->getTargetElement($entry); $target = $this->repo->getTargetElement($entry);
$target_name = ""; $target_name = '';
if ($target instanceof NamedDBElement) { if ($target instanceof NamedDBElement) {
$target_name = $target->getName() . ' <info>(' . $target->getID() . ')</info>'; $target_name = $target->getName().' <info>('.$target->getID().')</info>';
} elseif ($entry->getTargetID()) { } elseif ($entry->getTargetID()) {
$target_name = '<info>(' . $entry->getTargetID() . ')</info>'; $target_name = '<info>('.$entry->getTargetID().')</info>';
} }
$target_class = ""; $target_class = '';
if ($entry->getTargetClass() !== null) { if (null !== $entry->getTargetClass()) {
$target_class = $this->elementTypeNameGenerator->getLocalizedTypeLabel($entry->getTargetClass()); $target_class = $this->elementTypeNameGenerator->getLocalizedTypeLabel($entry->getTargetClass());
} }
@ -148,7 +150,7 @@ class ShowEventLogCommand extends Command
$entry->getType(), $entry->getType(),
$entry->getUser()->getFullName(true), $entry->getUser()->getFullName(true),
$target_class, $target_class,
$target_name $target_name,
]; ];
if ($showExtra) { if ($showExtra) {

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,10 +24,7 @@
namespace App\Controller; namespace App\Controller;
use App\DataTables\LogDataTable; use App\DataTables\LogDataTable;
use App\DataTables\PartsDataTable;
use App\Entity\Parts\Category;
use Omines\DataTablesBundle\DataTableFactory; use Omines\DataTablesBundle\DataTableFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
@ -54,7 +54,7 @@ class LogController extends AbstractController
} }
return $this->render('LogSystem/log_list.html.twig', [ return $this->render('LogSystem/log_list.html.twig', [
'datatable' => $table 'datatable' => $table,
]); ]);
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -34,35 +37,72 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* Similar to ORMAdapter this class allows to access objects from the doctrine ORM. * Similar to ORMAdapter this class allows to access objects from the doctrine ORM.
* Unlike the default ORMAdapter supports Fetch Joins (additional entites are fetched from DB via joins) using * Unlike the default ORMAdapter supports Fetch Joins (additional entites are fetched from DB via joins) using
* the Doctrine Paginator. * the Doctrine Paginator.
*
* @author Jan Böhmer * @author Jan Böhmer
*/ */
class FetchJoinORMAdapter extends ORMAdapter class FetchJoinORMAdapter extends ORMAdapter
{ {
protected $use_simple_total; protected $use_simple_total;
public function configure(array $options) public function configure(array $options): void
{ {
parent::configure($options); parent::configure($options);
$this->use_simple_total = $options['simple_total_query']; $this->use_simple_total = $options['simple_total_query'];
} }
protected function configureOptions(OptionsResolver $resolver) public function getResults(AdapterQuery $query): \Traversable
{
$builder = $query->get('qb');
$state = $query->getState();
// Apply definitive view state for current 'page' of the table
foreach ($state->getOrderBy() as [$column, $direction]) {
/** @var AbstractColumn $column */
if ($column->isOrderable()) {
$builder->addOrderBy($column->getOrderField(), $direction);
}
}
if ($state->getLength() > 0) {
$builder
->setFirstResult($state->getStart())
->setMaxResults($state->getLength());
}
$query = $builder->getQuery();
$event = new ORMAdapterQueryEvent($query);
$state->getDataTable()->getEventDispatcher()->dispatch($event, ORMAdapterEvents::PRE_QUERY);
//Use Doctrine paginator for result iteration
$paginator = new Paginator($query);
foreach ($paginator->getIterator() as $result) {
yield $result;
$this->manager->detach($result);
}
}
public function getCount(QueryBuilder $queryBuilder, $identifier)
{
$paginator = new Paginator($queryBuilder);
return $paginator->count();
}
protected function configureOptions(OptionsResolver $resolver): void
{ {
parent::configureOptions($resolver); parent::configureOptions($resolver);
//Enforce object hydration mode (fetch join only works for objects) //Enforce object hydration mode (fetch join only works for objects)
$resolver->addAllowedValues('hydrate', Query::HYDRATE_OBJECT); $resolver->addAllowedValues('hydrate', Query::HYDRATE_OBJECT);
/** /*
* Add the possibility to replace the query for total entity count through a very simple one, to improve performance. * Add the possibility to replace the query for total entity count through a very simple one, to improve performance.
* You can only use this option, if you did not apply any criteria to your total count. * You can only use this option, if you did not apply any criteria to your total count.
*/ */
$resolver->setDefault('simple_total_query', false); $resolver->setDefault('simple_total_query', false);
return $resolver;
} }
protected function prepareQuery(AdapterQuery $query) protected function prepareQuery(AdapterQuery $query): void
{ {
$state = $query->getState(); $state = $query->getState();
$query->set('qb', $builder = $this->createQueryBuilder($state)); $query->set('qb', $builder = $this->createQueryBuilder($state));
@ -96,43 +136,6 @@ class FetchJoinORMAdapter extends ORMAdapter
$query->setIdentifierPropertyPath($this->mapFieldToPropertyPath($identifier, $aliases)); $query->setIdentifierPropertyPath($this->mapFieldToPropertyPath($identifier, $aliases));
} }
public function getResults(AdapterQuery $query): \Traversable
{
$builder = $query->get('qb');
$state = $query->getState();
// Apply definitive view state for current 'page' of the table
foreach ($state->getOrderBy() as list($column, $direction)) {
/** @var AbstractColumn $column */
if ($column->isOrderable()) {
$builder->addOrderBy($column->getOrderField(), $direction);
}
}
if ($state->getLength() > 0) {
$builder
->setFirstResult($state->getStart())
->setMaxResults($state->getLength());
}
$query = $builder->getQuery();
$event = new ORMAdapterQueryEvent($query);
$state->getDataTable()->getEventDispatcher()->dispatch($event, ORMAdapterEvents::PRE_QUERY);
//Use Doctrine paginator for result iteration
$paginator = new Paginator($query);
foreach ($paginator->getIterator() as $result) {
yield $result;
$this->manager->detach($result);
}
}
public function getCount(QueryBuilder $queryBuilder, $identifier)
{
$paginator = new Paginator($queryBuilder);
return $paginator->count();
}
protected function getSimpleTotalCount(QueryBuilder $queryBuilder) protected function getSimpleTotalCount(QueryBuilder $queryBuilder)
{ {
/** The paginator count queries can be rather slow, so when query for total count (100ms or longer), /** The paginator count queries can be rather slow, so when query for total count (100ms or longer),
@ -140,6 +143,7 @@ class FetchJoinORMAdapter extends ORMAdapter
*/ */
/** @var Query\Expr\From $from_expr */ /** @var Query\Expr\From $from_expr */
$from_expr = $queryBuilder->getDQLPart('from')[0]; $from_expr = $queryBuilder->getDQLPart('from')[0];
return $this->manager->getRepository($from_expr->getFrom())->count([]); return $this->manager->getRepository($from_expr->getFrom())->count([]);
} }
} }

View file

@ -37,28 +37,27 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
*/ */
class ORMAdapter extends AbstractAdapter class ORMAdapter extends AbstractAdapter
{ {
/** @var ManagerRegistry */
private $registry;
/** @var EntityManager */ /** @var EntityManager */
protected $manager; protected $manager;
/** @var \Doctrine\ORM\Mapping\ClassMetadata */ /** @var \Doctrine\ORM\Mapping\ClassMetadata */
protected $metadata; protected $metadata;
/** @var QueryBuilderProcessorInterface[] */
protected $criteriaProcessors;
/** @var ManagerRegistry */
private $registry;
/** @var int */ /** @var int */
private $hydrationMode; private $hydrationMode;
/** @var QueryBuilderProcessorInterface[] */ /** @var QueryBuilderProcessorInterface[] */
private $queryBuilderProcessors; private $queryBuilderProcessors;
/** @var QueryBuilderProcessorInterface[] */
protected $criteriaProcessors;
/** /**
* DoctrineAdapter constructor. * DoctrineAdapter constructor.
*/ */
public function __construct(ManagerRegistry $registry = null) public function __construct(?ManagerRegistry $registry = null)
{ {
if (null === $registry) { if (null === $registry) {
throw new MissingDependencyException('Install doctrine/doctrine-bundle to use the ORMAdapter'); throw new MissingDependencyException('Install doctrine/doctrine-bundle to use the ORMAdapter');
@ -68,10 +67,7 @@ class ORMAdapter extends AbstractAdapter
$this->registry = $registry; $this->registry = $registry;
} }
/** public function configure(array $options): void
* {@inheritdoc}
*/
public function configure(array $options)
{ {
$resolver = new OptionsResolver(); $resolver = new OptionsResolver();
$this->configureOptions($resolver); $this->configureOptions($resolver);
@ -92,15 +88,12 @@ class ORMAdapter extends AbstractAdapter
$this->criteriaProcessors = $options['criteria']; $this->criteriaProcessors = $options['criteria'];
} }
/** public function addCriteriaProcessor($processor): void
* @param mixed $processor
*/
public function addCriteriaProcessor($processor)
{ {
$this->criteriaProcessors[] = $this->normalizeProcessor($processor); $this->criteriaProcessors[] = $this->normalizeProcessor($processor);
} }
protected function prepareQuery(AdapterQuery $query) protected function prepareQuery(AdapterQuery $query): void
{ {
$state = $query->getState(); $state = $query->getState();
$query->set('qb', $builder = $this->createQueryBuilder($state)); $query->set('qb', $builder = $this->createQueryBuilder($state));
@ -150,7 +143,7 @@ class ORMAdapter extends AbstractAdapter
continue; continue;
} }
list($origin, $target) = explode('.', $join->getJoin()); [$origin, $target] = explode('.', $join->getJoin());
$mapping = $aliases[$origin][1]->getAssociationMapping($target); $mapping = $aliases[$origin][1]->getAssociationMapping($target);
$aliases[$join->getAlias()] = [$join->getJoin(), $this->manager->getMetadataFactory()->getMetadataFor($mapping['targetEntity'])]; $aliases[$join->getAlias()] = [$join->getJoin(), $this->manager->getMetadataFactory()->getMetadataFor($mapping['targetEntity'])];
@ -160,9 +153,6 @@ class ORMAdapter extends AbstractAdapter
return $aliases; return $aliases;
} }
/**
* {@inheritdoc}
*/
protected function mapPropertyPath(AdapterQuery $query, AbstractColumn $column) protected function mapPropertyPath(AdapterQuery $query, AbstractColumn $column)
{ {
return $this->mapFieldToPropertyPath($column->getField(), $query->get('aliases')); return $this->mapFieldToPropertyPath($column->getField(), $query->get('aliases'));
@ -175,7 +165,7 @@ class ORMAdapter extends AbstractAdapter
$state = $query->getState(); $state = $query->getState();
// Apply definitive view state for current 'page' of the table // Apply definitive view state for current 'page' of the table
foreach ($state->getOrderBy() as list($column, $direction)) { foreach ($state->getOrderBy() as [$column, $direction]) {
/** @var AbstractColumn $column */ /** @var AbstractColumn $column */
if ($column->isOrderable()) { if ($column->isOrderable()) {
$builder->addOrderBy($column->getOrderField(), $direction); $builder->addOrderBy($column->getOrderField(), $direction);
@ -200,7 +190,7 @@ class ORMAdapter extends AbstractAdapter
} }
} }
protected function buildCriteria(QueryBuilder $queryBuilder, DataTableState $state) protected function buildCriteria(QueryBuilder $queryBuilder, DataTableState $state): void
{ {
foreach ($this->criteriaProcessors as $provider) { foreach ($this->criteriaProcessors as $provider) {
$provider->process($queryBuilder, $state); $provider->process($queryBuilder, $state);
@ -222,6 +212,7 @@ class ORMAdapter extends AbstractAdapter
/** /**
* @param $identifier * @param $identifier
*
* @return int * @return int
*/ */
protected function getCount(QueryBuilder $queryBuilder, $identifier) protected function getCount(QueryBuilder $queryBuilder, $identifier)
@ -230,21 +221,21 @@ class ORMAdapter extends AbstractAdapter
$qb->resetDQLPart('orderBy'); $qb->resetDQLPart('orderBy');
$gb = $qb->getDQLPart('groupBy'); $gb = $qb->getDQLPart('groupBy');
if (empty($gb) || !$this->hasGroupByPart($identifier, $gb)) { if (empty($gb) || ! $this->hasGroupByPart($identifier, $gb)) {
$qb->select($qb->expr()->count($identifier)); $qb->select($qb->expr()->count($identifier));
return (int) $qb->getQuery()->getSingleScalarResult(); return (int) $qb->getQuery()->getSingleScalarResult();
} else { }
$qb->resetDQLPart('groupBy'); $qb->resetDQLPart('groupBy');
$qb->select($qb->expr()->countDistinct($identifier)); $qb->select($qb->expr()->countDistinct($identifier));
return (int) $qb->getQuery()->getSingleScalarResult(); return (int) $qb->getQuery()->getSingleScalarResult();
} }
}
/** /**
* @param $identifier * @param $identifier
* @param Query\Expr\GroupBy[] $gbList * @param Query\Expr\GroupBy[] $gbList
*
* @return bool * @return bool
*/ */
protected function hasGroupByPart($identifier, array $gbList) protected function hasGroupByPart($identifier, array $gbList)
@ -260,6 +251,7 @@ class ORMAdapter extends AbstractAdapter
/** /**
* @param string $field * @param string $field
*
* @return string * @return string
*/ */
protected function mapFieldToPropertyPath($field, array $aliases = []) protected function mapFieldToPropertyPath($field, array $aliases = [])
@ -268,25 +260,25 @@ class ORMAdapter extends AbstractAdapter
if (count($parts) < 2) { if (count($parts) < 2) {
throw new InvalidConfigurationException(sprintf("Field name '%s' must consist at least of an alias and a field separated with a period", $field)); throw new InvalidConfigurationException(sprintf("Field name '%s' must consist at least of an alias and a field separated with a period", $field));
} }
list($origin, $target) = $parts; [$origin, $target] = $parts;
$path = [$target]; $path = [$target];
$current = $aliases[$origin][0]; $current = $aliases[$origin][0];
while (null !== $current) { while (null !== $current) {
list($origin, $target) = explode('.', $current); [$origin, $target] = explode('.', $current);
$path[] = $target; $path[] = $target;
$current = $aliases[$origin][0]; $current = $aliases[$origin][0];
} }
if (Query::HYDRATE_ARRAY === $this->hydrationMode) { if (Query::HYDRATE_ARRAY === $this->hydrationMode) {
return '[' . implode('][', array_reverse($path)) . ']'; return '['.implode('][', array_reverse($path)).']';
} else {
return implode('.', array_reverse($path));
}
} }
protected function configureOptions(OptionsResolver $resolver) return implode('.', array_reverse($path));
}
protected function configureOptions(OptionsResolver $resolver): void
{ {
$providerNormalizer = function (Options $options, $value) { $providerNormalizer = function (Options $options, $value) {
return array_map([$this, 'normalizeProcessor'], (array) $value); return array_map([$this, 'normalizeProcessor'], (array) $value);
@ -312,6 +304,7 @@ class ORMAdapter extends AbstractAdapter
/** /**
* @param callable|QueryBuilderProcessorInterface $provider * @param callable|QueryBuilderProcessorInterface $provider
*
* @return QueryBuilderProcessorInterface * @return QueryBuilderProcessorInterface
*/ */
private function normalizeProcessor($provider) private function normalizeProcessor($provider)

View file

@ -40,11 +40,11 @@ use Symfony\Contracts\Translation\TranslatorInterface;
final class AttachmentDataTable implements DataTableTypeInterface final class AttachmentDataTable implements DataTableTypeInterface
{ {
protected $translator; private $translator;
protected $entityURLGenerator; private $entityURLGenerator;
protected $attachmentHelper; private $attachmentHelper;
protected $elementTypeNameGenerator; private $elementTypeNameGenerator;
protected $attachmentURLGenerator; private $attachmentURLGenerator;
public function __construct(TranslatorInterface $translator, EntityURLGenerator $entityURLGenerator, public function __construct(TranslatorInterface $translator, EntityURLGenerator $entityURLGenerator,
AttachmentManager $attachmentHelper, AttachmentURLGenerator $attachmentURLGenerator, AttachmentManager $attachmentHelper, AttachmentURLGenerator $attachmentURLGenerator,
@ -203,7 +203,7 @@ final class AttachmentDataTable implements DataTableTypeInterface
]); ]);
} }
protected function getQuery(QueryBuilder $builder): void private function getQuery(QueryBuilder $builder): void
{ {
$builder->distinct()->select('attachment') $builder->distinct()->select('attachment')
->addSelect('attachment_type') ->addSelect('attachment_type')

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,16 +24,6 @@
namespace App\DataTables\Column; namespace App\DataTables\Column;
use App\Entity\LogSystem\DatabaseUpdatedLogEntry;
use App\Entity\LogSystem\ElementCreatedLogEntry;
use App\Entity\LogSystem\ElementDeletedLogEntry;
use App\Entity\LogSystem\ElementEditedLogEntry;
use App\Entity\LogSystem\ExceptionLogEntry;
use App\Entity\LogSystem\InstockChangedLogEntry;
use App\Entity\LogSystem\UserLoginLogEntry;
use App\Entity\LogSystem\UserLogoutLogEntry;
use App\Entity\LogSystem\UserNotAllowedLogEntry;
use App\Services\LogSystem\LogEntryExtraFormatter; use App\Services\LogSystem\LogEntryExtraFormatter;
use Omines\DataTablesBundle\Column\AbstractColumn; use Omines\DataTablesBundle\Column\AbstractColumn;
use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface;
@ -46,9 +39,6 @@ class LogEntryExtraColumn extends AbstractColumn
$this->formatter = $formatter; $this->formatter = $formatter;
} }
/**
* @inheritDoc
*/
public function normalize($value) public function normalize($value)
{ {
return $value; return $value;

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -24,7 +27,6 @@ namespace App\DataTables\Column;
use App\Entity\Base\DBElement; use App\Entity\Base\DBElement;
use App\Entity\Base\NamedDBElement; use App\Entity\Base\NamedDBElement;
use App\Entity\LogSystem\AbstractLogEntry; use App\Entity\LogSystem\AbstractLogEntry;
use App\Repository\LogEntryRepository;
use App\Services\ElementTypeNameGenerator; use App\Services\ElementTypeNameGenerator;
use App\Services\EntityURLGenerator; use App\Services\EntityURLGenerator;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@ -34,7 +36,6 @@ use Symfony\Contracts\Translation\TranslatorInterface;
class LogEntryTargetColumn extends AbstractColumn class LogEntryTargetColumn extends AbstractColumn
{ {
protected $em; protected $em;
protected $entryRepository; protected $entryRepository;
protected $entityURLGenerator; protected $entityURLGenerator;
@ -52,15 +53,12 @@ class LogEntryTargetColumn extends AbstractColumn
$this->translator = $translator; $this->translator = $translator;
} }
/**
* @inheritDoc
*/
public function normalize($value) public function normalize($value)
{ {
return $value; return $value;
} }
public function configureOptions(OptionsResolver $resolver) public function configureOptions(OptionsResolver $resolver): void
{ {
parent::configureOptions($resolver); parent::configureOptions($resolver);
} }
@ -89,7 +87,7 @@ class LogEntryTargetColumn extends AbstractColumn
} }
//Element was deleted //Element was deleted
if ($target === null && $context->hasTarget()) { if (null === $target && $context->hasTarget()) {
return sprintf( return sprintf(
'<i>%s</i>: %s [%s]', '<i>%s</i>: %s [%s]',
$this->elementTypeNameGenerator->getLocalizedTypeLabel($context->getTargetClass()), $this->elementTypeNameGenerator->getLocalizedTypeLabel($context->getTargetClass()),
@ -99,6 +97,6 @@ class LogEntryTargetColumn extends AbstractColumn
} }
//Log is not associated with an element //Log is not associated with an element
return ""; return '';
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,14 +24,10 @@
namespace App\DataTables; namespace App\DataTables;
use App\DataTables\Column\EntityColumn;
use App\DataTables\Column\LocaleDateTimeColumn; use App\DataTables\Column\LocaleDateTimeColumn;
use App\DataTables\Column\LogEntryExtraColumn; use App\DataTables\Column\LogEntryExtraColumn;
use App\DataTables\Column\LogEntryTargetColumn; use App\DataTables\Column\LogEntryTargetColumn;
use App\Entity\Attachments\Attachment;
use App\Entity\LogSystem\AbstractLogEntry; use App\Entity\LogSystem\AbstractLogEntry;
use App\Entity\UserSystem\User;
use App\Services\ElementTypeNameGenerator; use App\Services\ElementTypeNameGenerator;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter; use Omines\DataTablesBundle\Adapter\Doctrine\ORMAdapter;
@ -36,7 +35,6 @@ use Omines\DataTablesBundle\Column\TextColumn;
use Omines\DataTablesBundle\DataTable; use Omines\DataTablesBundle\DataTable;
use Omines\DataTablesBundle\DataTableTypeInterface; use Omines\DataTablesBundle\DataTableTypeInterface;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
use SebastianBergmann\CodeCoverage\Report\Text;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface;
@ -54,7 +52,7 @@ class LogDataTable implements DataTableTypeInterface
$this->urlGenerator = $urlGenerator; $this->urlGenerator = $urlGenerator;
} }
public function configure(DataTable $dataTable, array $options) public function configure(DataTable $dataTable, array $options): void
{ {
$dataTable->add('symbol', TextColumn::class, [ $dataTable->add('symbol', TextColumn::class, [
'label' => '', 'label' => '',
@ -62,35 +60,44 @@ class LogDataTable implements DataTableTypeInterface
switch ($context->getLevelString()) { switch ($context->getLevelString()) {
case LogLevel::DEBUG: case LogLevel::DEBUG:
$symbol = 'fa-bug'; $symbol = 'fa-bug';
break; break;
case LogLevel::INFO: case LogLevel::INFO:
$symbol = 'fa-info'; $symbol = 'fa-info';
break; break;
case LogLevel::NOTICE: case LogLevel::NOTICE:
$symbol = 'fa-flag'; $symbol = 'fa-flag';
break; break;
case LogLevel::WARNING: case LogLevel::WARNING:
$symbol = 'fa-exclamation-circle'; $symbol = 'fa-exclamation-circle';
break; break;
case LogLevel::ERROR: case LogLevel::ERROR:
$symbol = 'fa-exclamation-triangle'; $symbol = 'fa-exclamation-triangle';
break; break;
case LogLevel::CRITICAL: case LogLevel::CRITICAL:
$symbol = 'fa-bolt'; $symbol = 'fa-bolt';
break; break;
case LogLevel::ALERT: case LogLevel::ALERT:
$symbol = 'fa-radiation'; $symbol = 'fa-radiation';
break; break;
case LogLevel::EMERGENCY: case LogLevel::EMERGENCY:
$symbol = 'fa-skull-crossbones'; $symbol = 'fa-skull-crossbones';
break; break;
default: default:
$symbol = 'fa-question-circle'; $symbol = 'fa-question-circle';
break; break;
} }
return sprintf('<i class="fas fa-fw %s"></i>', $symbol); return sprintf('<i class="fas fa-fw %s"></i>', $symbol);
} },
]); ]);
$dataTable->add('id', TextColumn::class, [ $dataTable->add('id', TextColumn::class, [
@ -100,16 +107,15 @@ class LogDataTable implements DataTableTypeInterface
$dataTable->add('timestamp', LocaleDateTimeColumn::class, [ $dataTable->add('timestamp', LocaleDateTimeColumn::class, [
'label' => $this->translator->trans('log.timestamp'), 'label' => $this->translator->trans('log.timestamp'),
'timeFormat' => 'medium' 'timeFormat' => 'medium',
]); ]);
$dataTable->add('type', TextColumn::class, [ $dataTable->add('type', TextColumn::class, [
'label' => $this->translator->trans('log.type'), 'label' => $this->translator->trans('log.type'),
'propertyPath' => 'type', 'propertyPath' => 'type',
'render' => function (string $value, AbstractLogEntry $context) { 'render' => function (string $value, AbstractLogEntry $context) {
return $this->translator->trans('log.type.' . $value); return $this->translator->trans('log.type.'.$value);
} },
]); ]);
$dataTable->add('level', TextColumn::class, [ $dataTable->add('level', TextColumn::class, [
@ -117,42 +123,41 @@ class LogDataTable implements DataTableTypeInterface
'propertyPath' => 'levelString', 'propertyPath' => 'levelString',
'render' => function (string $value, AbstractLogEntry $context) { 'render' => function (string $value, AbstractLogEntry $context) {
return $value; return $value;
} },
]); ]);
$dataTable->add('user', TextColumn::class, [ $dataTable->add('user', TextColumn::class, [
'label' => $this->translator->trans('log.user'), 'label' => $this->translator->trans('log.user'),
'render' => function ($value, AbstractLogEntry $context) { 'render' => function ($value, AbstractLogEntry $context) {
$user = $context->getUser(); $user = $context->getUser();
return sprintf( return sprintf(
'<a href="%s">%s</a>', '<a href="%s">%s</a>',
$this->urlGenerator->generate('user_info', ['id' => $user->getID()]), $this->urlGenerator->generate('user_info', ['id' => $user->getID()]),
$user->getFullName(true) $user->getFullName(true)
); );
} },
]); ]);
$dataTable->add('target_type', TextColumn::class, [ $dataTable->add('target_type', TextColumn::class, [
'label' => $this->translator->trans('log.target_type'), 'label' => $this->translator->trans('log.target_type'),
'visible' => false, 'visible' => false,
'render' => function ($value, AbstractLogEntry $context) { 'render' => function ($value, AbstractLogEntry $context) {
$class = $context->getTargetClass(); $class = $context->getTargetClass();
if ($class !== null) { if (null !== $class) {
return $this->elementTypeNameGenerator->getLocalizedTypeLabel($class); return $this->elementTypeNameGenerator->getLocalizedTypeLabel($class);
} }
return ''; return '';
} },
]); ]);
$dataTable->add('target', LogEntryTargetColumn::class, [ $dataTable->add('target', LogEntryTargetColumn::class, [
'label' => $this->translator->trans('log.target') 'label' => $this->translator->trans('log.target'),
]); ]);
$dataTable->add('extra', LogEntryExtraColumn::class, [ $dataTable->add('extra', LogEntryExtraColumn::class, [
'label' => $this->translator->trans('log.extra') 'label' => $this->translator->trans('log.extra'),
]); ]);
$dataTable->addOrderBy('timestamp', DataTable::SORT_DESCENDING); $dataTable->addOrderBy('timestamp', DataTable::SORT_DESCENDING);

View file

@ -24,7 +24,6 @@ declare(strict_types=1);
namespace App\DataTables; namespace App\DataTables;
use App\DataTables\Adapter\CustomORMAdapter;
use App\DataTables\Adapter\FetchJoinORMAdapter; use App\DataTables\Adapter\FetchJoinORMAdapter;
use App\DataTables\Column\EntityColumn; use App\DataTables\Column\EntityColumn;
use App\DataTables\Column\LocaleDateTimeColumn; use App\DataTables\Column\LocaleDateTimeColumn;
@ -53,15 +52,15 @@ use Symfony\Contracts\Translation\TranslatorInterface;
final class PartsDataTable implements DataTableTypeInterface final class PartsDataTable implements DataTableTypeInterface
{ {
protected $translator; private $translator;
protected $treeBuilder; private $treeBuilder;
protected $amountFormatter; private $amountFormatter;
protected $previewGenerator; private $previewGenerator;
protected $attachmentURLGenerator; private $attachmentURLGenerator;
/** /**
* @var EntityURLGenerator * @var EntityURLGenerator
*/ */
protected $urlGenerator; private $urlGenerator;
public function __construct(EntityURLGenerator $urlGenerator, TranslatorInterface $translator, public function __construct(EntityURLGenerator $urlGenerator, TranslatorInterface $translator,
NodesListBuilder $treeBuilder, AmountFormatter $amountFormatter, NodesListBuilder $treeBuilder, AmountFormatter $amountFormatter,
@ -231,7 +230,7 @@ final class PartsDataTable implements DataTableTypeInterface
]); ]);
} }
protected function getQuery(QueryBuilder $builder): void private function getQuery(QueryBuilder $builder): void
{ {
$builder->distinct()->select('part') $builder->distinct()->select('part')
->addSelect('category') ->addSelect('category')
@ -257,7 +256,7 @@ final class PartsDataTable implements DataTableTypeInterface
->leftJoin('part.partUnit', 'partUnit'); ->leftJoin('part.partUnit', 'partUnit');
} }
protected function buildCriteria(QueryBuilder $builder, array $options): void private function buildCriteria(QueryBuilder $builder, array $options): void
{ {
$em = $builder->getEntityManager(); $em = $builder->getEntityManager();

View file

@ -31,7 +31,6 @@ use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use function get_class; use function get_class;
use InvalidArgumentException; use InvalidArgumentException;
use function is_array;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Serializer\Annotation\Groups; use Symfony\Component\Serializer\Annotation\Groups;
@ -55,7 +54,7 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement
public const ID_ROOT_ELEMENT = 0; public const ID_ROOT_ELEMENT = 0;
/** /**
* This is a not standard character, so build a const, so a dev can easily use it * This is a not standard character, so build a const, so a dev can easily use it.
*/ */
public const PATH_DELIMITER_ARROW = ' → '; public const PATH_DELIMITER_ARROW = ' → ';

View file

@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
/** /**
@ -24,8 +25,10 @@ declare(strict_types=1);
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use App\Entity\Attachments\Attachment; use App\Entity\Attachments\Attachment;
use App\Entity\Attachments\AttachmentType;
use App\Entity\Base\DBElement; use App\Entity\Base\DBElement;
use App\Entity\Devices\Device; use App\Entity\Devices\Device;
use App\Entity\Devices\DevicePart;
use App\Entity\Parts\Category; use App\Entity\Parts\Category;
use App\Entity\Parts\Footprint; use App\Entity\Parts\Footprint;
use App\Entity\Parts\Manufacturer; use App\Entity\Parts\Manufacturer;
@ -36,13 +39,11 @@ use App\Entity\UserSystem\Group;
use App\Entity\UserSystem\User; use App\Entity\UserSystem\User;
use DateTime; use DateTime;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use App\Entity\Attachments\AttachmentType;
use App\Entity\Devices\DevicePart;
use Psr\Log\LogLevel; use Psr\Log\LogLevel;
/** /**
* This entity describes a entry in the event log. * This entity describes a entry in the event log.
* @package App\Entity\LogSystem *
* @ORM\Entity(repositoryClass="App\Repository\LogEntryRepository") * @ORM\Entity(repositoryClass="App\Repository\LogEntryRepository")
* @ORM\Table("log") * @ORM\Table("log")
* @ORM\InheritanceType("SINGLE_TABLE") * @ORM\InheritanceType("SINGLE_TABLE")
@ -97,7 +98,6 @@ abstract class AbstractLogEntry extends DBElement
self::LEVEL_DEBUG => LogLevel::DEBUG, self::LEVEL_DEBUG => LogLevel::DEBUG,
]; ];
protected const TARGET_CLASS_MAPPING = [ protected const TARGET_CLASS_MAPPING = [
self::TARGET_TYPE_USER => User::class, self::TARGET_TYPE_USER => User::class,
self::TARGET_TYPE_ATTACHEMENT => Attachment::class, self::TARGET_TYPE_ATTACHEMENT => Attachment::class,
@ -113,7 +113,7 @@ abstract class AbstractLogEntry extends DBElement
self::TARGET_TYPE_SUPPLIER => Supplier::class, self::TARGET_TYPE_SUPPLIER => Supplier::class,
]; ];
/** @var User $user The user which has caused this log entry /** @var User The user which has caused this log entry
* @ORM\ManyToOne(targetEntity="App\Entity\UserSystem\User") * @ORM\ManyToOne(targetEntity="App\Entity\UserSystem\User")
* @ORM\JoinColumn(name="id_user", nullable=false) * @ORM\JoinColumn(name="id_user", nullable=false)
*/ */
@ -124,17 +124,17 @@ abstract class AbstractLogEntry extends DBElement
*/ */
protected $timestamp; protected $timestamp;
/** @var integer The priority level of the associated level. 0 is highest, 7 lowest /** @var int The priority level of the associated level. 0 is highest, 7 lowest
* @ORM\Column(type="integer", name="level", columnDefinition="TINYINT") * @ORM\Column(type="integer", name="level", columnDefinition="TINYINT")
*/ */
protected $level; protected $level;
/** @var int $target_id The ID of the element targeted by this event /** @var int The ID of the element targeted by this event
* @ORM\Column(name="target_id", type="integer", nullable=false) * @ORM\Column(name="target_id", type="integer", nullable=false)
*/ */
protected $target_id = 0; protected $target_id = 0;
/** @var int $target_type The Type of the targeted element /** @var int The Type of the targeted element
* @ORM\Column(name="target_type", type="smallint", nullable=false) * @ORM\Column(name="target_type", type="smallint", nullable=false)
*/ */
protected $target_type = 0; protected $target_type = 0;
@ -143,7 +143,7 @@ abstract class AbstractLogEntry extends DBElement
* The mapping between the log entry class and the discriminator column is done by doctrine. * The mapping between the log entry class and the discriminator column is done by doctrine.
* Each subclass should override this string to specify a better string. * Each subclass should override this string to specify a better string.
*/ */
protected $typeString = "unknown"; protected $typeString = 'unknown';
/** @var array The extra data in raw (short form) saved in the DB /** @var array The extra data in raw (short form) saved in the DB
* @ORM\Column(name="extra", type="json") * @ORM\Column(name="extra", type="json")
@ -158,6 +158,7 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* Get the user that caused the event associated with this log entry. * Get the user that caused the event associated with this log entry.
*
* @return User * @return User
*/ */
public function getUser(): ?User public function getUser(): ?User
@ -167,17 +168,19 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* Sets the user that caused the event. * Sets the user that caused the event.
* @param User $user *
* @return $this * @return $this
*/ */
public function setUser(User $user): self public function setUser(User $user): self
{ {
$this->user = $user; $this->user = $user;
return $this; return $this;
} }
/** /**
* Returns the timestamp when the event that caused this log entry happened * Returns the timestamp when the event that caused this log entry happened.
*
* @return DateTime * @return DateTime
*/ */
public function getTimestamp(): DateTime public function getTimestamp(): DateTime
@ -187,18 +190,20 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* Sets the timestamp when the event happened. * Sets the timestamp when the event happened.
* @param DateTime $timestamp *
* @return $this * @return $this
*/ */
public function setTimestamp(DateTime $timestamp): AbstractLogEntry public function setTimestamp(DateTime $timestamp): self
{ {
$this->timestamp = $timestamp; $this->timestamp = $timestamp;
return $this; return $this;
} }
/** /**
* Get the priority level of this log entry. 0 is highest and 7 lowest level. * Get the priority level of this log entry. 0 is highest and 7 lowest level.
* See LEVEL_* consts in this class for more info * See LEVEL_* consts in this class for more info.
*
* @return int * @return int
*/ */
public function getLevel(): int public function getLevel(): int
@ -207,25 +212,28 @@ abstract class AbstractLogEntry extends DBElement
if ($this->level < 0 || $this->level > 7) { if ($this->level < 0 || $this->level > 7) {
return self::LEVEL_ALERT; return self::LEVEL_ALERT;
} }
return $this->level; return $this->level;
} }
/** /**
* Sets the new level of this log entry. * Sets the new level of this log entry.
* @param int $level *
* @return $this * @return $this
*/ */
public function setLevel(int $level): AbstractLogEntry public function setLevel(int $level): self
{ {
if ($level < 0 || $this->level > 7) { if ($level < 0 || $this->level > 7) {
throw new \InvalidArgumentException(sprintf('$level must be between 0 and 7! %d given!', $level)); throw new \InvalidArgumentException(sprintf('$level must be between 0 and 7! %d given!', $level));
} }
$this->level = $level; $this->level = $level;
return $this; return $this;
} }
/** /**
* Get the priority level of this log entry as PSR3 compatible string * Get the priority level of this log entry as PSR3 compatible string.
*
* @return string * @return string
*/ */
public function getLevelString(): string public function getLevelString(): string
@ -234,18 +242,20 @@ abstract class AbstractLogEntry extends DBElement
} }
/** /**
* Sets the priority level of this log entry as PSR3 compatible string * Sets the priority level of this log entry as PSR3 compatible string.
* @param string $level *
* @return $this * @return $this
*/ */
public function setLevelString(string $level): AbstractLogEntry public function setLevelString(string $level): self
{ {
$this->setLevel(self::levelStringToInt($level)); $this->setLevel(self::levelStringToInt($level));
return $this; return $this;
} }
/** /**
* Returns the type of the event this log entry is associated with. * Returns the type of the event this log entry is associated with.
*
* @return string * @return string
*/ */
public function getType(): string public function getType(): string
@ -253,22 +263,20 @@ abstract class AbstractLogEntry extends DBElement
return $this->typeString; return $this->typeString;
} }
/**
* @inheritDoc
*/
public function getIDString(): string public function getIDString(): string
{ {
return "LOG".$this->getID(); return 'LOG'.$this->getID();
} }
/** /**
* Returns the class name of the target element associated with this log entry. * Returns the class name of the target element associated with this log entry.
* Returns null, if this log entry is not associated with an log entry. * Returns null, if this log entry is not associated with an log entry.
*
* @return string|null The class name of the target class. * @return string|null The class name of the target class.
*/ */
public function getTargetClass(): ?string public function getTargetClass(): ?string
{ {
if ($this->target_type === self::TARGET_TYPE_NONE) { if (self::TARGET_TYPE_NONE === $this->target_type) {
return null; return null;
} }
@ -278,11 +286,12 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* Returns the ID of the target element associated with this log entry. * Returns the ID of the target element associated with this log entry.
* Returns null, if this log entry is not associated with an log entry. * Returns null, if this log entry is not associated with an log entry.
*
* @return int|null The ID of the associated element. * @return int|null The ID of the associated element.
*/ */
public function getTargetID(): ?int public function getTargetID(): ?int
{ {
if ($this->target_id === 0) { if (0 === $this->target_id) {
return null; return null;
} }
@ -290,24 +299,28 @@ abstract class AbstractLogEntry extends DBElement
} }
/** /**
* Checks if this log entry is associated with an element * Checks if this log entry is associated with an element.
*
* @return bool True if this log entry is associated with an element, false otherwise. * @return bool True if this log entry is associated with an element, false otherwise.
*/ */
public function hasTarget(): bool public function hasTarget(): bool
{ {
return $this->getTargetID() !== null && $this->getTargetClass() !== null; return null !== $this->getTargetID() && null !== $this->getTargetClass();
} }
/** /**
* Sets the target element associated with this element * Sets the target element associated with this element.
*
* @param DBElement $element The element that should be associated with this element. * @param DBElement $element The element that should be associated with this element.
*
* @return $this * @return $this
*/ */
public function setTargetElement(?DBElement $element): self public function setTargetElement(?DBElement $element): self
{ {
if ($element === null) { if (null === $element) {
$this->target_id = 0; $this->target_id = 0;
$this->target_type = self::TARGET_TYPE_NONE; $this->target_type = self::TARGET_TYPE_NONE;
return $this; return $this;
} }
@ -324,12 +337,14 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* This function converts the internal numeric log level into an PSR3 compatible level string. * This function converts the internal numeric log level into an PSR3 compatible level string.
*
* @param int $level The numerical log level * @param int $level The numerical log level
*
* @return string The PSR3 compatible level string * @return string The PSR3 compatible level string
*/ */
final public static function levelIntToString(int $level): string final public static function levelIntToString(int $level): string
{ {
if (!isset(self::LEVEL_ID_TO_STRING[$level])) { if (! isset(self::LEVEL_ID_TO_STRING[$level])) {
throw new \InvalidArgumentException('No level with this int is existing!'); throw new \InvalidArgumentException('No level with this int is existing!');
} }
@ -338,13 +353,15 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* This function converts a PSR3 compatible string to the internal numeric level string. * This function converts a PSR3 compatible string to the internal numeric level string.
*
* @param string $level the PSR3 compatible string that should be converted * @param string $level the PSR3 compatible string that should be converted
*
* @return int The internal int representation. * @return int The internal int representation.
*/ */
final public static function levelStringToInt(string $level): int final public static function levelStringToInt(string $level): int
{ {
$tmp = array_flip(self::LEVEL_ID_TO_STRING); $tmp = array_flip(self::LEVEL_ID_TO_STRING);
if (!isset($tmp[$level])) { if (! isset($tmp[$level])) {
throw new \InvalidArgumentException('No level with this string is existing!'); throw new \InvalidArgumentException('No level with this string is existing!');
} }
@ -353,12 +370,14 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* Converts an target type id to an full qualified class name. * Converts an target type id to an full qualified class name.
*
* @param int $type_id The target type ID * @param int $type_id The target type ID
*
* @return string * @return string
*/ */
final public static function targetTypeIdToClass(int $type_id): string final public static function targetTypeIdToClass(int $type_id): string
{ {
if (!isset(self::TARGET_CLASS_MAPPING[$type_id])) { if (! isset(self::TARGET_CLASS_MAPPING[$type_id])) {
throw new \InvalidArgumentException('No target type with this ID is existing!'); throw new \InvalidArgumentException('No target type with this ID is existing!');
} }
@ -367,7 +386,9 @@ abstract class AbstractLogEntry extends DBElement
/** /**
* Convert a class name to a target type ID. * Convert a class name to a target type ID.
*
* @param string $class The name of the class (FQN) that should be converted to id * @param string $class The name of the class (FQN) that should be converted to id
*
* @return int The ID of the associated target type ID. * @return int The ID of the associated target type ID.
*/ */
final public static function targetTypeClassToID(string $class): int final public static function targetTypeClassToID(string $class): int
@ -387,6 +408,4 @@ abstract class AbstractLogEntry extends DBElement
throw new \InvalidArgumentException('No target ID for this class is existing!'); throw new \InvalidArgumentException('No target ID for this class is existing!');
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -26,11 +29,10 @@ use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity() * @ORM\Entity()
* @package App\Entity\LogSystem
*/ */
class ConfigChangedLogEntry extends AbstractLogEntry class ConfigChangedLogEntry extends AbstractLogEntry
{ {
protected $typeString = "config_changed"; protected $typeString = 'config_changed';
public function __construct() public function __construct()
{ {

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,7 +24,6 @@
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use App\Exceptions\LogEntryObsoleteException;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
@ -29,7 +31,7 @@ use Doctrine\ORM\Mapping as ORM;
*/ */
class DatabaseUpdatedLogEntry extends AbstractLogEntry class DatabaseUpdatedLogEntry extends AbstractLogEntry
{ {
protected $typeString = "database_updated"; protected $typeString = 'database_updated';
public function __construct(string $oldVersion, string $newVersion) public function __construct(string $oldVersion, string $newVersion)
{ {
@ -40,6 +42,7 @@ class DatabaseUpdatedLogEntry extends AbstractLogEntry
/** /**
* Checks if the database update was successful. * Checks if the database update was successful.
*
* @return bool * @return bool
*/ */
public function isSuccessful(): bool public function isSuccessful(): bool
@ -50,6 +53,7 @@ class DatabaseUpdatedLogEntry extends AbstractLogEntry
/** /**
* Gets the database version before update. * Gets the database version before update.
*
* @return int * @return int
*/ */
public function getOldVersion(): string public function getOldVersion(): string
@ -59,11 +63,11 @@ class DatabaseUpdatedLogEntry extends AbstractLogEntry
/** /**
* Gets the (target) database version after update. * Gets the (target) database version after update.
*
* @return int * @return int
*/ */
public function getNewVersion(): string public function getNewVersion(): string
{ {
return (string) $this->extra['n']; return (string) $this->extra['n'];
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,19 +24,18 @@
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity() * @ORM\Entity()
* @package App\Entity\LogSystem
*/ */
class ElementCreatedLogEntry extends AbstractLogEntry class ElementCreatedLogEntry extends AbstractLogEntry
{ {
protected $typeString = "element_created"; protected $typeString = 'element_created';
/** /**
* Gets the instock when the part was created * Gets the instock when the part was created.
*
* @return int|null * @return int|null
*/ */
public function getCreationInstockValue(): ?int public function getCreationInstockValue(): ?int
@ -43,10 +45,11 @@ class ElementCreatedLogEntry extends AbstractLogEntry
/** /**
* Checks if a creation instock value was saved with this entry. * Checks if a creation instock value was saved with this entry.
*
* @return bool * @return bool
*/ */
public function hasCreationInstockValue(): bool public function hasCreationInstockValue(): bool
{ {
return $this->getCreationInstockValue() !== null; return null !== $this->getCreationInstockValue();
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,7 +24,6 @@
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
@ -29,7 +31,7 @@ use Doctrine\ORM\Mapping as ORM;
*/ */
class ElementDeletedLogEntry extends AbstractLogEntry class ElementDeletedLogEntry extends AbstractLogEntry
{ {
protected $typeString = "element_deleted"; protected $typeString = 'element_deleted';
public function getOldName(): string public function getOldName(): string
{ {

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -25,17 +28,17 @@ use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity() * @ORM\Entity()
* @package App\Entity\LogSystem
*/ */
class ElementEditedLogEntry extends AbstractLogEntry class ElementEditedLogEntry extends AbstractLogEntry
{ {
protected $typeString = "element_edited"; protected $typeString = 'element_edited';
/** /**
* Returns the message associated with this edit change * Returns the message associated with this edit change.
*
* @return string * @return string
*/ */
public function getMessage() : string public function getMessage(): string
{ {
return $this->extra['m'] ?? ''; return $this->extra['m'] ?? '';
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,13 +24,11 @@
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use App\Exceptions\LogEntryObsoleteException; use App\Exceptions\LogEntryObsoleteException;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity() * @ORM\Entity()
* @package App\Entity\LogSystem
*/ */
class ExceptionLogEntry extends AbstractLogEntry class ExceptionLogEntry extends AbstractLogEntry
{ {
@ -40,15 +41,17 @@ class ExceptionLogEntry extends AbstractLogEntry
/** /**
* The class name of the exception that caused this log entry. * The class name of the exception that caused this log entry.
*
* @return string * @return string
*/ */
public function getExceptionClass(): string public function getExceptionClass(): string
{ {
return $this->extra['t'] ?? "Unknown Class"; return $this->extra['t'] ?? 'Unknown Class';
} }
/** /**
* Returns the file where the exception happened. * Returns the file where the exception happened.
*
* @return string * @return string
*/ */
public function getFile(): string public function getFile(): string
@ -57,7 +60,8 @@ class ExceptionLogEntry extends AbstractLogEntry
} }
/** /**
* Returns the line where the exception happened * Returns the line where the exception happened.
*
* @return int * @return int
*/ */
public function getLine(): int public function getLine(): int
@ -67,11 +71,11 @@ class ExceptionLogEntry extends AbstractLogEntry
/** /**
* Return the message of the exception. * Return the message of the exception.
*
* @return string * @return string
*/ */
public function getMessage(): string public function getMessage(): string
{ {
return $this->extra['m']; return $this->extra['m'];
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,20 +24,18 @@
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use App\Entity\Parts\Part;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity() * @ORM\Entity()
* @package App\Entity\LogSystem
*/ */
class InstockChangedLogEntry extends AbstractLogEntry class InstockChangedLogEntry extends AbstractLogEntry
{ {
protected $typeString = "instock_changed"; protected $typeString = 'instock_changed';
/** /**
* Get the old instock * Get the old instock.
*
* @return int * @return int
*/ */
public function getOldInstock(): int public function getOldInstock(): int
@ -43,7 +44,8 @@ class InstockChangedLogEntry extends AbstractLogEntry
} }
/** /**
* Get the new instock * Get the new instock.
*
* @return int * @return int
*/ */
public function getNewInstock(): int public function getNewInstock(): int
@ -52,7 +54,8 @@ class InstockChangedLogEntry extends AbstractLogEntry
} }
/** /**
* Gets the comment associated with the instock change * Gets the comment associated with the instock change.
*
* @return string * @return string
*/ */
public function getComment(): string public function getComment(): string
@ -62,7 +65,9 @@ class InstockChangedLogEntry extends AbstractLogEntry
/** /**
* Returns the price that has to be payed for the change (in the base currency). * Returns the price that has to be payed for the change (in the base currency).
* @param $absolute bool Set this to true, if you want only get the absolute value of the price (without minus) *
* @param bool $absolute Set this to true, if you want only get the absolute value of the price (without minus)
*
* @return float * @return float
*/ */
public function getPrice(bool $absolute = false): float public function getPrice(bool $absolute = false): float
@ -70,18 +75,21 @@ class InstockChangedLogEntry extends AbstractLogEntry
if ($absolute) { if ($absolute) {
return abs($this->extra['p']); return abs($this->extra['p']);
} }
return $this->extra['p']; return $this->extra['p'];
} }
/** /**
* Returns the difference value of the change ($new_instock - $old_instock). * Returns the difference value of the change ($new_instock - $old_instock).
* @param $absolute bool Set this to true if you want only the absolute value of the difference. *
* @param bool $absolute Set this to true if you want only the absolute value of the difference.
*
* @return int Difference is positive if instock has increased, negative if decreased. * @return int Difference is positive if instock has increased, negative if decreased.
*/ */
public function getDifference(bool $absolute = false): int public function getDifference(bool $absolute = false): int
{ {
// Check if one of the instock values is unknown // Check if one of the instock values is unknown
if ($this->getNewInstock() == -2 || $this->getOldInstock() == -2) { if (-2 === $this->getNewInstock() || -2 === $this->getOldInstock()) {
return 0; return 0;
} }
@ -95,11 +103,11 @@ class InstockChangedLogEntry extends AbstractLogEntry
/** /**
* Checks if the Change was an withdrawal of parts. * Checks if the Change was an withdrawal of parts.
*
* @return bool True if the change was an withdrawal, false if not. * @return bool True if the change was an withdrawal, false if not.
*/ */
public function isWithdrawal(): bool public function isWithdrawal(): bool
{ {
return $this->getNewInstock() < $this->getOldInstock(); return $this->getNewInstock() < $this->getOldInstock();
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -26,12 +29,12 @@ use Symfony\Component\HttpFoundation\IpUtils;
/** /**
* This log entry is created when a user logs in. * This log entry is created when a user logs in.
* @package App\Entity\LogSystem *
* @ORM\Entity() * @ORM\Entity()
*/ */
class UserLoginLogEntry extends AbstractLogEntry class UserLoginLogEntry extends AbstractLogEntry
{ {
protected $typeString = "user_login"; protected $typeString = 'user_login';
public function __construct(string $ip_address, bool $anonymize = true) public function __construct(string $ip_address, bool $anonymize = true)
{ {
@ -42,6 +45,7 @@ class UserLoginLogEntry extends AbstractLogEntry
/** /**
* Return the (anonymized) IP address used to login the user. * Return the (anonymized) IP address used to login the user.
*
* @return string * @return string
*/ */
public function getIPAddress(): string public function getIPAddress(): string
@ -50,9 +54,11 @@ class UserLoginLogEntry extends AbstractLogEntry
} }
/** /**
* Sets the IP address used to login the user * Sets the IP address used to login the user.
*
* @param string $ip The IP address used to login the user. * @param string $ip The IP address used to login the user.
* @param bool $anonymize Anonymize the IP address (remove last block) to be GPDR compliant * @param bool $anonymize Anonymize the IP address (remove last block) to be GPDR compliant
*
* @return $this * @return $this
*/ */
public function setIPAddress(string $ip, bool $anonymize = true): self public function setIPAddress(string $ip, bool $anonymize = true): self
@ -62,6 +68,7 @@ class UserLoginLogEntry extends AbstractLogEntry
} }
$this->extra['i'] = $ip; $this->extra['i'] = $ip;
return $this; return $this;
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,17 +24,15 @@
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\IpUtils; use Symfony\Component\HttpFoundation\IpUtils;
/** /**
* @ORM\Entity() * @ORM\Entity()
* @package App\Entity\LogSystem
*/ */
class UserLogoutLogEntry extends AbstractLogEntry class UserLogoutLogEntry extends AbstractLogEntry
{ {
protected $typeString = "user_logout"; protected $typeString = 'user_logout';
public function __construct(string $ip_address, bool $anonymize = true) public function __construct(string $ip_address, bool $anonymize = true)
{ {
@ -42,6 +43,7 @@ class UserLogoutLogEntry extends AbstractLogEntry
/** /**
* Return the (anonymized) IP address used to login the user. * Return the (anonymized) IP address used to login the user.
*
* @return string * @return string
*/ */
public function getIPAddress(): string public function getIPAddress(): string
@ -50,9 +52,11 @@ class UserLogoutLogEntry extends AbstractLogEntry
} }
/** /**
* Sets the IP address used to login the user * Sets the IP address used to login the user.
*
* @param string $ip The IP address used to login the user. * @param string $ip The IP address used to login the user.
* @param bool $anonymize Anonymize the IP address (remove last block) to be GPDR compliant * @param bool $anonymize Anonymize the IP address (remove last block) to be GPDR compliant
*
* @return $this * @return $this
*/ */
public function setIPAddress(string $ip, bool $anonymize = true): self public function setIPAddress(string $ip, bool $anonymize = true): self
@ -62,8 +66,7 @@ class UserLogoutLogEntry extends AbstractLogEntry
} }
$this->extra['i'] = $ip; $this->extra['i'] = $ip;
return $this; return $this;
} }
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,12 +24,10 @@
namespace App\Entity\LogSystem; namespace App\Entity\LogSystem;
use App\Exceptions\LogEntryObsoleteException; use App\Exceptions\LogEntryObsoleteException;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @package App\Entity\LogSystem
* @ORM\Entity() * @ORM\Entity()
*/ */
class UserNotAllowedLogEntry extends AbstractLogEntry class UserNotAllowedLogEntry extends AbstractLogEntry

View file

@ -84,7 +84,7 @@ class Part extends AttachmentContainingDBElement
use OrderTrait; use OrderTrait;
/** /**
* TODO * TODO.
*/ */
protected $devices; protected $devices;

View file

@ -90,7 +90,7 @@ class User extends AttachmentContainingDBElement implements UserInterface, HasPe
use MasterAttachmentTrait; use MasterAttachmentTrait;
/** /**
* The User id of the anonymous user * The User id of the anonymous user.
*/ */
public const ID_ANONYMOUS = 1; public const ID_ANONYMOUS = 1;

View file

@ -38,10 +38,10 @@ use Symfony\Contracts\Translation\TranslatorInterface;
*/ */
final class LoginSuccessListener implements EventSubscriberInterface final class LoginSuccessListener implements EventSubscriberInterface
{ {
protected $translator; private $translator;
protected $flashBag; private $flashBag;
protected $eventLogger; private $eventLogger;
protected $gpdr_compliance; private $gpdr_compliance;
public function __construct(TranslatorInterface $translator, FlashBagInterface $flashBag, EventLogger $eventLogger, bool $gpdr_compliance) public function __construct(TranslatorInterface $translator, FlashBagInterface $flashBag, EventLogger $eventLogger, bool $gpdr_compliance)
{ {

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,7 +24,6 @@
namespace App\EventSubscriber; namespace App\EventSubscriber;
use App\Entity\LogSystem\UserLogoutLogEntry; use App\Entity\LogSystem\UserLogoutLogEntry;
use App\Entity\UserSystem\User; use App\Entity\UserSystem\User;
use App\Services\LogSystem\EventLogger; use App\Services\LogSystem\EventLogger;
@ -41,10 +43,7 @@ class LogoutListener implements LogoutHandlerInterface
$this->gpdr_compliance = $gpdr_compliance; $this->gpdr_compliance = $gpdr_compliance;
} }
/** public function logout(Request $request, Response $response, TokenInterface $token): void
* @inheritDoc
*/
public function logout(Request $request, Response $response, TokenInterface $token)
{ {
$log = new UserLogoutLogEntry($request->getClientIp(), $this->gpdr_compliance); $log = new UserLogoutLogEntry($request->getClientIp(), $this->gpdr_compliance);
$user = $token->getUser(); $user = $token->getUser();

View file

@ -34,10 +34,10 @@ use Symfony\Component\Security\Core\Security;
final class LogoutOnDisabledUserListener implements EventSubscriberInterface final class LogoutOnDisabledUserListener implements EventSubscriberInterface
{ {
protected $security; private $security;
protected $translator; private $translator;
protected $flashBag; private $flashBag;
protected $urlGenerator; private $urlGenerator;
public function __construct(Security $security, UrlGeneratorInterface $urlGenerator) public function __construct(Security $security, UrlGeneratorInterface $urlGenerator)
{ {

View file

@ -31,8 +31,8 @@ use Symfony\Component\Mime\Email;
final class MailFromListener implements EventSubscriberInterface final class MailFromListener implements EventSubscriberInterface
{ {
protected $email; private $email;
protected $name; private $name;
public function __construct(string $email, string $name) public function __construct(string $email, string $name)
{ {

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,12 +24,10 @@
namespace App\EventSubscriber; namespace App\EventSubscriber;
use App\Entity\LogSystem\DatabaseUpdatedLogEntry; use App\Entity\LogSystem\DatabaseUpdatedLogEntry;
use App\Services\LogSystem\EventLogger; use App\Services\LogSystem\EventLogger;
use Doctrine\Common\EventSubscriber; use Doctrine\Common\EventSubscriber;
use Doctrine\Migrations\Event\MigrationsEventArgs; use Doctrine\Migrations\Event\MigrationsEventArgs;
use Doctrine\Migrations\Event\MigrationsVersionEventArgs;
use Doctrine\Migrations\Events; use Doctrine\Migrations\Events;
class MigrationListener implements EventSubscriber class MigrationListener implements EventSubscriber
@ -55,28 +56,22 @@ class MigrationListener implements EventSubscriber
$this->old_version = empty($this->old_version) ? 'legacy/empty' : $this->old_version; $this->old_version = empty($this->old_version) ? 'legacy/empty' : $this->old_version;
$this->new_version = empty($this->new_version) ? 'unknown' : $this->new_version; $this->new_version = empty($this->new_version) ? 'unknown' : $this->new_version;
try { try {
$log = new DatabaseUpdatedLogEntry($this->old_version, $this->new_version); $log = new DatabaseUpdatedLogEntry($this->old_version, $this->new_version);
$this->eventLogger->logAndFlush($log); $this->eventLogger->logAndFlush($log);
} catch (\Exception $exception) { } catch (\Throwable $exception) {
//Ignore any exception occuring here... //Ignore any exception occuring here...
} }
} }
public function onMigrationsMigrating(MigrationsEventArgs $args): void public function onMigrationsMigrating(MigrationsEventArgs $args): void
{ {
// Save the version before any migration // Save the version before any migration
if ($this->old_version == null) { if (null === $this->old_version) {
$this->old_version = $args->getConfiguration()->getCurrentVersion(); $this->old_version = $args->getConfiguration()->getCurrentVersion();
} }
} }
/**
* @inheritDoc
*/
public function getSubscribedEvents() public function getSubscribedEvents()
{ {
return [ return [

View file

@ -55,9 +55,9 @@ final class PasswordChangeNeededSubscriber implements EventSubscriberInterface
* @var string The route the user will redirected to, if he needs to change this password * @var string The route the user will redirected to, if he needs to change this password
*/ */
public const REDIRECT_TARGET = 'user_settings'; public const REDIRECT_TARGET = 'user_settings';
protected $security; private $security;
protected $flashBag; private $flashBag;
protected $httpUtils; private $httpUtils;
public function __construct(Security $security, FlashBagInterface $flashBag, HttpUtils $httpUtils) public function __construct(Security $security, FlashBagInterface $flashBag, HttpUtils $httpUtils)
{ {

View file

@ -30,7 +30,7 @@ use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
final class SymfonyDebugToolbarSubscriber implements EventSubscriberInterface final class SymfonyDebugToolbarSubscriber implements EventSubscriberInterface
{ {
protected $kernel; private $kernel;
public function __construct(ContainerInterface $kernel) public function __construct(ContainerInterface $kernel)
{ {

View file

@ -35,8 +35,8 @@ use Symfony\Component\Security\Core\Security;
*/ */
final class TimezoneListener implements EventSubscriberInterface final class TimezoneListener implements EventSubscriberInterface
{ {
protected $default_timezone; private $default_timezone;
protected $security; private $security;
public function __construct(string $timezone, Security $security) public function __construct(string $timezone, Security $security)
{ {

View file

@ -34,10 +34,10 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
final class U2FRegistrationSubscriber implements EventSubscriberInterface final class U2FRegistrationSubscriber implements EventSubscriberInterface
{ {
protected $em; private $em;
protected $demo_mode; private $demo_mode;
protected $flashBag; private $flashBag;
/** /**
* @var UrlGeneratorInterface * @var UrlGeneratorInterface
*/ */
@ -51,9 +51,6 @@ final class U2FRegistrationSubscriber implements EventSubscriberInterface
$this->flashBag = $flashBag; $this->flashBag = $flashBag;
} }
/**
*
*/
public static function getSubscribedEvents(): array public static function getSubscribedEvents(): array
{ {
return [ return [

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,8 +24,7 @@
namespace App\Exceptions; namespace App\Exceptions;
class LogEntryObsoleteException extends \RuntimeException class LogEntryObsoleteException extends \RuntimeException
{ {
protected $message = "This log entry is obsolete and exists only for compatibility reasons with old Part-DB versions. You should not use it!"; protected $message = 'This log entry is obsolete and exists only for compatibility reasons with old Part-DB versions. You should not use it!';
} }

View file

@ -36,8 +36,8 @@ use Traversable;
*/ */
final class PermissionsMapper implements DataMapperInterface final class PermissionsMapper implements DataMapperInterface
{ {
protected $resolver; private $resolver;
protected $inherit; private $inherit;
public function __construct(PermissionResolver $resolver, bool $inherit = false) public function __construct(PermissionResolver $resolver, bool $inherit = false)
{ {

View file

@ -32,15 +32,15 @@ use JsonSerializable;
*/ */
final class TreeViewNode implements JsonSerializable final class TreeViewNode implements JsonSerializable
{ {
protected $text; private $text;
protected $href; private $href;
protected $nodes; private $nodes;
protected $state = null; private $state = null;
protected $tags; private $tags;
protected $id; private $id;
/** /**
* Creates a new TreeView node with the given parameters. * Creates a new TreeView node with the given parameters.

View file

@ -31,22 +31,22 @@ final class TreeViewNodeState implements JsonSerializable
/** /**
* @var bool|null * @var bool|null
*/ */
protected $checked = null; private $checked = null;
/** /**
* @var bool|null * @var bool|null
*/ */
protected $disabled = null; private $disabled = null;
/** /**
* @var bool|null * @var bool|null
*/ */
protected $expanded = null; private $expanded = null;
/** /**
* @var bool|null * @var bool|null
*/ */
protected $selected = null; private $selected = null;
/** /**
* @return bool|null * @return bool|null

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace App; namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;

View file

@ -12,15 +12,15 @@ use Doctrine\Migrations\AbstractMigration;
*/ */
final class Version20200126191823 extends AbstractMigration final class Version20200126191823 extends AbstractMigration
{ {
public function getDescription() : string public function getDescription(): string
{ {
return 'Improve the schema of the log table'; return 'Improve the schema of the log table';
} }
public function up(Schema $schema) : void public function up(Schema $schema): void
{ {
// this up() migration is auto-generated, please modify it to your needs // 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('ALTER TABLE log CHANGE datetime datetime DATETIME NOT NULL, CHANGE level level TINYINT, CHANGE extra extra LONGTEXT NOT NULL COMMENT \'(DC2Type:json)\''); $this->addSql('ALTER TABLE log CHANGE datetime datetime DATETIME NOT NULL, CHANGE level level TINYINT, CHANGE extra extra LONGTEXT NOT NULL COMMENT \'(DC2Type:json)\'');
$this->addSql('DROP INDEX id_user ON log'); $this->addSql('DROP INDEX id_user ON log');
@ -28,10 +28,10 @@ final class Version20200126191823 extends AbstractMigration
$this->addSql('CREATE INDEX IDX_8F3F68C56B3CA4B ON log (id_user)'); $this->addSql('CREATE INDEX IDX_8F3F68C56B3CA4B ON log (id_user)');
} }
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 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 log DROP FOREIGN KEY FK_8F3F68C56B3CA4B'); $this->addSql('ALTER TABLE log DROP FOREIGN KEY FK_8F3F68C56B3CA4B');
$this->addSql('ALTER TABLE log DROP FOREIGN KEY FK_8F3F68C56B3CA4B'); $this->addSql('ALTER TABLE log DROP FOREIGN KEY FK_8F3F68C56B3CA4B');

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,15 +24,13 @@
namespace App\Repository; namespace App\Repository;
use App\Entity\Base\DBElement; use App\Entity\Base\DBElement;
use App\Entity\LogSystem\AbstractLogEntry; use App\Entity\LogSystem\AbstractLogEntry;
use Doctrine\ORM\EntityRepository; use Doctrine\ORM\EntityRepository;
class LogEntryRepository extends EntityRepository class LogEntryRepository extends EntityRepository
{ {
public function findBy(array $criteria, ?array $orderBy = null, $limit = null, $offset = null)
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{ {
//Emulate a target element criteria by splitting it manually in the needed criterias //Emulate a target element criteria by splitting it manually in the needed criterias
if (isset($criteria['target']) && $criteria['target'] instanceof DBElement) { if (isset($criteria['target']) && $criteria['target'] instanceof DBElement) {
@ -43,11 +44,13 @@ class LogEntryRepository extends EntityRepository
} }
/** /**
* Find log entries associated with the given element (the history of the element) * Find log entries associated with the given element (the history of the element).
*
* @param DBElement $element The element for which the history should be generated * @param DBElement $element The element for which the history should be generated
* @param string $order By default newest entries are shown first. Change this to ASC to show oldest entries first. * @param string $order By default newest entries are shown first. Change this to ASC to show oldest entries first.
* @param null $limit * @param null $limit
* @param null $offset * @param null $offset
*
* @return AbstractLogEntry[] * @return AbstractLogEntry[]
*/ */
public function getElementHistory(DBElement $element, $order = 'DESC', $limit = null, $offset = null) public function getElementHistory(DBElement $element, $order = 'DESC', $limit = null, $offset = null)
@ -56,10 +59,12 @@ class LogEntryRepository extends EntityRepository
} }
/** /**
* Gets the last log entries ordered by timestamp * Gets the last log entries ordered by timestamp.
*
* @param string $order * @param string $order
* @param null $limit * @param null $limit
* @param null $offset * @param null $offset
*
* @return array * @return array
*/ */
public function getLogsOrderedByTimestamp($order = 'DESC', $limit = null, $offset = null) public function getLogsOrderedByTimestamp($order = 'DESC', $limit = null, $offset = null)
@ -69,7 +74,7 @@ class LogEntryRepository extends EntityRepository
/** /**
* Gets the target element associated with the logentry. * Gets the target element associated with the logentry.
* @param AbstractLogEntry $logEntry *
* @return DBElement|null Returns the associated DBElement or null if the log either has no target or the element * @return DBElement|null Returns the associated DBElement or null if the log either has no target or the element
* was deleted from DB. * was deleted from DB.
*/ */
@ -78,7 +83,7 @@ class LogEntryRepository extends EntityRepository
$class = $logEntry->getTargetClass(); $class = $logEntry->getTargetClass();
$id = $logEntry->getTargetID(); $id = $logEntry->getTargetID();
if ($class === null || $id === null) { if (null === $class || null === $id) {
return null; return null;
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,26 +24,21 @@
namespace App\Security\Voter; namespace App\Security\Voter;
use App\Entity\LogSystem\AbstractLogEntry; use App\Entity\LogSystem\AbstractLogEntry;
use App\Entity\UserSystem\User; use App\Entity\UserSystem\User;
class LogEntryVoter extends ExtendedVoter class LogEntryVoter extends ExtendedVoter
{ {
public const ALLOWED_OPS = ['read', 'delete']; public const ALLOWED_OPS = ['read', 'delete'];
/**
* @inheritDoc
*/
protected function voteOnUser($attribute, $subject, User $user): bool protected function voteOnUser($attribute, $subject, User $user): bool
{ {
if ($subject instanceof AbstractLogEntry) { if ($subject instanceof AbstractLogEntry) {
if ($attribute === 'delete') { if ('delete' === $attribute) {
return $this->resolver->inherit($user, 'system', 'delete_logs') ?? false; return $this->resolver->inherit($user, 'system', 'delete_logs') ?? false;
} }
if ($attribute === 'read') { if ('read' === $attribute) {
//Allow read of the users own log entries //Allow read of the users own log entries
if ( if (
$subject->getUser() === $user $subject->getUser() === $user
@ -49,20 +47,17 @@ class LogEntryVoter extends ExtendedVoter
return true; return true;
} }
return $this->resolver->inherit($user, 'system','show_logs') ?? false; return $this->resolver->inherit($user, 'system', 'show_logs') ?? false;
} }
} }
return false; return false;
} }
/**
* @inheritDoc
*/
protected function supports($attribute, $subject) protected function supports($attribute, $subject)
{ {
if ($subject instanceof AbstractLogEntry) { if ($subject instanceof AbstractLogEntry) {
return in_array($subject, static::ALLOWED_OPS); return in_array($subject, static::ALLOWED_OPS, true);
} }
return false; return false;

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,7 +24,6 @@
namespace App\Services\LogSystem; namespace App\Services\LogSystem;
use App\Entity\LogSystem\AbstractLogEntry; use App\Entity\LogSystem\AbstractLogEntry;
use App\Entity\UserSystem\User; use App\Entity\UserSystem\User;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@ -47,15 +49,15 @@ class EventLogger
/** /**
* Adds the given log entry to the Log, if the entry fullfills the global configured criterias. * Adds the given log entry to the Log, if the entry fullfills the global configured criterias.
* The change will not be flushed yet. * The change will not be flushed yet.
* @param AbstractLogEntry $logEntry *
* @return bool Returns true, if the event was added to log. * @return bool Returns true, if the event was added to log.
*/ */
public function log(AbstractLogEntry $logEntry): bool public function log(AbstractLogEntry $logEntry): bool
{ {
$user = $this->security->getUser(); $user = $this->security->getUser();
//If the user is not specified explicitly, set it to the current user //If the user is not specified explicitly, set it to the current user
if (($user === null || $user instanceof User) && $logEntry->getUser() === null) { if ((null === $user || $user instanceof User) && null === $logEntry->getUser()) {
if ($user === null) { if (null === $user) {
$repo = $this->em->getRepository(User::class); $repo = $this->em->getRepository(User::class);
$user = $repo->getAnonymousUser(); $user = $repo->getAnonymousUser();
} }
@ -64,6 +66,7 @@ class EventLogger
if ($this->shouldBeAdded($logEntry)) { if ($this->shouldBeAdded($logEntry)) {
$this->em->persist($logEntry); $this->em->persist($logEntry);
return true; return true;
} }
@ -72,13 +75,14 @@ class EventLogger
/** /**
* Adds the given log entry to the Log, if the entry fullfills the global configured criterias and flush afterwards. * Adds the given log entry to the Log, if the entry fullfills the global configured criterias and flush afterwards.
* @param AbstractLogEntry $logEntry *
* @return bool Returns true, if the event was added to log. * @return bool Returns true, if the event was added to log.
*/ */
public function logAndFlush(AbstractLogEntry $logEntry): bool public function logAndFlush(AbstractLogEntry $logEntry): bool
{ {
$tmp = $this->log($logEntry); $tmp = $this->log($logEntry);
$this->em->flush(); $this->em->flush();
return $tmp; return $tmp;
} }
@ -99,12 +103,12 @@ class EventLogger
} }
//Check if the event type is black listed //Check if the event type is black listed
if (!empty($blacklist) && $this->isObjectClassInArray($logEntry, $blacklist)) { if (! empty($blacklist) && $this->isObjectClassInArray($logEntry, $blacklist)) {
return false; return false;
} }
//Check for whitelisting //Check for whitelisting
if (!empty($whitelist) && !$this->isObjectClassInArray($logEntry, $whitelist)) { if (! empty($whitelist) && ! $this->isObjectClassInArray($logEntry, $whitelist)) {
return false; return false;
} }
@ -113,15 +117,17 @@ class EventLogger
} }
/** /**
* Check if the object type is given in the classes array. This also works for inherited types * Check if the object type is given in the classes array. This also works for inherited types.
*
* @param object $object The object which should be checked * @param object $object The object which should be checked
* @param string[] $classes The list of class names that should be used for checking. * @param string[] $classes The list of class names that should be used for checking.
*
* @return bool * @return bool
*/ */
protected function isObjectClassInArray(object $object, array $classes): bool protected function isObjectClassInArray(object $object, array $classes): bool
{ {
//Check if the class is directly in the classes array //Check if the class is directly in the classes array
if (in_array(get_class($object), $classes)) { if (in_array(get_class($object), $classes, true)) {
return true; return true;
} }

View file

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony). * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
* *
@ -21,7 +24,6 @@
namespace App\Services\LogSystem; namespace App\Services\LogSystem;
use App\Entity\LogSystem\AbstractLogEntry; use App\Entity\LogSystem\AbstractLogEntry;
use App\Entity\LogSystem\DatabaseUpdatedLogEntry; use App\Entity\LogSystem\DatabaseUpdatedLogEntry;
use App\Entity\LogSystem\ElementCreatedLogEntry; use App\Entity\LogSystem\ElementCreatedLogEntry;
@ -36,7 +38,6 @@ use Symfony\Contracts\Translation\TranslatorInterface;
/** /**
* Format the Extra field of a log entry in a user readible form. * Format the Extra field of a log entry in a user readible form.
* @package App\Services\LogSystem
*/ */
class LogEntryExtraFormatter class LogEntryExtraFormatter
{ {
@ -49,7 +50,7 @@ class LogEntryExtraFormatter
/** /**
* Return an user viewable representation of the extra data in a log entry, styled for console output. * Return an user viewable representation of the extra data in a log entry, styled for console output.
* @param AbstractLogEntry $logEntry *
* @return string * @return string
*/ */
public function formatConsole(AbstractLogEntry $logEntry): string public function formatConsole(AbstractLogEntry $logEntry): string
@ -64,15 +65,15 @@ class LogEntryExtraFormatter
} }
/** /**
* Return a HTML formatted string containing a user viewable form of the Extra data * Return a HTML formatted string containing a user viewable form of the Extra data.
* @param AbstractLogEntry $context *
* @return string * @return string
*/ */
public function format(AbstractLogEntry $context): string public function format(AbstractLogEntry $context): string
{ {
if ($context instanceof UserLoginLogEntry || $context instanceof UserLogoutLogEntry) { if ($context instanceof UserLoginLogEntry || $context instanceof UserLogoutLogEntry) {
return sprintf( return sprintf(
"<i>%s</i>: %s", '<i>%s</i>: %s',
$this->translator->trans('log.user_login.ip'), $this->translator->trans('log.user_login.ip'),
htmlspecialchars($context->getIPAddress()) htmlspecialchars($context->getIPAddress())
); );
@ -113,7 +114,7 @@ class LogEntryExtraFormatter
); );
} }
if ($context instanceof ElementEditedLogEntry && !empty($context->getMessage())) { if ($context instanceof ElementEditedLogEntry && ! empty($context->getMessage())) {
return htmlspecialchars($context->getMessage()); return htmlspecialchars($context->getMessage());
} }
@ -123,7 +124,7 @@ class LogEntryExtraFormatter
$this->translator->trans($context->isWithdrawal() ? 'log.instock_changed.withdrawal' : 'log.instock_changed.added'), $this->translator->trans($context->isWithdrawal() ? 'log.instock_changed.withdrawal' : 'log.instock_changed.added'),
$context->getOldInstock(), $context->getOldInstock(),
$context->getNewInstock(), $context->getNewInstock(),
(!$context->isWithdrawal() ? '+' : '-') . $context->getDifference(true), (! $context->isWithdrawal() ? '+' : '-').$context->getDifference(true),
$this->translator->trans('log.instock_changed.comment'), $this->translator->trans('log.instock_changed.comment'),
htmlspecialchars($context->getComment()) htmlspecialchars($context->getComment())
); );
@ -133,6 +134,6 @@ class LogEntryExtraFormatter
return htmlspecialchars($context->getMessage()); return htmlspecialchars($context->getMessage());
} }
return ""; return '';
} }
} }

View file

@ -34,8 +34,8 @@ use Symfony\Component\Translation\MessageCatalogue;
*/ */
final class PermissionExtractor implements ExtractorInterface final class PermissionExtractor implements ExtractorInterface
{ {
protected $permission_structure; private $permission_structure;
protected $finished = false; private $finished = false;
public function __construct(PermissionResolver $resolver) public function __construct(PermissionResolver $resolver)
{ {