130 lines
7.4 KiB
JavaScript
130 lines
7.4 KiB
JavaScript
// The fixtures form's model (no DOM, tested in fixtures.test.mjs): the generators a field can have, their defaults, the sample shown beside
|
||
// each, the model sent to the PHP side (ide/src/Fixtures) and the plan of a load.
|
||
|
||
export const TYPES = ['faker', 'fixed', 'sequence', 'between', 'dateBetween', 'boolean', 'enum', 'ref', 'refs', 'null', 'skip'];
|
||
|
||
/** the label keys of the generator types (translated by the form with t()) */
|
||
export const TYPE_LABELS = {
|
||
faker: 'Faker formatter', fixed: 'Fixed value', sequence: 'Sequence', between: 'Number between', dateBetween: 'Date between', boolean: 'Boolean',
|
||
enum: 'Enum case', ref: 'Reference to a fixture', refs: 'References to fixtures (several)', null: 'Null', skip: 'Leave unset',
|
||
};
|
||
|
||
const short = (cls) => String(cls || '').split('\\').pop();
|
||
|
||
/** the generator types a field accepts: a relation takes references, an enum takes its cases, a column takes values */
|
||
export function typesFor(field) {
|
||
if (field.relation) return field.type === 'ManyToMany' ? ['refs', 'null', 'skip'] : ['ref', 'null', 'skip'];
|
||
if (field.enumType) return ['enum', 'fixed', 'null', 'skip'];
|
||
const t = String(field.type || '');
|
||
if (['boolean'].includes(t)) return ['boolean', 'fixed', 'null', 'skip'];
|
||
if (['integer', 'smallint', 'bigint', 'float', 'decimal'].includes(t)) return ['between', 'sequence', 'faker', 'fixed', 'null', 'skip'];
|
||
if (t.startsWith('date') || t.startsWith('time')) return ['dateBetween', 'faker', 'fixed', 'null', 'skip'];
|
||
return ['faker', 'fixed', 'sequence', 'between', 'dateBetween', 'boolean', 'null', 'skip'];
|
||
}
|
||
|
||
/** a generator of a type with sensible parameters for a field (what switching the select gives) */
|
||
export function defaultGenerator(type, field, info) {
|
||
switch (type) {
|
||
case 'faker': { const f = (info.catalog || []).find((c) => c.types.includes(field.type)) || { name: 'word', args: [] }; return { type, formatter: f.name, args: f.args.map((a) => a.default) }; }
|
||
case 'fixed': return { type, value: field.type === 'boolean' ? true : (['integer', 'smallint', 'bigint', 'float', 'decimal'].includes(field.type) ? 0 : '') };
|
||
case 'sequence': return { type, pattern: `${String(field.name || 'item')} {n}`, start: 1 };
|
||
case 'between': return { type, min: 1, max: 100, float: ['float', 'decimal'].includes(field.type), decimals: 2, cast: field.type === 'decimal' ? 'string' : undefined };
|
||
case 'dateBetween': return { type, from: '-1 year', to: 'now', immutable: !!field.immutable };
|
||
case 'boolean': return { type, chance: 50 };
|
||
case 'enum': return { type, class: field.enumType || '', mode: 'random', case: '' };
|
||
case 'ref': return { type, target: field.target || '', mode: 'random', index: 0 };
|
||
case 'refs': return { type, target: field.target || '', min: 1, max: 3 };
|
||
default: return { type };
|
||
}
|
||
}
|
||
|
||
/** one line of what a generator makes, for the grid's preview column (offline: the Faker samples of the catalog) */
|
||
export function sample(gen, info, i = 0) {
|
||
const g = gen || { type: 'skip' };
|
||
switch (g.type) {
|
||
case 'fixed': return typeof g.value === 'string' ? g.value : JSON.stringify(g.value);
|
||
case 'faker': {
|
||
const f = (info.catalog || []).find((c) => c.name === g.formatter);
|
||
const s = f?.samples?.length ? f.samples[i % f.samples.length] : g.formatter;
|
||
return typeof s === 'string' ? s : JSON.stringify(s);
|
||
}
|
||
case 'sequence': return String(g.pattern || '{n}').split('{n}').join(String(Number(g.start ?? 1) + i));
|
||
case 'between': {
|
||
const min = Number(g.min ?? 0); const max = Number(g.max ?? 100);
|
||
const v = min + ((i * 37 + 11) % Math.max(1, Math.floor(max - min) + 1));
|
||
return g.float ? v.toFixed(Number(g.decimals ?? 2)) : String(v);
|
||
}
|
||
case 'dateBetween': return ['2026-03-14 10:21', '2025-12-02 08:00', '2026-08-30 17:45'][i % 3];
|
||
case 'boolean': return i % 2 ? 'false' : 'true';
|
||
case 'enum': {
|
||
if (g.mode === 'case') return `${short(g.class)}::${g.case}`;
|
||
const cases = info.enums?.[g.class] || [];
|
||
return cases.length ? `${short(g.class)}::${cases[i % cases.length].name}` : short(g.class);
|
||
}
|
||
case 'ref': return g.mode === 'index' ? `→ ${short(g.target)} #${g.index ?? 0}` : `→ ${short(g.target)}`;
|
||
case 'refs': return `→ ${g.min ?? 1}-${g.max ?? 3} × ${short(g.target)}`;
|
||
case 'null': return 'null';
|
||
default: return '—';
|
||
}
|
||
}
|
||
|
||
/** the rows the grid shows without running anything: [{field: sample}] */
|
||
export function sampleRows(model, info, n = 3) {
|
||
return Array.from({ length: n }, (_, i) => Object.fromEntries(model.fields.filter((f) => f.generator.type !== 'skip').map((f) => [f.name, sample(f.generator, info, i)])));
|
||
}
|
||
|
||
/** a new model for an entity: every field with its suggested generator */
|
||
export function newModel(info, entityClass, kind = null) {
|
||
const e = (info.entities || []).find((x) => x.class === entityClass) || info.entities?.[0];
|
||
if (!e) return null;
|
||
return {
|
||
entity: e.class, class: `${e.name}Fixtures`, kind: kind || info.kind || 'faker', count: 10, groups: ['dev'], locale: 'en_US', seed: '',
|
||
rootNamespace: info.rootNamespace || 'App', fields: e.fields.map((f) => ({ name: f.name, generator: structuredClone(f.suggest) })),
|
||
};
|
||
}
|
||
|
||
/** the model as the PHP side wants it (numbers as numbers, groups as a list, no empty arguments) */
|
||
export function cleanModel(m) {
|
||
const groups = typeof m.groups === 'string' ? m.groups.split(/[,\s]+/).filter(Boolean) : (m.groups || []);
|
||
return { ...m, count: Math.max(1, Number(m.count) || 1), groups, seed: m.seed === '' || m.seed == null ? null : Number(m.seed), fields: m.fields.map((f) => ({ name: f.name, generator: cleanGenerator(f.generator) })) };
|
||
}
|
||
|
||
function cleanGenerator(g) {
|
||
const out = { ...g };
|
||
for (const k of ['min', 'max', 'decimals', 'chance', 'start', 'index']) if (k in out && out[k] !== '' && !Number.isNaN(Number(out[k]))) out[k] = Number(out[k]);
|
||
if (out.type === 'faker') out.args = (out.args || []).map(coerce);
|
||
if (out.cast === undefined) delete out.cast;
|
||
return out;
|
||
}
|
||
|
||
/** a typed argument: "3" is 3, "true" is true, a JSON list stays a list, anything else a string */
|
||
export function coerce(v) {
|
||
if (typeof v !== 'string') return v;
|
||
const s = v.trim();
|
||
if (s !== '' && !Number.isNaN(Number(s))) return Number(s);
|
||
if (s === 'true' || s === 'false') return s === 'true';
|
||
if (s.startsWith('[')) { try { return JSON.parse(s); } catch { /* a string */ } }
|
||
return v;
|
||
}
|
||
|
||
/** how an argument is typed back into its input */
|
||
export function argText(v) {
|
||
return typeof v === 'string' ? v : JSON.stringify(v);
|
||
}
|
||
|
||
/** the fixtures that load before this one (relations), from the fixtures of the project: names of classes */
|
||
export function dependencies(model, info) {
|
||
const known = Object.fromEntries((info.fixtures || []).filter((f) => f.entity).map((f) => [f.entity, f.class]));
|
||
const ns = `${model.rootNamespace || 'App'}\\DataFixtures`;
|
||
const out = [];
|
||
for (const f of model.fields) {
|
||
const g = f.generator;
|
||
if ((g.type === 'ref' || g.type === 'refs') && g.target && g.target !== model.entity) out.push(known[g.target] || `${ns}\\${short(g.target)}Fixtures`);
|
||
}
|
||
return [...new Set(out)];
|
||
}
|
||
|
||
/** the command a load runs (the PHP side makes the same line and checks the guards) */
|
||
export function loadLine({ mode = 'append', groups = [] }) {
|
||
return ['php bin/console doctrine:fixtures:load --no-interaction', mode === 'append' ? '--append' : '', ...groups.map((g) => `--group=${g}`)].filter(Boolean).join(' ');
|
||
}
|