-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectTransformer.php
81 lines (74 loc) · 3.1 KB
/
ObjectTransformer.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/*
* This file is part of the W3rOneJsonSchemaBundle.
*
* (c) w3r-one <contact@w3r.one>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace W3rOne\JsonSchemaBundle\Transformer;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use W3rOne\JsonSchemaBundle\Utils;
class ObjectTransformer extends AbstractTransformer
{
public function transform(FormInterface $form): array
{
// nested compound object or prototype
if (null !== $form->getParent() || '__name__' === $form->getName()) {
$schema = parent::transform($form);
$schema['properties'] = [];
$schema['type'] = 'object';
}
// base json schema
else {
if (null !== ($request = $this->requestStack->getCurrentRequest())) {
$hostName = $request->getSchemeAndHttpHost();
if (empty($action = $form->getConfig()->getOption('action'))) {
$action = $request->getUri();
}
elseif (0 === strpos(strtolower(trim($action)), 'http')) {
$action = $request->getUriForPath($action);
}
}
else {
$hostName = $action = 'http://localhost';
}
$widget = Utils::getWidget($form);
$schema = [
'$schema' => 'https://json-schema.org/draft/2020-12/schema',
# TODO: perhaps find a way to use more specific $id for caching purpose
'$id' => $hostName . '/schemas/' . $form->getName() . '.json',
'type' => 'object',
'title' => $form->getName(),
'properties' => [],
# TODO: try to guess required props
'required' => [],
'options' => [
'widget' => !empty($widget) ? $widget : 'object',
'layout' => $form->getConfig()->getOption('w3r_one_json_schema')['layout'] ?? $this->resolver->getDefaultLayout(),
'form' => [
'method' => $form->getConfig()->getOption('method', Request::METHOD_POST),
'action' => $action,
'async' => $form->getConfig()->getOption('w3r_one_json_schema')['xmlHttpRequest'] ?? true,
],
],
];
// add csrf field if needed
if (true === $form->getConfig()->getOption('csrf_protection')) {
$schema['properties'][$form->getConfig()->getOption('csrf_field_name', '_token')] = [
'type' => 'string',
'title' => '',
'writeOnly' => true,
'default' => $this->csrfTokenManager->getToken($form->getName())->getValue(),
'options' => [
'widget' => 'hidden',
'layout' => $this->resolver->getDefaultLayout(),
],
];
}
}
return $schema;
}
}