Skip to content

Commit

Permalink
Component version 9 (#58)
Browse files Browse the repository at this point in the history
* update main component to 9 version

* psalm tests fixes
  • Loading branch information
marvin255 authored Apr 10, 2021
1 parent 572961e commit d5a89d2
Show file tree
Hide file tree
Showing 98 changed files with 343 additions and 246 deletions.
17 changes: 17 additions & 0 deletions .php_cs.dist
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ $rules = [
'phpdoc_no_empty_return' => false,
'no_superfluous_phpdoc_tags' => false,
'single_line_throw' => false,
'array_indentation' => true,
'declare_strict_types' => true,
'void_return' => true,
'non_printable_character' => true,
'modernize_types_casting' => true,
'ordered_interfaces' => ['order' => 'alpha', 'direction' => 'ascend'],
'date_time_immutable' => true,
'native_constant_invocation' => true,
'combine_nested_dirname' => true,
'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'namespaced', 'strict' => true],
'php_unit_construct' => true,
'php_unit_dedicate_assert' => true,
'php_unit_expectation' => true,
'php_unit_internal_class' => true,
'php_unit_mock_short_will_return' => true,
'php_unit_strict' => true,
'strict_comparison' => true,
];

return PhpCsFixer\Config::create()->setRules($rules)->setFinder($finder);
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ user_id := $(shell id -u)
docker_compose_bin := $(shell command -v docker-compose 2> /dev/null) --file "docker/docker-compose.yml"
php_container_bin := $(docker_compose_bin) run --rm -u "$(user_id)" "php"

.PHONY : help build install shell fixer test coverage entites
.PHONY : help build install shell fixer test coverage entities
.DEFAULT_GOAL := build

# --- [ Development tasks ] -------------------------------------------------------------------------------------------
Expand Down
18 changes: 13 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"license": "MIT",
"require": {
"php": ">=7.3",
"liquetsoft/fias-component": "^8.0",
"liquetsoft/fias-component": "^9.0",
"illuminate/database": "^6.0|^7.0|^8.0",
"laravel/framework": "^6.0|^7.0|^8.0"
},
Expand All @@ -16,7 +16,8 @@
"friendsofphp/php-cs-fixer": "^2.11",
"sebastian/phpcpd": "^4.0|^5.0|^6.0",
"vimeo/psalm": "^3.0|^4.0",
"nette/php-generator": "^3.2"
"nette/php-generator": "^3.2",
"psalm/plugin-phpunit": "^0.15.1"
},
"autoload": {
"psr-4": {
Expand All @@ -38,9 +39,16 @@
"scripts": {
"test": "vendor/bin/phpunit --configuration phpunit.xml.dist",
"coverage": "vendor/bin/phpunit --configuration phpunit.xml.dist --coverage-html=tests/coverage",
"fixer": "vendor/bin/php-cs-fixer fix --config=.php_cs.dist -v",
"linter": "vendor/bin/php-cs-fixer fix --config=.php_cs.dist -v --dry-run --stop-on-violation && vendor/bin/phpcpd ./ --exclude vendor --exclude src/Model --exclude tests && vendor/bin/psalm --show-info=true",
"entities": "php -f generator/generate_entities.php && vendor/bin/php-cs-fixer fix --config=.php_cs.dist -q"
"fixer": "vendor/bin/php-cs-fixer fix --config=.php_cs.dist -v --allow-risky=yes",
"linter": [
"vendor/bin/php-cs-fixer fix --config=.php_cs.dist -v --dry-run --stop-on-violation --allow-risky=yes",
"vendor/bin/phpcpd ./ --exclude vendor --exclude src/Model --exclude tests",
"vendor/bin/psalm --show-info=true"
],
"entities": [
"php -f generator/generate_entities.php",
"vendor/bin/php-cs-fixer fix --config=.php_cs.dist --allow-risky=yes -q"
]
},
"extra": {
"laravel": {
Expand Down
10 changes: 6 additions & 4 deletions generator/MigrationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ protected function generateClassByDescriptor(EntityDescriptor $descriptor, SplFi
$phpFile->addUse(Migration::class);
$phpFile->addUse(Blueprint::class);
$phpFile->addUse(Schema::class);
$phpFile->addUse(DB::class);
$phpFile->addUse(Connection::class);

if ($descriptor->getPartitionsCount() > 1) {
$phpFile->addUse(DB::class);
$phpFile->addUse(Connection::class);
}

$class = $phpFile->addClass($className)->addExtend(Migration::class);
$class->addComment("Миграция для создания сущности '{$descriptor->getName()}'.");
Expand All @@ -64,7 +67,7 @@ protected function decorateClassWithUpMethodByDescription(ClassType $class, Enti
;

$method->addBody("Schema::connection(config('liquetsoft_fias.eloquent_connection'))->dropIfExists('{$tableName}');");
$method->addBody("Schema::connection(config('liquetsoft_fias.eloquent_connection'))->create('{$tableName}', function (Blueprint \$table) {");
$method->addBody("Schema::connection(config('liquetsoft_fias.eloquent_connection'))->create('{$tableName}', function (Blueprint \$table): void {");
$method->addBody(' // создание полей таблицы');
foreach ($descriptor->getFields() as $field) {
$name = $this->unifyColumnName($field->getName());
Expand Down Expand Up @@ -138,7 +141,6 @@ protected function decorateClassWithUpMethodByDescription(ClassType $class, Enti
}
$partitioningPrimaries = implode(', ', $partitioningPrimaries);
$partitionFields = implode(', ', $partitionFields);
$method->addBody("\n");
$method->addBody('//для mysql большие таблицы нужно разбивать на части');
$method->addBody('$connection = DB::connection(config(\'liquetsoft_fias.eloquent_connection\'));');
$method->addBody("if (\$connection instanceof Connection && \$connection->getDriverName() === 'mysql') {");
Expand Down
4 changes: 2 additions & 2 deletions generator/ModelGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,12 +124,12 @@ protected function decorateClass(ClassType $class, EntityDescriptor $descriptor)
;

$connectionMethod = "\$connection = \$this->connection;\n";
$connectionMethod .= "if (function_exists('app') && app()->has('config')) {\n";
$connectionMethod .= "if (\\function_exists('app') && app()->has('config')) {\n";
$connectionMethod .= " \$connection = app('config')->get('liquetsoft_fias.eloquent_connection') ?: \$this->connection;\n";
$connectionMethod .= "}\n\n";
$connectionMethod .= 'return $connection;';
$class->addMethod('getConnectionName')
->addComment('@inheritDoc')
->addComment('{@inheritDoc}')
->setBody($connectionMethod)
;
}
Expand Down
10 changes: 7 additions & 3 deletions generator/ModelTestGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,14 @@ protected function decorateClass(ClassType $class, EntityDescriptor $descriptor)
$modelName = $this->unifyClassName($descriptor->getName());
$tableName = $this->convertClassnameToTableName($descriptor->getName());

$class->addComment("Тест для модели '{$modelName}'.\n");
$class->addComment("Тест для модели '{$modelName}'.\n\n@internal\n");

$class->addMethod('testGetTable')
->setVisibility('public')
->addComment('Проверяет, что модель привязана к правильной таблице в базе.')
->addBody("\$model = new {$modelName}();\n")
->addBody("\$this->assertSame('{$tableName}', \$model->getTable());")
->setReturnType('void')
;

$fillable = [];
Expand All @@ -83,13 +84,15 @@ protected function decorateClass(ClassType $class, EntityDescriptor $descriptor)
$class->addMethod('testGetFillable')
->setVisibility('public')
->addComment('Проверяет, что в модели доступны для заполнения все поля.')
->setReturnType('void')
->addBody("\$model = new {$modelName}();")
->addBody("\$fields = \$model->getFillable();\n")
->addBody(implode(";\n", $fillable))
->addBody(implode("\n", $fillable))
;

$class->addMethod('testGetIncrementing')
->setVisibility('public')
->setReturnType('void')
->addComment('Проверяет, что в модель не исрользует autoincrement.')
->addBody("\$model = new {$modelName}();\n")
->addBody('$this->assertFalse($model->getIncrementing());')
Expand All @@ -98,9 +101,10 @@ protected function decorateClass(ClassType $class, EntityDescriptor $descriptor)
if ($isPrimaryIsUuid) {
$class->addMethod('testGetKeyType')
->setVisibility('public')
->setReturnType('void')
->addComment('Проверяет, что в модели правильно задана обработка первичного ключа.')
->addBody("\$model = new {$modelName}();\n")
->addBody('$this->assertEquals(\'string\', $model->getKeyType());')
->addBody('$this->assertSame(\'string\', $model->getKeyType());')
;
}
}
Expand Down
4 changes: 2 additions & 2 deletions generator/ResourceGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ protected function decorateNamespace(PhpNamespace $namespace, EntityDescriptor $
protected function decorateClass(ClassType $class, EntityDescriptor $descriptor): void
{
$entityName = $this->unifyClassName($descriptor->getName());
$class->addComment("Ресурс для сущности '{$entityName}'.");
$class->addComment("Ресурс для сущности '{$entityName}'.\n");

$toArray = [];
foreach ($descriptor->getFields() as $field) {
$toArray[] = $this->decorateProperty($class, $field);
}
$methodBody = "return [\n " . implode(",\n ", $toArray) . "\n];";
$methodBody = "return [\n " . implode(",\n ", $toArray) . ",\n];";

$method = $class->addMethod('toArray')
->addComment("Преобразует сущность '{$entityName}' в массив.\n")
Expand Down
18 changes: 15 additions & 3 deletions generator/ResourceTestGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,25 @@ protected function generateClassByDescriptor(EntityDescriptor $descriptor, SplFi
*/
protected function decorateNamespace(PhpNamespace $namespace, EntityDescriptor $descriptor): void
{
$hasDateTime = false;
foreach ($descriptor->getFields() as $field) {
if ($field->getSubType() === 'date') {
$hasDateTime = true;
break;
}
}

$namespace->addUse(BaseCase::class);
$namespace->addUse(stdClass::class);
$namespace->addUse(Request::class);
$namespace->addUse(DateTimeInterface::class);
$namespace->addUse(stdClass::class);
$namespace->addUse(
'Liquetsoft\\Fias\\Laravel\\LiquetsoftFiasBundle\\Resource\\' . $this->unifyClassName($descriptor->getName()),
'Resource'
);

if ($hasDateTime) {
$namespace->addUse(DateTimeInterface::class);
}
}

/**
Expand Down Expand Up @@ -97,13 +108,14 @@ protected function decorateClass(ClassType $class, EntityDescriptor $descriptor)

$toArray[] = "\$model->{$name} = {$fake};";
}
$methodBody = "\$model = new stdClass;\n" . implode("\n", $toArray);
$methodBody = "\$model = new stdClass();\n" . implode("\n", $toArray);
$methodBody .= "\n\n\$resource = new Resource(\$model);";
$methodBody .= "\n\$request = \$this->getMockBuilder(Request::class)->disableOriginalConstructor()->getMock();";
$methodBody .= "\n\$array = \$resource->toArray(\$request);";
$methodBody .= "\n\n" . implode("\n", $toAssert);

$method = $class->addMethod('testToArray')
->setReturnType('void')
->addComment("Проверяет, что ресурс верно преобразует сущность в массив.\n")
->setVisibility('public')
->setBody($methodBody);
Expand Down
6 changes: 3 additions & 3 deletions generator/SerializerGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ protected function decorateClass(ClassType $class): void
{
$constants = [];

$denormalizeBody = '$data = is_array($data) ? $data : [];' . "\n";
$denormalizeBody = '$data = \\is_array($data) ? $data : [];' . "\n";
$denormalizeBody .= '$type = trim($type, " \t\n\r\0\x0B\\\\/");' . "\n\n";
$denormalizeBody .= "\$entity = \$context[AbstractNormalizer::OBJECT_TO_POPULATE] ?? new \$type();\n\n";
$denormalizeBody .= "if (!(\$entity instanceof Model)) {\n";
Expand Down Expand Up @@ -107,9 +107,9 @@ protected function decorateClass(ClassType $class): void
$class->addConstant('ALLOWED_ENTITIES', $constants)->setPrivate();

$supports = $class->addMethod('supportsDenormalization')
->addComment("@inheritDoc\n")
->addComment("{@inheritDoc}\n")
->setVisibility('public')
->setBody('return in_array(trim($type, " \t\n\r\0\x0B\\\\/"), self::ALLOWED_ENTITIES);');
->setBody('return \\in_array(trim($type, " \t\n\r\0\x0B\\\\/"), self::ALLOWED_ENTITIES);');
$supports->addParameter('data');
$supports->addParameter('type')->setType('string');
$supports->addParameter('format', new PhpLiteral('null'))->setType('string');
Expand Down
2 changes: 2 additions & 0 deletions generator/generate_entities.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

declare(strict_types=1);

use Liquetsoft\Fias\Component\EntityDescriptor\BaseEntityDescriptor;
use Liquetsoft\Fias\Component\EntityField\BaseEntityField;
use Liquetsoft\Fias\Component\EntityRegistry\ArrayEntityRegistry;
Expand Down
9 changes: 7 additions & 2 deletions psalm.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@
xsi:schemaLocation="https://getpsalm.org/schema/config file:///var/www/vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="./src" />
<directory name="./src"/>
<directory name="./tests"/>
<ignoreFiles>
</ignoreFiles>
</projectFiles>

<issueHandlers>
<PropertyNotSetInConstructor errorLevel="suppress" />
<PropertyNotSetInConstructor errorLevel="suppress"/>
</issueHandlers>

<plugins>
<pluginClass class="Psalm\PhpUnitPlugin\Plugin"/>
</plugins>
</psalm>
8 changes: 4 additions & 4 deletions src/Command/DownloadCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public function handle(): void
private function getVersion(): string
{
$version = $this->argument('version');
$version = (string) (is_array($version) ? reset($version) : $version);
$version = (string) (\is_array($version) ? reset($version) : $version);

return $version;
}
Expand All @@ -104,8 +104,8 @@ private function getPathToDownload(): SplFileInfo
{
$version = $this->getVersion();
$target = $this->argument('pathToDownload');
$target = (string) (is_array($target) ? reset($target) : $target);
$target = rtrim($target, '/\\') . DIRECTORY_SEPARATOR . 'fias_' . $version . '.zip';
$target = (string) (\is_array($target) ? reset($target) : $target);
$target = rtrim($target, '/\\') . \DIRECTORY_SEPARATOR . 'fias_' . $version . '.zip';

return new SplFileInfo($target);
}
Expand Down Expand Up @@ -149,7 +149,7 @@ private function findUrlForVersion(string $version): string
*/
private function extract(SplFileInfo $archive): void
{
$extractTo = $archive->getPath() . DIRECTORY_SEPARATOR . $archive->getBasename('.zip');
$extractTo = $archive->getPath() . \DIRECTORY_SEPARATOR . $archive->getBasename('.zip');
$extractTo = new SplFileInfo($extractTo);

$this->fs->mkdirIfNotExist($extractTo);
Expand Down
2 changes: 1 addition & 1 deletion src/Command/InstallFromFolderCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function __construct(Application $app)
public function handle(): void
{
$folder = $this->argument('folder');
$folder = realpath(is_array($folder) ? (string) reset($folder) : (string) $folder);
$folder = realpath(\is_array($folder) ? (string) reset($folder) : (string) $folder);
if (!is_dir($folder)) {
throw new InvalidArgumentException("Can't find '{$folder}' folder to read FIAS files.");
}
Expand Down
4 changes: 2 additions & 2 deletions src/Command/InstallParallelRunningCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ public function __construct(Application $app)
public function handle(): void
{
$filesToInsert = $this->argument('files_to_insert');
if (is_array($filesToInsert)) {
if (\is_array($filesToInsert)) {
$filesToInsert = reset($filesToInsert);
}
$filesToInsert = json_decode((string) $filesToInsert, true);

$filesToDelete = $this->argument('files_to_delete');
if (is_array($filesToDelete)) {
if (\is_array($filesToDelete)) {
$filesToDelete = reset($filesToDelete);
}
$filesToDelete = json_decode((string) $filesToDelete, true);
Expand Down
2 changes: 1 addition & 1 deletion src/Command/UpdateFromFolderCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function __construct(Application $app)
public function handle(): void
{
$folder = $this->argument('folder');
$folder = realpath(is_array($folder) ? (string) reset($folder) : (string) $folder);
$folder = realpath(\is_array($folder) ? (string) reset($folder) : (string) $folder);
if (!is_dir($folder)) {
throw new InvalidArgumentException("Can't find '{$folder}' folder to read FIAS files.");
}
Expand Down
2 changes: 1 addition & 1 deletion src/Command/VersionSetCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ private function getVersion(int $number): InformerResponse
private function getNumber(): int
{
$number = $this->argument('number');
$number = is_array($number) ? (int) reset($number) : (int) $number;
$number = \is_array($number) ? (int) reset($number) : (int) $number;
if ($number <= 0) {
throw new InvalidArgumentException('Version number must integer instance more than 0.');
}
Expand Down
2 changes: 1 addition & 1 deletion src/Command/VersionsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public function handle(): void
}

$deltaVersions = $this->informer->getDeltaList();
$this->showTable('Delta versions of FIAS', array_slice($deltaVersions, 0, 15));
$this->showTable('Delta versions of FIAS', \array_slice($deltaVersions, 0, 15));

$this->line('');
}
Expand Down
2 changes: 2 additions & 0 deletions src/Config/liquetsoft_fias.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

declare(strict_types=1);

use Liquetsoft\Fias\Laravel\LiquetsoftFiasBundle\Entity\ActualStatus;
use Liquetsoft\Fias\Laravel\LiquetsoftFiasBundle\Entity\AddressObject;
use Liquetsoft\Fias\Laravel\LiquetsoftFiasBundle\Entity\AddressObjectType;
Expand Down
2 changes: 1 addition & 1 deletion src/Entity/ActualStatus.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class ActualStatus extends Model
public function getConnectionName()
{
$connection = $this->connection;
if (function_exists('app') && app()->has('config')) {
if (\function_exists('app') && app()->has('config')) {
$connection = app('config')->get('liquetsoft_fias.eloquent_connection') ?: $this->connection;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Entity/AddressObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ class AddressObject extends Model
public function getConnectionName()
{
$connection = $this->connection;
if (function_exists('app') && app()->has('config')) {
if (\function_exists('app') && app()->has('config')) {
$connection = app('config')->get('liquetsoft_fias.eloquent_connection') ?: $this->connection;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Entity/AddressObjectType.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class AddressObjectType extends Model
public function getConnectionName()
{
$connection = $this->connection;
if (function_exists('app') && app()->has('config')) {
if (\function_exists('app') && app()->has('config')) {
$connection = app('config')->get('liquetsoft_fias.eloquent_connection') ?: $this->connection;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Entity/CenterStatus.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class CenterStatus extends Model
public function getConnectionName()
{
$connection = $this->connection;
if (function_exists('app') && app()->has('config')) {
if (\function_exists('app') && app()->has('config')) {
$connection = app('config')->get('liquetsoft_fias.eloquent_connection') ?: $this->connection;
}

Expand Down
Loading

0 comments on commit d5a89d2

Please sign in to comment.