Skip to content

Commit

Permalink
Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
liquetsoft committed Sep 11, 2024
1 parent c133f0a commit 79d7636
Show file tree
Hide file tree
Showing 28 changed files with 115 additions and 74 deletions.
5 changes: 3 additions & 2 deletions generator/ResourceTestGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,16 @@ class ResourceTestGenerator extends AbstractGenerator
protected function generateClassByDescriptor(EntityDescriptor $descriptor, \SplFileInfo $dir, string $namespace): void
{
$name = $this->unifyClassName($descriptor->getName());
$fullPath = "{$dir->getPathname()}/{$name}Test.php";
$testName = "{$name}Test";
$fullPath = "{$dir->getPathname()}/{$testName}.php";

$phpFile = new PhpFile();
$phpFile->setStrictTypes();

$namespace = $phpFile->addNamespace($namespace);
$this->decorateNamespace($namespace, $descriptor);

$class = $namespace->addClass($name)->setExtends(BaseCase::class);
$class = $namespace->addClass($testName)->setExtends(BaseCase::class);
$this->decorateClass($class, $descriptor);

file_put_contents($fullPath, (new PsrPrinter())->printFile($phpFile));
Expand Down
42 changes: 20 additions & 22 deletions src/Storage/EloquentStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@ class EloquentStorage implements Storage
*
* @var int
*/
protected $insertBatch;
private $insertBatch;

/**
* Объект для логгирования данных.
*
* @var LoggerInterface|null
*/
protected $logger;
private $logger;

/**
* Сохраненные в памяти данные для множественной вставки.
Expand All @@ -37,7 +37,7 @@ class EloquentStorage implements Storage
*
* @var array<string, array<int, array<string, mixed>>>
*/
protected $insertData = [];
private $insertData = [];

/**
* Сохраненные в памяти данные для множественного обновления.
Expand All @@ -46,22 +46,22 @@ class EloquentStorage implements Storage
*
* @var array<string, array<string, array<string, mixed>>>
*/
protected $upsertData = [];
private $upsertData = [];

/**
* Список колонок для классов моделей.
*
* @var array<string, string[]>
*/
protected $columnsLists = [];
private $columnsLists = [];

/**
* Флаг, который обозначает, что после завершения работы нужно включить
* логгирование.
*
* @var bool
*/
protected $needToEnableLogging = false;
private $needToEnableLogging = false;

public function __construct(int $insertBatch = 1000, ?LoggerInterface $logger = null)
{
Expand Down Expand Up @@ -148,7 +148,7 @@ public function delete(object $entity): void
}
unset($persistedModel);
} catch (\Throwable $e) {
throw new StorageException("Can't delete entity from storage.", 0, $e);
throw new StorageException("Can't delete entity from storage", 0, $e);
}
}

Expand All @@ -173,15 +173,14 @@ public function truncate(string $entityClassName): void
{
if (!class_exists($entityClassName) || !is_subclass_of($entityClassName, Model::class)) {
throw new StorageException(
"Entity class for truncating must exists and extends '" . Model::class . "'"
. "got '{$entityClassName}'."
"Entity class for truncating must exists and extends '" . Model::class . "' got '{$entityClassName}'"
);
}

try {
$entityClassName::query()->delete();
} catch (\Throwable $e) {
throw new StorageException("Can't truncate storage.", 0, $e);
throw new StorageException("Can't truncate storage", 0, $e);
}
}

Expand All @@ -191,7 +190,7 @@ public function truncate(string $entityClassName): void
*
* @throws StorageException
*/
protected function checkAndFlushInsert(bool $forceInsert = false): void
private function checkAndFlushInsert(bool $forceInsert = false): void
{
foreach ($this->insertData as $className => $insertData) {
if ($forceInsert || \count($insertData) >= $this->insertBatch) {
Expand All @@ -209,7 +208,7 @@ protected function checkAndFlushInsert(bool $forceInsert = false): void
*
* @psalm-suppress InvalidStringClass
*/
protected function checkAndFlushUpsert(bool $forceUpsert = false): void
private function checkAndFlushUpsert(bool $forceUpsert = false): void
{
foreach ($this->upsertData as $className => $upsertData) {
if (!$forceUpsert && \count($upsertData) < $this->insertBatch) {
Expand All @@ -231,7 +230,7 @@ protected function checkAndFlushUpsert(bool $forceUpsert = false): void
try {
$persistedModel->save();
} catch (\Throwable $e) {
throw new StorageException("Can't update item in storage.", 0, $e);
throw new StorageException("Can't update item in storage", 0, $e);
}
} else {
$toInsert[] = $upsertItem;
Expand All @@ -251,12 +250,11 @@ protected function checkAndFlushUpsert(bool $forceUpsert = false): void
*
* @throws StorageException
*/
protected function checkIsEntityAllowedForEloquent(object $entity): Model
private function checkIsEntityAllowedForEloquent(object $entity): Model
{
if (!($entity instanceof Model)) {
throw new StorageException(
"Entity must be instance of '" . Model::class
. "', got '" . \get_class($entity) . "'."
"Entity must be instance of '" . Model::class . "', got '" . \get_class($entity) . "'"
);
}

Expand All @@ -268,7 +266,7 @@ protected function checkIsEntityAllowedForEloquent(object $entity): Model
*
* @return array<string, mixed>
*/
protected function collectValuesFromModel(Model $entity): array
private function collectValuesFromModel(Model $entity): array
{
$columns = $this->getColumnsListForModel($entity);

Expand All @@ -290,7 +288,7 @@ protected function collectValuesFromModel(Model $entity): array
*
* @return string[]
*/
protected function getColumnsListForModel(Model $model): array
private function getColumnsListForModel(Model $model): array
{
$class = \get_class($model);

Expand All @@ -312,7 +310,7 @@ protected function getColumnsListForModel(Model $model): array
*
* @psalm-suppress InvalidStringClass
*/
protected function bulkInsert(string $className, array $data): void
private function bulkInsert(string $className, array $data): void
{
try {
$className::insert($data);
Expand All @@ -330,15 +328,15 @@ protected function bulkInsert(string $className, array $data): void
*
* @psalm-suppress InvalidStringClass
*/
protected function bulkInsertFallback(string $className, array $data): void
private function bulkInsertFallback(string $className, array $data): void
{
foreach ($data as $item) {
try {
$className::insert([$item]);
} catch (\Throwable $e) {
$this->log(
LogLevel::ERROR,
"Error while inserting item of class '{$className}' to eloquent storage. Item wasn't proceed.",
"Error while inserting item of class '{$className}' to eloquent storage. Item wasn't proceed",
[
'item' => $item,
'error_message' => $e->getMessage(),
Expand All @@ -351,7 +349,7 @@ protected function bulkInsertFallback(string $className, array $data): void
/**
* Запись сообщения в лог.
*/
protected function log(string $errorLevel, string $message, array $context = []): void
private function log(string $errorLevel, string $message, array $context = []): void
{
if ($this->logger) {
$this->logger->log($errorLevel, $message, $context);
Expand Down
6 changes: 3 additions & 3 deletions tests/BaseCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@
*/
abstract class BaseCase extends TestCase
{
private ?Generator $faker;
private ?Generator $faker = null;

private ?FileSystemHelperInterface $fs;
private ?FileSystemHelperInterface $fs = null;

private ?string $tempDir;
private ?string $tempDir = null;

/**
* Возвращает объект php faker для генерации случайных данных.
Expand Down
22 changes: 10 additions & 12 deletions tests/Pipeline/InstallPipelineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Liquetsoft\Fias\Component\EntityField\BaseEntityField;
use Liquetsoft\Fias\Component\EntityManager\BaseEntityManager;
use Liquetsoft\Fias\Component\EntityRegistry\ArrayEntityRegistry;
use Liquetsoft\Fias\Component\FiasInformer\InformerResponse;
use Liquetsoft\Fias\Component\Pipeline\Pipe\ArrayPipe;
use Liquetsoft\Fias\Component\Pipeline\Pipe\Pipe;
use Liquetsoft\Fias\Component\Pipeline\State\ArrayState;
Expand Down Expand Up @@ -67,7 +66,10 @@ protected function setUp(): void
'type' => 'integer',
'primary' => true,
],
'url' => [
'fullurl' => [
'type' => 'string',
],
'deltaurl' => [
'type' => 'string',
],
'created_at' => [
Expand All @@ -86,17 +88,14 @@ public function testInstall(): void
$testArchive = "{$testDir}/install.zip";
copy(__DIR__ . '/_fixtures/install.zip', $testArchive);

$version = $this->createFakeData()->numberBetween(1, 1000);
$versionUrl = $this->createFakeData()->url();
$versionInfo = $this->getMockBuilder(InformerResponse::class)->getMock();
$versionInfo->method('getVersion')->willReturn($version);
$versionInfo->method('getUrl')->willReturn($versionUrl);
$versionInfo->method('hasResult')->willReturn(true);
$version = 123;
$versionUrl = 'https://test.test/full';

$state = new ArrayState();
$state->setAndLockParameter(StateParameter::DOWNLOAD_TO_FILE, new \SplFileInfo($testArchive));
$state->setAndLockParameter(StateParameter::EXTRACT_TO_FOLDER, new \SplFileInfo($testDir));
$state->setAndLockParameter(StateParameter::FIAS_INFO, $versionInfo);
$state->setAndLockParameter(StateParameter::PATH_TO_DOWNLOAD_FILE, $testArchive);
$state->setAndLockParameter(StateParameter::PATH_TO_EXTRACT_FOLDER, $testDir);
$state->setAndLockParameter(StateParameter::FIAS_NEXT_VERSION_NUMBER, $version);
$state->setAndLockParameter(StateParameter::FIAS_VERSION_ARCHIVE_URL, $versionUrl);

$pipeline = $this->createPipeLine();
$pipeline->run($state);
Expand All @@ -106,7 +105,6 @@ public function testInstall(): void
'fias_laravel_fias_version',
[
'version' => $version,
'url' => $versionUrl,
]
);
$this->assertDatabaseHasRow(
Expand Down
22 changes: 10 additions & 12 deletions tests/Pipeline/UpdatePipelineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use Liquetsoft\Fias\Component\EntityField\BaseEntityField;
use Liquetsoft\Fias\Component\EntityManager\BaseEntityManager;
use Liquetsoft\Fias\Component\EntityRegistry\ArrayEntityRegistry;
use Liquetsoft\Fias\Component\FiasInformer\InformerResponse;
use Liquetsoft\Fias\Component\Pipeline\Pipe\ArrayPipe;
use Liquetsoft\Fias\Component\Pipeline\Pipe\Pipe;
use Liquetsoft\Fias\Component\Pipeline\State\ArrayState;
Expand Down Expand Up @@ -66,7 +65,10 @@ protected function setUp(): void
'type' => 'integer',
'primary' => true,
],
'url' => [
'fullurl' => [
'type' => 'string',
],
'deltaurl' => [
'type' => 'string',
],
'created_at' => [
Expand All @@ -85,17 +87,14 @@ public function testUpdate(): void
$testArchive = "{$testDir}/update.zip";
copy(__DIR__ . '/_fixtures/update.zip', $testArchive);

$version = $this->createFakeData()->numberBetween(1, 1000);
$versionUrl = $this->createFakeData()->url();
$versionInfo = $this->getMockBuilder(InformerResponse::class)->getMock();
$versionInfo->method('getVersion')->willReturn($version);
$versionInfo->method('getUrl')->willReturn($versionUrl);
$versionInfo->method('hasResult')->willReturn(true);
$version = 123;
$versionUrl = 'https://test.test/full';

$state = new ArrayState();
$state->setAndLockParameter(StateParameter::DOWNLOAD_TO_FILE, new \SplFileInfo($testArchive));
$state->setAndLockParameter(StateParameter::EXTRACT_TO_FOLDER, new \SplFileInfo($testDir));
$state->setAndLockParameter(StateParameter::FIAS_INFO, $versionInfo);
$state->setAndLockParameter(StateParameter::PATH_TO_DOWNLOAD_FILE, $testArchive);
$state->setAndLockParameter(StateParameter::PATH_TO_EXTRACT_FOLDER, $testDir);
$state->setAndLockParameter(StateParameter::FIAS_NEXT_VERSION_NUMBER, $version);
$state->setAndLockParameter(StateParameter::FIAS_VERSION_ARCHIVE_URL, $versionUrl);

$pipeline = $this->createPipeLine();
$pipeline->run($state);
Expand All @@ -105,7 +104,6 @@ public function testUpdate(): void
'fias_laravel_fias_version',
[
'version' => $version,
'url' => $versionUrl,
]
);
$this->assertDatabaseHasRow(
Expand Down
4 changes: 3 additions & 1 deletion tests/Resource/AddrObjDivisionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

/**
* Тест ресурса для сущности 'AddrObjDivision'.
*
* @internal
*/
class AddrObjDivision extends BaseCase
class AddrObjDivisionTest extends BaseCase
{
/**
* Проверяет, что ресурс верно преобразует сущность в массив.
Expand Down
4 changes: 3 additions & 1 deletion tests/Resource/AddrObjTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

/**
* Тест ресурса для сущности 'AddrObj'.
*
* @internal
*/
class AddrObj extends BaseCase
class AddrObjTest extends BaseCase
{
/**
* Проверяет, что ресурс верно преобразует сущность в массив.
Expand Down
4 changes: 3 additions & 1 deletion tests/Resource/AddrObjTypesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

/**
* Тест ресурса для сущности 'AddrObjTypes'.
*
* @internal
*/
class AddrObjTypes extends BaseCase
class AddrObjTypesTest extends BaseCase
{
/**
* Проверяет, что ресурс верно преобразует сущность в массив.
Expand Down
4 changes: 3 additions & 1 deletion tests/Resource/AdmHierarchyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

/**
* Тест ресурса для сущности 'AdmHierarchy'.
*
* @internal
*/
class AdmHierarchy extends BaseCase
class AdmHierarchyTest extends BaseCase
{
/**
* Проверяет, что ресурс верно преобразует сущность в массив.
Expand Down
4 changes: 3 additions & 1 deletion tests/Resource/ApartmentTypesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

/**
* Тест ресурса для сущности 'ApartmentTypes'.
*
* @internal
*/
class ApartmentTypes extends BaseCase
class ApartmentTypesTest extends BaseCase
{
/**
* Проверяет, что ресурс верно преобразует сущность в массив.
Expand Down
4 changes: 3 additions & 1 deletion tests/Resource/ApartmentsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

/**
* Тест ресурса для сущности 'Apartments'.
*
* @internal
*/
class Apartments extends BaseCase
class ApartmentsTest extends BaseCase
{
/**
* Проверяет, что ресурс верно преобразует сущность в массив.
Expand Down
4 changes: 3 additions & 1 deletion tests/Resource/CarplacesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@

/**
* Тест ресурса для сущности 'Carplaces'.
*
* @internal
*/
class Carplaces extends BaseCase
class CarplacesTest extends BaseCase
{
/**
* Проверяет, что ресурс верно преобразует сущность в массив.
Expand Down
Loading

0 comments on commit 79d7636

Please sign in to comment.