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

/View/Helper/PlaceHelper.php

http://github.com/CakeDC/utils
PHP | 266 lines | 108 code | 26 blank | 132 comment | 10 complexity | 7c6ac8d82ec3d11f7c37575de8af715c MD5 | raw file
Possible License(s): MIT
  1. <?php
  2. /**
  3. * Copyright 2009 - 2013, Cake Development Corporation (http://cakedc.com)
  4. *
  5. * Licensed under The MIT License
  6. * Redistributions of files must retain the above copyright notice.
  7. *
  8. * @copyright Copyright 2009 - 2013, Cake Development Corporation (http://cakedc.com)
  9. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  10. */
  11. App::uses('AppHelper', 'View/Helper');
  12. App::uses('HttpSocket', 'Network/Http');
  13. /**
  14. * Helper for image and text placeholders
  15. *
  16. * @property HtmlHelper $Html
  17. * @package Utils
  18. * @subpackage Utils.View.Helper
  19. */
  20. class PlaceHelper extends AppHelper {
  21. /**
  22. * Used helpers
  23. *
  24. * @var array
  25. */
  26. public $helpers = array('Html');
  27. /**
  28. * Settings, configurable in controller or from view/layout/element
  29. *
  30. * cache - name of cache engine used for caching results of requests to lipsum.com, or false to disable caching
  31. * imageDimensions - array with default width and height for image placeholders
  32. *
  33. * @var array
  34. */
  35. public $settings = array(
  36. 'cache' => 'default',
  37. 'imageDimensions' => array(300, 200),
  38. );
  39. /**
  40. * Array map with URLs of services used for getting image and text placeholders
  41. *
  42. * @var array
  43. */
  44. protected $_urls = array(
  45. 'image' => 'http://placekitten.com/%s/%s',
  46. 'text' => 'http://www.lipsum.com/feed/json?amount=%s&what=%s&start=%s',
  47. );
  48. /**
  49. * Array map with allowed keywords used by lipsum.com service
  50. *
  51. * @var array
  52. */
  53. protected $_lipsumTypes = array(
  54. 'w' => 'words',
  55. 'p' => 'paras',
  56. 'l' => 'lists',
  57. 'b' => 'bytes',
  58. );
  59. /**
  60. * Instance of HttpSocket for accessing lipsum.com
  61. *
  62. * @var HttpSocket
  63. */
  64. protected $_Socket;
  65. /**
  66. * Returns <img> tag with placeholder image from placekitten.com.
  67. *
  68. * Default width and height is configurable in settings['imageDimensions'] array.
  69. *
  70. * @param integer $width image width
  71. * @param integer $height image height
  72. * @param array $options options for HtmlHelper::image()
  73. * @return string
  74. */
  75. public function image($width = null, $height = null, $options = array()) {
  76. $url = $this->_imageUrl($width, $height);
  77. $options = array_merge($options, compact('width', 'height'));
  78. $options['alt'] = isset($options['alt']) ? $options['alt'] : "$width x $height";
  79. return $this->Html->image($url, $options);
  80. }
  81. /**
  82. * Returns 'Lorem Ipsum' text placeholder
  83. *
  84. * ### Options
  85. *
  86. * - `start` If set to false, the generated string will not start with words
  87. * 'Lorem ipsum dolor sit amet...'. Defaults to true.
  88. *
  89. * @param integer $amount amount of units (see $what) to return
  90. * @param string $what allowed identifier - must start with (case insensitive) letter
  91. * used as key in PlaceHelper::$_lipsumTypes map (except for <ol>). Examples:
  92. * p, para, paragraph, paragraphs - returns requested $amount of <p> tags with text
  93. * w, word, words - returns requested $amount of words (not wrapped in any html tag)
  94. * b, byte, bytes - returns text with $amount of bytes (not wrapped in any html tag)
  95. * l, list - returns unordered list with $amount of items
  96. * ol - returns ordered list with $amount of items
  97. * Unknown identifiers (first characters of identifier) defaults to 'l' (unordered list).
  98. * @param array $options options for HtmlHelper::para() or HtmlHelper::nestedList()
  99. * @param array $itemOptions itemOptions for HtmlHelper::nestedList()
  100. * @return string
  101. */
  102. public function text($amount = 1, $what = 'p', $options = array(), $itemOptions = array()) {
  103. $type = $this->_getType($what);
  104. $start = true;
  105. if (isset($options['start'])) {
  106. $start = (bool)$options['start'];
  107. unset($options['start']);
  108. }
  109. $content = $this->_getData($amount, $type, $start);
  110. switch ($type) {
  111. case 'l':
  112. return $this->Html->nestedList($content, $options, $itemOptions, ($what == 'ol') ? 'ol' : 'ul');
  113. case 'p':
  114. foreach ($content as $key => $line) {
  115. $content[$key] = $this->Html->para(null, $line, $options);
  116. }
  117. return implode(PHP_EOL, $content);
  118. }
  119. return array_shift($content);
  120. }
  121. /**
  122. * Returns unique key for placeholder text caching
  123. *
  124. * @param integer $amount amount of units to return
  125. * @param string $type single character, key of PlaceHelper::$_lipsumTypes
  126. * @param boolean $start decides if the generated string should start with words
  127. * 'Lorem ipsum dolor sit amet...'
  128. * @return string
  129. */
  130. protected function _cacheKey($amount, $type, $start) {
  131. $name = __CLASS__;
  132. $start = (string)$start;
  133. return implode('_', compact('name', 'type', 'amount', 'start'));
  134. }
  135. /**
  136. * Decode json response from lipsum.com
  137. *
  138. * @param HttpResponse $response response from lipsum.com
  139. * @param boolean $noCache disables caching in runtime
  140. * @return array
  141. */
  142. protected function _decodeResponse($response, &$noCache) {
  143. if (!$response->isOk()) {
  144. $noCache = true;
  145. return array(__d('Utils', 'Server lipsum.com returns error code %s.', $response->code));
  146. }
  147. if (!empty($response->body)) {
  148. $eol = '__EOL__';
  149. $result = json_decode(str_replace(PHP_EOL, $eol, $response->body));
  150. if (!empty($result->feed->lipsum)) {
  151. return explode($eol, $result->feed->lipsum);
  152. }
  153. }
  154. $noCache = true;
  155. return array(__d('Utils', 'Response from lipsum.com is empty or could not be decoded.'));
  156. }
  157. /**
  158. * Fetches data from lipsum.com and returns them as an array
  159. *
  160. * @param integer $amount amount of units to return
  161. * @param string $type single character, key of PlaceHelper::$_lipsumTypes
  162. * @param boolean $start decides if the generated string should start with words
  163. * 'Lorem ipsum dolor sit amet...'
  164. * @param boolean $noCache disables caching in runtime
  165. * @return array
  166. */
  167. protected function _fetchData($amount, $type, $start, &$noCache) {
  168. if (empty($this->_Socket)) {
  169. $this->_Socket = new HttpSocket();
  170. }
  171. $noCache = false;
  172. $url = $this->_textUrl($amount, $type, $start);
  173. try {
  174. $response = $this->_Socket->get($url);
  175. return $this->_decodeResponse($response, $noCache);
  176. } catch (SocketException $e) {
  177. $noCache = true;
  178. return array(__d('Utils', 'Connection to server lipsum.com failed. %s.', $e->getMessage()));
  179. }
  180. }
  181. /**
  182. * Returns cached or fresh data for text placeholder
  183. *
  184. * @param integer $amount amount of units to return
  185. * @param string $type single character, key of PlaceHelper::$_lipsumTypes
  186. * @param boolean $start decides if the generated string should start with words
  187. * 'Lorem ipsum dolor sit amet...'
  188. * @return array
  189. */
  190. protected function _getData($amount, $type, $start) {
  191. $cache = $this->settings['cache'];
  192. if (empty($cache)) {
  193. return $this->_fetchData($amount, $type, $start, $noCache);
  194. }
  195. $cacheKey = $this->_cacheKey($amount, $type, $start);
  196. $result = Cache::read($cacheKey, $cache);
  197. if (empty($result)) {
  198. $result = $this->_fetchData($amount, $type, $start, $noCache);
  199. if (!$noCache) {
  200. Cache::write($cacheKey, $result, $cache);
  201. }
  202. }
  203. return $result;
  204. }
  205. /**
  206. * Maps text placeholder identifiers to single character.
  207. *
  208. * @param string $what allowed identifier
  209. * @return string
  210. */
  211. protected function _getType($what) {
  212. $key = strtolower(substr($what, 0, 1));
  213. return isset($this->_lipsumTypes[$key]) ? $key : 'l';
  214. }
  215. /**
  216. * Returns url for image placeholder service
  217. *
  218. * @param integer $width image width
  219. * @param integer $height image height
  220. * @return string
  221. */
  222. protected function _imageUrl(&$width, &$height) {
  223. foreach (array('width', 'height') as $key => $var) {
  224. ${$var} = empty(${$var}) ? $this->settings['imageDimensions'][$key] : ${$var};
  225. }
  226. return sprintf($this->_urls['image'], $width, $height);
  227. }
  228. /**
  229. * Returns url for text placeholder service
  230. *
  231. * @param integer $amount amount of units to return
  232. * @param string $type single character, key of PlaceHelper::$_lipsumTypes
  233. * @param boolean $start decides if the generated string should start with words
  234. * 'Lorem ipsum dolor sit amet...'
  235. * @return string
  236. */
  237. protected function _textUrl($amount, $type, $start) {
  238. return sprintf($this->_urls['text'], $amount, $this->_lipsumTypes[$type], ($start ? 'yes' : 'no'));
  239. }
  240. }