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"
- "common"
# very nice to have ↓
- "symplify"
# - "symplify"
- "symfony"
skip:

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,7 +24,6 @@
namespace App\Command;
use App\Entity\Base\NamedDBElement;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Services\ElementTypeNameGenerator;
@ -56,18 +58,6 @@ class ShowEventLogCommand extends Command
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)
{
$io = new SymfonyStyle($input, $output);
@ -83,11 +73,12 @@ class ShowEventLogCommand extends Command
$max_page = ceil($total_count / $limit);
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;
}
$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;
while ($continue && $page <= $max_page) {
@ -98,12 +89,23 @@ class ShowEventLogCommand extends Command
}
$continue = $io->confirm('Do you want to show the next page?');
$page++;
++$page;
}
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
{
$sorting = $desc ? 'ASC' : 'DESC';
@ -113,7 +115,7 @@ class ShowEventLogCommand extends Command
$entries = $this->repo->getLogsOrderedByTimestamp($sorting, $limit, $offset);
$table = new Table($output);
$table->setHeaderTitle("Page $page / $max_page");
$table->setHeaderTitle("Page ${page} / ${max_page}");
$headers = ['ID', 'Timestamp', 'Type', 'User', 'Target Type', 'Target'];
if ($showExtra) {
$headers[] = 'Extra data';
@ -130,15 +132,15 @@ class ShowEventLogCommand extends Command
protected function addTableRow(Table $table, AbstractLogEntry $entry, bool $showExtra): void
{
$target = $this->repo->getTargetElement($entry);
$target_name = "";
$target_name = '';
if ($target instanceof NamedDBElement) {
$target_name = $target->getName() . ' <info>(' . $target->getID() . ')</info>';
$target_name = $target->getName().' <info>('.$target->getID().')</info>';
} elseif ($entry->getTargetID()) {
$target_name = '<info>(' . $entry->getTargetID() . ')</info>';
$target_name = '<info>('.$entry->getTargetID().')</info>';
}
$target_class = "";
if ($entry->getTargetClass() !== null) {
$target_class = '';
if (null !== $entry->getTargetClass()) {
$target_class = $this->elementTypeNameGenerator->getLocalizedTypeLabel($entry->getTargetClass());
}
@ -148,7 +150,7 @@ class ShowEventLogCommand extends Command
$entry->getType(),
$entry->getUser()->getFullName(true),
$target_class,
$target_name
$target_name,
];
if ($showExtra) {
@ -157,4 +159,4 @@ class ShowEventLogCommand extends Command
$table->addRow($row);
}
}
}

View file

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

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -34,35 +37,72 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
* 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
* the Doctrine Paginator.
*
* @author Jan Böhmer
*/
class FetchJoinORMAdapter extends ORMAdapter
{
protected $use_simple_total;
public function configure(array $options)
public function configure(array $options): void
{
parent::configure($options);
$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);
//Enforce object hydration mode (fetch join only works for objects)
$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.
* You can only use this option, if you did not apply any criteria to your total count.
*/
$resolver->setDefault('simple_total_query', false);
return $resolver;
}
protected function prepareQuery(AdapterQuery $query)
protected function prepareQuery(AdapterQuery $query): void
{
$state = $query->getState();
$query->set('qb', $builder = $this->createQueryBuilder($state));
@ -96,43 +136,6 @@ class FetchJoinORMAdapter extends ORMAdapter
$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)
{
/** 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 */
$from_expr = $queryBuilder->getDQLPart('from')[0];
return $this->manager->getRepository($from_expr->getFrom())->count([]);
}
}
}

View file

@ -37,28 +37,27 @@ use Symfony\Component\OptionsResolver\OptionsResolver;
*/
class ORMAdapter extends AbstractAdapter
{
/** @var ManagerRegistry */
private $registry;
/** @var EntityManager */
protected $manager;
/** @var \Doctrine\ORM\Mapping\ClassMetadata */
protected $metadata;
/** @var QueryBuilderProcessorInterface[] */
protected $criteriaProcessors;
/** @var ManagerRegistry */
private $registry;
/** @var int */
private $hydrationMode;
/** @var QueryBuilderProcessorInterface[] */
private $queryBuilderProcessors;
/** @var QueryBuilderProcessorInterface[] */
protected $criteriaProcessors;
/**
* DoctrineAdapter constructor.
*/
public function __construct(ManagerRegistry $registry = null)
public function __construct(?ManagerRegistry $registry = null)
{
if (null === $registry) {
throw new MissingDependencyException('Install doctrine/doctrine-bundle to use the ORMAdapter');
@ -68,10 +67,7 @@ class ORMAdapter extends AbstractAdapter
$this->registry = $registry;
}
/**
* {@inheritdoc}
*/
public function configure(array $options)
public function configure(array $options): void
{
$resolver = new OptionsResolver();
$this->configureOptions($resolver);
@ -92,15 +88,12 @@ class ORMAdapter extends AbstractAdapter
$this->criteriaProcessors = $options['criteria'];
}
/**
* @param mixed $processor
*/
public function addCriteriaProcessor($processor)
public function addCriteriaProcessor($processor): void
{
$this->criteriaProcessors[] = $this->normalizeProcessor($processor);
}
protected function prepareQuery(AdapterQuery $query)
protected function prepareQuery(AdapterQuery $query): void
{
$state = $query->getState();
$query->set('qb', $builder = $this->createQueryBuilder($state));
@ -150,7 +143,7 @@ class ORMAdapter extends AbstractAdapter
continue;
}
list($origin, $target) = explode('.', $join->getJoin());
[$origin, $target] = explode('.', $join->getJoin());
$mapping = $aliases[$origin][1]->getAssociationMapping($target);
$aliases[$join->getAlias()] = [$join->getJoin(), $this->manager->getMetadataFactory()->getMetadataFor($mapping['targetEntity'])];
@ -160,9 +153,6 @@ class ORMAdapter extends AbstractAdapter
return $aliases;
}
/**
* {@inheritdoc}
*/
protected function mapPropertyPath(AdapterQuery $query, AbstractColumn $column)
{
return $this->mapFieldToPropertyPath($column->getField(), $query->get('aliases'));
@ -175,7 +165,7 @@ class ORMAdapter extends AbstractAdapter
$state = $query->getState();
// 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 */
if ($column->isOrderable()) {
$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) {
$provider->process($queryBuilder, $state);
@ -222,6 +212,7 @@ class ORMAdapter extends AbstractAdapter
/**
* @param $identifier
*
* @return int
*/
protected function getCount(QueryBuilder $queryBuilder, $identifier)
@ -230,21 +221,21 @@ class ORMAdapter extends AbstractAdapter
$qb->resetDQLPart('orderBy');
$gb = $qb->getDQLPart('groupBy');
if (empty($gb) || !$this->hasGroupByPart($identifier, $gb)) {
if (empty($gb) || ! $this->hasGroupByPart($identifier, $gb)) {
$qb->select($qb->expr()->count($identifier));
return (int) $qb->getQuery()->getSingleScalarResult();
} else {
$qb->resetDQLPart('groupBy');
$qb->select($qb->expr()->countDistinct($identifier));
return (int) $qb->getQuery()->getSingleScalarResult();
}
$qb->resetDQLPart('groupBy');
$qb->select($qb->expr()->countDistinct($identifier));
return (int) $qb->getQuery()->getSingleScalarResult();
}
/**
* @param $identifier
* @param Query\Expr\GroupBy[] $gbList
*
* @return bool
*/
protected function hasGroupByPart($identifier, array $gbList)
@ -260,6 +251,7 @@ class ORMAdapter extends AbstractAdapter
/**
* @param string $field
*
* @return string
*/
protected function mapFieldToPropertyPath($field, array $aliases = [])
@ -268,25 +260,25 @@ class ORMAdapter extends AbstractAdapter
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));
}
list($origin, $target) = $parts;
[$origin, $target] = $parts;
$path = [$target];
$current = $aliases[$origin][0];
while (null !== $current) {
list($origin, $target) = explode('.', $current);
[$origin, $target] = explode('.', $current);
$path[] = $target;
$current = $aliases[$origin][0];
}
if (Query::HYDRATE_ARRAY === $this->hydrationMode) {
return '[' . implode('][', array_reverse($path)) . ']';
} else {
return implode('.', array_reverse($path));
return '['.implode('][', array_reverse($path)).']';
}
return implode('.', array_reverse($path));
}
protected function configureOptions(OptionsResolver $resolver)
protected function configureOptions(OptionsResolver $resolver): void
{
$providerNormalizer = function (Options $options, $value) {
return array_map([$this, 'normalizeProcessor'], (array) $value);
@ -294,12 +286,12 @@ class ORMAdapter extends AbstractAdapter
$resolver
->setDefaults([
'hydrate' => Query::HYDRATE_OBJECT,
'query' => [],
'criteria' => function (Options $options) {
return [new SearchCriteriaProvider()];
},
])
'hydrate' => Query::HYDRATE_OBJECT,
'query' => [],
'criteria' => function (Options $options) {
return [new SearchCriteriaProvider()];
},
])
->setRequired('entity')
->setAllowedTypes('entity', ['string'])
->setAllowedTypes('hydrate', 'int')
@ -312,6 +304,7 @@ class ORMAdapter extends AbstractAdapter
/**
* @param callable|QueryBuilderProcessorInterface $provider
*
* @return QueryBuilderProcessorInterface
*/
private function normalizeProcessor($provider)

View file

@ -40,11 +40,11 @@ use Symfony\Contracts\Translation\TranslatorInterface;
final class AttachmentDataTable implements DataTableTypeInterface
{
protected $translator;
protected $entityURLGenerator;
protected $attachmentHelper;
protected $elementTypeNameGenerator;
protected $attachmentURLGenerator;
private $translator;
private $entityURLGenerator;
private $attachmentHelper;
private $elementTypeNameGenerator;
private $attachmentURLGenerator;
public function __construct(TranslatorInterface $translator, EntityURLGenerator $entityURLGenerator,
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')
->addSelect('attachment_type')

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,16 +24,6 @@
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 Omines\DataTablesBundle\Column\AbstractColumn;
use Symfony\Contracts\Translation\TranslatorInterface;
@ -46,9 +39,6 @@ class LogEntryExtraColumn extends AbstractColumn
$this->formatter = $formatter;
}
/**
* @inheritDoc
*/
public function normalize($value)
{
return $value;
@ -58,4 +48,4 @@ class LogEntryExtraColumn extends AbstractColumn
{
return $this->formatter->format($context);
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -1,4 +1,5 @@
<?php
declare(strict_types=1);
/**
@ -24,8 +25,10 @@ declare(strict_types=1);
namespace App\Entity\LogSystem;
use App\Entity\Attachments\Attachment;
use App\Entity\Attachments\AttachmentType;
use App\Entity\Base\DBElement;
use App\Entity\Devices\Device;
use App\Entity\Devices\DevicePart;
use App\Entity\Parts\Category;
use App\Entity\Parts\Footprint;
use App\Entity\Parts\Manufacturer;
@ -36,13 +39,11 @@ use App\Entity\UserSystem\Group;
use App\Entity\UserSystem\User;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Attachments\AttachmentType;
use App\Entity\Devices\DevicePart;
use Psr\Log\LogLevel;
/**
* This entity describes a entry in the event log.
* @package App\Entity\LogSystem
*
* @ORM\Entity(repositoryClass="App\Repository\LogEntryRepository")
* @ORM\Table("log")
* @ORM\InheritanceType("SINGLE_TABLE")
@ -97,7 +98,6 @@ abstract class AbstractLogEntry extends DBElement
self::LEVEL_DEBUG => LogLevel::DEBUG,
];
protected const TARGET_CLASS_MAPPING = [
self::TARGET_TYPE_USER => User::class,
self::TARGET_TYPE_ATTACHEMENT => Attachment::class,
@ -113,7 +113,7 @@ abstract class AbstractLogEntry extends DBElement
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\JoinColumn(name="id_user", nullable=false)
*/
@ -124,17 +124,17 @@ abstract class AbstractLogEntry extends DBElement
*/
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")
*/
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)
*/
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)
*/
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.
* 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
* @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.
*
* @return User
*/
public function getUser(): ?User
@ -167,17 +168,19 @@ abstract class AbstractLogEntry extends DBElement
/**
* Sets the user that caused the event.
* @param User $user
*
* @return $this
*/
public function setUser(User $user): self
{
$this->user = $user;
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
*/
public function getTimestamp(): DateTime
@ -187,18 +190,20 @@ abstract class AbstractLogEntry extends DBElement
/**
* Sets the timestamp when the event happened.
* @param DateTime $timestamp
*
* @return $this
*/
public function setTimestamp(DateTime $timestamp): AbstractLogEntry
public function setTimestamp(DateTime $timestamp): self
{
$this->timestamp = $timestamp;
return $this;
}
/**
* 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
*/
public function getLevel(): int
@ -207,25 +212,28 @@ abstract class AbstractLogEntry extends DBElement
if ($this->level < 0 || $this->level > 7) {
return self::LEVEL_ALERT;
}
return $this->level;
}
/**
* Sets the new level of this log entry.
* @param int $level
*
* @return $this
*/
public function setLevel(int $level): AbstractLogEntry
public function setLevel(int $level): self
{
if ($level < 0 || $this->level > 7) {
throw new \InvalidArgumentException(sprintf('$level must be between 0 and 7! %d given!', $level));
}
$this->level = $level;
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
*/
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
* @param string $level
* Sets the priority level of this log entry as PSR3 compatible string.
*
* @return $this
*/
public function setLevelString(string $level): AbstractLogEntry
public function setLevelString(string $level): self
{
$this->setLevel(self::levelStringToInt($level));
return $this;
}
/**
* Returns the type of the event this log entry is associated with.
*
* @return string
*/
public function getType(): string
@ -253,22 +263,20 @@ abstract class AbstractLogEntry extends DBElement
return $this->typeString;
}
/**
* @inheritDoc
*/
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 null, if this log entry is not associated with an log entry.
*
* @return string|null The class name of the target class.
*/
public function getTargetClass(): ?string
{
if ($this->target_type === self::TARGET_TYPE_NONE) {
if (self::TARGET_TYPE_NONE === $this->target_type) {
return null;
}
@ -278,11 +286,12 @@ abstract class AbstractLogEntry extends DBElement
/**
* 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.
*
* @return int|null The ID of the associated element.
*/
public function getTargetID(): ?int
{
if ($this->target_id === 0) {
if (0 === $this->target_id) {
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.
*/
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
* @param DBElement $element The element that should be associated with this element.
* Sets the target element associated with this element.
*
* @param DBElement $element The element that should be associated with this element.
*
* @return $this
*/
public function setTargetElement(?DBElement $element): self
{
if ($element === null) {
if (null === $element) {
$this->target_id = 0;
$this->target_type = self::TARGET_TYPE_NONE;
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.
* @param int $level The numerical log level
*
* @param int $level The numerical log level
*
* @return string The PSR3 compatible 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!');
}
@ -338,13 +353,15 @@ abstract class AbstractLogEntry extends DBElement
/**
* This function converts a PSR3 compatible string to the internal numeric level string.
*
* @param string $level the PSR3 compatible string that should be converted
*
* @return int The internal int representation.
*/
final public static function levelStringToInt(string $level): int
{
$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!');
}
@ -353,12 +370,14 @@ abstract class AbstractLogEntry extends DBElement
/**
* 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
*/
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!');
}
@ -367,7 +386,9 @@ abstract class AbstractLogEntry extends DBElement
/**
* 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.
*/
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!');
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -25,18 +28,18 @@ use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @package App\Entity\LogSystem
*/
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
*/
public function getMessage() : string
public function getMessage(): string
{
return $this->extra['m'] ?? '';
}
}
}

View file

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

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,20 +24,18 @@
namespace App\Entity\LogSystem;
use App\Entity\Parts\Part;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @package App\Entity\LogSystem
*/
class InstockChangedLogEntry extends AbstractLogEntry
{
protected $typeString = "instock_changed";
protected $typeString = 'instock_changed';
/**
* Get the old instock
* Get the old instock.
*
* @return int
*/
public function getOldInstock(): int
@ -43,7 +44,8 @@ class InstockChangedLogEntry extends AbstractLogEntry
}
/**
* Get the new instock
* Get the new instock.
*
* @return 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
*/
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).
* @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
*/
public function getPrice(bool $absolute = false): float
@ -70,18 +75,21 @@ class InstockChangedLogEntry extends AbstractLogEntry
if ($absolute) {
return abs($this->extra['p']);
}
return $this->extra['p'];
}
/**
* 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.
*/
public function getDifference(bool $absolute = false): int
{
// 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;
}
@ -95,11 +103,11 @@ class InstockChangedLogEntry extends AbstractLogEntry
/**
* Checks if the Change was an withdrawal of parts.
*
* @return bool True if the change was an withdrawal, false if not.
*/
public function isWithdrawal(): bool
{
return $this->getNewInstock() < $this->getOldInstock();
}
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -26,12 +29,12 @@ use Symfony\Component\HttpFoundation\IpUtils;
/**
* This log entry is created when a user logs in.
* @package App\Entity\LogSystem
*
* @ORM\Entity()
*/
class UserLoginLogEntry extends AbstractLogEntry
{
protected $typeString = "user_login";
protected $typeString = 'user_login';
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 string
*/
public function getIPAddress(): string
@ -50,9 +54,11 @@ class UserLoginLogEntry extends AbstractLogEntry
}
/**
* Sets 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
* Sets 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
*
* @return $this
*/
public function setIPAddress(string $ip, bool $anonymize = true): self
@ -62,6 +68,7 @@ class UserLoginLogEntry extends AbstractLogEntry
}
$this->extra['i'] = $ip;
return $this;
}
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,17 +24,15 @@
namespace App\Entity\LogSystem;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\IpUtils;
/**
* @ORM\Entity()
* @package App\Entity\LogSystem
*/
class UserLogoutLogEntry extends AbstractLogEntry
{
protected $typeString = "user_logout";
protected $typeString = 'user_logout';
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 string
*/
public function getIPAddress(): string
@ -50,9 +52,11 @@ class UserLogoutLogEntry extends AbstractLogEntry
}
/**
* Sets 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
* Sets 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
*
* @return $this
*/
public function setIPAddress(string $ip, bool $anonymize = true): self
@ -62,8 +66,7 @@ class UserLogoutLogEntry extends AbstractLogEntry
}
$this->extra['i'] = $ip;
return $this;
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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
*/
public const REDIRECT_TARGET = 'user_settings';
protected $security;
protected $flashBag;
protected $httpUtils;
private $security;
private $flashBag;
private $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
{
protected $kernel;
private $kernel;
public function __construct(ContainerInterface $kernel)
{

View file

@ -35,8 +35,8 @@ use Symfony\Component\Security\Core\Security;
*/
final class TimezoneListener implements EventSubscriberInterface
{
protected $default_timezone;
protected $security;
private $default_timezone;
private $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
{
protected $em;
private $em;
protected $demo_mode;
protected $flashBag;
private $demo_mode;
private $flashBag;
/**
* @var UrlGeneratorInterface
*/
@ -51,9 +51,6 @@ final class U2FRegistrationSubscriber implements EventSubscriberInterface
$this->flashBag = $flashBag;
}
/**
*
*/
public static function getSubscribedEvents(): array
{
return [

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,8 +24,7 @@
namespace App\Exceptions;
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
{
protected $resolver;
protected $inherit;
private $resolver;
private $inherit;
public function __construct(PermissionResolver $resolver, bool $inherit = false)
{

View file

@ -32,15 +32,15 @@ use JsonSerializable;
*/
final class TreeViewNode implements JsonSerializable
{
protected $text;
protected $href;
protected $nodes;
private $text;
private $href;
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.

View file

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

View file

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

View file

@ -12,15 +12,15 @@ use Doctrine\Migrations\AbstractMigration;
*/
final class Version20200126191823 extends AbstractMigration
{
public function getDescription() : string
public function getDescription(): string
{
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->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('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)');
}
public function down(Schema $schema) : void
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->abortIf('mysql' !== $this->connection->getDatabasePlatform()->getName(), 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE log DROP FOREIGN KEY FK_8F3F68C56B3CA4B');
$this->addSql('ALTER TABLE log DROP FOREIGN KEY FK_8F3F68C56B3CA4B');

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,15 +24,13 @@
namespace App\Repository;
use App\Entity\Base\DBElement;
use App\Entity\LogSystem\AbstractLogEntry;
use Doctrine\ORM\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
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)
* @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 null $limit
* @param null $offset
* 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 string $order By default newest entries are shown first. Change this to ASC to show oldest entries first.
* @param null $limit
* @param null $offset
*
* @return AbstractLogEntry[]
*/
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
* @param string $order
* @param null $limit
* @param null $offset
* Gets the last log entries ordered by timestamp.
*
* @param string $order
* @param null $limit
* @param null $offset
*
* @return array
*/
public function getLogsOrderedByTimestamp($order = 'DESC', $limit = null, $offset = null)
@ -69,19 +74,19 @@ class LogEntryRepository extends EntityRepository
/**
* 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
* was deleted from DB.
* was deleted from DB.
*/
public function getTargetElement(AbstractLogEntry $logEntry): ?DBElement
{
$class = $logEntry->getTargetClass();
$id = $logEntry->getTargetID();
if ($class === null || $id === null) {
if (null === $class || null === $id) {
return null;
}
return $this->getEntityManager()->find($class, $id);
}
}
}

View file

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

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,7 +24,6 @@
namespace App\Services\LogSystem;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Entity\UserSystem\User;
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.
* The change will not be flushed yet.
* @param AbstractLogEntry $logEntry
*
* @return bool Returns true, if the event was added to log.
*/
public function log(AbstractLogEntry $logEntry): bool
{
$user = $this->security->getUser();
//If the user is not specified explicitly, set it to the current user
if (($user === null || $user instanceof User) && $logEntry->getUser() === null) {
if ($user === null) {
if ((null === $user || $user instanceof User) && null === $logEntry->getUser()) {
if (null === $user) {
$repo = $this->em->getRepository(User::class);
$user = $repo->getAnonymousUser();
}
@ -64,6 +66,7 @@ class EventLogger
if ($this->shouldBeAdded($logEntry)) {
$this->em->persist($logEntry);
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.
* @param AbstractLogEntry $logEntry
*
* @return bool Returns true, if the event was added to log.
*/
public function logAndFlush(AbstractLogEntry $logEntry): bool
{
$tmp = $this->log($logEntry);
$this->em->flush();
return $tmp;
}
@ -99,12 +103,12 @@ class EventLogger
}
//Check if the event type is black listed
if (!empty($blacklist) && $this->isObjectClassInArray($logEntry, $blacklist)) {
if (! empty($blacklist) && $this->isObjectClassInArray($logEntry, $blacklist)) {
return false;
}
//Check for whitelisting
if (!empty($whitelist) && !$this->isObjectClassInArray($logEntry, $whitelist)) {
if (! empty($whitelist) && ! $this->isObjectClassInArray($logEntry, $whitelist)) {
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
* @param object $object The object which should be checked
* @param string[] $classes The list of class names that should be used for checking.
* 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 string[] $classes The list of class names that should be used for checking.
*
* @return bool
*/
protected function isObjectClassInArray(object $object, array $classes): bool
{
//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;
}
@ -134,4 +140,4 @@ class EventLogger
return false;
}
}
}

View file

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
*
@ -21,7 +24,6 @@
namespace App\Services\LogSystem;
use App\Entity\LogSystem\AbstractLogEntry;
use App\Entity\LogSystem\DatabaseUpdatedLogEntry;
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.
* @package App\Services\LogSystem
*/
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.
* @param AbstractLogEntry $logEntry
*
* @return 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
* @param AbstractLogEntry $context
* Return a HTML formatted string containing a user viewable form of the Extra data.
*
* @return string
*/
public function format(AbstractLogEntry $context): string
{
if ($context instanceof UserLoginLogEntry || $context instanceof UserLogoutLogEntry) {
return sprintf(
"<i>%s</i>: %s",
'<i>%s</i>: %s',
$this->translator->trans('log.user_login.ip'),
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());
}
@ -123,7 +124,7 @@ class LogEntryExtraFormatter
$this->translator->trans($context->isWithdrawal() ? 'log.instock_changed.withdrawal' : 'log.instock_changed.added'),
$context->getOldInstock(),
$context->getNewInstock(),
(!$context->isWithdrawal() ? '+' : '-') . $context->getDifference(true),
(! $context->isWithdrawal() ? '+' : '-').$context->getDifference(true),
$this->translator->trans('log.instock_changed.comment'),
htmlspecialchars($context->getComment())
);
@ -133,6 +134,6 @@ class LogEntryExtraFormatter
return htmlspecialchars($context->getMessage());
}
return "";
return '';
}
}
}

View file

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