427 lines
26 KiB
JavaScript
427 lines
26 KiB
JavaScript
// The Validation window (Symfony): the validation constraints of a class of the project (an entity, a DTO...), read from
|
|
// its #[Assert\...] attributes and from config/validator/*.yaml / *.xml. Each member (property, promoted parameter, getter)
|
|
// shows its constraints as chips: a click edits one (its options by kind: messages, numbers, lists, choices, regular
|
|
// expressions, nested constraints of All / Sequentially / When / AtLeastOneOf, Collection fields, groups, payload), + adds
|
|
// one from Symfony's whole catalogue (or the project's own constraints), suggestions come from the Doctrine mapping. The
|
|
// groups the class uses and its GroupSequence; a wizard writes a custom constraint (Constraint + ConstraintValidator, or a
|
|
// Compound); "Test a value" validates sample data through a small dev-only console command (the runner of the Console window).
|
|
// Every change is shown as a difference before it is written (symfony-diff.js). The PHP side: ide/src/Symfony/Validation*.php.
|
|
import { backend } from './backend.js';
|
|
import { el, clear, icon, notify, t, dialog, chooser } from './ui.js';
|
|
import { reviewChanges, symfonyToolsStyle } from './symfony-diff.js';
|
|
|
|
// the catalogue's families, as the chooser and the dialogs name them
|
|
const family = (f) => ({ Basic: t('Basic'), String: t('Strings'), Comparison: t('Comparisons'), Number: t('Numbers'), Date: t('Dates'), Choice: t('Choices'),
|
|
File: t('Files'), Financial: t('Finance'), Collection: t('Collections'), Other: t('Other'), Class: t('Class'), Doctrine: 'Doctrine', Custom: t('project') }[f] || f);
|
|
const TEXT_KINDS = ['text', 'message', 'regex', 'expression', 'propertyPath', 'class', 'callable'];
|
|
|
|
/** a value as the field shows it */
|
|
export function valueText(v) {
|
|
if (v === null || v === undefined) return '';
|
|
if (typeof v === 'object' && '@raw' in v) return v['@raw'];
|
|
if (typeof v === 'object') return JSON.stringify(v);
|
|
return String(v);
|
|
}
|
|
|
|
/** what a "value" field holds: a number, true / false / null, JSON, else the text */
|
|
export function parseValue(text) {
|
|
const s = text.trim();
|
|
if (s === '') return undefined;
|
|
if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
|
|
if (s === 'true' || s === 'false') return s === 'true';
|
|
if (s === 'null') return null;
|
|
if (/^[[{]/.test(s)) { try { return JSON.parse(s); } catch { /* a string */ } }
|
|
return text;
|
|
}
|
|
|
|
/** one constraint as a chip's text: Length(min: 2, max: 50) */
|
|
export function summary(c) {
|
|
const name = c.name.includes('\\') ? c.name.split('\\').pop() : c.name;
|
|
const opts = Object.entries(c.options || {}).filter(([k]) => k !== 'payload').map(([k, v]) => `${/^\d+$/.test(k) ? '' : k + ': '}${short(v)}`);
|
|
return [name, opts.join(', ')];
|
|
}
|
|
function short(v) {
|
|
if (v && typeof v === 'object' && '@constraint' in v) return summary(v['@constraint'])[0] + '(…)';
|
|
if (v && typeof v === 'object' && '@raw' in v) return v['@raw'];
|
|
if (Array.isArray(v)) return '[' + v.map(short).join(', ') + ']';
|
|
if (v && typeof v === 'object') return '{…}';
|
|
if (typeof v === 'string') return `'${v.length > 24 ? v.slice(0, 22) + '…' : v}'`;
|
|
return String(v);
|
|
}
|
|
|
|
export class ValidationPanel {
|
|
constructor(app) {
|
|
this.app = app;
|
|
this.node = el('div.sx-view');
|
|
this.catalog = null;
|
|
this.classes = [];
|
|
this.custom = [];
|
|
this.helper = false;
|
|
this.path = null;
|
|
this.model = null;
|
|
this.error = null;
|
|
this.test = { member: '', value: '', values: {}, groups: [], result: null, busy: false };
|
|
symfonyToolsStyle();
|
|
this.render();
|
|
app.editors.on('active', (tab) => this.follow(tab?.path));
|
|
app.editors.on('saved', (path) => { if (path === this.path) this.read(); });
|
|
}
|
|
|
|
title() { return t('Validation'); }
|
|
|
|
actions() {
|
|
return [
|
|
el('button', { title: t('New constraint…'), onclick: () => this.newConstraint() }, icon('plus')),
|
|
el('button', { title: t('Refresh'), onclick: () => this.load() }, icon('refresh')),
|
|
];
|
|
}
|
|
|
|
shown() { if (!this.catalog) this.load(); }
|
|
|
|
async load() {
|
|
try {
|
|
[this.catalog, { classes: this.classes, custom: this.custom, helper: this.helper }] = await Promise.all([
|
|
this.catalog ? this.catalog : backend.invoke('validation.catalog', {}), backend.invoke('validation.classes', {})]);
|
|
} catch (e) { this.error = e.message; }
|
|
const active = this.app.editors.activePath();
|
|
if (!this.path && active && this.classes.some((c) => c.path === active)) this.path = active;
|
|
if (!this.path && this.classes.length) this.path = this.classes[0].path;
|
|
if (this.path) await this.read(); else this.render();
|
|
}
|
|
|
|
/** the window follows the editor: a class of the list opened there is shown */
|
|
follow(path) {
|
|
if (path && path !== this.path && this.classes.some((c) => c.path === path)) { this.path = path; this.read(); }
|
|
}
|
|
|
|
async read() {
|
|
try { this.model = await backend.invoke('validation.read', { path: this.path }); this.error = null; } catch (e) { this.model = null; this.error = e.message; }
|
|
this.render();
|
|
}
|
|
|
|
describe(name) {
|
|
return this.catalog?.find((c) => c.name === name) || { name, family: 'Custom', property: true, class: true, main: null, options: [{ name: 'message', kind: 'message' }, { name: 'groups', kind: 'list' }, { name: 'payload', kind: 'value' }] };
|
|
}
|
|
|
|
render() {
|
|
clear(this.node);
|
|
const select = el('select.input', { onchange: (e) => { this.path = e.target.value; this.read(); } });
|
|
for (const kind of ['entity', 'dto', 'class']) {
|
|
const items = this.classes.filter((c) => c.kind === kind);
|
|
if (!items.length) continue;
|
|
const g = el('optgroup', { label: { entity: t('Entities'), dto: t('DTOs and models'), class: t('Other classes') }[kind] });
|
|
for (const c of items) g.append(el('option', { value: c.path, selected: c.path === this.path }, `${c.class.split('\\').pop()}${c.count ? ` (${c.count})` : ''}`));
|
|
select.append(g);
|
|
}
|
|
this.node.append(el('div.sx-bar', {}, select,
|
|
el('button.btn.small', { onclick: () => this.newConstraint(), title: t('A constraint of your own: a Constraint class and its validator, or a Compound') }, icon('plus'), t('New constraint…'))));
|
|
const body = el('div.sx-body');
|
|
this.node.append(body);
|
|
if (this.error) body.append(el('div.sx-warn.error', {}, icon('warning'), el('span', {}, this.error)));
|
|
if (!this.catalog) { body.append(el('div.sx-empty', {}, t('Loading…'))); return; }
|
|
if (!this.classes.length) { body.append(el('div.sx-empty', {}, t('No entity nor DTO in src/ yet. Open a PHP class to see its constraints.'))); return; }
|
|
const m = this.model;
|
|
if (!m) return;
|
|
body.append(el('div.sx-head', {}, el('h3', {}, m.short), el('span.sx-muted', {}, m.class.split('\\').slice(0, -1).join('\\')),
|
|
m.entity ? el('span.sx-badge.blue', {}, t('entity')) : null,
|
|
el('span.sx-link', { onclick: () => this.app.editors.open(m.path, { line: m.line }) }, t('Open'))));
|
|
|
|
// the class's own constraints
|
|
body.append(this.sectionHead(t('Class constraints'), () => this.pickConstraint('', true)));
|
|
body.append(this.chips('', m.constraints, m.suggestions.filter((s) => s.member === ''), m.mapped.filter((c) => c.member === '')));
|
|
|
|
body.append(this.sectionHead(t('Properties')));
|
|
for (const member of m.members) {
|
|
if (member.column?.id && !member.constraints.length) continue;
|
|
const box = el('div.sx-member', {}, el('div.sx-member-head', {},
|
|
el('b', { onclick: () => this.app.editors.open(m.path, { line: member.line }), style: { cursor: 'pointer' } }, member.kind === 'getter' ? member.name + '()' : '$' + member.name),
|
|
el('span.sx-type', {}, member.type || ''),
|
|
member.kind === 'getter' ? el('span.sx-badge', {}, t('getter')) : member.kind === 'param' ? el('span.sx-badge', {}, t('constructor')) : null,
|
|
member.column ? el('span.sx-badge', { title: JSON.stringify(member.column) }, 'ORM') : null,
|
|
el('span.sx-grow'),
|
|
el('button.sx-icon', { title: t('Add a constraint'), onclick: () => this.pickConstraint(member.id, false) }, icon('plus'))));
|
|
box.append(this.chips(member.id, member.constraints, m.suggestions.filter((s) => s.member === member.id), m.mapped.filter((c) => c.member === member.id)));
|
|
body.append(box);
|
|
}
|
|
|
|
// groups and the sequence
|
|
body.append(this.sectionHead(t('Validation groups')));
|
|
body.append(el('div.sx-chips', {}, ...m.groups.map((g) => el('span.sx-badge', {}, g))));
|
|
body.append(this.sequenceEditor());
|
|
|
|
body.append(this.sectionHead(t('Test a value')));
|
|
body.append(this.testBox());
|
|
}
|
|
|
|
sectionHead(text, add) {
|
|
return el('div.sx-section', {}, text, el('span.sx-grow'), add ? el('button.sx-icon', { title: t('Add a constraint'), onclick: add }, icon('plus')) : null);
|
|
}
|
|
|
|
chips(member, constraints, suggestions, mapped) {
|
|
const box = el('div.sx-chips');
|
|
constraints.forEach((c, i) => {
|
|
const [name, opts] = summary(c);
|
|
box.append(el('span.sx-chip', { title: c.text },
|
|
el('span', { onclick: () => this.editConstraint(member, i, c) }, el('b', {}, name), opts ? el('i', {}, `(${opts})`) : null),
|
|
i > 0 ? el('button', { title: t('Move up'), onclick: () => this.edit({ member, action: 'up', index: i }) }, icon('collapse')) : null,
|
|
el('button', { title: t('Remove'), onclick: () => this.edit({ member, action: 'remove', index: i }) }, icon('close'))));
|
|
});
|
|
for (const c of mapped) {
|
|
const [name, opts] = summary(c);
|
|
box.append(el('span.sx-chip.mapped', { title: `${c.file}:${c.line} (${t('read-only')})` },
|
|
el('span', { onclick: () => this.app.editors.open(c.file, { line: c.line }) }, el('b', {}, name), opts ? el('i', {}, `(${opts})`) : null, ' ', el('span.sx-badge', {}, c.format))));
|
|
}
|
|
for (const s of suggestions) {
|
|
const [name, opts] = summary(s.constraint);
|
|
box.append(el('span.sx-chip.suggest', { title: t('Suggested by the Doctrine mapping ({reason})', { reason: s.reason }), onclick: () => this.edit({ member, action: 'add', constraint: s.constraint }) },
|
|
icon('plus'), `${name}${opts ? `(${opts})` : ''}`));
|
|
}
|
|
if (!constraints.length && !mapped.length && !suggestions.length) box.append(el('span.sx-muted', {}, t('No constraint')));
|
|
return box;
|
|
}
|
|
|
|
/** the catalogue as a chooser: Symfony's constraints by family, then the project's own */
|
|
pickConstraint(member, forClass, onPick) {
|
|
const items = [];
|
|
for (const c of this.catalog) if (forClass ? c.class : c.property) items.push({ label: `Assert\\${c.name}`, hint: family(c.family), action: () => (onPick ? onPick(c.name) : this.editConstraint(member, -1, { name: c.name, options: {} })) });
|
|
for (const c of this.custom) items.push({ label: c.fqn, hint: family('Custom'), action: () => {
|
|
const constraint = { name: c.fqn, fqn: c.fqn, options: {} };
|
|
if (onPick) onPick(c.fqn); else this.editConstraint(member, -1, constraint);
|
|
} });
|
|
chooser(items, { placeholder: t('Constraint (NotBlank, Length, Email…)') });
|
|
}
|
|
|
|
/** the dialog of one constraint's options; index -1: a new one */
|
|
editConstraint(member, index, constraint) {
|
|
this.optionsDialog(constraint, (c) => this.edit(index < 0 ? { member, action: 'add', constraint: c } : { member, action: 'update', index, constraint: c }));
|
|
}
|
|
|
|
optionsDialog(constraint, done) {
|
|
const desc = this.describe(constraint.name);
|
|
const values = structuredClone(constraint.options || {});
|
|
const form = el('div.sx-form');
|
|
const known = new Set(desc.options.map((o) => o.name));
|
|
const options = [...desc.options, ...Object.keys(values).filter((k) => !known.has(k)).map((k) => ({ name: k, kind: 'value' }))];
|
|
for (const o of options) form.append(...this.optionField(o, values));
|
|
dialog({
|
|
title: `${constraint.name.split('\\').pop()} — ${family(desc.family)}`,
|
|
body: el('div', {}, el('p.sx-muted', {}, t('Empty fields keep Symfony\'s defaults.')), form),
|
|
buttons: [{ label: 'Cancel' }, { label: 'OK', primary: true, action: () => {
|
|
const clean = {};
|
|
for (const [k, v] of Object.entries(values)) if (v !== undefined && v !== '' && !(Array.isArray(v) && !v.length)) clean[k] = v;
|
|
done({ name: constraint.name, fqn: constraint.fqn, options: clean });
|
|
} }],
|
|
});
|
|
}
|
|
|
|
/** a label and a field for one option, by its kind; it writes into values[name] */
|
|
optionField(o, values) {
|
|
const v = values[o.name];
|
|
const label = el('label', { title: o.name }, o.name);
|
|
const set = (x) => { if (x === undefined) delete values[o.name]; else values[o.name] = x; };
|
|
if (v && typeof v === 'object' && !Array.isArray(v) && '@raw' in v) {
|
|
return [label, el('input.input', { value: v['@raw'], title: t('PHP code'), oninput: (e) => set(e.target.value.trim() ? { '@raw': e.target.value } : undefined) })];
|
|
}
|
|
switch (o.kind) {
|
|
case 'bool': {
|
|
const s = el('select.input', { onchange: (e) => set(e.target.value === '' ? undefined : e.target.value === 'true') },
|
|
el('option', { value: '' }, t('(default)')), el('option', { value: 'true', selected: v === true }, 'true'), el('option', { value: 'false', selected: v === false }, 'false'));
|
|
return [label, s];
|
|
}
|
|
case 'int': case 'number':
|
|
return [label, el('input.input', { type: 'number', value: v ?? '', step: o.kind === 'int' ? 1 : 'any', oninput: (e) => set(e.target.value === '' ? undefined : Number(e.target.value)) })];
|
|
case 'choice': {
|
|
const s = el('select.input', { onchange: (e) => set(e.target.value === '' ? undefined : (/^\d+$/.test(e.target.value) && typeof v !== 'string' && o.name === 'minScore' ? Number(e.target.value) : e.target.value)) },
|
|
el('option', { value: '' }, t('(default)')), ...o.choices.map((c) => el('option', { value: c, selected: String(v) === c }, c)));
|
|
return [label, s];
|
|
}
|
|
case 'list': {
|
|
const input = el('input.input', { value: Array.isArray(v) ? v.join(', ') : valueText(v), placeholder: 'a, b, c',
|
|
oninput: (e) => set(e.target.value.trim() === '' ? undefined : e.target.value.split(',').map((x) => x.trim()).filter(Boolean)) });
|
|
return [label, input];
|
|
}
|
|
case 'message':
|
|
return [label, el('textarea.input', { value: v ?? '', rows: 2, placeholder: '{{ value }}, {{ limit }}…', oninput: (e) => set(e.target.value === '' ? undefined : e.target.value) })];
|
|
case 'regex': {
|
|
const input = el('input.input', { value: v ?? '', placeholder: '/^[a-z0-9-]+$/', oninput: (e) => { set(e.target.value || undefined); input.classList.toggle('bad', !!e.target.value && !validRegex(e.target.value)); } });
|
|
input.classList.toggle('bad', !!v && !validRegex(v));
|
|
return [label, input];
|
|
}
|
|
case 'constraints': return [el('label.sx-full', {}, o.name), this.nestedList(o.name, values)];
|
|
case 'fields': return [el('label.sx-full', {}, o.name), this.fieldsEditor(o.name, values)];
|
|
case 'value':
|
|
return [label, el('input.input', { value: valueText(v), placeholder: '12, true, "text", [1, 2]', oninput: (e) => set(parseValue(e.target.value)) })];
|
|
default:
|
|
if (TEXT_KINDS.includes(o.kind)) return [label, el('input.input', { value: v ?? '', oninput: (e) => set(e.target.value === '' ? undefined : e.target.value) })];
|
|
return [label, el('input.input', { value: valueText(v), oninput: (e) => set(parseValue(e.target.value)) })];
|
|
}
|
|
}
|
|
|
|
/** nested constraints (All, Sequentially, When, AtLeastOneOf): a list of chips, each edited by its own dialog */
|
|
nestedList(name, values) {
|
|
const box = el('div.sx-nested.sx-full');
|
|
const draw = () => {
|
|
clear(box);
|
|
const list = Array.isArray(values[name]) ? values[name] : values[name] ? [values[name]] : [];
|
|
const chips = el('div.sx-chips');
|
|
list.forEach((item, i) => {
|
|
const c = item['@constraint'];
|
|
if (!c) { chips.append(el('span.sx-chip', {}, el('span', {}, valueText(item)))); return; }
|
|
const [n, opts] = summary(c);
|
|
chips.append(el('span.sx-chip', {},
|
|
el('span', { onclick: () => this.optionsDialog(c, (nc) => { list[i] = { '@constraint': nc }; values[name] = list; draw(); }) }, el('b', {}, n), opts ? el('i', {}, `(${opts})`) : null),
|
|
el('button', { title: t('Remove'), onclick: () => { list.splice(i, 1); values[name] = list; draw(); } }, icon('close'))));
|
|
});
|
|
chips.append(el('button.btn.small', { onclick: () => this.pickConstraint('', false, (cn) => this.optionsDialog({ name: cn, fqn: cn.includes('\\') ? cn : undefined, options: {} }, (nc) => { list.push({ '@constraint': nc }); values[name] = list; draw(); })) }, icon('plus'), t('Add')));
|
|
box.append(chips);
|
|
};
|
|
draw();
|
|
return box;
|
|
}
|
|
|
|
/** Collection's fields: a name and its constraints for each */
|
|
fieldsEditor(name, values) {
|
|
const box = el('div.sx-nested.sx-full');
|
|
const draw = () => {
|
|
clear(box);
|
|
const fields = values[name] && typeof values[name] === 'object' && !Array.isArray(values[name]) ? values[name] : {};
|
|
for (const [field, cs] of Object.entries(fields)) {
|
|
const holder = { list: Array.isArray(cs) ? cs : [cs] };
|
|
const row = el('div.sx-row', {}, el('b', { style: { fontFamily: 'var(--mono)' } }, field), this.nestedList('list', new Proxy(holder, { set: (h, k, val) => { h[k] = val; fields[field] = val; values[name] = fields; return true; } })),
|
|
el('button.sx-icon', { title: t('Remove'), onclick: () => { delete fields[field]; values[name] = fields; draw(); } }, icon('close')));
|
|
box.append(row);
|
|
}
|
|
const input = el('input.input', { placeholder: t('field name') });
|
|
box.append(el('div.sx-row', {}, input, el('button.btn.small', { onclick: () => { const f = input.value.trim(); if (!f) return; fields[f] = []; values[name] = fields; draw(); } }, icon('plus'), t('Add a field'))));
|
|
};
|
|
draw();
|
|
return box;
|
|
}
|
|
|
|
async edit(p) {
|
|
try {
|
|
const r = await backend.invoke('validation.edit', { path: this.path, ...p });
|
|
if (await reviewChanges(this.app, r.files, { title: t('Constraints of {class}', { class: this.model.short }) })) await this.read();
|
|
} catch (e) { notify(e.message, 'error', { title: t('Validation') }); }
|
|
}
|
|
|
|
sequenceEditor() {
|
|
const m = this.model;
|
|
const index = m.constraints.findIndex((c) => c.name === 'GroupSequence');
|
|
const groups = [...(m.sequence || [])];
|
|
const box = el('div.sx-test');
|
|
const list = el('div.sx-chips');
|
|
const draw = () => {
|
|
clear(list);
|
|
groups.forEach((g, i) => list.append(el('span.sx-chip', {}, el('span', {}, el('b', {}, `${i + 1}. ${g}`)),
|
|
i > 0 ? el('button', { title: t('Move up'), onclick: () => { [groups[i - 1], groups[i]] = [groups[i], groups[i - 1]]; draw(); } }, icon('collapse')) : null,
|
|
el('button', { title: t('Remove'), onclick: () => { groups.splice(i, 1); draw(); } }, icon('close')))));
|
|
if (!groups.length) list.append(el('span.sx-muted', {}, t('No group sequence: all the groups are validated together.')));
|
|
};
|
|
draw();
|
|
const add = el('select.input', {}, el('option', { value: '' }, t('Add a group…')), ...m.groups.map((g) => el('option', { value: g }, g)));
|
|
add.onchange = () => { if (add.value && !groups.includes(add.value)) groups.push(add.value); add.value = ''; draw(); };
|
|
const free = el('input.input', { placeholder: t('new group') });
|
|
box.append(el('div', { style: { marginBottom: '4px' } }, el('b', {}, 'GroupSequence'), ' ', el('span.sx-muted', {}, t('Groups validated in order: the next one only when the previous one has no violation.'))),
|
|
list, el('div.sx-row', {}, add, free, el('button.btn.small', { onclick: () => { const g = free.value.trim(); if (g && !groups.includes(g)) groups.push(g); free.value = ''; draw(); } }, icon('plus')),
|
|
el('button.btn.small.primary', { onclick: () => {
|
|
if (!groups.length) { if (index >= 0) this.edit({ member: '', action: 'remove', index }); return; }
|
|
const c = { name: 'GroupSequence', options: { groups } };
|
|
this.edit(index >= 0 ? { member: '', action: 'update', index, constraint: c } : { member: '', action: 'add', constraint: c });
|
|
} }, t('Save the sequence'))));
|
|
return box;
|
|
}
|
|
|
|
/** "Test a value": one property's value, or the whole object from sample values, validated by the project's validator */
|
|
testBox() {
|
|
const m = this.model;
|
|
const s = this.test;
|
|
const box = el('div.sx-test');
|
|
const members = m.members.filter((x) => x.kind !== 'getter');
|
|
const target = el('select.input', { onchange: (e) => { s.member = e.target.value; this.render(); } },
|
|
el('option', { value: '' }, t('The whole object')), ...members.map((x) => el('option', { value: x.name, selected: s.member === x.name }, '$' + x.name)));
|
|
box.append(el('div.sx-row', {}, target));
|
|
if (s.member) {
|
|
box.append(el('div.sx-row', {}, el('input.input', { value: s.value, placeholder: t('A value (text, 12, true, ["a"]…)'), oninput: (e) => { s.value = e.target.value; } })));
|
|
} else {
|
|
const form = el('div.sx-form');
|
|
for (const x of members) {
|
|
form.append(el('label', {}, '$' + x.name), el('input.input', { value: s.values[x.name] ?? '', placeholder: x.type, oninput: (e) => { s.values[x.name] = e.target.value; } }));
|
|
}
|
|
box.append(form);
|
|
}
|
|
const groups = el('div.sx-chips', {}, el('span.sx-muted', {}, t('Groups:')), ...m.groups.map((g) => el('label', { style: { display: 'inline-flex', gap: '3px', alignItems: 'center' } },
|
|
el('input', { type: 'checkbox', checked: s.groups.includes(g), onchange: (e) => { s.groups = e.target.checked ? [...s.groups, g] : s.groups.filter((x) => x !== g); } }), g)));
|
|
box.append(groups);
|
|
const run = el('button.btn.small.primary', { disabled: s.busy, onclick: () => this.runTest() }, icon('play'), s.busy ? t('Validating…') : t('Validate'));
|
|
box.append(el('div.sx-row', { style: { marginTop: '6px' } }, run, el('span.sx-muted', {}, this.app.project.capabilities?.console ? t('Runs bin/console where the Console window runs it.') : t('This project has no bin/console.'))));
|
|
const r = s.result;
|
|
if (r?.error) box.append(el('pre.sx-pre', {}, r.error));
|
|
else if (r?.violations?.length) for (const v of r.violations) box.append(el('div.sx-violation', {}, el('code', {}, v.path || (s.member ? '$' + s.member : '(object)')), ' ', v.message, v.constraint ? el('span.sx-muted', {}, ` — ${v.constraint}`) : null));
|
|
else if (r?.violations) box.append(el('div.sx-ok', {}, t('Valid: no violation.')));
|
|
return box;
|
|
}
|
|
|
|
async runTest() {
|
|
const s = this.test;
|
|
const m = this.model;
|
|
const p = { class: m.class, groups: s.groups };
|
|
if (s.member) { p.property = s.member; p.value = parseValue(s.value) ?? ''; }
|
|
else { p.values = {}; for (const [k, v] of Object.entries(s.values)) if (v !== '') p.values[k] = parseValue(v); }
|
|
s.busy = true; s.result = null; this.render();
|
|
try {
|
|
let r = await backend.invoke('validation.test', p);
|
|
if (r.missing) {
|
|
const h = await backend.invoke('validation.helper', {});
|
|
if (await reviewChanges(this.app, h.files, { title: t('A dev-only command validates the sample (jumphp:validate)') })) r = await backend.invoke('validation.test', p);
|
|
else r = null;
|
|
}
|
|
s.result = r;
|
|
} catch (e) { s.result = { error: e.message }; }
|
|
s.busy = false;
|
|
this.render();
|
|
}
|
|
|
|
/** the custom constraint wizard */
|
|
newConstraint() {
|
|
const spec = { name: '', namespace: 'App\\Validator', message: 'The value "{{ value }}" is not valid.', target: 'property', options: [], compound: false, constraints: [] };
|
|
const form = el('div.sx-form');
|
|
const draw = () => {
|
|
clear(form);
|
|
form.append(el('label', {}, t('Name')), el('input.input', { value: spec.name, placeholder: 'Slug', oninput: (e) => { spec.name = e.target.value.trim(); } }),
|
|
el('label', {}, t('Namespace')), el('input.input', { value: spec.namespace, oninput: (e) => { spec.namespace = e.target.value.trim(); } }),
|
|
el('label', {}, t('Kind')), el('select.input', { onchange: (e) => { spec.compound = e.target.value === 'compound'; draw(); } },
|
|
el('option', { value: 'validator' }, t('Constraint + validator')), el('option', { value: 'compound', selected: spec.compound }, t('Compound (several constraints under one name)'))));
|
|
if (spec.compound) {
|
|
const holder = { list: spec.constraints.map((c) => ({ '@constraint': c })) };
|
|
form.append(el('label.sx-full', {}, t('Constraints')), this.nestedList('list', new Proxy(holder, { set: (h, k, v) => { h[k] = v; spec.constraints = v.map((x) => x['@constraint']); return true; } })));
|
|
return;
|
|
}
|
|
form.append(el('label', {}, t('Target')), el('select.input', { onchange: (e) => { spec.target = e.target.value; } },
|
|
...[['property', t('A property or a getter')], ['class', t('The class')], ['both', t('Both')]].map(([v, l]) => el('option', { value: v, selected: spec.target === v }, l))),
|
|
el('label', {}, 'message'), el('textarea.input', { value: spec.message, rows: 2, oninput: (e) => { spec.message = e.target.value; } }),
|
|
el('label.sx-full', {}, t('Options')));
|
|
spec.options.forEach((o, i) => form.append(el('div.sx-row.sx-full', {},
|
|
el('input.input', { value: o.name, placeholder: 'mode', oninput: (e) => { o.name = e.target.value.trim(); } }),
|
|
el('select.input', { onchange: (e) => { o.type = e.target.value; } }, ...['string', 'int', 'float', 'bool', 'array'].map((x) => el('option', { selected: o.type === x }, x))),
|
|
el('input.input', { value: o.default ?? '', placeholder: t('default'), oninput: (e) => { o.default = e.target.value; } }),
|
|
el('button.sx-icon', { onclick: () => { spec.options.splice(i, 1); draw(); } }, icon('close')))));
|
|
form.append(el('div.sx-full', {}, el('button.btn.small', { onclick: () => { spec.options.push({ name: '', type: 'string', default: '' }); draw(); } }, icon('plus'), t('Add an option'))));
|
|
};
|
|
draw();
|
|
dialog({
|
|
title: t('New constraint'),
|
|
body: form,
|
|
buttons: [{ label: 'Cancel' }, { label: t('Preview'), primary: true, action: async () => {
|
|
const r = await backend.invoke('validation.newConstraint', { spec });
|
|
if (await reviewChanges(this.app, r.files, { title: t('New constraint') })) await this.load();
|
|
} }],
|
|
});
|
|
}
|
|
}
|
|
|
|
function validRegex(text) {
|
|
const m = /^(.)(.*)\1([a-zA-Z]*)$/s.exec(text);
|
|
if (!m) return false;
|
|
try { new RegExp(m[2], m[3].replace(/[^gimsuy]/g, '')); return true; } catch { return false; }
|
|
}
|