PHP code example of efureev / support

1. Go to this page and download the library: Download efureev/support 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/ */

    

efureev / support example snippets


use Php\Support\Helpers\Arr;
use Php\Support\Helpers\Str;
use Php\Support\Structures\Collections\ArrayCollection;

Arr::get($config, 'database.connections.pgsql.host', '127.0.0.1');

Str::slugify('Привет, мир!');                       // 'privet-mir'

(new ArrayCollection($orders))
    ->filter(static fn(array $o) => $o['paid'])
    ->groupBy('customer_id')
    ->map(static fn(ArrayCollection $c) => $c->sum('total'));

use Php\Support\Helpers\Arr;

$config = ['db' => ['host' => 'localhost', 'ports' => [5432, 5433]]];

Arr::get($config, 'db.host');            // 'localhost'
Arr::get($config, 'db.ports.0');         // 5432
Arr::get($config, 'db.user', 'postgres') // 'postgres' — the default
Arr::has($config, 'db.host');            // true

Arr::set($config, 'db.user', 'admin');   // returns the whole array
Arr::remove($config, 'db.ports');

Arr::get($config, 'db/host', null, '/');

$users = [
    ['id' => 1, 'name' => 'Ada',   'team' => 'core'],
    ['id' => 2, 'name' => 'Linus', 'team' => 'core'],
    ['id' => 3, 'name' => 'Grace', 'team' => 'ops'],
];

Arr::pluck($users, 'name');            // ['Ada', 'Linus', 'Grace']
Arr::pluck($users, 'name', 'id');      // [1 => 'Ada', 2 => 'Linus', 3 => 'Grace']
Arr::keyBy($users, 'id');              // [1 => [...], 2 => [...], 3 => [...]]
Arr::only($users[0], ['id', 'name']);  // ['id' => 1, 'name' => 'Ada']
Arr::first($users, static fn(array $u) => $u['team'] === 'ops');

Arr::dot(['db' => ['host' => 'localhost']]);   // ['db.host' => 'localhost']
Arr::undot(['db.host' => 'localhost']);        // ['db' => ['host' => 'localhost']]
Arr::flatten([1, [2, [3, [4]]]]);              // [1, 2, 3, 4]

use Php\Support\Helpers\Str;

Str::toSnake('getHTTPResponse');   // 'get_http_response'
Str::toCamel('user_first_name');   // 'UserFirstName'
Str::toLowerCamel('user_id');      // 'userId'
Str::toKebab('BackgroundColor');   // 'background-color'

Str::toSnake('ПриветМир');         // 'привет_мир'  — not only Latin
Str::toCamel('über_straße');       // 'ÜberStraße'

Str::slugify('Привет, мир!');            // 'privet-mir'
Str::slugify('Il était une fois');       // 'il-etait-une-fois'
Str::slugify('Hello World', '_');        // 'hello_world'

Str::truncate('The quick brown fox', 9);  // 'The...'     — at a word boundary
Str::limit('The quick brown fox', 9);     // 'The quick...' — at an exact length
Str::mask('4111111111111111', '*', 4, 8); // '4111********1111'
Str::padLeft('7', 3, '0');                // '007'
Str::squish("  too   much \n space ");    // 'too much space'

Str::uuid();   // '9f8c1f1e-...' — RFC 4122 v4
Str::ulid();   // '01J...'       — sortable by creation time
Str::random(); // 16 random alphanumerics from the CSPRNG

use Php\Support\Structures\Collections\ArrayCollection;

$orders = new ArrayCollection([
    ['id' => 1, 'customer' => 'ada',   'total' => 120, 'paid' => true],
    ['id' => 2, 'customer' => 'ada',   'total' => 80,  'paid' => true],
    ['id' => 3, 'customer' => 'linus', 'total' => 200, 'paid' => false],
]);

$orders->filter(static fn(array $o) => $o['paid'])->sum('total');  // 200
$orders->pluck('total')->median();                                 // 120
$orders->countBy('customer');                                      // ['ada' => 2, 'linus' => 1]
$orders->every(static fn(array $o) => $o['total'] > 0);            // true

$byCustomer = $orders->groupBy('customer');
$byCustomer->get('ada')->count();                                  // 2

json_encode($orders->pluck('id'));                                 // '[1,2,3]'

$orders
    ->when($onlyPaid, static fn($c) => $c->filter(static fn($o) => $o['paid']))
    ->sortBy('total', descending: true)
    ->take(10)
    ->values();

use Php\Support\Structures\Collections\HashCollection;

$handlers = new HashCollection();
$handlers[] = new SendEmail();          // keyed by SendEmail::class
$handlers->get(SendEmail::class);

use Php\Support\Storage;

$storage = new Storage();

$storage->set('user.profile.name', 'Ada');
$storage->get('user.profile.name');    // 'Ada'
$storage->exist('user.profile');       // true

$storage['user.profile.name'];         // same value, ArrayAccess
$storage->user;                        // ['profile' => ['name' => 'Ada']]

foreach ($storage as $key => $value) { /* ... */ }

$storage->merge(['app' => ['debug' => true]])->only('app')->toArray();

use Php\Support\Helpers\{Json, Number, Bit, B64};

Json::decodeOrThrow('{"a":1}');   // ['a' => 1] — throws on invalid input, unlike decode()
Json::prettyPrint(['a' => 1]);
Json::isValid('{oops');           // false

Number::humanize(1536);           // '1.5 KB'
Number::ordinal(22);              // '22nd'
Number::clamp(15, 0, 10);         // 10
Number::percentage(1, 3);         // 33.33
Number::safeInt('9007199254740993'); // stays a string: too big for JavaScript

const READ = 1, WRITE = 2, ADMIN = 4;

$perm = Bit::grant([READ, WRITE]);
Bit::checkFlag($perm, WRITE);     // true
Bit::hasAll($perm, [READ, WRITE]);// true
Bit::flags($perm);                // [1, 2]

B64::encodeSafe($binary);         // RFC 4648 URL-safe, readable by atob() and Python

use Php\Support\Enums\WithEnhancesForStrings;

enum Status: string
{
    use WithEnhancesForStrings;

    case Draft     = 'draft';
    case Published = 'published';
}

Status::values();                  // ['draft', 'published']
Status::names();                   // ['Draft', 'Published']
Status::labels();                  // ['draft' => 'Draft', 'published' => 'Published']
Status::hasValue('draft');         // true
Status::tryFromName('Draft');      // Status::Draft — from() only looks at values
Status::casesToEscapeString();     // "'draft', 'published'" — ready for an SQL IN list

use Php\Support\Exceptions\ExceptionInterface;

try {
    Json::decodeOrThrow($payload);
    Str::truncate($title, $length);
} catch (ExceptionInterface $e) {
    // InvalidValueException, InvalidParamException, MissingPropertyException, ...
}

use Php\Support\Traits\{Maker, UseErrorsBox, Metable};

final class Report
{
    use Maker;         // Report::make(...$args)
    use UseErrorsBox;  // addError(), errors(), firstError(), hasErrors()
    use Metable;       // withMeta(), metaAttribute()
}

Report::make()
    ->withMeta(['source' => 'cron'])
    ->addError('row 12 is malformed');

use Php\Support\Traits\HasPrePostActions;

final class Importer
{
    use HasPrePostActions;

    public function import(array $rows): bool
    {
        if (!$this->runActions('before', $rows)) {
            return false;                       // a listener said no
        }

        // ... do the work

        $this->runActions('after', count($rows));

        return true;
    }
}

$importer = (new Importer())
    ->addCallbackAction('before', static fn(array $rows) => $rows !== [])
    ->addCallbackAction('after', static fn(int $count) => $logger->info("imported {$count}"));

$importer->import([]);              // false — the guard vetoed it, nothing ran
$importer->import([['id' => 1]]);   // true

use Php\Support\ConditionalHandler;

$auditLink = ConditionalHandler::make(
    static fn(User $user) => ['label' => 'Audit log', 'href' => '/audit'],
)->handleIf(static fn(User $user) => $user->isAdmin());

$auditLink($admin);   // ['label' => 'Audit log', 'href' => '/audit']
$auditLink($guest);   // null — the handler was never called

$fields = array_filter(array_map(
    static fn(ConditionalHandler $field) => $field($user),
    [$auditLink, $billingLink, $profileLink],
));

ConditionalHandler::make(static fn() => buildReport(), $featureEnabled);

use Php\Support\Helpers\Arr;
use Php\Support\Types\GeoPoint;

Arr::toPostgresArray(['a,b', 'plain', null]);   // '{"a,b",plain,NULL}'
Arr::fromPostgresArray('{"a,b",plain}');        // ['a,b', 'plain']

$point = GeoPoint::castFromDatabase('(37.6,55.7)');
$point->toJson();                               // '{"longitude":37.6,"latitude":55.7}'

use Php\Support\Testing\{AdditionalAssertionsTrait, TestingHelper};

final class ReportTest extends TestCase
{
    use AdditionalAssertionsTrait;
    use TestingHelper;

    public function testItIsMakeable(): void
    {
        static::assertClassUsesTraits(Report::class, [Maker::class]);

        self::assertSame('hidden', static::runProtectedMethod(new Report(), 'internal'));
        self::assertSame(1, static::getProperty(new Report(), 'privateCounter'));
    }
}

dataGet($order, 'customer.address.city');
Func::dataGet($order, 'customer.address.city');   // identical