Cleanup code, improve typings

This commit is contained in:
ErickSkrauch
2019-12-13 22:27:13 +03:00
parent 830a17612b
commit d9ef27b745
28 changed files with 189 additions and 225 deletions

View File

@ -107,7 +107,7 @@ class AuthenticationController extends Controller {
], ],
]; ];
if ($model->getLoginAttribute() !== 'email') { if (strpos($model->login, '@') === false) {
$response['data']['emailMask'] = StringHelper::getEmailMask($model->getAccount()->email); $response['data']['emailMask'] = StringHelper::getEmailMask($model->getAccount()->email);
} }

View File

@ -1,10 +1,11 @@
<?php <?php
declare(strict_types=1);
namespace api\models\authentication; 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 api\traits\AccountFinder;
use common\components\UserFriendlyRandomKey; use common\components\UserFriendlyRandomKey;
use common\helpers\Error as E; use common\helpers\Error as E;
use common\models\Account; use common\models\Account;
@ -15,13 +16,12 @@ use Yii;
use yii\base\ErrorException; use yii\base\ErrorException;
class ForgotPasswordForm extends ApiForm { class ForgotPasswordForm extends ApiForm {
use AccountFinder;
public $captcha; public $captcha;
public $login; public $login;
public function rules() { public function rules(): array {
return [ return [
['captcha', ReCaptchaValidator::class], ['captcha', ReCaptchaValidator::class],
['login', 'required', 'message' => E::LOGIN_REQUIRED], ['login', 'required', 'message' => E::LOGIN_REQUIRED],
@ -31,7 +31,7 @@ class ForgotPasswordForm extends ApiForm {
]; ];
} }
public function validateLogin($attribute) { public function validateLogin(string $attribute): void {
if (!$this->hasErrors()) { if (!$this->hasErrors()) {
if ($this->getAccount() === null) { if ($this->getAccount() === null) {
$this->addError($attribute, E::LOGIN_NOT_EXIST); $this->addError($attribute, E::LOGIN_NOT_EXIST);
@ -39,7 +39,7 @@ class ForgotPasswordForm extends ApiForm {
} }
} }
public function validateActivity($attribute) { public function validateActivity(string $attribute): void {
if (!$this->hasErrors()) { if (!$this->hasErrors()) {
$account = $this->getAccount(); $account = $this->getAccount();
if ($account->status !== Account::STATUS_ACTIVE) { if ($account->status !== Account::STATUS_ACTIVE) {
@ -48,7 +48,7 @@ class ForgotPasswordForm extends ApiForm {
} }
} }
public function validateFrequency($attribute) { public function validateFrequency(string $attribute): void {
if (!$this->hasErrors()) { if (!$this->hasErrors()) {
$emailConfirmation = $this->getEmailActivation(); $emailConfirmation = $this->getEmailActivation();
if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) { if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) {
@ -57,12 +57,15 @@ class ForgotPasswordForm extends ApiForm {
} }
} }
public function getAccount(): ?Account {
return Account::find()->andWhereLogin($this->login)->one();
}
/** /**
* @CollectModelMetrics(prefix="authentication.forgotPassword") * @CollectModelMetrics(prefix="authentication.forgotPassword")
* @return bool * @return bool
* @throws ErrorException
*/ */
public function forgotPassword() { public function forgotPassword(): bool {
if (!$this->validate()) { if (!$this->validate()) {
return false; return false;
} }
@ -86,23 +89,13 @@ class ForgotPasswordForm extends ApiForm {
return true; return true;
} }
public function getLogin(): string { public function getEmailActivation(): ?EmailActivation {
return $this->login;
}
/**
* @return EmailActivation|null
* @throws ErrorException
*/
public function getEmailActivation() {
$account = $this->getAccount(); $account = $this->getAccount();
if ($account === null) { if ($account === null) {
throw new ErrorException('Account not founded'); return null;
} }
return $account->getEmailActivations() return $account->getEmailActivations()->withType(EmailActivation::TYPE_FORGOT_PASSWORD_KEY)->one();
->andWhere(['type' => EmailActivation::TYPE_FORGOT_PASSWORD_KEY])
->one();
} }
} }

View File

@ -5,7 +5,6 @@ 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 common\models\Account; use common\models\Account;
@ -14,14 +13,25 @@ use Webmozart\Assert\Assert;
use Yii; use Yii;
class LoginForm extends ApiForm { class LoginForm extends ApiForm {
use AccountFinder;
/**
* @var string
*/
public $login; public $login;
/**
* @var string
*/
public $password; public $password;
/**
* @var string|null
*/
public $totp; public $totp;
/**
* @var bool
*/
public $rememberMe = false; public $rememberMe = false;
public function rules(): array { public function rules(): array {
@ -90,8 +100,8 @@ class LoginForm extends ApiForm {
} }
} }
public function getLogin(): string { public function getAccount(): ?Account {
return $this->login; return Account::find()->andWhereLogin($this->login)->one();
} }
/** /**

View File

@ -1,4 +1,6 @@
<?php <?php
declare(strict_types=1);
namespace api\models\authentication; namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
@ -21,7 +23,7 @@ class RepeatAccountActivationForm extends ApiForm {
private $emailActivation; private $emailActivation;
public function rules() { public function rules(): array {
return [ return [
['captcha', ReCaptchaValidator::class], ['captcha', ReCaptchaValidator::class],
['email', 'filter', 'filter' => 'trim'], ['email', 'filter', 'filter' => 'trim'],
@ -31,7 +33,7 @@ class RepeatAccountActivationForm extends ApiForm {
]; ];
} }
public function validateEmailForAccount($attribute) { public function validateEmailForAccount(string $attribute): void {
if (!$this->hasErrors()) { if (!$this->hasErrors()) {
$account = $this->getAccount(); $account = $this->getAccount();
if ($account === null) { if ($account === null) {
@ -45,7 +47,7 @@ class RepeatAccountActivationForm extends ApiForm {
} }
} }
public function validateExistsActivation($attribute) { public function validateExistsActivation(string $attribute): void {
if (!$this->hasErrors()) { if (!$this->hasErrors()) {
$activation = $this->getActivation(); $activation = $this->getActivation();
if ($activation !== null && !$activation->canRepeat()) { if ($activation !== null && !$activation->canRepeat()) {
@ -58,11 +60,12 @@ class RepeatAccountActivationForm extends ApiForm {
* @CollectModelMetrics(prefix="signup.repeatEmail") * @CollectModelMetrics(prefix="signup.repeatEmail")
* @return bool * @return bool
*/ */
public function sendRepeatMessage() { public function sendRepeatMessage(): bool {
if (!$this->validate()) { if (!$this->validate()) {
return false; return false;
} }
/** @var Account $account */
$account = $this->getAccount(); $account = $this->getAccount();
$transaction = Yii::$app->db->beginTransaction(); $transaction = Yii::$app->db->beginTransaction();
@ -85,27 +88,17 @@ class RepeatAccountActivationForm extends ApiForm {
return true; return true;
} }
/** public function getAccount(): ?Account {
* @return Account|null
*/
public function getAccount() {
return Account::find() return Account::find()
->andWhere(['email' => $this->email]) ->andWhere(['email' => $this->email])
->one(); ->one();
} }
/** public function getActivation(): ?EmailActivation {
* @return EmailActivation|null return $this->getAccount()
*/ ->getEmailActivations()
public function getActivation() { ->withType(EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION)
if ($this->emailActivation === null) { ->one();
$this->emailActivation = $this->getAccount()
->getEmailActivations()
->andWhere(['type' => EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION])
->one();
}
return $this->emailActivation;
} }
} }

View File

@ -1,4 +1,6 @@
<?php <?php
declare(strict_types=1);
namespace api\modules\accounts\models; namespace api\modules\accounts\models;
use api\aop\annotations\CollectModelMetrics; use api\aop\annotations\CollectModelMetrics;
@ -26,7 +28,7 @@ class SendEmailVerificationForm extends AccountActionForm {
]; ];
} }
public function validateFrequency($attribute): void { public function validateFrequency(string $attribute): void {
if (!$this->hasErrors()) { if (!$this->hasErrors()) {
$emailConfirmation = $this->getEmailActivation(); $emailConfirmation = $this->getEmailActivation();
if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) { if ($emailConfirmation !== null && !$emailConfirmation->canRepeat()) {
@ -82,12 +84,10 @@ class SendEmailVerificationForm extends AccountActionForm {
public function getEmailActivation(): ?EmailActivation { public function getEmailActivation(): ?EmailActivation {
return $this->getAccount() return $this->getAccount()
->getEmailActivations() ->getEmailActivations()
->andWhere([ ->withType(
'type' => [ EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION,
EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION, EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION
EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION, )
],
])
->one(); ->one();
} }

View File

@ -75,10 +75,7 @@ class AuthenticationForm extends ApiForm {
// The previous authorization server implementation used the nickname field instead of username, // The previous authorization server implementation used the nickname field instead of username,
// so we keep such behavior // so we keep such behavior
$attribute = $loginForm->getLoginAttribute(); $attribute = strpos($this->username, '@') === false ? 'nickname' : 'email';
if ($attribute === 'username') {
$attribute = 'nickname';
}
// TODO: эта логика дублируется с логикой в SignoutForm // TODO: эта логика дублируется с логикой в SignoutForm

View File

@ -47,10 +47,7 @@ class SignoutForm extends ApiForm {
// The previous authorization server implementation used the nickname field instead of username, // The previous authorization server implementation used the nickname field instead of username,
// so we keep such behavior // so we keep such behavior
$attribute = $loginForm->getLoginAttribute(); $attribute = strpos($this->username, '@') === false ? 'nickname' : 'email';
if ($attribute === 'username') {
$attribute = 'nickname';
}
throw new ForbiddenOperationException("Invalid credentials. Invalid {$attribute} or password."); throw new ForbiddenOperationException("Invalid credentials. Invalid {$attribute} or password.");
} }

View File

@ -1,4 +1,6 @@
<?php <?php
declare(strict_types=1);
namespace api\request; namespace api\request;
use Yii; use Yii;
@ -18,7 +20,14 @@ use yii\web\RequestParserInterface;
*/ */
class RequestParser implements RequestParserInterface { class RequestParser implements RequestParserInterface {
public function parse($rawBody, $contentType) { /**
* @param string $rawBody
* @param string $contentType
*
* @return array
* @throws \yii\web\BadRequestHttpException
*/
public function parse($rawBody, $contentType): array {
if (!empty($_POST)) { if (!empty($_POST)) {
return $_POST; return $_POST;
} }

View File

@ -126,8 +126,8 @@ class ForgotPasswordFormTest extends TestCase {
return new class($params) extends ForgotPasswordForm { return new class($params) extends ForgotPasswordForm {
public $key; public $key;
public function getEmailActivation() { public function getEmailActivation(): ?EmailActivation {
return EmailActivation::findOne($this->key); return EmailActivation::findOne(['key' => $this->key]);
} }
}; };
} }

View File

@ -100,7 +100,7 @@ class RepeatAccountActivationFormTest extends TestCase {
return new class($params) extends RepeatAccountActivationForm { return new class($params) extends RepeatAccountActivationForm {
public $emailKey; public $emailKey;
public function getActivation() { public function getActivation(): ?EmailActivation {
return EmailActivation::findOne($this->emailKey); return EmailActivation::findOne($this->emailKey);
} }
}; };

View File

@ -29,7 +29,6 @@ class ChangeEmailFormTest extends TestCase {
'account_id' => $account->id, 'account_id' => $account->id,
'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION, 'type' => EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION,
])); ]));
/** @noinspection UnserializeExploitsInspection */
$data = unserialize($newEmailConfirmationFixture['_data']); $data = unserialize($newEmailConfirmationFixture['_data']);
$this->assertSame($data['newEmail'], $account->email); $this->assertSame($data['newEmail'], $account->email);
} }

View File

@ -1,52 +0,0 @@
<?php
namespace api\tests\_support\traits;
use api\tests\unit\TestCase;
use api\traits\AccountFinder;
use common\models\Account;
use common\tests\fixtures\AccountFixture;
class AccountFinderTest extends TestCase {
public function _fixtures(): array {
return [
'accounts' => AccountFixture::class,
];
}
public function testGetAccount() {
$model = new AccountFinderTestTestClass();
/** @var Account $account */
$accountFixture = $this->tester->grabFixture('accounts', 'admin');
$model->login = $accountFixture->email;
$account = $model->getAccount();
$this->assertInstanceOf(Account::class, $account);
$this->assertSame($accountFixture->id, $account->id, 'founded account for passed login data');
$model = new AccountFinderTestTestClass();
$model->login = 'unexpected';
$this->assertNull($account = $model->getAccount(), 'null, if account can\'t be found');
}
public function testGetLoginAttribute() {
$model = new AccountFinderTestTestClass();
$model->login = 'erickskrauch@ely.by';
$this->assertSame('email', $model->getLoginAttribute(), 'if login look like email value, then \'email\'');
$model = new AccountFinderTestTestClass();
$model->login = 'erickskrauch';
$this->assertSame('username', $model->getLoginAttribute(), 'username in any other case');
}
}
class AccountFinderTestTestClass {
use AccountFinder;
public $login;
public function getLogin(): string {
return $this->login;
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace api\traits;
use common\models\Account;
trait AccountFinder {
private $account;
abstract public function getLogin(): string;
public function getAccount(): ?Account {
if ($this->account === null) {
$this->account = Account::findOne([$this->getLoginAttribute() => $this->getLogin()]);
}
return $this->account;
}
public function getLoginAttribute(): string {
return strpos($this->getLogin(), '@') ? 'email' : 'username';
}
}

View File

@ -24,7 +24,7 @@ class EmailActivationKeyValidator extends Validator {
public $skipOnEmpty = false; public $skipOnEmpty = false;
public function validateAttribute($model, $attribute) { public function validateAttribute($model, $attribute): void {
$value = $model->$attribute; $value = $model->$attribute;
if (empty($value)) { if (empty($value)) {
$this->addError($model, $attribute, $this->keyRequired); $this->addError($model, $attribute, $this->keyRequired);
@ -49,7 +49,7 @@ class EmailActivationKeyValidator extends Validator {
$query = EmailActivation::find(); $query = EmailActivation::find();
$query->andWhere(['key' => $key]); $query->andWhere(['key' => $key]);
if ($type !== null) { if ($type !== null) {
$query->andWhere(['type' => $type]); $query->withType($type);
} }
return $query->one(); return $query->one();

View File

@ -59,6 +59,10 @@ class Account extends ActiveRecord {
return '{{%accounts}}'; return '{{%accounts}}';
} }
public static function find(): AccountQuery {
return new AccountQuery(self::class);
}
public function behaviors(): array { public function behaviors(): array {
return [ return [
TimestampBehavior::class, TimestampBehavior::class,
@ -88,7 +92,7 @@ class Account extends ActiveRecord {
$this->password_changed_at = time(); $this->password_changed_at = time();
} }
public function getEmailActivations(): ActiveQuery { public function getEmailActivations(): EmailActivationQuery {
return $this->hasMany(EmailActivation::class, ['account_id' => 'id']); return $this->hasMany(EmailActivation::class, ['account_id' => 'id']);
} }

View File

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace common\models;
use yii\db\ActiveQuery;
/**
* @see Account
*/
class AccountQuery extends ActiveQuery {
public function andWhereLogin(string $login): self {
return $this->andWhere([$this->getLoginAttribute($login) => $login]);
}
private function getLoginAttribute(string $login): string {
return strpos($login, '@') ? 'email' : 'username';
}
}

View File

@ -1,4 +1,6 @@
<?php <?php
declare(strict_types=1);
namespace common\models; namespace common\models;
use common\behaviors\DataBehavior; use common\behaviors\DataBehavior;
@ -33,11 +35,15 @@ class EmailActivation extends ActiveRecord {
public const TYPE_CURRENT_EMAIL_CONFIRMATION = 2; public const TYPE_CURRENT_EMAIL_CONFIRMATION = 2;
public const TYPE_NEW_EMAIL_CONFIRMATION = 3; public const TYPE_NEW_EMAIL_CONFIRMATION = 3;
public static function tableName() { public static function tableName(): string {
return '{{%email_activations}}'; return 'email_activations';
} }
public function behaviors() { public static function find(): EmailActivationQuery {
return new EmailActivationQuery(static::class);
}
public function behaviors(): array {
return [ return [
[ [
'class' => TimestampBehavior::class, 'class' => TimestampBehavior::class,
@ -61,7 +67,7 @@ class EmailActivation extends ActiveRecord {
]; ];
} }
public function getAccount() { public function getAccount(): AccountQuery {
return $this->hasOne(Account::class, ['id' => 'account_id']); return $this->hasOne(Account::class, ['id' => 'account_id']);
} }
@ -82,7 +88,7 @@ class EmailActivation extends ActiveRecord {
return new $classMap[$type](); return new $classMap[$type]();
} }
public static function getClassMap() { public static function getClassMap(): array {
return [ return [
self::TYPE_REGISTRATION_EMAIL_CONFIRMATION => confirmations\RegistrationConfirmation::class, self::TYPE_REGISTRATION_EMAIL_CONFIRMATION => confirmations\RegistrationConfirmation::class,
self::TYPE_FORGOT_PASSWORD_KEY => confirmations\ForgotPassword::class, self::TYPE_FORGOT_PASSWORD_KEY => confirmations\ForgotPassword::class,

View File

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace common\models;
use yii\db\ActiveQuery;
/**
* @see EmailActivation
*/
class EmailActivationQuery extends ActiveQuery {
public function withType(int ...$typeId): self {
return $this->andWhere(['type' => $typeId]);
}
}

View File

@ -1,50 +0,0 @@
<?php
namespace common\models;
use yii\helpers\ArrayHelper;
class OauthScopeQuery {
private $scopes;
private $internal;
private $owner;
public function __construct(array $scopes) {
$this->scopes = $scopes;
}
public function onlyPublic(): self {
$this->internal = false;
return $this;
}
public function onlyInternal(): self {
$this->internal = true;
return $this;
}
public function usersScopes(): self {
$this->owner = 'user';
return $this;
}
public function machineScopes(): self {
$this->owner = 'machine';
return $this;
}
public function all(): array {
return ArrayHelper::getColumn(array_filter($this->scopes, function($value) {
$shouldCheckInternal = $this->internal !== null;
$isInternalMatch = $value['internal'] === $this->internal;
$shouldCheckOwner = $this->owner !== null;
$isOwnerMatch = $value['owner'] === $this->owner;
return (!$shouldCheckInternal || $isInternalMatch)
&& (!$shouldCheckOwner || $isOwnerMatch);
}), 'value');
}
}

View File

@ -1,12 +1,19 @@
<?php <?php
declare(strict_types=1);
namespace common\models\confirmations; namespace common\models\confirmations;
use common\models\EmailActivation; use common\models\EmailActivation;
use common\models\EmailActivationQuery;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
class CurrentEmailConfirmation extends EmailActivation { class CurrentEmailConfirmation extends EmailActivation {
public function behaviors() { public static function find(): EmailActivationQuery {
return parent::find()->withType(EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION);
}
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [ return ArrayHelper::merge(parent::behaviors(), [
'expirationBehavior' => [ 'expirationBehavior' => [
'repeatTimeout' => 6 * 60 * 60, // 6h 'repeatTimeout' => 6 * 60 * 60, // 6h
@ -15,7 +22,7 @@ class CurrentEmailConfirmation extends EmailActivation {
]); ]);
} }
public function init() { public function init(): void {
parent::init(); parent::init();
$this->type = EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION; $this->type = EmailActivation::TYPE_CURRENT_EMAIL_CONFIRMATION;
} }

View File

@ -1,12 +1,19 @@
<?php <?php
declare(strict_types=1);
namespace common\models\confirmations; namespace common\models\confirmations;
use common\models\EmailActivation; use common\models\EmailActivation;
use common\models\EmailActivationQuery;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
class ForgotPassword extends EmailActivation { class ForgotPassword extends EmailActivation {
public function behaviors() { public static function find(): EmailActivationQuery {
return parent::find()->withType(EmailActivation::TYPE_FORGOT_PASSWORD_KEY);
}
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [ return ArrayHelper::merge(parent::behaviors(), [
'expirationBehavior' => [ 'expirationBehavior' => [
'repeatTimeout' => 30 * 60, 'repeatTimeout' => 30 * 60,
@ -15,7 +22,7 @@ class ForgotPassword extends EmailActivation {
]); ]);
} }
public function init() { public function init(): void {
parent::init(); parent::init();
$this->type = EmailActivation::TYPE_FORGOT_PASSWORD_KEY; $this->type = EmailActivation::TYPE_FORGOT_PASSWORD_KEY;
} }

View File

@ -1,7 +1,10 @@
<?php <?php
declare(strict_types=1);
namespace common\models\confirmations; namespace common\models\confirmations;
use common\models\EmailActivation; use common\models\EmailActivation;
use common\models\EmailActivationQuery;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
/** /**
@ -10,7 +13,11 @@ use yii\helpers\ArrayHelper;
*/ */
class NewEmailConfirmation extends EmailActivation { class NewEmailConfirmation extends EmailActivation {
public function behaviors() { public static function find(): EmailActivationQuery {
return parent::find()->withType(EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION);
}
public function behaviors(): array {
return ArrayHelper::merge(parent::behaviors(), [ return ArrayHelper::merge(parent::behaviors(), [
'expirationBehavior' => [ 'expirationBehavior' => [
'repeatTimeout' => 5 * 60, 'repeatTimeout' => 5 * 60,
@ -21,7 +28,7 @@ class NewEmailConfirmation extends EmailActivation {
]); ]);
} }
public function init() { public function init(): void {
parent::init(); parent::init();
$this->type = EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION; $this->type = EmailActivation::TYPE_NEW_EMAIL_CONFIRMATION;
} }

View File

@ -1,4 +1,6 @@
<?php <?php
declare(strict_types=1);
namespace common\models\confirmations; namespace common\models\confirmations;
use common\behaviors\DataBehavior; use common\behaviors\DataBehavior;

View File

@ -1,11 +1,18 @@
<?php <?php
declare(strict_types=1);
namespace common\models\confirmations; namespace common\models\confirmations;
use common\models\EmailActivation; use common\models\EmailActivation;
use common\models\EmailActivationQuery;
class RegistrationConfirmation extends EmailActivation { class RegistrationConfirmation extends EmailActivation {
public function init() { public static function find(): EmailActivationQuery {
return parent::find()->withType(EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION);
}
public function init(): void {
parent::init(); parent::init();
$this->type = EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION; $this->type = EmailActivation::TYPE_REGISTRATION_EMAIL_CONFIRMATION;
} }

View File

@ -1,7 +1,10 @@
<?php <?php
declare(strict_types=1);
namespace common\tests\unit\tasks; namespace common\tests\unit\tasks;
use common\models\Account; use common\models\Account;
use common\models\AccountQuery;
use common\models\confirmations\CurrentEmailConfirmation; use common\models\confirmations\CurrentEmailConfirmation;
use common\tasks\SendCurrentEmailConfirmation; use common\tasks\SendCurrentEmailConfirmation;
use common\tests\unit\TestCase; use common\tests\unit\TestCase;
@ -15,13 +18,14 @@ class SendCurrentEmailConfirmationTest extends TestCase {
$account->email = 'mock@ely.by'; $account->email = 'mock@ely.by';
$account->lang = 'id'; $account->lang = 'id';
/** @var \Mockery\Mock|CurrentEmailConfirmation $confirmation */ $accountQuery = $this->createMock(AccountQuery::class);
$confirmation = mock(CurrentEmailConfirmation::class)->makePartial(); $accountQuery->method('findFor')->willReturn($account);
$confirmation = $this->createPartialMock(CurrentEmailConfirmation::class, ['getAccount']);
$confirmation->method('getAccount')->willReturn($accountQuery);
$confirmation->key = 'ABCDEFG'; $confirmation->key = 'ABCDEFG';
$confirmation->shouldReceive('getAccount')->andReturn($account);
$result = SendCurrentEmailConfirmation::createFromConfirmation($confirmation); $result = SendCurrentEmailConfirmation::createFromConfirmation($confirmation);
$this->assertInstanceOf(SendCurrentEmailConfirmation::class, $result);
$this->assertSame('mock-username', $result->username); $this->assertSame('mock-username', $result->username);
$this->assertSame('mock@ely.by', $result->email); $this->assertSame('mock@ely.by', $result->email);
$this->assertSame('ABCDEFG', $result->code); $this->assertSame('ABCDEFG', $result->code);
@ -33,7 +37,7 @@ class SendCurrentEmailConfirmationTest extends TestCase {
$task->email = 'mock@ely.by'; $task->email = 'mock@ely.by';
$task->code = 'GFEDCBA'; $task->code = 'GFEDCBA';
$task->execute(mock(Queue::class)); $task->execute($this->createMock(Queue::class));
$this->tester->canSeeEmailIsSent(1); $this->tester->canSeeEmailIsSent(1);
/** @var \yii\swiftmailer\Message $email */ /** @var \yii\swiftmailer\Message $email */

View File

@ -1,7 +1,10 @@
<?php <?php
declare(strict_types=1);
namespace common\tests\unit\tasks; namespace common\tests\unit\tasks;
use common\models\Account; use common\models\Account;
use common\models\AccountQuery;
use common\models\confirmations\NewEmailConfirmation; use common\models\confirmations\NewEmailConfirmation;
use common\tasks\SendNewEmailConfirmation; use common\tasks\SendNewEmailConfirmation;
use common\tests\unit\TestCase; use common\tests\unit\TestCase;
@ -14,14 +17,15 @@ class SendNewEmailConfirmationTest extends TestCase {
$account->username = 'mock-username'; $account->username = 'mock-username';
$account->lang = 'id'; $account->lang = 'id';
/** @var \Mockery\Mock|NewEmailConfirmation $confirmation */ $accountQuery = $this->createMock(AccountQuery::class);
$confirmation = mock(NewEmailConfirmation::class)->makePartial(); $accountQuery->method('findFor')->willReturn($account);
$confirmation = $this->createPartialMock(NewEmailConfirmation::class, ['getAccount']);
$confirmation->method('getAccount')->willReturn($accountQuery);
$confirmation->setNewEmail('new-email@ely.by');
$confirmation->key = 'ABCDEFG'; $confirmation->key = 'ABCDEFG';
$confirmation->shouldReceive('getAccount')->andReturn($account);
$confirmation->shouldReceive('getNewEmail')->andReturn('new-email@ely.by');
$result = SendNewEmailConfirmation::createFromConfirmation($confirmation); $result = SendNewEmailConfirmation::createFromConfirmation($confirmation);
$this->assertInstanceOf(SendNewEmailConfirmation::class, $result);
$this->assertSame('mock-username', $result->username); $this->assertSame('mock-username', $result->username);
$this->assertSame('new-email@ely.by', $result->email); $this->assertSame('new-email@ely.by', $result->email);
$this->assertSame('ABCDEFG', $result->code); $this->assertSame('ABCDEFG', $result->code);
@ -33,7 +37,7 @@ class SendNewEmailConfirmationTest extends TestCase {
$task->email = 'mock@ely.by'; $task->email = 'mock@ely.by';
$task->code = 'GFEDCBA'; $task->code = 'GFEDCBA';
$task->execute(mock(Queue::class)); $task->execute($this->createMock(Queue::class));
$this->tester->canSeeEmailIsSent(1); $this->tester->canSeeEmailIsSent(1);
/** @var \yii\swiftmailer\Message $email */ /** @var \yii\swiftmailer\Message $email */

View File

@ -5,6 +5,7 @@ namespace common\tests\unit\tasks;
use common\emails\RendererInterface; use common\emails\RendererInterface;
use common\models\Account; use common\models\Account;
use common\models\AccountQuery;
use common\models\confirmations\ForgotPassword; use common\models\confirmations\ForgotPassword;
use common\tasks\SendPasswordRecoveryEmail; use common\tasks\SendPasswordRecoveryEmail;
use common\tests\unit\TestCase; use common\tests\unit\TestCase;
@ -24,10 +25,12 @@ class SendPasswordRecoveryEmailTest extends TestCase {
$account->email = 'mock@ely.by'; $account->email = 'mock@ely.by';
$account->lang = 'id'; $account->lang = 'id';
/** @var \Mockery\Mock|ForgotPassword $confirmation */ $accountQuery = $this->createMock(AccountQuery::class);
$confirmation = mock(ForgotPassword::class)->makePartial(); $accountQuery->method('findFor')->willReturn($account);
$confirmation = $this->createPartialMock(ForgotPassword::class, ['getAccount']);
$confirmation->method('getAccount')->willReturn($accountQuery);
$confirmation->key = 'ABCDEFG'; $confirmation->key = 'ABCDEFG';
$confirmation->shouldReceive('getAccount')->andReturn($account);
$result = SendPasswordRecoveryEmail::createFromConfirmation($confirmation); $result = SendPasswordRecoveryEmail::createFromConfirmation($confirmation);
$this->assertSame('mock-username', $result->username); $this->assertSame('mock-username', $result->username);
@ -51,7 +54,7 @@ class SendPasswordRecoveryEmailTest extends TestCase {
'link' => 'https://account.ely.by/recover-password/ABCDEFG', 'link' => 'https://account.ely.by/recover-password/ABCDEFG',
])->willReturn('mock-template'); ])->willReturn('mock-template');
$task->execute(mock(Queue::class)); $task->execute($this->createMock(Queue::class));
$this->tester->canSeeEmailIsSent(1); $this->tester->canSeeEmailIsSent(1);
/** @var \yii\swiftmailer\Message $email */ /** @var \yii\swiftmailer\Message $email */

View File

@ -5,6 +5,7 @@ namespace common\tests\unit\tasks;
use common\emails\RendererInterface; use common\emails\RendererInterface;
use common\models\Account; use common\models\Account;
use common\models\AccountQuery;
use common\models\confirmations\RegistrationConfirmation; use common\models\confirmations\RegistrationConfirmation;
use common\tasks\SendRegistrationEmail; use common\tasks\SendRegistrationEmail;
use common\tests\unit\TestCase; use common\tests\unit\TestCase;
@ -24,10 +25,12 @@ class SendRegistrationEmailTest extends TestCase {
$account->email = 'mock@ely.by'; $account->email = 'mock@ely.by';
$account->lang = 'ru'; $account->lang = 'ru';
/** @var \Mockery\Mock|RegistrationConfirmation $confirmation */ $accountQuery = $this->createMock(AccountQuery::class);
$confirmation = mock(RegistrationConfirmation::class)->makePartial(); $accountQuery->method('findFor')->willReturn($account);
$confirmation = $this->createPartialMock(RegistrationConfirmation::class, ['getAccount']);
$confirmation->method('getAccount')->willReturn($accountQuery);
$confirmation->key = 'ABCDEFG'; $confirmation->key = 'ABCDEFG';
$confirmation->shouldReceive('getAccount')->andReturn($account);
$result = SendRegistrationEmail::createFromConfirmation($confirmation); $result = SendRegistrationEmail::createFromConfirmation($confirmation);
$this->assertSame('mock-username', $result->username); $this->assertSame('mock-username', $result->username);