Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/Decorator/DecoratorManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не хватает объявления declare(strict_types=1); для строгой проверки входящих параметров функций

namespace src\Decorator;

use DateTime;
use Exception;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;
use src\Integration\DataProvider;

class DecoratorManager extends DataProvider
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Плохое название класса. По сути, это DataProvider с возможностью использования кэша. Скорее всего это какой-нибудь CachedDataProvider

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше использовать не наследование, а композицию. Увеличивает переиспользуемость кода

{
public $cache;
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет phpDoc для свойств

область видимости свойства объекта должна быть private, так как оно устанавливается через конструктор. При необходимости замены значения этого свойства после инициализации. лучше использовать соответствующий сеттер как минимум для контроля типа значения в свойстве

аналогично для свойства $logger - у него уже есть сеттер

public $logger;

/**
* @param string $host
* @param string $user
* @param string $password
* @param CacheItemPoolInterface $cache
*/
public function __construct($host, $user, $password, CacheItemPoolInterface $cache)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. нет типизации на аргументах $host, $user, $password
  2. в логике реализации заложено обязательное наличие свойства $logger в объекте, поэтому его стоит вынести в конструктор

В случае с использованием композиции. конструктор будет выглядеть так:
public function __construct(DataProviderInterface $dataProvider,CacheItemPoolInterface $cache, LoggerInterface $logger)

{
parent::__construct($host, $user, $password);
$this->cache = $cache;
}

public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}

/**
* {@inheritdoc}
*/
public function getResponse(array $input)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

некорректный phpDoc (в родителе DataProvider нет метода getResponse) или ошибка в названии метода и аргумента - должно быть get(array $request) (если этот метод должен переопределять родительский)

{
try {
$cacheKey = $this->getCacheKey($input);
$cacheItem = $this->cache->getItem($cacheKey);
if ($cacheItem->isHit()) {
return $cacheItem->get();
}

$result = parent::get($input);

$cacheItem
->set($result)
->expiresAt(
(new DateTime())->modify('+1 day')
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Срок действия кэша лучше задавать аргументом в конструктор. для увеличения переиспользованности класса

);

return $result;
} catch (Exception $e) {
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Желательно обрабатывать ошибки по интерфейсу \Throwable

$this->logger->critical('Error');
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если logger не обязательное свойство объекта. то должна быть проверка if (null !== $this->logger) {...

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не информативное сообщение лога

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

некорректный уровень логирования - скорее всего должно быть $this->logger->error

}

return [];
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Некорректно в случае возникновения ошибки возвращать пустой массив. Во-первых, это может быть не тот тип данных, который ожидается клиентом; во-вторых, логика клиента при пустом ответе и при возникновении ошибки, скорее всего, должна различаться

}

public function getCacheKey(array $input)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

отсутствует phpDoc метода

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

область видимости метода должена быть private, так как нет смысла его снаружи

{
return json_encode($input);
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

необходимо предусмотреть вероятность изменения порядка ключей в массиве, так как для двух одинаковых по логике массивов

[
  'key1' => 'value1',
  'key2' => 'value2',
]

[
  'key2' => 'value2',
  'key1' => 'value1',
]

метод будет отдавать разные ключи и не будет использовать кэш

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

встроенные функции необходимо вызывать через глобальное пространство имён для повышения производительности https://veewee.github.io/blog/optimizing-php-performance-by-fq-function-calls/

}
}
32 changes: 32 additions & 0 deletions src/Integration/DataProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не хватает объявления declare(strict_types=1); для строгой проверки входящих параметров функций

namespace src\Integration;

class DataProvider
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше создать интерфейс, на который можно было бы завязывать другие сервисы

{
private $host;
private $user;
private $password;
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет phpDoc для свойств


/**
* @param $host
* @param $user
* @param $password
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет описания типов аргументов

*/
public function __construct($host, $user, $password)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не типизированы аргументы

{
$this->host = $host;
$this->user = $user;
$this->password = $password;
}

/**
* @param array $request
*
* @return array
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если есть возможность. необходимо описать какие типы данных или какую структуру имеет возвращаемый массив

*/
public function get(array $request)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет типизации для возвращаемого значения

public function get(array $request): array

{
// returns a response from external service
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут точно не должно быть реализации?

}
}