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

/lib/Cake/Network/CakeRequest.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 825 lines | 407 code | 58 blank | 360 comment | 98 complexity | 6ef4849aa6d236062190348c7059ed94 MD5 | raw file
  1. <?php
  2. /**
  3. * CakeRequest
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  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. * @since CakePHP(tm) v 2.0
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. App::uses('Set', 'Utility');
  19. /**
  20. * A class that helps wrap Request information and particulars about a single request.
  21. * Provides methods commonly used to introspect on the request headers and request body.
  22. *
  23. * Has both an Array and Object interface. You can access framework parameters using indexes:
  24. *
  25. * `$request['controller']` or `$request->controller`.
  26. *
  27. * @package Cake.Network
  28. */
  29. class CakeRequest implements ArrayAccess {
  30. /**
  31. * Array of parameters parsed from the url.
  32. *
  33. * @var array
  34. */
  35. public $params = array(
  36. 'plugin' => null,
  37. 'controller' => null,
  38. 'action' => null,
  39. );
  40. /**
  41. * Array of POST data. Will contain form data as well as uploaded files.
  42. * Inputs prefixed with 'data' will have the data prefix removed. If there is
  43. * overlap between an input prefixed with data and one without, the 'data' prefixed
  44. * value will take precedence.
  45. *
  46. * @var array
  47. */
  48. public $data = array();
  49. /**
  50. * Array of querystring arguments
  51. *
  52. * @var array
  53. */
  54. public $query = array();
  55. /**
  56. * The url string used for the request.
  57. *
  58. * @var string
  59. */
  60. public $url;
  61. /**
  62. * Base url path.
  63. *
  64. * @var string
  65. */
  66. public $base = false;
  67. /**
  68. * webroot path segment for the request.
  69. *
  70. * @var string
  71. */
  72. public $webroot = '/';
  73. /**
  74. * The full address to the current request
  75. *
  76. * @var string
  77. */
  78. public $here = null;
  79. /**
  80. * The built in detectors used with `is()` can be modified with `addDetector()`.
  81. *
  82. * There are several ways to specify a detector, see CakeRequest::addDetector() for the
  83. * various formats and ways to define detectors.
  84. *
  85. * @var array
  86. */
  87. protected $_detectors = array(
  88. 'get' => array('env' => 'REQUEST_METHOD', 'value' => 'GET'),
  89. 'post' => array('env' => 'REQUEST_METHOD', 'value' => 'POST'),
  90. 'put' => array('env' => 'REQUEST_METHOD', 'value' => 'PUT'),
  91. 'delete' => array('env' => 'REQUEST_METHOD', 'value' => 'DELETE'),
  92. 'head' => array('env' => 'REQUEST_METHOD', 'value' => 'HEAD'),
  93. 'options' => array('env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'),
  94. 'ssl' => array('env' => 'HTTPS', 'value' => 1),
  95. 'ajax' => array('env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'),
  96. 'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
  97. 'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
  98. 'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone',
  99. 'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
  100. 'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
  101. 'webOS', 'Windows CE', 'Xiino'
  102. ))
  103. );
  104. /**
  105. * Copy of php://input. Since this stream can only be read once in most SAPI's
  106. * keep a copy of it so users don't need to know about that detail.
  107. *
  108. * @var string
  109. */
  110. protected $_input = '';
  111. /**
  112. * Constructor
  113. *
  114. * @param string $url Trimmed url string to use. Should not contain the application base path.
  115. * @param boolean $parseEnvironment Set to false to not auto parse the environment. ie. GET, POST and FILES.
  116. */
  117. public function __construct($url = null, $parseEnvironment = true) {
  118. $this->_base();
  119. if (empty($url)) {
  120. $url = $this->_url();
  121. }
  122. if ($url[0] == '/') {
  123. $url = substr($url, 1);
  124. }
  125. $this->url = $url;
  126. if ($parseEnvironment) {
  127. $this->_processPost();
  128. $this->_processGet();
  129. $this->_processFiles();
  130. }
  131. $this->here = $this->base . '/' . $this->url;
  132. }
  133. /**
  134. * process the post data and set what is there into the object.
  135. * processed data is available at $this->data
  136. *
  137. * @return void
  138. */
  139. protected function _processPost() {
  140. $this->data = $_POST;
  141. if (ini_get('magic_quotes_gpc') === '1') {
  142. $this->data = stripslashes_deep($this->data);
  143. }
  144. if (env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
  145. $this->data['_method'] = env('HTTP_X_HTTP_METHOD_OVERRIDE');
  146. }
  147. if (isset($this->data['_method'])) {
  148. if (!empty($_SERVER)) {
  149. $_SERVER['REQUEST_METHOD'] = $this->data['_method'];
  150. } else {
  151. $_ENV['REQUEST_METHOD'] = $this->data['_method'];
  152. }
  153. unset($this->data['_method']);
  154. }
  155. if (isset($this->data['data'])) {
  156. $data = $this->data['data'];
  157. unset($this->data['data']);
  158. $this->data = Set::merge($this->data, $data);
  159. }
  160. }
  161. /**
  162. * Process the GET parameters and move things into the object.
  163. *
  164. * @return void
  165. */
  166. protected function _processGet() {
  167. if (ini_get('magic_quotes_gpc') === '1') {
  168. $query = stripslashes_deep($_GET);
  169. } else {
  170. $query = $_GET;
  171. }
  172. unset($query['/' . str_replace('.', '_', $this->url)]);
  173. if (strpos($this->url, '?') !== false) {
  174. list(, $querystr) = explode('?', $this->url);
  175. parse_str($querystr, $queryArgs);
  176. $query += $queryArgs;
  177. }
  178. if (isset($this->params['url'])) {
  179. $query = array_merge($this->params['url'], $query);
  180. }
  181. $this->query = $query;
  182. }
  183. /**
  184. * Get the request uri. Looks in PATH_INFO first, as this is the exact value we need prepared
  185. * by PHP. Following that, REQUEST_URI, PHP_SELF, HTTP_X_REWRITE_URL and argv are checked in that order.
  186. * Each of these server variables have the base path, and query strings stripped off
  187. *
  188. * @return string URI The CakePHP request path that is being accessed.
  189. */
  190. protected function _url() {
  191. if (!empty($_SERVER['PATH_INFO'])) {
  192. return $_SERVER['PATH_INFO'];
  193. } elseif (isset($_SERVER['REQUEST_URI'])) {
  194. $uri = $_SERVER['REQUEST_URI'];
  195. } elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
  196. $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
  197. } elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
  198. $uri = $_SERVER['HTTP_X_REWRITE_URL'];
  199. } elseif ($var = env('argv')) {
  200. $uri = $var[0];
  201. }
  202. $base = $this->base;
  203. if (strlen($base) > 0 && strpos($uri, $base) === 0) {
  204. $uri = substr($uri, strlen($base));
  205. }
  206. if (strpos($uri, '?') !== false) {
  207. list($uri) = explode('?', $uri, 2);
  208. }
  209. if (empty($uri) || $uri == '/' || $uri == '//') {
  210. return '/';
  211. }
  212. return $uri;
  213. }
  214. /**
  215. * Returns a base URL and sets the proper webroot
  216. *
  217. * @return string Base URL
  218. */
  219. protected function _base() {
  220. $dir = $webroot = null;
  221. $config = Configure::read('App');
  222. extract($config);
  223. if (!isset($base)) {
  224. $base = $this->base;
  225. }
  226. if ($base !== false) {
  227. $this->webroot = $base . '/';
  228. return $this->base = $base;
  229. }
  230. if (!$baseUrl) {
  231. $base = dirname(env('SCRIPT_NAME'));
  232. if ($webroot === 'webroot' && $webroot === basename($base)) {
  233. $base = dirname($base);
  234. }
  235. if ($dir === 'app' && $dir === basename($base)) {
  236. $base = dirname($base);
  237. }
  238. if ($base === DS || $base === '.') {
  239. $base = '';
  240. }
  241. $this->webroot = $base .'/';
  242. return $this->base = $base;
  243. }
  244. $file = '/' . basename($baseUrl);
  245. $base = dirname($baseUrl);
  246. if ($base === DS || $base === '.') {
  247. $base = '';
  248. }
  249. $this->webroot = $base . '/';
  250. $docRoot = env('DOCUMENT_ROOT');
  251. $docRootContainsWebroot = strpos($docRoot, $dir . '/' . $webroot);
  252. if (!empty($base) || !$docRootContainsWebroot) {
  253. if (strpos($this->webroot, '/' . $dir . '/') === false) {
  254. $this->webroot .= $dir . '/' ;
  255. }
  256. if (strpos($this->webroot, '/' . $webroot . '/') === false) {
  257. $this->webroot .= $webroot . '/';
  258. }
  259. }
  260. return $this->base = $base . $file;
  261. }
  262. /**
  263. * Process $_FILES and move things into the object.
  264. *
  265. * @return void
  266. */
  267. protected function _processFiles() {
  268. if (isset($_FILES) && is_array($_FILES)) {
  269. foreach ($_FILES as $name => $data) {
  270. if ($name != 'data') {
  271. $this->params['form'][$name] = $data;
  272. }
  273. }
  274. }
  275. if (isset($_FILES['data'])) {
  276. foreach ($_FILES['data'] as $key => $data) {
  277. foreach ($data as $model => $fields) {
  278. if (is_array($fields)) {
  279. foreach ($fields as $field => $value) {
  280. if (is_array($value)) {
  281. foreach ($value as $k => $v) {
  282. $this->data[$model][$field][$k][$key] = $v;
  283. }
  284. } else {
  285. $this->data[$model][$field][$key] = $value;
  286. }
  287. }
  288. } else {
  289. $this->data[$model][$key] = $fields;
  290. }
  291. }
  292. }
  293. }
  294. }
  295. /**
  296. * Get the IP the client is using, or says they are using.
  297. *
  298. * @param boolean $safe Use safe = false when you think the user might manipulate their HTTP_CLIENT_IP
  299. * header. Setting $safe = false will will also look at HTTP_X_FORWARDED_FOR
  300. * @return string The client IP.
  301. */
  302. public function clientIp($safe = true) {
  303. if (!$safe && env('HTTP_X_FORWARDED_FOR') != null) {
  304. $ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
  305. } else {
  306. if (env('HTTP_CLIENT_IP') != null) {
  307. $ipaddr = env('HTTP_CLIENT_IP');
  308. } else {
  309. $ipaddr = env('REMOTE_ADDR');
  310. }
  311. }
  312. if (env('HTTP_CLIENTADDRESS') != null) {
  313. $tmpipaddr = env('HTTP_CLIENTADDRESS');
  314. if (!empty($tmpipaddr)) {
  315. $ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
  316. }
  317. }
  318. return trim($ipaddr);
  319. }
  320. /**
  321. * Returns the referer that referred this request.
  322. *
  323. * @param boolean $local Attempt to return a local address. Local addresses do not contain hostnames.
  324. * @return string The referring address for this request.
  325. */
  326. public function referer($local = false) {
  327. $ref = env('HTTP_REFERER');
  328. $forwarded = env('HTTP_X_FORWARDED_HOST');
  329. if ($forwarded) {
  330. $ref = $forwarded;
  331. }
  332. $base = '';
  333. if (defined('FULL_BASE_URL')) {
  334. $base = FULL_BASE_URL . $this->webroot;
  335. }
  336. if (!empty($ref) && !empty($base)) {
  337. if ($local && strpos($ref, $base) === 0) {
  338. $ref = substr($ref, strlen($base));
  339. if ($ref[0] != '/') {
  340. $ref = '/' . $ref;
  341. }
  342. return $ref;
  343. } elseif (!$local) {
  344. return $ref;
  345. }
  346. }
  347. return '/';
  348. }
  349. /**
  350. * Missing method handler, handles wrapping older style isAjax() type methods
  351. *
  352. * @param string $name The method called
  353. * @param array $params Array of parameters for the method call
  354. * @return mixed
  355. * @throws CakeException when an invalid method is called.
  356. */
  357. public function __call($name, $params) {
  358. if (strpos($name, 'is') === 0) {
  359. $type = strtolower(substr($name, 2));
  360. return $this->is($type);
  361. }
  362. throw new CakeException(__d('cake_dev', 'Method %s does not exist', $name));
  363. }
  364. /**
  365. * Magic get method allows access to parsed routing parameters directly on the object.
  366. *
  367. * Allows access to `$this->params['controller']` via `$this->controller`
  368. *
  369. * @param string $name The property being accessed.
  370. * @return mixed Either the value of the parameter or null.
  371. */
  372. public function __get($name) {
  373. if (isset($this->params[$name])) {
  374. return $this->params[$name];
  375. }
  376. return null;
  377. }
  378. /**
  379. * Magic isset method allows isset/empty checks
  380. * on routing parameters.
  381. *
  382. * @param string $name The property being accessed.
  383. * @return bool Existence
  384. */
  385. public function __isset($name) {
  386. return isset($this->params[$name]);
  387. }
  388. /**
  389. * Check whether or not a Request is a certain type. Uses the built in detection rules
  390. * as well as additional rules defined with CakeRequest::addDetector(). Any detector can be called
  391. * as `is($type)` or `is$Type()`.
  392. *
  393. * @param string $type The type of request you want to check.
  394. * @return boolean Whether or not the request is the type you are checking.
  395. */
  396. public function is($type) {
  397. $type = strtolower($type);
  398. if (!isset($this->_detectors[$type])) {
  399. return false;
  400. }
  401. $detect = $this->_detectors[$type];
  402. if (isset($detect['env'])) {
  403. if (isset($detect['value'])) {
  404. return env($detect['env']) == $detect['value'];
  405. }
  406. if (isset($detect['pattern'])) {
  407. return (bool)preg_match($detect['pattern'], env($detect['env']));
  408. }
  409. if (isset($detect['options'])) {
  410. $pattern = '/' . implode('|', $detect['options']) . '/i';
  411. return (bool)preg_match($pattern, env($detect['env']));
  412. }
  413. }
  414. if (isset($detect['callback']) && is_callable($detect['callback'])) {
  415. return call_user_func($detect['callback'], $this);
  416. }
  417. return false;
  418. }
  419. /**
  420. * Add a new detector to the list of detectors that a request can use.
  421. * There are several different formats and types of detectors that can be set.
  422. *
  423. * ### Environment value comparison
  424. *
  425. * An environment value comparison, compares a value fetched from `env()` to a known value
  426. * the environment value is equality checked against the provided value.
  427. *
  428. * e.g `addDetector('post', array('env' => 'REQUEST_METHOD', 'value' => 'POST'))`
  429. *
  430. * ### Pattern value comparison
  431. *
  432. * Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
  433. *
  434. * e.g `addDetector('iphone', array('env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i'));`
  435. *
  436. * ### Option based comparison
  437. *
  438. * Option based comparisons use a list of options to create a regular expression. Subsequent calls
  439. * to add an already defined options detector will merge the options.
  440. *
  441. * e.g `addDetector('mobile', array('env' => 'HTTP_USER_AGENT', 'options' => array('Fennec')));`
  442. *
  443. * ### Callback detectors
  444. *
  445. * Callback detectors allow you to provide a 'callback' type to handle the check. The callback will
  446. * receive the request object as its only parameter.
  447. *
  448. * e.g `addDetector('custom', array('callback' => array('SomeClass', 'somemethod')));`
  449. *
  450. * @param string $name The name of the detector.
  451. * @param array $options The options for the detector definition. See above.
  452. * @return void
  453. */
  454. public function addDetector($name, $options) {
  455. if (isset($this->_detectors[$name]) && isset($options['options'])) {
  456. $options = Set::merge($this->_detectors[$name], $options);
  457. }
  458. $this->_detectors[$name] = $options;
  459. }
  460. /**
  461. * Add parameters to the request's parsed parameter set. This will overwrite any existing parameters.
  462. * This modifies the parameters available through `$request->params`.
  463. *
  464. * @param array $params Array of parameters to merge in
  465. * @return The current object, you can chain this method.
  466. */
  467. public function addParams($params) {
  468. $this->params = array_merge($this->params, (array)$params);
  469. return $this;
  470. }
  471. /**
  472. * Add paths to the requests' paths vars. This will overwrite any existing paths.
  473. * Provides an easy way to modify, here, webroot and base.
  474. *
  475. * @param array $paths Array of paths to merge in
  476. * @return CakeRequest the current object, you can chain this method.
  477. */
  478. public function addPaths($paths) {
  479. foreach (array('webroot', 'here', 'base') as $element) {
  480. if (isset($paths[$element])) {
  481. $this->{$element} = $paths[$element];
  482. }
  483. }
  484. return $this;
  485. }
  486. /**
  487. * Get the value of the current requests url. Will include named parameters and querystring arguments.
  488. *
  489. * @param boolean $base Include the base path, set to false to trim the base path off.
  490. * @return string the current request url including query string args.
  491. */
  492. public function here($base = true) {
  493. $url = $this->here;
  494. if (!empty($this->query)) {
  495. $url .= '?' . http_build_query($this->query);
  496. }
  497. if (!$base) {
  498. $url = preg_replace('/^' . preg_quote($this->base, '/') . '/', '', $url, 1);
  499. }
  500. return $url;
  501. }
  502. /**
  503. * Read an HTTP header from the Request information.
  504. *
  505. * @param string $name Name of the header you want.
  506. * @return mixed Either false on no header being set or the value of the header.
  507. */
  508. public static function header($name) {
  509. $name = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
  510. if (!empty($_SERVER[$name])) {
  511. return $_SERVER[$name];
  512. }
  513. return false;
  514. }
  515. /**
  516. * Get the HTTP method used for this request.
  517. * There are a few ways to specify a method.
  518. *
  519. * - If your client supports it you can use native HTTP methods.
  520. * - You can set the HTTP-X-Method-Override header.
  521. * - You can submit an input with the name `_method`
  522. *
  523. * Any of these 3 approaches can be used to set the HTTP method used
  524. * by CakePHP internally, and will effect the result of this method.
  525. *
  526. * @return string The name of the HTTP method used.
  527. */
  528. public function method() {
  529. return env('REQUEST_METHOD');
  530. }
  531. /**
  532. * Get the host that the request was handled on.
  533. *
  534. * @return void
  535. */
  536. public function host() {
  537. return env('HTTP_HOST');
  538. }
  539. /**
  540. * Get the domain name and include $tldLength segments of the tld.
  541. *
  542. * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  543. * While `example.co.uk` contains 2.
  544. * @return string Domain name without subdomains.
  545. */
  546. public function domain($tldLength = 1) {
  547. $segments = explode('.', $this->host());
  548. $domain = array_slice($segments, -1 * ($tldLength + 1));
  549. return implode('.', $domain);
  550. }
  551. /**
  552. * Get the subdomains for a host.
  553. *
  554. * @param integer $tldLength Number of segments your tld contains. For example: `example.com` contains 1 tld.
  555. * While `example.co.uk` contains 2.
  556. * @return array of subdomains.
  557. */
  558. public function subdomains($tldLength = 1) {
  559. $segments = explode('.', $this->host());
  560. return array_slice($segments, 0, -1 * ($tldLength + 1));
  561. }
  562. /**
  563. * Find out which content types the client accepts or check if they accept a
  564. * particular type of content.
  565. *
  566. * #### Get all types:
  567. *
  568. * `$this->request->accepts();`
  569. *
  570. * #### Check for a single type:
  571. *
  572. * `$this->request->accepts('json');`
  573. *
  574. * This method will order the returned content types by the preference values indicated
  575. * by the client.
  576. *
  577. * @param string $type The content type to check for. Leave null to get all types a client accepts.
  578. * @return mixed Either an array of all the types the client accepts or a boolean if they accept the
  579. * provided type.
  580. */
  581. public function accepts($type = null) {
  582. $raw = $this->parseAccept();
  583. $accept = array();
  584. foreach ($raw as $value => $types) {
  585. $accept = array_merge($accept, $types);
  586. }
  587. if ($type === null) {
  588. return $accept;
  589. }
  590. return in_array($type, $accept);
  591. }
  592. /**
  593. * Parse the HTTP_ACCEPT header and return a sorted array with content types
  594. * as the keys, and pref values as the values.
  595. *
  596. * Generally you want to use CakeRequest::accept() to get a simple list
  597. * of the accepted content types.
  598. *
  599. * @return array An array of prefValue => array(content/types)
  600. */
  601. public function parseAccept() {
  602. $accept = array();
  603. $header = explode(',', $this->header('accept'));
  604. foreach (array_filter($header) as $value) {
  605. $prefPos = strpos($value, ';');
  606. if ($prefPos !== false) {
  607. $prefValue = substr($value, strpos($value, '=') + 1);
  608. $value = trim(substr($value, 0, $prefPos));
  609. } else {
  610. $prefValue = '1.0';
  611. $value = trim($value);
  612. }
  613. if (!isset($accept[$prefValue])) {
  614. $accept[$prefValue] = array();
  615. }
  616. if ($prefValue) {
  617. $accept[$prefValue][] = $value;
  618. }
  619. }
  620. krsort($accept);
  621. return $accept;
  622. }
  623. /**
  624. * Get the languages accepted by the client, or check if a specific language is accepted.
  625. *
  626. * Get the list of accepted languages:
  627. *
  628. * {{{ CakeRequest::acceptLanguage(); }}}
  629. *
  630. * Check if a specific language is accepted:
  631. *
  632. * {{{ CakeRequest::acceptLanguage('es-es'); }}}
  633. *
  634. * @param string $language The language to test.
  635. * @return If a $language is provided, a boolean. Otherwise the array of accepted languages.
  636. */
  637. public static function acceptLanguage($language = null) {
  638. $accepts = preg_split('/[;,]/', self::header('Accept-Language'));
  639. foreach ($accepts as &$accept) {
  640. $accept = strtolower($accept);
  641. if (strpos($accept, '_') !== false) {
  642. $accept = str_replace('_', '-', $accept);
  643. }
  644. }
  645. if ($language === null) {
  646. return $accepts;
  647. }
  648. return in_array($language, $accepts);
  649. }
  650. /**
  651. * Provides a read/write accessor for `$this->data`. Allows you
  652. * to use a syntax similar to `CakeSession` for reading post data.
  653. *
  654. * ## Reading values.
  655. *
  656. * `$request->data('Post.title');`
  657. *
  658. * When reading values you will get `null` for keys/values that do not exist.
  659. *
  660. * ## Writing values
  661. *
  662. * `$request->data('Post.title', 'New post!');`
  663. *
  664. * You can write to any value, even paths/keys that do not exist, and the arrays
  665. * will be created for you.
  666. *
  667. * @param string $name,... Dot separated name of the value to read/write
  668. * @return mixed Either the value being read, or this so you can chain consecutive writes.
  669. */
  670. public function data($name) {
  671. $args = func_get_args();
  672. if (count($args) == 2) {
  673. $this->data = Set::insert($this->data, $name, $args[1]);
  674. return $this;
  675. }
  676. return Set::classicExtract($this->data, $name);
  677. }
  678. /**
  679. * Read data from `php://input`. Useful when interacting with XML or JSON
  680. * request body content.
  681. *
  682. * Getting input with a decoding function:
  683. *
  684. * `$this->request->input('json_decode');`
  685. *
  686. * Getting input using a decoding function, and additional params:
  687. *
  688. * `$this->request->input('Xml::build', array('return' => 'DOMDocument'));`
  689. *
  690. * Any additional parameters are applied to the callback in the order they are given.
  691. *
  692. * @param string $callback A decoding callback that will convert the string data to another
  693. * representation. Leave empty to access the raw input data. You can also
  694. * supply additional parameters for the decoding callback using var args, see above.
  695. * @return The decoded/processed request data.
  696. */
  697. public function input($callback = null) {
  698. $input = $this->_readInput();
  699. $args = func_get_args();
  700. if (!empty($args)) {
  701. $callback = array_shift($args);
  702. array_unshift($args, $input);
  703. return call_user_func_array($callback, $args);
  704. }
  705. return $input;
  706. }
  707. /**
  708. * Read data from php://input, mocked in tests.
  709. *
  710. * @return string contents of php://input
  711. */
  712. protected function _readInput() {
  713. if (empty($this->_input)) {
  714. $fh = fopen('php://input', 'r');
  715. $content = stream_get_contents($fh);
  716. fclose($fh);
  717. $this->_input = $content;
  718. }
  719. return $this->_input;
  720. }
  721. /**
  722. * Array access read implementation
  723. *
  724. * @param string $name Name of the key being accessed.
  725. * @return mixed
  726. */
  727. public function offsetGet($name) {
  728. if (isset($this->params[$name])) {
  729. return $this->params[$name];
  730. }
  731. if ($name == 'url') {
  732. return $this->query;
  733. }
  734. if ($name == 'data') {
  735. return $this->data;
  736. }
  737. return null;
  738. }
  739. /**
  740. * Array access write implementation
  741. *
  742. * @param string $name Name of the key being written
  743. * @param mixed $value The value being written.
  744. * @return void
  745. */
  746. public function offsetSet($name, $value) {
  747. $this->params[$name] = $value;
  748. }
  749. /**
  750. * Array access isset() implementation
  751. *
  752. * @param string $name thing to check.
  753. * @return boolean
  754. */
  755. public function offsetExists($name) {
  756. return isset($this->params[$name]);
  757. }
  758. /**
  759. * Array access unset() implementation
  760. *
  761. * @param string $name Name to unset.
  762. * @return void
  763. */
  764. public function offsetUnset($name) {
  765. unset($this->params[$name]);
  766. }
  767. }