Browse Source

Reformat code te be PSR-2 compatible

tags/2.0.0-beta
SonicGD 11 years ago
parent
commit
b5f8a4dc22
  1. 16
      apps/advanced/backend/assets/AppAsset.php
  2. 56
      apps/advanced/backend/config/main.php
  3. 2
      apps/advanced/backend/config/params.php
  4. 125
      apps/advanced/backend/controllers/SiteController.php
  5. 16
      apps/advanced/backend/tests/_config.php
  6. 24
      apps/advanced/backend/tests/acceptance/_config.php
  7. 22
      apps/advanced/backend/tests/acceptance/_console.php
  8. 24
      apps/advanced/backend/tests/functional/_config.php
  9. 22
      apps/advanced/backend/tests/functional/_console.php
  10. 2
      apps/advanced/backend/tests/unit/DbTestCase.php
  11. 2
      apps/advanced/backend/tests/unit/TestCase.php
  12. 24
      apps/advanced/backend/tests/unit/_config.php
  13. 22
      apps/advanced/backend/tests/unit/_console.php
  14. 92
      apps/advanced/backend/views/layouts/main.php
  15. 20
      apps/advanced/backend/views/site/error.php
  16. 66
      apps/advanced/backend/views/site/index.php
  17. 28
      apps/advanced/backend/views/site/login.php
  18. 14
      apps/advanced/common/config/main.php
  19. 6
      apps/advanced/common/config/params.php
  20. 12
      apps/advanced/common/mail/layouts/html.php
  21. 2
      apps/advanced/common/mail/passwordResetToken.php
  22. 113
      apps/advanced/common/models/LoginForm.php
  23. 364
      apps/advanced/common/models/User.php
  24. 16
      apps/advanced/common/tests/_config.php
  25. 74
      apps/advanced/common/tests/_helpers/FixtureHelper.php
  26. 22
      apps/advanced/common/tests/_pages/LoginPage.php
  27. 2
      apps/advanced/common/tests/fixtures/UserFixture.php
  28. 20
      apps/advanced/common/tests/fixtures/data/init_login.php
  29. 49
      apps/advanced/common/tests/templates/fixtures/tbl_user.php
  30. 2
      apps/advanced/common/tests/unit/DbTestCase.php
  31. 2
      apps/advanced/common/tests/unit/TestCase.php
  32. 24
      apps/advanced/common/tests/unit/_config.php
  33. 22
      apps/advanced/common/tests/unit/_console.php
  34. 111
      apps/advanced/common/tests/unit/models/LoginFormTest.php
  35. 38
      apps/advanced/console/config/main.php
  36. 2
      apps/advanced/console/config/params.php
  37. 46
      apps/advanced/console/migrations/m130524_201442_init.php
  38. 16
      apps/advanced/console/tests/_config.php
  39. 2
      apps/advanced/console/tests/unit/DbTestCase.php
  40. 2
      apps/advanced/console/tests/unit/TestCase.php
  41. 20
      apps/advanced/console/tests/unit/_config.php
  42. 22
      apps/advanced/console/tests/unit/_console.php
  43. 8
      apps/advanced/environments/dev/backend/config/main-local.php
  44. 2
      apps/advanced/environments/dev/backend/web/index-test.php
  45. 8
      apps/advanced/environments/dev/backend/web/index.php
  46. 28
      apps/advanced/environments/dev/common/config/main-local.php
  47. 8
      apps/advanced/environments/dev/frontend/config/main-local.php
  48. 2
      apps/advanced/environments/dev/frontend/web/index-test.php
  49. 8
      apps/advanced/environments/dev/frontend/web/index.php
  50. 36
      apps/advanced/environments/index.php
  51. 8
      apps/advanced/environments/prod/backend/web/index.php
  52. 26
      apps/advanced/environments/prod/common/config/main-local.php
  53. 8
      apps/advanced/environments/prod/frontend/web/index.php
  54. 22
      apps/advanced/frontend/assets/AppAsset.php
  55. 52
      apps/advanced/frontend/config/main.php
  56. 2
      apps/advanced/frontend/config/params.php
  57. 298
      apps/advanced/frontend/controllers/SiteController.php
  58. 86
      apps/advanced/frontend/models/ContactForm.php
  59. 82
      apps/advanced/frontend/models/PasswordResetRequestForm.php
  60. 91
      apps/advanced/frontend/models/ResetPasswordForm.php
  61. 67
      apps/advanced/frontend/models/SignupForm.php
  62. 16
      apps/advanced/frontend/tests/_config.php
  63. 2
      apps/advanced/frontend/tests/_pages/AboutPage.php
  64. 24
      apps/advanced/frontend/tests/_pages/ContactPage.php
  65. 24
      apps/advanced/frontend/tests/_pages/SignupPage.php
  66. 20
      apps/advanced/frontend/tests/acceptance/ContactCept.php
  67. 120
      apps/advanced/frontend/tests/acceptance/SignupCest.php
  68. 24
      apps/advanced/frontend/tests/acceptance/_config.php
  69. 22
      apps/advanced/frontend/tests/acceptance/_console.php
  70. 20
      apps/advanced/frontend/tests/functional/ContactCept.php
  71. 158
      apps/advanced/frontend/tests/functional/SignupCest.php
  72. 24
      apps/advanced/frontend/tests/functional/_config.php
  73. 22
      apps/advanced/frontend/tests/functional/_console.php
  74. 2
      apps/advanced/frontend/tests/unit/DbTestCase.php
  75. 2
      apps/advanced/frontend/tests/unit/TestCase.php
  76. 24
      apps/advanced/frontend/tests/unit/_config.php
  77. 22
      apps/advanced/frontend/tests/unit/_console.php
  78. 38
      apps/advanced/frontend/tests/unit/fixtures/data/tbl_user.php
  79. 94
      apps/advanced/frontend/tests/unit/models/ContactFormTest.php
  80. 106
      apps/advanced/frontend/tests/unit/models/PasswordResetRequestFormTest.php
  81. 42
      apps/advanced/frontend/tests/unit/models/ResetPasswordFormTest.php
  82. 70
      apps/advanced/frontend/tests/unit/models/SignupFormTest.php
  83. 100
      apps/advanced/frontend/views/layouts/main.php
  84. 6
      apps/advanced/frontend/views/site/about.php
  85. 40
      apps/advanced/frontend/views/site/contact.php
  86. 20
      apps/advanced/frontend/views/site/error.php
  87. 66
      apps/advanced/frontend/views/site/index.php
  88. 34
      apps/advanced/frontend/views/site/login.php
  89. 24
      apps/advanced/frontend/views/site/requestPasswordResetToken.php
  90. 24
      apps/advanced/frontend/views/site/resetPassword.php
  91. 28
      apps/advanced/frontend/views/site/signup.php
  92. 76
      apps/advanced/frontend/widgets/Alert.php
  93. 166
      apps/advanced/requirements.php
  94. 22
      apps/basic/assets/AppAsset.php
  95. 16
      apps/basic/commands/HelloController.php
  96. 40
      apps/basic/config/console.php
  97. 10
      apps/basic/config/db.php
  98. 2
      apps/basic/config/params.php
  99. 68
      apps/basic/config/web.php
  100. 148
      apps/basic/controllers/SiteController.php
  101. Some files were not shown because too many files have changed in this diff Show More

16
apps/advanced/backend/assets/AppAsset.php

@ -15,12 +15,12 @@ use yii\web\AssetBundle;
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = ['css/site.css'];
public $js = [];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = ['css/site.css'];
public $js = [];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}

56
apps/advanced/backend/config/main.php

@ -1,34 +1,34 @@
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'preload' => ['log'],
'controllerNamespace' => 'backend\controllers',
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'preload' => ['log'],
'controllerNamespace' => 'backend\controllers',
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];

2
apps/advanced/backend/config/params.php

@ -1,4 +1,4 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'adminEmail' => 'admin@example.com',
];

125
apps/advanced/backend/controllers/SiteController.php

@ -12,71 +12,72 @@ use yii\web\VerbFilter;
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionIndex()
{
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}

16
apps/advanced/backend/tests/_config.php

@ -3,12 +3,12 @@
* application configurations shared by all test types
*/
return [
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
];

24
apps/advanced/backend/tests/acceptance/_config.php

@ -1,16 +1,16 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
);

22
apps/advanced/backend/tests/acceptance/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
);

24
apps/advanced/backend/tests/functional/_config.php

@ -5,16 +5,16 @@ $_SERVER['SCRIPT_FILENAME'] = TEST_ENTRY_FILE;
$_SERVER['SCRIPT_NAME'] = TEST_ENTRY_URL;
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
);

22
apps/advanced/backend/tests/functional/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
);

2
apps/advanced/backend/tests/unit/DbTestCase.php

@ -4,5 +4,5 @@ namespace backend\tests\unit;
class DbTestCase extends \yii\codeception\DbTestCase
{
public $appConfig = '@backend/tests/unit/_config.php';
public $appConfig = '@backend/tests/unit/_config.php';
}

2
apps/advanced/backend/tests/unit/TestCase.php

@ -4,5 +4,5 @@ namespace backend\tests\unit;
class TestCase extends \yii\codeception\TestCase
{
public $appConfig = '@backend/tests/unit/_config.php';
public $appConfig = '@backend/tests/unit/_config.php';
}

24
apps/advanced/backend/tests/unit/_config.php

@ -1,16 +1,16 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
);

22
apps/advanced/backend/tests/unit/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
);

92
apps/advanced/backend/views/layouts/main.php

@ -15,57 +15,57 @@ AppAsset::register($this);
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
<meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = [
'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = [
'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= $content ?>
</div>
</div>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">&copy; My Company <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<footer class="footer">
<div class="container">
<p class="pull-left">&copy; My Company <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endBody() ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

20
apps/advanced/backend/views/site/error.php

@ -13,17 +13,17 @@ $this->title = $name;
?>
<div class="site-error">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
</div>

66
apps/advanced/backend/views/site/index.php

@ -6,48 +6,48 @@ $this->title = 'My Yii Application';
?>
<div class="site-index">
<div class="jumbotron">
<h1>Congratulations!</h1>
<div class="jumbotron">
<h1>Congratulations!</h1>
<p class="lead">You have successfully created your Yii-powered application.</p>
<p class="lead">You have successfully created your Yii-powered application.</p>
<p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>
<p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>
<div class="body-content">
<div class="body-content">
<div class="row">
<div class="col-lg-4">
<h2>Heading</h2>
<div class="row">
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/doc/">Yii Documentation &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p><a class="btn btn-default" href="http://www.yiiframework.com/doc/">Yii Documentation &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/forum/">Yii Forum &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p><a class="btn btn-default" href="http://www.yiiframework.com/forum/">Yii Forum &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/extensions/">Yii Extensions &raquo;</a></p>
</div>
</div>
<p><a class="btn btn-default" href="http://www.yiiframework.com/extensions/">Yii Extensions &raquo;</a></p>
</div>
</div>
</div>
</div>
</div>

28
apps/advanced/backend/views/site/login.php

@ -11,20 +11,20 @@ $this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-login">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to login:</p>
<p>Please fill out the following fields to login:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

14
apps/advanced/common/config/main.php

@ -1,10 +1,10 @@
<?php
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'extensions' => require(__DIR__ . '/../../vendor/yiisoft/extensions.php'),
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'extensions' => require(__DIR__ . '/../../vendor/yiisoft/extensions.php'),
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
],
];

6
apps/advanced/common/config/params.php

@ -1,6 +1,6 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'supportEmail' => 'support@example.com',
'user.passwordResetTokenExpire' => 3600,
'adminEmail' => 'admin@example.com',
'supportEmail' => 'support@example.com',
'user.passwordResetTokenExpire' => 3600,
];

12
apps/advanced/common/mail/layouts/html.php

@ -10,14 +10,14 @@ use yii\helpers\Html;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?= Yii::$app->charset ?>" />
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
<meta http-equiv="Content-Type" content="text/html; charset=<?= Yii::$app->charset ?>" />
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

2
apps/advanced/common/mail/passwordResetToken.php

@ -13,4 +13,4 @@ Hello <?= Html::encode($user->username) ?>,
Follow the link below to reset your password:
<?= Html::a(Html::encode($resetLink), $resetLink) ?>
<?= Html::a(Html::encode($resetLink), $resetLink)

113
apps/advanced/common/models/LoginForm.php

@ -9,65 +9,66 @@ use yii\base\Model;
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
private $_user = false;
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
}
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Logs in a user using the provided username and password.
*
* @return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}

364
apps/advanced/common/models/User.php

@ -23,186 +23,186 @@ use yii\web\IdentityInterface;
*/
class User extends ActiveRecord implements IdentityInterface
{
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_USER = 10;
/**
* Creates a new user
*
* @param array $attributes the attributes given by field => value
* @return static|null the newly created model, or null on failure
*/
public static function create($attributes)
{
/** @var User $user */
$user = new static();
$user->setAttributes($attributes);
$user->setPassword($attributes['password']);
$user->generateAuthKey();
if ($user->save()) {
return $user;
} else {
return null;
}
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
],
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::find($id);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::find(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
$expire = \Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int)end($parts);
if ($timestamp + $expire < time()) {
// token expired
return null;
}
return static::find([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Security::validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Security::generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Security::generateRandomKey();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Security::generateRandomKey() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
['role', 'default', 'value' => self::ROLE_USER],
['role', 'in', 'range' => [self::ROLE_USER]],
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique'],
];
}
const STATUS_DELETED = 0;
const STATUS_ACTIVE = 10;
const ROLE_USER = 10;
/**
* Creates a new user
*
* @param array $attributes the attributes given by field => value
* @return static|null the newly created model, or null on failure
*/
public static function create($attributes)
{
/** @var User $user */
$user = new static();
$user->setAttributes($attributes);
$user->setPassword($attributes['password']);
$user->generateAuthKey();
if ($user->save()) {
return $user;
} else {
return null;
}
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
],
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::find($id);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::find(['username' => $username, 'status' => self::STATUS_ACTIVE]);
}
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
$expire = \Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
if ($timestamp + $expire < time()) {
// token expired
return null;
}
return static::find([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Security::validatePassword($password, $this->password_hash);
}
/**
* Generates password hash from password and sets it to the model
*
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Security::generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Security::generateRandomKey();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Security::generateRandomKey() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
['role', 'default', 'value' => self::ROLE_USER],
['role', 'in', 'range' => [self::ROLE_USER]],
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique'],
];
}
}

16
apps/advanced/common/tests/_config.php

@ -3,12 +3,12 @@
* application configurations shared by all test types
*/
return [
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
];

74
apps/advanced/common/tests/_helpers/FixtureHelper.php

@ -14,44 +14,44 @@ use common\tests\fixtures\UserFixture;
class FixtureHelper extends Module
{
/**
* Redeclare visibility because codeception includes all public methods that not starts from "_"
* and not excluded by module settings, in guy class.
*/
use FixtureTrait {
loadFixtures as protected;
fixtures as protected;
globalFixtures as protected;
unloadFixtures as protected;
getFixtures as protected;
getFixture as protected;
}
/**
* Redeclare visibility because codeception includes all public methods that not starts from "_"
* and not excluded by module settings, in guy class.
*/
use FixtureTrait {
loadFixtures as protected;
fixtures as protected;
globalFixtures as protected;
unloadFixtures as protected;
getFixtures as protected;
getFixture as protected;
}
/**
* Method called before any suite tests run. Loads User fixture login user
* to use in acceptance and functional tests.
* @param array $settings
*/
public function _beforeSuite($settings = [])
{
$this->loadFixtures();
}
/**
* Method called before any suite tests run. Loads User fixture login user
* to use in acceptance and functional tests.
* @param array $settings
*/
public function _beforeSuite($settings = [])
{
$this->loadFixtures();
}
/**
* Method is called after all suite tests run
*/
public function _afterSuite()
{
$this->unloadFixtures();
}
/**
* Method is called after all suite tests run
*/
public function _afterSuite()
{
$this->unloadFixtures();
}
protected function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@common/tests/fixtures/data/init_login.php',
],
];
}
protected function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@common/tests/fixtures/data/init_login.php',
],
];
}
}

22
apps/advanced/common/tests/_pages/LoginPage.php

@ -6,16 +6,16 @@ use yii\codeception\BasePage;
class LoginPage extends BasePage
{
public $route = 'site/login';
public $route = 'site/login';
/**
* @param string $username
* @param string $password
*/
public function login($username, $password)
{
$this->guy->fillField('input[name="LoginForm[username]"]', $username);
$this->guy->fillField('input[name="LoginForm[password]"]', $password);
$this->guy->click('login-button');
}
/**
* @param string $username
* @param string $password
*/
public function login($username, $password)
{
$this->guy->fillField('input[name="LoginForm[username]"]', $username);
$this->guy->fillField('input[name="LoginForm[password]"]', $password);
$this->guy->click('login-button');
}
}

2
apps/advanced/common/tests/fixtures/UserFixture.php vendored

@ -6,5 +6,5 @@ use yii\test\ActiveFixture;
class UserFixture extends ActiveFixture
{
public $modelClass = 'common\models\User';
public $modelClass = 'common\models\User';
}

20
apps/advanced/common/tests/fixtures/data/init_login.php vendored

@ -1,14 +1,14 @@
<?php
return [
[
'username' => 'erau',
'auth_key' => 'tUu1qHcde0diwUol3xeI-18MuHkkprQI',
// password_0
'password_hash' => '$2y$13$nJ1WDlBaGcbCdbNC5.5l4.sgy.OMEKCqtDQOdQ2OWpgiKRWYyzzne',
'password_reset_token' => 'RkD_Jw0_8HEedzLk7MM-ZKEFfYR7VbMr_1392559490',
'created_at' => '1392559490',
'updated_at' => '1392559490',
'email' => 'sfriesen@jenkins.info',
],
[
'username' => 'erau',
'auth_key' => 'tUu1qHcde0diwUol3xeI-18MuHkkprQI',
// password_0
'password_hash' => '$2y$13$nJ1WDlBaGcbCdbNC5.5l4.sgy.OMEKCqtDQOdQ2OWpgiKRWYyzzne',
'password_reset_token' => 'RkD_Jw0_8HEedzLk7MM-ZKEFfYR7VbMr_1392559490',
'created_at' => '1392559490',
'updated_at' => '1392559490',
'email' => 'sfriesen@jenkins.info',
],
];

49
apps/advanced/common/tests/templates/fixtures/tbl_user.php

@ -3,26 +3,31 @@
use yii\helpers\Security;
return [
'username' => 'userName',
'auth_key' => function ($fixture, $faker, $index) {
$fixture['auth_key'] = Security::generateRandomKey();
return $fixture;
},
'password_hash' => function ($fixture, $faker, $index) {
$fixture['password_hash'] = Security::generatePasswordHash('password_' . $index);
return $fixture;
},
'password_reset_token' => function ($fixture, $faker, $index) {
$fixture['password_reset_token'] = Security::generateRandomKey() . '_' . time();
return $fixture;
},
'created_at' => function ($fixture, $faker, $index) {
$fixture['created_at'] = time();
return $fixture;
},
'updated_at' => function ($fixture, $faker, $index) {
$fixture['updated_at'] = time();
return $fixture;
},
'email' => 'email',
'username' => 'userName',
'auth_key' => function ($fixture, $faker, $index) {
$fixture['auth_key'] = Security::generateRandomKey();
return $fixture;
},
'password_hash' => function ($fixture, $faker, $index) {
$fixture['password_hash'] = Security::generatePasswordHash('password_' . $index);
return $fixture;
},
'password_reset_token' => function ($fixture, $faker, $index) {
$fixture['password_reset_token'] = Security::generateRandomKey() . '_' . time();
return $fixture;
},
'created_at' => function ($fixture, $faker, $index) {
$fixture['created_at'] = time();
return $fixture;
},
'updated_at' => function ($fixture, $faker, $index) {
$fixture['updated_at'] = time();
return $fixture;
},
'email' => 'email',
];

2
apps/advanced/common/tests/unit/DbTestCase.php

@ -4,5 +4,5 @@ namespace common\tests\unit;
class DbTestCase extends \yii\codeception\DbTestCase
{
public $appConfig = '@frontend/tests/unit/_config.php';
public $appConfig = '@frontend/tests/unit/_config.php';
}

2
apps/advanced/common/tests/unit/TestCase.php

@ -4,5 +4,5 @@ namespace common\tests\unit;
class TestCase extends \yii\codeception\TestCase
{
public $appConfig = '@common/tests/unit/_config.php';
public $appConfig = '@common/tests/unit/_config.php';
}

24
apps/advanced/common/tests/unit/_config.php

@ -1,16 +1,16 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
'id' => 'app-common',
'basePath' => dirname(__DIR__),
]
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
'id' => 'app-common',
'basePath' => dirname(__DIR__),
]
);

22
apps/advanced/common/tests/unit/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
);

111
apps/advanced/common/tests/unit/models/LoginFormTest.php

@ -10,59 +10,60 @@ use yii\helpers\Security;
class LoginFormTest extends TestCase
{
use \Codeception\Specify;
protected function tearDown()
{
Yii::$app->user->logout();
parent::tearDown();
}
public function testLoginNoUser()
{
$model = $this->mockUser(null);
$model->username = 'some_username';
$model->password = 'some_password';
$this->specify('user should not be able to login, when there is no identity', function () use ($model) {
expect('model should not login user', $model->login())->false();
expect('user should not be logged in', Yii::$app->user->isGuest)->true();
});
}
public function testLoginWrongPassword()
{
$model = $this->mockUser(new User(['password_hash' => Security::generatePasswordHash('will-not-match')]));
$model->username = 'demo';
$model->password = 'wrong-password';
$this->specify('user should not be able to login with wrong password', function () use ($model) {
expect('model should not login user', $model->login())->false();
expect('error message should be set', $model->errors)->hasKey('password');
expect('user should not be logged in', Yii::$app->user->isGuest)->true();
});
}
public function testLoginCorrect()
{
$model = $this->mockUser(new User(['password_hash' => Security::generatePasswordHash('demo')]));
$model->username = 'demo';
$model->password = 'demo';
$this->specify('user should be able to login with correct credentials', function () use ($model) {
expect('model should login user', $model->login())->true();
expect('error message should not be set', $model->errors)->hasntKey('password');
expect('user should be logged in', Yii::$app->user->isGuest)->false();
});
}
private function mockUser($user)
{
$loginForm = $this->getMock('common\models\LoginForm', ['getUser']);
$loginForm->expects($this->any())->method('getUser')->will($this->returnValue($user));
return $loginForm;
}
use \Codeception\Specify;
protected function tearDown()
{
Yii::$app->user->logout();
parent::tearDown();
}
public function testLoginNoUser()
{
$model = $this->mockUser(null);
$model->username = 'some_username';
$model->password = 'some_password';
$this->specify('user should not be able to login, when there is no identity', function () use ($model) {
expect('model should not login user', $model->login())->false();
expect('user should not be logged in', Yii::$app->user->isGuest)->true();
});
}
public function testLoginWrongPassword()
{
$model = $this->mockUser(new User(['password_hash' => Security::generatePasswordHash('will-not-match')]));
$model->username = 'demo';
$model->password = 'wrong-password';
$this->specify('user should not be able to login with wrong password', function () use ($model) {
expect('model should not login user', $model->login())->false();
expect('error message should be set', $model->errors)->hasKey('password');
expect('user should not be logged in', Yii::$app->user->isGuest)->true();
});
}
public function testLoginCorrect()
{
$model = $this->mockUser(new User(['password_hash' => Security::generatePasswordHash('demo')]));
$model->username = 'demo';
$model->password = 'demo';
$this->specify('user should be able to login with correct credentials', function () use ($model) {
expect('model should login user', $model->login())->true();
expect('error message should not be set', $model->errors)->hasntKey('password');
expect('user should be logged in', Yii::$app->user->isGuest)->false();
});
}
private function mockUser($user)
{
$loginForm = $this->getMock('common\models\LoginForm', ['getUser']);
$loginForm->expects($this->any())->method('getUser')->will($this->returnValue($user));
return $loginForm;
}
}

38
apps/advanced/console/config/main.php

@ -1,25 +1,25 @@
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];

2
apps/advanced/console/config/params.php

@ -1,4 +1,4 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'adminEmail' => 'admin@example.com',
];

46
apps/advanced/console/migrations/m130524_201442_init.php

@ -4,30 +4,30 @@ use yii\db\Schema;
class m130524_201442_init extends \yii\db\Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable('tbl_user', [
'id' => Schema::TYPE_PK,
'username' => Schema::TYPE_STRING . ' NOT NULL',
'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL',
'password_hash' => Schema::TYPE_STRING . ' NOT NULL',
'password_reset_token' => Schema::TYPE_STRING,
'email' => Schema::TYPE_STRING . ' NOT NULL',
'role' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
$this->createTable('tbl_user', [
'id' => Schema::TYPE_PK,
'username' => Schema::TYPE_STRING . ' NOT NULL',
'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL',
'password_hash' => Schema::TYPE_STRING . ' NOT NULL',
'password_reset_token' => Schema::TYPE_STRING,
'email' => Schema::TYPE_STRING . ' NOT NULL',
'role' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
], $tableOptions);
}
'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
], $tableOptions);
}
public function down()
{
$this->dropTable('tbl_user');
}
public function down()
{
$this->dropTable('tbl_user');
}
}

16
apps/advanced/console/tests/_config.php

@ -3,12 +3,12 @@
* application configurations shared by all test types
*/
return [
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
];

2
apps/advanced/console/tests/unit/DbTestCase.php

@ -4,5 +4,5 @@ namespace console\tests\unit;
class DbTestCase extends \yii\codeception\DbTestCase
{
public $appConfig = '@console/tests/unit/_config.php';
public $appConfig = '@console/tests/unit/_config.php';
}

2
apps/advanced/console/tests/unit/TestCase.php

@ -4,5 +4,5 @@ namespace console\tests\unit;
class TestCase extends \yii\codeception\TestCase
{
public $appConfig = '@console/tests/unit/_config.php';
public $appConfig = '@console/tests/unit/_config.php';
}

20
apps/advanced/console/tests/unit/_config.php

@ -1,14 +1,14 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
);

22
apps/advanced/console/tests/unit/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
);

8
apps/advanced/environments/dev/backend/config/main-local.php

@ -3,10 +3,10 @@
$config = [];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = 'yii\gii\Module';
// configuration adjustments for 'dev' environment
$config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;

2
apps/advanced/environments/dev/backend/web/index-test.php

@ -2,7 +2,7 @@
// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
die('You are not allowed to access this file.');
die('You are not allowed to access this file.');
}
defined('YII_DEBUG') or define('YII_DEBUG', true);

8
apps/advanced/environments/dev/backend/web/index.php

@ -7,10 +7,10 @@ require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/aliases.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);

28
apps/advanced/environments/dev/common/config/main-local.php

@ -1,17 +1,17 @@
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'useFileTransport' => true,
],
],
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
'useFileTransport' => true,
],
],
];

8
apps/advanced/environments/dev/frontend/config/main-local.php

@ -3,10 +3,10 @@
$config = [];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = 'yii\gii\Module';
// configuration adjustments for 'dev' environment
$config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;

2
apps/advanced/environments/dev/frontend/web/index-test.php

@ -2,7 +2,7 @@
// NOTE: Make sure this file is not accessible when deployed to production
if (!in_array(@$_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1'])) {
die('You are not allowed to access this file.');
die('You are not allowed to access this file.');
}
defined('YII_DEBUG') or define('YII_DEBUG', true);

8
apps/advanced/environments/dev/frontend/web/index.php

@ -7,10 +7,10 @@ require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/aliases.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);

36
apps/advanced/environments/index.php

@ -17,22 +17,22 @@
* ```
*/
return [
'Development' => [
'path' => 'dev',
'writable' => [
// handled by composer.json already
],
'executable' => [
'yii',
],
],
'Production' => [
'path' => 'prod',
'writable' => [
// handled by composer.json already
],
'executable' => [
'yii',
],
],
'Development' => [
'path' => 'dev',
'writable' => [
// handled by composer.json already
],
'executable' => [
'yii',
],
],
'Production' => [
'path' => 'prod',
'writable' => [
// handled by composer.json already
],
'executable' => [
'yii',
],
],
];

8
apps/advanced/environments/prod/backend/web/index.php

@ -7,10 +7,10 @@ require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/aliases.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);

26
apps/advanced/environments/prod/common/config/main-local.php

@ -1,16 +1,16 @@
<?php
return [
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
],
],
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
],
],
];

8
apps/advanced/environments/prod/frontend/web/index.php

@ -7,10 +7,10 @@ require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/aliases.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
require(__DIR__ . '/../../common/config/main.php'),
require(__DIR__ . '/../../common/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);

22
apps/advanced/frontend/assets/AppAsset.php

@ -15,15 +15,15 @@ use yii\web\AssetBundle;
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}

52
apps/advanced/frontend/config/main.php

@ -1,32 +1,32 @@
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'frontend\controllers',
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'frontend\controllers',
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];

2
apps/advanced/frontend/config/params.php

@ -1,4 +1,4 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'adminEmail' => 'admin@example.com',
];

298
apps/advanced/frontend/controllers/SiteController.php

@ -17,151 +17,155 @@ use yii\web\VerbFilter;
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => \yii\web\AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
$user = $model->signup();
if ($user) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->getSession()->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => \yii\web\AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
$user = $model->signup();
if ($user) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->getSession()->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
}

86
apps/advanced/frontend/models/ContactForm.php

@ -10,50 +10,50 @@ use yii\base\Model;
*/
class ContactForm extends Model
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* @inheritdoc
*/
public function rules()
{
return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha'],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
// name, email, subject and body are required
[['name', 'email', 'subject', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'verifyCode' => 'Verification Code',
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'verifyCode' => 'Verification Code',
];
}
/**
* Sends an email to the specified email address using the information collected by this model.
*
* @param string $email the target email address
* @return boolean whether the email was sent
*/
public function sendEmail($email)
{
return Yii::$app->mail->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();
}
/**
* Sends an email to the specified email address using the information collected by this model.
*
* @param string $email the target email address
* @return boolean whether the email was sent
*/
public function sendEmail($email)
{
return Yii::$app->mail->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();
}
}

82
apps/advanced/frontend/models/PasswordResetRequestForm.php

@ -9,49 +9,49 @@ use yii\base\Model;
*/
class PasswordResetRequestForm extends Model
{
public $email;
public $email;
/**
* @inheritdoc
*/
public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'exist',
'targetClass' => '\common\models\User',
'filter' => ['status' => User::STATUS_ACTIVE],
'message' => 'There is no user with such email.'
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'exist',
'targetClass' => '\common\models\User',
'filter' => ['status' => User::STATUS_ACTIVE],
'message' => 'There is no user with such email.'
],
];
}
/**
* Sends an email with a link, for resetting the password.
*
* @return boolean whether the email was send
*/
public function sendEmail()
{
/** @var User $user */
$user = User::find([
'status' => User::STATUS_ACTIVE,
'email' => $this->email,
]);
/**
* Sends an email with a link, for resetting the password.
*
* @return boolean whether the email was send
*/
public function sendEmail()
{
/** @var User $user */
$user = User::find([
'status' => User::STATUS_ACTIVE,
'email' => $this->email,
]);
if ($user) {
$user->generatePasswordResetToken();
if ($user->save()) {
return \Yii::$app->mail->compose('passwordResetToken', ['user' => $user])
->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])
->setTo($this->email)
->setSubject('Password reset for ' . \Yii::$app->name)
->send();
}
}
if ($user) {
$user->generatePasswordResetToken();
if ($user->save()) {
return \Yii::$app->mail->compose('passwordResetToken', ['user' => $user])
->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])
->setTo($this->email)
->setSubject('Password reset for ' . \Yii::$app->name)
->send();
}
}
return false;
}
return false;
}
}

91
apps/advanced/frontend/models/ResetPasswordForm.php

@ -11,53 +11,54 @@ use Yii;
*/
class ResetPasswordForm extends Model
{
public $password;
public $password;
/**
* @var \common\models\User
*/
private $_user;
/**
* @var \common\models\User
*/
private $_user;
/**
* Creates a form model given a token.
*
* @param string $token
* @param array $config name-value pairs that will be used to initialize the object properties
* @throws \yii\base\InvalidParamException if token is empty or not valid
*/
public function __construct($token, $config = [])
{
if (empty($token) || !is_string($token)) {
throw new InvalidParamException('Password reset token cannot be blank.');
}
$this->_user = User::findByPasswordResetToken($token);
if (!$this->_user) {
throw new InvalidParamException('Wrong password reset token.');
}
parent::__construct($config);
}
/**
* Creates a form model given a token.
*
* @param string $token
* @param array $config name-value pairs that will be used to initialize the object properties
* @throws \yii\base\InvalidParamException if token is empty or not valid
*/
public function __construct($token, $config = [])
{
if (empty($token) || !is_string($token)) {
throw new InvalidParamException('Password reset token cannot be blank.');
}
$this->_user = User::findByPasswordResetToken($token);
if (!$this->_user) {
throw new InvalidParamException('Wrong password reset token.');
}
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Resets password.
*
* @return boolean if password was reset.
*/
public function resetPassword()
{
$user = $this->_user;
$user->password = $this->password;
$user->removePasswordResetToken();
return $user->save();
}
/**
* Resets password.
*
* @return boolean if password was reset.
*/
public function resetPassword()
{
$user = $this->_user;
$user->password = $this->password;
$user->removePasswordResetToken();
return $user->save();
}
}

67
apps/advanced/frontend/models/SignupForm.php

@ -10,41 +10,42 @@ use Yii;
*/
class SignupForm extends Model
{
public $username;
public $email;
public $password;
public $username;
public $email;
public $password;
/**
* @inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
/**
* @inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if ($this->validate()) {
return User::create($this->attributes);
}
return null;
}
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if ($this->validate()) {
return User::create($this->attributes);
}
return null;
}
}

16
apps/advanced/frontend/tests/_config.php

@ -3,12 +3,12 @@
* application configurations shared by all test types
*/
return [
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
'components' => [
'mail' => [
'useFileTransport' => true,
],
'urlManager' => [
'showScriptName' => true,
],
],
];

2
apps/advanced/frontend/tests/_pages/AboutPage.php

@ -6,5 +6,5 @@ use yii\codeception\BasePage;
class AboutPage extends BasePage
{
public $route = 'site/about';
public $route = 'site/about';
}

24
apps/advanced/frontend/tests/_pages/ContactPage.php

@ -6,17 +6,17 @@ use yii\codeception\BasePage;
class ContactPage extends BasePage
{
public $route = 'site/contact';
public $route = 'site/contact';
/**
* @param array $contactData
*/
public function submit(array $contactData)
{
foreach ($contactData as $field => $value) {
$inputType = $field === 'body' ? 'textarea' : 'input';
$this->guy->fillField($inputType . '[name="ContactForm[' . $field . ']"]', $value);
}
$this->guy->click('contact-button');
}
/**
* @param array $contactData
*/
public function submit(array $contactData)
{
foreach ($contactData as $field => $value) {
$inputType = $field === 'body' ? 'textarea' : 'input';
$this->guy->fillField($inputType . '[name="ContactForm[' . $field . ']"]', $value);
}
$this->guy->click('contact-button');
}
}

24
apps/advanced/frontend/tests/_pages/SignupPage.php

@ -7,17 +7,17 @@ use \yii\codeception\BasePage;
class SignupPage extends BasePage
{
public $route = 'site/signup';
public $route = 'site/signup';
/**
* @param array $signupData
*/
public function submit(array $signupData)
{
foreach ($signupData as $field => $value) {
$inputType = $field === 'body' ? 'textarea' : 'input';
$this->guy->fillField($inputType . '[name="SignupForm[' . $field . ']"]', $value);
}
$this->guy->click('signup-button');
}
/**
* @param array $signupData
*/
public function submit(array $signupData)
{
foreach ($signupData as $field => $value) {
$inputType = $field === 'body' ? 'textarea' : 'input';
$this->guy->fillField($inputType . '[name="SignupForm[' . $field . ']"]', $value);
}
$this->guy->click('signup-button');
}
}

20
apps/advanced/frontend/tests/acceptance/ContactCept.php

@ -21,11 +21,11 @@ $I->see('The verification code is incorrect', '.help-block');
$I->amGoingTo('submit contact form with not correct email');
$contactPage->submit([
'name' => 'tester',
'email' => 'tester.email',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
'name' => 'tester',
'email' => 'tester.email',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
]);
$I->expectTo('see that email adress is wrong');
$I->dontSee('Name cannot be blank', '.help-block');
@ -36,10 +36,10 @@ $I->dontSee('The verification code is incorrect', '.help-block');
$I->amGoingTo('submit contact form with correct data');
$contactPage->submit([
'name' => 'tester',
'email' => 'tester@example.com',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
'name' => 'tester',
'email' => 'tester@example.com',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
]);
$I->see('Thank you for contacting us. We will respond to you as soon as possible.');

120
apps/advanced/frontend/tests/acceptance/SignupCest.php

@ -8,75 +8,75 @@ use common\models\User;
class SignupCest
{
/**
* This method is called before each cest class test method
* @param \Codeception\Event\Test $event
*/
public function _before($event)
{
}
/**
* This method is called before each cest class test method
* @param \Codeception\Event\Test $event
*/
public function _before($event)
{
}
/**
* This method is called after each cest class test method, even if test failed.
* @param \Codeception\Event\Test $event
*/
public function _after($event)
{
User::deleteAll([
'email' => 'tester.email@example.com',
'username' => 'tester',
]);
}
/**
* This method is called after each cest class test method, even if test failed.
* @param \Codeception\Event\Test $event
*/
public function _after($event)
{
User::deleteAll([
'email' => 'tester.email@example.com',
'username' => 'tester',
]);
}
/**
* This method is called when test fails.
* @param \Codeception\Event\Fail $event
*/
public function _fail($event)
{
}
/**
* This method is called when test fails.
* @param \Codeception\Event\Fail $event
*/
public function _fail($event)
{
}
/**
* @param \WebGuy $I
* @param \Codeception\Scenario $scenario
*/
public function testUserSignup($I, $scenario)
{
$I->wantTo('ensure that signup works');
/**
* @param \WebGuy $I
* @param \Codeception\Scenario $scenario
*/
public function testUserSignup($I, $scenario)
{
$I->wantTo('ensure that signup works');
$signupPage = SignupPage::openBy($I);
$I->see('Signup', 'h1');
$I->see('Please fill out the following fields to signup:');
$signupPage = SignupPage::openBy($I);
$I->see('Signup', 'h1');
$I->see('Please fill out the following fields to signup:');
$I->amGoingTo('submit signup form with no data');
$I->amGoingTo('submit signup form with no data');
$signupPage->submit([]);
$signupPage->submit([]);
$I->expectTo('see validation errors');
$I->see('Username cannot be blank.', '.help-block');
$I->see('Email cannot be blank.', '.help-block');
$I->see('Password cannot be blank.', '.help-block');
$I->expectTo('see validation errors');
$I->see('Username cannot be blank.', '.help-block');
$I->see('Email cannot be blank.', '.help-block');
$I->see('Password cannot be blank.', '.help-block');
$I->amGoingTo('submit signup form with not correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email',
'password' => 'tester_password',
]);
$I->amGoingTo('submit signup form with not correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email',
'password' => 'tester_password',
]);
$I->expectTo('see that email address is wrong');
$I->dontSee('Username cannot be blank.', '.help-block');
$I->dontSee('Password cannot be blank.', '.help-block');
$I->see('Email is not a valid email address.', '.help-block');
$I->expectTo('see that email address is wrong');
$I->dontSee('Username cannot be blank.', '.help-block');
$I->dontSee('Password cannot be blank.', '.help-block');
$I->see('Email is not a valid email address.', '.help-block');
$I->amGoingTo('submit signup form with correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email@example.com',
'password' => 'tester_password',
]);
$I->amGoingTo('submit signup form with correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email@example.com',
'password' => 'tester_password',
]);
$I->expectTo('see that user logged in');
$I->seeLink('Logout (tester)');
}
$I->expectTo('see that user logged in');
$I->seeLink('Logout (tester)');
}
}

24
apps/advanced/frontend/tests/acceptance/_config.php

@ -1,16 +1,16 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
);

22
apps/advanced/frontend/tests/acceptance/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_acceptance',
],
],
]
);

20
apps/advanced/frontend/tests/functional/ContactCept.php

@ -21,11 +21,11 @@ $I->see('The verification code is incorrect', '.help-block');
$I->amGoingTo('submit contact form with not correct email');
$contactPage->submit([
'name' => 'tester',
'email' => 'tester.email',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
'name' => 'tester',
'email' => 'tester.email',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
]);
$I->expectTo('see that email adress is wrong');
$I->dontSee('Name cannot be blank', '.help-block');
@ -36,10 +36,10 @@ $I->dontSee('The verification code is incorrect', '.help-block');
$I->amGoingTo('submit contact form with correct data');
$contactPage->submit([
'name' => 'tester',
'email' => 'tester@example.com',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
'name' => 'tester',
'email' => 'tester@example.com',
'subject' => 'test subject',
'body' => 'test content',
'verifyCode' => 'testme',
]);
$I->see('Thank you for contacting us. We will respond to you as soon as possible.');

158
apps/advanced/frontend/tests/functional/SignupCest.php

@ -8,83 +8,83 @@ use common\models\User;
class SignupCest
{
/**
* This method is called before each cest class test method
* @param \Codeception\Event\Test $event
*/
public function _before($event)
{
}
/**
* This method is called after each cest class test method, even if test failed.
* @param \Codeception\Event\Test $event
*/
public function _after($event)
{
User::deleteAll([
'email' => 'tester.email@example.com',
'username' => 'tester',
]);
}
/**
* This method is called when test fails.
* @param \Codeception\Event\Fail $event
*/
public function _fail($event)
{
}
/**
*
* @param \TestGuy $I
* @param \Codeception\Scenario $scenario
*/
public function testUserSignup($I, $scenario)
{
$I->wantTo('ensure that signup works');
$signupPage = SignupPage::openBy($I);
$I->see('Signup', 'h1');
$I->see('Please fill out the following fields to signup:');
$I->amGoingTo('submit signup form with no data');
$signupPage->submit([]);
$I->expectTo('see validation errors');
$I->see('Username cannot be blank.', '.help-block');
$I->see('Email cannot be blank.', '.help-block');
$I->see('Password cannot be blank.', '.help-block');
$I->amGoingTo('submit signup form with not correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email',
'password' => 'tester_password',
]);
$I->expectTo('see that email address is wrong');
$I->dontSee('Username cannot be blank.', '.help-block');
$I->dontSee('Password cannot be blank.', '.help-block');
$I->see('Email is not a valid email address.', '.help-block');
$I->amGoingTo('submit signup form with correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email@example.com',
'password' => 'tester_password',
]);
$I->expectTo('see that user is created');
$I->seeRecord('common\models\User', [
'username' => 'tester',
'email' => 'tester.email@example.com',
]);
$I->expectTo('see that user logged in');
$I->seeLink('Logout (tester)');
}
/**
* This method is called before each cest class test method
* @param \Codeception\Event\Test $event
*/
public function _before($event)
{
}
/**
* This method is called after each cest class test method, even if test failed.
* @param \Codeception\Event\Test $event
*/
public function _after($event)
{
User::deleteAll([
'email' => 'tester.email@example.com',
'username' => 'tester',
]);
}
/**
* This method is called when test fails.
* @param \Codeception\Event\Fail $event
*/
public function _fail($event)
{
}
/**
*
* @param \TestGuy $I
* @param \Codeception\Scenario $scenario
*/
public function testUserSignup($I, $scenario)
{
$I->wantTo('ensure that signup works');
$signupPage = SignupPage::openBy($I);
$I->see('Signup', 'h1');
$I->see('Please fill out the following fields to signup:');
$I->amGoingTo('submit signup form with no data');
$signupPage->submit([]);
$I->expectTo('see validation errors');
$I->see('Username cannot be blank.', '.help-block');
$I->see('Email cannot be blank.', '.help-block');
$I->see('Password cannot be blank.', '.help-block');
$I->amGoingTo('submit signup form with not correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email',
'password' => 'tester_password',
]);
$I->expectTo('see that email address is wrong');
$I->dontSee('Username cannot be blank.', '.help-block');
$I->dontSee('Password cannot be blank.', '.help-block');
$I->see('Email is not a valid email address.', '.help-block');
$I->amGoingTo('submit signup form with correct email');
$signupPage->submit([
'username' => 'tester',
'email' => 'tester.email@example.com',
'password' => 'tester_password',
]);
$I->expectTo('see that user is created');
$I->seeRecord('common\models\User', [
'username' => 'tester',
'email' => 'tester.email@example.com',
]);
$I->expectTo('see that user logged in');
$I->seeLink('Logout (tester)');
}
}

24
apps/advanced/frontend/tests/functional/_config.php

@ -5,16 +5,16 @@ $_SERVER['SCRIPT_FILENAME'] = TEST_ENTRY_FILE;
$_SERVER['SCRIPT_NAME'] = TEST_ENTRY_URL;
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
);

22
apps/advanced/frontend/tests/functional/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_functional',
],
],
]
);

2
apps/advanced/frontend/tests/unit/DbTestCase.php

@ -4,5 +4,5 @@ namespace frontend\tests\unit;
class DbTestCase extends \yii\codeception\DbTestCase
{
public $appConfig = '@frontend/tests/unit/_config.php';
public $appConfig = '@frontend/tests/unit/_config.php';
}

2
apps/advanced/frontend/tests/unit/TestCase.php

@ -4,5 +4,5 @@ namespace frontend\tests\unit;
class TestCase extends \yii\codeception\TestCase
{
public $appConfig = '@frontend/tests/unit/_config.php';
public $appConfig = '@frontend/tests/unit/_config.php';
}

24
apps/advanced/frontend/tests/unit/_config.php

@ -1,16 +1,16 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../config/main.php'),
require(__DIR__ . '/../../config/main-local.php'),
require(__DIR__ . '/../_config.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
);

22
apps/advanced/frontend/tests/unit/_console.php

@ -1,15 +1,15 @@
<?php
return yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
require(__DIR__ . '/../../../common/config/main.php'),
require(__DIR__ . '/../../../common/config/main-local.php'),
require(__DIR__ . '/../../../console/config/main.php'),
require(__DIR__ . '/../../../console/config/main-local.php'),
[
'components' => [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=yii2_advanced_unit',
],
],
]
);

38
apps/advanced/frontend/tests/unit/fixtures/data/tbl_user.php

@ -1,23 +1,23 @@
<?php
return [
[
'username' => 'okirlin',
'auth_key' => 'iwTNae9t34OmnK6l4vT4IeaTk-YWI2Rv',
'password_hash' => '$2y$13$CXT0Rkle1EMJ/c1l5bylL.EylfmQ39O5JlHJVFpNn618OUS1HwaIi',
'password_reset_token' => 't5GU9NwpuGYSfb7FEZMAxqtuz2PkEvv_1391885313',
'created_at' => '1391885313',
'updated_at' => '1391885313',
'email' => 'brady.renner@rutherford.com',
],
[
'username' => 'troy.becker',
'auth_key' => 'EdKfXrx88weFMV0vIxuTMWKgfK2tS3Lp',
'password_hash' => '$2y$13$g5nv41Px7VBqhS3hVsVN2.MKfgT3jFdkXEsMC4rQJLfaMa7VaJqL2',
'password_reset_token' => '4BSNyiZNAuxjs5Mty990c47sVrgllIi_1391885313',
'created_at' => '1391885313',
'updated_at' => '1391885313',
'email' => 'nicolas.dianna@hotmail.com',
'status' => '0',
],
[
'username' => 'okirlin',
'auth_key' => 'iwTNae9t34OmnK6l4vT4IeaTk-YWI2Rv',
'password_hash' => '$2y$13$CXT0Rkle1EMJ/c1l5bylL.EylfmQ39O5JlHJVFpNn618OUS1HwaIi',
'password_reset_token' => 't5GU9NwpuGYSfb7FEZMAxqtuz2PkEvv_1391885313',
'created_at' => '1391885313',
'updated_at' => '1391885313',
'email' => 'brady.renner@rutherford.com',
],
[
'username' => 'troy.becker',
'auth_key' => 'EdKfXrx88weFMV0vIxuTMWKgfK2tS3Lp',
'password_hash' => '$2y$13$g5nv41Px7VBqhS3hVsVN2.MKfgT3jFdkXEsMC4rQJLfaMa7VaJqL2',
'password_reset_token' => '4BSNyiZNAuxjs5Mty990c47sVrgllIi_1391885313',
'created_at' => '1391885313',
'updated_at' => '1391885313',
'email' => 'nicolas.dianna@hotmail.com',
'status' => '0',
],
];

94
apps/advanced/frontend/tests/unit/models/ContactFormTest.php

@ -9,51 +9,51 @@ use frontend\models\ContactForm;
class ContactFormTest extends TestCase
{
use \Codeception\Specify;
protected function setUp()
{
parent::setUp();
Yii::$app->mail->fileTransportCallback = function ($mailer, $message) {
return 'testing_message.eml';
};
}
protected function tearDown()
{
unlink($this->getMessageFile());
parent::tearDown();
}
public function testContact()
{
$model = new ContactForm();
$model->attributes = [
'name' => 'Tester',
'email' => 'tester@example.com',
'subject' => 'very important letter subject',
'body' => 'body of current message',
];
$model->sendEmail('admin@example.com');
$this->specify('email should be send', function () {
expect('email file should exist', file_exists($this->getMessageFile()))->true();
});
$this->specify('message should contain correct data', function () use ($model) {
$emailMessage = file_get_contents($this->getMessageFile());
expect('email should contain user name', $emailMessage)->contains($model->name);
expect('email should contain sender email', $emailMessage)->contains($model->email);
expect('email should contain subject', $emailMessage)->contains($model->subject);
expect('email should contain body', $emailMessage)->contains($model->body);
});
}
private function getMessageFile()
{
return Yii::getAlias(Yii::$app->mail->fileTransportPath) . '/testing_message.eml';
}
use \Codeception\Specify;
protected function setUp()
{
parent::setUp();
Yii::$app->mail->fileTransportCallback = function ($mailer, $message) {
return 'testing_message.eml';
};
}
protected function tearDown()
{
unlink($this->getMessageFile());
parent::tearDown();
}
public function testContact()
{
$model = new ContactForm();
$model->attributes = [
'name' => 'Tester',
'email' => 'tester@example.com',
'subject' => 'very important letter subject',
'body' => 'body of current message',
];
$model->sendEmail('admin@example.com');
$this->specify('email should be send', function () {
expect('email file should exist', file_exists($this->getMessageFile()))->true();
});
$this->specify('message should contain correct data', function () use ($model) {
$emailMessage = file_get_contents($this->getMessageFile());
expect('email should contain user name', $emailMessage)->contains($model->name);
expect('email should contain sender email', $emailMessage)->contains($model->email);
expect('email should contain subject', $emailMessage)->contains($model->subject);
expect('email should contain body', $emailMessage)->contains($model->body);
});
}
private function getMessageFile()
{
return Yii::getAlias(Yii::$app->mail->fileTransportPath) . '/testing_message.eml';
}
}

106
apps/advanced/frontend/tests/unit/models/PasswordResetRequestFormTest.php

@ -10,69 +10,69 @@ use common\models\User;
class PasswordResetRequestFormTest extends DbTestCase
{
use \Codeception\Specify;
use \Codeception\Specify;
protected function setUp()
{
parent::setUp();
Yii::$app->mail->fileTransportCallback = function ($mailer, $message) {
return 'testing_message.eml';
};
}
protected function setUp()
{
parent::setUp();
Yii::$app->mail->fileTransportCallback = function ($mailer, $message) {
return 'testing_message.eml';
};
}
protected function tearDown()
{
@unlink($this->getMessageFile());
parent::tearDown();
}
protected function tearDown()
{
@unlink($this->getMessageFile());
parent::tearDown();
}
public function testSendEmailWrongUser()
{
$this->specify('no user with such email, message should not be send', function () {
$model = new PasswordResetRequestForm();
$model->email = 'not-existing-email@example.com';
public function testSendEmailWrongUser()
{
$this->specify('no user with such email, message should not be send', function () {
$model = new PasswordResetRequestForm();
$model->email = 'not-existing-email@example.com';
expect('email not send', $model->sendEmail())->false();
});
expect('email not send', $model->sendEmail())->false();
});
$this->specify('user is not active, message should not be send', function () {
$model = new PasswordResetRequestForm();
$model->email = $this->user[1]['email'];
$this->specify('user is not active, message should not be send', function () {
$model = new PasswordResetRequestForm();
$model->email = $this->user[1]['email'];
expect('email not send', $model->sendEmail())->false();
});
}
expect('email not send', $model->sendEmail())->false();
});
}
public function testSendEmailCorrectUser()
{
$model = new PasswordResetRequestForm();
$model->email = $this->user[0]['email'];
$user = User::find(['password_reset_token' => $this->user[0]['password_reset_token']]);
public function testSendEmailCorrectUser()
{
$model = new PasswordResetRequestForm();
$model->email = $this->user[0]['email'];
$user = User::find(['password_reset_token' => $this->user[0]['password_reset_token']]);
expect('email sent', $model->sendEmail())->true();
expect('user has valid token', $user->password_reset_token)->notNull();
expect('email sent', $model->sendEmail())->true();
expect('user has valid token', $user->password_reset_token)->notNull();
$this->specify('message has correct format', function () use ($model) {
expect('message file exists', file_exists($this->getMessageFile()))->true();
$this->specify('message has correct format', function () use ($model) {
expect('message file exists', file_exists($this->getMessageFile()))->true();
$message = file_get_contents($this->getMessageFile());
expect('message "from" is correct', $message)->contains(Yii::$app->params['supportEmail']);
expect('message "to" is correct', $message)->contains($model->email);
});
}
$message = file_get_contents($this->getMessageFile());
expect('message "from" is correct', $message)->contains(Yii::$app->params['supportEmail']);
expect('message "to" is correct', $message)->contains($model->email);
});
}
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@frontend/tests/unit/fixtures/data/tbl_user.php'
],
];
}
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@frontend/tests/unit/fixtures/data/tbl_user.php'
],
];
}
private function getMessageFile()
{
return Yii::getAlias(Yii::$app->mail->fileTransportPath) . '/testing_message.eml';
}
private function getMessageFile()
{
return Yii::getAlias(Yii::$app->mail->fileTransportPath) . '/testing_message.eml';
}
}

42
apps/advanced/frontend/tests/unit/models/ResetPasswordFormTest.php

@ -9,28 +9,28 @@ use frontend\models\ResetPasswordForm;
class ResetPasswordFormTest extends DbTestCase
{
use \Codeception\Specify;
use \Codeception\Specify;
public function testResetPassword()
{
$this->specify('wrong reset token', function () {
$this->setExpectedException('\Exception', 'Wrong password reset token.');
new ResetPasswordForm('notexistingtoken_1391882543');
});
public function testResetPassword()
{
$this->specify('wrong reset token', function () {
$this->setExpectedException('\Exception', 'Wrong password reset token.');
new ResetPasswordForm('notexistingtoken_1391882543');
});
$this->specify('not correct token', function () {
$this->setExpectedException('yii\base\InvalidParamException', 'Password reset token cannot be blank.');
new ResetPasswordForm('');
});
}
$this->specify('not correct token', function () {
$this->setExpectedException('yii\base\InvalidParamException', 'Password reset token cannot be blank.');
new ResetPasswordForm('');
});
}
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@frontend/tests/unit/fixtures/data/tbl_user.php'
],
];
}
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@frontend/tests/unit/fixtures/data/tbl_user.php'
],
];
}
}

70
apps/advanced/frontend/tests/unit/models/SignupFormTest.php

@ -8,39 +8,39 @@ use common\tests\fixtures\UserFixture;
class SignupFormTest extends DbTestCase
{
use \Codeception\Specify;
public function testCorrectSignup()
{
$model = $this->getMock('frontend\models\SignupForm', ['validate']);
$model->expects($this->once())->method('validate')->will($this->returnValue(true));
$model->username = 'some_username';
$model->email = 'some_email@example.com';
$model->password = 'some_password';
$user = $model->signup();
$this->assertInstanceOf('common\models\User', $user);
expect('username should be correct', $user->username)->equals('some_username');
expect('email should be correct', $user->email)->equals('some_email@example.com');
expect('password should be correct', $user->validatePassword('some_password'))->true();
}
public function testNotCorrectSignup()
{
$model = $this->getMock('frontend\models\SignupForm', ['validate']);
$model->expects($this->once())->method('validate')->will($this->returnValue(false));
expect('user should not be created', $model->signup())->null();
}
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => false, //do not load test data, only table cleanup
],
];
}
use \Codeception\Specify;
public function testCorrectSignup()
{
$model = $this->getMock('frontend\models\SignupForm', ['validate']);
$model->expects($this->once())->method('validate')->will($this->returnValue(true));
$model->username = 'some_username';
$model->email = 'some_email@example.com';
$model->password = 'some_password';
$user = $model->signup();
$this->assertInstanceOf('common\models\User', $user);
expect('username should be correct', $user->username)->equals('some_username');
expect('email should be correct', $user->email)->equals('some_email@example.com');
expect('password should be correct', $user->validatePassword('some_password'))->true();
}
public function testNotCorrectSignup()
{
$model = $this->getMock('frontend\models\SignupForm', ['validate']);
$model->expects($this->once())->method('validate')->will($this->returnValue(false));
expect('user should not be created', $model->signup())->null();
}
public function fixtures()
{
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => false, //do not load test data, only table cleanup
],
];
}
}

100
apps/advanced/frontend/views/layouts/main.php

@ -16,61 +16,61 @@ AppAsset::register($this);
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
<meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = [
'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<?php $this->beginBody() ?>
<div class="wrap">
<?php
NavBar::begin([
'brandLabel' => 'My Company',
'brandUrl' => Yii::$app->homeUrl,
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [
['label' => 'Home', 'url' => ['/site/index']],
['label' => 'About', 'url' => ['/site/about']],
['label' => 'Contact', 'url' => ['/site/contact']],
];
if (Yii::$app->user->isGuest) {
$menuItems[] = ['label' => 'Signup', 'url' => ['/site/signup']];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
} else {
$menuItems[] = [
'label' => 'Logout (' . Yii::$app->user->identity->username . ')',
'url' => ['/site/logout'],
'linkOptions' => ['data-method' => 'post']
];
}
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => $menuItems,
]);
NavBar::end();
?>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>
</div>
<div class="container">
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
</div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">&copy; My Company <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<footer class="footer">
<div class="container">
<p class="pull-left">&copy; My Company <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endBody() ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

6
apps/advanced/frontend/views/site/about.php

@ -8,9 +8,9 @@ $this->title = 'About';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-about">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<p>This is the About page. You may modify the following file to customize its content:</p>
<p>This is the About page. You may modify the following file to customize its content:</p>
<code><?= __FILE__ ?></code>
<code><?= __FILE__ ?></code>
</div>

40
apps/advanced/frontend/views/site/contact.php

@ -12,27 +12,27 @@ $this->title = 'Contact';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-contact">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>
<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'subject') ?>
<?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

20
apps/advanced/frontend/views/site/error.php

@ -13,17 +13,17 @@ $this->title = $name;
?>
<div class="site-error">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
</div>

66
apps/advanced/frontend/views/site/index.php

@ -6,48 +6,48 @@ $this->title = 'My Yii Application';
?>
<div class="site-index">
<div class="jumbotron">
<h1>Congratulations!</h1>
<div class="jumbotron">
<h1>Congratulations!</h1>
<p class="lead">You have successfully created your Yii-powered application.</p>
<p class="lead">You have successfully created your Yii-powered application.</p>
<p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>
<p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>
</div>
<div class="body-content">
<div class="body-content">
<div class="row">
<div class="col-lg-4">
<h2>Heading</h2>
<div class="row">
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/doc/">Yii Documentation &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p><a class="btn btn-default" href="http://www.yiiframework.com/doc/">Yii Documentation &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/forum/">Yii Forum &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p><a class="btn btn-default" href="http://www.yiiframework.com/forum/">Yii Forum &raquo;</a></p>
</div>
<div class="col-lg-4">
<h2>Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur.</p>
<p><a class="btn btn-default" href="http://www.yiiframework.com/extensions/">Yii Extensions &raquo;</a></p>
</div>
</div>
<p><a class="btn btn-default" href="http://www.yiiframework.com/extensions/">Yii Extensions &raquo;</a></p>
</div>
</div>
</div>
</div>
</div>

34
apps/advanced/frontend/views/site/login.php

@ -11,23 +11,23 @@ $this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-login">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to login:</p>
<p>Please fill out the following fields to login:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div style="color:#999;margin:1em 0">
If you forgot your password you can <?= Html::a('reset it', ['site/request-password-reset']) ?>.
</div>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div style="color:#999;margin:1em 0">
If you forgot your password you can <?= Html::a('reset it', ['site/request-password-reset']) ?>.
</div>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

24
apps/advanced/frontend/views/site/requestPasswordResetToken.php

@ -11,18 +11,18 @@ $this->title = 'Request password reset';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-request-password-reset">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out your email. A link to reset password will be sent there.</p>
<p>Please fill out your email. A link to reset password will be sent there.</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'request-password-reset-form']); ?>
<?= $form->field($model, 'email') ?>
<div class="form-group">
<?= Html::submitButton('Send', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'request-password-reset-form']); ?>
<?= $form->field($model, 'email') ?>
<div class="form-group">
<?= Html::submitButton('Send', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

24
apps/advanced/frontend/views/site/resetPassword.php

@ -11,18 +11,18 @@ $this->title = 'Reset password';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-reset-password">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<p>Please choose your new password:</p>
<p>Please choose your new password:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'reset-password-form']); ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'reset-password-form']); ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

28
apps/advanced/frontend/views/site/signup.php

@ -11,20 +11,20 @@ $this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to signup:</p>
<p>Please fill out the following fields to signup:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>

76
apps/advanced/frontend/widgets/Alert.php

@ -20,49 +20,49 @@ namespace frontend\widgets;
*/
class Alert extends \yii\bootstrap\Widget
{
/**
* @var array the alert types configuration for the flash messages.
* This array is setup as $key => $value, where:
* - $key is the name of the session flash variable
* - $value is the bootstrap alert type (i.e. danger, success, info, warning)
*/
public $alertTypes = [
'error' => 'alert-danger',
'danger' => 'alert-danger',
'success' => 'alert-success',
'info' => 'alert-info',
'warning' => 'alert-warning'
];
/**
* @var array the alert types configuration for the flash messages.
* This array is setup as $key => $value, where:
* - $key is the name of the session flash variable
* - $value is the bootstrap alert type (i.e. danger, success, info, warning)
*/
public $alertTypes = [
'error' => 'alert-danger',
'danger' => 'alert-danger',
'success' => 'alert-success',
'info' => 'alert-info',
'warning' => 'alert-warning'
];
/**
* @var array the options for rendering the close button tag.
*/
public $closeButton = [];
/**
* @var array the options for rendering the close button tag.
*/
public $closeButton = [];
public function init()
{
parent::init();
public function init()
{
parent::init();
$session = \Yii::$app->getSession();
$flashes = $session->getAllFlashes();
$appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
$session = \Yii::$app->getSession();
$flashes = $session->getAllFlashes();
$appendCss = isset($this->options['class']) ? ' ' . $this->options['class'] : '';
foreach ($flashes as $type => $message) {
if (isset($this->alertTypes[$type])) {
/* initialize css class for each alert box */
$this->options['class'] = $this->alertTypes[$type] . $appendCss;
foreach ($flashes as $type => $message) {
if (isset($this->alertTypes[$type])) {
/* initialize css class for each alert box */
$this->options['class'] = $this->alertTypes[$type] . $appendCss;
/* assign unique id to each alert box */
$this->options['id'] = $this->getId() . '-' . $type;
/* assign unique id to each alert box */
$this->options['id'] = $this->getId() . '-' . $type;
echo \yii\bootstrap\Alert::widget([
'body' => $message,
'closeButton' => $this->closeButton,
'options' => $this->options,
]);
echo \yii\bootstrap\Alert::widget([
'body' => $message,
'closeButton' => $this->closeButton,
'options' => $this->options,
]);
$session->removeFlash($type);
}
}
}
$session->removeFlash($type);
}
}
}
}

166
apps/advanced/requirements.php

@ -14,10 +14,10 @@
$frameworkPath = dirname(__FILE__) . '/vendor/yiisoft/yii2';
if (!is_dir($frameworkPath)) {
echo '<h1>Error</h1>';
echo '<p><strong>The path to yii framework seems to be incorrect.</strong></p>';
echo '<p>You need to install Yii framework via composer or adjust the framework path in file <abbr title="' . __FILE__ . '">' . basename(__FILE__) . '</abbr>.</p>';
echo '<p>Please refer to the <abbr title="' . dirname(__FILE__) . '/README.md">README</abbr> on how to install Yii.</p>';
echo '<h1>Error</h1>';
echo '<p><strong>The path to yii framework seems to be incorrect.</strong></p>';
echo '<p>You need to install Yii framework via composer or adjust the framework path in file <abbr title="' . __FILE__ . '">' . basename(__FILE__) . '</abbr>.</p>';
echo '<p>Please refer to the <abbr title="' . dirname(__FILE__) . '/README.md">README</abbr> on how to install Yii.</p>';
}
require_once($frameworkPath . '/requirements/YiiRequirementChecker.php');
@ -27,84 +27,84 @@ $requirementsChecker = new YiiRequirementChecker();
* Adjust requirements according to your application specifics.
*/
$requirements = array(
// Database :
array(
'name' => 'PDO extension',
'mandatory' => true,
'condition' => extension_loaded('pdo'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
),
array(
'name' => 'PDO SQLite extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_sqlite'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
'memo' => 'Required for SQLite database.',
),
array(
'name' => 'PDO MySQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_mysql'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
'memo' => 'Required for MySQL database.',
),
array(
'name' => 'PDO PostgreSQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_pgsql'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
'memo' => 'Required for PostgreSQL database.',
),
// Cache :
array(
'name' => 'Memcache extension',
'mandatory' => false,
'condition' => extension_loaded('memcache') || extension_loaded('memcached'),
'by' => '<a href="http://www.yiiframework.com/doc/api/CMemCache">CMemCache</a>',
'memo' => extension_loaded('memcached') ? 'To use memcached set <a href="http://www.yiiframework.com/doc/api/CMemCache#useMemcached-detail">CMemCache::useMemcached</a> to <code>true</code>.' : ''
),
array(
'name' => 'APC extension',
'mandatory' => false,
'condition' => extension_loaded('apc'),
'by' => '<a href="http://www.yiiframework.com/doc/api/CApcCache">CApcCache</a>',
),
// Additional PHP extensions :
array(
'name' => 'Mcrypt extension',
'mandatory' => false,
'condition' => extension_loaded('mcrypt'),
'by' => '<a href="http://www.yiiframework.com/doc/api/CSecurityManager">CSecurityManager</a>',
'memo' => 'Required by encrypt and decrypt methods.'
),
// PHP ini :
'phpSafeMode' => array(
'name' => 'PHP safe mode',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("safe_mode"),
'by' => 'File uploading and console command execution',
'memo' => '"safe_mode" should be disabled at php.ini',
),
'phpExposePhp' => array(
'name' => 'Expose PHP',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("expose_php"),
'by' => 'Security reasons',
'memo' => '"expose_php" should be disabled at php.ini',
),
'phpAllowUrlInclude' => array(
'name' => 'PHP allow url include',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("allow_url_include"),
'by' => 'Security reasons',
'memo' => '"allow_url_include" should be disabled at php.ini',
),
'phpSmtp' => array(
'name' => 'PHP mail SMTP',
'mandatory' => false,
'condition' => strlen(ini_get('SMTP'))>0,
'by' => 'Email sending',
'memo' => 'PHP mail SMTP server required',
),
// Database :
array(
'name' => 'PDO extension',
'mandatory' => true,
'condition' => extension_loaded('pdo'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
),
array(
'name' => 'PDO SQLite extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_sqlite'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
'memo' => 'Required for SQLite database.',
),
array(
'name' => 'PDO MySQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_mysql'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
'memo' => 'Required for MySQL database.',
),
array(
'name' => 'PDO PostgreSQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_pgsql'),
'by' => 'All <a href="http://www.yiiframework.com/doc/api/#system.db">DB-related classes</a>',
'memo' => 'Required for PostgreSQL database.',
),
// Cache :
array(
'name' => 'Memcache extension',
'mandatory' => false,
'condition' => extension_loaded('memcache') || extension_loaded('memcached'),
'by' => '<a href="http://www.yiiframework.com/doc/api/CMemCache">CMemCache</a>',
'memo' => extension_loaded('memcached') ? 'To use memcached set <a href="http://www.yiiframework.com/doc/api/CMemCache#useMemcached-detail">CMemCache::useMemcached</a> to <code>true</code>.' : ''
),
array(
'name' => 'APC extension',
'mandatory' => false,
'condition' => extension_loaded('apc'),
'by' => '<a href="http://www.yiiframework.com/doc/api/CApcCache">CApcCache</a>',
),
// Additional PHP extensions :
array(
'name' => 'Mcrypt extension',
'mandatory' => false,
'condition' => extension_loaded('mcrypt'),
'by' => '<a href="http://www.yiiframework.com/doc/api/CSecurityManager">CSecurityManager</a>',
'memo' => 'Required by encrypt and decrypt methods.'
),
// PHP ini :
'phpSafeMode' => array(
'name' => 'PHP safe mode',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("safe_mode"),
'by' => 'File uploading and console command execution',
'memo' => '"safe_mode" should be disabled at php.ini',
),
'phpExposePhp' => array(
'name' => 'Expose PHP',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("expose_php"),
'by' => 'Security reasons',
'memo' => '"expose_php" should be disabled at php.ini',
),
'phpAllowUrlInclude' => array(
'name' => 'PHP allow url include',
'mandatory' => false,
'condition' => $requirementsChecker->checkPhpIniOff("allow_url_include"),
'by' => 'Security reasons',
'memo' => '"allow_url_include" should be disabled at php.ini',
),
'phpSmtp' => array(
'name' => 'PHP mail SMTP',
'mandatory' => false,
'condition' => strlen(ini_get('SMTP'))>0,
'by' => 'Email sending',
'memo' => 'PHP mail SMTP server required',
),
);
$requirementsChecker->checkYii()->check($requirements)->render();

22
apps/basic/assets/AppAsset.php

@ -15,15 +15,15 @@ use yii\web\AssetBundle;
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}

16
apps/basic/commands/HelloController.php

@ -19,12 +19,12 @@ use yii\console\Controller;
*/
class HelloController extends Controller
{
/**
* This command echoes what you have entered as the message.
* @param string $message the message to be echoed.
*/
public function actionIndex($message = 'hello world')
{
echo $message . "\n";
}
/**
* This command echoes what you have entered as the message.
* @param string $message the message to be echoed.
*/
public function actionIndex($message = 'hello world')
{
echo $message . "\n";
}
}

40
apps/basic/config/console.php

@ -6,24 +6,24 @@ $params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
return [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'preload' => ['log'],
'controllerNamespace' => 'app\commands',
'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'preload' => ['log'],
'controllerNamespace' => 'app\commands',
'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
];

10
apps/basic/config/db.php

@ -1,9 +1,9 @@
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2basic',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2basic',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
];

2
apps/basic/config/params.php

@ -1,5 +1,5 @@
<?php
return [
'adminEmail' => 'admin@example.com',
'adminEmail' => 'admin@example.com',
];

68
apps/basic/config/web.php

@ -4,43 +4,43 @@ $params = require(__DIR__ . '/params.php');
$db = require(__DIR__ . '/db.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
'id' => 'basic',
'basePath' => dirname(__DIR__),
'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mail' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = 'yii\gii\Module';
// configuration adjustments for 'dev' environment
$config['preload'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;

148
apps/basic/controllers/SiteController.php

@ -11,84 +11,86 @@ use app\models\ContactForm;
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionIndex()
{
return $this->render('index');
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function actionLogout()
{
Yii::$app->user->logout();
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
return $this->goHome();
}
public function actionAbout()
{
return $this->render('about');
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save