Skip to content

Commit

Permalink
Refactored AssignSwitches for Hubs and Servers (#76)
Browse files Browse the repository at this point in the history
* Refactored `AssignSwitches` for Hubs and Servers

* minor
  • Loading branch information
tafid authored and hiqsol committed Apr 1, 2019
1 parent 678f4c5 commit d13b924
Show file tree
Hide file tree
Showing 18 changed files with 421 additions and 173 deletions.
37 changes: 37 additions & 0 deletions src/controllers/HubController.php
Expand Up @@ -21,11 +21,13 @@
use hipanel\filters\EasyAccessControl;
use hipanel\helpers\ArrayHelper;
use hipanel\models\Ref;
use hipanel\modules\server\forms\AssignSwitchesForm;
use hipanel\modules\server\forms\HubSellForm;
use hipanel\modules\server\models\HardwareSettings;
use hiqdev\hiart\Collection;
use Yii;
use yii\base\Event;
use yii\web\NotFoundHttpException;

class HubController extends CrudController
{
Expand Down Expand Up @@ -143,6 +145,41 @@ public function actions()
}
},
],
'assign-switches' => [
'class' => SmartUpdateAction::class,
'success' => Yii::t('hipanel:server:hub', 'Switches have been edited'),
'view' => 'assign-switches',
'on beforeFetch' => function (Event $event) {
/** @var \hipanel\actions\SearchAction $action */
$action = $event->sender;
$dataProvider = $action->getDataProvider();
$dataProvider->query->withBindings()->select(['*']);
},
'collection' => [
'class' => Collection::class,
'model' => new AssignSwitchesForm(),
'scenario' => 'default',
],
'data' => function (Action $action, array $data) {
$result = [];
foreach ($data['models'] as $model) {
$result['models'][] = AssignSwitchesForm::fromOriginalModel($model);
}
if (!$result['models']) {
throw new NotFoundHttpException('There are no entries available for the selected operation.');
}
$result['model'] = reset($result['models']);

return $result;
},
],
'validate-switches-form' => [
'class' => ValidateFormAction::class,
'collection' => [
'class' => Collection::class,
'model' => new AssignSwitchesForm(),
],
],
'validate-sell-form' => [
'class' => ValidateFormAction::class,
'collection' => [
Expand Down
4 changes: 2 additions & 2 deletions src/controllers/ServerController.php
Expand Up @@ -202,7 +202,7 @@ public function actions()
],
'assign-hubs' => [
'class' => SmartUpdateAction::class,
'success' => Yii::t('hipanel:server', 'Hubs were assigned'),
'success' => Yii::t('hipanel:server', 'Hubs have been assigned'),
'view' => 'assignHubs',
'on beforeFetch' => function (Event $event) {
/** @var \hipanel\actions\SearchAction $action */
Expand All @@ -218,7 +218,7 @@ public function actions()
'data' => function (Action $action, array $data) {
$result = [];
foreach ($data['models'] as $model) {
$result['models'][] = AssignHubsForm::fromServer($model);
$result['models'][] = AssignHubsForm::fromOriginalModel($model);
}
if (!$result['models']) {
throw new NotFoundHttpException('There are no entries available for the selected operation. The type of selected records may not be suitable for the selected operation.');
Expand Down
85 changes: 8 additions & 77 deletions src/forms/AssignHubsForm.php
Expand Up @@ -2,7 +2,7 @@

namespace hipanel\modules\server\forms;

use hipanel\modules\server\models\Binding;
use hipanel\base\ModelTrait;
use hipanel\modules\server\models\Server;
use Yii;

Expand All @@ -11,47 +11,27 @@
*/
class AssignHubsForm extends Server
{
use \hipanel\base\ModelTrait;
use ModelTrait;

/**
* @inheritdoc
* @var array
*/
public static function tableName()
{
return 'server';
}
public $switchVariants = ['net', 'kvm', 'pdu', 'rack', 'pdu2', 'nic2', 'ipmi'];

/**
* Create AttachHubsForm model from Server model
*
* @param Server $server
* @return AssignHubsForm
* @inheritdoc
*/
public static function fromServer(Server $server): AssignHubsForm
public static function tableName()
{
$attributes = array_merge($server->getAttributes(), []);
$model = new self(['scenario' => 'default']);
foreach ($server->bindings as $binding) {
if ($model->hasAttribute($binding->typeWithNo . '_id')) {
$attributes[$binding->typeWithNo . '_id'] = $binding->switch_id;
$attributes[$binding->typeWithNo . '_port'] = $binding->port;
}
}
$model->setAttributes($attributes);

return $model;
return 'server';
}

/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), [
[['id'], 'required'],
[['net_id', 'kvm_id', 'pdu_id', 'rack_id', 'pdu2_id', 'nic2_id', 'ipmi_id'], 'integer'],
[['net_port', 'kvm_port', 'pdu_port', 'rack_port', 'pdu2_port', 'nic2_port', 'ipmi_port'], 'string'],
], $this->generateUniqueValidators());
return array_merge(parent::rules(), $this->defaultSwitchRules(), $this->generateUniqueValidators());
}

public function attributeLabels()
Expand All @@ -61,54 +41,5 @@ public function attributeLabels()
'nic2' => Yii::t('hipanel:server', 'Switch 2'),
]);
}

/**
* For compatibility with [[hiqdev\hiart\Collection]]
*
* @param $defaultScenario
* @param array $data
* @param array $options
* @return mixed
*/
public function batchQuery($defaultScenario, $data = [], array $options = [])
{
$map = [
'update' => 'assign-hubs',
];
$scenario = isset($map[$defaultScenario]) ? $map[$defaultScenario] : $defaultScenario;

return (new Server)->batchQuery($scenario, $data, $options);
}

private function generateUniqueValidators(): array
{
$rules = [];

foreach (['net', 'kmv', 'pdu', 'rack', 'pdu2', 'nic2', 'ipmi'] as $variant) {
$rules[] = [
[$variant . '_port'],
function ($attribute, $params, $validator) use ($variant) {
if ($this->{$attribute} && $this->{$variant . '_id'}) {
$query = Binding::find();
$query->andWhere(['port' => $this->{$attribute}]);
$query->andWhere(['switch_id' => $this->{$variant . '_id'}]);
$query->andWhere(['ne', 'base_device_id', $this->id]);
/** @var Binding[] $bindings */
$bindings = $query->all();
if (!empty($bindings)) {
$binding = reset($bindings);
$this->addError($attribute, Yii::t('hipanel:server', '{switch}::{port} already taken by {device}', [
'switch' => $binding->switch_name,
'port' => $binding->port,
'device' => $binding->device_name,
]));
}
}
},
];
}

return $rules;
}
}

30 changes: 30 additions & 0 deletions src/forms/AssignSwitchesForm.php
@@ -0,0 +1,30 @@
<?php

namespace hipanel\modules\server\forms;

use hipanel\base\ModelTrait;
use hipanel\modules\server\models\AssignSwitchInterface;
use hipanel\modules\server\models\Hub;

class AssignSwitchesForm extends Hub implements AssignSwitchInterface
{
use ModelTrait;

public $switchVariants = ['net', 'kvm', 'pdu', 'rack', 'console'];

/**
* @inheritdoc
*/
public static function tableName()
{
return 'hub';
}

/**
* @inheritdoc
*/
public function rules()
{
return array_merge(parent::rules(), $this->defaultSwitchRules(), $this->generateUniqueValidators());
}
}
13 changes: 12 additions & 1 deletion src/menus/HubDetailMenu.php
Expand Up @@ -10,14 +10,25 @@

namespace hipanel\modules\server\menus;

use Yii;

class HubDetailMenu extends \hipanel\menus\AbstractDetailMenu
{
public $model;

public function items()
{
$actions = HubActionsMenu::create(['model' => $this->model])->items();
$items = array_merge($actions, []);
$items = array_merge($actions, [
'assign-switches' => [
'label' => Yii::t('hipanel:server', 'Switches'),
'icon' => 'fa-plug',
'url' => ['@hub/assign-switches', 'id' => $this->model->id],
'linkOptions' => [
'data-pjax' => 0,
],
],
]);
unset($items['view']);

return $items;
Expand Down
2 changes: 1 addition & 1 deletion src/menus/ServerActionsMenu.php
Expand Up @@ -52,7 +52,7 @@ public function items(): array
],
'assign-hubs' => [
'label' => Yii::t('hipanel:server', 'Assign hubs'),
'icon' => 'fa-exchange',
'icon' => 'fa-plug',
'url' => ['@server/assign-hubs', 'id' => $this->model->id],
'visible' => Yii::$app->user->can('server.update'),
'linkOptions' => [
Expand Down
1 change: 1 addition & 0 deletions src/messages/ru/hipanel:server.php
Expand Up @@ -308,4 +308,5 @@
'Mail settings have been changed successfully' => 'Настройки почты были успешно изменены',
'Number of mailboxes' => 'Количество почтовых ящиков',
'View parts' => 'Смотреть детали',
'Hubs have been assigned' => 'Свитчи назначены',
];
8 changes: 8 additions & 0 deletions src/models/AssignSwitchInterface.php
@@ -0,0 +1,8 @@
<?php

namespace hipanel\modules\server\models;

interface AssignSwitchInterface
{
public function getBindings();
}
18 changes: 16 additions & 2 deletions src/models/Hub.php
Expand Up @@ -10,13 +10,16 @@

namespace hipanel\modules\server\models;

use hipanel\base\ModelTrait;
use hipanel\modules\server\models\query\HubQuery;
use hipanel\modules\server\models\traits\AssignSwitchTrait;
use hipanel\modules\server\validators\MacValidator;
use hiqdev\hiart\ActiveQuery;
use Yii;

class Hub extends \hipanel\base\Model
class Hub extends \hipanel\base\Model implements AssignSwitchInterface
{
use \hipanel\base\ModelTrait;
use ModelTrait, AssignSwitchTrait;

const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
Expand Down Expand Up @@ -109,4 +112,15 @@ public function getHardwareSettings(): ActiveQuery
{
return $this->hasOne(HardwareSettings::class, ['id' => 'id']);
}

/**
* {@inheritdoc}
* @return HubQuery
*/
public static function find($options = [])
{
return new HubQuery(get_called_class(), [
'options' => $options,
]);
}
}
7 changes: 5 additions & 2 deletions src/models/Server.php
Expand Up @@ -10,11 +10,14 @@

namespace hipanel\modules\server\models;

use hipanel\base\Model;
use hipanel\base\ModelTrait;
use hipanel\models\Ref;
use hipanel\modules\finance\models\Sale;
use hipanel\modules\hosting\models\Ip;
use hipanel\modules\server\helpers\ServerHelper;
use hipanel\modules\server\models\query\ServerQuery;
use hipanel\modules\server\models\traits\AssignSwitchTrait;
use hipanel\validators\EidValidator;
use hipanel\validators\RefValidator;
use Yii;
Expand All @@ -28,9 +31,9 @@
*
* @property-read HardwareSale[] $hardwareSales
*/
class Server extends \hipanel\base\Model
class Server extends Model implements AssignSwitchInterface
{
use \hipanel\base\ModelTrait;
use ModelTrait, AssignSwitchTrait;

const STATE_OK = 'ok';
const STATE_DISABLED = 'disabled';
Expand Down
27 changes: 27 additions & 0 deletions src/models/query/HubQuery.php
@@ -0,0 +1,27 @@
<?php
/**
* Finance module for HiPanel
*
* @link https://github.com/hiqdev/hipanel-module-finance
* @package hipanel-module-finance
* @license BSD-3-Clause
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/)
*/

namespace hipanel\modules\server\models\query;

use hiqdev\hiart\ActiveQuery;
use Yii;

class HubQuery extends ActiveQuery
{
public function withBindings(): self
{
if (Yii::$app->user->can('hub.read')) {
$this->joinWith('bindings');
$this->andWhere(['with_bindings' => true]);
}

return $this;
}
}

0 comments on commit d13b924

Please sign in to comment.