Example #1
0
 function __invoke(Di $di, $share = [])
 {
     if (is_string($this->x)) {
         return $di->create($this->x, $this->params, false, $share);
     } else {
         return call_user_func_array($this->x, $this->params);
     }
 }
Example #2
0
 public function __construct($message, $code = 0, Exception $previous = null)
 {
     $di = new Di();
     $config = new Config($di);
     $di->register($config);
     $log = new Log($config);
     $log->log($message);
     parent::__construct($message, $code, $previous);
 }
Example #3
0
 function __call($func, $args)
 {
     $di = property_exists($this, 'di') && $this->di instanceof Di ? $this->di : Di::getInstance();
     if (substr($func, 0, 4) == 'call' && ctype_upper(substr($func, 4, 1)) && (method_exists($this, $m = lcfirst(substr($func, 4))) || method_exists($this, $m = '_' . $m))) {
         $params = $di->methodGetParams($this, $m, $args);
         $closure = function () use($m, $params) {
             return call_user_func_array([$this, $m], $params);
         };
         $closure->bindTo($this);
         return $closure();
     }
     $method = '_' . $func;
     if (method_exists($this, $method)) {
         if (!(new \ReflectionMethod($this, $method))->isPublic()) {
             throw new \RuntimeException("The called method is not public.");
         }
         return $di->method($this, $method, $args);
     }
     if (($c = get_parent_class($this)) && method_exists($c, __FUNCTION__)) {
         $m = new \ReflectionMethod($c, __FUNCTION__);
         $dc1 = $m->getDeclaringClass()->name;
         $dc2 = (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->name;
         $dc3 = get_class($this);
         if ($dc1 != $dc2 || $dc2 != $dc3 && $dc1 != $dc3) {
             return parent::__call($func, $args);
         }
     }
     throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '->' . $func);
 }
Example #4
0
 /**
  * Get RochaMarcelo\CakePimpleDi\Di\Di
  *
  * @return \RochaMarcelo\CakePimpleDi\Di\Di
  */
 public function di()
 {
     if ($this->DiInstance === null) {
         $this->DiInstance = Di::instance();
     }
     return $this->DiInstance;
 }
Example #5
0
 function __construct(array $values = [])
 {
     parent::__construct();
     $this->factories = new \SplObjectStorage();
     $this->protected = new \SplObjectStorage();
     foreach ($values as $key => $value) {
         $this->offsetSet($key, $value);
     }
 }
 /**
  *
  * @param string $title     required user friendly message to return to the requestor
  * @param int    $code      required HTTP response code
  * @param array  $errorList list of optional properites to set on the error object
  * @param null   $previous
  */
 public function __construct($title, $code, $errorList, $previous = null)
 {
     parent::__construct($title, $code, $previous);
     // store general error data
     $this->errorStore = new ErrorStore($errorList);
     $this->errorStore->title = $title;
     $this->response = $this->getResponseDescription($code);
     $this->di = Di::getDefault();
 }
Example #7
0
 /**
  * @param string $route
  * @return mixed event results
  */
 public function run($route)
 {
     if (isset($this->map[$route])) {
         if (is_array($this->map[$route])) {
             $class = \Di::getInstanceOf($this->map[$route][0]);
             return $class->{$this->map[$route][1]}();
         } else {
             return $this->map[$route]();
         }
     }
 }
Example #8
0
 public function initTwig()
 {
     $config = DI::get('Config');
     // Add custom namespace path to Imagine lib
     $vendorDir = $config->get('site.path') . '/../vendor';
     $autoload = (require $vendorDir . '/autoload.php');
     $autoload->add('Twig_', __DIR__ . '/vendor/twig/lib');
     $this->twig = new Twig($config);
     $this->twig->init();
     Di::set('Twig', $this->twig);
     Hook::trigger(Hook::ACTION, 'twigInitialized', $this->twig->getEnvironment());
 }
Example #9
0
 public function initialize()
 {
     self::$_tbprefix = config('config')['dbMaster']['prefix'];
     $this->cache = Di::getDefault()->get('cacheData');
     $this->setReadConnectionService('db');
     //读
     $this->setWriteConnectionService('dbMaster');
     //写
     $this->useDynamicUpdate(true);
     //关闭更新全字段
     $this->setup(array('notNullValidations' => false));
     //关闭ORM自动验证非空列的映射表
 }
Example #10
0
 public function serve()
 {
     $support_callback = ['start' => [$this, 'onStart'], 'managerStart' => [$this, 'onManagerStart'], 'workerStart' => [$this, 'onWorkerStart'], 'receive' => [$this, 'onReceive'], 'task' => null, 'finish' => null, 'workerStop' => [$this, 'onWorkerStop']];
     foreach ($support_callback as $name => $callback) {
         // If has the dependency injection
         if (is_callable(Di::get($name))) {
             $callback = Di::get($name);
         }
         if ($callback !== null) {
             $this->serv->on($name, $callback);
         }
     }
     $this->serv->set($this->swoole_config);
     $this->serv->start();
 }
Example #11
0
 /**
  * Init menu
  *
  */
 private function setMenu()
 {
     $cache = Di::getDefault()->get('cache');
     if ($cache->has('app:menu')) {
         $this->tree = $cache->get('app:menu');
         return null;
     }
     $db = Di::getDefault()->get('db_centreon');
     $this->tree = array();
     $stmt = $db->prepare("SELECT menu_id, name, parent_id, url, icon_class, icon, bgcolor, menu_order, menu_block\n            FROM cfg_menus\n            WHERE module_id IN (SELECT id FROM cfg_modules WHERE isactivated = '1' OR isactivated = '2')\n            ORDER BY (CASE WHEN menu_order IS NULL then 1 ELSE 0 END), menu_order ASC, name ASC");
     $stmt->execute();
     $menus = $stmt->fetchAll(\PDO::FETCH_ASSOC);
     $this->tree = $this->buildTree($menus);
     $cache->set('app:menu', $this->tree);
 }
Example #12
0
 /**
  * 
  * @return type
  * @throws Exception
  */
 public static function getCentreonVersion()
 {
     $di = Di::getDefault();
     $db = $di->get('db_centreon');
     try {
         $stmt = $db->query("SELECT `value` FROM cfg_informations WHERE `key` = 'version'");
         $res = $stmt->fetchAll(\PDO::FETCH_ASSOC);
         if (count($res) == 0) {
             throw new \Exception("No values");
         }
     } catch (\PDOException $e) {
         if ($e->getCode() == "42S02") {
             throw new \Exception("Table not exist");
         }
     }
     return $res[0]['value'];
 }
 /**
  * Important
  * ValidationException will accept a list of validation objects or a simple key->value list in the 3rd param of
  *
  * @param string $title         the basic error message
  * @param array $errorList      key=>value pairs for properites of ErrorStore
  * @param array $validationList list of phalcon validation objects or key=>value pairs to be converted
  *                               into validation objects
  */
 public function __construct($title, $errorList, $validationList)
 {
     // store general error data
     $this->errorStore = new ErrorStore($errorList);
     $this->errorStore->title = $title;
     $mergedValidations = [];
     foreach ($validationList as $key => $validation) {
         // process simple key pair
         if (is_string($validation)) {
             $mergedValidations[] = new Message($validation, $key, 'InvalidValue');
         } else {
             // assume a validation object
             $mergedValidations[] = $validation;
         }
     }
     $this->errorStore->validationList = $mergedValidations;
     $this->di = Di::getDefault();
 }
Example #14
0
 /**
  * Get user ACL
  *
  * @param string $route
  */
 public function getUserAcl($route)
 {
     static $rules = null;
     if (is_null($rules)) {
         $rules = array();
         $db = Di::getDefault()->get('db_centreon');
         $stmt = $db->prepare("SELECT DISTINCT acl_level, url \n                FROM cfg_acl_menu_menu_relations ammr, cfg_acl_groups_menus_relations agmr, cfg_menus m\n                WHERE ammr.acl_menu_id = agmr.acl_menu_id\n                AND ammr.menu_id = m.menu_id\n                AND agmr.acl_group_id IN (\n                    SELECT acl_group_id \n                    FROM cfg_acl_group_contacts_relations agcr\n                    WHERE agcr.contact_contact_id = :contactid\n                    UNION\n                    SELECT acl_group_id\n                    FROM cfg_acl_group_contactgroups_relations agcgr, cfg_contactgroups_contacts_relations ccr\n                    WHERE agcgr.cg_cg_id = ccr.contactgroup_cg_id\n                    AND ccr.contact_contact_id = :contactid\n                ) ");
         $stmt->bindParam(':contactid', $this->userId);
         $stmt->execute();
         $rows = $stmt->fetchAll();
         $aclFlag = 0;
         foreach ($rows as $row) {
             if (!isset($rules[$row['url']])) {
                 $rules[$row['url']] = 0;
             }
             $rules[$row['url']] = $rules[$row['url']] | $row['acl_level'];
         }
     }
     foreach ($rules as $uri => $acl) {
         if (strstr($route, $uri)) {
             return $acl;
         }
     }
 }
Example #15
0
 /**
  * Parse a array for generate the url
  *
  * @param array $params The url parameters
  * @param array $castedElement The element converted
  * @param array $values The values of row
  * @return string
  */
 protected static function parseUrl($params, $castedElement, $values)
 {
     if (isset($values['DT_RowData'])) {
         unset($values['DT_RowData']);
         unset($values['DT_RowId']);
     }
     $routeParams = array();
     if (isset($params['routeParams']) && is_array($params['routeParams'])) {
         $routeParams = str_replace($castedElement, $values, $params['routeParams']);
     }
     $finalRoute = str_replace("//", "/", Di::getDefault()->get('router')->getPathFor($params['route'], $routeParams));
     return $finalRoute;
 }
Example #16
0
 public function run()
 {
     Di::get('server')->serve();
 }
Example #17
0
<?php

header("Content-type:text/html;charset=utf8");
class A
{
    public $name;
    public $age;
    public function __construct($name = '')
    {
        $this->name = $name;
    }
}
include "Di.class.php";
$di = new Di();
//匿名函数方式注册一个a1服务
$di->setShared('a1', function ($name = '') {
    return new A($name);
});
//直接以类名的方式注册
$di->set('a2', 'A');
//直接传入实例化的对象
$di->set('a3', new A('小超'));
$a1 = $di->get('a1', array('小李'));
echo $a1->name, "<br/>";
$a1_1 = $di->get('a1', array('小王'));
echo $a1->name, "<br/>";
echo $a1_1->name, "<br/>";
$a2 = $di->get('a2', array("小张"));
echo $a2->name . "<br/>";
//小张
$a2_1 = $di->get('a2', array("小徐"));
Example #18
0
function CACHE()
{
    static $cache = null;
    if (!is_object($cache)) {
        $cache = Di::getDefault()->get('cacheData');
    }
    return $cache;
}
Example #19
0
 public static function registerCache(\SplitIO\Component\Cache\Pool $cache)
 {
     Di::setCache($cache);
 }
Example #20
0
 public function test_default_null_parameter_value()
 {
     $object = Di::get('DiTest\\FooBar');
     $this->assertNull($object->param1);
 }
Example #21
0
 /**
  * Get module hook cache
  *
  * @return array
  */
 private static function getModuleHookCache()
 {
     $db = Di::getDefault()->get('db_centreon');
     if (!isset(self::$moduleHookCache)) {
         self::$moduleHookCache = array();
         $sql = "SELECT module_id, hook_id, module_hook_name, module_hook_description\n                FROM cfg_modules_hooks";
         $stmt = $db->prepare($sql);
         $stmt->execute();
         $rows = $stmt->fetchAll();
         foreach ($rows as $row) {
             $unique = implode("_", array($row['module_id'], $row['hook_id'], $row['module_hook_name']));
             self::$moduleHookCache[$unique] = $row;
         }
     }
     return self::$moduleHookCache;
 }
Example #22
0
File: Di.php Project: pierredup/di
 /**
  * Clears the current mapping and instances
  *
  * @static
  */
 public static function clear()
 {
     self::$map = array();
     self::$instances = array();
 }
 public function setUp(\Phalcon\DiInterface $di = NULL, \Phalcon\Config $config = NULL)
 {
     $this->clearTables();
     $this->createUsers();
     parent::setUp(Di::getDefault());
 }
Example #24
0
 /**
  * Set a configuration variable
  *
  * @param $group string The group of configuration
  * @param $var string The variable name
  * @param $value mixed The value to store
  * @throws The group is not permit for store in database
  * @throws If the configuration is not set in database
  */
 public function set($group, $var, $value)
 {
     if (in_array($group, $this->fileGroups)) {
         throw new Exception("This configuration group is not permit.");
     }
     if (false === isset($this->config[$group]) || false === isset($this->config[$group][$var])) {
         throw new Exception("This configuration {$group} - {$var} does not exists into database.");
     }
     $di = Di::getDefault();
     /* Save information in database */
     $dbconn = $di->get('db_centreon');
     $stmt = $dbconn->prepare("UPDATE `cfg_options`\n                SET `value` = :value\n                WHERE `group` = :group\n                    AND `key` = :key");
     $stmt->bindParam(':value', $value, \PDO::PARAM_STR);
     $stmt->bindParam(':group', $group, \PDO::PARAM_STR);
     $stmt->bindParam(':key', $var, \PDO::PARAM_STR);
     $stmt->execute();
     $this->config[$group][$var] = $value;
     /* Save config into cache */
     $di->get('cache')->set('app:cache', $this->config);
 }
Example #25
0
 /**
  * Generate a new CSRF token an store it in session
  *
  * @return string
  */
 public static function generateToken()
 {
     $token = md5(uniqid(Di::getDefault()->get('config')->get('global', 'secret'), true));
     $_SESSION[self::$sessionTokenName] = $token;
     return $token;
 }
Example #26
0
 public function testFailDependenciesPrimitiveParam()
 {
     require_once codecept_data_dir() . 'FailDependenciesPrimitiveParam.php';
     $this->injectionShouldFail('Parameter \'required\' must have default value');
     $this->di->instantiate('FailDependenciesPrimitiveParam\\IncorrectDependenciesClass');
 }
Example #27
0
 public function setUp()
 {
     $di = Di::getDefault();
     $this->setDI($di);
     $this->_loaded = true;
 }
Example #28
0
 /**
  * Initializes the session bag. This method must not be called directly, the class calls it when its internal data is accesed
  *
  * @throws Exception
  */
 public function initialize()
 {
     /* Ensure session object is present */
     if (is_object($this->_session) === false) {
         if (is_object($this->_dependencyInjector) === false) {
             $dependencyInjector = DI::getDefault();
             if (is_object($dependencyInjector) === false) {
                 throw new Exception('A dependency injection object is required to access the \'session\' service');
             }
         } else {
             $dependencyInjector = $this->_dependencyInjector;
         }
         $session = $dependencyInjector->getShared('session');
         if (is_object($session) === false || $session instanceof AdapterInterface === false) {
             throw new Exception('Invalid session service.');
         }
         $this->_session = $session;
     }
     $session = $this->_session;
     if (!is_object($session)) {
         $dependencyInjector = $this->_dependencyInjector;
         if (!is_object($dependencyInjector)) {
             $dependencyInjector = Di::getDefault();
         }
         $session = $dependencyInjector->getShared('session');
         $this->_session = $session;
     }
     $data = $session->get($this->_name);
     if (!is_array($data)) {
         $data = [];
     }
     $this->_data = $data;
     $this->_initialized = true;
 }
Example #29
0
 /**
  * @return array
  */
 public function __debugInfo()
 {
     $defaultDi = Di::getDefault();
     $data = [];
     foreach (get_object_vars($this) as $k => $v) {
         if ($v === $defaultDi) {
             continue;
         }
         $data[$k] = $v;
     }
     return $data;
 }