PageRenderTime 63ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

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

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