composer require simple-widget
<?php
declare(strict_types=1);
namespace App\Widget;
use Yii\Extension\Simple\Widget\AbstractWidget;
use Yiisoft\Html\Html;
final class Widget extends AbstractWidget
{
protected function run(): string
{
return '<' . trim(html::renderTagAttributes($this->attributes)) . '>';
}
public function id(string $value): self
{
$new = clone $this;
$new->attributes['id'] = $value;
return $new;
}
protected function beforeRun(): bool
{
if (isset($this->attributes['id']) && $this->attributes['id'] === 'beforerun') {
return false;
}
return parent::beforeRun();
}
protected function afterRun(string $result): string
{
$result = parent::afterRun($result);
if (isset($this->attributes['id']) && $this->attributes['id'] === 'afterrun') {
$result = '<div>' . $result . '</div>';
}
return $result;
}
}
Using in view:
<?php
declare(strict_types=1);
?>
Widget::create()->id('id-test')->attributes(['class' => 'text-danger'])->render();
Code generated:
<id="id-test" class="text-danger">
<?php
declare(strict_types=1);
?>
Widget::create(['attributes()' => [['class' => 'test-class']], 'id()' => ['id-tests']])->render();
Code generated:
<id="id-tests" class="test-class">
Load config from file: /config/widget-definitions.php
:
return [
'attributes()' => ['class' => 'test-class'],
'id()' => 'id-tests',
];
<?php
declare(strict_types=1);
?>
Widget::create()->loadConfigFile(__DIR__ . '/config/widget-definitions.php')->render();
Code generated:
<id="id-tests" class="test-class">
<?php
declare(strict_types=1);
namespace App\Widget;
use Yii\Extension\Simple\Widget\AbstractWidget;
use Yiisoft\Html\Html;
final class Widget extends AbstractWidget
{
public function __construct(private HTML $html)
{
}
protected function run(): string
{
return '<' . trim($this->html->renderTagAttributes($this->attributes)) . '>';
}
public function id(string $value): self
{
$new = clone $this;
$new->attributes['id'] = $value;
return $new;
}
}
Using view:
<?php
declare(strict_types=1);
use App\Widget;
Widget::create(['attributes()' => [['class' => 'test-class']]], [new Html()])->id('w0')->render();
Code generated:
<id="w0" class="test-class">
Defined CONSTANT
: WIDGET_CONFIG_PATH
for example:
define('WIDGET_CONFIG_PATH', __DIR__ . '/config');
Create file /config/widget-definitions.php
:
<?php
declare(strict_types=1);
return [
// Sintax for array shortNameWidget => [method() => [$value]
'Widget' => [
'attributes()' => [['class' => 'test-class']],
'id()' => ['id-tests'],
],
];
The package is tested with PHPUnit. To run tests:
./vendor/bin/phpunit
The package tests are checked with Infection mutation framework. To run it:
./vendor/bin/roave-infection-static-analysis-plugin -j2 --ignore-msi-with-no-mutations --only-covered
The code is statically analyzed with Psalm. To run static analysis:
./vendor/bin/psalm
The simple-widget for Yii Packages is free software. It is released under the terms of the BSD License.
Please see LICENSE
for more information.
Maintained by Yii Extension.