PHP code example of karelwintersky / arris.request

1. Go to this page and download the library: Download karelwintersky/arris.request library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

karelwintersky / arris.request example snippets


use Arris\Request;

// Одна строка — строка из $_REQUEST
$email = Request::str('email');

// Эквиваленты
$age   = Request::from('age')->asInt();     // int из $_REQUEST
$age   = (new Request('age'))->asInt();     // то же самое

// __invoke-шорткат: сначала import() создаёт «пульт» (источник без поля),
// затем $r('field') читает конкретное поле из того же источника
$r      = Request::import($_POST);
$active = $r('active')->asBool();

$age = Request::from('age', ['age' => '42'])->asInt();  // 42

$r = Request::import($_POST);

$quote = $r('tavern_chef_quote')->apply('strip_tags')->trim()->asStr();
$name  = $r('name')->asString();

$whole = $r->raw();            // весь $_POST (массив)
$json  = $r->asJson();         // весь $_POST как JSON

$name = Request::from('name')
    ->trim()                                  // убрать пробелы
    ->maxLength(50)                           // обрезать до 50 символов
    ->default('нет данных')
    ->apply(fn($v) => mb_strtolower($v))      // свой коллбэк
    ->asString();                             // финальное приведение

// strip_tags — быстрая замена apply('strip_tags')
$clean = Request::from('content')->stripTags()->asString();

// substr — вырезать фрагмент. ВСЕГДА многобайтовый (mb_substr),
// работает с символами языка, а не байтами
$short = Request::from('name')
    ->trim()
    ->substr(1, 3)          // mb_substr($value, 1, 3)
    ->asString();

$rest = Request::from('name')->substr(2)->asString();  // до конца строки

// Чекбокс в БД
$active = Request::from('active')->asCheckbox();  // 0 или 1

// Весь payload как JSON (логгирование, подпись вебхука, отладка)
$json = Request::import($_POST)->asJson();

// Значение поля как JSON (например, поле-массив)
$tags = Request::from('tags', $_POST)->asJson();

// Пустой массив из формы -> дефолт
$tags = Request::from('tags')->default(['нет'])
    ->allowEmptyArray(false)   // пустой [] считается отсутствующим
    ->asArray();

// Вложенные массивы возвращаются как есть
$dishes = Request::from('dishes', $_POST)->asArray();

// Санитизация текста (удаляет теги и экранирует спецсимволы)
$text = Request::from('content')->asText();

// С сохранением HTML (например, для WYSIWYG-редактора)
$html = Request::from('content')->allowHtml()->asText();

// Отключить удаление пустых <p>/<div>
$raw = Request::from('content')->allowHtml()->noEmptyContent(false)->asText();

use Arris\Request;
use Arris\Request\Dataset;

$payload = Request::from('data', $_POST)->asArray();

$clean = Dataset::map($payload, [
    'name'  => ['type' => 'string'],
    'age'   => ['type' => 'int'],
    'email' => [
        'processor' => fn($v) => strtolower(trim($v)),
    ],
    'price_with_tax' => [
        'source'    => 'price',
        'processor' => fn($v) => $v * 1.2,
        'type'      => 'float',
    ],
    'active' => [
        'type'    => 'bool',
        'default' => false,
    ],
]);