Merge branch 'php-cs' into develop

This commit is contained in:
ErickSkrauch 2018-04-18 03:14:26 +03:00
commit 7d881682e5
115 changed files with 878 additions and 363 deletions

4
.gitignore vendored
View File

@ -19,3 +19,7 @@ npm-debug*
# id_rsa # id_rsa
/id_rsa /id_rsa
# PHP-CS-Fixer
.php_cs
.php_cs.cache

View File

@ -24,6 +24,14 @@ test:backend:
script: script:
- export TEMP_DEV_IMAGE="${CONTAINER_IMAGE}:ci-${CI_BUILD_ID}" - export TEMP_DEV_IMAGE="${CONTAINER_IMAGE}:ci-${CI_BUILD_ID}"
- docker build --pull -f Dockerfile-dev -t $TEMP_DEV_IMAGE . - docker build --pull -f Dockerfile-dev -t $TEMP_DEV_IMAGE .
- >
docker run --rm
$TEMP_DEV_IMAGE
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 docker run --rm
--add-host=mariadb:`getent hosts mariadb | awk '{ print $1 ; exit }'` --add-host=mariadb:`getent hosts mariadb | awk '{ print $1 ; exit }'`

16
.php_cs.dist Normal file
View File

@ -0,0 +1,16 @@
<?php
$finder = \PhpCsFixer\Finder::create()
->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);

View File

@ -1,7 +1,6 @@
<?php <?php
namespace api\aop; namespace api\aop;
use api\aop\aspects;
use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\AnnotationReader;
use Go\Core\AspectContainer; use Go\Core\AspectContainer;
use Go\Core\AspectKernel as BaseAspectKernel; use Go\Core\AspectKernel as BaseAspectKernel;

View File

@ -1,7 +1,6 @@
<?php <?php
namespace api\components\OAuth2; namespace api\components\OAuth2;
use api\components\OAuth2\Storage;
use League\OAuth2\Server\AuthorizationServer; use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Storage\AccessTokenInterface; use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\RefreshTokenInterface; use League\OAuth2\Server\Storage\RefreshTokenInterface;

View File

@ -30,14 +30,14 @@ class RefreshTokenEntity extends \League\OAuth2\Server\Entity\RefreshTokenEntity
return $this->sessionId; return $this->sessionId;
} }
public function setSession(OriginalSessionEntity $session) { public function setSession(OriginalSessionEntity $session): self {
parent::setSession($session); parent::setSession($session);
$this->setSessionId($session->getId()); $this->setSessionId($session->getId());
return $this; return $this;
} }
public function setSessionId(int $sessionId) { public function setSessionId(int $sessionId): void {
$this->sessionId = $sessionId; $this->sessionId = $sessionId;
} }

View File

@ -133,8 +133,10 @@ class AuthCodeGrant extends AbstractGrant {
throw new Exception\InvalidRequestException('client_id'); throw new Exception\InvalidRequestException('client_id');
} }
$clientSecret = $this->server->getRequest()->request->get('client_secret', $clientSecret = $this->server->getRequest()->request->get(
$this->server->getRequest()->getPassword()); 'client_secret',
$this->server->getRequest()->getPassword()
);
if ($clientSecret === null && $this->shouldRequireClientSecret()) { if ($clientSecret === null && $this->shouldRequireClientSecret()) {
throw new Exception\InvalidRequestException('client_secret'); throw new Exception\InvalidRequestException('client_secret');
} }

View File

@ -11,8 +11,8 @@ use yii\helpers\StringHelper;
class ClientStorage extends AbstractStorage implements ClientInterface { class ClientStorage extends AbstractStorage implements ClientInterface {
const REDIRECT_STATIC_PAGE = 'static_page'; private const REDIRECT_STATIC_PAGE = 'static_page';
const REDIRECT_STATIC_PAGE_WITH_CODE = 'static_page_with_code'; private const REDIRECT_STATIC_PAGE_WITH_CODE = 'static_page_with_code';
/** /**
* @inheritdoc * @inheritdoc

View File

@ -18,6 +18,10 @@ class Identity implements IdentityInterface {
*/ */
private $_accessToken; private $_accessToken;
private function __construct(AccessTokenEntity $accessToken) {
$this->_accessToken = $accessToken;
}
/** /**
* @inheritdoc * @inheritdoc
* @throws \yii\web\UnauthorizedHttpException * @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'); 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 { private function getSession(): OauthSession {
return OauthSession::findOne($this->_accessToken->getSessionId()); return OauthSession::findOne($this->_accessToken->getSessionId());
} }

View File

@ -23,6 +23,11 @@ class JwtIdentity implements IdentityInterface {
*/ */
private $token; private $token;
private function __construct(string $rawToken, Token $token) {
$this->rawToken = $rawToken;
$this->token = $token;
}
public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface { public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface {
/** @var \api\components\User\Component $component */ /** @var \api\components\User\Component $component */
$component = Yii::$app->user; $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'); 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;
}
} }

View File

@ -5,7 +5,7 @@ use Emarref\Jwt\Claim\AbstractClaim;
class ScopesClaim extends AbstractClaim { class ScopesClaim extends AbstractClaim {
const NAME = 'ely-scopes'; public const NAME = 'ely-scopes';
/** /**
* ScopesClaim constructor. * ScopesClaim constructor.

View File

@ -21,7 +21,7 @@ class SubjectPrefixVerifier implements VerifierInterface {
$subject = ($subjectClaim === null) ? null : $subjectClaim->getValue(); $subject = ($subjectClaim === null) ? null : $subjectClaim->getValue();
if (!StringHelper::startsWith($subject, $this->subjectPrefix)) { if (!StringHelper::startsWith($subject, $this->subjectPrefix)) {
throw new InvalidSubjectException; throw new InvalidSubjectException();
} }
} }

View File

@ -2,8 +2,8 @@
namespace api\controllers; namespace api\controllers;
use api\models\authentication\ConfirmEmailForm; use api\models\authentication\ConfirmEmailForm;
use api\models\authentication\RepeatAccountActivationForm;
use api\models\authentication\RegistrationForm; use api\models\authentication\RegistrationForm;
use api\models\authentication\RepeatAccountActivationForm;
use common\helpers\Error as E; use common\helpers\Error as E;
use Yii; use Yii;
use yii\filters\AccessControl; use yii\filters\AccessControl;

View File

@ -1,8 +1,8 @@
<?php <?php
namespace api\models; namespace api\models;
use common\helpers\Error as E;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use common\helpers\Error as E;
use common\models\Account; use common\models\Account;
use Yii; use Yii;
use yii\base\ErrorException; use yii\base\ErrorException;

View File

@ -4,9 +4,9 @@ namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\components\ReCaptcha\Validator as ReCaptchaValidator;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use common\helpers\Error as E;
use api\traits\AccountFinder; use api\traits\AccountFinder;
use common\components\UserFriendlyRandomKey; use common\components\UserFriendlyRandomKey;
use common\helpers\Error as E;
use common\models\Account; use common\models\Account;
use common\models\confirmations\ForgotPassword; use common\models\confirmations\ForgotPassword;
use common\models\EmailActivation; use common\models\EmailActivation;

View File

@ -3,9 +3,9 @@ namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use api\traits\AccountFinder;
use api\validators\TotpValidator; use api\validators\TotpValidator;
use common\helpers\Error as E; use common\helpers\Error as E;
use api\traits\AccountFinder;
use common\models\Account; use common\models\Account;
use Yii; use Yii;
@ -13,8 +13,11 @@ class LoginForm extends ApiForm {
use AccountFinder; use AccountFinder;
public $login; public $login;
public $password; public $password;
public $totp; public $totp;
public $rememberMe = false; public $rememberMe = false;
public function rules(): array { public function rules(): array {

View File

@ -4,8 +4,8 @@ namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\components\ReCaptcha\Validator as ReCaptchaValidator;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use common\helpers\Error as E;
use common\components\UserFriendlyRandomKey; use common\components\UserFriendlyRandomKey;
use common\helpers\Error as E;
use common\models\Account; use common\models\Account;
use common\models\confirmations\RegistrationConfirmation; use common\models\confirmations\RegistrationConfirmation;
use common\models\UsernameHistory; use common\models\UsernameHistory;

View File

@ -5,8 +5,8 @@ use api\aop\annotations\CollectModelMetrics;
use api\components\ReCaptcha\Validator as ReCaptchaValidator; use api\components\ReCaptcha\Validator as ReCaptchaValidator;
use api\exceptions\ThisShouldNotHappenException; use api\exceptions\ThisShouldNotHappenException;
use api\models\base\ApiForm; use api\models\base\ApiForm;
use common\helpers\Error as E;
use common\components\UserFriendlyRandomKey; use common\components\UserFriendlyRandomKey;
use common\helpers\Error as E;
use common\models\Account; use common\models\Account;
use common\models\confirmations\RegistrationConfirmation; use common\models\confirmations\RegistrationConfirmation;
use common\models\EmailActivation; use common\models\EmailActivation;

View File

@ -21,8 +21,6 @@ abstract class BaseAccountAction extends Action {
return $this->formatSuccessResult($model); return $this->formatSuccessResult($model);
} }
abstract protected function getFormClassName(): string;
public function getRequestData(): array { public function getRequestData(): array {
return Yii::$app->request->post(); return Yii::$app->request->post();
} }
@ -35,6 +33,8 @@ abstract class BaseAccountAction extends Action {
return []; return [];
} }
abstract protected function getFormClassName(): string;
private function formatFailedResult(AccountActionForm $model): array { private function formatFailedResult(AccountActionForm $model): array {
$response = [ $response = [
'success' => false, 'success' => false,

View File

@ -6,10 +6,6 @@ use api\modules\accounts\models\ChangeEmailForm;
class ChangeEmailAction extends BaseAccountAction { class ChangeEmailAction extends BaseAccountAction {
protected function getFormClassName(): string {
return ChangeEmailForm::class;
}
/** /**
* @param ChangeEmailForm|AccountActionForm $model * @param ChangeEmailForm|AccountActionForm $model
* @return array * @return array
@ -20,4 +16,8 @@ class ChangeEmailAction extends BaseAccountAction {
]; ];
} }
protected function getFormClassName(): string {
return ChangeEmailForm::class;
}
} }

View File

@ -7,10 +7,6 @@ use common\helpers\Error as E;
class EmailVerificationAction extends BaseAccountAction { class EmailVerificationAction extends BaseAccountAction {
protected function getFormClassName(): string {
return SendEmailVerificationForm::class;
}
/** /**
* @param SendEmailVerificationForm|AccountActionForm $model * @param SendEmailVerificationForm|AccountActionForm $model
* @return array * @return array
@ -29,4 +25,8 @@ class EmailVerificationAction extends BaseAccountAction {
]; ];
} }
protected function getFormClassName(): string {
return SendEmailVerificationForm::class;
}
} }

View File

@ -49,7 +49,7 @@ class ChangeEmailForm extends AccountActionForm {
} }
public function createTask(int $accountId, string $newEmail, string $oldEmail): void { public function createTask(int $accountId, string $newEmail, string $oldEmail): void {
$model = new EmailChanged; $model = new EmailChanged();
$model->accountId = $accountId; $model->accountId = $accountId;
$model->oldEmail = $oldEmail; $model->oldEmail = $oldEmail;
$model->newEmail = $newEmail; $model->newEmail = $newEmail;

View File

@ -6,6 +6,8 @@ use OTPHP\TOTP;
trait TotpHelper { trait TotpHelper {
abstract public function getAccount(): Account;
protected function getTotp(): TOTP { protected function getTotp(): TOTP {
$account = $this->getAccount(); $account = $this->getAccount();
$totp = TOTP::create($account->otp_secret); $totp = TOTP::create($account->otp_secret);
@ -15,6 +17,4 @@ trait TotpHelper {
return $totp; return $totp;
} }
abstract public function getAccount(): Account;
} }

View File

@ -14,7 +14,9 @@ use common\models\MinecraftAccessKey;
class AuthenticationForm extends ApiForm { class AuthenticationForm extends ApiForm {
public $username; public $username;
public $password; public $password;
public $clientToken; public $clientToken;
public function rules() { public function rules() {
@ -41,13 +43,15 @@ class AuthenticationForm extends ApiForm {
if (isset($errors['totp'])) { if (isset($errors['totp'])) {
Authserver::error("User with login = '{$this->username}' protected by two factor auth."); Authserver::error("User with login = '{$this->username}' protected by two factor auth.");
throw new ForbiddenOperationException('Account protected with 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) { if ($errors['login'] === E::ACCOUNT_BANNED) {
Authserver::error("User with login = '{$this->username}' is banned"); Authserver::error("User with login = '{$this->username}' is banned");
throw new ForbiddenOperationException('This account has been suspended.'); 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'])) { } elseif (isset($errors['password'])) {
Authserver::error("User with login = '{$this->username}' passed wrong password."); Authserver::error("User with login = '{$this->username}' passed wrong password.");
} }

View File

@ -8,6 +8,7 @@ use common\models\MinecraftAccessKey;
class InvalidateForm extends ApiForm { class InvalidateForm extends ApiForm {
public $accessToken; public $accessToken;
public $clientToken; public $clientToken;
public function rules() { public function rules() {

View File

@ -10,6 +10,7 @@ use common\models\MinecraftAccessKey;
class RefreshTokenForm extends ApiForm { class RefreshTokenForm extends ApiForm {
public $accessToken; public $accessToken;
public $clientToken; public $clientToken;
public function rules() { public function rules() {

View File

@ -12,6 +12,7 @@ use Yii;
class SignoutForm extends ApiForm { class SignoutForm extends ApiForm {
public $username; public $username;
public $password; public $password;
public function rules() { public function rules() {

View File

@ -4,4 +4,5 @@ declare(strict_types=1);
namespace api\modules\oauth\exceptions; namespace api\modules\oauth\exceptions;
interface OauthException { interface OauthException {
} }

View File

@ -10,6 +10,7 @@ use yii\web\TooManyRequestsHttpException;
class RateLimiter extends \yii\filters\RateLimiter { class RateLimiter extends \yii\filters\RateLimiter {
public $limit = 180; public $limit = 180;
public $limitTime = 3600; // 1h public $limitTime = 3600; // 1h
public $authserverDomain; public $authserverDomain;

View File

@ -7,9 +7,9 @@ use api\modules\session\models\protocols\JoinInterface;
use api\modules\session\Module as Session; use api\modules\session\Module as Session;
use api\modules\session\validators\RequiredValidator; use api\modules\session\validators\RequiredValidator;
use common\helpers\StringHelper; use common\helpers\StringHelper;
use common\rbac\Permissions as P;
use common\models\Account; use common\models\Account;
use common\models\MinecraftAccessKey; use common\models\MinecraftAccessKey;
use common\rbac\Permissions as P;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use Yii; use Yii;
use yii\base\ErrorException; use yii\base\ErrorException;
@ -19,7 +19,9 @@ use yii\web\UnauthorizedHttpException;
class JoinForm extends Model { class JoinForm extends Model {
public $accessToken; public $accessToken;
public $selectedProfile; public $selectedProfile;
public $serverId; public $serverId;
/** /**

View File

@ -6,7 +6,7 @@ use Yii;
class SessionModel { class SessionModel {
const KEY_TIME = 120; // 2 min private const KEY_TIME = 120; // 2 min
public $username; public $username;

View File

@ -4,6 +4,7 @@ namespace api\modules\session\models\protocols;
abstract class BaseHasJoined implements HasJoinedInterface { abstract class BaseHasJoined implements HasJoinedInterface {
private $username; private $username;
private $serverId; private $serverId;
public function __construct(string $username, string $serverId) { public function __construct(string $username, string $serverId) {

View File

@ -4,10 +4,13 @@ namespace api\modules\session\models\protocols;
class LegacyJoin extends BaseJoin { class LegacyJoin extends BaseJoin {
private $user; private $user;
private $sessionId; private $sessionId;
private $serverId; private $serverId;
private $accessToken; private $accessToken;
private $uuid; private $uuid;
public function __construct(string $user, string $sessionId, string $serverId) { public function __construct(string $user, string $sessionId, string $serverId) {

View File

@ -4,7 +4,9 @@ namespace api\modules\session\models\protocols;
class ModernJoin extends BaseJoin { class ModernJoin extends BaseJoin {
private $accessToken; private $accessToken;
private $selectedProfile; private $selectedProfile;
private $serverId; private $serverId;
public function __construct(string $accessToken, string $selectedProfile, string $serverId) { public function __construct(string $accessToken, string $selectedProfile, string $serverId) {

View File

@ -7,7 +7,7 @@ trait AccountFinder {
private $account; private $account;
public abstract function getLogin(): string; abstract public function getLogin(): string;
public function getAccount(): ?Account { public function getAccount(): ?Account {
if ($this->account === null) { if ($this->account === null) {

View File

@ -5,6 +5,7 @@ use yii\base\Behavior;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
class DataBehavior extends Behavior { class DataBehavior extends Behavior {
/** /**
* @var string имя атрибута, к которому будет применяться поведение * @var string имя атрибута, к которому будет применяться поведение
*/ */

View File

@ -106,7 +106,6 @@ class ElyDecorator implements DecoratorInterface {
$topPadding, $topPadding,
$multiple $multiple
) { ) {
} }
private function encodeSvgToBase64(string $filePath): string { private function encodeSvgToBase64(string $filePath): string {

View File

@ -1,11 +1,11 @@
<?php <?php
namespace common\components\RabbitMQ; namespace common\components\RabbitMQ;
use yii\base\Exception;
use yii\helpers\Json;
use PhpAmqpLib\Channel\AMQPChannel; use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage; use PhpAmqpLib\Message\AMQPMessage;
use yii\base\Exception;
use yii\helpers\Json;
/** /**
* Не гибкий компонент для работы с RabbitMQ, заточенный под нужны текущего проекта * Не гибкий компонент для работы с RabbitMQ, заточенный под нужны текущего проекта
@ -17,20 +17,10 @@ use PhpAmqpLib\Message\AMQPMessage;
*/ */
class Component extends \yii\base\Component { class Component extends \yii\base\Component {
const TYPE_TOPIC = 'topic'; public const TYPE_TOPIC = 'topic';
const TYPE_DIRECT = 'direct'; public const TYPE_DIRECT = 'direct';
const TYPE_HEADERS = 'headers'; public const TYPE_HEADERS = 'headers';
const TYPE_FANOUT = 'fanout'; public const TYPE_FANOUT = 'fanout';
/**
* @var AMQPStreamConnection
*/
protected $amqpConnection;
/**
* @var AMQPChannel[]
*/
protected $channels = [];
/** /**
* @var string * @var string
@ -57,6 +47,16 @@ class Component extends \yii\base\Component {
*/ */
public $vhost = '/'; public $vhost = '/';
/**
* @var AMQPStreamConnection
*/
protected $amqpConnection;
/**
* @var AMQPChannel[]
*/
protected $channels = [];
/** /**
* @inheritdoc * @inheritdoc
*/ */
@ -115,6 +115,30 @@ class Component extends \yii\base\Component {
$channel->basic_publish(...$this->preparePublishArgs($message, $exchangeName, $routingKey, $publishArgs)); $channel->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); ], $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);
}
} }

View File

@ -157,7 +157,7 @@ class Connection extends Component implements ConnectionInterface {
/** /**
* @var array List of available redis commands http://redis.io/commands * @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 '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 '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 '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; 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) { public function __call($name, $params) {
$redisCommand = mb_strtoupper($name); $redisCommand = mb_strtoupper($name);
if (in_array($redisCommand, self::REDIS_COMMANDS)) { if (in_array($redisCommand, self::REDIS_COMMANDS)) {
@ -385,6 +377,14 @@ class Connection extends Component implements ConnectionInterface {
return parent::__call($name, $params); 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 = []) { public function executeCommand(string $name, array $params = []) {
return $this->getConnection()->$name(...$params); return $this->getConnection()->$name(...$params);
} }

View File

@ -30,11 +30,13 @@ class Key {
public function setValue($value): self { public function setValue($value): self {
$this->getRedis()->set($this->key, $value); $this->getRedis()->set($this->key, $value);
return $this; return $this;
} }
public function delete(): self { public function delete(): self {
$this->getRedis()->del([$this->getKey()]); $this->getRedis()->del([$this->getKey()]);
return $this; return $this;
} }
@ -44,11 +46,13 @@ class Key {
public function expire(int $ttl): self { public function expire(int $ttl): self {
$this->getRedis()->expire($this->key, $ttl); $this->getRedis()->expire($this->key, $ttl);
return $this; return $this;
} }
public function expireAt(int $unixTimestamp): self { public function expireAt(int $unixTimestamp): self {
$this->getRedis()->expireat($this->key, $unixTimestamp); $this->getRedis()->expireat($this->key, $unixTimestamp);
return $this; return $this;
} }

View File

@ -8,11 +8,13 @@ class Set extends Key implements IteratorAggregate {
public function add($value): self { public function add($value): self {
$this->getRedis()->sadd($this->getKey(), $value); $this->getRedis()->sadd($this->getKey(), $value);
return $this; return $this;
} }
public function remove($value): self { public function remove($value): self {
$this->getRedis()->srem($this->getKey(), $value); $this->getRedis()->srem($this->getKey(), $value);
return $this; return $this;
} }

View File

@ -6,7 +6,7 @@ use Yii;
class Api { class Api {
const BASE_DOMAIN = 'http://skinsystem.ely.by'; private const BASE_DOMAIN = 'http://skinsystem.ely.by';
/** /**
* @param string $username * @param string $username

View File

@ -1,10 +1,11 @@
<?php <?php
namespace common\components; declare(strict_types=1);
namespace common\components;
class UserFriendlyRandomKey { class UserFriendlyRandomKey {
public static function make ($length = 18) { public static function make(int $length = 18) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$numChars = strlen($chars); $numChars = strlen($chars);
$key = ''; $key = '';

View File

@ -1,7 +1,6 @@
<?php <?php
namespace common\components; namespace common\components;
/** /**
* Этот класс был использован для изначальной генерации паролей на Ely.by и сейчас должен быть планомерно выпилен * Этот класс был использован для изначальной генерации паролей на Ely.by и сейчас должен быть планомерно выпилен
* с проекта с целью заменить этот алгоритм каким-нибудь посерьёзнее. * с проекта с целью заменить этот алгоритм каким-нибудь посерьёзнее.

View File

@ -1,7 +1,7 @@
<?php <?php
namespace common\db\mysql; namespace common\db\mysql;
use yii\db\Expression; use yii\db\ExpressionInterface;
use yii\db\mysql\QueryBuilder as MysqlQueryBuilder; use yii\db\mysql\QueryBuilder as MysqlQueryBuilder;
class QueryBuilder extends MysqlQueryBuilder { class QueryBuilder extends MysqlQueryBuilder {
@ -13,10 +13,10 @@ class QueryBuilder extends MysqlQueryBuilder {
$orders = []; $orders = [];
foreach ($columns as $name => $direction) { foreach ($columns as $name => $direction) {
if ($direction instanceof Expression) { if ($direction instanceof ExpressionInterface) {
$orders[] = $direction->expression; $orders[] = $direction->expression;
} elseif (is_array($direction)) { } elseif (is_array($direction)) {
// This is new feature // This condition branch is our custom solution
if (empty($direction)) { if (empty($direction)) {
continue; continue;
} }
@ -27,7 +27,6 @@ class QueryBuilder extends MysqlQueryBuilder {
} }
$orders[] = 'FIELD(' . $this->db->quoteColumnName($name) . ',' . implode(',', $fieldValues) . ')'; $orders[] = 'FIELD(' . $this->db->quoteColumnName($name) . ',' . implode(',', $fieldValues) . ')';
// End of new feature
} else { } else {
$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : ''); $orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
} }

View File

@ -42,7 +42,7 @@ abstract class TemplateWithRenderer extends Template {
*/ */
abstract public function getTemplateName(): string; abstract public function getTemplateName(): string;
protected final function getView() { final protected function getView() {
return $this->getTemplateName(); return $this->getTemplateName();
} }

View File

@ -16,6 +16,12 @@ class ChangeEmailConfirmCurrentEmail extends Template {
return 'Ely.by Account change E-mail confirmation'; return 'Ely.by Account change E-mail confirmation';
} }
public function getParams(): array {
return [
'key' => $this->key,
];
}
/** /**
* @return string|array * @return string|array
*/ */
@ -26,10 +32,4 @@ class ChangeEmailConfirmCurrentEmail extends Template {
]; ];
} }
public function getParams(): array {
return [
'key' => $this->key,
];
}
} }

View File

@ -19,6 +19,13 @@ class ChangeEmailConfirmNewEmail extends Template {
return 'Ely.by Account new E-mail confirmation'; return 'Ely.by Account new E-mail confirmation';
} }
public function getParams(): array {
return [
'key' => $this->key,
'username' => $this->username,
];
}
/** /**
* @return string|array * @return string|array
*/ */
@ -29,11 +36,4 @@ class ChangeEmailConfirmNewEmail extends Template {
]; ];
} }
public function getParams(): array {
return [
'key' => $this->key,
'username' => $this->username,
];
}
} }

View File

@ -3,70 +3,70 @@ namespace common\helpers;
final class Error { final class Error {
const USERNAME_REQUIRED = 'error.username_required'; public const USERNAME_REQUIRED = 'error.username_required';
const USERNAME_TOO_SHORT = 'error.username_too_short'; public const USERNAME_TOO_SHORT = 'error.username_too_short';
const USERNAME_TOO_LONG = 'error.username_too_long'; public const USERNAME_TOO_LONG = 'error.username_too_long';
const USERNAME_INVALID = 'error.username_invalid'; public const USERNAME_INVALID = 'error.username_invalid';
const USERNAME_NOT_AVAILABLE = 'error.username_not_available'; public const USERNAME_NOT_AVAILABLE = 'error.username_not_available';
const EMAIL_REQUIRED = 'error.email_required'; public const EMAIL_REQUIRED = 'error.email_required';
const EMAIL_TOO_LONG = 'error.email_too_long'; public const EMAIL_TOO_LONG = 'error.email_too_long';
const EMAIL_INVALID = 'error.email_invalid'; public const EMAIL_INVALID = 'error.email_invalid';
const EMAIL_IS_TEMPMAIL = 'error.email_is_tempmail'; public const EMAIL_IS_TEMPMAIL = 'error.email_is_tempmail';
const EMAIL_NOT_AVAILABLE = 'error.email_not_available'; public const EMAIL_NOT_AVAILABLE = 'error.email_not_available';
const EMAIL_NOT_FOUND = 'error.email_not_found'; public const EMAIL_NOT_FOUND = 'error.email_not_found';
const LOGIN_REQUIRED = 'error.login_required'; public const LOGIN_REQUIRED = 'error.login_required';
const LOGIN_NOT_EXIST = 'error.login_not_exist'; public const LOGIN_NOT_EXIST = 'error.login_not_exist';
const PASSWORD_REQUIRED = 'error.password_required'; public const PASSWORD_REQUIRED = 'error.password_required';
const PASSWORD_INCORRECT = 'error.password_incorrect'; public const PASSWORD_INCORRECT = 'error.password_incorrect';
const PASSWORD_TOO_SHORT = 'error.password_too_short'; public const PASSWORD_TOO_SHORT = 'error.password_too_short';
const KEY_REQUIRED = 'error.key_required'; public const KEY_REQUIRED = 'error.key_required';
const KEY_NOT_EXISTS = 'error.key_not_exists'; public const KEY_NOT_EXISTS = 'error.key_not_exists';
const KEY_EXPIRE = 'error.key_expire'; public const KEY_EXPIRE = 'error.key_expire';
const ACCOUNT_BANNED = 'error.account_banned'; public const ACCOUNT_BANNED = 'error.account_banned';
const ACCOUNT_NOT_ACTIVATED = 'error.account_not_activated'; public const ACCOUNT_NOT_ACTIVATED = 'error.account_not_activated';
const ACCOUNT_ALREADY_ACTIVATED = 'error.account_already_activated'; public const ACCOUNT_ALREADY_ACTIVATED = 'error.account_already_activated';
const ACCOUNT_CANNOT_RESEND_MESSAGE = 'error.account_cannot_resend_message'; 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'; public const NEW_PASSWORD_REQUIRED = 'error.newPassword_required';
const NEW_RE_PASSWORD_REQUIRED = 'error.newRePassword_required'; public const NEW_RE_PASSWORD_REQUIRED = 'error.newRePassword_required';
const NEW_RE_PASSWORD_DOES_NOT_MATCH = self::RE_PASSWORD_DOES_NOT_MATCH; public const NEW_RE_PASSWORD_DOES_NOT_MATCH = self::RE_PASSWORD_DOES_NOT_MATCH;
const REFRESH_TOKEN_REQUIRED = 'error.refresh_token_required'; public const REFRESH_TOKEN_REQUIRED = 'error.refresh_token_required';
const REFRESH_TOKEN_NOT_EXISTS = 'error.refresh_token_not_exist'; public const REFRESH_TOKEN_NOT_EXISTS = 'error.refresh_token_not_exist';
const CAPTCHA_REQUIRED = 'error.captcha_required'; public const CAPTCHA_REQUIRED = 'error.captcha_required';
const CAPTCHA_INVALID = 'error.captcha_invalid'; 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'; public const RE_PASSWORD_REQUIRED = 'error.rePassword_required';
const RE_PASSWORD_DOES_NOT_MATCH = 'error.rePassword_does_not_match'; 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'; public const SUBJECT_REQUIRED = 'error.subject_required';
const MESSAGE_REQUIRED = 'error.message_required'; public const MESSAGE_REQUIRED = 'error.message_required';
const TOTP_REQUIRED = 'error.totp_required'; public const TOTP_REQUIRED = 'error.totp_required';
const TOTP_INCORRECT = 'error.totp_incorrect'; public const TOTP_INCORRECT = 'error.totp_incorrect';
const OTP_ALREADY_ENABLED = 'error.otp_already_enabled'; public const OTP_ALREADY_ENABLED = 'error.otp_already_enabled';
const OTP_NOT_ENABLED = 'error.otp_not_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'; public const REDIRECT_URI_REQUIRED = 'error.redirectUri_required';
const REDIRECT_URI_INVALID = 'error.redirectUri_invalid'; 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';
} }

View File

@ -44,13 +44,13 @@ use const common\LATEST_RULES_VERSION;
*/ */
class Account extends ActiveRecord { class Account extends ActiveRecord {
const STATUS_DELETED = -10; public const STATUS_DELETED = -10;
const STATUS_BANNED = -1; public const STATUS_BANNED = -1;
const STATUS_REGISTERED = 0; public const STATUS_REGISTERED = 0;
const STATUS_ACTIVE = 10; public const STATUS_ACTIVE = 10;
const PASS_HASH_STRATEGY_OLD_ELY = 0; public const PASS_HASH_STRATEGY_OLD_ELY = 0;
const PASS_HASH_STRATEGY_YII2 = 1; public const PASS_HASH_STRATEGY_YII2 = 1;
public static function tableName(): string { public static function tableName(): string {
return '{{%accounts}}'; return '{{%accounts}}';
@ -69,8 +69,7 @@ class Account extends ActiveRecord {
switch ($passwordHashStrategy) { switch ($passwordHashStrategy) {
case self::PASS_HASH_STRATEGY_OLD_ELY: case self::PASS_HASH_STRATEGY_OLD_ELY:
$hashedPass = UserPass::make($this->email, $password); return UserPass::make($this->email, $password) === $this->password_hash;
return $hashedPass === $this->password_hash;
case self::PASS_HASH_STRATEGY_YII2: case self::PASS_HASH_STRATEGY_YII2:
return Yii::$app->security->validatePassword($password, $this->password_hash); return Yii::$app->security->validatePassword($password, $this->password_hash);

View File

@ -28,10 +28,10 @@ use yii\helpers\ArrayHelper;
*/ */
class EmailActivation extends ActiveRecord { class EmailActivation extends ActiveRecord {
const TYPE_REGISTRATION_EMAIL_CONFIRMATION = 0; public const TYPE_REGISTRATION_EMAIL_CONFIRMATION = 0;
const TYPE_FORGOT_PASSWORD_KEY = 1; public const TYPE_FORGOT_PASSWORD_KEY = 1;
const TYPE_CURRENT_EMAIL_CONFIRMATION = 2; public const TYPE_CURRENT_EMAIL_CONFIRMATION = 2;
const TYPE_NEW_EMAIL_CONFIRMATION = 3; public const TYPE_NEW_EMAIL_CONFIRMATION = 3;
public static function tableName() { public static function tableName() {
return '{{%email_activations}}'; return '{{%email_activations}}';
@ -79,7 +79,7 @@ class EmailActivation extends ActiveRecord {
throw new InvalidConfigException('Unexpected type'); throw new InvalidConfigException('Unexpected type');
} }
return new $classMap[$type]; return new $classMap[$type]();
} }
public static function getClassMap() { public static function getClassMap() {

View File

@ -29,7 +29,7 @@ use yii\db\ActiveRecord;
*/ */
class MinecraftAccessKey extends ActiveRecord { class MinecraftAccessKey extends ActiveRecord {
const LIFETIME = 172800; // Ключ актуален в течение 2 дней public const LIFETIME = 172800; // Ключ актуален в течение 2 дней
public static function tableName(): string { public static function tableName(): string {
return '{{%minecraft_access_keys}}'; return '{{%minecraft_access_keys}}';

View File

@ -11,6 +11,10 @@ class OauthScopeQuery {
private $owner; private $owner;
public function __construct(array $scopes) {
$this->scopes = $scopes;
}
public function onlyPublic(): self { public function onlyPublic(): self {
$this->internal = false; $this->internal = false;
return $this; return $this;
@ -43,8 +47,4 @@ class OauthScopeQuery {
}), 'value'); }), 'value');
} }
public function __construct(array $scopes) {
$this->scopes = $scopes;
}
} }

View File

@ -54,9 +54,9 @@ class Textures {
if (!$encrypted) { if (!$encrypted) {
return $array; return $array;
} else {
return static::encrypt($array);
} }
return static::encrypt($array);
} }
public function getTextures(): array { public function getTextures(): array {

View File

@ -45,7 +45,7 @@ class UsernameHistory extends ActiveRecord {
* @param int $afterTime * @param int $afterTime
* @return UsernameHistory|null * @return UsernameHistory|null
*/ */
public function findNext(int $afterTime = null) /*: ?UsernameHistory*/ { public function findNext(int $afterTime = null): ?UsernameHistory {
return self::find() return self::find()
->andWhere(['account_id' => $this->account_id]) ->andWhere(['account_id' => $this->account_id])
->andWhere(['>', 'applied_in', $afterTime ?: $this->applied_in]) ->andWhere(['>', 'applied_in', $afterTime ?: $this->applied_in])

View File

@ -12,7 +12,7 @@ class NewEmailConfirmationBehavior extends DataBehavior {
return $this->getKey('newEmail'); return $this->getKey('newEmail');
} }
public function setNewEmail(string $newEmail) { public function setNewEmail(string $newEmail): void {
$this->setKey('newEmail', $newEmail); $this->setKey('newEmail', $newEmail);
} }

View File

@ -38,7 +38,9 @@
"codeception/specify": "^1.0.0", "codeception/specify": "^1.0.0",
"codeception/verify": "*", "codeception/verify": "*",
"mockery/mockery": "^1.0.0", "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": [ "repositories": [
{ {

465
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "b322fafe1486ee057b633a35d336c1a1", "content-hash": "63497214afa6b50f50d3bc80fe9eb269",
"packages": [ "packages": [
{ {
"name": "bacon/bacon-qr-code", "name": "bacon/bacon-qr-code",
@ -3165,6 +3165,68 @@
"description": "BDD assertion library for PHPUnit", "description": "BDD assertion library for PHPUnit",
"time": "2017-11-12T01:51:59+00:00" "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", "name": "doctrine/instantiator",
"version": "1.1.0", "version": "1.1.0",
@ -3219,6 +3281,55 @@
], ],
"time": "2017-07-22T11:58:36+00:00" "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", "name": "facebook/webdriver",
"version": "1.5.0", "version": "1.5.0",
@ -3315,6 +3426,100 @@
"description": "JSONPath implementation for parsing, searching and flattening arrays", "description": "JSONPath implementation for parsing, searching and flattening arrays",
"time": "2016-09-06T17:43:18+00:00" "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", "name": "fzaninotto/faker",
"version": "v1.7.1", "version": "v1.7.1",
@ -3625,6 +3830,57 @@
"description": "Library for handling version information and constraints", "description": "Library for handling version information and constraints",
"time": "2017-03-05T17:38:23+00:00" "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", "name": "php-mock/php-mock",
"version": "1.0.1", "version": "1.0.1",
@ -5257,6 +5513,55 @@
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-01-03T07:38:00+00:00" "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", "name": "symfony/finder",
"version": "v4.0.4", "version": "v4.0.4",
@ -5306,6 +5611,164 @@
"homepage": "https://symfony.com", "homepage": "https://symfony.com",
"time": "2018-01-03T07:38:00+00:00" "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", "name": "symfony/yaml",
"version": "v4.0.4", "version": "v4.0.4",

View File

@ -17,7 +17,7 @@ abstract class AmqpController extends Controller {
private $reconnected = false; private $reconnected = false;
public final function actionIndex() { final public function actionIndex() {
$this->start(); $this->start();
} }

View File

@ -85,7 +85,7 @@ class CleanupController extends Controller {
$durationsMap = []; $durationsMap = [];
foreach (EmailActivation::getClassMap() as $typeId => $className) { foreach (EmailActivation::getClassMap() as $typeId => $className) {
/** @var EmailActivation $object */ /** @var EmailActivation $object */
$object = new $className; $object = new $className();
/** @var \common\behaviors\EmailActivationExpirationBehavior $behavior */ /** @var \common\behaviors\EmailActivationExpirationBehavior $behavior */
$behavior = $object->getBehavior('expirationBehavior'); $behavior = $object->getBehavior('expirationBehavior');
/** @noinspection NullPointerExceptionInspection */ /** @noinspection NullPointerExceptionInspection */

View File

@ -95,7 +95,7 @@ class RbacController extends Controller {
$authManager = $this->getAuthManager(); $authManager = $this->getAuthManager();
$permission = $authManager->createPermission($name); $permission = $authManager->createPermission($name);
if ($ruleClassName !== null) { if ($ruleClassName !== null) {
$rule = new $ruleClassName; $rule = new $ruleClassName();
if (!$rule instanceof Rule) { if (!$rule instanceof Rule) {
throw new InvalidArgumentException('ruleClassName must be rule class name'); throw new InvalidArgumentException('ruleClassName must be rule class name');
} }

View File

@ -43,7 +43,7 @@ class Migration extends YiiMigration {
private function buildKey(array $columns) { private function buildKey(array $columns) {
$key = ''; $key = '';
foreach ($columns as $i => $column) { foreach ($columns as $i => $column) {
$key .= $i == count($columns) ? $column : "$column,"; $key .= $i === count($columns) ? $column : "$column,";
} }
return $key; return $key;

View File

@ -4,8 +4,6 @@ use console\db\Migration;
class m161030_013122_ely_by_admin_app extends Migration { class m161030_013122_ely_by_admin_app extends Migration {
const APP_NAME = 'ely_admin';
public function safeUp() { public function safeUp() {
$exists = $this->db->createCommand(' $exists = $this->db->createCommand('
SELECT COUNT(*) SELECT COUNT(*)
@ -13,12 +11,12 @@ class m161030_013122_ely_by_admin_app extends Migration {
WHERE id = :app_name WHERE id = :app_name
LIMIT 1 LIMIT 1
', [ ', [
'app_name' => self::APP_NAME, 'app_name' => 'ely_admin',
])->queryScalar(); ])->queryScalar();
if (!$exists) { if (!$exists) {
$this->insert('{{%oauth_clients}}', [ $this->insert('{{%oauth_clients}}', [
'id' => self::APP_NAME, 'id' => 'ely_admin',
'secret' => 'change_this_on_production', 'secret' => 'change_this_on_production',
'name' => 'Admin Ely.by', 'name' => 'Admin Ely.by',
'description' => '', 'description' => '',
@ -30,7 +28,7 @@ class m161030_013122_ely_by_admin_app extends Migration {
} }
public function safeDown() { public function safeDown() {
$this->delete('{{%oauth_clients}}', ['id' => self::APP_NAME]); $this->delete('{{%oauth_clients}}', ['id' => 'ely_admin']);
} }
} }

View File

@ -16,11 +16,11 @@ namespace tests\codeception\api;
* *
* @SuppressWarnings(PHPMD) * @SuppressWarnings(PHPMD)
*/ */
class UnitTester extends \Codeception\Actor class UnitTester extends \Codeception\Actor {
{
use _generated\UnitTesterActions; use _generated\UnitTesterActions;
/** /**
* Define custom actions here * Define custom actions here
*/ */
} }

View File

@ -1,8 +1,8 @@
<?php <?php
namespace tests\codeception\api\functional\authserver; namespace tests\codeception\api\functional\authserver;
use tests\codeception\api\_pages\AuthserverRoute;
use Ramsey\Uuid\Uuid; use Ramsey\Uuid\Uuid;
use tests\codeception\api\_pages\AuthserverRoute;
use tests\codeception\api\FunctionalTester; use tests\codeception\api\FunctionalTester;
class AuthorizationCest { class AuthorizationCest {

View File

@ -67,6 +67,7 @@ class UsernamesToUuidsCest {
for ($i = 0; $i < 150; $i++) { for ($i = 0; $i < 150; $i++) {
$usernames[] = random_bytes(10); $usernames[] = random_bytes(10);
} }
$this->route->uuidsByUsernames($usernames); $this->route->uuidsByUsernames($usernames);
$I->canSeeResponseCodeIs(400); $I->canSeeResponseCodeIs(400);
$I->canSeeResponseIsJson(); $I->canSeeResponseIsJson();

View File

@ -10,6 +10,11 @@ class TestCase extends \Codeception\Test\Unit {
*/ */
protected $tester; protected $tester;
protected function tearDown() {
parent::tearDown();
Mockery::close();
}
/** /**
* Список фикстур, что будут загружены перед тестом, но после зачистки базы данных * Список фикстур, что будут загружены перед тестом, но после зачистки базы данных
* *
@ -21,9 +26,4 @@ class TestCase extends \Codeception\Test\Unit {
return []; return [];
} }
protected function tearDown() {
parent::tearDown();
Mockery::close();
}
} }

View File

@ -1,9 +1,9 @@
<?php <?php
namespace codeception\api\unit\components\User; namespace codeception\api\unit\components\User;
use api\components\User\AuthenticationResult;
use api\components\User\Component; use api\components\User\Component;
use api\components\User\Identity; use api\components\User\Identity;
use api\components\User\AuthenticationResult;
use common\models\Account; use common\models\Account;
use common\models\AccountSession; use common\models\AccountSession;
use Emarref\Jwt\Claim; use Emarref\Jwt\Claim;

View File

@ -1,8 +1,8 @@
<?php <?php
namespace tests\codeception\api\unit\modules\internal\models; namespace tests\codeception\api\unit\modules\internal\models;
use api\modules\internal\helpers\Error as E;
use api\modules\accounts\models\BanAccountForm; use api\modules\accounts\models\BanAccountForm;
use api\modules\internal\helpers\Error as E;
use common\models\Account; use common\models\Account;
use tests\codeception\api\unit\TestCase; use tests\codeception\api\unit\TestCase;

View File

@ -1,8 +1,8 @@
<?php <?php
namespace tests\codeception\api\unit\modules\internal\models; namespace tests\codeception\api\unit\modules\internal\models;
use api\modules\internal\helpers\Error as E;
use api\modules\accounts\models\PardonAccountForm; use api\modules\accounts\models\PardonAccountForm;
use api\modules\internal\helpers\Error as E;
use common\models\Account; use common\models\Account;
use tests\codeception\api\unit\TestCase; use tests\codeception\api\unit\TestCase;

View File

@ -55,7 +55,6 @@ class OauthClientFormTest extends TestCase {
$form->shouldReceive('isClientExists')->andReturn(false); $form->shouldReceive('isClientExists')->andReturn(false);
$request = new class implements OauthClientTypeForm { $request = new class implements OauthClientTypeForm {
public function load($data): bool { public function load($data): bool {
return true; return true;
} }
@ -72,7 +71,6 @@ class OauthClientFormTest extends TestCase {
$client->name = 'New name'; $client->name = 'New name';
$client->description = 'New description.'; $client->description = 'New description.';
} }
}; };
$this->assertTrue($form->save($request)); $this->assertTrue($form->save($request));

View File

@ -25,7 +25,7 @@ class RateLimiterTest extends TestCase {
/** @var RateLimiter|\PHPUnit_Framework_MockObject_MockObject $filter */ /** @var RateLimiter|\PHPUnit_Framework_MockObject_MockObject $filter */
$filter = $this->getMockBuilder(RateLimiter::class) $filter = $this->getMockBuilder(RateLimiter::class)
->setConstructorArgs([[ ->setConstructorArgs([[
'authserverDomain' => Yii::$app->params['authserverHost'] 'authserverDomain' => Yii::$app->params['authserverHost'],
]]) ]])
->setMethods(['getServer']) ->setMethods(['getServer'])
->getMock(); ->getMock();
@ -58,7 +58,7 @@ class RateLimiterTest extends TestCase {
->will($this->returnValue('http://authserver.ely.by')); ->will($this->returnValue('http://authserver.ely.by'));
$filter = new RateLimiter([ $filter = new RateLimiter([
'authserverDomain' => Yii::$app->params['authserverHost'] 'authserverDomain' => Yii::$app->params['authserverHost'],
]); ]);
$filter->checkRateLimit(null, $request, null, null); $filter->checkRateLimit(null, $request, null, null);
} }

View File

@ -2,11 +2,11 @@
namespace codeception\api\unit\validators; namespace codeception\api\unit\validators;
use api\validators\PasswordRequiredValidator; use api\validators\PasswordRequiredValidator;
use common\helpers\Error as E;
use common\models\Account; use common\models\Account;
use common\rbac\Permissions as P; use common\rbac\Permissions as P;
use tests\codeception\api\unit\TestCase; use tests\codeception\api\unit\TestCase;
use tests\codeception\common\_support\ProtectedCaller; use tests\codeception\common\_support\ProtectedCaller;
use common\helpers\Error as E;
use yii\web\User; use yii\web\User;
class PasswordRequiredValidatorTest extends TestCase { class PasswordRequiredValidatorTest extends TestCase {

View File

@ -1,7 +1,6 @@
<?php <?php
namespace tests\codeception\common\_support; namespace tests\codeception\common\_support;
use Codeception\Module;
use ReflectionClass; use ReflectionClass;
trait ProtectedCaller { trait ProtectedCaller {

View File

@ -22,4 +22,5 @@ class UnitTester extends \Codeception\Actor {
/** /**
* Define custom actions here * Define custom actions here
*/ */
} }

View File

@ -8,6 +8,11 @@ class Queue extends BaseQueue {
private $messages = []; 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) { public function push($job) {
$this->messages[] = $job; $this->messages[] = $job;
} }
@ -24,9 +29,4 @@ class Queue extends BaseQueue {
// This function is abstract, but will be not called // 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
}
} }

View File

@ -10,6 +10,11 @@ class TestCase extends \Codeception\Test\Unit {
*/ */
protected $tester; protected $tester;
protected function tearDown() {
parent::tearDown();
Mockery::close();
}
/** /**
* Список фикстур, что будут загружены перед тестом, но после зачистки базы данных * Список фикстур, что будут загружены перед тестом, но после зачистки базы данных
* *
@ -21,9 +26,4 @@ class TestCase extends \Codeception\Test\Unit {
return []; return [];
} }
protected function tearDown() {
parent::tearDown();
Mockery::close();
}
} }

View File

@ -50,6 +50,7 @@ class UsernameValidatorTest extends TestCase {
$this->assertNotEquals(['error.username_too_long'], $model->getErrors('field')); $this->assertNotEquals(['error.username_too_long'], $model->getErrors('field'));
} }
// TODO: rewrite this test with @provider usage
public function testValidateAttributePattern() { public function testValidateAttributePattern() {
$shouldBeValid = [ $shouldBeValid = [
'русский_ник', 'русский_ник_на_грани!', 'numbers1132', '*__*-Stars-*__*', '1-_.!$%^&*()[]', 'русский_ник', 'русский_ник_на_грани!', 'numbers1132', '*__*-Stars-*__*', '1-_.!$%^&*()[]',
@ -62,7 +63,7 @@ class UsernameValidatorTest extends TestCase {
} }
$shouldBeInvalid = [ $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); $model = $this->createModel($nickname);

View File

@ -16,11 +16,11 @@ namespace tests\codeception\console;
* *
* @SuppressWarnings(PHPMD) * @SuppressWarnings(PHPMD)
*/ */
class UnitTester extends \Codeception\Actor class UnitTester extends \Codeception\Actor {
{
use _generated\UnitTesterActions; use _generated\UnitTesterActions;
/** /**
* Define custom actions here * Define custom actions here
*/ */
} }

View File

@ -11,6 +11,11 @@ class TestCase extends Unit {
*/ */
protected $tester; protected $tester;
protected function tearDown() {
parent::tearDown();
Mockery::close();
}
/** /**
* Список фикстур, что будут загружены перед тестом, но после зачистки базы данных * Список фикстур, что будут загружены перед тестом, но после зачистки базы данных
* *
@ -22,9 +27,4 @@ class TestCase extends Unit {
return []; return [];
} }
protected function tearDown() {
parent::tearDown();
Mockery::close();
}
} }

View File

@ -49,9 +49,9 @@ class AccountQueueControllerTest extends TestCase {
->willReturnCallback(function() { ->willReturnCallback(function() {
if ($this->expectedResponse === false) { if ($this->expectedResponse === false) {
throw new NoContentException(); throw new NoContentException();
} else {
return $this->expectedResponse;
} }
return $this->expectedResponse;
}); });
$controller $controller

8
yii
View File

@ -1,13 +1,13 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
require(__DIR__ . '/vendor/autoload.php'); require __DIR__ . '/vendor/autoload.php';
defined('YII_DEBUG') or define('YII_DEBUG', (boolean)getenv('YII_DEBUG')); defined('YII_DEBUG') or define('YII_DEBUG', (boolean)getenv('YII_DEBUG'));
defined('YII_ENV') or define('YII_ENV', getenv('YII_ENV')); defined('YII_ENV') or define('YII_ENV', getenv('YII_ENV'));
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php'); require __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
require(__DIR__ . '/common/config/bootstrap.php'); require __DIR__ . '/common/config/bootstrap.php';
require(__DIR__ . '/console/config/bootstrap.php'); require __DIR__ . '/console/config/bootstrap.php';
$config = \common\config\ConfigLoader::load('console'); $config = \common\config\ConfigLoader::load('console');