From 778a94ff2223bd06398b2e2bfdd77ce0dd839cc9 Mon Sep 17 00:00:00 2001 From: Steeve Andrian Salim Date: Tue, 29 May 2018 14:49:36 +0700 Subject: [PATCH] Optimize codes --- src/Config/Mimes.php | 72 ++++----- src/Directory.php | 108 +++++++------- src/File.php | 192 ++++++++++++------------ src/Files/Abstracts/AbstractFile.php | 19 +-- src/Files/CsvFile.php | 37 ++--- src/Files/IniFile.php | 77 +++++----- src/Files/JsonFile.php | 23 +-- src/Files/XmlFile.php | 33 ++-- src/Files/ZipFile.php | 85 +++++------ src/Handlers/Downloader.php | 181 +++++++++++----------- src/Handlers/Ftp.php | 215 ++++++++++++++------------- src/Handlers/Uploader.php | 154 +++++++++---------- src/System.php | 80 +++++----- src/autoload.php | 22 +-- 14 files changed, 655 insertions(+), 643 deletions(-) diff --git a/src/Config/Mimes.php b/src/Config/Mimes.php index 585dc77..a8dcec8 100644 --- a/src/Config/Mimes.php +++ b/src/Config/Mimes.php @@ -49,9 +49,9 @@ 'dms' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', - 'exe' => [ 'application/octet-stream', 'application/x-msdownload' ], + 'exe' => ['application/octet-stream', 'application/x-msdownload'], 'class' => 'application/octet-stream', - 'psd' => [ 'application/x-photoshop', 'image/vnd.adobe.photoshop' ], + 'psd' => ['application/x-photoshop', 'image/vnd.adobe.photoshop'], 'so' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'dll' => 'application/octet-stream', @@ -62,7 +62,7 @@ 'application/x-download', 'binary/octet-stream', ], - 'ai' => [ 'application/pdf', 'application/postscript' ], + 'ai' => ['application/pdf', 'application/postscript'], 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', @@ -114,11 +114,11 @@ 'php3' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', - 'js' => [ 'application/x-javascript', 'text/plain' ], + 'js' => ['application/x-javascript', 'text/plain'], 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', - 'tgz' => [ 'application/x-tar', 'application/x-gzip-compressed' ], + 'tgz' => ['application/x-tar', 'application/x-gzip-compressed'], 'z' => 'application/x-compress', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', @@ -129,21 +129,21 @@ 'application/s-compressed', 'multipart/x-zip', ], - 'rar' => [ 'application/x-rar', 'application/rar', 'application/x-rar-compressed' ], + 'rar' => ['application/x-rar', 'application/rar', 'application/x-rar-compressed'], 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', - 'mp3' => [ 'audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3' ], - 'aif' => [ 'audio/x-aiff', 'audio/aiff' ], - 'aiff' => [ 'audio/x-aiff', 'audio/aiff' ], + 'mp3' => ['audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'], + 'aif' => ['audio/x-aiff', 'audio/aiff'], + 'aiff' => ['audio/x-aiff', 'audio/aiff'], 'aifc' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'rv' => 'video/vnd.rn-realvideo', - 'wav' => [ 'audio/x-wav', 'audio/wave', 'audio/wav' ], + 'wav' => ['audio/x-wav', 'audio/wave', 'audio/wav'], 'bmp' => [ 'image/bmp', 'image/x-bmp', @@ -161,35 +161,35 @@ 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpe' => 'image/jpeg', - 'png' => [ 'image/png', 'image/x-png' ], + 'png' => ['image/png', 'image/x-png'], 'tiff' => 'image/tiff', 'tif' => 'image/tiff', - 'css' => [ 'text/css', 'text/plain' ], - 'html' => [ 'text/html', 'text/plain' ], - 'htm' => [ 'text/html', 'text/plain' ], - 'shtml' => [ 'text/html', 'text/plain' ], + 'css' => ['text/css', 'text/plain'], + 'html' => ['text/html', 'text/plain'], + 'htm' => ['text/html', 'text/plain'], + 'shtml' => ['text/html', 'text/plain'], 'txt' => 'text/plain', 'text' => 'text/plain', - 'log' => [ 'text/plain', 'text/x-log' ], + 'log' => ['text/plain', 'text/x-log'], 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', - 'xml' => [ 'application/xml', 'text/xml', 'text/plain' ], - 'xsl' => [ 'application/xml', 'text/xsl', 'text/xml' ], + 'xml' => ['application/xml', 'text/xml', 'text/plain'], + 'xsl' => ['application/xml', 'text/xsl', 'text/xml'], 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', - 'avi' => [ 'video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo' ], + 'avi' => ['video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo'], 'movie' => 'video/x-sgi-movie', - 'doc' => [ 'application/msword', 'application/vnd.ms-office' ], + 'doc' => ['application/msword', 'application/vnd.ms-office'], 'docx' => [ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword', 'application/x-zip', ], - 'dot' => [ 'application/msword', 'application/vnd.ms-office' ], + 'dot' => ['application/msword', 'application/vnd.ms-office'], 'dotx' => [ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', @@ -202,20 +202,20 @@ 'application/msword', 'application/x-zip', ], - 'word' => [ 'application/msword', 'application/octet-stream' ], + 'word' => ['application/msword', 'application/octet-stream'], 'xl' => 'application/excel', 'eml' => 'message/rfc822', - 'json' => [ 'application/json', 'text/json' ], - 'pem' => [ 'application/x-x509-user-cert', 'application/x-pem-file', 'application/octet-stream' ], - 'p10' => [ 'application/x-pkcs10', 'application/pkcs10' ], + 'json' => ['application/json', 'text/json'], + 'pem' => ['application/x-x509-user-cert', 'application/x-pem-file', 'application/octet-stream'], + 'p10' => ['application/x-pkcs10', 'application/pkcs10'], 'p12' => 'application/x-pkcs12', 'p7a' => 'application/x-pkcs7-signature', - 'p7c' => [ 'application/pkcs7-mime', 'application/x-pkcs7-mime' ], - 'p7m' => [ 'application/pkcs7-mime', 'application/x-pkcs7-mime' ], + 'p7c' => ['application/pkcs7-mime', 'application/x-pkcs7-mime'], + 'p7m' => ['application/pkcs7-mime', 'application/x-pkcs7-mime'], 'p7r' => 'application/x-pkcs7-certreqresp', 'p7s' => 'application/pkcs7-signature', - 'crt' => [ 'application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert' ], - 'crl' => [ 'application/pkix-crl', 'application/pkcs-crl' ], + 'crt' => ['application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert'], + 'crl' => ['application/pkix-crl', 'application/pkcs-crl'], 'der' => 'application/x-x509-ca-cert', 'kdb' => 'application/octet-stream', 'pgp' => 'application/pgp', @@ -223,7 +223,7 @@ 'sst' => 'application/octet-stream', 'csr' => 'application/octet-stream', 'rsa' => 'application/x-pkcs7', - 'cer' => [ 'application/pkix-cert', 'application/x-x509-ca-cert' ], + 'cer' => ['application/pkix-cert', 'application/x-x509-ca-cert'], '3g2' => 'video/3gpp2', '3gp' => 'video/3gp', 'mp4' => 'video/mp4', @@ -235,13 +235,13 @@ 'm3u' => 'text/plain', 'xspf' => 'application/xspf+xml', 'vlc' => 'application/videolan', - 'wmv' => [ 'video/x-ms-wmv', 'video/x-ms-asf' ], + 'wmv' => ['video/x-ms-wmv', 'video/x-ms-asf'], 'au' => 'audio/x-au', 'ac3' => 'audio/ac3', 'flac' => 'audio/x-flac', 'ogg' => 'audio/ogg', - 'kmz' => [ 'application/vnd.google-earth.kmz', 'application/zip', 'application/x-zip' ], - 'kml' => [ 'application/vnd.google-earth.kml+xml', 'application/xml', 'text/xml' ], + 'kmz' => ['application/vnd.google-earth.kmz', 'application/zip', 'application/x-zip'], + 'kml' => ['application/vnd.google-earth.kml+xml', 'application/xml', 'text/xml'], 'ics' => 'text/calendar', 'ical' => 'text/calendar', 'zsh' => 'text/x-scriptzsh', @@ -260,16 +260,16 @@ 'image/x-cdr', 'zz-application/zz-winassoc-cdr', ], - 'wma' => [ 'audio/x-ms-wma', 'video/x-ms-asf' ], + 'wma' => ['audio/x-ms-wma', 'video/x-ms-asf'], 'jar' => [ 'application/java-archive', 'application/x-java-application', 'application/x-jar', 'application/x-compressed', ], - 'svg' => [ 'image/svg+xml', 'application/xml', 'text/xml' ], + 'svg' => ['image/svg+xml', 'application/xml', 'text/xml'], 'vcf' => 'text/x-vcard', - 'ttf' => [ 'application/x-font-ttf', 'application/x-font-truetype' ], + 'ttf' => ['application/x-font-ttf', 'application/x-font-truetype'], 'otf' => 'application/x-font-opentype', 'woff' => 'application/font-woff', 'woff2' => 'application/font-woff2', diff --git a/src/Directory.php b/src/Directory.php index 4a8de85..bd4389d 100644 --- a/src/Directory.php +++ b/src/Directory.php @@ -8,6 +8,7 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem; @@ -34,30 +35,30 @@ class Directory extends SplDirectoryInfo * * @return bool|\O2System\Spl\Info\SplDirectoryInfo */ - public function make( $dir = null, $mode = 0777, $recursive = true ) + public function make($dir = null, $mode = 0777, $recursive = true) { - $dir = is_null( $dir ) ? $this->getPathName() : $dir; + $dir = is_null($dir) ? $this->getPathName() : $dir; - if ( is_dir( $dir ) ) { - return new SplDirectoryInfo( $dir ); - } elseif ( null !== ( $pathName = $this->getPathName() ) ) { - if ( mkdir( + if (is_dir($dir)) { + return new SplDirectoryInfo($dir); + } elseif (null !== ($pathName = $this->getPathName())) { + if (mkdir( $makeDirectory = $pathName . DIRECTORY_SEPARATOR . str_replace( - [ '\\', '/' ], + ['\\', '/'], DIRECTORY_SEPARATOR, $dir ), $mode, $recursive - ) ) { - return new SplDirectoryInfo( $makeDirectory ); + )) { + return new SplDirectoryInfo($makeDirectory); } - } elseif ( mkdir( - $makeDirectory = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $dir ), + } elseif (mkdir( + $makeDirectory = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $dir), $mode, $recursive - ) ) { - return new SplDirectoryInfo( $makeDirectory ); + )) { + return new SplDirectoryInfo($makeDirectory); } return false; @@ -74,9 +75,9 @@ public function make( $dir = null, $mode = 0777, $recursive = true ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function delete( $fileOnly = false ) + public function delete($fileOnly = false) { - return $this->recursiveDelete( $this->getRealPath(), $fileOnly ); + return $this->recursiveDelete($this->getRealPath(), $fileOnly); } // ------------------------------------------------------------------------ @@ -89,23 +90,23 @@ public function delete( $fileOnly = false ) * * @return bool Returns TRUE on success or FALSE on failure. */ - private function recursiveDelete( $dir, $fileOnly = false ) + private function recursiveDelete($dir, $fileOnly = false) { - $dir = realpath( $dir ); - - if ( is_dir( $dir ) ) { - $iterator = new \RecursiveDirectoryIterator( $dir, \RecursiveDirectoryIterator::SKIP_DOTS ); - $files = new \RecursiveIteratorIterator( $iterator, \RecursiveIteratorIterator::CHILD_FIRST ); - foreach ( $files as $file ) { - if ( $file->isDir() ) { - $this->recursiveDelete( $file->getRealPath(), $fileOnly ); - } elseif ( $file->isFile() ) { - unlink( $file->getRealPath() ); + $dir = realpath($dir); + + if (is_dir($dir)) { + $iterator = new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS); + $files = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST); + foreach ($files as $file) { + if ($file->isDir()) { + $this->recursiveDelete($file->getRealPath(), $fileOnly); + } elseif ($file->isFile()) { + unlink($file->getRealPath()); } } - if ( $fileOnly === false ) { - rmdir( $dir ); + if ($fileOnly === false) { + rmdir($dir); } return true; @@ -128,12 +129,12 @@ private function recursiveDelete( $dir, $fileOnly = false ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function setGroup( $group ) + public function setGroup($group) { $params[] = $this->getRealPath(); $params[] = $group; - return call_user_func_array( 'chgrp', $params ); + return call_user_func_array('chgrp', $params); } // ------------------------------------------------------------------------ @@ -153,12 +154,12 @@ public function setGroup( $group ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function setMode( $mode ) + public function setMode($mode) { $params[] = $this->getRealPath(); $params[] = $mode; - return call_user_func_array( 'chmod', $params ); + return call_user_func_array('chmod', $params); } // ------------------------------------------------------------------------ @@ -173,34 +174,34 @@ public function setMode( $mode ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function setOwner( $user ) + public function setOwner($user) { $params[] = $this->getRealPath(); $params[] = $user; - return call_user_func_array( 'chown', $params ); + return call_user_func_array('chown', $params); } // ------------------------------------------------------------------------ - public function findFilesByExtension( $extension ) + public function findFilesByExtension($extension) { - $extension = trim( $extension, '.' ); + $extension = trim($extension, '.'); $directoryIterator = new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator( $this->getRealPath() ), + new \RecursiveDirectoryIterator($this->getRealPath()), \RecursiveIteratorIterator::SELF_FIRST ); $result = []; - foreach ( $directoryIterator as $directoryFile ) { - if ( $directoryFile->isFile() ) { - if ( $extension === '*' ) { - array_push( $result, $directoryFile->getFilename() ); - } elseif ( preg_match( '/\.' . $extension . '$/ui', $directoryFile->getFilename() ) ) { - if ( ! in_array( $directoryFile->getRealPath(), $result ) ) { - array_push( $result, $directoryFile->getRealPath() ); + foreach ($directoryIterator as $directoryFile) { + if ($directoryFile->isFile()) { + if ($extension === '*') { + array_push($result, $directoryFile->getFilename()); + } elseif (preg_match('/\.' . $extension . '$/ui', $directoryFile->getFilename())) { + if ( ! in_array($directoryFile->getRealPath(), $result)) { + array_push($result, $directoryFile->getRealPath()); } } } @@ -215,26 +216,27 @@ public function findFilesByExtension( $extension ) * Directory::findFilesByFilename * * Find Files By Filename - * + * * @param string $filename + * * @return array */ - public function findFilesByFilename( $filename ) + public function findFilesByFilename($filename) { $directoryIterator = new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator( $this->getRealPath() ), + new \RecursiveDirectoryIterator($this->getRealPath()), \RecursiveIteratorIterator::SELF_FIRST ); $result = []; - foreach ( $directoryIterator as $directoryFile ) { - if ( $directoryFile->isFile() ) { - if ( preg_match( '/\\' . $filename . '.*/ui', $directoryFile->getFilename() ) OR - preg_match( '/\\' . ucfirst( $filename ) . '.*/ui', $directoryFile->getFilename() ) + foreach ($directoryIterator as $directoryFile) { + if ($directoryFile->isFile()) { + if (preg_match('/\\' . $filename . '.*/ui', $directoryFile->getFilename()) OR + preg_match('/\\' . ucfirst($filename) . '.*/ui', $directoryFile->getFilename()) ) { - if ( ! in_array( $directoryFile->getRealPath(), $result ) ) { - array_push( $result, $directoryFile->getRealPath() ); + if ( ! in_array($directoryFile->getRealPath(), $result)) { + array_push($result, $directoryFile->getRealPath()); } } } diff --git a/src/File.php b/src/File.php index cc8b09b..ae096ca 100644 --- a/src/File.php +++ b/src/File.php @@ -8,6 +8,7 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem; @@ -35,14 +36,14 @@ class File extends SplFileInfo /** * File::__construct - * + * * @param string|null $filePath */ - public function __construct( $filePath = null ) + public function __construct($filePath = null) { - if ( isset( $filePath ) ) { + if (isset($filePath)) { $this->filePath = $filePath; - parent::__construct( $filePath ); + parent::__construct($filePath); } } @@ -60,12 +61,12 @@ public function __construct( $filePath = null ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function setGroup( $group ) + public function setGroup($group) { $params[] = $this->getRealPath(); $params[] = $group; - return call_user_func_array( 'chgrp', $params ); + return call_user_func_array('chgrp', $params); } // ------------------------------------------------------------------------ @@ -84,12 +85,12 @@ public function setGroup( $group ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function setMode( $mode ) + public function setMode($mode) { $params[] = $this->getRealPath(); $params[] = $mode; - return call_user_func_array( 'chmod', $params ); + return call_user_func_array('chmod', $params); } // ------------------------------------------------------------------------ @@ -104,12 +105,12 @@ public function setMode( $mode ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function setOwner( $user ) + public function setOwner($user) { $params[] = $this->getRealPath(); $params[] = $user; - return call_user_func_array( 'chown', $params ); + return call_user_func_array('chown', $params); } // ------------------------------------------------------------------------ @@ -123,12 +124,12 @@ public function setOwner( $user ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function setLink( $link ) + public function setLink($link) { $params[] = $this->getRealPath(); $params[] = $link; - return call_user_func_array( 'symlink', $params ); + return call_user_func_array('symlink', $params); } // ------------------------------------------------------------------------ @@ -154,18 +155,18 @@ public function setLink( $link ) * * @return string The function returns the read data or FALSE on failure. */ - public function getContents( $useIncludePath = false, $context = null, $offset = 0, $maxlen = 0 ) + public function getContents($useIncludePath = false, $context = null, $offset = 0, $maxlen = 0) { $params[] = $this->getRealPath(); $params[] = $useIncludePath; $params[] = $context; $params[] = $offset; - if ( $maxlen > 0 ) { + if ($maxlen > 0) { $params[] = $maxlen; } - return call_user_func_array( 'file_get_contents', $params ); + return call_user_func_array('file_get_contents', $params); } // ------------------------------------------------------------------------ @@ -180,13 +181,13 @@ public function getContents( $useIncludePath = false, $context = null, $offset = * * @return bool Returns TRUE on success or FALSE on failure. */ - public function touch( $time = null, $atime = null ) + public function touch($time = null, $atime = null) { $params[] = $this->getRealPath(); - $params[] = ( isset( $time ) ? $time : time() ); - $params[] = ( isset( $atime ) ? $atime : time() ); + $params[] = (isset($time) ? $time : time()); + $params[] = (isset($atime) ? $atime : time()); - return call_user_func_array( 'touch', $params ); + return call_user_func_array('touch', $params); } // ------------------------------------------------------------------------ @@ -200,56 +201,56 @@ public function touch( $time = null, $atime = null ) */ public function show() { - if ( $mime = $this->getMime() ) { - $mime = is_array( $mime ) ? $mime[ 0 ] : $mime; - } elseif ( is_file( $this->getRealPath() ) ) { + if ($mime = $this->getMime()) { + $mime = is_array($mime) ? $mime[ 0 ] : $mime; + } elseif (is_file($this->getRealPath())) { $mime = 'application/octet-stream'; } - $fileSize = filesize( $this->getRealPath() ); - $filename = pathinfo( $this->getRealPath(), PATHINFO_BASENAME ); + $fileSize = filesize($this->getRealPath()); + $filename = pathinfo($this->getRealPath(), PATHINFO_BASENAME); // Common headers $expires = 604800; // (60*60*24*7) - header( 'Expires:' . gmdate( 'D, d M Y H:i:s', time() + $expires ) . ' GMT' ); + header('Expires:' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT'); - header( 'Accept-Ranges: bytes', true ); - header( "Cache-control: private", true ); - header( 'Pragma: private', true ); + header('Accept-Ranges: bytes', true); + header("Cache-control: private", true); + header('Pragma: private', true); - header( 'Content-Type: ' . $mime ); - header( 'Content-Disposition: inline; filename="' . $filename . '"' ); - header( 'Content-Transfer-Encoding: binary' ); - header( 'Accept-Ranges: bytes' ); + header('Content-Type: ' . $mime); + header('Content-Disposition: inline; filename="' . $filename . '"'); + header('Content-Transfer-Encoding: binary'); + header('Accept-Ranges: bytes'); - $ETag = '"' . md5( $filename ) . '"'; + $ETag = '"' . md5($filename) . '"'; - if ( ! empty( $_SERVER[ 'HTTP_IF_NONE_MATCH' ] ) + if ( ! empty($_SERVER[ 'HTTP_IF_NONE_MATCH' ]) && $_SERVER[ 'HTTP_IF_NONE_MATCH' ] == $ETag ) { - header( 'HTTP/1.1 304 Not Modified' ); - header( 'Content-Length: ' . $fileSize ); + header('HTTP/1.1 304 Not Modified'); + header('Content-Length: ' . $fileSize); exit; } $expires = 604800; // (60*60*24*7) - header( 'ETag: ' . $ETag ); - header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s', time() ) . ' GMT' ); - header( 'Expires:' . gmdate( 'D, d M Y H:i:s', time() + $expires ) . ' GMT' ); + header('ETag: ' . $ETag); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT'); + header('Expires:' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT'); // Open file // @readfile($file_path); - $file = @fopen( $filename, "rb" ); - if ( $file ) { - while ( ! feof( $file ) ) { - print( fread( $file, 1024 * 8 ) ); + $file = @fopen($filename, "rb"); + if ($file) { + while ( ! feof($file)) { + print(fread($file, 1024 * 8)); flush(); - if ( connection_status() != 0 ) { - @fclose( $file ); + if (connection_status() != 0) { + @fclose($file); die(); } } - @fclose( $file ); + @fclose($file); } } @@ -265,9 +266,9 @@ public function show() public function getMime() { $mimes = $this->getMimes(); - $ext = strtolower( $this->getExtension() ); + $ext = strtolower($this->getExtension()); - if ( isset( $mimes[ $ext ] ) ) { + if (isset($mimes[ $ext ])) { return $mimes[ $ext ]; } @@ -288,9 +289,9 @@ public static function getMimes() { static $mimes; - if ( empty( $mimes ) ) { - if ( file_exists( __DIR__ . '/Config/Mimes.php' ) ) { - $mimes = require( __DIR__ . '/Config/Mimes.php' ); + if (empty($mimes)) { + if (file_exists(__DIR__ . '/Config/Mimes.php')) { + $mimes = require(__DIR__ . '/Config/Mimes.php'); } } @@ -311,76 +312,77 @@ public static function getMimes() * @return int Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless * the function was called as @readfile(), an error message is printed. */ - public function read( $useIncludePath = false, $context = null ) + public function read($useIncludePath = false, $context = null) { $params[] = $this->getRealPath(); $params[] = $useIncludePath; $params[] = $context; - return call_user_func_array( 'readfile', $params ); + return call_user_func_array('readfile', $params); } // ------------------------------------------------------------------------ /** - * File::create + * File::write * - * Create a File - * - * @param string|null $filePath - * @param string $mode - * @return resource + * Writes a file. + * + * @param string $contents File contents to write. + * @param string $mode File handle mode. + * + * @return bool */ - public function create( $filePath = null, $mode = 'wb' ) + public function write($filePath, $contents, $mode = 'wb') { - $filePath = isset( $filePath ) ? $filePath : $this->filePath; - $dir = dirname( $filePath ); + if (false !== ($fp = $this->create($filePath, $mode))) { + flock($fp, LOCK_EX); - if ( ! is_writable( $dir ) ) { - if ( ! file_exists( $dir ) ) { - mkdir( $dir, 0777, true ); + for ($result = $written = 0, $length = strlen($contents); $written < $length; $written += $result) { + if (($result = fwrite($fp, substr($contents, $written))) === false) { + break; + } } - } - if ( ! $fp = @fopen( $filePath, $mode ) ) { - return false; - } + flock($fp, LOCK_UN); + fclose($fp); - parent::__construct( $filePath ); + return is_int($result); + } - return $fp; + return false; } // ------------------------------------------------------------------------ /** - * File::write + * File::create * - * Writes a file. + * Create a File * - * @param string $contents File contents to write. - * @param string $mode File handle mode. + * @param string|null $filePath + * @param string $mode * - * @return bool + * @return resource */ - public function write( $filePath, $contents, $mode = 'wb' ) + public function create($filePath = null, $mode = 'wb') { - if ( false !== ( $fp = $this->create( $filePath, $mode ) ) ) { - flock( $fp, LOCK_EX ); + $filePath = isset($filePath) ? $filePath : $this->filePath; + $dir = dirname($filePath); - for ( $result = $written = 0, $length = strlen( $contents ); $written < $length; $written += $result ) { - if ( ( $result = fwrite( $fp, substr( $contents, $written ) ) ) === false ) { - break; - } + if ( ! is_writable($dir)) { + if ( ! file_exists($dir)) { + mkdir($dir, 0777, true); } + } - flock( $fp, LOCK_UN ); - fclose( $fp ); - - return is_int( $result ); + if ( ! $fp = @fopen($filePath, $mode)) { + return false; } - return false; + parent::__construct($filePath); + + return $fp; } // ------------------------------------------------------------------------ @@ -396,13 +398,13 @@ public function write( $filePath, $contents, $mode = 'wb' ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function rename( $newFilename, $context = null ) + public function rename($newFilename, $context = null) { $params[] = $this->getRealPath(); - $params[] = dirname( $this->getRealPath() ) . DIRECTORY_SEPARATOR . $newFilename; + $params[] = dirname($this->getRealPath()) . DIRECTORY_SEPARATOR . $newFilename; $params[] = $context; - return call_user_func_array( 'rename', $params ); + return call_user_func_array('rename', $params); } // ------------------------------------------------------------------------ @@ -418,13 +420,13 @@ public function rename( $newFilename, $context = null ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function copy( $destination, $context = null ) + public function copy($destination, $context = null) { $params[] = $this->getRealPath(); $params[] = $destination; $params[] = $context; - return call_user_func_array( 'copy', $params ); + return call_user_func_array('copy', $params); } // ------------------------------------------------------------------------ @@ -439,11 +441,11 @@ public function copy( $destination, $context = null ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function delete( $context = null ) + public function delete($context = null) { $params[] = $this->getRealPath(); $params[] = $context; - return call_user_func_array( 'unlink', $params ); + return call_user_func_array('unlink', $params); } } \ No newline at end of file diff --git a/src/Files/Abstracts/AbstractFile.php b/src/Files/Abstracts/AbstractFile.php index 3960514..5f1c998 100644 --- a/src/Files/Abstracts/AbstractFile.php +++ b/src/Files/Abstracts/AbstractFile.php @@ -8,6 +8,7 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Files\Abstracts; @@ -25,14 +26,14 @@ abstract class AbstractFile extends AbstractRepository { /** * AbstractFile::$fileExtension - * + * * @var string */ protected $fileExtension; /** * AbstractFile::$filePath - * + * * @var string */ protected $filePath; @@ -44,9 +45,9 @@ abstract class AbstractFile extends AbstractRepository * * @param string|null $filePath Path to the file. */ - final public function __construct( $filePath = null ) + final public function __construct($filePath = null) { - if ( isset( $filePath ) ) { + if (isset($filePath)) { $this->filePath = $filePath; } } @@ -60,13 +61,13 @@ final public function __construct( $filePath = null ) * * @return static */ - final public function createFile( $filePath = null ) + final public function createFile($filePath = null) { - if ( isset( $filePath ) ) { + if (isset($filePath)) { $this->filePath = $filePath; } - if( pathinfo( $this->filePath, PATHINFO_EXTENSION) === '') { + if (pathinfo($this->filePath, PATHINFO_EXTENSION) === '') { $this->filePath .= $this->fileExtension; } @@ -83,7 +84,7 @@ final public function createFile( $filePath = null ) * * @return mixed */ - abstract public function readFile( $filePath = null, array $options = [] ); + abstract public function readFile($filePath = null, array $options = []); // ------------------------------------------------------------------------ @@ -95,5 +96,5 @@ abstract public function readFile( $filePath = null, array $options = [] ); * * @return bool Returns TRUE on success or FALSE on failure. */ - abstract public function writeFile( $filePath = null, array $options = [] ); + abstract public function writeFile($filePath = null, array $options = []); } \ No newline at end of file diff --git a/src/Files/CsvFile.php b/src/Files/CsvFile.php index 45a47e5..f37fea3 100644 --- a/src/Files/CsvFile.php +++ b/src/Files/CsvFile.php @@ -8,14 +8,15 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Files; // ------------------------------------------------------------------------ -use O2System\Filesystem\Files\Abstracts\AbstractFile; use O2System\Filesystem\File; +use O2System\Filesystem\Files\Abstracts\AbstractFile; /** * Class CsvFile @@ -26,13 +27,13 @@ class CsvFile extends AbstractFile { /** * CsvFile::$fileExtension - * + * * @var string */ protected $fileExtension = '.csv'; // ------------------------------------------------------------------------ - + /** * CsvFile::readFile * @@ -41,24 +42,24 @@ class CsvFile extends AbstractFile * * @return mixed */ - public function readFile( $filePath = null, array $options = [] ) + public function readFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; $defaultOptions = [ - 'length' => 1000, - 'delimiter' => ',' + 'length' => 1000, + 'delimiter' => ',', ]; $options = array_merge($defaultOptions, $options); $result = []; - if ( false !== ( $handle = fopen( $filePath, 'r' ) ) ) { - while ( false !== ($data = fgetcsv($handle, $options['length'], $options['delimiter']) ) ) { - $result[] = fgetcsv( $handle ); + if (false !== ($handle = fopen($filePath, 'r'))) { + while (false !== ($data = fgetcsv($handle, $options[ 'length' ], $options[ 'delimiter' ]))) { + $result[] = fgetcsv($handle); } } @@ -75,23 +76,23 @@ public function readFile( $filePath = null, array $options = [] ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function writeFile( $filePath = null, array $options = [] ) + public function writeFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; - $handle = ( new File() )->create( $filePath ); + $handle = (new File())->create($filePath); - foreach ( $this->getArrayCopy() as $key => $value ) { - if ( ! is_array( $value ) ) { - $list = [ $key, $value ]; + foreach ($this->getArrayCopy() as $key => $value) { + if ( ! is_array($value)) { + $list = [$key, $value]; } else { $list = $value; } - fputcsv( $handle, $list ); + fputcsv($handle, $list); } - return fclose( $handle ); + return fclose($handle); } } \ No newline at end of file diff --git a/src/Files/IniFile.php b/src/Files/IniFile.php index b1cc233..2c7d62c 100644 --- a/src/Files/IniFile.php +++ b/src/Files/IniFile.php @@ -8,14 +8,15 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Files; // ------------------------------------------------------------------------ -use O2System\Filesystem\Files\Abstracts\AbstractFile; use O2System\Filesystem\File; +use O2System\Filesystem\Files\Abstracts\AbstractFile; /** * Class IniFile @@ -34,16 +35,16 @@ class IniFile extends AbstractFile * * @return mixed */ - public function readFile( $filePath, array $options = [] ) + public function readFile($filePath, array $options = []) { $items = parse_ini_file( $filePath, - ( empty( $options ) + (empty($options) ? true - : $options[ 'sections' ] ) + : $options[ 'sections' ]) ); - $this->merge( $items ); + $this->merge($items); return $items; } @@ -58,72 +59,72 @@ public function readFile( $filePath, array $options = [] ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function writeFile( $filePath = null, array $options = [] ) + public function writeFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; - $sections = ( empty( $options ) + $sections = (empty($options) ? true - : $options[ 'sections' ] ); + : $options[ 'sections' ]); $content = null; - if ( $sections ) { - foreach ( $this->getArrayCopy() as $section => $data ) { - if ( is_array( $data ) ) { + if ($sections) { + foreach ($this->getArrayCopy() as $section => $data) { + if (is_array($data)) { $content .= '[' . $section . ']' . PHP_EOL; - foreach ( $data as $key => $value ) { - if ( is_array( $value ) ) { - foreach ( $value as $valueChild ) { - $content .= $key . '[] = ' . ( is_numeric( $valueChild ) + foreach ($data as $key => $value) { + if (is_array($value)) { + foreach ($value as $valueChild) { + $content .= $key . '[] = ' . (is_numeric($valueChild) ? $valueChild - : '"' . $valueChild . '"' ) . PHP_EOL; + : '"' . $valueChild . '"') . PHP_EOL; } - } elseif ( strpos( $key, ';' ) !== false ) { - $content .= '; ' . trim( ucfirst( $key ), ';' ) . ' ' . $value . PHP_EOL; - } elseif ( empty( $value ) ) { + } elseif (strpos($key, ';') !== false) { + $content .= '; ' . trim(ucfirst($key), ';') . ' ' . $value . PHP_EOL; + } elseif (empty($value)) { $content .= $key . ' = ' . PHP_EOL; } else { - $content .= $key . ' = ' . ( is_numeric( $value ) + $content .= $key . ' = ' . (is_numeric($value) ? $value - : '"' . $value . '"' ) . PHP_EOL; + : '"' . $value . '"') . PHP_EOL; } } $content .= PHP_EOL; - } elseif ( strpos( $section, ';' ) !== false ) { - $content .= '; ' . trim( ucfirst( $section ), ';' ) . ' ' . $data . PHP_EOL; - } elseif ( empty( $data ) ) { + } elseif (strpos($section, ';') !== false) { + $content .= '; ' . trim(ucfirst($section), ';') . ' ' . $data . PHP_EOL; + } elseif (empty($data)) { $content .= $section . ' = ' . PHP_EOL; } else { - $content .= $section . ' = ' . ( is_numeric( $data ) + $content .= $section . ' = ' . (is_numeric($data) ? $data - : '"' . $data . '"' ) . PHP_EOL; + : '"' . $data . '"') . PHP_EOL; } } } else { - foreach ( $this->getArrayCopy() as $key => $value ) { - if ( is_array( $value ) ) { - foreach ( $value as $valueChild ) { - $content .= $key . '[] = ' . ( is_numeric( $valueChild ) + foreach ($this->getArrayCopy() as $key => $value) { + if (is_array($value)) { + foreach ($value as $valueChild) { + $content .= $key . '[] = ' . (is_numeric($valueChild) ? $valueChild - : '"' . $valueChild . '"' ) . PHP_EOL; + : '"' . $valueChild . '"') . PHP_EOL; } - } elseif ( strpos( $key, ';' ) !== false ) { - $content .= '; ' . trim( ucfirst( $key ), ';' ) . ' ' . $value . PHP_EOL; - } elseif ( empty( $value ) ) { + } elseif (strpos($key, ';') !== false) { + $content .= '; ' . trim(ucfirst($key), ';') . ' ' . $value . PHP_EOL; + } elseif (empty($value)) { $content .= $key . ' = ' . PHP_EOL; } else { - $content .= $key . ' = ' . ( is_numeric( $value ) + $content .= $key . ' = ' . (is_numeric($value) ? $value - : '"' . $value . '"' ) . PHP_EOL; + : '"' . $value . '"') . PHP_EOL; } } } - return ( new File() )->write( $filePath, $content ); + return (new File())->write($filePath, $content); } } \ No newline at end of file diff --git a/src/Files/JsonFile.php b/src/Files/JsonFile.php index 4e097e1..38f91c4 100644 --- a/src/Files/JsonFile.php +++ b/src/Files/JsonFile.php @@ -8,14 +8,15 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Files; // ------------------------------------------------------------------------ -use O2System\Filesystem\Files\Abstracts\AbstractFile; use O2System\Filesystem\File; +use O2System\Filesystem\Files\Abstracts\AbstractFile; use O2System\Spl\Datastructures\SplArrayObject; use O2System\Spl\Iterators\ArrayIterator; @@ -36,18 +37,18 @@ class JsonFile extends AbstractFile * * @return mixed */ - public function readFile( $filePath = null, array $options = [] ) + public function readFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; $result = new ArrayIterator(); - if ( false !== ( $contents = json_decode( file_get_contents( $filePath ), true ) ) ) { - if ( json_last_error() === JSON_ERROR_NONE ) { - foreach($contents as $content) { - $result[] = new SplArrayObject( $content ); + if (false !== ($contents = json_decode(file_get_contents($filePath), true))) { + if (json_last_error() === JSON_ERROR_NONE) { + foreach ($contents as $content) { + $result[] = new SplArrayObject($content); } } } @@ -65,14 +66,14 @@ public function readFile( $filePath = null, array $options = [] ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function writeFile( $filePath = null, array $options = [] ) + public function writeFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; - if ( $this->count() ) { - return ( new File() )->write( $filePath, json_encode( $this->getArrayCopy(), JSON_PRETTY_PRINT ) ); + if ($this->count()) { + return (new File())->write($filePath, json_encode($this->getArrayCopy(), JSON_PRETTY_PRINT)); } } } \ No newline at end of file diff --git a/src/Files/XmlFile.php b/src/Files/XmlFile.php index ceaa026..e8642ef 100644 --- a/src/Files/XmlFile.php +++ b/src/Files/XmlFile.php @@ -8,14 +8,15 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Files; // ------------------------------------------------------------------------ -use O2System\Filesystem\Files\Abstracts\AbstractFile; use O2System\Filesystem\File; +use O2System\Filesystem\Files\Abstracts\AbstractFile; use O2System\Spl\Datastructures\SplArrayObject; use O2System\Spl\Iterators\ArrayIterator; @@ -36,24 +37,24 @@ class XmlFile extends AbstractFile * * @return mixed */ - public function readFile( $filePath = null, array $options = [] ) + public function readFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; $result = new ArrayIterator(); - if ( false !== ( $xml = simplexml_load_file( $filePath ) ) ) { - $contents = json_decode( json_encode( $xml ), true ); // force to array conversion + if (false !== ($xml = simplexml_load_file($filePath))) { + $contents = json_decode(json_encode($xml), true); // force to array conversion - if(count($contents) == 1) { + if (count($contents) == 1) { $contents = reset($contents); } - if ( json_last_error() === JSON_ERROR_NONE ) { - foreach($contents as $content) { - $result[] = new SplArrayObject( $content ); + if (json_last_error() === JSON_ERROR_NONE) { + foreach ($contents as $content) { + $result[] = new SplArrayObject($content); } } } @@ -71,20 +72,20 @@ public function readFile( $filePath = null, array $options = [] ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function writeFile( $filePath = null, array $options = [] ) + public function writeFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; - if ( $this->count() ) { - $root = '<' . pathinfo( $filePath, PATHINFO_FILENAME ) . '/>'; + if ($this->count()) { + $root = '<' . pathinfo($filePath, PATHINFO_FILENAME) . '/>'; $contents = $this->getArrayCopy(); - $xml = new \SimpleXMLElement( $root ); - array_walk_recursive( $contents, [ &$xml, 'addChild' ] ); + $xml = new \SimpleXMLElement($root); + array_walk_recursive($contents, [&$xml, 'addChild']); - return ( new File() )->write( $filePath, $xml->asXML() ); + return (new File())->write($filePath, $xml->asXML()); } } } \ No newline at end of file diff --git a/src/Files/ZipFile.php b/src/Files/ZipFile.php index 33a05db..a509f1e 100644 --- a/src/Files/ZipFile.php +++ b/src/Files/ZipFile.php @@ -8,6 +8,7 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Files; @@ -31,22 +32,22 @@ class ZipFile extends AbstractFile * * @return mixed */ - public function readFile( $filePath, array $options = [] ) + public function readFile($filePath, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; $result = []; - if ( extension_loaded( 'zip' ) ) { - if ( $zipHandle = zip_open( $filePath ) ) { - while ( $zipContent = zip_read( $zipHandle ) ) { - $result[] = zip_entry_name( $zipContent ); + if (extension_loaded('zip')) { + if ($zipHandle = zip_open($filePath)) { + while ($zipContent = zip_read($zipHandle)) { + $result[] = zip_entry_name($zipContent); } - zip_close( $zipHandle ); + zip_close($zipHandle); } } @@ -63,26 +64,26 @@ public function readFile( $filePath, array $options = [] ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function writeFile( $filePath = null, array $options = [] ) + public function writeFile($filePath = null, array $options = []) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; - if ( $this->count() ) { + if ($this->count()) { $zip = new \ZipArchive(); - if ( $zip->open( $filePath, \ZipArchive::CREATE ) ) { - foreach ( $this->getArrayCopy() as $directory => $files ) { - if ( is_array( $files ) ) { - $zip->addEmptyDir( $directory ); - foreach ( $files as $file ) { - if ( is_file( $file ) ) { - $zip->addFile( $file ); + if ($zip->open($filePath, \ZipArchive::CREATE)) { + foreach ($this->getArrayCopy() as $directory => $files) { + if (is_array($files)) { + $zip->addEmptyDir($directory); + foreach ($files as $file) { + if (is_file($file)) { + $zip->addFile($file); } } - } elseif ( is_file( $files ) ) { - $zip->addFile( $files ); + } elseif (is_file($files)) { + $zip->addFile($files); } } @@ -103,16 +104,16 @@ public function writeFile( $filePath = null, array $options = [] ) * @param string $sourcePath Path of directory to be zip. * @param string|null $filePath Path to the zip file. */ - public function compress( $sourcePath, $filePath = null ) + public function compress($sourcePath, $filePath = null) { - $filePath = empty( $filePath ) + $filePath = empty($filePath) ? $this->filePath : $filePath; $zip = new \ZipArchive(); - $zip->open( $filePath, \ZipArchive::CREATE ); - $zip->addEmptyDir( pathinfo( $sourcePath, PATHINFO_BASENAME ) ); - $this->recursiveCompress( $sourcePath, strlen( dirname( $sourcePath, 2 ) . DIRECTORY_SEPARATOR ), $zip ); + $zip->open($filePath, \ZipArchive::CREATE); + $zip->addEmptyDir(pathinfo($sourcePath, PATHINFO_BASENAME)); + $this->recursiveCompress($sourcePath, strlen(dirname($sourcePath, 2) . DIRECTORY_SEPARATOR), $zip); $zip->close(); } @@ -127,25 +128,25 @@ public function compress( $sourcePath, $filePath = null ) * @param int $exclusiveLength Number of text to be exclusive from the file path. * @param \ZipArchive $zipArchive Zip Archive instance. */ - private function recursiveCompress( $directory, $exclusiveLength, &$zipArchive ) + private function recursiveCompress($directory, $exclusiveLength, &$zipArchive) { - $handle = opendir( $directory ); + $handle = opendir($directory); - while ( false !== ( $file = readdir( $handle ) ) ) { - if ( $file != '.' && $file != '..' ) { + while (false !== ($file = readdir($handle))) { + if ($file != '.' && $file != '..') { $filePath = "$directory/$file"; // Remove prefix from file path before add to zip. - $localPath = substr( $filePath, $exclusiveLength ); - if ( is_file( $filePath ) ) { - $zipArchive->addFile( $filePath, $localPath ); - } elseif ( is_dir( $filePath ) ) { + $localPath = substr($filePath, $exclusiveLength); + if (is_file($filePath)) { + $zipArchive->addFile($filePath, $localPath); + } elseif (is_dir($filePath)) { // Add sub-directory. - $zipArchive->addEmptyDir( $localPath ); - $this->recursiveCompress( $filePath, $exclusiveLength, $zipArchive ); + $zipArchive->addEmptyDir($localPath); + $this->recursiveCompress($filePath, $exclusiveLength, $zipArchive); } } } - closedir( $handle ); + closedir($handle); } // ------------------------------------------------------------------------ @@ -159,16 +160,16 @@ private function recursiveCompress( $directory, $exclusiveLength, &$zipArchive ) * * @return bool Returns TRUE on success or FALSE on failure. */ - public function extract( $destinationPath ) + public function extract($destinationPath) { - if ( extension_loaded( 'zip' ) ) { - if ( is_file( $this->filePath ) ) { + if (extension_loaded('zip')) { + if (is_file($this->filePath)) { $zip = new \ZipArchive; - $contents = $zip->open( $this->filePath ); + $contents = $zip->open($this->filePath); - if ( $contents === true ) { - if ( is_dir( $destinationPath ) ) { - $zip->extractTo( $destinationPath ); + if ($contents === true) { + if (is_dir($destinationPath)) { + $zip->extractTo($destinationPath); $zip->close(); return true; diff --git a/src/Handlers/Downloader.php b/src/Handlers/Downloader.php index 73ff682..ce9d633 100644 --- a/src/Handlers/Downloader.php +++ b/src/Handlers/Downloader.php @@ -8,6 +8,7 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Handlers; @@ -44,42 +45,42 @@ class Downloader protected $speedLimit = 512; protected $bufferSize = 2048; - public function __construct( $filePath, $mode = self::MODE_FILESTREAM ) + public function __construct($filePath, $mode = self::MODE_FILESTREAM) { global $HTTP_SERVER_VARS; $this->mode = $mode; // disables apache compression mod_deflate || mod_gzip - if( function_exists( 'apache_setenv' ) ) { - @apache_setenv( 'no-gzip', 1 ); + if (function_exists('apache_setenv')) { + @apache_setenv('no-gzip', 1); } // disable php cpmpression - @ini_set( 'zlib.output_compression', 'Off' ); + @ini_set('zlib.output_compression', 'Off'); - if ( $mode === self::MODE_FILESTREAM ) { + if ($mode === self::MODE_FILESTREAM) { // Check if File exists and is file or not - if ( ! is_file( $filePath ) ) { + if ( ! is_file($filePath)) { output() - ->withStatus( 404, 'File Not Found' ) - ->send( 'File Not Found' ); + ->withStatus(404, 'File Not Found') + ->send('File Not Found'); }// Try To Open File for read - elseif ( ! is_readable( $filePath ) || ! ( $this->filedata = fopen( $filePath, 'rb' ) ) ) { + elseif ( ! is_readable($filePath) || ! ($this->filedata = fopen($filePath, 'rb'))) { output() - ->withStatus( 403, 'Forbidden' ) - ->send( 'File Not Accessible' ); + ->withStatus(403, 'Forbidden') + ->send('File Not Accessible'); } - $this->fileinfo = pathinfo( $filePath ); - $this->filesize = filesize( $filePath ); - $this->filemime = $this->getMime( $filePath ); - $this->lastModified = filemtime( $filePath ); + $this->fileinfo = pathinfo($filePath); + $this->filesize = filesize($filePath); + $this->filemime = $this->getMime($filePath); + $this->lastModified = filemtime($filePath); - } elseif ( $mode === self::MODE_DATASTREAM ) { - if ( is_file( $filePath ) ) { - $this->filedata = file_get_contents( $filePath ); - $this->fileinfo = pathinfo( $filePath ); + } elseif ($mode === self::MODE_DATASTREAM) { + if (is_file($filePath)) { + $this->filedata = file_get_contents($filePath); + $this->fileinfo = pathinfo($filePath); } else { $this->filedata = $filePath; $this->fileinfo = [ @@ -90,30 +91,30 @@ public function __construct( $filePath, $mode = self::MODE_FILESTREAM ) ]; } - $this->filesize = strlen( $this->filedata ); - $this->filemime = $this->getMime( $this->fileinfo[ 'filename' ] ); + $this->filesize = strlen($this->filedata); + $this->filemime = $this->getMime($this->fileinfo[ 'filename' ]); $this->lastModified = time(); } else { output() - ->withStatus( 400, 'Bad Request' ) - ->send( 'Undefined Download Mode' ); + ->withStatus(400, 'Bad Request') + ->send('Undefined Download Mode'); } // Range - if ( isset( $_SERVER[ 'HTTP_RANGE' ] ) || isset( $HTTP_SERVER_VARS[ 'HTTP_RANGE' ] ) ) { + if (isset($_SERVER[ 'HTTP_RANGE' ]) || isset($HTTP_SERVER_VARS[ 'HTTP_RANGE' ])) { $this->partialRequest = true; - $http_range = isset( $_SERVER[ 'HTTP_RANGE' ] ) ? $_SERVER[ 'HTTP_RANGE' ] : $HTTP_SERVER_VARS[ 'HTTP_RANGE' ]; - if ( stripos( $http_range, 'bytes' ) === false ) { + $http_range = isset($_SERVER[ 'HTTP_RANGE' ]) ? $_SERVER[ 'HTTP_RANGE' ] : $HTTP_SERVER_VARS[ 'HTTP_RANGE' ]; + if (stripos($http_range, 'bytes') === false) { output() - ->withStatus( 416, 'Requested Range Not Satisfiable' ) - ->send( 'Requested Range Not Satisfiable' ); + ->withStatus(416, 'Requested Range Not Satisfiable') + ->send('Requested Range Not Satisfiable'); } - $range = substr( $http_range, strlen( 'bytes=' ) ); - $range = explode( '-', $range, 3 ); - $this->seekStart = ( $range[ 0 ] > 0 && $range[ 0 ] < $this->filesize - 1 ) ? $range[ 0 ] : 0; - $this->seekEnd = ( $range[ 1 ] > 0 && $range[ 1 ] < $this->filesize && $range[ 1 ] > $this->seekStart ) ? $range[ 1 ] : $this->filesize - 1; + $range = substr($http_range, strlen('bytes=')); + $range = explode('-', $range, 3); + $this->seekStart = ($range[ 0 ] > 0 && $range[ 0 ] < $this->filesize - 1) ? $range[ 0 ] : 0; + $this->seekEnd = ($range[ 1 ] > 0 && $range[ 1 ] < $this->filesize && $range[ 1 ] > $this->seekStart) ? $range[ 1 ] : $this->filesize - 1; $this->seekFilesize = $this->seekEnd - $this->seekStart + 1; } else { $this->partialRequest = false; @@ -123,20 +124,39 @@ public function __construct( $filePath, $mode = self::MODE_FILESTREAM ) } } - public function download( $filename = null ) + private function getMime($filePath) + { + $file = new File($filePath); + $mime = $file->getMime(); + + if (is_array($mime)) { + $mime = reset($mime); + } + + return $mime; + } + + public function forceDownload($filename = null, $filemime = 'application/octet-stream') + { + // Force mime + $this->filemime = $filemime; + $this->download($filename); + } + + public function download($filename = null) { - $filename = isset( $filename ) ? $filename : $this->fileinfo[ 'basename' ]; + $filename = isset($filename) ? $filename : $this->fileinfo[ 'basename' ]; - if ( $this->partialRequest ) { - if ( $this->resumeable ) { + if ($this->partialRequest) { + if ($this->resumeable) { // Turn on resume capability output() - ->sendHeaderStatus( 206, 'Partial Content', '1.0' ) - ->sendHeader( 'Status', '206 Partial Content' ) - ->sendHeader( 'Accept-Ranges', 'bytes' ); + ->sendHeaderStatus(206, 'Partial Content', '1.0') + ->sendHeader('Status', '206 Partial Content') + ->sendHeader('Accept-Ranges', 'bytes'); - output()->sendHeader( 'Content-range', - 'bytes ' . $this->seekStart . '-' . $this->seekEnd . '/' . $this->filesize ); + output()->sendHeader('Content-range', + 'bytes ' . $this->seekStart . '-' . $this->seekEnd . '/' . $this->filesize); } else { // Turn off resume capability $this->seekStart = 0; @@ -147,22 +167,22 @@ public function download( $filename = null ) // Common Download Headers content type, content disposition, content length and last modified output() - ->sendHeader( 'Content-Type', $this->filemime ) - ->sendHeader( 'Content-Disposition', 'attachment; filename=' . $filename ) - ->sendHeader( 'Content-Length', $this->seekFilesize ) - ->sendHeader( 'Last-Modified', date( 'D, d M Y H:i:s \G\M\T', $this->lastModified ) ); + ->sendHeader('Content-Type', $this->filemime) + ->sendHeader('Content-Disposition', 'attachment; filename=' . $filename) + ->sendHeader('Content-Length', $this->seekFilesize) + ->sendHeader('Last-Modified', date('D, d M Y H:i:s \G\M\T', $this->lastModified)); // End Headers Stage // Work On Download Speed Limit - if ( $this->speedLimit ) { + if ($this->speedLimit) { // how many buffers ticks per second $bufferTicks = 10; //10 // how long one buffering tick takes by micro second $bufferMicroTime = 150; // 100 // Calculate sleep micro time after each tick - $sleepMicroTime = round( ( 1000000 - ( $bufferTicks * $bufferMicroTime ) ) / $bufferTicks ); + $sleepMicroTime = round((1000000 - ($bufferTicks * $bufferMicroTime)) / $bufferTicks); // Calculate required buffer per one tick, make sure it is integer so round the result - $this->bufferSize = round( $this->speedLimit * 1024 / $bufferTicks ); + $this->bufferSize = round($this->speedLimit * 1024 / $bufferTicks); } // Immediatly Before Downloading // clean any output buffer @@ -170,29 +190,29 @@ public function download( $filename = null ) // get oignore_user_abort value, then change it to yes $oldUserAbortSetting = ignore_user_abort(); - ignore_user_abort( true ); + ignore_user_abort(true); // set script execution time to be unlimited - @set_time_limit( 0 ); + @set_time_limit(0); // Download According Download Mode - if ( $this->mode === self::MODE_FILESTREAM ) { + if ($this->mode === self::MODE_FILESTREAM) { // Download Data by fopen $downloadFileBytes = $this->seekFilesize; $downloaded = 0; // goto the position of the first byte to download - fseek( $this->filedata, $this->seekStart ); - while ( $downloadFileBytes > 0 && ! ( connection_aborted() || connection_status() == 1 ) ) { + fseek($this->filedata, $this->seekStart); + while ($downloadFileBytes > 0 && ! (connection_aborted() || connection_status() == 1)) { // still Downloading - if ( $downloadFileBytes > $this->bufferSize ) { + if ($downloadFileBytes > $this->bufferSize) { // send buffer size - echo fread( $this->filedata, $this->bufferSize ); // this also will seek to after last read byte + echo fread($this->filedata, $this->bufferSize); // this also will seek to after last read byte $downloaded += $this->bufferSize; // updated downloaded $downloadFileBytes -= $this->bufferSize; // update remaining bytes } else { // send required size // this will happens when we reaches the end of the file normally we wll download remaining bytes - echo fread( $this->filedata, $downloadFileBytes ); // this also will seek to last reat + echo fread($this->filedata, $downloadFileBytes); // this also will seek to last reat $downloaded += $downloadFileBytes; // Add to downloaded @@ -202,31 +222,31 @@ public function download( $filename = null ) // send to buffer flush(); // Check For Download Limit - if ( $this->speedLimit ) { - usleep( $sleepMicroTime ); + if ($this->speedLimit) { + usleep($sleepMicroTime); } } // all bytes have been sent to user // Close File - fclose( $this->filedata ); - } elseif( $this->mode === self::MODE_DATASTREAM ) { + fclose($this->filedata); + } elseif ($this->mode === self::MODE_DATASTREAM) { // Download Data String $downloadFileBytes = $this->seekFilesize; $downloaded = 0; $offset = $this->seekStart; - while ( $downloadFileBytes > 0 && ( ! connection_aborted() ) ) { - if ( $downloadFileBytes > $this->bufferSize ) { + while ($downloadFileBytes > 0 && ( ! connection_aborted())) { + if ($downloadFileBytes > $this->bufferSize) { // Download by buffer - echo mb_strcut( $this->filedata, $offset, $this->bufferSize ); + echo mb_strcut($this->filedata, $offset, $this->bufferSize); $downloadFileBytes -= $this->bufferSize; $downloaded += $this->bufferSize; $offset += $this->bufferSize; } else { // download last bytes - echo mb_strcut( $this->filedata, $offset, $downloadFileBytes ); + echo mb_strcut($this->filedata, $offset, $downloadFileBytes); $downloaded += $downloadFileBytes; $offset += $downloadFileBytes; $downloadFileBytes = 0; @@ -234,8 +254,8 @@ public function download( $filename = null ) // Send Data to Buffer flush(); // Check Limit - if ( $this->speedLimit ) { - usleep( $sleepMicroTime ); + if ($this->speedLimit) { + usleep($sleepMicroTime); } } @@ -243,43 +263,24 @@ public function download( $filename = null ) // Set Downloaded Bytes $this->downloadedFilesize = $downloaded; - ignore_user_abort( $oldUserAbortSetting ); // Restore old user abort settings - set_time_limit( ini_get( 'max_execution_time' ) ); // Restore Default script max execution Time + ignore_user_abort($oldUserAbortSetting); // Restore old user abort settings + set_time_limit(ini_get('max_execution_time')); // Restore Default script max execution Time exit; } - public function forceDownload( $filename = null, $filemime = 'application/octet-stream' ) - { - // Force mime - $this->filemime = $filemime; - $this->download( $filename ); - } - - public function resumeable( $status = true ) + public function resumeable($status = true) { $this->partialRequest = $this->resumeable = ( bool )$status; return $this; } - public function speedLimit( $limit ) + public function speedLimit($limit) { - $limit = intval( $limit ); + $limit = intval($limit); $this->speedLimit = $limit; return $this; } - - private function getMime( $filePath ) - { - $file = new File( $filePath ); - $mime = $file->getMime(); - - if ( is_array( $mime ) ) { - $mime = reset( $mime ); - } - - return $mime; - } } \ No newline at end of file diff --git a/src/Handlers/Ftp.php b/src/Handlers/Ftp.php index 1a75b24..04bb436 100644 --- a/src/Handlers/Ftp.php +++ b/src/Handlers/Ftp.php @@ -8,6 +8,7 @@ * @author Steeve Andrian Salim * @copyright Copyright (c) Steeve Andrian Salim */ + // ------------------------------------------------------------------------ namespace O2System\Filesystem\Handlers; @@ -62,8 +63,8 @@ class Ftp public function __construct() { language() - ->addFilePath( str_replace( 'Handlers', '', __DIR__ ) . DIRECTORY_SEPARATOR ) - ->loadFile( 'ftp' ); + ->addFilePath(str_replace('Handlers', '', __DIR__) . DIRECTORY_SEPARATOR) + ->loadFile('ftp'); } // -------------------------------------------------------------------- @@ -78,33 +79,33 @@ public function __construct() * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function connect( array $config = [] ) + public function connect(array $config = []) { // Prep the port - $config[ 'port' ] = empty( $config[ 'port' ] ) ? 21 : (int)$config[ 'port' ]; + $config[ 'port' ] = empty($config[ 'port' ]) ? 21 : (int)$config[ 'port' ]; // Prep the hostname - $config[ 'hostname' ] = preg_replace( '|.+?://|', '', $config[ 'hostname' ] ); + $config[ 'hostname' ] = preg_replace('|.+?://|', '', $config[ 'hostname' ]); - if ( false === ( $this->handle = @ftp_connect( $config[ 'hostname' ], $config[ 'port' ] ) ) ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_CONNECT' ); + if (false === ($this->handle = @ftp_connect($config[ 'hostname' ], $config[ 'port' ]))) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_CONNECT'); } return false; } - if ( false !== ( @ftp_login( $this->handle, $config[ 'username' ], $config[ 'password' ] ) ) ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_LOGIN' ); + if (false !== (@ftp_login($this->handle, $config[ 'username' ], $config[ 'password' ]))) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_LOGIN'); } return false; } // Set passive mode if needed - if ( $this->passiveMode === true ) { - ftp_pasv( $this->handle, true ); + if ($this->passiveMode === true) { + ftp_pasv($this->handle, true); } $this->config = $config; @@ -126,26 +127,26 @@ public function connect( array $config = [] ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function download( $remoteFilePath, $localFilePath, $mode = 'auto' ) + public function download($remoteFilePath, $localFilePath, $mode = 'auto') { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } // Set the mode if not specified - if ( $mode === 'auto' ) { + if ($mode === 'auto') { // Get the file extension so we can set the upload type - $ext = $this->getExtension( $remoteFilePath ); - $mode = $this->getTransferMode( $ext ); + $ext = $this->getExtension($remoteFilePath); + $mode = $this->getTransferMode($ext); } - $mode = ( $mode === 'ascii' ) ? FTP_ASCII : FTP_BINARY; + $mode = ($mode === 'ascii') ? FTP_ASCII : FTP_BINARY; - $result = @ftp_get( $this->handle, $localFilePath, $remoteFilePath, $mode ); + $result = @ftp_get($this->handle, $localFilePath, $remoteFilePath, $mode); - if ( $result === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_DOWNLOAD' ); + if ($result === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_DOWNLOAD'); } return false; @@ -166,9 +167,9 @@ public function download( $remoteFilePath, $localFilePath, $mode = 'auto' ) */ protected function isConnected() { - if ( ! is_resource( $this->handle ) ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_NO_CONNECTION' ); + if ( ! is_resource($this->handle)) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_NO_CONNECTION'); } return false; @@ -188,11 +189,11 @@ protected function isConnected() * * @return string By default it's set into txt file extension. */ - protected function getExtension( $filename ) + protected function getExtension($filename) { - return ( ( $dot = strrpos( $filename, '.' ) ) === false ) + return (($dot = strrpos($filename, '.')) === false) ? 'txt' - : substr( $filename, $dot + 1 ); + : substr($filename, $dot + 1); } // -------------------------------------------------------------------- @@ -206,11 +207,11 @@ protected function getExtension( $filename ) * * @return string By default it's set into ascii mode. */ - protected function getTransferMode( $ext ) + protected function getTransferMode($ext) { return in_array( $ext, - [ 'txt', 'text', 'php', 'phps', 'php4', 'js', 'css', 'htm', 'html', 'phtml', 'shtml', 'log', 'xml' ], + ['txt', 'text', 'php', 'phps', 'php4', 'js', 'css', 'htm', 'html', 'phtml', 'shtml', 'log', 'xml'], true ) ? 'ascii' @@ -230,17 +231,17 @@ protected function getTransferMode( $ext ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function rename( $oldFilename, $newFilename ) + public function rename($oldFilename, $newFilename) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } - $result = @ftp_rename( $this->handle, $oldFilename, $newFilename ); + $result = @ftp_rename($this->handle, $oldFilename, $newFilename); - if ( $result === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_UNABLE_TO_RENAME' ); + if ($result === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_UNABLE_TO_RENAME'); } return false; @@ -262,17 +263,17 @@ public function rename( $oldFilename, $newFilename ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function move( $oldRemoteFilePath, $newRemoteFilePath ) + public function move($oldRemoteFilePath, $newRemoteFilePath) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } - $result = @ftp_rename( $this->handle, $oldRemoteFilePath, $newRemoteFilePath ); + $result = @ftp_rename($this->handle, $oldRemoteFilePath, $newRemoteFilePath); - if ( $result === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_UNABLE_TO_MOVE' ); + if ($result === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_UNABLE_TO_MOVE'); } return false; @@ -293,17 +294,17 @@ public function move( $oldRemoteFilePath, $newRemoteFilePath ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function deleteFile( $filePath ) + public function deleteFile($filePath) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } - $result = @ftp_delete( $this->handle, $filePath ); + $result = @ftp_delete($this->handle, $filePath); - if ( $result === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_DELETE' ); + if ($result === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_DELETE'); } return false; @@ -325,29 +326,29 @@ public function deleteFile( $filePath ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function deleteDir( $remotePath ) + public function deleteDir($remotePath) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } // Add a trailing slash to the file path if needed - $remotePath = preg_replace( '/(.+?)\/*$/', '\\1/', $remotePath ); + $remotePath = preg_replace('/(.+?)\/*$/', '\\1/', $remotePath); - $list = $this->getFiles( $remotePath ); - if ( ! empty( $list ) ) { - for ( $i = 0, $c = count( $list ); $i < $c; $i++ ) { + $list = $this->getFiles($remotePath); + if ( ! empty($list)) { + for ($i = 0, $c = count($list); $i < $c; $i++) { // If we can't delete the item it's probaly a directory, // so we'll recursively call delete_dir() - if ( ! preg_match( '#/\.\.?$#', $list[ $i ] ) && ! @ftp_delete( $this->handle, $list[ $i ] ) ) { - $this->deleteDir( $list[ $i ] ); + if ( ! preg_match('#/\.\.?$#', $list[ $i ]) && ! @ftp_delete($this->handle, $list[ $i ])) { + $this->deleteDir($list[ $i ]); } } } - if ( @ftp_rmdir( $this->handle, $remotePath ) === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_DELETE_DIRECTORY' ); + if (@ftp_rmdir($this->handle, $remotePath) === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_DELETE_DIRECTORY'); } return false; @@ -368,10 +369,10 @@ public function deleteDir( $remotePath ) * @return array|bool Returns array of files list or FALSE on failure. * @throws RuntimeException */ - public function getFiles( $remotePath = '.' ) + public function getFiles($remotePath = '.') { return $this->isConnected() - ? ftp_nlist( $this->handle, $remotePath ) + ? ftp_nlist($this->handle, $remotePath) : false; } @@ -393,32 +394,32 @@ public function getFiles( $remotePath = '.' ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function mirror( $localPath, $remotePath ) + public function mirror($localPath, $remotePath) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } // Open the local file path - if ( $fp = @opendir( $localPath ) ) { + if ($fp = @opendir($localPath)) { // Attempt to open the remote file path and try to create it, if it doesn't exist - if ( ! $this->changeDir( $remotePath, true ) && ( ! $this->makeDir( $remotePath ) OR ! $this->changeDir( + if ( ! $this->changeDir($remotePath, true) && ( ! $this->makeDir($remotePath) OR ! $this->changeDir( $remotePath - ) ) + )) ) { return false; } // Recursively read the local directory - while ( false !== ( $file = readdir( $fp ) ) ) { - if ( is_dir( $localPath . $file ) && $file[ 0 ] !== '.' ) { - $this->mirror( $localPath . $file . '/', $remotePath . $file . '/' ); - } elseif ( $file[ 0 ] !== '.' ) { + while (false !== ($file = readdir($fp))) { + if (is_dir($localPath . $file) && $file[ 0 ] !== '.') { + $this->mirror($localPath . $file . '/', $remotePath . $file . '/'); + } elseif ($file[ 0 ] !== '.') { // Get the file extension so we can se the upload type - $ext = $this->getExtension( $file ); - $mode = $this->getTransferMode( $ext ); + $ext = $this->getExtension($file); + $mode = $this->getTransferMode($ext); - $this->upload( $localPath . $file, $remotePath . $file, $mode ); + $this->upload($localPath . $file, $remotePath . $file, $mode); } } @@ -445,17 +446,17 @@ public function mirror( $localPath, $remotePath ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function changeDir( $remotePath, $suppressDebug = false ) + public function changeDir($remotePath, $suppressDebug = false) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } - $result = @ftp_chdir( $this->handle, $remotePath ); + $result = @ftp_chdir($this->handle, $remotePath); - if ( $result === false ) { - if ( $this->debugMode === true AND $suppressDebug === false ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_CHANGE_DIRECTORY' ); + if ($result === false) { + if ($this->debugMode === true AND $suppressDebug === false) { + throw new RuntimeException('FTP_E_UNABLE_TO_CHANGE_DIRECTORY'); } return false; @@ -477,25 +478,25 @@ public function changeDir( $remotePath, $suppressDebug = false ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function makeDir( $remotePath, $permissions = null ) + public function makeDir($remotePath, $permissions = null) { - if ( $remotePath === '' OR ! $this->isConnected() ) { + if ($remotePath === '' OR ! $this->isConnected()) { return false; } - $result = @ftp_mkdir( $this->handle, $remotePath ); + $result = @ftp_mkdir($this->handle, $remotePath); - if ( $result === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_MAKE_DIRECTORY' ); + if ($result === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_MAKE_DIRECTORY'); } return false; } // Set file permissions if needed - if ( $permissions !== null ) { - $this->setChmod( $remotePath, (int)$permissions ); + if ($permissions !== null) { + $this->setChmod($remotePath, (int)$permissions); } return true; @@ -514,15 +515,15 @@ public function makeDir( $remotePath, $permissions = null ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function setChmod( $remotePath, $mode ) + public function setChmod($remotePath, $mode) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } - if ( @ftp_chmod( $this->handle, $mode, $remotePath ) === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_CHMOD' ); + if (@ftp_chmod($this->handle, $mode, $remotePath) === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_CHMOD'); } return false; @@ -546,35 +547,35 @@ public function setChmod( $remotePath, $mode ) * @return bool Returns TRUE on success or FALSE on failure. * @throws RuntimeException */ - public function upload( $localFilePath, $remoteFilePath, $mode = 'auto', $permissions = null ) + public function upload($localFilePath, $remoteFilePath, $mode = 'auto', $permissions = null) { - if ( ! $this->isConnected() ) { + if ( ! $this->isConnected()) { return false; } - if ( is_file( $localFilePath ) ) { + if (is_file($localFilePath)) { // Set the mode if not specified - if ( $mode === 'auto' ) { + if ($mode === 'auto') { // Get the file extension so we can set the upload type - $ext = $this->getExtension( $localFilePath ); - $mode = $this->getTransferMode( $ext ); + $ext = $this->getExtension($localFilePath); + $mode = $this->getTransferMode($ext); } - $mode = ( $mode === 'ascii' ) ? FTP_ASCII : FTP_BINARY; + $mode = ($mode === 'ascii') ? FTP_ASCII : FTP_BINARY; - $result = @ftp_put( $this->handle, $remoteFilePath, $localFilePath, $mode ); + $result = @ftp_put($this->handle, $remoteFilePath, $localFilePath, $mode); - if ( $result === false ) { - if ( $this->debugMode === true ) { - throw new RuntimeException( 'FTP_E_UNABLE_TO_UPLOAD' ); + if ($result === false) { + if ($this->debugMode === true) { + throw new RuntimeException('FTP_E_UNABLE_TO_UPLOAD'); } return false; } // Set file permissions if needed - if ( $permissions !== null ) { - $this->setChmod( $remoteFilePath, (int)$permissions ); + if ($permissions !== null) { + $this->setChmod($remoteFilePath, (int)$permissions); } return true; @@ -596,7 +597,7 @@ public function upload( $localFilePath, $remoteFilePath, $mode = 'auto', $permis public function close() { return $this->isConnected() - ? @ftp_close( $this->handle ) + ? @ftp_close($this->handle) : false; } } \ No newline at end of file diff --git a/src/Handlers/Uploader.php b/src/Handlers/Uploader.php index 892d2d4..b5eaba8 100644 --- a/src/Handlers/Uploader.php +++ b/src/Handlers/Uploader.php @@ -279,34 +279,6 @@ public function setMaxFileSize($fileSize, $unit = 'M') // -------------------------------------------------------------------------------------- - /** - * Uploader::setTargetFilename - * - * Sets target filename. - * - * @param string $filename The target filename. - * @param string $conversionFunction Conversion function name, by default it's using dash inflector function. - * - * @return static - */ - public function setTargetFilename($filename, $conversionFunction = 'dash') - { - $this->targetFilename = call_user_func_array( - $conversionFunction, - [ - strtolower( - trim( - pathinfo($filename, PATHINFO_FILENAME) - ) - ), - ] - ); - - return $this; - } - - // -------------------------------------------------------------------------------------- - /** * Uploader::setMaxIncrementFilename * @@ -323,55 +295,6 @@ public function setMaxIncrementFilename($increment = 0) // -------------------------------------------------------------------------------------- - protected function validate(UploadFile $file) - { - /* Validate extension */ - if (is_array($this->allowedExtensions) && count($this->allowedExtensions)) { - if ( ! in_array('.' . $file->getExtension(), $this->allowedExtensions)) { - $this->errors[] = language()->getLine( - 'UPLOADER_E_ALLOWED_EXTENSIONS', - [implode(',', $this->allowedExtensions), $file->getExtension()] - ); - } - } - - /* Validate mime */ - if (is_array($this->allowedMimes) && count($this->allowedExtensions)) { - if ( ! in_array($file->getFileMime(), $this->allowedMimes)) { - $this->errors[] = language()->getLine( - 'UPLOADER_E_ALLOWED_MIMES', - [implode(',', $this->allowedMimes), $file->getFileMime()] - ); - } - } - - /* Validate min size */ - if ($this->allowedFileSize[ 'min' ] > 0) { - if ($file->getSize() < $this->allowedFileSize[ 'min' ]) { - $this->errors[] = language()->getLine( - 'UPLOADER_E_ALLOWED_MIN_FILESIZE', - [$this->allowedFileSize[ 'min' ], $file->getSize()] - ); - } - } - - /* Validate max size */ - if ($this->allowedFileSize[ 'min' ] > 0) { - if ($file->getSize() > $this->allowedFileSize[ 'max' ]) { - $this->errors[] = language()->getLine( - 'UPLOADER_E_ALLOWED_MAX_FILESIZE', - [$this->allowedFileSize[ 'max' ], $file->getSize()] - ); - } - } - - if (count($this->errors) == 0) { - return true; - } - - return false; - } - /** * Uploader::process * @@ -445,6 +368,83 @@ public function process($field = null) return false; } + // -------------------------------------------------------------------------------------- + + /** + * Uploader::setTargetFilename + * + * Sets target filename. + * + * @param string $filename The target filename. + * @param string $conversionFunction Conversion function name, by default it's using dash inflector function. + * + * @return static + */ + public function setTargetFilename($filename, $conversionFunction = 'dash') + { + $this->targetFilename = call_user_func_array( + $conversionFunction, + [ + strtolower( + trim( + pathinfo($filename, PATHINFO_FILENAME) + ) + ), + ] + ); + + return $this; + } + + protected function validate(UploadFile $file) + { + /* Validate extension */ + if (is_array($this->allowedExtensions) && count($this->allowedExtensions)) { + if ( ! in_array('.' . $file->getExtension(), $this->allowedExtensions)) { + $this->errors[] = language()->getLine( + 'UPLOADER_E_ALLOWED_EXTENSIONS', + [implode(',', $this->allowedExtensions), $file->getExtension()] + ); + } + } + + /* Validate mime */ + if (is_array($this->allowedMimes) && count($this->allowedExtensions)) { + if ( ! in_array($file->getFileMime(), $this->allowedMimes)) { + $this->errors[] = language()->getLine( + 'UPLOADER_E_ALLOWED_MIMES', + [implode(',', $this->allowedMimes), $file->getFileMime()] + ); + } + } + + /* Validate min size */ + if ($this->allowedFileSize[ 'min' ] > 0) { + if ($file->getSize() < $this->allowedFileSize[ 'min' ]) { + $this->errors[] = language()->getLine( + 'UPLOADER_E_ALLOWED_MIN_FILESIZE', + [$this->allowedFileSize[ 'min' ], $file->getSize()] + ); + } + } + + /* Validate max size */ + if ($this->allowedFileSize[ 'min' ] > 0) { + if ($file->getSize() > $this->allowedFileSize[ 'max' ]) { + $this->errors[] = language()->getLine( + 'UPLOADER_E_ALLOWED_MAX_FILESIZE', + [$this->allowedFileSize[ 'max' ], $file->getSize()] + ); + } + } + + if (count($this->errors) == 0) { + return true; + } + + return false; + } + protected function move(UploadFile $file, $targetPath) { $file->moveTo($targetPath); diff --git a/src/System.php b/src/System.php index 491bec6..11b0a8e 100644 --- a/src/System.php +++ b/src/System.php @@ -232,46 +232,6 @@ public function getConfigurations($extension = null, $details = true) // ------------------------------------------------------------------------ - /** - * System::getCpuCores - * - * Gets the numbers of system cores. - * - * @return int - */ - public function getCpuCores() - { - $numCpus = 1; - if (is_file('/proc/cpuinfo')) { - $cpuinfo = file_get_contents('/proc/cpuinfo'); - preg_match_all('/^processor/m', $cpuinfo, $matches); - $numCpus = count($matches[ 0 ]); - } else { - if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))) { - $process = @popen('wmic cpu get NumberOfCores', 'rb'); - if (false !== $process) { - fgets($process); - $numCpus = intval(fgets($process)); - pclose($process); - } - } else { - $process = @popen('sysctl -a', 'rb'); - if (false !== $process) { - $output = stream_get_contents($process); - preg_match('/hw.ncpu: (\d+)/', $output, $matches); - if ($matches) { - $numCpus = intval($matches[ 1 ][ 0 ]); - } - pclose($process); - } - } - } - - return $numCpus; - } - - // ------------------------------------------------------------------------ - /** * System::getMacAddress * @@ -324,4 +284,44 @@ public function getLoadAvg($interval = 1) } // ------------------------------------------------------------------------ + + /** + * System::getCpuCores + * + * Gets the numbers of system cores. + * + * @return int + */ + public function getCpuCores() + { + $numCpus = 1; + if (is_file('/proc/cpuinfo')) { + $cpuinfo = file_get_contents('/proc/cpuinfo'); + preg_match_all('/^processor/m', $cpuinfo, $matches); + $numCpus = count($matches[ 0 ]); + } else { + if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))) { + $process = @popen('wmic cpu get NumberOfCores', 'rb'); + if (false !== $process) { + fgets($process); + $numCpus = intval(fgets($process)); + pclose($process); + } + } else { + $process = @popen('sysctl -a', 'rb'); + if (false !== $process) { + $output = stream_get_contents($process); + preg_match('/hw.ncpu: (\d+)/', $output, $matches); + if ($matches) { + $numCpus = intval($matches[ 1 ][ 0 ]); + } + pclose($process); + } + } + } + + return $numCpus; + } + + // ------------------------------------------------------------------------ } \ No newline at end of file diff --git a/src/autoload.php b/src/autoload.php index efe914a..c8c9095 100644 --- a/src/autoload.php +++ b/src/autoload.php @@ -16,29 +16,29 @@ * @param $className */ spl_autoload_register( - function ( $className ) { - if ( $className === 'O2System\Filesystem' ) { + function ($className) { + if ($className === 'O2System\Filesystem') { require __DIR__ . DIRECTORY_SEPARATOR . 'File.php'; - } elseif ( strpos( $className, 'O2System\Filesystem\\' ) === false ) { + } elseif (strpos($className, 'O2System\Filesystem\\') === false) { return; } - $className = ltrim( $className, '\\' ); + $className = ltrim($className, '\\'); $filePath = ''; - if ( $lastNsPos = strripos( $className, '\\' ) ) { - $namespace = substr( $className, 0, $lastNsPos ); - $className = substr( $className, $lastNsPos + 1 ); + if ($lastNsPos = strripos($className, '\\')) { + $namespace = substr($className, 0, $lastNsPos); + $className = substr($className, $lastNsPos + 1); $filePath = $namespace . '\\'; } - $filePath .= str_replace( '_', DIRECTORY_SEPARATOR, $className ) . '.php'; + $filePath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; // Fixed Path - $filePath = str_replace( 'O2System\Filesystem\\', __DIR__ . DIRECTORY_SEPARATOR, $filePath ); - $filePath = str_replace( [ '\\', '/' ], DIRECTORY_SEPARATOR, $filePath ); + $filePath = str_replace('O2System\Filesystem\\', __DIR__ . DIRECTORY_SEPARATOR, $filePath); + $filePath = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $filePath); - if ( file_exists( $filePath ) ) { + if (file_exists($filePath)) { require $filePath; }