PageRenderTime 59ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/Croogo/Controller/Component/BaseApiComponent.php

https://github.com/kareypowell/croogo
PHP | 97 lines | 36 code | 15 blank | 46 comment | 4 complexity | 0756590a14a9c0d46784ba13f0f1e2dd MD5 | raw file
  1. <?php
  2. App::uses('Component', 'Controller');
  3. /**
  4. * Base Api Component class
  5. *
  6. * @package Croogo.Croogo.Controller.Component
  7. * @since 1.6
  8. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  9. * @link http://www.croogo.org
  10. */
  11. class BaseApiComponent extends Component {
  12. /**
  13. * Controller instance
  14. */
  15. protected $_controller;
  16. /**
  17. * API Methods
  18. */
  19. protected $_apiMethods = array();
  20. /**
  21. * API Version
  22. */
  23. protected $_apiVersion;
  24. /**
  25. * Route prefix representing the API version
  26. */
  27. protected $_apiVersionPrefix;
  28. /**
  29. * Initialize the component
  30. *
  31. * Setup properties and injects API methods to the controller
  32. * @return void
  33. */
  34. public function initialize(Controller $controller) {
  35. $this->_controller = $controller;
  36. parent::initialize($controller);
  37. $this->_apiVersionPrefix = str_replace('.', '_', $this->_apiVersion);
  38. $methods = $this->_apiMethods;
  39. foreach ($methods as &$method) {
  40. $method = $this->_apiVersionPrefix . '_' . $method;
  41. }
  42. $controller->methods =
  43. array_keys(array_flip($controller->methods) +
  44. array_flip($methods));
  45. }
  46. /**
  47. * Get API version
  48. *
  49. * @return string API Version
  50. */
  51. public function version() {
  52. return $this->_apiVersion;
  53. }
  54. /**
  55. * Verify that current request matches API version this component is serving
  56. *
  57. * @return bool
  58. */
  59. public function isVersionMatched() {
  60. if (!$this->_controller->request || !$this->_controller->request->is('api')) {
  61. return false;
  62. }
  63. $prefix = str_replace('.', '_', $this->_controller->request['prefix']);
  64. return $this->_apiVersionPrefix == $prefix;
  65. }
  66. /**
  67. * Verify that $action exists in the current request
  68. *
  69. * @return bool
  70. */
  71. public function isValidAction($action) {
  72. return $this->isVersionMatched() && in_array($action, $this->_apiMethods);
  73. }
  74. /**
  75. * Get a list of API methods
  76. *
  77. * @return array Array of method names
  78. */
  79. public function apiMethods() {
  80. return $this->_apiMethods;
  81. }
  82. }