Exemple #1
0
 /**
  * @param object|string|array|static $reference an object or a reference to the desired object.
  * @param string|null $defaultClass default name of class
  * @param array $args arguments of constructor.
  * @param bool $throwException
  * @return ObjectInterface
  * @throws InstanceException
  */
 public static function ensure($reference, $defaultClass = null, array $args = [], $throwException = true)
 {
     if (is_object($reference)) {
         return $reference;
     }
     if (isset($reference) && class_exists('\\rock\\di\\Container')) {
         return \rock\di\Container::load($reference, $args, $throwException);
     } else {
         $config = [];
         if (is_array($reference)) {
             $config = $reference;
             if (!isset($defaultClass)) {
                 $defaultClass = $config['class'];
             }
             unset($config['class']);
         } elseif (is_string($reference) && !isset($defaultClass)) {
             $defaultClass = $reference;
         }
         if (!class_exists($defaultClass)) {
             if ($throwException) {
                 throw new InstanceException(InstanceException::UNKNOWN_CLASS, ['class' => Helper::getValue($defaultClass, 'null', true)]);
             }
             return null;
         }
         $reflect = new \ReflectionClass($defaultClass);
         $args = static::calculateArgs($reflect, $args, $config);
         return $reflect->newInstanceArgs($reflect->getConstructor() ? $args : []);
     }
 }
Exemple #2
0
 public function beforeAction($action)
 {
     /** @var Access $access */
     $this->access = Container::load(['class' => Access::className(), 'owner' => $this->owner, 'rules' => $this->rules]);
     if (!$this->access->checkAccess()) {
         return false;
     }
     return parent::beforeAction($action);
 }
Exemple #3
0
 /**
  * Modify date.
  *
  * @param string|int $time time for modify
  * @param string|\DateTimeZone $timezone
  * @param array $config the configuration. It can be either a string representing the class name
  *                             or an array representing the object configuration.
  * @throws \rock\di\ContainerException
  * @return $this
  */
 public static function set($time = 'now', $timezone = null, array $config = [])
 {
     if (!isset($time)) {
         $time = 'now';
     }
     if (class_exists('\\rock\\di\\Container')) {
         $config['class'] = static::className();
         return \rock\di\Container::load($config, [$time, $timezone]);
     }
     return new static($time, $timezone, $config);
 }
Exemple #4
0
 public function init()
 {
     parent::init();
     $this->captcha = Container::load($this->captcha);
 }
Exemple #5
0
 public function init()
 {
     parent::init();
     $this->authClientCollection = Container::load('authClientCollection');
 }
Exemple #6
0
 /**
  * Creates auth client instance from its array configuration.
  *
  * @param array $config auth client instance configuration.
  * @return ClientInterface auth client instance.
  */
 protected function createClient($config)
 {
     return Container::load($config);
 }
Exemple #7
0
 /**
  * Returns self instance.
  *
  * If exists {@see \rock\di\Container} that uses it.
  * @return static
  */
 protected static function getInstance()
 {
     if (class_exists('\\rock\\di\\Container')) {
         return \rock\di\Container::load(static::className());
     }
     return new static();
 }
Exemple #8
0
    } elseif (in_array(current($keys), ['isLogged', 'isAuthenticated'], true)) {
        return !Rock::$app->user->isGuest();
    }
    return \rock\helpers\ArrayHelper::getValue(Rock::$app->user->getAll(), $keys);
}, 'call' => function (array $call, array $params = [], Template $template) {
    if (!isset($call[1])) {
        $call[1] = null;
    }
    list($class, $method) = $call;
    if ($class === 'context') {
        $object = $template->context;
        $function = [$object, $method];
    } elseif (function_exists($class) && !$class instanceof \Closure) {
        return call_user_func_array($class, $params);
    } else {
        $object = \rock\di\Container::load($class);
        if (!method_exists($object, $method)) {
            throw new \rock\base\BaseException(\rock\base\BaseException::UNKNOWN_METHOD, ['method' => "{$class}::{$method}"]);
        }
        $function = [$object, $method];
    }
    return call_user_func_array($function, $params);
}], 'title' => 'Demo', 'metaTags' => ['charset' => '<meta charset="' . Rock::$app->charset . '" />'], 'linkTags' => ['favicon' => '<link rel="Shortcut Icon" type="image/x-icon" href="/favicon.ico?10">'], 'snippets' => ['request.get' => ['class' => \rock\snippets\request\Get::className()], 'request.post' => ['class' => \rock\snippets\request\Post::className()], 'csrf' => ['class' => \rock\snippets\CSRF::className()], 'captchaView' => ['class' => \rock\snippets\CaptchaView::className()], 'activeForm' => ['class' => \rock\snippets\ActiveForm::className()]]], 'execute' => ['class' => \rock\execute\CacheExecute::className()], 'i18n' => ['class' => \rock\i18n\i18n::className(), 'pathsDicts' => ['ru' => ['@rock/messages/ru/lang.php', '@rock/messages/ru/validate.php'], 'en' => ['@rock/messages/en/lang.php', '@rock/messages/en/validate.php']], 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'date' => ['class' => \rock\date\DateTime::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale'], 'formats' => ['dmy' => function (\rock\date\DateTime $dateTime) {
    $nowYear = date('Y');
    $lastYear = $dateTime->format('Y');
    return $nowYear > $lastYear ? $dateTime->format('j F Y') : $dateTime->format('d F');
}, 'dmyhm' => function (\rock\date\DateTime $dateTime) {
    $nowYear = date('Y');
    $lastYear = $dateTime->format('Y');
    return $nowYear > $lastYear ? $dateTime->format('j F Y H:i') : $dateTime->format('j F H:i');
}]], 'mail' => ['class' => \rock\mail\Mail::className(), 'From' => 'support@' . (new \rock\request\Request())->getHost(), 'FromName' => 'Rock Framework'], 'url' => ['class' => \rock\url\Url::className()], 'request' => ['class' => \rock\request\Request::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'response' => ['class' => \rock\response\Response::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'htmlResponseFormatter' => ['class' => \rock\response\HtmlResponseFormatter::className()], 'jsonResponseFormatter' => ['class' => \rock\response\JsonResponseFormatter::className()], 'xmlResponseFormatter' => ['class' => \rock\response\XmlResponseFormatter::className()], 'rssResponseFormatter' => ['class' => \rock\response\RssResponseFormatter::className()], 'session' => ['class' => \rock\session\Session::className(), 'cookieParams' => ['httponly' => true, 'lifetime' => 60 * 60 * 24 * 60, 'setUseCookies' => \rock\session\Session::USE_ONLY_COOKIES]], 'cookie' => ['class' => \rock\cookie\Cookie::className()], 'security' => ['class' => Security::className()], 'sanitize' => ['class' => \rock\sanitize\Sanitize::className()], 'validate' => ['class' => \rock\validate\Validate::className(), 'locale' => [\rock\LocaleProperties::className(), 'locale']], 'csrf' => ['class' => \rock\csrf\CSRF::className()], 'captcha' => ['class' => \rock\captcha\Captcha::className(), 'length' => 0, 'whiteNoiseDensity' => 1 / 6, 'blackNoiseDensity' => 1 / 30], 'user' => ['class' => \rock\user\User::className(), 'container' => 'user'], 'rbac' => ['class' => \rock\rbac\DBManager::className()], 'log' => ['class' => \rock\log\Log::className()], Role::className() => ['class' => Role::className()], Permission::className() => ['class' => Permission::className()]], require __DIR__ . '/widgets.php');
 /**
  * Sets the value of a component property.
  *
  * This method will check in the following order and act accordingly:
  *
  *  - a property defined by a setter: set the property value
  *  - an event in the format of "on xyz": attach the handler to the event "xyz"
  *  - a behavior in the format of "as xyz": attach the behavior named as "xyz"
  *  - a property of a behavior: set the behavior property value
  *
  * Do not call this method directly as it is a PHP magic method that
  * will be implicitly called when executing `$component->property = $value;`.
  *
  * @param string $name the property name or the event name
  * @param mixed $value the property value
  * @throws BaseException if the property is not defined
  * @throws BaseException if the property is read-only.
  * @see __get()
  */
 public function __set($name, $value)
 {
     $setter = 'set' . $name;
     if (method_exists($this, $setter)) {
         // set property
         $this->{$setter}($value);
         return;
     } elseif (strncmp($name, 'on ', 3) === 0) {
         // on event: attach event handler
         $this->on(trim(substr($name, 3)), $value);
         return;
     } elseif (strncmp($name, 'as ', 3) === 0) {
         // as behavior: attach behavior
         $name = trim(substr($name, 3));
         if ($value instanceof Behavior) {
             $behavior = $value;
         } elseif (class_exists('\\rock\\di\\Container')) {
             $behavior = Container::load($value);
         } elseif (class_exists($value)) {
             $behavior = new $value();
         } else {
             throw new BaseException(BaseException::UNKNOWN_CLASS, ['class' => $value]);
         }
         $this->attachBehavior($name, $behavior);
         return;
     } else {
         // behavior property
         $this->ensureBehaviors();
         /** @var Behavior $behavior */
         foreach ($this->_behaviors as $behavior) {
             if ($behavior->canSetProperty($name)) {
                 $behavior->{$name} = $value;
                 return;
             }
         }
     }
     if (method_exists($this, 'get' . $name)) {
         throw new BaseException(BaseException::SETTING_READ_ONLY_PROPERTY, ['class' => get_class($this), 'property' => $name]);
     } else {
         throw new BaseException(BaseException::SETTING_UNKNOWN_PROPERTY, ['class' => get_class($this), 'property' => $name]);
     }
 }
Exemple #10
0
<?php

use apps\common\migrations\mysql\AccessAssignmentsMigration;
use apps\common\migrations\mysql\AccessItemsMigration;
use apps\common\migrations\mysql\AccessRolesItemsMigration;
use apps\common\migrations\mysql\UsersMigration;
use rock\Rock;
require dirname(dirname(dirname(__DIR__))) . '/vendor/autoload.php';
Rock::$app = new Rock();
Rock::$app->language = 'en';
if (!($config = (require dirname(dirname(__DIR__)) . '/common/configs/configs.php'))) {
    die('configs is empty/not found');
}
Rock::$components = $config['components'];
unset($config['components']);
Rock::$config = $config;
\rock\di\Container::registerMulti(Rock::$components);
(new UsersMigration())->up();
(new AccessItemsMigration())->up();
(new AccessRolesItemsMigration())->up();
(new AccessAssignmentsMigration())->up();
Exemple #11
0
 /**
  * Get instance.
  *
  * If exists {@see \rock\di\Container} that uses it.
  *
  * @param string|array $config the configuration. It can be either a string representing the class name
  *                                     or an array representing the object configuration.
  * @return $this
  * @throws \rock\di\ContainerException
  */
 protected static function getSelfInstance($config)
 {
     if (class_exists('\\rock\\di\\Container')) {
         return Container::load($config);
     }
     unset($config['class']);
     return new static($config);
 }
Exemple #12
0
 protected function defaultRESTHandlers()
 {
     return ['index' => [self::GET, '/{url}/', function (Route $route) {
         return call_user_func([Container::load($route['controller']), 'actionIndex'], $route);
     }], 'create' => [self::GET, '/{url}/create/', function (Route $route) {
         return call_user_func([Container::load($route['controller']), 'actionCreate'], $route);
     }], 'store' => [self::POST, '/{url}/', function (Route $route) {
         return call_user_func([Container::load($route['controller']), 'actionStore'], $route);
     }], 'show' => [self::GET, '~/^\\/{url}\\/(?P<id>[^\\/]+)$/', function (Route $route) {
         return call_user_func([Container::load($route['controller']), 'actionShow'], $route);
     }], 'edit' => [self::GET, '~/^\\/{url}\\/(?P<id>[^\\/]+)\\/edit\\/$/', function (Route $route) {
         return call_user_func([Container::load($route['controller']), 'actionEdit'], $route);
     }], 'update' => [[self::PUT, self::PATCH], '~/^\\/{url}\\/(?P<id>[^\\/]+)$/', function (Route $route) {
         return call_user_func([Container::load($route['controller']), 'actionUpdate'], $route);
     }], 'delete' => [self::DELETE, '~/^\\/{url}\\/(?P<id>[^\\/]+)$/', function (Route $route) {
         return call_user_func([Container::load($route['controller']), 'actionDelete'], $route);
     }]];
 }
Exemple #13
0
 public static function __callStatic($name, $arguments)
 {
     /** @var static $self */
     $self = Container::load(static::className());
     return call_user_func_array([$self, $name], $arguments);
 }
Exemple #14
0
 /**
  * Call function.
  *
  * ```php
  * $this->callFunction('\foo\Snippet');
  * $this->callFunction('\foo\FooController.get');
  * $this->callFunction(function{}());
  * $this->callFunction([Foo::className(), 'get']);
  * $this->callFunction([new Foo(), 'get']);
  * ```
  *
  * @param mixed $function may be a callable, snippet, and instance.
  * @param array $params
  * @return mixed
  */
 protected function callFunction($function, array $params = [])
 {
     if (is_string($function)) {
         $function = trim($function);
         if (strpos($function, '.') !== false) {
             $function = explode('.', $function);
         } else {
             return $this->template->getSnippet($function, $params);
         }
     }
     if (is_array($function)) {
         if ($function[0] === 'context') {
             $function[0] = $this->template->getContext();
             return call_user_func_array($function, $params);
         } elseif (is_string($function[0])) {
             if (class_exists('\\rock\\di\\Container') && Container::exists($function[0])) {
                 $function[0] = Container::load($function[0]);
             }
             return call_user_func_array($function, $params);
         }
     }
     return call_user_func_array($function, $params);
 }
 public function afterRecovery()
 {
     $users = $this->getUsers();
     /** @var Security $security */
     $security = Container::load('security');
     $password = $security->generateRandomString(7);
     $users->setPassword($password);
     if (!$users->save()) {
         $this->addError('alerts', i18n::t('failRecovery'));
         return;
     }
     $event = new ModelEvent();
     $users->password = $password;
     $event->result = $users;
     $this->trigger(self::EVENT_AFTER_RECOVERY, $event);
 }
Exemple #16
0
 public function init()
 {
     $this->parentInit();
     $this->session = Container::load($this->session);
     $this->length = Helper::getValue($this->length, mt_rand(5, 7));
     $this->foregroundColor = Helper::getValue($this->foregroundColor, [mt_rand(0, 80), mt_rand(0, 80), mt_rand(0, 80)]);
     $this->backgroundColor = Helper::getValue($this->backgroundColor, [mt_rand(220, 255), mt_rand(220, 255), mt_rand(220, 255)]);
 }
Exemple #17
0
 /**
  * Creates a new object using the given configuration.
  *
  * The configuration can be either a string or an array.
  * If a string, it is treated as the *object class*; if an array,
  * it must contain a `class` element specifying the *object class*, and
  * the rest of the name-value pairs in the array will be used to initialize
  * the corresponding object properties.
  *
  * Below are some usage examples:
  *
  * ```php
  * $object = Rock::factory('\rock\db\Connection');
  * $object = Rock::factory(\rock\db\Connection::className());
  * $object = Rock::factory([
  *     'class' => '\rock\db\Connection',
  *     'dsn' => $dsn,
  *     'username' => $username,
  *     'password' => $password,
  * ]);
  * $object = Rock::factory([
  *     'class' => 'apps\frontend\FooController',
  *     'test' => 'test',
  * ], [$arg1, $arg2]);
  * ```
  *
  *
  * This method can be used to create any object as long as the object's constructor is
  * defined like the following:
  *
  * ```php
  * public function __construct(..., $config = []) {
  * }
  * ```
  *
  * The method will pass the given configuration as the last parameter of the constructor,
  * and any additional parameters to this method will be passed as the rest of the constructor parameters.
  *
  * @param string|array $config the configuration. It can be either a string representing the class name
  *                             or an array representing the object configuration.
  * @param array $args arguments of constructor.
  * @param mixed $throwException throws exception
  * @return null|ObjectInterface the created object
  * @throws di\ContainerException
  */
 public static function factory($config, array $args = [], $throwException = true)
 {
     return Container::load($config, $args, $throwException);
 }
Exemple #18
0
 public function get()
 {
     /** @var \rock\csrf\CSRF $csrf */
     $csrf = Container::load('csrf');
     return $csrf->get();
 }