Cake\Console\Shell::createFile PHP Method

createFile() public method

Creates a file at given path
public createFile ( string $path, string $contents ) : boolean
$path string Where to put the file.
$contents string Content to put in the file.
return boolean Success
    public function createFile($path, $contents)
    {
        $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
        $this->_io->out();
        if (is_file($path) && empty($this->params['force']) && $this->interactive) {
            $this->_io->out(sprintf('<warning>File `%s` exists</warning>', $path));
            $key = $this->_io->askChoice('Do you want to overwrite?', ['y', 'n', 'a', 'q'], 'n');
            if (strtolower($key) === 'q') {
                $this->_io->out('<error>Quitting</error>.', 2);
                $this->_stop();
                return false;
            }
            if (strtolower($key) === 'a') {
                $this->params['force'] = true;
                $key = 'y';
            }
            if (strtolower($key) !== 'y') {
                $this->_io->out(sprintf('Skip `%s`', $path), 2);
                return false;
            }
        } else {
            $this->out(sprintf('Creating file %s', $path));
        }
        $File = new File($path, true);
        try {
            if ($File->exists() && $File->writable()) {
                $File->write($contents);
                $this->_io->out(sprintf('<success>Wrote</success> `%s`', $path));
                return true;
            }
            $this->_io->err(sprintf('<error>Could not write to `%s`</error>.', $path), 2);
            return false;
        } finally {
            $File->close();
        }
    }

Usage Example

Beispiel #1
1
 /**
  * Creates a file at given path
  * @param string $path Where to put the file
  * @param string $contents Content to put in the file
  * @return bool
  */
 public function createFile($path, $contents)
 {
     //Checks if the file already exist
     if (file_exists($path)) {
         $this->verbose(__d('me_tools', 'File or directory {0} already exists', rtr($path)));
         return false;
     }
     return parent::createFile($path, $contents);
 }