/** * Set the handled file. Automatically reopens the file handle if the handle was opened with a different file. * * @param File|\carbon\core\io\filesystem\FilesystemObject|string $file Handled file, a file or filesystem object * or the path of a file as a string. * @param FileAccessMode|string $mode [optional] The file access mode used by the handler as file access mode * instance or as PHPs file access mode string. See PHPs fopen() function for more details. This file access mode * will be used if the handle needs to be reopened. If set to null, the current file access mode will be used. * @param resource $context [optional] See PHPs fopen() function for more details. * This file context will be used if the handle needs to be reopened. * If set to null, the current file context will be used. * * @return bool True if succeed, false on failure. Also returns true if the file wasn't changed. * * @see fopen(); */ public function setFile($file, $mode = null, $context = null) { // Get $file as File instance and $mode as FileAccessMode instance, return false on failure if (($file = File::asFile($file)) === null) { return false; } $mode = FileAccessMode::asFileAccessMode($mode); // Make sure the file changed if ($this->file === $file) { return true; } // Set the file instance, return the result $this->file = $file; // Reopen the file handler if it's opened already, return the result if ($this->isOpened()) { return $this->reopen($mode->getMode(), $context); } return true; }
/** * Set the file to write to. The new file will automatically open if the current file was opened already. * * @param File|string| $file File instance or the file as a path string to write to. * * @return bool True if the file was successfully set, false on failure. */ public function setFile($file) { // Get $file as File instance, make sure it's not null if (($file = File::asFile($file)) === null) { return false; } // Make sure the file has changed if ($this->file === $file) { return true; } // Set the file $this->file = $file; // Open a new file handler if if hasn't been instantiated yet, return the result if ($this->handler === null) { $this->handler = new FileHandler($this->file); return true; } // Set the file being handled, reopen the file handler with the new file if it is opened, return the result return $this->handler->setFile($this->file); }