PageRenderTime 40ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/View/Helper/JsHelper.php

https://github.com/Nervie/Beta
PHP | 427 lines | 207 code | 30 blank | 190 comment | 48 complexity | 83063c7c29f192283df78e2ef686f4b1 MD5 | raw file
  1. <?php
  2. /**
  3. * Javascript Generator class file.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc.
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc.
  14. * @link http://cakephp.org CakePHP Project
  15. * @package Cake.View.Helper
  16. * @since CakePHP v 1.2
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('AppHelper', 'View/Helper');
  20. App::uses('JsBaseEngineHelper', 'View/Helper');
  21. App::uses('Multibyte', 'I18n');
  22. /**
  23. * Javascript Generator helper class for easy use of JavaScript.
  24. *
  25. * JsHelper provides an abstract interface for authoring JavaScript with a
  26. * given client-side library.
  27. *
  28. * @package Cake.View.Helper
  29. */
  30. class JsHelper extends AppHelper {
  31. /**
  32. * Whether or not you want scripts to be buffered or output.
  33. *
  34. * @var boolean
  35. * @access public
  36. */
  37. public $bufferScripts = true;
  38. /**
  39. * helpers
  40. *
  41. * @var array
  42. * @access public
  43. */
  44. public $helpers = array('Html', 'Form');
  45. /**
  46. * Variables to pass to Javascript.
  47. *
  48. * @var array
  49. * @see JsHelper::set()
  50. * @access private
  51. */
  52. private $__jsVars = array();
  53. /**
  54. * Scripts that are queued for output
  55. *
  56. * @var array
  57. * @see JsHelper::buffer()
  58. * @access private
  59. */
  60. private $__bufferedScripts = array();
  61. /**
  62. * Current Javascript Engine that is being used
  63. *
  64. * @var string
  65. * @access private
  66. */
  67. private $__engineName;
  68. /**
  69. * The javascript variable created by set() variables.
  70. *
  71. * @var string
  72. * @access public
  73. */
  74. public $setVariable = APP_DIR;
  75. /**
  76. * Constructor - determines engine helper
  77. *
  78. * @param View $View the view object the helper is attached to.
  79. * @param array $settings Settings array contains name of engine helper.
  80. */
  81. public function __construct(View $View, $settings = array()) {
  82. $className = 'Jquery';
  83. if (is_array($settings) && isset($settings[0])) {
  84. $className = $settings[0];
  85. } elseif (is_string($settings)) {
  86. $className = $settings;
  87. }
  88. $engineName = $className;
  89. list($plugin, $className) = pluginSplit($className);
  90. $this->__engineName = $className . 'Engine';
  91. $engineClass = $engineName . 'Engine';
  92. $this->helpers[] = $engineClass;
  93. parent::__construct($View, $settings);
  94. }
  95. /**
  96. * call__ Allows for dispatching of methods to the Engine Helper.
  97. * methods in the Engines bufferedMethods list will be automatically buffered.
  98. * You can control buffering with the buffer param as well. By setting the last parameter to
  99. * any engine method to a boolean you can force or disable buffering.
  100. *
  101. * e.g. `$js->get('#foo')->effect('fadeIn', array('speed' => 'slow'), true);`
  102. *
  103. * Will force buffering for the effect method. If the method takes an options array you may also add
  104. * a 'buffer' param to the options array and control buffering there as well.
  105. *
  106. * e.g. `$js->get('#foo')->event('click', $functionContents, array('buffer' => true));`
  107. *
  108. * The buffer parameter will not be passed onto the EngineHelper.
  109. *
  110. * @param string $method Method to be called
  111. * @param array $params Parameters for the method being called.
  112. * @return mixed Depends on the return of the dispatched method, or it could be an instance of the EngineHelper
  113. */
  114. public function __call($method, $params) {
  115. if ($this->{$this->__engineName} && method_exists($this->{$this->__engineName}, $method)) {
  116. $buffer = false;
  117. $engineHelper = $this->{$this->__engineName};
  118. if (in_array(strtolower($method), $engineHelper->bufferedMethods)) {
  119. $buffer = true;
  120. }
  121. if (count($params) > 0) {
  122. $lastParam = $params[count($params) - 1];
  123. $hasBufferParam = (is_bool($lastParam) || is_array($lastParam) && isset($lastParam['buffer']));
  124. if ($hasBufferParam && is_bool($lastParam)) {
  125. $buffer = $lastParam;
  126. unset($params[count($params) - 1]);
  127. } elseif ($hasBufferParam && is_array($lastParam)) {
  128. $buffer = $lastParam['buffer'];
  129. unset($params['buffer']);
  130. }
  131. }
  132. $out = call_user_func_array(array(&$engineHelper, $method), $params);
  133. if ($this->bufferScripts && $buffer && is_string($out)) {
  134. $this->buffer($out);
  135. return null;
  136. }
  137. if (is_object($out) && is_a($out, 'JsBaseEngineHelper')) {
  138. return $this;
  139. }
  140. return $out;
  141. }
  142. if (method_exists($this, $method . '_')) {
  143. return call_user_func(array(&$this, $method . '_'), $params);
  144. }
  145. trigger_error(__d('cake_dev', 'JsHelper:: Missing Method %s is undefined', $method), E_USER_WARNING);
  146. }
  147. /**
  148. * Overwrite inherited Helper::value()
  149. * See JsBaseEngineHelper::value() for more information on this method.
  150. *
  151. * @param mixed $val A PHP variable to be converted to JSON
  152. * @param boolean $quoteStrings If false, leaves string values unquoted
  153. * @return string a JavaScript-safe/JSON representation of $val
  154. * @access public
  155. **/
  156. public function value($val, $quoteString = true) {
  157. return $this->{$this->__engineName}->value($val, $quoteString);
  158. }
  159. /**
  160. * Writes all Javascript generated so far to a code block or
  161. * caches them to a file and returns a linked script. If no scripts have been
  162. * buffered this method will return null. If the request is an XHR(ajax) request
  163. * onDomReady will be set to false. As the dom is already 'ready'.
  164. *
  165. * ### Options
  166. *
  167. * - `inline` - Set to true to have scripts output as a script block inline
  168. * if `cache` is also true, a script link tag will be generated. (default true)
  169. * - `cache` - Set to true to have scripts cached to a file and linked in (default false)
  170. * - `clear` - Set to false to prevent script cache from being cleared (default true)
  171. * - `onDomReady` - wrap cached scripts in domready event (default true)
  172. * - `safe` - if an inline block is generated should it be wrapped in <![CDATA[ ... ]]> (default true)
  173. *
  174. * @param array $options options for the code block
  175. * @return mixed Completed javascript tag if there are scripts, if there are no buffered
  176. * scripts null will be returned.
  177. */
  178. public function writeBuffer($options = array()) {
  179. $domReady = $this->request->is('ajax');
  180. $defaults = array(
  181. 'onDomReady' => $domReady, 'inline' => true,
  182. 'cache' => false, 'clear' => true, 'safe' => true
  183. );
  184. $options = array_merge($defaults, $options);
  185. $script = implode("\n", $this->getBuffer($options['clear']));
  186. if (empty($script)) {
  187. return null;
  188. }
  189. if ($options['onDomReady']) {
  190. $script = $this->{$this->__engineName}->domReady($script);
  191. }
  192. $opts = $options;
  193. unset($opts['onDomReady'], $opts['cache'], $opts['clear']);
  194. if (!$options['cache'] && $options['inline']) {
  195. return $this->Html->scriptBlock($script, $opts);
  196. }
  197. if ($options['cache'] && $options['inline']) {
  198. $filename = md5($script);
  199. if (!file_exists(JS . $filename . '.js')) {
  200. cache(str_replace(WWW_ROOT, '', JS) . $filename . '.js', $script, '+999 days', 'public');
  201. }
  202. return $this->Html->script($filename);
  203. }
  204. $this->Html->scriptBlock($script, $opts);
  205. return null;
  206. }
  207. /**
  208. * Write a script to the buffered scripts.
  209. *
  210. * @param string $script Script string to add to the buffer.
  211. * @param boolean $top If true the script will be added to the top of the
  212. * buffered scripts array. If false the bottom.
  213. * @return void
  214. */
  215. public function buffer($script, $top = false) {
  216. if ($top) {
  217. array_unshift($this->__bufferedScripts, $script);
  218. } else {
  219. $this->__bufferedScripts[] = $script;
  220. }
  221. }
  222. /**
  223. * Get all the buffered scripts
  224. *
  225. * @param boolean $clear Whether or not to clear the script caches (default true)
  226. * @return array Array of scripts added to the request.
  227. */
  228. public function getBuffer($clear = true) {
  229. $this->_createVars();
  230. $scripts = $this->__bufferedScripts;
  231. if ($clear) {
  232. $this->__bufferedScripts = array();
  233. $this->__jsVars = array();
  234. }
  235. return $scripts;
  236. }
  237. /**
  238. * Generates the object string for variables passed to javascript.
  239. *
  240. * @return string Generated JSON object of all set vars
  241. */
  242. protected function _createVars() {
  243. if (!empty($this->__jsVars)) {
  244. $setVar = (strpos($this->setVariable, '.')) ? $this->setVariable : 'window.' . $this->setVariable;
  245. $this->buffer($setVar . ' = ' . $this->object($this->__jsVars) . ';', true);
  246. }
  247. }
  248. /**
  249. * Generate an 'Ajax' link. Uses the selected JS engine to create a link
  250. * element that is enhanced with Javascript. Options can include
  251. * both those for HtmlHelper::link() and JsBaseEngine::request(), JsBaseEngine::event();
  252. *
  253. * ### Options
  254. *
  255. * - `confirm` - Generate a confirm() dialog before sending the event.
  256. * - `id` - use a custom id.
  257. * - `htmlAttributes` - additional non-standard htmlAttributes. Standard attributes are class, id,
  258. * rel, title, escape, onblur and onfocus.
  259. * - `buffer` - Disable the buffering and return a script tag in addition to the link.
  260. *
  261. * @param string $title Title for the link.
  262. * @param mixed $url Mixed either a string URL or an cake url array.
  263. * @param array $options Options for both the HTML element and Js::request()
  264. * @return string Completed link. If buffering is disabled a script tag will be returned as well.
  265. */
  266. public function link($title, $url = null, $options = array()) {
  267. if (!isset($options['id'])) {
  268. $options['id'] = 'link-' . intval(mt_rand());
  269. }
  270. list($options, $htmlOptions) = $this->_getHtmlOptions($options);
  271. $out = $this->Html->link($title, $url, $htmlOptions);
  272. $this->get('#' . $htmlOptions['id']);
  273. $requestString = $event = '';
  274. if (isset($options['confirm'])) {
  275. $requestString = $this->confirmReturn($options['confirm']);
  276. unset($options['confirm']);
  277. }
  278. $buffer = isset($options['buffer']) ? $options['buffer'] : null;
  279. $safe = isset($options['safe']) ? $options['safe'] : true;
  280. unset($options['buffer'], $options['safe']);
  281. $requestString .= $this->request($url, $options);
  282. if (!empty($requestString)) {
  283. $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
  284. }
  285. if (isset($buffer) && !$buffer) {
  286. $opts = array('safe' => $safe);
  287. $out .= $this->Html->scriptBlock($event, $opts);
  288. }
  289. return $out;
  290. }
  291. /**
  292. * Pass variables into Javascript. Allows you to set variables that will be
  293. * output when the buffer is fetched with `JsHelper::getBuffer()` or `JsHelper::writeBuffer()`
  294. * The Javascript variable used to output set variables can be controlled with `JsHelper::$setVariable`
  295. *
  296. * @param mixed $one Either an array of variables to set, or the name of the variable to set.
  297. * @param mixed $two If $one is a string, $two is the value for that key.
  298. * @return void
  299. */
  300. public function set($one, $two = null) {
  301. $data = null;
  302. if (is_array($one)) {
  303. if (is_array($two)) {
  304. $data = array_combine($one, $two);
  305. } else {
  306. $data = $one;
  307. }
  308. } else {
  309. $data = array($one => $two);
  310. }
  311. if ($data == null) {
  312. return false;
  313. }
  314. $this->__jsVars = array_merge($this->__jsVars, $data);
  315. }
  316. /**
  317. * Uses the selected JS engine to create a submit input
  318. * element that is enhanced with Javascript. Options can include
  319. * both those for FormHelper::submit() and JsBaseEngine::request(), JsBaseEngine::event();
  320. *
  321. * Forms submitting with this method, cannot send files. Files do not transfer over XmlHttpRequest
  322. * and require an iframe or flash.
  323. *
  324. * ### Options
  325. *
  326. * - `url` The url you wish the XHR request to submit to.
  327. * - `confirm` A string to use for a confirm() message prior to submitting the request.
  328. * - `method` The method you wish the form to send by, defaults to POST
  329. * - `buffer` Whether or not you wish the script code to be buffered, defaults to true.
  330. * - Also see options for JsHelper::request() and JsHelper::event()
  331. *
  332. * @param string $title The display text of the submit button.
  333. * @param array $options Array of options to use. See the options for the above mentioned methods.
  334. * @return string Completed submit button.
  335. */
  336. public function submit($caption = null, $options = array()) {
  337. if (!isset($options['id'])) {
  338. $options['id'] = 'submit-' . intval(mt_rand());
  339. }
  340. $formOptions = array('div');
  341. list($options, $htmlOptions) = $this->_getHtmlOptions($options, $formOptions);
  342. $out = $this->Form->submit($caption, $htmlOptions);
  343. $this->get('#' . $htmlOptions['id']);
  344. $options['data'] = $this->serializeForm(array('isForm' => false, 'inline' => true));
  345. $requestString = $url = '';
  346. if (isset($options['confirm'])) {
  347. $requestString = $this->confirmReturn($options['confirm']);
  348. unset($options['confirm']);
  349. }
  350. if (isset($options['url'])) {
  351. $url = $options['url'];
  352. unset($options['url']);
  353. }
  354. if (!isset($options['method'])) {
  355. $options['method'] = 'post';
  356. }
  357. $options['dataExpression'] = true;
  358. $buffer = isset($options['buffer']) ? $options['buffer'] : null;
  359. $safe = isset($options['safe']) ? $options['safe'] : true;
  360. unset($options['buffer'], $options['safe']);
  361. $requestString .= $this->request($url, $options);
  362. if (!empty($requestString)) {
  363. $event = $this->event('click', $requestString, $options + array('buffer' => $buffer));
  364. }
  365. if (isset($buffer) && !$buffer) {
  366. $opts = array('safe' => $safe);
  367. $out .= $this->Html->scriptBlock($event, $opts);
  368. }
  369. return $out;
  370. }
  371. /**
  372. * Parse a set of Options and extract the Html options.
  373. * Extracted Html Options are removed from the $options param.
  374. *
  375. * @param array $options Options to filter.
  376. * @param array $additional Array of additional keys to extract and include in the return options array.
  377. * @return array Array of js options and Htmloptions
  378. */
  379. protected function _getHtmlOptions($options, $additional = array()) {
  380. $htmlKeys = array_merge(
  381. array('class', 'id', 'escape', 'onblur', 'onfocus', 'rel', 'title', 'style'),
  382. $additional
  383. );
  384. $htmlOptions = array();
  385. foreach ($htmlKeys as $key) {
  386. if (isset($options[$key])) {
  387. $htmlOptions[$key] = $options[$key];
  388. }
  389. unset($options[$key]);
  390. }
  391. if (isset($options['htmlAttributes'])) {
  392. $htmlOptions = array_merge($htmlOptions, $options['htmlAttributes']);
  393. unset($options['htmlAttributes']);
  394. }
  395. return array($options, $htmlOptions);
  396. }
  397. }