Helper.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 0.2.9
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View;
  16. use Cake\Core\App;
  17. use Cake\Core\Configure;
  18. use Cake\Core\Object;
  19. use Cake\Core\Plugin;
  20. use Cake\Event\EventListener;
  21. use Cake\Routing\Router;
  22. use Cake\Utility\ClassRegistry;
  23. use Cake\Utility\Hash;
  24. use Cake\Utility\Inflector;
  25. /**
  26. * Abstract base class for all other Helpers in CakePHP.
  27. * Provides common methods and features.
  28. *
  29. *
  30. * ## Callback methods
  31. *
  32. * Helpers support a number of callback methods. These callbacks allow you to hook into
  33. * the various view lifecycle events and either modify existing view content or perform
  34. * other application specific logic. The events are not implemented by this base class, as
  35. * implementing a callback method subscribes a helper to the related event. The callback methods
  36. * are as follows:
  37. *
  38. * - `beforeRender(Event $event, $viewFile)` - beforeRender is called before the view file is rendered.
  39. * - `afterRender(Event $event, $viewFile)` - afterRender is called after the view file is rendered
  40. * but before the layout has been rendered.
  41. * - beforeLayout(Event $event, $layoutFile)` - beforeLayout is called before the layout is rendered.
  42. * - `afterLayout(Event $event, $layoutFile)` - afterLayout is called after the layout has rendered.
  43. * - `beforeRenderFile(Event $event, $viewFile)` - Called before any view fragment is rendered.
  44. * - `afterRenderFile(Event $event, $viewFile, $content)` - Called after any view fragment is rendered.
  45. * If a listener returns a non-null value, the output of the rendered file will be set to that.
  46. *
  47. */
  48. class Helper extends Object implements EventListener {
  49. /**
  50. * Settings for this helper.
  51. *
  52. * @var array
  53. */
  54. public $settings = array();
  55. /**
  56. * List of helpers used by this helper
  57. *
  58. * @var array
  59. */
  60. public $helpers = array();
  61. /**
  62. * A helper lookup table used to lazy load helper objects.
  63. *
  64. * @var array
  65. */
  66. protected $_helperMap = array();
  67. /**
  68. * The current theme name if any.
  69. *
  70. * @var string
  71. */
  72. public $theme = null;
  73. /**
  74. * Request object
  75. *
  76. * @var Cake\Network\Request
  77. */
  78. public $request = null;
  79. /**
  80. * Plugin path
  81. *
  82. * @var string
  83. */
  84. public $plugin = null;
  85. /**
  86. * Holds the fields array('field_name' => array('type' => 'string', 'length' => 100),
  87. * primaryKey and validates array('field_name')
  88. *
  89. * @var array
  90. */
  91. public $fieldset = array();
  92. /**
  93. * Holds tag templates.
  94. *
  95. * @var array
  96. */
  97. public $tags = array();
  98. /**
  99. * The View instance this helper is attached to
  100. *
  101. * @var View
  102. */
  103. protected $_View;
  104. /**
  105. * A list of strings that should be treated as suffixes, or
  106. * sub inputs for a parent input. This is used for date/time
  107. * inputs primarily.
  108. *
  109. * @var array
  110. */
  111. protected $_fieldSuffixes = array(
  112. 'year', 'month', 'day', 'hour', 'min', 'second', 'meridian'
  113. );
  114. /**
  115. * The name of the current model entities are in scope of.
  116. *
  117. * @see Helper::setEntity()
  118. * @var string
  119. */
  120. protected $_modelScope;
  121. /**
  122. * The name of the current model association entities are in scope of.
  123. *
  124. * @see Helper::setEntity()
  125. * @var string
  126. */
  127. protected $_association;
  128. /**
  129. * The dot separated list of elements the current field entity is for.
  130. *
  131. * @see Helper::setEntity()
  132. * @var string
  133. */
  134. protected $_entityPath;
  135. /**
  136. * Minimized attributes
  137. *
  138. * @var array
  139. */
  140. protected $_minimizedAttributes = array(
  141. 'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected',
  142. 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize',
  143. 'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate'
  144. );
  145. /**
  146. * Format to attribute
  147. *
  148. * @var string
  149. */
  150. protected $_attributeFormat = '%s="%s"';
  151. /**
  152. * Format to attribute
  153. *
  154. * @var string
  155. */
  156. protected $_minimizedAttributeFormat = '%s="%s"';
  157. /**
  158. * Default Constructor
  159. *
  160. * @param View $View The View this helper is being attached to.
  161. * @param array $settings Configuration settings for the helper.
  162. */
  163. public function __construct(View $View, $settings = array()) {
  164. $this->_View = $View;
  165. $this->request = $View->request;
  166. if ($settings) {
  167. $this->settings = Hash::merge($this->settings, $settings);
  168. }
  169. if (!empty($this->helpers)) {
  170. $this->_helperMap = $View->Helpers->normalizeArray($this->helpers);
  171. }
  172. }
  173. /**
  174. * Provide non fatal errors on missing method calls.
  175. *
  176. * @param string $method Method to invoke
  177. * @param array $params Array of params for the method.
  178. * @return void
  179. */
  180. public function __call($method, $params) {
  181. trigger_error(__d('cake_dev', 'Method %1$s::%2$s does not exist', get_class($this), $method), E_USER_WARNING);
  182. }
  183. /**
  184. * Lazy loads helpers.
  185. *
  186. * @param string $name Name of the property being accessed.
  187. * @return mixed Helper or property found at $name
  188. */
  189. public function __get($name) {
  190. if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
  191. $settings = array_merge((array)$this->_helperMap[$name]['settings'], array('enabled' => false));
  192. $this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $settings);
  193. }
  194. if (isset($this->{$name})) {
  195. return $this->{$name};
  196. }
  197. }
  198. /**
  199. * Finds URL for specified action.
  200. *
  201. * Returns an URL pointing at the provided parameters.
  202. *
  203. * @param string|array $url Either a relative string url like `/products/view/23` or
  204. * an array of URL parameters. Using an array for URLs will allow you to leverage
  205. * the reverse routing features of CakePHP.
  206. * @param boolean $full If true, the full base URL will be prepended to the result
  207. * @return string Full translated URL with base path.
  208. * @link http://book.cakephp.org/2.0/en/views/helpers.html
  209. */
  210. public function url($url = null, $full = false) {
  211. return h(Router::url($url, $full));
  212. }
  213. /**
  214. * Checks if a file exists when theme is used, if no file is found default location is returned
  215. *
  216. * @param string $file The file to create a webroot path to.
  217. * @return string Web accessible path to file.
  218. */
  219. public function webroot($file) {
  220. $asset = explode('?', $file);
  221. $asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
  222. $webPath = "{$this->request->webroot}" . $asset[0];
  223. $file = $asset[0];
  224. if (!empty($this->theme)) {
  225. $file = trim($file, '/');
  226. $theme = $this->theme . '/';
  227. if (DS === '\\') {
  228. $file = str_replace('/', '\\', $file);
  229. }
  230. if (file_exists(Configure::read('App.www_root') . 'theme/' . $this->theme . DS . $file)) {
  231. $webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
  232. } else {
  233. $themePath = App::themePath($this->theme);
  234. $path = $themePath . 'webroot/' . $file;
  235. if (file_exists($path)) {
  236. $webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
  237. }
  238. }
  239. }
  240. if (strpos($webPath, '//') !== false) {
  241. return str_replace('//', '/', $webPath . $asset[1]);
  242. }
  243. return $webPath . $asset[1];
  244. }
  245. /**
  246. * Generate URL for given asset file. Depending on options passed provides full URL with domain name.
  247. * Also calls Helper::assetTimestamp() to add timestamp to local files
  248. *
  249. * @param string|array Path string or URL array
  250. * @param array $options Options array. Possible keys:
  251. * `fullBase` Return full URL with domain name
  252. * `pathPrefix` Path prefix for relative URLs
  253. * `ext` Asset extension to append
  254. * `plugin` False value will prevent parsing path as a plugin
  255. * @return string Generated URL
  256. */
  257. public function assetUrl($path, $options = array()) {
  258. if (is_array($path)) {
  259. return $this->url($path, !empty($options['fullBase']));
  260. }
  261. if (strpos($path, '://') !== false) {
  262. return $path;
  263. }
  264. if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
  265. list($plugin, $path) = $this->_View->pluginSplit($path, false);
  266. }
  267. if (!empty($options['pathPrefix']) && $path[0] !== '/') {
  268. $path = $options['pathPrefix'] . $path;
  269. }
  270. if (
  271. !empty($options['ext']) &&
  272. strpos($path, '?') === false &&
  273. substr($path, -strlen($options['ext'])) !== $options['ext']
  274. ) {
  275. $path .= $options['ext'];
  276. }
  277. if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
  278. return $path;
  279. }
  280. if (isset($plugin)) {
  281. $path = Inflector::underscore($plugin) . '/' . $path;
  282. }
  283. $path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
  284. if (!empty($options['fullBase'])) {
  285. $path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
  286. }
  287. return $path;
  288. }
  289. /**
  290. * Encodes an URL for use in HTML attributes.
  291. *
  292. * @param string $url The URL to encode.
  293. * @return string The URL encoded for both URL & HTML contexts.
  294. */
  295. protected function _encodeUrl($url) {
  296. $path = parse_url($url, PHP_URL_PATH);
  297. $parts = array_map('rawurldecode', explode('/', $path));
  298. $parts = array_map('rawurlencode', $parts);
  299. $encoded = implode('/', $parts);
  300. return h(str_replace($path, $encoded, $url));
  301. }
  302. /**
  303. * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
  304. * Configure. If Asset.timestamp is true and debug > 0, or Asset.timestamp === 'force'
  305. * a timestamp will be added.
  306. *
  307. * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
  308. * @return string Path with a timestamp added, or not.
  309. */
  310. public function assetTimestamp($path) {
  311. $stamp = Configure::read('Asset.timestamp');
  312. $timestampEnabled = $stamp === 'force' || ($stamp === true && Configure::read('debug') > 0);
  313. if ($timestampEnabled && strpos($path, '?') === false) {
  314. $filepath = preg_replace(
  315. '/^' . preg_quote($this->request->webroot, '/') . '/',
  316. '',
  317. urldecode($path)
  318. );
  319. $webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
  320. if (file_exists($webrootPath)) {
  321. //@codingStandardsIgnoreStart
  322. return $path . '?' . @filemtime($webrootPath);
  323. //@codingStandardsIgnoreEnd
  324. }
  325. $segments = explode('/', ltrim($filepath, '/'));
  326. if ($segments[0] === 'theme') {
  327. $theme = $segments[1];
  328. unset($segments[0], $segments[1]);
  329. $themePath = App::themePath($theme) . 'webroot' . DS . implode(DS, $segments);
  330. //@codingStandardsIgnoreStart
  331. return $path . '?' . @filemtime($themePath);
  332. //@codingStandardsIgnoreEnd
  333. } else {
  334. $plugin = Inflector::camelize($segments[0]);
  335. if (Plugin::loaded($plugin)) {
  336. unset($segments[0]);
  337. $pluginPath = Plugin::path($plugin) . 'webroot' . DS . implode(DS, $segments);
  338. //@codingStandardsIgnoreStart
  339. return $path . '?' . @filemtime($pluginPath);
  340. //@codingStandardsIgnoreEnd
  341. }
  342. }
  343. }
  344. return $path;
  345. }
  346. /**
  347. * Returns a space-delimited string with items of the $options array. If a key
  348. * of $options array happens to be one of those listed in `Helper::$_minimizedAttributes`
  349. *
  350. * And its value is one of:
  351. *
  352. * - '1' (string)
  353. * - 1 (integer)
  354. * - true (boolean)
  355. * - 'true' (string)
  356. *
  357. * Then the value will be reset to be identical with key's name.
  358. * If the value is not one of these 3, the parameter is not output.
  359. *
  360. * 'escape' is a special option in that it controls the conversion of
  361. * attributes to their html-entity encoded equivalents. Set to false to disable html-encoding.
  362. *
  363. * If value for any option key is set to `null` or `false`, that option will be excluded from output.
  364. *
  365. * @param array $options Array of options.
  366. * @param array $exclude Array of options to be excluded, the options here will not be part of the return.
  367. * @param string $insertBefore String to be inserted before options.
  368. * @param string $insertAfter String to be inserted after options.
  369. * @return string Composed attributes.
  370. * @deprecated This method will be moved to HtmlHelper in 3.0
  371. */
  372. protected function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
  373. if (!is_string($options)) {
  374. $options = (array)$options + array('escape' => true);
  375. if (!is_array($exclude)) {
  376. $exclude = array();
  377. }
  378. $exclude = array('escape' => true) + array_flip($exclude);
  379. $escape = $options['escape'];
  380. $attributes = array();
  381. foreach ($options as $key => $value) {
  382. if (!isset($exclude[$key]) && $value !== false && $value !== null) {
  383. $attributes[] = $this->_formatAttribute($key, $value, $escape);
  384. }
  385. }
  386. $out = implode(' ', $attributes);
  387. } else {
  388. $out = $options;
  389. }
  390. return $out ? $insertBefore . $out . $insertAfter : '';
  391. }
  392. /**
  393. * Formats an individual attribute, and returns the string value of the composed attribute.
  394. * Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
  395. *
  396. * @param string $key The name of the attribute to create
  397. * @param string $value The value of the attribute to create.
  398. * @param boolean $escape Define if the value must be escaped
  399. * @return string The composed attribute.
  400. * @deprecated This method will be moved to HtmlHelper in 3.0
  401. */
  402. protected function _formatAttribute($key, $value, $escape = true) {
  403. if (is_array($value)) {
  404. $value = implode(' ', $value);
  405. }
  406. if (is_numeric($key)) {
  407. return sprintf($this->_minimizedAttributeFormat, $value, $value);
  408. }
  409. $truthy = array(1, '1', true, 'true', $key);
  410. $isMinimized = in_array($key, $this->_minimizedAttributes);
  411. if ($isMinimized && in_array($value, $truthy, true)) {
  412. return sprintf($this->_minimizedAttributeFormat, $key, $key);
  413. }
  414. if ($isMinimized) {
  415. return '';
  416. }
  417. return sprintf($this->_attributeFormat, $key, ($escape ? h($value) : $value));
  418. }
  419. /**
  420. * Returns a string to be used as onclick handler for confirm dialogs.
  421. *
  422. * @param string $message Message to be displayed
  423. * @param string $okCode Code to be executed after user chose 'OK'
  424. * @param string $cancelCode Code to be executed after user chose 'Cancel'
  425. * @param array $options Array of options
  426. * @return string onclick JS code
  427. */
  428. protected function _confirm($message, $okCode, $cancelCode = '', $options = array()) {
  429. $message = json_encode($message);
  430. $confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
  431. if (isset($options['escape']) && $options['escape'] === false) {
  432. $confirm = h($confirm);
  433. }
  434. return $confirm;
  435. }
  436. /**
  437. * Sets this helper's model and field properties to the dot-separated value-pair in $entity.
  438. *
  439. * @param string $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
  440. * @param boolean $setScope Sets the view scope to the model specified in $tagValue
  441. * @return void
  442. */
  443. public function setEntity($entity, $setScope = false) {
  444. if ($entity === null) {
  445. $this->_modelScope = false;
  446. }
  447. if ($setScope === true) {
  448. $this->_modelScope = $entity;
  449. }
  450. $parts = array_values(Hash::filter(explode('.', $entity)));
  451. if (empty($parts)) {
  452. return;
  453. }
  454. $count = count($parts);
  455. $lastPart = isset($parts[$count - 1]) ? $parts[$count - 1] : null;
  456. // Either 'body' or 'date.month' type inputs.
  457. if (
  458. ($count === 1 && $this->_modelScope && !$setScope) ||
  459. (
  460. $count === 2 &&
  461. in_array($lastPart, $this->_fieldSuffixes) &&
  462. $this->_modelScope &&
  463. $parts[0] !== $this->_modelScope
  464. )
  465. ) {
  466. $entity = $this->_modelScope . '.' . $entity;
  467. }
  468. // 0.name, 0.created.month style inputs. Excludes inputs with the modelScope in them.
  469. if (
  470. $count >= 2 &&
  471. is_numeric($parts[0]) &&
  472. !is_numeric($parts[1]) &&
  473. $this->_modelScope &&
  474. strpos($entity, $this->_modelScope) === false
  475. ) {
  476. $entity = $this->_modelScope . '.' . $entity;
  477. }
  478. $this->_association = null;
  479. $isHabtm = (
  480. isset($this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type']) &&
  481. $this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type'] === 'multiple'
  482. );
  483. // habtm models are special
  484. if ($count === 1 && $isHabtm) {
  485. $this->_association = $parts[0];
  486. $entity = $parts[0] . '.' . $parts[0];
  487. } else {
  488. // check for associated model.
  489. $reversed = array_reverse($parts);
  490. foreach ($reversed as $i => $part) {
  491. if ($i > 0 && preg_match('/^[A-Z]/', $part)) {
  492. $this->_association = $part;
  493. break;
  494. }
  495. }
  496. }
  497. $this->_entityPath = $entity;
  498. }
  499. /**
  500. * Returns the entity reference of the current context as an array of identity parts
  501. *
  502. * @return array An array containing the identity elements of an entity
  503. */
  504. public function entity() {
  505. return explode('.', $this->_entityPath);
  506. }
  507. /**
  508. * Gets the currently-used model of the rendering context.
  509. *
  510. * @return string
  511. */
  512. public function model() {
  513. if ($this->_association) {
  514. return $this->_association;
  515. }
  516. return $this->_modelScope;
  517. }
  518. /**
  519. * Gets the currently-used model field of the rendering context.
  520. * Strips off field suffixes such as year, month, day, hour, min, meridian
  521. * when the current entity is longer than 2 elements.
  522. *
  523. * @return string
  524. */
  525. public function field() {
  526. $entity = $this->entity();
  527. $count = count($entity);
  528. $last = $entity[$count - 1];
  529. if ($count > 2 && in_array($last, $this->_fieldSuffixes)) {
  530. $last = isset($entity[$count - 2]) ? $entity[$count - 2] : null;
  531. }
  532. return $last;
  533. }
  534. /**
  535. * Generates a DOM ID for the selected element, if one is not set.
  536. * Uses the current View::entity() settings to generate a CamelCased id attribute.
  537. *
  538. * @param array|string $options Either an array of html attributes to add $id into, or a string
  539. * with a view entity path to get a domId for.
  540. * @param string $id The name of the 'id' attribute.
  541. * @return mixed If $options was an array, an array will be returned with $id set. If a string
  542. * was supplied, a string will be returned.
  543. */
  544. public function domId($options = null, $id = 'id') {
  545. if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
  546. unset($options[$id]);
  547. return $options;
  548. } elseif (!is_array($options) && $options !== null) {
  549. $this->setEntity($options);
  550. return $this->domId();
  551. }
  552. $entity = $this->entity();
  553. $model = array_shift($entity);
  554. $dom = $model . implode('', array_map(array('Cake\Utility\Inflector', 'camelize'), $entity));
  555. if (is_array($options) && !array_key_exists($id, $options)) {
  556. $options[$id] = $dom;
  557. } elseif ($options === null) {
  558. return $dom;
  559. }
  560. return $options;
  561. }
  562. /**
  563. * Gets the input field name for the current tag. Creates input name attributes
  564. * using CakePHP's `Model[field]` formatting.
  565. *
  566. * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
  567. * If a string or null, will be used as the View entity.
  568. * @param string $field
  569. * @param string $key The name of the attribute to be set, defaults to 'name'
  570. * @return mixed If an array was given for $options, an array with $key set will be returned.
  571. * If a string was supplied a string will be returned.
  572. */
  573. protected function _name($options = array(), $field = null, $key = 'name') {
  574. if ($options === null) {
  575. $options = array();
  576. } elseif (is_string($options)) {
  577. $field = $options;
  578. $options = 0;
  579. }
  580. if (!empty($field)) {
  581. $this->setEntity($field);
  582. }
  583. if (is_array($options) && array_key_exists($key, $options)) {
  584. return $options;
  585. }
  586. switch ($field) {
  587. case '_method':
  588. $name = $field;
  589. break;
  590. default:
  591. $entity = $this->entity();
  592. $first = array_shift($entity);
  593. $name = $first . ($entity ? '[' . implode('][', $entity) . ']' : '');
  594. break;
  595. }
  596. if (is_array($options)) {
  597. $options[$key] = $name;
  598. return $options;
  599. }
  600. return $name;
  601. }
  602. /**
  603. * Gets the data for the current tag
  604. *
  605. * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
  606. * If a string or null, will be used as the View entity.
  607. * @param string $field
  608. * @param string $key The name of the attribute to be set, defaults to 'value'
  609. * @return mixed If an array was given for $options, an array with $key set will be returned.
  610. * If a string was supplied a string will be returned.
  611. */
  612. public function value($options = array(), $field = null, $key = 'value') {
  613. if ($options === null) {
  614. $options = array();
  615. } elseif (is_string($options)) {
  616. $field = $options;
  617. $options = 0;
  618. }
  619. if (is_array($options) && isset($options[$key])) {
  620. return $options;
  621. }
  622. if (!empty($field)) {
  623. $this->setEntity($field);
  624. }
  625. $result = null;
  626. $data = $this->request->data;
  627. $entity = $this->entity();
  628. if (!empty($data) && is_array($data) && !empty($entity)) {
  629. $result = Hash::get($data, implode('.', $entity));
  630. }
  631. $habtmKey = $this->field();
  632. if (empty($result) && isset($data[$habtmKey][$habtmKey]) && is_array($data[$habtmKey])) {
  633. $result = $data[$habtmKey][$habtmKey];
  634. } elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) {
  635. if (ClassRegistry::isKeySet($habtmKey)) {
  636. $model = ClassRegistry::getObject($habtmKey);
  637. $result = $this->_selectedArray($data[$habtmKey], $model->primaryKey);
  638. }
  639. }
  640. if (is_array($options)) {
  641. if ($result === null && isset($options['default'])) {
  642. $result = $options['default'];
  643. }
  644. unset($options['default']);
  645. }
  646. if (is_array($options)) {
  647. $options[$key] = $result;
  648. return $options;
  649. }
  650. return $result;
  651. }
  652. /**
  653. * Sets the defaults for an input tag. Will set the
  654. * name, value, and id attributes for an array of html attributes.
  655. *
  656. * @param string $field The field name to initialize.
  657. * @param array $options Array of options to use while initializing an input field.
  658. * @return array Array options for the form input.
  659. */
  660. protected function _initInputField($field, $options = array()) {
  661. if ($field !== null) {
  662. $this->setEntity($field);
  663. }
  664. $options = (array)$options;
  665. $options = $this->_name($options);
  666. $options = $this->value($options);
  667. $options = $this->domId($options);
  668. return $options;
  669. }
  670. /**
  671. * Adds the given class to the element options
  672. *
  673. * @param array $options Array options/attributes to add a class to
  674. * @param string $class The classname being added.
  675. * @param string $key the key to use for class.
  676. * @return array Array of options with $key set.
  677. */
  678. public function addClass($options = array(), $class = null, $key = 'class') {
  679. if (isset($options[$key]) && trim($options[$key])) {
  680. $options[$key] .= ' ' . $class;
  681. } else {
  682. $options[$key] = $class;
  683. }
  684. return $options;
  685. }
  686. /**
  687. * Get the View callbacks this helper is interested in.
  688. *
  689. * By defining one of the callback methods a helper is assumed
  690. * to be interested in the related event.
  691. *
  692. * Override this method if you need to add non-conventional event listeners.
  693. * Or if you want helpers to listen to non-standard events.
  694. *
  695. * @return array
  696. */
  697. public function implementedEvents() {
  698. $eventMap = [
  699. 'View.beforeRenderFile' => 'beforeRenderFile',
  700. 'View.afterRenderFile' => 'afterRenderFile',
  701. 'View.beforeRender' => 'beforeRender',
  702. 'View.afterRender' => 'afterRender',
  703. 'View.beforeLayout' => 'beforeLayout',
  704. 'View.afterLayout' => 'afterLayout'
  705. ];
  706. $events = [];
  707. foreach ($eventMap as $event => $method) {
  708. if (method_exists($this, $method)) {
  709. $events[$event] = $method;
  710. }
  711. }
  712. return $events;
  713. }
  714. /**
  715. * Transforms a recordset from a hasAndBelongsToMany association to a list of selected
  716. * options for a multiple select element
  717. *
  718. * @param string|array $data
  719. * @param string $key
  720. * @return array
  721. */
  722. protected function _selectedArray($data, $key = 'id') {
  723. if (!is_array($data)) {
  724. $model = $data;
  725. if (!empty($this->request->data[$model][$model])) {
  726. return $this->request->data[$model][$model];
  727. }
  728. if (!empty($this->request->data[$model])) {
  729. $data = $this->request->data[$model];
  730. }
  731. }
  732. $array = array();
  733. if (!empty($data)) {
  734. foreach ($data as $row) {
  735. if (isset($row[$key])) {
  736. $array[$row[$key]] = $row[$key];
  737. }
  738. }
  739. }
  740. return empty($array) ? null : $array;
  741. }
  742. }