mekramy / support

为laravel提供支持库和函数

v1.0.1 2020-04-04 07:54 UTC

This package is auto-updated.

Last update: 2024-09-04 17:56:25 UTC


README

支持库是一个为laravel提供的辅助工具集

发布翻译文件

php artisan vendor:publish --provider="MEkramy\Support\SupportServiceProvider"

JSON API响应

response()->error($data = 'invalid', $code = 400); // HTTP status code is 400
/*
* {
*     "success" => false,
*     "data" => "invalid"
* }
*/

response()->success($data = true, $code = 200); // HTTP status code is 200
/*
* {
*     "success" => true,
*     "data" => true
* }
*/

response()->unauthorized($data = 'unauthorized'); // HTTP status code is 401
/*
* {
*     "success" => false,
*     "data" => "unauthorized"
* }
*/

response()->forbidden($data = 'forbidden'); // HTTP status code is 403
/*
* {
*     "success" => false,
*     "data" => "forbidden"
* }
*/

查询构建器selectAs

$user = User::where("is_banned", false)->select('phone', 'mobile')->selectAs("full_name", "CONCAT_WS('-', firstname, lastname)");

分页器

分页器扩展了默认的laravel分页器,并返回结果实例的json或数组。

注意:需要设置排序列表和查询,并调用解析方法!

注意:默认情况下,所有元数据都是从请求中解析出来的,但您也可以重写它们。

注意:接收和发送的标签以base64格式存储,以便可以存储在URL或查询字符串中。

use MEkramy\Support\Paginator;
use Illuminate\Routing\Controller;
class UserController extends Controller
{
    public function index(Paginator $paginator)
    {
        // Set valid sorts
        // if invalid sort passed by request first sort used
        $paginator->setSorts(['id', 'username', 'firstname', 'lastname']);
        // or
        $paginator->sorts = ['id', 'username', 'firstname', 'lastname'];

        //  Set valid limits, default is [10, 25, 50, 100]
        // if invalid limit passed by request first limit used
        $paginator->setLimits([25, 50, 100]);
        // or
        $paginator->limits = [25, 50, 100];

        // Parse page, limit, sort, order, search and tags from request
        $paginator->parse();

        // Set default meta (page, limit, sort, order, search and tags)
        $paginator->setPage((int) $request->page);
        // or
        $paginator->limit = 10;

        // Get default meta
        $sort = $paginator->sort;
        // or
        $order = $paginator->getOrder();

        // Set extra meta
        $paginator->addMeta('author', 'm ekramy');
        // or simply add Meta to end of tag name and set by property
        $paginator->authorMeta = 'm ekramy';

        // Get extra meta
        $author = $paginator->getMeta('author');
        // or simply add Meta to end of tag name and get by property
        $author = $paginator->authorMeta;

        // Set query
        $paginator->setQuery(User::where('is_banned', false));
        // you can access query by query property or getter methods
        $paginator->query->where('firstname', 'like', "%{$paginator->search}%")

        // Tags: tags are list of filters come in base64 encoded string and parsed as array

        // Check if tag passed
        // in this example accesses is array of access list ex: ["admin", "support"]
        if($paginator->hasTag('accesses')){
            $paginator->query->whereIn('access', $paginator->getTag('access'))
        }

        // Access tag
        $bannedOnly = $paginator->getTag('banned');
        // or simply add Tag to end of tag name and get by property
        $bannedOnly = $paginator->bannedTag;

        // Add Tag to final response and send to user
        $paginator->addTag('gender', 'male');
        // or simply add Tag to end of tag name and set by property
        $paginator->genderTag = 'male';

        // Get paginated result

        $arrayOfResult = $paginator->toArray();
        $jsonOfResult = $paginator->toJson();

        // or you can simply return paginator as result (return json)
        return $paginator;
        /* returned response
         * {
         *     "meta": {
         *         "page": 1,
         *         "limit": 10,
         *         "sort": "id",
         *         "order": "asc",
         *         "search": "",
         *         "author": "m ekramy",
         *         "tags": "eyJnZW5kZXIiOiJtYWxlIiwiYWNjZXNzZXMiOlsiYWRtaW4iLCJzdXBwb3J0Il19"
         *     },
         *     "pagination": {
         *         "current_page": 1,
         *         "from": 1,
         *         "last_page": 11,
         *         "per_page": 10,
         *         "to": 10,
         *         "total": 103
         *     },
         *     "data": {...}
         * }
    }
}

速率限制器

速率限制器扩展了默认的laravel速率限制器,并允许将速率限制器作为对象使用。

use MEkramy\Support\Paginator;
use Illuminate\Routing\Controller;

class LoginController extends Controller
{
    public function index(RateLimiter $limiter)
    {
        // Set rate limiter parameters
        // $limiter->init(string $key, int $maxAttempts: 3, int $decaySeconds: 300);
        $limiter->init('key', 5, 600);
        // or you can set parameter separately using setter or property
        $limiter->setKey('key');
        $limiter->key = 'key'
        $limiter->setMaxAttempts(5);
        $limiter->maxAttempts = 5
        $limiter->setDecaySeconds(600);
        $limiter->decaySeconds = 600;

        // Check if limiter must look
        if($limiter->mustLock()){
            return response()->error('too many attempts', 419);
            // or return number of seconds until unlock
            return response()->error($limiter->availableIn(), 419);
        }


        // increase number of try. also return current number of attempts.
        $totalAttempts = $limiter->addAttempts();

        // reset rate limiter
        $limiter->reset;

        // get number of retries left
        $retriesLeft = $limiter->retriesLeft();

        // get number of second until available to unlock
        $av = $limiter->availableIn();

        // Lock rate limiter in special case
        if($someThingHappen) {
            $limiter->lock();
        }
    }
}

验证器

username 输入必须只包含0-9,a-z,A-Z,-(减号),.(点)和_(下划线)。

注意: x代表数字。

tel 匹配(0xx) xxxx-xxxx或0xxxxxxxxxx

mobile 匹配(09xx) xxx-xxxx或09xxxxxxxxx

postalcode 匹配xxxxx-xxxxx或xxxxxxxxxx

identifier 匹配任何大于0的数值

minlength 检查输入的最小长度(输入解析为字符串)。

maxlength 检查输入的最大长度(输入解析为字符串)。

    "username" => "minlength:3|maxlength:10"

unsigned 匹配任何大于或等于0的数值

range 匹配任何在a到b范围内的数值

    "input" => "range:1,3",
    "input" => "range:0.3,0.75

idnumber 匹配任何1到10位长度的数值

nationalcode 匹配xxx-xxxxxx-x或xxxxxxxxxx

jalali 匹配格式为的贾拉利日期时间

    "input" => "jalali", // default format is Y/m/d
    "input" => "jalali:Y-m-d H:i"

numericarray 匹配数字数组

length 匹配固定长度的字符串(输入解析为字符串)。

    "input" => "length:3"