3

vfsStream的用例如下:

$directories = explode('/', 'path/to/some/dir');

$structure = [];
$reference =& $structure;

foreach ($directories as $directory) {
    $reference[$directory] = [];
    $reference =& $reference[$directory];
}

vfsStream::setup();
$root = vfsStream::create($structure);
$file = vfsStream::newFile('file')
    ->at($root) //should changes be introduced here?
    ->setContent($content = 'Some content here');

的输出vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure()

Array
(
    [root] => Array
    (
        [path] => Array
        (
            [to] => Array
            (
                [some] => Array
                (
                    [dir] => Array
                    (
                    )
                )
            )
        )

        [file] => Some content here
    )
)

是否可以将文件插入特定目录,例如dir目录下?

4

2 回答 2

1

是的,显然可以vfsStreamFirectory使用以下addChild()方法将孩子添加到 a 中:

但是,我在API Docs中发现没有简单的方法可以轻松遍历结构以添加内容。对于这种特殊情况,这是一个可怕的 hacky,例如,如果每个路径元素有多个文件夹,它将失败。

基本上我们必须递归地遍历每个级别,验证名称是否是我们要添加文件的名称,然后在找到时添加它。

use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use org\bovigo\vfs\visitor\vfsStreamStructureVisitor;

$directories = explode('/', 'path/to/some/dir');

$structure = [];
$reference =& $structure;

foreach ($directories as $directory) {
    $reference[$directory] = [];
    $reference =& $reference[$directory];
}

vfsStream::setup();
$root = vfsStream::create($structure);
$file = vfsStream::newFile('file')
    ->setContent($content = 'Some content here');

$elem = $root;
while ($elem instanceof vfsStreamDirectory)
{
    if ($elem->getName() === 'dir')
    {
        $elem->addChild($file);
    }
    $children = $elem = $elem->getChildren();
    if (!isset($children[0]))
    {
        break;
    }
    $elem = $children[0];
}

print_r(vfsStream::inspect(new vfsStreamStructureVisitor())->getStructure());
于 2015-12-31T21:35:14.793 回答
0

答案在 github 上给出;因此而不是

->at($root)

应该使用

->at($root->getChild('path/to/some/dir')).
于 2016-01-06T13:26:28.990 回答