2

在我最近的项目中,处理控制台命令,我需要根据 linux 标准约定执行/运行 json 中提到的各种操作

what:mv(Move),type:file,dir
what:mkdir(Make Directory)
what:touch(Make File)
what:cp(Copy), type:file,dir
what:echo (Write into File), type:override,append
what:sed (Find and Replace in file)

并且 param 模式与 linux 约定几乎完全相同。

当前设置(Mkdir,触摸)

Json 模式(数组)

          "actions" => [
                [
                    'what'  => "mkdir",
                    'param' => [
                        'name' => "cache",
                        'in'   => "bootstrap",
                    ],
                ],
                [
                    'what'  => "touch",
                    'param' => [
                        'name' => ".gitignore",
                        'in'   => "bootstrap/cache",
                    ],
                ]
            ],

它遍历所有动作并解析每个what类型(mkdir,touch)的动作类,例如MkdirOperation分别用于mkdir和调用句柄函数。

<?php
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;

class MkdirOperation extends Operation
{
    const ATTR_IN = "in";
    const ATTR_NAME = "name";

    public function handle()
    {
        $path = $this->_path();
        $this->oIO->comment($path);
        if ($this->oFileSystem->isAbsolutePath($path)) {
            try {
                $this->oFileSystem->mkdir($path);
            } catch (IOExceptionInterface $e) {
                echo "An error occurred while creating your directory at "
                    .$e->getPath();
            }
            $this->oIO->info("Directory created at:".$path);
        }
    }

    private function _path()
    {
        return $this->oConfig->getBaseDir()
        .$this->aParam[self::ATTR_IN].DIRECTORY_SEPARATOR
        .$this->aParam[self::ATTR_NAME]
        .DIRECTORY_SEPARATOR;
    }
}

要求:

//somefile.php
$path = "/var/www/ins/"

//someotherfile.php
return [
 'files' = [
     'Path\\To\\NameSpace',
     'Path\\To\\NameSpace'
 ]
];

所以,基本上我想根据特定规则更新/覆盖我提到的变量/数组,为此,我尝试在 json 模式中准备规则:

"actions": [
        {
          "what": "sed",
          "in": "path/to/somefile.php",
          "find": {
            "type": "variable",
            "value": "path"
          },
          "replace": {
            "type": "variable",
            "value": "__DIR__.'/../vendor/compiled.php';"
          }
        },{
          "what": "put",
          "value": "Path\\To\\NameSpace",
          "in": "path/to/someotherfile.php",
          "find": {
            "type": "array",
            "at": "files"
          }
        }
      ]

我正在使用的组件

  • symfony/控制台
  • symfony/finder
  • Symfony/文件系统

寻找:

  • 建议以这种方式组织规则集模式,以迭代更新/覆盖变量或从数组中推/拉元素的所有操作并执行操作。
  • 更新特定变量值的机制,以及使用 php 从数组/子数组中推/拉元素的机制。

如果我身边仍有不清楚的地方,请告诉我。提前致谢。

4

0 回答 0