1: <?php
2:
3: App::uses('Component', 'Controller');
4: App::uses('Contexts', 'Contexts.Lib');
5:
6: class ContextComponent extends Component {
7:
8: private $currentId;
9:
10: public function __construct(\ComponentCollection $collection, $settings = array()) {
11: parent::__construct($collection,
12: Hash::merge(array(
13: 'id' => false,
14: ), $settings));
15: if (!$this->settings['id']) {
16: throw new Exception("ID de contexto não informado");
17: }
18: }
19:
20: public function initialize(\Controller $controller) {
21: parent::initialize($controller);
22:
23: $this->currentId = Contexts::getContext($this->settings['id'])->getInstanceIdByUrl(
24: $controller->request->params
25: );
26: $this->_checkChangeContext($controller);
27: }
28:
29: private function _checkChangeContext(\Controller $controller) {
30: if (!empty($controller->request->params['named']['changeContextId'])) {
31: $this->_changeContext(
32: $controller
33: , $controller->request->params['named']['changeContextId']);
34: }
35: }
36:
37: private function _changeContext(\Controller $controller, $contextId) {
38: $controller->redirect($this->_changeUrl($controller, $contextId));
39: }
40:
41: private function _changeUrl(\Controller $controller, $contextId) {
42: $url = Router::parse($controller->request->url);
43: unset($url['named']['changeContextId']);
44: $url['pass'][0] = $contextId;
45: $url = array_merge($url['named'], $url['pass'], $url);
46: unset($url['named']);
47: unset($url['pass']);
48: return $url;
49: }
50:
51: public function beforeRender(\Controller $controller) {
52: $controller->set(
53: 'contextCurrentId'
54: , $this->getCurrentId()
55: );
56: $controller->set(
57: 'contextId'
58: , $this->settings['id']
59: );
60: }
61:
62: public function getCurrentId() {
63: return $this->currentId;
64: }
65:
66: }
67: