/
ModalController.php
98 lines (83 loc) · 2.73 KB
/
ModalController.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace SilverStripe\LinkField\Extensions;
use InvalidArgumentException;
use SilverStripe\Admin\ModalController as OwnerController;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Core\Extension;
use SilverStripe\Forms\Form;
use SilverStripe\LinkField\Form\FormFactory;
use SilverStripe\LinkField\Type\Registry;
/**
* Extensions to apply to ModalController so it knows how to handle the DynamicLink action.
*
* This action receive a link type key and some link data as a JSON string and retrieve a Form Schema for a
* specific Link Type.
*/
class ModalController extends Extension
{
private static $url_handlers = [
'editorAnchorLink/$ItemID' => 'editorAnchorLink', // Matches LeftAndMain::methodSchema args
];
private static $allowed_actions = [
'DynamicLink',
];
/**
* Builds and returns the external link form
*
* @return Form
*/
public function DynamicLink()
{
// Show link text field if requested
$linkDataJsonStr = $this->getOwner()->controller->getRequest()->getVar('data');
/** @var OwnerController $owner */
$owner = $this->getOwner();
$factory = FormFactory::singleton();
$data = $this->getData();
return $factory->getForm(
$owner->getController(),
"{$owner->getName()}/DynamicLink",
$this->getContext()
)->loadDataFrom($data);
}
/**
* Build the context to pass to the Form Link Factory
* @return array
* @throws HTTPResponse_Exception
*/
private function getContext(): array
{
$linkTypeKey = $this->getOwner()->controller->getRequest()->getVar('key');
if (empty($linkTypeKey)) {
throw new HTTPResponse_Exception(sprintf('key is required', __CLASS__), 400);
}
$type = Registry::singleton()->byKey($linkTypeKey);
if (empty($type)) {
throw new HTTPResponse_Exception(sprintf('%s is not a valid link type', 400));
}
return [
'LinkData' => $this->getData(),
'LinkType' => $type,
'LinkTypeKey' => $linkTypeKey,
'RequireLinkText' => false
];
}
/**
* Extract the Link Data out of the Request.
* @return array
*/
private function getData(): array
{
$data = [];
$dataString = $this->getOwner()->controller->getRequest()->getVar('data');
if ($dataString) {
$parsedData = json_decode($dataString, true);
if (json_last_error() === JSON_ERROR_NONE) {
$data = $parsedData;
} else {
throw new InvalidArgumentException(json_last_error_msg());
}
}
return $data;
}
}