简体   繁体   中英

How to create nested directory from array in php

In laravel, I am trying to create the file using console. The file that I will be creating is a trait file. My situation is that, if I just write the name of the file, it gets created as desired. But when passed as a directory, it doesn't gets created.

The array can be dynamic. It is upto the user how much deep the directory should be.

Just for the example: I am taking 2 levels of directories.

My array is:

Array
(
    [0] => 'RootTrait' // the root place of the trait folder
    [1] => 'Level-1' // Directory inside the trait folder
    [2] => 'Level-2' // Directory inside the Level-1 folder
    [3] => 'file.php' // The file that will be created inside Level 2 folder
)

What should I do to achieve this ?

The code that I have tried so far is:

/**
 * Process the creation of trait file.
 * 
 * @param  string $traitName
 * @param  \Illuminate\Filesystem\Filesystem $file
 * @param  string $nameSpace
 * @return bool
 */
 public function processTraitFile($traitName, Filesystem $file, $nameSpace = 'App')
 {
     $traitFileName = $file->get('app/stubs/Trait.stub');

     $newTraitFile = str_replace(['TraitName', 'App'], [$traitName, $nameSpace], $traitFileName);

     if (! file_exists("app/Http/Traits/{$traitName}")) {
         $traitFolders = explode('/', $traitName);
         $lastElement = array_pop($traitFolders);

         foreach ($traitFolders as $key => $folder) {
             $file->makeDirectory('app/Http/Traits/' . $folder, 0755, true);
         }
     }

     return $file->put("app/Http/Traits/{$traitName}.php", $newTraitFile);
 }

The above method does create the folders, but not nested. It is creating the folder like this:

|-- Root Trait Folder
    |-- Level-1
    |-- Level-2
    |-- file.php

I know this must be simple to achieve, but I am failing.

Kindly help me out. Thanks.

I will simply change your for loop

$n = 'app/Http/Traits/';
foreach ($traitFolders as $key => $folder) {
         $file->makeDirectory($n. $folder, 0755, true);
         $n .= $folder.'/';
     }

Please use below code

<?php 
   $n = 'app/Http/Traits/';
   $n .= $traitName;
   mkdir($n, 0755, true);
?>

You could use the dirname :

// $traitName = 'RootTrait/Level-1/Level-2/file.php';

if (! $file->exists("app/Http/Traits/{$traitName}")) {
    $traitFolders = dirname($traitName);

    $file->makeDirectory('app/Http/Traits/' . $traitFolders, 0755, true);
}

return $file->put("app/Http/Traits/{$traitName}", $newTraitFile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM