diff --git a/.gitattributes b/.gitattributes index 29a574c..d982ce3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,8 +1,11 @@ * text=auto -/.github export-ignore -/tests export-ignore -/*.md export-ignore -/LICENSE* export-ignore -/.* export-ignore -/phpunit.xml export-ignore +/.github export-ignore +/tests export-ignore +/[Dd]ocker* export-ignore +/CODE_OF_CONDUCT.md export-ignore +/CONTRIBUTING.md export-ignore +/.* export-ignore +/phpunit.xml* export-ignore +/phpstan.* export-ignore +/Makefile export-ignore diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..a0c6fb4 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,3 @@ +# @link + +* @tarampampam diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 0c6a525..d9d8466 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -5,7 +5,11 @@ ## Description -> Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change. + Fixes # (issue) @@ -17,9 +21,13 @@ Fixes # (issue) - [ ] I wrote unit tests for my code - [ ] I have made changes in [CHANGELOG.md](https://github.com/avto-dev/static-references-laravel/blob/master/CHANGELOG.md) file -> About your changes in `CHANGELOG.md`: -> -> * Add new version header like `## v1.x.x`, if it does not exists -> * Add description under `added`/`changed`/`fixed` sections -> * Add reference to closed issues `[#000]` -> * Add link to issue in the end of document + diff --git a/.scrutinizer.yml b/.scrutinizer.yml deleted file mode 100644 index 71cdc8e..0000000 --- a/.scrutinizer.yml +++ /dev/null @@ -1,34 +0,0 @@ -filter: - excluded_paths: - - tests/ - dependency_paths: - - vendor/ - -checks: - php: - code_rating: true - duplication: true - -build_failure_conditions: -- 'elements.rating(<= D).exists' # No classes/methods with a rating of D or worse - -build: - environment: - mysql: false - postgresql: false - mongodb: false - elasticsearch: false - redis: false - memcached: false - neo4j: false - rabbitmq: false - - dependencies: - override: - - composer update --no-interaction - - nodes: - analysis: - tests: - override: - - php-scrutinizer-run --enable-security-analysis diff --git a/.travis.yml b/.travis.yml index 9f61e46..93cba83 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,63 +2,70 @@ language: php cache: directories: - - $HOME/.composer/cache + - $HOME/.composer/cache env: global: - - setup=basic - - coverage=false + - setup=basic + - coverage=false + - laravel=default sudo: false branches: except: - - gh-pages - - /analysis-.*/ + - /analysis-.*/ before_install: -- if [[ $coverage = 'false' ]]; then phpenv config-rm xdebug.ini || true; fi + - if [[ $coverage = 'false' ]]; then phpenv config-rm xdebug.ini || true; fi + - composer global require hirak/prestissimo --update-no-dev install: -- if [[ $setup = 'basic' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest; fi -- if [[ $setup = 'stable' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest --prefer-stable; fi -- if [[ $setup = 'lowest' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest --prefer-stable --prefer-lowest; fi + - if [[ $setup = 'basic' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest; fi + - if [[ $setup = 'stable' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest --prefer-stable; fi + - if [[ $setup = 'lowest' ]]; then travis_retry composer update --prefer-dist --no-interaction --no-suggest --prefer-lowest; fi + - if [[ $laravel != 'default' ]]; then travis_retry composer require --dev --update-with-dependencies --prefer-dist --no-interaction --no-suggest laravel/laravel "$laravel"; fi + - composer info | grep -e laravel/laravel -e phpunit/phpunit -e phpstan/phpstan script: -- if [[ $coverage = 'true' ]]; then composer test-cover; else composer test; fi + - if [[ $coverage = 'true' ]]; then composer test-cover; else composer test; fi after_success: -- if [[ $coverage = 'true' ]]; then bash <(curl -s https://codecov.io/bash); fi + - if [[ $coverage = 'true' ]]; then bash <(curl -s https://codecov.io/bash); fi matrix: include: - - php: 5.6 - env: coverage=true - - php: 5.6 - env: setup=lowest - - php: 5.6 - env: setup=stable + - php: 7.1.3 + - php: 7.1.3 + env: setup=lowest + - php: 7.1.3 + env: laravel=5.5 + - php: 7.1.3 + env: laravel=5.6 + - php: 7.1.3 + env: laravel=5.7 + - php: 7.1.3 + env: coverage=true - - php: 7.0 - - php: 7.0 - env: setup=lowest + - php: 7.2 + - php: 7.2 + env: setup=lowest + - php: 7.2 + env: coverage=true - - php: 7.1 - - php: 7.1 - env: setup=lowest + - php: 7.3 + - php: 7.3 + env: setup=lowest + - php: 7.3 + env: laravel=5.5 + - php: 7.3 + env: laravel=5.6 + - php: 7.3 + env: laravel=5.7 + - php: 7.3 + env: coverage=true - - php: 7.2 - env: coverage=true - - php: 7.2 - env: setup=lowest - - php: 7.2 - env: setup=stable - - - php: 7.3 - - php: 7.3 - env: setup=lowest - - - php: nightly + - php: nightly allow_failures: - - php: nightly + - php: nightly diff --git a/CHANGELOG.md b/CHANGELOG.md index ef7cb7d..f4f753e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,23 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog][keepachangelog] and this project adheres to [Semantic Versioning][semver]. +## v3.0.0 + +### Added + +- Docker-based environment for development +- Project `Makefile` + +### Changed + +- Minimal `PHP` version now is `^7.1.3` +- Maximal `Laravel` version now is `5.8.x` +- Dependency `laravel/framework` changed to `illuminate/*` +- Composer scripts +- Argument and return types +- Class `\AvtoDev\StaticReferences\StaticReferencesServiceProvider` renamed to `\AvtoDev\StaticReferences\ServiceProvider` +- Service provider dependency `\Illuminate\Contracts\Foundation\Application` changed to `\Illuminate\Contracts\Container\Container` + ## v2.4.0 ### Changed diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4c0079f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,27 @@ +FROM composer:1.8.6 AS composer + +FROM php:7.1.3-alpine + +ENV \ + COMPOSER_ALLOW_SUPERUSER="1" \ + COMPOSER_HOME="/tmp/composer" + +COPY --from=composer /usr/bin/composer /usr/bin/composer + +RUN set -xe \ + && apk add --no-cache binutils git curl \ + && apk add --no-cache --virtual .build-deps autoconf pkgconf make g++ gcc \ + # install xdebug (for testing with code coverage), but not enable it + && pecl install xdebug-2.7.2 \ + && apk del .build-deps \ + && mkdir /src ${COMPOSER_HOME} \ + && composer global require 'hirak/prestissimo' --no-interaction --no-suggest --prefer-dist \ + && ln -s /usr/bin/composer /usr/bin/c \ + && chmod -R 777 ${COMPOSER_HOME} \ + && composer --version \ + && php -v \ + && php -m + +WORKDIR /src + +VOLUME ["/src"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..8a6c1fd --- /dev/null +++ b/Makefile @@ -0,0 +1,41 @@ +#!/usr/bin/make +# Makefile readme (ru): +# Makefile readme (en): + +dc_bin := $(shell command -v docker-compose 2> /dev/null) + +SHELL = /bin/sh +RUN_APP_ARGS = --rm --user "$(shell id -u):$(shell id -g)" app + +.PHONY : help build latest install lowest test test-cover shell clean +.DEFAULT_GOAL : help + +# This will output the help for each task. thanks to https://marmelab.com/blog/2016/02/29/auto-documented-makefile.html +help: ## Show this help + @printf "\033[33m%s:\033[0m\n" 'Available commands' + @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf " \033[32m%-14s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST) + +build: ## Build docker images, required for current package environment + $(dc_bin) build + +latest: clean ## Install latest php dependencies + $(dc_bin) run $(RUN_APP_ARGS) composer update -n --ansi --no-suggest --prefer-dist --prefer-stable + +install: clean ## Install regular php dependencies + $(dc_bin) run $(RUN_APP_ARGS) composer update -n --prefer-dist --no-interaction --no-suggest + +lowest: clean ## Install lowest php dependencies + $(dc_bin) run $(RUN_APP_ARGS) composer update -n --ansi --no-suggest --prefer-dist --prefer-lowest + +test: ## Execute php tests and linters + $(dc_bin) run $(RUN_APP_ARGS) composer test + +test-cover: ## Execute php tests with coverage + $(dc_bin) run --rm --user "0:0" app sh -c 'docker-php-ext-enable xdebug && su $(shell whoami) -s /bin/sh -c "composer phpunit-cover"' + +shell: ## Start shell into container with php + $(dc_bin) run -e "PS1=\[\033[1;32m\]\[\033[1;36m\][\u@docker] \[\033[1;34m\]\w\[\033[0;35m\] \[\033[1;36m\]# \[\033[0m\]" \ + $(RUN_APP_ARGS) sh + +clean: ## Remove all dependencies and unimportant files + -rm -Rf ./composer.lock ./vendor ./coverage diff --git a/README.md b/README.md index 4976363..c3448bf 100644 --- a/README.md +++ b/README.md @@ -19,21 +19,19 @@ Require this package with composer using the following command: ```shell -$ composer require avto-dev/static-references-laravel "^2.4" +$ composer require avto-dev/static-references-laravel "^3.0" ``` > Installed `composer` is required ([how to install composer][getcomposer]). > You need to fix the major version of package. -> **Внимание!** Версии 1.x и 2.x имеют кардинальные отличия, поэтому при переходе с версии 1.x на 2.x пожалуйста ознакомьтесь с изменения и в коде. - Если вы используете Laravel версии 5.5 и выше, то сервис-провайдер данного пакета будет зарегистрирован автоматически. В противном случае вам необходимо самостоятельно зарегистрировать сервис-провайдер в секции `providers` файла `./config/app.php`: ```php 'providers' => [ // ... - AvtoDev\StaticReferences\StaticReferencesServiceProvider::class, + AvtoDev\StaticReferences\ServiceProvider::class, ] ``` @@ -124,12 +122,12 @@ $auto_regions->hasAutoCode(666); // false ### Testing -For package testing we use `phpunit` framework. Just write into your terminal: +For package testing we use `phpunit` framework and `docker-ce` + `docker-compose` as develop environment. So, just write into your terminal after repository cloning: -```shell -$ git clone git@github.com:avto-dev/static-references-laravel.git ./static-references-laravel && cd $_ -$ composer install -$ composer test +```bash +$ make build +$ make latest # or 'make lowest' +$ make test ``` ## Changes log diff --git a/composer.json b/composer.json index 899f607..19729c3 100644 --- a/composer.json +++ b/composer.json @@ -15,15 +15,20 @@ } ], "require": { - "php": "^5.6 || >=7.0", + "php": "^7.1.3", "ext-json": "*", "avto-dev/static-references-data": "^2.3", - "laravel/framework": ">=5.4.0 <5.8.0" + "illuminate/support": ">=5.4.0 <5.9.0", + "illuminate/container": ">=5.4.0 <5.9.0", + "illuminate/contracts": ">=5.4.0 <5.9.0", + "illuminate/cache": ">=5.4.0 <5.9.0", + "illuminate/config": ">=5.4.0 <5.9.0" }, "require-dev": { - "laravel/laravel": ">=5.4.0 <5.8.0", - "mockery/mockery": "0.9.* || ~1.0", - "phpunit/phpunit": "~5.7.10 || ^6.4 || ~7.0" + "laravel/laravel": ">=5.4.0 <5.9.0", + "mockery/mockery": "^1.0", + "phpstan/phpstan": "^0.11.3", + "phpunit/phpunit": "^6.4 || ~7.5" }, "autoload": { "psr-4": { @@ -40,13 +45,23 @@ "source": "https://github.com/avto-dev/static-references-laravel" }, "scripts": { - "test": "@php ./vendor/bin/phpunit --no-coverage", - "test-cover": "@php ./vendor/bin/phpunit --coverage-html='./coverage/html'" + "phpunit": "@php ./vendor/bin/phpunit --no-coverage --colors=always", + "phpunit-feature": "@php ./vendor/bin/phpunit --no-coverage --colors=always", + "phpunit-cover": "@php ./vendor/bin/phpunit --coverage-html='./coverage/html'", + "phpstan": "@php ./vendor/bin/phpstan analyze -c ./phpstan.neon.dist --no-progress --ansi", + "test": [ + "@phpstan", + "@phpunit" + ], + "test-cover": [ + "@phpstan", + "@phpunit-cover" + ] }, "extra": { "laravel": { "providers": [ - "AvtoDev\\StaticReferences\\StaticReferencesServiceProvider" + "AvtoDev\\StaticReferences\\ServiceProvider" ] }, "aliases": { diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..c69660d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,21 @@ +version: '3.2' + +networks: + app-network: + driver: bridge + +volumes: + composer-data: + +services: + app: + build: + context: . + dockerfile: Dockerfile + volumes: + - /etc/passwd:/etc/passwd:ro + - /etc/group:/etc/group:ro + - .:/src:cached + - composer-data:/tmp/composer:cached + networks: + - app-network diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 0000000..6725ff7 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,5 @@ +parameters: + level: 'max' + reportUnmatchedIgnoredErrors: false + paths: + - src diff --git a/phpunit.xml b/phpunit.xml.dist similarity index 96% rename from phpunit.xml rename to phpunit.xml.dist index 2198db5..cfaf03b 100644 --- a/phpunit.xml +++ b/phpunit.xml.dist @@ -7,6 +7,7 @@ convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" + forceCoversAnnotation="true" stopOnFailure="true"> diff --git a/src/Facades/AbstractFacade.php b/src/Facades/AbstractFacade.php deleted file mode 100644 index 2d7f45f..0000000 --- a/src/Facades/AbstractFacade.php +++ /dev/null @@ -1,10 +0,0 @@ -referenceEntityFactory($item_data); - }, array_filter(static::getVendorStaticReferenceInstance()->getContent()))); + }, \array_filter(static::getVendorStaticReferenceInstance()->getContent()))); } - /** - * {@inheritdoc} - */ - abstract public function getReferenceEntryClassName(); - /** * {@inheritdoc} * * @throws Exception */ - public function offsetSet($key, $value) + public function offsetSet($key, $value): void { if ($key === null) { $this->items[] = $this->referenceEntityFactory($value); diff --git a/src/References/AbstractReferenceEntry.php b/src/References/AbstractReferenceEntry.php index feddbad..d5b6d92 100644 --- a/src/References/AbstractReferenceEntry.php +++ b/src/References/AbstractReferenceEntry.php @@ -1,15 +1,11 @@ hiddenPropertiesNames(), true) && \property_exists($this, $offset); } @@ -58,7 +49,7 @@ public function offsetGet($offset) /** * {@inheritdoc} */ - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { if ($this->offsetExists($offset)) { $this->{$offset} = $value; @@ -68,7 +59,7 @@ public function offsetSet($offset, $value) /** * {@inheritdoc} */ - public function offsetUnset($offset) + public function offsetUnset($offset): void { if ($this->offsetExists($offset)) { unset($this->{$offset}); @@ -78,7 +69,7 @@ public function offsetUnset($offset) /** * {@inheritdoc} */ - public function getIterator() + public function getIterator(): ArrayIterator { return new ArrayIterator($this->toArray()); } @@ -86,15 +77,15 @@ public function getIterator() /** * {@inheritdoc} */ - public function toJson($options = 0) + public function toJson($options = 0): string { - return \json_encode($this->toArray(), $options); + return (string) \json_encode($this->toArray(), $options); } /** * {@inheritdoc} */ - public function toArray() + public function toArray(): array { $result = []; diff --git a/src/References/AutoCategories/AutoCategories.php b/src/References/AutoCategories/AutoCategories.php index a158dbe..6af67c8 100644 --- a/src/References/AutoCategories/AutoCategories.php +++ b/src/References/AutoCategories/AutoCategories.php @@ -1,14 +1,14 @@ uppercaseAndSafeTransliterate($code)))) { foreach ($this->items as $auto_category) { @@ -44,6 +42,8 @@ public function getByCode($code) } } } + + return null; } /** @@ -53,7 +53,7 @@ public function getByCode($code) * * @return bool */ - public function hasCode($code) + public function hasCode($code): bool { return $this->getByCode($code) instanceof AutoCategoryEntry; } @@ -65,15 +65,20 @@ public function hasCode($code) * * @return AutoCategoryEntry|null */ - public function getByDescription($description) + public function getByDescription($description): ?AutoCategoryEntry { - if (\is_scalar($description) && ! empty($description = Str::lower(trim((string) $description)))) { + if (\is_string($description) && ! empty($description = Str::lower(trim((string) $description)))) { foreach ($this->items as $auto_category) { - if (Str::contains(Str::lower($auto_category->getDescription()), $description)) { + if ( + \is_string($auto_category->getDescription()) && + Str::contains(Str::lower($auto_category->getDescription()), $description) + ) { return $auto_category; } } } + + return null; } /** @@ -83,7 +88,7 @@ public function getByDescription($description) * * @return bool */ - public function hasDescription($description) + public function hasDescription($description): bool { return $this->getByDescription($description) instanceof AutoCategoryEntry; } @@ -91,7 +96,7 @@ public function hasDescription($description) /** * {@inheritdoc} */ - public function getReferenceEntryClassName() + public function getReferenceEntryClassName(): string { return AutoCategoryEntry::class; } diff --git a/src/References/AutoCategories/AutoCategoryEntry.php b/src/References/AutoCategories/AutoCategoryEntry.php index 5cb3361..5eeac71 100644 --- a/src/References/AutoCategories/AutoCategoryEntry.php +++ b/src/References/AutoCategories/AutoCategoryEntry.php @@ -1,5 +1,7 @@ $value) { @@ -55,7 +57,7 @@ public function configure($input = []) * * @return null|string */ - public function getCode() + public function getCode(): ?string { return $this->code; } @@ -65,7 +67,7 @@ public function getCode() * * @return null|string */ - public function getDescription() + public function getDescription(): ?string { return $this->description; } diff --git a/src/References/AutoFines/AutoFineEntry.php b/src/References/AutoFines/AutoFineEntry.php index 5750891..897de04 100644 --- a/src/References/AutoFines/AutoFineEntry.php +++ b/src/References/AutoFines/AutoFineEntry.php @@ -1,13 +1,12 @@ $value) { @@ -51,7 +50,7 @@ public function configure($input = []) * * @return null|string */ - public function getArticle() + public function getArticle(): ?string { return $this->article; } @@ -61,7 +60,7 @@ public function getArticle() * * @return null|string */ - public function getDescription() + public function getDescription(): ?string { return $this->description; } diff --git a/src/References/AutoFines/AutoFines.php b/src/References/AutoFines/AutoFines.php index b3cfe6a..215f794 100644 --- a/src/References/AutoFines/AutoFines.php +++ b/src/References/AutoFines/AutoFines.php @@ -1,10 +1,13 @@ clearArticleValue($article); foreach ($this->items as $auto_fine_entry) { - if ($this->clearArticleValue($auto_fine_entry->getArticle()) === $article) { + if ( + \is_string($auto_fine_entry->getArticle()) && + $this->clearArticleValue($auto_fine_entry->getArticle()) === $article + ) { return $auto_fine_entry; } } } + + return null; } /** @@ -56,7 +62,7 @@ public function getByArticle($article) * * @return bool */ - public function hasArticle($code) + public function hasArticle($code): bool { return $this->getByArticle($code) instanceof AutoFineEntry; } @@ -69,15 +75,20 @@ public function hasArticle($code) * * @return AutoFineEntry|null */ - public function getByDescription($description) + public function getByDescription($description): ?AutoFineEntry { if (\is_scalar($description) && ! empty($description = Str::lower(trim((string) $description)))) { foreach ($this->items as $auto_fine_entry) { - if (Str::contains(Str::lower($auto_fine_entry->getDescription()), $description)) { + if ( + \is_string($auto_fine_entry->getDescription()) && + Str::contains(Str::lower($auto_fine_entry->getDescription()), $description) + ) { return $auto_fine_entry; } } } + + return null; } /** @@ -87,7 +98,7 @@ public function getByDescription($description) * * @return bool */ - public function hasDescription($description) + public function hasDescription($description): bool { return $this->getByDescription($description) instanceof AutoFineEntry; } @@ -95,7 +106,7 @@ public function hasDescription($description) /** * {@inheritdoc} */ - public function getReferenceEntryClassName() + public function getReferenceEntryClassName(): string { return AutoFineEntry::class; } @@ -108,10 +119,10 @@ public function getReferenceEntryClassName() * * @return string */ - protected function clearArticleValue($value) + protected function clearArticleValue($value): string { // Заменяем все символы, кроме чисел - на точки + trim по точкам - $value = \trim(\preg_replace('/[\D]/', '.', (string) $value), '.'); + $value = \trim((string) \preg_replace('/[\D]/', '.', (string) $value), '.'); // Множественные точки - заменяем на одинарные $value = \preg_replace('/\.+/', '.', $value); diff --git a/src/References/AutoRegions/AutoRegionEntry.php b/src/References/AutoRegions/AutoRegionEntry.php index 8115bfb..55b3646 100644 --- a/src/References/AutoRegions/AutoRegionEntry.php +++ b/src/References/AutoRegions/AutoRegionEntry.php @@ -1,13 +1,12 @@ $value) { @@ -105,7 +104,7 @@ public function configure($input = []) // Код региона по стандарту ISO-31662 case 'code_iso_31662': $this->iso_31662 = Str::upper( - \preg_replace('~[^a-z-]~i', '', (string) $value) + (string) \preg_replace('~[^a-z-]~i', '', (string) $value) ); break; @@ -123,7 +122,7 @@ public function configure($input = []) * * @return int|null */ - public function getRegionCode() + public function getRegionCode(): ?int { return $this->region_code; } @@ -133,7 +132,7 @@ public function getRegionCode() * * @return int[]|null */ - public function getAutoCodes() + public function getAutoCodes(): ?array { return $this->auto_codes; } @@ -143,7 +142,7 @@ public function getAutoCodes() * * @return null|string */ - public function getIso31662() + public function getIso31662(): ?string { return $this->iso_31662; } @@ -153,7 +152,7 @@ public function getIso31662() * * @return null|string */ - public function getOkato() + public function getOkato(): ?string { return $this->okato; } @@ -163,7 +162,7 @@ public function getOkato() * * @return string[]|null */ - public function getShortTitles() + public function getShortTitles(): ?array { return $this->short_titles; } @@ -173,7 +172,7 @@ public function getShortTitles() * * @return null|string */ - public function getTitle() + public function getTitle(): ?string { return $this->title; } @@ -183,7 +182,7 @@ public function getTitle() * * @return null|string */ - public function getType() + public function getType(): ?string { return $this->type; } diff --git a/src/References/AutoRegions/AutoRegions.php b/src/References/AutoRegions/AutoRegions.php index 5cfb871..c4dc95f 100644 --- a/src/References/AutoRegions/AutoRegions.php +++ b/src/References/AutoRegions/AutoRegions.php @@ -1,14 +1,14 @@ items as $region) { if ($region->getRegionCode() === $region_code) { return $region; } } } + + return null; } /** @@ -55,7 +55,7 @@ public function getByRegionCode($region_code) * * @return bool */ - public function hasRegionCode($region_code) + public function hasRegionCode($region_code): bool { return $this->getByRegionCode($region_code) instanceof AutoRegionEntry; } @@ -69,9 +69,9 @@ public function hasRegionCode($region_code) * * @return AutoRegionEntry|null */ - public function getByTitle($region_title, $strict_search = false) + public function getByTitle($region_title, bool $strict_search = false): ?AutoRegionEntry { - if (! empty($region_title) && \is_string($region_title)) { + if (\is_string($region_title) && $region_title !== '') { // Ближайшее совпадение $closest = null; // Наименьшее расстояние @@ -84,9 +84,8 @@ public function getByTitle($region_title, $strict_search = false) $titles = \array_merge($titles, (array) $region->getShortTitles()); } foreach ($titles as $title) { - $title = trim($title); // Вычисляем расстояние между входным словом и текущим - $lev = \levenshtein($region_title, $title); + $lev = \levenshtein($region_title, \trim((string) $title)); // Проверяем полное совпадение if ($lev === 0) { $closest = $region; @@ -100,10 +99,14 @@ public function getByTitle($region_title, $strict_search = false) } } - return $strict_search === true - ? ($shortest === 0 ? $closest : null) - : ($shortest <= 5 ? $closest : null); // Этим числом можно регулировать строгость похожести + if ($strict_search) { + return $shortest === 0 ? $closest : null; + } + + return $shortest <= 5 ? $closest : null; // Этим числом можно регулировать строгость похожести } + + return null; } /** @@ -114,7 +117,7 @@ public function getByTitle($region_title, $strict_search = false) * * @return bool */ - public function hasTitle($region_title, $strict_search = false) + public function hasTitle($region_title, bool $strict_search = false): bool { return $this->getByTitle($region_title, $strict_search) instanceof AutoRegionEntry; } @@ -122,15 +125,15 @@ public function hasTitle($region_title, $strict_search = false) /** * Получаем регион по его авто-коду (коду региона по ГИБДД). * - * @param string|int $auto_code + * @param string|int|mixed $auto_code * * @return AutoRegionEntry|null */ - public function getByAutoCode($auto_code) + public function getByAutoCode($auto_code): ?AutoRegionEntry { - if (\is_scalar($auto_code)) { + if (\is_string($auto_code) || \is_int($auto_code)) { // Очищаем входящее значение и приводим к числу - $auto_code = (int) \preg_replace('~\D~', '', $auto_code); + $auto_code = (int) \preg_replace('~\D~', '', (string) $auto_code); foreach ($this->items as $region) { foreach ((array) $region->getAutoCodes() as $region_auto_code) { if ($region_auto_code === $auto_code) { @@ -139,6 +142,8 @@ public function getByAutoCode($auto_code) } } } + + return null; } /** @@ -148,7 +153,7 @@ public function getByAutoCode($auto_code) * * @return bool */ - public function hasAutoCode($auto_code) + public function hasAutoCode($auto_code): bool { return $this->getByAutoCode($auto_code) instanceof AutoRegionEntry; } @@ -160,7 +165,7 @@ public function hasAutoCode($auto_code) * * @return AutoRegionEntry|null */ - public function getByOkato($okato_code) + public function getByOkato($okato_code): ?AutoRegionEntry { if (\is_scalar($okato_code)) { // Очищаем входящее значение и приводим к числу @@ -171,6 +176,8 @@ public function getByOkato($okato_code) } } } + + return null; } /** @@ -180,7 +187,7 @@ public function getByOkato($okato_code) * * @return bool */ - public function hasOkato($okato_code) + public function hasOkato($okato_code): bool { return $this->getByOkato($okato_code) instanceof AutoRegionEntry; } @@ -188,13 +195,13 @@ public function hasOkato($okato_code) /** * Получаем объект региона по коду ISO-31662. * - * @param string $iso_31662 + * @param string|mixed $iso_31662 * * @return AutoRegionEntry|null */ - public function getByIso31662($iso_31662) + public function getByIso31662($iso_31662): ?AutoRegionEntry { - if (! empty($iso_31662) && \is_string($iso_31662)) { + if (\is_string($iso_31662) && $iso_31662 !== '') { // Очищаем входящее значение $iso_31662 = \preg_replace('~[^A-Z-]~', '', Str::upper($iso_31662)); foreach ($this->items as $region) { @@ -203,6 +210,8 @@ public function getByIso31662($iso_31662) } } } + + return null; } /** @@ -212,7 +221,7 @@ public function getByIso31662($iso_31662) * * @return bool */ - public function hasIso31662($iso_31662) + public function hasIso31662($iso_31662): bool { return $this->getByIso31662($iso_31662) instanceof AutoRegionEntry; } @@ -220,7 +229,7 @@ public function hasIso31662($iso_31662) /** * {@inheritdoc} */ - public function getReferenceEntryClassName() + public function getReferenceEntryClassName(): string { return AutoRegionEntry::class; } diff --git a/src/References/ReferenceEntryInterface.php b/src/References/ReferenceEntryInterface.php index 3d9786e..5e5c468 100644 --- a/src/References/ReferenceEntryInterface.php +++ b/src/References/ReferenceEntryInterface.php @@ -10,18 +10,18 @@ interface ReferenceEntryInterface extends ArrayAccess, IteratorAggregate, Arrayable, Jsonable { /** - * ReferenceEntryInterface constructor. + * Create a new reference entry instance. * * @param array $raw_data */ public function __construct($raw_data = []); /** - * Выполняет собственную конфигурации в зависимости от входящих данных. + * Configure self using passed array. * * @param array|mixed $input * * @return void */ - public function configure($input = []); + public function configure($input = []): void; } diff --git a/src/References/ReferenceInterface.php b/src/References/ReferenceInterface.php index d7b53ce..5df86fc 100644 --- a/src/References/ReferenceInterface.php +++ b/src/References/ReferenceInterface.php @@ -25,11 +25,11 @@ public static function getVendorStaticReferenceInstance(); public function all(); /** - * Возвращает класс сущности, с которой работает справочник. + * Get reference entity class name. * * @return string */ - public function getReferenceEntryClassName(); + public function getReferenceEntryClassName(): string; /** * Execute a callback over each item. diff --git a/src/References/RegistrationActions/RegistrationActionEntry.php b/src/References/RegistrationActions/RegistrationActionEntry.php index a624ffb..a2929c6 100644 --- a/src/References/RegistrationActions/RegistrationActionEntry.php +++ b/src/References/RegistrationActions/RegistrationActionEntry.php @@ -1,13 +1,12 @@ $value) { @@ -54,7 +53,7 @@ public function configure($input = []) * * @return string */ - public function getDescription() + public function getDescription(): string { return $this->description; } @@ -64,7 +63,7 @@ public function getDescription() * * @return int[] */ - public function getCodes() + public function getCodes(): array { return $this->codes; } diff --git a/src/References/RegistrationActions/RegistrationActions.php b/src/References/RegistrationActions/RegistrationActions.php index a2a490b..e431807 100644 --- a/src/References/RegistrationActions/RegistrationActions.php +++ b/src/References/RegistrationActions/RegistrationActions.php @@ -1,19 +1,17 @@ items as $reg_action) { if (\in_array($reg_action_code, $reg_action->getCodes(), true)) { return $reg_action; } } } + + return null; } /** @@ -57,7 +55,7 @@ public function getByCode($reg_action_code) * * @return bool */ - public function hasCode($reg_action_code) + public function hasCode($reg_action_code): bool { return $this->getByCode($reg_action_code) instanceof RegistrationActionEntry; } @@ -69,7 +67,7 @@ public function hasCode($reg_action_code) * * @return RegistrationActionEntry|null */ - public function getByDescription($description) + public function getByDescription($description): ?RegistrationActionEntry { if (\is_scalar($description) && ! empty($description = Str::lower(trim((string) $description)))) { foreach ($this->items as $registration_action) { @@ -78,6 +76,8 @@ public function getByDescription($description) } } } + + return null; } /** @@ -87,7 +87,7 @@ public function getByDescription($description) * * @return bool */ - public function hasDescription($description) + public function hasDescription($description): bool { return $this->getByDescription($description) instanceof RegistrationActionEntry; } @@ -95,7 +95,7 @@ public function hasDescription($description) /** * {@inheritdoc} */ - public function getReferenceEntryClassName() + public function getReferenceEntryClassName(): string { return RegistrationActionEntry::class; } diff --git a/src/References/RepairMethods/RepairMethods.php b/src/References/RepairMethods/RepairMethods.php index d6aa02b..ed4ac50 100644 --- a/src/References/RepairMethods/RepairMethods.php +++ b/src/References/RepairMethods/RepairMethods.php @@ -1,19 +1,17 @@ items as $repair_method) { @@ -46,28 +42,30 @@ public function getByCode($repair_method_code) } } } + + return null; } /** - * Проверяет наличие объекта метода ремонта по его коду. + * Repair method by code is exists? * * @param string $repair_method_code * * @return bool */ - public function hasCode($repair_method_code) + public function hasCode($repair_method_code): bool { return $this->getByCode($repair_method_code) instanceof RepairMethodsEntry; } /** - * Возвращает объект метода ремонта по его описанию. Регистронезависимый. + * Get repair method by description (description is case insensitive). * * @param string $description * * @return RepairMethodsEntry|null */ - public function getByDescription($description) + public function getByDescription($description): ?RepairMethodsEntry { if (\is_scalar($description) && ! empty($description = Str::lower(trim((string) $description)))) { foreach ($this->items as $repair_method) { @@ -76,6 +74,8 @@ public function getByDescription($description) } } } + + return null; } /** @@ -85,7 +85,7 @@ public function getByDescription($description) * * @return bool */ - public function hasDescription($description) + public function hasDescription($description): bool { return $this->getByDescription($description) instanceof RepairMethodsEntry; } @@ -93,7 +93,7 @@ public function hasDescription($description) /** * {@inheritdoc} */ - public function getReferenceEntryClassName() + public function getReferenceEntryClassName(): string { return RepairMethodsEntry::class; } diff --git a/src/References/RepairMethods/RepairMethodsEntry.php b/src/References/RepairMethods/RepairMethodsEntry.php index bd72d07..5f15c34 100644 --- a/src/References/RepairMethods/RepairMethodsEntry.php +++ b/src/References/RepairMethods/RepairMethodsEntry.php @@ -1,13 +1,12 @@ $value) { @@ -56,7 +55,7 @@ public function configure($input = []) * * @return string */ - public function getDescription() + public function getDescription(): string { return $this->description; } @@ -66,7 +65,7 @@ public function getDescription() * * @return string[]|array */ - public function getCodes() + public function getCodes(): array { return $this->codes; } diff --git a/src/References/Traits/TransliterateTrait.php b/src/References/Traits/TransliterateTrait.php index 445d89a..3b736c2 100644 --- a/src/References/Traits/TransliterateTrait.php +++ b/src/References/Traits/TransliterateTrait.php @@ -1,43 +1,38 @@ 'ya'), и переводим в верхний регистр - $string = \str_replace($cyr_chars, $latin_chars, Str::upper((string) $string)); + // Make replaces (like 'я' -> 'ya') and uppercase + $string = \str_replace($cyr_chars, $latin_chars, Str::upper($string)); - // Производим конечную транслитерацию + // Make final transliteration return Str::ascii($string); } } diff --git a/src/ServiceProvider.php b/src/ServiceProvider.php new file mode 100644 index 0000000..3f1ab6a --- /dev/null +++ b/src/ServiceProvider.php @@ -0,0 +1,103 @@ +getReferencesClasses() as $references_class) { + $this->app->singleton($references_class, function (Container $app) use ($references_class) { + return $this->bootUpReferenceInstance($app, $references_class); + }); + } + } + + /** + * Get reference instance by class name. + * + * @param Container $app + * @param string $references_class + * + * @throws Exception + * + * @return ReferenceInterface + */ + protected function bootUpReferenceInstance(Container $app, string $references_class): ReferenceInterface + { + $cache = $this->cacheFactory($app); + + /** @var ReferenceInterface $references_class */ + $hash = $references_class::getVendorStaticReferenceInstance()->getHash(); + + if ($cache->has($cache_key = $this->generateCacheKey($references_class, $hash))) { + return $cache->get($cache_key); + } + + $instance = new $references_class; + + // По умолчанию - храним справочник в кэше одни сутки до его пересоздания + $cache->put($cache_key, $instance, Carbon::now()->addDays(1)); + + return $instance; + } + + /** + * Generate cache key name. + * + * @param array ...$arguments + * + * @return string + */ + protected function generateCacheKey(...$arguments): string + { + return \sprintf('static_reference_%s', \crc32(\serialize($arguments))); + } + + /** + * Get cache instance. + * + * @param Container $app + * @param null|string $cache_storage_name + * + * @return CacheContract + */ + protected function cacheFactory(Container $app, ?string $cache_storage_name = null): CacheContract + { + return $app->make('cache')->store($cache_storage_name ?? $app->make('config')->get('cache.default')); + } +} diff --git a/src/StaticReferencesServiceProvider.php b/src/StaticReferencesServiceProvider.php deleted file mode 100644 index cd2c5d0..0000000 --- a/src/StaticReferencesServiceProvider.php +++ /dev/null @@ -1,114 +0,0 @@ -getReferencesClasses() as $references_class) { - $this->app->singleton($references_class, function (Application $app) use ($references_class) { - return $this->bootUpReferenceInstance($references_class, $app); - }); - } - } - - /** - * Производит инициализацию инстанса справочника по имени его класса. - * - * Алсо - производит проверку его наличия в кэше, валидируя его актуальность по его хэшу. - * - * @param string $references_class - * @param Application $app - * - * @throws Exception - * - * @return mixed - */ - protected function bootUpReferenceInstance($references_class, Application $app) - { - $cache = $this->cacheFactory(null, $app); - - /** @var ReferenceInterface $references_class */ - $hash = $references_class::getVendorStaticReferenceInstance()->getHash(); - - if ($cache->has($cache_key = $this->generateCacheKey($references_class, $hash))) { - return $cache->get($cache_key); - } - - $instance = new $references_class; - - // По умолчанию - храним справочник в кэше одни сутки до его пересоздания - $cache->put($cache_key, $instance, Carbon::now()->addDays(1)); - - return $instance; - } - - /** - * Generate cache key name. - * - * @param array ...$arguments - * - * @return string - */ - protected function generateCacheKey(...$arguments) - { - return sprintf('static_reference_%s', \crc32(\serialize($arguments))); - } - - /** - * Возвращает инстанс кэша приложения. Если не передать имя хранилища, то будет использовано то, что установлено - * у приложения по умолчанию. - * - * @param null|string $cache_storage_name Имя используемого хранилища кэша - * @param null|Application $app Инстанс приложения (опционально) - * - * @return CacheContract - */ - protected function cacheFactory($cache_storage_name = null, $app = null) - { - /** @var Application $app */ - $app = $app instanceof Application - ? $app - : $this->app; - - $storage_name = $cache_storage_name === null - ? $app->make('config')->get('cache.default') - : $cache_storage_name; - - return $app->make('cache')->store($storage_name); - } -} diff --git a/tests/AbstractUnitTestCase.php b/tests/AbstractUnitTestCase.php index 4d7d1d4..58e876e 100644 --- a/tests/AbstractUnitTestCase.php +++ b/tests/AbstractUnitTestCase.php @@ -1,12 +1,11 @@ app = $this->createApplication(); - - $this->files = $this->app->make('files'); - - // Перебираем все имена методов собственного класса - foreach (get_class_methods(static::class) as $method_name) { - // Если метод начинается с подстроки 'boot' - if (Str::startsWith($method_name, static::MAGIC_METHODS_PREFIX)) { - // То вызываем метод, передавая ему на вход массив коллекций (хотя передавать не обязательно) - if (call_user_func_array([$this, $method_name], []) !== true) { - throw new Exception(sprintf( - 'Bootstrap method "%s" has non-true result. So, we cannot start tests for this reason', - $method_name - )); - } - } - } - - $this->log(null); - } - - /** - * Выводит сообщение (с необходимым "стилем") в консоль. - * - * @param string|null $message - * @param string $style - */ - protected function log($message = null, $style = 'info') - { - /** @var ConsoleOutput|null $output */ - static $output = null; - - if (! ($output instanceof ConsoleOutput)) { - $output = $this->app->make(ConsoleOutput::class); - } - - $output->writeln(empty($message) - ? '' - : sprintf('<%1$s>> Bootstrap: <%2$s>%3$s', 'comment', $style, $message) - ); - } -} diff --git a/tests/Bootstrap/TestsBootstraper.php b/tests/Bootstrap/TestsBootstraper.php deleted file mode 100644 index e8a054d..0000000 --- a/tests/Bootstrap/TestsBootstraper.php +++ /dev/null @@ -1,42 +0,0 @@ -log('Register service-provider'); - - $this->app->register(StaticReferencesServiceProvider::class); - - return true; - } - - /** - * Очищает кэш. - * - * @return bool - */ - protected function bootMakeMigrations() - { - $this->log('Clear cache'); - - $this->app->make(Kernel::class)->call('cache:clear'); - - return true; - } -} diff --git a/tests/References/AbstractReferenceTestCase.php b/tests/References/AbstractReferenceTestCase.php index 8874b7d..9e1e72b 100644 --- a/tests/References/AbstractReferenceTestCase.php +++ b/tests/References/AbstractReferenceTestCase.php @@ -1,12 +1,18 @@ clearCache(); + $this->instance = $this->app->make($this->getReferenceClassName()); } /** - * Тест метода `all()`. - * * @return void */ - public function testAll() + public function testAll(): void { $class = $this->instance->getReferenceEntryClassName(); @@ -42,27 +48,23 @@ public function testAll() } /** - * Тест преобразования элементов справочника в массив и json. + * @return void */ - public function testEntryToArrayAndToJson() + public function testEntryToArrayAndToJson(): void { $first = $this->instance->first(); - $this->assertTrue(is_array($first->toArray())); + $this->assertInternalType('array', $first->toArray()); $this->assertJson($first->toJson()); } /** - * Тест метода преобразования элемента справочника в массив. - * * @return void */ - abstract public function testArrayKeys(); + abstract public function testArrayKeys(): void; /** - * Returns reference class name. - * * @return string */ - abstract protected function getReferenceClassName(); + abstract protected function getReferenceClassName(): string; } diff --git a/tests/References/AutoCategoriesReferenceTest.php b/tests/References/AutoCategoriesReferenceTest.php index 573c46e..c2cccb9 100644 --- a/tests/References/AutoCategoriesReferenceTest.php +++ b/tests/References/AutoCategoriesReferenceTest.php @@ -1,10 +1,16 @@ + * @covers \AvtoDev\StaticReferences\References\AutoCategories\AutoCategoryEntry + */ class AutoCategoriesReferenceTest extends AbstractReferenceTestCase { /** @@ -15,7 +21,7 @@ class AutoCategoriesReferenceTest extends AbstractReferenceTestCase /** * {@inheritdoc} */ - public function testArrayKeys() + public function testArrayKeys(): void { foreach (['code', 'description'] as $key_name) { $this->assertArrayHasKey($key_name, $this->instance->first()->toArray()); @@ -27,7 +33,7 @@ public function testArrayKeys() * * @return void */ - public function testBasicData() + public function testBasicData(): void { $this->assertGreaterThan(10, count($this->instance->all())); $assert_with = 'Мотоциклы'; @@ -66,7 +72,7 @@ public function testBasicData() /** * {@inheritdoc} */ - protected function getReferenceClassName() + protected function getReferenceClassName(): string { return AutoCategories::class; } diff --git a/tests/References/AutoFinesReferenceTest.php b/tests/References/AutoFinesReferenceTest.php index 9907eb1..6751771 100644 --- a/tests/References/AutoFinesReferenceTest.php +++ b/tests/References/AutoFinesReferenceTest.php @@ -1,10 +1,16 @@ + * @covers \AvtoDev\StaticReferences\References\AutoFines\AutoFineEntry + */ class AutoFinesReferenceTest extends AbstractReferenceTestCase { /** @@ -15,7 +21,7 @@ class AutoFinesReferenceTest extends AbstractReferenceTestCase /** * {@inheritdoc} */ - public function testArrayKeys() + public function testArrayKeys(): void { foreach (['article', 'description'] as $key_name) { $this->assertArrayHasKey($key_name, $this->instance->first()->toArray()); @@ -27,7 +33,7 @@ public function testArrayKeys() * * @return void */ - public function testBasicData() + public function testBasicData(): void { $this->assertGreaterThanOrEqual(179, count($this->instance->all())); $assert_with = 'Нарушение правил перевозки грузов, а равно правил буксировки'; @@ -91,7 +97,7 @@ public function testBasicData() /** * {@inheritdoc} */ - protected function getReferenceClassName() + protected function getReferenceClassName(): string { return AutoFines::class; } diff --git a/tests/References/AutoRegionsReferenceTest.php b/tests/References/AutoRegionsReferenceTest.php index df8e7fe..dbdeae8 100644 --- a/tests/References/AutoRegionsReferenceTest.php +++ b/tests/References/AutoRegionsReferenceTest.php @@ -1,9 +1,15 @@ + * @covers \AvtoDev\StaticReferences\References\AutoRegions\AutoRegionEntry + */ class AutoRegionsReferenceTest extends AbstractReferenceTestCase { /** @@ -16,7 +22,7 @@ class AutoRegionsReferenceTest extends AbstractReferenceTestCase * * @return void */ - public function testBasicData() + public function testBasicData(): void { $this->assertGreaterThan(10, count($this->instance->all())); } @@ -24,7 +30,7 @@ public function testBasicData() /** * {@inheritdoc} */ - public function testArrayKeys() + public function testArrayKeys(): void { $keys = [ 'title', @@ -44,7 +50,7 @@ public function testArrayKeys() /** * Тест метода `getByRegionCode()` + has. */ - public function testGetByRegionCode() + public function testGetByRegionCode(): void { $this->assertEquals( 'Республика Марий Эл', @@ -71,7 +77,7 @@ public function testGetByRegionCode() /** * Тестируем метод `getByAutoCode()` + has. */ - public function testGetByAutoCode() + public function testGetByAutoCode(): void { // Существующие области $moscow = 'Москва'; @@ -107,7 +113,7 @@ public function testGetByAutoCode() /** * Тестируем метод `getByTitle()` + has. */ - public function testGetByTitle() + public function testGetByTitle(): void { $moscow = 'Москва'; @@ -139,7 +145,7 @@ public function testGetByTitle() /** * Тестируем метод `getByOkato()` + has. */ - public function testGetByOkato() + public function testGetByOkato(): void { $sverdl_obl = 'Свердловская область'; $this->assertEquals($sverdl_obl, $this->instance->getByOkato(65)->getTitle()); @@ -161,7 +167,7 @@ public function testGetByOkato() /** * Тестируем метод `getByIso31662()` + has. */ - public function testGetByIso31662() + public function testGetByIso31662(): void { $sverdl_obl = 'Свердловская область'; $this->assertEquals( @@ -192,7 +198,7 @@ public function testGetByIso31662() /** * {@inheritdoc} */ - protected function getReferenceClassName() + protected function getReferenceClassName(): string { return AutoRegions::class; } diff --git a/tests/References/RegistrationActionsReferenceTest.php b/tests/References/RegistrationActionsReferenceTest.php index e329dff..9bca2a5 100644 --- a/tests/References/RegistrationActionsReferenceTest.php +++ b/tests/References/RegistrationActionsReferenceTest.php @@ -1,10 +1,16 @@ + * @covers \AvtoDev\StaticReferences\References\RegistrationActions\RegistrationActionEntry + */ class RegistrationActionsReferenceTest extends AbstractReferenceTestCase { /** @@ -15,7 +21,7 @@ class RegistrationActionsReferenceTest extends AbstractReferenceTestCase /** * {@inheritdoc} */ - public function testArrayKeys() + public function testArrayKeys(): void { foreach (['codes', 'description'] as $key_name) { $this->assertArrayHasKey($key_name, $this->instance->first()->toArray()); @@ -27,7 +33,7 @@ public function testArrayKeys() * * @return void */ - public function testBasicData() + public function testBasicData(): void { $this->assertGreaterThan(50, count($this->instance->all())); $assert_with = 'Восстановление регистрации после аннулирования'; @@ -64,7 +70,7 @@ public function testBasicData() /** * {@inheritdoc} */ - protected function getReferenceClassName() + protected function getReferenceClassName(): string { return RegistrationActions::class; } diff --git a/tests/References/RepairMethodsReferenceTest.php b/tests/References/RepairMethodsReferenceTest.php index 31d5f15..fe59868 100644 --- a/tests/References/RepairMethodsReferenceTest.php +++ b/tests/References/RepairMethodsReferenceTest.php @@ -1,12 +1,15 @@ + * @covers \AvtoDev\StaticReferences\References\RepairMethods\RepairMethodsEntry * * @group repair_methods */ @@ -20,7 +23,7 @@ class RepairMethodsReferenceTest extends AbstractReferenceTestCase /** * {@inheritdoc} */ - public function testArrayKeys() + public function testArrayKeys(): void { foreach (['codes', 'description'] as $key_name) { $this->assertArrayHasKey($key_name, $this->instance->first()->toArray()); @@ -32,7 +35,7 @@ public function testArrayKeys() * * @return void */ - public function testBasicData() + public function testBasicData(): void { $this->assertGreaterThan(18, count($this->instance->all())); $assert_with = 'Частичная замена'; @@ -60,7 +63,7 @@ public function testBasicData() /** * {@inheritdoc} */ - protected function getReferenceClassName() + protected function getReferenceClassName(): string { return RepairMethods::class; } diff --git a/tests/StaticReferencesServiceProviderTest.php b/tests/ServiceProviderTest.php similarity index 79% rename from tests/StaticReferencesServiceProviderTest.php rename to tests/ServiceProviderTest.php index 4a6bdbe..57d3ffe 100644 --- a/tests/StaticReferencesServiceProviderTest.php +++ b/tests/ServiceProviderTest.php @@ -1,5 +1,7 @@ */ -class StaticReferencesServiceProviderTest extends AbstractUnitTestCase +class ServiceProviderTest extends AbstractUnitTestCase { /** * Tests service-provider loading. * + * @covers \AvtoDev\StaticReferences\Facades\AutoCategoriesFacade + * @covers \AvtoDev\StaticReferences\Facades\AutoFinesFacade + * @covers \AvtoDev\StaticReferences\Facades\AutoRegionsFacade + * @covers \AvtoDev\StaticReferences\Facades\RegistrationActionsFacade + * @covers \AvtoDev\StaticReferences\Facades\RepairMethodsFacade + * * @return void */ - public function testServiceProviderLoading() + public function testServiceProviderLoading(): void { $this->assertInstanceOf(AutoRegions::class, $this->app[AutoRegions::class]); $this->assertInstanceOf(AutoRegions::class, app(AutoRegions::class)); @@ -53,10 +61,11 @@ public function testServiceProviderLoading() * * @return void */ - public function testResolvingInstanceFromCache() + public function testResolvingInstanceFromCache(): void { $this->assertInstanceOf(AutoRegions::class, $this->app[AutoRegions::class]); + $this->clearCache(); $this->refreshApplication(); $this->assertInstanceOf(AutoRegions::class, $this->app[AutoRegions::class]); diff --git a/tests/SomeFeatureTest.php b/tests/SomeFeatureTest.php index 4c97c11..3791e2d 100644 --- a/tests/SomeFeatureTest.php +++ b/tests/SomeFeatureTest.php @@ -1,5 +1,7 @@ resolveApplication($app); @@ -45,7 +43,7 @@ public function console(ApplicationContract $app = null) * * @return ConfigRepository */ - public function config(ApplicationContract $app = null) + public function config(ApplicationContract $app = null): ConfigRepository { $app = $this->resolveApplication($app); @@ -59,7 +57,7 @@ public function config(ApplicationContract $app = null) * * @return void */ - public function clearCache(ApplicationContract $app = null) + public function clearCache(ApplicationContract $app = null): void { $this->console($app)->call('cache:clear'); } diff --git a/tests/Traits/CreatesApplicationTrait.php b/tests/Traits/CreatesApplicationTrait.php index 7cdab22..f9d9962 100644 --- a/tests/Traits/CreatesApplicationTrait.php +++ b/tests/Traits/CreatesApplicationTrait.php @@ -1,10 +1,12 @@ make(Kernel::class)->bootstrap(); // Register our service-provider manually - $app->register(StaticReferencesServiceProvider::class); + $app->register(ServiceProvider::class); return $app; } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index de106ff..91a1304 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,3 +1,5 @@