覆盖/更新php文件

时间:2016-06-27 08:54:14

标签: php json symfony symfony-components symfony-console

在我最近的项目中,使用console命令,我需要执行/运行基于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 Schema(数组)

          "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 / console
  • symfony / finder
  • 的Symfony /文件系统

寻找:

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

如果我身边还有一些不清楚的地方让我知道。 提前谢谢。

0 个答案:

没有答案