承接 stillat/primitives 相关项目开发

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

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

stillat/primitives

Composer 安装命令:

composer require stillat/primitives

包简介

Parses strings of primitive values into a PHP array.

README 文档

README

Primitives

This library provides a simple way to convert a string of simple values to their PHP runtime equivalents.

This library will parse the following types of values:

  • Numbers
  • Strings
  • Arrays
  • Associative arrays
  • true, false, null
  • Built-in PHP constants

Unknown types will return null as their value.

Installation

This library can be installed with composer:

composer require stillat/primitives

Example Usage

To use the library, create a new instance of the Parser class and call the parseString method:

<?php

use Stillat\Primitives\Parser;

$parser = new Parser();

$result = $parser->parseString('[1, 2, 3], "some-string", "another", ["one" => 1, "two" => 2]');

would produce the following runtime result:

array(4) {
  [0] =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(2)
    [2] =>
    int(3)
  }
  [1] =>
  string(11) "some-string"
  [2] =>
  string(7) "another"
  [3] =>
  array(2) {
    'one' =>
    int(1)
    'two' =>
    int(2)
  }
}

This library can also parse basic method details using the parseMethod method:

<?php

use Stillat\Primitives\Parser;

$parser = new Parser();

$result = $parser->parseMethod('methodName([1, 2, 3])');

would produce the following runtime result:

array(2) {
  [0] =>
  string(10) "methodName"
  [1] =>
  array(1) {
    [0] =>
    array(3) {
      [0] =>
      int(1)
      [1] =>
      int(2)
      [2] =>
      int(3)
    }
  }
}

Invalid input will produce a null value.

Parsing Nested Methods

A more advanced alternative of parseMethod is the parseMethods method:

use Stillat\Primitives\Parser;

$parser = new Parser();

$result = $parser->parseMethods("randomElements(['a', 'b', 'c', 'd', 'e'], rand(1, 5))"); 

Detected method calls will be returned as instances of Stillat\Primitives\MethodCall. Each instance of this class will contain the original method's name, as well as the parsed (and evaluated) runtime arguments. parseMethods will not run any methods for you.

Executing Runtime Methods

Primitives provides a utility MethodRunner class that can be used to execute the results of the parseMethods on any target class:

<?php

use Stillat\Primitives\Parser;
use Stillat\Primitives\MethodRunner;

$parser = new Parser();
$runner = new MethodRunner();

class MyClass {

    public function sayHello($name)
    {
        return 'Hello, '.$name;
    }

}

$myClassInstance = new MyClass();

$methods = $parser->parseMethods("sayHello('Dave')");
$result = $runner->run($methods, $myClassInstance);

After the above code has executed, $result would contain the value Hello, Dave.

Important notes when using MethodRunner:

  • There must only be one root method call
  • If there is more than one root element, the run method returns null
  • MethodRunner does not check for method existence, allowing __call to be invoked

Calling Native PHP Functions

The internal method runner does not support calling native PHP functions. However, we can create a class instance that can (and utilize whatever logic is appropriate for the current project to determine what is a "safe" function to call):

<?php

use Stillat\Primitives\Parser;
use Stillat\Primitives\MethodRunner;

$parser = new Parser();
$runner = new MethodRunner();

class Greeter {

    public function sayHello($name)
    {
        return 'Hello, '.$name;
    }

}

class MethodTarget
{

    protected $instance;
    protected $safePhpFunctions = [
        'strtoupper'
    ];

    public function __construct()
    {
        $this->instance = new Greeter();
    }

    public function __call($name, $arguments)
    {
        // Replace with whatever logic makes sense. This approach
        // utilizes an allowed list of functions, but using
        // something like function_exists also works.
        if (in_array($name, $this->safePhpFunctions)) {
            return call_user_func($name, ...$arguments);
        }

        return call_user_func([$this->instance, $name], ...$arguments);
    }

}

$instance = new MethodTarget();

$result = $parser->parseMethods('sayHello(strtoupper("this is lowercase"))');

$methodResult = $runner->run($result, $instance);

After the above code has executed, $methodResult would contain the value Hello, THIS IS LOWERCASE. This approach works because we are making use of PHP's __call magic method to perform method overloading. When we attempt to call a method on our class instance that does not exist, the __call method will receive the method name and arguments. If the list of safe functions contains the incoming method name, we will invoke it and return the results with the original arguments. If our safe list does not contain the function, we default to attempting to call it on our target class instance.

Context Variables

You may also supply an array of contextual data that can be used when evaluating the input string. Context variables utilize the $ syntax. The variable name in the input string will be replaced with their actual values once evaluated:

<?php

use Stillat\Primitives\Parser;

$parser = new Parser();

$context = [
    'name' => 'Dave',
    'city' => 'Anywhere'
];

$result = $parser->parseString('[$name, $city]', $context);

Once the previous example has executed, $result would contain a value similar to:

array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(4) "Dave"
    [1] =>
    string(8) "Anywhere"
  }
}

Nested variable paths can be utilized by using PHP's property fetcher syntax (array accessor syntax is not supported):

<?php

use Stillat\Primitives\Parser;

$parser = new Parser();

$context = [
    'nested' => [
        'arrays' => [
            'test' => [
                'name' => 'Dave',
                'city' => 'Anywhere'
            ]
        ]
    ]
];

$result = $parser->parseString('[$nested->arrays->test->name,' .
    '$nested->arrays->test->city]', $context);

Like before, the $result variable would contain a value similar to the following:

array(1) {
  [0] =>
  array(2) {
    [0] =>
    string(4) "Dave"
    [1] =>
    string(8) "Anywhere"
  }
}

License

MIT License. See LICENSE.MD

stillat/primitives 适用场景与选型建议

stillat/primitives 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.18k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2021 年 09 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 stillat/primitives 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 stillat/primitives 我们能提供哪些服务?
定制开发 / 二次开发

基于 stillat/primitives 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.18k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 5
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-09-18