/** * Constructor. * * @param FilesystemObject|string $file File instance or the path of a file as a string of the file to read from. * The file or file path must be an existing file. * * @throws \Exception Throws an exception on error. */ public function __construct($file) { // Set the default file access mode $this->fileMode = FileAccessModeFactory::createReadOnlyMode(); // Get and store $file as File instance, throw an exception if failed if (($file = File::asFile($file)) === null) { // TODO: Throw a better exception! throw new \Exception("Invalid file!"); } // Set the file $this->setFile($file); }
/** * Get a file access mode instance. This method will try to instantiate a file access mode instance based on the * input. This method won't verify the validity of the file access mode string. * * @param FileAccessMode|string $mode File access mode instance, or a PHPs file access mode string. * * @return FileAccessMode|null The file access mode instance, or null on failure. */ public static function asFileAccessMode($mode) { // Return $mode if it's an FileAccessMode instance if ($mode instanceof FileAccessMode) { return $mode; } // The $mode must be a string if (!is_string($mode)) { return null; } // Trim $mode from unwanted whitespaces $mode = trim($mode); // Make sure $mode isn't empty and has a maximum of 4 characters. if (empty($mode) || strlen($mode) > 4) { return null; } // Try to convert the file access mode string into an instance, return the result return FileAccessModeFactory::createFromMode($mode); }
/** * Append to a file. * * @param File|string $file File instance or a file path as string to append to. * @param string $data The data to append to the file. * @param resource $context [optional] See PHPs fopen() function for more details. * @param bool $create [optional] True to attempt to create the file if it doens't exist. * * @return int|null The amount of bytes appended to the file. */ public static function append($file, $data, $context = null, $create = true) { // Convert the file into a path string, return the $default value if failed if (($file = self::asPath($file, false)) === null) { return null; } // Make sure the file is valid. If the file shouldn't be created make sure it exists already. if ($create) { if (!self::isValid($file)) { return null; } } else { if (!self::isFile($file)) { return null; } } // Open the file with the file writer $writer = new FileWriter($file, FileAccessModeFactory::createAppendMode(false)); if (!$writer->open(null, $context)) { return null; } // Append to the file, return the result return $writer->write($data); }