/
ActionRunner.php
399 lines (334 loc) · 10.4 KB
/
ActionRunner.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
<?php
namespace ActionKit;
use Exception;
use IteratorAggregate;
use ArrayAccess;
use ActionKit\Utils;
/**
* Run actions!
*
*
* full-qualified action name in web form:
* Yasumi::Action::Login
* Phifty::Action::Login
* names like "Login", "Signup" should refer to
* {App}::Action::Login or
* {App}::Action::Signup
*
* $runner = ActionKit\ActionRunner::getInstance();
* $result = $runner->run();
* if ($result) {
* if ( $runner->isAjax() ) {
* echo $result;
* }
* }
*
* Iterator support:
*
* foreach ($runner as $name => $result) {
*
* }
*
*/
class ActionRunner
implements IteratorAggregate, ArrayAccess
{
public $cacheDir;
/**
* @var array
* @DEPRECATED
*/
protected $dynamicActions = array();
/**
* @var array The new action class generator pool
*/
protected $dynamicActionsNew = array();
/**
* @var array Abstract CRUD action pool
* @DEPRECATED
*/
public $crudActions = array();
/**
* @var array Result pool
*/
public $results = array();
public $generator;
public function __construct($options = array()) {
if ( isset($options['cache_dir']) ) {
$this->cacheDir = $options['cache_dir'];
} else {
$this->cacheDir = __DIR__ . DIRECTORY_SEPARATOR . 'Cache';
if ( ! file_exists($this->cacheDir) ) {
mkdir($this->cacheDir, 0755, true);
}
}
$this->generator = new ActionGenerator(array( 'cache' => true , 'cache_dir' => $this->cacheDir ));
}
/**
* Check if action request, then dispatch the action class.
*
*
* @param string $actionName
* @param array $arguments
* @return ActionKit\Result result array if there is such an action.
* */
public function run($actionName, $arguments = array() )
{
if ( ! Utils::validateActionName( $actionName ) ) {
throw new Exception( "Invalid action name: $actionName." );
}
/* translate :: into php namespace */
$class = Utils::toActionClass($actionName);
/* register results into hash */
if ( $action = $this->createAction( $class , $arguments ) ) {
$action->invoke();
return $this->results[ $actionName ] = $action->getResult();
}
throw new Exception( "Can not create action class $class" );
}
public function loadClass($class)
{
if ( isset($this->dynamicActionsNew[$class]) ) {
$actionArgs = $this->dynamicActionsNew[ $class ];
$cacheFile = $this->getClassCacheFile($class, $actionArgs);
$loader = $this->generator->getTwigLoader();
// filemtime($cacheFile)
if ( ! file_exists($cacheFile) ) {
$template = $this->generator->generate2($class, $actionArgs);
if ( false === $template->writeTo($cacheFile) ) {
throw new Exception("Can not write action class cache file: $cacheFile");
}
}
require $cacheFile;
return true;
}
if ( isset( $this->dynamicActions[ $class ] ) ) {
$actionArgs = $this->dynamicActions[ $class ];
$cacheFile = $this->getClassCacheFile($class);
$loader = $this->generator->getTwigLoader();
if ( ! file_exists($cacheFile) || ! $loader->isFresh($actionArgs['template'], filemtime($cacheFile) ) ) {
$code = $this->generator->generate($class, $actionArgs['template'], $actionArgs['variables']);
if ( false === file_put_contents($cacheFile, $code) ) {
throw new Exception("Can not write action class cache file: $cacheFile");
}
}
require $cacheFile;
return true;
}
// DEPRECATED: backward compatible code
if ( isset( $this->crudActions[$class] ) ) {
// \FB::info('Generate action class: ' . $class);
// Generate the crud action
//
// @see registerRecordAction method
$args = $this->crudActions[$class];
$template = $this->generator->generateRecordActionNs( $args['ns'] , $args['model_name'], $args['type'] );
return $this->loadClassTemplate($class, $template);
}
}
public function registerAutoloader()
{
// use throw and not to prepend
spl_autoload_register(array($this,'loadClass'),true, false);
}
/**
* Register dynamic action by template.
*
* XXX: deprecated
*
* @param string $targetActionClass target action class name, full-qualified.
* @param string $templateName source template
* @param array $variables template variables.
*/
public function registerAction($targetActionClass, $templateName, $variables = array() )
{
$this->dynamicActions[ $targetActionClass ] = array(
'template' => $templateName,
'variables' => $variables,
);
}
/**
* $this->register('App\Action\SortProductType',[
* 'extends' => '....',
* 'properties' => [ 'recordClass' => .... ]
* ]);
*/
public function register($targetActionClass, $options = array() ) {
$this->dynamicActionsNew[ $targetActionClass ] = $options;
}
/**
* Add CRUD action class to pool, so we can generate these class later
* if needed. (lazy)
*
* - registerRecordAction( 'News' , 'News' , array('Create','Update') );
*
* Which generates:
*
* News\Action\CreateNews
* News\Action\UpdateNews
*
* @param string $ns namespace name
* @param string $modelName model name
* @param array $types action types
*/
public function registerRecordAction( $ns , $modelName , $types )
{
foreach ( (array) $types as $type ) {
$class = $ns . '\\Action\\' . $type . $modelName;
$this->register( $class , [
'extends' => "\\ActionKit\\RecordAction\\{$type}RecordAction",
'properties' => [
'recordClass' => "$ns\\Model\\$modelName",
],
]);
$this->crudActions[$class] = array(
'ns' => $ns,
'type' => $type,
'model_name' => $modelName,
);
}
}
public function registerCRUD( $ns , $modelName , $types )
{
$this->registerRecordAction( $ns, $modelName, $types );
}
public function isInvalidActionName( $actionName )
{
return preg_match( '/[^A-Za-z0-9:]/i' , $actionName );
}
public function isFullQualifiedName( $actionName )
{
return strpos( $actionName, '::' ) != -1;
}
public function isAjax()
{
return isset($_REQUEST['__ajax_request']);
}
/**
* Convert action signature into the actual full-qualified class name.
*
* This method replaces "::" charactors with "\" from action signature string.
*
* @param string $actionName
*/
public function getActionClass( $actionName )
{
// replace :: with '\'
return str_replace( '::' , '\\' , $actionName );
}
/**
* Return the cache path of the class name
*
* @param string $className
* @return string path
*/
public function getClassCacheFile($className, $params = array())
{
$chk = empty($params) ? '' : md5(serialize($params));
return $this->cacheDir . DIRECTORY_SEPARATOR . str_replace('\\','_',$className) . $chk . '.php';
}
/**
*
* @param string $className
* @param ClassTemplate the class template object
*/
public function loadClassTemplate($className, $template)
{
$cacheFile = $this->getClassCacheFile($className);
if ( file_exists($cacheFile) ) {
require $cacheFile;
return true;
}
// generate cache file
$template->writeTo($cacheFile);
return require $cacheFile;
}
/**
* Create action object
*
* @param string $class
*/
public function createAction( $class , $args = array() )
{
$args = array_merge( $_REQUEST , $args );
if ( isset($args['__ajax_request']) ) {
unset( $args['__ajax_request'] );
}
if ( isset($args['action']) ) {
unset( $args['action'] );
}
if ( class_exists($class, true) ) {
return new $class( $args );
}
$this->loadClass($class);
// call spl to autoload the class
if ( ! class_exists($class,true) ) {
throw new Exception( "Action class not found: $class, you might need to setup action autoloader" );
}
return new $class( $args );
}
/**
* Get all results
*
* @return ActionKit\Result[]
*/
public function getResults()
{
return $this->results;
}
/**
* Get Action result by action name
*
* @param string $name action name (format: App::Action::ActionName)
*/
public function getResult( $name )
{
return isset($this->results[ $name ]) ?
$this->results[ $name ] : null;
}
/**
* Check if we have action result
*
* @param string $name Action name
*/
public function hasResult($name)
{
return isset($this->results[$name]);
}
public function setResult($name, $result) {
$this->results[$name] = $result;
}
public function removeResult($name)
{
unset( $this->results[$name] );
}
public static function getInstance()
{
static $self;
if ( $self )
return $self;
return $self = new static;
}
// Implement IteratorAggregate methods
public function getIterator()
{
return new ArrayIterator($this->results);
}
// Implement ArrayAccess
public function offsetSet($name,$value)
{
$this->results[ $name ] = $value;
}
public function offsetExists($name)
{
return isset($this->results[ $name ]);
}
public function offsetGet($name)
{
return $this->results[ $name ];
}
public function offsetUnset($name)
{
unset( $this->results[$name] );
}
}