gpt4 book ai didi

php - 使用 vfsStream 将文件插入特定目录/节点

转载 作者:行者123 更新时间:2023-12-04 18:01:32 26 4
gpt4 key购买 nike

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目录下?

最佳答案

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

但是我在 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());

关于php - 使用 vfsStream 将文件插入特定目录/节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com