Giter Club home page Giter Club logo

lumen-generators's Introduction

Lumen generators

Build Status Scrutinizer Code Quality SensioLabsInsight License

A collection of generators for Lumen and Laravel 5.

Contents

Why ?

I installed Lumen and wanted to use it to create a REST API (since this is the main usage of Lumen). But I didn't find commands which will speed up my workflow. That's why I created this package and included useful commands to build a RESTful API.

This packages was mainly built to be used with Lumen, but it should work fine with Laravel 5 too.

Installation

Add the generators package to your composer.json by running the command:

composer require wn/lumen-generators

Then add the service provider in the file app/Providers/AppServiceProvider.phplike the following:

public function register()
{
    if ($this->app->environment() == 'local') {
        $this->app->register('Wn\Generators\CommandsServiceProvider');
    }
}

Don't forget to include the application service provider on your bootstrap/app.php and to enable Eloquent and Facades if you are using Lumen

If you run the command php artisan list you will see the list of added commands:

wn:controller               Generates RESTful controller using the RESTActions trait
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.

Quick Usage

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

will generate these files:

app/Task.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model {

	protected $fillable = ["name", "project_id"];

	protected $dates = ["due"];

	public static $rules = [
		"name" => "required",
		"project_id" => "numeric",
	];

	public function project()
	{
		return $this->belongsTo("App\Project");
	}

}

app/Http/Controllers/RESTActions.php

<?php namespace App\Http\Controllers;

use Illuminate\Http\Request;


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('done', $m::all());
	}

	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('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('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('not_found');
		}
		$m::destroy($id);
		return $this->respond('removed');
	}

    protected function respond($status, $data = [])
    {
    	return response()->json($data, $this->statusCodes[$status]);
    }

}

app/Http/Controllers/TasksController.php

<?php namespace App\Http\Controllers;


class TasksController extends Controller {

	const MODEL = "App\Task";

	use RESTActions;

}

app/Http/routes.php

// These lignes will be added
/**
 * Routes for resource task
 */
$app->get('task', 'TasksController@all');
$app->get('task/{id}', 'TasksController@get');
$app->post('task', 'TasksController@add');
$app->put('task/{id}', 'TasksController@put');
$app->delete('task/{id}', 'TasksController@remove');

database/migrations/date_time_create_tasks.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTasksMigration extends Migration
{
    
    public function up()
    {
        Schema::create('tasks', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('project_id')->unsigned();
            $table->date('due');
            $table->foreign('project_id')
                ->references('id')
                ->on('projects');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('tasks');
    }
}

Now simply run the migration and you are ready to go.

More then that, you can generate multiple resources with only one command ! Click here to see an example

Detailed Usage

Model Generator

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]
  • name: the name of the model.

php artisan wn:model Task generates the following:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model {

	protected $fillable = [];

	protected $dates = [];

	public static $rules = [
		// Validation rules
	];

	// Relationships

}
  • --fillable: the mass fillable fields of the model separated with commas.

php artisan wn:model Task --fillable=name,title gives:

//...	
	protected $fillable = ['name', 'title'];
  • --dates: the date fields of the model, these will be converted automatically to Carbon instances on retrieval.

php artisan wn:model Task --dates=started_at,published_at gives:

//...	
	protected $dates = ['started_at', 'published_at'];
  • --path: specifies the path where to store the model php file. This path is used to know the namespace of the model. The default value is "app".

php artisan wn:model Task --path="app/Http/Models" gives:

<?php namespace App\Http\Models;
//...
  • --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.
php artisan wn:model Task --has-many=accounts --belongs-to="owner:App\User" --has-one=number:Phone belongs-to-many=tags --path=tests/tmp

gives:

//...
	public function accounts()
	{
		return $this->hasMany("Tests\Tmp\Account");
	}

	public function owner()
	{
		return $this->belongsTo("App\User");
	}

	public function number()
	{
		return $this->hasOne("Tests\Tmp\Phone");
	}

	public function tags()
	{
		return $this->belongsToMany("Tests\Tmp\Tag")->withTimestamps();
	}
  • --rules: specifies the validation rules of the model's fields. The syntax is field1=rules1 field2=rules2 ....
php artisan wn:model TestingModel --rules="name=required age=integer|min:13 email=email|unique:users,email_address"`

gives:

// ...
	public static $rules = [
		"name" => "required",
		"age" => "integer|min:13",
		"email" => "email|unique:users,email_address",
	];
  • --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=...]
  • 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.

  • --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 for the list of available types and modifiers.

php artisan wn:migration tasks --schema="amount:decimal.5,2:after.'size':default.8 title:string:nullable"

gives:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTasksMigration extends Migration
{
    
    public function up()
    {
        Schema::create('tasks', function(Blueprint $table) {
            $table->increments('id');
            $table->decimal('amount', 5, 2)->after('size')->default(8);
            $table->string('title')->nullable();
            // Constraints declaration

        });
    }

    public function down()
    {
        Schema::drop('tasks');
    }
}
  • --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.

php artisan wn:migration tasks --keys="category_type_id user_id:identifier:members:cascade"

gives:

//...
$table->foreign('category_type_id')
    ->references('id')
    ->on('category_types');

$table->foreign('user_id')
    ->references('identifier')
    ->on('members')
    ->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

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:

  • all() : returns all the model entries as JSON.

  • get($id) : returns a specific model by id as JSON.

  • add(Request $request) : adds a new model or returns validation errors as JSON.

  • put(Request $request, $id) : updates a model or returns validation errors as JSON.

  • remove($id) : removes an entry by id.

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].

  • 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:

<?php namespace App\Http\Controllers;


class TasksController extends Controller {

	const MODEL = "App\\Task";

	use RESTActions;

}

Routes Generator

The wn:route command is used to generate RESTfull routes for a controller. It has the following syntax:

wn:route resource [--controller=...] [--force=true]

  • 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:

$app->get('project-type', 'ProjectTypesController@all');
$app->get('project-type/{id}', 'ProjectTypesController@get');
$app->post('project-type', 'ProjectTypesController@add');
$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:

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]

  • name: the name of the resource used in the URLs and to determine the model, table and controller names.

  • fields: specifies the fields of the resource along with schema and validation rules. It follows the syntax name;schema;rules;tags ...

    • name: the name of the field

    • schema: the schema following the syntax in the model generator. (note that the name is not part of the schema like on the model generator)

    • rules: the validation rules

    • tags: additional tags separated by commas. The possible tags are:

      • fillable: add this field to the fillable array of the model.

      • date: add this field to the dates array of the model.

      • 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 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

---
Store:
  hasMany: products
  fields:
    name:
      schema: string:50 unique
      rules: required|min:3
      tags: fillable
Product:
  belongsTo: store
  fields:
    name:
      schema: string
      rules: required
      tags: fillable
    store_id:
      schema: integer unsigned
      rules: required numeric
      tags: fillable key
    desc:
      schema: text nullable
      tags: fillable
    published_at:
      schema: date
      rules: date
      tags: date fillable
    price:
      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. To run tests you just have to execute the install.sh to install dependencies then execute test.sh.

Development Notes

Contributing

Pull requests are welcome :D

lumen-generators's People

Contributors

abdillah avatar afzalh avatar asafmah avatar davidporos92 avatar josiahdahl avatar khalidhisham7 avatar stephanebour avatar webneat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lumen-generators's Issues

"wn:resources filename" may not generate schema if there are dependencies between tables

Problem

When putting schema definitions in a YAML file and running wn:resources yml-file, errors may occur related to certain tables not existing, if the schema has several tables and there are dependencies between them, e.g. foreign keys etc.

Possible cause

The sequence of running migration is not as expected. The generated migration files seems to be run in alphabetical order, which may not be the correct order of creating tables.

Work around

Rename the migration files so that the files are ordered per the sequence of creating tables

Suggested Fix

Name the migration files per the order in the yml-file, so that the tables can be created in the sequence as expected

Doesn't work with Lumen 5.2

composer require wn/lumen-generators
Using version ^1.1 for wn/lumen-generators
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)

  • Installing wn/lumen-generators (1.1.1)
    Loading from cache

Generating autoload files


class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment() == 'local') {
            $this->app->register('Wn\Generators\CommandsServiceProvider');
        }
    }
}

After that run php artisan list

Doesn't show any WN commands.

If run 'php artisan wn:resource`, show below:

  [Symfony\Component\Console\Exception\CommandNotFoundException]
  There are no commands defined in the "wn" namespace.

--force=true does not overwrite migration and db table

If I realize I made a mistake in the model definition and I run resource(s) generator again (--force=true), it creates another migration, with new timestamp and either fails when trying to declare again the migration class with the same name or fails when running the migration, because the table already exists in the db.

Probably this also applies to the model and migration generator.

Failing tests on fresh install

On fresh package install after running install.sh there is a lot of core tests failing due to wrong indendation/spaces. Also there is an issue when starting tests from operating system other than Linux because of wget which is not pre-installed on OSX or Win. And also not able to run clean.sh from outside lumen-test folder.

Expected Behavior

All the core tests should pass.

After running install.sh, codecept.phar should exist inside lumen-test.

Being able to run clean.sh outside of lumen-test folder.

Current Behavior

Not all core tests pass.

After running install.sh I get an error wget command not found.

After running clean.sh outside of lumen-test folder I get a bunch of 'File doesn't exist' issues.

Possible Solution

Remove all indentation inside stubs to avoid tests failing.

Install either with curl or wget.

Do all operations inside clean.sh relative to it's parent and not current dir.

Steps to Reproduce

# Command Error
1. git clone _repo
2. sh install.sh wget command not found
3. sh test.sh A bunch of errors in core tests
4. cd lumen-test
5. sh clean.sh api/routes not found

Context (Environment)

Testing env - Trying to fix the failing core tests and optimize the shell scripts a bit.

Detailed Description

/

Possible Implementation

I will do a pull request to fix the above issues

Fractal integration

Hi, Fractal provides a nice separation layer between the Model and the JSON data, it would be good to have an option to integrate it into your useful set of generators.

Thanks,
Tomasz

enum

how do i generate enum in column in migration?

Should (or could) this just be a development dependency?

Since we should not be generating anything on production, can this package be installed as a dev only dependency?

composer require --dev wn/lumen-generators

I'm asking in case there is any production run-time component of this package that is needed by generated components that I am not aware of.

If it can, then the documentation should probably mention this, since having it in production, I assume, will provide some extra load each request.

Migrations don't seem to migrate

I created a resource named Hall, used artisan migrate to migrate, and I get the error " Class 'CreateHalls' not found ".
For reference here is the generated CreateHallsMIgration:

class CreateHallsMigration extends Migration
{

    public function up()
    {
        Schema::create('halls', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name', 100);
            $table->string('email', 255);
            $table->string('phone', 11);
            $table->string('address', 255);
            // Constraints declaration
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('halls');
    }
}

In case it wasn't clear, this was after generating with composer dump-autoload

Generic error message

image
I think this error message should be more verbose, identifying which part of the argument is not being parsed. I don't know if it really is a good idea to create a resource with 10+ fields (my current use case) in this generator, but I eventually gave up and started creating most of the fields manually.

Issue with Lumen 5.4

I m unable to get artisan commands to make controller, model.

I got this when running "php artisan list"

Laravel Framework Lumen (5.4.6) (Laravel Components 5.4.*)

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
      --env[=ENV]       The environment the command should run under
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  help                Displays help for a command
  list                Lists commands
  migrate             Run the database migrations
 auth
  auth:clear-resets   Flush expired password reset tokens
 cache
  cache:clear         Flush the application cache
  cache:forget        Remove an item from the cache
  cache:table         Create a migration for the cache database table
 db
  db:seed             Seed the database with records
 make
  make:migration      Create a new migration file
  make:seeder         Create a new seeder class
 migrate
  migrate:install     Create the migration repository
  migrate:refresh     Reset and re-run all migrations
  migrate:reset       Rollback all database migrations
  migrate:rollback    Rollback the last database migration
  migrate:status      Show the status of each migration
 queue
  queue:failed        List all of the failed queue jobs
  queue:failed-table  Create a migration for the failed queue jobs database table
  queue:flush         Flush all of the failed queue jobs
  queue:forget        Delete a failed queue job
  queue:listen        Listen to a given queue
  queue:restart       Restart queue worker daemons after their current job
  queue:retry         Retry a failed queue job
  queue:table         Create a migration for the queue jobs database table
  queue:work          Start processing jobs on the queue as a daemon
 schedule
  schedule:run        Run the scheduled commands

const MODEL doesn't respect namespace from --path option

I ran into this when creating resources from a resource file, though it may happen with the other commands.

If I run php artisan wn:resources [file] --path="app/Models"

I would expect the models to be put into a Models folder (which happens), and the const MODEL value in the associated controller to be set to "App\Model\[model]" (which does not happen, it remains as "App\[model]").

Migrations generated from resources file cause name collisions

It seems wn:resources doesn't check to see if a create file for the resource's table already exists. When combined with the automatic migration attempt, this results in a cannot redeclare class error, which kills the migration.

Steps to reproduce:

  1. Create a resource using the single wn:resource command.
  2. Create resources (including the previously-created resource) with a file and the wn:resources command.

Expected actions would probably be to look for that class name and one of:

  1. Adjust the name of the incoming generated class so as to not collide
  2. Overwrite the found class file (probably not recommended in most cases, but may be useful with the --force switch)
  3. Not create a migration file for that resource (or better yet, create an update migration with the changes from the existing schema)

Are Nested Routes Possible?

Is it possible using this generator to create nested routes something a long the lines of user/{user}/post/{post}?

Adding a model inside a directory does not add the directory to the namespace, and includes the directory in the classname

Using the command php artisan wn:model Models/Product generates Products.php inside the Models directory as expected but does not add the \Models postfix to the namespace and sets the class name as Models/Product.

Using PHP 7.1 and Lumen 5.4

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Models/Product extends Model {

    protected $fillable = [];

    protected $dates = [];

    public static $rules = [
        // Validation rules
    ];

    // Relationships

}

PSR-2 compliance

Please fix class formatting to be PSR-2 compliant.

Put namespace declarations and opening brace for classes on new lines.

Update for lumen 5.3

Routs in 5.3 have moved wn:routes gives an error

  [Illuminate\Contracts\Filesystem\FileNotFoundException]
  File does not exist at path ./app/Http/routes.php

does lumen-generators support laravel 5.5?

when I install this package in laravel 5.5, it report a error like this:

Problem 1
- doctrine/instantiator 1.1.0 requires php ^7.1 -> your PHP version (7.0.13) does not satisfy that requirement.
- doctrine/instantiator 1.1.0 requires php ^7.1 -> your PHP version (7.0.13) does not satisfy that requirement.
- doctrine/instantiator 1.1.0 requires php ^7.1 -> your PHP version (7.0.13) does not satisfy that requirement.
- Installation request for doctrine/instantiator (locked at 1.1.0) -> satisfiable by doctrine/instantiator[1.1.0].

Error on MigrationCommand.php: count()

Hello, i try to create one model with method wn:resources and get this error:
In MigrationCommand.php line 118:
count(): Parameter must be an array or an object that implements Countable

I check the MigrationCommnand.php file and change the method count by strlen and this work fine.

I hope can you update the repo with this fix to the next version (i have 1.3.4v).

Bye!

I think theres a bug when generating resources from a file.

When trying to create a resource with a relationship like

User:
  hasMany: messages
  fields:
    name:
      schema: string:50
      rules: required|min:3
      tags: fillable
    email:
      schema: string unique
      rules: required|email|unique:users,email
      tags: fillable
    password:
      schema: string
      rules: required|min:6
      tags: fillable
Message:
  belongsTo: user
  belongsToMany: channel
  fields:
    text:
      schema: text
      rules: required
      tags: fillable
  add: timestamps softDeletes 

and you run wn:resources /path/to/file.yaml

it will generate a duplicate column for the foriegn key

    public function up()
    {
        Schema::create('messages', function(Blueprint $table) {
            $table->increments('id');
            $table->text('text');
            $table->integer('user_id');
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')
                ->references('id')
                ->on('users');
            $table->timestamps();
            $table->softDeletes();
        });
    }

Also after a bit of testing and poking around I think there should be option or a flag to prevent the resource from running a migration.

(Feature Request) Allow command options to be declared in resources file

I love the resources file as a concept and thought it might be nice to expand upon the basic concept of having a configuration for enduring options (instead of only relying on command options).

I'm thinking something like:

---
path: 'App/Models'
laravel: true
[...]

Use of the command line options would override the file options, if present, but this would allow everything to be defined (and thus backed up) in the file.

Two Errors running your multiresource yaml example

1st problem is with the "store_id" field definition:

[Wn\Generators\Exceptions\ArgumentParserException]
Required field missing: 3 given (store_id;integer:nullable;required) but 4
required (name;schema;rules;tags)

when I remove the "rules: required numeric" from "store_id" it works fine, but:

2nd the definition of the field which has already been indirectly defined by relation "belongsTo: gives the duplicate field definition in the migration and the model:

public function up()
{
Schema::create('products', function(Blueprint $table) {
$table->increments('id');
$table->integer('store_id')->nullable();
$table->text('desc')->nullable();
$table->date('published_at');
$table->decimal('price', 5, 2);
$table->integer('store_id')->unsigned();
$table->foreign('store_id')
->references('id')
->on('stores');
$table->timestamps();
$table->softDeletes();
});
}

the correct result should be:

$table->integer('store_id')->unsigned()->nullable();

...as it should be possible to define additional properties of the field being used as a FK (like making it nullable for instance)

Resource creation damages artisan

After executing a standard artisan wn:resource command, artisan console becomes unusable.

Example:
>php artisan list
Laravel Framework Lumen (5.5.2) (Laravel Components 5.5.*)

Usage:
command [options] [arguments]

Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
help Displays help for a command
list Lists commands
migrate Run the database migrations
auth
auth:clear-resets Flush expired password reset tokens
cache
cache:clear Flush the application cache
cache:forget Remove an item from the cache
cache:table Create a migration for the cache database table
db
db:seed Seed the database with records
make
make:migration Create a new migration file
make:seeder Create a new seeder class
migrate
migrate:install Create the migration repository
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
migrate:status Show the status of each migration
queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:restart Restart queue worker daemons after their current job
queue:retry Retry a failed queue job
queue:table Create a migration for the queue jobs database table
queue:work Start processing jobs on the queue as a daemon
schedule
schedule:run Run the scheduled commands
wn
wn:controller Generates RESTful controller using the RESTActions trait
wn:controller:rest-actions Generates REST actions trait to use into controllers
wn:factory Generates a model factory
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.

>php artisan wn:resource State "name;string.200;required;fillable initials;string.2;required;fillable"
State model generated !
States migration generated !
StatesController generated !
state routes generated !
App\State factory generated !

>php artisan list

[ErrorException]
Undefined variable: app

A folder for example resource generator files

I think it could be helpful if we could make a kind of example folder for some common resources files. Things like generating a User model or showing how relationships can be mapped out.

Model can't be found in RESTactions trait

Hi,
I am having an issue, that the generated RESTaction.php trait does not get the model everytime it tries to get it via $m = self::MODEL;.

The corresponding generated controller looks like this:

<?php namespace App\Http\Controllers;

use App\Spots;

class SpotsController extends Controller {

    const MODEL = "App\Spots";

    use RESTActions;

}

Stacktrace, when calling the endpoint:
image

Files (with the Spot Model selected):
image

Versions:

"name": "laravel/lumen-framework",
"version": "v5.7.7",
"name": "wn/lumen-generators",
"version": "1.3.4",

I am kind of a beginner with lumen so maybe I am missing anything in using the generators or setting it all up. Therefore it's still hard for me to properly debug the php code. I am thankful for any tips regarding this issue and will of course provide more infos if I can.

Undefined variable app in web.php Lumen 5.5

Routes/web.php

$app->get('task', 'TasksController@all');
$app->get('task/{id}', 'TasksController@get');
$app->post('task', 'TasksController@add');
$app->put('task/{id}', 'TasksController@put');
$app->delete('task/{id}', 'TasksController@remove');

resolved by changing $app to router.

Pivot table migrations can come before their dependent tables

image

Due to the speed at which the files are generated, it can result in the timestamps being identical, and pivot tables coming before the tables that the pivot table relies on and has foreign keys to. Since the dependent tables don't exist yet, this results in a failed migration.

Add the rest of the parameters for the model

The rest of the parameters, for the reason of a better personalization for already existing structures, which are required to map to LUMEN.

Add:

  • protected $table
  • protected $primaryKey
  • public $incrementing

Change:

  • The first letter to upper case

Trying to generate resources with wn:resources error

Whenever I try to generate resources with wn:resources I'm getting this error:
Illegal string offset 'name'
I've tried searching on Google to see if I could find a solution that way, but I sadly couldn't find one.

The error comes from this file: ResourcesCommand.php line 95

Which says:

foreach($i['fields'] as $name => $value) {
            $value['name'] = $name;
            $fields[] = $this->serializeField($value);
}

But I do not understand what's wrong there.

softDeletes does not seem to work as expected

it doesn't add

use Illuminate\Database\Eloquent\SoftDeletes;
(...)
use SoftDeletes

...to the model. I tried php artisan wn:resource test tekst;string;; --add=timestamps;softDeletes and also the resources file

Class 'Wn\Generator\CommandsServiceProvider' not found in *\vendor\laravel\lumen-framework\src\Application.php

first I run composer require wn/lumen-generators

then I edit my AppServiceProvider,php like this:

    public function register()
    {
        //
        if ($this->app->environment() == 'local') {
            $this->app->register('Wn\Generator\CommandsServiceProvider');
        }
    }

I have already uncommentted 3 lines in the bootstrap/app.php file

$app->withFacades();
$app->withEloquent();
$app->register(App\Providers\AppServiceProvider::class);

but when I run php artisan list, I get this:
PHP Fatal error: Class 'Wn\Generator\CommandsServiceProvider' not found in *\vendor\laravel\lumen-framework\src\Application.php on line 162

if I config a wrong composer.json?
my composer.json:

{
    "name": "laravel/lumen",
    "description": "The Laravel Lumen Framework.",
    "keywords": ["framework", "laravel", "lumen"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/lumen-framework": "5.2.*",
        "vlucas/phpdotenv": "~2.2",
        "wn/lumen-generators": "^1.1"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "phpunit/phpunit": "~4.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/",
            "database/"
        ]
    }
}

Check existence of file

Hi @webNeat

Would it make sense that the generator would check the existence of a file before creating it?
Like if you're generating a model, so you accidentally don't overwrite a existing model.

Cannot add foreign key constraint wn:resources

When I try to run command "wn:resources file --path='app/Models' --force=true". I receive the error Cannot add foreign key constraint. I see that the migrations order is incorrect, is generating in alphabetical order and not found the foreign key. How I can change the order, and not make by alphabetical order, but do it by relationship.

Thanks

Pivots not Generating through Yaml

Seems the pivot table migrations are not being created due to line 38:ResourcesCommand.php

theres a dd(...)

was there a reason why this was placed here?

Adding additional fields in pivot table with resources?

Hey :)

Is it possible to add additional fields in the automatically generated pivot table in the yaml file which is used for generating everything via the resources command?
By that I mean proper self defined fields. Not something just like timestamps.
If so, how? Couldn't find anything in the documentation

Cheers :)

Add a possibility to rollback an action

Would be good for each generator, but at least for a specific resource - that would look for migration, model, controller and routes and delete them if found. Especially useful since the "resources" generator currently creates and runs the migration. See the other isse I reported.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.