graze / graze/sprout

Support php class based seeding/chopping

Open
#7 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
PHP
Stars
0
Forks
0
PR merge metrics
No merged PRs in 30d

Description

Create some sort of interface `SeederInterface`, `ChopperInterface`.

```php
interface SeederInterface {
public function seed( $db, string $schema);
}

interface ChopperInterface {
public function chop( $db, string $schema);
}
```

Example

```php
class CountrySeeder implements SeederInterface, ChopperInterface {
public function seed($db, string $schema) {
$db->insert('table', [
['name' => 'Algeria', 'country_code' => 'AL'],
['name' => 'Afghanistan', 'country_code' => 'AF'],
]);
}

public function chop($db, string $schema) {
$db->delete('table', ['country_code' => ['AL', 'AF']]);
}
}
```

Be able to place these files with the `.sql` files. They can be called anything.

This will allow you to seed dynamic data, or data without requiring the id's.

Then we can extended it to deal with just data, and ignore the method of seeding

```php
interface SeedDataInterface {
const SEED_TYPE_TRUNCATE = 'truncate'; // truncate the whole table first
const SEED_TYPE_UPDATE = 'update'; // seed that data, and update any existing entries
const SEED_TYPE_IGNORE = 'ignore'; // seed the data, but ignore any existing entries

public function getData(): array; // [[key => value, ...], ...]
public function getTableName(): string;
public function getSeedType(): string; // SEED_TYPE_*
}
```

Example:

```php
class CountrySeedData implements SeedDataInterface
{
public function getTableName(): string {
return 'country';
}

public function getSeedType(): string {
return static::SEED_TYPE_UPDATE;
}

public function getData(): array {
return [
'AF' => [
'country_code' => 'AF',
'country_code_iso2' => 'AF',
'country_code_iso3' => 'AFG',
'name' => 'Afghanistan',
],
'AX' => [
'country_code' => 'AX',
'country_code_iso2' => 'AX',
'country_code_iso3' => 'ALA',
'name' => 'Aland Islands',
],
];
}
}
```

We could use this as the bases for file format (Yaml/Json/CSV) importing; something like:

```php
class FileParser implements FileParserInterface {
public function __construct(FormatParserInterface $parser) {}
public function parse(string $filePath): SeedDataInterface {
$data = $this->parser->parse($filePath);
return new SeedData($data['table'], $data['data'], $data['type'] ?? static::SEED_TYPE_TRUNCATE);
}
}

class SeedData implements SeedDataInterface {
public function __construct(string $table, array $data, string $type = static::SEED_TYPE_TRUNCATE) {}
}

$yamlFileParser = new FileParser(new YamlFormatParser());
$seeder->seed($yamlFileParser->parse('/a/path/to/some/file'));
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.