/** * test for Page not found * * @return void */ public function testNotFoundError404() { $this->dispatchUri(uniqid('module') . '/' . uniqid('controller')); $this->assertModule('error'); $this->assertController('index'); $this->assertEquals(Response::getStatusCode(), 404); }
/** * Dispatch module/controllers */ public function testControllerPage() { $this->getApp()->useLayout(false); $this->dispatchRouter('/test/closure/'); $this->assertOk(); $closure = Response::getBody(); $this->assertInstanceOf('\\Closure', $closure); $this->expectOutputRegex('/Closure is back/'); $closure(); }
public function testCreateMusicianError() { $this->dispatchRouter('/musician/crud/', $this->invalidRecord, Http\Request::METHOD_POST); $response = Response::getBody()->toArray(); $error = $response['errors']; $this->assertEquals(count($error), 1); $this->assertEquals('ConcertDate is required', $error['concertDate'][0]); $count = Db::fetchOne('SELECT count(*) FROM musician WHERE nickname = ?', ['uniqNickname']); $this->assertEquals($count, 0); }
/** * Reset layout and Request */ protected static function resetApp() { if (self::$app) { self::$app->useLayout(true); } Proxy\Auth::clearIdentity(); Proxy\Messages::popAll(); Proxy\Request::setInstance(new Http\Request()); Proxy\Response::setInstance(new Http\Response()); Proxy\Response::setPresentation(null); }
/** * {@inheritdoc} * * @param int $offset * @param int $limit * @param array $params * @return array|int|mixed */ public function readSet($offset = 0, $limit = 10, $params = array()) { $select = Db::select('*')->from('test', 't'); if ($limit) { $selectPart = $select->getQueryPart('select'); $selectPart = 'SQL_CALC_FOUND_ROWS ' . current($selectPart); $select->select($selectPart); $select->setLimit($limit); $select->setOffset($offset); } $result = $select->execute('\\Application\\Test\\Row'); if ($limit) { $total = Db::fetchOne('SELECT FOUND_ROWS()'); } else { $total = sizeof($result); } if (sizeof($result) < $total && Request::METHOD_GET == Request::getMethod()) { Response::setStatusCode(206); Response::setHeader('Content-Range', 'items ' . $offset . '-' . ($offset + sizeof($result)) . '/' . $total); } return $result; }
/** * Test Helper Reload * * @expectedException \Bluz\Application\Exception\RedirectException */ public function testHelperReload() { Response::reload(); }
return false; } $datetime1 = new \DateTime(); // now $datetime2 = new \DateTime($actionRow->expired); $interval = $datetime1->diff($datetime2); if ($actionRow->action !== UsersActions\Table::ACTION_ACTIVATION) { Messages::addError('Invalid activation code'); } elseif ($interval->invert) { Messages::addError('The activation code has expired'); $actionRow->delete(); } else { // change user status $userRow = Users\Table::findRow($id); $userRow->status = Users\Table::STATUS_ACTIVE; $userRow->save(); // create user role // get member role $roleRow = Roles\Table::findRowWhere(['name' => Table::BASIC_MEMBER]); // create relation user to role $usersRoleRow = new UsersRoles\Row(); $usersRoleRow->roleId = $roleRow->id; $usersRoleRow->userId = $userRow->id; $usersRoleRow->save(); // remove old code $actionRow->delete(); Messages::addSuccess('Your Account has been successfully activated. <br/>' . 'You can now log in using the username and password you chose during the registration.'); Response::redirectTo('users', 'signin'); } Response::redirectTo('index', 'index'); };
case 406: $title = __("Not Acceptable"); $description = __("The server is not acceptable generating content type described at `Accept` header"); break; case 500: $title = __("Internal Server Error"); $description = __("The server encountered an unexpected condition"); break; case 501: $title = __("Not Implemented"); $description = __("The server does not understand or does not support the HTTP method"); break; case 503: $title = __("Service Unavailable"); $description = __("The server is currently unable to handle the request due to a temporary overloading"); Response::setHeader('Retry-After', '600'); break; default: $title = __("Internal Server Error"); $description = __("An unexpected error occurred with your request. Please try again later"); break; } // check CLI or HTTP request if (Request::isHttp()) { // simple AJAX call, accept JSON if (Request::getAccept(['application/json'])) { $this->useJson(); Messages::addError($description); return null; } // dialog AJAX call, accept HTML
break; default: $code = 500; $title = __("Internal Server Error"); $description = __("An unexpected error occurred with your request. Please try again later"); break; } // check CLI or HTTP request if (Request::isHttp()) { // simple AJAX call, accept JSON if (Request::getAccept() == Request::ACCEPT_JSON) { $this->useJson(); Messages::addError($description); return $view; } // dialog AJAX call, accept HTML if (!Request::isXmlHttpRequest()) { $this->useLayout('small.phtml'); } } Layout::title($title); $view->error = $title; $view->description = $description; if ($this->isDebug() && ($e = Response::getException()) && $code >= 500) { $whoops = new Run(); $whoops->pushHandler(new PrettyPageHandler()); $whoops->handleException($e); return false; } return $view; };
/** * Reset layout and Request */ protected static function resetApp() { if (self::$app) { self::$app->useLayout(true); self::$app->resetRouter(); } Proxy\Auth::clearIdentity(); Proxy\Messages::popAll(); Proxy\Request::setInstance(RequestFactory::fromGlobals()); Proxy\Response::setInstance(new Bluz\Response\Response()); }
/** * Get Response instance * * @api * @return Http\Response */ public function getResponse() { return Response::getInstance(); }
* Grid of Media * * @author Anton Shevchuk */ /** * @namespace */ namespace Application; use Bluz\Proxy\Layout; use Bluz\Proxy\Request; use Bluz\Proxy\Response; return function () use($view) { /** * @var Bootstrap $this * @var \Bluz\View\View $view */ Layout::setTemplate('dashboard.phtml'); Layout::breadCrumbs([$view->ahref('Dashboard', ['dashboard', 'index']), __('Media')]); $grid = new Media\Grid(); $countCol = Request::getParam('countCol'); if ($countCol != null) { Response::setCookie("countCol", $countCol, time() + 3600, '/'); } else { $countCol = Request::getCookie('countCol', 4); } $lnCol = (int) (12 / $countCol); $view->countCol = $countCol; $view->col = $lnCol; $view->grid = $grid; };
/** * PUT request with invalid data should return ERROR and information */ public function testUpdateValidationErrors() { $this->dispatchRouter('/test/crud/', ['id' => 2, 'name' => '123456', 'email' => 'leonardo[at]turtles.ua'], Http\Request::METHOD_PUT); $this->assertNotNull(Response::getBody()->errors); $this->assertEquals(sizeof(Response::getBody()->errors), 2); $this->assertOk(); }
/** * Render, is send Response * * @return void */ public function render() { Response::send(); }
/** * Pre process * @return void */ protected function preProcess() { Router::process(); Response::switchType('CLI'); }
* * @param \Bluz\Crud\Table $crud * @param mixed $primary * @param array $data * @return void|array * @throws BadRequestException * @throws NotImplementedException */ return function ($crud, $primary, $data) { if (!sizeof($data)) { // data not found throw new BadRequestException(); } try { if (!empty($primary)) { // update one item $result = $crud->updateOne($primary, $data); } else { // update collection $result = $crud->updateSet($data); } // if $result === 0 it's means a update is not apply // or records not found if (0 === $result) { Response::setStatusCode(304); } } catch (ValidatorException $e) { Response::setStatusCode(400); return ['errors' => $e->getErrors()]; } };
* @link https://github.com/bluzphp/framework */ /** * @namespace */ namespace Bluz\Application\Helper; use Bluz\Application\Application; use Bluz\Controller\Controller; use Bluz\Proxy\Response; use Bluz\Proxy\Router; /** * Reload helper can be declared inside Bootstrap * @param \Exception $exception * @return Controller */ return function ($exception) { /** * @var Application $this */ Response::removeHeaders(); Response::clearBody(); // cast to valid HTTP error code // 500 - Internal Server Error $statusCode = 100 <= $exception->getCode() && $exception->getCode() <= 505 ? $exception->getCode() : 500; Response::setStatusCode($statusCode); $module = Router::getErrorModule(); $controller = Router::getErrorController(); $params = ['code' => $exception->getCode(), 'message' => $exception->getMessage()]; return $this->dispatch($module, $controller, $params); };
/** * Render with debug headers * @return void */ public function render() { if ($this->debugFlag && !headers_sent()) { $debugString = sprintf("%fsec; %skb", microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], ceil(memory_get_usage() / 1024)); $debugString .= '; ' . Request::getModule() . '/' . Request::getController(); Response::setHeader('Bluz-Debug', $debugString); if ($info = Logger::get('info')) { Response::setHeader('Bluz-Bar', json_encode($info)); } else { Response::setHeader('Bluz-Bar', '{"!":"Logger is disabled"}'); } } parent::render(); }
/** * OPTIONS request should set Allow header */ public function testOptionsSet() { Request::setMethod(Request::METHOD_OPTIONS); $this->processRest(); $this->assertEquals('HEAD,OPTIONS,GET,POST', Response::getHeader('Allow')); }
/** * Test Response Json */ public function testRender() { $this->expectOutputString('foo'); Response::setBody('foo'); $this->getApp()->render(); }
/** * Execute a DOM query * * @param string $path * @return Document\NodeList */ private function query($path) { if (!$this->document) { $this->document = new Document(Response::getBody()); } return Document\Query::execute($path, $this->document, Document\Query::TYPE_CSS); }
public function testLoginSuccess() { $this->dispatchRouter('api/login', ['login' => 'admin', 'password' => 'admin'], 'POST'); $this->assertOk(); $this->assertArrayHasKey('token', Response::getBody()->toArray()); }
/** * Init instance * * @return Instance */ protected static function initInstance() { if ('cli' === PHP_SAPI) { return new Nil(); } else { return new Instance(Response::getInstance()); } }
/** * @return void */ public function finish() { if ($messages = Logger::get('error')) { foreach ($messages as $message) { errorLog($message); } } // return code 1 for invalid behaviour of application if ($exception = Response::getException()) { echo $exception->getMessage(); exit(1); } exit; }
/** * POST request with invalid data should return ERROR and information */ public function testCreateValidationErrors() { $this->dispatchRouter('/test/rest/', ['name' => '', 'email' => ''], Http\Request::METHOD_POST); $this->assertNotNull(Response::getBody()->errors); $this->assertEquals(sizeof(Response::getBody()->errors), 2); $this->assertResponseCode(400); }
/** * Generates cookie for authentication * * @throws \Bluz\Db\Exception\DbException */ public function generateCookie() { $hash = hash('md5', microtime(true)); $ttl = Config::getModuleData('users', 'rememberMe'); $this->delete(['userId' => Auth::getIdentity()->id, 'foreignKey' => Auth::getIdentity()->login, 'provider' => self::PROVIDER_COOKIE, 'tokenType' => self::TYPE_ACCESS]); $row = new Row(); $row->userId = Auth::getIdentity()->id; $row->foreignKey = Auth::getIdentity()->login; $row->provider = self::PROVIDER_COOKIE; $row->tokenType = self::TYPE_ACCESS; $row->expired = gmdate('Y-m-d H:i:s', time() + $ttl); $row->tokenSecret = $this->generateSecret(Auth::getIdentity()->id); $row->token = hash('md5', $row->tokenSecret . $hash); $row->save(); Response::setCookie('rToken', $hash, time() + $ttl, '/'); Response::setCookie('rId', Auth::getIdentity()->id, time() + $ttl, '/'); }
} elseif ($interval->invert) { Messages::addError('The activation code has expired'); $actionRow->delete(); Response::redirectTo('index', 'index'); } else { $user = Users\Table::findRow($id); $this->assign('user', $user); $this->assign('code', $code); if (Request::isPost()) { try { if (empty($password) or empty($password2)) { throw new Exception('Please enter your new password'); } if ($password != $password2) { throw new Exception('Please repeat your new password'); } // remove old auth record if ($oldAuth = Auth\Table::getInstance()->getAuthRow(Auth\Table::PROVIDER_EQUALS, $user->login)) { $oldAuth->delete(); } // create new auth record Auth\Table::getInstance()->generateEquals($user, $password); // show notification and redirect Messages::addSuccess("Your password has been updated"); Response::redirectTo('users', 'signin'); } catch (Exception $e) { Messages::addError($e->getMessage()); } } } };
/** * Method OPTIONS * * @return false */ public function methodOptions() { $allow = $this->getMethods(sizeof($this->primary)); Response::setHeader('Allow', join(',', $allow)); return null; // no body }
$mail->msgHTML(nl2br($body)); $mail->addAddress($email); Mailer::send($mail); Messages::addNotice('Check your email and follow instructions in letter.'); } catch (\Exception $e) { Logger::log('error', $e->getMessage(), ['module' => 'users', 'controller' => 'change-email', 'userId' => $userId]); throw new Exception('Unable to send email. Please contact administrator.'); } // try back to index Response::redirectTo('users', 'profile'); } catch (Exception $e) { Messages::addError($e->getMessage()); $this->assign('email', $email); } catch (AuthException $e) { Messages::addError($e->getMessage()); $this->assign('email', $email); } } elseif ($token) { // process activation $actionRow = UsersActions\Table::findRowWhere(['code' => $token, 'userId' => $userId]); if (!$actionRow) { throw new Exception('Invalid token'); } $params = $actionRow->getParams(); $user->email = $params['email']; $user->save(); $actionRow->delete(); Messages::addSuccess('Email was updated'); Response::redirectTo('users', 'profile'); } };
/** * Check `Method` * * @throws NotAllowedException */ public function checkMethod() { if ($this->getReflection()->getMethod() && !in_array(Request::getMethod(), $this->getReflection()->getMethod())) { Response::setHeader('Allow', join(',', $this->getReflection()->getMethod())); throw new NotAllowedException(); } }