Skip to content

Commit

Permalink
added kernel component
Browse files Browse the repository at this point in the history
  • Loading branch information
metalagman committed Jul 11, 2017
1 parent 8725c4f commit 513f0ee
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 0 deletions.
82 changes: 82 additions & 0 deletions src/Kernel/Kernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
/**
* @author Alexey Samoylov <[email protected]>
*/

namespace YarCode\Yii2\Kernel;

use yii\base\BootstrapInterface;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;

class Kernel extends Component implements BootstrapInterface
{
/** @var KernelPlugin[] */
protected $plugins = [];

public function bootstrap($app)
{
static::getInstance();
}

/**
* @return static
* @throws \yii\base\InvalidConfigException
*/
public static function getInstance()
{
return \Yii::$app->get('kernel');
}

/**
* @param array $config
*/
public function setPlugins($config)
{
if (!is_array($config)) {
throw new \LogicException("Plugins configuration must be an array");
}

foreach ($config as $pluginClassName) {
$this->registerPlugin($pluginClassName);
}
}

/**
* @param string $className
* @throws InvalidConfigException
*/
public function registerPlugin($className)
{
if (!class_exists($className)) {
throw new \LogicException("Unknown plugin className {$className}");
}

if (isset($this->plugins[$className])) {
return;
}

/** @var KernelPlugin $plugin */
$plugin = \Yii::createObject($className);
$plugin->kernel = $this;
$this->plugins[$className] = $plugin;
$this->plugins[$className]->bootstrap();
}

/**
* @param $class
* @return KernelPlugin
*/
public function getPlugin($class)
{
$plugin = ArrayHelper::getValue($this->plugins, $class);

if (null === $plugin) {
throw new \LogicException("Unknown plugin: {$class}");
}

return $plugin;
}

}
34 changes: 34 additions & 0 deletions src/Kernel/KernelPlugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
namespace YarCode\Yii2\Kernel;

use yii\base\Component;

abstract class KernelPlugin extends Component
{
/** @var Kernel */
public $kernel;

/**
* Bootstrap method for this plugin
*/
abstract public function bootstrap();

/**
* Plugin instance getter
* @return static
*/
public static function getInstance()
{
return Kernel::getInstance()->getPlugin(static::class);
}

/**
* Performs active transaction check and fails if the transaction is missing
*/
protected function ensureDbTransaction()
{
if (null === \Yii::$app->db->transaction) {
throw new \LogicException('You must use DB transaction to call ' . __METHOD__);
}
}
}

0 comments on commit 513f0ee

Please sign in to comment.