Compare commits

..

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

80 changed files with 2121 additions and 2525 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

6
.gitignore vendored
View File

@ -3,9 +3,3 @@
*.sublime-*
tests/_output/*
lumen-test/app
lumen-test/database
lumen-test/tests/tmp
.idea

View File

@ -4,12 +4,11 @@ php:
- 5.5
- 5.6
- 7.0
- 7.1
- hhvm
matrix:
allow_failures:
- php: hhvm
- php: 7.0
sudo: false

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.

252
README.md
View File

@ -1,41 +1,8 @@
# 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)
[![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/).
## Contents
- [Why ?](#why)
- [Installation](#installation)
- [Quick Usage](#quick-usage)
- [Detailed Usage](#detailed-usage)
- [Model Generator](#model-generator)
- [Migration Generator](#migration-generator)
- [Pivot Table Generator](#pivot-table-generator) (Since version 1.1.0)
- [Controller Generator](#controller-generator)
- [Routes Generator](#routes-generator)
- [Resource Generator](#resource-generator)
- [Multiple Resources From File](#multiple-resources-from-file)
- [Testing](#testing)
- [Development Notes](#development-notes)
- [Contributing](#contributing)
A collection of generators for Lumen and Laravel 5. Since Lumen comes
## Why ?
@ -70,7 +37,6 @@ wn:controller Generates RESTful controller using the RESTActions t
wn:controller:rest-actions Generates REST actions trait to use into controllers
wn:migration Generates a migration to create a table with schema
wn:model Generates a model class for a RESTfull resource
wn:pivot-table Generates creation migration for a pivot table
wn:resource Generates a model, migration, controller and routes for RESTful resource
wn:resources Generates multiple resources from a file
wn:route Generates RESTful routes.
@ -81,7 +47,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:
```
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:
@ -259,7 +225,7 @@ 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:
```
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=...] [--rules=...] [--path=...]
```
- **name**: the name of the model.
@ -313,10 +279,10 @@ class Task extends Model {
//...
```
- **--has-one**, **--has-many**, **--belongs-to** and **--belongs-to-many**: the relationships of the model following the syntax `relation1:model1,relation2:model2,...`. If the `model` is missing, it will be deducted from the relation's name. If the `model` is given without a namespace, it will be considered having the same namespace as the model being generated.
- **--has-one**, **--has-many** and **--belongs-to**: the relationships of the model following the syntax `relation1:model1,relation2:model2,...`. If the `model` is missing, it will be deducted from the relation's name. If the `model` is given without a namespace, it will be considered having the same namespace as the model being generated.
```
php artisan wn:model Task --has-many=accounts --belongs-to="owner:App\User" --has-one=number:Phone belongs-to-many=tags --path=tests/tmp
php artisan wn:model Task --has-many=accounts --belongs-to="owner:App\User" --has-one=number:Phone --path=tests/tmp
```
gives:
@ -324,22 +290,17 @@ gives:
//...
public function accounts()
{
return $this->hasMany("Tests\Tmp\Account");
return $this->hasMany("Tests\\Tmp\\Account");
}
public function owner()
{
return $this->belongsTo("App\User");
return $this->belongsTo("App\\User");
}
public function number()
{
return $this->hasOne("Tests\Tmp\Phone");
}
public function tags()
{
return $this->belongsToMany("Tests\Tmp\Tag")->withTimestamps();
return $this->hasOne("Tests\\Tmp\\Phone");
}
```
@ -359,27 +320,17 @@ 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
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.
- **--file**: The migration file name (to speicify only for testing purpose). By default the name follows the patern `date_time_create_tableName_table.php`.
- **--file**: The migration file name. By default the name follows the patern `date_time_create_table_name.php`.
- **--schema**: the schema of the table using the syntax `field1:type.arg1,ag2:modifier1:modifier2.. field2:...`. The `type` could be `text`, `string.50`, `decimal.5,2` for example. Modifiers can be `unique` or `nullable` for example. [See documentation](http://laravel.com/docs/5.1/migrations#creating-columns) for the list of available types and modifiers.
@ -404,7 +355,7 @@ class CreateTasksMigration extends Migration
$table->decimal('amount', 5, 2)->after('size')->default(8);
$table->string('title')->nullable();
// Constraints declaration
$table->timestamps();
});
}
@ -415,8 +366,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.
```
@ -436,57 +385,6 @@ $table->foreign('user_id')
->onDelete('cascade');
```
### Pivot Table Generator
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=...]
```
- **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`.
```
php artisan wn:pivot-table Tag Project --add=timestamps
```
gives:
```php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectTagMigration extends Migration
{
public function up()
{
Schema::create('project_tag', function(Blueprint $table) {
$table->increments('id');
$table->integer('project_id')->unsigned()->index();
$table->integer('tag_id')->unsigned()->index();
$table->foreign('project_id')
->references('id')
->on('projects');
$table->foreign('tag_id')
->references('id')
->on('tags');
$table->timestamps();
});
}
public function down()
{
Schema::drop('project_tag');
}
}
```
### Controller Generator
There are two commands for controllers. The first one is `wn:controller:rest-actions` which generates a trait used by all generated controllers. This trait includes the following methods:
@ -503,16 +401,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.
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`).
- **--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:
@ -533,17 +427,12 @@ class TasksController extends Controller {
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.
- **--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
@ -554,20 +443,9 @@ $app->put('project-type/{id}', 'ProjectTypesController@put');
$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
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.
@ -587,36 +465,16 @@ The `wn:resource` command makes it very easy to generate a RESTful resource. It
- `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.
- **--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
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]
```
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 `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`
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
---
Store:
@ -648,88 +506,8 @@ Product:
schema: 'decimal:5,2' # need quotes when using ','
rules: numeric
tags: fillable
add: timestamps softDeletes
```
## Testing
To test the generators, I included a fresh lumen installation under the folder `lumen-test` to which I added this package and have written some acceptance tests using [Codeception](http://codeception.com/). To run tests you just have to execute the `install.sh` to install dependencies then execute `test.sh`.
## 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**
- Model Generator
- Migration Generator
- Controller Generator
- Routes Generator
- Resource Generator
- Multiple Resources From File
## Contributing
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.",
"keywords": ["lumen", "laravel", "rest", "api", "generators"],
"license": "MIT",
@ -10,10 +10,9 @@
}
],
"require": {
"php": "^7.2",
"illuminate/console": "^5.1|^6",
"illuminate/filesystem": "^5.1|^6",
"fzaninotto/faker": "^1.5"
"php": ">=5.5.0",
"illuminate/console": "^5.1",
"illuminate/filesystem": "^5.1"
},
"autoload": {
"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",
"tags[]",
{
"name": "factory",
"type": "string",
"default": false
}
"tags[]"
]
}
}

View File

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

View File

@ -1,11 +1,6 @@
/vendor
.env
codecept.phar
tests/_output/*
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';
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
support: tests/_support
envs: tests/_envs
helpers: nil
settings:
bootstrap: _bootstrap.php
colors: false
colors: true
memory_limit: 1024M
extensions:
enabled:

View File

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

View File

@ -14,7 +14,7 @@ class DatabaseSeeder extends Seeder
{
Model::unguard();
// $this->call(ProjectsTableSeeder::class);
// $this->call('UserTableSeeder');
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 lookForwardTo($achieveValue)
* @method void comment($description)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
* @method \Codeception\Lib\Friend haveFriend($name, $actorClass = null)
*
* @SuppressWarnings(PHPMD)
*/

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
<?php //[STAMP] d6606f78456705b0875c6b8343fc6a4a
<?php //[STAMP] 90ca27738c5db3919bd1f5813987c735
namespace _generated;
// This class was automatically generated by build task
@ -17,22 +17,6 @@ trait AcceptanceTesterActions
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.
*
@ -111,7 +95,7 @@ trait AcceptanceTesterActions
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $regex
*
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Cli::seeShellOutputMatches()
*/
@ -121,7 +105,7 @@ trait AcceptanceTesterActions
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* @param $regex
*
* @see \Codeception\Module\Cli::seeShellOutputMatches()
*/
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.
*
* Enters a directory In local filesystem.
* Project root directory is used by default
*
* @param string $path
* @param $path
* @see \Codeception\Module\Filesystem::amInPath()
*/
public function amInPath($path) {
@ -227,7 +141,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $filename
* @param $filename
* @see \Codeception\Module\Filesystem::openFile()
*/
public function openFile($filename) {
@ -246,7 +160,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $filename
* @param $filename
* @see \Codeception\Module\Filesystem::deleteFile()
*/
public function deleteFile($filename) {
@ -265,7 +179,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $dirname
* @param $dirname
* @see \Codeception\Module\Filesystem::deleteDir()
*/
public function deleteDir($dirname) {
@ -284,8 +198,8 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $src
* @param string $dst
* @param $src
* @param $dst
* @see \Codeception\Module\Filesystem::copyDir()
*/
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
* @see \Codeception\Module\Filesystem::seeInThisFile()
*/
@ -328,7 +242,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $text
* @param $text
* @see \Codeception\Module\Filesystem::seeInThisFile()
*/
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.
*
@ -419,7 +265,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $text
* @param $text
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::seeFileContentsEqual()
*/
@ -441,7 +287,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $text
* @param $text
* @see \Codeception\Module\Filesystem::seeFileContentsEqual()
*/
public function seeFileContentsEqual($text) {
@ -461,7 +307,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $text
* @param $text
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::dontSeeInThisFile()
*/
@ -480,7 +326,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $text
* @param $text
* @see \Codeception\Module\Filesystem::dontSeeInThisFile()
*/
public function dontSeeInThisFile($text) {
@ -511,7 +357,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $filename
* @param $filename
* @param string $path
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::seeFileFound()
@ -531,7 +377,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $filename
* @param $filename
* @param string $path
* @see \Codeception\Module\Filesystem::seeFileFound()
*/
@ -545,7 +391,7 @@ trait AcceptanceTesterActions
*
* Checks if file does not exist in path
*
* @param string $filename
* @param $filename
* @param string $path
* Conditional Assertion: Test won't be stopped on fail
* @see \Codeception\Module\Filesystem::dontSeeFileFound()
@ -558,7 +404,7 @@ trait AcceptanceTesterActions
*
* Checks if file does not exist in path
*
* @param string $filename
* @param $filename
* @param string $path
* @see \Codeception\Module\Filesystem::dontSeeFileFound()
*/
@ -578,7 +424,7 @@ trait AcceptanceTesterActions
* ?>
* ```
*
* @param string $dirname
* @param $dirname
* @see \Codeception\Module\Filesystem::cleanDir()
*/
public function cleanDir($dirname) {
@ -591,8 +437,8 @@ trait AcceptanceTesterActions
*
* Saves contents to file
*
* @param string $filename
* @param string $contents
* @param $filename
* @param $contents
* @see \Codeception\Module\Filesystem::writeToFile()
*/
public function writeToFile($filename, $contents) {

View File

@ -1,4 +1,4 @@
<?php //[STAMP] d2a298893573661fdbd787dcfa27a7b0
<?php //[STAMP] ffada6587f597b23930f2f63d3309fd0
namespace _generated;
// This class was automatically generated by build task
@ -15,18 +15,4 @@ trait FunctionalTesterActions
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;
// This class was automatically generated by build task
@ -19,29 +19,16 @@ trait UnitTesterActions
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that two variables are equal. If you're comparing floating-point values,
* 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);
* ```
* Checks that two variables are equal.
*
* @param $expected
* @param $actual
* @param string $message
* @param float $delta
*
* @return mixed
* @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()));
}
@ -49,29 +36,14 @@ trait UnitTesterActions
/**
* [!] Method is generated. Documentation taken from corresponding module.
*
* Checks that two variables are not equal. If you're comparing floating-point values,
* 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);
* ```
* Checks that two variables are not equal
*
* @param $expected
* @param $actual
* @param string $message
* @param float $delta
* @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()));
}
@ -84,6 +56,8 @@ trait UnitTesterActions
* @param $expected
* @param $actual
* @param string $message
*
* @return mixed
* @see \Codeception\Module\Asserts::assertSame()
*/
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.
*
@ -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.
*
@ -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.
*
@ -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.
*
@ -511,38 +345,4 @@ trait UnitTesterActions
public function fail($message) {
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
modules:
enabled:
# - PhpBrowser:
# url: http://localhost/myapp
- \Helper\Acceptance
- Cli
- Filesystem

View File

@ -8,11 +8,12 @@ $I->seeFileFound('./app/Http/Controllers/TestsController.php');
$I->openFile('./app/Http/Controllers/TestsController.php');
$I->seeFileContentsEqual('<?php namespace App\Http\Controllers;
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->seeFileContentsEqual('<?php namespace App\Http\Controllers;
class CategoriesController extends Controller {
const MODEL = "App\\Models\\Category";
const MODEL = "App\\Models\\Category";
use RESTActions;
use RESTActions;
}
');

View File

@ -2,7 +2,7 @@
$I = new AcceptanceTester($scenario);
$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->seeFileFound('./app/Http/Controllers/RESTActions.php');
$I->openFile('./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

@ -2,7 +2,7 @@
$I = new AcceptanceTester($scenario);
$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->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php');
@ -11,7 +11,7 @@ $I->seeFileContentsEqual('<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
class CreateTasksMigration extends Migration
{
public function up()
@ -32,39 +32,8 @@ class CreateTasksTable extends Migration
');
$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->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->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php');
@ -73,7 +42,7 @@ $I->seeFileContentsEqual('<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
class CreateTasksMigration extends Migration
{
public function up()
@ -100,24 +69,11 @@ $I->runShellCommand('php artisan wn:migration tasks --file=create_tasks --keys="
$I->seeInShellOutput('tasks migration generated');
$I->seeFileFound('./database/migrations/create_tasks.php');
$I->openFile('./database/migrations/create_tasks.php');
$I->seeInThisFile(
"\$table->foreign('category_type_id')\n".
" ->references('id')\n".
" ->on('category_types');"
);
$I->seeInThisFile(
"\$table->foreign('user_id')\n".
" ->references('identifier')\n".
" ->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->seeInThisFile('$table->foreign(\'category_type_id\')
->references(\'id\')
->on(\'category_types\');');
$I->seeInThisFile('$table->foreign(\'user_id\')
->references(\'identifier\')
->on(\'members\')
->onDelete(\'cascade\');');
$I->deleteFile('./database/migrations/create_tasks.php');

View File

@ -2,7 +2,7 @@
$I = new AcceptanceTester($scenario);
$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->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php');
@ -13,122 +13,64 @@ use Illuminate\Database\Eloquent\Model;
class TestingModel extends Model {
protected $fillable = [];
protected $fillable = [];
protected $dates = [];
protected $dates = [];
public static $rules = [
// Validation rules
];
public static $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->runShellCommand('php artisan wn:model TestingModel --fillable=name,title --path=tests/tmp');
$I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile('protected $fillable = ["name", "title"];');
$I->deleteFile('./tests/tmp/TestingModel.php');
$I->wantTo('generate a model with dates fields');
$I->runShellCommand('php artisan wn:model TestingModel --dates=started_at --path=tests/tmp');
$I->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile('protected $dates = ["started_at"];');
$I->deleteFile('./tests/tmp/TestingModel.php');
$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->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile('
public function accounts()
{
return $this->hasMany("Tests\\Tmp\\Account");
}
public function accounts()
{
return $this->hasMany("Tests\\Tmp\\Account");
}
');
$I->seeInThisFile('
public function owner()
{
return $this->belongsTo("App\\User");
}
public function owner()
{
return $this->belongsTo("App\\User");
}
');
$I->seeInThisFile('
public function number()
{
return $this->hasOne("Tests\\Tmp\\Phone");
}
public function number()
{
return $this->hasOne("Tests\\Tmp\\Phone");
}
');
$I->deleteFile('./tests/tmp/TestingModel.php');
$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->seeFileFound('./tests/tmp/TestingModel.php');
$I->openFile('./tests/tmp/TestingModel.php');
$I->seeInThisFile(
" public static \$rules = [\n" .
" \"name\" => \"required\"," . PHP_EOL .
" \"age\" => \"integer|min:13\"," . PHP_EOL .
" \"email\" => \"email|unique:users,email_address\",\n".
" ];"
);
$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->seeInThisFile('
public static $rules = [
"name" => "required",
"age" => "integer|min:13",
"email" => "email|unique:users,email_address",
];
');
$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,39 +0,0 @@
<?php
$I = new AcceptanceTester($scenario);
$I->wantTo('generate a pivot table');
$I->runShellCommand('php artisan wn:pivot-table Tag Project --add=timestamps --file=pivot_table');
$I->seeInShellOutput('project_tag migration generated');
$I->seeFileFound('./database/migrations/pivot_table.php');
$I->openFile('./database/migrations/pivot_table.php');
$I->seeFileContentsEqual('<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectTagTable extends Migration
{
public function up()
{
Schema::create(\'project_tag\', function(Blueprint $table) {
$table->increments(\'id\');
$table->integer(\'project_id\')->unsigned()->index();
$table->integer(\'tag_id\')->unsigned()->index();
$table->foreign(\'project_id\')
->references(\'id\')
->on(\'projects\');
$table->foreign(\'tag_id\')
->references(\'id\')
->on(\'tags\');
$table->timestamps();
});
}
public function down()
{
Schema::drop(\'project_tag\');
}
}
');
$I->deleteFile('./database/migrations/pivot_table.php');

View File

@ -2,7 +2,7 @@
$I = new AcceptanceTester($scenario);
$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
$I->seeInShellOutput('TaskCategory model generated');
@ -11,34 +11,32 @@ $I->openFile('./app/TaskCategory.php');
$I->seeInThisFile('namespace App;');
$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(
"public static \$rules = [\n".
" \"name\" => \"requied\"," . PHP_EOL .
" \"project_id\" => \"required|numeric\"," . PHP_EOL .
" \"user_id\" => \"required|numeric\",\n".
" ];");
$I->seeInThisFile(
' public function tags()
{
return $this->hasMany("App\Tag");
}');
$I->seeInThisFile(
' public function tasks()
{
return $this->hasMany("App\Task");
}');
$I->seeInThisFile(
' public function project()
{
return $this->belongsTo("App\Project");
}');
$I->seeInThisFile(
' public function creator()
{
return $this->belongsTo("App\User");
}');
$I->seeInThisFile('public static $rules = [
"name" => "requied",
"project_id" => "required",
];');
$I->seeInThisFile('
public function tags()
{
return $this->hasMany("App\Tag");
}
public function tasks()
{
return $this->hasMany("App\Task");
}
public function project()
{
return $this->belongsTo("App\Project");
}
public function creator()
{
return $this->belongsTo("App\User");
}');
$I->deleteFile('./app/TaskCategory.php');
// Checking the migration
@ -46,21 +44,18 @@ $I->seeInShellOutput('task_categories migration generated');
$I->seeFileFound('./database/migrations/create_task_categories.php');
$I->openFile('./database/migrations/create_task_categories.php');
$I->seeInThisFile('class CreateTaskCategoriesTable extends Migration');
$I->seeInThisFile("Schema::create('task_categories', function(Blueprint \$table) {\n".
" \$table->increments('id');\n".
" \$table->string('name')->unique();" . PHP_EOL .
" \$table->text('descr')->nullable();" . PHP_EOL .
" \$table->timestamp('due');" . PHP_EOL .
" \$table->integer('project_id')->unsigned();" . PHP_EOL.
" \$table->integer('user_id')->unsigned();\n" .
" \$table->foreign('project_id')\n".
" ->references('id')\n".
" ->on('projects');" . PHP_EOL .
" \$table->foreign('user_id')\n".
" ->references('id')\n".
" ->on('users');\n".
" \$table->timestamps();");
$I->seeInThisFile('class CreateTaskCategoriesMigration extends Migration');
$I->seeInThisFile('Schema::create(\'task_categories\', function(Blueprint $table) {
$table->increments(\'id\');
$table->string(\'name\')->unique();
$table->text(\'descr\')->nullable();
$table->integer(\'project_id\');
$table->timestamp(\'due\');
$table->foreign(\'project_id\')
->references(\'id\')
->on(\'projects\');
$table->timestamps();
});');
$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 {
const MODEL = "App\TaskCategory";
const MODEL = "App\TaskCategory";
use RESTActions;
use RESTActions;
}');
@ -108,53 +103,3 @@ $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),
];
});
");
// 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

@ -59,38 +59,3 @@ $app->get("/", function () use ($app) {
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

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

View File

@ -31,15 +31,10 @@ class BaseCommand extends Command {
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->fs->put($path, $content);
$this->info("{$name} generated !");
}
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;
use InvalidArgumentException;
class ControllerCommand extends BaseCommand {
protected $signature = 'wn:controller
{model : Name of the model (with namespace if not App)}
{--no-routes= : without routes}
{--force= : override the existing files}
{--laravel : Use Laravel style route definitions}
';
{--no-routes= : without routes}';
protected $description = 'Generates RESTful controller using the RESTActions trait';
@ -33,18 +28,15 @@ class ControllerCommand extends BaseCommand {
])
->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')){
$options = [
$this->call('wn:route', [
'resource' => snake_case($name, '-'),
'--controller' => $controller,
];
if ($this->option('laravel')) {
$options['--laravel'] = true;
}
$this->call('wn:route', $options);
'--controller' => $controller
]);
}
}

View File

@ -3,8 +3,7 @@
class ControllerRestActionsCommand extends BaseCommand {
protected $signature = 'wn:controller:rest-actions
{--force= : override the existing files}';
protected $signature = 'wn:controller:rest-actions';
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();
$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 {
protected $signature = 'wn:migration
protected $signature = 'wn:migration
{table : The table name.}
{--schema= : the schema.}
{--add= : specifies additional columns like timestamps, softDeletes, rememberToken and nullableTimestamps.}
{--keys= : foreign keys.}
{--file= : name of the migration file (to use only for testing purpose).}
{--file= : name of the migration 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}
';
// {action : One of create, add, remove or drop options.}
// The action is only create for the moment
';
// {action : One of create, add, remove or drop options.}
// 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()
{
$table = $this->argument('table');
$name = 'Create' . ucwords(camel_case($table));
$snakeName = snake_case($name);
$content = $this->getTemplate('migration')
->with([
'table' => $table,
'name' => $name,
'schema' => $this->getSchema(),
'additionals' => $this->getAdditionals(),
'constraints' => $this->getConstraints()
])
->get();
$file = $this->option('file');
if(! $file){
$file = date('Y_m_d_His_') . $snakeName . '_table';
$this->deleteOldMigration($snakeName);
}else{
$this->deleteOldMigration($file);
$file = date('Y_m_d_His_') . snake_case($name);
}
$this->save($content, "./database/migrations/{$file}.php", "{$table} migration");
}
$this->save($content, "./database/migrations/{$file}.php");
protected function deleteOldMigration($fileName)
{
foreach (new \DirectoryIterator("./database/migrations/") as $fileInfo){
if($fileInfo->isDot()) continue;
if(strpos($fileInfo->getFilename(), $fileName) !== FALSE){
unlink($fileInfo->getPathname());
}
}
$this->info("{$table} migration generated !");
}
protected function getSchema()
{
$schema = $this->option('schema');
if(! $schema){
return $this->spaces(12) . "// Schema declaration";
return " // Schema declaration";
}
$items = $schema;
@ -75,23 +59,6 @@ class MigrationCommand extends BaseCommand {
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)
{
$name = $parts[0]['name'];
@ -107,7 +74,7 @@ class MigrationCommand extends BaseCommand {
{
$keys = $this->option('keys');
if(! $keys){
return $this->spaces(12) . "// Constraints declaration";
return " // Constraints declaration";
}
$items = $keys;
@ -142,20 +109,20 @@ class MigrationCommand extends BaseCommand {
if($key['on_delete']){
$constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
->with([
'event' => 'Delete',
'action' => $key['on_delete']
])
->get();
->with([
'event' => 'Delete',
'action' => $key['on_delete']
])
->get();
}
if($key['on_update']){
$constraint .= PHP_EOL . $this->getTemplate('migration/on-constraint')
->with([
'event' => 'Update',
'action' => $key['on_update']
])
->get();
->with([
'event' => 'Update',
'action' => $key['on_update']
])
->get();
}
return $constraint . ';';

View File

@ -10,14 +10,9 @@ class ModelCommand extends BaseCommand {
{--has-many= : hasMany relationships.}
{--has-one= : hasOne relationships.}
{--belongs-to= : belongsTo relationships.}
{--belongs-to-many= : belongsToMany relationships.}
{--rules= : fields validation rules.}
{--timestamps=true : enables timestamps on the model.}
{--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}
{--force= : override the existing files}
';
{--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}';
protected $description = 'Generates a model class for a RESTfull resource';
@ -33,13 +28,13 @@ class ModelCommand extends BaseCommand {
'fillable' => $this->getAsArrayFields('fillable'),
'dates' => $this->getAsArrayFields('dates'),
'relations' => $this->getRelations(),
'rules' => $this->getRules(),
'additional' => $this->getAdditional(),
'uses' => $this->getUses()
'rules' => $this->getRules()
])
->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)
@ -65,18 +60,17 @@ class ModelCommand extends BaseCommand {
$relations = array_merge([],
$this->getRelationsByType('hasOne', 'has-one'),
$this->getRelationsByType('hasMany', 'has-many'),
$this->getRelationsByType('belongsTo', 'belongs-to'),
$this->getRelationsByType('belongsToMany', 'belongs-to-many', true)
$this->getRelationsByType('belongsTo', 'belongs-to')
);
if(empty($relations)){
return " // Relationships";
return "\t// Relationships";
}
return implode(PHP_EOL, $relations);
}
protected function getRelationsByType($type, $option, $withTimestamps = false)
protected function getRelationsByType($type, $option)
{
$relations = [];
$option = $this->option($option);
@ -84,8 +78,7 @@ class ModelCommand extends BaseCommand {
$items = $this->getArgumentParser('relations')->parse($option);
$template = ($withTimestamps) ? 'model/relation-with-timestamps' : 'model/relation';
$template = $this->getTemplate($template);
$template = $this->getTemplate('model/relation');
foreach ($items as $item) {
$item['type'] = $type;
if(! $item['model']){
@ -103,7 +96,7 @@ class ModelCommand extends BaseCommand {
{
$rules = $this->option('rules');
if(! $rules){
return " // Validation rules";
return "\t\t// Validation rules";
}
$items = $rules;
if(! $this->option('parsed')){
@ -118,18 +111,4 @@ class ModelCommand extends BaseCommand {
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

@ -1,56 +0,0 @@
<?php namespace Wn\Generators\Commands;
class PivotTableCommand extends BaseCommand {
protected $signature = 'wn:pivot-table
{model1 : Name of the first 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).}
{--force= : override the existing files}
';
protected $description = 'Generates creation migration for a pivot table';
protected $tables;
public function handle()
{
$this->parseTables();
$this->call('wn:migration', [
'table' => implode('_', $this->tables),
'--schema' => $this->schema(),
'--keys' => $this->keys(),
'--file' => $this->option('file'),
'--parsed' => false,
'--force' => $this->option('force'),
'--add' => $this->option('add')
]);
}
protected function parseTables()
{
$this->tables = array_map(function($arg) {
return snake_case(str_singular($this->argument($arg)));
}, ['model1', 'model2']);
sort($this->tables);
}
protected function schema()
{
return implode(' ', array_map(function($table){
return $table . '_id:integer:unsigned:index';
}, $this->tables));
}
protected function keys()
{
return implode(' ', array_map(function($table){
return $table . '_id';
}, $this->tables));
}
}

View File

@ -1,8 +1,6 @@
<?php namespace Wn\Generators\Commands;
use InvalidArgumentException;
class ResourceCommand extends BaseCommand {
protected $signature = 'wn:resource
@ -11,14 +9,9 @@ class ResourceCommand extends BaseCommand {
{--has-many= : hasMany relationships.}
{--has-one= : hasOne relationships.}
{--belongs-to= : belongsTo relationships.}
{--belongs-to-many= : belongsToMany relationships.}
{--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}
{--force= : override the existing files}
{--laravel= : Use Laravel style route definitions}
';
';
protected $description = 'Generates a model, migration, controller and routes for RESTful resource';
@ -40,12 +33,8 @@ class ResourceCommand extends BaseCommand {
'--has-many' => $this->option('has-many'),
'--has-one' => $this->option('has-one'),
'--belongs-to' => $this->option('belongs-to'),
'--belongs-to-many' => $this->option('belongs-to-many'),
'--rules' => $this->rules(),
'--path' => $this->option('path'),
'--force' => $this->option('force'),
'--timestamps' => $this->hasTimestamps() ? 'true' : 'false',
'--soft-deletes' => $this->hasSoftDeletes() ? 'true' : 'false',
'--path' => 'app',
'--parsed' => true
]);
@ -53,41 +42,22 @@ class ResourceCommand extends BaseCommand {
$this->call('wn:migration', [
'table' => $tableName,
'--schema' => $this->schema(),
'--keys' => $this->migrationKeys(),
'--keys' => $this->foreignKeys(),
'--file' => $this->option('migration-file'),
'--force' => $this->option('force'),
'--add' => $this->option('add'),
'--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')){
$this->call('wn:controller:rest-actions');
}
// generating the controller and routes
$controllerOptions = [
$this->call('wn:controller', [
'model' => $modelName,
'--force' => $this->option('force'),
'--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
'--no-routes' => false
]);
// generating database seeder
// $this->call('wn:seeder', [
// 'model' => 'App\\' . $modelName
// ]);
}
protected function parseFields()
@ -95,27 +65,12 @@ class ResourceCommand extends BaseCommand {
$fields = $this->argument('fields');
if($this->option('parsed')){
$this->fields = $fields;
} else if(! $fields){
$this->fields = [];
} else {
if(! $fields){
$this->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()));
$this->fields = $this->getArgumentParser('fields')
->parse($fields);
}
}
protected function fieldsHavingTag($tag)
@ -151,57 +106,17 @@ class ResourceCommand extends BaseCommand {
protected function foreignKeys()
{
$belongsTo = $this->option('belongs-to');
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 array_map(function($field){
return [
'name' => $name,
'name' => $field['name'],
'column' => '',
'table' => '',
'on_delete' => '',
'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){
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,84 +1,38 @@
<?php namespace Wn\Generators\Commands;
use InvalidArgumentException;
use Symfony\Component\Yaml\Yaml;
class ResourcesCommand extends BaseCommand {
protected $signature = 'wn:resources
{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}
';
{file : Path to the file containing resources declarations}';
protected $description = 'Generates multiple resources from a file';
protected $pivotTables = [];
public function handle()
{
$content = $this->fs->get($this->argument('file'));
$content = Yaml::parse($content);
$modelIndex = 0;
foreach ($content as $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';
$options = [
$this->call('wn:resource', [
'name' => $i['name'],
'fields' => $i['fields'],
'--add' => $i['add'],
'--has-many' => $i['hasMany'],
'--has-one' => $i['hasOne'],
'--belongs-to' => $i['belongsTo'],
'--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(
'unserialize',
array_unique(array_map('serialize', $this->pivotTables))
);
foreach ($this->pivotTables as $tables) {
$this->call('wn:pivot-table', [
'model1' => $tables[0],
'model2' => $tables[1],
'--force' => $this->option('force')
'--belongs-to' => $i['belongsTo']
]);
// $this->call('wn:pivot-seeder', [
// 'model1' => $tables[0],
// 'model2' => $tables[1],
// '--force' => $this->option('force')
// ]);
}
$this->call('migrate');
}
protected function getResourceParams($modelName, $i)
{
$i['name'] = snake_case($modelName);
foreach(['hasMany', 'hasOne', 'add', 'belongsTo', 'belongsToMany'] as $relation){
foreach(['hasMany', 'hasOne', 'belongsTo'] as $relation){
if(isset($i[$relation])){
$i[$relation] = $this->convertArray($i[$relation], ' ', ',');
} else {
@ -86,21 +40,22 @@ class ResourcesCommand extends BaseCommand {
}
}
if($i['belongsToMany']){
$relations = $this->getArgumentParser('relations')->parse($i['belongsToMany']);
if($i['belongsTo']){
$relations = $this->getArgumentParser('relations')->parse($i['belongsTo']);
foreach ($relations as $relation){
$table = '';
$foreignName = '';
if(! $relation['model']){
$table = snake_case($relation['name']);
$foreignName = snake_case($relation['name']) . '_id';
} else {
$names = array_reverse(explode("\\", $relation['model']));
$table = snake_case($names[0]);
$foreignName = snake_case($names[0]) . '_id';
}
$tables = [ str_singular($table), $i['name'] ];
sort($tables);
$this->pivotTables[] = $tables;
$i['fields'][$foreignName] = [
'schema' => 'integer',
'tags' => 'key'
];
}
}
@ -119,18 +74,9 @@ class ResourcesCommand extends BaseCommand {
$name = $field['name'];
$schema = $this->convertArray(str_replace(':', '.', $field['schema']), ' ', ':');
$rules = (isset($field['rules'])) ? trim($field['rules']) : '';
// Replace space by comma
$rules = str_replace(' ', ',', $rules);
$tags = $this->convertArray($field['tags'], ' ', ',');
$string = "{$name};{$schema};{$rules};{$tags}";
if(isset($field['factory']) && !empty($field['factory'])){
$string .= ';' . $field['factory'];
}
return $string;
return "{$name};{$schema};{$rules};{$tags}";
}
protected function convertArray($list, $old, $new)

View File

@ -1,67 +1,30 @@
<?php namespace Wn\Generators\Commands;
use InvalidArgumentException;
class RouteCommand extends BaseCommand {
protected $signature = 'wn:route
{resource : Name of the resource.}
{--controller= : Name of the RESTful controller.}
{--laravel= : Use Laravel style route definitions}
';
{--controller= : Name of the RESTful controller.}';
protected $description = 'Generates RESTful routes.';
public function handle()
{
$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!
|
*/
$content .= PHP_EOL . $this->getTemplate('routes')
->with([
'resource' => $resource,
'controller' => $this->getController()
])
->get();
Route::middleware('auth:api')->get('/user', function (Request \$request) {
return \$request->user();
});
$this->save($content, './app/Http/routes.php');
");
}
}
if (!$this->fs->isFile($routesPath)) {
$routesPath = 'app/Http/routes.php';
}
$content = $this->fs->get($routesPath);
$content .= PHP_EOL . $this->getTemplate($templateFile)
->with([
'resource' => $resource,
'controller' => $this->getController()
])
->get();
$this->save($content, $routesPath, "{$resource} routes", true);
$this->info("{$resource} routes generated !");
}
protected function getController()

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

@ -14,11 +14,8 @@ class CommandsServiceProvider extends ServiceProvider
$this->registerMigrationCommand();
$this->registerResourceCommand();
$this->registerResourcesCommand();
$this->registerPivotTableCommand();
$this->registerFactoryCommand();
// registerSeederCommand
// registerPivotSeederCommand
// registerTestCommand
// $this->registerSeedCommand();
// $this->registerTestCommand();
}
protected function registerModelCommand(){
@ -26,6 +23,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ModelCommand'];
});
$this->commands('command.wn.model');
}
protected function registerControllerRestActionsCommand(){
@ -33,6 +31,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ControllerRestActionsCommand'];
});
$this->commands('command.wn.controller.rest-actions');
}
protected function registerControllerCommand(){
@ -40,6 +39,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ControllerCommand'];
});
$this->commands('command.wn.controller');
}
protected function registerMigrationCommand(){
@ -47,6 +47,15 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\MigrationCommand'];
});
$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(){
@ -54,6 +63,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\RouteCommand'];
});
$this->commands('command.wn.route');
}
protected function registerTestCommand(){
@ -61,6 +71,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\TestCommand'];
});
$this->commands('command.wn.test');
}
protected function registerResourceCommand(){
@ -68,6 +79,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ResourceCommand'];
});
$this->commands('command.wn.resource');
}
protected function registerResourcesCommand(){
@ -75,34 +87,7 @@ class CommandsServiceProvider extends ServiceProvider
return $app['Wn\Generators\Commands\ResourcesCommand'];
});
$this->commands('command.wn.resources');
}
protected function registerPivotTableCommand(){
$this->app->singleton('command.wn.pivot-table', function($app){
return $app['Wn\Generators\Commands\PivotTableCommand'];
});
$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,9 +1,10 @@
<?php namespace App\Http\Controllers;
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;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
trait RESTActions {
protected $statusCodes = [
'done' => 200,
'created' => 201,
'removed' => 204,
'not_valid' => 400,
'not_found' => 404,
'conflict' => 409,
'permissions' => 401
];
public function all()
{
$m = self::MODEL;
return $this->respond(Response::HTTP_OK, $m::all());
}
public function all()
{
$m = self::MODEL;
return $this->respond('done', $m::all());
}
public function get($id)
{
$m = self::MODEL;
$model = $m::find($id);
if(is_null($model)){
return $this->respond(Response::HTTP_NOT_FOUND);
}
return $this->respond(Response::HTTP_OK, $model);
}
public function get($id)
{
$m = self::MODEL;
$model = $m::find($id);
if(is_null($model)){
return $this->respond('not_found');
}
return $this->respond('done', $model);
}
public function add(Request $request)
{
$m = self::MODEL;
$this->validate($request, $m::$rules);
return $this->respond(Response::HTTP_CREATED, $m::create($request->all()));
}
public function add(Request $request)
{
$m = self::MODEL;
$this->validate($request, $m::$rules);
return $this->respond('created', $m::create($request->all()));
}
public function put(Request $request, $id)
{
$m = self::MODEL;
$this->validate($request, $m::$rules);
$model = $m::find($id);
if(is_null($model)){
return $this->respond(Response::HTTP_NOT_FOUND);
}
$model->update($request->all());
return $this->respond(Response::HTTP_OK, $model);
}
public function put(Request $request, $id)
{
$m = self::MODEL;
$this->validate($request, $m::$rules);
$model = $m::find($id);
if(is_null($model)){
return $this->respond('not_found');
}
$model->update($request->all());
return $this->respond('done', $model);
}
public function remove($id)
{
$m = self::MODEL;
if(is_null($m::find($id))){
return $this->respond(Response::HTTP_NOT_FOUND);
}
$m::destroy($id);
return $this->respond(Response::HTTP_NO_CONTENT);
}
public function remove($id)
{
$m = self::MODEL;
if(is_null($m::find($id))){
return $this->respond('not_found');
}
$m::destroy($id);
return $this->respond('removed');
}
protected function respond($status, $data = [])
{
if($status == Response::HTTP_NO_CONTENT){
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);
return response()->json($data, $this->statusCodes[$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

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

View File

@ -4,14 +4,14 @@ use Illuminate\Database\Eloquent\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}}
];
];
{{additional}}{{relations}}
{{relations}}
}

View File

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

View File

@ -1,4 +1,4 @@
public function {{name}}()
{
return $this->{{type}}("{{model}}");
}
public function {{name}}()
{
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}}
*/
$router->get('{{resource}}', '{{controller}}@all');
$router->get('{{resource}}/{id}', '{{controller}}@get');
$router->post('{{resource}}', '{{controller}}@add');
$router->put('{{resource}}/{id}', '{{controller}}@put');
$router->delete('{{resource}}/{id}', '{{controller}}@remove');
$app->get('{{resource}}', '{{controller}}@all');
$app->get('{{resource}}/{id}', '{{controller}}@get');
$app->post('{{resource}}', '{{controller}}@add');
$app->put('{{resource}}/{id}', '{{controller}}@put');
$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
cd lumen-test || return
if [ ! -f codecept.phar ]; then
wget http://codeception.com/codecept.phar
fi
cd lumen-test
wget http://codeception.com/codecept.phar
php codecept.phar run