PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

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

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