PageRenderTime 84ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/View/Helper/JsBaseEngineHelper.php

https://bitbucket.org/praveen_excell/opshop
PHP | 592 lines | 316 code | 28 blank | 248 comment | 27 complexity | 1b3712bfba717659159dcf1f369de063 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  1. <?php
  2. /**
  3. * CakePHP : Rapid Development Framework (http://cakephp.org)
  4. * Copyright 2005-2012, Cake Software Foundation, Inc.
  5. *
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  10. * @link http://cakephp.org CakePHP(tm) Project
  11. * @package Cake.View.Helper
  12. * @since CakePHP(tm) v 2.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. App::uses('AppHelper', 'View/Helper');
  16. /**
  17. * JsEngineBaseClass
  18. *
  19. * Abstract Base Class for All JsEngines to extend. Provides generic methods.
  20. *
  21. * @package Cake.View.Helper
  22. */
  23. abstract class JsBaseEngineHelper extends AppHelper {
  24. /**
  25. * The js snippet for the current selection.
  26. *
  27. * @var string
  28. */
  29. public $selection;
  30. /**
  31. * Collection of option maps. Option maps allow other helpers to use generic names for engine
  32. * callbacks and options. Allowing uniform code access for all engine types. Their use is optional
  33. * for end user use though.
  34. *
  35. * @var array
  36. */
  37. protected $_optionMap = array();
  38. /**
  39. * An array of lowercase method names in the Engine that are buffered unless otherwise disabled.
  40. * This allows specific 'end point' methods to be automatically buffered by the JsHelper.
  41. *
  42. * @var array
  43. */
  44. public $bufferedMethods = array('event', 'sortable', 'drag', 'drop', 'slider');
  45. /**
  46. * Contains a list of callback names -> default arguments.
  47. *
  48. * @var array
  49. */
  50. protected $_callbackArguments = array();
  51. /**
  52. * Create an `alert()` message in Javascript
  53. *
  54. * @param string $message Message you want to alter.
  55. * @return string completed alert()
  56. */
  57. public function alert($message) {
  58. return 'alert("' . $this->escape($message) . '");';
  59. }
  60. /**
  61. * Redirects to a URL. Creates a window.location modification snippet
  62. * that can be used to trigger 'redirects' from Javascript.
  63. *
  64. * @param string|array $url
  65. * @param array $options
  66. * @return string completed redirect in javascript
  67. */
  68. public function redirect($url = null) {
  69. return 'window.location = "' . Router::url($url) . '";';
  70. }
  71. /**
  72. * Create a `confirm()` message
  73. *
  74. * @param string $message Message you want confirmed.
  75. * @return string completed confirm()
  76. */
  77. public function confirm($message) {
  78. return 'confirm("' . $this->escape($message) . '");';
  79. }
  80. /**
  81. * Generate a confirm snippet that returns false from the current
  82. * function scope.
  83. *
  84. * @param string $message Message to use in the confirm dialog.
  85. * @return string completed confirm with return script
  86. */
  87. public function confirmReturn($message) {
  88. $out = 'var _confirm = ' . $this->confirm($message);
  89. $out .= "if (!_confirm) {\n\treturn false;\n}";
  90. return $out;
  91. }
  92. /**
  93. * Create a `prompt()` Javascript function
  94. *
  95. * @param string $message Message you want to prompt.
  96. * @param string $default Default message
  97. * @return string completed prompt()
  98. */
  99. public function prompt($message, $default = '') {
  100. return 'prompt("' . $this->escape($message) . '", "' . $this->escape($default) . '");';
  101. }
  102. /**
  103. * Generates a JavaScript object in JavaScript Object Notation (JSON)
  104. * from an array. Will use native JSON encode method if available, and $useNative == true
  105. *
  106. * ### Options:
  107. *
  108. * - `prefix` - String prepended to the returned data.
  109. * - `postfix` - String appended to the returned data.
  110. *
  111. * @param array $data Data to be converted.
  112. * @param array $options Set of options, see above.
  113. * @return string A JSON code block
  114. */
  115. public function object($data = array(), $options = array()) {
  116. $defaultOptions = array(
  117. 'prefix' => '', 'postfix' => '',
  118. );
  119. $options = array_merge($defaultOptions, $options);
  120. return $options['prefix'] . json_encode($data) . $options['postfix'];
  121. }
  122. /**
  123. * Converts a PHP-native variable of any type to a JSON-equivalent representation
  124. *
  125. * @param mixed $val A PHP variable to be converted to JSON
  126. * @param boolean $quoteString If false, leaves string values unquoted
  127. * @return string a JavaScript-safe/JSON representation of $val
  128. */
  129. public function value($val = array(), $quoteString = null, $key = 'value') {
  130. if ($quoteString === null) {
  131. $quoteString = true;
  132. }
  133. switch (true) {
  134. case (is_array($val) || is_object($val)):
  135. $val = $this->object($val);
  136. break;
  137. case ($val === null):
  138. $val = 'null';
  139. break;
  140. case (is_bool($val)):
  141. $val = ($val === true) ? 'true' : 'false';
  142. break;
  143. case (is_int($val)):
  144. $val = $val;
  145. break;
  146. case (is_float($val)):
  147. $val = sprintf("%.11f", $val);
  148. break;
  149. default:
  150. $val = $this->escape($val);
  151. if ($quoteString) {
  152. $val = '"' . $val . '"';
  153. }
  154. break;
  155. }
  156. return $val;
  157. }
  158. /**
  159. * Escape a string to be JSON friendly.
  160. *
  161. * List of escaped elements:
  162. *
  163. * - "\r" => '\n'
  164. * - "\n" => '\n'
  165. * - '"' => '\"'
  166. *
  167. * @param string $string String that needs to get escaped.
  168. * @return string Escaped string.
  169. */
  170. public function escape($string) {
  171. return $this->_utf8ToHex($string);
  172. }
  173. /**
  174. * Encode a string into JSON. Converts and escapes necessary characters.
  175. *
  176. * @param string $string The string that needs to be utf8->hex encoded
  177. * @return void
  178. */
  179. protected function _utf8ToHex($string) {
  180. $length = strlen($string);
  181. $return = '';
  182. for ($i = 0; $i < $length; ++$i) {
  183. $ord = ord($string{$i});
  184. switch (true) {
  185. case $ord == 0x08:
  186. $return .= '\b';
  187. break;
  188. case $ord == 0x09:
  189. $return .= '\t';
  190. break;
  191. case $ord == 0x0A:
  192. $return .= '\n';
  193. break;
  194. case $ord == 0x0C:
  195. $return .= '\f';
  196. break;
  197. case $ord == 0x0D:
  198. $return .= '\r';
  199. break;
  200. case $ord == 0x22:
  201. case $ord == 0x2F:
  202. case $ord == 0x5C:
  203. $return .= '\\' . $string{$i};
  204. break;
  205. case (($ord >= 0x20) && ($ord <= 0x7F)):
  206. $return .= $string{$i};
  207. break;
  208. case (($ord & 0xE0) == 0xC0):
  209. if ($i + 1 >= $length) {
  210. $i += 1;
  211. $return .= '?';
  212. break;
  213. }
  214. $charbits = $string{$i} . $string{$i + 1};
  215. $char = Multibyte::utf8($charbits);
  216. $return .= sprintf('\u%04s', dechex($char[0]));
  217. $i += 1;
  218. break;
  219. case (($ord & 0xF0) == 0xE0):
  220. if ($i + 2 >= $length) {
  221. $i += 2;
  222. $return .= '?';
  223. break;
  224. }
  225. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2};
  226. $char = Multibyte::utf8($charbits);
  227. $return .= sprintf('\u%04s', dechex($char[0]));
  228. $i += 2;
  229. break;
  230. case (($ord & 0xF8) == 0xF0):
  231. if ($i + 3 >= $length) {
  232. $i += 3;
  233. $return .= '?';
  234. break;
  235. }
  236. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3};
  237. $char = Multibyte::utf8($charbits);
  238. $return .= sprintf('\u%04s', dechex($char[0]));
  239. $i += 3;
  240. break;
  241. case (($ord & 0xFC) == 0xF8):
  242. if ($i + 4 >= $length) {
  243. $i += 4;
  244. $return .= '?';
  245. break;
  246. }
  247. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4};
  248. $char = Multibyte::utf8($charbits);
  249. $return .= sprintf('\u%04s', dechex($char[0]));
  250. $i += 4;
  251. break;
  252. case (($ord & 0xFE) == 0xFC):
  253. if ($i + 5 >= $length) {
  254. $i += 5;
  255. $return .= '?';
  256. break;
  257. }
  258. $charbits = $string{$i} . $string{$i + 1} . $string{$i + 2} . $string{$i + 3} . $string{$i + 4} . $string{$i + 5};
  259. $char = Multibyte::utf8($charbits);
  260. $return .= sprintf('\u%04s', dechex($char[0]));
  261. $i += 5;
  262. break;
  263. }
  264. }
  265. return $return;
  266. }
  267. /**
  268. * Create javascript selector for a CSS rule
  269. *
  270. * @param string $selector The selector that is targeted
  271. * @return JsBaseEngineHelper instance of $this. Allows chained methods.
  272. */
  273. abstract public function get($selector);
  274. /**
  275. * Add an event to the script cache. Operates on the currently selected elements.
  276. *
  277. * ### Options
  278. *
  279. * - `wrap` - Whether you want the callback wrapped in an anonymous function. (defaults to true)
  280. * - `stop` - Whether you want the event to stopped. (defaults to true)
  281. *
  282. * @param string $type Type of event to bind to the current dom id
  283. * @param string $callback The Javascript function you wish to trigger or the function literal
  284. * @param array $options Options for the event.
  285. * @return string completed event handler
  286. */
  287. abstract public function event($type, $callback, $options = array());
  288. /**
  289. * Create a domReady event. This is a special event in many libraries
  290. *
  291. * @param string $functionBody The code to run on domReady
  292. * @return string completed domReady method
  293. */
  294. abstract public function domReady($functionBody);
  295. /**
  296. * Create an iteration over the current selection result.
  297. *
  298. * @param string $callback The function body you wish to apply during the iteration.
  299. * @return string completed iteration
  300. */
  301. abstract public function each($callback);
  302. /**
  303. * Trigger an Effect.
  304. *
  305. * ### Supported Effects
  306. *
  307. * The following effects are supported by all core JsEngines
  308. *
  309. * - `show` - reveal an element.
  310. * - `hide` - hide an element.
  311. * - `fadeIn` - Fade in an element.
  312. * - `fadeOut` - Fade out an element.
  313. * - `slideIn` - Slide an element in.
  314. * - `slideOut` - Slide an element out.
  315. *
  316. * ### Options
  317. *
  318. * - `speed` - Speed at which the animation should occur. Accepted values are 'slow', 'fast'. Not all effects use
  319. * the speed option.
  320. *
  321. * @param string $name The name of the effect to trigger.
  322. * @param array $options Array of options for the effect.
  323. * @return string completed string with effect.
  324. */
  325. abstract public function effect($name, $options = array());
  326. /**
  327. * Make an XHR request
  328. *
  329. * ### Event Options
  330. *
  331. * - `complete` - Callback to fire on complete.
  332. * - `success` - Callback to fire on success.
  333. * - `before` - Callback to fire on request initialization.
  334. * - `error` - Callback to fire on request failure.
  335. *
  336. * ### Options
  337. *
  338. * - `method` - The method to make the request with defaults to GET in more libraries
  339. * - `async` - Whether or not you want an asynchronous request.
  340. * - `data` - Additional data to send.
  341. * - `update` - Dom id to update with the content of the request.
  342. * - `type` - Data type for response. 'json' and 'html' are supported. Default is html for most libraries.
  343. * - `evalScripts` - Whether or not <script> tags should be eval'ed.
  344. * - `dataExpression` - Should the `data` key be treated as a callback. Useful for supplying `$options['data']` as
  345. * another Javascript expression.
  346. *
  347. * @param string|array $url Array or String URL to target with the request.
  348. * @param array $options Array of options. See above for cross library supported options
  349. * @return string XHR request.
  350. */
  351. abstract public function request($url, $options = array());
  352. /**
  353. * Create a draggable element. Works on the currently selected element.
  354. * Additional options may be supported by the library implementation.
  355. *
  356. * ### Options
  357. *
  358. * - `handle` - selector to the handle element.
  359. * - `snapGrid` - The pixel grid that movement snaps to, an array(x, y)
  360. * - `container` - The element that acts as a bounding box for the draggable element.
  361. *
  362. * ### Event Options
  363. *
  364. * - `start` - Event fired when the drag starts
  365. * - `drag` - Event fired on every step of the drag
  366. * - `stop` - Event fired when dragging stops (mouse release)
  367. *
  368. * @param array $options Options array see above.
  369. * @return string Completed drag script
  370. */
  371. abstract public function drag($options = array());
  372. /**
  373. * Create a droppable element. Allows for draggable elements to be dropped on it.
  374. * Additional options may be supported by the library implementation.
  375. *
  376. * ### Options
  377. *
  378. * - `accept` - Selector for elements this droppable will accept.
  379. * - `hoverclass` - Class to add to droppable when a draggable is over.
  380. *
  381. * ### Event Options
  382. *
  383. * - `drop` - Event fired when an element is dropped into the drop zone.
  384. * - `hover` - Event fired when a drag enters a drop zone.
  385. * - `leave` - Event fired when a drag is removed from a drop zone without being dropped.
  386. *
  387. * @param array $options Array of options for the drop. See above.
  388. * @return string Completed drop script
  389. */
  390. abstract public function drop($options = array());
  391. /**
  392. * Create a sortable element.
  393. * Additional options may be supported by the library implementation.
  394. *
  395. * ### Options
  396. *
  397. * - `containment` - Container for move action
  398. * - `handle` - Selector to handle element. Only this element will start sort action.
  399. * - `revert` - Whether or not to use an effect to move sortable into final position.
  400. * - `opacity` - Opacity of the placeholder
  401. * - `distance` - Distance a sortable must be dragged before sorting starts.
  402. *
  403. * ### Event Options
  404. *
  405. * - `start` - Event fired when sorting starts
  406. * - `sort` - Event fired during sorting
  407. * - `complete` - Event fired when sorting completes.
  408. *
  409. * @param array $options Array of options for the sortable. See above.
  410. * @return string Completed sortable script.
  411. */
  412. abstract public function sortable($options = array());
  413. /**
  414. * Create a slider UI widget. Comprised of a track and knob.
  415. * Additional options may be supported by the library implementation.
  416. *
  417. * ### Options
  418. *
  419. * - `handle` - The id of the element used in sliding.
  420. * - `direction` - The direction of the slider either 'vertical' or 'horizontal'
  421. * - `min` - The min value for the slider.
  422. * - `max` - The max value for the slider.
  423. * - `step` - The number of steps or ticks the slider will have.
  424. * - `value` - The initial offset of the slider.
  425. *
  426. * ### Events
  427. *
  428. * - `change` - Fired when the slider's value is updated
  429. * - `complete` - Fired when the user stops sliding the handle
  430. *
  431. * @param array $options Array of options for the slider. See above.
  432. * @return string Completed slider script
  433. */
  434. abstract public function slider($options = array());
  435. /**
  436. * Serialize the form attached to $selector.
  437. * Pass `true` for $isForm if the current selection is a form element.
  438. * Converts the form or the form element attached to the current selection into a string/json object
  439. * (depending on the library implementation) for use with XHR operations.
  440. *
  441. * ### Options
  442. *
  443. * - `isForm` - is the current selection a form, or an input? (defaults to false)
  444. * - `inline` - is the rendered statement going to be used inside another JS statement? (defaults to false)
  445. *
  446. * @param array $options options for serialization generation.
  447. * @return string completed form serialization script
  448. */
  449. abstract public function serializeForm($options = array());
  450. /**
  451. * Parse an options assoc array into an Javascript object literal.
  452. * Similar to object() but treats any non-integer value as a string,
  453. * does not include `{ }`
  454. *
  455. * @param array $options Options to be converted
  456. * @param array $safeKeys Keys that should not be escaped.
  457. * @return string Parsed JSON options without enclosing { }.
  458. */
  459. protected function _parseOptions($options, $safeKeys = array()) {
  460. $out = array();
  461. $safeKeys = array_flip($safeKeys);
  462. foreach ($options as $key => $value) {
  463. if (!is_int($value) && !isset($safeKeys[$key])) {
  464. $value = $this->value($value);
  465. }
  466. $out[] = $key . ':' . $value;
  467. }
  468. sort($out);
  469. return join(', ', $out);
  470. }
  471. /**
  472. * Maps Abstract options to engine specific option names.
  473. * If attributes are missing from the map, they are not changed.
  474. *
  475. * @param string $method Name of method whose options are being worked with.
  476. * @param array $options Array of options to map.
  477. * @return array Array of mapped options.
  478. */
  479. protected function _mapOptions($method, $options) {
  480. if (!isset($this->_optionMap[$method])) {
  481. return $options;
  482. }
  483. foreach ($this->_optionMap[$method] as $abstract => $concrete) {
  484. if (isset($options[$abstract])) {
  485. $options[$concrete] = $options[$abstract];
  486. unset($options[$abstract]);
  487. }
  488. }
  489. return $options;
  490. }
  491. /**
  492. * Prepare callbacks and wrap them with function ([args]) { } as defined in
  493. * _callbackArgs array.
  494. *
  495. * @param string $method Name of the method you are preparing callbacks for.
  496. * @param array $options Array of options being parsed
  497. * @param array $callbacks Additional Keys that contain callbacks
  498. * @return array Array of options with callbacks added.
  499. */
  500. protected function _prepareCallbacks($method, $options, $callbacks = array()) {
  501. $wrapCallbacks = true;
  502. if (isset($options['wrapCallbacks'])) {
  503. $wrapCallbacks = $options['wrapCallbacks'];
  504. }
  505. unset($options['wrapCallbacks']);
  506. if (!$wrapCallbacks) {
  507. return $options;
  508. }
  509. $callbackOptions = array();
  510. if (isset($this->_callbackArguments[$method])) {
  511. $callbackOptions = $this->_callbackArguments[$method];
  512. }
  513. $callbacks = array_unique(array_merge(array_keys($callbackOptions), (array)$callbacks));
  514. foreach ($callbacks as $callback) {
  515. if (empty($options[$callback])) {
  516. continue;
  517. }
  518. $args = null;
  519. if (!empty($callbackOptions[$callback])) {
  520. $args = $callbackOptions[$callback];
  521. }
  522. $options[$callback] = 'function (' . $args . ') {' . $options[$callback] . '}';
  523. }
  524. return $options;
  525. }
  526. /**
  527. * Convenience wrapper method for all common option processing steps.
  528. * Runs _mapOptions, _prepareCallbacks, and _parseOptions in order.
  529. *
  530. * @param string $method Name of method processing options for.
  531. * @param array $options Array of options to process.
  532. * @return string Parsed options string.
  533. */
  534. protected function _processOptions($method, $options) {
  535. $options = $this->_mapOptions($method, $options);
  536. $options = $this->_prepareCallbacks($method, $options);
  537. $options = $this->_parseOptions($options, array_keys($this->_callbackArguments[$method]));
  538. return $options;
  539. }
  540. /**
  541. * Convert an array of data into a query string
  542. *
  543. * @param array $parameters Array of parameters to convert to a query string
  544. * @return string Querystring fragment
  545. */
  546. protected function _toQuerystring($parameters) {
  547. $out = '';
  548. $keys = array_keys($parameters);
  549. $count = count($parameters);
  550. for ($i = 0; $i < $count; $i++) {
  551. $out .= $keys[$i] . '=' . $parameters[$keys[$i]];
  552. if ($i < $count - 1) {
  553. $out .= '&';
  554. }
  555. }
  556. return $out;
  557. }
  558. }