Coding datasets
Collection
Datasets for high quality small LM model pre-training.
•
3 items
•
Updated
repo_name
string | text
string |
|---|---|
Mirocow/pingcrm-yii2
|
version: '2'
services:
php:
image: yiisoftware/yii2-php:7.1-apache
volumes:
- ~/.composer-docker/cache:/root/.composer/cache:delegated
- ./:/app:delegated
ports:
- '8000:80'<|endoftext|>const purgecss = require("@fullhuman/postcss-purgecss")({
content: ["./web/**/*.html"],
defaultExtractor: (content) => content.match(/[A-Za-z0-9-_:/]+/g) || [],
});
module.exports = {
plugins: [
require("postcss-import"),
require("tailwindcss"),
require("autoprefixer"),
...(process.env.NODE_ENV === "production"
? [purgecss, require("cssnano")]
: []),
],
};
<|endoftext|>{
"name": "pingcrm-yii2",
"version": "1.0.0",
"description": "<p align=\"center\"> <a href=\"https://github.com/yiisoft\" target=\"_blank\"> <img src=\"https://avatars0.githubusercontent.com/u/993323\" height=\"100px\"> </a> <h1 align=\"center\">Yii 2 Basic Project Template</h1> <br> </p>",
"main": "index.js",
"directories": {
"test": "tests"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --config webpack.config.js",
"prod": "webpack --config webpack.config.js --optimize-minimize --mode production",
"css-dev": "cross-env NODE_ENV=development postcss resources/css/app.css -o web/assets/inertia/css/app.css",
"css-prod": "cross-env NODE_ENV=development postcss resources/css/app.css -o web/assets/inertia/css/app.min.css"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tbreuss/pingcrm-yii2.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/tbreuss/pingcrm-yii2/issues"
},
"homepage": "https://github.com/tbreuss/pingcrm-yii2#readme",
"dependencies": {
"@inertiajs/inertia": "^0.1.7",
"@inertiajs/inertia-vue": "^0.1.2",
"lodash": "^4.17.15",
"popper.js": "^1.16.1",
"portal-vue": "^2.1.7",
"tailwindcss": "^1.2.0",
"vue": "^2.6.11",
"vue-meta": "^2.3.3"
},
"devDependencies": {
"@fullhuman/postcss-purgecss": "^2.1.0",
"autoprefixer": "^9.7.4",
"cross-env": "^7.0.2",
"css-loader": "^3.4.2",
"cssnano": "^4.1.10",
"minimist": ">=1.2.2",
"postcss-cli": "^7.1.0",
"postcss-import": "^12.0.1",
"style-loader": "^1.1.3",
"vue-loader": "^15.9.1",
"vue-style-loader": "^4.1.2",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.10"
}
}
<|endoftext|>// webpack.config.js
const path = require("node:path");
const _webpack = require("webpack");
const PATHS = {
source: path.join(__dirname, "resources/js"),
build: path.join(__dirname, "web"),
};
const { VueLoaderPlugin } = require("vue-loader");
module.exports = (_env, argv) => {
const config = {
production: argv.mode === "production",
};
return {
mode: "development",
entry: ["./resources/js/app.js"],
output: {
path: PATHS.build,
filename: config.production
? "assets/inertia/js/app.min.js"
: "assets/inertia/js/app.js",
},
resolve: {
extensions: [".js", ".vue", ".json"],
alias: {
"@": `/${path.resolve(__dirname, "resources/js")}`,
},
},
module: {
rules: [
{
test: /\.vue$/,
use: "vue-loader",
},
{
test: /\.css$/,
loader: ["style-loader", "css-loader"],
},
],
},
plugins: [new VueLoaderPlugin()],
};
};
<|endoftext|>{
"name": "tebe/pingcrm-yii2",
"description": "Ping CRM on Yii 2 - A Yii 2 demo application to illustrate how Inertia.js works",
"keywords": [
"inertiajs",
"vuejs",
"yii2",
"framework",
"basic",
"project template",
"demo"
],
"homepage": "https://pingcrm-yii2.tebe.ch",
"type": "project",
"license": "BSD-3-Clause",
"support": {
"issues": "https://github.com/yiisoft/yii2/issues?state=open",
"forum": "http://www.yiiframework.com/forum/",
"wiki": "http://www.yiiframework.com/wiki/",
"irc": "irc://irc.freenode.net/yii",
"source": "https://github.com/yiisoft/yii2"
},
"minimum-stability": "stable",
"require": {
"php": ">=5.6.0",
"yiisoft/yii2": "~2.0.14",
"yiisoft/yii2-swiftmailer": "~2.0.0 || ~2.1.0",
"tebazil/db-seeder": "^0.0.0",
"tebe/yii2-inertia": "dev-master"
},
"require-dev": {
"yiisoft/yii2-debug": "~2.1.0",
"yiisoft/yii2-gii": "~2.1.0",
"yiisoft/yii2-faker": "~2.0.0",
"codeception/codeception": "^4.0",
"codeception/verify": "~0.5.0 || ~1.1.0",
"codeception/specify": "~0.4.6",
"symfony/browser-kit": ">=2.7 <=4.2.4",
"codeception/module-filesystem": "^1.0.0",
"codeception/module-yii2": "^1.0.0",
"codeception/module-asserts": "^1.0.0"
},
"config": {
"process-timeout": 1800,
"fxp-asset": {
"enabled": false
}
},
"scripts": {
"post-install-cmd": ["yii\\composer\\Installer::postInstall"],
"post-create-project-cmd": [
"yii\\composer\\Installer::postCreateProject",
"yii\\composer\\Installer::postInstall"
]
},
"extra": {
"yii\\composer\\Installer::postCreateProject": {
"setPermission": [
{
"runtime": "0777",
"web/assets": "0777",
"yii": "0755"
}
]
},
"yii\\composer\\Installer::postInstall": {
"generateCookieValidationKey": ["config/web.php"]
}
},
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
]
}
<|endoftext|><?php
/**
* Application requirement checker script.
*
* In order to run this script use the following console command:
* php requirements.php
*
* In order to run this script from the web, you should copy it to the web root.
* If you are using Linux you can create a hard link instead, using the following command:
* ln ../requirements.php requirements.php
*/
// you may need to adjust this path to the correct Yii framework path
// uncomment and adjust the following line if Yii is not located at the default path
//$frameworkPath = dirname(__FILE__) . '/vendor/yiisoft/yii2';
if (!isset($frameworkPath)) {
$searchPaths = array(
dirname(__FILE__) . '/vendor/yiisoft/yii2',
dirname(__FILE__) . '/../vendor/yiisoft/yii2',
);
foreach ($searchPaths as $path) {
if (is_dir($path)) {
$frameworkPath = $path;
break;
}
}
}
if (!isset($frameworkPath) || !is_dir($frameworkPath)) {
$message = "<h1>Error</h1>\n\n"
. "<p><strong>The path to yii framework seems to be incorrect.</strong></p>\n"
. '<p>You need to install Yii framework via composer or adjust the framework path in file <abbr title="' . __FILE__ . '">' . basename(__FILE__) . "</abbr>.</p>\n"
. '<p>Please refer to the <abbr title="' . dirname(__FILE__) . "/README.md\">README</abbr> on how to install Yii.</p>\n";
if (!empty($_SERVER['argv'])) {
// do not print HTML when used in console mode
echo strip_tags($message);
} else {
echo $message;
}
exit(1);
}
require_once($frameworkPath . '/requirements/YiiRequirementChecker.php');
$requirementsChecker = new YiiRequirementChecker();
$gdMemo = $imagickMemo = 'Either GD PHP extension with FreeType support or ImageMagick PHP extension with PNG support is required for image CAPTCHA.';
$gdOK = $imagickOK = false;
if (extension_loaded('imagick')) {
$imagick = new Imagick();
$imagickFormats = $imagick->queryFormats('PNG');
if (in_array('PNG', $imagickFormats)) {
$imagickOK = true;
} else {
$imagickMemo = 'Imagick extension should be installed with PNG support in order to be used for image CAPTCHA.';
}
}
if (extension_loaded('gd')) {
$gdInfo = gd_info();
if (!empty($gdInfo['FreeType Support'])) {
$gdOK = true;
} else {
$gdMemo = 'GD extension should be installed with FreeType support in order to be used for image CAPTCHA.';
}
}
/**
* Adjust requirements according to your application specifics.
*/
$requirements = array(
// Database :
array(
'name' => 'PDO extension',
'mandatory' => true,
'condition' => extension_loaded('pdo'),
'by' => 'All DB-related classes',
),
array(
'name' => 'PDO SQLite extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_sqlite'),
'by' => 'All DB-related classes',
'memo' => 'Required for SQLite database.',
),
array(
'name' => 'PDO MySQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_mysql'),
'by' => 'All DB-related classes',
'memo' => 'Required for MySQL database.',
),
array(
'name' => 'PDO PostgreSQL extension',
'mandatory' => false,
'condition' => extension_loaded('pdo_pgsql'),
'by' => 'All DB-related classes',
'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-2.0/yii-caching-memcache.html">MemCache</a>',
'memo' => extension_loaded('memcached') ? 'To use memcached set <a href="http://www.yiiframework.com/doc-2.0/yii-caching-memcache.html#$useMemcached-detail">MemCache::useMemcached</a> to <code>true</code>.' : ''
),
// CAPTCHA:
array(
'name' => 'GD PHP extension with FreeType support',
'mandatory' => false,
'condition' => $gdOK,
'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html">Captcha</a>',
'memo' => $gdMemo,
),
array(
'name' => 'ImageMagick PHP extension with PNG support',
'mandatory' => false,
'condition' => $imagickOK,
'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-captcha-captcha.html">Captcha</a>',
'memo' => $imagickMemo,
),
// 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',
),
);
// OPcache check
if (!version_compare(phpversion(), '5.5', '>=')) {
$requirements[] = array(
'name' => 'APC extension',
'mandatory' => false,
'condition' => extension_loaded('apc'),
'by' => '<a href="http://www.yiiframework.com/doc-2.0/yii-caching-apccache.html">ApcCache</a>',
);
}
$result = $requirementsChecker->checkYii()->check($requirements)->getResult();
$requirementsChecker->render();
exit($result['summary']['errors'] === 0 ? 0 : 1);
<|endoftext|>actor: Tester
bootstrap: _bootstrap.php
paths:
tests: tests
log: tests/_output
data: tests/_data
helpers: tests/_support
settings:
memory_limit: 1024M
colors: true
modules:
config:
Yii2:
configFile: 'config/test.php'
# To enable code coverage:
#coverage:
# #c3_url: http://localhost:8080/index-test.php/
# enabled: true
# #remote: true
# #remote_config: '../codeception.yml'
# whitelist:
# include:
# - models/*
# - controllers/*
# - commands/*
# - mail/*
# blacklist:
# include:
# - assets/*
# - config/*
# - runtime/*
# - vendor/*
# - views/*
# - web/*
# - tests/*
<|endoftext|>Copyright © 2008 by Yii Software LLC (http://www.yiisoft.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Yii Software LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
<|endoftext|>const defaultTheme = require("tailwindcss/defaultTheme");
module.exports = {
theme: {
extend: {
fontFamily: {
sans: ["Cerebri Sans", ...defaultTheme.fontFamily.sans],
},
colors: {
indigo: {
900: "#191e38",
800: "#2f365f",
600: "#5661b3",
500: "#6574cd",
400: "#7886d7",
300: "#b2b7ff",
100: "#e6e8ff",
},
},
boxShadow: (theme) => ({
outline: `0 0 0 2px ${theme("colors.indigo.500")}`,
}),
fill: (theme) => theme("colors"),
},
},
variants: {
fill: ["responsive", "hover", "focus", "group-hover"],
textColor: ["responsive", "hover", "focus", "group-hover"],
zIndex: ["responsive", "focus"],
},
plugins: [],
};
<|endoftext|>
# Ping CRM on Yii 2
A Yii 2 demo application to illustrate how [Inertia.js](https://inertiajs.com) works.
With Inertia you are able to build single-page apps using classic server-side routing and controllers, without building an API.
This application is a port of the original [Ping CRM written in Laravel](https://github.com/inertiajs/pingcrm) and based on the [Yii 2 Basic Project Template](https://github.com/yiisoft/yii2-app-basic).

## Demo
<https://pingcrm-yii2.tebe.ch>
## Installation
Clone the repo locally:
```sh
git clone https://github.com/tbreuss/pingcrm-yii2 pingcrm-yii2
cd pingcrm-yii2
```
Install PHP dependencies:
```sh
composer install
```
Install NPM dependencies:
```sh
npm ci
```
Build assets:
```sh
npm run dev
npm run css-dev
```
Create an SQLite database. You can also use another database (MySQL, Postgres), simply update your configuration accordingly.
```sh
touch database/database.sqlite
```
Run database migrations:
```sh
php yii migrate
```
Run database seeder:
```sh
php yii db/seed
```
Run the dev server (the output will give the address):
```sh
php yii serve
```
You're ready to go! Visit Ping CRM in your browser, and login with:
- **Username:** johndoe@example.com
- **Password:** secret
## Running tests
To run the Ping CRM tests, run:
```
(to be done)
```
## Requirements
- PHP >= 5.6.0
- Node.js & NPM
- SQLite
## Extending this project
The following steps are required when extending this project with new features.
### In the backend
- add new controller, that extends from inertia controller
- add one ore more actions
- return from the actions with a call to the inertia render method
~~~php
<?php
namespace app\controllers;
use tebe\inertia\web\Controller;
class CustomController extends Controller
{
public function actionIndex()
{
$params = [
'data' => [],
];
return $this->inertia('demo/index', $params);
}
}
~~~
You can find more information at <https://github.com/tbreuss/yii2-inertia>.
### In the frontend
- add a new page under `resources/js/Pages` for each controller action you added in the backend
- copy&paste one of the existing page examples
- implement and/or extend Vue.js stuff as needed
- use frontend tooling as described here and in package.json
You can find more information at <https://inertiajs.com>.
## Credits
- Original work by Jonathan Reinink (@reinink) and contributors
- Port to Yii 2 by Thomas Breuss (@tbreuss)
<|endoftext|><?php
namespace app\components;
use app\models\User;
use Yii;
use yii\base\Action;
use yii\base\ActionFilter;
use yii\base\InvalidConfigException;
class SharedDataFilter extends ActionFilter
{
/**
* @param Action $action
* @return bool
* @throws InvalidConfigException
* @throws \Throwable
*/
public function beforeAction($action)
{
$shared = [
'auth' => [
'user' => $this->getUser()
],
'flash' => $this->getFlashMessages(),
'errors' => $this->getErrors(),
'filters' => [
'search' => null,
'trashed' => null
]
];
Yii::$app->get('inertia')->share($shared);
return true;
}
/**
* @return array|null
* @throws \Throwable
*/
private function getUser()
{
$webUser = Yii::$app->getUser();
if ($webUser->isGuest) {
return null;
}
/** @var User */
$user = $webUser->getIdentity();
$return = [
'id' => $user->id,
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'email' => $user->email,
'role' => null,
'account' => [
'id' => $user->account->id,
'name' => $user->account->name
],
];
return $return;
}
/**
* @return array
*/
private function getFlashMessages()
{
$flash = [
'success' => null,
'error' => null,
];
if (Yii::$app->session->hasFlash('success')) {
$flash['success'] = Yii::$app->session->getFlash('success');
}
if (Yii::$app->session->hasFlash('error')) {
$flash['error'] = Yii::$app->session->getFlash('error');
}
return $flash;
}
/**
* @return object
*/
private function getErrors()
{
$errors = [];
if (Yii::$app->session->hasFlash('errors')) {
$errors = (array)Yii::$app->session->getFlash('errors');
}
return (object) $errors;
}
}
<|endoftext|><?php
namespace app\components;
trait SoftDeleteTrait
{
/**
* @return int
*/
public function delete()
{
if ($this->isNewRecord) {
return 0;
}
$this->deleted_at = date('Y-m-d H:i:s');
try {
return $this->update(false, ['deleted_at']);
} catch (\Exception $t) {
return 0;
} catch (\Throwable $t) {
return 0;
}
}
/**
* @return int
*/
public function restore()
{
if ($this->isNewRecord) {
return 0;
}
$this->deleted_at = null;
try {
return $this->update(false, ['deleted_at']);
} catch (\Exception $t) {
return 0;
} catch (\Throwable $t) {
return 0;
}
}
}
<|endoftext|><?php
namespace app\components;
use yii\data\Pagination;
use yii\helpers\Url;
class PaginationHelper
{
/**
* @param Pagination $pagination
* @param string $route
* @param string $search
* @param string $trashed
* @param int $page
* @return array
*/
public static function getLinks(Pagination $pagination, $route = 'index', $search = null, $trashed = null, $page = 1)
{
$pageCount = $pagination->getPageCount();
$links = [];
if ($pageCount > 1) {
$params = [];
if (isset($search)) {
$params['search'] = $search;
}
if (isset($trashed)) {
$params['trashed'] = $trashed;
}
$links[] = [
'url' => $page > 1 ? Url::toRoute(array_merge($params, [$route, 'page' => $page - 1])) : null,
'label' => 'Previous',
'active' => false
];
for ($i = 1; $i <= $pageCount; $i++) {
$links[] = [
'url' => Url::toRoute(array_merge($params, [$route, 'page' => $i])),
'label' => $i,
'active' => $page == $i
];
}
$links[] = [
'url' => $page < $pageCount ? Url::toRoute(array_merge($params, [$route, 'page' => $page + 1])) : null,
'label' => 'Next',
'active' => false
];
}
return $links;
}
}
<|endoftext|><?php
namespace app\commands;
use app\models\User;
use tebazil\dbseeder\Seeder;
use Yii;
use yii\console\Controller;
class DbController extends Controller
{
public function actionSeed()
{
$db = Yii::$app->db;
$db->open();
$seeder = new Seeder($db->pdo);
$generator = $seeder->getGeneratorConfigurator();
$faker = $generator->getFakerConfigurator();
$seeder->table('accounts')->columns([
'id' => 1,
'name' => 'Acme Corporation',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
])->rowQuantity(1);
$seeder->table('organizations')->columns([
'id', // automatic pk
'account_id' => $generator->relation('accounts', 'id'),
'name' => $faker->company,
'email' => $faker->companyEmail,
'phone' => $faker->tollFreePhoneNumber,
'address' => $faker->streetAddress,
'city' => $faker->city,
'region' => $faker->state,
'country' => 'US',
'postal_code' => $faker->postcode,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
])->rowQuantity(100);
$seeder->table('contacts')->columns([
'id', // automatic pk
'account_id' => $generator->relation('accounts', 'id'),
'organization_id' => $generator->relation('organizations', 'id'),
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $faker->unique()->safeEmail,
'phone' => $faker->tollFreePhoneNumber,
'address' => $faker->streetAddress,
'city' => $faker->city,
'region' => $faker->state,
'country' => 'US',
'postal_code' => $faker->postcode,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
])->rowQuantity(100);
$seeder->table('users')->columns([
'id', // automatic pk
'account_id' => $generator->relation('accounts', 'id'),
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $faker->unique()->safeEmail,
'password' => 'secret',
'owner' => '0',
'remember_token' => $faker->regexify('[A-Za-z0-9]{10}'),
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
])->rowQuantity(5);
$seeder->refill();
$user = new User();
$user->detachBehaviors();
$user->attributes = [
'account_id' => 1,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'johndoe@example.com',
'password' => 'secret',
'owner' => 1
];
$user->save(false);
}
}
<|endoftext|><?php
use yii\db\Migration;
/**
* Class m200208_000000_create_organizations_table
*/
class m200208_000000_create_organizations_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('organizations', [
'id' => $this->primaryKey(),
'account_id' => $this->integer()->null(),
'name' => $this->string(100)->notNull(),
'email' => $this->string(50)->null(),
'phone' => $this->string(50)->null(),
'address' => $this->string(150)->null(),
'city' => $this->string(50)->null(),
'region' => $this->string(50)->null(),
'country' => $this->string(2)->null(),
'postal_code' => $this->string(25)->null(),
'created_at' => $this->dateTime()->null(),
'updated_at' => $this->dateTime()->null(),
'deleted_at' => $this->dateTime()->null()
]);
$this->createIndex('organizations_account_id_index', 'organizations', 'account_id');
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
return false;
}
}
<|endoftext|><?php
use yii\db\Migration;
/**
* Class m200208_000000_create_users_table
*/
class m200208_000000_create_users_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('users', [
'id' => $this->primaryKey(),
'account_id' => $this->integer()->null(),
'first_name' => $this->string(25)->notNull(),
'last_name' => $this->string(25)->notNull(),
'email' => $this->string(50)->unique(),
'password' => $this->string()->null(),
'owner' => $this->integer(1)->defaultValue(0),
'photo_path' => $this->string(100)->null(),
'remember_token' => $this->string()->null(),
'created_at' => $this->dateTime()->null(),
'updated_at' => $this->dateTime()->null(),
'deleted_at' => $this->dateTime()->null()
]);
$this->createIndex('users_account_id_index', 'users', 'account_id');
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
return false;
}
}
<|endoftext|><?php
use yii\db\Migration;
/**
* Class m200208_000000_create_accounts_table
*/
class m200208_000000_create_accounts_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('accounts', [
'id' => $this->primaryKey(),
'name' => $this->string(50)->notNull(),
'created_at' => $this->dateTime()->null(),
'updated_at' => $this->dateTime()->null()
]);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
return false;
}
}
<|endoftext|><?php
use yii\db\Migration;
/**
* Class m200208_000000_create_contacts_table
*/
class m200208_000000_create_contacts_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('contacts', [
'id' => $this->primaryKey(),
'account_id' => $this->integer()->notNull(),
'organization_id' => $this->integer()->null(),
'first_name' => $this->string(25)->notNull(),
'last_name' => $this->string(25)->notNull(),
'email' => $this->string(50)->null(),
'phone' => $this->string(50)->null(),
'address' => $this->string(150)->null(),
'city' => $this->string(50)->null(),
'region' => $this->string(50)->null(),
'country' => $this->string(2)->null(),
'postal_code' => $this->string(25)->null(),
'created_at' => $this->dateTime()->null(),
'updated_at' => $this->dateTime()->null(),
'deleted_at' => $this->dateTime()->null()
]);
$this->createIndex('contacts_account_id_index', 'contacts', 'account_id');
$this->createIndex('contacts_organization_id_index', 'contacts', 'organization_id');
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
return false;
}
}
<|endoftext|><?php
use yii\db\Migration;
/**
* Class m200208_000000_create_password_resets_table
*/
class m200208_000000_create_password_resets_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->createTable('password_resets', [
'email' => $this->string()->notNull(),
'token' => $this->string()->notNull(),
'created_at' => $this->dateTime()->null()
]);
$this->createIndex('password_resets_email_index', 'password_resets', 'email');
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
return false;
}
}
<|endoftext|><?php
// 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.');
}
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../config/test.php';
(new yii\web\Application($config))->run();
<|endoftext|><?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../config/web.php';
(new yii\web\Application($config))->run();
<|endoftext|><?php
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public function init()
{
parent::init();
if (YII_ENV === 'dev') {
$this->css[] = 'assets/inertia/css/app.css';
$this->js[] = 'assets/inertia/js/app.js';
} else {
$this->css[] = 'assets/inertia/css/app.min.css';
$this->js[] = 'assets/inertia/js/app.min.js';
}
}
}
<|endoftext|><?php
namespace app\models;
use app\components\SoftDeleteTrait;
use Yii;
use yii\behaviors\AttributeBehavior;
use yii\behaviors\TimestampBehavior;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;
use yii\db\Query;
/**
* This is the model class for table "contacts".
*
* @property int $id
* @property int $account_id
* @property int|null $organization_id
* @property string $first_name
* @property string $last_name
* @property string|null $email
* @property string|null $phone
* @property string|null $address
* @property string|null $city
* @property string|null $region
* @property string|null $country
* @property string|null $postal_code
* @property string|null $created_at
* @property string|null $updated_at
* @property string|null $deleted_at
*/
class Contact extends ActiveRecord
{
use SoftDeleteTrait;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'contacts';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['first_name', 'last_name'], 'required'],
[['account_id', 'organization_id'], 'integer'],
[['created_at', 'updated_at', 'deleted_at'], 'safe'],
[['first_name', 'last_name', 'postal_code'], 'string', 'max' => 25],
[['email', 'phone', 'city', 'region'], 'string', 'max' => 50],
[['address'], 'string', 'max' => 150],
[['country'], 'string', 'max' => 2],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'account_id' => 'Account ID',
'organization_id' => 'Organization ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'phone' => 'Phone',
'address' => 'Address',
'city' => 'City',
'region' => 'Region',
'country' => 'Country',
'postal_code' => 'Postal Code',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'deleted_at' => 'Deleted At',
];
}
/**
* @return array
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'value' => date('Y-m-d H:i:s')
],
[
'class' => AttributeBehavior::class,
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'account_id',
ActiveRecord::EVENT_BEFORE_UPDATE => 'account_id'
],
'value' => function () {
return Yii::$app->user->getIdentity()->account_id;
}
]
];
}
/**
* @param array $params
* @return Organization
*/
public static function fromArray(array $params = [])
{
$organization = new static();
$organization->attributes = $params;
return $organization;
}
/**
* @param int $id
* @return Organization|null
*/
public static function findById($id)
{
return static::find()
->select('id, first_name, last_name, organization_id, email, phone, address, city, region, country, postal_code, deleted_at')
->where('id=:id', ['id' => $id])
->asArray()
->one();
}
/**
* @param string $search
* @param string $trashed
* @return ActiveDataProvider
*/
public static function findByParams($search = null, $trashed = null)
{
$query = (new Query())
->select('contacts.id, contacts.first_name, contacts.last_name, contacts.phone, contacts.city, contacts.deleted_at, organizations.name AS organization_name')
->from('contacts')
->leftJoin('organizations', 'organizations.id = contacts.organization_id');
if (!empty($search)) {
$query->andWhere(['like', 'contacts.first_name', $search]);
$query->orWhere(['like', 'contacts.last_name', $search]);
}
if ($trashed === 'with') {
} elseif ($trashed === 'only') {
$query->andWhere(['not', ['contacts.deleted_at' => null]]);
} else {
$query->andWhere(['contacts.deleted_at' => null]);
}
$query->orderBy('contacts.last_name ASC, contacts.first_name');
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
]);
return $dataProvider;
}
}
<|endoftext|><?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $email;
public $password;
public $remember = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// email and password are both required
[['email', 'password'], 'required'],
// remember must be a boolean value
['remember', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect email or password.');
}
}
}
/**
* Logs in a user using the provided email and password.
* @return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
$user = $this->getUser();
return Yii::$app->user->login($user, $this->remember ? 3600*24*30 : 0);
}
return false;
}
/**
* Finds user by [[email]]
*
* @return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByEmail($this->email);
}
return $this->_user;
}
}
<|endoftext|><?php
namespace app\models;
use yii\db\ActiveRecord;
/**
* This is the model class for table "accounts".
*
* @property int $id
* @property string $name
* @property string|null $created_at
* @property string|null $updated_at
*/
class Account extends ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'accounts';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['name'], 'string', 'max' => 50],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}
<|endoftext|><?php
namespace app\models;
use app\components\SoftDeleteTrait;
use Yii;
use yii\behaviors\AttributeBehavior;
use yii\behaviors\TimestampBehavior;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;
use yii\db\Query;
/**
* This is the model class for table "organizations".
*
* @property int $id
* @property int|null $account_id
* @property string $name
* @property string|null $email
* @property string|null $phone
* @property string|null $address
* @property string|null $city
* @property string|null $region
* @property string|null $country
* @property string|null $postal_code
* @property string|null $created_at
* @property string|null $updated_at
* @property string|null $deleted_at
*/
class Organization extends ActiveRecord
{
use SoftDeleteTrait;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'organizations';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['account_id'], 'integer'],
[['name'], 'required'],
[['created_at', 'updated_at', 'deleted_at'], 'safe'],
[['name'], 'string', 'max' => 100],
[['email', 'phone', 'city', 'region'], 'string', 'max' => 50],
[['email'], 'email'],
[['address'], 'string', 'max' => 150],
[['country'], 'string', 'max' => 2],
[['postal_code'], 'string', 'max' => 25],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'account_id' => 'Account ID',
'name' => 'Name',
'email' => 'Email',
'phone' => 'Phone',
'address' => 'Address',
'city' => 'City',
'region' => 'Region',
'country' => 'Country',
'postal_code' => 'Postal Code',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'deleted_at' => 'Deleted At',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getContacts()
{
return $this->hasMany(Contact::class, ['organization_id' => 'id']);
}
/**
* @return array
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'value' => date('Y-m-d H:i:s')
],
[
'class' => AttributeBehavior::class,
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'account_id',
ActiveRecord::EVENT_BEFORE_UPDATE => 'account_id'
],
'value' => function () {
return Yii::$app->user->getIdentity()->account_id;
}
]
];
}
/**
* @param int $id
* @return array|null
*/
public static function findById($id)
{
$organization = static::find()
->select('id, name, email, phone, address, city, region, country, postal_code, deleted_at')
->with('contacts')
->where('id=:id', ['id' => $id])
->asArray()
->one();
if (is_null($organization)) {
return $organization;
}
$organization['contacts'] = array_map(function ($row) {
return [
'id' => $row['id'],
'name' => $row['first_name'] . ' ' . $row['last_name'],
'city' => $row['city'],
'phone' => $row['phone']
];
}, $organization['contacts']);
return $organization;
}
/**
* @param array $params
* @return Organization
*/
public static function fromArray(array $params = [])
{
$organization = new static();
$organization->attributes = $params;
return $organization;
}
/**
* @param string $search
* @param string $trashed
* @return ActiveDataProvider
*/
public static function findByParams($search = null, $trashed = null)
{
$query = (new Query())
->select('id, name, phone, city, deleted_at')
->from('organizations');
if (!empty($search)) {
$query->andWhere(['like', 'name', $search]);
}
if ($trashed === 'with') {
} elseif ($trashed === 'only') {
$query->andWhere(['not', ['deleted_at' => null]]);
} else {
$query->andWhere(['deleted_at' => null]);
}
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
]);
return $dataProvider;
}
/**
* @return array
*/
public static function getPairs()
{
$pairs = (new Query())
->select('id, name')
->from('organizations')
->orderBy('name')
->where(['deleted_at' => null])
->all();
return $pairs;
}
}
<|endoftext|><?php
namespace app\models;
use app\components\SoftDeleteTrait;
use Yii;
use yii\behaviors\AttributeBehavior;
use yii\behaviors\TimestampBehavior;
use yii\data\ActiveDataProvider;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\web\IdentityInterface;
/**
* This is the model class for table "users".
*
* @property int $id
* @property int|null $account_id
* @property string $first_name
* @property string $last_name
* @property string|null $email
* @property string|null $password
* @property bool|null $owner
* @property string|null $photo_path
* @property string|null $remember_token
* @property string|null $created_at
* @property string|null $updated_at
* @property string|null $deleted_at
*/
class User extends ActiveRecord implements IdentityInterface
{
use SoftDeleteTrait;
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'users';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['account_id'], 'integer'],
[['first_name', 'last_name'], 'required'],
[['owner'], 'boolean'],
[['created_at', 'updated_at', 'deleted_at'], 'safe'],
[['first_name', 'last_name'], 'string', 'max' => 25],
[['email'], 'string', 'max' => 50],
[['password', 'remember_token'], 'string', 'max' => 255],
[['photo_path'], 'string', 'max' => 100],
[['email'], 'unique'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'account_id' => 'Account ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'password' => 'Password',
'owner' => 'Owner',
'photo_path' => 'Photo Path',
'remember_token' => 'Remember Token',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'deleted_at' => 'Deleted At',
];
}
/**
* @return array
*/
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'value' => date('Y-m-d H:i:s')
],
[
'class' => AttributeBehavior::class,
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'account_id',
ActiveRecord::EVENT_BEFORE_UPDATE => 'account_id'
],
'value' => function () {
return Yii::$app->user->getIdentity()->account_id;
}
]
];
}
public function getAccount()
{
return $this->hasOne(Account::class, ['id' => 'account_id']);
}
/**
* Validates password
*
* @param string $password password to validate
* @return bool if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
public static function findByEmail($email)
{
return static::find()
->where(['email' => $email])
->one();
}
/**
* Finds an identity by the given ID.
* @param string|int $id the ID to be looked for
* @return IdentityInterface|null the identity object that matches the given ID.
* Null should be returned if such an identity cannot be found
* or the identity is not in an active state (disabled, deleted, etc.)
*/
public static function findIdentity($id)
{
return static::find()
->where(['id' => $id])
->one();
}
/**
* Finds an identity by the given token.
* @param mixed $token the token to be looked for
* @param mixed $type the type of the token. The value of this parameter depends on the implementation.
* For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
* @return IdentityInterface|null the identity object that matches the given token.
* Null should be returned if such an identity cannot be found
* or the identity is not in an active state (disabled, deleted, etc.)
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return null;
}
/**
* Returns an ID that can uniquely identify a user identity.
* @return string|int an ID that uniquely identifies a user identity.
*/
public function getId()
{
return $this->id;
}
/**
* Returns a key that can be used to check the validity of a given identity ID.
*
* The key should be unique for each individual user, and should be persistent
* so that it can be used to check the validity of the user identity.
*
* The space of such keys should be big enough to defeat potential identity attacks.
*
* This is required if [[User::enableAutoLogin]] is enabled. The returned key will be stored on the
* client side as a cookie and will be used to authenticate user even if PHP session has been expired.
*
* Make sure to invalidate earlier issued authKeys when you implement force user logout, password change and
* other scenarios, that require forceful access revocation for old sessions.
*
* @return string a key that is used to check the validity of a given identity ID.
* @see validateAuthKey()
*/
public function getAuthKey()
{
return null;
}
/**
* Validates the given auth key.
*
* This is required if [[User::enableAutoLogin]] is enabled.
* @param string $authKey the given auth key
* @return bool whether the given auth key is valid.
* @see getAuthKey()
*/
public function validateAuthKey($authKey)
{
return false;
}
public static function findById($id)
{
return static::find()
->select('id, first_name, last_name, email, owner, photo_path, deleted_at')
->where('id=:id', ['id' => $id])
->asArray()
->one();
}
public static function findByParams($search = null, $role = null, $trashed = null)
{
$query = (new Query())
->select('id, first_name, last_name, email, owner, photo_path, deleted_at')
->from('users');
if (!empty($search)) {
$query->andWhere(['like', 'first_name', $search]);
$query->orWhere(['like', 'last_name', $search]);
}
if ($role === 'user') {
$query->andWhere(['owner' => '0']);
} elseif ($role === 'owner') {
$query->andWhere(['owner' => '1']);
}
if ($trashed === 'with') {
} elseif ($trashed === 'only') {
$query->andWhere(['not', ['deleted_at' => null]]);
} else {
$query->andWhere(['deleted_at' => null]);
}
$query->orderBy('last_name ASC, first_name ASC');
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 100000,
],
]);
return $dataProvider;
}
/**
* @param array $params
* @return User
*/
public static function fromArray(array $params = [])
{
$user = new static();
$user->attributes = $params;
return $user;
}
}
<|endoftext|><?php
namespace app\controllers;
use app\components\SharedDataFilter;
use app\models\LoginForm;
use tebe\inertia\web\Controller;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\ServerErrorHttpException;
class SiteController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => AccessControl::className(),
'only' => ['index', 'logout'],
'rules' => [
[
'actions' => ['index', 'logout'],
'allow' => true,
'roles' => ['@']
]
]
],
[
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post']
]
],
[
'class' => SharedDataFilter::class
]
];
}
public function actionError()
{
$this->layout = 'error';
if (($exception = Yii::$app->getErrorHandler()->exception) === null) {
$exception = new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
}
Yii::$app->getResponse()->setStatusCodeByException($exception);
return $this->render('error', [
'name' => $exception->getName(),
'message' => $exception->getMessage(),
'exception' => $exception,
]);
}
/**
* Displays homepage.
*
* @return string
*/
public function actionIndex()
{
return $this->inertia('Dashboard/Index');
}
/**
* Login action.
*
* @return Response|string
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$postData = Yii::$app->request->post();
$model = new LoginForm();
if ($model->load($postData, '')) {
if ($model->login()) {
return $this->goBack();
}
Yii::$app->session->setFlash('errors', $model->getErrors());
}
return $this->inertia('Auth/Login');
}
/**
* Logout action.
*
* @return Response
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
public function action500()
{
sleep(1);
throw new ServerErrorHttpException('An unexpected error happend.');
}
}
<|endoftext|><?php
namespace app\controllers;
use app\components\SharedDataFilter;
use app\components\PaginationHelper;
use app\models\Contact;
use app\models\Organization;
use tebe\inertia\web\Controller;
use Yii;
use yii\filters\AccessControl;
use yii\web\HttpException;
use yii\web\Response;
class ContactController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@']
]
]
],
[
'class' => SharedDataFilter::class
]
];
}
/**
* @param string $search
* @param string $trashed
* @param string $remember
* @param int $page
* @return array|string
*/
public function actionIndex($search = null, $trashed = null, $remember = null, $page = 1)
{
if ($remember === 'forget') {
$search = null;
$trashed = null;
}
$dataProvider = Contact::findByParams($search, $trashed);
return $this->inertia('Contacts/Index', [
'filters' => [
'search' => $search,
'trashable' => $trashed,
],
'contacts' => [
'data' => array_map(function ($row) {
$row['name'] = $row['first_name'] . ' ' . $row['last_name'];
$row['organization'] = [
'name' => $row['organization_name']
];
unset($row['first_name'], $row['last_name'], $row['organization_name']);
return $row;
}, $dataProvider->getModels()
),
'links' => PaginationHelper::getLinks(
$dataProvider->getPagination(),
'index',
$search,
$trashed,
$page
),
]
]);
}
/**
* @return array|string
*/
public function actionCreate()
{
return $this->inertia('Contacts/Create', [
'organizations' => Organization::getPairs()
]);
}
/**
* @param int $id
* @return array|string
* @throws HttpException
*/
public function actionEdit($id)
{
$contact = Contact::findById($id);
if (is_null($contact)) {
throw new HttpException(404);
}
return $this->inertia('Contacts/Edit', [
'contact' => $contact,
'organizations' => Organization::getPairs()
]);
}
/**
* @return Response
*/
public function actionInsert()
{
$params = Yii::$app->request->post();
$contact = Contact::fromArray($params);
if ($contact->save()) {
Yii::$app->session->setFlash('success', 'Contact created.');
return $this->redirect(['contact/index']);
}
Yii::$app->session->setFlash('errors', $contact->getErrors());
return $this->redirect(['contact/create']);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionUpdate($id)
{
$contact = Contact::findOne($id);
if (is_null($contact)) {
throw new HttpException(404);
}
$contact->attributes = Yii::$app->request->post();
if ($contact->save()) {
Yii::$app->session->setFlash('success', 'Contact updated.');
return $this->redirect(['contact/edit', 'id' => $id]);
}
Yii::$app->session->setFlash('errors', $contact->getErrors());
return $this->redirect(['contact/edit', 'id' => $id]);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionDelete($id)
{
$contact = Contact::findOne($id);
if (is_null($contact)) {
throw new HttpException(404);
}
if ($contact->delete() > 0) {
Yii::$app->session->setFlash('success', 'Contact deleted.');
}
return $this->redirect(['contact/edit', 'id' => $id]);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionRestore($id)
{
$contact = Contact::findOne($id);
if (is_null($contact)) {
throw new HttpException(404);
}
if ($contact->restore() > 0) {
Yii::$app->session->setFlash('success', 'Contact restored.');
}
return $this->redirect(['contact/edit', 'id' => $id]);
}
}
<|endoftext|><?php
namespace app\controllers;
use app\components\SharedDataFilter;
use app\components\PaginationHelper;
use app\models\Organization;
use tebe\inertia\web\Controller;
use Yii;
use yii\filters\AccessControl;
use yii\web\HttpException;
use yii\web\Response;
class OrganizationController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@']
]
]
],
[
'class' => SharedDataFilter::class
]
];
}
/**
* @param string $search
* @param string $trashed
* @param string $remember
* @param int $page
* @return array|string
*/
public function actionIndex($search = null, $trashed = null, $remember = null, $page = 1)
{
if ($remember === 'forget') {
$search = null;
$trashed = null;
}
$dataProvider = Organization::findByParams($search, $trashed);
return $this->inertia('Organizations/Index', [
'filters' => [
'search' => $search,
'trashable' => $trashed,
],
'organizations' => [
'data' => $dataProvider->getModels(),
'links' => PaginationHelper::getLinks(
$dataProvider->getPagination(),
'index',
$search,
$trashed,
$page
),
]
]);
}
/**
* @return array|string
*/
public function actionCreate()
{
return $this->inertia('Organizations/Create');
}
/**
* @param int $id
* @return array|string
* @throws HttpException
*/
public function actionEdit($id)
{
$organization = Organization::findById($id);
if (is_null($organization)) {
throw new HttpException(404);
}
return $this->inertia('Organizations/Edit', [
'organization' => $organization
]);
}
/**
* @return Response
*/
public function actionInsert()
{
$params = Yii::$app->request->post();
$organization = Organization::fromArray($params);
if ($organization->save()) {
Yii::$app->session->setFlash('success', 'Organization created.');
return $this->redirect(['organization/index']);
}
Yii::$app->session->setFlash('errors', $organization->getErrors());
return $this->redirect(['organization/create']);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionUpdate($id)
{
$organization = Organization::findOne($id);
if (is_null($organization)) {
throw new HttpException(404);
}
$organization->attributes = Yii::$app->request->post();
if ($organization->save()) {
Yii::$app->session->setFlash('success', 'Organization updated.');
return $this->redirect(['organization/edit', 'id' => $id]);
}
Yii::$app->session->setFlash('errors', $organization->getErrors());
return $this->redirect(['organization/edit', 'id' => $id]);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionDelete($id)
{
$organization = Organization::findOne($id);
if (is_null($organization)) {
throw new HttpException(404);
}
if ($organization->delete() > 0) {
Yii::$app->session->setFlash('success', 'Organization deleted.');
}
return $this->redirect(['organization/edit', 'id' => $id]);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionRestore($id)
{
$organization = Organization::findOne($id);
if (is_null($organization)) {
throw new HttpException(404);
}
if ($organization->restore() > 0) {
Yii::$app->session->setFlash('success', 'Organization restored.');
}
return $this->redirect(['organization/edit', 'id' => $id]);
}
}
<|endoftext|><?php
namespace app\controllers;
use app\components\SharedDataFilter;
use app\models\User;
use tebe\inertia\web\Controller;
use Yii;
use yii\filters\AccessControl;
use yii\web\HttpException;
use yii\web\Response;
class UserController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@'],
]
]
],
[
'class' => SharedDataFilter::class,
]
];
}
public function actionIndex($search = null, $role = null, $trashed = null, $remember = null)
{
if ($remember === 'forget') {
$search = null;
$role = null;
$trashed = null;
}
$dataProvider = User::findByParams($search, $role, $trashed);
return $this->inertia('Users/Index', [
'filters' => [
'search' => $search,
'role' => $role,
'trashable' => $trashed,
],
'users' => $this->mapUsers($dataProvider->getModels()),
]);
}
/**
* @param int $id
* @return array|string
* @throws HttpException
*/
public function actionEdit($id)
{
$user = User::findById($id);
if (is_null($user)) {
throw new HttpException(404);
}
$user['owner'] = (bool)$user['owner'];
return $this->inertia('Users/Edit', [
'user' => $user
]);
}
/**
* @return array|string
*/
public function actionCreate()
{
return $this->inertia('Users/Create');
}
/**
* @return Response
*/
public function actionInsert()
{
$params = Yii::$app->request->post();
$user = User::fromArray($params);
if ($user->save()) {
Yii::$app->session->setFlash('success', 'User created.');
return $this->redirect(['user/index']);
}
Yii::$app->session->setFlash('errors', $user->getErrors());
return $this->redirect(['user/create']);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionUpdate($id)
{
$user = User::findOne($id);
if (is_null($user)) {
throw new HttpException(404);
}
if ($user->email === 'johndoe@example.com') {
Yii::$app->session->setFlash('error', 'Updating the demo user is not allowed.');
return $this->redirect(['user/edit', 'id' => $id]);
}
$user->attributes = Yii::$app->request->post();
if ($user->save()) {
Yii::$app->session->setFlash('success', 'User updated.');
return $this->redirect(['user/edit', 'id' => $id]);
}
Yii::$app->session->setFlash('errors', $user->getErrors());
return $this->redirect(['user/edit', 'id' => $id]);
}
/**
* @param int $id
* @return Response
* @throws HttpException
*/
public function actionDelete($id)
{
$user = User::findOne($id);
if (is_null($user)) {
throw new HttpException(404);
}
if ($user->email === 'johndoe@example.com') {
Yii::$app->session->setFlash('error', 'Deleting the demo user is not allowed.');
return $this->redirect(['user/edit', 'id' => $id]);
}
if ($user->delete() > 0) {
Yii::$app->session->setFlash('success', 'User deleted.');
}
return $this->redirect(['user/edit', 'id' => $id]);
}
/**
* @param $id
* @return Response
* @throws HttpException
*/
public function actionRestore($id)
{
$user = User::findOne($id);
if (is_null($user)) {
throw new HttpException(404);
}
if ($user->restore() > 0) {
Yii::$app->session->setFlash('success', 'User restored.');
}
return $this->redirect(['user/edit', 'id' => $id]);
}
/**
* @param array $users
* @return array
*/
private function mapUsers(array $users)
{
return array_map(function ($row) {
$row['name'] = $row['first_name'] . ' ' . $row['last_name'];
$row['owner'] = (bool)$row['owner'];
unset($row['first_name'], $row['last_name']);
return $row;
}, $users);
}
}
<|endoftext|><?php
namespace app\controllers;
use app\components\SharedDataFilter;
use tebe\inertia\web\Controller;
use yii\filters\AccessControl;
class ReportController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => AccessControl::class,
'rules' => [
[
'allow' => true,
'roles' => ['@']
]
]
],
[
'class' => SharedDataFilter::class
]
];
}
public function actionIndex()
{
$params = [
'filters' => [
'search' => null,
'trashable' => null
],
'contacts' => [
'data' => [],
'links' => []
]
];
return $this->inertia('Reports/Index', $params);
}
}
<|endoftext|><?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/test_db.php';
/**
* Application configuration shared by all test types
*/
return [
'id' => 'basic-tests',
'basePath' => dirname(__DIR__),
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'language' => 'en-US',
'components' => [
'db' => $db,
'mailer' => [
'useFileTransport' => true,
],
'assetManager' => [
'basePath' => __DIR__ . '/../web/assets',
],
'urlManager' => [
'showScriptName' => true,
],
'user' => [
'identityClass' => 'app\models\User',
],
'request' => [
'cookieValidationKey' => 'test',
'enableCsrfValidation' => false,
// but if you absolutely need it set cookie domain to localhost
/*
'csrfCookie' => [
'domain' => 'localhost',
],
*/
],
],
'params' => $params,
];
<|endoftext|><?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log', 'inertia'],
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
],
'components' => [
'request' => [
'class' => 'tebe\inertia\web\Request',
'cookieValidationKey' => '7d0d683457df8f6ff9d65e2b507c08cd'
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'login' => 'site/login',
'logout' => 'site/logout',
// Contacts
'GET contacts' => 'contact/index',
'POST contacts' => 'contact/insert',
'GET contacts/create' => 'contact/create',
'GET contacts/<id:\d+>/edit' => 'contact/edit',
'PUT contacts/<id:\d+>' => 'contact/update',
'DELETE contacts/<id:\d+>' => 'contact/delete',
'PUT contacts/<id:\d+>/restore' => 'contact/restore',
// Organizations
'GET organizations' => 'organization/index',
'POST organizations' => 'organization/insert',
'GET organizations/create' => 'organization/create',
'GET organizations/<id:\d+>/edit' => 'organization/edit',
'PUT organizations/<id:\d+>' => 'organization/update',
'DELETE organizations/<id:\d+>' => 'organization/delete',
'PUT organizations/<id:\d+>/restore' => 'organization/restore',
// Users
'GET users' => 'user/index',
'POST users' => 'user/insert',
'GET users/create' => 'user/create',
'GET users/<id:\d+>/edit' => 'user/edit',
'PUT users/<id:\d+>' => 'user/update',
'DELETE users/<id:\d+>' => 'user/delete',
'PUT users/<id:\d+>/restore' => 'user/restore',
'reports' => 'report/index',
'500' => 'site/500'
]
],
'inertia' => [
'class' => 'tebe\inertia\Inertia',
'assetsDirs' => [
'@webroot/assets/inertia'
]
]
],
'params' => $params,
];
if (false && YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
<|endoftext|><?php
$db = require __DIR__ . '/db.php';
// test database! Important not to run tests on production or development databases
$db['dsn'] = 'mysql:host=localhost;dbname=yii2_basic_tests';
return $db;
<|endoftext|><?php
return [
'adminEmail' => 'admin@example.com',
'senderEmail' => 'noreply@example.com',
'senderName' => 'Example.com mailer',
];
<|endoftext|><?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:@app/database/database.sqlite',
// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache',
];
<|endoftext|><?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\commands',
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm' => '@vendor/npm-asset',
'@tests' => '@app/tests',
],
'components' => [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
],
'params' => $params,
/*
'controllerMap' => [
'fixture' => [ // Fixture generation command line.
'class' => 'yii\faker\FixtureController',
],
],
*/
];
if (false && YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
];
}
return $config;
<|endoftext|># Codeception Test Suite Configuration
# suite for unit (internal) tests.
# RUN `build` COMMAND AFTER ADDING/REMOVING MODULES.
class_name: UnitTester
modules:
enabled:
- Asserts
- Yii2:
part: [orm, email, fixtures]
<|endoftext|><?php
define('YII_ENV', 'test');
defined('YII_DEBUG') or define('YII_DEBUG', true);
require_once __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
require __DIR__ .'/../vendor/autoload.php';<|endoftext|># Codeception Test Suite Configuration
# suite for functional (integration) tests.
# emulate web requests and make application process them.
# (tip: better to use with frameworks).
# RUN `build` COMMAND AFTER ADDING/REMOVING MODULES.
#basic/web/index.php
class_name: FunctionalTester
modules:
enabled:
- Filesystem
- Yii2
<|endoftext|>#!/usr/bin/env bash
#== Import script args ==
timezone=$(echo "$1")
#== Bash helpers ==
function info {
echo " "
echo "--> $1"
echo " "
}
#== Provision script ==
info "Provision-script user: `whoami`"
export DEBIAN_FRONTEND=noninteractive
info "Configure timezone"
timedatectl set-timezone ${timezone} --no-ask-password
info "Prepare root password for MySQL"
debconf-set-selections <<< "mariadb-server-10.0 mysql-server/root_password password \"''\""
debconf-set-selections <<< "mariadb-server-10.0 mysql-server/root_password_again password \"''\""
echo "Done!"
info "Update OS software"
apt-get update
apt-get upgrade -y
info "Install additional software"
apt-get install -y php7.0-curl php7.0-cli php7.0-intl php7.0-mysqlnd php7.0-gd php7.0-fpm php7.0-mbstring php7.0-xml unzip nginx mariadb-server-10.0 php.xdebug
info "Configure MySQL"
sed -i "s/.*bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/mariadb.conf.d/50-server.cnf
mysql -uroot <<< "CREATE USER 'root'@'%' IDENTIFIED BY ''"
mysql -uroot <<< "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'"
mysql -uroot <<< "DROP USER 'root'@'localhost'"
mysql -uroot <<< "FLUSH PRIVILEGES"
echo "Done!"
info "Configure PHP-FPM"
sed -i 's/user = www-data/user = vagrant/g' /etc/php/7.0/fpm/pool.d/www.conf
sed -i 's/group = www-data/group = vagrant/g' /etc/php/7.0/fpm/pool.d/www.conf
sed -i 's/owner = www-data/owner = vagrant/g' /etc/php/7.0/fpm/pool.d/www.conf
cat << EOF > /etc/php/7.0/mods-available/xdebug.ini
zend_extension=xdebug.so
xdebug.remote_enable=1
xdebug.remote_connect_back=1
xdebug.remote_port=9000
xdebug.remote_autostart=1
EOF
echo "Done!"
info "Configure NGINX"
sed -i 's/user www-data/user vagrant/g' /etc/nginx/nginx.conf
echo "Done!"
info "Enabling site configuration"
ln -s /app/vagrant/nginx/app.conf /etc/nginx/sites-enabled/app.conf
echo "Done!"
info "Removing default site configuration"
rm /etc/nginx/sites-enabled/default
echo "Done!"
info "Initailize databases for MySQL"
mysql -uroot <<< "CREATE DATABASE yii2basic"
mysql -uroot <<< "CREATE DATABASE yii2basic_test"
echo "Done!"
info "Install composer"
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer<|endoftext|>#!/usr/bin/env bash
#== Import script args ==
github_token=$(echo "$1")
#== Bash helpers ==
function info {
echo " "
echo "--> $1"
echo " "
}
#== Provision script ==
info "Provision-script user: `whoami`"
info "Configure composer"
composer config --global github-oauth.github.com ${github_token}
echo "Done!"
info "Install project dependencies"
cd /app
composer --no-progress --prefer-dist install
info "Create bash-alias 'app' for vagrant user"
echo 'alias app="cd /app"' | tee /home/vagrant/.bash_aliases
info "Enabling colorized prompt for guest console"
sed -i "s/#force_color_prompt=yes/force_color_prompt=yes/" /home/vagrant/.bashrc
<|endoftext|>#!/usr/bin/env bash
#== Bash helpers ==
function info {
echo " "
echo "--> $1"
echo " "
}
#== Provision script ==
info "Provision-script user: `whoami`"
info "Restart web-stack"
service php7.0-fpm restart
service nginx restart
service mysql restart<|endoftext|># Your personal GitHub token
github_token: <your-personal-github-token>
# Read more: https://github.com/blog/1509-personal-api-tokens
# You can generate it here: https://github.com/settings/tokens
# Guest OS timezone
timezone: Europe/London
# Are we need check box updates for every 'vagrant up'?
box_check_update: false
# Virtual machine name
machine_name: yii2basic
# Virtual machine IP
ip: 192.168.83.137
# Virtual machine CPU cores number
cpus: 1
# Virtual machine RAM
memory: 1024
<|endoftext|><?php
// add unit testing specific bootstrap code here
<|endoftext|><?php
use yii\helpers\Url;
class LoginCest
{
public function ensureThatLoginWorks(AcceptanceTester $I)
{
$I->amOnPage(Url::toRoute('/site/login'));
$I->see('Login', 'h1');
$I->amGoingTo('try to login with correct credentials');
$I->fillField('input[name="LoginForm[username]"]', 'admin');
$I->fillField('input[name="LoginForm[password]"]', 'admin');
$I->click('login-button');
$I->wait(2); // wait for button to be clicked
$I->expectTo('see user info');
$I->see('Logout');
}
}
<|endoftext|><?php
use yii\helpers\Url;
class HomeCest
{
public function ensureThatHomePageWorks(AcceptanceTester $I)
{
$I->amOnPage(Url::toRoute('/site/index'));
$I->see('My Company');
$I->seeLink('About');
$I->click('About');
$I->wait(2); // wait for page to be opened
$I->see('This is the About page.');
}
}
<|endoftext|><?php
use yii\helpers\Url;
class ContactCest
{
public function _before(\AcceptanceTester $I)
{
$I->amOnPage(Url::toRoute('/site/contact'));
}
public function contactPageWorks(AcceptanceTester $I)
{
$I->wantTo('ensure that contact page works');
$I->see('Contact', 'h1');
}
public function contactFormCanBeSubmitted(AcceptanceTester $I)
{
$I->amGoingTo('submit contact form with correct data');
$I->fillField('#contactform-name', 'tester');
$I->fillField('#contactform-email', 'tester@example.com');
$I->fillField('#contactform-subject', 'test subject');
$I->fillField('#contactform-body', 'test content');
$I->fillField('#contactform-verifycode', 'testme');
$I->click('contact-button');
$I->wait(2); // wait for button to be clicked
$I->dontSeeElement('#contact-form');
$I->see('Thank you for contacting us. We will respond to you as soon as possible.');
}
}
<|endoftext|><?php
use yii\helpers\Url;
class AboutCest
{
public function ensureThatAboutWorks(AcceptanceTester $I)
{
$I->amOnPage(Url::toRoute('/site/about'));
$I->see('About', 'h1');
}
}
<|endoftext|><?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class AcceptanceTester extends \Codeception\Actor
{
use _generated\AcceptanceTesterActions;
/**
* Define custom actions here
*/
}
<|endoftext|><?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class FunctionalTester extends \Codeception\Actor
{
use _generated\FunctionalTesterActions;
}
<|endoftext|><?php
/**
* Inherited Methods
* @method void wantToTest($text)
* @method void wantTo($text)
* @method void execute($callable)
* @method void expectTo($prediction)
* @method void expect($prediction)
* @method void amGoingTo($argumentation)
* @method void am($role)
* @method void lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
*
* @SuppressWarnings(PHPMD)
*/
class UnitTester extends \Codeception\Actor
{
use _generated\UnitTesterActions;
/**
* Define custom actions here
*/
}
<|endoftext|><?php
class LoginFormCest
{
public function _before(\FunctionalTester $I)
{
$I->amOnRoute('site/login');
}
public function openLoginPage(\FunctionalTester $I)
{
$I->see('Login', 'h1');
}
// demonstrates `amLoggedInAs` method
public function internalLoginById(\FunctionalTester $I)
{
$I->amLoggedInAs(100);
$I->amOnPage('/');
$I->see('Logout (admin)');
}
// demonstrates `amLoggedInAs` method
public function internalLoginByInstance(\FunctionalTester $I)
{
$I->amLoggedInAs(\app\models\User::findByUsername('admin'));
$I->amOnPage('/');
$I->see('Logout (admin)');
}
public function loginWithEmptyCredentials(\FunctionalTester $I)
{
$I->submitForm('#login-form', []);
$I->expectTo('see validations errors');
$I->see('Username cannot be blank.');
$I->see('Password cannot be blank.');
}
public function loginWithWrongCredentials(\FunctionalTester $I)
{
$I->submitForm('#login-form', [
'LoginForm[username]' => 'admin',
'LoginForm[password]' => 'wrong',
]);
$I->expectTo('see validations errors');
$I->see('Incorrect username or password.');
}
public function loginSuccessfully(\FunctionalTester $I)
{
$I->submitForm('#login-form', [
'LoginForm[username]' => 'admin',
'LoginForm[password]' => 'admin',
]);
$I->see('Logout (admin)');
$I->dontSeeElement('form#login-form');
}
}<|endoftext|><?php
class ContactFormCest
{
public function _before(\FunctionalTester $I)
{
$I->amOnPage(['site/contact']);
}
public function openContactPage(\FunctionalTester $I)
{
$I->see('Contact', 'h1');
}
public function submitEmptyForm(\FunctionalTester $I)
{
$I->submitForm('#contact-form', []);
$I->expectTo('see validations errors');
$I->see('Contact', 'h1');
$I->see('Name cannot be blank');
$I->see('Email cannot be blank');
$I->see('Subject cannot be blank');
$I->see('Body cannot be blank');
$I->see('The verification code is incorrect');
}
public function submitFormWithIncorrectEmail(\FunctionalTester $I)
{
$I->submitForm('#contact-form', [
'ContactForm[name]' => 'tester',
'ContactForm[email]' => 'tester.email',
'ContactForm[subject]' => 'test subject',
'ContactForm[body]' => 'test content',
'ContactForm[verifyCode]' => 'testme',
]);
$I->expectTo('see that email address is wrong');
$I->dontSee('Name cannot be blank', '.help-inline');
$I->see('Email is not a valid email address.');
$I->dontSee('Subject cannot be blank', '.help-inline');
$I->dontSee('Body cannot be blank', '.help-inline');
$I->dontSee('The verification code is incorrect', '.help-inline');
}
public function submitFormSuccessfully(\FunctionalTester $I)
{
$I->submitForm('#contact-form', [
'ContactForm[name]' => 'tester',
'ContactForm[email]' => 'tester@example.com',
'ContactForm[subject]' => 'test subject',
'ContactForm[body]' => 'test content',
'ContactForm[verifyCode]' => 'testme',
]);
$I->seeEmailIsSent();
$I->dontSeeElement('#contact-form');
$I->see('Thank you for contacting us. We will respond to you as soon as possible.');
}
}
<|endoftext|><?php
namespace tests\unit\models;
use app\models\LoginForm;
class LoginFormTest extends \Codeception\Test\Unit
{
private $model;
protected function _after()
{
\Yii::$app->user->logout();
}
public function testLoginNoUser()
{
$this->model = new LoginForm([
'username' => 'not_existing_username',
'password' => 'not_existing_password',
]);
expect_not($this->model->login());
expect_that(\Yii::$app->user->isGuest);
}
public function testLoginWrongPassword()
{
$this->model = new LoginForm([
'username' => 'demo',
'password' => 'wrong_password',
]);
expect_not($this->model->login());
expect_that(\Yii::$app->user->isGuest);
expect($this->model->errors)->hasKey('password');
}
public function testLoginCorrect()
{
$this->model = new LoginForm([
'username' => 'demo',
'password' => 'demo',
]);
expect_that($this->model->login());
expect_not(\Yii::$app->user->isGuest);
expect($this->model->errors)->hasntKey('password');
}
}
<|endoftext|><?php
namespace tests\unit\models;
use app\models\ContactForm;
use yii\mail\MessageInterface;
class ContactFormTest extends \Codeception\Test\Unit
{
private $model;
/**
* @var \UnitTester
*/
public $tester;
public function testEmailIsSentOnContact()
{
/** @var ContactForm $model */
$this->model = $this->getMockBuilder('app\models\ContactForm')
->setMethods(['validate'])
->getMock();
$this->model->expects($this->once())
->method('validate')
->willReturn(true);
$this->model->attributes = [
'name' => 'Tester',
'email' => 'tester@example.com',
'subject' => 'very important letter subject',
'body' => 'body of current message',
];
expect_that($this->model->contact('admin@example.com'));
// using Yii2 module actions to check email was sent
$this->tester->seeEmailIsSent();
/** @var MessageInterface $emailMessage */
$emailMessage = $this->tester->grabLastSentEmail();
expect('valid email is sent', $emailMessage)->isInstanceOf('yii\mail\MessageInterface');
expect($emailMessage->getTo())->hasKey('admin@example.com');
expect($emailMessage->getFrom())->hasKey('noreply@example.com');
expect($emailMessage->getReplyTo())->hasKey('tester@example.com');
expect($emailMessage->getSubject())->equals('very important letter subject');
expect($emailMessage->toString())->stringContainsString('body of current message');
}
}
<|endoftext|><?php
namespace tests\unit\models;
use app\models\User;
class UserTest extends \Codeception\Test\Unit
{
public function testFindUserById()
{
expect_that($user = User::findIdentity(100));
expect($user->username)->equals('admin');
expect_not(User::findIdentity(999));
}
public function testFindUserByAccessToken()
{
expect_that($user = User::findIdentityByAccessToken('100-token'));
expect($user->username)->equals('admin');
expect_not(User::findIdentityByAccessToken('non-existing'));
}
public function testFindUserByUsername()
{
expect_that($user = User::findByUsername('admin'));
expect_not(User::findByUsername('not-admin'));
}
/**
* @depends testFindUserByUsername
*/
public function testValidateUser($user)
{
$user = User::findByUsername('admin');
expect_that($user->validateAuthKey('test100key'));
expect_not($user->validateAuthKey('test102key'));
expect_that($user->validatePassword('admin'));
expect_not($user->validatePassword('123456'));
}
}
<|endoftext|>name: Build & Deploy
on: [push]
env:
NODE_VERSION: '13.x'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate
- name: Install composer dependencies
run: composer install --no-dev --prefer-dist --no-progress --no-suggest
- name: Migrate database
run: |
php yii migrate/up --interactive 0
php yii db/seed
- name: Use Node.js ${{ env.NODE_VERSION }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.NODE_VERSION }}
- name: Install npm dependencies and build JS and CSS
run: |
npm install
npm run dev
npm run css-dev
- name: Cleanup directory
run: |
rm -rf .git .github node_modules resources tests vagrant
rm .bowerrc .gitignore Vagrantfile *.js *.json *.php *.png *.yml
- name: Deploy to server via scp
uses: appleboy/scp-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USERNAME }}
password: ${{ secrets.SSH_PASSWORD }}
port: 22
source: "."
target: "/home/tbreusst/public_html/ch.tebe.pingcrm-yii2"
<|endoftext|><?php
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
use yii\helpers\Html;
$this->title = $name;
?>
<div class="flex-center position-ref full-height">
<div class="code"><?= Html::encode($this->title) ?></div>
<div class="message" style="padding: 10px;">
<?= nl2br(Html::encode($message)) ?>
</div>
</div>
<|endoftext|><?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<base href="/">
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title><?= Html::encode($this->title) ?></title>
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 100;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.code {
border-right: 2px solid;
font-size: 26px;
padding: 0 15px 0 15px;
text-align: center;
}
.message {
font-size: 18px;
text-align: center;
}
</style>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<|endoftext|><?php
use yii\helpers\Html;
/* @var $this \yii\web\View view component instance */
/* @var $message \yii\mail\MessageInterface the message being composed */
/* @var $content string main view render result */
?>
<?php $this->beginPage() ?>
<!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() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<|endoftext|>import { InertiaApp } from "@inertiajs/inertia-vue";
import PortalVue from "portal-vue";
import Vue from "vue";
import VueMeta from "vue-meta";
Vue.config.productionTip = false;
Vue.mixin({ methods: { route: window.route } });
Vue.use(InertiaApp);
Vue.use(PortalVue);
Vue.use(VueMeta);
const app = document.getElementById("app");
new Vue({
metaInfo: {
titleTemplate: (title) => (title ? `${title} - Ping CRM` : "Ping CRM"),
},
render: (h) =>
h(InertiaApp, {
props: {
initialPage: JSON.parse(app.dataset.page),
resolveComponent: (name) =>
import(`@/Pages/${name}`).then((module) => module.default),
},
}),
}).$mount(app);
<|endoftext|>
|
philiply/philiply.github.io
| "# philiply.com\n\n## Intro\n\nStoring dev code in github while personal site is hosted on philiply.(...TRUNCATED)
|
benjdiasaad/MapReduce_WordCount
| "package org.mbds.hadoop.wordcount;\n\nimport org.apache.hadoop.fs.Path;\nimport org.apache.hadoop.m(...TRUNCATED)
|
jeffs06/ps4-enable-updates
| "{\n \"title\": \"Enable Updates\",\n \"version\": \"1.0.0\",\n \"updated\": \"2001-01-01T00:00:0(...TRUNCATED)
|
ArtUshak/wiki_tool_python
| "[tool.poetry]\nname = \"wiki_tool_python\"\nversion = \"0.2.7\"\ndescription = \"Script to perform (...TRUNCATED)
|
erickakoyama/cst336_hw4
| "{\n\t\"name\": \"cst336_hw4\",\n\t\"version\": \"1.0.0\",\n\t\"description\": \"\",\n\t\"main\": \"(...TRUNCATED)
|
tearsduh/OG-VANITY
| "import os\nimport threading\nimport time\n\nimport requests\nfrom colorama import Fore\n\nr1 = Fore(...TRUNCATED)
|
eeng/shevek
| "version: \"3\"\nservices:\n shevek:\n build: .\n depends_on:\n - mongo\n ports:\n (...TRUNCATED)
|
pocke/rubocop-typed
| "require: rubocop-typed\n\nAllCops:\n DisabledByDefault: true\n\nTyped:\n Enabled: true\n<|endofte(...TRUNCATED)
|
consolidation/json-api-cli
| "{\n \"name\": \"consolidation/jsonapi-cli\",\n \"description\": \"JSON API cli.\",\n \"lic(...TRUNCATED)
|
Incrementally uploaded Parquet shards under data/ with columns:
repo_name: strtext: strDownloaded all repos from https://huggingface.co/datasets/thepowerfuldeez/the-stack-v2-train-smol-ids-updated and run
formatting / linting / import sort on all files
Using ruff + black + ty stack for python and biomejs for js / ts / html / css / json / graphql
Total amount of tokens: ~100B
Example:
from datasets import load_dataset
ds = load_dataset("thepowerfuldeez/the-stack-v2-train-smol-ids-updated-content", split="train", streaming=True)
for row in ds.take(3):
print(row)