-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgenerate-models.php
55 lines (43 loc) · 1.4 KB
/
generate-models.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
/**
* This script generates models in YAML or JSON format
* from Drupal model entities.
*
* Usage:
* Invoke this script with Drush from the project root.
* Pass 'json' or 'yaml' as an argument.
*
* Example:
* vendor/bin/drush scr scripts/generate-models.php json
* vendor/bin/drush scr scripts/generate-models.php yaml
*/
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
use Drush\Drush;
$args = Drush::input()->getArguments();
if (!isset($args['extra'][1])) {
throw new InvalidArgumentException('Missing "json" or "yaml" argument.');
}
if ($args['extra'][1] !== 'json' && $args['extra'][1] !== 'yaml') {
throw new InvalidArgumentException('Invalid argument.');
}
$format = $args['extra'][1];
$serializer = \Drupal::service('model_serializer');
$path = \Drupal::root() . '/../models/';
foreach (\Drupal::entityTypeManager()
->getStorage('model')
->loadMultiple() as $model) {
if ($format === 'yaml') {
$output = $serializer->toYaml($model);
$ext = '.yml';
}
else if ($format === 'json') {
$output = $serializer->toJson($model);
$ext = '.json';
}
$bytes = file_put_contents($path . $model->label() . $ext, $output);
if ($bytes === false) {
throw new RuntimeException('Failed to write model file.');
}
print 'Generated ' . realpath($path) . '/' . $model->label() . $ext . PHP_EOL;
}