承接 ui-awesome/html-helper 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ui-awesome/html-helper

最新稳定版本:0.6.3

Composer 安装命令:

composer require ui-awesome/html-helper

包简介

UI Awesome HTML Helpers for PHP.

README 文档

README

UI Awesome

Html helper


PHPUnit Mutation Testing PHPStan

A powerful PHP library to simplify HTML element creation
Generate attributes, encode content, sanitize HTML, and manage CSS classes with ease.

Features

Feature Overview

Installation

composer require ui-awesome/html-helper:^0.5

Quick start

Attribute key normalization

Ensures attribute keys have the correct prefix (like aria-, data-, or on), supporting strings, Enums, and Stringables.

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\Attributes;

// normalize string key (adds prefix if missing)
echo Attributes::normalizeKey('label', 'aria-');
// aria-label

// normalize Enum key
echo Attributes::normalizeKey(Data::ACTION, 'data-');
// data-action

// normalize event (flexible prefixing)
echo Attributes::normalizeKey('click', 'on');
// onclick

Universal Stringable support

Pass your domain objects directly to helpers like Encode, Attributes, or CSSClass. The library automatically handles __toString().

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\Encode;

class User implements \Stringable
{
    public function __construct(private string $name) {}

    public function __toString(): string
    {
        return $this->name;
    }
}

$user = new User('<John Doe>');

// automatically casts and safely encodes
echo Encode::content($user);
// &lt;John Doe&gt;

Rendering HTML attributes

Use Attributes::render() to generate a safe, escaped HTML attribute string from an array. It automatically handles class arrays, style arrays, and data-* expansions.

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\Attributes;
?>

<?= Attributes::render(
    [
        'id' => 'submit-btn',
        // automatically joined
        'class' => ['btn', 'btn-primary'],
        // `true` booleans are rendered as valueless attributes
        'disabled' => true,
        // `false` booleans are skipped
        'readonly' => false,
        // JSON encoded automatically
        'data' => [
            'id' => 42,
            'options' => ['modal' => true],
        ],
        'style' => [
            'color' => '#fff',
            'margin-top' => '10px'
        ],
    ]
) ?>
// class="btn btn-primary" id="submit-btn" disabled data-id="42" data-options='{"modal":true}' style='color: #fff; margin-top: 10px;'

Advanced: DOM & SVG Integration

When working with DOMDocument, SimpleXMLElement, or other XML/SVG builders, you should not use pre-escaped strings to avoid "double escaping" (for example, &amp;lt;).

Use Attributes::normalizeAttributes() with encode: false to get a flat array of raw values ready for insertion.

use UIAwesome\Html\Helper\Attributes;

$attributes = [
    'class' => ['icon', ButtonType::PRIMARY],
    'data-config' => ['key' => '<val>'],
    'title' => '<Safe Title>',
];

// Get raw values (encode: false)
$rawAttributes = Attributes::normalizeAttributes($attributes, encode: false);
// [
//    'class' => 'icon btn-primary',
//    'data-config' => '{"key":"<val>"}'
//    'title' => '<Safe Title>',
// ]

// Perfect for DOMDocument
foreach ($rawAttributes as $name => $value) {
    // DOMDocument handles the escaping automatically here
    $domElement->setAttribute($name, $value);
}

Managing CSS classes

Allows you to merge, add, or override CSS classes within an attributes array smartly.

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\CSSClass;

$attributes = ['class' => 'base-class'];

// add new classes (merges efficiently)
CSSClass::add($attributes, ['text-center', 'mt-5']);

// override existing classes
CSSClass::add($attributes, 'alert alert-danger', true);

echo $attributes['class'];
// alert alert-danger

Encoding

Ensures your content and attribute values are safe from XSS.

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\Encode;

// safe Content
echo Encode::content('<script>alert("xss")</script>');
// &lt;script&gt;alert("xss")&lt;/script&gt;

// safe Attribute Value
echo Encode::value('Name "Quote"');
// Name &quot;Quote&quot;

Enum normalization

Normalizes values against a predefined set, supporting both arrays and Enums.

<?php

declare(strict_types=1);

namespace App;

use App\Enums\Status;
use UIAwesome\Html\Helper\Enum;

// normalize array of Enums
$result = Enum::normalizeArray([Status::ACTIVE, Status::INACTIVE]);
// ['active', 'inactive']

// normalize mixed array
$result = Enum::normalizeArray(['foo', Status::ACTIVE, 42]);
// ['foo', 'active', 42]

// normalize value from Enum
Enum::normalizeValue(Status::ACTIVE);
// 'active'

// normalize value from mixed
Enum::normalizeValue('foo');
// 'foo'

Form naming & IDs

Generates standard PHP form names and valid HTML IDs, handling arrayable and nested properties effortlessly.

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\Naming;

// generate input name (Nested)
echo Naming::generateInputName('User', 'profile[0][email]');
// User[profile][0][email]

// generate input ID (Sanitized)
echo Naming::generateInputId('User', 'profile[0][email]');
// user-profile-0-email

// convert regex to pattern
echo Naming::convertToPattern('/^[a-z]+$/i');
// ^[a-z]+$

Template rendering

Performs clean token replacement with normalized line endings.

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\Template;

echo Template::render("Hello, {name}!", ['{name}' => 'Yii3']);
// Hello, Yii3!

Validation

Enforces strict types and approved values for your HTML logic.

<?php

declare(strict_types=1);

namespace App;

use UIAwesome\Html\Helper\Validator;

// validate integer-like string
$isValid = Validator::intLike('123', 0, 1000);

// validate against allowed list (supports Enums)
Validator::oneOf('sm', ['sm', 'md', 'lg'], 'size');
// passes

// validate positive-like number
$isPositive = Validator::positiveLike('42.5', 0, 100);
// true

Documentation

For detailed configuration options and advanced usage.

Package information

PHP Latest Stable Version Total Downloads

Quality code

Codecov PHPStan Level Max Super-Linter StyleCI

Our social networks

Follow on X

License

License

统计信息

  • 总下载量: 19.71k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 1
  • 依赖项目数: 13
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2024-03-05