Exemple #1
0
 /**
  * @return IPresenterResponse
  */
 public function run(PresenterRequest $request)
 {
     $this->request = $request;
     $httpRequest = $this->context->getByType('IHttpRequest');
     if (!$httpRequest->isAjax() && ($request->isMethod('get') || $request->isMethod('head'))) {
         $refUrl = clone $httpRequest->getUrl();
         $url = $this->context->router->constructUrl($request, $refUrl->setPath($refUrl->getScriptPath()));
         if ($url !== NULL && !$httpRequest->getUrl()->isEqual($url)) {
             return new RedirectResponse($url, IHttpResponse::S301_MOVED_PERMANENTLY);
         }
     }
     $params = $request->getParameters();
     if (!isset($params['callback'])) {
         return;
     }
     $params['presenter'] = $this;
     $callback = new Callback($params['callback']);
     $response = $callback->invokeArgs(PresenterComponentReflection::combineArgs($callback->toReflection(), $params));
     if (is_string($response)) {
         $response = array($response, array());
     }
     if (is_array($response)) {
         if ($response[0] instanceof SplFileInfo) {
             $response = $this->createTemplate('FileTemplate')->setParameters($response[1])->setFile($response[0]);
         } else {
             $response = $this->createTemplate('Template')->setParameters($response[1])->setSource($response[0]);
         }
     }
     if ($response instanceof ITemplate) {
         return new TextResponse($response);
     } else {
         return $response;
     }
 }
Exemple #2
0
 public function mockModel($route)
 {
     $file = DIR_APPLICATION . 'model/' . $route . '.php';
     $class = 'Model' . preg_replace('/[^a-zA-Z0-9]/', '', $route);
     if (file_exists($file)) {
         include_once $file;
         $di = new DIContainer($this->registry);
         foreach (get_class_methods($class) as $method) {
             $di->attach($method, $this->closure($route));
         }
         return $di;
     } else {
         return false;
     }
 }
Exemple #3
0
 public function redirect($url)
 {
     $request = DIContainer::build('request');
     header('Referer: ' . $request->getURI());
     header('Location: ' . $url, false, 301);
     die;
 }
Exemple #4
0
 /**
  * Create new presenter instance.
  * @param  string  presenter name
  * @return IPresenter
  */
 public function createPresenter($name)
 {
     $presenter = $this->container->createInstance($this->getPresenterClass($name));
     if (method_exists($presenter, 'setContext')) {
         $this->container->callMethod(array($presenter, 'setContext'));
     }
     foreach (array_reverse(get_class_methods($presenter)) as $method) {
         if (substr($method, 0, 6) === 'inject') {
             $this->container->callMethod(array($presenter, $method));
         }
     }
     if ($presenter instanceof Presenter && $presenter->invalidLinkMode === NULL) {
         $presenter->invalidLinkMode = $this->container->parameters['debugMode'] ? Presenter::INVALID_LINK_WARNING : Presenter::INVALID_LINK_SILENT;
     }
     return $presenter;
 }
Exemple #5
0
 public function processServices()
 {
     $this->parseServices($this->container, $this->config);
     foreach ($this->extensions as $name => $extension) {
         $this->container->addDefinition($name)->setClass('DINestedAccessor', array('@container', $name))->setAutowired(FALSE);
         if (isset($this->config[$name])) {
             $this->parseServices($this->container, $this->config[$name], $name);
         }
     }
     foreach ($this->container->getDefinitions() as $name => $def) {
         $factory = $name . 'Factory';
         if (!$def->shared && !$def->internal && !$this->container->hasDefinition($factory)) {
             $this->container->addDefinition($factory)->setClass('Callback', array('@container', DIContainer::getMethodName($name, FALSE)))->setAutowired(FALSE)->tags = $def->tags;
         }
     }
 }
Exemple #6
0
 /**
  * Run controller action
  *
  * @param $controller
  * @param $action
  * @param null $params
  * @return Response|mixed|null
  */
 public function runControllerAction($controller, $action, $params = null)
 {
     $result = null;
     try {
         if (class_exists($controller)) {
             $action = $action . 'Action';
             $param_values = $params;
             $meta_controller = new \ReflectionClass($controller);
             if ($meta_controller->hasMethod($action)) {
                 $method = new \ReflectionMethod($controller, $action);
                 $params = $method->getParameters();
                 $response = empty($params) ? $method->invoke(DIContainer::build($controller)) : $method->invokeArgs(DIContainer::build($controller), $param_values);
                 $result = $response;
             }
         } else {
             throw new \Exception(self::ROUTE_NOT_FOUND, 404);
         }
     } catch (\Exception $e) {
         $result = $this->renderError($e);
     }
     return $result;
 }
Exemple #7
0
<?php

include_once dirname(__FILE__) . '/DIContainer1.php';
class MyComponentFactory extends ComponentFactory
{
    function buildConfig()
    {
        $config = new stdClass();
        $config->db = 'mysql';
        $config->dbname = 'scalr';
        $config->host = 'localhost';
        $config->user = '******';
        $config->password = '';
        return $config;
    }
    function buildPDO()
    {
        $config = $this->container->get('config');
        $dsn = "{$config->db}:dbname={$config->dbname};host={$config->host}";
        $pdo = new PDO($dsn, $config->user, $config->password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    }
}
$container = new DIContainer(new MyComponentFactory());
// オブジェクトをコンテナから取り出す
$pdo = $container->get('pdo');
Exemple #8
0
 /**
  * @return bool
  */
 public function __isset($name)
 {
     return $this->container->hasService($this->namespace . $name);
 }
Exemple #9
0
 /**
  * Does the service exist?
  * @param  string service name
  * @return bool
  */
 public function hasService($name)
 {
     return isset($this->registry[$name]) || isset($this->factories[$name]) || method_exists($this, $method = DIContainer::getMethodName($name)) && $this->getReflection()->getMethod($method)->getName() === $method;
 }
Exemple #10
0
 /**
  * Render data
  *
  * @param $view
  * @param array $data
  * @return string
  */
 public static function renderIt($view, array $data)
 {
     self::$_layout = $view;
     self::$_data = !empty($data) ? $data : array();
     $router = DIContainer::build('router');
     $app = DIContainer::build('app');
     $config = DIContainer::build('config');
     $funCurRoute = $router->findRoute();
     $funGetRoute = function ($route_name, $params = null) use($router) {
         return $router->generateRoute($route_name, $params);
     };
     $funDoAction = function ($class_name, $action, $params) use($app) {
         $response = $app->runControllerAction($class_name, $action, $params);
         if (is_object($response)) {
             $response->send();
         }
     };
     $funGetImg = function ($img) {
         $default_img = '/img/phone.png';
         return !empty($img) && getimagesize($img) ? $img : $default_img;
     };
     $data = array_merge($data, array('config' => $config, 'getRoute' => $funGetRoute, 'include' => $funDoAction, 'route' => $funCurRoute, 'getImg' => $funGetImg, 'isAjax' => self::isAjax()));
     ob_start();
     extract(self::$_data);
     extract($data);
     include self::$_layout;
     $result = ob_get_clean();
     return $result;
 }
Exemple #11
0
     * @param array $arguments 引数
     */
    public function __call($name, $arguments)
    {
        $callback = array($this->delegate, $name);
        if (!is_callable($callback)) {
            throw new Exception("Call to undefined method " . __CLASS__ . "::" . $name . "()");
        }
        return call_user_func_array($callback, $arguments);
    }
    /**
     * データベース接続設定を設定し、新しいPDOオブジェクトを生成します。
     *
     * @param array $config データベース接続設定
     */
    public function setConfig($config)
    {
        $dsn = $config['db'] . ':dbname=' . $config['dbname'] . ';host=' . $config['host'];
        $this->delegate = new PDO($dsn, $config['user'], $config['password']);
        $this->delegate->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
}
// テスト時のデータベース接続設定
$test_config = new ArrayObject(array('db' => 'mysql', 'dbname' => 'hoge_test', 'host' => 'localhost', 'user' => 'dbusername', 'password' => 'dbpassword'));
// 本番稼働時のデータベース接続設定
$prod_config = new ArrayObject(array('db' => 'mysql', 'dbname' => 'hoge_prod', 'host' => 'localhost', 'user' => 'dbusername', 'password' => 'dbpassword'));
$container = new DIContainer();
$container->add('config', getenv('TEST') ? $test_config : $prod_config);
$container->add('pdo', new PDOComponent());
// オブジェクトをコンテナから取り出す
$pdo = $container->get('pdo');
Exemple #12
0
 /**
  * Find route
  *
  * @param Request|null $uri
  * @return array|null
  */
 public function findRoute($uri = null)
 {
     $uri = empty($uri) ? $this->getRequest()->getURI() : $uri;
     $result_route = null;
     foreach ($this->getRoutes() as $name => $route_config) {
         $pattern = $route_config['pattern'];
         $pattern = str_replace('/', '\\/', $pattern);
         $params = array();
         if (isset($route_config['params'])) {
             foreach ($route_config['params'] as $key => $value) {
                 $search = "{" . $key . "}";
                 $pattern = str_replace($search, '(' . $value . ')', $pattern);
                 $params[$key] = $value;
             }
         }
         if (preg_match('/^' . $pattern . '$/', $uri, $matches)) {
             $full_action = isset($route_config['action']) ? $route_config['action'] : self::DEFAULT_CONTROLLER . '#' . self::DEFAULT_ACTION;
             list($controller, $action) = explode('#', $full_action);
             $result_route = array('controller' => $controller, 'action' => $action);
             $result_route['name'] = $name;
             array_shift($matches);
             $params = array_combine(array_keys($params), $matches);
             $result_route['params'] = !empty($params) ? $params : null;
         }
     }
     if (DIContainer::build('config')['debug']) {
         error_log('>>> ROUTE > ctrl > ' . (isset($result_route['controller']) ? $result_route['controller'] : '') . ' > action >' . (isset($result_route['action']) ? $result_route['action'] : '') . ' > params > ' . (isset($result_route['params']) ? serialize($result_route['params']) : ''));
     }
     return $result_route;
 }
Exemple #13
0
 /**
  * @return User
  */
 public function getUser()
 {
     return $this->context->getByType('User');
 }
Exemple #14
0
 /**
  * Formats PHP code for class instantiating, function calling or property setting in PHP.
  * @return string
  * @internal
  */
 public function formatStatement(DIStatement $statement, $self = NULL)
 {
     $entity = $this->normalizeEntity($statement->entity);
     $arguments = $statement->arguments;
     if (is_string($entity) && Strings::contains($entity, '?')) {
         // PHP literal
         return $this->formatPhp($entity, $arguments, $self);
     } elseif ($service = $this->getServiceName($entity)) {
         // factory calling or service retrieving
         if ($this->definitions[$service]->shared) {
             if ($arguments) {
                 throw new ServiceCreationException("Unable to call service '{$entity}'.");
             }
             return $this->formatPhp('$this->getService(?)', array($service));
         }
         $params = array();
         foreach ($this->definitions[$service]->parameters as $k => $v) {
             $params[] = preg_replace('#\\w+$#', '\\$$0', is_int($k) ? $v : $k) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
         }
         $rm = new FunctionReflection(create_function(implode(', ', $params), ''));
         $arguments = DIHelpers::autowireArguments($rm, $arguments, $this);
         return $this->formatPhp('$this->?(?*)', array(DIContainer::getMethodName($service, FALSE), $arguments), $self);
     } elseif ($entity === 'not') {
         // operator
         return $this->formatPhp('!?', array($arguments[0]));
     } elseif (is_string($entity)) {
         // class name
         if ($constructor = ClassReflection::from($entity)->getConstructor()) {
             $this->addDependency($constructor->getFileName());
             $arguments = DIHelpers::autowireArguments($constructor, $arguments, $this);
         } elseif ($arguments) {
             throw new ServiceCreationException("Unable to pass arguments, class {$entity} has no constructor.");
         }
         return $this->formatPhp("new {$entity}" . ($arguments ? '(?*)' : ''), array($arguments), $self);
     } elseif (!Validators::isList($entity) || count($entity) !== 2) {
         throw new InvalidStateException("Expected class, method or property, " . PhpHelpers::dump($entity) . " given.");
     } elseif ($entity[0] === '') {
         // globalFunc
         return $this->formatPhp("{$entity['1']}(?*)", array($arguments), $self);
     } elseif (Strings::contains($entity[1], '$')) {
         // property setter
         Validators::assert($arguments, 'list:1', "setup arguments for '" . Callback::create($entity) . "'");
         if ($this->getServiceName($entity[0], $self)) {
             return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0]), $self);
         } else {
             return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0]), $self);
         }
     } elseif ($service = $this->getServiceName($entity[0], $self)) {
         // service method
         if ($this->definitions[$service]->class) {
             $arguments = $this->autowireArguments($this->definitions[$service]->class, $entity[1], $arguments);
         }
         return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments), $self);
     } else {
         // static method
         $arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
         return $this->formatPhp("{$entity['0']}::{$entity['1']}(?*)", array($arguments), $self);
     }
 }
Exemple #15
0
 /**
  * Get list of table Primary indexes
  *
  * @return mixed
  */
 protected static function getListPriIndexes()
 {
     try {
         $sql = "show index from " . self::_getTableName() . " where Key_name='PRIMARY'";
         $stmt = self::getDb()->prepare($sql);
         $stmt->execute();
         return $stmt->fetchAll(\PDO::FETCH_ASSOC);
     } catch (\PDOException $e) {
         DIContainer::build('app')->renderError($e);
     }
 }
Exemple #16
0
 /**
  * Returns current authorization handler.
  * @return IAuthorizator
  */
 public final function getAuthorizator()
 {
     return ($tmp = $this->authorizator) ? $tmp : $this->context->getByType('IAuthorizator');
 }