124 lines
7.5 KiB
JavaScript
124 lines
7.5 KiB
JavaScript
// The field rows of the "New entity" dialog (no DOM): defaults, which options a type has, validation, and the conversion to what
|
|
// ide/src/Doctrine/EntityWriter wants (fields: name, type, length, precision, scale, nullable, unique, default, enumType; relations
|
|
// are written afterwards through doctrine.relation.add).
|
|
export const FIELD_TYPES = ['string', 'text', 'integer', 'smallint', 'bigint', 'boolean', 'float', 'decimal', 'datetime_immutable', 'datetime', 'date_immutable', 'date',
|
|
'time_immutable', 'time', 'json', 'simple_array', 'guid', 'uuid', 'ulid', 'binary', 'blob', 'enum'];
|
|
export const RELATION_KINDS = ['ManyToOne', 'OneToMany', 'OneToOne', 'ManyToMany'];
|
|
const RESERVED = new Set(['abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'do', 'echo',
|
|
'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'enum', 'eval', 'exit', 'extends', 'final', 'finally', 'fn', 'for', 'foreach',
|
|
'function', 'global', 'goto', 'if', 'implements', 'include', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'match', 'namespace', 'new', 'or', 'print', 'private',
|
|
'protected', 'public', 'readonly', 'require', 'return', 'static', 'switch', 'this', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor', 'yield']);
|
|
|
|
/** a new row: string(255), not nullable */
|
|
export function newRow(over = {}) {
|
|
return { name: '', type: 'string', length: 255, precision: 10, scale: 2, nullable: false, unique: false, default: '', enumType: null,
|
|
relation: { target: '', kind: 'ManyToOne', inverse: '', orphanRemoval: false }, ...over };
|
|
}
|
|
|
|
/** the type of a row once the type select is changed: the options that no longer apply are reset */
|
|
export function setType(row, type) {
|
|
row.type = type;
|
|
row.length = has(row, 'length') ? (row.length || (type === 'string' ? 255 : null)) : null;
|
|
return row;
|
|
}
|
|
|
|
/** the options a type has: length, decimal (precision + scale), nullable, unique, default, enum, relation */
|
|
export function has(row, option) {
|
|
const ty = row.type;
|
|
switch (option) {
|
|
case 'length': return ty === 'string' || ty === 'binary';
|
|
case 'decimal': return ty === 'decimal';
|
|
case 'enum': return ty === 'enum';
|
|
case 'relation': return ty === 'relation';
|
|
case 'unique': return ty !== 'relation' && !['json', 'simple_array', 'blob'].includes(ty);
|
|
case 'default': return ty !== 'relation' && !['json', 'simple_array', 'blob', 'binary', 'uuid', 'ulid', 'guid', 'enum'].includes(ty);
|
|
case 'nullable': return true;
|
|
default: return false;
|
|
}
|
|
}
|
|
|
|
/** the problems of the rows: [{ index, field, key (untranslated message), params }]; index -1 = the class name */
|
|
export function validate(rows, { className = '', targets = [] } = {}) {
|
|
const errors = [];
|
|
const seen = new Set();
|
|
rows.forEach((r, index) => {
|
|
const name = String(r.name ?? '').trim();
|
|
const add = (field, key, params = {}) => errors.push({ index, field, key, params });
|
|
if (name === '') add('name', 'The name is empty');
|
|
else if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) add('name', '"{name}" is not a PHP name', { name });
|
|
else if (RESERVED.has(name.toLowerCase())) add('name', '"{name}" is a reserved word', { name });
|
|
else if (name === 'id') add('name', '"id" is already the primary key');
|
|
else if (seen.has(name.toLowerCase())) add('name', '"{name}" is used twice', { name });
|
|
if (name !== '') seen.add(name.toLowerCase());
|
|
if (r.type === 'relation') {
|
|
if (!r.relation?.target || (targets.length && !targets.includes(r.relation.target))) add('target', 'Pick the target entity');
|
|
const inv = String(r.relation?.inverse ?? '').trim();
|
|
if (inv !== '' && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(inv)) add('inverse', '"{name}" is not a PHP name', { name: inv });
|
|
}
|
|
if (has(r, 'length') && r.length !== null && r.length !== '' && !(Number(r.length) >= 1)) add('length', 'The length must be at least 1');
|
|
if (r.type === 'decimal') {
|
|
if (!(Number(r.precision) >= 1)) add('precision', 'The precision must be at least 1');
|
|
else if (!(Number(r.scale) >= 0) || Number(r.scale) > Number(r.precision)) add('scale', 'The scale must be between 0 and the precision');
|
|
}
|
|
if (r.type === 'enum' && !r.enumType) add('enumType', 'Pick a PHP enum');
|
|
});
|
|
if (className !== '' && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(className)) errors.push({ index: -1, field: 'class', key: '"{name}" is not a PHP name', params: { name: className } });
|
|
return errors;
|
|
}
|
|
|
|
/** rows -> { fields, relations } for EntityWriter::newEntity and doctrine.relation.add. Rows without a name are left out. */
|
|
export function toBackend(rows, { enums = [] } = {}) {
|
|
const fields = [];
|
|
const relations = [];
|
|
for (const r of rows) {
|
|
const name = String(r.name ?? '').trim();
|
|
if (name === '') continue;
|
|
if (r.type === 'relation') {
|
|
relations.push({ kind: r.relation.kind, property: name, target: r.relation.target, inverse: String(r.relation.inverse ?? '').trim(), nullable: !!r.nullable,
|
|
cascade: [], orphanRemoval: !!r.relation.orphanRemoval, onDelete: null, joinTable: '' });
|
|
continue;
|
|
}
|
|
const f = { name, type: r.type, nullable: !!r.nullable };
|
|
if (r.type === 'enum') {
|
|
f.type = enums.find((x) => x.class === r.enumType)?.backing === 'int' ? 'integer' : 'string';
|
|
f.enumType = r.enumType;
|
|
}
|
|
if (has(r, 'length') && r.length !== null && r.length !== '') f.length = Number(r.length);
|
|
if (r.type === 'decimal') { f.precision = Number(r.precision); f.scale = Number(r.scale); }
|
|
if (has(r, 'unique') && r.unique) f.unique = true;
|
|
if (has(r, 'default') && String(r.default ?? '') !== '') f.default = String(r.default);
|
|
fields.push(f);
|
|
}
|
|
return { fields, relations };
|
|
}
|
|
|
|
const PHP = { string: 'string', text: 'string', guid: 'string', bigint: 'string', decimal: 'string', integer: 'int', smallint: 'int', boolean: 'bool', float: 'float', json: 'array',
|
|
simple_array: 'array', uuid: 'Uuid', ulid: 'Ulid', binary: 'mixed', blob: 'mixed' };
|
|
|
|
/** a short preview of the property a row writes */
|
|
export function previewRow(r) {
|
|
const name = String(r.name ?? '').trim() || '…';
|
|
if (r.type === 'relation') {
|
|
const target = (r.relation.target || '…').split('\\').pop();
|
|
const many = ['OneToMany', 'ManyToMany'].includes(r.relation.kind);
|
|
return `#[ORM\\${r.relation.kind}(targetEntity: ${target}::class)]\nprivate ${many ? 'Collection' : (r.nullable ? '?' : '') + target} $${name};`;
|
|
}
|
|
const args = [];
|
|
if (!['string', 'enum', 'integer', 'boolean', 'float', 'json', 'uuid', 'ulid'].includes(r.type)) args.push(`type: '${r.type}'`);
|
|
if (has(r, 'length') && r.length) args.push(`length: ${r.length}`);
|
|
if (r.type === 'decimal') args.push(`precision: ${r.precision}, scale: ${r.scale}`);
|
|
if (r.nullable) args.push('nullable: true');
|
|
if (has(r, 'unique') && r.unique) args.push('unique: true');
|
|
if (has(r, 'default') && String(r.default ?? '') !== '') args.push(`options: ['default' => '${String(r.default).replace(/'/g, "\\'")}']`);
|
|
if (r.type === 'enum') args.push(`enumType: ${(r.enumType || '…').split('\\').pop()}::class`);
|
|
const php = r.type === 'enum' ? (r.enumType || 'mixed').split('\\').pop() : (PHP[r.type] || '\\DateTimeImmutable');
|
|
return `#[ORM\\Column${args.length ? '(' + args.join(', ') + ')' : ''}]\nprivate ?${php} $${name} = null;`;
|
|
}
|
|
|
|
/** moves a row by delta (-1 up, +1 down); returns the same array */
|
|
export function move(rows, index, delta) {
|
|
const to = index + delta;
|
|
if (to < 0 || to >= rows.length) return rows;
|
|
[rows[index], rows[to]] = [rows[to], rows[index]];
|
|
return rows;
|
|
}
|