Skip to content

Commit

Permalink
createFile() should create directories.
Browse files Browse the repository at this point in the history
To improve compatibility with `Shell::createFile()`
`ConsoleIo::createFile()` should also create the required directories.
Because `Cake\Filesystem` is soft-deprecated I've rebuilt the directory
creation logic here as Spl does not handle it.
  • Loading branch information
markstory committed Dec 17, 2018
1 parent 540c353 commit e4b9b53
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Console/ConsoleIo.php
Expand Up @@ -566,6 +566,12 @@ public function createFile($path, $contents, $forceOverwrite = false)
}

try {
// Create the directory using the current user permissions.
$directory = dirname($path);
if (!file_exists($directory)) {
mkdir($directory, 0777 ^ umask(), true);
}

$file = new SplFileObject($path, 'w');
} catch (RuntimeException $e) {
$this->error("Could not write to `{$path}`. Permission denied.", 2);
Expand Down
19 changes: 19 additions & 0 deletions tests/TestCase/Console/ConsoleIoTest.php
Expand Up @@ -580,6 +580,8 @@ public function testErrHelpers($method)
*/
public function testCreateFileSuccess()
{
$this->err->expects($this->never())
->method('write');
$path = TMP . 'shell_test';
mkdir($path);

Expand All @@ -592,6 +594,23 @@ public function testCreateFileSuccess()
$this->assertStringEqualsFile($file, $contents);
}

public function testCreateFileDirectoryCreation()
{
$this->err->expects($this->never())
->method('write');

$directory = TMP . 'shell_test';
$this->assertFileNotExists($directory, 'Directory should not exist before createFile');

$path = $directory . DS . 'create.txt';
$contents = 'some content';
$result = $this->io->createFile($path, $contents);

$this->assertTrue($result, 'File should create');
$this->assertFileExists($path);
$this->assertStringEqualsFile($path, $contents);
}

/**
* Test that createFile with permissions error.
*
Expand Down

0 comments on commit e4b9b53

Please sign in to comment.