From 838c4a43d23d02a2338b5a27fcb0408ba40d7045 Mon Sep 17 00:00:00 2001 From: Ivan Dudarev Date: Wed, 15 Jul 2020 19:36:05 +0700 Subject: [PATCH] version 1.0.0 --- .github/CODE_OF_CONDUCT.md | 46 +++ .github/CONTRIBUTING.md | 12 + .github/FUNDING.yml | 1 + .github/ISSUE_TEMPLATE/bug_report.md | 22 ++ .github/ISSUE_TEMPLATE/custom.md | 8 + .github/ISSUE_TEMPLATE/feature_request.md | 20 ++ .github/PULL_REQUEST_TEMPLATE.md | 5 + .gitignore | 4 + LICENSE | 19 ++ README.md | 48 +++ composer.json | 41 +++ fn.php | 93 ++++++ phpcs.xml.dist | 18 ++ phpunit.xml.dist | 8 + src/Form.php | 376 ++++++++++++++++++++++ src/Wizard.php | 33 ++ tests/FormTest.php | 271 ++++++++++++++++ tests/WizardTest.php | 44 +++ 18 files changed, 1069 insertions(+) create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/custom.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 composer.json create mode 100644 fn.php create mode 100644 phpcs.xml.dist create mode 100644 phpunit.xml.dist create mode 100644 src/Form.php create mode 100644 src/Wizard.php create mode 100644 tests/FormTest.php create mode 100644 tests/WizardTest.php diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b80343e --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ivan@ddrv.ru. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..51838e4 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing + +## Report an issue + +Please follow the guidelines below when creating an issue so that your issue can be more promptly resolved: +* Provide information including: the version of PHP and This package, the type of operating system and Web server; +* Provide the complete error call stack if available; +* Describe the steps for reproducing the issue. It would be even better if you could provide code to reproduce the issue; + +Do not report an issue if you are asking how to use some feature. You should use the `README.md` file. + +Before you report an issue, please search through existing issues to see if your issue is already reported or fixed to make sure you are not reporting a duplicated issue. Also make sure you have the latest version of package and see if the issue still exists. \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..67705ab --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +custom: "https://www.paypal.me/ddrv" \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..be4328f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,22 @@ +--- +name: Bug report +about: Create a report to help us improve +title: 'Bug' +labels: bug +assignees: ddrv + +--- + +### What steps will reproduce the problem? + +### What is the expected result? + +### What do you get instead? + +### Additional info + +| Q | A +| ---------------- | --- +| Library version | 1.? +| PHP version | ? +| Operating system | ? diff --git a/.github/ISSUE_TEMPLATE/custom.md b/.github/ISSUE_TEMPLATE/custom.md new file mode 100644 index 0000000..b2ffc55 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/custom.md @@ -0,0 +1,8 @@ +--- +name: Custom issue template +about: Describe this issue template's purpose here. +title: '' +labels: '' +assignees: ddrv + +--- diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..fa05c62 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: feature +assignees: ddrv + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..3380d2b --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ +| Q | A +| ------------- | --- +| Bug fix? | yes/no +| New feature? | yes/no +| Tickets | Fix #... \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..776c153 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +vendor/ +composer.lock +phpcs.xml +phpunit.xml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9341a54 --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2020 Ivan Dudarev, https://github.com/ddrv + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..284cda1 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +[![Latest Stable Version](https://img.shields.io/packagist/v/webclient/helper-form.svg?style=flat-square)](https://packagist.org/packages/webclient/helper-form) +[![Total Downloads](https://img.shields.io/packagist/dt/webclient/helper-form.svg?style=flat-square)](https://packagist.org/packages/webclient/helper-form/stats) +[![License](https://img.shields.io/packagist/l/webclient/helper-form.svg?style=flat-square)](https://github.com/phpwebclient/helper-form/blob/master/LICENSE) +[![PHP](https://img.shields.io/packagist/php-v/webclient/helper-form.svg?style=flat-square)](https://php.net) + +# webclient/helper-form + +Helper for creating PSR-7 request with files. + +# Install + +Install this package and your favorite [psr-17 implementation](https://packagist.org/providers/psr/http-factory-implementation). + +```bash +composer require webclient/helper-form:^1.0 +``` + +> Now it’s very easy to create file requests for PSR-18 HTTP Clients! + +# Using + +```php +createForm('http://localhost:8080/path?query=webclient#fragment', 'POST') + ->addField('sign_up[login]', 'user42') + ->addField('sign_up[password]', '$ecr3t') + ->uploadFromString('about', 'hi!', 'about.txt', 'text/plain; charset=UTF-8') + ->uploadFromFile('photo', '/home/user42/images/DCIM_4564.JPEG', 'image/jpeg', 'avatar.jpg') + ->uploadFromResource('public_ssh_key', $fh, 'id_sra.pub', 'text/plain') + ->createRequest() +; +``` diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..f0ec57d --- /dev/null +++ b/composer.json @@ -0,0 +1,41 @@ +{ + "name": "webclient/helper-form", + "type": "library", + "description": "Helper for creating PSR-7 request with files", + "keywords": ["http", "client", "psr7", "psr-7", "helper"], + "license": "MIT", + "authors": [ + { + "name": "Ivan Dudarev", + "email": "ivan@ddrv.ru", + "homepage": "https://ddrv.ru" + } + ], + "require": { + "php": ">=7.0", + "psr/http-message": "^1.0", + "psr/http-factory": "^1.0" + }, + "require-dev": { + "nyholm/psr7": "^1.3", + "phpunit/phpunit": "^6.5", + "squizlabs/php_codesniffer": "^3.5" + }, + "suggest": { + "ext-fileinfo": "Need for defining mime types", + "psr/http-factory-implementation": "Choice your favorite psr-17 implementation" + }, + "autoload": { + "psr-4": { + "Webclient\\Helper\\Form\\": "src/" + }, + "files": [ + "fn.php" + ] + }, + "autoload-dev": { + "psr-4": { + "Tests\\Webclient\\Helper\\Form\\": "tests/" + } + } +} diff --git a/fn.php b/fn.php new file mode 100644 index 0000000..d4bffbf --- /dev/null +++ b/fn.php @@ -0,0 +1,93 @@ + 'text/plain', + 'htm' => 'text/html', + 'html' => 'text/html', + 'php' => 'text/html', + 'css' => 'text/css', + 'js' => 'application/javascript', + 'json' => 'application/json', + 'xml' => 'application/xml', + 'swf' => 'application/x-shockwave-flash', + 'flv' => 'video/x-flv', + + // images + 'png' => 'image/png', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'gif' => 'image/gif', + 'bmp' => 'image/bmp', + 'ico' => 'image/vnd.microsoft.icon', + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'svg' => 'image/svg+xml', + 'svgz' => 'image/svg+xml', + + // archives + 'zip' => 'application/zip', + 'rar' => 'application/x-rar-compressed', + 'exe' => 'application/x-msdownload', + 'msi' => 'application/x-msdownload', + 'cab' => 'application/vnd.ms-cab-compressed', + + // audio/video + 'mp3' => 'audio/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + + // adobe + 'pdf' => 'application/pdf', + 'psd' => 'image/vnd.adobe.photoshop', + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + + // ms office + 'doc' => 'application/msword', + 'rtf' => 'application/rtf', + 'xls' => 'application/vnd.ms-excel', + 'ppt' => 'application/vnd.ms-powerpoint', + + // open office + 'odt' => 'application/vnd.oasis.opendocument.text', + 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', + ]; + $arr = explode('.', $filename); + $ext = strtolower(array_pop($arr)); + if (array_key_exists($ext, $types)) { + return $types[$ext]; + } + return 'application/octet-stream'; + } +} + +function mime(string $file) +{ + if (file_exists($file)) { + return mime_content_type($file); + } + if (function_exists('finfo_open')) { + /** @noinspection PhpComposerExtensionStubsInspection */ + $info = finfo_open(FILEINFO_MIME); + /** @noinspection PhpComposerExtensionStubsInspection */ + $mime = finfo_buffer($info, $file); + /** @noinspection PhpComposerExtensionStubsInspection */ + finfo_close($info); + return $mime; + } + return 'application/octet-stream'; +} diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..7d9a4eb --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,18 @@ + + + Coding standard + + + + + + + + + + + + + src + tests + \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..66b98f0 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + tests + + + \ No newline at end of file diff --git a/src/Form.php b/src/Form.php new file mode 100644 index 0000000..cc6ff58 --- /dev/null +++ b/src/Form.php @@ -0,0 +1,376 @@ +checkUri($uri); + $this->requestFactory = $requestFactory; + $this->streamFactory = $streamFactory; + $this->uri = $uri; + $this->method = $method; + $this->idx = [ + 'fields' => [], + 'files' => [], + ]; + } + + /** + * @param string $field + * @param string $value + * @return $this + */ + public function addField(string $field, string $value): self + { + $field = $this->prepareField($field, 'field'); + $this->fields[$field][] = $value; + return $this; + } + + /** + * @param string $field + * @param string $content + * @param string $filename + * @param string $mime + * @return $this + */ + public function uploadFromString(string $field, string $content, string $filename, string $mime = ''): self + { + if (!$mime) { + $mime = mime($content); + } + $resource = fopen('php://temp', 'rw+'); + fwrite($resource, $content); + return $this->uploadFromResource($field, $resource, $filename, $mime); + } + + /** + * @param string $field + * @param string $path + * @param string $mime + * @param string $filename + * @return $this + */ + public function uploadFromFile(string $field, string $path, string $mime = '', string $filename = ''): self + { + if (!$filename) { + $filename = pathinfo($path, PATHINFO_BASENAME); + } + if (!$mime) { + $mime = mime($path); + } + return $this->uploadFromResource($field, fopen($path, 'rb+'), $filename, $mime); + } + + /** + * @param string $field + * @param resource $resource + * @param string $filename + * @param string $mime + * @return $this + */ + public function uploadFromResource(string $field, $resource, string $filename, string $mime = ''): self + { + if (!is_resource($resource)) { + throw new InvalidArgumentException('parameter $resource must be a resource'); + } + if (!$mime) { + rewind($resource); + $mime = mime(fread($resource, 4096)); + rewind($resource); + } + if ($mime === 'application/octet-stream') { + $mime = mime($filename); + } + $field = $this->prepareField($field, 'field'); + $this->files[$field][] = [ + 'name' => $filename, + 'mime' => $mime, + 'resource' => $resource, + ]; + return $this; + } + + /** + * @return RequestInterface + */ + public function createRequest(): RequestInterface + { + $resource = fopen('php://temp', 'rw+'); + $queryMethods = ['GET', 'HEAD', 'OPTIONS']; + if (empty($this->files) || in_array($this->method, $queryMethods)) { + $contentType = 'application/x-www-form-urlencoded'; + $this->fillSimple($resource); + } else { + $this->prepareBoundary(); + $contentType = 'multipart/form-data; boundary="' . $this->boundary . '"'; + $this->fillMultipart($resource); + } + $body = null; + $uri = $this->uri; + if (in_array($this->method, $queryMethods)) { + $contentType = null; + rewind($resource); + $line = ''; + while (!feof($resource)) { + $line .= fread($resource, 1024); + } + $query = []; + parse_str($line, $query); + list($uri, $fragment) = array_replace(['', ''], explode('#', $uri)); + list($uri, $temp) = array_replace(['', ''], explode('?', $uri)); + $get = []; + parse_str($temp, $get); + $query = array_replace($get, $query); + if ($query) { + $uri .= '?' . http_build_query($query); + } + if ($fragment) { + $uri .= '#' . $fragment; + } + fclose($resource); + } else { + $body = $this->streamFactory->createStreamFromResource($resource); + $body->rewind(); + } + $request = $this->requestFactory->createRequest($this->method, $uri); + if ($contentType) { + $request = $request->withHeader('Content-Type', [$contentType]); + } + if ($body) { + $request = $request + ->withHeader('Content-Length', [(string)$body->getSize()]) + ->withBody($body) + ; + } + return $request; + } + + /** + * @param string $field + * @param string $type + * @return string + */ + private function prepareField(string $field, string $type): string + { + $field = preg_replace('/\[\s+/ui', '[', $field); + $field = preg_replace('/\s+]/ui', ']', $field); + $key = $type . 's'; + if (strpos($field, '[]') === false) { + if (array_key_exists($field, $this->idx[$key])) { + throw new InvalidArgumentException($type . ' ' . $field . ' already exists'); + } + $this->idx[$key][$field] = true; + } + return $field; + } + + /** + * @param resource $body + */ + private function fillMultipart($body) + { + $eol = "\r\n"; + fwrite($body, $eol); + foreach ($this->fields as $field => $values) { + foreach ($values as $value) { + fwrite($body, '--' . $this->boundary . $eol); + fwrite($body, 'Content-Disposition: form-data; name="' . addslashes($field) . '"' . $eol); + fwrite($body, $eol . $value . $eol); + } + } + + foreach ($this->files as $field => $values) { + foreach ($values as $value) { + $disposition = 'Content-Disposition: form-data; name="' . addslashes($field) . '"; '; + $disposition .= 'filename="' . addslashes($value['name']) . '"'; + + fwrite($body, '--' . $this->boundary . $eol); + fwrite($body, $disposition . $eol); + fwrite($body, 'Content-Type: ' . $value['mime'] . $eol . $eol); + rewind($value['resource']); + while (!feof($value['resource'])) { + fwrite($body, fread($value['resource'], 1024)); + } + fwrite($body, $eol); + } + } + fwrite($body, '--' . $this->boundary . '--' . $eol); + } + + /** + * @param resource $body + */ + private function fillSimple($body) + { + $result = ''; + foreach ($this->fields as $field => $values) { + foreach ($values as $value) { + $result .= urlencode($field) . '=' . urlencode($value) . '&'; + } + } + if (!$result) { + return; + } + fwrite($body, substr($result, 0, -1)); + } + + private function prepareBoundary() + { + $generate = false; + do { + $boundary = md5((string)rand(0, PHP_INT_MAX)); + foreach ($this->fields as $field => $values) { + if ($generate) { + continue; + } + if ($this->isContainBoundary($field, $boundary)) { + $generate = true; + continue; + } + foreach ($values as $value) { + if ($generate) { + continue; + } + if ($this->isContainBoundary($value, $boundary)) { + $generate = true; + continue; + } + } + } + foreach ($this->files as $field => $values) { + if ($generate) { + continue; + } + if ($this->isContainBoundary($field, $boundary)) { + $generate = true; + } + foreach ($values as $value) { + if ($generate) { + continue; + } + if ($this->isContainBoundary($value['name'], $boundary)) { + $generate = true; + continue; + } + if ($this->isContainBoundary($value['mime'], $boundary)) { + $generate = true; + continue; + } + $resource = $value['resource']; + $lines = ['']; + rewind($resource); + while (!feof($resource) && !$generate) { + $lines[] = fread($resource, 512); + $data = implode('', $lines); + if ($this->isContainBoundary($data, $boundary)) { + $generate = true; + } + array_shift($lines); + } + rewind($resource); + } + } + } while ($generate); + $this->boundary = $boundary; + } + + private function isContainBoundary(string $data, string $boundary): bool + { + return strlen($data) > 33 && strpos($data, '--' . $boundary) !== false; + } + + private function checkUri(string $uri) + { + $arr = parse_url($uri); + if ( + !is_array($arr) + || !array_key_exists('scheme', $arr) + || !$arr['scheme'] + || !array_key_exists('host', $arr) + || !$arr['host'] + ) { + throw new InvalidArgumentException('uri must contains scheme and host'); + } + } +} diff --git a/src/Wizard.php b/src/Wizard.php new file mode 100644 index 0000000..aef93d8 --- /dev/null +++ b/src/Wizard.php @@ -0,0 +1,33 @@ +requestFactory = $requestFactory; + $this->streamFactory = $streamFactory; + } + + public function createForm(string $uri, string $method = 'GET'): Form + { + return new Form($this->requestFactory, $this->streamFactory, $uri, $method); + } +} diff --git a/tests/FormTest.php b/tests/FormTest.php new file mode 100644 index 0000000..63fbf5c --- /dev/null +++ b/tests/FormTest.php @@ -0,0 +1,271 @@ +responseFactory = $factory; + $this->streamFactory = $factory; + } + + /** + * @param string $method + * @param string $uri + * @param string $error + * @dataProvider provideConstruct + */ + public function testConstruct(string $method, string $uri, string $error) + { + if ($error) { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($error); + } + $form = $this->getForm($uri, $method); + $this->assertInstanceOf(Form::class, $form); + $request = $form->createRequest(); + $this->assertSame($method, $request->getMethod()); + $this->assertSame($uri, $request->getUri()->__toString()); + } + + public function testAddFieldPost() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'POST'); + $form->addField('auth[user]', 'phpunit'); + $form->addField('auth[pass]', 'secret'); + $request = $form->createRequest(); + $this->assertSame('auth%5Buser%5D=phpunit&auth%5Bpass%5D=secret', $request->getBody()->__toString()); + $this->assertSame('http://localhost:8000/path?query=yes#fragment', $request->getUri()->__toString()); + } + + public function testUploadFromString() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'POST'); + $content = 'hello, world!'; + $form->uploadFromString('files[]', $content, 'readme.txt', 'text/plain; charset=UTF-8'); + $request = $form->createRequest(); + $pattern = '/multipart\/form-data\s*;\s*boundary=\"(?[a-f0-9]{32})\"/ui'; + preg_match($pattern, $request->getHeaderLine('Content-Type'), $matches); + $this->assertArrayHasKey('boundary', $matches); + $boundary = $matches['boundary']; + $body = "\r\n--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"readme.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$content\r\n--$boundary--\r\n"; + $this->assertSame($body, $request->getBody()->__toString()); + $this->assertSame('http://localhost:8000/path?query=yes#fragment', $request->getUri()->__toString()); + } + + public function testUploadFromFile() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'POST'); + $file = dirname(__DIR__) . '/LICENSE'; + $content = file_get_contents($file); + $form->uploadFromFile('files[]', $file, 'text/plain; charset=UTF-8'); + $request = $form->createRequest(); + $pattern = '/multipart\/form-data\s*;\s*boundary=\"(?[a-f0-9]{32})\"/ui'; + preg_match($pattern, $request->getHeaderLine('Content-Type'), $matches); + $this->assertArrayHasKey('boundary', $matches); + $boundary = $matches['boundary']; + $body = "\r\n--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"LICENSE\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$content\r\n--$boundary--\r\n"; + $this->assertSame($body, $request->getBody()->__toString()); + $this->assertSame('http://localhost:8000/path?query=yes#fragment', $request->getUri()->__toString()); + } + + public function testUploadFromResource() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'POST'); + $content = 'hello, world!'; + $resource = fopen('php://temp', 'rw+'); + $form->uploadFromResource('files[]', $resource, 'readme.txt', 'text/plain; charset=UTF-8'); + fwrite($resource, $content); + $request = $form->createRequest(); + $pattern = '/multipart\/form-data\s*;\s*boundary=\"(?[a-f0-9]{32})\"/ui'; + preg_match($pattern, $request->getHeaderLine('Content-Type'), $matches); + $this->assertArrayHasKey('boundary', $matches); + $boundary = $matches['boundary']; + $body = "\r\n--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"readme.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$content\r\n--$boundary--\r\n"; + $this->assertSame($body, $request->getBody()->__toString()); + $this->assertSame('http://localhost:8000/path?query=yes#fragment', $request->getUri()->__toString()); + } + + public function testAllUploads() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'POST'); + $string = 'hello, world! I am created from string!'; + $form->uploadFromString('files[]', $string, 'string.txt', 'text/plain; charset=UTF-8'); + + $path = dirname(__DIR__) . '/LICENSE'; + $file = file_get_contents($path); + $form->uploadFromFile('files[]', $path, 'text/plain; charset=UTF-8', 'file.txt'); + + $resource = 'hello, world! I am created from resource!'; + $fh = fopen('php://temp', 'rw+'); + fwrite($fh, $resource); + $form->uploadFromResource('files[]', $fh, 'resource.txt', 'text/plain; charset=UTF-8'); + + $request = $form->createRequest(); + $pattern = '/multipart\/form-data\s*;\s*boundary=\"(?[a-f0-9]{32})\"/ui'; + preg_match($pattern, $request->getHeaderLine('Content-Type'), $matches); + $this->assertArrayHasKey('boundary', $matches); + $boundary = $matches['boundary']; + + $body = "\r\n--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"string.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$string\r\n"; + + $body .= "--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"file.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$file\r\n"; + + $body .= "--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"resource.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$resource\r\n"; + + $body .= "--$boundary--\r\n"; + + $this->assertSame($body, $request->getBody()->__toString()); + $this->assertSame('http://localhost:8000/path?query=yes#fragment', $request->getUri()->__toString()); + } + + public function testAllUploadsAndFieldsPost() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'POST'); + + $form->addField('auth[user]', 'phpunit'); + $form->addField('auth[pass]', 'secret'); + + $string = 'hello, world! I am created from string!'; + $form->uploadFromString('files[]', $string, 'string.txt', 'text/plain; charset=UTF-8'); + + $path = dirname(__DIR__) . '/LICENSE'; + $file = file_get_contents($path); + $form->uploadFromFile('files[]', $path, 'text/plain; charset=UTF-8', 'file.txt'); + + $resource = 'hello, world! I am created from resource!'; + $fh = fopen('php://temp', 'rw+'); + fwrite($fh, $resource); + $form->uploadFromResource('files[]', $fh, 'resource.txt', 'text/plain; charset=UTF-8'); + + $request = $form->createRequest(); + $pattern = '/multipart\/form-data\s*;\s*boundary=\"(?[a-f0-9]{32})\"/ui'; + preg_match($pattern, $request->getHeaderLine('Content-Type'), $matches); + $this->assertArrayHasKey('boundary', $matches); + $boundary = $matches['boundary']; + + $body = "\r\n--$boundary\r\nContent-Disposition: form-data; name=\"auth[user]\"\r\n\r\nphpunit\r\n"; + $body .= "--$boundary\r\nContent-Disposition: form-data; name=\"auth[pass]\"\r\n\r\nsecret\r\n"; + + $body .= "--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"string.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$string\r\n"; + + $body .= "--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"file.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$file\r\n"; + + $body .= "--$boundary\r\nContent-Disposition: form-data; name=\"files[]\"; filename=\"resource.txt\"\r\n"; + $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n$resource\r\n"; + + $body .= "--$boundary--\r\n"; + + $this->assertSame($body, $request->getBody()->__toString()); + $this->assertSame('http://localhost:8000/path?query=yes#fragment', $request->getUri()->__toString()); + } + + public function testAllUploadsAndFieldsGet() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'GET'); + + $form->addField('auth[user]', 'phpunit'); + $form->addField('auth[pass]', 'secret'); + + $string = 'hello, world! I am created from string!'; + $form->uploadFromString('files[]', $string, 'string.txt', 'text/plain; charset=UTF-8'); + + $path = dirname(__DIR__) . '/LICENSE'; + $form->uploadFromFile('files[]', $path, 'text/plain; charset=UTF-8', 'file.txt'); + + $resource = 'hello, world! I am created from resource!'; + $fh = fopen('php://temp', 'rw+'); + fwrite($fh, $resource); + $form->uploadFromResource('files[]', $fh, 'resource.txt', 'text/plain; charset=UTF-8'); + + $request = $form->createRequest(); + + $this->assertSame('', $request->getBody()->__toString()); + $merged = 'http://localhost:8000/path?query=yes&auth%5Buser%5D=phpunit&auth%5Bpass%5D=secret#fragment'; + $this->assertSame($merged, $request->getUri()->__toString()); + } + + public function testAddFieldGet() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'GET'); + $form->addField('auth[user]', 'phpunit'); + $form->addField('auth[pass]', 'secret'); + $request = $form->createRequest(); + $this->assertSame('', $request->getBody()->__toString()); + $merged = 'http://localhost:8000/path?query=yes&auth%5Buser%5D=phpunit&auth%5Bpass%5D=secret#fragment'; + $this->assertSame($merged, $request->getUri()->__toString()); + } + + public function testDoubleAddField() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'GET'); + $form->addField('auth[user]', 'phpunit'); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('field auth[user] already exists'); + $form->addField('auth[user]', 'phpunit'); + } + + public function testDoubleAddFieldArray() + { + $form = $this->getForm('http://localhost:8000/path?query=yes#fragment', 'GET'); + $form->addField('auth[user][]', 'phpunit'); + $form->addField('auth[user][]', 'phpunit'); + $this->assertTrue(true); + } + + public function provideConstruct() + { + return [ + ['GET', 'http://localhost:8000/path?query=yes#fragment', ''], + ['HEAD', 'http://localhost:8000/path?query=yes#fragment', ''], + ['OPTIONS', 'http://localhost:8000/path?query=yes', ''], + ['POST', 'http://localhost:8000/path', ''], + ['PUT', '/path?query=yes#fragment', 'uri must contains scheme and host'], + ['PATCH', 'http://localhost', ''], + ['DELETE', 'localhost:8000', 'uri must contains scheme and host'], + ['TRACE', 'http://', 'uri must contains scheme and host'], + ]; + } + + private function getForm(string $uri, string $method): Form + { + return new Form($this->responseFactory, $this->streamFactory, $uri, $method); + } +} diff --git a/tests/WizardTest.php b/tests/WizardTest.php new file mode 100644 index 0000000..65f5229 --- /dev/null +++ b/tests/WizardTest.php @@ -0,0 +1,44 @@ +createForm($uri, $method); + $this->assertInstanceOf(Form::class, $form); + $request = $form->createRequest(); + $this->assertSame($method, $request->getMethod()); + $this->assertSame($uri, $request->getUri()->__toString()); + } + + public function provideCreateForm() + { + return [ + ['GET', 'http://localhost:8000/path?query=yes#fragment'], + ['HEAD', 'http://localhost:8000/path?query=yes#fragment'], + ['OPTIONS', 'http://localhost:8000/path?query=yes#fragment'], + ['POST', 'http://localhost:8000/path?query=yes#fragment'], + ['PUT', 'http://localhost:8000/path?query=yes'], + ['PATCH', 'http://localhost:8000/path'], + ['DELETE', 'http://localhost:8000'], + ['TRACE', 'http://localhost'], + ]; + } +}