Created
July 30, 2017 05:34
-
-
Save meysampg/dbe7418a28b3a6284bd01207904a79b4 to your computer and use it in GitHub Desktop.
A Yii2 Controller With Support of DI on Actions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Created by PhpStorm. | |
| * User: meysampg | |
| * Date: 7/30/17 | |
| * Time: 8:46 AM | |
| */ | |
| namespace app\controllers; | |
| use Yii; | |
| use yii\web\Controller as BaseController; | |
| use yii\web\BadRequestHttpException; | |
| use yii\base\InlineAction; | |
| class Controller extends BaseController | |
| { | |
| /** | |
| * @inheritdoc | |
| */ | |
| public function bindActionParams($action, $params) | |
| { | |
| if ($action instanceof InlineAction) { | |
| $method = new \ReflectionMethod($this, $action->actionMethod); | |
| } else { | |
| $method = new \ReflectionMethod($action, 'run'); | |
| } | |
| $args = []; | |
| $missing = []; | |
| $actionParams = []; | |
| foreach ($method->getParameters() as $param) { | |
| $name = $param->getName(); | |
| if (($class = $param->getClass()) !== null) { | |
| $className = $class->getName(); | |
| if (Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) { | |
| $args[] = $actionParams[$name] = $obj; | |
| }else{ | |
| $args[] = $actionParams[$name] = Yii::$container->get($className); | |
| } | |
| } elseif (array_key_exists($name, $params)) { | |
| if ($param->isArray()) { | |
| $args[] = $actionParams[$name] = (array) $params[$name]; | |
| } elseif (!is_array($params[$name])) { | |
| $args[] = $actionParams[$name] = $params[$name]; | |
| } else { | |
| throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [ | |
| 'param' => $name, | |
| ])); | |
| } | |
| unset($params[$name]); | |
| } elseif ($param->isDefaultValueAvailable()) { | |
| $args[] = $actionParams[$name] = $param->getDefaultValue(); | |
| } else { | |
| $missing[] = $name; | |
| } | |
| } | |
| if (!empty($missing)) { | |
| throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [ | |
| 'params' => implode(', ', $missing), | |
| ])); | |
| } | |
| $this->actionParams = $actionParams; | |
| return $args; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment