new Container

This commit is contained in:
Visman 2017-02-21 17:47:34 +07:00
parent ffdcefb076
commit 5f2e45ee58
33 changed files with 417 additions and 705 deletions

View file

@ -2,21 +2,21 @@
namespace ForkBB\Controllers;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
class Primary
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
/**
* Конструктор
* @param array $config
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
}
@ -29,14 +29,14 @@ class Primary
*/
public function check()
{
$config = $this->c->get('config');
$config = $this->c->config;
// Проверяем режим обслуживания форума
if ($config['o_maintenance'] && ! defined('PUN_TURN_OFF_MAINT')) { //????
if (! in_array($this->c->get('UserCookie')->id(), $this->c->get('admins'))
|| ! in_array($this->c->get('user')['id'], $this->c->get('admins'))
if (! in_array($this->c->UserCookie->id(), $this->c->admins)
|| ! in_array($this->c->user['id'], $this->c->admins)
) {
return $this->c->get('Maintenance');
return $this->c->Maintenance;
}
}
@ -46,8 +46,8 @@ class Primary
exit;
}
if (($banned = $this->c->get('CheckBans')->check()) !== null) {
return $this->c->get('Ban')->ban($banned);
if (($banned = $this->c->CheckBans->check()) !== null) {
return $this->c->Ban->ban($banned);
}
}
}

View file

@ -2,21 +2,21 @@
namespace ForkBB\Controllers;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
class Routing
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
/**
* Конструктор
* @param array $config
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
}
@ -27,9 +27,9 @@ class Routing
*/
public function routing()
{
$user = $this->c->get('user');
$config = $this->c->get('config');
$r = $this->c->get('Router');
$user = $this->c->user;
$config = $this->c->config;
$r = $this->c->Router;
// регистрация/вход/выход
if ($user->isGuest) {
@ -99,23 +99,23 @@ class Routing
case $r::OK:
// ... 200 OK
list($page, $action) = explode(':', $route[1], 2);
$page = $this->c->get($page)->$action($route[2]);
$page = $this->c->$page->$action($route[2]);
break;
case $r::NOT_FOUND:
// ... 404 Not Found
if ($user->gReadBoard != '1' && $user->isGuest) {
$page = $this->c->get('Redirect')->setPage('Login');
$page = $this->c->Redirect->setPage('Login');
} else {
// $page = $this->c->get('Message')->message('Bad request');
// $page = $this->c->Message->message('Bad request');
}
break;
case $r::METHOD_NOT_ALLOWED:
// ... 405 Method Not Allowed
$page = $this->c->get('Message')->message('Bad request', true, 405, ['Allow: ' . implode(',', $route[1])]);
$page = $this->c->Message->message('Bad request', true, 405, ['Allow: ' . implode(',', $route[1])]);
break;
case $r::NOT_IMPLEMENTED:
// ... 501 Not implemented
$page = $this->c->get('Message')->message('Bad request', true, 501);
$page = $this->c->Message->message('Bad request', true, 501);
break;
}
return $page;

196
app/Core/Container.php Normal file
View file

@ -0,0 +1,196 @@
<?php
/**
* based on code Container https://github.com/artoodetoo/container
* by artoodetoo
*/
namespace ForkBB\Core;
use InvalidArgumentException;
/**
* Service Container
*/
class Container
{
protected $instances = [];
protected $shared = [];
protected $multiple = [];
/**
* Конструктор
* @param array config
*/
public function __construct(array $config = null)
{
if (empty($config)) {
return;
}
if (isset($config['shared'])) {
$this->shared = $config['shared'];
}
if (isset($config['multiple'])) {
$this->multiple = $config['multiple'];
}
unset($config['shared'], $config['multiple']);
$this->instances = $config;
}
/**
* Adding config
* @param array config
*/
public function config(array $config)
{
if (isset($config['shared'])) {
$this->shared = array_replace_recursive($this->shared, $config['shared']);
}
if (isset($config['multiple'])) {
$this->multiple = array_replace_recursive($this->multiple, $config['multiple']);
}
unset($config['shared'], $config['multiple']);
$this->config = array_replace_recursive($this->config, $config);
}
/**
* Gets a service or parameter.
* @param string $id
* @return mixed
* @throws \InvalidArgumentException
*/
public function __get($id)
{
if (isset($this->instances[$id])) {
return $this->instances[$id];
} elseif (strpos($id, '.') !== false) {
$tree = explode('.', $id);
$service = $this->__get(array_shift($tree));
if (is_array($service)) {
return $this->fromArray($service, $tree);
} elseif (is_object($service)) {
return $service->$tree;
} else {
return null;
}
}
if (isset($this->shared[$id])) {
$toShare = true;
$config = (array) $this->shared[$id];
} elseif (isset($this->multiple[$id])) {
$toShare = false;
$config = (array) $this->multiple[$id];
} else {
throw new InvalidArgumentException('Wrong property name '.$id);
}
// N.B. "class" is just the first element, regardless of its key
$class = array_shift($config);
$args = [];
// If you want to susbtitute some values in arguments, use non-numeric keys for them
foreach ($config as $k => $v) {
$args[] = is_numeric($k) ? $v : $this->resolve($v);
}
// Special case: reference to factory method
if ($class{0} == '@' && strpos($class, ':') !== false) {
list($name, $method) = explode(':', substr($class, 1), 2);
$factory = $this->__get($name);
$service = $factory->$method(...$args);
} else {
// Adding this container in the arguments for constructor
$args[] = $this;
$service = new $class(...$args);
}
if ($toShare) {
$this->instances[$id] = $service;
}
return $service;
}
/**
* Sets a service or parameter.
* Provides a fluent interface.
* @param string $id
* @param mixed $service
*/
public function __set($id, $service)
{
if (strpos($id, '.') !== false) {
//????
} else {
$this->instances[$id] = $service;
}
}
/**
* Gets data from array.
* @param array $array
* @param array $tree
* @return mixed
*/
public function fromArray(array $array, array $tree)
{
$ptr = & $array;
foreach ($tree as $s) {
if (isset($ptr[$s])) {
$ptr = & $ptr[$s];
} else {
return null;
}
}
return $ptr;
}
/**
* Sets a parameter.
* Provides a fluent interface.
*
* @param string $name The parameter name
* @param mixed $value The parameter value
*
* @return ContainerInterface Self reference
*/
public function setParameter($name, $value)
{
$segments = explode('.', $name);
$n = count($segments);
$ptr =& $this->config;
foreach ($segments as $s) {
if (--$n) {
if (!array_key_exists($s, $ptr)) {
$ptr[$s] = [];
} elseif (!is_array($ptr[$s])) {
throw new \InvalidArgumentException("Scalar \"{$s}\" in the path \"{$name}\"");
}
$ptr =& $ptr[$s];
} else {
$ptr[$s] = $value;
}
}
return $this;
}
protected function resolve($value)
{
if (is_string($value)) {
if (strpos($value, '%') !== false) {
// whole string substitution can return any type of value
if (preg_match('~^%(\w+(?:\.\w+)*)%$~', $value, $matches)) {
$value = $this->__get($matches[1]);
} else {
// partial string substitution casts value to string
$value = preg_replace_callback('~%(\w+(?:\.\w+)*)%~',
function ($matches) {
return $this->__get($matches[1]);
}, $value);
}
} elseif (isset($value{0}) && $value{0} === '@') {
return $this->__get(substr($value, 1));
}
} elseif (is_array($value)) {
foreach ($value as &$v) {
$v = $this->resolve($v);
}
unset($v);
}
return $value;
}
}

View file

@ -2,7 +2,7 @@
namespace ForkBB\Core;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
use RuntimeException;
class Install
@ -14,7 +14,7 @@ class Install
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -22,7 +22,7 @@ class Install
* Конструктор
* @param Request $request
*/
public function __construct($request, ContainerInterface $container)
public function __construct($request, Container $container)
{
$this->request = $request;
$this->c = $container;
@ -34,7 +34,7 @@ class Install
*/
protected function generate_config_file($base_url, $db_type, $db_host, $db_name, $db_username, $db_password, $db_prefix, $cookie_prefix)
{
$config = file_get_contents($this->c->getParameter('DIR_CONFIG') . '/main.dist.php');
$config = file_get_contents($this->c->DIR_CONFIG . '/main.dist.php');
if (false === $config) {
throw new RuntimeException('No access to main.dist.php.');
}
@ -46,7 +46,7 @@ class Install
$config = str_replace('_DB_NAME_', addslashes($db_name), $config);
$config = str_replace('_DB_PREFIX_', addslashes($db_prefix), $config);
$config = str_replace('_COOKIE_PREFIX_', addslashes($cookie_prefix), $config);
$config = str_replace('_SALT_FOR_HMAC_', addslashes($this->c->get('Secury')->randomPass(21)), $config);
$config = str_replace('_SALT_FOR_HMAC_', addslashes($this->c->Secury->randomPass(21)), $config);
return $config;
}
@ -184,8 +184,8 @@ class Install
}
// Check if the cache directory is writable
if (! forum_is_writable($this->c->getParameter('DIR_CACHE')))
$alerts[] = sprintf($lang_install['Alert cache'], $this->c->getParameter('DIR_CACHE'));
if (! forum_is_writable($this->c->DIR_CACHE))
$alerts[] = sprintf($lang_install['Alert cache'], $this->c->DIR_CACHE);
// Check if default avatar directory is writable
if (! forum_is_writable(PUN_ROOT . 'img/avatars/'))
@ -479,14 +479,14 @@ foreach ($styles as $temp)
if (strlen($db_prefix) > 0 && (! preg_match('%^[a-zA-Z]\w*$%', $db_prefix) || strlen($db_prefix) > 40))
error(sprintf($lang_install['Table prefix error'], $db->prefix));
$this->c->setParameter('DB_TYPE', $db_type);
$this->c->setParameter('DB_HOST', $db_host);
$this->c->setParameter('DB_USERNAME', $db_username);
$this->c->setParameter('DB_PASSWORD', $db_password);
$this->c->setParameter('DB_NAME', $db_name);
$this->c->setParameter('DB_PREFIX', $db_prefix);
$this->c->DB_TYPE = $db_type;
$this->c->DB_HOST = $db_host;
$this->c->DB_USERNAME = $db_username;
$this->c->DB_PASSWORD = $db_password;
$this->c->DB_NAME = $db_name;
$this->c->DB_PREFIX = $db_prefix;
$db = $this->c->get('DB');
$db = $this->c->DB;
// Do some DB type specific checks
switch ($db_type)
@ -2077,8 +2077,8 @@ foreach ($styles as $temp)
'o_coding_forms' => 1, // кодирование форм - Visman
'o_check_ip' => 0, // проверка ip администрации - Visman
'o_crypto_enable' => 1, // случайные имена полей форм - Visman
'o_crypto_pas' => $this->c->get('Secury')->randomPass(25),
'o_crypto_salt' => $this->c->get('Secury')->randomPass(13),
'o_crypto_pas' => $this->c->Secury->randomPass(25),
'o_crypto_salt' => $this->c->Secury->randomPass(13),
'o_enable_acaptcha' => 1, // математическая каптча
'st_max_users' => 1, // статистика по максимуму юзеров - Visman
'st_max_users_time' => time(),
@ -2127,9 +2127,9 @@ foreach ($styles as $temp)
// Attempt to write main.php and serve it up for download if writing fails
$written = false;
if (forum_is_writable($this->c->getParameter('DIR_CONFIG')))
if (forum_is_writable($this->c->DIR_CONFIG))
{
$fh = @fopen($this->c->getParameter('DIR_CONFIG') . '/main.php', 'wb');
$fh = @fopen($this->c->DIR_CONFIG . '/main.php', 'wb');
if ($fh)
{
fwrite($fh, $config);

View file

@ -2,14 +2,14 @@
namespace ForkBB\Core;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
use RuntimeException;
class Lang
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -27,9 +27,9 @@ class Lang
/**
* Конструктор
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
__($this);
@ -71,8 +71,8 @@ class Lang
} elseif (isset($this->loaded[$name])) {
return;
}
$lang = $lang ?: $this->c->get('user')->language;
$path = $path ?: $this->c->getParameter('DIR_LANG');
$lang = $lang ?: $this->c->user->language;
$path = $path ?: $this->c->DIR_LANG;
do {
$flag = true;
$fullPath = $path . '/'. $lang . '/' . $name . '.po';

View file

@ -3,14 +3,14 @@
namespace ForkBB\Models\Actions;
use ForkBB\Core\Cache;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
use InvalidArgumentException;
class CacheLoader
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -22,9 +22,9 @@ class CacheLoader
/**
* Конструктор
* @param Cache $cache
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(Cache $cache, ContainerInterface $container)
public function __construct(Cache $cache, Container $container)
{
$this->cache = $cache;
$this->c = $container;
@ -45,10 +45,10 @@ class CacheLoader
if (! $update && $this->cache->has($key)) {
return $this->cache->get($key);
} else {
$value = $this->c->get('get ' . $key);
$value = $this->c->{'get ' . $key};
$this->cache->set($key, $value);
if ($update) {
$this->c->set($key, $value);
$this->c->$key = $value;
}
return $value;
}
@ -61,11 +61,11 @@ class CacheLoader
public function loadForums()
{
$mark = $this->cache->get('forums_mark');
$key = 'forums_' . $this->c->get('user')->gId;
$key = 'forums_' . $this->c->user->gId;
if (empty($mark)) {
$this->cache->set('forums_mark', time());
$value = $this->c->get('get forums');
$value = $this->c->{'get forums'};
$this->cache->set($key, [time(), $value]);
return $value;
}
@ -73,7 +73,7 @@ class CacheLoader
$result = $this->cache->get($key);
if (empty($result) || $result[0] < $mark) {
$value = $this->c->get('get forums');
$value = $this->c->{'get forums'};
$this->cache->set($key, [time(), $value]);
return $value;
}

View file

@ -2,21 +2,21 @@
namespace ForkBB\Models\Actions;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
class CheckBans
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
/**
* Конструктор
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
}
@ -27,8 +27,8 @@ class CheckBans
*/
public function check()
{
$bans = $this->c->get('bans');
$user = $this->c->get('user');
$bans = $this->c->bans;
$user = $this->c->user;
// Для админов и при отсутствии банов прекращаем проверку
if ($user->isAdmin || empty($bans)) {
@ -83,15 +83,15 @@ class CheckBans
// If we removed any expired bans during our run-through, we need to regenerate the bans cache
if (! empty($remove))
{
$db = $this->c->get('DB');
$db = $this->c->DB;
$db->query('DELETE FROM '.$db->prefix.'bans WHERE id IN (' . implode(',', $remove) . ')') or error('Unable to delete expired ban', __FILE__, __LINE__, $db->error());
$this->c->get('bans update');
$this->c->{'bans update'};
}
if ($banned)
{
//???? а зачем это надо?
$this->c->get('Online')->delete($user);
$this->c->Online->delete($user);
return $banned;
}

View file

@ -2,16 +2,16 @@
namespace ForkBB\Models;
use ForkBB\Core\Container;
use ForkBB\Models\User;
use ForkBB\Models\Pages\Page;
use R2\DependencyInjection\ContainerInterface;
use RuntimeException;
class Online
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -41,9 +41,9 @@ class Online
* @param array $config
* @param DB $db
* @param User $user
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(array $config, $db, User $user, ContainerInterface $container)
public function __construct(array $config, $db, User $user, Container $container)
{
$this->config = $config;
$this->db = $db;
@ -162,7 +162,7 @@ class Online
$this->db->query('UPDATE '.$this->db->prefix.'config SET conf_value=\''.$all.'\' WHERE conf_name=\'st_max_users\'') or error('Unable to update config value \'st_max_users\'', __FILE__, __LINE__, $this->db->error());
$this->db->query('UPDATE '.$this->db->prefix.'config SET conf_value=\''.$now.'\' WHERE conf_name=\'st_max_users_time\'') or error('Unable to update config value \'st_max_users_time\'', __FILE__, __LINE__, $this->db->error());
$this->c->get('config update');
$this->c->{'config update'};
}
/*
@set_time_limit(0);
@ -190,7 +190,7 @@ for ($i=0;$i<100;++$i) {
$this->db->query('INSERT INTO '.$this->db->prefix.'online (user_id, ident, logged, o_position, o_name) SELECT 1, \''.$this->db->escape($this->user->ip).'\', '.$now.', \''.$this->db->escape($position).'\', \''.$this->db->escape($oname).'\' FROM '.$this->db->prefix.'groups WHERE NOT EXISTS (SELECT 1 FROM '.$this->db->prefix.'online WHERE user_id=1 AND ident=\''.$this->db->escape($this->user->ip).'\') LIMIT 1') or error('Unable to insert into online list', __FILE__, __LINE__, $this->db->error());
// With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
/* switch ($this->c->getParameter('DB_TYPE')) {
/* switch ($this->c->DB_TYPE) {
case 'mysql':
case 'mysqli':
case 'mysql_innodb':
@ -213,7 +213,7 @@ for ($i=0;$i<100;++$i) {
} else {
$this->db->query('INSERT INTO '.$this->db->prefix.'online (user_id, ident, logged, o_position) SELECT '.$this->user->id.', \''.$this->db->escape($this->user->username).'\', '.$now.', \''.$this->db->escape($position).'\' FROM '.$this->db->prefix.'groups WHERE NOT EXISTS (SELECT 1 FROM '.$this->db->prefix.'online WHERE user_id='.$this->user->id.') LIMIT 1') or error('Unable to insert into online list', __FILE__, __LINE__, $this->db->error());
// With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
/* switch ($this->c->getParameter('DB_TYPE')) {
/* switch ($this->c->DB_TYPE) {
case 'mysql':
case 'mysqli':
case 'mysql_innodb':

View file

@ -2,8 +2,8 @@
namespace ForkBB\Models\Pages\Admin;
use ForkBB\Core\Container;
use ForkBB\Models\Pages\Page;
use R2\DependencyInjection\ContainerInterface;
abstract class Admin extends Page
{
@ -27,12 +27,12 @@ abstract class Admin extends Page
/**
* Конструктор
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
parent::__construct($container);
$container->get('Lang')->load('admin');
$container->Lang->load('admin');
$this->titles = [__('Admin title')];
}
@ -42,8 +42,6 @@ abstract class Admin extends Page
*/
public function getData()
{
$this->c->get('Online')->handle($this);
$data = parent::getData();
$data['aNavigation'] = $this->aNavigation();
$data['aIndex'] = $this->adminIndex;
@ -56,8 +54,8 @@ abstract class Admin extends Page
*/
protected function aNavigation()
{
$user = $this->c->get('user');
$r = $this->c->get('Router');
$user = $this->c->user;
$r = $this->c->Router;
$nav = [
'Moderator menu' => [

View file

@ -22,10 +22,10 @@ class Index extends Admin
*/
public function index()
{
$this->c->get('Lang')->load('admin_index');
$this->c->Lang->load('admin_index');
$this->data = [
'version' => $this->config['s_fork_version'] . '.' . $this->config['i_fork_revision'],
'linkStat' => $this->c->get('Router')->link('AdminStatistics'),
'linkStat' => $this->c->Router->link('AdminStatistics'),
];
$this->titles[] = __('Admin index');
return $this;

View file

@ -24,7 +24,7 @@ class Statistics extends Admin
{
// Is phpinfo() a disabled function?
if (strpos(strtolower((string) ini_get('disable_functions')), 'phpinfo') !== false) {
$this->c->get('Message')->message('PHPinfo disabled message', true, 200);
$this->c->Message->message('PHPinfo disabled message', true, 200);
}
phpinfo();
@ -37,11 +37,11 @@ class Statistics extends Admin
*/
public function statistics()
{
$this->c->get('Lang')->load('admin_index');
$this->c->Lang->load('admin_index');
$this->data = [];
$this->titles[] = __('Server statistics');
$this->data['isAdmin'] = $this->c->get('user')->isAdmin;
$this->data['linkInfo'] = $this->c->get('Router')->link('AdminInfo');
$this->data['isAdmin'] = $this->c->user->isAdmin;
$this->data['linkInfo'] = $this->c->Router->link('AdminInfo');
// Get the server load averages (if possible)
if (@file_exists('/proc/loadavg') && is_readable('/proc/loadavg')) {
@ -66,12 +66,12 @@ class Statistics extends Admin
}
// Get number of current visitors
$db = $this->c->get('DB');
$db = $this->c->DB;
$result = $db->query('SELECT COUNT(user_id) FROM '.$db->prefix.'online WHERE idle=0') or error('Unable to fetch online count', __FILE__, __LINE__, $db->error());
$this->data['numOnline'] = $db->result($result);
// Collect some additional info about MySQL
if (in_array($this->c->getParameter('DB_TYPE'), ['mysql', 'mysqli', 'mysql_innodb', 'mysqli_innodb'])) {
if (in_array($this->c->DB_TYPE, ['mysql', 'mysqli', 'mysql_innodb', 'mysqli_innodb'])) {
// Calculate total db size/row count
$result = $db->query('SHOW TABLE STATUS LIKE \''.$db->prefix.'%\'') or error('Unable to fetch table status', __FILE__, __LINE__, $db->error());

View file

@ -2,8 +2,6 @@
namespace ForkBB\Models\Pages;
use R2\DependencyInjection\ContainerInterface;
class Auth extends Page
{
/**
@ -31,19 +29,19 @@ class Auth extends Page
*/
public function logout($args)
{
$this->c->get('Lang')->load('login');
$this->c->Lang->load('login');
if ($this->c->get('Csrf')->verify($args['token'], 'Logout', $args)) {
$user = $this->c->get('user');
if ($this->c->Csrf->verify($args['token'], 'Logout', $args)) {
$user = $this->c->user;
$this->c->get('UserCookie')->deleteUserCookie();
$this->c->get('Online')->delete($user);
$this->c->get('UserMapper')->updateLastVisit($user);
$this->c->UserCookie->deleteUserCookie();
$this->c->Online->delete($user);
$this->c->UserMapper->updateLastVisit($user);
return $this->c->get('Redirect')->setPage('Index')->setMessage(__('Logout redirect'));
return $this->c->Redirect->setPage('Index')->setMessage(__('Logout redirect'));
}
return $this->c->get('Redirect')->setPage('Index')->setMessage(__('Bad token'));
return $this->c->Redirect->setPage('Index')->setMessage(__('Bad token'));
}
/**
@ -53,14 +51,14 @@ class Auth extends Page
*/
public function login(array $args)
{
$this->c->get('Lang')->load('login');
$this->c->Lang->load('login');
if (! isset($args['_username'])) {
$args['_username'] = '';
}
if (! isset($args['_redirect'])) {
$args['_redirect'] = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER'];
$args['_redirect'] = $this->c->get('Router')->validate($args['_redirect'], 'Index');
$args['_redirect'] = $this->c->Router->validate($args['_redirect'], 'Index');
}
$this->titles = [
@ -68,11 +66,11 @@ class Auth extends Page
];
$this->data = [
'username' => $args['_username'],
'formAction' => $this->c->get('Router')->link('Login'),
'formToken' => $this->c->get('Csrf')->create('Login'),
'forgetLink' => $this->c->get('Router')->link('Forget'),
'formAction' => $this->c->Router->link('Login'),
'formToken' => $this->c->Csrf->create('Login'),
'forgetLink' => $this->c->Router->link('Forget'),
'regLink' => $this->config['o_regs_allow'] == '1'
? $this->c->get('Router')->link('Registration')
? $this->c->Router->link('Registration')
: null,
'formRedirect' => $args['_redirect'],
'formSave' => ! empty($args['_save'])
@ -87,9 +85,9 @@ class Auth extends Page
*/
public function loginPost()
{
$this->c->get('Lang')->load('login');
$this->c->Lang->load('login');
$v = $this->c->get('Validator');
$v = $this->c->Validator;
$v->setRules([
'token' => 'token:Login',
'redirect' => 'referer:Index',
@ -108,7 +106,7 @@ class Auth extends Page
}
if ($ok) {
return $this->c->get('Redirect')->setUrl($data['redirect'])->setMessage(__('Login redirect'));
return $this->c->Redirect->setUrl($data['redirect'])->setMessage(__('Login redirect'));
} else {
return $this->login([
'_username' => $data['username'],
@ -127,7 +125,7 @@ class Auth extends Page
*/
protected function loginProcess($username, $password, $save)
{
$user = $this->c->get('UserMapper')->getUser($username, 'username');
$user = $this->c->UserMapper->getUser($username, 'username');
if (null == $user) {
return false;
}
@ -138,7 +136,7 @@ class Auth extends Page
// For FluxBB by Visman 1.5.10.74 and above
if (strlen($hash) == 40) {
if (hash_equals($hash, sha1($password . $this->c->getParameter('SALT1')))) {
if (hash_equals($hash, sha1($password . $this->c->SALT1))) {
$hash = password_hash($password, PASSWORD_DEFAULT);
$update['password'] = $hash;
$authorized = true;
@ -159,19 +157,19 @@ class Auth extends Page
// перезаписываем ip админа и модератора - Visman
if ($user->isAdmMod
&& $this->config['o_check_ip']
&& $user->registrationIp != $this->c->get('user')->ip
&& $user->registrationIp != $this->c->user->ip
) {
$update['registration_ip'] = $this->c->get('user')->ip;
$update['registration_ip'] = $this->c->user->ip;
}
// изменения юзера в базе
$this->c->get('UserMapper')->updateUser($user->id, $update);
$this->c->UserMapper->updateUser($user->id, $update);
// обновления кэша
if (isset($update['group_id'])) {
$this->c->get('users_info update');
$this->c->{'users_info update'};
}
$this->c->get('Online')->delete($this->c->get('user'));
$this->c->get('UserCookie')->setUserCookie($user->id, $hash, $save);
$this->c->Online->delete($this->c->user);
$this->c->UserCookie->setUserCookie($user->id, $hash, $save);
return true;
}
@ -183,7 +181,7 @@ class Auth extends Page
*/
public function forget(array $args)
{
$this->c->get('Lang')->load('login');
$this->c->Lang->load('login');
$this->nameTpl = 'login/forget';
$this->onlinePos = 'forget';
@ -197,8 +195,8 @@ class Auth extends Page
];
$this->data = [
'email' => $args['_email'],
'formAction' => $this->c->get('Router')->link('Forget'),
'formToken' => $this->c->get('Csrf')->create('Forget'),
'formAction' => $this->c->Router->link('Forget'),
'formToken' => $this->c->Csrf->create('Forget'),
];
return $this;
@ -210,9 +208,9 @@ class Auth extends Page
*/
public function forgetPost()
{
$this->c->get('Lang')->load('login');
$this->c->Lang->load('login');
$v = $this->c->get('Validator');
$v = $this->c->Validator;
$v->setRules([
'token' => 'token:Forget',
'email' => 'required|email',
@ -224,7 +222,7 @@ class Auth extends Page
$data = $v->getData();
$this->iswev = $v->getErrors();
if ($ok && ($user = $this->c->get('UserMapper')->getUser($data['email'], 'email')) === null) {
if ($ok && ($user = $this->c->UserMapper->getUser($data['email'], 'email')) === null) {
$this->iswev['v'][] = __('Invalid email');
$ok = false;
}
@ -239,20 +237,20 @@ class Auth extends Page
]);
}
$mail = $this->c->get('Mail');
$mail->setFolder($this->c->getParameter('DIR_LANG'))
$mail = $this->c->Mail;
$mail->setFolder($this->c->DIR_LANG)
->setLanguage($user->language);
$key = 'p' . $this->c->get('Secury')->randomPass(75);
$hash = $this->c->get('Secury')->hash($data['email'] . $key);
$link = $this->c->get('Router')->link('ChangePassword', ['email' => $data['email'], 'key' => $key, 'hash' => $hash]);
$key = 'p' . $this->c->Secury->randomPass(75);
$hash = $this->c->Secury->hash($data['email'] . $key);
$link = $this->c->Router->link('ChangePassword', ['email' => $data['email'], 'key' => $key, 'hash' => $hash]);
$tplData = ['link' => $link];
if ($mail->send($data['email'], 'change_password.tpl', $tplData)) {
$this->c->get('UserMapper')->updateUser($user->id, ['activate_string' => $key, 'last_email_sent' => time()]);
return $this->c->get('Message')->message(__('Forget mail', $this->config['o_admin_email']), false, 200);
$this->c->UserMapper->updateUser($user->id, ['activate_string' => $key, 'last_email_sent' => time()]);
return $this->c->Message->message(__('Forget mail', $this->config['o_admin_email']), false, 200);
} else {
return $this->c->get('Message')->message(__('Error mail', $this->config['o_admin_email']), true, 200);
return $this->c->Message->message(__('Error mail', $this->config['o_admin_email']), true, 200);
}
}
@ -270,26 +268,26 @@ class Auth extends Page
unset($args['_ok']);
} else {
// что-то пошло не так
if (! hash_equals($args['hash'], $this->c->get('Secury')->hash($args['email'] . $args['key']))
|| ! $this->c->get('Mail')->valid($args['email'])
|| ($user = $this->c->get('UserMapper')->getUser($args['email'], 'email')) === null
if (! hash_equals($args['hash'], $this->c->Secury->hash($args['email'] . $args['key']))
|| ! $this->c->Mail->valid($args['email'])
|| ($user = $this->c->UserMapper->getUser($args['email'], 'email')) === null
|| empty($user->activateString)
|| $user->activateString{0} !== 'p'
|| ! hash_equals($user->activateString, $args['key'])
) {
return $this->c->get('Message')->message(__('Bad request'), false);
return $this->c->Message->message(__('Bad request'), false);
}
}
$this->c->get('Lang')->load('login');
$this->c->get('Lang')->load('profile');
$this->c->Lang->load('login');
$this->c->Lang->load('profile');
$this->titles = [
__('Change pass'),
];
$this->data = [
'formAction' => $this->c->get('Router')->link('ChangePassword', $args),
'formToken' => $this->c->get('Csrf')->create('ChangePassword', $args),
'formAction' => $this->c->Router->link('ChangePassword', $args),
'formToken' => $this->c->Csrf->create('ChangePassword', $args),
];
return $this;
@ -302,22 +300,22 @@ class Auth extends Page
*/
public function changePassPost(array $args)
{
$this->c->get('Lang')->load('login');
$this->c->Lang->load('login');
// что-то пошло не так
if (! hash_equals($args['hash'], $this->c->get('Secury')->hash($args['email'] . $args['key']))
|| ! $this->c->get('Mail')->valid($args['email'])
|| ($user = $this->c->get('UserMapper')->getUser($args['email'], 'email')) === null
if (! hash_equals($args['hash'], $this->c->Secury->hash($args['email'] . $args['key']))
|| ! $this->c->Mail->valid($args['email'])
|| ($user = $this->c->UserMapper->getUser($args['email'], 'email')) === null
|| empty($user->activateString)
|| $user->activateString{0} !== 'p'
|| ! hash_equals($user->activateString, $args['key'])
) {
return $this->c->get('Message')->message(__('Bad request'), false);
return $this->c->Message->message(__('Bad request'), false);
}
$this->c->get('Lang')->load('profile');
$this->c->Lang->load('profile');
$v = $this->c->get('Validator');
$v = $this->c->Validator;
$v->setRules([
'token' => 'token:ChangePassword',
'password' => ['required|string|min:8', __('New pass')],
@ -335,9 +333,9 @@ class Auth extends Page
}
$data = $v->getData();
$this->c->get('UserMapper')->updateUser($user->id, ['password' => password_hash($data['password'], PASSWORD_DEFAULT), 'activate_string' => null]);
$this->c->UserMapper->updateUser($user->id, ['password' => password_hash($data['password'], PASSWORD_DEFAULT), 'activate_string' => null]);
$this->iswev['s'][] = __('Pass updated');
return $this->login(['_redirect' => $this->c->get('Router')->link('Index')]);
return $this->login(['_redirect' => $this->c->Router->link('Index')]);
}
}

View file

@ -23,14 +23,14 @@ class Debug extends Page
public function debug()
{
$this->data = [
'time' => $this->number(microtime(true) - (empty($_SERVER['REQUEST_TIME_FLOAT']) ? $this->c->getParameter('START') : $_SERVER['REQUEST_TIME_FLOAT']), 3),
'numQueries' => $this->c->get('DB')->get_num_queries(),
'time' => $this->number(microtime(true) - (empty($_SERVER['REQUEST_TIME_FLOAT']) ? $this->c->START : $_SERVER['REQUEST_TIME_FLOAT']), 3),
'numQueries' => $this->c->DB->get_num_queries(),
'memory' => $this->size(memory_get_usage()),
'peak' => $this->size(memory_get_peak_usage()),
];
if (defined('PUN_SHOW_QUERIES')) {
$this->data['queries'] = $this->c->get('DB')->get_saved_queries();
$this->data['queries'] = $this->c->DB->get_saved_queries();
} else {
$this->data['queries'] = null;
}

View file

@ -36,14 +36,14 @@ class Index extends Page
*/
public function view()
{
$this->c->get('Lang')->load('index');
$this->c->get('Lang')->load('subforums');
$this->c->Lang->load('index');
$this->c->Lang->load('subforums');
$db = $this->c->get('DB');
$user = $this->c->get('user');
$r = $this->c->get('Router');
$db = $this->c->DB;
$user = $this->c->user;
$r = $this->c->Router;
$stats = $this->c->get('users_info');
$stats = $this->c->users_info;
$result = $db->query('SELECT SUM(num_topics), SUM(num_posts) FROM '.$db->prefix.'forums') or error('Unable to fetch topic/post count', __FILE__, __LINE__, $db->error());
list($stats['total_topics'], $stats['total_posts']) = array_map([$this, 'number'], array_map('intval', $db->fetch_row($result)));
@ -70,7 +70,7 @@ class Index extends Page
$this->data['online']['max_time'] = $this->time($this->config['st_max_users_time']);
// данные онлайн посетителей
list($users, $guests, $bots) = $this->c->get('Online')->handle($this);
list($users, $guests, $bots) = $this->c->Online->handle($this);
$list = [];
if ($user->gViewUsers == '1') {
@ -105,7 +105,7 @@ class Index extends Page
$this->data['online']['list'] = $list;
} else {
$this->onlineType = false;
$this->c->get('Online')->handle($this);
$this->c->Online->handle($this);
$this->data['online'] = null;
}
$this->data['forums'] = $this->getForumsData();
@ -119,15 +119,15 @@ class Index extends Page
*/
protected function getForumsData($root = 0)
{
list($fTree, $fDesc, $fAsc) = $this->c->get('forums');
list($fTree, $fDesc, $fAsc) = $this->c->forums;
// раздел $root не имеет подразделов для вывода или они не доступны
if (empty($fTree[$root])) {
return [];
}
$db = $this->c->get('DB');
$user = $this->c->get('user');
$db = $this->c->DB;
$user = $this->c->user;
// текущие данные по подразделам
$forums = array_slice($fAsc[$root], 1);
@ -168,7 +168,7 @@ class Index extends Page
}
}
$r = $this->c->get('Router');
$r = $this->c->Router;
// формированием таблицы разделов
$result = [];

View file

@ -2,7 +2,7 @@
namespace ForkBB\Models\Pages;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
class Maintenance extends Page
{
@ -32,13 +32,13 @@ class Maintenance extends Page
/**
* Конструктор
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
$this->config = $container->get('config');
$container->get('Lang')->load('common', $this->config['o_default_lang']);
$this->config = $container->config;
$container->Lang->load('common', $this->config['o_default_lang']);
}
/**

View file

@ -2,14 +2,14 @@
namespace ForkBB\Models\Pages;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
use RuntimeException;
abstract class Page
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -85,13 +85,13 @@ abstract class Page
/**
* Конструктор
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
$this->config = $container->get('config');
$container->get('Lang')->load('common');
$this->config = $container->config;
$container->Lang->load('common');
}
/**
@ -170,7 +170,7 @@ abstract class Page
'fNavigation' => $this->fNavigation(),
'fIndex' => $this->index,
'fAnnounce' => $this->fAnnounce(),
'fRootLink' => $this->c->get('Router')->link('Index'),
'fRootLink' => $this->c->Router->link('Index'),
'fIswev' => $this->getIswev(),
];
}
@ -182,9 +182,9 @@ abstract class Page
protected function getIswev()
{
if ($this->config['o_maintenance'] == '1') {
$user = $this->c->get('user');
$user = $this->c->user;
if ($user->isAdmMod) {
$this->iswev['w'][] = '<a href="' . $this->c->get('Router')->link('AdminOptions', ['#' => 'maintenance']). '">' . __('Maintenance mode enabled') . '</a>';
$this->iswev['w'][] = '<a href="' . $this->c->Router->link('AdminOptions', ['#' => 'maintenance']). '">' . __('Maintenance mode enabled') . '</a>';
}
}
return $this->iswev;
@ -225,8 +225,8 @@ abstract class Page
*/
protected function fNavigation()
{
$user = $this->c->get('user');
$r = $this->c->get('Router');
$user = $this->c->user;
$r = $this->c->Router;
$nav = [
'index' => [$r->link('Index'), __('Index')]
@ -263,7 +263,7 @@ abstract class Page
}
$nav['logout'] = [$r->link('Logout', [
'token' => $this->c->get('Csrf')->create('Logout'),
'token' => $this->c->Csrf->create('Logout'),
]), __('Logout')];
}
@ -357,16 +357,16 @@ abstract class Page
return __('Never');
}
$user = $this->c->get('user');
$user = $this->c->user;
$diff = ($user->timezone + $user->dst) * 3600;
$timestamp += $diff;
if (null === $dateFormat) {
$dateFormat = $this->c->getParameter('date_formats')[$user->dateFormat];
$dateFormat = $this->c->date_formats[$user->dateFormat];
}
if(null === $timeFormat) {
$timeFormat = $this->c->getParameter('time_formats')[$user->timeFormat];
$timeFormat = $this->c->time_formats[$user->timeFormat];
}
$date = gmdate($dateFormat, $timestamp);

View file

@ -39,7 +39,7 @@ class Redirect extends Page
*/
public function setPage($marker, array $args = [])
{
$this->link = $this->c->get('Router')->link($marker, $args);
$this->link = $this->c->Router->link($marker, $args);
return $this;
}

View file

@ -3,14 +3,14 @@
namespace ForkBB\Models;
use ForkBB\Core\AbstractModel;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
use RuntimeException;
class User extends AbstractModel
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -38,13 +38,13 @@ class User extends AbstractModel
/**
* Конструктор
*/
public function __construct(array $data, ContainerInterface $container)
public function __construct(array $data, Container $container)
{
$this->now = time();
$this->c = $container;
$this->config = $container->get('config');
$this->userCookie = $container->get('UserCookie');
$this->db = $container->get('DB');
$this->config = $container->config;
$this->userCookie = $container->UserCookie;
$this->db = $container->DB;
parent::__construct($data);
}
@ -89,7 +89,7 @@ class User extends AbstractModel
protected function getLanguage()
{
if ($this->isGuest
|| ! file_exists($this->c->getParameter('DIR_LANG') . '/' . $this->data['language'] . '/common.po')
|| ! file_exists($this->c->DIR_LANG . '/' . $this->data['language'] . '/common.po')
) {
return $this->config['o_default_lang'];
} else {
@ -100,7 +100,7 @@ class User extends AbstractModel
protected function getStyle()
{
if ($this->isGuest
//??? || ! file_exists($this->c->getParameter('DIR_LANG') . '/' . $this->data['language'])
//??? || ! file_exists($this->c->DIR_LANG . '/' . $this->data['language'])
) {
return $this->config['o_default_style'];
} else {

View file

@ -4,7 +4,7 @@ namespace ForkBB\Models;
use ForkBB\Core\Cookie;
use ForkBB\Core\Secury;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
class UserCookie extends Cookie
{
@ -14,7 +14,7 @@ class UserCookie extends Cookie
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -45,9 +45,9 @@ class UserCookie extends Cookie
/**
* Конструктор
*
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(Secury $secury, array $options, ContainerInterface $container)
public function __construct(Secury $secury, array $options, Container $container)
{
parent::__construct($secury, $options);
$this->c = $container;
@ -125,11 +125,11 @@ class UserCookie extends Cookie
&& $this->remember
)
) {
$expTime = time() + $this->c->getParameter('TIME_REMEMBER');
$expTime = time() + $this->c->TIME_REMEMBER;
$expire = $expTime;
$pfx = '';
} else {
$expTime = time() + $this->c->get('config')['o_timeout_visit'];
$expTime = time() + $this->c->config['o_timeout_visit'];
$expire = 0;
$pfx = '-';
}

View file

@ -3,7 +3,7 @@
namespace ForkBB\Models;
use ForkBB\Models\User;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
use RuntimeException;
use InvalidArgumentException;
@ -11,7 +11,7 @@ class UserMapper
{
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -27,13 +27,13 @@ class UserMapper
/**
* Конструктор
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
$this->config = $container->get('config');
$this->db = $container->get('DB');
$this->config = $container->config;
$this->db = $container->DB;
}
/**

View file

@ -2,7 +2,7 @@
namespace ForkBB\Models;
use R2\DependencyInjection\ContainerInterface;
use ForkBB\Core\Container;
use RuntimeException;
class Validator
@ -15,7 +15,7 @@ class Validator
/**
* Контейнер
* @var ContainerInterface
* @var Container
*/
protected $c;
@ -57,9 +57,9 @@ class Validator
/**
* Конструктор
* @param ContainerInterface $container
* @param Container $container
*/
public function __construct(ContainerInterface $container)
public function __construct(Container $container)
{
$this->c = $container;
}
@ -157,7 +157,7 @@ class Validator
list($value, $error) = $this->requiredRule('', $attr, $args);
} else {
$value = isset($raw[$field])
? $this->c->get('Secury')->replInvalidChars($raw[$field])
? $this->c->Secury->replInvalidChars($raw[$field])
: null;
// перебор правил для текущего поля
foreach ($rules as $rule => $attr) {
@ -380,7 +380,7 @@ class Validator
if (! is_array($args)) {
$args = [];
}
if (is_string($value) && $this->c->get('Csrf')->verify($value, $attr, $args)) {
if (is_string($value) && $this->c->Csrf->verify($value, $attr, $args)) {
return [$value, false];
} else {
return ['', ['Bad token', 'e']];
@ -397,12 +397,12 @@ class Validator
if (! is_array($args)) {
$args = [];
}
return [$this->c->get('Router')->validate($value, $attr), false];
return [$this->c->Router->validate($value, $attr), false];
}
protected function emailRule($value, $attr)
{
if ($this->c->get('Mail')->valid($value)) {
if ($this->c->Mail->valid($value)) {
return [$value, false];
} else {
if (! is_string($value)) {

View file

@ -2,7 +2,7 @@
namespace ForkBB;
use R2\DependencyInjection\Container;
use ForkBB\Core\Container;
use ForkBB\Models\Pages\Page;
use Exception;
@ -47,31 +47,31 @@ if (file_exists(__DIR__ . '/config/main.php')) {
define('PUN', 1);
$container->setParameter('DIR_CONFIG', __DIR__ . '/config');
$container->setParameter('DIR_CACHE', __DIR__ . '/cache');
$container->setParameter('DIR_VIEWS', __DIR__ . '/templates');
$container->setParameter('DIR_LANG', __DIR__ . '/lang');
$container->setParameter('START', $pun_start);
$container->DIR_CONFIG = __DIR__ . '/config';
$container->DIR_CACHE = __DIR__ . '/cache';
$container->DIR_VIEWS = __DIR__ . '/templates';
$container->DIR_LANG = __DIR__ . '/lang';
$container->START = $pun_start;
$config = $container->get('config');
$container->setParameter('date_formats', [$config['o_date_format'], 'Y-m-d', 'Y-d-m', 'd-m-Y', 'm-d-Y', 'M j Y', 'jS M Y']);
$container->setParameter('time_formats', [$config['o_time_format'], 'H:i:s', 'H:i', 'g:i:s a', 'g:i a']);
$config = $container->config;
$container->date_formats = [$config['o_date_format'], 'Y-m-d', 'Y-d-m', 'd-m-Y', 'm-d-Y', 'M j Y', 'jS M Y'];
$container->time_formats = [$config['o_time_format'], 'H:i:s', 'H:i', 'g:i:s a', 'g:i a'];
$page = null;
$controllers = ['Routing', 'Primary'];
while (! $page instanceof Page && $cur = array_pop($controllers)) {
$page = $container->get($cur);
$page = $container->$cur;
}
if ($page instanceof Page) { //????
if ($page->getDataForOnline(true)) {
$container->get('Online')->handle($page);
$container->Online->handle($page);
}
$tpl = $container->get('View')->setPage($page)->outputPage();
$tpl = $container->View->setPage($page)->outputPage();
if (defined('PUN_DEBUG')) {
$debug = $container->get('Debug')->debug();
$debug = $container->get('View')->setPage($debug)->outputPage();
$debug = $container->Debug->debug();
$debug = $container->View->setPage($debug)->outputPage();
$tpl = str_replace('<!-- debuginfo -->', $debug, $tpl);
}
exit($tpl);

View file

@ -11,15 +11,8 @@
"homepage": "https://github.com/MioVisman"
}
],
"repositories": [
{
"type": "vcs",
"url": "https://github.com/MioVisman/container"
}
],
"require": {
"php": ">=5.6.0",
"artoodetoo/container": "dev-visman",
"artoodetoo/dirk": "dev-master"
}
}

46
composer.lock generated
View file

@ -4,50 +4,9 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "66793e0ac7d0499d9403c353c1a60b7b",
"content-hash": "8160828b885585e30e73fe34aaca440c",
"hash": "6c899de021c8c6537d723a4f7d26f06d",
"content-hash": "b734e8bdbede86eb0dbd047bb31d3a03",
"packages": [
{
"name": "artoodetoo/container",
"version": "dev-visman",
"source": {
"type": "git",
"url": "https://github.com/MioVisman/container.git",
"reference": "bf147763641e3b6362286d3401b3ee55b2c2760e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MioVisman/container/zipball/bf147763641e3b6362286d3401b3ee55b2c2760e",
"reference": "bf147763641e3b6362286d3401b3ee55b2c2760e",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"type": "library",
"autoload": {
"psr-4": {
"R2\\DependencyInjection\\": "src/"
}
},
"license": [
"MIT"
],
"authors": [
{
"name": "artoodetoo"
}
],
"description": "Yet another service container",
"keywords": [
"container",
"service"
],
"support": {
"source": "https://github.com/MioVisman/container/tree/visman"
},
"time": "2017-01-23 11:54:39"
},
{
"name": "artoodetoo/dirk",
"version": "dev-master",
@ -99,7 +58,6 @@
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {
"artoodetoo/container": 20,
"artoodetoo/dirk": 20
},
"prefer-stable": false,

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2016
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,110 +0,0 @@
# Container
Yet another service container
Container **DOES NOT** use reflection and type hint information in any form.
## Features
Container keep two kind of values: services and parameters.
Service will instantiated when you call call it by name. _Usually_ service is object type, but not nesessary. Mind it as
"product" of some routine.
Methods: `get()` and `set()`.
Parameters are not instantiating, they just stored and retrieved.
Methods: `getParameter()` and `setParameter()`.
## Install
To install with composer:
```sh
composer require artoodetoo/container
```
## Basic Usage
### Configuration
There are special configuraton sections:
- root used to store basic values, which can be substituted into service definition.
- `shared` node defines shared services. after it created once it can be retrieved many times.
- `multiple` node defines new instance created on every get() call
In other sections you can store any kind of information and retrieve it in dot notation (see below).
### Simple service definition
```php
use R2\DependancyInjection\Container;
$config = [
'shared' => [
'view' => R2\Templating\Dirk::class
]
];
$c = new Container($config);
$c->get('view')->render('index');
```
### Parameters substitution
```php
$config = [
'ROOT' => '\var\www\mysite',
'PUBLIC' => '\var\www\mysite\public',
'shared' => [
'view' => [
'class=' => R2\Templating\Dirk::class,
'options' => [
'views' => '%ROOT%/views',
'cache' => '%ROOT%/cache',
],
...
]
];
...
$c->get('view')->render('index');
```
### Factory method
```php
$config = [
'shared' => [
'userManager' => App\UserManager::class,
'user' => '@userManager:getCurrentUser',
...
]
]
...
echo $c->get('user')->username;
```
### Parameters and dot notation:
```php
$config = [
'options' => [
'cookie' => [
'name' => 'the-cookie',
'domain' => '.example.com'
]
];
...
setcookie(
$c->getParameter('options.cookie.name'),
$value,
0,
'/',
$c->getParameter('options.cookie.domain')
);
```
### Notes and Limits
Any part of configuration can be read by getParameter, including special sections `shared` and `multiple`.
As for now, substitution patterns work in service production only.
Only parameters from config root can be used in substitution patterns.
### License
The Container is open-source software, licensed under the [MIT license](http://opensource.org/licenses/MIT)

View file

@ -1,19 +0,0 @@
{
"name": "artoodetoo/container",
"description": "Yet another service container",
"keywords": ["service", "container"],
"license": "MIT",
"authors": [
{
"name": "artoodetoo"
}
],
"require": {
"php": ">=5.6"
},
"autoload": {
"psr-4": {
"R2\\DependencyInjection\\": "src/"
}
}
}

View file

@ -1,173 +0,0 @@
<?php
namespace R2\DependencyInjection;
use InvalidArgumentException;
use R2\DependencyInjection\ContainerInterface;
use R2\DependencyInjection\ContainerAwareInterface;
/**
* Service Container
*/
class Container implements ContainerInterface
{
private $instances = [];
private $config = [ 'shared' => [], 'multiple' => [] ];
public function __construct(array $config = null)
{
if (!empty($config)) {
$this->config($config);
}
$this->config['CONTAINER'] = $this;
}
public function config(array $config)
{
$this->config = array_replace_recursive($this->config, $config);
}
/**
* Gets a service.
*
* @param string $id The service identifier
*
* @return mixed The associated service
*/
public function get($id)
{
if (isset($this->instances[$id])) {
return $this->instances[$id];
}
$toShare = false;
if (isset($this->config['shared'][$id])) {
$toShare = true;
$config = (array) $this->config['shared'][$id];
} elseif (isset($this->config['multiple'][$id])) {
$config = (array) $this->config['multiple'][$id];
} else {
throw new \InvalidArgumentException('Wrong property name '.$id);
}
// N.B. "class" is just the first element, regardless of its key
$class = array_shift($config);
$args = [];
// If you want to susbtitute some values in arguments, use non-numeric keys for them
foreach ($config as $k => $v) {
$args[] = is_numeric($k) ? $v : $this->resolve($v);
}
// Special case: reference to factory method
if ($class{0} == '@' && strpos($class, ':') !== false) {
list($factoryName, $methodName) = explode(':', substr($class, 1));
$f = [$this->get($factoryName), $methodName]; /** @var string $f suppress IDE warning :( */
$service = $f(...$args);
} else {
$service = new $class(...$args);
}
if ($toShare) {
$this->instances[$id] = $service;
}
return $service;
}
/**
* Sets a service.
* Provides a fluent interface.
*
* @param string $id The service identifier
* @param mixed $service The service instance
*
* @return ContainerInterface Self reference
*/
public function set($id, $service)
{
$this->instances[$id] = $service;
return $this;
}
/**
* Gets a parameter.
*
* @param string $name The parameter name
*
* @return mixed The parameter value
*/
public function getParameter($name, $default = null)
{
$segments = explode('.', $name);
$ptr =& $this->config;
foreach ($segments as $s) {
if (isset($ptr[$s])
|| (is_array($ptr) && array_key_exists($s, $ptr))
) {
$ptr =& $ptr[$s];
} else {
return $default;
}
}
return $ptr;
}
/**
* Sets a parameter.
* Provides a fluent interface.
*
* @param string $name The parameter name
* @param mixed $value The parameter value
*
* @return ContainerInterface Self reference
*/
public function setParameter($name, $value)
{
$segments = explode('.', $name);
$n = count($segments);
$ptr =& $this->config;
foreach ($segments as $s) {
if (--$n) {
if (!array_key_exists($s, $ptr)) {
$ptr[$s] = [];
} elseif (!is_array($ptr[$s])) {
throw new \InvalidArgumentException("Scalar \"{$s}\" in the path \"{$name}\"");
}
$ptr =& $ptr[$s];
} else {
$ptr[$s] = $value;
}
}
return $this;
}
protected function resolve($value)
{
if (is_string($value)) {
if (strpos($value, '%') !== false) {
// whole string substitution can return any type of value
if (preg_match('~^%(\w+(?:\.\w+)*)%$~', $value, $matches)) {
$value = $this->getParameter($matches[1]);
// partial string substitution casts value to string
} else {
$value = preg_replace_callback('~%(\w+(?:\.\w+)*)%~',
function ($matches) {
return $this->getParameter($matches[1], '');
}, $value);
}
} elseif (isset($value{0}) && $value{0} === '@') {
// получение данных из объекта как массива по индексу
if (preg_match('~^@([\w-]+)\[(\w+)\]$~', $value, $matches)) {
$obj = $this->get($matches[1]);
return isset($obj[$matches[2]]) ? $obj[$matches[2]] : null;
} else {
return $this->get(substr($value, 1));
}
}
} elseif (is_array($value)) {
foreach ($value as &$v) {
$v = $this->resolve($v);
}
unset($v);
}
return $value;
}
}

View file

@ -1,16 +0,0 @@
<?php
namespace R2\DependencyInjection;
interface ContainerAwareInterface
{
/**
* Sets the Container.
* Provides a fluent interface.
*
* @param ContainerInterface $container A ContainerInterface instance
*
* @return $this
*/
public function setContainer(ContainerInterface $container);
}

View file

@ -1,43 +0,0 @@
<?php
namespace R2\DependencyInjection;
interface ContainerInterface
{
/**
* Gets a service.
*
* @param string $id The service identifier
*
* @return mixed The associated service
*/
public function get($id);
/**
* Sets a service.
* Provides a fluent interface.
*
* @param string $id The service identifier
* @param mixed $service The service instance
*
* @return ContainerInterface Self reference
*/
public function set($id, $service);
/**
* Gets a parameter.
*
* @param string $name The parameter name
*
* @return mixed The parameter value
*/
public function getParameter($name);
/**
* Sets a parameter.
* Provides a fluent interface.
*
* @param string $name The parameter name
* @param mixed $value The parameter value
*
* @return ContainerInterface Self reference
*/
public function setParameter($name, $value);
}

View file

@ -7,5 +7,4 @@ $baseDir = dirname($vendorDir);
return array(
'R2\\Templating\\' => array($vendorDir . '/artoodetoo/dirk/src'),
'R2\\DependencyInjection\\' => array($vendorDir . '/artoodetoo/container/src'),
);

View file

@ -10,7 +10,6 @@ class ComposerStaticInit90ad93c7251d4f60daa9e545879c49e7
'R' =>
array (
'R2\\Templating\\' => 14,
'R2\\DependencyInjection\\' => 23,
),
);
@ -19,10 +18,6 @@ class ComposerStaticInit90ad93c7251d4f60daa9e545879c49e7
array (
0 => __DIR__ . '/..' . '/artoodetoo/dirk/src',
),
'R2\\DependencyInjection\\' =>
array (
0 => __DIR__ . '/..' . '/artoodetoo/container/src',
),
);
public static function getInitializer(ClassLoader $loader)

View file

@ -46,48 +46,5 @@
"templating",
"views"
]
},
{
"name": "artoodetoo/container",
"version": "dev-visman",
"version_normalized": "dev-visman",
"source": {
"type": "git",
"url": "https://github.com/MioVisman/container.git",
"reference": "bf147763641e3b6362286d3401b3ee55b2c2760e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MioVisman/container/zipball/bf147763641e3b6362286d3401b3ee55b2c2760e",
"reference": "bf147763641e3b6362286d3401b3ee55b2c2760e",
"shasum": ""
},
"require": {
"php": ">=5.6"
},
"time": "2017-01-23 11:54:39",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"R2\\DependencyInjection\\": "src/"
}
},
"license": [
"MIT"
],
"authors": [
{
"name": "artoodetoo"
}
],
"description": "Yet another service container",
"keywords": [
"container",
"service"
],
"support": {
"source": "https://github.com/MioVisman/container/tree/visman"
}
}
]