dfeyer

Untitled

Oct 10th, 2012
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.40 KB | None | 0 0
  1. /**
  2. * An HTTP based multi-action controller.
  3. *
  4. * The action specified in the given ActionRequest is dispatched to a method in
  5. * the concrete controller whose name ends with "*Action". If no matching action
  6. * method is found, the action specified in $errorMethodName is invoked.
  7. *
  8. * This controller also takes care of mapping arguments found in the ActionRequest
  9. * to the corresponding method arguments of the action method. It also invokes
  10. * validation for these arguments by invoking the Property Mapper.
  11. *
  12. * By defining media types in $supportedMediaTypes, content negotiation based on
  13. * the browser's Accept header and additional routing configuration is used to
  14. * determine the output format the controller should return.
  15. *
  16. * Depending on the action being called, a fitting view - by default a Fluid template
  17. * view - will be selected. By specifying patterns, custom view classes or an alternative
  18. * controller / action to template path mapping can be defined.
  19. *
  20. * @FLOW3\Scope("singleton")
  21. * @api
  22. */
  23. class ActionController_Original extends AbstractController {
  24.  
  25. /**
  26. * @FLOW3\Inject
  27. * @var \TYPO3\FLOW3\Object\ObjectManagerInterface
  28. */
  29. protected $objectManager;
  30.  
  31. /**
  32. * @FLOW3\Inject
  33. * @var \TYPO3\FLOW3\Reflection\ReflectionService
  34. */
  35. protected $reflectionService;
  36.  
  37. /**
  38. * @FLOW3\Inject
  39. * @var \TYPO3\FLOW3\Mvc\Controller\MvcPropertyMappingConfigurationService
  40. */
  41. protected $mvcPropertyMappingConfigurationService;
  42.  
  43. /**
  44. * The current view, as resolved by resolveView()
  45. *
  46. * @var \TYPO3\FLOW3\Mvc\View\ViewInterface
  47. * @api
  48. */
  49. protected $view = NULL;
  50.  
  51. /**
  52. * Pattern after which the view object name is built if no format-specific
  53. * view could be resolved.
  54. *
  55. * @var string
  56. * @api
  57. */
  58. protected $viewObjectNamePattern = '@package\View\@controller\@action@format';
  59.  
  60. /**
  61. * A list of formats and object names of the views which should render them.
  62. *
  63. * Example:
  64. *
  65. * array('html' => 'MyCompany\MyApp\MyHtmlView', 'json' => 'MyCompany\...
  66. *
  67. * @var array
  68. */
  69. protected $viewFormatToObjectNameMap = array();
  70.  
  71. /**
  72. * The default view object to use if none of the resolved views can render
  73. * a response for the current request.
  74. *
  75. * @var string
  76. * @api
  77. */
  78. protected $defaultViewObjectName = 'TYPO3\Fluid\View\TemplateView';
  79.  
  80. /**
  81. * Name of the action method
  82. *
  83. * @var string
  84. */
  85. protected $actionMethodName;
  86.  
  87. /**
  88. * Name of the special error action method which is called in case of errors
  89. *
  90. * @var string
  91. * @api
  92. */
  93. protected $errorMethodName = 'errorAction';
  94.  
  95. /**
  96. * @var array
  97. */
  98. protected $settings;
  99.  
  100. /**
  101. * @param array $settings
  102. * @return void
  103. */
  104. public function injectSettings(array $settings) {
  105. $this->settings = $settings;
  106. }
  107.  
  108. /**
  109. * Handles a request. The result output is returned by altering the given response.
  110. *
  111. * @param \TYPO3\FLOW3\Mvc\RequestInterface $request The request object
  112. * @param \TYPO3\FLOW3\Mvc\ResponseInterface $response The response, modified by this handler
  113. * @return void
  114. * @throws \TYPO3\FLOW3\Mvc\Exception\UnsupportedRequestTypeException
  115. * @api
  116. */
  117. public function processRequest(\TYPO3\FLOW3\Mvc\RequestInterface $request, \TYPO3\FLOW3\Mvc\ResponseInterface $response) {
  118. $this->initializeController($request, $response);
  119.  
  120. $this->actionMethodName = $this->resolveActionMethodName();
  121.  
  122. $this->initializeActionMethodArguments();
  123. $this->initializeActionMethodValidators();
  124. $this->mvcPropertyMappingConfigurationService->initializePropertyMappingConfigurationFromRequest($this->request, $this->arguments);
  125.  
  126. $this->initializeAction();
  127. $actionInitializationMethodName = 'initialize' . ucfirst($this->actionMethodName);
  128. if (method_exists($this, $actionInitializationMethodName)) {
  129. call_user_func(array($this, $actionInitializationMethodName));
  130. }
  131.  
  132. $this->mapRequestArgumentsToControllerArguments();
  133.  
  134. $this->view = $this->resolveView();
  135. if ($this->view !== NULL) {
  136. $this->view->assign('settings', $this->settings);
  137. $this->initializeView($this->view);
  138. }
  139. $this->callActionMethod();
  140. }
  141.  
  142. /**
  143. * Resolves and checks the current action method name
  144. *
  145. * @return string Method name of the current action
  146. * @throws \TYPO3\FLOW3\Mvc\Exception\NoSuchActionException
  147. */
  148. protected function resolveActionMethodName() {
  149. $actionMethodName = $this->request->getControllerActionName() . 'Action';
  150. if (!is_callable(array($this, $actionMethodName))) {
  151. throw new \TYPO3\FLOW3\Mvc\Exception\NoSuchActionException('An action "' . $actionMethodName . '" does not exist in controller "' . get_class($this) . '".', 1186669086);
  152. }
  153. return $actionMethodName;
  154. }
  155.  
  156. /**
  157. * Implementation of the arguments initialization in the action controller:
  158. * Automatically registers arguments of the current action
  159. *
  160. * Don't override this method - use initializeAction() instead.
  161. *
  162. * @return void
  163. * @throws \TYPO3\FLOW3\Mvc\Exception\InvalidArgumentTypeException
  164. * @see initializeArguments()
  165. */
  166. protected function initializeActionMethodArguments() {
  167. $methodParameters = $this->reflectionService->getMethodParameters(get_class($this), $this->actionMethodName);
  168.  
  169. $this->arguments->removeAll();
  170. foreach ($methodParameters as $parameterName => $parameterInfo) {
  171. $dataType = NULL;
  172. if (isset($parameterInfo['type'])) {
  173. $dataType = $parameterInfo['type'];
  174. } elseif ($parameterInfo['array']) {
  175. $dataType = 'array';
  176. }
  177. if ($dataType === NULL) throw new \TYPO3\FLOW3\Mvc\Exception\InvalidArgumentTypeException('The argument type for parameter $' . $parameterName . ' of method ' . get_class($this) . '->' . $this->actionMethodName . '() could not be detected.' , 1253175643);
  178. $defaultValue = (isset($parameterInfo['defaultValue']) ? $parameterInfo['defaultValue'] : NULL);
  179. $this->arguments->addNewArgument($parameterName, $dataType, ($parameterInfo['optional'] === FALSE), $defaultValue);
  180. }
  181. }
  182.  
  183. /**
  184. * Adds the needed valiators to the Arguments:
  185. *
  186. * - Validators checking the data type from the @param annotation
  187. * - Custom validators specified with validate annotations.
  188. * - Model-based validators (validate annotations in the model)
  189. * - Custom model validator classes
  190. *
  191. * @return void
  192. */
  193. protected function initializeActionMethodValidators() {
  194. $parameterValidators = $this->validatorResolver->buildMethodArgumentsValidatorConjunctions(get_class($this), $this->actionMethodName);
  195.  
  196. foreach ($this->arguments as $argument) {
  197. $validator = $parameterValidators[$argument->getName()];
  198.  
  199. $baseValidatorConjunction = $this->validatorResolver->getBaseValidatorConjunction($argument->getDataType(), array('Default', 'Controller'));
  200. if (count($baseValidatorConjunction) > 0) {
  201. $validator->addValidator($baseValidatorConjunction);
  202. }
  203. $argument->setValidator($validator);
  204. }
  205. }
  206.  
  207. /**
  208. * Initializes the controller before invoking an action method.
  209. *
  210. * Override this method to solve tasks which all actions have in
  211. * common.
  212. *
  213. * @return void
  214. * @api
  215. */
  216. protected function initializeAction() {
  217. }
  218.  
  219. /**
  220. * Calls the specified action method and passes the arguments.
  221. *
  222. * If the action returns a string, it is appended to the content in the
  223. * response object. If the action doesn't return anything and a valid
  224. * view exists, the view is rendered automatically.
  225. *
  226. * @return void
  227. */
  228. protected function callActionMethod() {
  229. $preparedArguments = array();
  230. foreach ($this->arguments as $argument) {
  231. $preparedArguments[] = $argument->getValue();
  232. }
  233.  
  234. $validationResult = $this->arguments->getValidationResults();
  235.  
  236. if (!$validationResult->hasErrors()) {
  237. $actionResult = call_user_func_array(array($this, $this->actionMethodName), $preparedArguments);
  238. } else {
  239. $ignoreValidationAnnotations = $this->reflectionService->getMethodAnnotations(get_class($this), $this->actionMethodName, 'TYPO3\FLOW3\Annotations\IgnoreValidation');
  240. $ignoredArguments = array_map(function($annotation) { return $annotation->argumentName; }, $ignoreValidationAnnotations);
  241.  
  242. // if there exists more errors than in ignoreValidationAnnotations_=> call error method
  243. // else => call action method
  244. $shouldCallActionMethod = TRUE;
  245. foreach ($validationResult->getSubResults() as $argumentName => $subValidationResult) {
  246. if (!$subValidationResult->hasErrors()) continue;
  247.  
  248. if (array_search($argumentName, $ignoredArguments) !== FALSE) {
  249. continue;
  250. }
  251.  
  252. $shouldCallActionMethod = FALSE;
  253. }
  254.  
  255. if ($shouldCallActionMethod) {
  256. $actionResult = call_user_func_array(array($this, $this->actionMethodName), $preparedArguments);
  257. } else {
  258. $actionResult = call_user_func(array($this, $this->errorMethodName));
  259. }
  260. }
  261.  
  262. if ($actionResult === NULL && $this->view instanceof \TYPO3\FLOW3\Mvc\View\ViewInterface) {
  263. $this->response->appendContent($this->view->render());
  264. } elseif (is_string($actionResult) && strlen($actionResult) > 0) {
  265. $this->response->appendContent($actionResult);
  266. } elseif (is_object($actionResult) && method_exists($actionResult, '__toString')) {
  267. $this->response->appendContent((string)$actionResult);
  268. }
  269. }
  270.  
  271. /**
  272. * Prepares a view for the current action and stores it in $this->view.
  273. * By default, this method tries to locate a view with a name matching
  274. * the current action.
  275. *
  276. * @return \TYPO3\FLOW3\Mvc\View\ViewInterface the resolved view
  277. * @api
  278. */
  279. protected function resolveView() {
  280. $viewObjectName = $this->resolveViewObjectName();
  281. if ($viewObjectName !== FALSE) {
  282. $view = $this->objectManager->get($viewObjectName);
  283. if ($view->canRender($this->controllerContext) === FALSE) {
  284. unset($view);
  285. }
  286. }
  287. if (!isset($view) && $this->defaultViewObjectName != '') {
  288. $view = $this->objectManager->get($this->defaultViewObjectName);
  289. if ($view->canRender($this->controllerContext) === FALSE) {
  290. unset($view);
  291. }
  292. }
  293. if (!isset($view)) {
  294. $view = $this->objectManager->get('TYPO3\FLOW3\Mvc\View\NotFoundView');
  295. $view->assign('errorMessage', 'No template was found. View could not be resolved for action "' . $this->request->getControllerActionName() . '"');
  296. }
  297. $view->setControllerContext($this->controllerContext);
  298. return $view;
  299. }
  300.  
  301. /**
  302. * Determines the fully qualified view object name.
  303. *
  304. * @return mixed The fully qualified view object name or FALSE if no matching view could be found.
  305. * @api
  306. */
  307. protected function resolveViewObjectName() {
  308. $possibleViewObjectName = $this->viewObjectNamePattern;
  309. $packageKey = $this->request->getControllerPackageKey();
  310. $subpackageKey = $this->request->getControllerSubpackageKey();
  311. $format = $this->request->getFormat();
  312.  
  313. if ($subpackageKey !== NULL && $subpackageKey !== '') {
  314. $packageKey.= '\\' . $subpackageKey;
  315. }
  316. $possibleViewObjectName = str_replace('@package', str_replace('.', '\\', $packageKey), $possibleViewObjectName);
  317. $possibleViewObjectName = str_replace('@controller', $this->request->getControllerName(), $possibleViewObjectName);
  318. $possibleViewObjectName = str_replace('@action', $this->request->getControllerActionName(), $possibleViewObjectName);
  319.  
  320. $viewObjectName = $this->objectManager->getCaseSensitiveObjectName(strtolower(str_replace('@format', $format, $possibleViewObjectName)));
  321. if ($viewObjectName === FALSE) {
  322. $viewObjectName = $this->objectManager->getCaseSensitiveObjectName(strtolower(str_replace('@format', '', $possibleViewObjectName)));
  323. }
  324. if ($viewObjectName === FALSE && isset($this->viewFormatToObjectNameMap[$format])) {
  325. $viewObjectName = $this->viewFormatToObjectNameMap[$format];
  326. }
  327. return $viewObjectName;
  328. }
  329.  
  330. /**
  331. * Initializes the view before invoking an action method.
  332. *
  333. * Override this method to solve assign variables common for all actions
  334. * or prepare the view in another way before the action is called.
  335. *
  336. * @param \TYPO3\FLOW3\Mvc\View\ViewInterface $view The view to be initialized
  337. * @return void
  338. * @api
  339. */
  340. protected function initializeView(\TYPO3\FLOW3\Mvc\View\ViewInterface $view) {
  341. }
  342.  
  343. /**
  344. * A special action which is called if the originally intended action could
  345. * not be called, for example if the arguments were not valid.
  346. *
  347. * The default implementation sets a flash message, request errors and forwards back
  348. * to the originating action. This is suitable for most actions dealing with form input.
  349. *
  350. * @return string
  351. * @api
  352. */
  353. protected function errorAction() {
  354. $errorFlashMessage = $this->getErrorFlashMessage();
  355. if ($errorFlashMessage !== FALSE) {
  356. $this->flashMessageContainer->addMessage($errorFlashMessage);
  357. }
  358. $referringRequest = $this->request->getReferringRequest();
  359. if ($referringRequest !== NULL) {
  360. $subPackageKey = $referringRequest->getControllerSubpackageKey();
  361. if ($subPackageKey !== NULL) {
  362. rtrim($packageAndSubpackageKey = $referringRequest->getControllerPackageKey() . '\\' . $referringRequest->getControllerSubpackageKey(), '\\');
  363. } else {
  364. $packageAndSubpackageKey = $referringRequest->getControllerPackageKey();
  365. }
  366. $argumentsForNextController = $referringRequest->getArguments();
  367. $argumentsForNextController['__submittedArguments'] = $this->request->getArguments();
  368. $argumentsForNextController['__submittedArgumentValidationResults'] = $this->arguments->getValidationResults();
  369.  
  370. $this->forward($referringRequest->getControllerActionName(), $referringRequest->getControllerName(), $packageAndSubpackageKey, $argumentsForNextController);
  371. }
  372.  
  373. $message = 'An error occurred while trying to call ' . get_class($this) . '->' . $this->actionMethodName . '().' . PHP_EOL;
  374. foreach ($this->arguments->getValidationResults()->getFlattenedErrors() as $propertyPath => $errors) {
  375. foreach ($errors as $error) {
  376. $message .= 'Error for ' . $propertyPath . ': ' . $error->render() . PHP_EOL;
  377. }
  378. }
  379.  
  380. return $message;
  381. }
  382.  
  383. /**
  384. * A template method for displaying custom error flash messages, or to
  385. * display no flash message at all on errors. Override this to customize
  386. * the flash message in your action controller.
  387. *
  388. * @return \TYPO3\FLOW3\Error\Message The flash message or FALSE if no flash message should be set
  389. * @api
  390. */
  391. protected function getErrorFlashMessage() {
  392. return new \TYPO3\FLOW3\Error\Error('An error occurred while trying to call %1$s->%2$s()', NULL, array(get_class($this), $this->actionMethodName));
  393. }
  394. }
Advertisement
Add Comment
Please, Sign In to add comment