Repository navigation
Expand file tree
/
Copy pathJsFunction.php
More file actions
99 lines (77 loc) · 2.52 KB
/
Copy pathJsFunction.php
File metadata and controls
99 lines (77 loc) · 2.52 KB
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
99
<?php
declare(strict_types=1);
namespace Atk4\Ui;
use Atk4\Core\WarnDynamicPropertyTrait;
/**
* Implements structure for js closure.
*/
class JsFunction implements JsExpressionable
{
use WarnDynamicPropertyTrait;
/** @var array */
public $fx_args;
/** @var array */
public $fx_statements = [];
/** @var bool add preventDefault(event) to generated method */
public $preventDefault = false;
/** @var bool add stopPropagation(event) to generated method */
public $stopPropagation = false;
/** @var string */
public $indent = ' ';
/**
* @param array $args
* @param array $statements
*/
public function __construct($args = [], $statements = null)
{
if ($statements === null) {
$statements = $args;
$args = [];
}
$this->fx_args = $args ?: [];
if (!is_array($statements)) {
throw (new Exception('$statements is not array'))
->addMoreInfo('statements', $statements);
}
foreach ($statements as $key => $value) {
if (is_numeric($key)) {
$this->fx_statements[] = $value;
} else {
$this->{$key} = $value;
}
}
}
public function jsRender(): string
{
$pre = '';
if ($this->preventDefault) {
$this->fx_args = ['event'];
$pre .= "\n" . $this->indent . ' event.preventDefault();';
}
if ($this->stopPropagation) {
$this->fx_args = ['event'];
$pre .= "\n" . $this->indent . ' event.stopPropagation();';
}
$output = 'function(' . implode(',', $this->fx_args) . ') {';
$output .= $pre;
foreach ($this->fx_statements as $statement) {
if (!$statement) {
// null passed
continue;
}
if ($statement instanceof JsChain && !$statement->_chain) {
// chain contains no statements, so probably is useless
continue;
}
if ($statement instanceof JsExpressionable) {
$statement = $statement->jsRender();
} else {
throw (new Exception('Incorrect statement for JsFunction.'))
->addMoreInfo('statement', $statement);
}
$output .= "\n" . $this->indent . ' ' . $statement . (!preg_match('~[;}]\s*$~', $statement) ? ';' : '');
}
$output .= "\n" . $this->indent . '}';
return $output;
}
}