Giter Site home page Giter Site logo

yii-web's Introduction

Yii Framework Web Extension


Latest Stable Version Total Downloads Build Status Scrutinizer Quality Score Code Coverage Mutation testing badge static analysis type-coverage

Installation

The package could be installed with composer:

composer require yiisoft/yii-web

General usage

Unit testing

The package is tested with PHPUnit. To run tests:

./vendor/bin/phpunit

Mutation testing

The package tests are checked with Infection mutation framework. To run it:

./vendor/bin/infection

Static analysis

The code is statically analyzed with Psalm. To run static analysis:

./vendor/bin/psalm

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

License

The Yii Framework Web Extension is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

yii-web's People

Contributors

alexkart avatar armpogart avatar charescape avatar damasco avatar denyadzi avatar dependabot-preview[bot] avatar dependabot[bot] avatar devanych avatar fantom409 avatar hstrychalski avatar kamarton avatar mapeveri avatar mister-42 avatar mj4444ru avatar pchapl avatar pistej avatar romkatsu avatar roxblnfk avatar rustamwin avatar samdark avatar tairesh avatar terabytesoftw avatar thenotsoft avatar tomtomsen avatar uniserpl avatar viktorprogger avatar vjik avatar xepozz avatar yiiliveext avatar zhukovra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii-web's Issues

Improvements rendering PHP files

@SamMousa commented on Jul 9, 2018, 10:05 AM UTC:

Currently rendering PHP files is an exception with respect to other files in the View class:

if (isset($this->renderers[$ext])) {
                if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
                    $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
                }
                /* @var $renderer ViewRenderer */
                $renderer = $this->renderers[$ext];
                $output = $renderer->render($this, $viewFile, $params);
            } else {
                $output = $this->renderPhpFile($viewFile, $params);
            }
  1. I propose removing the exception and implementing a PhpRenderer and having a default renderer in the View class.

Currently rendering of PHP files happens inside the object context, this means that the View object itself is available via $this. This makes several tools unhappy, since you're calling $this outside of an objects' context, as far as they can tell.
Since you need to use something like assertions or PHPDoc to type hint the parameters anyway, I feel there could be better ways to make the View object available, for example by naming it $view instead of $this.

  1. Implement PHP file rendering by including the file inside a closure that has a static scope:
$renderer = function() use ($file, $params) {
  extract($params, EXTR_OVERWRITE);
  require $file;
};
$_obInitialLevel_ = ob_get_level();
ob_start();
ob_implicit_flush(false);
try {
    $renderer->bindTo(null)()
    return ob_get_clean();
} catch (\Throwable $e) {
    while (ob_get_level() > $_obInitialLevel_) {
        if (!@ob_end_clean()) {
            ob_clean();
        }
    }
    throw $e;
}

Output buffering is used by the framework to render views widgets among others. Currently PHP file rendering properly checks for output buffer states in error handling, but not in happy flows.

  1. When rendering a PHP file, the rendering could (and should?) always check that the number of nested buffers is the same before and after rendering. If it differs we should either:
  • Throw an error (Clean up your buffers when you're done, Yii is not your mom!)
  • Flush the nested buffers until the nesting level returns to the expected value.

This issue was moved by samdark from yiisoft/yii2#16500.

Check if a param value matches the "int" param type in bindActionParams

What steps will reproduce the problem?

Using php7, have an action with the signature public function actionIndex(int $count): string.
Visit the corresponding action url with a non-numeric $count param, e.g. /site/index?count=test.

What is the expected result?

I think a correct result should be a thrown BadRequestHttpException with a message Invalid data received for parameter "{param}", expected type "{type}"., same as it happens when an array url query param is specified for a non-array action method param, e.g. public function actionIndex(string $name) and the url /site/index?name[0]=test&name[1]=test.

Specifying action params types allows to avoid some errors (and strict typing is always better, right?), but I see an incorrect action method param we get from the url more as a user error (and therefore 400 or maybe 422) than a server error.

I guess int is the only important type we should check for, maybe float too. boolean doesn't require a check since any value can be casted to that type.

What do you get instead?

TypeError server error Argument 1 passed to ... must be of the type integer, string given.

Additional info

Q A
Yii version 2.0.?
PHP version 7.1
Operating system macOS

[yii\base\Request] should have $id field

What steps will reproduce the problem?

Currently if looking at log output that generates thousands of lines per second it is really hard(read: not possible) to distinguish which lines belong to what request

What is the expected result?

each request should have unique identifier(could be UUID, huge random number or whatever) which users can use to distinguish different requests to write log or whatever they want

Additional info

Log output could put this unique identifier before data so that people can distinguish different requests

Separate namespace in $_SESSION for flash messages

Currently the session component uses the "global" session namespace when setting messages:

* @param string $key the key identifying the flash message. Note that flash messages
* and normal session variables share the same name space. If you have a normal
* session variable using the same name, its value will be overwritten by this method.
* 

However there is also the $flashParam configuration.

/**
 * @var string the name of the session variable that stores the flash message data.
 */
 public $flashParam = '__flash';

Would it not make sense to store all messages inside $_SESSION[$flashParam]['messages'] and move the counters to $_SESSION[$flashParam]['counters']?

Just like any name global namespace the session should be kept clean. The session is often part of the attack surface for a web application; reducing the global usage could reduce impact of incorrect usage.

It's a small change that won't affect anyone who is not writing / reading the session directly, which they should not any way.

PS. This is just something I feel could be a small improvement, I do have any usage issues with how it currently works, so if you disagree feel free to close this; no reason to have a lengthy discussion about it :)

PHP Warning: ini_set() has been disabled for security reasons

PHP Warning: ini_set() has been disabled for security reasons in /vendor/yiisoft/yii2/base/ErrorHandler.php on line 60

public function register()
{
        ini_set('display_errors', false);
        // ......
}

can add @ to ignore warning error ?

public function register()
{
        @ini_set('display_errors', false);
        // ......
}

Encrypt and validate session and/or cache data?

Feature idea

Data is vulnerable to theft and modification while it is at rest in a cache or session store and while it is in transit between PHP and that store. Users can reduce vulnerability with cryptographic validation to detect tampering or with encryption+validation incorporated into session/cache read and write handling.

I think Yii could support for these functions so that they are relatively easy to use. The user should need to do little more than configure it and provide a function that returns a key within a specific context (e.g. session context).

Add support for Content-Security-Policy

We should add advanced support for Content-Security-Policy directives:

  • Sign inline scripts using a hash.
  • Only allow scripts that are included via registerJs, registerJsFile.
  • Research what else we should support (CSP has options for framing as well as font loading).
  • Support CSP for asset bundles

jsonp response doesn't display error information.

What steps will reproduce the problem?

When $repsonseFormat is set to Response::FORMAT_JSONP, any exceptions will occur this problem.

What is the expected result?

Erorr infomation formatted to jsonp.

What do you get instead?

An empty 500 response.

Additional info

Q A
Yii version 2.0.9
PHP version 7.0.11
Operating system CentOS 6.5

Cause

Member function renderException in \yii\web\ErrorHandler didn't process $process->data for jsonp format.

Easy bound controller middleware

Goal

Embrace convention for controller routes to simplify RAD-style development.

Idea

$router->addRoute(Route::any('/site/{action}')->to(new WebActionsCaller(SiteController::class));

That would route any URL that starts with /site to a method of SiteController named {action} i.e. /site/index would be routed to

class SiteController
{
    public function site()
    {
    }
}

Issues

  1. Unable to handle URLs like site/update/{id} because router needs to know all the parameters beforehand. In Yii 2 such cases required separate route anyway, so could be left as is.

Move CSRF protection to separate class

The current design of CSRF is spread out over the framework:

  1. yii\web\Request manages the token and does validation.
  2. yii\web\Controller::beforeAction() checks if CSRF is enabled and then tells the request object to perform validation, it then handles the result.
  3. yii\helpers\Html::csrfMetaTags() renders the tags after inspecting if CSRF validation is active in the request object.

I think the following approach would be cleaner:

  1. CSRF is checked by a filter instead of the controller: CsrfFilter, this reduces code coupling in yii\web\controller. Since both the controller and the application have a beforeAction event, the behavior could even be connected to the application to provide application wide CSRF protection.

  2. The CSRF token is managed by a component yii\web\Csrf. This component is responsible for secure generation, masking. It can also register the meta tags with the View component.
    Html::csrfMetaTags() is no longer needed. Html::beginForm() must be updated to use the Csrf component instead of the Request component.

yii\web\User dependend from Yiisoft\Rbac\CheckAccessInterface

yii\web\User require implementation of Yiisoft\Rbac\CheckAccessInterface so it force us to install yii-rbac package even we don't want to use it. Also yii-web has'nt yii-rbac as production dependency, so seems something wrong

Additional info

Q A
Yii version 3.0@dev

VerbFilter provokes potential serious security mistakes

Consider code:

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
                'change-subscription-plan' => ['post'],
            ],
        ],
    ];
}

And for example:

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
                'change-subscrition-plan' => ['post'],
            ],
        ],
    ];
}

In second variation there is typo in action ID change-subscrition-plan. It will be silently ignored. In result action IS NOT restricted. VerbFilter should check existence of providen action ids and if it does not exist it should throws exception. Probably more filters should be checked from that aspect.

Session cookie and yii\web\Request::getCookies()

Related yiisoft/yii2#5480 (comment)

IMO, makes sense to skip session cookie from validation in loadCookies() and include it in CookieCollection - to make retrieving cookies more straightforward.

It is inconvenient to keep in mind that you need different approach to get complete cookies list.
It will only result that everybody will access $_COOKIE directly.

Support PHP7 type hints for action params.

With PHP7 comes type hinting for basic types like int and string.
Yii should support these type hints for action parameters.
For example:

  • Convert numeric strings to appropriate type based on type hint.
  • Throw exception on invalid data just like it does now for array type hints.

This issue is just to have it written down. I am not yet on PHP7 so don't intend to implement this myself.

AJAX mode redirection logic is not RFC conform

The current implementation of redirection logic in AJAX mode is not RFC conform.
In RFC 1945 under 302 Moved Temporarily it says: The URL must be given by the Location field in the response. In RFC 2616 the polite version of it: The temporary URI SHOULD be given by the Location field in the response.

In my case I using axios as http client in my ReactJS app. When I request a action on my Yii2 app which response with a redirect the request will fail. The axios library expects to see a Location header when getting a 302 status code.

As I think that Yii2 is not RFC conform I decided to raise here an issue.

Should I provide a PR for that?
The affected line is this one.

What steps will reproduce the problem?

Consider you have a actions like this:

...
public function actionIndex()
{
   Yii::$app->response->format = 'json';
   return $this->redirect(['site/login']);
}
...

Request it in AJAX mode:

curl -H "X-Requested-With: XMLHttpRequest" -I http://localhost/

What is the expected result?

...
HTTP/1.1 302 Found
Location: http://localhost/login
...

What do you get instead?

...
HTTP/1.1 302 Found
X-Redirect: http://localhost/login
...

Additional info

Q A
Yii version 2.0.13.1
PHP version 7.2.1
Operating system Ubuntu 16.04

Hyphens in module names

What steps will reproduce the problem?

Create a module with camel case in the ID. E.g.: manageUsers
The link should be:
"manage-users" instead of "manageUsers"
"manage-users/user/create" instead of "manageUsers/user/create"

What is the expected result?

Module name in URL should contain hyphens instead of camel case words (just like controllers).

What do you get instead?

Hyphens in the module name don't work.

Additional info

Q A
Yii version 2.0.
PHP version 7.0
Operating system Windows 10

Empty auth key should throw exception

What steps will reproduce the problem?

Create yii2 basic application
Create table users
Generate user class
Add some entities to the table
Add a new column "auth_key" in db - with default null values :)
Implement user model with \yii\web\IdentityInterface for login

What is the expected result?

Throw an Error, anyone has to call the developer, immediately for bad programming practices

What do you get instead?

logged in users will have a null value in their cookies, may leading to security issues

Additional info

Q A
Yii version 2.0.15.1
PHP version 7.0.32
Operating system Ubuntu

Object assigned to a $config key instead plain config

'normalizer' => $this->factory->create([

Why do you assign to 'normalizer' key the object created with $this->factory->create by its configuration?

The configurations should be like this:

        $manager = $this->factory->create([
            '__class' => UrlManager::class,
            'cache' => null,
            'normalizer' => [
                '__class' => UrlNormalizer::class,
                'action' => $normalizerAction,
            ],
        ]);

In main/config.php configuration I could not call $this->factory->create in 'normalizer' key.

Route params shouldn’t modify $_GET or affect getQueryParams()

yii\web\Request::resolve() will merge any route params returned by UrlManager::parseRequest() into $_GET or ($this->_queryParams if Request::setQueryParams() was called).

This feels wrong – Yii shouldn’t be modifying $_GET in any way, and Request::getQueryParams()'s name loses its semantics.

Why can't the route params just be merged with the query params for the resolve() response, but leaving $_GET as-is? For example, that is what we are doing in craft\web\Request::resolve() now: https://github.com/craftcms/cms/blob/139876e7cc064e4be28efe65a9a7ecb20d11864f/src/web/Request.php#L801-L810

CSRF Improvement proposal

I propose storing the CSRF token in LocalStorage instead of a meta tag.
Inside each page we can then add the following javascript snippet to auto update hidden form input elements in case the CSRF token changes from another window:

// Created instead of the meta tag:
localStorage.setItem('yiiCsrfToken', "xyz");

// Allows this window to be notified if the csrf token changes, note that this is pretty cheap performance wise.
window.addEventHandler('storage', function(e) {
    if (e.key === 'yiiCsrfToken') {
        // do some stuff here 
        $('input[name=_csrf]').val(e.newValue);
    } 
});

This will allow for a better session resumption user experience.

This does not tackle the session renewal itself, it just makes sure that when a CSRF token is renewed other windows are kept in sync.

Without any evidence to back it up, it could also resolve some issues like #16200 and #9504.

Same-site Cookies support (new feature discusion)

"Same-site cookies allow servers to mitigate the risk of CSRF and information leakage attacks by asserting that a particular cookie should only be sent with requests initiated from the same registrable domain."

Same-site cookies are implemented in Chrome, coming to Mozilla, and on standard track at IETF.

PHP apps can set same-site cookies by setting the Set-Cookie HTTP header. It seems likely that support for same-site cookies (i.e. an API making it easier to set same-site cookies) will be built into PHP 7.3.

If, as a developer using yii\web\Cookie, I want to set same-site, it makes sense to do it through that API. So I suggest we consider adding it.

I also wonder if it is desirable to add it to Yii's implementation of sessions.

PSR-7 Request/Response immutability

PSR-7 has been accepted for 2.1. However, while PSR interfaces are satisfied by the code the PSR 'spirit' is not.
PSR-7 demands Request and Response classes to be immutable, which means thier internal state can be set only at constructor stage and can not be modified since without creating (cloning) of another object.

@samdark's opinion from yiisoft/yii2#15416 (comment) :

Currently Request serves many responsibilities:

- Filling itself with $_GET, $_POST, $_SERVER etc. considering trusted hosts and trusted headers.
- Storing data obtained and giving it to end user via convenient methods.
- Resolving request into route via resolve() method.
- Generating and setting cookies/tokens for CSRF. Verifying CSRF tokens.

The idea of PSR-7 is immutability and it makes sense in request/response paradigm. After request is received and PSR-7 request object is created, it's set in stone. Attempt to modify it usually means a possible bug.

It makes sens to have multiple classes:

- PSR-7 Request which is data container that serves purpose 2: storing data and having convenient methods for its retrieval. It could be initialized via constructor. There are multiple advantages in having it separate. It's more lightweight. Middlewares don't need to re-parse request same as everything else. Also it will be very convenient in tests.
- Request builder that has methods/settings to prepare data for PSR-7 Request.
- Resolving request data into route isn't request responsibility so should be moved into router (application).
- CSRF protection should be converted into middleware.

This issue depends on #15436 as it require rewise of the way Yii DI creates objects and stores thier configuration.

This issue also affects Yii filters system (e.g. yii\base\ActionFilter descendant) as they may modify Response object in the chain.

Call to a member function allows() on array in AccessControl.php:122

What steps will reproduce the problem?

When executing logout in applications

What is the expected result?

Logout

Additional info

Rules in controller:

	public function behaviors()
	{
		return [
			'access' => [
				'__class' => AccessControl::class,
				'only' => ['logout'],
				'rules' => [
					[
						'actions' => ['logout'],
						'allow' => true,
						'roles' => ['@'],
					],
				],
			],
			'verbs' => [
				'__class' => VerbFilter::class,
				'actions' => [
					'logout' => ['POST'],
				],
			],
		];
	}
2018-12-28 18:12:05 [190.142.158.89][1][l1k039mhme6vo5jnul7hbkf3h5][error][Error] Error: Call to a member function allows() on array in /home/domain.com/public_html/vendor/yiisoft/yii-web/src/filters/AccessControl.php:122
Stack trace:
#0 /home/domain.com/public_html/vendor/yiisoft/yii-core/src/base/ActionFilter.php(77): yii\web\filters\AccessControl->beforeAction(Object(yii\base\InlineAction))
#1 [internal function]: yii\base\ActionFilter->beforeFilter(Object(yii\base\ActionEvent))
#2 /home/domain.com/public_html/vendor/yiisoft/yii-core/src/base/Component.php(642): call_user_func(Array, Object(yii\base\ActionEvent))
#3 /home/domain.com/public_html/vendor/yiisoft/yii-core/src/base/Controller.php(276): yii\base\Component->trigger(Object(yii\base\ActionEvent))
#4 /home/domain.com/public_html/vendor/yiisoft/yii-web/src/Controller.php(367): yii\base\Controller->beforeAction(Object(yii\base\InlineAction))
#5 /home/domain.com/public_html/vendor/yiisoft/yii-core/src/base/Controller.php(158): yii\web\Controller->beforeAction(Object(yii\base\InlineAction))
#6 /home/domain.com/public_html/vendor/yiisoft/yii-core/src/base/Module.php(542): yii\base\Controller->runAction('logout', Array)
#7 /home/domain.com/public_html/vendor/yiisoft/yii-web/src/Application.php(94): yii\base\Module->runAction('site/logout', Array)
#8 /home/domain.com/public_html/vendor/yiisoft/yii-core/src/base/Application.php(544): yii\web\Application->handleRequest(Object(yii\web\Request))
#9 /home/domain.com/public_html/public/index.php(11): yii\base\Application->run()
#10 /home/domain.com/public_html/public/index.php(12): {closure}()
#11 {main}
Fix Instance::ensure, but it still did not work.

    public function init(): void
    {
        parent::init();
        if ($this->user !== false) {
            $this->user = Yii::ensureObject($this->user, User::class);
        }
        foreach ($this->rules as $i => $rule) {
            if (is_array($rule)) {
                $this->rules[$i] = Yii::createObject(array_merge($this->ruleConfig, $rule));
            }
        }
    }
Q A
Yii version 3.0
PHP version 7.1.23
Operating system Centos 7

Pathinfo should not be decoded

In yii\web\Request::resolvePathInfo(), pathinfo has been decoded using urldecode(), which is similar in yii 1.x.

That would be an issue if the url path contains %2f.
For example a url path like /foo/GNU%2fLinux/bar, the pathinfo would become /foo/GNU/Linux/bar, which used for matching url rule.
This may cause some problem when routing.

The code for resolving PathInfo is coming from Zend Framework, but the urldecode behavior has been added later, described in https://code.google.com/p/yii/issues/detail?id=1309
Zend Framework also fixed the similar issue in http://framework.zend.com/issues/browse/ZF-11017

Here are some test cases in Zend Framework for reference:
https://github.com/zendframework/zf1/blob/master/tests/Zend/Controller/Request/HttpTest.php#L988

Make AccessRule::matchIP() public.

Make AccessRule::matchIP() public for external use (not to reimplement in user's code what's already implemented in framework). It would be convenient if it's static and list of ips is passed as parameter (instead of retrieving $this->ips). Therefore in allows() instead of

https://github.com/yiisoft/yii2/blob/ec4509f21c2aa286fbb7aa2f258e561ece05ea38/framework/filters/AccessRule.php#L170

it would be
&& static::matchIP($request->getUserIP(), $this->ips);

Additional info

Q A
Yii version 2.0.15.1?
PHP version 7.1.23

Assets preload

This is just a proposal for discussion of assets preload (https://www.w3.org/TR/preload/).

I've not found any mechanism to implement this option in the current framework release (nothing in View, AssetManager or AssetBundle). Maybe it will make sense to add this option in the future releases? (maybe, something like the other frameworks did, for example https://goo.gl/DH1Ymt)

[RFC] Routing and URL manager

@samdark commented on Dec 14, 2017, 11:41 PM UTC:

Routing in Yii is quite powerful but is different from other frameworks at the same time. It is criticised for the
following:

  • No middleware support.
  • No ability to name routes.
  • No ability to map route to class/method or a callable.
  • No locale support out of the box.

Let's check these and other points one by one.

Middleware support

Middlewares are a good approach to modifying request by a chain of handlers. It's similar to our behavior-based
ActionFilter. There are multiple differences though:

  1. Middlewares are going to have a PSR soon and there are many ready to use ones available via packagist.
  2. Middlewares could be attached to route groups and even to all routes.
  3. They're attached at routing level. Though they're easy to use with callback-based route handlers while action filters
    are controller-specific.

Overall it's good to have it and, I think we need it the next major Yii release.

Abiltiy to name routes

Abiltiy to name routes is very handy when you're using callbacks as handlers. In this case it's not possible to
determine controller/action pair automatically so developer should name route explicitly in order to create it
later.

In case of using controllers it is a good idea to keep our current default of controller/action that proved itself
good.

Abiltiy to map route to class/method or a callable

Yii 2.0 can only map route to contrller action. I've personally seen projects where standalone actions were used
extensively and controller itself was just to hold a config for these. In this case it would've been better to
map routes to actions directly and drop controller.

Locale support out of the box

While there's codemix router for the purpose, it's still a third party extension and since i18n is core Yii feature,
supporting locales out of the box makes sense. It could be implemented through locale middleware.

Vital features of current routing

The following current features should present in new implementation:

  • Ability to create URL by route.
  • Named placeholders.
  • Regular expressions.
  • Custom rule classes.
  • URL normalization.
  • HTTP methods.
  • Default values.
  • Mapping named arguments to handler signature.
  • Route groups (see #12960).

This issue was moved by samdark from yiisoft/yii2#15363.

Support PSR-15 HTTP Middleware

Introduce the suport for PSR-15 HTTP Middleware.

Proposed PSR draft:
https://github.com/php-fig/fig-standards/tree/master/proposed/http-handlers

Unofficial, but widely-used, PSR implementation is the http-interop/http-server-middleware:
https://github.com/http-interop/http-server-middleware

In order to provide the support there should be abilty to setup handlers matching the Psr\Http\Server\MiddlewareInterface:

interface MiddlewareInterface
{
    /**
     * Process an incoming server request and return a response, optionally delegating
     * response creation to a handler.
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     *
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
}

Consider removing HTTP exceptions

HTTP exceptions could be removed for the following reasons:

  1. It is not correct for domain logic or any layer that doesn't deal with request-response to throw HTTP exceptions.
  2. Response is accessible in controller so setting response code there (either manually or by using a shortcut-method) is as easy as throwing HTTP exception.

To start phpunit not in a root directory

What steps will reproduce the problem?

To start phpunit not in a root directory

D:\projects\yii\yii-web\tests>phpunit --configuration ..\phpunit.xml.dist RequestTest.php
You need to set up the project dependencies using Composer

What is the expected result?

Start of the test

What do you get instead?

Show message You need to set up the project dependencies using Composer

Additional info

Q A
Yii version 3.0
PHP version 7.2
Operating system Windows 10 x64

This mistake appeared after change in phpunit.xml.dist
b82f091

getcwd() returns the current path and the path to autoload.php is not correctly formed

Suggestion: defaults property for yii\rest\UrlRule

Please add a defaults property to yii\rest\UrlRule same with yii\web\UrlRule. The property should allow to set up default $_GET parameters which automatically injected to the path always and independently. In yii\rest\UrlRule context it would be add the parameters to all generated rules.

[2.1] Remove supposed IIS workaround from `Request`

@SamMousa commented on Jul 6, 2017, 10:47 AM UTC:

Yii's Request object supports getting the request URI from a header called X-Rewrite-Url.

It's hard to find any documentation, but I think X-Rewrite-Url is not even part of IIS, but of a 3rd party plugin: http://www.helicontech.com/isapi_rewrite/

https://forums.asp.net/post/5807236.aspx

In some modules like http://www.micronovae.com/ModRewrite/ref/XAddOriginalURL.html the name of the header is different.

I think this should be removed from Yii since it is out of scope for an application framework. Instead proper configuration of URL routing can solve most problems.

This issue was moved by samdark from yiisoft/yii2#14400.

The suggestion to Yii2 core team is to design RateLimiter filter good enough not only for API calls, but to make it more reusable in simple controllers.

Here is the use case:

Limit number of API calls globally - 5 requests/second
Limit number of API calls for action1 - 30 requests/minute
Limit number of API calls for action2 - 60 requests/minute

Limit number of successfull user registrations (action /register) - 1/hour
Limit number of failed user logins (action /login) - 5 requests/15 minutes
Add possibility to have 1 shared limit for several actions

Make This With FileCache.

Routing Redirect

Would you consider adding to urlManager 301/302 redirect support for the rules. This way it doesn't have to go to a controller/action of something like a deprecated path to be redirected by that action.

[
   'pattern' => 'some/old/route/',
   'redirect' => 'some/new/route/', // could accept parameters like how the route prop does
   'statusCode' => 301 // optional, but defaults to 301
]

Implement session

  1. Should provide an interface.
  2. Implementations could be native (we can skip it) and something like stateless-token-based that is required in order to be able to use Yii in setups such as RoadRunner or Swoole.

Request/response should be injected in controller, actions and related classes via constructor

Current state

Currently we're working with request/response globally via Yii::$app->request and Yii::$app->response.

Problem

Encapsulation violated. Request and response aren't meant to be dealt with outside of controller and related classes. Accessing them directly and especially doing that in the guide could be easily interpreted like "accessing request anywhere via Yii::$app->request is OK".

Suggested syntax

// old
Yii::$app->request->...
Yii::$app->response->...

// new
$this->request->...
$this->response->...

set_time_limit exception

This line fail when is not possible change max_execution_time (secure mode on shared hosting).

set_time_limit(0); // Reset time limit for big files

this is the Exception:
2018-07-17 17:49:57 [79.152.50.37][1][5a0d110aa5700ad29f45e00b218e02a6][error][yii\base\ErrorException:2] yii\base\ErrorException: set_time_limit() has been disabled for security reasons in /vendor/yiisoft/yii2/web/Response.php:419 Stack trace: #0 /vendor/craftcms/cms/src/web/ErrorHandler.php(84): yii\base\ErrorHandler->handleError(2, 'set_time_limit(...', '/usr/home/affor...', 419) #1 [internal function]: craft\web\ErrorHandler->handleError(2, 'set_time_limit(...', '/usr/home/affor...', 419, Array) #2 /vendor/yiisoft/yii2/web/Response.php(419): set_time_limit(0) #3 /vendor/yiisoft/yii2/web/Response.php(340): yii\web\Response->sendContent() #4 /usr/home/affordablemallorca.com/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response->send() #5 /usr/home/affordablemallorca.com/web/index.php(21): yii\base\Application->run() #6 {main} 2018-07-17 17:49:56 [79.152.50.37][1][5a0d110aa5700ad29f45e00b218e02a6][info][application] $_GET = [ 'p' => 'admin/actions/assets/thumb' 'uid' => '5688258a-a695-4d6f-b1b1-428e8d06b8e8' 'width' => '60' 'height' => '60' 'v' => '1531837664' ]

I had to comment on the line in the project where I have the problem.
Thanks in advance and sorry for my english.

Add support of upload files from base64 encoded inputs

Hi.

Consider a case that you want upload a file in your yii2 rest api as json request. what should we do?
In some cases mobile developer send files in base64 encode format to server.
So i think yii2 should support this feature.

Like as yii\web\UploadedFile we will use something that extend this and implement base 64 or add this to current class.

Q A
Yii version 2.0.13
PHP version 7.1
Operating system windows

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.