Perforce Chronicle 2012.2/486814
API Documentation

P4Cms_FileUtility Class Reference

Provides utility methods for manipulating files. More...

List of all members.

Static Public Member Functions

static copyRecursive ($source, $target)
 Copy a file or folder recursively.
static createWritablePath ($path)
 Create the given path and make it writable.
static deleteRecursive ($path)
 Delete a directory (and all its contents) recursively.
static getMimeType ($file)
 Detect the mime-type of the given file.
static md5Recursive ($path, $basePath=null, array $exclude=null)
 Calculate the md5sum of a directory (and all its contents) recursively.

Detailed Description

Provides utility methods for manipulating files.

Copyright:
2011-2012 Perforce Software. All rights reserved
License:
Please see LICENSE.txt in top-level folder of this distribution.
Version:
2012.2/486814

Member Function Documentation

static P4Cms_FileUtility::copyRecursive ( source,
target 
) [static]

Copy a file or folder recursively.

Parameters:
string$sourcethe source path to copy.
string$targetthe target path to copy to.
Exceptions:
InvalidArgumentExceptionif the source does not exist or if the target's containing folder doesn't exist
Exceptionif the copy fails
    {
        // strip trailing slashes on source/target.
        $source = rtrim($source, '/\\');
        $target = rtrim($target, '/\\');

        // verify source exists.
        if (!file_exists($source)) {
            throw new InvalidArgumentException("Cannot copy from non-existent source.");
        }

        // verify parent of target exists.
        if (!file_exists(dirname($target))) {
            throw new InvalidArgumentException("Cannot copy to target with non-existent parent.");
        }

        // deal with copying a single file.
        $error = "Failed to copy from $source to $target";
        if (!is_dir($source)) {
            $result = @copy($source, $target);
            if (!$result) {
                throw new Exception($error);
            }
            return;
        }

        // copying a folder - start by creating target folder
        if (!@mkdir($target, fileperms($source))) {
            throw new Exception($error);
        }

        // recursively copy contents of source
        $sourceList = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator(
                $source,
                RecursiveDirectoryIterator::SKIP_DOTS
            ),
            RecursiveIteratorIterator::SELF_FIRST
        );
        foreach ($sourceList as $item) {
            if ($item->isDir()) {
                $result = @mkdir($target . '/' . $sourceList->getSubPathName(), fileperms($item->getPathname()));
            } else {
                $result = @copy($item->getPathname(), $target . '/' . $sourceList->getSubPathName());
            }
            if (!$result) {
                throw new Exception($error);
            }
        }
    }
static P4Cms_FileUtility::createWritablePath ( path) [static]

Create the given path and make it writable.

Parameters:
string$paththe path to create and make writable.
    {
        if (!is_dir($path)) {
            if (!@mkdir($path, 0755, true)) {
                throw new Exception(
                    basename($path) . " directory does not exist and could not be created ('$path')."
                );
            }
        }
        if (!is_writable($path)) {
            if (!@chmod($path, 0755)) {
                throw new Exception(
                    "Unable to make " . basename($path) . " directory writable ('$path')."
                );
            }
        }
    }
static P4Cms_FileUtility::deleteRecursive ( path) [static]

Delete a directory (and all its contents) recursively.

Parameters:
string$paththe path to the directory to remove.
Returns:
bool true on success, false on failure.
    {
        // nothing to do if path doesn't exist.
        if (!file_exists($path)) {
            return;
        }

        // only delete directories.
        if (!is_dir($path)) {
            throw new InvalidArgumentException(
                "Failed to delete path. Path is not a directory."
            );
        }

        // delete contents of the given directory.
        $entries = new DirectoryIterator($path);
        foreach ($entries as $entry) {

            // skip '.' and '..'
            if ($entry->isDir() && $entry->isDot()) {
                continue;
            }

            // delete file entries, recurse for directories.
            if ($entry->isFile()) {
                @chmod($entry->getPathname(), 0777);
                @unlink($entry->getPathname());
            } else {
                static::deleteRecursive($entry->getPathname());
            }
        }

        // delete the directory itself.
        @chmod($path, 0777);
        return @rmdir($path);
    }
static P4Cms_FileUtility::getMimeType ( file) [static]

Detect the mime-type of the given file.

Parameters:
string$filethe file to detect the mime type of.
Exceptions:
InvalidArgumentExceptionif the given file does not exist.
    {
        if (!is_file($file)) {
            throw new InvalidArgumentException(
                "Cannot get mime-type of non-existent file ('$file')."
            );
        }

        return P4Cms_Validate_File_MimeType::getTypeOfFile($file);
    }
static P4Cms_FileUtility::md5Recursive ( path,
basePath = null,
array $  exclude = null 
) [static]

Calculate the md5sum of a directory (and all its contents) recursively.

Parameters:
string$paththe path to the directory to examine.
string$basePaththe base path for the action
array$excludea list of file(s) including relative path to exclude
    {
        // only md5sum files in a directory, md5 can be used for individual files
        if (!is_dir($path)) {
            throw new InvalidArgumentException('Provided path is not a valid directory.');
        }

        // if no base path provided, set to the provided path
        $basePath   = ($basePath === null ) ? $path : $basePath;

        $path       = rtrim($path, '/');
        $md5List    = array();

        // calculate md5 for contents of the given directory.
        // @todo: what about sort order?  Will it differ on different systems?
        $entries = new DirectoryIterator($path);
        foreach ($entries as $entry) {
            // skip '.' and '..'
            if ($entry->isDir() && $entry->isDot()) {
                continue;
            }

            // calculate md5 for file entries, recurse for directories.
            if ($entry->isFile()) {
                // strip off base path and remove the leading slash/backslashes
                if (strpos($path, $basePath) === 0) {
                    $relativePath = ltrim(substr($path, strlen($basePath)), '/\\');
                }

                // on Windows platform, replace backslashes with forward slashes
                if (P4_Environment::isWindows()) {
                    $relativePath = str_replace('\\', '/', $relativePath);
                }

                $filename = $entry->getFilename();
                $relativeFile = !empty($relativePath)
                    ? $relativePath . '/' . $filename
                    : $filename;

                // calculate md5 for non-excluded files
                if ($exclude === null || !in_array($relativeFile, $exclude)) {
                    $md5List[] = md5_file($path . '/' . $filename) . '  ' . $relativeFile;
                }
            } else {
                $md5List = array_merge($md5List, static::md5Recursive($entry->getPathname(), $basePath, $exclude));
            }
        }

        // return the list
        return $md5List;
    }

The documentation for this class was generated from the following file: