Giter Site home page Giter Site logo

oc-seeder-plugin's Introduction

oc-seeder-plugin

Laravel Seeder integration for October CMS.

This plugin integrates Laravel's Factory and Database Seeder features with October CMS.

Installation

  1. Install the plugin using Composer.
composer require offline/oc-seeder-plugin
  1. Setup the random file helpers.
php artisan seeder:init

Defining factories

To define a new Factory for your plugin, create a YourModelFactory.php in the plugin's factories folder and define your factories as you would in Laravel:

<?php
// plugins/yourvendor/yourplugin/factories/YourModelFactory.php
namespace YourVendor\YourPlugin\Factories;

class YourModelFactory extends \OFFLINE\Seeder\Classes\Factory
{
    /**
     * Default model attributes.
     */
    public function definition()
    {
        return [
            'name' => fake()->name,
            'number' => fake()->numberBetween(0, 6),
        ];
    }

    /**
     * Define states: Override attributes that differ from the default definition.
     * Use it like this: YourModel::factory()->withHigherNumber()->make();
     */
    public function withHigherNumber()
    {
        return $this->states(function(array $attributes) {
            return [
                'number' => fake()->numberBetween(100, 900);
            ];
        });
    }
}

Next, add the OFFLINE\Seeder\Traits\HasSeederFactory trait to your model:

<?php
// plugins/yourvendor/yourplugin/models/YourModel.php
namespace YourVendor\YourPlugin\Models;

class YourModel extends Model
{
    use \OFFLINE\Seeder\Traits\HasSeederFactory; // add this
}

Defining seeders

Add a registerSeeder method to your Plugin.php in which you seed your plugin's models:

public function registerSeeder()
{
    \YourVendor\YourPlugin\Models\YourModel::factory()->count(50)->create();
}

Tailor integration

Starting from version 2.1, this plugin can be used to seed Tailor data.

Requirements

To seed Tailor data using this plugin, it is required that all Tailor blueprint handles are in the SomeSection\SomeEntity format, like Blog\Post.

Defining factories

For a Tailor entity like Blog\Post, create the file app/factories/blog/PostFactory.php and define your factory in it.

<?php

namespace App\Factories\Blog;

class PostFactory extends \OFFLINE\Seeder\Classes\Factory
{
    public function definition()
    {
        return [
            'title' => fake()->sentence,
            // ...
            'is_enabled' => true,
        ];
    }
}

Registering seeders

In the app/Provider.php, add a static registerSeeder method and define your seeders like so:

<?php

namespace App;

use OFFLINE\Seeder\Classes\Factory;

class Provider extends \System\Classes\AppBase
{
    // ...

    /**
     * @param $seed \Closure(string $handle, \Closure(Factory $factory) $callback): void
     */
    public static function registerSeeder(\Closure $seed)
    {
        // Blog\Post = blueprint handle
        $seed('Blog\Post', function(Factory $factory) {
            $factory->count(10)->create();
        });

        $seed('Blog\Category', function(Factory $factory) {
            // ...
        });

        $seed('Blog\Author', function(Factory $factory) {
            // ...
        });
    }

Seeding specific blueprints

The --plugins flag can be used to seed specific entities:

php artisan offline:seeder --plugins=Blog\\Post

Migrate from 2.x

October 3.3 introduced its own plugin:seed Artisan command. To resolve this conflict, the Artisan command of this plugin was renamed to offline:seeder.

No special migration work is required, you can just use the new Artisan command.

Migrate from 1.x

To migrate old seeders from Version 1.0 of this plugin, make the following changes:

  1. Move all factories from the factories.php to their own Factory classes in the factories directory.
  2. Add the OFFLINE\Seeder\Traits\HasSeederFactory trait to all models
  3. Change your registerSeeder method:
// Old
factory(YourModel::class)->make();
factory(YourModel::class)->states('special')->make();
// New
YourModel::factory()->make();
YourModel::factory()->special()->make();

Running seeders

Simply run php artisan offline:seeder to run the seeders of all plugins. The seeder of each plugin will be only run once.

To run a seeder for a already seeded plugin, use the --fresh option. Be aware that this will rollback and reinstall all plugins with a registered seeder completely, so any plugin data will be lost.

You can use the --plugins option to run only specified seeders. Simply provide a comma-separated list of plugin names.

php artisan offline:seeder --plugins=Vendor.PluginA,Vendor.PluginB --fresh

Included factories

This plugin includes factories for the following models:

\System\Models\File::class

\System\Models\File::factory()->make() returns a File model with a random image. You can use it in any seeder to attach a file to a created model:

// Create a model
$myModel = \YourVendor\YourPlugin\Models\YourModel::factory()->create();

// Attach an image
$image = \System\Models\File::factory()->make();
$myModel->image()->save($image);

There are size states available: tiny returns a 90x90 image, hd returns a 1920x1080 image and huge returns a 6000x4000 image. Only one side of the image will match the given dimension (it is uncropped by default).

$tiny = \System\Models\File::factory()->tiny()->make();
$hd = \System\Models\File::factory()->hd()->make();
$huge = \System\Models\File::factory()->huge()->make();

If you need something other than an image, you can use the file, pdf, mp3 or xlsx states:

$randomType = \System\Models\File::factory()->file()->make();
$pdf = \System\Models\File::factory()->pdf()->make();
$mp3 = \System\Models\File::factory()->mp3()->make();
$xlsx = \System\Models\File::factory()->xlsx()->make();

\Backend\Models\User::class

\Backend\Models\User::factory()->make() returns a Backend User model. You can use the superuser state to generate a superuser.

// Build a simple backend user.
\Backend\Models\User::factory()->make();

// Build a superuser backend user.
\Backend\Models\User::factory()->superuser()->make();

\RainLab\User\Models\User::class

\RainLab\User\Models\User::factory()->make() returns a RainLab User model.

Twig helper functions

You can use the random_image() helper function to get a random image directly in your markup.

<img src="{{ random_image().thumb(400, 800) }}" alt=""/>
<img src="{{ random_image('tiny').thumb(400, 800) }}" alt=""/>
<img src="{{ random_image('hd').thumb(400, 800) }}" alt=""/>
<img src="{{ random_image('huge').thumb(400, 800) }}" alt=""/>

If you need a valid file download, you can use the random_file() function:

<a href="{{ random_file('xlsx').path }}" download>Download the spreadsheet!</a>
<a href="{{ random_file('pdf').path }}" download>Download the PDF!</a>

{# or make some noise #}
<audio controls src="{{ random_file('mp3').path }}"></audio>

Attribution

All images used in this plugin are provided by unsplash.com.

Credits

This plugin is heavily inspired by Inetis' oc-testing-plugin.

oc-seeder-plugin's People

Contributors

chkilel avatar tobias-kuendig avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

marcomessa dheia

oc-seeder-plugin's Issues

Exception when running the console command

factories.php

<?php

/** @var $factory Illuminate\Database\Eloquent\Factory */
$factory->define(\Voilaah\Octovod\Models\Author::class, function (\OFFLINE\Seeder\Classes\Generator $faker) {
    return [
        'name' => $name = $faker->name,
        'slug' => str_slug($name),
    ];
});

Exception after running the command console php artisan plugin:seed

[2020-08-14 10:35:56] development.ERROR: OFFLINE.Seeder failed: Unable to locate factory with name [default] [Voilaah\Octovod\Models\Author]. ["[object] (InvalidArgumentException(code: 0): Unable to locate factory with name [default] [Voilaah\\Octovod\\Models\\Author]. at /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:248)\n[stacktrace]\n#0 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php(122): Illuminate\\Database\\Eloquent\\FactoryBuilder->Illuminate\\Database\\Eloquent\\{closure}()\n#1 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php(260): Illuminate\\Database\\Eloquent\\Model::unguarded(Object(Closure))\n#2 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php(193): Illuminate\\Database\\Eloquent\\FactoryBuilder->makeInstance(Array)\n#3 [internal function]: Illuminate\\Database\\Eloquent\\FactoryBuilder->Illuminate\\Database\\Eloquent\\{closure}(1)\n#4 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php(194): array_map(Object(Closure), Array)\n#5 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php(148): Illuminate\\Database\\Eloquent\\FactoryBuilder->make(Array)\n#6 /Users/christophevidal/Sites/octoflix/plugins/voilaah/octovod/Plugin.php(17): Illuminate\\Database\\Eloquent\\FactoryBuilder->create()\n#7 /Users/christophevidal/Sites/octoflix/plugins/offline/seeder/classes/SeederManager.php(41): Voilaah\\Octovod\\Plugin->registerSeeder()\n#8 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Support/Collection.php(339): OFFLINE\\Seeder\\Classes\\SeederManager->OFFLINE\\Seeder\\Classes\\{closure}(Object(Voilaah\\Octovod\\Plugin), 'Voilaah.Octovod')\n#9 /Users/christophevidal/Sites/octoflix/plugins/offline/seeder/classes/SeederManager.php(54): Illuminate\\Support\\Collection->each(Object(Closure))\n#10 /Users/christophevidal/Sites/octoflix/plugins/offline/seeder/console/PluginSeedCommand.php(20): OFFLINE\\Seeder\\Classes\\SeederManager->seed(false, Object(Illuminate\\Console\\OutputStyle))\n#11 [internal function]: OFFLINE\\Seeder\\Console\\PluginSeedCommand->handle()\n#12 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array)\n#13 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\\Container\\BoundMethod::Illuminate\\Container\\{closure}()\n#14 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\\Container\\BoundMethod::callBoundMethod(Object(October\\Rain\\Foundation\\Application), Array, Object(Closure))\n#15 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Container/Container.php(549): Illuminate\\Container\\BoundMethod::call(Object(October\\Rain\\Foundation\\Application), Array, Array, NULL)\n#16 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Console/Command.php(183): Illuminate\\Container\\Container->call(Array)\n#17 /Users/christophevidal/Sites/octoflix/vendor/symfony/console/Command/Command.php(255): Illuminate\\Console\\Command->execute(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))\n#18 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\\Component\\Console\\Command\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Illuminate\\Console\\OutputStyle))\n#19 /Users/christophevidal/Sites/octoflix/vendor/symfony/console/Application.php(987): Illuminate\\Console\\Command->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#20 /Users/christophevidal/Sites/octoflix/vendor/symfony/console/Application.php(255): Symfony\\Component\\Console\\Application->doRunCommand(Object(OFFLINE\\Seeder\\Console\\PluginSeedCommand), Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#21 /Users/christophevidal/Sites/octoflix/vendor/symfony/console/Application.php(148): Symfony\\Component\\Console\\Application->doRun(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#22 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Console/Application.php(88): Symfony\\Component\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#23 /Users/christophevidal/Sites/octoflix/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(121): Illuminate\\Console\\Application->run(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#24 /Users/christophevidal/Sites/octoflix/artisan(35): Illuminate\\Foundation\\Console\\Kernel->handle(Object(Symfony\\Component\\Console\\Input\\ArgvInput), Object(Symfony\\Component\\Console\\Output\\ConsoleOutput))\n#25 {main}\n"] 

Make available on packagist

Would be good if this package was available on packagist as well so we can easily install it with composer. I saw a lot of your other packages are already on there.

I've installed it directly from this repository for now:

    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/OFFLINE-GmbH/oc-seeder-plugin"
        }
    ],
    "require-dev": {
        "offline/oc-seeder-plugin": "~1.0.5"
    },

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.