Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tihomiro committed Jul 17, 2013
1 parent 1ef5bd8 commit 06c6cdd
Show file tree
Hide file tree
Showing 12 changed files with 378 additions and 3 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/vendor
composer.phar
composer.lock
.DS_Store
12 changes: 12 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
language: php

php:
- 5.3
- 5.4
- 5.5

before_script:
- curl -s http://getcomposer.org/installer | php
- php composer.phar install --dev

script: phpunit
89 changes: 86 additions & 3 deletions README.md
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,4 +1,87 @@
iseed
=====
**Inverse seed generator (iSeed)** is a Laravel 4 package that provides a method to generate a new seed file based on data from the existing database table.

Laravel 4 Inverse Seed Generator
## Installation

1) Edit your project's `composer.json` file to require `orangehill/iseed`.

"require": {
"laravel/framework": "4.0.*",
"orangehill/iseed": "dev-master"
}

2) Update Composer from the CLI:

composer update

3) Once this operation completes, add the service provider by opening a `app/config/app.php` file, and adding a new item to the `providers` array.

'Orangehill\Iseed\IseedServiceProvider'

## Usage

To generate a seed file simply call: `\Iseed::generateSeed('users');`

This will create a file inside a `/app/database/seeds`, with the contents similar to following example:

<?php

// File: /app/database/seeds/UsersTableSeeder.php

class UsersTableSeeder extends Seeder {

/**
* Auto generated seed file
*
* @return void
*/
public function run()
{
\DB::table('users')->delete();
\DB::table('users')->insert(array (
0 =>
array (
'id' => '1',
'email' => '[email protected]',
'password' => '$2y$10$tUGCkQf/0NY3w1l9sobGsudt6UngnoVXx/lUoh9ElcSOD0ERRkK9C',
'permissions' => NULL,
'activated' => '1',
'activation_code' => NULL,
'activated_at' => NULL,
'last_login' => NULL,
'persist_code' => NULL,
'reset_password_code' => NULL,
'first_name' => NULL,
'last_name' => NULL,
'created_at' => '2013-06-11 07:47:40',
'updated_at' => '2013-06-11 07:47:40',
),
1 =>
array (
'id' => '2',
'email' => '[email protected]',
'password' => '$2y$10$ImNvsMzK/BOgNSYgpjs/3OjMKMHeA9BH/hjl43EiuBuLkZGPMuZ2W',
'permissions' => NULL,
'activated' => '1',
'activation_code' => NULL,
'activated_at' => NULL,
'last_login' => '2013-06-11 07:54:57',
'persist_code' => '$2y$10$C0la8WuyqC6AU2TpUwj0I.E3Mrva8A3tuVFWxXN5u7jswRKzsYYHK',
'reset_password_code' => NULL,
'first_name' => NULL,
'last_name' => NULL,
'created_at' => '2013-06-11 07:47:40',
'updated_at' => '2013-06-11 07:54:57',
),
));
}

}

This command will also update `app/database/seeds/DatabaseSeeder.php` to include a call to this newly generated seed class.

To (re)seed the database go to the Terminal and run Laravel's `db:seed command` (`php artisan db:seed`).

## Todo

- implement as artisan command `iseed:make table_name`
- implement tests
21 changes: 21 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "orangehill/iseed",
"description": "Generate a new seed file based on data from the existing database table.",
"license": "BSD-2-Clause",
"authors": [
{
"name": "Tihomir Opacic",
"email": "[email protected]"
}
],
"require": {
"php": ">=5.3.0",
"illuminate/support": "4.0.x"
},
"autoload": {
"psr-0": {
"Orangehill\\Iseed": "src/"
}
},
"minimum-stability": "dev"
}
18 changes: 18 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
3 changes: 3 additions & 0 deletions src/Orangehill/Iseed/Exceptions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?php namespace Orangehill\Iseed;

class TableNotFoundException extends \RuntimeException {}
14 changes: 14 additions & 0 deletions src/Orangehill/Iseed/Facades/Iseed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php namespace Orangehill\Iseed\Facades;

use Illuminate\Support\Facades\Facade;

class Iseed extends Facade {

/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'iseed'; }

}
145 changes: 145 additions & 0 deletions src/Orangehill/Iseed/Iseed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<?php namespace Orangehill\Iseed;

use Illuminate\Filesystem\Filesystem;

class Iseed {

public function __construct()
{
$this->files = new Filesystem;
}

/**
* Generates a seed file.
*
* @param string $table
* @return void
* @throws Orangehill\Iseed\TableNotFoundException
*/
public function generateSeed($table)
{

// Check if table exists
if (!\Schema::hasTable($table)) throw new TableNotFoundException("Table $table was not found.");

// Get the data
$data = \DB::table($table)->get();

foreach ($data as $row)
{
$rowArray = array();
foreach($row as $columnName => $columnValue)
{
$rowArray[$columnName] = $columnValue;
}
$dataArray[] = $rowArray;
}

// Generate class name
$className = $this->generateClassName($table);

// Get template for a seed file contents
$stub = $this->files->get($this->getStubPath() . '/seed.stub');

// Get a seed folder path
$seedPath = app_path() . \Config::get('iseed::path');

// Save a populated stub
$this->files->put($this->getPath($className, $seedPath), $this->populateStub($className, $stub, $table, $this->prettifyArray($dataArray)));

// Update the DatabaseSeeder.php file
$this->updateDatabaseSeederRunMethod($className);

}

/**
* Generates a seed class name (also used as a filename)
*
* @param string $table
* @return string
*/
protected function generateClassName($table)
{
return ucfirst($table) . 'TableSeeder';
}

/**
* Get the path to the stub file.
*
* @return string
*/
protected function getStubPath()
{
return __DIR__ . '/Stubs';
}

/**
* Populate the place-holders in the seed stub.
*
* @param string $class
* @param string $stub
* @param string $table
* @param string $data
* @return string
*/
protected function populateStub($class, $stub, $table, $data)
{
$stub = str_replace('{{class}}', $class, $stub);

if ( ! is_null($table))
{
$stub = str_replace('{{table}}', $table, $stub);
}

if ( ! is_null($data))
{
$stub = str_replace('{{data}}', $data, $stub);
}

return $stub;
}

/**
* Create the full path name to the seed file.
*
* @param string $name
* @param string $path
* @return string
*/
protected function getPath($name, $path)
{
return $path . '/' . $name . '.php';
}

/**
* Prettify a var_export of an array
*
* @param array $array
* @return string
*/
protected function prettifyArray($array)
{
$content = var_export($array, true);
$content = str_replace(" ", "\t", $content);
$content = str_replace("\n", "\n\t\t", $content);
return $content;
}

/**
* Updates the DatabaseSeeder file's run method (kudoz to: https://github.com/JeffreyWay/Laravel-4-Generators)
*
* @param string $className
* @return void
*/
protected function updateDatabaseSeederRunMethod($className)
{
$databaseSeederPath = app_path() . \Config::get('iseed::path') . '/DatabaseSeeder.php';

$content = $this->files->get($databaseSeederPath);
if(strpos($content, '$this->call(\'UsersTableSeeder\')')===false)
$content = preg_replace("/(run\(\).+?)}/us", "$1\t\$this->call('{$className}');\n\t}", $content);

$this->files->put($databaseSeederPath, $content);
}

}
52 changes: 52 additions & 0 deletions src/Orangehill/Iseed/IseedServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php namespace Orangehill\Iseed;

use Illuminate\Support\ServiceProvider;

class IseedServiceProvider extends ServiceProvider {

/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = false;

/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
$this->package('orangehill/iseed');
}

/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app['iseed'] = $this->app->share(function($app)
{
return new Iseed;
});
$this->app->booting(function()
{
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Iseed', 'Orangehill\Iseed\Facades\Iseed');
});
}

/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return array('iseed');
}

}
16 changes: 16 additions & 0 deletions src/Orangehill/Iseed/Stubs/seed.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

class {{class}} extends Seeder {

/**
* Auto generated seed file
*
* @return void
*/
public function run()
{
\DB::table('{{table}}')->delete();
\DB::table('{{table}}')->insert({{data}});
}

}
7 changes: 7 additions & 0 deletions src/config/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

return array(

'path' => '/database/seeds',

);
Empty file added tests/.gitkeep
Empty file.

0 comments on commit 06c6cdd

Please sign in to comment.