first commit

This commit is contained in:
aschwarz
2022-11-28 10:27:30 +01:00
commit 9015dd2102
2720 changed files with 605111 additions and 0 deletions

View File

@ -0,0 +1 @@
{"name":"dummy app","description":"This app is only a dummy for downloading with the option require.","homepage":"https://php-download.com/","type":"project","require":{"phpoffice/phpspreadsheet":"^1.8.1.0"}}

647
phpspreadsheet_1.8.1.0/composer.lock generated Executable file
View File

@ -0,0 +1,647 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "162c774ce42fa5587fb8266fc56e1f1b",
"packages": [
{
"name": "maennchen/zipstream-php",
"version": "2.1.0",
"source": {
"type": "git",
"url": "https://github.com/maennchen/ZipStream-PHP.git",
"reference": "c4c5803cc1f93df3d2448478ef79394a5981cc58"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/maennchen/ZipStream-PHP/zipball/c4c5803cc1f93df3d2448478ef79394a5981cc58",
"reference": "c4c5803cc1f93df3d2448478ef79394a5981cc58",
"shasum": ""
},
"require": {
"myclabs/php-enum": "^1.5",
"php": ">= 7.1",
"psr/http-message": "^1.0",
"symfony/polyfill-mbstring": "^1.0"
},
"require-dev": {
"ext-zip": "*",
"guzzlehttp/guzzle": ">= 6.3",
"mikey179/vfsstream": "^1.6",
"phpunit/phpunit": ">= 7.5"
},
"type": "library",
"autoload": {
"psr-4": {
"ZipStream\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paul Duncan",
"email": "pabs@pablotron.org"
},
{
"name": "Jonatan Männchen",
"email": "jonatan@maennchen.ch"
},
{
"name": "Jesse Donat",
"email": "donatj@gmail.com"
},
{
"name": "András Kolesár",
"email": "kolesar@kolesar.hu"
}
],
"description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.",
"keywords": [
"stream",
"zip"
],
"time": "2020-05-30T13:11:16+00:00"
},
{
"name": "markbaker/complex",
"version": "1.4.8",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPComplex.git",
"reference": "8eaa40cceec7bf0518187530b2e63871be661b72"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/8eaa40cceec7bf0518187530b2e63871be661b72",
"reference": "8eaa40cceec7bf0518187530b2e63871be661b72",
"shasum": ""
},
"require": {
"php": "^5.6.0|^7.0.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "^0.5.0",
"phpcompatibility/php-compatibility": "^9.0",
"phpdocumentor/phpdocumentor": "2.*",
"phploc/phploc": "2.*",
"phpmd/phpmd": "2.*",
"phpunit/phpunit": "^4.8.35|^5.4.0",
"sebastian/phpcpd": "2.*",
"squizlabs/php_codesniffer": "^3.4.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Complex\\": "classes/src/"
},
"files": [
"classes/src/functions/abs.php",
"classes/src/functions/acos.php",
"classes/src/functions/acosh.php",
"classes/src/functions/acot.php",
"classes/src/functions/acoth.php",
"classes/src/functions/acsc.php",
"classes/src/functions/acsch.php",
"classes/src/functions/argument.php",
"classes/src/functions/asec.php",
"classes/src/functions/asech.php",
"classes/src/functions/asin.php",
"classes/src/functions/asinh.php",
"classes/src/functions/atan.php",
"classes/src/functions/atanh.php",
"classes/src/functions/conjugate.php",
"classes/src/functions/cos.php",
"classes/src/functions/cosh.php",
"classes/src/functions/cot.php",
"classes/src/functions/coth.php",
"classes/src/functions/csc.php",
"classes/src/functions/csch.php",
"classes/src/functions/exp.php",
"classes/src/functions/inverse.php",
"classes/src/functions/ln.php",
"classes/src/functions/log2.php",
"classes/src/functions/log10.php",
"classes/src/functions/negative.php",
"classes/src/functions/pow.php",
"classes/src/functions/rho.php",
"classes/src/functions/sec.php",
"classes/src/functions/sech.php",
"classes/src/functions/sin.php",
"classes/src/functions/sinh.php",
"classes/src/functions/sqrt.php",
"classes/src/functions/tan.php",
"classes/src/functions/tanh.php",
"classes/src/functions/theta.php",
"classes/src/operations/add.php",
"classes/src/operations/subtract.php",
"classes/src/operations/multiply.php",
"classes/src/operations/divideby.php",
"classes/src/operations/divideinto.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mark Baker",
"email": "mark@lange.demon.co.uk"
}
],
"description": "PHP Class for working with complex numbers",
"homepage": "https://github.com/MarkBaker/PHPComplex",
"keywords": [
"complex",
"mathematics"
],
"time": "2020-03-11T20:15:49+00:00"
},
{
"name": "markbaker/matrix",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPMatrix.git",
"reference": "5348c5a67e3b75cd209d70103f916a93b1f1ed21"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/5348c5a67e3b75cd209d70103f916a93b1f1ed21",
"reference": "5348c5a67e3b75cd209d70103f916a93b1f1ed21",
"shasum": ""
},
"require": {
"php": "^5.6.0|^7.0.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "dev-master",
"phpcompatibility/php-compatibility": "dev-master",
"phploc/phploc": "^4",
"phpmd/phpmd": "dev-master",
"phpunit/phpunit": "^5.7",
"sebastian/phpcpd": "^3.0",
"squizlabs/php_codesniffer": "^3.0@dev"
},
"type": "library",
"autoload": {
"psr-4": {
"Matrix\\": "classes/src/"
},
"files": [
"classes/src/functions/adjoint.php",
"classes/src/functions/antidiagonal.php",
"classes/src/functions/cofactors.php",
"classes/src/functions/determinant.php",
"classes/src/functions/diagonal.php",
"classes/src/functions/identity.php",
"classes/src/functions/inverse.php",
"classes/src/functions/minors.php",
"classes/src/functions/trace.php",
"classes/src/functions/transpose.php",
"classes/src/operations/add.php",
"classes/src/operations/directsum.php",
"classes/src/operations/subtract.php",
"classes/src/operations/multiply.php",
"classes/src/operations/divideby.php",
"classes/src/operations/divideinto.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mark Baker",
"email": "mark@lange.demon.co.uk"
}
],
"description": "PHP Class for working with matrices",
"homepage": "https://github.com/MarkBaker/PHPMatrix",
"keywords": [
"mathematics",
"matrix",
"vector"
],
"time": "2019-10-06T11:29:25+00:00"
},
{
"name": "myclabs/php-enum",
"version": "1.7.6",
"source": {
"type": "git",
"url": "https://github.com/myclabs/php-enum.git",
"reference": "5f36467c7a87e20fbdc51e524fd8f9d1de80187c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/myclabs/php-enum/zipball/5f36467c7a87e20fbdc51e524fd8f9d1de80187c",
"reference": "5f36467c7a87e20fbdc51e524fd8f9d1de80187c",
"shasum": ""
},
"require": {
"ext-json": "*",
"php": ">=7.1"
},
"require-dev": {
"phpunit/phpunit": "^7",
"squizlabs/php_codesniffer": "1.*",
"vimeo/psalm": "^3.8"
},
"type": "library",
"autoload": {
"psr-4": {
"MyCLabs\\Enum\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP Enum contributors",
"homepage": "https://github.com/myclabs/php-enum/graphs/contributors"
}
],
"description": "PHP Enum implementation",
"homepage": "http://github.com/myclabs/php-enum",
"keywords": [
"enum"
],
"time": "2020-02-14T08:15:52+00:00"
},
{
"name": "phpoffice/phpspreadsheet",
"version": "1.14.1",
"source": {
"type": "git",
"url": "https://github.com/PHPOffice/PhpSpreadsheet.git",
"reference": "2383aad5689778470491581442aab38cec41bf1d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/2383aad5689778470491581442aab38cec41bf1d",
"reference": "2383aad5689778470491581442aab38cec41bf1d",
"shasum": ""
},
"require": {
"ext-ctype": "*",
"ext-dom": "*",
"ext-fileinfo": "*",
"ext-gd": "*",
"ext-iconv": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
"ext-simplexml": "*",
"ext-xml": "*",
"ext-xmlreader": "*",
"ext-xmlwriter": "*",
"ext-zip": "*",
"ext-zlib": "*",
"maennchen/zipstream-php": "^2.1",
"markbaker/complex": "^1.4",
"markbaker/matrix": "^1.2",
"php": "^7.2",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"psr/simple-cache": "^1.0"
},
"require-dev": {
"dompdf/dompdf": "^0.8.5",
"friendsofphp/php-cs-fixer": "^2.16",
"jpgraph/jpgraph": "^4.0",
"mpdf/mpdf": "^8.0",
"phpcompatibility/php-compatibility": "^9.3",
"phpunit/phpunit": "^8.5",
"squizlabs/php_codesniffer": "^3.5",
"tecnickcom/tcpdf": "^6.3"
},
"suggest": {
"dompdf/dompdf": "Option for rendering PDF with PDF Writer",
"jpgraph/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers",
"mpdf/mpdf": "Option for rendering PDF with PDF Writer",
"tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer"
},
"type": "library",
"autoload": {
"psr-4": {
"PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Maarten Balliauw",
"homepage": "https://blog.maartenballiauw.be"
},
{
"name": "Mark Baker",
"homepage": "https://markbakeruk.net"
},
{
"name": "Franck Lefevre",
"homepage": "https://rootslabs.net"
},
{
"name": "Erik Tilt"
},
{
"name": "Adrien Crivelli"
}
],
"description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine",
"homepage": "https://github.com/PHPOffice/PhpSpreadsheet",
"keywords": [
"OpenXML",
"excel",
"gnumeric",
"ods",
"php",
"spreadsheet",
"xls",
"xlsx"
],
"time": "2020-07-19T09:51:35+00:00"
},
{
"name": "psr/http-client",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-client.git",
"reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621",
"reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621",
"shasum": ""
},
"require": {
"php": "^7.0 || ^8.0",
"psr/http-message": "^1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP clients",
"homepage": "https://github.com/php-fig/http-client",
"keywords": [
"http",
"http-client",
"psr",
"psr-18"
],
"time": "2020-06-29T06:28:15+00:00"
},
{
"name": "psr/http-factory",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be",
"reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be",
"shasum": ""
},
"require": {
"php": ">=7.0.0",
"psr/http-message": "^1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
],
"time": "2019-04-30T12:38:16+00:00"
},
{
"name": "psr/http-message",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"time": "2016-08-06T14:39:51+00:00"
},
{
"name": "psr/simple-cache",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/simple-cache.git",
"reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
"reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\SimpleCache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interfaces for simple caching",
"keywords": [
"cache",
"caching",
"psr",
"psr-16",
"simple-cache"
],
"time": "2017-10-23T01:57:42+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.18.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/a6977d63bf9a0ad4c65cd352709e230876f9904a",
"reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.18-dev"
},
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"time": "2020-07-14T12:35:20+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": []
}

View File

@ -0,0 +1,4 @@
<?php
require_once("vendor/autoload.php");
/* Start to develop here. Best regards https://php-download.com/ */

7
phpspreadsheet_1.8.1.0/vendor/autoload.php vendored Executable file
View File

@ -0,0 +1,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit5703a41519d94f81d9a2a045a99c45ea::getLoader();

View File

@ -0,0 +1,445 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}

View File

@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,9 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);

View File

@ -0,0 +1,68 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'abede361264e2ae69ec1eee813a101af' => $vendorDir . '/markbaker/complex/classes/src/functions/abs.php',
'21a5860fbef5be28db5ddfbc3cca67c4' => $vendorDir . '/markbaker/complex/classes/src/functions/acos.php',
'1546e3f9d127f2a9bb2d1b6c31c26ef1' => $vendorDir . '/markbaker/complex/classes/src/functions/acosh.php',
'd2516f7f4fba5ea5905f494b4a8262e0' => $vendorDir . '/markbaker/complex/classes/src/functions/acot.php',
'4511163d560956219b96882c0980b65e' => $vendorDir . '/markbaker/complex/classes/src/functions/acoth.php',
'c361f5616dc2a8da4fa3e137077cd4ea' => $vendorDir . '/markbaker/complex/classes/src/functions/acsc.php',
'02d68920fc98da71991ce569c91df0f6' => $vendorDir . '/markbaker/complex/classes/src/functions/acsch.php',
'88e19525eae308b4a6aa3419364875d3' => $vendorDir . '/markbaker/complex/classes/src/functions/argument.php',
'60e8e2d0827b58bfc904f13957e51849' => $vendorDir . '/markbaker/complex/classes/src/functions/asec.php',
'13d2f040713999eab66c359b4d79871d' => $vendorDir . '/markbaker/complex/classes/src/functions/asech.php',
'838ab38beb32c68a79d3cd2c007d5a04' => $vendorDir . '/markbaker/complex/classes/src/functions/asin.php',
'bb28eccd0f8f008333a1b3c163d604ac' => $vendorDir . '/markbaker/complex/classes/src/functions/asinh.php',
'9e483de83558c98f7d3feaa402c78cb3' => $vendorDir . '/markbaker/complex/classes/src/functions/atan.php',
'36b74b5b765ded91ee58c8ee3c0e85e3' => $vendorDir . '/markbaker/complex/classes/src/functions/atanh.php',
'05c15ee9510da7fd6bf6136f436500c0' => $vendorDir . '/markbaker/complex/classes/src/functions/conjugate.php',
'd3208dfbce2505e370788f9f22f6785f' => $vendorDir . '/markbaker/complex/classes/src/functions/cos.php',
'141cf1fb3a3046f8b64534b0ebab33ca' => $vendorDir . '/markbaker/complex/classes/src/functions/cosh.php',
'be660df75fd0dbe7fa7c03b7434b3294' => $vendorDir . '/markbaker/complex/classes/src/functions/cot.php',
'01e31ea298a51bc9e91517e3ce6b9e76' => $vendorDir . '/markbaker/complex/classes/src/functions/coth.php',
'803ddd97f7b1da68982a7b087c3476f6' => $vendorDir . '/markbaker/complex/classes/src/functions/csc.php',
'3001cdfd101ec3c32da34ee43c2e149b' => $vendorDir . '/markbaker/complex/classes/src/functions/csch.php',
'77b2d7629ef2a93fabb8c56754a91051' => $vendorDir . '/markbaker/complex/classes/src/functions/exp.php',
'4a4471296dec796c21d4f4b6552396a9' => $vendorDir . '/markbaker/complex/classes/src/functions/inverse.php',
'c3e9897e1744b88deb56fcdc39d34d85' => $vendorDir . '/markbaker/complex/classes/src/functions/ln.php',
'a83cacf2de942cff288de15a83afd26d' => $vendorDir . '/markbaker/complex/classes/src/functions/log2.php',
'6a861dacc9ee2f3061241d4c7772fa21' => $vendorDir . '/markbaker/complex/classes/src/functions/log10.php',
'4d2522d968c8ba78d6c13548a1b4200e' => $vendorDir . '/markbaker/complex/classes/src/functions/negative.php',
'fd587ca933fc0447fa5ab4843bdd97f7' => $vendorDir . '/markbaker/complex/classes/src/functions/pow.php',
'383ef01c62028fc78cd4388082fce3c2' => $vendorDir . '/markbaker/complex/classes/src/functions/rho.php',
'150fbd1b95029dc47292da97ecab9375' => $vendorDir . '/markbaker/complex/classes/src/functions/sec.php',
'549abd9bae174286d660bdaa07407c68' => $vendorDir . '/markbaker/complex/classes/src/functions/sech.php',
'6bfbf5eaea6b17a0ed85cb21ba80370c' => $vendorDir . '/markbaker/complex/classes/src/functions/sin.php',
'22efe13f1a497b8e199540ae2d9dc59c' => $vendorDir . '/markbaker/complex/classes/src/functions/sinh.php',
'e90135ab8e787795a509ed7147de207d' => $vendorDir . '/markbaker/complex/classes/src/functions/sqrt.php',
'bb0a7923ffc6a90919cd64ec54ff06bc' => $vendorDir . '/markbaker/complex/classes/src/functions/tan.php',
'2d302f32ce0fd4e433dd91c5bb404a28' => $vendorDir . '/markbaker/complex/classes/src/functions/tanh.php',
'24dd4658a952171a4ee79218c4f9fd06' => $vendorDir . '/markbaker/complex/classes/src/functions/theta.php',
'e49b7876281d6f5bc39536dde96d1f4a' => $vendorDir . '/markbaker/complex/classes/src/operations/add.php',
'47596e02b43cd6da7700134fd08f88cf' => $vendorDir . '/markbaker/complex/classes/src/operations/subtract.php',
'883af48563631547925fa4c3b48ead07' => $vendorDir . '/markbaker/complex/classes/src/operations/multiply.php',
'f190e3308e6ca23234a2875edc985c03' => $vendorDir . '/markbaker/complex/classes/src/operations/divideby.php',
'ac9e33ce6841aa5bf5d16d465a2f03a7' => $vendorDir . '/markbaker/complex/classes/src/operations/divideinto.php',
'9d8e013a5160a09477beb8e44f8ae97b' => $vendorDir . '/markbaker/matrix/classes/src/functions/adjoint.php',
'6e78d1bdea6248d6aa117229efae50f2' => $vendorDir . '/markbaker/matrix/classes/src/functions/antidiagonal.php',
'4623d87924d94f5412fe5afbf1cef31d' => $vendorDir . '/markbaker/matrix/classes/src/functions/cofactors.php',
'901fd1f6950a637ca85f66b701a45e13' => $vendorDir . '/markbaker/matrix/classes/src/functions/determinant.php',
'83057abc0e4acc99ba80154ee5d02a49' => $vendorDir . '/markbaker/matrix/classes/src/functions/diagonal.php',
'07b7fd7a434451149b4fd477fca0ce06' => $vendorDir . '/markbaker/matrix/classes/src/functions/identity.php',
'c8d43b340583e07ae89f2a3baef2cf89' => $vendorDir . '/markbaker/matrix/classes/src/functions/inverse.php',
'499bb10ed7a3aee2ba4c09a31a85e8d1' => $vendorDir . '/markbaker/matrix/classes/src/functions/minors.php',
'1cad2e6414d652e8b1c64e8967f6f37d' => $vendorDir . '/markbaker/matrix/classes/src/functions/trace.php',
'95a7f134ac17161d07def442b3b737e8' => $vendorDir . '/markbaker/matrix/classes/src/functions/transpose.php',
'b3a6bc628377118d4b4b8ba08d1eb949' => $vendorDir . '/markbaker/matrix/classes/src/operations/add.php',
'5fef6d0e407f3f8887266dfa4a6c534c' => $vendorDir . '/markbaker/matrix/classes/src/operations/directsum.php',
'684ba247e1385946e3babdaa054119de' => $vendorDir . '/markbaker/matrix/classes/src/operations/subtract.php',
'aa53dcba601214d17ad405b7c291b7e8' => $vendorDir . '/markbaker/matrix/classes/src/operations/multiply.php',
'75c79eb1b25749b05a47976f32b0d8a2' => $vendorDir . '/markbaker/matrix/classes/src/operations/divideby.php',
'6ab8ad87a734f276a6bcd5a0fe1289be' => $vendorDir . '/markbaker/matrix/classes/src/operations/divideinto.php',
);

View File

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);

View File

@ -0,0 +1,18 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'ZipStream\\' => array($vendorDir . '/maennchen/zipstream-php/src'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
'PhpOffice\\PhpSpreadsheet\\' => array($vendorDir . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet'),
'MyCLabs\\Enum\\' => array($vendorDir . '/myclabs/php-enum/src'),
'Matrix\\' => array($vendorDir . '/markbaker/matrix/classes/src'),
'Complex\\' => array($vendorDir . '/markbaker/complex/classes/src'),
);

View File

@ -0,0 +1,70 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit5703a41519d94f81d9a2a045a99c45ea
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit5703a41519d94f81d9a2a045a99c45ea', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit5703a41519d94f81d9a2a045a99c45ea', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit5703a41519d94f81d9a2a045a99c45ea::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit5703a41519d94f81d9a2a045a99c45ea::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire5703a41519d94f81d9a2a045a99c45ea($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequire5703a41519d94f81d9a2a045a99c45ea($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}

View File

@ -0,0 +1,146 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit5703a41519d94f81d9a2a045a99c45ea
{
public static $files = array (
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'abede361264e2ae69ec1eee813a101af' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/abs.php',
'21a5860fbef5be28db5ddfbc3cca67c4' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acos.php',
'1546e3f9d127f2a9bb2d1b6c31c26ef1' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acosh.php',
'd2516f7f4fba5ea5905f494b4a8262e0' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acot.php',
'4511163d560956219b96882c0980b65e' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acoth.php',
'c361f5616dc2a8da4fa3e137077cd4ea' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acsc.php',
'02d68920fc98da71991ce569c91df0f6' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/acsch.php',
'88e19525eae308b4a6aa3419364875d3' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/argument.php',
'60e8e2d0827b58bfc904f13957e51849' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asec.php',
'13d2f040713999eab66c359b4d79871d' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asech.php',
'838ab38beb32c68a79d3cd2c007d5a04' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asin.php',
'bb28eccd0f8f008333a1b3c163d604ac' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/asinh.php',
'9e483de83558c98f7d3feaa402c78cb3' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/atan.php',
'36b74b5b765ded91ee58c8ee3c0e85e3' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/atanh.php',
'05c15ee9510da7fd6bf6136f436500c0' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/conjugate.php',
'd3208dfbce2505e370788f9f22f6785f' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/cos.php',
'141cf1fb3a3046f8b64534b0ebab33ca' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/cosh.php',
'be660df75fd0dbe7fa7c03b7434b3294' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/cot.php',
'01e31ea298a51bc9e91517e3ce6b9e76' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/coth.php',
'803ddd97f7b1da68982a7b087c3476f6' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/csc.php',
'3001cdfd101ec3c32da34ee43c2e149b' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/csch.php',
'77b2d7629ef2a93fabb8c56754a91051' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/exp.php',
'4a4471296dec796c21d4f4b6552396a9' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/inverse.php',
'c3e9897e1744b88deb56fcdc39d34d85' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/ln.php',
'a83cacf2de942cff288de15a83afd26d' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/log2.php',
'6a861dacc9ee2f3061241d4c7772fa21' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/log10.php',
'4d2522d968c8ba78d6c13548a1b4200e' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/negative.php',
'fd587ca933fc0447fa5ab4843bdd97f7' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/pow.php',
'383ef01c62028fc78cd4388082fce3c2' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/rho.php',
'150fbd1b95029dc47292da97ecab9375' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sec.php',
'549abd9bae174286d660bdaa07407c68' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sech.php',
'6bfbf5eaea6b17a0ed85cb21ba80370c' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sin.php',
'22efe13f1a497b8e199540ae2d9dc59c' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sinh.php',
'e90135ab8e787795a509ed7147de207d' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/sqrt.php',
'bb0a7923ffc6a90919cd64ec54ff06bc' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/tan.php',
'2d302f32ce0fd4e433dd91c5bb404a28' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/tanh.php',
'24dd4658a952171a4ee79218c4f9fd06' => __DIR__ . '/..' . '/markbaker/complex/classes/src/functions/theta.php',
'e49b7876281d6f5bc39536dde96d1f4a' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/add.php',
'47596e02b43cd6da7700134fd08f88cf' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/subtract.php',
'883af48563631547925fa4c3b48ead07' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/multiply.php',
'f190e3308e6ca23234a2875edc985c03' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/divideby.php',
'ac9e33ce6841aa5bf5d16d465a2f03a7' => __DIR__ . '/..' . '/markbaker/complex/classes/src/operations/divideinto.php',
'9d8e013a5160a09477beb8e44f8ae97b' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/adjoint.php',
'6e78d1bdea6248d6aa117229efae50f2' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/antidiagonal.php',
'4623d87924d94f5412fe5afbf1cef31d' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/cofactors.php',
'901fd1f6950a637ca85f66b701a45e13' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/determinant.php',
'83057abc0e4acc99ba80154ee5d02a49' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/diagonal.php',
'07b7fd7a434451149b4fd477fca0ce06' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/identity.php',
'c8d43b340583e07ae89f2a3baef2cf89' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/inverse.php',
'499bb10ed7a3aee2ba4c09a31a85e8d1' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/minors.php',
'1cad2e6414d652e8b1c64e8967f6f37d' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/trace.php',
'95a7f134ac17161d07def442b3b737e8' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/functions/transpose.php',
'b3a6bc628377118d4b4b8ba08d1eb949' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/add.php',
'5fef6d0e407f3f8887266dfa4a6c534c' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/directsum.php',
'684ba247e1385946e3babdaa054119de' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/subtract.php',
'aa53dcba601214d17ad405b7c291b7e8' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/multiply.php',
'75c79eb1b25749b05a47976f32b0d8a2' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/divideby.php',
'6ab8ad87a734f276a6bcd5a0fe1289be' => __DIR__ . '/..' . '/markbaker/matrix/classes/src/operations/divideinto.php',
);
public static $prefixLengthsPsr4 = array (
'Z' =>
array (
'ZipStream\\' => 10,
),
'S' =>
array (
'Symfony\\Polyfill\\Mbstring\\' => 26,
),
'P' =>
array (
'Psr\\SimpleCache\\' => 16,
'Psr\\Http\\Message\\' => 17,
'Psr\\Http\\Client\\' => 16,
'PhpOffice\\PhpSpreadsheet\\' => 25,
),
'M' =>
array (
'MyCLabs\\Enum\\' => 13,
'Matrix\\' => 7,
),
'C' =>
array (
'Complex\\' => 8,
),
);
public static $prefixDirsPsr4 = array (
'ZipStream\\' =>
array (
0 => __DIR__ . '/..' . '/maennchen/zipstream-php/src',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Psr\\SimpleCache\\' =>
array (
0 => __DIR__ . '/..' . '/psr/simple-cache/src',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Http\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-client/src',
),
'PhpOffice\\PhpSpreadsheet\\' =>
array (
0 => __DIR__ . '/..' . '/phpoffice/phpspreadsheet/src/PhpSpreadsheet',
),
'MyCLabs\\Enum\\' =>
array (
0 => __DIR__ . '/..' . '/myclabs/php-enum/src',
),
'Matrix\\' =>
array (
0 => __DIR__ . '/..' . '/markbaker/matrix/classes/src',
),
'Complex\\' =>
array (
0 => __DIR__ . '/..' . '/markbaker/complex/classes/src',
),
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit5703a41519d94f81d9a2a045a99c45ea::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit5703a41519d94f81d9a2a045a99c45ea::$prefixDirsPsr4;
}, null, ClassLoader::class);
}
}

View File

@ -0,0 +1,651 @@
[
{
"name": "maennchen/zipstream-php",
"version": "2.1.0",
"version_normalized": "2.1.0.0",
"source": {
"type": "git",
"url": "https://github.com/maennchen/ZipStream-PHP.git",
"reference": "c4c5803cc1f93df3d2448478ef79394a5981cc58"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/maennchen/ZipStream-PHP/zipball/c4c5803cc1f93df3d2448478ef79394a5981cc58",
"reference": "c4c5803cc1f93df3d2448478ef79394a5981cc58",
"shasum": ""
},
"require": {
"myclabs/php-enum": "^1.5",
"php": ">= 7.1",
"psr/http-message": "^1.0",
"symfony/polyfill-mbstring": "^1.0"
},
"require-dev": {
"ext-zip": "*",
"guzzlehttp/guzzle": ">= 6.3",
"mikey179/vfsstream": "^1.6",
"phpunit/phpunit": ">= 7.5"
},
"time": "2020-05-30T13:11:16+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"ZipStream\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paul Duncan",
"email": "pabs@pablotron.org"
},
{
"name": "Jonatan Männchen",
"email": "jonatan@maennchen.ch"
},
{
"name": "Jesse Donat",
"email": "donatj@gmail.com"
},
{
"name": "András Kolesár",
"email": "kolesar@kolesar.hu"
}
],
"description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.",
"keywords": [
"stream",
"zip"
]
},
{
"name": "markbaker/complex",
"version": "1.4.8",
"version_normalized": "1.4.8.0",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPComplex.git",
"reference": "8eaa40cceec7bf0518187530b2e63871be661b72"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MarkBaker/PHPComplex/zipball/8eaa40cceec7bf0518187530b2e63871be661b72",
"reference": "8eaa40cceec7bf0518187530b2e63871be661b72",
"shasum": ""
},
"require": {
"php": "^5.6.0|^7.0.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "^0.5.0",
"phpcompatibility/php-compatibility": "^9.0",
"phpdocumentor/phpdocumentor": "2.*",
"phploc/phploc": "2.*",
"phpmd/phpmd": "2.*",
"phpunit/phpunit": "^4.8.35|^5.4.0",
"sebastian/phpcpd": "2.*",
"squizlabs/php_codesniffer": "^3.4.0"
},
"time": "2020-03-11T20:15:49+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Complex\\": "classes/src/"
},
"files": [
"classes/src/functions/abs.php",
"classes/src/functions/acos.php",
"classes/src/functions/acosh.php",
"classes/src/functions/acot.php",
"classes/src/functions/acoth.php",
"classes/src/functions/acsc.php",
"classes/src/functions/acsch.php",
"classes/src/functions/argument.php",
"classes/src/functions/asec.php",
"classes/src/functions/asech.php",
"classes/src/functions/asin.php",
"classes/src/functions/asinh.php",
"classes/src/functions/atan.php",
"classes/src/functions/atanh.php",
"classes/src/functions/conjugate.php",
"classes/src/functions/cos.php",
"classes/src/functions/cosh.php",
"classes/src/functions/cot.php",
"classes/src/functions/coth.php",
"classes/src/functions/csc.php",
"classes/src/functions/csch.php",
"classes/src/functions/exp.php",
"classes/src/functions/inverse.php",
"classes/src/functions/ln.php",
"classes/src/functions/log2.php",
"classes/src/functions/log10.php",
"classes/src/functions/negative.php",
"classes/src/functions/pow.php",
"classes/src/functions/rho.php",
"classes/src/functions/sec.php",
"classes/src/functions/sech.php",
"classes/src/functions/sin.php",
"classes/src/functions/sinh.php",
"classes/src/functions/sqrt.php",
"classes/src/functions/tan.php",
"classes/src/functions/tanh.php",
"classes/src/functions/theta.php",
"classes/src/operations/add.php",
"classes/src/operations/subtract.php",
"classes/src/operations/multiply.php",
"classes/src/operations/divideby.php",
"classes/src/operations/divideinto.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mark Baker",
"email": "mark@lange.demon.co.uk"
}
],
"description": "PHP Class for working with complex numbers",
"homepage": "https://github.com/MarkBaker/PHPComplex",
"keywords": [
"complex",
"mathematics"
]
},
{
"name": "markbaker/matrix",
"version": "1.2.0",
"version_normalized": "1.2.0.0",
"source": {
"type": "git",
"url": "https://github.com/MarkBaker/PHPMatrix.git",
"reference": "5348c5a67e3b75cd209d70103f916a93b1f1ed21"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MarkBaker/PHPMatrix/zipball/5348c5a67e3b75cd209d70103f916a93b1f1ed21",
"reference": "5348c5a67e3b75cd209d70103f916a93b1f1ed21",
"shasum": ""
},
"require": {
"php": "^5.6.0|^7.0.0"
},
"require-dev": {
"dealerdirect/phpcodesniffer-composer-installer": "dev-master",
"phpcompatibility/php-compatibility": "dev-master",
"phploc/phploc": "^4",
"phpmd/phpmd": "dev-master",
"phpunit/phpunit": "^5.7",
"sebastian/phpcpd": "^3.0",
"squizlabs/php_codesniffer": "^3.0@dev"
},
"time": "2019-10-06T11:29:25+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Matrix\\": "classes/src/"
},
"files": [
"classes/src/functions/adjoint.php",
"classes/src/functions/antidiagonal.php",
"classes/src/functions/cofactors.php",
"classes/src/functions/determinant.php",
"classes/src/functions/diagonal.php",
"classes/src/functions/identity.php",
"classes/src/functions/inverse.php",
"classes/src/functions/minors.php",
"classes/src/functions/trace.php",
"classes/src/functions/transpose.php",
"classes/src/operations/add.php",
"classes/src/operations/directsum.php",
"classes/src/operations/subtract.php",
"classes/src/operations/multiply.php",
"classes/src/operations/divideby.php",
"classes/src/operations/divideinto.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mark Baker",
"email": "mark@lange.demon.co.uk"
}
],
"description": "PHP Class for working with matrices",
"homepage": "https://github.com/MarkBaker/PHPMatrix",
"keywords": [
"mathematics",
"matrix",
"vector"
]
},
{
"name": "myclabs/php-enum",
"version": "1.7.6",
"version_normalized": "1.7.6.0",
"source": {
"type": "git",
"url": "https://github.com/myclabs/php-enum.git",
"reference": "5f36467c7a87e20fbdc51e524fd8f9d1de80187c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/myclabs/php-enum/zipball/5f36467c7a87e20fbdc51e524fd8f9d1de80187c",
"reference": "5f36467c7a87e20fbdc51e524fd8f9d1de80187c",
"shasum": ""
},
"require": {
"ext-json": "*",
"php": ">=7.1"
},
"require-dev": {
"phpunit/phpunit": "^7",
"squizlabs/php_codesniffer": "1.*",
"vimeo/psalm": "^3.8"
},
"time": "2020-02-14T08:15:52+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"MyCLabs\\Enum\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP Enum contributors",
"homepage": "https://github.com/myclabs/php-enum/graphs/contributors"
}
],
"description": "PHP Enum implementation",
"homepage": "http://github.com/myclabs/php-enum",
"keywords": [
"enum"
]
},
{
"name": "phpoffice/phpspreadsheet",
"version": "1.14.1",
"version_normalized": "1.14.1.0",
"source": {
"type": "git",
"url": "https://github.com/PHPOffice/PhpSpreadsheet.git",
"reference": "2383aad5689778470491581442aab38cec41bf1d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/PHPOffice/PhpSpreadsheet/zipball/2383aad5689778470491581442aab38cec41bf1d",
"reference": "2383aad5689778470491581442aab38cec41bf1d",
"shasum": ""
},
"require": {
"ext-ctype": "*",
"ext-dom": "*",
"ext-fileinfo": "*",
"ext-gd": "*",
"ext-iconv": "*",
"ext-libxml": "*",
"ext-mbstring": "*",
"ext-simplexml": "*",
"ext-xml": "*",
"ext-xmlreader": "*",
"ext-xmlwriter": "*",
"ext-zip": "*",
"ext-zlib": "*",
"maennchen/zipstream-php": "^2.1",
"markbaker/complex": "^1.4",
"markbaker/matrix": "^1.2",
"php": "^7.2",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"psr/simple-cache": "^1.0"
},
"require-dev": {
"dompdf/dompdf": "^0.8.5",
"friendsofphp/php-cs-fixer": "^2.16",
"jpgraph/jpgraph": "^4.0",
"mpdf/mpdf": "^8.0",
"phpcompatibility/php-compatibility": "^9.3",
"phpunit/phpunit": "^8.5",
"squizlabs/php_codesniffer": "^3.5",
"tecnickcom/tcpdf": "^6.3"
},
"suggest": {
"dompdf/dompdf": "Option for rendering PDF with PDF Writer",
"jpgraph/jpgraph": "Option for rendering charts, or including charts with PDF or HTML Writers",
"mpdf/mpdf": "Option for rendering PDF with PDF Writer",
"tecnickcom/tcpdf": "Option for rendering PDF with PDF Writer"
},
"time": "2020-07-19T09:51:35+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"PhpOffice\\PhpSpreadsheet\\": "src/PhpSpreadsheet"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Maarten Balliauw",
"homepage": "https://blog.maartenballiauw.be"
},
{
"name": "Mark Baker",
"homepage": "https://markbakeruk.net"
},
{
"name": "Franck Lefevre",
"homepage": "https://rootslabs.net"
},
{
"name": "Erik Tilt"
},
{
"name": "Adrien Crivelli"
}
],
"description": "PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP - Spreadsheet engine",
"homepage": "https://github.com/PHPOffice/PhpSpreadsheet",
"keywords": [
"OpenXML",
"excel",
"gnumeric",
"ods",
"php",
"spreadsheet",
"xls",
"xlsx"
]
},
{
"name": "psr/http-client",
"version": "1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-client.git",
"reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-client/zipball/2dfb5f6c5eff0e91e20e913f8c5452ed95b86621",
"reference": "2dfb5f6c5eff0e91e20e913f8c5452ed95b86621",
"shasum": ""
},
"require": {
"php": "^7.0 || ^8.0",
"psr/http-message": "^1.0"
},
"time": "2020-06-29T06:28:15+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP clients",
"homepage": "https://github.com/php-fig/http-client",
"keywords": [
"http",
"http-client",
"psr",
"psr-18"
]
},
{
"name": "psr/http-factory",
"version": "1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-factory.git",
"reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-factory/zipball/12ac7fcd07e5b077433f5f2bee95b3a771bf61be",
"reference": "12ac7fcd07e5b077433f5f2bee95b3a771bf61be",
"shasum": ""
},
"require": {
"php": ">=7.0.0",
"psr/http-message": "^1.0"
},
"time": "2019-04-30T12:38:16+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interfaces for PSR-7 HTTP message factories",
"keywords": [
"factory",
"http",
"message",
"psr",
"psr-17",
"psr-7",
"request",
"response"
]
},
{
"name": "psr/http-message",
"version": "1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2016-08-06T14:39:51+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
]
},
{
"name": "psr/simple-cache",
"version": "1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/simple-cache.git",
"reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
"reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2017-10-23T01:57:42+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\SimpleCache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interfaces for simple caching",
"keywords": [
"cache",
"caching",
"psr",
"psr-16",
"simple-cache"
]
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.18.0",
"version_normalized": "1.18.0.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/a6977d63bf9a0ad4c65cd352709e230876f9904a",
"reference": "a6977d63bf9a0ad4c65cd352709e230876f9904a",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"time": "2020-07-14T12:35:20+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.18-dev"
},
"thanks": {
"name": "symfony/polyfill",
"url": "https://github.com/symfony/polyfill"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
]
}
]

View File

@ -0,0 +1 @@
open_collective: zipstream

View File

@ -0,0 +1,12 @@
# Description of the problem
Please be very descriptive and include as much details as possible.
# Example code
# Informations
* ZipStream-PHP version:
* PHP version:
Please include any supplemental information you deem relevant to this issue.

View File

@ -0,0 +1,6 @@
clover.xml
composer.lock
coverage.clover
.idea
phpunit.xml
vendor

View File

@ -0,0 +1,12 @@
language: php
dist: trusty
sudo: false
php:
- 7.1
- 7.2
- 7.3
install: composer install
script: ./vendor/bin/phpunit --coverage-clover=coverage.clover
after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.clover

View File

@ -0,0 +1,51 @@
# CHANGELOG for ZipStream-PHP
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [2.1.0] - 2020-06-01
### Changed
- Don't execute ob_flush() when output buffering is not enabled (#152)
- Fix inconsistent return type on 32-bit systems (#149) Fix #144
- Use mbstring polyfill (#151)
- Promote 7zip usage over unzip to avoid UTF-8 issues (#147)
## [2.0.0] - 2020-02-22
### Breaking change
- Only the self opened streams will be closed (#139)
If you were relying on ZipStream to close streams that the library didn't open,
you'll need to close them yourself now.
### Changed
- Minor change to data descriptor (#136)
## [1.2.0] - 2019-07-11
### Added
- Option to flush output buffer after every write (#122)
## [1.1.0] - 2019-04-30
### Fixed
- Honor last-modified timestamps set via `ZipStream\Option\File::setTime()` (#106)
- Documentation regarding output of HTTP headers
- Test warnings with PHPUnit (#109)
### Added
- Test for FileNotReadableException (#114)
- Size attribute to File options (#113)
- Tests on PHP 7.3 (#108)
## [1.0.0] - 2019-04-17
### Breaking changes
- Mininum PHP version is now 7.1
- Options are now passed to the ZipStream object via the Option\Archive object. See the wiki for available options and code examples
### Added
- Add large file support with Zip64 headers
### Changed
- Major refactoring and code cleanup

View File

@ -0,0 +1,25 @@
# ZipStream Readme for Contributors
## Code styling
### Indention
For spaces are used to indent code. The convention is [K&R](http://en.wikipedia.org/wiki/Indent_style#K&R)
### Comments
Double Slashes are used for an one line comment.
Classes, Variables, Methods etc:
```php
/**
* My comment
*
* @myanotation like @param etc.
*/
```
## Pull requests
Feel free to submit pull requests.
## Testing
For every new feature please write a new PHPUnit test.
Before every commit execute `./vendor/bin/phpunit` to check if your changes wrecked something:

View File

@ -0,0 +1,24 @@
MIT License
Copyright (C) 2007-2009 Paul Duncan <pabs@pablotron.org>
Copyright (C) 2014 Jonatan Männchen <jonatan@maennchen.ch>
Copyright (C) 2014 Jesse G. Donat <donatj@gmail.com>
Copyright (C) 2018 Nicolas CARPi <nicolas.carpi@curie.fr>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,123 @@
# ZipStream-PHP
[![Build Status](https://travis-ci.org/maennchen/ZipStream-PHP.svg?branch=master)](https://travis-ci.org/maennchen/ZipStream-PHP)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/maennchen/ZipStream-PHP/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/maennchen/ZipStream-PHP/)
[![Code Coverage](https://scrutinizer-ci.com/g/maennchen/ZipStream-PHP/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/maennchen/ZipStream-PHP/)
[![Latest Stable Version](https://poser.pugx.org/maennchen/zipstream-php/v/stable)](https://packagist.org/packages/maennchen/zipstream-php)
[![Total Downloads](https://poser.pugx.org/maennchen/zipstream-php/downloads)](https://packagist.org/packages/maennchen/zipstream-php)
[![Financial Contributors on Open Collective](https://opencollective.com/zipstream/all/badge.svg?label=financial+contributors)](https://opencollective.com/zipstream) [![License](https://img.shields.io/github/license/maennchen/zipstream-php.svg)](LICENSE)
## Overview
A fast and simple streaming zip file downloader for PHP. Using this library will save you from having to write the Zip to disk. You can directly send it to the user, which is much faster. It can work with S3 buckets or any PSR7 Stream.
Please see the [LICENSE](LICENSE) file for licensing and warranty information.
## Installation
Simply add a dependency on maennchen/zipstream-php to your project's composer.json file if you use Composer to manage the dependencies of your project. Use following command to add the package to your project's dependencies:
```bash
composer require maennchen/zipstream-php
```
## Usage and options
Here's a simple example:
```php
// Autoload the dependencies
require 'vendor/autoload.php';
// enable output of HTTP headers
$options = new ZipStream\Option\Archive();
$options->setSendHttpHeaders(true);
// create a new zipstream object
$zip = new ZipStream\ZipStream('example.zip', $options);
// create a file named 'hello.txt'
$zip->addFile('hello.txt', 'This is the contents of hello.txt');
// add a file named 'some_image.jpg' from a local file 'path/to/image.jpg'
$zip->addFileFromPath('some_image.jpg', 'path/to/image.jpg');
// add a file named 'goodbye.txt' from an open stream resource
$fp = tmpfile();
fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
rewind($fp);
$zip->addFileFromStream('goodbye.txt', $fp);
fclose($fp);
// finish the zip stream
$zip->finish();
```
You can also add comments, modify file timestamps, and customize (or
disable) the HTTP headers. It is also possible to specify the storage method when adding files,
the current default storage method is 'deflate' i.e files are stored with Compression mode 0x08.
See the [Wiki](https://github.com/maennchen/ZipStream-PHP/wiki) for details.
## Known issue
The native Mac OS archive extraction tool might not open archives in some conditions. A workaround is to disable the Zip64 feature with the option `$opt->setEnableZip64(false)`. This limits the archive to 4 Gb and 64k files but will allow Mac OS users to open them without issue. See #116.
The linux `unzip` utility might not handle properly unicode characters. It is recommended to extract with another tool like [7-zip](https://www.7-zip.org/). See #146.
## Upgrade to version 2.0.0
* Only the self opened streams will be closed (#139)
If you were relying on ZipStream to close streams that the library didn't open,
you'll need to close them yourself now.
## Upgrade to version 1.0.0
* All options parameters to all function have been moved from an `array` to structured option objects. See [the wiki](https://github.com/maennchen/ZipStream-PHP/wiki/Available-options) for examples.
* The whole library has been refactored. The minimal PHP requirement has been raised to PHP 7.1.
## Usage with Symfony and S3
You can find example code on [the wiki](https://github.com/maennchen/ZipStream-PHP/wiki/Symfony-example).
## Contributing
ZipStream-PHP is a collaborative project. Please take a look at the [CONTRIBUTING.md](CONTRIBUTING.md) file.
## About the Authors
* Paul Duncan <pabs@pablotron.org> - https://pablotron.org/
* Jonatan Männchen <jonatan@maennchen.ch> - https://maennchen.dev
* Jesse G. Donat <donatj@gmail.com> - https://donatstudios.com
* Nicolas CARPi <nico-git@deltablot.email> - https://www.deltablot.com
* Nik Barham <nik@brokencube.co.uk> - https://www.brokencube.co.uk
## Contributors
### Code Contributors
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
<a href="https://github.com/maennchen/ZipStream-PHP/graphs/contributors"><img src="https://opencollective.com/zipstream/contributors.svg?width=890&button=false" /></a>
### Financial Contributors
Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/zipstream/contribute)]
#### Individuals
<a href="https://opencollective.com/zipstream"><img src="https://opencollective.com/zipstream/individuals.svg?width=890"></a>
#### Organizations
Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/zipstream/contribute)]
<a href="https://opencollective.com/zipstream/organization/0/website"><img src="https://opencollective.com/zipstream/organization/0/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/1/website"><img src="https://opencollective.com/zipstream/organization/1/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/2/website"><img src="https://opencollective.com/zipstream/organization/2/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/3/website"><img src="https://opencollective.com/zipstream/organization/3/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/4/website"><img src="https://opencollective.com/zipstream/organization/4/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/5/website"><img src="https://opencollective.com/zipstream/organization/5/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/6/website"><img src="https://opencollective.com/zipstream/organization/6/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/7/website"><img src="https://opencollective.com/zipstream/organization/7/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/8/website"><img src="https://opencollective.com/zipstream/organization/8/avatar.svg"></a>
<a href="https://opencollective.com/zipstream/organization/9/website"><img src="https://opencollective.com/zipstream/organization/9/avatar.svg"></a>

View File

@ -0,0 +1,41 @@
{
"name": "maennchen/zipstream-php",
"description": "ZipStream is a library for dynamically streaming dynamic zip files from PHP without writing to the disk at all on the server.",
"keywords": ["zip", "stream"],
"type": "library",
"license": "MIT",
"authors": [{
"name": "Paul Duncan",
"email": "pabs@pablotron.org"
},
{
"name": "Jonatan Männchen",
"email": "jonatan@maennchen.ch"
},
{
"name": "Jesse Donat",
"email": "donatj@gmail.com"
},
{
"name": "András Kolesár",
"email": "kolesar@kolesar.hu"
}
],
"require": {
"php": ">= 7.1",
"symfony/polyfill-mbstring": "^1.0",
"psr/http-message": "^1.0",
"myclabs/php-enum": "^1.5"
},
"require-dev": {
"phpunit/phpunit": ">= 7.5",
"guzzlehttp/guzzle": ">= 6.3",
"ext-zip": "*",
"mikey179/vfsstream": "^1.6"
},
"autoload": {
"psr-4": {
"ZipStream\\": "src/"
}
}
}

View File

@ -0,0 +1,17 @@
<phpunit bootstrap="test/bootstrap.php">
<testsuites>
<testsuite name="Application">
<directory>test</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-clover" target="clover.xml"/>
</logging>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>

View File

@ -0,0 +1,55 @@
<?xml version="1.0"?>
<psalm
totallyTyped="false"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="src" />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
<issueHandlers>
<LessSpecificReturnType errorLevel="info" />
<!-- level 3 issues - slightly lazy code writing, but provably low false-negatives -->
<DeprecatedMethod errorLevel="info" />
<DeprecatedProperty errorLevel="info" />
<DeprecatedClass errorLevel="info" />
<DeprecatedConstant errorLevel="info" />
<DeprecatedFunction errorLevel="info" />
<DeprecatedInterface errorLevel="info" />
<DeprecatedTrait errorLevel="info" />
<InternalMethod errorLevel="info" />
<InternalProperty errorLevel="info" />
<InternalClass errorLevel="info" />
<MissingClosureReturnType errorLevel="info" />
<MissingReturnType errorLevel="info" />
<MissingPropertyType errorLevel="info" />
<InvalidDocblock errorLevel="info" />
<MisplacedRequiredParam errorLevel="info" />
<PropertyNotSetInConstructor errorLevel="info" />
<MissingConstructor errorLevel="info" />
<MissingClosureParamType errorLevel="info" />
<MissingParamType errorLevel="info" />
<RedundantCondition errorLevel="info" />
<DocblockTypeContradiction errorLevel="info" />
<RedundantConditionGivenDocblockType errorLevel="info" />
<UnresolvableInclude errorLevel="info" />
<RawObjectIteration errorLevel="info" />
<InvalidStringClass errorLevel="info" />
</issueHandlers>
</psalm>

View File

@ -0,0 +1,172 @@
<?php
declare(strict_types=1);
namespace ZipStream;
use OverflowException;
class Bigint
{
/**
* @var int[]
*/
private $bytes = [0, 0, 0, 0, 0, 0, 0, 0];
/**
* Initialize the bytes array
*
* @param int $value
*/
public function __construct(int $value = 0)
{
$this->fillBytes($value, 0, 8);
}
/**
* Fill the bytes field with int
*
* @param int $value
* @param int $start
* @param int $count
* @return void
*/
protected function fillBytes(int $value, int $start, int $count): void
{
for ($i = 0; $i < $count; $i++) {
$this->bytes[$start + $i] = $i >= PHP_INT_SIZE ? 0 : $value & 0xFF;
$value >>= 8;
}
}
/**
* Get an instance
*
* @param int $value
* @return Bigint
*/
public static function init(int $value = 0): self
{
return new self($value);
}
/**
* Fill bytes from low to high
*
* @param int $low
* @param int $high
* @return Bigint
*/
public static function fromLowHigh(int $low, int $high): self
{
$bigint = new Bigint();
$bigint->fillBytes($low, 0, 4);
$bigint->fillBytes($high, 4, 4);
return $bigint;
}
/**
* Get high 32
*
* @return int
*/
public function getHigh32(): int
{
return $this->getValue(4, 4);
}
/**
* Get value from bytes array
*
* @param int $end
* @param int $length
* @return int
*/
public function getValue(int $end = 0, int $length = 8): int
{
$result = 0;
for ($i = $end + $length - 1; $i >= $end; $i--) {
$result <<= 8;
$result |= $this->bytes[$i];
}
return $result;
}
/**
* Get low FF
*
* @param bool $force
* @return float
*/
public function getLowFF(bool $force = false): float
{
if ($force || $this->isOver32()) {
return (float)0xFFFFFFFF;
}
return (float)$this->getLow32();
}
/**
* Check if is over 32
*
* @param bool $force
* @return bool
*/
public function isOver32(bool $force = false): bool
{
// value 0xFFFFFFFF already needs a Zip64 header
return $force ||
max(array_slice($this->bytes, 4, 4)) > 0 ||
min(array_slice($this->bytes, 0, 4)) === 0xFF;
}
/**
* Get low 32
*
* @return int
*/
public function getLow32(): int
{
return $this->getValue(0, 4);
}
/**
* Get hexadecimal
*
* @return string
*/
public function getHex64(): string
{
$result = '0x';
for ($i = 7; $i >= 0; $i--) {
$result .= sprintf('%02X', $this->bytes[$i]);
}
return $result;
}
/**
* Add
*
* @param Bigint $other
* @return Bigint
*/
public function add(Bigint $other): Bigint
{
$result = clone $this;
$overflow = false;
for ($i = 0; $i < 8; $i++) {
$result->bytes[$i] += $other->bytes[$i];
if ($overflow) {
$result->bytes[$i]++;
$overflow = false;
}
if ($result->bytes[$i] & 0x100) {
$overflow = true;
$result->bytes[$i] &= 0xFF;
}
}
if ($overflow) {
throw new OverflowException;
}
return $result;
}
}

View File

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace ZipStream;
class DeflateStream extends Stream
{
protected $filter;
/**
* @var Option\File
*/
protected $options;
/**
* Rewind stream
*
* @return void
*/
public function rewind(): void
{
// deflate filter needs to be removed before rewind
if ($this->filter) {
$this->removeDeflateFilter();
$this->seek(0);
$this->addDeflateFilter($this->options);
} else {
rewind($this->stream);
}
}
/**
* Remove the deflate filter
*
* @return void
*/
public function removeDeflateFilter(): void
{
if (!$this->filter) {
return;
}
stream_filter_remove($this->filter);
$this->filter = null;
}
/**
* Add a deflate filter
*
* @param Option\File $options
* @return void
*/
public function addDeflateFilter(Option\File $options): void
{
$this->options = $options;
// parameter 4 for stream_filter_append expects array
// so we convert the option object in an array
$optionsArr = [
'comment' => $options->getComment(),
'method' => $options->getMethod(),
'deflateLevel' => $options->getDeflateLevel(),
'time' => $options->getTime()
];
$this->filter = stream_filter_append(
$this->stream,
'zlib.deflate',
STREAM_FILTER_READ,
$optionsArr
);
}
}

View File

@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace ZipStream;
/**
* This class is only for inheriting
*/
abstract class Exception extends \Exception
{
}

View File

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace ZipStream\Exception;
use ZipStream\Exception;
/**
* This Exception gets invoked if file or comment encoding is incorrect
*/
class EncodingException extends Exception
{
}

View File

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace ZipStream\Exception;
use ZipStream\Exception;
/**
* This Exception gets invoked if a file wasn't found
*/
class FileNotFoundException extends Exception
{
/**
* Constructor of the Exception
*
* @param String $path - The path which wasn't found
*/
public function __construct(string $path)
{
parent::__construct("The file with the path $path wasn't found.");
}
}

View File

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace ZipStream\Exception;
use ZipStream\Exception;
/**
* This Exception gets invoked if a file wasn't found
*/
class FileNotReadableException extends Exception
{
/**
* Constructor of the Exception
*
* @param String $path - The path which wasn't found
*/
public function __construct(string $path)
{
parent::__construct("The file with the path $path isn't readable.");
}
}

View File

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace ZipStream\Exception;
use ZipStream\Exception;
/**
* This Exception gets invoked if options are incompatible
*/
class IncompatibleOptionsException extends Exception
{
}

View File

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace ZipStream\Exception;
use ZipStream\Exception;
/**
* This Exception gets invoked if a counter value exceeds storage size
*/
class OverflowException extends Exception
{
public function __construct()
{
parent::__construct('File size exceeds limit of 32 bit integer. Please enable "zip64" option.');
}
}

View File

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace ZipStream\Exception;
use ZipStream\Exception;
/**
* This Exception gets invoked if `fread` fails on a stream.
*/
class StreamNotReadableException extends Exception
{
/**
* Constructor of the Exception
*
* @param string $fileName - The name of the file which the stream belongs to.
*/
public function __construct(string $fileName)
{
parent::__construct("The stream for $fileName could not be read.");
}
}

View File

@ -0,0 +1,477 @@
<?php
declare(strict_types=1);
namespace ZipStream;
use Psr\Http\Message\StreamInterface;
use ZipStream\Exception\EncodingException;
use ZipStream\Exception\FileNotFoundException;
use ZipStream\Exception\FileNotReadableException;
use ZipStream\Exception\OverflowException;
use ZipStream\Option\File as FileOptions;
use ZipStream\Option\Method;
use ZipStream\Option\Version;
class File
{
const HASH_ALGORITHM = 'crc32b';
const BIT_ZERO_HEADER = 0x0008;
const BIT_EFS_UTF8 = 0x0800;
const COMPUTE = 1;
const SEND = 2;
private const CHUNKED_READ_BLOCK_SIZE = 1048576;
/**
* @var string
*/
public $name;
/**
* @var FileOptions
*/
public $opt;
/**
* @var Bigint
*/
public $len;
/**
* @var Bigint
*/
public $zlen;
/** @var int */
public $crc;
/**
* @var Bigint
*/
public $hlen;
/**
* @var Bigint
*/
public $ofs;
/**
* @var int
*/
public $bits;
/**
* @var Version
*/
public $version;
/**
* @var ZipStream
*/
public $zip;
/**
* @var resource
*/
private $deflate;
/**
* @var resource
*/
private $hash;
/**
* @var Method
*/
private $method;
/**
* @var Bigint
*/
private $totalLength;
public function __construct(ZipStream $zip, string $name, ?FileOptions $opt = null)
{
$this->zip = $zip;
$this->name = $name;
$this->opt = $opt ?: new FileOptions();
$this->method = $this->opt->getMethod();
$this->version = Version::STORE();
$this->ofs = new Bigint();
}
public function processPath(string $path): void
{
if (!is_readable($path)) {
if (!file_exists($path)) {
throw new FileNotFoundException($path);
}
throw new FileNotReadableException($path);
}
if ($this->zip->isLargeFile($path) === false) {
$data = file_get_contents($path);
$this->processData($data);
} else {
$this->method = $this->zip->opt->getLargeFileMethod();
$stream = new DeflateStream(fopen($path, 'rb'));
$this->processStream($stream);
$stream->close();
}
}
public function processData(string $data): void
{
$this->len = new Bigint(strlen($data));
$this->crc = crc32($data);
// compress data if needed
if ($this->method->equals(Method::DEFLATE())) {
$data = gzdeflate($data);
}
$this->zlen = new Bigint(strlen($data));
$this->addFileHeader();
$this->zip->send($data);
$this->addFileFooter();
}
/**
* Create and send zip header for this file.
*
* @return void
* @throws \ZipStream\Exception\EncodingException
*/
public function addFileHeader(): void
{
$name = static::filterFilename($this->name);
// calculate name length
$nameLength = strlen($name);
// create dos timestamp
$time = static::dosTime($this->opt->getTime()->getTimestamp());
$comment = $this->opt->getComment();
if (!mb_check_encoding($name, 'ASCII') ||
!mb_check_encoding($comment, 'ASCII')) {
// Sets Bit 11: Language encoding flag (EFS). If this bit is set,
// the filename and comment fields for this file
// MUST be encoded using UTF-8. (see APPENDIX D)
if (!mb_check_encoding($name, 'UTF-8') ||
!mb_check_encoding($comment, 'UTF-8')) {
throw new EncodingException(
'File name and comment should use UTF-8 ' .
'if one of them does not fit into ASCII range.'
);
}
$this->bits |= self::BIT_EFS_UTF8;
}
if ($this->method->equals(Method::DEFLATE())) {
$this->version = Version::DEFLATE();
}
$force = (boolean)($this->bits & self::BIT_ZERO_HEADER) &&
$this->zip->opt->isEnableZip64();
$footer = $this->buildZip64ExtraBlock($force);
// If this file will start over 4GB limit in ZIP file,
// CDR record will have to use Zip64 extension to describe offset
// to keep consistency we use the same value here
if ($this->zip->ofs->isOver32()) {
$this->version = Version::ZIP64();
}
$fields = [
['V', ZipStream::FILE_HEADER_SIGNATURE],
['v', $this->version->getValue()], // Version needed to Extract
['v', $this->bits], // General purpose bit flags - data descriptor flag set
['v', $this->method->getValue()], // Compression method
['V', $time], // Timestamp (DOS Format)
['V', $this->crc], // CRC32 of data (0 -> moved to data descriptor footer)
['V', $this->zlen->getLowFF($force)], // Length of compressed data (forced to 0xFFFFFFFF for zero header)
['V', $this->len->getLowFF($force)], // Length of original data (forced to 0xFFFFFFFF for zero header)
['v', $nameLength], // Length of filename
['v', strlen($footer)], // Extra data (see above)
];
// pack fields and calculate "total" length
$header = ZipStream::packFields($fields);
// print header and filename
$data = $header . $name . $footer;
$this->zip->send($data);
// save header length
$this->hlen = Bigint::init(strlen($data));
}
/**
* Strip characters that are not legal in Windows filenames
* to prevent compatibility issues
*
* @param string $filename Unprocessed filename
* @return string
*/
public static function filterFilename(string $filename): string
{
// strip leading slashes from file name
// (fixes bug in windows archive viewer)
$filename = preg_replace('/^\\/+/', '', $filename);
return str_replace(['\\', ':', '*', '?', '"', '<', '>', '|'], '_', $filename);
}
/**
* Convert a UNIX timestamp to a DOS timestamp.
*
* @param int $when
* @return int DOS Timestamp
*/
final protected static function dosTime(int $when): int
{
// get date array for timestamp
$d = getdate($when);
// set lower-bound on dates
if ($d['year'] < 1980) {
$d = array(
'year' => 1980,
'mon' => 1,
'mday' => 1,
'hours' => 0,
'minutes' => 0,
'seconds' => 0
);
}
// remove extra years from 1980
$d['year'] -= 1980;
// return date string
return
($d['year'] << 25) |
($d['mon'] << 21) |
($d['mday'] << 16) |
($d['hours'] << 11) |
($d['minutes'] << 5) |
($d['seconds'] >> 1);
}
protected function buildZip64ExtraBlock(bool $force = false): string
{
$fields = [];
if ($this->len->isOver32($force)) {
$fields[] = ['P', $this->len]; // Length of original data
}
if ($this->len->isOver32($force)) {
$fields[] = ['P', $this->zlen]; // Length of compressed data
}
if ($this->ofs->isOver32()) {
$fields[] = ['P', $this->ofs]; // Offset of local header record
}
if (!empty($fields)) {
if (!$this->zip->opt->isEnableZip64()) {
throw new OverflowException();
}
array_unshift(
$fields,
['v', 0x0001], // 64 bit extension
['v', count($fields) * 8] // Length of data block
);
$this->version = Version::ZIP64();
}
return ZipStream::packFields($fields);
}
/**
* Create and send data descriptor footer for this file.
*
* @return void
*/
public function addFileFooter(): void
{
if ($this->bits & self::BIT_ZERO_HEADER) {
// compressed and uncompressed size
$sizeFormat = 'V';
if ($this->zip->opt->isEnableZip64()) {
$sizeFormat = 'P';
}
$fields = [
['V', ZipStream::DATA_DESCRIPTOR_SIGNATURE],
['V', $this->crc], // CRC32
[$sizeFormat, $this->zlen], // Length of compressed data
[$sizeFormat, $this->len], // Length of original data
];
$footer = ZipStream::packFields($fields);
$this->zip->send($footer);
} else {
$footer = '';
}
$this->totalLength = $this->hlen->add($this->zlen)->add(Bigint::init(strlen($footer)));
$this->zip->addToCdr($this);
}
public function processStream(StreamInterface $stream): void
{
$this->zlen = new Bigint();
$this->len = new Bigint();
if ($this->zip->opt->isZeroHeader()) {
$this->processStreamWithZeroHeader($stream);
} else {
$this->processStreamWithComputedHeader($stream);
}
}
protected function processStreamWithZeroHeader(StreamInterface $stream): void
{
$this->bits |= self::BIT_ZERO_HEADER;
$this->addFileHeader();
$this->readStream($stream, self::COMPUTE | self::SEND);
$this->addFileFooter();
}
protected function readStream(StreamInterface $stream, ?int $options = null): void
{
$this->deflateInit();
$total = 0;
$size = $this->opt->getSize();
while (!$stream->eof() && ($size === 0 || $total < $size)) {
$data = $stream->read(self::CHUNKED_READ_BLOCK_SIZE);
$total += strlen($data);
if ($size > 0 && $total > $size) {
$data = substr($data, 0 , strlen($data)-($total - $size));
}
$this->deflateData($stream, $data, $options);
if ($options & self::SEND) {
$this->zip->send($data);
}
}
$this->deflateFinish($options);
}
protected function deflateInit(): void
{
$this->hash = hash_init(self::HASH_ALGORITHM);
if ($this->method->equals(Method::DEFLATE())) {
$this->deflate = deflate_init(
ZLIB_ENCODING_RAW,
['level' => $this->opt->getDeflateLevel()]
);
}
}
protected function deflateData(StreamInterface $stream, string &$data, ?int $options = null): void
{
if ($options & self::COMPUTE) {
$this->len = $this->len->add(Bigint::init(strlen($data)));
hash_update($this->hash, $data);
}
if ($this->deflate) {
$data = deflate_add(
$this->deflate,
$data,
$stream->eof()
? ZLIB_FINISH
: ZLIB_NO_FLUSH
);
}
if ($options & self::COMPUTE) {
$this->zlen = $this->zlen->add(Bigint::init(strlen($data)));
}
}
protected function deflateFinish(?int $options = null): void
{
if ($options & self::COMPUTE) {
$this->crc = hexdec(hash_final($this->hash));
}
}
protected function processStreamWithComputedHeader(StreamInterface $stream): void
{
$this->readStream($stream, self::COMPUTE);
$stream->rewind();
// incremental compression with deflate_add
// makes this second read unnecessary
// but it is only available from PHP 7.0
if (!$this->deflate && $stream instanceof DeflateStream && $this->method->equals(Method::DEFLATE())) {
$stream->addDeflateFilter($this->opt);
$this->zlen = new Bigint();
while (!$stream->eof()) {
$data = $stream->read(self::CHUNKED_READ_BLOCK_SIZE);
$this->zlen = $this->zlen->add(Bigint::init(strlen($data)));
}
$stream->rewind();
}
$this->addFileHeader();
$this->readStream($stream, self::SEND);
$this->addFileFooter();
}
/**
* Send CDR record for specified file.
*
* @return string
*/
public function getCdrFile(): string
{
$name = static::filterFilename($this->name);
// get attributes
$comment = $this->opt->getComment();
// get dos timestamp
$time = static::dosTime($this->opt->getTime()->getTimestamp());
$footer = $this->buildZip64ExtraBlock();
$fields = [
['V', ZipStream::CDR_FILE_SIGNATURE], // Central file header signature
['v', ZipStream::ZIP_VERSION_MADE_BY], // Made by version
['v', $this->version->getValue()], // Extract by version
['v', $this->bits], // General purpose bit flags - data descriptor flag set
['v', $this->method->getValue()], // Compression method
['V', $time], // Timestamp (DOS Format)
['V', $this->crc], // CRC32
['V', $this->zlen->getLowFF()], // Compressed Data Length
['V', $this->len->getLowFF()], // Original Data Length
['v', strlen($name)], // Length of filename
['v', strlen($footer)], // Extra data len (see above)
['v', strlen($comment)], // Length of comment
['v', 0], // Disk number
['v', 0], // Internal File Attributes
['V', 32], // External File Attributes
['V', $this->ofs->getLowFF()] // Relative offset of local header
];
// pack fields, then append name and comment
$header = ZipStream::packFields($fields);
return $header . $name . $footer . $comment;
}
/**
* @return Bigint
*/
public function getTotalLength(): Bigint
{
return $this->totalLength;
}
}

View File

@ -0,0 +1,261 @@
<?php
declare(strict_types=1);
namespace ZipStream\Option;
final class Archive
{
const DEFAULT_DEFLATE_LEVEL = 6;
/**
* @var string
*/
private $comment = '';
/**
* Size, in bytes, of the largest file to try
* and load into memory (used by
* addFileFromPath()). Large files may also
* be compressed differently; see the
* 'largeFileMethod' option. Default is ~20 Mb.
*
* @var int
*/
private $largeFileSize = 20 * 1024 * 1024;
/**
* How to handle large files. Legal values are
* Method::STORE() (the default), or
* Method::DEFLATE(). STORE sends the file
* raw and is significantly
* faster, while DEFLATE compresses the file
* and is much, much slower. Note that DEFLATE
* must compress the file twice and is extremely slow.
*
* @var Method
*/
private $largeFileMethod;
/**
* Boolean indicating whether or not to send
* the HTTP headers for this file.
*
* @var bool
*/
private $sendHttpHeaders = false;
/**
* The method called to send headers
*
* @var Callable
*/
private $httpHeaderCallback = 'header';
/**
* Enable Zip64 extension, supporting very large
* archives (any size > 4 GB or file count > 64k)
*
* @var bool
*/
private $enableZip64 = true;
/**
* Enable streaming files with single read where
* general purpose bit 3 indicates local file header
* contain zero values in crc and size fields,
* these appear only after file contents
* in data descriptor block.
*
* @var bool
*/
private $zeroHeader = false;
/**
* Enable reading file stat for determining file size.
* When a 32-bit system reads file size that is
* over 2 GB, invalid value appears in file size
* due to integer overflow. Should be disabled on
* 32-bit systems with method addFileFromPath
* if any file may exceed 2 GB. In this case file
* will be read in blocks and correct size will be
* determined from content.
*
* @var bool
*/
private $statFiles = true;
/**
* Enable flush after every write to output stream.
* @var bool
*/
private $flushOutput = false;
/**
* HTTP Content-Disposition. Defaults to
* 'attachment', where
* FILENAME is the specified filename.
*
* Note that this does nothing if you are
* not sending HTTP headers.
*
* @var string
*/
private $contentDisposition = 'attachment';
/**
* Note that this does nothing if you are
* not sending HTTP headers.
*
* @var string
*/
private $contentType = 'application/x-zip';
/**
* @var int
*/
private $deflateLevel = 6;
/**
* @var resource
*/
private $outputStream;
/**
* Options constructor.
*/
public function __construct()
{
$this->largeFileMethod = Method::STORE();
$this->outputStream = fopen('php://output', 'wb');
}
public function getComment(): string
{
return $this->comment;
}
public function setComment(string $comment): void
{
$this->comment = $comment;
}
public function getLargeFileSize(): int
{
return $this->largeFileSize;
}
public function setLargeFileSize(int $largeFileSize): void
{
$this->largeFileSize = $largeFileSize;
}
public function getLargeFileMethod(): Method
{
return $this->largeFileMethod;
}
public function setLargeFileMethod(Method $largeFileMethod): void
{
$this->largeFileMethod = $largeFileMethod;
}
public function isSendHttpHeaders(): bool
{
return $this->sendHttpHeaders;
}
public function setSendHttpHeaders(bool $sendHttpHeaders): void
{
$this->sendHttpHeaders = $sendHttpHeaders;
}
public function getHttpHeaderCallback(): Callable
{
return $this->httpHeaderCallback;
}
public function setHttpHeaderCallback(Callable $httpHeaderCallback): void
{
$this->httpHeaderCallback = $httpHeaderCallback;
}
public function isEnableZip64(): bool
{
return $this->enableZip64;
}
public function setEnableZip64(bool $enableZip64): void
{
$this->enableZip64 = $enableZip64;
}
public function isZeroHeader(): bool
{
return $this->zeroHeader;
}
public function setZeroHeader(bool $zeroHeader): void
{
$this->zeroHeader = $zeroHeader;
}
public function isFlushOutput(): bool
{
return $this->flushOutput;
}
public function setFlushOutput(bool $flushOutput): void
{
$this->flushOutput = $flushOutput;
}
public function isStatFiles(): bool
{
return $this->statFiles;
}
public function setStatFiles(bool $statFiles): void
{
$this->statFiles = $statFiles;
}
public function getContentDisposition(): string
{
return $this->contentDisposition;
}
public function setContentDisposition(string $contentDisposition): void
{
$this->contentDisposition = $contentDisposition;
}
public function getContentType(): string
{
return $this->contentType;
}
public function setContentType(string $contentType): void
{
$this->contentType = $contentType;
}
/**
* @return resource
*/
public function getOutputStream()
{
return $this->outputStream;
}
/**
* @param resource $outputStream
*/
public function setOutputStream($outputStream): void
{
$this->outputStream = $outputStream;
}
/**
* @return int
*/
public function getDeflateLevel(): int
{
return $this->deflateLevel;
}
/**
* @param int $deflateLevel
*/
public function setDeflateLevel(int $deflateLevel): void
{
$this->deflateLevel = $deflateLevel;
}
}

View File

@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace ZipStream\Option;
use DateTime;
final class File
{
/**
* @var string
*/
private $comment = '';
/**
* @var Method
*/
private $method;
/**
* @var int
*/
private $deflateLevel;
/**
* @var DateTime
*/
private $time;
/**
* @var int
*/
private $size = 0;
public function defaultTo(Archive $archiveOptions): void
{
$this->deflateLevel = $this->deflateLevel ?: $archiveOptions->getDeflateLevel();
$this->time = $this->time ?: new DateTime();
}
/**
* @return string
*/
public function getComment(): string
{
return $this->comment;
}
/**
* @param string $comment
*/
public function setComment(string $comment): void
{
$this->comment = $comment;
}
/**
* @return Method
*/
public function getMethod(): Method
{
return $this->method ?: Method::DEFLATE();
}
/**
* @param Method $method
*/
public function setMethod(Method $method): void
{
$this->method = $method;
}
/**
* @return int
*/
public function getDeflateLevel(): int
{
return $this->deflateLevel ?: Archive::DEFAULT_DEFLATE_LEVEL;
}
/**
* @param int $deflateLevel
*/
public function setDeflateLevel(int $deflateLevel): void
{
$this->deflateLevel = $deflateLevel;
}
/**
* @return DateTime
*/
public function getTime(): DateTime
{
return $this->time;
}
/**
* @param DateTime $time
*/
public function setTime(DateTime $time): void
{
$this->time = $time;
}
/**
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* @param int $size
*/
public function setSize(int $size): void
{
$this->size = $size;
}
}

View File

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace ZipStream\Option;
use MyCLabs\Enum\Enum;
/**
* Methods enum
*
* @method static STORE(): Method
* @method static DEFLATE(): Method
* @psalm-immutable
*/
class Method extends Enum
{
const STORE = 0x00;
const DEFLATE = 0x08;
}

View File

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace ZipStream\Option;
use MyCLabs\Enum\Enum;
/**
* Class Version
* @package ZipStream\Option
*
* @method static STORE(): Version
* @method static DEFLATE(): Version
* @method static ZIP64(): Version
* @psalm-immutable
*/
class Version extends Enum
{
const STORE = 0x000A; // 1.00
const DEFLATE = 0x0014; // 2.00
const ZIP64 = 0x002D; // 4.50
}

View File

@ -0,0 +1,253 @@
<?php
declare(strict_types=1);
namespace ZipStream;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
/**
* Describes a data stream.
*
* Typically, an instance will wrap a PHP stream; this interface provides
* a wrapper around the most common operations, including serialization of
* the entire stream to a string.
*/
class Stream implements StreamInterface
{
protected $stream;
public function __construct($stream)
{
$this->stream = $stream;
}
/**
* Closes the stream and any underlying resources.
*
* @return void
*/
public function close(): void
{
if (is_resource($this->stream)) {
fclose($this->stream);
}
$this->detach();
}
/**
* Separates any underlying resources from the stream.
*
* After the stream has been detached, the stream is in an unusable state.
*
* @return resource|null Underlying PHP stream, if any
*/
public function detach()
{
$result = $this->stream;
$this->stream = null;
return $result;
}
/**
* Reads all data from the stream into a string, from the beginning to end.
*
* This method MUST attempt to seek to the beginning of the stream before
* reading data and read the stream until the end is reached.
*
* Warning: This could attempt to load a large amount of data into memory.
*
* This method MUST NOT raise an exception in order to conform with PHP's
* string casting operations.
*
* @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
* @return string
*/
public function __toString(): string
{
try {
$this->seek(0);
} catch (\RuntimeException $e) {}
return (string) stream_get_contents($this->stream);
}
/**
* Seek to a position in the stream.
*
* @link http://www.php.net/manual/en/function.fseek.php
* @param int $offset Stream offset
* @param int $whence Specifies how the cursor position will be calculated
* based on the seek offset. Valid values are identical to the built-in
* PHP $whence values for `fseek()`. SEEK_SET: Set position equal to
* offset bytes SEEK_CUR: Set position to current location plus offset
* SEEK_END: Set position to end-of-stream plus offset.
* @throws \RuntimeException on failure.
*/
public function seek($offset, $whence = SEEK_SET): void
{
if (!$this->isSeekable()) {
throw new RuntimeException;
}
if (fseek($this->stream, $offset, $whence) !== 0) {
throw new RuntimeException;
}
}
/**
* Returns whether or not the stream is seekable.
*
* @return bool
*/
public function isSeekable(): bool
{
return (bool)$this->getMetadata('seekable');
}
/**
* Get stream metadata as an associative array or retrieve a specific key.
*
* The keys returned are identical to the keys returned from PHP's
* stream_get_meta_data() function.
*
* @link http://php.net/manual/en/function.stream-get-meta-data.php
* @param string $key Specific metadata to retrieve.
* @return array|mixed|null Returns an associative array if no key is
* provided. Returns a specific key value if a key is provided and the
* value is found, or null if the key is not found.
*/
public function getMetadata($key = null)
{
$metadata = stream_get_meta_data($this->stream);
return $key !== null ? @$metadata[$key] : $metadata;
}
/**
* Get the size of the stream if known.
*
* @return int|null Returns the size in bytes if known, or null if unknown.
*/
public function getSize(): ?int
{
$stats = fstat($this->stream);
return $stats['size'];
}
/**
* Returns the current position of the file read/write pointer
*
* @return int Position of the file pointer
* @throws \RuntimeException on error.
*/
public function tell(): int
{
$position = ftell($this->stream);
if ($position === false) {
throw new RuntimeException;
}
return $position;
}
/**
* Returns true if the stream is at the end of the stream.
*
* @return bool
*/
public function eof(): bool
{
return feof($this->stream);
}
/**
* Seek to the beginning of the stream.
*
* If the stream is not seekable, this method will raise an exception;
* otherwise, it will perform a seek(0).
*
* @see seek()
* @link http://www.php.net/manual/en/function.fseek.php
* @throws \RuntimeException on failure.
*/
public function rewind(): void
{
$this->seek(0);
}
/**
* Write data to the stream.
*
* @param string $string The string that is to be written.
* @return int Returns the number of bytes written to the stream.
* @throws \RuntimeException on failure.
*/
public function write($string): int
{
if (!$this->isWritable()) {
throw new RuntimeException;
}
if (fwrite($this->stream, $string) === false) {
throw new RuntimeException;
}
return \mb_strlen($string);
}
/**
* Returns whether or not the stream is writable.
*
* @return bool
*/
public function isWritable(): bool
{
return preg_match('/[waxc+]/', $this->getMetadata('mode')) === 1;
}
/**
* Read data from the stream.
*
* @param int $length Read up to $length bytes from the object and return
* them. Fewer than $length bytes may be returned if underlying stream
* call returns fewer bytes.
* @return string Returns the data read from the stream, or an empty string
* if no bytes are available.
* @throws \RuntimeException if an error occurs.
*/
public function read($length): string
{
if (!$this->isReadable()) {
throw new RuntimeException;
}
$result = fread($this->stream, $length);
if ($result === false) {
throw new RuntimeException;
}
return $result;
}
/**
* Returns whether or not the stream is readable.
*
* @return bool
*/
public function isReadable(): bool
{
return preg_match('/[r+]/', $this->getMetadata('mode')) === 1;
}
/**
* Returns the remaining contents in a string
*
* @return string
* @throws \RuntimeException if unable to read or an error occurs while
* reading.
*/
public function getContents(): string
{
if (!$this->isReadable()) {
throw new RuntimeException;
}
$result = stream_get_contents($this->stream);
if ($result === false) {
throw new RuntimeException;
}
return $result;
}
}

View File

@ -0,0 +1,599 @@
<?php
declare(strict_types=1);
namespace ZipStream;
use Psr\Http\Message\StreamInterface;
use ZipStream\Exception\OverflowException;
use ZipStream\Option\Archive as ArchiveOptions;
use ZipStream\Option\File as FileOptions;
use ZipStream\Option\Version;
/**
* ZipStream
*
* Streamed, dynamically generated zip archives.
*
* Usage:
*
* Streaming zip archives is a simple, three-step process:
*
* 1. Create the zip stream:
*
* $zip = new ZipStream('example.zip');
*
* 2. Add one or more files to the archive:
*
* * add first file
* $data = file_get_contents('some_file.gif');
* $zip->addFile('some_file.gif', $data);
*
* * add second file
* $data = file_get_contents('some_file.gif');
* $zip->addFile('another_file.png', $data);
*
* 3. Finish the zip stream:
*
* $zip->finish();
*
* You can also add an archive comment, add comments to individual files,
* and adjust the timestamp of files. See the API documentation for each
* method below for additional information.
*
* Example:
*
* // create a new zip stream object
* $zip = new ZipStream('some_files.zip');
*
* // list of local files
* $files = array('foo.txt', 'bar.jpg');
*
* // read and add each file to the archive
* foreach ($files as $path)
* $zip->addFile($path, file_get_contents($path));
*
* // write archive footer to stream
* $zip->finish();
*/
class ZipStream
{
/**
* This number corresponds to the ZIP version/OS used (2 bytes)
* From: https://www.iana.org/assignments/media-types/application/zip
* The upper byte (leftmost one) indicates the host system (OS) for the
* file. Software can use this information to determine
* the line record format for text files etc. The current
* mappings are:
*
* 0 - MS-DOS and OS/2 (F.A.T. file systems)
* 1 - Amiga 2 - VAX/VMS
* 3 - *nix 4 - VM/CMS
* 5 - Atari ST 6 - OS/2 H.P.F.S.
* 7 - Macintosh 8 - Z-System
* 9 - CP/M 10 thru 255 - unused
*
* The lower byte (rightmost one) indicates the version number of the
* software used to encode the file. The value/10
* indicates the major version number, and the value
* mod 10 is the minor version number.
* Here we are using 6 for the OS, indicating OS/2 H.P.F.S.
* to prevent file permissions issues upon extract (see #84)
* 0x603 is 00000110 00000011 in binary, so 6 and 3
*/
const ZIP_VERSION_MADE_BY = 0x603;
/**
* The following signatures end with 0x4b50, which in ASCII is PK,
* the initials of the inventor Phil Katz.
* See https://en.wikipedia.org/wiki/Zip_(file_format)#File_headers
*/
const FILE_HEADER_SIGNATURE = 0x04034b50;
const CDR_FILE_SIGNATURE = 0x02014b50;
const CDR_EOF_SIGNATURE = 0x06054b50;
const DATA_DESCRIPTOR_SIGNATURE = 0x08074b50;
const ZIP64_CDR_EOF_SIGNATURE = 0x06064b50;
const ZIP64_CDR_LOCATOR_SIGNATURE = 0x07064b50;
/**
* Global Options
*
* @var ArchiveOptions
*/
public $opt;
/**
* @var array
*/
public $files = [];
/**
* @var Bigint
*/
public $cdr_ofs;
/**
* @var Bigint
*/
public $ofs;
/**
* @var bool
*/
protected $need_headers;
/**
* @var null|String
*/
protected $output_name;
/**
* Create a new ZipStream object.
*
* Parameters:
*
* @param String $name - Name of output file (optional).
* @param ArchiveOptions $opt - Archive Options
*
* Large File Support:
*
* By default, the method addFileFromPath() will send send files
* larger than 20 megabytes along raw rather than attempting to
* compress them. You can change both the maximum size and the
* compression behavior using the largeFile* options above, with the
* following caveats:
*
* * For "small" files (e.g. files smaller than largeFileSize), the
* memory use can be up to twice that of the actual file. In other
* words, adding a 10 megabyte file to the archive could potentially
* occupy 20 megabytes of memory.
*
* * Enabling compression on large files (e.g. files larger than
* large_file_size) is extremely slow, because ZipStream has to pass
* over the large file once to calculate header information, and then
* again to compress and send the actual data.
*
* Examples:
*
* // create a new zip file named 'foo.zip'
* $zip = new ZipStream('foo.zip');
*
* // create a new zip file named 'bar.zip' with a comment
* $opt->setComment = 'this is a comment for the zip file.';
* $zip = new ZipStream('bar.zip', $opt);
*
* Notes:
*
* In order to let this library send HTTP headers, a filename must be given
* _and_ the option `sendHttpHeaders` must be `true`. This behavior is to
* allow software to send its own headers (including the filename), and
* still use this library.
*/
public function __construct(?string $name = null, ?ArchiveOptions $opt = null)
{
$this->opt = $opt ?: new ArchiveOptions();
$this->output_name = $name;
$this->need_headers = $name && $this->opt->isSendHttpHeaders();
$this->cdr_ofs = new Bigint();
$this->ofs = new Bigint();
}
/**
* addFile
*
* Add a file to the archive.
*
* @param String $name - path of file in archive (including directory).
* @param String $data - contents of file
* @param FileOptions $options
*
* File Options:
* time - Last-modified timestamp (seconds since the epoch) of
* this file. Defaults to the current time.
* comment - Comment related to this file.
* method - Storage method for file ("store" or "deflate")
*
* Examples:
*
* // add a file named 'foo.txt'
* $data = file_get_contents('foo.txt');
* $zip->addFile('foo.txt', $data);
*
* // add a file named 'bar.jpg' with a comment and a last-modified
* // time of two hours ago
* $data = file_get_contents('bar.jpg');
* $opt->setTime = time() - 2 * 3600;
* $opt->setComment = 'this is a comment about bar.jpg';
* $zip->addFile('bar.jpg', $data, $opt);
*/
public function addFile(string $name, string $data, ?FileOptions $options = null): void
{
$options = $options ?: new FileOptions();
$options->defaultTo($this->opt);
$file = new File($this, $name, $options);
$file->processData($data);
}
/**
* addFileFromPath
*
* Add a file at path to the archive.
*
* Note that large files may be compressed differently than smaller
* files; see the "Large File Support" section above for more
* information.
*
* @param String $name - name of file in archive (including directory path).
* @param String $path - path to file on disk (note: paths should be encoded using
* UNIX-style forward slashes -- e.g '/path/to/some/file').
* @param FileOptions $options
*
* File Options:
* time - Last-modified timestamp (seconds since the epoch) of
* this file. Defaults to the current time.
* comment - Comment related to this file.
* method - Storage method for file ("store" or "deflate")
*
* Examples:
*
* // add a file named 'foo.txt' from the local file '/tmp/foo.txt'
* $zip->addFileFromPath('foo.txt', '/tmp/foo.txt');
*
* // add a file named 'bigfile.rar' from the local file
* // '/usr/share/bigfile.rar' with a comment and a last-modified
* // time of two hours ago
* $path = '/usr/share/bigfile.rar';
* $opt->setTime = time() - 2 * 3600;
* $opt->setComment = 'this is a comment about bar.jpg';
* $zip->addFileFromPath('bigfile.rar', $path, $opt);
*
* @return void
* @throws \ZipStream\Exception\FileNotFoundException
* @throws \ZipStream\Exception\FileNotReadableException
*/
public function addFileFromPath(string $name, string $path, ?FileOptions $options = null): void
{
$options = $options ?: new FileOptions();
$options->defaultTo($this->opt);
$file = new File($this, $name, $options);
$file->processPath($path);
}
/**
* addFileFromStream
*
* Add an open stream to the archive.
*
* @param String $name - path of file in archive (including directory).
* @param resource $stream - contents of file as a stream resource
* @param FileOptions $options
*
* File Options:
* time - Last-modified timestamp (seconds since the epoch) of
* this file. Defaults to the current time.
* comment - Comment related to this file.
*
* Examples:
*
* // create a temporary file stream and write text to it
* $fp = tmpfile();
* fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
*
* // add a file named 'streamfile.txt' from the content of the stream
* $x->addFileFromStream('streamfile.txt', $fp);
*
* @return void
*/
public function addFileFromStream(string $name, $stream, ?FileOptions $options = null): void
{
$options = $options ?: new FileOptions();
$options->defaultTo($this->opt);
$file = new File($this, $name, $options);
$file->processStream(new DeflateStream($stream));
}
/**
* addFileFromPsr7Stream
*
* Add an open stream to the archive.
*
* @param String $name - path of file in archive (including directory).
* @param StreamInterface $stream - contents of file as a stream resource
* @param FileOptions $options
*
* File Options:
* time - Last-modified timestamp (seconds since the epoch) of
* this file. Defaults to the current time.
* comment - Comment related to this file.
*
* Examples:
*
* // create a temporary file stream and write text to it
* $fp = tmpfile();
* fwrite($fp, 'The quick brown fox jumped over the lazy dog.');
*
* // add a file named 'streamfile.txt' from the content of the stream
* $x->addFileFromPsr7Stream('streamfile.txt', $fp);
*
* @return void
*/
public function addFileFromPsr7Stream(
string $name,
StreamInterface $stream,
?FileOptions $options = null
): void {
$options = $options ?: new FileOptions();
$options->defaultTo($this->opt);
$file = new File($this, $name, $options);
$file->processStream($stream);
}
/**
* finish
*
* Write zip footer to stream.
*
* Example:
*
* // add a list of files to the archive
* $files = array('foo.txt', 'bar.jpg');
* foreach ($files as $path)
* $zip->addFile($path, file_get_contents($path));
*
* // write footer to stream
* $zip->finish();
* @return void
*
* @throws OverflowException
*/
public function finish(): void
{
// add trailing cdr file records
foreach ($this->files as $cdrFile) {
$this->send($cdrFile);
$this->cdr_ofs = $this->cdr_ofs->add(Bigint::init(strlen($cdrFile)));
}
// Add 64bit headers (if applicable)
if (count($this->files) >= 0xFFFF ||
$this->cdr_ofs->isOver32() ||
$this->ofs->isOver32()) {
if (!$this->opt->isEnableZip64()) {
throw new OverflowException();
}
$this->addCdr64Eof();
$this->addCdr64Locator();
}
// add trailing cdr eof record
$this->addCdrEof();
// The End
$this->clear();
}
/**
* Send ZIP64 CDR EOF (Central Directory Record End-of-File) record.
*
* @return void
*/
protected function addCdr64Eof(): void
{
$num_files = count($this->files);
$cdr_length = $this->cdr_ofs;
$cdr_offset = $this->ofs;
$fields = [
['V', static::ZIP64_CDR_EOF_SIGNATURE], // ZIP64 end of central file header signature
['P', 44], // Length of data below this header (length of block - 12) = 44
['v', static::ZIP_VERSION_MADE_BY], // Made by version
['v', Version::ZIP64], // Extract by version
['V', 0x00], // disk number
['V', 0x00], // no of disks
['P', $num_files], // no of entries on disk
['P', $num_files], // no of entries in cdr
['P', $cdr_length], // CDR size
['P', $cdr_offset], // CDR offset
];
$ret = static::packFields($fields);
$this->send($ret);
}
/**
* Create a format string and argument list for pack(), then call
* pack() and return the result.
*
* @param array $fields
* @return string
*/
public static function packFields(array $fields): string
{
$fmt = '';
$args = [];
// populate format string and argument list
foreach ($fields as [$format, $value]) {
if ($format === 'P') {
$fmt .= 'VV';
if ($value instanceof Bigint) {
$args[] = $value->getLow32();
$args[] = $value->getHigh32();
} else {
$args[] = $value;
$args[] = 0;
}
} else {
if ($value instanceof Bigint) {
$value = $value->getLow32();
}
$fmt .= $format;
$args[] = $value;
}
}
// prepend format string to argument list
array_unshift($args, $fmt);
// build output string from header and compressed data
return pack(...$args);
}
/**
* Send string, sending HTTP headers if necessary.
* Flush output after write if configure option is set.
*
* @param String $str
* @return void
*/
public function send(string $str): void
{
if ($this->need_headers) {
$this->sendHttpHeaders();
}
$this->need_headers = false;
fwrite($this->opt->getOutputStream(), $str);
if ($this->opt->isFlushOutput()) {
// flush output buffer if it is on and flushable
$status = ob_get_status();
if (isset($status['flags']) && ($status['flags'] & PHP_OUTPUT_HANDLER_FLUSHABLE)) {
ob_flush();
}
// Flush system buffers after flushing userspace output buffer
flush();
}
}
/**
* Send HTTP headers for this stream.
*
* @return void
*/
protected function sendHttpHeaders(): void
{
// grab content disposition
$disposition = $this->opt->getContentDisposition();
if ($this->output_name) {
// Various different browsers dislike various characters here. Strip them all for safety.
$safe_output = trim(str_replace(['"', "'", '\\', ';', "\n", "\r"], '', $this->output_name));
// Check if we need to UTF-8 encode the filename
$urlencoded = rawurlencode($safe_output);
$disposition .= "; filename*=UTF-8''{$urlencoded}";
}
$headers = array(
'Content-Type' => $this->opt->getContentType(),
'Content-Disposition' => $disposition,
'Pragma' => 'public',
'Cache-Control' => 'public, must-revalidate',
'Content-Transfer-Encoding' => 'binary'
);
$call = $this->opt->getHttpHeaderCallback();
foreach ($headers as $key => $val) {
$call("$key: $val");
}
}
/**
* Send ZIP64 CDR Locator (Central Directory Record Locator) record.
*
* @return void
*/
protected function addCdr64Locator(): void
{
$cdr_offset = $this->ofs->add($this->cdr_ofs);
$fields = [
['V', static::ZIP64_CDR_LOCATOR_SIGNATURE], // ZIP64 end of central file header signature
['V', 0x00], // Disc number containing CDR64EOF
['P', $cdr_offset], // CDR offset
['V', 1], // Total number of disks
];
$ret = static::packFields($fields);
$this->send($ret);
}
/**
* Send CDR EOF (Central Directory Record End-of-File) record.
*
* @return void
*/
protected function addCdrEof(): void
{
$num_files = count($this->files);
$cdr_length = $this->cdr_ofs;
$cdr_offset = $this->ofs;
// grab comment (if specified)
$comment = $this->opt->getComment();
$fields = [
['V', static::CDR_EOF_SIGNATURE], // end of central file header signature
['v', 0x00], // disk number
['v', 0x00], // no of disks
['v', min($num_files, 0xFFFF)], // no of entries on disk
['v', min($num_files, 0xFFFF)], // no of entries in cdr
['V', $cdr_length->getLowFF()], // CDR size
['V', $cdr_offset->getLowFF()], // CDR offset
['v', strlen($comment)], // Zip Comment size
];
$ret = static::packFields($fields) . $comment;
$this->send($ret);
}
/**
* Clear all internal variables. Note that the stream object is not
* usable after this.
*
* @return void
*/
protected function clear(): void
{
$this->files = [];
$this->ofs = new Bigint();
$this->cdr_ofs = new Bigint();
$this->opt = new ArchiveOptions();
}
/**
* Is this file larger than large_file_size?
*
* @param string $path
* @return bool
*/
public function isLargeFile(string $path): bool
{
if (!$this->opt->isStatFiles()) {
return false;
}
$stat = stat($path);
return $stat['size'] > $this->opt->getLargeFileSize();
}
/**
* Save file attributes for trailing CDR record.
*
* @param File $file
* @return void
*/
public function addToCdr(File $file): void
{
$file->ofs = $this->ofs;
$this->ofs = $this->ofs->add($file->getTotalLength());
$this->files[] = $file->getCdrFile();
}
}

View File

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace BigintTest;
use OverflowException;
use PHPUnit\Framework\TestCase;
use ZipStream\Bigint;
class BigintTest extends TestCase
{
public function testConstruct(): void
{
$bigint = new Bigint(0x12345678);
$this->assertSame('0x0000000012345678', $bigint->getHex64());
$this->assertSame(0x12345678, $bigint->getLow32());
$this->assertSame(0, $bigint->getHigh32());
}
public function testConstructLarge(): void
{
$bigint = new Bigint(0x87654321);
$this->assertSame('0x0000000087654321', $bigint->getHex64());
$this->assertSame('87654321', bin2hex(pack('N', $bigint->getLow32())));
$this->assertSame(0, $bigint->getHigh32());
}
public function testAddSmallValue(): void
{
$bigint = new Bigint(1);
$bigint = $bigint->add(Bigint::init(2));
$this->assertSame(3, $bigint->getLow32());
$this->assertFalse($bigint->isOver32());
$this->assertTrue($bigint->isOver32(true));
$this->assertSame($bigint->getLowFF(), (float)$bigint->getLow32());
$this->assertSame($bigint->getLowFF(true), (float)0xFFFFFFFF);
}
public function testAddWithOverflowAtLowestByte(): void
{
$bigint = new Bigint(0xFF);
$bigint = $bigint->add(Bigint::init(0x01));
$this->assertSame(0x100, $bigint->getLow32());
}
public function testAddWithOverflowAtInteger32(): void
{
$bigint = new Bigint(0xFFFFFFFE);
$this->assertFalse($bigint->isOver32());
$bigint = $bigint->add(Bigint::init(0x01));
$this->assertTrue($bigint->isOver32());
$bigint = $bigint->add(Bigint::init(0x01));
$this->assertSame('0x0000000100000000', $bigint->getHex64());
$this->assertTrue($bigint->isOver32());
$this->assertSame((float)0xFFFFFFFF, $bigint->getLowFF());
}
public function testAddWithOverflowAtInteger64(): void
{
$bigint = Bigint::fromLowHigh(0xFFFFFFFF, 0xFFFFFFFF);
$this->assertSame('0xFFFFFFFFFFFFFFFF', $bigint->getHex64());
$this->expectException(OverflowException::class);
$bigint->add(Bigint::init(1));
}
}

View File

@ -0,0 +1,586 @@
<?php
declare(strict_types=1);
namespace ZipStreamTest;
use org\bovigo\vfs\vfsStream;
use GuzzleHttp\Psr7\Response;
use PHPUnit\Framework\TestCase;
use ZipStream\File;
use ZipStream\Option\Archive as ArchiveOptions;
use ZipStream\Option\File as FileOptions;
use ZipStream\Option\Method;
use ZipStream\ZipStream;
/**
* Test Class for the Main ZipStream CLass
*/
class ZipStreamTest extends TestCase
{
const OSX_ARCHIVE_UTILITY =
'/System/Library/CoreServices/Applications/Archive Utility.app/Contents/MacOS/Archive Utility';
public function testFileNotFoundException(): void
{
$this->expectException(\ZipStream\Exception\FileNotFoundException::class);
// Get ZipStream Object
$zip = new ZipStream();
// Trigger error by adding a file which doesn't exist
$zip->addFileFromPath('foobar.php', '/foo/bar/foobar.php');
}
public function testFileNotReadableException(): void
{
// create new virtual filesystem
$root = vfsStream::setup('vfs');
// create a virtual file with no permissions
$file = vfsStream::newFile('foo.txt', 0000)->at($root)->setContent('bar');
$zip = new ZipStream();
$this->expectException(\ZipStream\Exception\FileNotReadableException::class);
$zip->addFileFromPath('foo.txt', $file->url());
}
public function testDostime(): void
{
// Allows testing of protected method
$class = new \ReflectionClass(File::class);
$method = $class->getMethod('dostime');
$method->setAccessible(true);
$this->assertSame($method->invoke(null, 1416246368), 1165069764);
// January 1 1980 - DOS Epoch.
$this->assertSame($method->invoke(null, 315532800), 2162688);
// January 1 1970 -> January 1 1980 due to minimum DOS Epoch. @todo Throw Exception?
$this->assertSame($method->invoke(null, 0), 2162688);
}
public function testAddFile(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$zip->addFile('sample.txt', 'Sample String Data');
$zip->addFile('test/sample.txt', 'More Simple Sample Data');
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(['sample.txt', 'test/sample.txt'], $files);
$this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data');
$this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data');
}
/**
* @return array
*/
protected function getTmpFileStream(): array
{
$tmp = tempnam(sys_get_temp_dir(), 'zipstreamtest');
$stream = fopen($tmp, 'wb+');
return array($tmp, $stream);
}
/**
* @param string $tmp
* @return string
*/
protected function validateAndExtractZip($tmp): string
{
$tmpDir = $this->getTmpDir();
$zipArch = new \ZipArchive;
$res = $zipArch->open($tmp);
if ($res !== true) {
$this->fail("Failed to open {$tmp}. Code: $res");
return $tmpDir;
}
$this->assertEquals(0, $zipArch->status);
$this->assertEquals(0, $zipArch->statusSys);
$zipArch->extractTo($tmpDir);
$zipArch->close();
return $tmpDir;
}
protected function getTmpDir(): string
{
$tmp = tempnam(sys_get_temp_dir(), 'zipstreamtest');
unlink($tmp);
mkdir($tmp) or $this->fail('Failed to make directory');
return $tmp;
}
/**
* @param string $path
* @return string[]
*/
protected function getRecursiveFileList(string $path): array
{
$data = array();
$path = (string)realpath($path);
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
$pathLen = strlen($path);
foreach ($files as $file) {
$filePath = $file->getRealPath();
if (!is_dir($filePath)) {
$data[] = substr($filePath, $pathLen + 1);
}
}
sort($data);
return $data;
}
public function testAddFileUtf8NameComment(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$name = 'árvíztűrő tükörfúrógép.txt';
$content = 'Sample String Data';
$comment =
'Filename has every special characters ' .
'from Hungarian language in lowercase. ' .
'In uppercase: ÁÍŰŐÜÖÚÓÉ';
$fileOptions = new FileOptions();
$fileOptions->setComment($comment);
$zip->addFile($name, $content, $fileOptions);
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(array($name), $files);
$this->assertStringEqualsFile($tmpDir . '/' . $name, $content);
$zipArch = new \ZipArchive();
$zipArch->open($tmp);
$this->assertEquals($comment, $zipArch->getCommentName($name));
}
public function testAddFileUtf8NameNonUtfComment(): void
{
$this->expectException(\ZipStream\Exception\EncodingException::class);
$stream = $this->getTmpFileStream()[1];
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$name = 'á.txt';
$content = 'any';
$comment = 'á';
$fileOptions = new FileOptions();
$fileOptions->setComment(mb_convert_encoding($comment, 'ISO-8859-2', 'UTF-8'));
$zip->addFile($name, $content, $fileOptions);
}
public function testAddFileNonUtf8NameUtfComment(): void
{
$this->expectException(\ZipStream\Exception\EncodingException::class);
$stream = $this->getTmpFileStream()[1];
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$name = 'á.txt';
$content = 'any';
$comment = 'á';
$fileOptions = new FileOptions();
$fileOptions->setComment($comment);
$zip->addFile(mb_convert_encoding($name, 'ISO-8859-2', 'UTF-8'), $content, $fileOptions);
}
public function testAddFileWithStorageMethod(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$fileOptions = new FileOptions();
$fileOptions->setMethod(Method::STORE());
$zip->addFile('sample.txt', 'Sample String Data', $fileOptions);
$zip->addFile('test/sample.txt', 'More Simple Sample Data');
$zip->finish();
fclose($stream);
$zipArch = new \ZipArchive();
$zipArch->open($tmp);
$sample1 = $zipArch->statName('sample.txt');
$sample12 = $zipArch->statName('test/sample.txt');
$this->assertEquals($sample1['comp_method'], Method::STORE);
$this->assertEquals($sample12['comp_method'], Method::DEFLATE);
$zipArch->close();
}
public function testDecompressFileWithMacUnarchiver(): void
{
if (!file_exists(self::OSX_ARCHIVE_UTILITY)) {
$this->markTestSkipped('The Mac OSX Archive Utility is not available.');
}
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$folder = uniqid('', true);
$zip->addFile($folder . '/sample.txt', 'Sample Data');
$zip->finish();
fclose($stream);
exec(escapeshellarg(self::OSX_ARCHIVE_UTILITY) . ' ' . escapeshellarg($tmp), $output, $returnStatus);
$this->assertEquals(0, $returnStatus);
$this->assertCount(0, $output);
$this->assertFileExists(dirname($tmp) . '/' . $folder . '/sample.txt');
$this->assertStringEqualsFile(dirname($tmp) . '/' . $folder . '/sample.txt', 'Sample Data');
}
public function testAddFileFromPath(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
[$tmpExample, $streamExample] = $this->getTmpFileStream();
fwrite($streamExample, 'Sample String Data');
fclose($streamExample);
$zip->addFileFromPath('sample.txt', $tmpExample);
[$tmpExample, $streamExample] = $this->getTmpFileStream();
fwrite($streamExample, 'More Simple Sample Data');
fclose($streamExample);
$zip->addFileFromPath('test/sample.txt', $tmpExample);
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(array('sample.txt', 'test/sample.txt'), $files);
$this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data');
$this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data');
}
public function testAddFileFromPathWithStorageMethod(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$fileOptions = new FileOptions();
$fileOptions->setMethod(Method::STORE());
[$tmpExample, $streamExample] = $this->getTmpFileStream();
fwrite($streamExample, 'Sample String Data');
fclose($streamExample);
$zip->addFileFromPath('sample.txt', $tmpExample, $fileOptions);
[$tmpExample, $streamExample] = $this->getTmpFileStream();
fwrite($streamExample, 'More Simple Sample Data');
fclose($streamExample);
$zip->addFileFromPath('test/sample.txt', $tmpExample);
$zip->finish();
fclose($stream);
$zipArch = new \ZipArchive();
$zipArch->open($tmp);
$sample1 = $zipArch->statName('sample.txt');
$this->assertEquals(Method::STORE, $sample1['comp_method']);
$sample2 = $zipArch->statName('test/sample.txt');
$this->assertEquals(Method::DEFLATE, $sample2['comp_method']);
$zipArch->close();
}
public function testAddLargeFileFromPath(): void
{
$methods = [Method::DEFLATE(), Method::STORE()];
$falseTrue = [false, true];
foreach ($methods as $method) {
foreach ($falseTrue as $zeroHeader) {
foreach ($falseTrue as $zip64) {
if ($zeroHeader && $method->equals(Method::DEFLATE())) {
continue;
}
$this->addLargeFileFileFromPath($method, $zeroHeader, $zip64);
}
}
}
}
protected function addLargeFileFileFromPath($method, $zeroHeader, $zip64): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$options->setLargeFileMethod($method);
$options->setLargeFileSize(5);
$options->setZeroHeader($zeroHeader);
$options->setEnableZip64($zip64);
$zip = new ZipStream(null, $options);
[$tmpExample, $streamExample] = $this->getTmpFileStream();
for ($i = 0; $i <= 10000; $i++) {
fwrite($streamExample, sha1((string)$i));
if ($i % 100 === 0) {
fwrite($streamExample, "\n");
}
}
fclose($streamExample);
$shaExample = sha1_file($tmpExample);
$zip->addFileFromPath('sample.txt', $tmpExample);
unlink($tmpExample);
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(array('sample.txt'), $files);
$this->assertEquals(sha1_file($tmpDir . '/sample.txt'), $shaExample, "SHA-1 Mismatch Method: {$method}");
}
public function testAddFileFromStream(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
// In this test we can't use temporary stream to feed data
// because zlib.deflate filter gives empty string before PHP 7
// it works fine with file stream
$streamExample = fopen(__FILE__, 'rb');
$zip->addFileFromStream('sample.txt', $streamExample);
// fclose($streamExample);
$fileOptions = new FileOptions();
$fileOptions->setMethod(Method::STORE());
$streamExample2 = fopen('php://temp', 'wb+');
fwrite($streamExample2, 'More Simple Sample Data');
rewind($streamExample2); // move the pointer back to the beginning of file.
$zip->addFileFromStream('test/sample.txt', $streamExample2, $fileOptions);
// fclose($streamExample2);
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(array('sample.txt', 'test/sample.txt'), $files);
$this->assertStringEqualsFile(__FILE__, file_get_contents($tmpDir . '/sample.txt'));
$this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data');
}
public function testAddFileFromStreamWithStorageMethod(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$fileOptions = new FileOptions();
$fileOptions->setMethod(Method::STORE());
$streamExample = fopen('php://temp', 'wb+');
fwrite($streamExample, 'Sample String Data');
rewind($streamExample); // move the pointer back to the beginning of file.
$zip->addFileFromStream('sample.txt', $streamExample, $fileOptions);
// fclose($streamExample);
$streamExample2 = fopen('php://temp', 'bw+');
fwrite($streamExample2, 'More Simple Sample Data');
rewind($streamExample2); // move the pointer back to the beginning of file.
$zip->addFileFromStream('test/sample.txt', $streamExample2);
// fclose($streamExample2);
$zip->finish();
fclose($stream);
$zipArch = new \ZipArchive();
$zipArch->open($tmp);
$sample1 = $zipArch->statName('sample.txt');
$this->assertEquals(Method::STORE, $sample1['comp_method']);
$sample2 = $zipArch->statName('test/sample.txt');
$this->assertEquals(Method::DEFLATE, $sample2['comp_method']);
$zipArch->close();
}
public function testAddFileFromPsr7Stream(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$body = 'Sample String Data';
$response = new Response(200, [], $body);
$fileOptions = new FileOptions();
$fileOptions->setMethod(Method::STORE());
$zip->addFileFromPsr7Stream('sample.json', $response->getBody(), $fileOptions);
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(array('sample.json'), $files);
$this->assertStringEqualsFile($tmpDir . '/sample.json', $body);
}
public function testAddFileFromPsr7StreamWithFileSizeSet(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$zip = new ZipStream(null, $options);
$body = 'Sample String Data';
$fileSize = strlen($body);
// Add fake padding
$fakePadding = "\0\0\0\0\0\0";
$response = new Response(200, [], $body . $fakePadding);
$fileOptions = new FileOptions();
$fileOptions->setMethod(Method::STORE());
$fileOptions->setSize($fileSize);
$zip->addFileFromPsr7Stream('sample.json', $response->getBody(), $fileOptions);
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(array('sample.json'), $files);
$this->assertStringEqualsFile($tmpDir . '/sample.json', $body);
}
public function testCreateArchiveWithFlushOptionSet(): void
{
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$options->setFlushOutput(true);
$zip = new ZipStream(null, $options);
$zip->addFile('sample.txt', 'Sample String Data');
$zip->addFile('test/sample.txt', 'More Simple Sample Data');
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$files = $this->getRecursiveFileList($tmpDir);
$this->assertEquals(['sample.txt', 'test/sample.txt'], $files);
$this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data');
$this->assertStringEqualsFile($tmpDir . '/test/sample.txt', 'More Simple Sample Data');
}
public function testCreateArchiveWithOutputBufferingOffAndFlushOptionSet(): void
{
// WORKAROUND (1/2): remove phpunit's output buffer in order to run test without any buffering
ob_end_flush();
$this->assertEquals(0, ob_get_level());
[$tmp, $stream] = $this->getTmpFileStream();
$options = new ArchiveOptions();
$options->setOutputStream($stream);
$options->setFlushOutput(true);
$zip = new ZipStream(null, $options);
$zip->addFile('sample.txt', 'Sample String Data');
$zip->finish();
fclose($stream);
$tmpDir = $this->validateAndExtractZip($tmp);
$this->assertStringEqualsFile($tmpDir . '/sample.txt', 'Sample String Data');
// WORKAROUND (2/2): add back output buffering so that PHPUnit doesn't complain that it is missing
ob_start();
}
}

View File

@ -0,0 +1,6 @@
<?php
declare(strict_types=1);
date_default_timezone_set('UTC');
require __DIR__ . '/../vendor/autoload.php';

View File

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace BugHonorFileTimeTest;
use DateTime;
use PHPUnit\Framework\TestCase;
use ZipStream\Option\{
Archive,
File
};
use ZipStream\ZipStream;
use function fopen;
/**
* Asserts that specified last-modified timestamps are not overwritten when a
* file is added
*/
class BugHonorFileTimeTest extends TestCase
{
public function testHonorsFileTime(): void
{
$archiveOpt = new Archive();
$fileOpt = new File();
$expectedTime = new DateTime('2019-04-21T19:25:00-0800');
$archiveOpt->setOutputStream(fopen('php://memory', 'wb'));
$fileOpt->setTime(clone $expectedTime);
$zip = new ZipStream(null, $archiveOpt);
$zip->addFile('sample.txt', 'Sample', $fileOpt);
$zip->finish();
$this->assertEquals($expectedTime, $fileOpt->getTime());
}
}

View File

@ -0,0 +1,156 @@
PHPComplex
==========
---
PHP Class for handling Complex numbers
Master: [![Build Status](https://travis-ci.org/MarkBaker/PHPComplex.png?branch=master)](http://travis-ci.org/MarkBaker/PHPComplex)
Develop: [![Build Status](https://travis-ci.org/MarkBaker/PHPComplex.png?branch=develop)](http://travis-ci.org/MarkBaker/PHPComplex)
[![Complex Numbers](https://imgs.xkcd.com/comics/complex_numbers_2x.png)](https://xkcd.com/2028/)
---
The library currently provides the following operations:
- addition
- subtraction
- multiplication
- division
- division by
- division into
together with functions for
- theta (polar theta angle)
- rho (polar distance/radius)
- conjugate
* negative
- inverse (1 / complex)
- cos (cosine)
- acos (inverse cosine)
- cosh (hyperbolic cosine)
- acosh (inverse hyperbolic cosine)
- sin (sine)
- asin (inverse sine)
- sinh (hyperbolic sine)
- asinh (inverse hyperbolic sine)
- sec (secant)
- asec (inverse secant)
- sech (hyperbolic secant)
- asech (inverse hyperbolic secant)
- csc (cosecant)
- acsc (inverse cosecant)
- csch (hyperbolic secant)
- acsch (inverse hyperbolic secant)
- tan (tangent)
- atan (inverse tangent)
- tanh (hyperbolic tangent)
- atanh (inverse hyperbolic tangent)
- cot (cotangent)
- acot (inverse cotangent)
- coth (hyperbolic cotangent)
- acoth (inverse hyperbolic cotangent)
- sqrt (square root)
- exp (exponential)
- ln (natural log)
- log10 (base-10 log)
- log2 (base-2 log)
- pow (raised to the power of a real number)
---
# Usage
To create a new complex object, you can provide either the real, imaginary and suffix parts as individual values, or as an array of values passed passed to the constructor; or a string representing the value. e.g
```
$real = 1.23;
$imaginary = -4.56;
$suffix = 'i';
$complexObject = new Complex\Complex($real, $imaginary, $suffix);
```
or
```
$real = 1.23;
$imaginary = -4.56;
$suffix = 'i';
$arguments = [$real, $imaginary, $suffix];
$complexObject = new Complex\Complex($arguments);
```
or
```
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
```
Complex objects are immutable: whenever you call a method or pass a complex value to a function that returns a complex value, a new Complex object will be returned, and the original will remain unchanged.
This also allows you to chain multiple methods as you would for a fluent interface (as long as they are methods that will return a Complex result).
## Performing Mathematical Operations
To perform mathematical operations with Complex values, you can call the appropriate method against a complex value, passing other values as arguments
```
$complexString1 = '1.23-4.56i';
$complexString2 = '2.34+5.67i';
$complexObject = new Complex\Complex($complexString1);
echo $complexObject->add($complexString2);
```
or pass all values to the appropriate function
```
$complexString1 = '1.23-4.56i';
$complexString2 = '2.34+5.67i';
echo Complex\add($complexString1, $complexString2);
```
If you want to perform the same operation against multiple values (e.g. to add three or more complex numbers), then you can pass multiple arguments to any of the operations.
You can pass these arguments as Complex objects, or as an array or string that will parse to a complex object.
## Using functions
When calling any of the available functions for a complex value, you can either call the relevant method for the Complex object
```
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
echo $complexObject->sinh();
```
or you can call the function as you would in procedural code, passing the Complex object as an argument
```
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
echo Complex\sinh($complexObject);
```
When called procedurally using the function, you can pass in the argument as a Complex object, or as an array or string that will parse to a complex object.
```
$complexString = '1.23-4.56i';
echo Complex\sinh($complexString);
```
In the case of the `pow()` function (the only implemented function that requires an additional argument) you need to pass both arguments when calling the function procedurally
```
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
echo Complex\pow($complexObject, 2);
```
or pass the additional argument when calling the method
```
$complexString = '1.23-4.56i';
$complexObject = new Complex\Complex($complexString);
echo $complexObject->pow(2);
```

View File

@ -0,0 +1,53 @@
<?php
namespace Complex;
/**
*
* Autoloader for Complex classes
*
* @package Complex
* @copyright Copyright (c) 2014 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
class Autoloader
{
/**
* Register the Autoloader with SPL
*
*/
public static function Register()
{
if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
spl_autoload_register('__autoload');
}
// Register ourselves with SPL
return spl_autoload_register(['Complex\\Autoloader', 'Load']);
}
/**
* Autoload a class identified by name
*
* @param string $pClassName Name of the object to load
*/
public static function Load($pClassName)
{
if ((class_exists($pClassName, false)) || (strpos($pClassName, 'Complex\\') !== 0)) {
// Either already loaded, or not a Complex class request
return false;
}
$pClassFilePath = __DIR__ . DIRECTORY_SEPARATOR .
'src' . DIRECTORY_SEPARATOR .
str_replace(['Complex\\', '\\'], ['', '/'], $pClassName) .
'.php';
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
// Can't load
return false;
}
require($pClassFilePath);
}
}

View File

@ -0,0 +1,38 @@
<?php
include_once __DIR__ . '/Autoloader.php';
\Complex\Autoloader::Register();
abstract class FilesystemRegexFilter extends RecursiveRegexIterator
{
protected $regex;
public function __construct(RecursiveIterator $it, $regex)
{
$this->regex = $regex;
parent::__construct($it, $regex);
}
}
class FilenameFilter extends FilesystemRegexFilter
{
// Filter files against the regex
public function accept()
{
return (!$this->isFile() || preg_match($this->regex, $this->getFilename()));
}
}
$srcFolder = __DIR__ . DIRECTORY_SEPARATOR . 'src';
$srcDirectory = new RecursiveDirectoryIterator($srcFolder);
$filteredFileList = new FilenameFilter($srcDirectory, '/(?:php)$/i');
$filteredFileList = new FilenameFilter($filteredFileList, '/^(?!.*(Complex|Exception)\.php).*$/i');
foreach (new RecursiveIteratorIterator($filteredFileList) as $file) {
if ($file->isFile()) {
include_once $file;
}
}

View File

@ -0,0 +1,390 @@
<?php
/**
*
* Class for the management of Complex numbers
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Complex Number object.
*
* @package Complex
*
* @method float abs()
* @method Complex acos()
* @method Complex acosh()
* @method Complex acot()
* @method Complex acoth()
* @method Complex acsc()
* @method Complex acsch()
* @method float argument()
* @method Complex asec()
* @method Complex asech()
* @method Complex asin()
* @method Complex asinh()
* @method Complex atan()
* @method Complex atanh()
* @method Complex conjugate()
* @method Complex cos()
* @method Complex cosh()
* @method Complex cot()
* @method Complex coth()
* @method Complex csc()
* @method Complex csch()
* @method Complex exp()
* @method Complex inverse()
* @method Complex ln()
* @method Complex log2()
* @method Complex log10()
* @method Complex negative()
* @method Complex pow(int|float $power)
* @method float rho()
* @method Complex sec()
* @method Complex sech()
* @method Complex sin()
* @method Complex sinh()
* @method Complex sqrt()
* @method Complex tan()
* @method Complex tanh()
* @method float theta()
* @method Complex add(...$complexValues)
* @method Complex subtract(...$complexValues)
* @method Complex multiply(...$complexValues)
* @method Complex divideby(...$complexValues)
* @method Complex divideinto(...$complexValues)
*/
class Complex
{
/**
* @constant Euler's Number.
*/
const EULER = 2.7182818284590452353602874713526624977572;
/**
* @constant Regexp to split an input string into real and imaginary components and suffix
*/
const NUMBER_SPLIT_REGEXP =
'` ^
( # Real part
[-+]?(\d+\.?\d*|\d*\.?\d+) # Real value (integer or float)
([Ee][-+]?[0-2]?\d{1,3})? # Optional real exponent for scientific format
)
( # Imaginary part
[-+]?(\d+\.?\d*|\d*\.?\d+) # Imaginary value (integer or float)
([Ee][-+]?[0-2]?\d{1,3})? # Optional imaginary exponent for scientific format
)?
( # Imaginary part is optional
([-+]?) # Imaginary (implicit 1 or -1) only
([ij]?) # Imaginary i or j - depending on whether mathematical or engineering
)
$`uix';
/**
* @var float $realPart The value of of this complex number on the real plane.
*/
protected $realPart = 0.0;
/**
* @var float $imaginaryPart The value of of this complex number on the imaginary plane.
*/
protected $imaginaryPart = 0.0;
/**
* @var string $suffix The suffix for this complex number (i or j).
*/
protected $suffix;
/**
* Validates whether the argument is a valid complex number, converting scalar or array values if possible
*
* @param mixed $complexNumber The value to parse
* @return array
* @throws Exception If the argument isn't a Complex number or cannot be converted to one
*/
private static function parseComplex($complexNumber)
{
// Test for real number, with no imaginary part
if (is_numeric($complexNumber)) {
return [$complexNumber, 0, null];
}
// Fix silly human errors
$complexNumber = str_replace(
['+-', '-+', '++', '--'],
['-', '-', '+', '+'],
$complexNumber
);
// Basic validation of string, to parse out real and imaginary parts, and any suffix
$validComplex = preg_match(
self::NUMBER_SPLIT_REGEXP,
$complexNumber,
$complexParts
);
if (!$validComplex) {
// Neither real nor imaginary part, so test to see if we actually have a suffix
$validComplex = preg_match('/^([\-\+]?)([ij])$/ui', $complexNumber, $complexParts);
if (!$validComplex) {
throw new Exception('Invalid complex number');
}
// We have a suffix, so set the real to 0, the imaginary to either 1 or -1 (as defined by the sign)
$imaginary = 1;
if ($complexParts[1] === '-') {
$imaginary = 0 - $imaginary;
}
return [0, $imaginary, $complexParts[2]];
}
// If we don't have an imaginary part, identify whether it should be +1 or -1...
if (($complexParts[4] === '') && ($complexParts[9] !== '')) {
if ($complexParts[7] !== $complexParts[9]) {
$complexParts[4] = 1;
if ($complexParts[8] === '-') {
$complexParts[4] = -1;
}
} else {
// ... or if we have only the real and no imaginary part
// (in which case our real should be the imaginary)
$complexParts[4] = $complexParts[1];
$complexParts[1] = 0;
}
}
// Return real and imaginary parts and suffix as an array, and set a default suffix if user input lazily
return [
$complexParts[1],
$complexParts[4],
!empty($complexParts[9]) ? $complexParts[9] : 'i'
];
}
public function __construct($realPart = 0.0, $imaginaryPart = null, $suffix = 'i')
{
if ($imaginaryPart === null) {
if (is_array($realPart)) {
// We have an array of (potentially) real and imaginary parts, and any suffix
list ($realPart, $imaginaryPart, $suffix) = array_values($realPart) + [0.0, 0.0, 'i'];
} elseif ((is_string($realPart)) || (is_numeric($realPart))) {
// We've been given a string to parse to extract the real and imaginary parts, and any suffix
list($realPart, $imaginaryPart, $suffix) = self::parseComplex($realPart);
}
}
if ($imaginaryPart != 0.0 && empty($suffix)) {
$suffix = 'i';
} elseif ($imaginaryPart == 0.0 && !empty($suffix)) {
$suffix = '';
}
// Set parsed values in our properties
$this->realPart = (float) $realPart;
$this->imaginaryPart = (float) $imaginaryPart;
$this->suffix = strtolower($suffix);
}
/**
* Gets the real part of this complex number
*
* @return Float
*/
public function getReal()
{
return $this->realPart;
}
/**
* Gets the imaginary part of this complex number
*
* @return Float
*/
public function getImaginary()
{
return $this->imaginaryPart;
}
/**
* Gets the suffix of this complex number
*
* @return String
*/
public function getSuffix()
{
return $this->suffix;
}
/**
* Returns true if this is a real value, false if a complex value
*
* @return Bool
*/
public function isReal()
{
return $this->imaginaryPart == 0.0;
}
/**
* Returns true if this is a complex value, false if a real value
*
* @return Bool
*/
public function isComplex()
{
return !$this->isReal();
}
public function format()
{
$str = "";
if ($this->imaginaryPart != 0.0) {
if (\abs($this->imaginaryPart) != 1.0) {
$str .= $this->imaginaryPart . $this->suffix;
} else {
$str .= (($this->imaginaryPart < 0.0) ? '-' : '') . $this->suffix;
}
}
if ($this->realPart != 0.0) {
if (($str) && ($this->imaginaryPart > 0.0)) {
$str = "+" . $str;
}
$str = $this->realPart . $str;
}
if (!$str) {
$str = "0.0";
}
return $str;
}
public function __toString()
{
return $this->format();
}
/**
* Validates whether the argument is a valid complex number, converting scalar or array values if possible
*
* @param mixed $complex The value to validate
* @return Complex
* @throws Exception If the argument isn't a Complex number or cannot be converted to one
*/
public static function validateComplexArgument($complex)
{
if (is_scalar($complex) || is_array($complex)) {
$complex = new Complex($complex);
} elseif (!is_object($complex) || !($complex instanceof Complex)) {
throw new Exception('Value is not a valid complex number');
}
return $complex;
}
/**
* Returns the reverse of this complex number
*
* @return Complex
*/
public function reverse()
{
return new Complex(
$this->imaginaryPart,
$this->realPart,
($this->realPart == 0.0) ? null : $this->suffix
);
}
public function invertImaginary()
{
return new Complex(
$this->realPart,
$this->imaginaryPart * -1,
($this->imaginaryPart == 0.0) ? null : $this->suffix
);
}
public function invertReal()
{
return new Complex(
$this->realPart * -1,
$this->imaginaryPart,
($this->imaginaryPart == 0.0) ? null : $this->suffix
);
}
protected static $functions = [
'abs',
'acos',
'acosh',
'acot',
'acoth',
'acsc',
'acsch',
'argument',
'asec',
'asech',
'asin',
'asinh',
'atan',
'atanh',
'conjugate',
'cos',
'cosh',
'cot',
'coth',
'csc',
'csch',
'exp',
'inverse',
'ln',
'log2',
'log10',
'negative',
'pow',
'rho',
'sec',
'sech',
'sin',
'sinh',
'sqrt',
'tan',
'tanh',
'theta',
];
protected static $operations = [
'add',
'subtract',
'multiply',
'divideby',
'divideinto',
];
/**
* Returns the result of the function call or operation
*
* @return Complex|float
* @throws Exception|\InvalidArgumentException
*/
public function __call($functionName, $arguments)
{
$functionName = strtolower(str_replace('_', '', $functionName));
// Test for function calls
if (in_array($functionName, self::$functions)) {
$functionName = "\\" . __NAMESPACE__ . "\\{$functionName}";
return $functionName($this, ...$arguments);
}
// Test for operation calls
if (in_array($functionName, self::$operations)) {
$functionName = "\\" . __NAMESPACE__ . "\\{$functionName}";
return $functionName($this, ...$arguments);
}
throw new Exception('Function or Operation does not exist');
}
}

View File

@ -0,0 +1,13 @@
<?php
/**
* Exception.
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
class Exception extends \Exception
{
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex abs() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the absolute value (modulus) of a complex number.
* Also known as the rho of the complex number, i.e. the distance/radius
* from the centrepoint to the representation of the number in polar coordinates.
*
* This function is a synonym for rho()
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return float The absolute (or rho) value of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*
* @see rho
*
*/
function abs($complex)
{
return rho($complex);
}

View File

@ -0,0 +1,38 @@
<?php
/**
*
* Function code for the complex acos() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse cosine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse cosine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function acos($complex)
{
$complex = Complex::validateComplexArgument($complex);
$square = clone $complex;
$square = multiply($square, $complex);
$invsqrt = new Complex(1.0);
$invsqrt = subtract($invsqrt, $square);
$invsqrt = sqrt($invsqrt);
$adjust = new Complex(
$complex->getReal() - $invsqrt->getImaginary(),
$complex->getImaginary() + $invsqrt->getReal()
);
$log = ln($adjust);
return new Complex(
$log->getImaginary(),
-1 * $log->getReal()
);
}

View File

@ -0,0 +1,34 @@
<?php
/**
*
* Function code for the complex acosh() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse hyperbolic cosine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse hyperbolic cosine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function acosh($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal() && ($complex->getReal() > 1)) {
return new Complex(\acosh($complex->getReal()));
}
$acosh = acos($complex)
->reverse();
if ($acosh->getReal() < 0.0) {
$acosh = $acosh->invertReal();
}
return $acosh;
}

View File

@ -0,0 +1,25 @@
<?php
/**
*
* Function code for the complex acot() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse cotangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse cotangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function acot($complex)
{
$complex = Complex::validateComplexArgument($complex);
return atan(inverse($complex));
}

View File

@ -0,0 +1,25 @@
<?php
/**
*
* Function code for the complex acoth() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse hyperbolic cotangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse hyperbolic cotangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function acoth($complex)
{
$complex = Complex::validateComplexArgument($complex);
return atanh(inverse($complex));
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex acsc() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse cosecant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse cosecant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function acsc($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
return INF;
}
return asin(inverse($complex));
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex acsch() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse hyperbolic cosecant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse hyperbolic cosecant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function acsch($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
return INF;
}
return asinh(inverse($complex));
}

View File

@ -0,0 +1,28 @@
<?php
/**
*
* Function code for the complex argument() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the argument of a complex number.
* Also known as the theta of the complex number, i.e. the angle in radians
* from the real axis to the representation of the number in polar coordinates.
*
* This function is a synonym for theta()
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return float The argument (or theta) value of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*
* @see theta
*/
function argument($complex)
{
return theta($complex);
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex asec() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse secant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse secant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function asec($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
return INF;
}
return acos(inverse($complex));
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex asech() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse hyperbolic secant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse hyperbolic secant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function asech($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
return INF;
}
return acosh(inverse($complex));
}

View File

@ -0,0 +1,37 @@
<?php
/**
*
* Function code for the complex asin() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse sine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse sine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function asin($complex)
{
$complex = Complex::validateComplexArgument($complex);
$square = multiply($complex, $complex);
$invsqrt = new Complex(1.0);
$invsqrt = subtract($invsqrt, $square);
$invsqrt = sqrt($invsqrt);
$adjust = new Complex(
$invsqrt->getReal() - $complex->getImaginary(),
$invsqrt->getImaginary() + $complex->getReal()
);
$log = ln($adjust);
return new Complex(
$log->getImaginary(),
-1 * $log->getReal()
);
}

View File

@ -0,0 +1,33 @@
<?php
/**
*
* Function code for the complex asinh() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse hyperbolic sine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse hyperbolic sine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function asinh($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal() && ($complex->getReal() > 1)) {
return new Complex(\asinh($complex->getReal()));
}
$asinh = clone $complex;
$asinh = $asinh->reverse()
->invertReal();
$asinh = asin($asinh);
return $asinh->reverse()
->invertImaginary();
}

View File

@ -0,0 +1,45 @@
<?php
/**
*
* Function code for the complex atan() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
//include_once 'Math/Complex.php';
//include_once 'Math/ComplexOp.php';
/**
* Returns the inverse tangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse tangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function atan($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal()) {
return new Complex(\atan($complex->getReal()));
}
$t1Value = new Complex(-1 * $complex->getImaginary(), $complex->getReal());
$uValue = new Complex(1, 0);
$d1Value = clone $uValue;
$d1Value = subtract($d1Value, $t1Value);
$d2Value = add($t1Value, $uValue);
$uResult = $d1Value->divideBy($d2Value);
$uResult = ln($uResult);
return new Complex(
(($uResult->getImaginary() == M_PI) ? -M_PI : $uResult->getImaginary()) * -0.5,
$uResult->getReal() * 0.5,
$complex->getSuffix()
);
}

View File

@ -0,0 +1,38 @@
<?php
/**
*
* Function code for the complex atanh() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse hyperbolic tangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse hyperbolic tangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function atanh($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal()) {
$real = $complex->getReal();
if ($real >= -1.0 && $real <= 1.0) {
return new Complex(\atanh($real));
} else {
return new Complex(\atanh(1 / $real), (($real < 0.0) ? M_PI_2 : -1 * M_PI_2));
}
}
$iComplex = clone $complex;
$iComplex = $iComplex->invertImaginary()
->reverse();
return atan($iComplex)
->invertReal()
->reverse();
}

View File

@ -0,0 +1,28 @@
<?php
/**
*
* Function code for the complex conjugate() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the complex conjugate of a complex number
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The conjugate of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function conjugate($complex)
{
$complex = Complex::validateComplexArgument($complex);
return new Complex(
$complex->getReal(),
-1 * $complex->getImaginary(),
$complex->getSuffix()
);
}

View File

@ -0,0 +1,34 @@
<?php
/**
*
* Function code for the complex cos() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the cosine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The cosine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function cos($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal()) {
return new Complex(\cos($complex->getReal()));
}
return conjugate(
new Complex(
\cos($complex->getReal()) * \cosh($complex->getImaginary()),
\sin($complex->getReal()) * \sinh($complex->getImaginary()),
$complex->getSuffix()
)
);
}

View File

@ -0,0 +1,32 @@
<?php
/**
*
* Function code for the complex cosh() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the hyperbolic cosine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The hyperbolic cosine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function cosh($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal()) {
return new Complex(\cosh($complex->getReal()));
}
return new Complex(
\cosh($complex->getReal()) * \cos($complex->getImaginary()),
\sinh($complex->getReal()) * \sin($complex->getImaginary()),
$complex->getSuffix()
);
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex cot() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the cotangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The cotangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function cot($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
return new Complex(INF);
}
return inverse(tan($complex));
}

View File

@ -0,0 +1,24 @@
<?php
/**
*
* Function code for the complex coth() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the hyperbolic cotangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The hyperbolic cotangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function coth($complex)
{
$complex = Complex::validateComplexArgument($complex);
return inverse(tanh($complex));
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex csc() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the cosecant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The cosecant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function csc($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
return INF;
}
return inverse(sin($complex));
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex csch() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the hyperbolic cosecant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The hyperbolic cosecant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function csch($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
return INF;
}
return inverse(sinh($complex));
}

View File

@ -0,0 +1,34 @@
<?php
/**
*
* Function code for the complex exp() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the exponential of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The exponential of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function exp($complex)
{
$complex = Complex::validateComplexArgument($complex);
if (($complex->getReal() == 0.0) && (\abs($complex->getImaginary()) == M_PI)) {
return new Complex(-1.0, 0.0);
}
$rho = \exp($complex->getReal());
return new Complex(
$rho * \cos($complex->getImaginary()),
$rho * \sin($complex->getImaginary()),
$complex->getSuffix()
);
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex inverse() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the inverse of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The inverse of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function inverse($complex)
{
$complex = clone Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
throw new \InvalidArgumentException('Division by zero');
}
return $complex->divideInto(1.0);
}

View File

@ -0,0 +1,33 @@
<?php
/**
*
* Function code for the complex ln() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the natural logarithm of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The natural logarithm of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If the real and the imaginary parts are both zero
*/
function ln($complex)
{
$complex = Complex::validateComplexArgument($complex);
if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
throw new \InvalidArgumentException();
}
return new Complex(
\log(rho($complex)),
theta($complex),
$complex->getSuffix()
);
}

View File

@ -0,0 +1,32 @@
<?php
/**
*
* Function code for the complex log10() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the common logarithm (base 10) of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The common logarithm (base 10) of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If the real and the imaginary parts are both zero
*/
function log10($complex)
{
$complex = Complex::validateComplexArgument($complex);
if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
throw new \InvalidArgumentException();
} elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) {
return new Complex(\log10($complex->getReal()), 0.0, $complex->getSuffix());
}
return ln($complex)
->multiply(\log10(Complex::EULER));
}

View File

@ -0,0 +1,32 @@
<?php
/**
*
* Function code for the complex log2() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the base-2 logarithm of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The base-2 logarithm of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If the real and the imaginary parts are both zero
*/
function log2($complex)
{
$complex = Complex::validateComplexArgument($complex);
if (($complex->getReal() == 0.0) && ($complex->getImaginary() == 0.0)) {
throw new \InvalidArgumentException();
} elseif (($complex->getReal() > 0.0) && ($complex->getImaginary() == 0.0)) {
return new Complex(\log($complex->getReal(), 2), 0.0, $complex->getSuffix());
}
return ln($complex)
->multiply(\log(Complex::EULER, 2));
}

View File

@ -0,0 +1,31 @@
<?php
/**
*
* Function code for the complex negative() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the negative of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return float The negative value of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*
* @see rho
*
*/
function negative($complex)
{
$complex = Complex::validateComplexArgument($complex);
return new Complex(
-1 * $complex->getReal(),
-1 * $complex->getImaginary(),
$complex->getSuffix()
);
}

View File

@ -0,0 +1,40 @@
<?php
/**
*
* Function code for the complex pow() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns a complex number raised to a power.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @param float|integer $power The power to raise this value to
* @return Complex The complex argument raised to the real power.
* @throws Exception If the power argument isn't a valid real
*/
function pow($complex, $power)
{
$complex = Complex::validateComplexArgument($complex);
if (!is_numeric($power)) {
throw new Exception('Power argument must be a real number');
}
if ($complex->getImaginary() == 0.0 && $complex->getReal() >= 0.0) {
return new Complex(\pow($complex->getReal(), $power));
}
$rValue = \sqrt(($complex->getReal() * $complex->getReal()) + ($complex->getImaginary() * $complex->getImaginary()));
$rPower = \pow($rValue, $power);
$theta = $complex->argument() * $power;
if ($theta == 0) {
return new Complex(1);
}
return new Complex($rPower * \cos($theta), $rPower * \sin($theta), $complex->getSuffix());
}

View File

@ -0,0 +1,28 @@
<?php
/**
*
* Function code for the complex rho() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the rho of a complex number.
* This is the distance/radius from the centrepoint to the representation of the number in polar coordinates.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return float The rho value of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function rho($complex)
{
$complex = Complex::validateComplexArgument($complex);
return \sqrt(
($complex->getReal() * $complex->getReal()) +
($complex->getImaginary() * $complex->getImaginary())
);
}

View File

@ -0,0 +1,25 @@
<?php
/**
*
* Function code for the complex sec() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the secant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The secant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function sec($complex)
{
$complex = Complex::validateComplexArgument($complex);
return inverse(cos($complex));
}

View File

@ -0,0 +1,25 @@
<?php
/**
*
* Function code for the complex sech() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the hyperbolic secant of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The hyperbolic secant of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function sech($complex)
{
$complex = Complex::validateComplexArgument($complex);
return inverse(cosh($complex));
}

View File

@ -0,0 +1,32 @@
<?php
/**
*
* Function code for the complex sin() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the sine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The sine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function sin($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal()) {
return new Complex(\sin($complex->getReal()));
}
return new Complex(
\sin($complex->getReal()) * \cosh($complex->getImaginary()),
\cos($complex->getReal()) * \sinh($complex->getImaginary()),
$complex->getSuffix()
);
}

View File

@ -0,0 +1,32 @@
<?php
/**
*
* Function code for the complex sinh() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the hyperbolic sine of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The hyperbolic sine of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function sinh($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal()) {
return new Complex(\sinh($complex->getReal()));
}
return new Complex(
\sinh($complex->getReal()) * \cos($complex->getImaginary()),
\cosh($complex->getReal()) * \sin($complex->getImaginary()),
$complex->getSuffix()
);
}

View File

@ -0,0 +1,29 @@
<?php
/**
*
* Function code for the complex sqrt() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the square root of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The Square root of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function sqrt($complex)
{
$complex = Complex::validateComplexArgument($complex);
$theta = theta($complex);
$delta1 = \cos($theta / 2);
$delta2 = \sin($theta / 2);
$rho = \sqrt(rho($complex));
return new Complex($delta1 * $rho, $delta2 * $rho, $complex->getSuffix());
}

View File

@ -0,0 +1,40 @@
<?php
/**
*
* Function code for the complex tan() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the tangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The tangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function tan($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->isReal()) {
return new Complex(\tan($complex->getReal()));
}
$real = $complex->getReal();
$imaginary = $complex->getImaginary();
$divisor = 1 + \pow(\tan($real), 2) * \pow(\tanh($imaginary), 2);
if ($divisor == 0.0) {
throw new \InvalidArgumentException('Division by zero');
}
return new Complex(
\pow(sech($imaginary)->getReal(), 2) * \tan($real) / $divisor,
\pow(sec($real)->getReal(), 2) * \tanh($imaginary) / $divisor,
$complex->getSuffix()
);
}

View File

@ -0,0 +1,35 @@
<?php
/**
*
* Function code for the complex tanh() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the hyperbolic tangent of a complex number.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The hyperbolic tangent of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
* @throws \InvalidArgumentException If function would result in a division by zero
*/
function tanh($complex)
{
$complex = Complex::validateComplexArgument($complex);
$real = $complex->getReal();
$imaginary = $complex->getImaginary();
$divisor = \cos($imaginary) * \cos($imaginary) + \sinh($real) * \sinh($real);
if ($divisor == 0.0) {
throw new \InvalidArgumentException('Division by zero');
}
return new Complex(
\sinh($real) * \cosh($real) / $divisor,
0.5 * \sin(2 * $imaginary) / $divisor,
$complex->getSuffix()
);
}

View File

@ -0,0 +1,38 @@
<?php
/**
*
* Function code for the complex theta() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the theta of a complex number.
* This is the angle in radians from the real axis to the representation of the number in polar coordinates.
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return float The theta value of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function theta($complex)
{
$complex = Complex::validateComplexArgument($complex);
if ($complex->getReal() == 0.0) {
if ($complex->isReal()) {
return 0.0;
} elseif ($complex->getImaginary() < 0.0) {
return M_PI / -2;
}
return M_PI / 2;
} elseif ($complex->getReal() > 0.0) {
return \atan($complex->getImaginary() / $complex->getReal());
} elseif ($complex->getImaginary() < 0.0) {
return -(M_PI - \atan(\abs($complex->getImaginary()) / \abs($complex->getReal())));
}
return M_PI - \atan($complex->getImaginary() / \abs($complex->getReal()));
}

View File

@ -0,0 +1,46 @@
<?php
/**
*
* Function code for the complex addition operation
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Adds two or more complex numbers
*
* @param array of string|integer|float|Complex $complexValues The numbers to add
* @return Complex
*/
function add(...$complexValues)
{
if (count($complexValues) < 2) {
throw new \Exception('This function requires at least 2 arguments');
}
$base = array_shift($complexValues);
$result = clone Complex::validateComplexArgument($base);
foreach ($complexValues as $complex) {
$complex = Complex::validateComplexArgument($complex);
if ($result->isComplex() && $complex->isComplex() &&
$result->getSuffix() !== $complex->getSuffix()) {
throw new Exception('Suffix Mismatch');
}
$real = $result->getReal() + $complex->getReal();
$imaginary = $result->getImaginary() + $complex->getImaginary();
$result = new Complex(
$real,
$imaginary,
($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
);
}
return $result;
}

View File

@ -0,0 +1,56 @@
<?php
/**
*
* Function code for the complex division operation
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Divides two or more complex numbers
*
* @param array of string|integer|float|Complex $complexValues The numbers to divide
* @return Complex
*/
function divideby(...$complexValues)
{
if (count($complexValues) < 2) {
throw new \Exception('This function requires at least 2 arguments');
}
$base = array_shift($complexValues);
$result = clone Complex::validateComplexArgument($base);
foreach ($complexValues as $complex) {
$complex = Complex::validateComplexArgument($complex);
if ($result->isComplex() && $complex->isComplex() &&
$result->getSuffix() !== $complex->getSuffix()) {
throw new Exception('Suffix Mismatch');
}
if ($complex->getReal() == 0.0 && $complex->getImaginary() == 0.0) {
throw new \InvalidArgumentException('Division by zero');
}
$delta1 = ($result->getReal() * $complex->getReal()) +
($result->getImaginary() * $complex->getImaginary());
$delta2 = ($result->getImaginary() * $complex->getReal()) -
($result->getReal() * $complex->getImaginary());
$delta3 = ($complex->getReal() * $complex->getReal()) +
($complex->getImaginary() * $complex->getImaginary());
$real = $delta1 / $delta3;
$imaginary = $delta2 / $delta3;
$result = new Complex(
$real,
$imaginary,
($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
);
}
return $result;
}

View File

@ -0,0 +1,56 @@
<?php
/**
*
* Function code for the complex division operation
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Divides two or more complex numbers
*
* @param array of string|integer|float|Complex $complexValues The numbers to divide
* @return Complex
*/
function divideinto(...$complexValues)
{
if (count($complexValues) < 2) {
throw new \Exception('This function requires at least 2 arguments');
}
$base = array_shift($complexValues);
$result = clone Complex::validateComplexArgument($base);
foreach ($complexValues as $complex) {
$complex = Complex::validateComplexArgument($complex);
if ($result->isComplex() && $complex->isComplex() &&
$result->getSuffix() !== $complex->getSuffix()) {
throw new Exception('Suffix Mismatch');
}
if ($result->getReal() == 0.0 && $result->getImaginary() == 0.0) {
throw new \InvalidArgumentException('Division by zero');
}
$delta1 = ($complex->getReal() * $result->getReal()) +
($complex->getImaginary() * $result->getImaginary());
$delta2 = ($complex->getImaginary() * $result->getReal()) -
($complex->getReal() * $result->getImaginary());
$delta3 = ($result->getReal() * $result->getReal()) +
($result->getImaginary() * $result->getImaginary());
$real = $delta1 / $delta3;
$imaginary = $delta2 / $delta3;
$result = new Complex(
$real,
$imaginary,
($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
);
}
return $result;
}

View File

@ -0,0 +1,48 @@
<?php
/**
*
* Function code for the complex multiplication operation
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Multiplies two or more complex numbers
*
* @param array of string|integer|float|Complex $complexValues The numbers to multiply
* @return Complex
*/
function multiply(...$complexValues)
{
if (count($complexValues) < 2) {
throw new \Exception('This function requires at least 2 arguments');
}
$base = array_shift($complexValues);
$result = clone Complex::validateComplexArgument($base);
foreach ($complexValues as $complex) {
$complex = Complex::validateComplexArgument($complex);
if ($result->isComplex() && $complex->isComplex() &&
$result->getSuffix() !== $complex->getSuffix()) {
throw new Exception('Suffix Mismatch');
}
$real = ($result->getReal() * $complex->getReal()) -
($result->getImaginary() * $complex->getImaginary());
$imaginary = ($result->getReal() * $complex->getImaginary()) +
($result->getImaginary() * $complex->getReal());
$result = new Complex(
$real,
$imaginary,
($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
);
}
return $result;
}

View File

@ -0,0 +1,46 @@
<?php
/**
*
* Function code for the complex subtraction operation
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Subtracts two or more complex numbers
*
* @param array of string|integer|float|Complex $complexValues The numbers to subtract
* @return Complex
*/
function subtract(...$complexValues)
{
if (count($complexValues) < 2) {
throw new \Exception('This function requires at least 2 arguments');
}
$base = array_shift($complexValues);
$result = clone Complex::validateComplexArgument($base);
foreach ($complexValues as $complex) {
$complex = Complex::validateComplexArgument($complex);
if ($result->isComplex() && $complex->isComplex() &&
$result->getSuffix() !== $complex->getSuffix()) {
throw new Exception('Suffix Mismatch');
}
$real = $result->getReal() - $complex->getReal();
$imaginary = $result->getImaginary() - $complex->getImaginary();
$result = new Complex(
$real,
$imaginary,
($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
);
}
return $result;
}

View File

@ -0,0 +1,94 @@
{
"name": "markbaker/complex",
"type": "library",
"description": "PHP Class for working with complex numbers",
"keywords": ["complex", "mathematics"],
"homepage": "https://github.com/MarkBaker/PHPComplex",
"license": "MIT",
"authors": [
{
"name": "Mark Baker",
"email": "mark@lange.demon.co.uk"
}
],
"require": {
"php": "^5.6.0|^7.0.0"
},
"require-dev": {
"phpunit/phpunit": "^4.8.35|^5.4.0",
"phpdocumentor/phpdocumentor":"2.*",
"phpmd/phpmd": "2.*",
"sebastian/phpcpd": "2.*",
"phploc/phploc": "2.*",
"squizlabs/php_codesniffer": "^3.4.0",
"phpcompatibility/php-compatibility": "^9.0",
"dealerdirect/phpcodesniffer-composer-installer": "^0.5.0"
},
"autoload": {
"psr-4": {
"Complex\\": "classes/src/"
},
"files": [
"classes/src/functions/abs.php",
"classes/src/functions/acos.php",
"classes/src/functions/acosh.php",
"classes/src/functions/acot.php",
"classes/src/functions/acoth.php",
"classes/src/functions/acsc.php",
"classes/src/functions/acsch.php",
"classes/src/functions/argument.php",
"classes/src/functions/asec.php",
"classes/src/functions/asech.php",
"classes/src/functions/asin.php",
"classes/src/functions/asinh.php",
"classes/src/functions/atan.php",
"classes/src/functions/atanh.php",
"classes/src/functions/conjugate.php",
"classes/src/functions/cos.php",
"classes/src/functions/cosh.php",
"classes/src/functions/cot.php",
"classes/src/functions/coth.php",
"classes/src/functions/csc.php",
"classes/src/functions/csch.php",
"classes/src/functions/exp.php",
"classes/src/functions/inverse.php",
"classes/src/functions/ln.php",
"classes/src/functions/log2.php",
"classes/src/functions/log10.php",
"classes/src/functions/negative.php",
"classes/src/functions/pow.php",
"classes/src/functions/rho.php",
"classes/src/functions/sec.php",
"classes/src/functions/sech.php",
"classes/src/functions/sin.php",
"classes/src/functions/sinh.php",
"classes/src/functions/sqrt.php",
"classes/src/functions/tan.php",
"classes/src/functions/tanh.php",
"classes/src/functions/theta.php",
"classes/src/operations/add.php",
"classes/src/operations/subtract.php",
"classes/src/operations/multiply.php",
"classes/src/operations/divideby.php",
"classes/src/operations/divideinto.php"
]
},
"scripts": {
"style": [
"phpcs --report-width=200 --report=summary,full -n"
],
"mess": [
"phpmd classes/src/ xml codesize,unusedcode,design,naming -n"
],
"lines": [
"phploc classes/src/ -n"
],
"cpd": [
"phpcpd classes/src/ -n"
],
"versions": [
"phpcs --report-width=200 --report=summary,full classes/src/ --standard=PHPCompatibility --runtime-set testVersion 5.6- -n"
]
},
"minimum-stability": "dev"
}

View File

@ -0,0 +1,154 @@
<?php
use Complex\Complex as Complex;
include('../classes/Bootstrap.php');
echo 'Create', PHP_EOL;
$x = new Complex(123);
echo $x, PHP_EOL;
$x = new Complex(123, 456);
echo $x, PHP_EOL;
$x = new Complex(array(123,456,'j'));
echo $x, PHP_EOL;
$x = new Complex('1.23e-4--2.34e-5i');
echo $x, PHP_EOL;
echo PHP_EOL, 'Add', PHP_EOL;
$x = new Complex(123);
$x->add(456);
echo $x, PHP_EOL;
$x = new Complex(123.456);
$x->add(789.012);
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->add(new Complex(-987.654, -32.1));
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->add(-987.654);
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->add(new Complex(0, 1));
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->add(new Complex(0, -1));
echo $x, PHP_EOL;
echo PHP_EOL, 'Subtract', PHP_EOL;
$x = new Complex(123);
$x->subtract(456);
echo $x, PHP_EOL;
$x = new Complex(123.456);
$x->subtract(789.012);
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->subtract(new Complex(-987.654, -32.1));
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->subtract(-987.654);
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->subtract(new Complex(0, 1));
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->subtract(new Complex(0, -1));
echo $x, PHP_EOL;
echo PHP_EOL, 'Multiply', PHP_EOL;
$x = new Complex(123);
$x->multiply(456);
echo $x, PHP_EOL;
$x = new Complex(123.456);
$x->multiply(789.012);
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->multiply(new Complex(-987.654, -32.1));
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->multiply(-987.654);
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->multiply(new Complex(0, 1));
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->multiply(new Complex(0, -1));
echo $x, PHP_EOL;
echo PHP_EOL, 'Divide By', PHP_EOL;
$x = new Complex(123);
$x->divideBy(456);
echo $x, PHP_EOL;
$x = new Complex(123.456);
$x->divideBy(789.012);
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->divideBy(new Complex(-987.654, -32.1));
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->divideBy(-987.654);
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->divideBy(new Complex(0, 1));
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->divideBy(new Complex(0, -1));
echo $x, PHP_EOL;
echo PHP_EOL, 'Divide Into', PHP_EOL;
$x = new Complex(123);
$x->divideInto(456);
echo $x, PHP_EOL;
$x = new Complex(123.456);
$x->divideInto(789.012);
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->divideInto(new Complex(-987.654, -32.1));
echo $x, PHP_EOL;
$x = new Complex(123.456, 78.90);
$x->divideInto(-987.654);
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->divideInto(new Complex(0, 1));
echo $x, PHP_EOL;
$x = new Complex(-987.654, -32.1);
$x->divideInto(new Complex(0, -1));
echo $x, PHP_EOL;

View File

@ -0,0 +1,52 @@
<?php
namespace Complex;
include('../classes/Bootstrap.php');
echo 'Function Examples', PHP_EOL;
$functions = array(
'abs',
'acos',
'acosh',
'acsc',
'acsch',
'argument',
'asec',
'asech',
'asin',
'asinh',
'conjugate',
'cos',
'cosh',
'csc',
'csch',
'exp',
'inverse',
'ln',
'log2',
'log10',
'rho',
'sec',
'sech',
'sin',
'sinh',
'sqrt',
'theta'
);
for ($real = -3.5; $real <= 3.5; $real += 0.5) {
for ($imaginary = -3.5; $imaginary <= 3.5; $imaginary += 0.5) {
foreach ($functions as $function) {
$complexFunction = __NAMESPACE__ . '\\' . $function;
$complex = new Complex($real, $imaginary);
try {
echo $function, '(', $complex, ') = ', $complexFunction($complex), PHP_EOL;
} catch (\Exception $e) {
echo $function, '(', $complex, ') ERROR: ', $e->getMessage(), PHP_EOL;
}
}
echo PHP_EOL;
}
}

View File

@ -0,0 +1,34 @@
<?php
use Complex\Complex as Complex;
include('../classes/Bootstrap.php');
$values = [
new Complex(123),
new Complex(456, 123),
new Complex(0.0, 456),
];
foreach ($values as $value) {
echo $value, PHP_EOL;
}
echo 'Addition', PHP_EOL;
$result = \Complex\add(...$values);
echo '=> ', $result, PHP_EOL;
echo PHP_EOL;
echo 'Subtraction', PHP_EOL;
$result = \Complex\subtract(...$values);
echo '=> ', $result, PHP_EOL;
echo PHP_EOL;
echo 'Multiplication', PHP_EOL;
$result = \Complex\multiply(...$values);
echo '=> ', $result, PHP_EOL;

View File

@ -0,0 +1,25 @@
The MIT License (MIT)
=====================
Copyright © `2017` `Mark Baker`
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,165 @@
PHPMatrix
==========
---
PHP Class for handling Matrices
Master: [![Build Status](https://travis-ci.org/MarkBaker/PHPMatrix.png?branch=master)](http://travis-ci.org/MarkBaker/PHPMatrix)
Develop: [![Build Status](https://travis-ci.org/MarkBaker/PHPMatrix.png?branch=develop)](http://travis-ci.org/MarkBaker/PHPMatrix)
[![Matrix Transform](https://imgs.xkcd.com/comics/matrix_transform.png)](https://xkcd.com/184/)
Matrix Transform
---
This library currently provides the following operations:
- addition
- direct sum
- subtraction
- multiplication
- division (using [A].[B]<sup>-1</sup>)
- division by
- division into
together with functions for
- adjoint
- antidiagonal
- cofactors
- determinant
- diagonal
- identity
- inverse
- minors
- trace
- transpose
## TO DO
- power()
- EigenValues
- EigenVectors
- Decomposition
---
# Usage
To create a new Matrix object, provide an array as the constructor argument
```
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
[ 9, 6, 7, 12],
[ 4, 15, 14, 1],
];
$matrix = new Matrix\Matrix($grid);
```
The `Builder` class provides helper methods for creating specific matrices, specifically an identity matrix of a specified size; or a matrix of a specified dimensions, with every cell containing a set value.
```
$matrix = new Matrix\Builder::createFilledMatrix(1, 5, 3);
```
Will create a matrix of 5 rows and 3 columns, filled with a `1` in every cell; while
```
$matrix = new Matrix\Builder::createIdentityMatrix(3);
```
will create a 3x3 identity matrix.
Matrix objects are immutable: whenever you call a method or pass a grid to a function that returns a matrix value, a new Matrix object will be returned, and the original will remain unchanged. This also allows you to chain multiple methods as you would for a fluent interface (as long as they are methods that will return a Matrix result).
## Performing Mathematical Operations
To perform mathematical operations with Matrices, you can call the appropriate method against a matrix value, passing other values as arguments
```
$matrix1 = new Matrix([
[2, 7, 6],
[9, 5, 1],
[4, 3, 8],
]);
$matrix2 = new Matrix([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
echo $matrix1->multiply($matrix2);
```
or pass all values to the appropriate function
```
$matrix1 = new Matrix([
[2, 7, 6],
[9, 5, 1],
[4, 3, 8],
]);
$matrix2 = new Matrix([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]);
echo Matrix\multiply($matrix1, $matrix2);
```
You can pass in the arguments as Matrix objects, or as arrays.
If you want to perform the same operation against multiple values (e.g. to add three or more matrices), then you can pass multiple arguments to any of the operations.
## Using functions
When calling any of the available functions for a matrix value, you can either call the relevant method for the Matrix object
```
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
[ 9, 6, 7, 12],
[ 4, 15, 14, 1],
];
$matrix = new Matrix\Matrix($grid);
echo $matrix->trace();
```
or you can call the function as you would in procedural code, passing the Matrix object as an argument
```
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
[ 9, 6, 7, 12],
[ 4, 15, 14, 1],
];
$matrix = new Matrix\Matrix($grid);
echo Matrix\trace($matrix);
```
When called procedurally using the function, you can pass in the argument as a Matrix object, or as an array.
```
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
[ 9, 6, 7, 12],
[ 4, 15, 14, 1],
];
echo Matrix\trace($grid);
```
As an alternative, it is also possible to call the method directly from the `Functions` class.
```
$grid = [
[16, 3, 2, 13],
[ 5, 10, 11, 8],
[ 9, 6, 7, 12],
[ 4, 15, 14, 1],
];
$matrix = new Matrix\Matrix($grid);
echo Matrix\Functions::trace($matrix);
```
Used this way, methods must be called statically, and the argument must be the Matrix object, and cannot be an array.

View File

@ -0,0 +1,62 @@
<?php
# required: PHP 5.3+ and zlib extension
// ini option check
if (ini_get('phar.readonly')) {
echo "php.ini: set the 'phar.readonly' option to 0 to enable phar creation\n";
exit(1);
}
// output name
$pharName = 'Matrix.phar';
// target folder
$sourceDir = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR;
// default meta information
$metaData = array(
'Author' => 'Mark Baker <mark@lange.demon.co.uk>',
'Description' => 'PHP Class for working with Matrix numbers',
'Copyright' => 'Mark Baker (c) 2013-' . date('Y'),
'Timestamp' => time(),
'Version' => '0.1.0',
'Date' => date('Y-m-d')
);
// cleanup
if (file_exists($pharName)) {
echo "Removed: {$pharName}\n";
unlink($pharName);
}
echo "Building phar file...\n";
// the phar object
$phar = new Phar($pharName, null, 'Matrix');
$phar->buildFromDirectory($sourceDir);
$phar->setStub(
<<<'EOT'
<?php
spl_autoload_register(function ($className) {
include 'phar://' . $className . '.php';
});
try {
Phar::mapPhar();
} catch (PharException $e) {
error_log($e->getMessage());
exit(1);
}
include 'phar://functions/sqrt.php';
__HALT_COMPILER();
EOT
);
$phar->setMetadata($metaData);
$phar->compressFiles(Phar::GZ);
echo "Complete.\n";
exit();

View File

@ -0,0 +1,53 @@
<?php
namespace Matrix;
/**
*
* Autoloader for Matrix classes
*
* @package Matrix
* @copyright Copyright (c) 2014 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
* @license https://opensource.org/licenses/MIT MIT
*/
class Autoloader
{
/**
* Register the Autoloader with SPL
*
*/
public static function Register()
{
if (function_exists('__autoload')) {
// Register any existing autoloader function with SPL, so we don't get any clashes
spl_autoload_register('__autoload');
}
// Register ourselves with SPL
return spl_autoload_register(['Matrix\\Autoloader', 'Load']);
}
/**
* Autoload a class identified by name
*
* @param string $pClassName Name of the object to load
*/
public static function Load($pClassName)
{
if ((class_exists($pClassName, false)) || (strpos($pClassName, 'Matrix\\') !== 0)) {
// Either already loaded, or not a Matrix class request
return false;
}
$pClassFilePath = __DIR__ . DIRECTORY_SEPARATOR .
'src' . DIRECTORY_SEPARATOR .
str_replace(['Matrix\\', '\\'], ['', '/'], $pClassName) .
'.php';
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
// Can't load
return false;
}
require($pClassFilePath);
}
}

View File

@ -0,0 +1,38 @@
<?php
include_once __DIR__ . '/Autoloader.php';
\Matrix\Autoloader::Register();
abstract class FilesystemRegexFilter extends RecursiveRegexIterator
{
protected $regex;
public function __construct(RecursiveIterator $it, $regex)
{
$this->regex = $regex;
parent::__construct($it, $regex);
}
}
class FilenameFilter extends FilesystemRegexFilter
{
// Filter files against the regex
public function accept()
{
return (!$this->isFile() || preg_match($this->regex, $this->getFilename()));
}
}
$srcFolder = __DIR__ . DIRECTORY_SEPARATOR . 'src';
$srcDirectory = new RecursiveDirectoryIterator($srcFolder);
$filteredFileList = new FilenameFilter($srcDirectory, '/(?:php)$/i');
$filteredFileList = new FilenameFilter($filteredFileList, '/^(?!.*(Matrix|Exception)\.php).*$/i');
foreach (new RecursiveIteratorIterator($filteredFileList) as $file) {
if ($file->isFile()) {
include_once $file;
}
}

Some files were not shown because too many files have changed in this diff Show More