copied code from https://github.com/yiisoft/yii2/pull/3273/files