Example of usage use Bluz\Proxy\Request; Request::getParam('foo');
See also: Zend\Diactoros\RequestTrait::getUri()
Author: Anton Shevchuk
Inheritance: use trait ProxyTrait
Beispiel #1
0
 /**
  * get CLI Request
  *
  * @return Cli\Request
  */
 public function initRequest()
 {
     $request = new Cli\Request();
     if ($config = Config::getData('request')) {
         $request->setOptions($config);
     }
     Request::setInstance($request);
 }
Beispiel #2
0
 /**
  * Process Request
  */
 public function testProcessRequest()
 {
     $request = Request::getInstance();
     $request = $request->withQueryParams(['arr-page' => 2, 'arr-limit' => 2, 'arr-order-id' => 'desc', 'arr-filter-name' => 'ne-Smith', 'arr-filter-status' => 'disable']);
     Request::setInstance($request);
     $grid = new ArrayGrid();
     $this->assertEquals(8, $grid->total());
     $this->assertEquals(4, $grid->pages());
 }
Beispiel #3
0
 /**
  * get CLI Request
  * @return void
  * @throws ApplicationException
  */
 public function initRequest()
 {
     $arguments = getopt("u:", ["uri:"]);
     if (!array_key_exists('u', $arguments) && !array_key_exists('uri', $arguments)) {
         throw new ApplicationException('Attribute `--uri` is required');
     }
     $uri = $arguments['u'] ?? $arguments['uri'];
     $request = RequestFactory::fromGlobals(['REQUEST_URI' => $uri, 'REQUEST_METHOD' => 'CLI']);
     Request::setInstance($request);
 }
Beispiel #4
0
 /**
  * Test of params
  */
 public function testParamManipulation()
 {
     Request::setParam('foo', 'bar');
     Request::setParam('baz', 'qux');
     $this->assertEquals('bar', Request::getParam('foo'));
     $this->assertEquals('qux', Request::getParam('baz'));
     $this->assertEquals('moo', Request::getParam('qux', 'moo'));
     $this->assertEqualsArray(['foo' => 'bar', 'baz' => 'qux'], Request::getParams());
     $this->assertEqualsArray(['foo' => 'bar', 'baz' => 'qux'], Request::getAllParams());
 }
Beispiel #5
0
 /**
  * Test run Error Controller
  */
 public function testErrorController()
 {
     // setup Request
     $request = new ServerRequest([], [], uniqid('module') . '/' . uniqid('controller'), Request::METHOD_GET);
     Request::setInstance($request);
     // run Application
     $this->getApp()->process();
     $this->assertEquals(Router::getErrorModule(), $this->getApp()->getModule());
     $this->assertEquals(Router::getErrorController(), $this->getApp()->getController());
 }
Beispiel #6
0
 /**
  * Test run Error Controller
  */
 public function testErrorController()
 {
     // setup Request
     Request::setRequestUri(uniqid('module') . '/' . uniqid('controller'));
     Request::setMethod(Request::METHOD_GET);
     // run Application
     $this->getApp()->process();
     $this->assertEquals(Router::getErrorModule(), $this->getApp()->getModule());
     $this->assertEquals(Router::getErrorController(), $this->getApp()->getController());
 }
Beispiel #7
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);
 }
Beispiel #8
0
 /**
  * Return identity if user agent is correct
  * @api
  * @return EntityInterface|null
  */
 public function getIdentity()
 {
     if (!$this->identity) {
         // check user agent
         if (Session::get('auth:agent') == Request::getServer('HTTP_USER_AGENT')) {
             $this->identity = Session::get('auth:identity');
         } else {
             $this->clearIdentity();
         }
     }
     return $this->identity;
 }
 /**
  * Prepare request for processing
  */
 public function __construct()
 {
     // rewrite REST with "_method" param
     // this is workaround
     $this->method = strtoupper(Request::getParam('_method', Request::getMethod()));
     // get all params
     $query = Request::getQuery();
     if (is_array($query) && !empty($query)) {
         unset($query['_method']);
         $this->params = $query;
     }
     $this->data = Request::getParams();
 }
Beispiel #10
0
 /**
  * Test upload file
  */
 public function testUploadFile()
 {
     // get path from config
     $path = 'uploads/musician';
     if (empty($path)) {
         throw new Exception('Temporary path is not configured');
     }
     $_FILES = array('file' => array('name' => 'test.jpg', 'size' => filesize($path), 'type' => 'image/jpeg', 'tmp_name' => $path, 'error' => 0));
     Request::setFileUpload(new TestFileUpload());
     $this->dispatchUri('media/crud', ['title' => 'test', 'file' => $_FILES['file']], 'POST');
     $this->assertQueryCount('input[name="title"]', 1);
     $this->assertOk();
 }
Beispiel #11
0
 /**
  * {@inheritdoc}
  *
  * @throws NotImplementedException
  * @throws NotFoundException
  * @throws BadRequestException
  * @return mixed
  */
 public function __invoke()
 {
     $primary = $this->getPrimaryKey();
     // switch by method
     switch ($this->method) {
         case Request::METHOD_GET:
             $row = $this->readOne($primary);
             $result = ['row' => $row];
             if (!empty($primary)) {
                 // update form
                 $result['method'] = Request::METHOD_PUT;
             } else {
                 // create form
                 $result['method'] = Request::METHOD_POST;
             }
             break;
         case Request::METHOD_POST:
             try {
                 $result = $this->createOne($this->data);
                 if (!Request::isXmlHttpRequest()) {
                     $row = $this->readOne($result);
                     $result = ['row' => $row, 'method' => Request::METHOD_PUT];
                 }
             } catch (ValidatorException $e) {
                 $row = $this->readOne(null);
                 $row->setFromArray($this->data);
                 $result = ['row' => $row, 'errors' => $e->getErrors(), 'method' => $this->getMethod()];
             }
             break;
         case Request::METHOD_PATCH:
         case Request::METHOD_PUT:
             try {
                 $result = $this->updateOne($primary, $this->data);
                 if (!Request::isXmlHttpRequest()) {
                     $row = $this->readOne($primary);
                     $result = ['row' => $row, 'method' => $this->getMethod()];
                 }
             } catch (ValidatorException $e) {
                 $row = $this->readOne($primary);
                 $row->setFromArray($this->data);
                 $result = ['row' => $row, 'errors' => $e->getErrors(), 'method' => $this->getMethod()];
             }
             break;
         case Request::METHOD_DELETE:
             $result = $this->deleteOne($primary);
             break;
         default:
             throw new NotImplementedException();
     }
     return $result;
 }
Beispiel #12
0
 /**
  * Send body
  *
  * @return void
  */
 protected function sendBody()
 {
     // Nobody for HEAD and OPTIONS
     if (Request::METHOD_HEAD == ProxyRequest::getMethod() || Request::METHOD_OPTIONS == ProxyRequest::getMethod()) {
         return;
     }
     // Body can be Closures
     $content = $this->body;
     if ($content instanceof \Closure) {
         $content();
     } else {
         echo $content;
     }
 }
Beispiel #13
0
 /**
  * createOne
  *
  * @param array $data
  * @throws \Application\Exception
  * @throws \Bluz\Request\RequestException
  * @return integer
  */
 public function createOne($data)
 {
     /**
      * Process HTTP File
      * @var \Bluz\Http\File $file
      */
     $file = Request::getFileUpload()->getFile('file');
     if (!$file or $file->getErrorCode() != UPLOAD_ERR_OK) {
         if ($file->getErrorCode() == UPLOAD_ERR_NO_FILE) {
             throw new Exception("Please choose file for upload");
         }
         throw new Exception("Sorry, I can't receive file");
     }
     /**
      * Generate image name
      */
     $fileName = strtolower(isset($data['title']) ? $data['title'] : $file->getName());
     // Prepare filename
     $fileName = preg_replace('/[ _;:]+/i', '-', $fileName);
     $fileName = preg_replace('/[-]+/i', '-', $fileName);
     $fileName = preg_replace('/[^a-z0-9.-]+/i', '', $fileName);
     // If name is wrong
     if (empty($fileName)) {
         $fileName = date('Y-m-d-His');
     }
     // If file already exists, increment name
     $originFileName = $fileName;
     $counter = 0;
     while (file_exists($this->uploadDir . '/' . $fileName . '.' . $file->getExtension())) {
         $counter++;
         $fileName = $originFileName . '-' . $counter;
     }
     // Setup new name and move to user directory
     $file->setName($fileName);
     $file->moveTo($this->uploadDir);
     $this->uploadDir = substr($this->uploadDir, strlen(PATH_PUBLIC) + 1);
     $data['file'] = $this->uploadDir . '/' . $file->getFullName();
     $data['type'] = $file->getMimeType();
     $row = $this->getTable()->create();
     $row->setFromArray($data);
     return $row->save();
 }
Beispiel #14
0
 /**
  * Response as JSONP
  */
 public function process()
 {
     // override response code so javascript can process it
     $this->response->setHeader('Content-Type', 'application/javascript');
     // prepare body
     if ($body = $this->response->getBody()) {
         // convert to JSON
         $body = json_encode($body);
         // try to guess callback function name
         //  - check `callback` param
         //  - check `jsonp` param
         //  - use `callback` as default callback name
         $callback = Request::getParam('jsonp', Request::getParam('callback', 'callback'));
         $body = $callback . '(' . $body . ')';
         // setup content length
         $this->response->setHeader('Content-Length', strlen($body));
         // prepare to JSON output
         $this->response->setBody($body);
     }
 }
Beispiel #15
0
 /**
  * {@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;
 }
Beispiel #16
0
 /**
  * @param array $data
  * @throws Exception
  * @throws \Bluz\Request\RequestException
  * @return integer
  */
 public function createOne($data)
 {
     /** @var \Bluz\Http\File $file */
     $file = Request::getFileUpload()->getFile('image');
     if (!$file or $file->getErrorCode() != UPLOAD_ERR_OK) {
         if (!$file || $file->getErrorCode() == UPLOAD_ERR_NO_FILE) {
             throw new Exception('Please choose file to upload');
         }
         throw new Exception('Sorry I can`t receive file');
     }
     $filename = $file->getName();
     $name = explode(".", $filename);
     $name[0] = uniqid($name[0]);
     $filename = implode(".", $name);
     $file->setName($filename);
     $file->moveTo($this->uploadDir);
     $data['file'] = $this->uploadDir . '/' . $file->getFullName();
     $data['type'] = $file->getMimeType();
     $row = $this->getTable()->create();
     $row->setFromArray($data);
     return $row->save();
 }
Beispiel #17
0
 /**
  * @param array $data
  * @throws Exception
  * @throws \Bluz\Request\RequestException
  * @return integer
  */
 public function upload()
 {
     /** @var \Bluz\Http\File $file */
     $file = Request::getFileUpload()->getFile('files');
     $type = $file->getType();
     $row = new \Application\MusicianImage\Row();
     $row->getTable()->create();
     $row->setFromArray(['type' => $type]);
     $row->beforeSave();
     $row->afterSave();
     if (!$file or $file->getErrorCode() != UPLOAD_ERR_OK) {
         if (!$file || $file->getErrorCode() == UPLOAD_ERR_NO_FILE) {
             throw new Exception('Please choose file to upload');
         }
         throw new Exception('Sorry I can`t receive file');
     }
     $name = uniqid();
     $filename = $name . "." . $file->getExtension();
     $file->setName($name);
     $file->moveTo($this->uploadDir);
     Session::set('image', $filename);
     return $file;
 }
Beispiel #18
0
 public function createOne()
 {
     //get saved data
     $existFilesData = Session::get('files');
     $files = unserialize($existFilesData);
     //get paths to upload directory
     $path = Config::getModuleData('menu', 'full_path');
     $relativePath = Config::getModuleData('menu', 'relative_path');
     //get new file,that saved in /tmp directory
     $newFileData = Request::getFileUpload()->getFile('files');
     $editor = new Manager($newFileData, $path);
     //validate file name
     $editor->renameFileName();
     //merge new and exist files data
     if ($existFilesData) {
         $fileObjects = $files;
         $fileObjects[uniqid()] = $editor->getFile();
     } else {
         $fileObjects = [uniqid() => $editor->getFile()];
     }
     Session::set('files', serialize($fileObjects));
     $file = $editor->getFile();
     return array('id' => array_search($editor->getFile(), $fileObjects), 'path' => $relativePath . $file->getName() . '.' . $file->getExtension());
 }
Beispiel #19
0
 /**
  * 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());
 }
Beispiel #20
0
 /**
  * Process request
  *
  * Example of request url
  * - http://domain.com/pages/grid/
  * - http://domain.com/pages/grid/page/2/
  * - http://domain.com/pages/grid/page/2/order-alias/desc/
  * - http://domain.com/pages/grid/page/2/order-created/desc/order-alias/asc/
  *
  * with prefix for support more than one grid on page
  * - http://domain.com/users/grid/users-page/2/users-order-created/desc/
  * - http://domain.com/users/grid/users-page/2/users-filter-status/active/
  *
  * hash support
  * - http://domain.com/pages/grid/#/page/2/order-created/desc/order-alias/asc/
  *
  * @return Grid
  */
 public function processRequest()
 {
     $this->module = Request::getModule();
     $this->controller = Request::getController();
     $page = Request::getParam($this->prefix . 'page', 1);
     $this->setPage($page);
     $limit = Request::getParam($this->prefix . 'limit', $this->limit);
     $this->setLimit($limit);
     foreach ($this->allowOrders as $column) {
         $order = Request::getParam($this->prefix . 'order-' . $column);
         if ($order) {
             $this->addOrder($column, $order);
         }
     }
     foreach ($this->allowFilters as $column) {
         $filter = Request::getParam($this->prefix . 'filter-' . $column);
         if ($filter) {
             if (strpos($filter, '-')) {
                 $filter = trim($filter, ' -');
                 while ($pos = strpos($filter, '-')) {
                     $filterType = substr($filter, 0, $pos);
                     $filter = substr($filter, $pos + 1);
                     if (strpos($filter, '-')) {
                         $filterValue = substr($filter, 0, strpos($filter, '-'));
                         $filter = substr($filter, strpos($filter, '-') + 1);
                     } else {
                         $filterValue = $filter;
                     }
                     $this->addFilter($column, $filterType, $filterValue);
                 }
             } else {
                 $this->addFilter($column, self::FILTER_EQ, $filter);
             }
         }
     }
     return $this;
 }
Beispiel #21
0
 /**
  * dispatch URI
  *
  * @param string $uri in format "module/controllers"
  * @param array $params of request
  * @param string $method HTTP
  * @param bool $ajax
  * @return void
  */
 protected function dispatchUri($uri, array $params = null, $method = Http\Request::METHOD_GET, $ajax = false)
 {
     $this->prepareRequest($uri, $params, $method, $ajax);
     $uri = trim($uri, '/ ');
     list($module, $controller) = explode('/', $uri);
     // set default controllers
     if (!$controller) {
         $controller = Request::getController();
     }
     Request::setModule($module);
     Request::setController($controller);
     Request::setRequestUri($uri);
     $this->getApp()->process();
 }
 /**
  * Get Request instance
  *
  * @api
  * @return Http\Request
  */
 public function getRequest()
 {
     return Request::getInstance();
 }
Beispiel #23
0
 * 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;
};
Beispiel #24
0
 /**
  * Process router by default rules
  *
  * Default routers examples
  *     /
  *     /:module/
  *     /:module/:controller/
  *     /:module/:controller/:key1/:value1/:key2/:value2...
  *
  * @return bool
  */
 protected function processRoute()
 {
     $uri = Request::getCleanUri();
     $uri = trim($uri, '/');
     $params = explode('/', $uri);
     if (sizeof($params)) {
         Request::setModule(array_shift($params));
     }
     if (sizeof($params)) {
         Request::setController(array_shift($params));
     }
     if ($size = sizeof($params)) {
         // save raw params
         Request::setRawParams($params);
         // remove tail
         if ($size % 2 == 1) {
             array_pop($params);
             $size = sizeof($params);
         }
         // or use array_chunk and run another loop?
         for ($i = 0; $i < $size; $i = $i + 2) {
             Request::setParam($params[$i], $params[$i + 1]);
         }
     }
     return true;
 }
Beispiel #25
0
            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
        if (!Request::isXmlHttpRequest()) {
            $this->useLayout('small.phtml');
        }
    }
    Layout::title($title);
    return ['error' => $title, 'description' => $description];
};
Beispiel #26
0
 *          description = "Upload images",
 *          required = true,
 *          type="File"
 *      ),
 *      @SWG\ResponseMessage(code=400, message="Invalid file type"),
 *      @SWG\ResponseMessage(code=200, message="File was uploaded")
 *  )
 * )
 */
return function () {
    /**
     * @var Bootstrap $this
     */
    /** @var \Bluz\Http\File $file */
    //if (Request::getFileUpload()->getFile('files')->getType() == 'image') {
    if (Request::getInstance()->isPost()) {
        $upload = new Musician\Upload();
        $path = Config::getModuleData('musician', 'upload_path');
        if (empty($path)) {
            throw new Exception('Upload_path is not configured');
        }
        $upload->setUploadDir($path . "/musician");
        $file = $upload->upload();
        $url = "/uploads/musician/" . $file->getFullName();
        return ['fullName' => $file->getFullName(), 'url' => $url];
    } else {
        return [];
    }
    //  } else {
    //      throw new Exception('Invalid file type');
    //   }
<?php

/**
 *
 *
 * @category Application
 *
 * @author   dark
 * @created  18.12.13 18:39
 */
namespace Application;

use Bluz\Proxy\Request;
return function ($alias) use($module, $controller, $view) {
    /**
     * @var Bootstrap $this
     * @var \Bluz\View\View $view
     */
    var_dump($alias);
    var_dump(Request::getParams());
    var_dump(Request::getAllParams());
    var_dump(Request::getRawParams());
    return false;
};
Beispiel #28
0
<?php

/**
 * Example of forms handle
 *
 * @category Application
 *
 * @author   dark
 * @created  13.12.13 18:12
 */
namespace Application;

use Bluz\Proxy\Layout;
use Bluz\Proxy\Request;
return function ($int, $string, $array, $optional = 0) use($view) {
    /**
     * @var Bootstrap $this
     * @var \Bluz\View\View $view
     */
    Layout::breadCrumbs([$view->ahref('Test', ['test', 'index']), 'Form Example']);
    if (Request::isPost()) {
        ob_start();
        var_dump($int, $string, $array, $optional);
        $view->inside = ob_get_contents();
        ob_end_clean();
        $view->params = Request::getAllParams();
    }
};
Beispiel #29
0
return function ($email = null, $password = null, $token = null) {
    /**
     * @var Controller $this
     */
    // change layout
    $this->useLayout('small.phtml');
    $userId = $this->user() ? $this->user()->id : null;
    /**
     * @var Users\Row $user
     */
    $user = Users\Table::findRow($userId);
    if (!$user) {
        throw new NotFoundException('User not found');
    }
    $this->assign('email', $user->email);
    if (Request::isPost()) {
        // process form
        try {
            if (empty($password)) {
                throw new Exception('Password is empty');
            }
            // login/password
            Auth\Table::getInstance()->checkEquals($user->login, $password);
            // check email for unique
            $emailUnique = Users\Table::findRowWhere(['email' => $email]);
            if ($emailUnique && $emailUnique->id != $userId) {
                throw new Exception('User with email "' . htmlentities($email) . '" already exists');
            }
            // generate change mail token and get full url
            $actionRow = UsersActions\Table::getInstance()->generate($userId, Table::ACTION_CHANGE_EMAIL, 5, ['email' => $email]);
            $changeUrl = Router::getFullUrl('users', 'change-email', ['token' => $actionRow->code]);
Beispiel #30
0
 /**
  * Test FileUpload with three sub key
  */
 public function testFileUploadWithThreeSubKey()
 {
     $_FILES = array('file' => array('name' => array('a' => array('b' => array('test.jpeg', 'test1.jpeg'))), 'size' => array('a' => array('b' => array(filesize($this->path1), filesize($this->path2)))), 'type' => array('a' => array('b' => array('image/jpeg', 'image/jpeg'))), 'tmp_name' => array('a' => array('b' => array($this->path1, $this->path2))), 'error' => array('a' => array('b' => array(0, 0)))));
     $result = Request::getFileUpload()->getFiles('file[a][b]');
     $this->assertNotEmpty($result);
 }