elegant-bro/stringify

0.4.1 2022-08-24 10:55 UTC

This package is auto-updated.

Last update: 2024-09-24 15:12:11 UTC


README

Build Status Coverage Status

以优雅的方式处理字符串

Stringify 接口为任何对象提供了将它们表示为字符串的能力。这个库包含了从PHP中组织起来的最实用的字符串操作功能。您可以优雅地组合它们。

示例

假设您创建了一些用于执行SQL查询的抽象

<?php

use ElegantBro\Stringify\Stringify;

interface Connection
{
    public function execute(Stringify $query, array $params): void;
}

然后您可以使用它如下

<?php

use ElegantBro\Stringify\Just;

// Let's change user's (which id is 10) first name to Jonh
$connection->execute(
    new Just('UPDATE users SET first_name = ? WHERE id = ?'),
    ['John', 10]
);

上面的示例中没有什么特别之处,那么魔法在哪里呢?

<?php

use ElegantBro\Stringify\Stringify;
use ElegantBro\Stringify\Imploded;
use ElegantBro\Stringify\Joined;
use ElegantBro\Stringify\Just;
use ElegantBro\Stringify\Formatted;

final class UpdateQuery implements Stringify
{
    private $table;
    private $fields;
    
    public function __construct(string $table, array $fields) 
    {
        $this->table = $table;
        $this->fields = $fields;
    }
    
    public function asString(): string
    {
        return 
            (new Joined(
                new Formatted(new Just('UPDATE %s SET '), $this->table),
                new Imploded(
                    new Just(' '),
                    array_map(
                        static function (string $field) { return $field.' = ?'; },
                        $this->fields
                    )
                )
            ))->asString();
    }
}

现在我们可以轻松使用它

<?php

$connection->execute(
    new UpdateQuery('users', ['first_name']),
    ['John']
);

嘿,那关于 where 呢?!

<?php

use ElegantBro\Stringify\Stringify;
use ElegantBro\Stringify\Imploded;
use ElegantBro\Stringify\Joined;
use ElegantBro\Stringify\Just;

final class Where implements Stringify
{
    private $origin;
    
    private $fields;
    
    public function __construct(Stringify $query, array $fields)
    {
        $this->origin = $query;
        $this->fields = $fields;
    }
    
    public function asString(): string
    {
        return 
            (new Joined(
                $this->origin,
                new Just(' WHERE '),
                new Imploded(
                    new Just(' '),
                    array_map(
                        static function (string $field) { return $field.' = ?'; },
                        $this->fields
                    )
                ) 
            ))->asString();
    }
}

就是这样

<?php

$connection->execute(
    new Where(
        new UpdateQuery('users', ['first_name']),
        ['id']
    ),
    ['John', 10]
);

这是一个非常简单的示例,但它反映了常见思路。通过这种方法,您可以创建某种查询构建器,但以一种优雅的声明式方式。

对于贡献者

在创建 pull request 之前,请先在本地上运行所有测试。

构建测试容器并运行所有测试

make all

其他命令

# build the Dockerfile
make build 

# install composer requirements
make install

# enter the container shell
make shell

# style check
make style-check

# run unit tests
make unit

# ensure coverage is 100%
make coverage