PHP code example of xin / support

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

    

xin / support example snippets


use Xin\Support\Str;

$hello = "hello world!";
echo Str::startsWith($hello, 'hello') ? 'true' : 'false'; // true
echo Str::endsWith($hello, 'world!') ? 'true' : 'false'; // true
echo Str::contains($hello, 'lo wo') ? 'true' : 'false'; // true

// 驼峰与下划线转换
echo Str::snake('camelCase'); // camel_case
echo Str::camel('snake_case'); // snakeCase
echo Str::studly('snake_case'); // SnakeCase

// 生成随机字符串
echo Str::random(10); // 随机10位字符串
echo Str::random(10, 0); // 随机10位数字

// UUID生成
echo Str::uuid(); // 生成UUID对象
echo Str::assignUuid(); // 生成UUID字符串

use Xin\Support\Arr;

$array = [1, 2, 3, 4, 5];
echo Arr::contains($array, 3) ? 'true' : 'false'; // true

$result = Arr::pluck($array, function ($item) {
    return $item * 2;
});
print_r($result); // [2, 4, 6, 8, 10]

// 点符号访问数组
$data = [
    'user' => [
        'name' => 'John',
        'profile' => [
            'email' => '[email protected]'
        ]
    ]
];

echo Arr::get($data, 'user.name'); // John
echo Arr::get($data, 'user.profile.email'); // [email protected]

// 设置值
Arr::set($data, 'user.profile.phone', '123456789');
print_r($data); // 包含电话号码的新数组

// 检查值是否存在
echo Arr::has($data, 'user.profile.email') ? 'true' : 'false'; // true

use Xin\Support\Collection;

$collection = new Collection([1, 2, 3, 4, 5]);
$result = $collection->map(function ($item) {
    return $item * 2;
})->all();

print_r($result); // [2, 4, 6, 8, 10]

$filtered = $collection->filter(function ($item) {
    return $item > 2;
})->all();

print_r($filtered); // [3, 4, 5]

// 更多集合操作
$collection->each(function ($item, $key) {
    echo "Item {$key}: {$item}\n";
});

echo $collection->first(); // 1
echo $collection->last(); // 5

use Xin\Support\File;

if (File::exists('path/to/file.txt')) {
    echo File::get('path/to/file.txt');
}

// 写入文件
File::put('path/to/newfile.txt', 'Hello World');

// 获取文件哈希
$hash = File::hash('path/to/file.txt', File::HASH_ETAG);
$md5 = File::hash('path/to/file.txt', File::HASH_MD5);

// 获取目录下所有文件
$files = File::files('path/to/directory');
foreach ($files as $file) {
    echo $file->getPathname() . "\n";
}

use Xin\Support\Time;

echo Time::now(); // 当前时间
echo Time::parse('2023-10-01')->format('Y-m-d'); // 格式化日期

// 时间计算
$nextWeek = Time::addWeeks(time(), 1);
$lastMonth = Time::subMonths(time(), 1);

// 获取时间范围
[$start, $end] = Time::todayRange();
[$start, $end] = Time::weekRange();
[$start, $end] = Time::monthRange();

// 格式化相对时间
echo Time::formatRelative(strtotime('-2 hours')); // 2小时前

// 格式化时长
echo Time::formatDuration(3661); // 1小时1分1秒

use Xin\Support\SimpleEncrypt;
use Xin\Support\Security\Encrypter;
use Xin\Support\Security\Hash;

// 简单加密
$encrypted = SimpleEncrypt::encrypt('secret message', 'mykey');
$decrypted = SimpleEncrypt::decrypt($encrypted, 'mykey');

// 高级加密
$encryption = new Encrypter('my-encryption-key');
$encrypted = $encryption->encrypt('secret data');
$decrypted = $encryption->decrypt($encrypted);

// 哈希处理
$hash = new Hash();
$hashedPassword = $hash->make('password123');
$isVerified = $hash->verify('password123', $hashedPassword);

use Xin\Support\Reflect;

$reflection = Reflect::on('SomeClass');
$reflection->call('someMethod');

// 获取类属性
$value = Reflect::get($object, 'privateProperty');
Reflect::set($object, 'privateProperty', 'newValue');

use Xin\Support\Retry;

Retry::make(function ($attempts) {
    // 可能会失败的操作
    if ($attempts < 3) {
        throw new Exception("Failed attempt {$attempts}");
    }
    return "Success on attempt {$attempts}";
}, 5)->invoke(); // 最多重试5次

use Xin\Support\LimitThrottle;

LimitThrottle::general(
    function () {
        // 获取当前计数
        return (int) cache()->get('counter', 0);
    },
    function ($limits, $value) {
        // 当达到限制时执行的操作
        echo "Limit reached at {$value}\n";
        return true;
    }
);

use Xin\Support\Version;

echo Version::compare('1.0.0', '1.0.1'); // -1
echo Version::compare('1.0.1', '1.0.0'); // 1
echo Version::compare('1.0.0', '1.0.0'); // 0

// 便捷方法
echo Version::gt('1.0.1', '1.0.0') ? 'true' : 'false'; // true
echo Version::eq('1.0.0', '1.0.0') ? 'true' : 'false'; // true
echo Version::lt('1.0.0', '1.0.1') ? 'true' : 'false'; // true

use Xin\Support\Xml;

$xml = Xml::parse('<root><child>value</child></root>');
echo $xml['child']; // value

// 转换为XML
$array = ['name' => 'John', 'age' => 30];
$xmlString = Xml::encode($array, 'person');

use Xin\Support\Str;

$ubb = '[b]Bold Text[/b]';
$html = Str::ubbToHtml($ubb); // <b>Bold Text</b>

use Xin\Support\Fluent;

$fluent = new Fluent(['key' => 'value']);
echo $fluent->get('key'); // value
$fluent->set('newKey', 'newValue');
print_r($fluent->all()); // ['key' => 'value', 'newKey' => 'newValue']

// 链式调用
$fluent->merge(['another' => 'value'])
       ->except('key')
       ->only(['newKey', 'another']);

use Xin\Support\HigherOrderTapProxy;

$proxy = new HigherOrderTapProxy($object);
$proxy->method(function ($item) {
    // 对对象进行操作
});

use Xin\Support\MacroProxy;

// 使用自定义宏扩展对象
$proxy = new MacroProxy($object);
$proxy->macro('macroName', function ($item) {
    // 在此处定义宏逻辑
});

use Xin\Support\Regex;

echo Regex::isEmail('[email protected]') ? '有效邮箱' : '无效邮箱';
echo Regex::isUrl('https://example.com') ? '有效URL' : '无效URL';
echo Regex::isMobile('13800138000') ? '有效手机号' : '无效手机号';
echo Regex::isUsername('username', 3, 20) ? '有效用户名' : '无效用户名';

use Xin\Support\Web\ServerInfo;

echo ServerInfo::isLocalhost() ? '本地运行' : '非本地';
echo ServerInfo::ip(); // 服务器IP地址

use Xin\Support\Web\Javascript;

Javascript::render('console.log("Hello, World!");');

use Xin\Support\Position;

$distance = Position::calcDistance(
    34.052235, -118.243683,
    40.712776, -74.005974
);
echo $distance; // 计算出的距离(公里)

// 坐标系转换
[$gcjLat, $gcjLng] = Position::gps84ToGcj02(34.052235, -118.243683);
[$bdLat, $bdLng] = Position::gcj02ToBD09($gcjLat, $gcjLng);

use Xin\Support\Radix;

// 62进制转换
$converter = Radix::radix62();
$encoded = $converter->generate(12345); // 数字转62进制
$decoded = $converter->parse($encoded); // 62进制转数字

// Base64
echo base64_encode('Hello, World!');
echo base64_decode('SGVsbG8sIFdvcmxkIQ==');

use Xin\Support\Web\Redirect;

Redirect::redirect('https://example.com', 3, '页面将在3秒后跳转...');