PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

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