From 02ea7346a866ac89fef2cfaf00585833e9f7a564 Mon Sep 17 00:00:00 2001 From: ErickSkrauch Date: Tue, 17 Apr 2018 23:47:25 +0300 Subject: [PATCH 1/2] Implemented PHP-CS-Fixer support --- .gitignore | 4 + .gitlab-ci.yml | 13 + .php_cs.dist | 16 + api/aop/AspectKernel.php | 1 - api/components/OAuth2/Component.php | 1 - .../OAuth2/Entities/RefreshTokenEntity.php | 10 +- .../OAuth2/Grants/AuthCodeGrant.php | 6 +- .../OAuth2/Storage/AccessTokenStorage.php | 6 +- .../OAuth2/Storage/AuthCodeStorage.php | 4 +- .../OAuth2/Storage/ClientStorage.php | 6 +- .../OAuth2/Storage/RefreshTokenStorage.php | 4 +- .../OAuth2/Storage/SessionStorage.php | 2 +- api/components/User/Component.php | 2 +- api/components/User/Identity.php | 8 +- api/components/User/JwtIdentity.php | 10 +- api/components/User/ScopesClaim.php | 2 +- api/components/User/SubjectPrefixVerifier.php | 2 +- api/controllers/SignupController.php | 2 +- api/models/FeedbackForm.php | 4 +- .../authentication/ForgotPasswordForm.php | 2 +- api/models/authentication/LoginForm.php | 5 +- api/models/authentication/LogoutForm.php | 2 +- .../authentication/RegistrationForm.php | 4 +- .../RepeatAccountActivationForm.php | 2 +- .../accounts/actions/BaseAccountAction.php | 4 +- .../accounts/actions/ChangeEmailAction.php | 8 +- .../actions/EmailVerificationAction.php | 8 +- .../accounts/models/ChangeEmailForm.php | 2 +- api/modules/accounts/models/TotpHelper.php | 4 +- .../controllers/AuthenticationController.php | 8 +- .../authserver/models/AuthenticateData.php | 4 +- .../authserver/models/AuthenticationForm.php | 14 +- .../authserver/models/InvalidateForm.php | 3 +- .../authserver/models/RefreshTokenForm.php | 1 + api/modules/authserver/models/SignoutForm.php | 3 +- .../authserver/models/ValidateForm.php | 2 +- .../mojang/controllers/ApiController.php | 8 +- .../controllers/AuthorizationController.php | 2 +- .../oauth/exceptions/OauthException.php | 1 + api/modules/oauth/models/ApplicationType.php | 2 +- .../session/controllers/SessionController.php | 2 +- .../ForbiddenOperationException.php | 2 +- api/modules/session/filters/RateLimiter.php | 3 +- api/modules/session/models/JoinForm.php | 4 +- api/modules/session/models/SessionModel.php | 2 +- .../models/protocols/BaseHasJoined.php | 1 + .../session/models/protocols/LegacyJoin.php | 5 +- .../session/models/protocols/ModernJoin.php | 2 + api/traits/AccountFinder.php | 2 +- common/behaviors/DataBehavior.php | 1 + .../EmailActivationExpirationBehavior.php | 12 +- common/behaviors/PrimaryKeyValueBehavior.php | 8 +- common/components/EmailRenderer.php | 2 +- common/components/Qr/ElyDecorator.php | 1 - common/components/RabbitMQ/Component.php | 80 +-- common/components/Redis/Connection.php | 18 +- common/components/Redis/Key.php | 6 +- common/components/Redis/Set.php | 2 + common/components/SkinSystem/Api.php | 2 +- common/components/UserFriendlyRandomKey.php | 5 +- common/components/UserPass.php | 1 - common/config/ConfigLoader.php | 6 +- common/config/config.php | 2 +- common/db/mysql/QueryBuilder.php | 11 +- common/emails/TemplateWithRenderer.php | 2 +- .../ChangeEmailConfirmCurrentEmail.php | 12 +- .../templates/ChangeEmailConfirmNewEmail.php | 14 +- common/helpers/Error.php | 92 ++-- common/helpers/StringHelper.php | 4 +- common/models/Account.php | 17 +- common/models/EmailActivation.php | 16 +- common/models/MinecraftAccessKey.php | 2 +- common/models/OauthScopeQuery.php | 8 +- common/models/Textures.php | 6 +- common/models/UsernameHistory.php | 2 +- .../confirmations/NewEmailConfirmation.php | 2 +- .../NewEmailConfirmationBehavior.php | 4 +- composer.json | 4 +- composer.lock | 465 +++++++++++++++++- console/controllers/AmqpController.php | 2 +- console/controllers/CleanupController.php | 2 +- console/controllers/RbacController.php | 2 +- console/db/Migration.php | 2 +- console/migrations/m160201_055928_oauth.php | 26 +- ...60414_231110_account_nicknames_history.php | 2 +- ...m160819_211139_minecraft_access_tokens.php | 6 +- .../m161030_013122_ely_by_admin_app.php | 8 +- ...1222_222520_remove_oauth_access_tokens.php | 4 +- tests/codeception/api/_bootstrap.php | 4 +- tests/codeception/api/_support/UnitTester.php | 10 +- .../functional/_steps/SessionServerSteps.php | 2 +- .../authserver/AuthorizationCest.php | 2 +- .../mojang/UsernamesToUuidsCest.php | 3 +- tests/codeception/api/unit/TestCase.php | 12 +- .../unit/components/User/ComponentTest.php | 2 +- .../models/authentication/LoginFormTest.php | 14 +- .../models/authentication/LogoutFormTest.php | 4 +- .../modules/internal/models/BanFormTest.php | 2 +- .../internal/models/PardonFormTest.php | 2 +- .../oauth/models/OauthClientFormTest.php | 2 - .../session/filters/RateLimiterTest.php | 4 +- .../PasswordRequiredValidatorTest.php | 2 +- .../common/_support/ProtectedCaller.php | 1 - .../common/_support/UnitTester.php | 7 +- .../common/_support/amqp/Helper.php | 2 +- .../common/_support/amqp/TestComponent.php | 4 +- .../common/_support/queue/Queue.php | 10 +- tests/codeception/common/unit/TestCase.php | 12 +- .../behaviors/PrimaryKeyValueBehaviorTest.php | 26 +- .../unit/validators/EmailValidatorTest.php | 2 +- .../unit/validators/UsernameValidatorTest.php | 9 +- .../console/_support/UnitTester.php | 10 +- tests/codeception/console/unit/TestCase.php | 10 +- .../AccountQueueControllerTest.php | 4 +- yii | 8 +- 115 files changed, 883 insertions(+), 363 deletions(-) create mode 100644 .php_cs.dist diff --git a/.gitignore b/.gitignore index 7749dee..f18c018 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,7 @@ npm-debug* # id_rsa /id_rsa + +# PHP-CS-Fixer +.php_cs +.php_cs.cache diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index a5d6184..d24b075 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -24,6 +24,19 @@ test:backend: script: - export TEMP_DEV_IMAGE="${CONTAINER_IMAGE}:ci-${CI_BUILD_ID}" - docker build --pull -f Dockerfile-dev -t $TEMP_DEV_IMAGE . + # https://github.com/FriendsOfPHP/PHP-CS-Fixer#using-php-cs-fixer-on-ci + - COMMIT_RANGE="${CI_COMMIT_BEFORE_SHA}...${CI_COMMIT_SHA}" + - CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "${COMMIT_RANGE}") + - | + if ! echo "${CHANGED_FILES}" | grep -qE "^(\\.php_cs(\\.dist)?|composer\\.lock)$"; then + EXTRA_ARGS=$(printf -- '--path-mode=intersection\n--\n%s' "${CHANGED_FILES}") + else + EXTRA_ARGS='' + fi + - > + docker run --rm + $TEMP_DEV_IMAGE + vendor/bin/php-cs-fixer fix -v --dry-run --stop-on-violation --using-cache=no ${EXTRA_ARGS} - > docker run --rm --add-host=mariadb:`getent hosts mariadb | awk '{ print $1 ; exit }'` diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 0000000..a8fc27d --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,16 @@ +in(__DIR__) + ->exclude('data') + ->exclude('docker') + ->exclude('frontend') + ->notPath('common/emails/views') + ->notPath('/.*\/runtime/') + ->notPath('autocompletion.php') + ->notPath('tests/codeception/_output') + ->notPath('/tests\/codeception\/.*\/_output/') + ->notPath('/tests\/codeception\/.*\/_support\/_generated/') + ->name('yii'); + +return \Ely\CS\Config::create() + ->setFinder($finder); diff --git a/api/aop/AspectKernel.php b/api/aop/AspectKernel.php index bd03dc3..5cfb386 100644 --- a/api/aop/AspectKernel.php +++ b/api/aop/AspectKernel.php @@ -1,7 +1,6 @@ session instanceof SessionEntity) { return $this->session; } @@ -26,18 +26,18 @@ class RefreshTokenEntity extends \League\OAuth2\Server\Entity\RefreshTokenEntity return $sessionStorage->getById($this->sessionId); } - public function getSessionId() : int { + public function getSessionId(): int { return $this->sessionId; } - public function setSession(OriginalSessionEntity $session) { + public function setSession(OriginalSessionEntity $session): self { parent::setSession($session); $this->setSessionId($session->getId()); return $this; } - public function setSessionId(int $sessionId) { + public function setSessionId(int $sessionId): void { $this->sessionId = $sessionId; } diff --git a/api/components/OAuth2/Grants/AuthCodeGrant.php b/api/components/OAuth2/Grants/AuthCodeGrant.php index c1f5dca..7b7279b 100644 --- a/api/components/OAuth2/Grants/AuthCodeGrant.php +++ b/api/components/OAuth2/Grants/AuthCodeGrant.php @@ -133,8 +133,10 @@ class AuthCodeGrant extends AbstractGrant { throw new Exception\InvalidRequestException('client_id'); } - $clientSecret = $this->server->getRequest()->request->get('client_secret', - $this->server->getRequest()->getPassword()); + $clientSecret = $this->server->getRequest()->request->get( + 'client_secret', + $this->server->getRequest()->getPassword() + ); if ($clientSecret === null && $this->shouldRequireClientSecret()) { throw new Exception\InvalidRequestException('client_secret'); } diff --git a/api/components/OAuth2/Storage/AccessTokenStorage.php b/api/components/OAuth2/Storage/AccessTokenStorage.php index c31742b..2d54cbf 100644 --- a/api/components/OAuth2/Storage/AccessTokenStorage.php +++ b/api/components/OAuth2/Storage/AccessTokenStorage.php @@ -31,7 +31,7 @@ class AccessTokenStorage extends AbstractStorage implements AccessTokenInterface public function getScopes(OriginalAccessTokenEntity $token) { $scopes = $this->scopes($token->getId()); $entities = []; - foreach($scopes as $scope) { + foreach ($scopes as $scope) { if ($this->server->getScopeStorage()->get($scope) !== null) { $entities[] = (new ScopeEntity($this->server))->hydrate(['id' => $scope]); } @@ -59,11 +59,11 @@ class AccessTokenStorage extends AbstractStorage implements AccessTokenInterface $this->scopes($token->getId())->delete(); } - private function key(string $token) : Key { + private function key(string $token): Key { return new Key($this->dataTable, $token); } - private function scopes(string $token) : Set { + private function scopes(string $token): Set { return new Set($this->dataTable, $token, 'scopes'); } diff --git a/api/components/OAuth2/Storage/AuthCodeStorage.php b/api/components/OAuth2/Storage/AuthCodeStorage.php index 77d7f51..681ec57 100644 --- a/api/components/OAuth2/Storage/AuthCodeStorage.php +++ b/api/components/OAuth2/Storage/AuthCodeStorage.php @@ -61,11 +61,11 @@ class AuthCodeStorage extends AbstractStorage implements AuthCodeInterface { $this->scopes($token->getId())->delete(); } - private function key(string $token) : Key { + private function key(string $token): Key { return new Key($this->dataTable, $token); } - private function scopes(string $token) : Set { + private function scopes(string $token): Set { return new Set($this->dataTable, $token, 'scopes'); } diff --git a/api/components/OAuth2/Storage/ClientStorage.php b/api/components/OAuth2/Storage/ClientStorage.php index d5979e2..d7cca10 100644 --- a/api/components/OAuth2/Storage/ClientStorage.php +++ b/api/components/OAuth2/Storage/ClientStorage.php @@ -11,8 +11,8 @@ use yii\helpers\StringHelper; class ClientStorage extends AbstractStorage implements ClientInterface { - const REDIRECT_STATIC_PAGE = 'static_page'; - const REDIRECT_STATIC_PAGE_WITH_CODE = 'static_page_with_code'; + private const REDIRECT_STATIC_PAGE = 'static_page'; + private const REDIRECT_STATIC_PAGE_WITH_CODE = 'static_page_with_code'; /** * @inheritdoc @@ -66,7 +66,7 @@ class ClientStorage extends AbstractStorage implements ClientInterface { return $this->hydrate($model); } - private function hydrate(OauthClient $model) : ClientEntity { + private function hydrate(OauthClient $model): ClientEntity { $entity = new ClientEntity($this->server); $entity->setId($model->id); $entity->setName($model->name); diff --git a/api/components/OAuth2/Storage/RefreshTokenStorage.php b/api/components/OAuth2/Storage/RefreshTokenStorage.php index c1acfe6..6764b2d 100644 --- a/api/components/OAuth2/Storage/RefreshTokenStorage.php +++ b/api/components/OAuth2/Storage/RefreshTokenStorage.php @@ -51,12 +51,12 @@ class RefreshTokenStorage extends AbstractStorage implements RefreshTokenInterfa $this->sessionHash($token->getSessionId())->remove($token->getId()); } - public function sessionHash(string $sessionId) : Set { + public function sessionHash(string $sessionId): Set { $tableName = Yii::$app->db->getSchema()->getRawTableName(OauthSession::tableName()); return new Set($tableName, $sessionId, 'refresh_tokens'); } - private function key(string $token) : Key { + private function key(string $token): Key { return new Key($this->dataTable, $token); } diff --git a/api/components/OAuth2/Storage/SessionStorage.php b/api/components/OAuth2/Storage/SessionStorage.php index c056f9b..2efdfe4 100644 --- a/api/components/OAuth2/Storage/SessionStorage.php +++ b/api/components/OAuth2/Storage/SessionStorage.php @@ -76,7 +76,7 @@ class SessionStorage extends AbstractStorage implements SessionInterface { $this->getSessionModel($session->getId())->getScopes()->add($scope->getId()); } - private function getSessionModel(string $sessionId) : OauthSession { + private function getSessionModel(string $sessionId): OauthSession { $session = OauthSession::findOne($sessionId); if ($session === null) { throw new ErrorException('Cannot find oauth session'); diff --git a/api/components/User/Component.php b/api/components/User/Component.php index 95b52fd..97ec500 100644 --- a/api/components/User/Component.php +++ b/api/components/User/Component.php @@ -214,7 +214,7 @@ class Component extends YiiUserComponent { protected function createToken(Account $account): Token { $token = new Token(); - foreach($this->getClaims($account) as $claim) { + foreach ($this->getClaims($account) as $claim) { $token->addClaim($claim); } diff --git a/api/components/User/Identity.php b/api/components/User/Identity.php index 89a2286..0220eb2 100644 --- a/api/components/User/Identity.php +++ b/api/components/User/Identity.php @@ -18,6 +18,10 @@ class Identity implements IdentityInterface { */ private $_accessToken; + private function __construct(AccessTokenEntity $accessToken) { + $this->_accessToken = $accessToken; + } + /** * @inheritdoc * @throws \yii\web\UnauthorizedHttpException @@ -73,10 +77,6 @@ class Identity implements IdentityInterface { throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); } - private function __construct(AccessTokenEntity $accessToken) { - $this->_accessToken = $accessToken; - } - private function getSession(): OauthSession { return OauthSession::findOne($this->_accessToken->getSessionId()); } diff --git a/api/components/User/JwtIdentity.php b/api/components/User/JwtIdentity.php index 78a8491..71b41e1 100644 --- a/api/components/User/JwtIdentity.php +++ b/api/components/User/JwtIdentity.php @@ -23,6 +23,11 @@ class JwtIdentity implements IdentityInterface { */ private $token; + private function __construct(string $rawToken, Token $token) { + $this->rawToken = $rawToken; + $this->token = $token; + } + public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface { /** @var \api\components\User\Component $component */ $component = Yii::$app->user; @@ -86,9 +91,4 @@ class JwtIdentity implements IdentityInterface { throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth'); } - private function __construct(string $rawToken, Token $token) { - $this->rawToken = $rawToken; - $this->token = $token; - } - } diff --git a/api/components/User/ScopesClaim.php b/api/components/User/ScopesClaim.php index 743c87f..d89c76b 100644 --- a/api/components/User/ScopesClaim.php +++ b/api/components/User/ScopesClaim.php @@ -5,7 +5,7 @@ use Emarref\Jwt\Claim\AbstractClaim; class ScopesClaim extends AbstractClaim { - const NAME = 'ely-scopes'; + public const NAME = 'ely-scopes'; /** * ScopesClaim constructor. diff --git a/api/components/User/SubjectPrefixVerifier.php b/api/components/User/SubjectPrefixVerifier.php index e784dbd..614d6d7 100644 --- a/api/components/User/SubjectPrefixVerifier.php +++ b/api/components/User/SubjectPrefixVerifier.php @@ -21,7 +21,7 @@ class SubjectPrefixVerifier implements VerifierInterface { $subject = ($subjectClaim === null) ? null : $subjectClaim->getValue(); if (!StringHelper::startsWith($subject, $this->subjectPrefix)) { - throw new InvalidSubjectException; + throw new InvalidSubjectException(); } } diff --git a/api/controllers/SignupController.php b/api/controllers/SignupController.php index 04e1f86..3634dc7 100644 --- a/api/controllers/SignupController.php +++ b/api/controllers/SignupController.php @@ -2,8 +2,8 @@ namespace api\controllers; use api\models\authentication\ConfirmEmailForm; -use api\models\authentication\RepeatAccountActivationForm; use api\models\authentication\RegistrationForm; +use api\models\authentication\RepeatAccountActivationForm; use common\helpers\Error as E; use Yii; use yii\filters\AccessControl; diff --git a/api/models/FeedbackForm.php b/api/models/FeedbackForm.php index 52d899f..6e5730c 100644 --- a/api/models/FeedbackForm.php +++ b/api/models/FeedbackForm.php @@ -1,8 +1,8 @@ validate()) { return false; } diff --git a/api/models/authentication/ForgotPasswordForm.php b/api/models/authentication/ForgotPasswordForm.php index 45cf5cc..b0e5bc2 100644 --- a/api/models/authentication/ForgotPasswordForm.php +++ b/api/models/authentication/ForgotPasswordForm.php @@ -4,9 +4,9 @@ namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\models\base\ApiForm; -use common\helpers\Error as E; use api\traits\AccountFinder; use common\components\UserFriendlyRandomKey; +use common\helpers\Error as E; use common\models\Account; use common\models\confirmations\ForgotPassword; use common\models\EmailActivation; diff --git a/api/models/authentication/LoginForm.php b/api/models/authentication/LoginForm.php index c5a2948..8919300 100644 --- a/api/models/authentication/LoginForm.php +++ b/api/models/authentication/LoginForm.php @@ -3,9 +3,9 @@ namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; use api\models\base\ApiForm; +use api\traits\AccountFinder; use api\validators\TotpValidator; use common\helpers\Error as E; -use api\traits\AccountFinder; use common\models\Account; use Yii; @@ -13,8 +13,11 @@ class LoginForm extends ApiForm { use AccountFinder; public $login; + public $password; + public $totp; + public $rememberMe = false; public function rules(): array { diff --git a/api/models/authentication/LogoutForm.php b/api/models/authentication/LogoutForm.php index 8028c68..6f05ac0 100644 --- a/api/models/authentication/LogoutForm.php +++ b/api/models/authentication/LogoutForm.php @@ -11,7 +11,7 @@ class LogoutForm extends ApiForm { * @CollectModelMetrics(prefix="authentication.logout") * @return bool */ - public function logout() : bool { + public function logout(): bool { $component = Yii::$app->user; $session = $component->getActiveSession(); if ($session === null) { diff --git a/api/models/authentication/RegistrationForm.php b/api/models/authentication/RegistrationForm.php index 2382fd5..fba45d4 100644 --- a/api/models/authentication/RegistrationForm.php +++ b/api/models/authentication/RegistrationForm.php @@ -4,8 +4,8 @@ namespace api\models\authentication; use api\aop\annotations\CollectModelMetrics; use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\models\base\ApiForm; -use common\helpers\Error as E; use common\components\UserFriendlyRandomKey; +use common\helpers\Error as E; use common\models\Account; use common\models\confirmations\RegistrationConfirmation; use common\models\UsernameHistory; @@ -126,7 +126,7 @@ class RegistrationForm extends ApiForm { * * @return bool */ - protected function canContinue(array $errors) : bool { + protected function canContinue(array $errors): bool { if (ArrayHelper::getValue($errors, 'username') === E::USERNAME_NOT_AVAILABLE) { $duplicatedUsername = Account::findOne([ 'username' => $this->username, diff --git a/api/models/authentication/RepeatAccountActivationForm.php b/api/models/authentication/RepeatAccountActivationForm.php index 9cbec46..a569c1d 100644 --- a/api/models/authentication/RepeatAccountActivationForm.php +++ b/api/models/authentication/RepeatAccountActivationForm.php @@ -5,8 +5,8 @@ use api\aop\annotations\CollectModelMetrics; use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\exceptions\ThisShouldNotHappenException; use api\models\base\ApiForm; -use common\helpers\Error as E; use common\components\UserFriendlyRandomKey; +use common\helpers\Error as E; use common\models\Account; use common\models\confirmations\RegistrationConfirmation; use common\models\EmailActivation; diff --git a/api/modules/accounts/actions/BaseAccountAction.php b/api/modules/accounts/actions/BaseAccountAction.php index 6f637a4..149cf34 100644 --- a/api/modules/accounts/actions/BaseAccountAction.php +++ b/api/modules/accounts/actions/BaseAccountAction.php @@ -21,8 +21,6 @@ abstract class BaseAccountAction extends Action { return $this->formatSuccessResult($model); } - abstract protected function getFormClassName(): string; - public function getRequestData(): array { return Yii::$app->request->post(); } @@ -35,6 +33,8 @@ abstract class BaseAccountAction extends Action { return []; } + abstract protected function getFormClassName(): string; + private function formatFailedResult(AccountActionForm $model): array { $response = [ 'success' => false, diff --git a/api/modules/accounts/actions/ChangeEmailAction.php b/api/modules/accounts/actions/ChangeEmailAction.php index 241c7ed..ddb26ad 100644 --- a/api/modules/accounts/actions/ChangeEmailAction.php +++ b/api/modules/accounts/actions/ChangeEmailAction.php @@ -6,10 +6,6 @@ use api\modules\accounts\models\ChangeEmailForm; class ChangeEmailAction extends BaseAccountAction { - protected function getFormClassName(): string { - return ChangeEmailForm::class; - } - /** * @param ChangeEmailForm|AccountActionForm $model * @return array @@ -20,4 +16,8 @@ class ChangeEmailAction extends BaseAccountAction { ]; } + protected function getFormClassName(): string { + return ChangeEmailForm::class; + } + } diff --git a/api/modules/accounts/actions/EmailVerificationAction.php b/api/modules/accounts/actions/EmailVerificationAction.php index 76ff768..d03efdf 100644 --- a/api/modules/accounts/actions/EmailVerificationAction.php +++ b/api/modules/accounts/actions/EmailVerificationAction.php @@ -7,10 +7,6 @@ use common\helpers\Error as E; class EmailVerificationAction extends BaseAccountAction { - protected function getFormClassName(): string { - return SendEmailVerificationForm::class; - } - /** * @param SendEmailVerificationForm|AccountActionForm $model * @return array @@ -29,4 +25,8 @@ class EmailVerificationAction extends BaseAccountAction { ]; } + protected function getFormClassName(): string { + return SendEmailVerificationForm::class; + } + } diff --git a/api/modules/accounts/models/ChangeEmailForm.php b/api/modules/accounts/models/ChangeEmailForm.php index c1c92c4..1f03b67 100644 --- a/api/modules/accounts/models/ChangeEmailForm.php +++ b/api/modules/accounts/models/ChangeEmailForm.php @@ -49,7 +49,7 @@ class ChangeEmailForm extends AccountActionForm { } public function createTask(int $accountId, string $newEmail, string $oldEmail): void { - $model = new EmailChanged; + $model = new EmailChanged(); $model->accountId = $accountId; $model->oldEmail = $oldEmail; $model->newEmail = $newEmail; diff --git a/api/modules/accounts/models/TotpHelper.php b/api/modules/accounts/models/TotpHelper.php index 0f3111b..830667c 100644 --- a/api/modules/accounts/models/TotpHelper.php +++ b/api/modules/accounts/models/TotpHelper.php @@ -6,6 +6,8 @@ use OTPHP\TOTP; trait TotpHelper { + abstract public function getAccount(): Account; + protected function getTotp(): TOTP { $account = $this->getAccount(); $totp = TOTP::create($account->otp_secret); @@ -15,6 +17,4 @@ trait TotpHelper { return $totp; } - abstract public function getAccount(): Account; - } diff --git a/api/modules/authserver/controllers/AuthenticationController.php b/api/modules/authserver/controllers/AuthenticationController.php index 0f514a1..728859b 100644 --- a/api/modules/authserver/controllers/AuthenticationController.php +++ b/api/modules/authserver/controllers/AuthenticationController.php @@ -17,10 +17,10 @@ class AuthenticationController extends Controller { public function verbs() { return [ 'authenticate' => ['POST'], - 'refresh' => ['POST'], - 'validate' => ['POST'], - 'signout' => ['POST'], - 'invalidate' => ['POST'], + 'refresh' => ['POST'], + 'validate' => ['POST'], + 'signout' => ['POST'], + 'invalidate' => ['POST'], ]; } diff --git a/api/modules/authserver/models/AuthenticateData.php b/api/modules/authserver/models/AuthenticateData.php index 8f8cdea..68e373a 100644 --- a/api/modules/authserver/models/AuthenticateData.php +++ b/api/modules/authserver/models/AuthenticateData.php @@ -14,11 +14,11 @@ class AuthenticateData { $this->minecraftAccessKey = $minecraftAccessKey; } - public function getMinecraftAccessKey() : MinecraftAccessKey { + public function getMinecraftAccessKey(): MinecraftAccessKey { return $this->minecraftAccessKey; } - public function getResponseData(bool $includeAvailableProfiles = false) : array { + public function getResponseData(bool $includeAvailableProfiles = false): array { $accessKey = $this->minecraftAccessKey; $account = $accessKey->account; diff --git a/api/modules/authserver/models/AuthenticationForm.php b/api/modules/authserver/models/AuthenticationForm.php index b8c8921..5bacab6 100644 --- a/api/modules/authserver/models/AuthenticationForm.php +++ b/api/modules/authserver/models/AuthenticationForm.php @@ -14,7 +14,9 @@ use common\models\MinecraftAccessKey; class AuthenticationForm extends ApiForm { public $username; + public $password; + public $clientToken; public function rules() { @@ -41,13 +43,15 @@ class AuthenticationForm extends ApiForm { if (isset($errors['totp'])) { Authserver::error("User with login = '{$this->username}' protected by two factor auth."); throw new ForbiddenOperationException('Account protected with two factor auth.'); - } elseif (isset($errors['login'])) { + } + + if (isset($errors['login'])) { if ($errors['login'] === E::ACCOUNT_BANNED) { Authserver::error("User with login = '{$this->username}' is banned"); throw new ForbiddenOperationException('This account has been suspended.'); - } else { - Authserver::error("Cannot find user by login = '{$this->username}'"); } + + Authserver::error("Cannot find user by login = '{$this->username}'"); } elseif (isset($errors['password'])) { Authserver::error("User with login = '{$this->username}' passed wrong password."); } @@ -72,7 +76,7 @@ class AuthenticationForm extends ApiForm { return $dataModel; } - protected function createMinecraftAccessToken(Account $account) : MinecraftAccessKey { + protected function createMinecraftAccessToken(Account $account): MinecraftAccessKey { /** @var MinecraftAccessKey|null $accessTokenModel */ $accessTokenModel = MinecraftAccessKey::findOne([ 'account_id' => $account->id, @@ -92,7 +96,7 @@ class AuthenticationForm extends ApiForm { return $accessTokenModel; } - protected function createLoginForm() : LoginForm { + protected function createLoginForm(): LoginForm { return new LoginForm(); } diff --git a/api/modules/authserver/models/InvalidateForm.php b/api/modules/authserver/models/InvalidateForm.php index a81e0ef..d270c7f 100644 --- a/api/modules/authserver/models/InvalidateForm.php +++ b/api/modules/authserver/models/InvalidateForm.php @@ -8,6 +8,7 @@ use common\models\MinecraftAccessKey; class InvalidateForm extends ApiForm { public $accessToken; + public $clientToken; public function rules() { @@ -20,7 +21,7 @@ class InvalidateForm extends ApiForm { * @return bool * @throws \api\modules\authserver\exceptions\AuthserverException */ - public function invalidateToken() : bool { + public function invalidateToken(): bool { $this->validate(); $token = MinecraftAccessKey::findOne([ diff --git a/api/modules/authserver/models/RefreshTokenForm.php b/api/modules/authserver/models/RefreshTokenForm.php index 063e324..2deb3b1 100644 --- a/api/modules/authserver/models/RefreshTokenForm.php +++ b/api/modules/authserver/models/RefreshTokenForm.php @@ -10,6 +10,7 @@ use common\models\MinecraftAccessKey; class RefreshTokenForm extends ApiForm { public $accessToken; + public $clientToken; public function rules() { diff --git a/api/modules/authserver/models/SignoutForm.php b/api/modules/authserver/models/SignoutForm.php index f1602c2..7f4b1d7 100644 --- a/api/modules/authserver/models/SignoutForm.php +++ b/api/modules/authserver/models/SignoutForm.php @@ -12,6 +12,7 @@ use Yii; class SignoutForm extends ApiForm { public $username; + public $password; public function rules() { @@ -20,7 +21,7 @@ class SignoutForm extends ApiForm { ]; } - public function signout() : bool { + public function signout(): bool { $this->validate(); $loginForm = new LoginForm(); diff --git a/api/modules/authserver/models/ValidateForm.php b/api/modules/authserver/models/ValidateForm.php index 2e0a26e..75370e2 100644 --- a/api/modules/authserver/models/ValidateForm.php +++ b/api/modules/authserver/models/ValidateForm.php @@ -16,7 +16,7 @@ class ValidateForm extends ApiForm { ]; } - public function validateToken() : bool { + public function validateToken(): bool { $this->validate(); /** @var MinecraftAccessKey|null $result */ diff --git a/api/modules/mojang/controllers/ApiController.php b/api/modules/mojang/controllers/ApiController.php index 680fb7f..a7b19b2 100644 --- a/api/modules/mojang/controllers/ApiController.php +++ b/api/modules/mojang/controllers/ApiController.php @@ -54,7 +54,7 @@ class ApiController extends Controller { public function actionUsernamesByUuid($uuid) { try { $uuid = Uuid::fromString($uuid)->toString(); - } catch(\InvalidArgumentException $e) { + } catch (\InvalidArgumentException $e) { return $this->illegalArgumentResponse('Invalid uuid format.'); } @@ -69,7 +69,7 @@ class ApiController extends Controller { ->all(); $data = []; - foreach($usernameHistory as $record) { + foreach ($usernameHistory as $record) { $data[] = [ 'name' => $record->username, 'changedToAt' => $record->applied_in * 1000, @@ -94,7 +94,7 @@ class ApiController extends Controller { return $this->illegalArgumentResponse('Not more that 100 profile name per call is allowed.'); } - foreach($usernames as $username) { + foreach ($usernames as $username) { if (empty($username) || is_array($username)) { return $this->illegalArgumentResponse('profileName can not be null, empty or array key.'); } @@ -108,7 +108,7 @@ class ApiController extends Controller { ->all(); $responseData = []; - foreach($accounts as $account) { + foreach ($accounts as $account) { $responseData[] = [ 'id' => str_replace('-', '', $account->uuid), 'name' => $account->username, diff --git a/api/modules/oauth/controllers/AuthorizationController.php b/api/modules/oauth/controllers/AuthorizationController.php index aceb385..d0ad35c 100644 --- a/api/modules/oauth/controllers/AuthorizationController.php +++ b/api/modules/oauth/controllers/AuthorizationController.php @@ -38,7 +38,7 @@ class AuthorizationController extends Controller { return [ 'validate' => ['GET'], 'complete' => ['POST'], - 'token' => ['POST'], + 'token' => ['POST'], ]; } diff --git a/api/modules/oauth/exceptions/OauthException.php b/api/modules/oauth/exceptions/OauthException.php index 775c0a7..3197b75 100644 --- a/api/modules/oauth/exceptions/OauthException.php +++ b/api/modules/oauth/exceptions/OauthException.php @@ -4,4 +4,5 @@ declare(strict_types=1); namespace api\modules\oauth\exceptions; interface OauthException { + } diff --git a/api/modules/oauth/models/ApplicationType.php b/api/modules/oauth/models/ApplicationType.php index 244bf7c..c4745a2 100644 --- a/api/modules/oauth/models/ApplicationType.php +++ b/api/modules/oauth/models/ApplicationType.php @@ -16,7 +16,7 @@ class ApplicationType extends BaseOauthClientType { public function rules(): array { return ArrayHelper::merge(parent::rules(), [ ['redirectUri', 'required', 'message' => E::REDIRECT_URI_REQUIRED], - ['redirectUri', 'url', 'validSchemes' => ['[\w]+'], 'message' => E::REDIRECT_URI_INVALID], + ['redirectUri', 'url', 'validSchemes' => ['[\w]+'], 'message' => E::REDIRECT_URI_INVALID], ['description', 'string'], ]); } diff --git a/api/modules/session/controllers/SessionController.php b/api/modules/session/controllers/SessionController.php index 4c860ba..6e88b11 100644 --- a/api/modules/session/controllers/SessionController.php +++ b/api/modules/session/controllers/SessionController.php @@ -98,7 +98,7 @@ class SessionController extends Controller { public function actionProfile($uuid) { try { $uuid = Uuid::fromString($uuid)->toString(); - } catch(\InvalidArgumentException $e) { + } catch (\InvalidArgumentException $e) { throw new IllegalArgumentException('Invalid uuid format.'); } diff --git a/api/modules/session/exceptions/ForbiddenOperationException.php b/api/modules/session/exceptions/ForbiddenOperationException.php index 420aaec..2a389e4 100644 --- a/api/modules/session/exceptions/ForbiddenOperationException.php +++ b/api/modules/session/exceptions/ForbiddenOperationException.php @@ -1,7 +1,7 @@ server; } - protected function buildKey($ip) : string { + protected function buildKey($ip): string { return 'sessionserver:ratelimit:' . $ip; } diff --git a/api/modules/session/models/JoinForm.php b/api/modules/session/models/JoinForm.php index 8b47053..0361ae5 100644 --- a/api/modules/session/models/JoinForm.php +++ b/api/modules/session/models/JoinForm.php @@ -7,9 +7,9 @@ use api\modules\session\models\protocols\JoinInterface; use api\modules\session\Module as Session; use api\modules\session\validators\RequiredValidator; use common\helpers\StringHelper; -use common\rbac\Permissions as P; use common\models\Account; use common\models\MinecraftAccessKey; +use common\rbac\Permissions as P; use Ramsey\Uuid\Uuid; use Yii; use yii\base\ErrorException; @@ -19,7 +19,9 @@ use yii\web\UnauthorizedHttpException; class JoinForm extends Model { public $accessToken; + public $selectedProfile; + public $serverId; /** diff --git a/api/modules/session/models/SessionModel.php b/api/modules/session/models/SessionModel.php index c58c65e..ed5e626 100644 --- a/api/modules/session/models/SessionModel.php +++ b/api/modules/session/models/SessionModel.php @@ -6,7 +6,7 @@ use Yii; class SessionModel { - const KEY_TIME = 120; // 2 min + private const KEY_TIME = 120; // 2 min public $username; diff --git a/api/modules/session/models/protocols/BaseHasJoined.php b/api/modules/session/models/protocols/BaseHasJoined.php index 2bce25e..99e5d28 100644 --- a/api/modules/session/models/protocols/BaseHasJoined.php +++ b/api/modules/session/models/protocols/BaseHasJoined.php @@ -4,6 +4,7 @@ namespace api\modules\session\models\protocols; abstract class BaseHasJoined implements HasJoinedInterface { private $username; + private $serverId; public function __construct(string $username, string $serverId) { diff --git a/api/modules/session/models/protocols/LegacyJoin.php b/api/modules/session/models/protocols/LegacyJoin.php index 16ee65e..6b119ff 100644 --- a/api/modules/session/models/protocols/LegacyJoin.php +++ b/api/modules/session/models/protocols/LegacyJoin.php @@ -4,10 +4,13 @@ namespace api\modules\session\models\protocols; class LegacyJoin extends BaseJoin { private $user; + private $sessionId; + private $serverId; private $accessToken; + private $uuid; public function __construct(string $user, string $sessionId, string $serverId) { @@ -18,7 +21,7 @@ class LegacyJoin extends BaseJoin { $this->parseSessionId($this->sessionId); } - public function getAccessToken() : string { + public function getAccessToken(): string { return $this->accessToken; } diff --git a/api/modules/session/models/protocols/ModernJoin.php b/api/modules/session/models/protocols/ModernJoin.php index 6fd0942..493bc21 100644 --- a/api/modules/session/models/protocols/ModernJoin.php +++ b/api/modules/session/models/protocols/ModernJoin.php @@ -4,7 +4,9 @@ namespace api\modules\session\models\protocols; class ModernJoin extends BaseJoin { private $accessToken; + private $selectedProfile; + private $serverId; public function __construct(string $accessToken, string $selectedProfile, string $serverId) { diff --git a/api/traits/AccountFinder.php b/api/traits/AccountFinder.php index 782ba57..33a01b5 100644 --- a/api/traits/AccountFinder.php +++ b/api/traits/AccountFinder.php @@ -7,7 +7,7 @@ trait AccountFinder { private $account; - public abstract function getLogin(): string; + abstract public function getLogin(): string; public function getAccount(): ?Account { if ($this->account === null) { diff --git a/common/behaviors/DataBehavior.php b/common/behaviors/DataBehavior.php index 8c0c2e1..967cf85 100644 --- a/common/behaviors/DataBehavior.php +++ b/common/behaviors/DataBehavior.php @@ -5,6 +5,7 @@ use yii\base\Behavior; use yii\helpers\ArrayHelper; class DataBehavior extends Behavior { + /** * @var string имя атрибута, к которому будет применяться поведение */ diff --git a/common/behaviors/EmailActivationExpirationBehavior.php b/common/behaviors/EmailActivationExpirationBehavior.php index 3412455..d518437 100644 --- a/common/behaviors/EmailActivationExpirationBehavior.php +++ b/common/behaviors/EmailActivationExpirationBehavior.php @@ -30,7 +30,7 @@ class EmailActivationExpirationBehavior extends Behavior { * @see EmailActivation::compareTime() * @return bool */ - public function canRepeat() : bool { + public function canRepeat(): bool { return $this->compareTime($this->repeatTimeout); } @@ -44,7 +44,7 @@ class EmailActivationExpirationBehavior extends Behavior { * @see EmailActivation::compareTime() * @return bool */ - public function isExpired() : bool { + public function isExpired(): bool { return $this->compareTime($this->expirationTimeout); } @@ -53,7 +53,7 @@ class EmailActivationExpirationBehavior extends Behavior { * * @return int */ - public function canRepeatIn() : int { + public function canRepeatIn(): int { return $this->calculateTime($this->repeatTimeout); } @@ -62,11 +62,11 @@ class EmailActivationExpirationBehavior extends Behavior { * * @return int */ - public function expireIn() : int { + public function expireIn(): int { return $this->calculateTime($this->expirationTimeout); } - protected function compareTime(int $value) : bool { + protected function compareTime(int $value): bool { if ($value < 0) { return false; } @@ -78,7 +78,7 @@ class EmailActivationExpirationBehavior extends Behavior { return time() > $this->calculateTime($value); } - protected function calculateTime(int $value) : int { + protected function calculateTime(int $value): int { return $this->owner->created_at + $value; } diff --git a/common/behaviors/PrimaryKeyValueBehavior.php b/common/behaviors/PrimaryKeyValueBehavior.php index b882547..0882f20 100644 --- a/common/behaviors/PrimaryKeyValueBehavior.php +++ b/common/behaviors/PrimaryKeyValueBehavior.php @@ -24,7 +24,7 @@ class PrimaryKeyValueBehavior extends Behavior { ]; } - public function setPrimaryKeyValue() : bool { + public function setPrimaryKeyValue(): bool { if ($this->owner->getPrimaryKey() === null) { $this->refreshPrimaryKeyValue(); } @@ -40,15 +40,15 @@ class PrimaryKeyValueBehavior extends Behavior { $this->owner->{$this->getPrimaryKeyName()} = $key; } - protected function generateValue() : string { + protected function generateValue(): string { return (string)call_user_func($this->value); } - protected function isValueExists(string $key) : bool { + protected function isValueExists(string $key): bool { return $this->owner->find()->andWhere([$this->getPrimaryKeyName() => $key])->exists(); } - protected function getPrimaryKeyName() : string { + protected function getPrimaryKeyName(): string { $owner = $this->owner; $primaryKeys = $owner->primaryKey(); if (!isset($primaryKeys[0])) { diff --git a/common/components/EmailRenderer.php b/common/components/EmailRenderer.php index ce0e3e7..615906e 100644 --- a/common/components/EmailRenderer.php +++ b/common/components/EmailRenderer.php @@ -43,7 +43,7 @@ class EmailRenderer extends Component { $this->renderer->setBaseDomain($this->buildBasePath()); } - public function getBaseDomain() : string { + public function getBaseDomain(): string { return $this->_baseDomain; } diff --git a/common/components/Qr/ElyDecorator.php b/common/components/Qr/ElyDecorator.php index 6ce2f47..20876e8 100644 --- a/common/components/Qr/ElyDecorator.php +++ b/common/components/Qr/ElyDecorator.php @@ -106,7 +106,6 @@ class ElyDecorator implements DecoratorInterface { $topPadding, $multiple ) { - } private function encodeSvgToBase64(string $filePath): string { diff --git a/common/components/RabbitMQ/Component.php b/common/components/RabbitMQ/Component.php index 0ce0f91..b7e6177 100644 --- a/common/components/RabbitMQ/Component.php +++ b/common/components/RabbitMQ/Component.php @@ -1,11 +1,11 @@ basic_publish(...$this->preparePublishArgs($message, $exchangeName, $routingKey, $publishArgs)); } + /** + * Returns prepaired AMQP message. + * + * @param string|array|object $message + * @param array $properties + * @return AMQPMessage + * @throws Exception If message is empty. + */ + public function prepareMessage($message, $properties = null) { + if ($message instanceof AMQPMessage) { + return $message; + } + + if (empty($message)) { + throw new Exception('AMQP message can not be empty'); + } + + if (is_array($message) || is_object($message)) { + $message = Json::encode($message); + } + + return new AMQPMessage($message, $properties); + } + /** * Объединяет переданный набор аргументов с поведением по умолчанию * @@ -150,28 +174,4 @@ class Component extends \yii\base\Component { ], $args); } - /** - * Returns prepaired AMQP message. - * - * @param string|array|object $message - * @param array $properties - * @return AMQPMessage - * @throws Exception If message is empty. - */ - public function prepareMessage($message, $properties = null) { - if ($message instanceof AMQPMessage) { - return $message; - } - - if (empty($message)) { - throw new Exception('AMQP message can not be empty'); - } - - if (is_array($message) || is_object($message)) { - $message = Json::encode($message); - } - - return new AMQPMessage($message, $properties); - } - } diff --git a/common/components/Redis/Connection.php b/common/components/Redis/Connection.php index 5bdc47d..28d62c4 100644 --- a/common/components/Redis/Connection.php +++ b/common/components/Redis/Connection.php @@ -157,7 +157,7 @@ class Connection extends Component implements ConnectionInterface { /** * @var array List of available redis commands http://redis.io/commands */ - const REDIS_COMMANDS = [ + public const REDIS_COMMANDS = [ 'BLPOP', // key [key ...] timeout Remove and get the first element in a list, or block until one is available 'BRPOP', // key [key ...] timeout Remove and get the last element in a list, or block until one is available 'BRPOPLPUSH', // source destination timeout Pop a value from a list, push it to another list and return it; or block until one is available @@ -368,14 +368,6 @@ class Connection extends Component implements ConnectionInterface { */ private $_client; - public function getConnection() : ClientInterface { - if ($this->_client === null) { - $this->_client = new Client($this->prepareParams(), $this->options); - } - - return $this->_client; - } - public function __call($name, $params) { $redisCommand = mb_strtoupper($name); if (in_array($redisCommand, self::REDIS_COMMANDS)) { @@ -385,6 +377,14 @@ class Connection extends Component implements ConnectionInterface { return parent::__call($name, $params); } + public function getConnection(): ClientInterface { + if ($this->_client === null) { + $this->_client = new Client($this->prepareParams(), $this->options); + } + + return $this->_client; + } + public function executeCommand(string $name, array $params = []) { return $this->getConnection()->$name(...$params); } diff --git a/common/components/Redis/Key.php b/common/components/Redis/Key.php index 2f38b95..3ce7e15 100644 --- a/common/components/Redis/Key.php +++ b/common/components/Redis/Key.php @@ -30,11 +30,13 @@ class Key { public function setValue($value): self { $this->getRedis()->set($this->key, $value); + return $this; } public function delete(): self { $this->getRedis()->del([$this->getKey()]); + return $this; } @@ -44,17 +46,19 @@ class Key { public function expire(int $ttl): self { $this->getRedis()->expire($this->key, $ttl); + return $this; } public function expireAt(int $unixTimestamp): self { $this->getRedis()->expireat($this->key, $unixTimestamp); + return $this; } private function buildKey(array $parts): string { $keyParts = []; - foreach($parts as $part) { + foreach ($parts as $part) { $keyParts[] = str_replace('_', ':', $part); } diff --git a/common/components/Redis/Set.php b/common/components/Redis/Set.php index debae64..b106304 100644 --- a/common/components/Redis/Set.php +++ b/common/components/Redis/Set.php @@ -8,11 +8,13 @@ class Set extends Key implements IteratorAggregate { public function add($value): self { $this->getRedis()->sadd($this->getKey(), $value); + return $this; } public function remove($value): self { $this->getRedis()->srem($this->getKey(), $value); + return $this; } diff --git a/common/components/SkinSystem/Api.php b/common/components/SkinSystem/Api.php index 4237eac..4854354 100644 --- a/common/components/SkinSystem/Api.php +++ b/common/components/SkinSystem/Api.php @@ -6,7 +6,7 @@ use Yii; class Api { - const BASE_DOMAIN = 'http://skinsystem.ely.by'; + private const BASE_DOMAIN = 'http://skinsystem.ely.by'; /** * @param string $username diff --git a/common/components/UserFriendlyRandomKey.php b/common/components/UserFriendlyRandomKey.php index ebeb111..6c66c02 100644 --- a/common/components/UserFriendlyRandomKey.php +++ b/common/components/UserFriendlyRandomKey.php @@ -1,10 +1,11 @@ application = $application; } - public function getEnvironment() : string { + public function getEnvironment(): string { return YII_ENV; } - public function getConfig() : array { + public function getConfig(): array { $toMerge = [ require __DIR__ . '/config.php', ]; @@ -55,7 +55,7 @@ class ConfigLoader { return ArrayHelper::merge(...$toMerge); } - public static function load(string $application) : array { + public static function load(string $application): array { return (new static($application))->getConfig(); } diff --git a/common/config/config.php b/common/config/config.php index c8f3632..36b1266 100644 --- a/common/config/config.php +++ b/common/config/config.php @@ -115,6 +115,6 @@ return [ ], 'aliases' => [ '@bower' => '@vendor/bower-asset', - '@npm' => '@vendor/npm-asset', + '@npm' => '@vendor/npm-asset', ], ]; diff --git a/common/db/mysql/QueryBuilder.php b/common/db/mysql/QueryBuilder.php index f467396..66c5a24 100644 --- a/common/db/mysql/QueryBuilder.php +++ b/common/db/mysql/QueryBuilder.php @@ -1,7 +1,7 @@ $direction) { - if ($direction instanceof Expression) { + foreach ($columns as $name => $direction) { + if ($direction instanceof ExpressionInterface) { $orders[] = $direction->expression; } elseif (is_array($direction)) { - // This is new feature + // This condition branch is our custom solution if (empty($direction)) { continue; } $fieldValues = []; - foreach($direction as $fieldValue) { + foreach ($direction as $fieldValue) { $fieldValues[] = $this->db->quoteValue($fieldValue); } $orders[] = 'FIELD(' . $this->db->quoteColumnName($name) . ',' . implode(',', $fieldValues) . ')'; - // End of new feature } else { $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : ''); } diff --git a/common/emails/TemplateWithRenderer.php b/common/emails/TemplateWithRenderer.php index 33b40f1..adfef8c 100644 --- a/common/emails/TemplateWithRenderer.php +++ b/common/emails/TemplateWithRenderer.php @@ -42,7 +42,7 @@ abstract class TemplateWithRenderer extends Template { */ abstract public function getTemplateName(): string; - protected final function getView() { + final protected function getView() { return $this->getTemplateName(); } diff --git a/common/emails/templates/ChangeEmailConfirmCurrentEmail.php b/common/emails/templates/ChangeEmailConfirmCurrentEmail.php index 8c48907..ea280dd 100644 --- a/common/emails/templates/ChangeEmailConfirmCurrentEmail.php +++ b/common/emails/templates/ChangeEmailConfirmCurrentEmail.php @@ -16,6 +16,12 @@ class ChangeEmailConfirmCurrentEmail extends Template { return 'Ely.by Account change E-mail confirmation'; } + public function getParams(): array { + return [ + 'key' => $this->key, + ]; + } + /** * @return string|array */ @@ -26,10 +32,4 @@ class ChangeEmailConfirmCurrentEmail extends Template { ]; } - public function getParams(): array { - return [ - 'key' => $this->key, - ]; - } - } diff --git a/common/emails/templates/ChangeEmailConfirmNewEmail.php b/common/emails/templates/ChangeEmailConfirmNewEmail.php index 507b830..ea1dd9b 100644 --- a/common/emails/templates/ChangeEmailConfirmNewEmail.php +++ b/common/emails/templates/ChangeEmailConfirmNewEmail.php @@ -19,6 +19,13 @@ class ChangeEmailConfirmNewEmail extends Template { return 'Ely.by Account new E-mail confirmation'; } + public function getParams(): array { + return [ + 'key' => $this->key, + 'username' => $this->username, + ]; + } + /** * @return string|array */ @@ -29,11 +36,4 @@ class ChangeEmailConfirmNewEmail extends Template { ]; } - public function getParams(): array { - return [ - 'key' => $this->key, - 'username' => $this->username, - ]; - } - } diff --git a/common/helpers/Error.php b/common/helpers/Error.php index 8e34ba9..1d34bfc 100644 --- a/common/helpers/Error.php +++ b/common/helpers/Error.php @@ -3,70 +3,70 @@ namespace common\helpers; final class Error { - const USERNAME_REQUIRED = 'error.username_required'; - const USERNAME_TOO_SHORT = 'error.username_too_short'; - const USERNAME_TOO_LONG = 'error.username_too_long'; - const USERNAME_INVALID = 'error.username_invalid'; - const USERNAME_NOT_AVAILABLE = 'error.username_not_available'; + public const USERNAME_REQUIRED = 'error.username_required'; + public const USERNAME_TOO_SHORT = 'error.username_too_short'; + public const USERNAME_TOO_LONG = 'error.username_too_long'; + public const USERNAME_INVALID = 'error.username_invalid'; + public const USERNAME_NOT_AVAILABLE = 'error.username_not_available'; - const EMAIL_REQUIRED = 'error.email_required'; - const EMAIL_TOO_LONG = 'error.email_too_long'; - const EMAIL_INVALID = 'error.email_invalid'; - const EMAIL_IS_TEMPMAIL = 'error.email_is_tempmail'; - const EMAIL_NOT_AVAILABLE = 'error.email_not_available'; - const EMAIL_NOT_FOUND = 'error.email_not_found'; + public const EMAIL_REQUIRED = 'error.email_required'; + public const EMAIL_TOO_LONG = 'error.email_too_long'; + public const EMAIL_INVALID = 'error.email_invalid'; + public const EMAIL_IS_TEMPMAIL = 'error.email_is_tempmail'; + public const EMAIL_NOT_AVAILABLE = 'error.email_not_available'; + public const EMAIL_NOT_FOUND = 'error.email_not_found'; - const LOGIN_REQUIRED = 'error.login_required'; - const LOGIN_NOT_EXIST = 'error.login_not_exist'; + public const LOGIN_REQUIRED = 'error.login_required'; + public const LOGIN_NOT_EXIST = 'error.login_not_exist'; - const PASSWORD_REQUIRED = 'error.password_required'; - const PASSWORD_INCORRECT = 'error.password_incorrect'; - const PASSWORD_TOO_SHORT = 'error.password_too_short'; + public const PASSWORD_REQUIRED = 'error.password_required'; + public const PASSWORD_INCORRECT = 'error.password_incorrect'; + public const PASSWORD_TOO_SHORT = 'error.password_too_short'; - const KEY_REQUIRED = 'error.key_required'; - const KEY_NOT_EXISTS = 'error.key_not_exists'; - const KEY_EXPIRE = 'error.key_expire'; + public const KEY_REQUIRED = 'error.key_required'; + public const KEY_NOT_EXISTS = 'error.key_not_exists'; + public const KEY_EXPIRE = 'error.key_expire'; - const ACCOUNT_BANNED = 'error.account_banned'; - const ACCOUNT_NOT_ACTIVATED = 'error.account_not_activated'; - const ACCOUNT_ALREADY_ACTIVATED = 'error.account_already_activated'; - const ACCOUNT_CANNOT_RESEND_MESSAGE = 'error.account_cannot_resend_message'; + public const ACCOUNT_BANNED = 'error.account_banned'; + public const ACCOUNT_NOT_ACTIVATED = 'error.account_not_activated'; + public const ACCOUNT_ALREADY_ACTIVATED = 'error.account_already_activated'; + public const ACCOUNT_CANNOT_RESEND_MESSAGE = 'error.account_cannot_resend_message'; - const RECENTLY_SENT_MESSAGE = 'error.recently_sent_message'; + public const RECENTLY_SENT_MESSAGE = 'error.recently_sent_message'; - const NEW_PASSWORD_REQUIRED = 'error.newPassword_required'; - const NEW_RE_PASSWORD_REQUIRED = 'error.newRePassword_required'; - const NEW_RE_PASSWORD_DOES_NOT_MATCH = self::RE_PASSWORD_DOES_NOT_MATCH; + public const NEW_PASSWORD_REQUIRED = 'error.newPassword_required'; + public const NEW_RE_PASSWORD_REQUIRED = 'error.newRePassword_required'; + public const NEW_RE_PASSWORD_DOES_NOT_MATCH = self::RE_PASSWORD_DOES_NOT_MATCH; - const REFRESH_TOKEN_REQUIRED = 'error.refresh_token_required'; - const REFRESH_TOKEN_NOT_EXISTS = 'error.refresh_token_not_exist'; + public const REFRESH_TOKEN_REQUIRED = 'error.refresh_token_required'; + public const REFRESH_TOKEN_NOT_EXISTS = 'error.refresh_token_not_exist'; - const CAPTCHA_REQUIRED = 'error.captcha_required'; - const CAPTCHA_INVALID = 'error.captcha_invalid'; + public const CAPTCHA_REQUIRED = 'error.captcha_required'; + public const CAPTCHA_INVALID = 'error.captcha_invalid'; - const RULES_AGREEMENT_REQUIRED = 'error.rulesAgreement_required'; + public const RULES_AGREEMENT_REQUIRED = 'error.rulesAgreement_required'; - const RE_PASSWORD_REQUIRED = 'error.rePassword_required'; - const RE_PASSWORD_DOES_NOT_MATCH = 'error.rePassword_does_not_match'; + public const RE_PASSWORD_REQUIRED = 'error.rePassword_required'; + public const RE_PASSWORD_DOES_NOT_MATCH = 'error.rePassword_does_not_match'; - const UNSUPPORTED_LANGUAGE = 'error.unsupported_language'; + public const UNSUPPORTED_LANGUAGE = 'error.unsupported_language'; - const SUBJECT_REQUIRED = 'error.subject_required'; - const MESSAGE_REQUIRED = 'error.message_required'; + public const SUBJECT_REQUIRED = 'error.subject_required'; + public const MESSAGE_REQUIRED = 'error.message_required'; - const TOTP_REQUIRED = 'error.totp_required'; - const TOTP_INCORRECT = 'error.totp_incorrect'; + public const TOTP_REQUIRED = 'error.totp_required'; + public const TOTP_INCORRECT = 'error.totp_incorrect'; - const OTP_ALREADY_ENABLED = 'error.otp_already_enabled'; - const OTP_NOT_ENABLED = 'error.otp_not_enabled'; + public const OTP_ALREADY_ENABLED = 'error.otp_already_enabled'; + public const OTP_NOT_ENABLED = 'error.otp_not_enabled'; - const NAME_REQUIRED = 'error.name_required'; + public const NAME_REQUIRED = 'error.name_required'; - const REDIRECT_URI_REQUIRED = 'error.redirectUri_required'; - const REDIRECT_URI_INVALID = 'error.redirectUri_invalid'; + public const REDIRECT_URI_REQUIRED = 'error.redirectUri_required'; + public const REDIRECT_URI_INVALID = 'error.redirectUri_invalid'; - const WEBSITE_URL_INVALID = 'error.websiteUrl_invalid'; + public const WEBSITE_URL_INVALID = 'error.websiteUrl_invalid'; - const MINECRAFT_SERVER_IP_INVALID = 'error.minecraftServerIp_invalid'; + public const MINECRAFT_SERVER_IP_INVALID = 'error.minecraftServerIp_invalid'; } diff --git a/common/helpers/StringHelper.php b/common/helpers/StringHelper.php index 97be7b1..1e29e61 100644 --- a/common/helpers/StringHelper.php +++ b/common/helpers/StringHelper.php @@ -13,9 +13,9 @@ class StringHelper { if ($usernameLength === 1) { $mask = $maskChars; - } elseif($usernameLength === 2) { + } elseif ($usernameLength === 2) { $mask = mb_substr($username, 0, 1) . $maskChars; - } elseif($usernameLength === 3) { + } elseif ($usernameLength === 3) { $mask = mb_substr($username, 0, 1) . $maskChars . mb_substr($username, 2, 1); } else { $mask = mb_substr($username, 0, 2) . $maskChars . mb_substr($username, -2, 2); diff --git a/common/models/Account.php b/common/models/Account.php index a923a63..06d1961 100644 --- a/common/models/Account.php +++ b/common/models/Account.php @@ -44,13 +44,13 @@ use const common\LATEST_RULES_VERSION; */ class Account extends ActiveRecord { - const STATUS_DELETED = -10; - const STATUS_BANNED = -1; - const STATUS_REGISTERED = 0; - const STATUS_ACTIVE = 10; + public const STATUS_DELETED = -10; + public const STATUS_BANNED = -1; + public const STATUS_REGISTERED = 0; + public const STATUS_ACTIVE = 10; - const PASS_HASH_STRATEGY_OLD_ELY = 0; - const PASS_HASH_STRATEGY_YII2 = 1; + public const PASS_HASH_STRATEGY_OLD_ELY = 0; + public const PASS_HASH_STRATEGY_YII2 = 1; public static function tableName(): string { return '{{%accounts}}'; @@ -67,10 +67,9 @@ class Account extends ActiveRecord { $passwordHashStrategy = $this->password_hash_strategy; } - switch($passwordHashStrategy) { + switch ($passwordHashStrategy) { case self::PASS_HASH_STRATEGY_OLD_ELY: - $hashedPass = UserPass::make($this->email, $password); - return $hashedPass === $this->password_hash; + return UserPass::make($this->email, $password) === $this->password_hash; case self::PASS_HASH_STRATEGY_YII2: return Yii::$app->security->validatePassword($password, $this->password_hash); diff --git a/common/models/EmailActivation.php b/common/models/EmailActivation.php index 0b53bf7..b71e4e8 100644 --- a/common/models/EmailActivation.php +++ b/common/models/EmailActivation.php @@ -28,10 +28,10 @@ use yii\helpers\ArrayHelper; */ class EmailActivation extends ActiveRecord { - const TYPE_REGISTRATION_EMAIL_CONFIRMATION = 0; - const TYPE_FORGOT_PASSWORD_KEY = 1; - const TYPE_CURRENT_EMAIL_CONFIRMATION = 2; - const TYPE_NEW_EMAIL_CONFIRMATION = 3; + public const TYPE_REGISTRATION_EMAIL_CONFIRMATION = 0; + public const TYPE_FORGOT_PASSWORD_KEY = 1; + public const TYPE_CURRENT_EMAIL_CONFIRMATION = 2; + public const TYPE_NEW_EMAIL_CONFIRMATION = 3; public static function tableName() { return '{{%email_activations}}'; @@ -79,15 +79,15 @@ class EmailActivation extends ActiveRecord { throw new InvalidConfigException('Unexpected type'); } - return new $classMap[$type]; + return new $classMap[$type](); } public static function getClassMap() { return [ self::TYPE_REGISTRATION_EMAIL_CONFIRMATION => confirmations\RegistrationConfirmation::class, - self::TYPE_FORGOT_PASSWORD_KEY => confirmations\ForgotPassword::class, - self::TYPE_CURRENT_EMAIL_CONFIRMATION => confirmations\CurrentEmailConfirmation::class, - self::TYPE_NEW_EMAIL_CONFIRMATION => confirmations\NewEmailConfirmation::class, + self::TYPE_FORGOT_PASSWORD_KEY => confirmations\ForgotPassword::class, + self::TYPE_CURRENT_EMAIL_CONFIRMATION => confirmations\CurrentEmailConfirmation::class, + self::TYPE_NEW_EMAIL_CONFIRMATION => confirmations\NewEmailConfirmation::class, ]; } diff --git a/common/models/MinecraftAccessKey.php b/common/models/MinecraftAccessKey.php index 57294fa..202570a 100644 --- a/common/models/MinecraftAccessKey.php +++ b/common/models/MinecraftAccessKey.php @@ -29,7 +29,7 @@ use yii\db\ActiveRecord; */ class MinecraftAccessKey extends ActiveRecord { - const LIFETIME = 172800; // Ключ актуален в течение 2 дней + public const LIFETIME = 172800; // Ключ актуален в течение 2 дней public static function tableName(): string { return '{{%minecraft_access_keys}}'; diff --git a/common/models/OauthScopeQuery.php b/common/models/OauthScopeQuery.php index 27577c5..b81730d 100644 --- a/common/models/OauthScopeQuery.php +++ b/common/models/OauthScopeQuery.php @@ -11,6 +11,10 @@ class OauthScopeQuery { private $owner; + public function __construct(array $scopes) { + $this->scopes = $scopes; + } + public function onlyPublic(): self { $this->internal = false; return $this; @@ -43,8 +47,4 @@ class OauthScopeQuery { }), 'value'); } - public function __construct(array $scopes) { - $this->scopes = $scopes; - } - } diff --git a/common/models/Textures.php b/common/models/Textures.php index 85ec58c..6046fff 100644 --- a/common/models/Textures.php +++ b/common/models/Textures.php @@ -21,7 +21,7 @@ class Textures { } public function getMinecraftResponse() { - $response = [ + $response = [ 'name' => $this->account->username, 'id' => str_replace('-', '', $this->account->uuid), 'properties' => [ @@ -54,9 +54,9 @@ class Textures { if (!$encrypted) { return $array; - } else { - return static::encrypt($array); } + + return static::encrypt($array); } public function getTextures(): array { diff --git a/common/models/UsernameHistory.php b/common/models/UsernameHistory.php index 720cc10..bba421b 100644 --- a/common/models/UsernameHistory.php +++ b/common/models/UsernameHistory.php @@ -45,7 +45,7 @@ class UsernameHistory extends ActiveRecord { * @param int $afterTime * @return UsernameHistory|null */ - public function findNext(int $afterTime = null) /*: ?UsernameHistory*/ { + public function findNext(int $afterTime = null): ?UsernameHistory { return self::find() ->andWhere(['account_id' => $this->account_id]) ->andWhere(['>', 'applied_in', $afterTime ?: $this->applied_in]) diff --git a/common/models/confirmations/NewEmailConfirmation.php b/common/models/confirmations/NewEmailConfirmation.php index 91f0fab..a8e4177 100644 --- a/common/models/confirmations/NewEmailConfirmation.php +++ b/common/models/confirmations/NewEmailConfirmation.php @@ -13,7 +13,7 @@ class NewEmailConfirmation extends EmailActivation { public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'expirationBehavior' => [ - 'repeatTimeout' => 5 * 60, + 'repeatTimeout' => 5 * 60, ], 'dataBehavior' => [ 'class' => NewEmailConfirmationBehavior::class, diff --git a/common/models/confirmations/NewEmailConfirmationBehavior.php b/common/models/confirmations/NewEmailConfirmationBehavior.php index ee804a5..169d88c 100644 --- a/common/models/confirmations/NewEmailConfirmationBehavior.php +++ b/common/models/confirmations/NewEmailConfirmationBehavior.php @@ -8,11 +8,11 @@ use common\behaviors\DataBehavior; */ class NewEmailConfirmationBehavior extends DataBehavior { - public function getNewEmail() : string { + public function getNewEmail(): string { return $this->getKey('newEmail'); } - public function setNewEmail(string $newEmail) { + public function setNewEmail(string $newEmail): void { $this->setKey('newEmail', $newEmail); } diff --git a/composer.json b/composer.json index 2f89bdd..0b2d338 100644 --- a/composer.json +++ b/composer.json @@ -38,7 +38,9 @@ "codeception/specify": "^1.0.0", "codeception/verify": "*", "mockery/mockery": "^1.0.0", - "php-mock/php-mock-mockery": "^1.2.0" + "php-mock/php-mock-mockery": "^1.2.0", + "friendsofphp/php-cs-fixer": "^2.11", + "ely/php-code-style": "^0.1.0" }, "repositories": [ { diff --git a/composer.lock b/composer.lock index d3642b6..19ec143 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "content-hash": "b322fafe1486ee057b633a35d336c1a1", + "content-hash": "63497214afa6b50f50d3bc80fe9eb269", "packages": [ { "name": "bacon/bacon-qr-code", @@ -3165,6 +3165,68 @@ "description": "BDD assertion library for PHPUnit", "time": "2017-11-12T01:51:59+00:00" }, + { + "name": "composer/semver", + "version": "1.4.2", + "source": { + "type": "git", + "url": "https://github.com/composer/semver.git", + "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/composer/semver/zipball/c7cb9a2095a074d131b65a8a0cd294479d785573", + "reference": "c7cb9a2095a074d131b65a8a0cd294479d785573", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.5 || ^5.0.5", + "phpunit/phpunit-mock-objects": "2.3.0 || ^3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Composer\\Semver\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http://www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http://robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "time": "2016-08-30T16:08:34+00:00" + }, { "name": "doctrine/instantiator", "version": "1.1.0", @@ -3219,6 +3281,55 @@ ], "time": "2017-07-22T11:58:36+00:00" }, + { + "name": "ely/php-code-style", + "version": "0.1.0", + "source": { + "type": "git", + "url": "https://github.com/elyby/php-code-style.git", + "reference": "0bb3e8082753981af4775f5b95d159c9cd9c6bf4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/elyby/php-code-style/zipball/0bb3e8082753981af4775f5b95d159c9cd9c6bf4", + "reference": "0bb3e8082753981af4775f5b95d159c9cd9c6bf4", + "shasum": "" + }, + "require": { + "friendsofphp/php-cs-fixer": "^2.11", + "php": "^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Ely\\CS\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Ely.by team", + "email": "team@ely.by" + }, + { + "name": "ErickSkrauch", + "email": "erickskrauch@ely.by" + } + ], + "description": "Set of PHP-CS-Fixer rules used in the development of Ely.by PHP projects", + "homepage": "https://github.com/elyby/php-code-style", + "keywords": [ + "Code style", + "php-cs-fixer" + ], + "time": "2018-04-17T18:28:51+00:00" + }, { "name": "facebook/webdriver", "version": "1.5.0", @@ -3315,6 +3426,100 @@ "description": "JSONPath implementation for parsing, searching and flattening arrays", "time": "2016-09-06T17:43:18+00:00" }, + { + "name": "friendsofphp/php-cs-fixer", + "version": "v2.11.1", + "source": { + "type": "git", + "url": "https://github.com/FriendsOfPHP/PHP-CS-Fixer.git", + "reference": "ad94441c17b8ef096e517acccdbf3238af8a2da8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/FriendsOfPHP/PHP-CS-Fixer/zipball/ad94441c17b8ef096e517acccdbf3238af8a2da8", + "reference": "ad94441c17b8ef096e517acccdbf3238af8a2da8", + "shasum": "" + }, + "require": { + "composer/semver": "^1.4", + "doctrine/annotations": "^1.2", + "ext-json": "*", + "ext-tokenizer": "*", + "php": "^5.6 || >=7.0 <7.3", + "php-cs-fixer/diff": "^1.3", + "symfony/console": "^3.2 || ^4.0", + "symfony/event-dispatcher": "^3.0 || ^4.0", + "symfony/filesystem": "^3.0 || ^4.0", + "symfony/finder": "^3.0 || ^4.0", + "symfony/options-resolver": "^3.0 || ^4.0", + "symfony/polyfill-php70": "^1.0", + "symfony/polyfill-php72": "^1.4", + "symfony/process": "^3.0 || ^4.0", + "symfony/stopwatch": "^3.0 || ^4.0" + }, + "conflict": { + "hhvm": "*" + }, + "require-dev": { + "johnkary/phpunit-speedtrap": "^1.1 || ^2.0 || ^3.0", + "justinrainbow/json-schema": "^5.0", + "keradus/cli-executor": "^1.0", + "mikey179/vfsstream": "^1.6", + "php-coveralls/php-coveralls": "^2.0", + "php-cs-fixer/accessible-object": "^1.0", + "phpunit/phpunit": "^5.7.23 || ^6.4.3 || ^7.0", + "phpunitgoodpractices/traits": "^1.3.1", + "symfony/phpunit-bridge": "^3.2.2 || ^4.0" + }, + "suggest": { + "ext-mbstring": "For handling non-UTF8 characters in cache signature.", + "symfony/polyfill-mbstring": "When enabling `ext-mbstring` is not possible." + }, + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "extra": { + "branch-alias": { + "dev-master": "2.11-dev" + } + }, + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src/" + }, + "classmap": [ + "tests/Test/AbstractFixerTestCase.php", + "tests/Test/AbstractIntegrationCaseFactory.php", + "tests/Test/AbstractIntegrationTestCase.php", + "tests/Test/Assert/AssertTokensTrait.php", + "tests/Test/Constraint/SameStringsConstraint.php", + "tests/Test/Constraint/SameStringsConstraintForV5.php", + "tests/Test/Constraint/SameStringsConstraintForV7.php", + "tests/Test/IntegrationCase.php", + "tests/Test/IntegrationCaseFactory.php", + "tests/Test/IntegrationCaseFactoryInterface.php", + "tests/Test/InternalIntegrationCaseFactory.php", + "tests/TestCase.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Dariusz Rumiński", + "email": "dariusz.ruminski@gmail.com" + }, + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "time": "2018-03-21T17:41:26+00:00" + }, { "name": "fzaninotto/faker", "version": "v1.7.1", @@ -3625,6 +3830,57 @@ "description": "Library for handling version information and constraints", "time": "2017-03-05T17:38:23+00:00" }, + { + "name": "php-cs-fixer/diff", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/PHP-CS-Fixer/diff.git", + "reference": "78bb099e9c16361126c86ce82ec4405ebab8e756" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHP-CS-Fixer/diff/zipball/78bb099e9c16361126c86ce82ec4405ebab8e756", + "reference": "78bb099e9c16361126c86ce82ec4405ebab8e756", + "shasum": "" + }, + "require": { + "php": "^5.6 || ^7.0" + }, + "require-dev": { + "phpunit/phpunit": "^5.7.23 || ^6.4.3", + "symfony/process": "^3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "SpacePossum" + } + ], + "description": "sebastian/diff v2 backport support for PHP5.6", + "homepage": "https://github.com/PHP-CS-Fixer", + "keywords": [ + "diff" + ], + "time": "2018-02-15T16:58:55+00:00" + }, { "name": "php-mock/php-mock", "version": "1.0.1", @@ -5257,6 +5513,55 @@ "homepage": "https://symfony.com", "time": "2018-01-03T07:38:00+00:00" }, + { + "name": "symfony/filesystem", + "version": "v4.0.8", + "source": { + "type": "git", + "url": "https://github.com/symfony/filesystem.git", + "reference": "5d2d655b2c72fc4d9bf7e9bf14f72a447b940f21" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/5d2d655b2c72fc4d9bf7e9bf14f72a447b940f21", + "reference": "5d2d655b2c72fc4d9bf7e9bf14f72a447b940f21", + "shasum": "" + }, + "require": { + "php": "^7.1.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Filesystem Component", + "homepage": "https://symfony.com", + "time": "2018-02-22T10:50:29+00:00" + }, { "name": "symfony/finder", "version": "v4.0.4", @@ -5306,6 +5611,164 @@ "homepage": "https://symfony.com", "time": "2018-01-03T07:38:00+00:00" }, + { + "name": "symfony/options-resolver", + "version": "v4.0.8", + "source": { + "type": "git", + "url": "https://github.com/symfony/options-resolver.git", + "reference": "371532a2cfe932f7a3766dd4c45364566def1dd0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/371532a2cfe932f7a3766dd4c45364566def1dd0", + "reference": "371532a2cfe932f7a3766dd4c45364566def1dd0", + "shasum": "" + }, + "require": { + "php": "^7.1.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony OptionsResolver Component", + "homepage": "https://symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "time": "2018-01-18T22:19:33+00:00" + }, + { + "name": "symfony/polyfill-php72", + "version": "v1.7.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php72.git", + "reference": "8eca20c8a369e069d4f4c2ac9895144112867422" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/8eca20c8a369e069d4f4c2ac9895144112867422", + "reference": "8eca20c8a369e069d4f4c2ac9895144112867422", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.7-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php72\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "time": "2018-01-31T17:43:24+00:00" + }, + { + "name": "symfony/stopwatch", + "version": "v4.0.8", + "source": { + "type": "git", + "url": "https://github.com/symfony/stopwatch.git", + "reference": "6795ffa2f8eebedac77f045aa62c0c10b2763042" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/6795ffa2f8eebedac77f045aa62c0c10b2763042", + "reference": "6795ffa2f8eebedac77f045aa62c0c10b2763042", + "shasum": "" + }, + "require": { + "php": "^7.1.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "4.0-dev" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Component\\Stopwatch\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Stopwatch Component", + "homepage": "https://symfony.com", + "time": "2018-02-19T16:50:22+00:00" + }, { "name": "symfony/yaml", "version": "v4.0.4", diff --git a/console/controllers/AmqpController.php b/console/controllers/AmqpController.php index e06c765..1c6360c 100644 --- a/console/controllers/AmqpController.php +++ b/console/controllers/AmqpController.php @@ -17,7 +17,7 @@ abstract class AmqpController extends Controller { private $reconnected = false; - public final function actionIndex() { + final public function actionIndex() { $this->start(); } diff --git a/console/controllers/CleanupController.php b/console/controllers/CleanupController.php index fc72371..ef1bff0 100644 --- a/console/controllers/CleanupController.php +++ b/console/controllers/CleanupController.php @@ -85,7 +85,7 @@ class CleanupController extends Controller { $durationsMap = []; foreach (EmailActivation::getClassMap() as $typeId => $className) { /** @var EmailActivation $object */ - $object = new $className; + $object = new $className(); /** @var \common\behaviors\EmailActivationExpirationBehavior $behavior */ $behavior = $object->getBehavior('expirationBehavior'); /** @noinspection NullPointerExceptionInspection */ diff --git a/console/controllers/RbacController.php b/console/controllers/RbacController.php index 0c615da..66f9a7c 100644 --- a/console/controllers/RbacController.php +++ b/console/controllers/RbacController.php @@ -95,7 +95,7 @@ class RbacController extends Controller { $authManager = $this->getAuthManager(); $permission = $authManager->createPermission($name); if ($ruleClassName !== null) { - $rule = new $ruleClassName; + $rule = new $ruleClassName(); if (!$rule instanceof Rule) { throw new InvalidArgumentException('ruleClassName must be rule class name'); } diff --git a/console/db/Migration.php b/console/db/Migration.php index 9633643..e05b6aa 100644 --- a/console/db/Migration.php +++ b/console/db/Migration.php @@ -43,7 +43,7 @@ class Migration extends YiiMigration { private function buildKey(array $columns) { $key = ''; foreach ($columns as $i => $column) { - $key .= $i == count($columns) ? $column : "$column,"; + $key .= $i === count($columns) ? $column : "$column,"; } return $key; diff --git a/console/migrations/m160201_055928_oauth.php b/console/migrations/m160201_055928_oauth.php index bfc71c7..9347b3c 100644 --- a/console/migrations/m160201_055928_oauth.php +++ b/console/migrations/m160201_055928_oauth.php @@ -6,14 +6,14 @@ class m160201_055928_oauth extends Migration { public function safeUp() { $this->createTable('{{%oauth_clients}}', [ - 'id' => $this->string(64), - 'secret' => $this->string()->notNull(), - 'name' => $this->string()->notNull(), - 'description' => $this->string(), + 'id' => $this->string(64), + 'secret' => $this->string()->notNull(), + 'name' => $this->string()->notNull(), + 'description' => $this->string(), 'redirect_uri' => $this->string()->notNull(), - 'account_id' => $this->getDb()->getTableSchema('{{%accounts}}')->getColumn('id')->dbType, - 'is_trusted' => $this->boolean()->defaultValue(false)->notNull(), - 'created_at' => $this->integer()->notNull(), + 'account_id' => $this->getDb()->getTableSchema('{{%accounts}}')->getColumn('id')->dbType, + 'is_trusted' => $this->boolean()->defaultValue(false)->notNull(), + 'created_at' => $this->integer()->notNull(), $this->primary('id'), ], $this->tableOptions); @@ -23,17 +23,17 @@ class m160201_055928_oauth extends Migration { ], $this->tableOptions); $this->createTable('{{%oauth_sessions}}', [ - 'id' => $this->primaryKey(), - 'owner_type' => $this->string()->notNull(), - 'owner_id' => $this->string()->notNull(), - 'client_id' => $this->getDb()->getTableSchema('{{%oauth_clients}}')->getColumn('id')->dbType, + 'id' => $this->primaryKey(), + 'owner_type' => $this->string()->notNull(), + 'owner_id' => $this->string()->notNull(), + 'client_id' => $this->getDb()->getTableSchema('{{%oauth_clients}}')->getColumn('id')->dbType, 'client_redirect_uri' => $this->string(), ], $this->tableOptions); $this->createTable('{{%oauth_access_tokens}}', [ 'access_token' => $this->string(64), - 'session_id' => $this->getDb()->getTableSchema('{{%oauth_sessions}}')->getColumn('id')->dbType, - 'expire_time' => $this->integer()->notNull(), + 'session_id' => $this->getDb()->getTableSchema('{{%oauth_sessions}}')->getColumn('id')->dbType, + 'expire_time' => $this->integer()->notNull(), $this->primary('access_token'), ], $this->tableOptions); diff --git a/console/migrations/m160414_231110_account_nicknames_history.php b/console/migrations/m160414_231110_account_nicknames_history.php index 944ba3b..1598535 100644 --- a/console/migrations/m160414_231110_account_nicknames_history.php +++ b/console/migrations/m160414_231110_account_nicknames_history.php @@ -21,7 +21,7 @@ class m160414_231110_account_nicknames_history extends Migration { FROM {{%accounts}} ')->queryAll(); - foreach($accountNicknames as $row) { + foreach ($accountNicknames as $row) { $this->insert('{{%usernames_history}}', [ 'username' => $row['username'], 'account_id' => $row['id'], diff --git a/console/migrations/m160819_211139_minecraft_access_tokens.php b/console/migrations/m160819_211139_minecraft_access_tokens.php index 8756c47..95ceaf8 100644 --- a/console/migrations/m160819_211139_minecraft_access_tokens.php +++ b/console/migrations/m160819_211139_minecraft_access_tokens.php @@ -8,9 +8,9 @@ class m160819_211139_minecraft_access_tokens extends Migration { $this->createTable('{{%minecraft_access_keys}}', [ 'access_token' => $this->string(36)->notNull(), 'client_token' => $this->string(36)->notNull(), - 'account_id' => $this->db->getTableSchema('{{%accounts}}')->getColumn('id')->dbType . ' NOT NULL', - 'created_at' => $this->integer()->unsigned()->notNull(), - 'updated_at' => $this->integer()->unsigned()->notNull(), + 'account_id' => $this->db->getTableSchema('{{%accounts}}')->getColumn('id')->dbType . ' NOT NULL', + 'created_at' => $this->integer()->unsigned()->notNull(), + 'updated_at' => $this->integer()->unsigned()->notNull(), ]); $this->addPrimaryKey('access_token', '{{%minecraft_access_keys}}', 'access_token'); diff --git a/console/migrations/m161030_013122_ely_by_admin_app.php b/console/migrations/m161030_013122_ely_by_admin_app.php index 49fa91b..628e447 100644 --- a/console/migrations/m161030_013122_ely_by_admin_app.php +++ b/console/migrations/m161030_013122_ely_by_admin_app.php @@ -4,8 +4,6 @@ use console\db\Migration; class m161030_013122_ely_by_admin_app extends Migration { - const APP_NAME = 'ely_admin'; - public function safeUp() { $exists = $this->db->createCommand(' SELECT COUNT(*) @@ -13,12 +11,12 @@ class m161030_013122_ely_by_admin_app extends Migration { WHERE id = :app_name LIMIT 1 ', [ - 'app_name' => self::APP_NAME, + 'app_name' => 'ely_admin', ])->queryScalar(); if (!$exists) { $this->insert('{{%oauth_clients}}', [ - 'id' => self::APP_NAME, + 'id' => 'ely_admin', 'secret' => 'change_this_on_production', 'name' => 'Admin Ely.by', 'description' => '', @@ -30,7 +28,7 @@ class m161030_013122_ely_by_admin_app extends Migration { } public function safeDown() { - $this->delete('{{%oauth_clients}}', ['id' => self::APP_NAME]); + $this->delete('{{%oauth_clients}}', ['id' => 'ely_admin']); } } diff --git a/console/migrations/m161222_222520_remove_oauth_access_tokens.php b/console/migrations/m161222_222520_remove_oauth_access_tokens.php index ebc228d..945f659 100644 --- a/console/migrations/m161222_222520_remove_oauth_access_tokens.php +++ b/console/migrations/m161222_222520_remove_oauth_access_tokens.php @@ -12,8 +12,8 @@ class m161222_222520_remove_oauth_access_tokens extends Migration { public function safeDown() { $this->createTable('{{%oauth_access_tokens}}', [ 'access_token' => $this->string(64), - 'session_id' => $this->getDb()->getTableSchema('{{%oauth_sessions}}')->getColumn('id')->dbType, - 'expire_time' => $this->integer()->notNull(), + 'session_id' => $this->getDb()->getTableSchema('{{%oauth_sessions}}')->getColumn('id')->dbType, + 'expire_time' => $this->integer()->notNull(), $this->primary('access_token'), ], $this->tableOptions); diff --git a/tests/codeception/api/_bootstrap.php b/tests/codeception/api/_bootstrap.php index fe5358e..3bd1f3c 100644 --- a/tests/codeception/api/_bootstrap.php +++ b/tests/codeception/api/_bootstrap.php @@ -17,7 +17,7 @@ require_once __DIR__ . '/../../../api/config/bootstrap.php'; // the entry script file path for functional tests $_SERVER['SCRIPT_FILENAME'] = API_ENTRY_FILE; $_SERVER['SCRIPT_NAME'] = API_ENTRY_URL; -$_SERVER['SERVER_NAME'] = parse_url(Configuration::config()['config']['test_entry_url'], PHP_URL_HOST); -$_SERVER['SERVER_PORT'] = parse_url(Configuration::config()['config']['test_entry_url'], PHP_URL_PORT) ?: '80'; +$_SERVER['SERVER_NAME'] = parse_url(Configuration::config()['config']['test_entry_url'], PHP_URL_HOST); +$_SERVER['SERVER_PORT'] = parse_url(Configuration::config()['config']['test_entry_url'], PHP_URL_PORT) ?: '80'; Yii::setAlias('@tests', dirname(__DIR__, 2)); diff --git a/tests/codeception/api/_support/UnitTester.php b/tests/codeception/api/_support/UnitTester.php index 1919072..33d0a54 100644 --- a/tests/codeception/api/_support/UnitTester.php +++ b/tests/codeception/api/_support/UnitTester.php @@ -16,11 +16,11 @@ namespace tests\codeception\api; * * @SuppressWarnings(PHPMD) */ -class UnitTester extends \Codeception\Actor -{ +class UnitTester extends \Codeception\Actor { use _generated\UnitTesterActions; - /** - * Define custom actions here - */ + /** + * Define custom actions here + */ + } diff --git a/tests/codeception/api/functional/_steps/SessionServerSteps.php b/tests/codeception/api/functional/_steps/SessionServerSteps.php index a976752..8c97085 100644 --- a/tests/codeception/api/functional/_steps/SessionServerSteps.php +++ b/tests/codeception/api/functional/_steps/SessionServerSteps.php @@ -35,7 +35,7 @@ class SessionServerSteps extends FunctionalTester { return [$username, $serverId]; } - + public function canSeeValidTexturesResponse($expectedUsername, $expectedUuid) { $this->seeResponseIsJson(); $this->canSeeResponseContainsJson([ diff --git a/tests/codeception/api/functional/authserver/AuthorizationCest.php b/tests/codeception/api/functional/authserver/AuthorizationCest.php index 2b17c1e..8dd03c7 100644 --- a/tests/codeception/api/functional/authserver/AuthorizationCest.php +++ b/tests/codeception/api/functional/authserver/AuthorizationCest.php @@ -1,8 +1,8 @@ wantTo('get specific response when pass too many usernames'); $usernames = []; - for($i = 0; $i < 150; $i++) { + for ($i = 0; $i < 150; $i++) { $usernames[] = random_bytes(10); } + $this->route->uuidsByUsernames($usernames); $I->canSeeResponseCodeIs(400); $I->canSeeResponseIsJson(); diff --git a/tests/codeception/api/unit/TestCase.php b/tests/codeception/api/unit/TestCase.php index 91b79ad..f62c5b8 100644 --- a/tests/codeception/api/unit/TestCase.php +++ b/tests/codeception/api/unit/TestCase.php @@ -3,13 +3,18 @@ namespace tests\codeception\api\unit; use Mockery; -class TestCase extends \Codeception\Test\Unit { +class TestCase extends \Codeception\Test\Unit { /** * @var \tests\codeception\api\UnitTester */ protected $tester; + protected function tearDown() { + parent::tearDown(); + Mockery::close(); + } + /** * Список фикстур, что будут загружены перед тестом, но после зачистки базы данных * @@ -21,9 +26,4 @@ class TestCase extends \Codeception\Test\Unit { return []; } - protected function tearDown() { - parent::tearDown(); - Mockery::close(); - } - } diff --git a/tests/codeception/api/unit/components/User/ComponentTest.php b/tests/codeception/api/unit/components/User/ComponentTest.php index 65cd5f9..00f117b 100644 --- a/tests/codeception/api/unit/components/User/ComponentTest.php +++ b/tests/codeception/api/unit/components/User/ComponentTest.php @@ -1,9 +1,9 @@ specify('error.login_not_exist if login not exists', function () { + $this->specify('error.login_not_exist if login not exists', function() { $model = $this->createModel([ 'login' => 'mr-test', 'account' => null, @@ -41,7 +41,7 @@ class LoginFormTest extends TestCase { $this->assertEquals(['error.login_not_exist'], $model->getErrors('login')); }); - $this->specify('no errors if login exists', function () { + $this->specify('no errors if login exists', function() { $model = $this->createModel([ 'login' => 'mr-test', 'account' => new Account(), @@ -52,7 +52,7 @@ class LoginFormTest extends TestCase { } public function testValidatePassword() { - $this->specify('error.password_incorrect if password invalid', function () { + $this->specify('error.password_incorrect if password invalid', function() { $model = $this->createModel([ 'password' => '87654321', 'account' => new Account(['password' => '12345678']), @@ -61,7 +61,7 @@ class LoginFormTest extends TestCase { $this->assertEquals(['error.password_incorrect'], $model->getErrors('password')); }); - $this->specify('no errors if password valid', function () { + $this->specify('no errors if password valid', function() { $model = $this->createModel([ 'password' => '12345678', 'account' => new Account(['password' => '12345678']), @@ -100,7 +100,7 @@ class LoginFormTest extends TestCase { } public function testValidateActivity() { - $this->specify('error.account_not_activated if account in not activated state', function () { + $this->specify('error.account_not_activated if account in not activated state', function() { $model = $this->createModel([ 'account' => new Account(['status' => Account::STATUS_REGISTERED]), ]); @@ -108,7 +108,7 @@ class LoginFormTest extends TestCase { $this->assertEquals(['error.account_not_activated'], $model->getErrors('login')); }); - $this->specify('error.account_banned if account has banned status', function () { + $this->specify('error.account_banned if account has banned status', function() { $model = $this->createModel([ 'account' => new Account(['status' => Account::STATUS_BANNED]), ]); @@ -116,7 +116,7 @@ class LoginFormTest extends TestCase { $this->assertEquals(['error.account_banned'], $model->getErrors('login')); }); - $this->specify('no errors if account active', function () { + $this->specify('no errors if account active', function() { $model = $this->createModel([ 'account' => new Account(['status' => Account::STATUS_ACTIVE]), ]); diff --git a/tests/codeception/api/unit/models/authentication/LogoutFormTest.php b/tests/codeception/api/unit/models/authentication/LogoutFormTest.php index 861a666..7f63533 100644 --- a/tests/codeception/api/unit/models/authentication/LogoutFormTest.php +++ b/tests/codeception/api/unit/models/authentication/LogoutFormTest.php @@ -13,7 +13,7 @@ class LogoutFormTest extends TestCase { use Specify; public function testValidateLogout() { - $this->specify('No actions if active session is not exists', function () { + $this->specify('No actions if active session is not exists', function() { $userComp = $this ->getMockBuilder(Component::class) ->setConstructorArgs([$this->getComponentArgs()]) @@ -30,7 +30,7 @@ class LogoutFormTest extends TestCase { expect($model->logout())->true(); }); - $this->specify('if active session is presented, then delete should be called', function () { + $this->specify('if active session is presented, then delete should be called', function() { $session = $this ->getMockBuilder(AccountSession::class) ->setMethods(['delete']) diff --git a/tests/codeception/api/unit/modules/internal/models/BanFormTest.php b/tests/codeception/api/unit/modules/internal/models/BanFormTest.php index a9fe788..4cd3c02 100644 --- a/tests/codeception/api/unit/modules/internal/models/BanFormTest.php +++ b/tests/codeception/api/unit/modules/internal/models/BanFormTest.php @@ -1,8 +1,8 @@ shouldReceive('isClientExists')->andReturn(false); $request = new class implements OauthClientTypeForm { - public function load($data): bool { return true; } @@ -72,7 +71,6 @@ class OauthClientFormTest extends TestCase { $client->name = 'New name'; $client->description = 'New description.'; } - }; $this->assertTrue($form->save($request)); diff --git a/tests/codeception/api/unit/modules/session/filters/RateLimiterTest.php b/tests/codeception/api/unit/modules/session/filters/RateLimiterTest.php index a0c3710..81fc370 100644 --- a/tests/codeception/api/unit/modules/session/filters/RateLimiterTest.php +++ b/tests/codeception/api/unit/modules/session/filters/RateLimiterTest.php @@ -25,7 +25,7 @@ class RateLimiterTest extends TestCase { /** @var RateLimiter|\PHPUnit_Framework_MockObject_MockObject $filter */ $filter = $this->getMockBuilder(RateLimiter::class) ->setConstructorArgs([[ - 'authserverDomain' => Yii::$app->params['authserverHost'] + 'authserverDomain' => Yii::$app->params['authserverHost'], ]]) ->setMethods(['getServer']) ->getMock(); @@ -58,7 +58,7 @@ class RateLimiterTest extends TestCase { ->will($this->returnValue('http://authserver.ely.by')); $filter = new RateLimiter([ - 'authserverDomain' => Yii::$app->params['authserverHost'] + 'authserverDomain' => Yii::$app->params['authserverHost'], ]); $filter->checkRateLimit(null, $request, null, null); } diff --git a/tests/codeception/api/unit/validators/PasswordRequiredValidatorTest.php b/tests/codeception/api/unit/validators/PasswordRequiredValidatorTest.php index e6fdc38..b2b5aa5 100644 --- a/tests/codeception/api/unit/validators/PasswordRequiredValidatorTest.php +++ b/tests/codeception/api/unit/validators/PasswordRequiredValidatorTest.php @@ -2,11 +2,11 @@ namespace codeception\api\unit\validators; use api\validators\PasswordRequiredValidator; +use common\helpers\Error as E; use common\models\Account; use common\rbac\Permissions as P; use tests\codeception\api\unit\TestCase; use tests\codeception\common\_support\ProtectedCaller; -use common\helpers\Error as E; use yii\web\User; class PasswordRequiredValidatorTest extends TestCase { diff --git a/tests/codeception/common/_support/ProtectedCaller.php b/tests/codeception/common/_support/ProtectedCaller.php index e62b56b..ca28cf9 100644 --- a/tests/codeception/common/_support/ProtectedCaller.php +++ b/tests/codeception/common/_support/ProtectedCaller.php @@ -1,7 +1,6 @@ getYii2()->grabComponent($component); } - private function getYii2() : Yii2 { + private function getYii2(): Yii2 { $yii2 = $this->getModule('Yii2'); if (!$yii2 instanceof Yii2) { throw new ModuleException($this, 'Yii2 module must be configured'); diff --git a/tests/codeception/common/_support/amqp/TestComponent.php b/tests/codeception/common/_support/amqp/TestComponent.php index f305e7d..ed90730 100644 --- a/tests/codeception/common/_support/amqp/TestComponent.php +++ b/tests/codeception/common/_support/amqp/TestComponent.php @@ -40,13 +40,13 @@ class TestComponent extends Component { * @param string|null $exchangeName * @return \PhpAmqpLib\Message\AMQPMessage[] */ - public function getSentMessages(string $exchangeName = null) : array { + public function getSentMessages(string $exchangeName = null): array { if ($exchangeName !== null) { return $this->sentMessages[$exchangeName] ?? []; } $messages = []; - foreach($this->sentMessages as $exchangeGroup) { + foreach ($this->sentMessages as $exchangeGroup) { foreach ($exchangeGroup as $message) { $messages[] = $message; } diff --git a/tests/codeception/common/_support/queue/Queue.php b/tests/codeception/common/_support/queue/Queue.php index 169da26..e6b57d6 100644 --- a/tests/codeception/common/_support/queue/Queue.php +++ b/tests/codeception/common/_support/queue/Queue.php @@ -8,6 +8,11 @@ class Queue extends BaseQueue { private $messages = []; + public function __set($name, $value) { + // Yii2 components may contains some configuration + // But we just ignore it for this mock component + } + public function push($job) { $this->messages[] = $job; } @@ -24,9 +29,4 @@ class Queue extends BaseQueue { // This function is abstract, but will be not called } - public function __set($name, $value) { - // Yii2 components may contains some configuration - // But we just ignore it for this mock component - } - } diff --git a/tests/codeception/common/unit/TestCase.php b/tests/codeception/common/unit/TestCase.php index b3c1f9b..2a72963 100644 --- a/tests/codeception/common/unit/TestCase.php +++ b/tests/codeception/common/unit/TestCase.php @@ -3,13 +3,18 @@ namespace tests\codeception\common\unit; use Mockery; -class TestCase extends \Codeception\Test\Unit { +class TestCase extends \Codeception\Test\Unit { /** * @var \tests\codeception\common\UnitTester */ protected $tester; + protected function tearDown() { + parent::tearDown(); + Mockery::close(); + } + /** * Список фикстур, что будут загружены перед тестом, но после зачистки базы данных * @@ -21,9 +26,4 @@ class TestCase extends \Codeception\Test\Unit { return []; } - protected function tearDown() { - parent::tearDown(); - Mockery::close(); - } - } diff --git a/tests/codeception/common/unit/behaviors/PrimaryKeyValueBehaviorTest.php b/tests/codeception/common/unit/behaviors/PrimaryKeyValueBehaviorTest.php index a7b9cc1..4ec7406 100644 --- a/tests/codeception/common/unit/behaviors/PrimaryKeyValueBehaviorTest.php +++ b/tests/codeception/common/unit/behaviors/PrimaryKeyValueBehaviorTest.php @@ -14,17 +14,17 @@ class PrimaryKeyValueBehaviorTest extends TestCase { $model = new DummyModel(); /** @var PrimaryKeyValueBehavior|\PHPUnit_Framework_MockObject_MockObject $behavior */ $behavior = $this->getMockBuilder(PrimaryKeyValueBehavior::class) - ->setMethods(['isValueExists']) - ->setConstructorArgs([[ - 'value' => function() { - return 'mock'; - }, - ]]) - ->getMock(); + ->setMethods(['isValueExists']) + ->setConstructorArgs([[ + 'value' => function() { + return 'mock'; + }, + ]]) + ->getMock(); $behavior->expects($this->once()) - ->method('isValueExists') - ->will($this->returnValue(false)); + ->method('isValueExists') + ->will($this->returnValue(false)); $model->attachBehavior('primary-key-value-behavior', $behavior); $behavior->setPrimaryKeyValue(); @@ -44,12 +44,12 @@ class PrimaryKeyValueBehaviorTest extends TestCase { ->getMock(); $behavior->expects($this->exactly(3)) - ->method('generateValue') - ->will($this->onConsecutiveCalls('1', '2', '3')); + ->method('generateValue') + ->will($this->onConsecutiveCalls('1', '2', '3')); $behavior->expects($this->exactly(3)) - ->method('isValueExists') - ->will($this->onConsecutiveCalls(true, true, false)); + ->method('isValueExists') + ->will($this->onConsecutiveCalls(true, true, false)); $model->attachBehavior('primary-key-value-behavior', $behavior); $behavior->setPrimaryKeyValue(); diff --git a/tests/codeception/common/unit/validators/EmailValidatorTest.php b/tests/codeception/common/unit/validators/EmailValidatorTest.php index 614085a..caa24ce 100644 --- a/tests/codeception/common/unit/validators/EmailValidatorTest.php +++ b/tests/codeception/common/unit/validators/EmailValidatorTest.php @@ -115,7 +115,7 @@ class EmailValidatorTest extends TestCase { * @param string $fieldValue * @return Model */ - private function createModel(string $fieldValue) : Model { + private function createModel(string $fieldValue): Model { $class = new class extends Model { public $field; }; diff --git a/tests/codeception/common/unit/validators/UsernameValidatorTest.php b/tests/codeception/common/unit/validators/UsernameValidatorTest.php index 58154a5..b8bae8d 100644 --- a/tests/codeception/common/unit/validators/UsernameValidatorTest.php +++ b/tests/codeception/common/unit/validators/UsernameValidatorTest.php @@ -50,21 +50,22 @@ class UsernameValidatorTest extends TestCase { $this->assertNotEquals(['error.username_too_long'], $model->getErrors('field')); } + // TODO: rewrite this test with @provider usage public function testValidateAttributePattern() { $shouldBeValid = [ 'русский_ник', 'русский_ник_на_грани!', 'numbers1132', '*__*-Stars-*__*', '1-_.!$%^&*()[]', '[ESP]Эрик', 'Свят_помидор;', 'зроблена_ў_беларусі:)', ]; - foreach($shouldBeValid as $nickname) { + foreach ($shouldBeValid as $nickname) { $model = $this->createModel($nickname); $this->validator->validateAttribute($model, 'field'); $this->assertNotEquals(['error.username_invalid'], $model->getErrors('field')); } $shouldBeInvalid = [ - 'nick@name', 'spaced nick', 'im#hashed', 'quest?ion' + 'nick@name', 'spaced nick', 'im#hashed', 'quest?ion', ]; - foreach($shouldBeInvalid as $nickname) { + foreach ($shouldBeInvalid as $nickname) { $model = $this->createModel($nickname); $this->validator->validateAttribute($model, 'field'); $this->assertEquals(['error.username_invalid'], $model->getErrors('field')); @@ -100,7 +101,7 @@ class UsernameValidatorTest extends TestCase { * @param string $fieldValue * @return Model */ - private function createModel(string $fieldValue) : Model { + private function createModel(string $fieldValue): Model { $class = new class extends Model { public $field; }; diff --git a/tests/codeception/console/_support/UnitTester.php b/tests/codeception/console/_support/UnitTester.php index 3cf7a9c..a906302 100644 --- a/tests/codeception/console/_support/UnitTester.php +++ b/tests/codeception/console/_support/UnitTester.php @@ -16,11 +16,11 @@ namespace tests\codeception\console; * * @SuppressWarnings(PHPMD) */ -class UnitTester extends \Codeception\Actor -{ +class UnitTester extends \Codeception\Actor { use _generated\UnitTesterActions; - /** - * Define custom actions here - */ + /** + * Define custom actions here + */ + } diff --git a/tests/codeception/console/unit/TestCase.php b/tests/codeception/console/unit/TestCase.php index 650812b..d1d8a15 100644 --- a/tests/codeception/console/unit/TestCase.php +++ b/tests/codeception/console/unit/TestCase.php @@ -11,6 +11,11 @@ class TestCase extends Unit { */ protected $tester; + protected function tearDown() { + parent::tearDown(); + Mockery::close(); + } + /** * Список фикстур, что будут загружены перед тестом, но после зачистки базы данных * @@ -22,9 +27,4 @@ class TestCase extends Unit { return []; } - protected function tearDown() { - parent::tearDown(); - Mockery::close(); - } - } diff --git a/tests/codeception/console/unit/controllers/AccountQueueControllerTest.php b/tests/codeception/console/unit/controllers/AccountQueueControllerTest.php index 4c9e236..0fbe3fe 100644 --- a/tests/codeception/console/unit/controllers/AccountQueueControllerTest.php +++ b/tests/codeception/console/unit/controllers/AccountQueueControllerTest.php @@ -49,9 +49,9 @@ class AccountQueueControllerTest extends TestCase { ->willReturnCallback(function() { if ($this->expectedResponse === false) { throw new NoContentException(); - } else { - return $this->expectedResponse; } + + return $this->expectedResponse; }); $controller diff --git a/yii b/yii index 36011f7..20610d6 100755 --- a/yii +++ b/yii @@ -1,13 +1,13 @@ #!/usr/bin/env php Date: Wed, 18 Apr 2018 02:48:27 +0300 Subject: [PATCH 2/2] Simplify the call of the php-cs-fixer --- .gitlab-ci.yml | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index d24b075..bc8b26b 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -24,19 +24,14 @@ test:backend: script: - export TEMP_DEV_IMAGE="${CONTAINER_IMAGE}:ci-${CI_BUILD_ID}" - docker build --pull -f Dockerfile-dev -t $TEMP_DEV_IMAGE . - # https://github.com/FriendsOfPHP/PHP-CS-Fixer#using-php-cs-fixer-on-ci - - COMMIT_RANGE="${CI_COMMIT_BEFORE_SHA}...${CI_COMMIT_SHA}" - - CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "${COMMIT_RANGE}") - - | - if ! echo "${CHANGED_FILES}" | grep -qE "^(\\.php_cs(\\.dist)?|composer\\.lock)$"; then - EXTRA_ARGS=$(printf -- '--path-mode=intersection\n--\n%s' "${CHANGED_FILES}") - else - EXTRA_ARGS='' - fi - > docker run --rm $TEMP_DEV_IMAGE - vendor/bin/php-cs-fixer fix -v --dry-run --stop-on-violation --using-cache=no ${EXTRA_ARGS} + bash -c " + rm /usr/local/etc/php/conf.d/xdebug.ini && + cp -r /var/www/vendor /var/www/html/vendor && + vendor/bin/php-cs-fixer fix -v --dry-run + " - > docker run --rm --add-host=mariadb:`getent hosts mariadb | awk '{ print $1 ; exit }'`