Controller PHP Class Code Examples

This page contains top rated real world PHP examples of class Controller extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: ControllerTest.php Project: helpfulrobot/camspiers-silverstripe-csp-logging
0
 public function testIndex()
 {
     $logger = $this->getMock('Psr\\Log\\LoggerInterface');
     $logger->expects($this->once())->method('info');
     $controller = new Controller($logger);
     $prop = new \ReflectionProperty(__NAMESPACE__ . '\\Controller', 'response');
     $prop->setAccessible(true);
     $prop->setValue($controller, new \SS_HTTPResponse());
     $req = new \SS_HTTPRequest('GET', '/');
     $req->setBody(<<<JSON

csp-report": {
 "document-uri": "http://example.com/signup.html",
 "referrer": "",
 "blocked-uri": "http://example.com/css/style.css",
 "violated-directive": "style-src cdn.example.com",
 "original-policy": "default-src 'none'; style-src cdn.example.com; report-uri /_/csp-reports"


N

     $response = $controller->index($req);
     $this->assertEquals(204, $response->getStatusCode());
     $this->assertEquals('', $response->getBody());
 }
Example #2
Show file File: ClassloaderTest.php Project: masteramuk/concrete5
0
 public function testUpgradedPackageSrcFiles()
 {
     $env = Environment::get();
     $env->clearOverrideCache();
     require 'fixtures/amazing_power.php';
     $package = new \Concrete\Package\AmazingPower\Controller();
     $loader = ClassLoader::getInstance();
     $loader->registerPackage($package);
     $root = dirname(DIR_BASE_CORE . '../');
     @mkdir($root . '/packages/amazing_power/src/ElectricState/Routing', 0777, true);
     @mkdir($root . '/packages/amazing_power/src/Concrete/Captcha', 0777, true);
     @copy(dirname(__FILE__) . '/fixtures/amazing_power/RouteHelper.php', $root . '/packages/amazing_power/src/ElectricState/Routing/RouteHelper.php');
     @copy(dirname(__FILE__) . '/fixtures/amazing_power/AkismetController.php', $root . '/packages/amazing_power/src/Concrete/Captcha/AkismetController.php');
     $class = overrideable_core_class('\\Captcha\\AkismetController', 'Captcha/AkismetController.php', $package->getPackageHandle());
     $this->assertEquals('\\Concrete\\Package\\AmazingPower\\Captcha\\AkismetController', $class);
     $this->assertTrue(class_exists('\\Concrete\\Package\\AmazingPower\\Captcha\\AkismetController'));
     $this->assertTrue(class_exists('\\ElectricState\\AmazingPower\\Routing\\RouteHelper'));
     @unlink($root . '/packages/amazing_power/src/ElectricState/Routing/RouteHelper.php');
     @unlink($root . '/packages/amazing_power/src/Concrete/Captcha/AkismetController.php');
     @rmdir($root . '/packages/amazing_power/src/ElectricState/Routing');
     @rmdir($root . '/packages/amazing_power/src/ElectricState');
     @unlink($root . '/packages/amazing_power/src/Concrete/Captcha');
     @unlink($root . '/packages/amazing_power/src/Concrete');
     @unlink($root . '/packages/amazing_power/src');
     @unlink($root . '/packages/amazing_power');
 }
Example #3
Show file File: AclShell.php Project: rednazj/Inventory
0
 /**
  * Override startup of the Shell
  *
  * @return void
  */
 public function startup()
 {
     parent::startup();
     if (isset($this->params['connection'])) {
         $this->connection = $this->params['connection'];
     }
     $class = Configure::read('Acl.classname');
     list($plugin, $class) = pluginSplit($class, true);
     App::uses($class, $plugin . 'Controller/Component/Acl');
     if (!in_array($class, array('DbAcl', 'DB_ACL')) && !is_subclass_of($class, 'DbAcl')) {
         $out = "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
         $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
         $out .= "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Current ACL Classname: %s', $class) . "\n";
         $out .= "--------------------------------------------------\n";
         $this->err($out);
         $this->_stop();
     }
     if ($this->command) {
         if (!config('database')) {
             $this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
             $this->args = null;
             return $this->DbConfig->execute();
         }
         require_once APP . 'Config' . DS . 'database.php';
         if (!in_array($this->command, array('initdb'))) {
             $collection = new ComponentCollection();
             $this->Acl = new AclComponent($collection);
             $controller = new Controller();
             $this->Acl->startup($controller);
         }
     }
 }
Example #4
Show file File: ToolbarComponent.php Project: SebFav/ApplicationInternet2
0
 /**
  * Save the current state of the toolbar varibles to the cache file.
  *
  * @param \Controller|object $controller Controller instance
  * @param array $vars Vars to save.
  * @return void
  */
 protected function _saveState(Controller $controller, $vars)
 {
     $config = Cache::config('debug_kit');
     if (empty($config) || !isset($this->panels['history'])) {
         return;
     }
     $history = Cache::read($this->cacheKey, 'debug_kit');
     if (empty($history)) {
         $history = array();
     }
     if (count($history) == $this->panels['history']->history) {
         array_pop($history);
     }
     if (isset($vars['variables']['content'])) {
         // Remove unserializable native objects.
         array_walk_recursive($vars['variables']['content'], function (&$item) {
             if ($item instanceof Closure || $item instanceof PDO || $item instanceof SimpleXmlElement) {
                 $item = 'Unserializable object - ' . get_class($item);
             } elseif ($item instanceof Exception) {
                 $item = sprintf('Unserializable object - %s. Error: %s in %s, line %s', get_class($item), $item, $item->getMessage(), $item->getFile(), $item->getLine());
             }
             return $item;
         });
     }
     unset($vars['history']);
     array_unshift($history, $vars);
     Cache::write($this->cacheKey, $history, 'debug_kit');
 }
Example #5
Show file File: UserController.php Project: renziito/webapp
0
 /**
  * Guarda la foto subida
  */
 public static function actionchangePic()
 {
     $transaction = Yii::app()->db->beginTransaction();
     try {
         $model = ModelUser::model()->findbyPk(Yii::app()->user->id_user);
         $file = CUploadedFile::getInstance($model, 'pic_file');
         if (trim($file) != "") {
             $urlcarpetaFile = Params::Server()->urlImagesUser . Yii::app()->user->id_user . '/';
             $extensionfile = Files::getNombreExtensionFile($file->name);
             $nombrefile = rand(1, 100) . '_' . strtotime("now");
             $urlimagen = $urlcarpetaFile . "/" . $nombrefile . "." . $extensionfile['extension'];
             $model->pic_file = $nombrefile . '.' . $extensionfile['extension'];
             if (!$model->update()) {
                 $er = "<pre>" . json_encode($model->getErrors()) . "</pre>";
                 throw new Exception("No se pudo guardar la información por : {$er}");
             }
             $file->saveAs($urlimagen);
         }
         $transaction->commit();
         Yii::app()->request->redirect(Yii::app()->baseUrl . '/user/account');
     } catch (Exception $ex) {
         $transaction->rollBack();
         $c = new Controller('site');
         $c->render('application.views.site.error', $ex);
     }
 }
Example #6
Show file File: View.php Project: manzapanza/cakephp-api-utils
0
 /**
  * Constructor
  *
  * @param Controller $controller A controller object to pull View::_passedVars from.
  */
 public function __construct(Controller $controller = null)
 {
     if (is_object($controller)) {
         $count = count($this->_passedVars);
         for ($j = 0; $j < $count; $j++) {
             $var = $this->_passedVars[$j];
             $this->{$var} = $controller->{$var};
         }
         $this->_eventManager = $controller->getEventManager();
     }
     if (empty($this->request) && !($this->request = Router::getRequest(true))) {
         $this->request = new CakeRequest(null, false);
         $this->request->base = '';
         $this->request->here = $this->request->webroot = '/';
     }
     if (is_object($controller) && isset($controller->response)) {
         $this->response = $controller->response;
     } else {
         $this->response = new CakeResponse();
     }
     $this->Helpers = new HelperCollection($this);
     $this->Blocks = new ViewBlock();
     $this->loadHelpers();
     parent::__construct();
 }
Example #7
Show file File: SqlLogPanel.php Project: gjcamacho/blog_test
0
 /**
  * Gets the connection names that should have logs + dumps generated.
  *
  * @param Controller $controller The controller.
  * @return array
  */
 public function beforeRender(Controller $controller)
 {
     if (!class_exists('ConnectionManager')) {
         return array();
     }
     $connections = array();
     $dbConfigs = ConnectionManager::sourceList();
     foreach ($dbConfigs as $configName) {
         $driver = null;
         $db = ConnectionManager::getDataSource($configName);
         if (empty($db->config['driver']) && empty($db->config['datasource']) || !method_exists($db, 'getLog')) {
             continue;
         }
         if (isset($db->config['datasource'])) {
             $driver = $db->config['datasource'];
         }
         $explain = false;
         $isExplainable = preg_match('/(Mysql|Postgres)$/', $driver);
         if ($isExplainable) {
             $explain = true;
         }
         $connections[$configName] = $explain;
     }
     return array('connections' => $connections, 'threshold' => $this->slowRate);
 }
Example #8
Show file File: dispatcher.php Project: kenwi/core
0
 /**
  * Handles a request and calls the dispatcher on the controller
  * @param Controller $controller the controller which will be called
  * @param string $methodName the method name which will be called on
  * the controller
  * @return array $array[0] contains a string with the http main header,
  * $array[1] contains headers in the form: $key => value, $array[2] contains
  * the response output
  * @throws \Exception
  */
 public function dispatch(Controller $controller, $methodName)
 {
     $out = array(null, array(), null);
     try {
         // prefill reflector with everything thats needed for the
         // middlewares
         $this->reflector->reflect($controller, $methodName);
         $this->middlewareDispatcher->beforeController($controller, $methodName);
         $response = $this->executeController($controller, $methodName);
         // if an exception appears, the middleware checks if it can handle the
         // exception and creates a response. If no response is created, it is
         // assumed that theres no middleware who can handle it and the error is
         // thrown again
     } catch (\Exception $exception) {
         $response = $this->middlewareDispatcher->afterException($controller, $methodName, $exception);
         if (is_null($response)) {
             throw $exception;
         }
     }
     $response = $this->middlewareDispatcher->afterController($controller, $methodName, $response);
     // depending on the cache object the headers need to be changed
     $out[0] = $this->protocol->getStatusHeader($response->getStatus(), $response->getLastModified(), $response->getETag());
     $out[1] = array_merge($response->getHeaders());
     $out[2] = $response->getCookies();
     $out[3] = $this->middlewareDispatcher->beforeOutput($controller, $methodName, $response->render());
     $out[4] = $response;
     return $out;
 }
Example #9
Show file File: Scaffold.php Project: Vighnesh123/book-a-bus
0
 /**
  * Construct and set up given controller with given parameters.
  *
  * @param Controller $controller Controller to scaffold
  * @param CakeRequest $request Request parameters.
  * @throws MissingModelException
  */
 public function __construct(Controller $controller, CakeRequest $request)
 {
     $this->controller = $controller;
     $count = count($this->_passedVars);
     for ($j = 0; $j < $count; $j++) {
         $var = $this->_passedVars[$j];
         $this->{$var} = $controller->{$var};
     }
     $this->redirect = array('action' => 'index');
     $this->modelClass = $controller->modelClass;
     $this->modelKey = $controller->modelKey;
     if (!is_object($this->controller->{$this->modelClass})) {
         throw new MissingModelException($this->modelClass);
     }
     $this->ScaffoldModel = $this->controller->{$this->modelClass};
     $this->scaffoldTitle = Inflector::humanize(Inflector::underscore($this->viewPath));
     $this->scaffoldActions = $controller->scaffold;
     $title = __d('cake', 'Scaffold :: ') . Inflector::humanize($request->action) . ' :: ' . $this->scaffoldTitle;
     $modelClass = $this->controller->modelClass;
     $primaryKey = $this->ScaffoldModel->primaryKey;
     $displayField = $this->ScaffoldModel->displayField;
     $singularVar = Inflector::variable($modelClass);
     $pluralVar = Inflector::variable($this->controller->name);
     $singularHumanName = Inflector::humanize(Inflector::underscore($modelClass));
     $pluralHumanName = Inflector::humanize(Inflector::underscore($this->controller->name));
     $scaffoldFields = array_keys($this->ScaffoldModel->schema());
     $associations = $this->_associations();
     $this->controller->set(compact('modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar', 'singularHumanName', 'pluralHumanName', 'scaffoldFields', 'associations'));
     $this->controller->set('title_for_layout', $title);
     if ($this->controller->viewClass) {
         $this->controller->viewClass = 'Scaffold';
     }
     $this->_validSession = isset($this->controller->Session) && $this->controller->Session->valid();
     $this->_scaffold($request);
 }
Example #10
Show file File: ControllerTest.php Project: malhan23/assignment-3
0
 /**
  * Tests that the shutdown process calls the correct functions
  *
  * @return void
  */
 public function testShutdownProcess()
 {
     $eventManager = $this->getMock('Cake\\Event\\EventManager');
     $controller = new Controller(null, null, null, $eventManager);
     $eventManager->expects($this->once())->method('dispatch')->with($this->logicalAnd($this->isInstanceOf('Cake\\Event\\Event'), $this->attributeEqualTo('_name', 'Controller.shutdown'), $this->attributeEqualTo('_subject', $controller)))->will($this->returnValue($this->getMock('Cake\\Event\\Event', null, [], '', false)));
     $controller->shutdownProcess();
 }
Example #11
Show file File: RowLevelAclComponent.php Project: saydulk/croogo
0
 /**
  * startup
  */
 public function startup(Controller $controller)
 {
     if (!empty($controller->request->params['pass'][0])) {
         $id = $controller->request->params['pass'][0];
         $this->_rolePermissions($id);
     }
 }
Example #12
Show file File: Composer.php Project: ceko/concrete5-1
0
 /**
  * @param PageType $pt
  * @param \Controller $cnt
  */
 public function addAssetsToRequest(PageType $pt, \Controller $cnt)
 {
     $list = PageTypeComposerControl::getList($pt);
     foreach ($list as $l) {
         $l->addAssetsToRequest($cnt);
     }
 }
Example #13
Show file File: XmlView.php Project: ophilli/Inventory
0
 /**
  * Constructor
  *
  * @param Controller $controller
  */
 public function __construct(Controller $controller = null)
 {
     parent::__construct($controller);
     if (isset($controller->response) && $controller->response instanceof CakeResponse) {
         $controller->response->type('xml');
     }
 }
Example #14
Show file File: AclShell.php Project: julkar9/gss
0
 /**
  * Override startup of the Shell
  *
  * @return void
  */
 public function startup()
 {
     parent::startup();
     if (isset($this->params['connection'])) {
         $this->connection = $this->params['connection'];
     }
     if (!in_array(Configure::read('Acl.classname'), array('DbAcl', 'DB_ACL'))) {
         $out = "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
         $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
         $out .= "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Current ACL Classname: %s', Configure::read('Acl.classname')) . "\n";
         $out .= "--------------------------------------------------\n";
         $this->err($out);
         $this->_stop();
     }
     if ($this->command) {
         if (!config('database')) {
             $this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
             $this->args = null;
             return $this->DbConfig->execute();
         }
         require_once APP . 'Config' . DS . 'database.php';
         if (!in_array($this->command, array('initdb'))) {
             $collection = new ComponentCollection();
             $this->Acl = new AclComponent($collection);
             $controller = new Controller();
             $this->Acl->startup($controller);
         }
     }
 }
Example #15
Show file File: SecurityComponent.php Project: yao-dev/blog-mvc.github.io
0
 /**
  * Check if authentication is required
  *
  * @param Controller $controller Instantiating controller
  * @return bool true if authentication required
  */
 protected function _authRequired(Controller $controller)
 {
     if (is_array($this->_config['requireAuth']) && !empty($this->_config['requireAuth']) && !empty($this->request->data)) {
         $requireAuth = $this->_config['requireAuth'];
         if (in_array($this->request->params['action'], $requireAuth) || $requireAuth == ['*']) {
             if (!isset($controller->request->data['_Token'])) {
                 if (!$this->blackHole($controller, 'auth')) {
                     return false;
                 }
             }
             if ($this->session->check('_Token')) {
                 $tData = $this->session->read('_Token');
                 if (!empty($tData['allowedControllers']) && !in_array($this->request->params['controller'], $tData['allowedControllers']) || !empty($tData['allowedActions']) && !in_array($this->request->params['action'], $tData['allowedActions'])) {
                     if (!$this->blackHole($controller, 'auth')) {
                         return false;
                     }
                 }
             } else {
                 if (!$this->blackHole($controller, 'auth')) {
                     return false;
                 }
             }
         }
     }
     return true;
 }
Example #16
Show file File: ExceptionRenderer.php Project: ophilli/Inventory
0
 /**
  * Get the controller instance to handle the exception.
  * Override this method in subclasses to customize the controller used.
  * This method returns the built in `CakeErrorController` normally, or if an error is repeated
  * a bare controller will be used.
  *
  * @param Exception $exception The exception to get a controller for.
  * @return Controller
  */
 protected function _getController($exception)
 {
     App::uses('AppController', 'Controller');
     App::uses('CakeErrorController', 'Controller');
     if (!($request = Router::getRequest(true))) {
         $request = new CakeRequest();
     }
     $response = new CakeResponse();
     if (method_exists($exception, 'responseHeader')) {
         $response->header($exception->responseHeader());
     }
     try {
         $controller = new CakeErrorController($request, $response);
         $controller->startupProcess();
     } catch (Exception $e) {
         if (!empty($controller) && $controller->Components->enabled('RequestHandler')) {
             $controller->RequestHandler->startup($controller);
         }
     }
     if (empty($controller)) {
         $controller = new Controller($request, $response);
         $controller->viewPath = 'Errors';
     }
     return $controller;
 }
Example #17
Show file File: session.test.php Project: BGCX067/fambom-svn-to-git
0
 /**
  * testFlash method
  *
  * @access public
  * @return void
  */
 function testFlash()
 {
     ob_start();
     $this->Session->flash();
     $result = ob_get_contents();
     ob_clean();
     $expected = '<div id="flashMessage" class="message">This is a calling</div>';
     $this->assertEqual($result, $expected);
     $this->assertFalse($this->Session->check('Message.flash'));
     $expected = '<div id="classyMessage" class="positive">Recorded</div>';
     ob_start();
     $this->Session->flash('classy');
     $result = ob_get_clean();
     $this->assertEqual($result, $expected);
     Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS));
     $controller = new Controller();
     $this->Session->view = new View($controller);
     ob_start();
     $this->Session->flash('notification');
     $result = ob_get_contents();
     ob_clean();
     $result = str_replace("\r\n", "\n", $result);
     $expected = "<div id=\"notificationLayout\">\n\t<h1>Alert!</h1>\n\t<h3>Notice!</h3>\n\t<p>This is a test of the emergency broadcasting system</p>\n</div>";
     $this->assertEqual($result, $expected);
     $this->assertFalse($this->Session->check('Message.notification'));
     ob_start();
     $this->Session->flash('bare');
     $result = ob_get_contents();
     ob_clean();
     $expected = 'Bare message';
     $this->assertEqual($result, $expected);
     $this->assertFalse($this->Session->check('Message.bare'));
 }
Example #18
Show file File: SecurityComponent.php Project: noibilism/nst_portal
0
 /**
  * Calls a controller callback method
  *
  * @param Controller $controller Controller to run callback on
  * @param string $method Method to execute
  * @param array $params Parameters to send to method
  * @return mixed Controller callback method's response
  * @throws BadRequestException When a the blackholeCallback is not callable.
  */
 protected function _callback(Controller $controller, $method, $params = array())
 {
     if (!is_callable(array($controller, $method))) {
         throw new BadRequestException(__d('cake_dev', 'The request has been black-holed'));
     }
     return call_user_func_array(array(&$controller, $method), empty($params) ? null : $params);
 }
Frequently Used Methods