Compare commits

..

No commits in common. "master" and "1.1.0" have entirely different histories.

80 changed files with 2151 additions and 2286 deletions

View File

@ -1,14 +0,0 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
[*.php]
charset = utf-8
indent_size = 4
[*.{json,yml}]
charset = utf-8
indent_size = 2

8
.gitignore vendored
View File

@ -2,10 +2,4 @@
/about/ /about/
*.sublime-* *.sublime-*
tests/_output/* tests/_output/*
lumen-test/app
lumen-test/database
lumen-test/tests/tmp
.idea

View File

@ -4,15 +4,14 @@ php:
- 5.5 - 5.5
- 5.6 - 5.6
- 7.0 - 7.0
- 7.1
- hhvm - hhvm
matrix: matrix:
allow_failures: allow_failures:
- php: hhvm - php: 7.0
sudo: false sudo: false
install: ./install.sh install: ./install.sh
script: ./test.sh script: ./test.sh

21
LICENSE
View File

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Amine Ben hammou <webneat@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

147
README.md
View File

@ -1,11 +1,9 @@
# Lumen generators # Lumen generators
[![Build Status](https://travis-ci.org/webNeat/lumen-generators.svg?branch=master)](https://travis-ci.org/webNeat/lumen-generators) [![Build Status](https://travis-ci.org/webNeat/lumen-generators.svg?branch=master)](https://travis-ci.org/webNeat/lumen-generators)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/webNeat/lumen-generators/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/webNeat/lumen-generators/?branch=master) [![License](https://poser.pugx.org/laravel/framework/license.svg)](http://opensource.org/licenses/MIT)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/838624c3-208d-4ba5-84aa-3afc76b093bb/mini.png)](https://insight.sensiolabs.com/projects/838624c3-208d-4ba5-84aa-3afc76b093bb)
[![License](https://poser.pugx.org/laravel/framework/license.svg)](https://github.com/webNeat/lumen-generators/blob/master/LICENSE)
A collection of generators for [Lumen](http://lumen.laravel.com) and [Laravel 6](http://laravel.com/). A collection of generators for [Lumen](http://lumen.laravel.com) and [Laravel 5](http://laravel.com/).
## Contents ## Contents
@ -81,7 +79,7 @@ wn:route Generates RESTful routes.
To generate a RESTful resource for your application (model, migration, controller and RESTful routes), you simply need to run one single command. For example: To generate a RESTful resource for your application (model, migration, controller and RESTful routes), you simply need to run one single command. For example:
``` ```
php artisan wn:resource task "name;string;required;fillable project_id;integer:unsigned;numeric;fillable,key due;date;;date" --add=timestamps --belongs-to=project php artisan wn:resource task "name;string;required;fillable project_id;integer:unsigned;numeric;fillable,key due;date;;date" --belongs-to=project
``` ```
will generate these files: will generate these files:
@ -259,10 +257,10 @@ More then that, you can generate multiple resources with only one command ! [Cli
The `wn:model` command is used to generate a model class based on Eloquent. It has the following syntax: The `wn:model` command is used to generate a model class based on Eloquent. It has the following syntax:
``` ```
wn:model name [--fillable=...] [--dates=...] [--has-many=...] [--has-one=...] [--belongs-to=...] [--belongs-to-many=...] [--rules=...] [--timestamps=false] [--path=...] [--soft-deletes=true] [--force=true] wn:model name [--fillable=...] [--dates=...] [--has-many=...] [--has-one=...] [--belongs-to=...] [--belongs-to-many=...] [--rules=...] [--path=...]
``` ```
- **name**: the name of the model. - **name**: the name of the model.
`php artisan wn:model Task` generates the following: `php artisan wn:model Task` generates the following:
@ -359,22 +357,12 @@ gives:
]; ];
``` ```
- **--timestamps**: Enables timestamps on the model. Giving `--timestamps=false` will add `public $timestamps = false;` to the generated model. The default value is `true`.
- **--soft-deletes**: Adds `Illuminate\Database\Eloquent\SoftDeletes` trait to the model. This is disabled by default.
- **--force**: tells the generator to override the existing file. By default, if the model file already exists, it will not be overriden and the output will be something like:
```
TestingModel model already exists; use --force option to override it !
```
### Migration Generator ### Migration Generator
The `wn:migration` command is used to generate a migration to create a table with schema. It has the following syntax: The `wn:migration` command is used to generate a migration to create a table with schema. It has the following syntax:
``` ```
wn:migration table [--schema=...] [--add=...] [--keys=...] [--force=true] [--file=...] wn:migration table [--schema=...] [--keys=...] [--file=...]
``` ```
- **table**: the name of the table to create. - **table**: the name of the table to create.
@ -404,7 +392,7 @@ class CreateTasksMigration extends Migration
$table->decimal('amount', 5, 2)->after('size')->default(8); $table->decimal('amount', 5, 2)->after('size')->default(8);
$table->string('title')->nullable(); $table->string('title')->nullable();
// Constraints declaration // Constraints declaration
$table->timestamps();
}); });
} }
@ -415,8 +403,6 @@ class CreateTasksMigration extends Migration
} }
``` ```
- **--add**: Specifies additional columns like `timestamps`, `softDeletes`, `rememberToken` and `nullableTimestamps`.
- **--keys**: the foreign keys of the table following the syntax `field:column:table:on_delete:on_update ...`. The `column` is optional ("id" by default). The `table` is optional if the field follows the naming convention `singular_table_name_id`. `on_delete` and `on_update` are optional too. - **--keys**: the foreign keys of the table following the syntax `field:column:table:on_delete:on_update ...`. The `column` is optional ("id" by default). The `table` is optional if the field follows the naming convention `singular_table_name_id`. `on_delete` and `on_update` are optional too.
``` ```
@ -441,17 +427,15 @@ $table->foreign('user_id')
The `wn:pivot-table` command is used to generate a migration to create a pivot table between two models. It has the following syntax: The `wn:pivot-table` command is used to generate a migration to create a pivot table between two models. It has the following syntax:
``` ```
wn:pivot-table model1 model2 [--add=...] [--force=true] [--file=...] wn:pivot-table model1 model2 [--file=...]
``` ```
- **model1** and **model2**: names of the two models (or the two tables if the models don't follow the naming conventions) - **model1** and **model2**: names of the two models (or the two tables if the models don't follow the naming conventions)
- **--add**: Specifies additional columns like `timestamps`, `softDeletes`, `rememberToken` and `nullableTimestamps`.
- **--file**: The migration file name. By default the name follows the patern `date_time_create_table_name.php`. - **--file**: The migration file name. By default the name follows the patern `date_time_create_table_name.php`.
``` ```
php artisan wn:pivot-table Tag Project --add=timestamps php artisan wn:pivot-table Tag Project
``` ```
gives: gives:
@ -503,16 +487,12 @@ There are two commands for controllers. The first one is `wn:controller:rest-act
Note that the trait doesn't use the common used methods on Laravel (like index, store, ...) to avoid conflicts. Which enables you to use this trait with controllers you already have in your application. Note that the trait doesn't use the common used methods on Laravel (like index, store, ...) to avoid conflicts. Which enables you to use this trait with controllers you already have in your application.
The second command is `wn:controller` which actually generates the controller. The syntax of this command is `wn:controller model [--no-routes] [--force=true]`. The second command is `wn:controller` which actually generates the controller. The syntax of this command is `wn:controller model [--no-routes]`.
- **model**: Name of the model (with namespace if not `App`). - **model**: Name of the model (with namespace if not `App`).
- **--no-routes**: Since routes are generated by default for the controller, this option is used to tell the generator "do not generate routes !". - **--no-routes**: Since routes are generated by default for the controller, this option is used to tell the generator "do not generate routes !".
- **--force**: tells the generator to override the existing file.
- **--laravel**: create Laravel style routes
`php artisan wn:controller Task --no-routes` gives: `php artisan wn:controller Task --no-routes` gives:
@ -533,17 +513,12 @@ class TasksController extends Controller {
The `wn:route` command is used to generate RESTfull routes for a controller. It has the following syntax: The `wn:route` command is used to generate RESTfull routes for a controller. It has the following syntax:
`wn:route resource [--controller=...] [--force=true]` `wn:route resource [--controller=...]`
- **resource**: the resource name to use in the URLs. - **resource**: the resource name to use in the URLs.
- **--controller**: the corresponding controller. If missing it's deducted from the resource name. - **--controller**: the corresponding controller. If missing it's deducted from the resource name.
- **--force**: tells the generator to override the existing file.
- **--laravel**: create Laravel style routes
`php artisan wn:route project-type` adds the following routes: `php artisan wn:route project-type` adds the following routes:
```php ```php
@ -554,20 +529,9 @@ $app->put('project-type/{id}', 'ProjectTypesController@put');
$app->delete('project-type/{id}', 'ProjectTypesController@remove'); $app->delete('project-type/{id}', 'ProjectTypesController@remove');
``` ```
`php artisan wn:route project-type --laravel` adds the following routes:
```php
Route::get('project-type', 'ProjectTypesController@all');
Route::get('project-type/{id}', 'ProjectTypesController@get');
Route::post('project-type', 'ProjectTypesController@add');
Route::put('project-type/{id}', 'ProjectTypesController@put');
Route::delete('project-type/{id}', 'ProjectTypesController@remove');
```
### Resource Generator ### Resource Generator
The `wn:resource` command makes it very easy to generate a RESTful resource. It generates a model, migration, controller and routes. The syntax is : `wn:resource name fields [--add=...] [--has-many=...] [--has-one=...] [--belongs-to=...] [--migration-file=...] [--path=...] [--force=true]` The `wn:resource` command makes it very easy to generate a RESTful resource. It generates a model, migration, controller and routes. The syntax is : `wn:resource name fields [--has-many=...] [--has-one=...] [--belongs-to=...] [--migration-file=...]`
- **name**: the name of the resource used in the URLs and to determine the model, table and controller names. - **name**: the name of the resource used in the URLs and to determine the model, table and controller names.
@ -587,36 +551,22 @@ The `wn:resource` command makes it very easy to generate a RESTful resource. It
- `key`: this field is a foreign key. - `key`: this field is a foreign key.
- **--add**: Specifies additional columns like `timestamps`, `softDeletes`, `rememberToken` and `nullableTimestamps` of the migration and if the list contains no timestamps, the model with contain `public $timestamps = false;`.
- **--has-one**, **--has-many** and **--belongs-to** are the same as for the `wn:model` command. - **--has-one**, **--has-many** and **--belongs-to** are the same as for the `wn:model` command.
- **--migration-file**: passed to the `wn:migration` as the `--file` option. - **--migration-file**: passed to the `wn:migration` as the `--file` option.
- **--path**: Defines where to store the model file as well as its namespace.
- **--force**: tells the generator to override the existing file.
- **--laravel**: create Laravel style routes
### Multiple Resources From File ### Multiple Resources From File
The `wn:resources` (note the "s" in "resources") command takes the generation process to an other level by parsing a file and generating multiple resources based on it. The syntax is The `wn:resources` (note the "s" in "resources") command takes the generation process to an other level by parsing a file and generating multiple resources based on it. The syntax is
``` ```
wn:resources filename [--path=...] [--force=true] wn:resources filename
``` ```
This generator is smart enough to add foreign keys automatically when finding a belongsTo relation. It also generates pivot tables for belongsToMany relations automatically. This generator is smart enough to add foreign keys automatically when finding a belongsTo relation. It also generates pivot tables for belongsToMany relations automatically.
The file given to the command should be a valid YAML file ( for the moment, support of other types like XML or JSON could be added in the future). An example is the following: The file given to the command should be a valid YAML file ( for the moment, support of other types like XML or JSON could be added in the future). An example is the following:
- **--path**: Defines where to store the model files as well as their namespace.
- **--laravel**: create Laravel style routes
```yaml ```yaml
--- ---
Store: Store:
@ -648,7 +598,6 @@ Product:
schema: 'decimal:5,2' # need quotes when using ',' schema: 'decimal:5,2' # need quotes when using ','
rules: numeric rules: numeric
tags: fillable tags: fillable
add: timestamps softDeletes
``` ```
## Testing ## Testing
@ -657,64 +606,6 @@ To test the generators, I included a fresh lumen installation under the folder `
## Development Notes ## Development Notes
- **Comming versions**
- **Seeder and Test generators**
- Requested Feature: [Custom Templates](https://github.com/webNeat/lumen-generators/issues/13)
- Requested Feature: [Fractal integration](https://github.com/webNeat/lumen-generators/issues/24)
- Requested Feature: [Add possibility to not run migrations when using `wn:resources`](https://github.com/webNeat/lumen-generators/issues/23)
- Documentation: [Adding examples](https://github.com/webNeat/lumen-generators/issues/20)
- **Version 1.3.3**
- Bug Fixed: [Rules issue when creating resources from YAML file](https://github.com/webNeat/lumen-generators/issues/30)
- **Version 1.3.2**
- Bug Fixed: [softDeletes not added to model](https://github.com/webNeat/lumen-generators/issues/25)
- **Version 1.3.1**
- Bug Fixed: [duplicate column for the foriegn key when using `wn:resources`](https://github.com/webNeat/lumen-generators/issues/22)
- **Version 1.3.0**
- Requested Feature: [Disabling timestamps](https://github.com/webNeat/lumen-generators/issues/15)
- Requested Feature: [Lumen 5.3 routes support](https://github.com/webNeat/lumen-generators/issues/21)
- **Version 1.2.0**
- Tests fixed.
- Bug fixed: [Undefined index: factory](https://github.com/webNeat/lumen-generators/issues/14)
- Feature added: [Check if file already exists before generating it](https://github.com/webNeat/lumen-generators/issues/11)
- Feature added: [Support for additional columns like nullableTimestamps() and softDeletes() in migrations](https://github.com/webNeat/lumen-generators/issues/12)
- Feature added: [Specifying namespace for `wn:resource` and `wn:resources`](https://github.com/webNeat/lumen-generators/issues/18)
- **Version 1.1.1**
- Pivot table generation from the `wn:resources` command bug fixed.
- **Version 1.1.0**
- Pivot table generator added.
- belongsToMany relationship added to model generator.
- Multiple resources generator adds foreign keys for belongsTo relationships automatically.
- Multiple resources generator adds pivot tables for belongsToMany relationships automatically.
- Generated migrations file names changed to be supported by `migrate` command.
- **Version 1.0.0** - **Version 1.0.0**
- Model Generator - Model Generator
@ -729,6 +620,18 @@ To test the generators, I included a fresh lumen installation under the folder `
- Multiple Resources From File - Multiple Resources From File
- **Version 1.1.0**
- Pivot table generator added.
- belongsToMany relationship added to model generator.
- Multiple resources generator adds foreign keys for belongsTo relationships automatically.
- Multiple resources generator adds pivot tables for belongsToMany relationships automatically.
- Generated migrations file names changed to be supported by `migrate` command.
## Contributing ## Contributing
Pull requests are welcome :D Pull requests are welcome :D

View File

@ -1,5 +1,5 @@
{ {
"name": "zorgcc/lumen-generators", "name": "wn/lumen-generators",
"description": "A collection of generators for Lumen and Laravel 5.", "description": "A collection of generators for Lumen and Laravel 5.",
"keywords": ["lumen", "laravel", "rest", "api", "generators"], "keywords": ["lumen", "laravel", "rest", "api", "generators"],
"license": "MIT", "license": "MIT",
@ -10,10 +10,9 @@
} }
], ],
"require": { "require": {
"php": "^7.2", "php": ">=5.5.0",
"illuminate/console": "^5.1|^6", "illuminate/console": "^5.1",
"illuminate/filesystem": "^5.1|^6", "illuminate/filesystem": "^5.1"
"fzaninotto/faker": "^1.5"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

1911
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +0,0 @@
{
"type": "array",
"fields": {
"type": "object",
"separator": ":",
"fields": ["name","type"]
}
}

View File

@ -28,12 +28,7 @@
} }
}, },
"rules", "rules",
"tags[]", "tags[]"
{
"name": "factory",
"type": "string",
"default": false
}
] ]
} }
} }

View File

@ -2,19 +2,19 @@ APP_ENV=local
APP_DEBUG=true APP_DEBUG=true
APP_KEY=SomeRandomKey!!! APP_KEY=SomeRandomKey!!!
# APP_LOCALE=en APP_LOCALE=en
# APP_FALLBACK_LOCALE=en APP_FALLBACK_LOCALE=en
DB_CONNECTION=sqlite DB_CONNECTION=mysql
# DB_HOST=localhost DB_HOST=localhost
# DB_PORT=3306 DB_PORT=3306
# DB_DATABASE=homestead DB_DATABASE=homestead
# DB_USERNAME=homestead DB_USERNAME=homestead
# DB_PASSWORD=secret DB_PASSWORD=secret
# CACHE_DRIVER=memcached CACHE_DRIVER=memcached
# SESSION_DRIVER=memcached SESSION_DRIVER=memcached
# QUEUE_DRIVER=database QUEUE_DRIVER=database
# MAIL_DRIVER=smtp # MAIL_DRIVER=smtp
# MAIL_HOST=mailtrap.io # MAIL_HOST=mailtrap.io

View File

@ -1,11 +1,6 @@
/vendor /vendor
.env .env
codecept.phar
tests/_output/* tests/_output/*
composer.lock composer.lock
tests/_output/*
codecept.phar

View File

@ -8,4 +8,3 @@ class Controller extends BaseController
{ {
// //
} }

View File

@ -2,7 +2,7 @@
require_once __DIR__.'/../vendor/autoload.php'; require_once __DIR__.'/../vendor/autoload.php';
Dotenv::load(__DIR__.'/../'); // Dotenv::load(__DIR__.'/../');
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View File

@ -1,51 +0,0 @@
# models
rm app/*.php 2> /dev/null
# migrations
rm database/migrations/*.php 2> /dev/null
# routes
echo "<?php
\$app->get(\"/\", function () use (\$app) {
return \$app->welcome();
});" > app/Http/routes.php
echo "<?php
/*
|------------------------------------------
| ***** DUMMY ROUTES FOR TESTING ONLY *****
|------------------------------------------
*/
" > routes/api.php
# Controllers
rm app/Http/Controllers/*.php 2> /dev/null
echo "<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
class Controller extends BaseController
{
//
}
" > app/Http/Controllers/Controller.php
# factories
echo "<?php
\$factory->define(App\User::class, function (\$faker) {
return [
'name' => \$faker->name,
'email' => \$faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
];
});
" > database/factories/ModelFactory.php
# database
rm database/database.sqlite 2> /dev/null
touch database/database.sqlite

View File

@ -5,10 +5,9 @@ paths:
data: tests/_data data: tests/_data
support: tests/_support support: tests/_support
envs: tests/_envs envs: tests/_envs
helpers: nil
settings: settings:
bootstrap: _bootstrap.php bootstrap: _bootstrap.php
colors: false colors: true
memory_limit: 1024M memory_limit: 1024M
extensions: extensions:
enabled: enabled:

View File

@ -13,12 +13,12 @@
"phpunit/phpunit": "~4.0", "phpunit/phpunit": "~4.0",
"fzaninotto/faker": "~1.0", "fzaninotto/faker": "~1.0",
"phpspec/phpspec": "2.0.0", "phpspec/phpspec": "2.0.0",
"codeception/codeception": "^2.2" "codeception/codeception": "2.0.0",
"wn/lumen-generators": "@dev"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"App\\": "app/", "App\\": "app/"
"Wn\\Generators\\": "../src/"
}, },
"classmap": [ "classmap": [
"database/" "database/"

View File

@ -13,9 +13,9 @@ class DatabaseSeeder extends Seeder
public function run() public function run()
{ {
Model::unguard(); Model::unguard();
// $this->call(ProjectsTableSeeder::class); // $this->call('UserTableSeeder');
Model::reguard(); Model::reguard();
} }
} }

View File

@ -0,0 +1,15 @@
<?php
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicExample()
{
$this->visit('/')
->see('Lumen.');
}
}

View File

@ -0,0 +1,14 @@
<?php
class TestCase extends Laravel\Lumen\Testing\TestCase
{
/**
* Creates the application.
*
* @return \Laravel\Lumen\Application
*/
public function createApplication()
{
return require __DIR__.'/../bootstrap/app.php';
}
}

View File

@ -1,26 +0,0 @@
---
Author:
belongsTo: book
fields:
name:
schema: string
tags: fillable
Book:
belongsTo: librarys # Yes I know it's misspelled...
hasOne: author
fields:
title:
schema: string
tags: fillable
published:
schema: date
tags: fillable
Library:
hasMany: books
fields:
name:
schema: string
tags: fillable
address:
schema: string
tags: fillable

View File

@ -12,7 +12,7 @@
* @method void am($role) * @method void am($role)
* @method void lookForwardTo($achieveValue) * @method void lookForwardTo($achieveValue)
* @method void comment($description) * @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = null)
* *
* @SuppressWarnings(PHPMD) * @SuppressWarnings(PHPMD)
*/ */

View File

@ -12,7 +12,7 @@
* @method void am($role) * @method void am($role)
* @method void lookForwardTo($achieveValue) * @method void lookForwardTo($achieveValue)
* @method void comment($description) * @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = null)
* *
* @SuppressWarnings(PHPMD) * @SuppressWarnings(PHPMD)
*/ */

View File

@ -1,6 +1,5 @@
<?php <?php
namespace Helper; namespace Helper;
// here you can define custom actions // here you can define custom actions
// all public methods declared in helper class will be available in $I // all public methods declared in helper class will be available in $I

View File

@ -1,6 +1,5 @@
<?php <?php
namespace Helper; namespace Helper;
// here you can define custom actions // here you can define custom actions
// all public methods declared in helper class will be available in $I // all public methods declared in helper class will be available in $I

View File

@ -1,6 +1,5 @@
<?php <?php
namespace Helper; namespace Helper;
// here you can define custom actions // here you can define custom actions
// all public methods declared in helper class will be available in $I // all public methods declared in helper class will be available in $I

View File

@ -12,7 +12,7 @@
* @method void am($role) * @method void am($role)
* @method void lookForwardTo($achieveValue) * @method void lookForwardTo($achieveValue)
* @method void comment($description) * @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = null)
* *
* @SuppressWarnings(PHPMD) * @SuppressWarnings(PHPMD)
*/ */

View File

@ -1,4 +1,4 @@
<?php //[STAMP] d6606f78456705b0875c6b8343fc6a4a <?php //[STAMP] 90ca27738c5db3919bd1f5813987c735
namespace _generated; namespace _generated;
// This class was automatically generated by build task // This class was automatically generated by build task
@ -17,22 +17,6 @@ trait AcceptanceTesterActions
abstract protected function getScenario(); abstract protected function getScenario();
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that array contains subset.
*
* @param array $subset
* @param array $array
* @param bool $strict
* @param string $message
* @see \Codeception\Module::assertArraySubset()
*/
public function assertArraySubset($subset, $array, $strict = null, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArraySubset', func_get_args()));
}
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
@ -111,7 +95,7 @@ trait AcceptanceTesterActions
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
* @param $regex *
* Conditional Assertion: Test won't be stopped on fail * Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Cli::seeShellOutputMatches() * @see \Codeception\Module\Cli::seeShellOutputMatches()
*/ */
@ -121,7 +105,7 @@ trait AcceptanceTesterActions
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
* @param $regex *
* @see \Codeception\Module\Cli::seeShellOutputMatches() * @see \Codeception\Module\Cli::seeShellOutputMatches()
*/ */
public function seeShellOutputMatches($regex) { public function seeShellOutputMatches($regex) {
@ -129,83 +113,13 @@ trait AcceptanceTesterActions
} }
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks result code
*
* ```php
* <?php
* $I->seeResultCodeIs(0);
* ```
*
* @param $code
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Cli::seeResultCodeIs()
*/
public function canSeeResultCodeIs($code) {
return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeResultCodeIs', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks result code
*
* ```php
* <?php
* $I->seeResultCodeIs(0);
* ```
*
* @param $code
* @see \Codeception\Module\Cli::seeResultCodeIs()
*/
public function seeResultCodeIs($code) {
return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeResultCodeIs', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks result code
*
* ```php
* <?php
* $I->seeResultCodeIsNot(0);
* ```
*
* @param $code
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Cli::seeResultCodeIsNot()
*/
public function canSeeResultCodeIsNot($code) {
return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeResultCodeIsNot', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks result code
*
* ```php
* <?php
* $I->seeResultCodeIsNot(0);
* ```
*
* @param $code
* @see \Codeception\Module\Cli::seeResultCodeIsNot()
*/
public function seeResultCodeIsNot($code) {
return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeResultCodeIsNot', func_get_args()));
}
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
* Enters a directory In local filesystem. * Enters a directory In local filesystem.
* Project root directory is used by default * Project root directory is used by default
* *
* @param string $path * @param $path
* @see \Codeception\Module\Filesystem::amInPath() * @see \Codeception\Module\Filesystem::amInPath()
*/ */
public function amInPath($path) { public function amInPath($path) {
@ -227,7 +141,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $filename * @param $filename
* @see \Codeception\Module\Filesystem::openFile() * @see \Codeception\Module\Filesystem::openFile()
*/ */
public function openFile($filename) { public function openFile($filename) {
@ -246,7 +160,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $filename * @param $filename
* @see \Codeception\Module\Filesystem::deleteFile() * @see \Codeception\Module\Filesystem::deleteFile()
*/ */
public function deleteFile($filename) { public function deleteFile($filename) {
@ -265,7 +179,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $dirname * @param $dirname
* @see \Codeception\Module\Filesystem::deleteDir() * @see \Codeception\Module\Filesystem::deleteDir()
*/ */
public function deleteDir($dirname) { public function deleteDir($dirname) {
@ -284,8 +198,8 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $src * @param $src
* @param string $dst * @param $dst
* @see \Codeception\Module\Filesystem::copyDir() * @see \Codeception\Module\Filesystem::copyDir()
*/ */
public function copyDir($src, $dst) { public function copyDir($src, $dst) {
@ -307,7 +221,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $text * @param $text
* Conditional Assertion: Test won't be stopped on fail * Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::seeInThisFile() * @see \Codeception\Module\Filesystem::seeInThisFile()
*/ */
@ -328,7 +242,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $text * @param $text
* @see \Codeception\Module\Filesystem::seeInThisFile() * @see \Codeception\Module\Filesystem::seeInThisFile()
*/ */
public function seeInThisFile($text) { public function seeInThisFile($text) {
@ -336,74 +250,6 @@ trait AcceptanceTesterActions
} }
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks If opened file has the `number` of new lines.
*
* Usage:
*
* ``` php
* <?php
* $I->openFile('composer.json');
* $I->seeNumberNewLines(5);
* ?>
* ```
*
* @param int $number New lines
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::seeNumberNewLines()
*/
public function canSeeNumberNewLines($number) {
return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeNumberNewLines', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks If opened file has the `number` of new lines.
*
* Usage:
*
* ``` php
* <?php
* $I->openFile('composer.json');
* $I->seeNumberNewLines(5);
* ?>
* ```
*
* @param int $number New lines
* @see \Codeception\Module\Filesystem::seeNumberNewLines()
*/
public function seeNumberNewLines($number) {
return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeNumberNewLines', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that contents of currently opened file matches $regex
*
* @param string $regex
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::seeThisFileMatches()
*/
public function canSeeThisFileMatches($regex) {
return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeThisFileMatches', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that contents of currently opened file matches $regex
*
* @param string $regex
* @see \Codeception\Module\Filesystem::seeThisFileMatches()
*/
public function seeThisFileMatches($regex) {
return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeThisFileMatches', func_get_args()));
}
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
@ -419,7 +265,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $text * @param $text
* Conditional Assertion: Test won't be stopped on fail * Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::seeFileContentsEqual() * @see \Codeception\Module\Filesystem::seeFileContentsEqual()
*/ */
@ -441,7 +287,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $text * @param $text
* @see \Codeception\Module\Filesystem::seeFileContentsEqual() * @see \Codeception\Module\Filesystem::seeFileContentsEqual()
*/ */
public function seeFileContentsEqual($text) { public function seeFileContentsEqual($text) {
@ -461,7 +307,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $text * @param $text
* Conditional Assertion: Test won't be stopped on fail * Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::dontSeeInThisFile() * @see \Codeception\Module\Filesystem::dontSeeInThisFile()
*/ */
@ -480,7 +326,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $text * @param $text
* @see \Codeception\Module\Filesystem::dontSeeInThisFile() * @see \Codeception\Module\Filesystem::dontSeeInThisFile()
*/ */
public function dontSeeInThisFile($text) { public function dontSeeInThisFile($text) {
@ -511,7 +357,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $filename * @param $filename
* @param string $path * @param string $path
* Conditional Assertion: Test won't be stopped on fail * Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::seeFileFound() * @see \Codeception\Module\Filesystem::seeFileFound()
@ -531,7 +377,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $filename * @param $filename
* @param string $path * @param string $path
* @see \Codeception\Module\Filesystem::seeFileFound() * @see \Codeception\Module\Filesystem::seeFileFound()
*/ */
@ -545,7 +391,7 @@ trait AcceptanceTesterActions
* *
* Checks if file does not exist in path * Checks if file does not exist in path
* *
* @param string $filename * @param $filename
* @param string $path * @param string $path
* Conditional Assertion: Test won't be stopped on fail * Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::dontSeeFileFound() * @see \Codeception\Module\Filesystem::dontSeeFileFound()
@ -558,7 +404,7 @@ trait AcceptanceTesterActions
* *
* Checks if file does not exist in path * Checks if file does not exist in path
* *
* @param string $filename * @param $filename
* @param string $path * @param string $path
* @see \Codeception\Module\Filesystem::dontSeeFileFound() * @see \Codeception\Module\Filesystem::dontSeeFileFound()
*/ */
@ -578,7 +424,7 @@ trait AcceptanceTesterActions
* ?> * ?>
* ``` * ```
* *
* @param string $dirname * @param $dirname
* @see \Codeception\Module\Filesystem::cleanDir() * @see \Codeception\Module\Filesystem::cleanDir()
*/ */
public function cleanDir($dirname) { public function cleanDir($dirname) {
@ -591,8 +437,8 @@ trait AcceptanceTesterActions
* *
* Saves contents to file * Saves contents to file
* *
* @param string $filename * @param $filename
* @param string $contents * @param $contents
* @see \Codeception\Module\Filesystem::writeToFile() * @see \Codeception\Module\Filesystem::writeToFile()
*/ */
public function writeToFile($filename, $contents) { public function writeToFile($filename, $contents) {

View File

@ -1,4 +1,4 @@
<?php //[STAMP] d2a298893573661fdbd787dcfa27a7b0 <?php //[STAMP] ffada6587f597b23930f2f63d3309fd0
namespace _generated; namespace _generated;
// This class was automatically generated by build task // This class was automatically generated by build task
@ -15,18 +15,4 @@ trait FunctionalTesterActions
abstract protected function getScenario(); abstract protected function getScenario();
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that array contains subset.
*
* @param array $subset
* @param array $array
* @param bool $strict
* @param string $message
* @see \Codeception\Module::assertArraySubset()
*/
public function assertArraySubset($subset, $array, $strict = null, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArraySubset', func_get_args()));
}
} }

View File

@ -1,4 +1,4 @@
<?php //[STAMP] 1467e0d5027bbc2413077351642a21f3 <?php //[STAMP] c871459f363e639d6d4c21f535bb78f4
namespace _generated; namespace _generated;
// This class was automatically generated by build task // This class was automatically generated by build task
@ -19,29 +19,16 @@ trait UnitTesterActions
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
* Checks that two variables are equal. If you're comparing floating-point values, * Checks that two variables are equal.
* you can specify the optional "delta" parameter which dictates how great of a precision
* error are you willing to tolerate in order to consider the two values equal.
*
* Regular example:
* ```php
* <?php
* $I->assertEquals($element->getChildrenCount(), 5);
* ```
*
* Floating-point example:
* ```php
* <?php
* $I->assertEquals($calculator->add(0.1, 0.2), 0.3, 'Calculator should add the two numbers correctly.', 0.01);
* ```
* *
* @param $expected * @param $expected
* @param $actual * @param $actual
* @param string $message * @param string $message
* @param float $delta *
* @return mixed
* @see \Codeception\Module\Asserts::assertEquals() * @see \Codeception\Module\Asserts::assertEquals()
*/ */
public function assertEquals($expected, $actual, $message = null, $delta = null) { public function assertEquals($expected, $actual, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertEquals', func_get_args())); return $this->getScenario()->runStep(new \Codeception\Step\Action('assertEquals', func_get_args()));
} }
@ -49,29 +36,14 @@ trait UnitTesterActions
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
* Checks that two variables are not equal. If you're comparing floating-point values, * Checks that two variables are not equal
* you can specify the optional "delta" parameter which dictates how great of a precision
* error are you willing to tolerate in order to consider the two values not equal.
*
* Regular example:
* ```php
* <?php
* $I->assertNotEquals($element->getChildrenCount(), 0);
* ```
*
* Floating-point example:
* ```php
* <?php
* $I->assertNotEquals($calculator->add(0.1, 0.2), 0.4, 'Calculator should add the two numbers correctly.', 0.01);
* ```
* *
* @param $expected * @param $expected
* @param $actual * @param $actual
* @param string $message * @param string $message
* @param float $delta
* @see \Codeception\Module\Asserts::assertNotEquals() * @see \Codeception\Module\Asserts::assertNotEquals()
*/ */
public function assertNotEquals($expected, $actual, $message = null, $delta = null) { public function assertNotEquals($expected, $actual, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotEquals', func_get_args())); return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotEquals', func_get_args()));
} }
@ -84,6 +56,8 @@ trait UnitTesterActions
* @param $expected * @param $expected
* @param $actual * @param $actual
* @param string $message * @param string $message
*
* @return mixed
* @see \Codeception\Module\Asserts::assertSame() * @see \Codeception\Module\Asserts::assertSame()
*/ */
public function assertSame($expected, $actual, $message = null) { public function assertSame($expected, $actual, $message = null) {
@ -121,6 +95,17 @@ trait UnitTesterActions
} }
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @deprecated
* @see \Codeception\Module\Asserts::assertGreaterThen()
*/
public function assertGreaterThen($expected, $actual, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterThen', func_get_args()));
}
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
@ -136,6 +121,17 @@ trait UnitTesterActions
} }
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @deprecated
* @see \Codeception\Module\Asserts::assertGreaterThenOrEqual()
*/
public function assertGreaterThenOrEqual($expected, $actual, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterThenOrEqual', func_get_args()));
}
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
@ -226,36 +222,6 @@ trait UnitTesterActions
} }
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that a string starts with the given prefix.
*
* @param string $prefix
* @param string $string
* @param string $message
* @see \Codeception\Module\Asserts::assertStringStartsWith()
*/
public function assertStringStartsWith($prefix, $string, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertStringStartsWith', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that a string doesn't start with the given prefix.
*
* @param string $prefix
* @param string $string
* @param string $message
* @see \Codeception\Module\Asserts::assertStringStartsNotWith()
*/
public function assertStringStartsNotWith($prefix, $string, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertStringStartsNotWith', func_get_args()));
}
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
@ -344,7 +310,7 @@ trait UnitTesterActions
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
* Checks if file exists * Checks if file exists
* *
* @param string $filename * @param string $filename
* @param string $message * @param string $message
* @see \Codeception\Module\Asserts::assertFileExists() * @see \Codeception\Module\Asserts::assertFileExists()
@ -358,7 +324,7 @@ trait UnitTesterActions
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
* Checks if file doesn't exist * Checks if file doesn't exist
* *
* @param string $filename * @param string $filename
* @param string $message * @param string $message
* @see \Codeception\Module\Asserts::assertFileNotExists() * @see \Codeception\Module\Asserts::assertFileNotExists()
@ -368,138 +334,6 @@ trait UnitTesterActions
} }
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $expected
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertGreaterOrEquals()
*/
public function assertGreaterOrEquals($expected, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterOrEquals', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $expected
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertLessOrEquals()
*/
public function assertLessOrEquals($expected, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertLessOrEquals', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertIsEmpty()
*/
public function assertIsEmpty($actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertIsEmpty', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $key
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertArrayHasKey()
*/
public function assertArrayHasKey($key, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArrayHasKey', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $key
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertArrayNotHasKey()
*/
public function assertArrayNotHasKey($key, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArrayNotHasKey', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that array contains subset.
*
* @param array $subset
* @param array $array
* @param bool $strict
* @param string $message
* @see \Codeception\Module::assertArraySubset()
*/
public function assertArraySubset($subset, $array, $strict = null, $message = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArraySubset', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $expectedCount
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertCount()
*/
public function assertCount($expectedCount, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertCount', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $class
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertInstanceOf()
*/
public function assertInstanceOf($class, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertInstanceOf', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $class
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertNotInstanceOf()
*/
public function assertNotInstanceOf($class, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotInstanceOf', func_get_args()));
}
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $type
* @param $actual
* @param $description
* @see \Codeception\Module\Asserts::assertInternalType()
*/
public function assertInternalType($type, $actual, $description = null) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('assertInternalType', func_get_args()));
}
/** /**
* [!] Method is generated. Documentation taken from corresponding module. * [!] Method is generated. Documentation taken from corresponding module.
* *
@ -511,38 +345,4 @@ trait UnitTesterActions
public function fail($message) { public function fail($message) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('fail', func_get_args())); return $this->getScenario()->runStep(new \Codeception\Step\Action('fail', func_get_args()));
} }
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Handles and checks exception called inside callback function.
* Either exception class name or exception instance should be provided.
*
* ```php
* <?php
* $I->expectException(MyException::class, function() {
* $this->doSomethingBad();
* });
*
* $I->expectException(new MyException(), function() {
* $this->doSomethingBad();
* });
* ```
* If you want to check message or exception code, you can pass them with exception instance:
* ```php
* <?php
* // will check that exception MyException is thrown with "Don't do bad things" message
* $I->expectException(new MyException("Don't do bad things"), function() {
* $this->doSomethingBad();
* });
* ```
*
* @param $exception string or \Exception
* @param $callback
* @see \Codeception\Module\Asserts::expectException()
*/
public function expectException($exception, $callback) {
return $this->getScenario()->runStep(new \Codeception\Step\Action('expectException', func_get_args()));
}
} }

View File

@ -7,6 +7,8 @@
class_name: AcceptanceTester class_name: AcceptanceTester
modules: modules:
enabled: enabled:
# - PhpBrowser:
# url: http://localhost/myapp
- \Helper\Acceptance - \Helper\Acceptance
- Cli - Cli
- Filesystem - Filesystem

View File

@ -1,4 +1,4 @@
<?php <?php
$I = new AcceptanceTester($scenario); $I = new AcceptanceTester($scenario);
$I->wantTo('generate a RESTful controller with short model name'); $I->wantTo('generate a RESTful controller with short model name');
@ -8,11 +8,12 @@ $I->seeFileFound('./app/Http/Controllers/TestsController.php');
$I->openFile('./app/Http/Controllers/TestsController.php'); $I->openFile('./app/Http/Controllers/TestsController.php');
$I->seeFileContentsEqual('<?php namespace App\Http\Controllers; $I->seeFileContentsEqual('<?php namespace App\Http\Controllers;
class TestsController extends Controller { class TestsController extends Controller {
const MODEL = "App\\Test"; const MODEL = "App\\Test";
use RESTActions; use RESTActions;
} }
'); ');
@ -25,11 +26,12 @@ $I->seeFileFound('./app/Http/Controllers/CategoriesController.php');
$I->openFile('./app/Http/Controllers/CategoriesController.php'); $I->openFile('./app/Http/Controllers/CategoriesController.php');
$I->seeFileContentsEqual('<?php namespace App\Http\Controllers; $I->seeFileContentsEqual('<?php namespace App\Http\Controllers;
class CategoriesController extends Controller { class CategoriesController extends Controller {
const MODEL = "App\\Models\\Category"; const MODEL = "App\\Models\\Category";
use RESTActions; use RESTActions;
} }
'); ');

View File

@ -1,10 +1,10 @@
<?php <?php
$I = new AcceptanceTester($scenario); $I = new AcceptanceTester($scenario);
$I->wantTo('generate the REST actions trait'); $I->wantTo('generate the REST actions trait');
$I->runShellCommand('php artisan wn:controller:rest-actions --force=true'); $I->runShellCommand('php artisan wn:controller:rest-actions');
$I->seeInShellOutput('REST actions trait generated'); $I->seeInShellOutput('REST actions trait generated');
$I->seeFileFound('./app/Http/Controllers/RESTActions.php'); $I->seeFileFound('./app/Http/Controllers/RESTActions.php');
$I->openFile('./app/Http/Controllers/RESTActions.php'); $I->openFile('./app/Http/Controllers/RESTActions.php');
$I->seeInThisFile('trait RESTActions {'); $I->seeInThisFile('trait RESTActions {');
$I->deleteFile('./app/Http/Controllers/RESTActions.php'); $I->deleteFile('./app/Http/Controllers/RESTActions.php');

View File

@ -1,68 +0,0 @@
<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('generate model factories without fields');
$I->runShellCommand('php artisan wn:factory "App\Task"');
$I->seeInShellOutput('App\Task factory generated');
$I->openFile('./database/factories/ModelFactory.php');
$I->seeInThisFile('
$factory->define(App\Task::class, function ($faker) {
return [
// Fields here
];
});');
$I->writeToFile('./database/factories/ModelFactory.php', "<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
\$factory->define(App\User::class, function (\$faker) {
return [
'name' => \$faker->name,
'email' => \$faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
];
});
");
$I->wantTo('generate model factories with fields');
$I->runShellCommand('php artisan wn:factory "App\Task" --fields="title:sentence(3),description:paragraph(3),due:date,hidden:boolean"');
$I->seeInShellOutput('App\Task factory generated');
$I->openFile('./database/factories/ModelFactory.php');
$I->seeInThisFile(
" 'title' => \$faker->sentence(3)," . PHP_EOL .
" 'description' => \$faker->paragraph(3)," . PHP_EOL .
" 'due' => \$faker->date," . PHP_EOL .
" 'hidden' => \$faker->boolean,"
);
$I->writeToFile('./database/factories/ModelFactory.php', "<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
\$factory->define(App\User::class, function (\$faker) {
return [
'name' => \$faker->name,
'email' => \$faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
];
});
");

View File

@ -1,8 +1,8 @@
<?php <?php
$I = new AcceptanceTester($scenario); $I = new AcceptanceTester($scenario);
$I->wantTo('generate a migration without schema'); $I->wantTo('generate a migration without schema');
$I->runShellCommand('php artisan wn:migration tasks --add=timestamps --file=create_tasks'); $I->runShellCommand('php artisan wn:migration tasks --file=create_tasks');
$I->seeInShellOutput('tasks migration generated'); $I->seeInShellOutput('tasks migration generated');
$I->seeFileFound('./database/migrations/create_tasks.php'); $I->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php'); $I->openFile('./database/migrations/create_tasks.php');
@ -13,7 +13,7 @@ use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration class CreateTasksTable extends Migration
{ {
public function up() public function up()
{ {
Schema::create(\'tasks\', function(Blueprint $table) { Schema::create(\'tasks\', function(Blueprint $table) {
@ -32,39 +32,8 @@ class CreateTasksTable extends Migration
'); ');
$I->deleteFile('./database/migrations/create_tasks.php'); $I->deleteFile('./database/migrations/create_tasks.php');
$I->wantTo('generate a migration without schema or timestamps');
$I->runShellCommand('php artisan wn:migration tasks --file=create_tasks');
$I->seeInShellOutput('tasks migration generated');
$I->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php');
$I->seeFileContentsEqual('<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
public function up()
{
Schema::create(\'tasks\', function(Blueprint $table) {
$table->increments(\'id\');
// Schema declaration
// Constraints declaration
});
}
public function down()
{
Schema::drop(\'tasks\');
}
}
');
$I->deleteFile('./database/migrations/create_tasks.php');
$I->wantTo('generate a migration with schema'); $I->wantTo('generate a migration with schema');
$I->runShellCommand('php artisan wn:migration tasks --add=timestamps --file=create_tasks --schema="amount:decimal.5,2:after.\'size\':default.8 title:string:nullable"'); $I->runShellCommand('php artisan wn:migration tasks --file=create_tasks --schema="amount:decimal.5,2:after.\'size\':default.8 title:string:nullable"');
$I->seeInShellOutput('tasks migration generated'); $I->seeInShellOutput('tasks migration generated');
$I->seeFileFound('./database/migrations/create_tasks.php'); $I->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php'); $I->openFile('./database/migrations/create_tasks.php');
@ -75,7 +44,7 @@ use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration class CreateTasksTable extends Migration
{ {
public function up() public function up()
{ {
Schema::create(\'tasks\', function(Blueprint $table) { Schema::create(\'tasks\', function(Blueprint $table) {
@ -100,24 +69,11 @@ $I->runShellCommand('php artisan wn:migration tasks --file=create_tasks --keys="
$I->seeInShellOutput('tasks migration generated'); $I->seeInShellOutput('tasks migration generated');
$I->seeFileFound('./database/migrations/create_tasks.php'); $I->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php'); $I->openFile('./database/migrations/create_tasks.php');
$I->seeInThisFile( $I->seeInThisFile('$table->foreign(\'category_type_id\')
"\$table->foreign('category_type_id')\n". ->references(\'id\')
" ->references('id')\n". ->on(\'category_types\');');
" ->on('category_types');" $I->seeInThisFile('$table->foreign(\'user_id\')
); ->references(\'identifier\')
$I->seeInThisFile( ->on(\'members\')
"\$table->foreign('user_id')\n". ->onDelete(\'cascade\');');
" ->references('identifier')\n". $I->deleteFile('./database/migrations/create_tasks.php');
" ->on('members')". PHP_EOL .
" ->onDelete('cascade');");
$I->deleteFile('./database/migrations/create_tasks.php');
$I->wantTo('generate a migration with additional columns');
$I->runShellCommand('php artisan wn:migration tasks --file=create_tasks --add=softDeletes,nullableTimestamps');
$I->seeInShellOutput('tasks migration generated');
$I->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php');
$I->dontSeeInThisFile("\$table->timestamps();");
$I->seeInThisFile("\$table->softDeletes();");
$I->seeInThisFile("\$table->nullableTimestamps();");
$I->deleteFile('./database/migrations/create_tasks.php');

View File

@ -1,8 +1,8 @@
<?php <?php
$I = new AcceptanceTester($scenario); $I = new AcceptanceTester($scenario);
$I->wantTo('generate a model without fillable fields or dates'); $I->wantTo('generate a model without fillable fields or dates');
$I->runShellCommand('php artisan wn:model TestingModel --path=tests/tmp --force=true'); $I->runShellCommand('php artisan wn:model TestingModel --path=tests/tmp');
$I->seeInShellOutput('TestingModel model generated'); $I->seeInShellOutput('TestingModel model generated');
$I->seeFileFound('./tests/tmp/TestingModel.php'); $I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php'); $I->openFile('./tests/tmp/TestingModel.php');
@ -13,122 +13,64 @@ use Illuminate\Database\Eloquent\Model;
class TestingModel extends Model { class TestingModel extends Model {
protected $fillable = []; protected $fillable = [];
protected $dates = []; protected $dates = [];
public static $rules = [ public static $rules = [
// Validation rules // Validation rules
]; ];
// Relationships // Relationships
} }
'); ');
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->wantTo('generate a model without fillable fields, dates or timestamps');
$I->runShellCommand('php artisan wn:model TestingModel --path=tests/tmp --force=true --timestamps=false');
$I->seeInShellOutput('TestingModel model generated');
$I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php');
$I->seeFileContentsEqual('<?php namespace Tests\Tmp;
use Illuminate\Database\Eloquent\Model;
class TestingModel extends Model {
protected $fillable = [];
protected $dates = [];
public static $rules = [
// Validation rules
];
public $timestamps = false;
// Relationships
}
');
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->wantTo('generate a model with fillable fields'); $I->wantTo('generate a model with fillable fields');
$I->runShellCommand('php artisan wn:model TestingModel --fillable=name,title --path=tests/tmp'); $I->runShellCommand('php artisan wn:model TestingModel --fillable=name,title --path=tests/tmp');
$I->seeFileFound('./tests/tmp/TestingModel.php'); $I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php'); $I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile('protected $fillable = ["name", "title"];'); $I->seeInThisFile('protected $fillable = ["name", "title"];');
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->wantTo('generate a model with dates fields'); $I->wantTo('generate a model with dates fields');
$I->runShellCommand('php artisan wn:model TestingModel --dates=started_at --path=tests/tmp'); $I->runShellCommand('php artisan wn:model TestingModel --dates=started_at --path=tests/tmp');
$I->seeFileFound('./tests/tmp/TestingModel.php'); $I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php'); $I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile('protected $dates = ["started_at"];'); $I->seeInThisFile('protected $dates = ["started_at"];');
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->wantTo('generate a model with relations'); $I->wantTo('generate a model with relations');
$I->runShellCommand('php artisan wn:model TestingModel --has-many=accounts --belongs-to="owner:App\User" --has-one=number:Phone --path=tests/tmp'); $I->runShellCommand('php artisan wn:model TestingModel --has-many=accounts --belongs-to="owner:App\User" --has-one=number:Phone --path=tests/tmp');
$I->seeFileFound('./tests/tmp/TestingModel.php'); $I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php'); $I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile(' $I->seeInThisFile('
public function accounts() public function accounts()
{ {
return $this->hasMany("Tests\\Tmp\\Account"); return $this->hasMany("Tests\\Tmp\\Account");
} }
'); ');
$I->seeInThisFile(' $I->seeInThisFile('
public function owner() public function owner()
{ {
return $this->belongsTo("App\\User"); return $this->belongsTo("App\\User");
} }
'); ');
$I->seeInThisFile(' $I->seeInThisFile('
public function number() public function number()
{ {
return $this->hasOne("Tests\\Tmp\\Phone"); return $this->hasOne("Tests\\Tmp\\Phone");
} }
'); ');
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->wantTo('generate a model with validation rules'); $I->wantTo('generate a model with validation rules');
$I->runShellCommand('php artisan wn:model TestingModel --rules="name=required age=integer|min:13 email=email|unique:users,email_address" --path=tests/tmp'); $I->runShellCommand('php artisan wn:model TestingModel --rules="name=required age=integer|min:13 email=email|unique:users,email_address" --path=tests/tmp');
$I->seeFileFound('./tests/tmp/TestingModel.php'); $I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php'); $I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile( $I->seeInThisFile('
" public static \$rules = [\n" . public static $rules = [
" \"name\" => \"required\"," . PHP_EOL . "name" => "required",
" \"age\" => \"integer|min:13\"," . PHP_EOL . "age" => "integer|min:13",
" \"email\" => \"email|unique:users,email_address\",\n". "email" => "email|unique:users,email_address",
" ];" ];
);
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->wantTo('generate a model with softDeletes');
$I->runShellCommand('php artisan wn:model TestingModel --soft-deletes=true --path=tests/tmp --force=true');
$I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php');
$I->seeFileContentsEqual('<?php namespace Tests\Tmp;
use Illuminate\Database\Eloquent\Model;
class TestingModel extends Model {
use \Illuminate\Database\Eloquent\SoftDeletes;
protected $fillable = [];
protected $dates = [];
public static $rules = [
// Validation rules
];
// Relationships
}
'); ');
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->deleteFile('./tests/tmp/TestingModel.php');

View File

@ -1,29 +0,0 @@
<?php
$I = new AcceptanceTester($scenario);
// $I->wantTo('generate a pivot table seeder');
// $I->runShellCommand('php artisan wn:pivot-seeder tasks ShortTag');
// $I->seeInShellOutput('ShortTagTaskTableSeeder generated');
// $I->openFile('./database/seeds/ShortTagTaskTableSeeder.php');
// $I->seeInThisFile("
// use Illuminate\Database\Seeder;
// use Faker\Factory as Faker;
// class ShortTagTaskTableSeeder extends Seeder
// {
// public function run()
// {
// \$faker = Faker::create();
// \$firstIds = DB::table('short_tags')->lists('id');
// \$secondIds = DB::table('tasks')->lists('id');
// for(\$i = 0; \$i < 10; \$i++) {
// DB::table('short_tag_task')->insert([
// 'short_tag_id' => \$faker->randomElement(\$firstIds),
// 'task_id' => \$faker->randomElement(\$secondIds)
// ]);
// }
// }
// }");
// $I->deleteFile('./database/seeds/ShortTagTaskTableSeeder.php');

View File

@ -1,8 +1,8 @@
<?php <?php
$I = new AcceptanceTester($scenario); $I = new AcceptanceTester($scenario);
$I->wantTo('generate a pivot table'); $I->wantTo('generate a pivot table');
$I->runShellCommand('php artisan wn:pivot-table Tag Project --add=timestamps --file=pivot_table'); $I->runShellCommand('php artisan wn:pivot-table Tag Project --file=pivot_table');
$I->seeInShellOutput('project_tag migration generated'); $I->seeInShellOutput('project_tag migration generated');
$I->seeFileFound('./database/migrations/pivot_table.php'); $I->seeFileFound('./database/migrations/pivot_table.php');
$I->openFile('./database/migrations/pivot_table.php'); $I->openFile('./database/migrations/pivot_table.php');
@ -13,7 +13,7 @@ use Illuminate\Database\Migrations\Migration;
class CreateProjectTagTable extends Migration class CreateProjectTagTable extends Migration
{ {
public function up() public function up()
{ {
Schema::create(\'project_tag\', function(Blueprint $table) { Schema::create(\'project_tag\', function(Blueprint $table) {
@ -36,4 +36,4 @@ class CreateProjectTagTable extends Migration
} }
} }
'); ');
$I->deleteFile('./database/migrations/pivot_table.php'); $I->deleteFile('./database/migrations/pivot_table.php');

View File

@ -1,8 +1,8 @@
<?php <?php
$I = new AcceptanceTester($scenario); $I = new AcceptanceTester($scenario);
$I->wantTo('generate a RESTful resource'); $I->wantTo('generate a RESTful resource');
$I->runShellCommand('php artisan wn:resource task_category "name;string:unique;requied;fillable;word descr;text:nullable;;fillable;paragraph due;timestamp;;fillable,date;date" --has-many="tags,tasks" --belongs-to="project,creator:User" --add=timestamps --migration-file=create_task_categories'); $I->runShellCommand('php artisan wn:resource task_category "name;string:unique;requied;fillable descr;text:nullable;;fillable project_id;integer;required;key,fillable due;timestamp;;fillable,date" --has-many="tags,tasks" --belongs-to="project,creator:User" --migration-file=create_task_categories');
// Checking the model // Checking the model
$I->seeInShellOutput('TaskCategory model generated'); $I->seeInShellOutput('TaskCategory model generated');
@ -11,34 +11,32 @@ $I->openFile('./app/TaskCategory.php');
$I->seeInThisFile('namespace App;'); $I->seeInThisFile('namespace App;');
$I->seeInThisFile('class TaskCategory extends Model'); $I->seeInThisFile('class TaskCategory extends Model');
$I->seeInThisFile('protected $fillable = ["name", "descr", "due", "project_id", "user_id"];'); $I->seeInThisFile('protected $fillable = ["name", "descr", "project_id", "due"];');
$I->seeInThisFile('protected $dates = ["due"];'); $I->seeInThisFile('protected $dates = ["due"];');
$I->seeInThisFile( $I->seeInThisFile('public static $rules = [
"public static \$rules = [\n". "name" => "requied",
" \"name\" => \"requied\"," . PHP_EOL . "project_id" => "required",
" \"project_id\" => \"required|numeric\"," . PHP_EOL . ];');
" \"user_id\" => \"required|numeric\",\n". $I->seeInThisFile('
" ];"); public function tags()
$I->seeInThisFile( {
' public function tags() return $this->hasMany("App\Tag");
{ }
return $this->hasMany("App\Tag");
}'); public function tasks()
$I->seeInThisFile( {
' public function tasks() return $this->hasMany("App\Task");
{ }
return $this->hasMany("App\Task");
}'); public function project()
$I->seeInThisFile( {
' public function project() return $this->belongsTo("App\Project");
{ }
return $this->belongsTo("App\Project");
}'); public function creator()
$I->seeInThisFile( {
' public function creator() return $this->belongsTo("App\User");
{ }');
return $this->belongsTo("App\User");
}');
$I->deleteFile('./app/TaskCategory.php'); $I->deleteFile('./app/TaskCategory.php');
// Checking the migration // Checking the migration
@ -47,20 +45,17 @@ $I->seeFileFound('./database/migrations/create_task_categories.php');
$I->openFile('./database/migrations/create_task_categories.php'); $I->openFile('./database/migrations/create_task_categories.php');
$I->seeInThisFile('class CreateTaskCategoriesTable extends Migration'); $I->seeInThisFile('class CreateTaskCategoriesTable extends Migration');
$I->seeInThisFile("Schema::create('task_categories', function(Blueprint \$table) {\n". $I->seeInThisFile('Schema::create(\'task_categories\', function(Blueprint $table) {
" \$table->increments('id');\n". $table->increments(\'id\');
" \$table->string('name')->unique();" . PHP_EOL . $table->string(\'name\')->unique();
" \$table->text('descr')->nullable();" . PHP_EOL . $table->text(\'descr\')->nullable();
" \$table->timestamp('due');" . PHP_EOL . $table->integer(\'project_id\');
" \$table->integer('project_id')->unsigned();" . PHP_EOL. $table->timestamp(\'due\');
" \$table->integer('user_id')->unsigned();\n" . $table->foreign(\'project_id\')
" \$table->foreign('project_id')\n". ->references(\'id\')
" ->references('id')\n". ->on(\'projects\');
" ->on('projects');" . PHP_EOL . $table->timestamps();
" \$table->foreign('user_id')\n". });');
" ->references('id')\n".
" ->on('users');\n".
" \$table->timestamps();");
$I->deleteFile('./database/migrations/create_task_categories.php'); $I->deleteFile('./database/migrations/create_task_categories.php');
@ -75,9 +70,9 @@ $I->openFile('./app/Http/Controllers/TaskCategoriesController.php');
$I->seeInThisFile('class TaskCategoriesController extends Controller { $I->seeInThisFile('class TaskCategoriesController extends Controller {
const MODEL = "App\TaskCategory"; const MODEL = "App\TaskCategory";
use RESTActions; use RESTActions;
}'); }');
@ -108,53 +103,3 @@ $app->get("/", function () use ($app) {
return $app->welcome(); return $app->welcome();
}); });
'); ');
// Checking model factory
// $I->openFile('./database/factories/ModelFactory.php');
// $I->seeInThisFile(
// "/**
// * Factory definition for model App\TaskCategory.
// */
// \$factory->define(App\TaskCategory::class, function (\$faker) {
// return [
// 'name' => \$faker->word,
// 'descr' => \$faker->paragraph,
// 'due' => \$faker->date,
// ];
// });");
$I->writeToFile('./database/factories/ModelFactory.php', "<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
\$factory->define(App\User::class, function (\$faker) {
return [
'name' => \$faker->name,
'email' => \$faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
];
});
");
// Checking database seeder
// $I->openFile('./database/seeds/TaskCategoriesTableSeeder.php');
// $I->seeInThisFile('
// use Illuminate\Database\Seeder;
// class TaskCategoriesTableSeeder extends Seeder
// {
// public function run()
// {
// factory(App\TaskCategory::class, 10)->create();
// }
// }');
// $I->deleteFile('./database/seeds/TaskCategoriesTableSeeder.php');

View File

@ -1,136 +0,0 @@
<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('Generate RESTful resources from a file');
$I->writeToFile('database/database.sqlite', '');
$I->runShellCommand('php artisan wn:resources tests/_data/ResourcesTest.yml');
// Checking the model
$I->seeInShellOutput('Author model generated');
$I->seeInShellOutput('Book model generated');
$I->seeInShellOutput('Library model generated');
$I->seeFileFound('./app/Author.php');
$I->seeFileFound('./app/Book.php');
$I->seeFileFound('./app/Library.php');
$I->deleteFile('./app/Author.php');
$I->deleteFile('./app/Book.php');
$I->deleteFile('./app/Library.php');
// Checking the migration
$I->seeInShellOutput('authors migration generated');
$I->seeInShellOutput('books migration generated');
$I->seeInShellOutput('libraries migration generated');
// Can't check for specific file names, so we'll just strip the directory
$I->cleanDir('database/migrations');
$I->writeToFile('database/migrations/.gitkeep', '');
// Checking the RESTActions trait
$I->seeFileFound('./app/Http/Controllers/RESTActions.php');
$I->deleteFile('./app/Http/Controllers/RESTActions.php');
// Checking the controller
$I->seeInShellOutput('AuthorsController generated');
$I->seeInShellOutput('LibrariesController generated');
$I->seeInShellOutput('BooksController generated');
$I->seeFileFound('./app/Http/Controllers/AuthorsController.php');
$I->seeFileFound('./app/Http/Controllers/LibrariesController.php');
$I->seeFileFound('./app/Http/Controllers/BooksController.php');
$I->deleteFile('./app/Http/Controllers/AuthorsController.php');
$I->deleteFile('./app/Http/Controllers/LibrariesController.php');
$I->deleteFile('./app/Http/Controllers/BooksController.php');
// Checking routes
$I->openFile('./app/Http/routes.php');
$I->seeInThisFile('
$app->get(\'author\', \'AuthorsController@all\');
$app->get(\'author/{id}\', \'AuthorsController@get\');
$app->post(\'author\', \'AuthorsController@add\');
$app->put(\'author/{id}\', \'AuthorsController@put\');
$app->delete(\'author/{id}\', \'AuthorsController@remove\');');
$I->seeInThisFile('
$app->get(\'book\', \'BooksController@all\');
$app->get(\'book/{id}\', \'BooksController@get\');
$app->post(\'book\', \'BooksController@add\');
$app->put(\'book/{id}\', \'BooksController@put\');
$app->delete(\'book/{id}\', \'BooksController@remove\');');
$I->seeInThisFile('
$app->get(\'library\', \'LibrariesController@all\');
$app->get(\'library/{id}\', \'LibrariesController@get\');
$app->post(\'library\', \'LibrariesController@add\');
$app->put(\'library/{id}\', \'LibrariesController@put\');
$app->delete(\'library/{id}\', \'LibrariesController@remove\');');
$I->writeToFile('./app/Http/routes.php', '<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$app->get("/", function () use ($app) {
return $app->welcome();
});
');
// Checking model factory
// $I->openFile('./database/factories/ModelFactory.php');
// $I->seeInThisFile(
// "/**
// * Factory definition for model App\TaskCategory.
// */
// \$factory->define(App\TaskCategory::class, function (\$faker) {
// return [
// 'name' => \$faker->word,
// 'descr' => \$faker->paragraph,
// 'due' => \$faker->date,
// ];
// });");
$I->writeToFile('./database/factories/ModelFactory.php', "<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
\$factory->define(App\User::class, function (\$faker) {
return [
'name' => \$faker->name,
'email' => \$faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
];
});
");
$I->deleteFile('database/database.sqlite');
// Checking database seeder
// $I->openFile('./database/seeds/TaskCategoriesTableSeeder.php');
// $I->seeInThisFile('
// use Illuminate\Database\Seeder;
// class TaskCategoriesTableSeeder extends Seeder
// {
// public function run()
// {
// factory(App\TaskCategory::class, 10)->create();
// }
// }');
// $I->deleteFile('./database/seeds/TaskCategoriesTableSeeder.php');

View File

@ -1,124 +0,0 @@
<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('Generate RESTful resources from a file with Laravel Routes');
$I->writeToFile('database/database.sqlite', '');
$I->runShellCommand('php artisan wn:resources tests/_data/ResourcesTest.yml --laravel=true');
// Checking the model
$I->seeInShellOutput('Author model generated');
$I->seeInShellOutput('Book model generated');
$I->seeInShellOutput('Library model generated');
$I->seeFileFound('./app/Author.php');
$I->seeFileFound('./app/Book.php');
$I->seeFileFound('./app/Library.php');
$I->deleteFile('./app/Author.php');
$I->deleteFile('./app/Book.php');
$I->deleteFile('./app/Library.php');
// Checking the migration
$I->seeInShellOutput('authors migration generated');
$I->seeInShellOutput('books migration generated');
$I->seeInShellOutput('libraries migration generated');
// Can't check for specific file names, so we'll just strip the directory
$I->cleanDir('database/migrations');
$I->writeToFile('database/migrations/.gitkeep', '');
// Checking the RESTActions trait
$I->seeFileFound('./app/Http/Controllers/RESTActions.php');
$I->deleteFile('./app/Http/Controllers/RESTActions.php');
// Checking the controller
$I->seeInShellOutput('AuthorsController generated');
$I->seeInShellOutput('LibrariesController generated');
$I->seeInShellOutput('BooksController generated');
$I->seeFileFound('./app/Http/Controllers/AuthorsController.php');
$I->seeFileFound('./app/Http/Controllers/LibrariesController.php');
$I->seeFileFound('./app/Http/Controllers/BooksController.php');
$I->deleteFile('./app/Http/Controllers/AuthorsController.php');
$I->deleteFile('./app/Http/Controllers/LibrariesController.php');
$I->deleteFile('./app/Http/Controllers/BooksController.php');
$I->seeFileFound('./routes/api.php');
$I->seeInThisFile('
Route::get(\'author\', \'AuthorsController@all\');
Route::get(\'author/{id}\', \'AuthorsController@get\');
Route::post(\'author\', \'AuthorsController@add\');
Route::put(\'author/{id}\', \'AuthorsController@put\');
Route::delete(\'author/{id}\', \'AuthorsController@remove\');');
$I->seeInThisFile('
Route::get(\'book\', \'BooksController@all\');
Route::get(\'book/{id}\', \'BooksController@get\');
Route::post(\'book\', \'BooksController@add\');
Route::put(\'book/{id}\', \'BooksController@put\');
Route::delete(\'book/{id}\', \'BooksController@remove\');');
$I->seeInThisFile('
Route::get(\'library\', \'LibrariesController@all\');
Route::get(\'library/{id}\', \'LibrariesController@get\');
Route::post(\'library\', \'LibrariesController@add\');
Route::put(\'library/{id}\', \'LibrariesController@put\');
Route::delete(\'library/{id}\', \'LibrariesController@remove\');');
$I->writeToFile('./app/Http/routes.php', '<?php
/*
|------------------------------------------
| ***** DUMMY ROUTES FOR TESTING ONLY *****
|------------------------------------------
*/
');
// Checking model factory
// $I->openFile('./database/factories/ModelFactory.php');
// $I->seeInThisFile(
// "/**
// * Factory definition for model App\TaskCategory.
// */
// \$factory->define(App\TaskCategory::class, function (\$faker) {
// return [
// 'name' => \$faker->word,
// 'descr' => \$faker->paragraph,
// 'due' => \$faker->date,
// ];
// });");
$I->writeToFile('./database/factories/ModelFactory.php', "<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
\$factory->define(App\User::class, function (\$faker) {
return [
'name' => \$faker->name,
'email' => \$faker->email,
'password' => str_random(10),
'remember_token' => str_random(10),
];
});
");
$I->deleteFile('database/database.sqlite');
// Checking database seeder
// $I->openFile('./database/seeds/TaskCategoriesTableSeeder.php');
// $I->seeInThisFile('
// use Illuminate\Database\Seeder;
// class TaskCategoriesTableSeeder extends Seeder
// {
// public function run()
// {
// factory(App\TaskCategory::class, 10)->create();
// }
// }');
// $I->deleteFile('./database/seeds/TaskCategoriesTableSeeder.php');

View File

@ -1,4 +1,4 @@
<?php <?php
$I = new AcceptanceTester($scenario); $I = new AcceptanceTester($scenario);
$I->wantTo('generate RESTful routes for a resource with default controller'); $I->wantTo('generate RESTful routes for a resource with default controller');
@ -58,39 +58,4 @@ $I->writeToFile('./app/Http/routes.php', '<?php
$app->get("/", function () use ($app) { $app->get("/", function () use ($app) {
return $app->welcome(); return $app->welcome();
}); });
'); ');
$I->wantTo('run wn:routes in Lumen 5.3+');
if(!file_exists('./routes')) {
mkdir('./routes');
}
$I->writeToFile('./routes/web.php', '<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It is a breeze. Simply tell Lumen the URIs it should respond to
| and give it the Closure to call when that URI is requested.
|
*/
$app->get("/", function () use ($app) {
return $app->version();
});
');
$I->runShellCommand('php artisan wn:route foo --controller=customController');
$I->seeInShellOutput('foo routes generated');
$I->openFile('./routes/web.php');
$I->seeInThisFile("
\$app->get('foo', 'customController@all');
\$app->get('foo/{id}', 'customController@get');
\$app->post('foo', 'customController@add');
\$app->put('foo/{id}', 'customController@put');
\$app->delete('foo/{id}', 'customController@remove');
");
$I->deleteDir('./routes');

View File

@ -1,34 +0,0 @@
<?php
$I = new AcceptanceTester($scenario);
// $I->wantTo('generate a seeder with default options');
// $I->runShellCommand('php artisan wn:seeder "App\Task"');
// $I->seeInShellOutput('TasksTableSeeder generated');
// $I->openFile('./database/seeds/TasksTableSeeder.php');
// $I->seeInThisFile('
// use Illuminate\Database\Seeder;
// class TasksTableSeeder extends Seeder
// {
// public function run()
// {
// factory(App\Task::class, 10)->create();
// }
// }');
// $I->deleteFile('./database/seeds/TasksTableSeeder.php');
// $I->wantTo('generate a seeder with custom options');
// $I->runShellCommand('php artisan wn:seeder "App\Category" --count=25');
// $I->seeInShellOutput('CategoriesTableSeeder generated');
// $I->openFile('./database/seeds/CategoriesTableSeeder.php');
// $I->seeInThisFile('
// use Illuminate\Database\Seeder;
// class CategoriesTableSeeder extends Seeder
// {
// public function run()
// {
// factory(App\Category::class, 25)->create();
// }
// }');
// $I->deleteFile('./database/seeds/CategoriesTableSeeder.php');

View File

@ -40,4 +40,4 @@ class ArgumentFormat {
*/ */
public $format; public $format;
} }

View File

@ -138,9 +138,9 @@ class ArgumentFormatLoader {
$attr = $matches['attr']; $attr = $matches['attr'];
$type = empty($matches['type']) ? null : $matches['type']; $type = empty($matches['type']) ? null : $matches['type'];
$isArray = (isset($matches[2][0]) && $matches[2][0] === '['); $isArray = (@$matches[2][0] === '[');
return [$attr, $type, $isArray]; return [$attr, $type, $isArray];
} }
} }

View File

@ -112,4 +112,4 @@ class ArgumentParser {
return $result; return $result;
} }
} }

View File

@ -8,14 +8,14 @@ use Wn\Generators\Template\TemplateLoader;
class BaseCommand extends Command { class BaseCommand extends Command {
protected $fs; protected $fs;
protected $templates; protected $templates;
public function __construct(Filesystem $fs) public function __construct(Filesystem $fs)
{ {
parent::__construct(); parent::__construct();
$this->fs = $fs; $this->fs = $fs;
$this->templates = new TemplateLoader($fs); $this->templates = new TemplateLoader($fs);
$this->argumentFormatLoader = new ArgumentFormatLoader($fs); $this->argumentFormatLoader = new ArgumentFormatLoader($fs);
@ -31,15 +31,10 @@ class BaseCommand extends Command {
return new ArgumentParser($format); return new ArgumentParser($format);
} }
protected function save($content, $path, $name, $force = false) protected function save($content, $path)
{ {
if (!$force && $this->fs->exists($path) && $this->input->hasOption('force') && !$this->option('force')) {
$this->info("{$name} already exists; use --force option to override it !");
return;
}
$this->makeDirectory($path); $this->makeDirectory($path);
$this->fs->put($path, $content); $this->fs->put($path, $content);
$this->info("{$name} generated !");
} }
protected function makeDirectory($path) protected function makeDirectory($path)
@ -49,9 +44,4 @@ class BaseCommand extends Command {
} }
} }
protected function spaces($n) }
{
return str_repeat(' ', $n);
}
}

View File

@ -1,16 +1,11 @@
<?php namespace Wn\Generators\Commands; <?php namespace Wn\Generators\Commands;
use InvalidArgumentException;
class ControllerCommand extends BaseCommand { class ControllerCommand extends BaseCommand {
protected $signature = 'wn:controller protected $signature = 'wn:controller
{model : Name of the model (with namespace if not App)} {model : Name of the model (with namespace if not App)}
{--no-routes= : without routes} {--no-routes= : without routes}';
{--force= : override the existing files}
{--laravel : Use Laravel style route definitions}
';
protected $description = 'Generates RESTful controller using the RESTActions trait'; protected $description = 'Generates RESTful controller using the RESTActions trait';
@ -33,19 +28,16 @@ class ControllerCommand extends BaseCommand {
]) ])
->get(); ->get();
$this->save($content, "./app/Http/Controllers/{$controller}.php", "{$controller}"); $this->save($content, "./app/Http/Controllers/{$controller}.php");
$this->info("{$controller} generated !");
if(! $this->option('no-routes')){ if(! $this->option('no-routes')){
$options = [ $this->call('wn:route', [
'resource' => snake_case($name, '-'), 'resource' => snake_case($name, '-'),
'--controller' => $controller, '--controller' => $controller
]; ]);
if ($this->option('laravel')) {
$options['--laravel'] = true;
}
$this->call('wn:route', $options);
} }
} }
} }

View File

@ -3,8 +3,7 @@
class ControllerRestActionsCommand extends BaseCommand { class ControllerRestActionsCommand extends BaseCommand {
protected $signature = 'wn:controller:rest-actions protected $signature = 'wn:controller:rest-actions';
{--force= : override the existing files}';
protected $description = 'Generates REST actions trait to use into controllers'; protected $description = 'Generates REST actions trait to use into controllers';
@ -12,7 +11,9 @@ class ControllerRestActionsCommand extends BaseCommand {
{ {
$content = $this->getTemplate('controller/rest-actions')->get(); $content = $this->getTemplate('controller/rest-actions')->get();
$this->save($content, "./app/Http/Controllers/RESTActions.php", "REST actions trait"); $this->save($content, "./app/Http/Controllers/RESTActions.php");
}
} $this->info("REST actions trait generated !");
}
}

View File

@ -1,65 +0,0 @@
<?php namespace Wn\Generators\Commands;
class FactoryCommand extends BaseCommand {
protected $signature = 'wn:factory
{model : full qualified name of the model.}
{--fields= : the fields to generate.}
{--file= : the factories file.}
{--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options}
{--force= : override the existing files}
';
protected $description = 'Generates a model factory';
public function handle()
{
$model = $this->argument('model');
$file = $this->getFile();
$content = $this->fs->get($file);
$content .= $this->getTemplate('factory')
->with([
'model' => $model,
'factory_fields' => $this->getFieldsContent()
])
->get();
$this->save($content, $file, "{$model} factory", true);
}
protected function getFile()
{
$file = $this->option('file');
if(! $file){
$file = './database/factories/ModelFactory.php';
}
return $file;
}
protected function getFieldsContent()
{
$content = [];
$fields = $this->option('fields');
if($fields){
if(! $this->option('parsed')){
$fields = $this->getArgumentParser('factory-fields')->parse($fields);
}
$template = $this->getTemplate('factory/field');
foreach($fields as $field){
$content[] = $template->with($field)->get();
}
$content = implode(PHP_EOL, $content);
} else {
$content = " // Fields here";
}
return $content;
}
}

View File

@ -3,63 +3,47 @@
class MigrationCommand extends BaseCommand { class MigrationCommand extends BaseCommand {
protected $signature = 'wn:migration protected $signature = 'wn:migration
{table : The table name.} {table : The table name.}
{--schema= : the schema.} {--schema= : the schema.}
{--add= : specifies additional columns like timestamps, softDeletes, rememberToken and nullableTimestamps.}
{--keys= : foreign keys.} {--keys= : foreign keys.}
{--file= : name of the migration file (to use only for testing purpose).} {--file= : name of the migration file (to use only for testing purpose).}
{--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options} {--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options}
{--force= : override the existing files} ';
'; // {action : One of create, add, remove or drop options.}
// {action : One of create, add, remove or drop options.} // The action is only create for the moment
// The action is only create for the moment
protected $description = 'Generates a migration to create a table with schema'; protected $description = 'Generates a migration to create a table with schema';
public function handle() public function handle()
{ {
$table = $this->argument('table'); $table = $this->argument('table');
$name = 'Create' . ucwords(camel_case($table)); $name = 'Create' . ucwords(camel_case($table));
$snakeName = snake_case($name);
$content = $this->getTemplate('migration') $content = $this->getTemplate('migration')
->with([ ->with([
'table' => $table, 'table' => $table,
'name' => $name, 'name' => $name,
'schema' => $this->getSchema(), 'schema' => $this->getSchema(),
'additionals' => $this->getAdditionals(),
'constraints' => $this->getConstraints() 'constraints' => $this->getConstraints()
]) ])
->get(); ->get();
$file = $this->option('file'); $file = $this->option('file');
if(! $file){ if(! $file){
$file = date('Y_m_d_His_') . $snakeName . '_table'; $file = date('Y_m_d_His_') . snake_case($name) . '_table';
$this->deleteOldMigration($snakeName);
}else{
$this->deleteOldMigration($file);
} }
$this->save($content, "./database/migrations/{$file}.php", "{$table} migration"); $this->save($content, "./database/migrations/{$file}.php");
}
protected function deleteOldMigration($fileName) $this->info("{$table} migration generated !");
{
foreach (new \DirectoryIterator("./database/migrations/") as $fileInfo){
if($fileInfo->isDot()) continue;
if(strpos($fileInfo->getFilename(), $fileName) !== FALSE){
unlink($fileInfo->getPathname());
}
}
} }
protected function getSchema() protected function getSchema()
{ {
$schema = $this->option('schema'); $schema = $this->option('schema');
if(! $schema){ if(! $schema){
return $this->spaces(12) . "// Schema declaration"; return " // Schema declaration";
} }
$items = $schema; $items = $schema;
@ -75,23 +59,6 @@ class MigrationCommand extends BaseCommand {
return implode(PHP_EOL, $fields); return implode(PHP_EOL, $fields);
} }
protected function getAdditionals()
{
$additionals = $this->option('add');
if (empty($additionals)) {
return '';
}
$additionals = explode(',', $additionals);
$lines = [];
foreach ($additionals as $add) {
$add = trim($add);
$lines[] = $this->spaces(12) . "\$table->{$add}();";
}
return implode(PHP_EOL, $lines);
}
protected function getFieldDeclaration($parts) protected function getFieldDeclaration($parts)
{ {
$name = $parts[0]['name']; $name = $parts[0]['name'];
@ -107,7 +74,7 @@ class MigrationCommand extends BaseCommand {
{ {
$keys = $this->option('keys'); $keys = $this->option('keys');
if(! $keys){ if(! $keys){
return $this->spaces(12) . "// Constraints declaration"; return " // Constraints declaration";
} }
$items = $keys; $items = $keys;
@ -142,23 +109,23 @@ class MigrationCommand extends BaseCommand {
if($key['on_delete']){ if($key['on_delete']){
$constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint') $constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
->with([ ->with([
'event' => 'Delete', 'event' => 'Delete',
'action' => $key['on_delete'] 'action' => $key['on_delete']
]) ])
->get(); ->get();
} }
if($key['on_update']){ if($key['on_update']){
$constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint') $constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
->with([ ->with([
'event' => 'Update', 'event' => 'Update',
'action' => $key['on_update'] 'action' => $key['on_update']
]) ])
->get(); ->get();
} }
return $constraint . ';'; return $constraint . ';';
} }
} }

View File

@ -12,12 +12,8 @@ class ModelCommand extends BaseCommand {
{--belongs-to= : belongsTo relationships.} {--belongs-to= : belongsTo relationships.}
{--belongs-to-many= : belongsToMany relationships.} {--belongs-to-many= : belongsToMany relationships.}
{--rules= : fields validation rules.} {--rules= : fields validation rules.}
{--timestamps=true : enables timestamps on the model.}
{--path=app : where to store the model php file.} {--path=app : where to store the model php file.}
{--soft-deletes= : adds SoftDeletes trait to the model.} {--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options}';
{--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options}
{--force= : override the existing files}
';
protected $description = 'Generates a model class for a RESTfull resource'; protected $description = 'Generates a model class for a RESTfull resource';
@ -33,13 +29,13 @@ class ModelCommand extends BaseCommand {
'fillable' => $this->getAsArrayFields('fillable'), 'fillable' => $this->getAsArrayFields('fillable'),
'dates' => $this->getAsArrayFields('dates'), 'dates' => $this->getAsArrayFields('dates'),
'relations' => $this->getRelations(), 'relations' => $this->getRelations(),
'rules' => $this->getRules(), 'rules' => $this->getRules()
'additional' => $this->getAdditional(),
'uses' => $this->getUses()
]) ])
->get(); ->get();
$this->save($content, "./{$path}/{$name}.php", "{$name} model"); $this->save($content, "./{$path}/{$name}.php");
$this->info("{$name} model generated !");
} }
protected function getAsArrayFields($arg, $isOption = true) protected function getAsArrayFields($arg, $isOption = true)
@ -59,10 +55,10 @@ class ModelCommand extends BaseCommand {
{ {
return str_replace(' ', '\\', ucwords(str_replace('/', ' ', $this->option('path')))); return str_replace(' ', '\\', ucwords(str_replace('/', ' ', $this->option('path'))));
} }
protected function getRelations() protected function getRelations()
{ {
$relations = array_merge([], $relations = array_merge([],
$this->getRelationsByType('hasOne', 'has-one'), $this->getRelationsByType('hasOne', 'has-one'),
$this->getRelationsByType('hasMany', 'has-many'), $this->getRelationsByType('hasMany', 'has-many'),
$this->getRelationsByType('belongsTo', 'belongs-to'), $this->getRelationsByType('belongsTo', 'belongs-to'),
@ -70,7 +66,7 @@ class ModelCommand extends BaseCommand {
); );
if(empty($relations)){ if(empty($relations)){
return " // Relationships"; return "\t// Relationships";
} }
return implode(PHP_EOL, $relations); return implode(PHP_EOL, $relations);
@ -83,7 +79,7 @@ class ModelCommand extends BaseCommand {
if($option){ if($option){
$items = $this->getArgumentParser('relations')->parse($option); $items = $this->getArgumentParser('relations')->parse($option);
$template = ($withTimestamps) ? 'model/relation-with-timestamps' : 'model/relation'; $template = ($withTimestamps) ? 'model/relation-with-timestamps' : 'model/relation';
$template = $this->getTemplate($template); $template = $this->getTemplate($template);
foreach ($items as $item) { foreach ($items as $item) {
@ -103,7 +99,7 @@ class ModelCommand extends BaseCommand {
{ {
$rules = $this->option('rules'); $rules = $this->option('rules');
if(! $rules){ if(! $rules){
return " // Validation rules"; return "\t\t// Validation rules";
} }
$items = $rules; $items = $rules;
if(! $this->option('parsed')){ if(! $this->option('parsed')){
@ -117,19 +113,5 @@ class ModelCommand extends BaseCommand {
return implode(PHP_EOL, $rules); return implode(PHP_EOL, $rules);
} }
protected function getAdditional() }
{
return $this->option('timestamps') == 'false'
? " public \$timestamps = false;" . PHP_EOL . PHP_EOL
: '';
}
protected function getUses()
{
return $this->option('soft-deletes') == 'true'
? ' use \Illuminate\Database\Eloquent\SoftDeletes;' . PHP_EOL . PHP_EOL
: '';
}
}

View File

@ -1,58 +0,0 @@
<?php namespace Wn\Generators\Commands;
class PivotSeederCommand extends BaseCommand {
protected $signature = 'wn:pivot-seeder
{model1 : Name of the first model or table}
{model2 : Name of the second model or table}
{--count=10 : number of elements to add in database.}
{--force= : override the existing files}
';
protected $description = 'Generates seeder for pivot table';
public function handle()
{
$resources = $this->getResources();
$name = $this->getSeederName($resources);
$tables = $this->getTableNames($resources);
$file = "./database/seeds/{$name}.php";
$content = $this->getTemplate('pivot-seeder')
->with([
'first_resource' => $resources[0],
'second_resource' => $resources[1],
'first_table' => $tables[0],
'second_table' => $tables[1],
'name' => $name,
'count' => $this->option('count')
])
->get();
$this->save($content, $file, $name);
}
protected function getResources()
{
$resources = array_map(function($arg) {
return snake_case(str_singular($this->argument($arg)));
}, ['model1', 'model2']);
sort($resources);
return $resources;
}
protected function getSeederName($resources) {
$resources = array_map(function($resource){
return ucwords(camel_case($resource));
}, $resources);
return implode('', $resources) . 'TableSeeder';
}
protected function getTableNames($resources) {
return array_map('str_plural', $resources);
}
}

View File

@ -6,10 +6,8 @@ class PivotTableCommand extends BaseCommand {
protected $signature = 'wn:pivot-table protected $signature = 'wn:pivot-table
{model1 : Name of the first model or table} {model1 : Name of the first model or table}
{model2 : Name of the second model or table} {model2 : Name of the second model or table}
{--add= : specifies additional columns like timestamps, softDeletes, rememberToken and nullableTimestamps.}
{--file= : name of the migration file (to use only for testing purpose).} {--file= : name of the migration file (to use only for testing purpose).}
{--force= : override the existing files} ';
';
protected $description = 'Generates creation migration for a pivot table'; protected $description = 'Generates creation migration for a pivot table';
@ -24,9 +22,7 @@ class PivotTableCommand extends BaseCommand {
'--schema' => $this->schema(), '--schema' => $this->schema(),
'--keys' => $this->keys(), '--keys' => $this->keys(),
'--file' => $this->option('file'), '--file' => $this->option('file'),
'--parsed' => false, '--parsed' => false
'--force' => $this->option('force'),
'--add' => $this->option('add')
]); ]);
} }
@ -35,7 +31,7 @@ class PivotTableCommand extends BaseCommand {
$this->tables = array_map(function($arg) { $this->tables = array_map(function($arg) {
return snake_case(str_singular($this->argument($arg))); return snake_case(str_singular($this->argument($arg)));
}, ['model1', 'model2']); }, ['model1', 'model2']);
sort($this->tables); sort($this->tables);
} }
@ -52,5 +48,5 @@ class PivotTableCommand extends BaseCommand {
return $table . '_id'; return $table . '_id';
}, $this->tables)); }, $this->tables));
} }
} }

View File

@ -1,8 +1,6 @@
<?php namespace Wn\Generators\Commands; <?php namespace Wn\Generators\Commands;
use InvalidArgumentException;
class ResourceCommand extends BaseCommand { class ResourceCommand extends BaseCommand {
protected $signature = 'wn:resource protected $signature = 'wn:resource
@ -13,12 +11,8 @@ class ResourceCommand extends BaseCommand {
{--belongs-to= : belongsTo relationships.} {--belongs-to= : belongsTo relationships.}
{--belongs-to-many= : belongsToMany relationships.} {--belongs-to-many= : belongsToMany relationships.}
{--migration-file= : the migration file name.} {--migration-file= : the migration file name.}
{--add= : specifies additional columns like timestamps, softDeletes, rememberToken and nullableTimestamps.}
{--path=app : where to store the model file.}
{--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options} {--parsed : tells the command that arguments have been already parsed. To use when calling the command from an other command and passing the parsed arguments and options}
{--force= : override the existing files} ';
{--laravel= : Use Laravel style route definitions}
';
protected $description = 'Generates a model, migration, controller and routes for RESTful resource'; protected $description = 'Generates a model, migration, controller and routes for RESTful resource';
@ -42,52 +36,30 @@ class ResourceCommand extends BaseCommand {
'--belongs-to' => $this->option('belongs-to'), '--belongs-to' => $this->option('belongs-to'),
'--belongs-to-many' => $this->option('belongs-to-many'), '--belongs-to-many' => $this->option('belongs-to-many'),
'--rules' => $this->rules(), '--rules' => $this->rules(),
'--path' => $this->option('path'), '--path' => 'app',
'--force' => $this->option('force'),
'--timestamps' => $this->hasTimestamps() ? 'true' : 'false',
'--soft-deletes' => $this->hasSoftDeletes() ? 'true' : 'false',
'--parsed' => true '--parsed' => true
]); ]);
// generating the migration // generating the migration
$this->call('wn:migration', [ $this->call('wn:migration', [
'table' => $tableName, 'table' => $tableName,
'--schema' => $this->schema(), '--schema' => $this->schema(),
'--keys' => $this->migrationKeys(), '--keys' => $this->foreignKeys(),
'--file' => $this->option('migration-file'), '--file' => $this->option('migration-file'),
'--force' => $this->option('force'),
'--add' => $this->option('add'),
'--parsed' => true '--parsed' => true
]); ]);
// generating REST actions trait if doesn't exist // generation REST actions trait if doesn't exist
if(! $this->fs->exists('./app/Http/Controllers/RESTActions.php')){ if(! $this->fs->exists('./app/Http/Controllers/RESTActions.php')){
$this->call('wn:controller:rest-actions'); $this->call('wn:controller:rest-actions');
} }
// generating the controller and routes // generating the controller and routes
$controllerOptions = [ $this->call('wn:controller', [
'model' => $modelName, 'model' => $modelName,
'--force' => $this->option('force'), '--no-routes' => false
'--no-routes' => false,
];
if ($this->option('laravel')) {
$controllerOptions['--laravel'] = true;
}
$this->call('wn:controller', $controllerOptions);
// generating model factory
$this->call('wn:factory', [
'model' => 'App\\' . $modelName,
'--fields' => $this->factoryFields(),
'--force' => $this->option('force'),
'--parsed' => true
]); ]);
// generating database seeder
// $this->call('wn:seeder', [
// 'model' => 'App\\' . $modelName
// ]);
} }
protected function parseFields() protected function parseFields()
@ -95,29 +67,14 @@ class ResourceCommand extends BaseCommand {
$fields = $this->argument('fields'); $fields = $this->argument('fields');
if($this->option('parsed')){ if($this->option('parsed')){
$this->fields = $fields; $this->fields = $fields;
} else if(! $fields){
$this->fields = [];
} else { } else {
if(! $fields){ $this->fields = $this->getArgumentParser('fields')
$this->fields = []; ->parse($fields);
} else {
$this->fields = $this->getArgumentParser('fields')
->parse($fields);
}
$this->fields = array_merge($this->fields, array_map(function($name) {
return [
'name' => $name,
'schema' => [
['name' => 'integer', 'args' => []],
['name' => 'unsigned', 'args' => []]
],
'rules' => 'required|numeric',
'tags' => ['fillable', 'key'],
'factory' => 'key'
];
}, $this->foreignKeys()));
} }
} }
protected function fieldsHavingTag($tag) protected function fieldsHavingTag($tag)
{ {
return array_map(function($field){ return array_map(function($field){
@ -151,57 +108,17 @@ class ResourceCommand extends BaseCommand {
protected function foreignKeys() protected function foreignKeys()
{ {
$belongsTo = $this->option('belongs-to'); return array_map(function($field){
if(! $belongsTo) {
return [];
}
$relations = $this->getArgumentParser('relations')->parse($belongsTo);
return array_map(function($relation){
$name = $relation['model'] ? $relation['model'] : $relation['name'];
$index = strrpos($name, "\\");
if($index) {
$name = substr($name, $index + 1);
}
return snake_case(str_singular($name)) . '_id';
}, $relations);
}
protected function migrationKeys() {
return array_map(function($name) {
return [ return [
'name' => $name, 'name' => $field['name'],
'column' => '', 'column' => '',
'table' => '', 'table' => '',
'on_delete' => '', 'on_delete' => '',
'on_update' => '' 'on_update' => ''
]; ];
}, $this->foreignKeys());
}
protected function factoryFields()
{
return array_map(function($field){
return [
'name' => $field['name'],
'type' => $field['factory']
];
}, array_filter($this->fields, function($field){ }, array_filter($this->fields, function($field){
return isset($field['factory']) && $field['factory']; return in_array('key', $field['tags']);
})); }));
} }
protected function hasTimestamps()
{
$additionals = explode(',', $this->option('add'));
return in_array('nullableTimestamps', $additionals)
|| in_array('timestamps', $additionals)
|| in_array('timestampsTz', $additionals);
}
protected function hasSoftDeletes()
{
$additionals = explode(',', $this->option('add'));
return in_array('softDeletes', $additionals);
}
} }

View File

@ -1,18 +1,12 @@
<?php namespace Wn\Generators\Commands; <?php namespace Wn\Generators\Commands;
use InvalidArgumentException;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
class ResourcesCommand extends BaseCommand { class ResourcesCommand extends BaseCommand {
protected $signature = 'wn:resources protected $signature = 'wn:resources
{file : Path to the file containing resources declarations} {file : Path to the file containing resources declarations}';
{--path=app : where to store the model files.}
{--force= : override the existing files}
{--laravel= : Use Laravel style route definitions}
';
protected $description = 'Generates multiple resources from a file'; protected $description = 'Generates multiple resources from a file';
@ -23,62 +17,39 @@ class ResourcesCommand extends BaseCommand {
$content = $this->fs->get($this->argument('file')); $content = $this->fs->get($this->argument('file'));
$content = Yaml::parse($content); $content = Yaml::parse($content);
$modelIndex = 0;
foreach ($content as $model => $i){ foreach ($content as $model => $i){
$i = $this->getResourceParams($model, $i); $i = $this->getResourceParams($model, $i);
$migrationName = 'Create' . ucwords(str_plural($i['name']));
$migrationFile = date('Y_m_d_His') . '-' . str_pad($modelIndex , 3, 0, STR_PAD_LEFT) . '_' . snake_case($migrationName) . '_table'; $this->call('wn:resource', [
$options = [
'name' => $i['name'], 'name' => $i['name'],
'fields' => $i['fields'], 'fields' => $i['fields'],
'--add' => $i['add'],
'--has-many' => $i['hasMany'], '--has-many' => $i['hasMany'],
'--has-one' => $i['hasOne'], '--has-one' => $i['hasOne'],
'--belongs-to' => $i['belongsTo'], '--belongs-to' => $i['belongsTo'],
'--belongs-to-many' => $i['belongsToMany'], '--belongs-to-many' => $i['belongsToMany']
'--path' => $this->option('path'), ]);
'--force' => $this->option('force'),
'--migration-file' => $migrationFile
];
if ($this->option('laravel')) {
$options['--laravel'] = true;
}
$this->call('wn:resource', $options);
$modelIndex++;
} }
// $this->call('migrate'); // actually needed for pivot seeders !
$this->pivotTables = array_map( $this->pivotTables = array_map(
'unserialize', 'unserialize',
array_unique(array_map('serialize', $this->pivotTables)) array_unique(array_map('serialize', $this->pivotTables))
); );
dd($this->pivotTables);
foreach ($this->pivotTables as $tables) { foreach ($this->pivotTables as $tables) {
$this->call('wn:pivot-table', [ $this->call('wn:pivot-table', [
'model1' => $tables[0], 'model1' => $tables[0],
'model2' => $tables[1], 'model2' => $tables[1]
'--force' => $this->option('force')
]); ]);
// $this->call('wn:pivot-seeder', [
// 'model1' => $tables[0],
// 'model2' => $tables[1],
// '--force' => $this->option('force')
// ]);
} }
$this->call('migrate');
} }
protected function getResourceParams($modelName, $i) protected function getResourceParams($modelName, $i)
{ {
$i['name'] = snake_case($modelName); $i['name'] = snake_case($modelName);
foreach(['hasMany', 'hasOne', 'add', 'belongsTo', 'belongsToMany'] as $relation){ foreach(['hasMany', 'hasOne', 'belongsTo', 'belongsToMany'] as $relation){
if(isset($i[$relation])){ if(isset($i[$relation])){
$i[$relation] = $this->convertArray($i[$relation], ' ', ','); $i[$relation] = $this->convertArray($i[$relation], ' ', ',');
} else { } else {
@ -86,16 +57,35 @@ class ResourcesCommand extends BaseCommand {
} }
} }
if($i['belongsTo']){
$relations = $this->getArgumentParser('relations')->parse($i['belongsTo']);
foreach ($relations as $relation){
$foreignName = '';
if(! $relation['model']){
$foreignName = snake_case($relation['name']) . '_id';
} else {
$names = array_reverse(explode("\\", $relation['model']));
$foreignName = snake_case($names[0]) . '_id';
}
$i['fields'][$foreignName] = [
'schema' => 'integer',
'tags' => 'key'
];
}
}
if($i['belongsToMany']){ if($i['belongsToMany']){
$relations = $this->getArgumentParser('relations')->parse($i['belongsToMany']); $relations = $this->getArgumentParser('relations')->parse($i['belongsToMany']);
foreach ($relations as $relation){ foreach ($relations as $relation){
$table = ''; $table = '';
if(! $relation['model']){ if(! $relation['model']){
$table = snake_case($relation['name']); $table = snake_case($relation['name']);
} else { } else {
$names = array_reverse(explode("\\", $relation['model'])); $names = array_reverse(explode("\\", $relation['model']));
$table = snake_case($names[0]); $table = snake_case($names[0]);
} }
$tables = [ str_singular($table), $i['name'] ]; $tables = [ str_singular($table), $i['name'] ];
@ -119,18 +109,9 @@ class ResourcesCommand extends BaseCommand {
$name = $field['name']; $name = $field['name'];
$schema = $this->convertArray(str_replace(':', '.', $field['schema']), ' ', ':'); $schema = $this->convertArray(str_replace(':', '.', $field['schema']), ' ', ':');
$rules = (isset($field['rules'])) ? trim($field['rules']) : ''; $rules = (isset($field['rules'])) ? trim($field['rules']) : '';
// Replace space by comma
$rules = str_replace(' ', ',', $rules);
$tags = $this->convertArray($field['tags'], ' ', ','); $tags = $this->convertArray($field['tags'], ' ', ',');
$string = "{$name};{$schema};{$rules};{$tags}"; return "{$name};{$schema};{$rules};{$tags}";
if(isset($field['factory']) && !empty($field['factory'])){
$string .= ';' . $field['factory'];
}
return $string;
} }
protected function convertArray($list, $old, $new) protected function convertArray($list, $old, $new)

View File

@ -1,67 +1,30 @@
<?php namespace Wn\Generators\Commands; <?php namespace Wn\Generators\Commands;
use InvalidArgumentException;
class RouteCommand extends BaseCommand { class RouteCommand extends BaseCommand {
protected $signature = 'wn:route protected $signature = 'wn:route
{resource : Name of the resource.} {resource : Name of the resource.}
{--controller= : Name of the RESTful controller.} {--controller= : Name of the RESTful controller.}';
{--laravel= : Use Laravel style route definitions}
';
protected $description = 'Generates RESTful routes.'; protected $description = 'Generates RESTful routes.';
public function handle() public function handle()
{ {
$resource = $this->argument('resource'); $resource = $this->argument('resource');
$laravelRoutes = $this->option('laravel');
$templateFile = 'routes';
$routesPath = 'routes/web.php';
if ($laravelRoutes) {
$templateFile = 'routes-laravel';
$routesPath = 'routes/api.php';
if (!$this->fs->isFile($routesPath)) {
if (!$this->fs->isDirectory('./routes')) {
$this->fs->makeDirectory('./routes');
}
$this->fs->put($routesPath, "
<?php
use Illuminate\Http\Request; $content = $this->fs->get('./app/Http/routes.php');
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the \"api\" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request \$request) {
return \$request->user();
});
"); $content .= PHP_EOL . $this->getTemplate('routes')
} ->with([
} 'resource' => $resource,
'controller' => $this->getController()
])
->get();
if (!$this->fs->isFile($routesPath)) { $this->save($content, './app/Http/routes.php');
$routesPath = 'app/Http/routes.php';
}
$content = $this->fs->get($routesPath);
$content .= PHP_EOL . $this->getTemplate($templateFile) $this->info("{$resource} routes generated !");
->with([
'resource' => $resource,
'controller' => $this->getController()
])
->get();
$this->save($content, $routesPath, "{$resource} routes", true);
} }
protected function getController() protected function getController()
@ -72,5 +35,5 @@ class RouteCommand extends BaseCommand {
} }
return $controller; return $controller;
} }
} }

View File

@ -0,0 +1,4 @@
<?php
/**
* Comming Soon
*/

View File

@ -1,40 +0,0 @@
<?php namespace Wn\Generators\Commands;
class SeederCommand extends BaseCommand {
protected $signature = 'wn:seeder
{model : full qualified name of the model.}
{--count=10 : number of elements to add in database.}
{--force= : override the existing files}
';
protected $description = 'Generates a seeder';
public function handle()
{
$model = $this->argument('model');
$name = $this->getSeederName($model);
$file = "./database/seeds/{$name}.php";
$content = $this->getTemplate('seeder')
->with([
'model' => $model,
'name' => $name,
'count' => $this->option('count')
])
->get();
$this->save($content, $file, $name);
}
protected function getSeederName($name)
{
$name = explode("\\", $name);
$name = ucwords(str_plural($name[count($name) - 1]));
$name = $name . 'TableSeeder';
return $name;
}
}

View File

@ -1,4 +1,4 @@
<?php <?php
/** /**
* Comming Soon * Comming Soon
*/ */

View File

@ -15,10 +15,8 @@ class CommandsServiceProvider extends ServiceProvider
$this->registerResourceCommand(); $this->registerResourceCommand();
$this->registerResourcesCommand(); $this->registerResourcesCommand();
$this->registerPivotTableCommand(); $this->registerPivotTableCommand();
$this->registerFactoryCommand(); // $this->registerSeedCommand();
// registerSeederCommand // $this->registerTestCommand();
// registerPivotSeederCommand
// registerTestCommand
} }
protected function registerModelCommand(){ protected function registerModelCommand(){
@ -26,6 +24,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ModelCommand']; return $app['Wn\Generators\Commands\ModelCommand'];
}); });
$this->commands('command.wn.model'); $this->commands('command.wn.model');
} }
protected function registerControllerRestActionsCommand(){ protected function registerControllerRestActionsCommand(){
@ -33,6 +32,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ControllerRestActionsCommand']; return $app['Wn\Generators\Commands\ControllerRestActionsCommand'];
}); });
$this->commands('command.wn.controller.rest-actions'); $this->commands('command.wn.controller.rest-actions');
} }
protected function registerControllerCommand(){ protected function registerControllerCommand(){
@ -40,6 +40,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ControllerCommand']; return $app['Wn\Generators\Commands\ControllerCommand'];
}); });
$this->commands('command.wn.controller'); $this->commands('command.wn.controller');
} }
protected function registerMigrationCommand(){ protected function registerMigrationCommand(){
@ -47,6 +48,15 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\MigrationCommand']; return $app['Wn\Generators\Commands\MigrationCommand'];
}); });
$this->commands('command.wn.migration'); $this->commands('command.wn.migration');
}
protected function registerSeedCommand(){
$this->app->singleton('command.wn.seed', function($app){
return $app['Wn\Generators\Commands\SeedCommand'];
});
$this->commands('command.wn.seed');
} }
protected function registerRouteCommand(){ protected function registerRouteCommand(){
@ -54,6 +64,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\RouteCommand']; return $app['Wn\Generators\Commands\RouteCommand'];
}); });
$this->commands('command.wn.route'); $this->commands('command.wn.route');
} }
protected function registerTestCommand(){ protected function registerTestCommand(){
@ -61,6 +72,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\TestCommand']; return $app['Wn\Generators\Commands\TestCommand'];
}); });
$this->commands('command.wn.test'); $this->commands('command.wn.test');
} }
protected function registerResourceCommand(){ protected function registerResourceCommand(){
@ -68,6 +80,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ResourceCommand']; return $app['Wn\Generators\Commands\ResourceCommand'];
}); });
$this->commands('command.wn.resource'); $this->commands('command.wn.resource');
} }
protected function registerResourcesCommand(){ protected function registerResourcesCommand(){
@ -75,6 +88,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ResourcesCommand']; return $app['Wn\Generators\Commands\ResourcesCommand'];
}); });
$this->commands('command.wn.resources'); $this->commands('command.wn.resources');
} }
protected function registerPivotTableCommand(){ protected function registerPivotTableCommand(){
@ -82,27 +96,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\PivotTableCommand']; return $app['Wn\Generators\Commands\PivotTableCommand'];
}); });
$this->commands('command.wn.pivot-table'); $this->commands('command.wn.pivot-table');
}
protected function registerFactoryCommand(){
$this->app->singleton('command.wn.factory', function($app){
return $app['Wn\Generators\Commands\FactoryCommand'];
});
$this->commands('command.wn.factory');
}
protected function registerSeederCommand(){
$this->app->singleton('command.wn.seeder', function($app){
return $app['Wn\Generators\Commands\SeederCommand'];
});
$this->commands('command.wn.seeder');
}
protected function registerPivotSeederCommand(){
$this->app->singleton('command.wn.pivot.seeder', function($app){
return $app['Wn\Generators\Commands\PivotSeederCommand'];
});
$this->commands('command.wn.pivot.seeder');
} }
} }

View File

@ -1,4 +1,4 @@
<?php namespace Wn\Generators\Exceptions; <?php namespace Wn\Generators\Exceptions;
class ArgumentFormatException extends \Exception {} class ArgumentFormatException extends \Exception {}

View File

@ -1,4 +1,4 @@
<?php namespace Wn\Generators\Exceptions; <?php namespace Wn\Generators\Exceptions;
class ArgumentParserException extends \Exception {} class ArgumentParserException extends \Exception {}

View File

@ -1,4 +1,4 @@
<?php namespace Wn\Generators\Exceptions; <?php namespace Wn\Generators\Exceptions;
class TemplateException extends \Exception {} class TemplateException extends \Exception {}

View File

@ -59,4 +59,4 @@ class Template {
return $this; return $this;
} }
} }

View File

@ -30,4 +30,4 @@ class TemplateLoader {
return new Template($this, $this->loaded[$name]); return new Template($this, $this->loaded[$name]);
} }
} }

View File

@ -1,9 +1,10 @@
<?php namespace App\Http\Controllers; <?php namespace App\Http\Controllers;
class {{name}} extends Controller { class {{name}} extends Controller {
const MODEL = '{{model}}'; const MODEL = "{{model}}";
use RESTActions; use RESTActions;
} }

View File

@ -1,65 +1,68 @@
<?php namespace App\Http\Controllers; <?php namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Response;
trait RESTActions { trait RESTActions {
protected $statusCodes = [
'done' => 200,
'created' => 201,
'removed' => 204,
'not_valid' => 400,
'not_found' => 404,
'conflict' => 409,
'permissions' => 401
];
public function all() public function all()
{ {
$m = self::MODEL; $m = self::MODEL;
return $this->respond(Response::HTTP_OK, $m::all()); return $this->respond('done', $m::all());
} }
public function get($id) public function get($id)
{ {
$m = self::MODEL; $m = self::MODEL;
$model = $m::find($id); $model = $m::find($id);
if(is_null($model)){ if(is_null($model)){
return $this->respond(Response::HTTP_NOT_FOUND); return $this->respond('not_found');
} }
return $this->respond(Response::HTTP_OK, $model); return $this->respond('done', $model);
} }
public function add(Request $request) public function add(Request $request)
{ {
$m = self::MODEL; $m = self::MODEL;
$this->validate($request, $m::$rules); $this->validate($request, $m::$rules);
return $this->respond(Response::HTTP_CREATED, $m::create($request->all())); return $this->respond('created', $m::create($request->all()));
} }
public function put(Request $request, $id) public function put(Request $request, $id)
{ {
$m = self::MODEL; $m = self::MODEL;
$this->validate($request, $m::$rules); $this->validate($request, $m::$rules);
$model = $m::find($id); $model = $m::find($id);
if(is_null($model)){ if(is_null($model)){
return $this->respond(Response::HTTP_NOT_FOUND); return $this->respond('not_found');
} }
$model->update($request->all()); $model->update($request->all());
return $this->respond(Response::HTTP_OK, $model); return $this->respond('done', $model);
} }
public function remove($id) public function remove($id)
{ {
$m = self::MODEL; $m = self::MODEL;
if(is_null($m::find($id))){ if(is_null($m::find($id))){
return $this->respond(Response::HTTP_NOT_FOUND); return $this->respond('not_found');
} }
$m::destroy($id); $m::destroy($id);
return $this->respond(Response::HTTP_NO_CONTENT); return $this->respond('removed');
} }
protected function respond($status, $data = []) protected function respond($status, $data = [])
{ {
if($status == Response::HTTP_NO_CONTENT){ return response()->json($data, $this->statusCodes[$status]);
return response(null,Response::HTTP_NO_CONTENT);
}
if($status == Response::HTTP_NOT_FOUND){
return response(['message'=>'resource not found'],Response::HTTP_NOT_FOUND);
}
return response()->json($data, $status);
} }
} }

View File

@ -1,9 +0,0 @@
/**
* Factory definition for model {{model}}.
*/
$factory->define({{model}}::class, function ($faker) {
return [
{{factory_fields}}
];
});

View File

@ -1 +0,0 @@
'{{name}}' => $faker->{{type}},

View File

@ -5,14 +5,14 @@ use Illuminate\Database\Migrations\Migration;
class {{name}}Table extends Migration class {{name}}Table extends Migration
{ {
public function up() public function up()
{ {
Schema::create('{{table}}', function(Blueprint $table) { Schema::create('{{table}}', function(Blueprint $table) {
$table->increments('id'); $table->increments('id');
{{schema}} {{schema}}
{{constraints}} {{constraints}}
{{additionals}} $table->timestamps();
}); });
} }

View File

@ -4,14 +4,14 @@ use Illuminate\Database\Eloquent\Model;
class {{name}} extends Model { class {{name}} extends Model {
{{uses}} protected $fillable = [{{fillable}}]; protected $fillable = [{{fillable}}];
protected $dates = [{{dates}}]; protected $dates = [{{dates}}];
public static $rules = [ public static $rules = [
{{rules}} {{rules}}
]; ];
{{additional}}{{relations}} {{relations}}
} }

View File

@ -1,4 +1,4 @@
public function {{name}}() public function {{name}}()
{ {
return $this->{{type}}("{{model}}")->withTimestamps(); return $this->{{type}}("{{model}}")->withTimestamps();
} }

View File

@ -1,4 +1,4 @@
public function {{name}}() public function {{name}}()
{ {
return $this->{{type}}("{{model}}"); return $this->{{type}}("{{model}}");
} }

View File

@ -1 +1 @@
"{{name}}" => "{{rule}}", "{{name}}" => "{{rule}}",

View File

@ -1,22 +0,0 @@
<?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
class {{name}} extends Seeder
{
public function run()
{
$faker = Faker::create();
$firstIds = DB::table('{{first_table}}')->lists('id');
$secondIds = DB::table('{{second_table}}')->lists('id');
for($i = 0; $i < {{count}}; $i++) {
DB::table('{{first_resource}}_{{second_resource}}')->insert([
'{{first_resource}}_id' => $faker->randomElement($firstIds),
'{{second_resource}}_id' => $faker->randomElement($secondIds)
]);
}
}
}

View File

@ -1,8 +0,0 @@
/**
* Routes for resource {{resource}}
*/
Route::get('{{resource}}', '{{controller}}@all');
Route::get('{{resource}}/{id}', '{{controller}}@get');
Route::post('{{resource}}', '{{controller}}@add');
Route::put('{{resource}}/{id}', '{{controller}}@put');
Route::delete('{{resource}}/{id}', '{{controller}}@remove');

View File

@ -1,8 +1,8 @@
/** /**
* Routes for resource {{resource}} * Routes for resource {{resource}}
*/ */
$router->get('{{resource}}', '{{controller}}@all'); $app->get('{{resource}}', '{{controller}}@all');
$router->get('{{resource}}/{id}', '{{controller}}@get'); $app->get('{{resource}}/{id}', '{{controller}}@get');
$router->post('{{resource}}', '{{controller}}@add'); $app->post('{{resource}}', '{{controller}}@add');
$router->put('{{resource}}/{id}', '{{controller}}@put'); $app->put('{{resource}}/{id}', '{{controller}}@put');
$router->delete('{{resource}}/{id}', '{{controller}}@remove'); $app->delete('{{resource}}/{id}', '{{controller}}@remove');

View File

@ -1,11 +0,0 @@
<?php
use Illuminate\Database\Seeder;
class {{name}} extends Seeder
{
public function run()
{
factory({{model}}::class, {{count}})->create();
}
}

View File

@ -1,9 +1,4 @@
#!/usr/bin/env bash
# Runing tests for Lumen # Runing tests for Lumen
cd lumen-test || return cd lumen-test
wget http://codeception.com/codecept.phar
if [ ! -f codecept.phar ]; then
wget http://codeception.com/codecept.phar
fi
php codecept.phar run php codecept.phar run