From 8013fb4fce9d9ec5345fbbaad5130c5e86a4e16e Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 31 Aug 2012 14:44:59 -0500 Subject: [PATCH 1/2] [zendframework/zf2#2284][ZF2-507] Updated README - Notice about Date header --- .coveralls.yml | 3 + .gitattributes | 6 + .gitignore | 14 + .php_cs | 43 ++ .travis.yml | 35 ++ CONTRIBUTING.md | 229 ++++++++ LICENSE.txt | 27 + README.md | 11 + composer.json | 29 + phpunit.xml.dist | 34 ++ phpunit.xml.travis | 34 ++ src/Adapter/AbstractAdapter.php | 93 ++++ src/Adapter/Console.php | 516 ++++++++++++++++++ src/Adapter/Exception/ExceptionInterface.php | 23 + .../Exception/InvalidArgumentException.php | 23 + src/Adapter/Exception/RuntimeException.php | 23 + src/Adapter/JsPull.php | 99 ++++ src/Adapter/JsPush.php | 130 +++++ src/Exception/ExceptionInterface.php | 21 + src/Exception/InvalidArgumentException.php | 21 + src/Exception/OutOfRangeException.php | 21 + src/Exception/RuntimeException.php | 20 + src/ProgressBar.php | 200 +++++++ test/Adapter/ConsoleTest.php | 316 +++++++++++ test/Adapter/JsPullTest.php | 62 +++ test/Adapter/JsPushTest.php | 63 +++ test/Adapter/MockupStream.php | 102 ++++ test/ProgressBarTest.php | 189 +++++++ test/bootstrap.php | 34 ++ 29 files changed, 2421 insertions(+) create mode 100644 .coveralls.yml create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .php_cs create mode 100644 .travis.yml create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 composer.json create mode 100644 phpunit.xml.dist create mode 100644 phpunit.xml.travis create mode 100644 src/Adapter/AbstractAdapter.php create mode 100644 src/Adapter/Console.php create mode 100644 src/Adapter/Exception/ExceptionInterface.php create mode 100644 src/Adapter/Exception/InvalidArgumentException.php create mode 100644 src/Adapter/Exception/RuntimeException.php create mode 100644 src/Adapter/JsPull.php create mode 100644 src/Adapter/JsPush.php create mode 100644 src/Exception/ExceptionInterface.php create mode 100644 src/Exception/InvalidArgumentException.php create mode 100644 src/Exception/OutOfRangeException.php create mode 100644 src/Exception/RuntimeException.php create mode 100644 src/ProgressBar.php create mode 100644 test/Adapter/ConsoleTest.php create mode 100644 test/Adapter/JsPullTest.php create mode 100644 test/Adapter/JsPushTest.php create mode 100644 test/Adapter/MockupStream.php create mode 100644 test/ProgressBarTest.php create mode 100644 test/bootstrap.php diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 0000000..53bda82 --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1,3 @@ +coverage_clover: clover.xml +json_path: coveralls-upload.json +src_dir: src diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..85dc9a8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +/test export-ignore +/vendor export-ignore +.gitattributes export-ignore +.gitignore export-ignore +.travis.yml export-ignore +.php_cs export-ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4cac0a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.buildpath +.DS_Store +.idea +.project +.settings/ +.*.sw* +.*.un~ +nbproject +tmp/ + +clover.xml +coveralls-upload.json +phpunit.xml +vendor diff --git a/.php_cs b/.php_cs new file mode 100644 index 0000000..bf4b799 --- /dev/null +++ b/.php_cs @@ -0,0 +1,43 @@ +notPath('TestAsset') + ->notPath('_files') + ->filter(function (SplFileInfo $file) { + if (strstr($file->getPath(), 'compatibility')) { + return false; + } + }); +$config = Symfony\CS\Config\Config::create(); +$config->level(null); +$config->fixers( + array( + 'braces', + 'duplicate_semicolon', + 'elseif', + 'empty_return', + 'encoding', + 'eof_ending', + 'function_call_space', + 'function_declaration', + 'indentation', + 'join_function', + 'line_after_namespace', + 'linefeed', + 'lowercase_keywords', + 'parenthesis', + 'multiple_use', + 'method_argument_space', + 'object_operator', + 'php_closing_tag', + 'psr0', + 'remove_lines_between_uses', + 'short_tag', + 'standardize_not_equal', + 'trailing_spaces', + 'unused_use', + 'visibility', + 'whitespacy_lines', + ) +); +$config->finder($finder); +return $config; diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..fe909ec --- /dev/null +++ b/.travis.yml @@ -0,0 +1,35 @@ +sudo: false + +language: php + +matrix: + fast_finish: true + include: + - php: 5.5 + - php: 5.6 + env: + - EXECUTE_TEST_COVERALLS=true + - EXECUTE_CS_CHECK=true + - php: 7 + - php: hhvm + allow_failures: + - php: 7 + - php: hhvm + +notifications: + irc: "irc.freenode.org#zftalk.dev" + email: false + +before_install: + - if [[ $EXECUTE_TEST_COVERALLS != 'true' ]]; then phpenv config-rm xdebug.ini || return 0 ; fi + +install: + - composer install --no-interaction --prefer-source + +script: + - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/phpunit -c phpunit.xml.travis --coverage-clover clover.xml ; fi + - if [[ $EXECUTE_TEST_COVERALLS != 'true' ]]; then ./vendor/bin/phpunit -c phpunit.xml.travis ; fi + - if [[ $EXECUTE_CS_CHECK == 'true' ]]; then ./vendor/bin/php-cs-fixer fix -v --diff --dry-run --config-file=.php_cs ; fi + +after_script: + - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/coveralls ; fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..09d13df --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,229 @@ +# CONTRIBUTING + +## RESOURCES + +If you wish to contribute to Zend Framework, please be sure to +read/subscribe to the following resources: + + - [Coding Standards](https://github.com/zendframework/zf2/wiki/Coding-Standards) + - [Contributor's Guide](http://framework.zend.com/participate/contributor-guide) + - ZF Contributor's mailing list: + Archives: http://zend-framework-community.634137.n4.nabble.com/ZF-Contributor-f680267.html + Subscribe: zf-contributors-subscribe@lists.zend.com + - ZF Contributor's IRC channel: + #zftalk.dev on Freenode.net + +If you are working on new features or refactoring [create a proposal](https://github.com/zendframework/zend-progress-bar/issues/new). + +## Reporting Potential Security Issues + +If you have encountered a potential security vulnerability, please **DO NOT** report it on the public +issue tracker: send it to us at [zf-security@zend.com](mailto:zf-security@zend.com) instead. +We will work with you to verify the vulnerability and patch it as soon as possible. + +When reporting issues, please provide the following information: + +- Component(s) affected +- A description indicating how to reproduce the issue +- A summary of the security vulnerability and impact + +We request that you contact us via the email address above and give the project +contributors a chance to resolve the vulnerability and issue a new release prior +to any public exposure; this helps protect users and provides them with a chance +to upgrade and/or update in order to protect their applications. + +For sensitive email communications, please use [our PGP key](http://framework.zend.com/zf-security-pgp-key.asc). + +## RUNNING TESTS + +> ### Note: testing versions prior to 2.4 +> +> This component originates with Zend Framework 2. During the lifetime of ZF2, +> testing infrastructure migrated from PHPUnit 3 to PHPUnit 4. In most cases, no +> changes were necessary. However, due to the migration, tests may not run on +> versions < 2.4. As such, you may need to change the PHPUnit dependency if +> attempting a fix on such a version. + +To run tests: + +- Clone the repository: + + ```console + $ git clone git@github.com:zendframework/zend-progress-bar.git + $ cd + ``` + +- Install dependencies via composer: + + ```console + $ curl -sS https://getcomposer.org/installer | php -- + $ ./composer.phar install + ``` + + If you don't have `curl` installed, you can also download `composer.phar` from https://getcomposer.org/ + +- Run the tests via `phpunit` and the provided PHPUnit config, like in this example: + + ```console + $ ./vendor/bin/phpunit + ``` + +You can turn on conditional tests with the phpunit.xml file. +To do so: + + - Copy `phpunit.xml.dist` file to `phpunit.xml` + - Edit `phpunit.xml` to enable any specific functionality you + want to test, as well as to provide test values to utilize. + +## Running Coding Standards Checks + +This component uses [php-cs-fixer](http://cs.sensiolabs.org/) for coding +standards checks, and provides configuration for our selected checks. +`php-cs-fixer` is installed by default via Composer. + +To run checks only: + +```console +$ ./vendor/bin/php-cs-fixer fix . -v --diff --dry-run --config-file=.php_cs +``` + +To have `php-cs-fixer` attempt to fix problems for you, omit the `--dry-run` +flag: + +```console +$ ./vendor/bin/php-cs-fixer fix . -v --diff --config-file=.php_cs +``` + +If you allow php-cs-fixer to fix CS issues, please re-run the tests to ensure +they pass, and make sure you add and commit the changes after verification. + +## Recommended Workflow for Contributions + +Your first step is to establish a public repository from which we can +pull your work into the master repository. We recommend using +[GitHub](https://github.com), as that is where the component is already hosted. + +1. Setup a [GitHub account](http://github.com/), if you haven't yet +2. Fork the repository (http://github.com/zendframework/zend-progress-bar) +3. Clone the canonical repository locally and enter it. + + ```console + $ git clone git://github.com:zendframework/zend-progress-bar.git + $ cd zend-progress-bar + ``` + +4. Add a remote to your fork; substitute your GitHub username in the command + below. + + ```console + $ git remote add {username} git@github.com:{username}/zend-progress-bar.git + $ git fetch {username} + ``` + +### Keeping Up-to-Date + +Periodically, you should update your fork or personal repository to +match the canonical ZF repository. Assuming you have setup your local repository +per the instructions above, you can do the following: + + +```console +$ git checkout master +$ git fetch origin +$ git rebase origin/master +# OPTIONALLY, to keep your remote up-to-date - +$ git push {username} master:master +``` + +If you're tracking other branches -- for example, the "develop" branch, where +new feature development occurs -- you'll want to do the same operations for that +branch; simply substitute "develop" for "master". + +### Working on a patch + +We recommend you do each new feature or bugfix in a new branch. This simplifies +the task of code review as well as the task of merging your changes into the +canonical repository. + +A typical workflow will then consist of the following: + +1. Create a new local branch based off either your master or develop branch. +2. Switch to your new local branch. (This step can be combined with the + previous step with the use of `git checkout -b`.) +3. Do some work, commit, repeat as necessary. +4. Push the local branch to your remote repository. +5. Send a pull request. + +The mechanics of this process are actually quite trivial. Below, we will +create a branch for fixing an issue in the tracker. + +```console +$ git checkout -b hotfix/9295 +Switched to a new branch 'hotfix/9295' +``` + +... do some work ... + + +```console +$ git commit +``` + +... write your log message ... + + +```console +$ git push {username} hotfix/9295:hotfix/9295 +Counting objects: 38, done. +Delta compression using up to 2 threads. +Compression objects: 100% (18/18), done. +Writing objects: 100% (20/20), 8.19KiB, done. +Total 20 (delta 12), reused 0 (delta 0) +To ssh://git@github.com/{username}/zend-progress-bar.git + b5583aa..4f51698 HEAD -> master +``` + +To send a pull request, you have two options. + +If using GitHub, you can do the pull request from there. Navigate to +your repository, select the branch you just created, and then select the +"Pull Request" button in the upper right. Select the user/organization +"zendframework" as the recipient. + +If using your own repository - or even if using GitHub - you can use `git +format-patch` to create a patchset for us to apply; in fact, this is +**recommended** for security-related patches. If you use `format-patch`, please +send the patches as attachments to: + +- zf-devteam@zend.com for patches without security implications +- zf-security@zend.com for security patches + +#### What branch to issue the pull request against? + +Which branch should you issue a pull request against? + +- For fixes against the stable release, issue the pull request against the + "master" branch. +- For new features, or fixes that introduce new elements to the public API (such + as new public methods or properties), issue the pull request against the + "develop" branch. + +### Branch Cleanup + +As you might imagine, if you are a frequent contributor, you'll start to +get a ton of branches both locally and on your remote. + +Once you know that your changes have been accepted to the master +repository, we suggest doing some cleanup of these branches. + +- Local branch cleanup + + ```console + $ git branch -d + ``` + +- Remote branch removal + + ```console + $ git push {username} : + ``` diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..6eab5aa --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2005-2015, Zend Technologies USA, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of Zend Technologies USA, Inc. nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9dbe703 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# zend-progressbar + +`Zend\ProgressBar` is a component to create and update progress bars in different +environments. It consists of a single backend, which outputs the progress through +one of the multiple adapters. On every update, it takes an absolute value and +optionally a status message, and then calls the adapter with some precalculated +values like percentage and estimated time left. + + +- File issues at https://github.com/zendframework/zend-progressbar/issues +- Documentation is at http://framework.zend.com/manual/current/en/index.html#zend-progressbar diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..a41009e --- /dev/null +++ b/composer.json @@ -0,0 +1,29 @@ +{ + "name": "zendframework/zend-progressbar", + "description": "component to create and update progressbars in different environments", + "license": "BSD-3-Clause", + "keywords": [ + "zf2", + "progressbar" + ], + "autoload": { + "psr-4": { + "Zend\\ProgressBar": "src/" + } + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "homepage": "https://github.com/zendframework/zend-progress-bar", + "autoload-dev": { + "psr-4": { + "ZendTest\\ProgressBar\\": "test/" + } + }, + "require-dev": { + "fabpot/php-cs-fixer": "1.7.*", + "satooshi/php-coveralls": "dev-master", + "phpunit/PHPUnit": "~4.0" + } +} \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..6ddeaad --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,34 @@ + + + + + ./test/ + + + + + + disable + + + + + + ./src + + + + + + + + + + + diff --git a/phpunit.xml.travis b/phpunit.xml.travis new file mode 100644 index 0000000..6ddeaad --- /dev/null +++ b/phpunit.xml.travis @@ -0,0 +1,34 @@ + + + + + ./test/ + + + + + + disable + + + + + + ./src + + + + + + + + + + + diff --git a/src/Adapter/AbstractAdapter.php b/src/Adapter/AbstractAdapter.php new file mode 100644 index 0000000..d2e2cba --- /dev/null +++ b/src/Adapter/AbstractAdapter.php @@ -0,0 +1,93 @@ +setOptions($options); + } + } + + /** + * Set options via an array + * + * @param array $options + * @return AbstractAdapter + */ + public function setOptions(array $options) + { + foreach ($options as $key => $value) { + if (in_array(strtolower($key), $this->skipOptions)) { + continue; + } + + $method = 'set' . ucfirst($key); + if (method_exists($this, $method)) { + $this->$method($value); + } + } + + return $this; + } + + /** + * Notify the adapter about an update + * + * @param float $current Current progress value + * @param float $max Max progress value + * @param float $percent Current percent value + * @param integer $timeTaken Taken time in seconds + * @param integer $timeRemaining Remaining time in seconds + * @param string $text Status text + * @return void + */ + abstract public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text); + + /** + * Called when the progress is explicitly finished + * + * @return void + */ + abstract public function finish(); +} diff --git a/src/Adapter/Console.php b/src/Adapter/Console.php new file mode 100644 index 0000000..6b834ad --- /dev/null +++ b/src/Adapter/Console.php @@ -0,0 +1,516 @@ +width === null) { + $this->setWidth(); + } + } + + /** + * Close local stdout, when open + */ + public function __destruct() + { + if ($this->outputStream !== null) { + fclose($this->outputStream); + } + } + + /** + * Set a different output-stream + * + * @param string $resource + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setOutputStream($resource) + { + ErrorHandler::start(); + $stream = fopen($resource, 'w'); + $error = ErrorHandler::stop(); + + if ($stream === false) { + throw new Exception\RuntimeException('Unable to open stream', 0, $error); + } + + if ($this->outputStream !== null) { + fclose($this->outputStream); + } + + $this->outputStream = $stream; + } + + /** + * Get the current output stream + * + * @return resource + */ + public function getOutputStream() + { + if ($this->outputStream === null) { + if (!defined('STDOUT')) { + $this->outputStream = fopen('php://stdout', 'w'); + } else { + return STDOUT; + } + } + + return $this->outputStream; + } + + /** + * Set the width of the progressbar + * + * @param integer $width + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setWidth($width = null) + { + if ($width === null || !is_integer($width)) { + if (substr(PHP_OS, 0, 3) === 'WIN') { + // We have to default to 79 on windows, because the windows + // terminal always has a fixed width of 80 characters and the + // cursor is counted to the line, else windows would line break + // after every update. + $this->width = 79; + } else { + // Set the default width of 80 + $this->width = 80; + + // Try to determine the width through stty + ErrorHandler::start(); + if (preg_match('#\d+ (\d+)#', shell_exec('stty size'), $match) === 1) { + $this->width = (int) $match[1]; + } elseif (preg_match('#columns = (\d+);#', shell_exec('stty'), $match) === 1) { + $this->width = (int) $match[1]; + } + ErrorHandler::stop(); + } + } else { + $this->width = (int) $width; + } + + $this->_calculateBarWidth(); + + return $this; + } + + /** + * Set the elements to display with the progressbar + * + * @param array $elements + * @throws \Zend\ProgressBar\Adapter\Exception\InvalidArgumentException When an invalid element is found in the array + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setElements(array $elements) + { + $allowedElements = array(self::ELEMENT_PERCENT, + self::ELEMENT_BAR, + self::ELEMENT_ETA, + self::ELEMENT_TEXT); + + if (count(array_diff($elements, $allowedElements)) > 0) { + throw new Exception\InvalidArgumentException('Invalid element found in $elements array'); + } + + $this->elements = $elements; + + $this->_calculateBarWidth(); + + return $this; + } + + /** + * Set the left-hand character for the bar + * + * @param string $char + * @throws \Zend\ProgressBar\Adapter\Exception\InvalidArgumentException When character is empty + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setBarLeftChar($char) + { + if (empty($char)) { + throw new Exception\InvalidArgumentException('Character may not be empty'); + } + + $this->barLeftChar = (string) $char; + + return $this; + } + + /** + * Set the right-hand character for the bar + * + * @param string $char + * @throws \Zend\ProgressBar\Adapter\Exception\InvalidArgumentException When character is empty + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setBarRightChar($char) + { + if (empty($char)) { + throw new Exception\InvalidArgumentException('Character may not be empty'); + } + + $this->barRightChar = (string) $char; + + return $this; + } + + /** + * Set the indicator character for the bar + * + * @param string $char + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setBarIndicatorChar($char) + { + $this->barIndicatorChar = (string) $char; + + return $this; + } + + /** + * Set the width of the text element + * + * @param integer $width + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setTextWidth($width) + { + $this->textWidth = (int) $width; + + $this->_calculateBarWidth(); + + return $this; + } + + /** + * Set the charset of the text element + * + * @param string $charset + */ + public function setCharset($charset) + { + $this->charset = $charset; + } + + /** + * Set the finish action + * + * @param string $action + * @throws \Zend\ProgressBar\Adapter\Exception\InvalidArgumentException When an invalid action is specified + * @return \Zend\ProgressBar\Adapter\Console + */ + public function setFinishAction($action) + { + $allowedActions = array(self::FINISH_ACTION_CLEAR_LINE, + self::FINISH_ACTION_EOL, + self::FINISH_ACTION_NONE); + + if (!in_array($action, $allowedActions)) { + throw new Exception\InvalidArgumentException('Invalid finish action specified'); + } + + $this->finishAction = $action; + + return $this; + } + + /** + * Defined by Zend\ProgressBar\Adapter\AbstractAdapter + * + * @param float $current Current progress value + * @param float $max Max progress value + * @param float $percent Current percent value + * @param integer $timeTaken Taken time in seconds + * @param integer $timeRemaining Remaining time in seconds + * @param string $text Status text + * @return void + */ + public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) + { + // See if we must clear the line + if ($this->outputStarted) { + $data = str_repeat("\x08", $this->width); + } else { + $data = ''; + $this->outputStarted = true; + } + + // Build all elements + $renderedElements = array(); + + foreach ($this->elements as $element) { + switch ($element) { + case self::ELEMENT_BAR: + $visualWidth = $this->barWidth - 2; + $bar = '['; + + $indicatorWidth = strlen($this->barIndicatorChar); + + $doneWidth = min($visualWidth - $indicatorWidth, round($visualWidth * $percent)); + if ($doneWidth > 0) { + $bar .= substr(str_repeat($this->barLeftChar, ceil($doneWidth / strlen($this->barLeftChar))), 0, $doneWidth); + } + + $bar .= $this->barIndicatorChar; + + $leftWidth = $visualWidth - $doneWidth - $indicatorWidth; + if ($leftWidth > 0) { + $bar .= substr(str_repeat($this->barRightChar, ceil($leftWidth / strlen($this->barRightChar))), 0, $leftWidth); + } + + $bar .= ']'; + + $renderedElements[] = $bar; + break; + + case self::ELEMENT_PERCENT: + $renderedElements[] = str_pad(round($percent * 100), 3, ' ', STR_PAD_LEFT) . '%'; + break; + + case self::ELEMENT_ETA: + // In the first 5 seconds we don't get accurate results, + // this skipping technique is found in many progressbar + // implementations. + if ($timeTaken < 5) { + $renderedElements[] = str_repeat(' ', 12); + break; + } + + if ($timeRemaining === null || $timeRemaining > 86400) { + $etaFormatted = '??:??:??'; + } else { + $hours = floor($timeRemaining / 3600); + $minutes = floor(($timeRemaining % 3600) / 60); + $seconds = ($timeRemaining % 3600 % 60); + + $etaFormatted = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds); + } + + $renderedElements[] = 'ETA ' . $etaFormatted; + break; + + case self::ELEMENT_TEXT: + $renderedElements[] = \Zend\Text\MultiByte::strPad(substr($text, 0, $this->textWidth), $this->textWidth, ' ', STR_PAD_RIGHT, $this->charset); + break; + } + } + + $data .= implode(' ', $renderedElements); + + // Output line data + $this->_outputData($data); + } + + /** + * Defined by Zend\ProgressBar\Adapter\AbstractAdapter + * + * @return void + */ + public function finish() + { + switch ($this->finishAction) { + case self::FINISH_ACTION_EOL: + $this->_outputData(PHP_EOL); + break; + + case self::FINISH_ACTION_CLEAR_LINE: + if ($this->outputStarted) { + $data = str_repeat("\x08", $this->width) + . str_repeat(' ', $this->width) + . str_repeat("\x08", $this->width); + + $this->_outputData($data); + } + break; + + case self::FINISH_ACTION_NONE: + break; + } + } + + /** + * Calculate the bar width when other elements changed + * + * @return void + */ + protected function _calculateBarWidth() + { + if (in_array(self::ELEMENT_BAR, $this->elements)) { + $barWidth = $this->width; + + if (in_array(self::ELEMENT_PERCENT, $this->elements)) { + $barWidth -= 4; + } + + if (in_array(self::ELEMENT_ETA, $this->elements)) { + $barWidth -= 12; + } + + if (in_array(self::ELEMENT_TEXT, $this->elements)) { + $barWidth -= $this->textWidth; + } + + $this->barWidth = $barWidth - (count($this->elements) - 1); + } + } + + /** + * Outputs given data to STDOUT. + * + * This split-off is required for unit-testing. + * + * @param string $data + * @return void + */ + protected function _outputData($data) + { + fwrite($this->getOutputStream(), $data); + } +} diff --git a/src/Adapter/Exception/ExceptionInterface.php b/src/Adapter/Exception/ExceptionInterface.php new file mode 100644 index 0000000..d8feb3a --- /dev/null +++ b/src/Adapter/Exception/ExceptionInterface.php @@ -0,0 +1,23 @@ +exitAfterSend = $exitAfterSend; + } + + /** + * Defined by Zend\ProgressBar\Adapter\AbstractAdapter + * + * @param float $current Current progress value + * @param float $max Max progress value + * @param float $percent Current percent value + * @param integer $timeTaken Taken time in seconds + * @param integer $timeRemaining Remaining time in seconds + * @param string $text Status text + * @return void + */ + public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) + { + $arguments = array( + 'current' => $current, + 'max' => $max, + 'percent' => ($percent * 100), + 'timeTaken' => $timeTaken, + 'timeRemaining' => $timeRemaining, + 'text' => $text, + 'finished' => false + ); + + $data = Json::encode($arguments); + + // Output the data + $this->_outputData($data); + } + + /** + * Defined by Zend\ProgressBar\Adapter\AbstractAdapter + * + * @return void + */ + public function finish() + { + $data = Json::encode(array('finished' => true)); + + $this->_outputData($data); + } + + /** + * Outputs given data the user agent. + * + * This split-off is required for unit-testing. + * + * @param string $data + * @return void + */ + protected function _outputData($data) + { + echo $data; + + if ($this->exitAfterSend) { + exit; + } + } +} diff --git a/src/Adapter/JsPush.php b/src/Adapter/JsPush.php new file mode 100644 index 0000000..3903b8b --- /dev/null +++ b/src/Adapter/JsPush.php @@ -0,0 +1,130 @@ +updateMethodName = $methodName; + + return $this; + } + + /** + * Set the finish method name + * + * @param string $methodName + * @return \Zend\ProgressBar\Adapter\JsPush + */ + public function setFinishMethodName($methodName) + { + $this->finishMethodName = $methodName; + + return $this; + } + + /** + * Defined by Zend\ProgressBar\Adapter\AbstractAdapter + * + * @param float $current Current progress value + * @param float $max Max progress value + * @param float $percent Current percent value + * @param integer $timeTaken Taken time in seconds + * @param integer $timeRemaining Remaining time in seconds + * @param string $text Status text + * @return void + */ + public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) + { + $arguments = array( + 'current' => $current, + 'max' => $max, + 'percent' => ($percent * 100), + 'timeTaken' => $timeTaken, + 'timeRemaining' => $timeRemaining, + 'text' => $text + ); + + $data = ''; + + // Output the data + $this->_outputData($data); + } + + /** + * Defined by Zend\ProgressBar\Adapter\AbstractAdapter + * + * @return void + */ + public function finish() + { + if ($this->finishMethodName === null) { + return; + } + + $data = ''; + + $this->_outputData($data); + } + + /** + * Outputs given data the user agent. + * + * This split-off is required for unit-testing. + * + * @param string $data + * @return void + */ + protected function _outputData($data) + { + // 1024 padding is required for Safari, while 256 padding is required + // for Internet Explorer. The
is required so Safari actually + // executes the #', $output, $result); + $this->assertEquals(1, $matches); + + $data = json_decode($result[1], true); + + $this->assertEquals(0, $data['current']); + $this->assertEquals(2, $data['max']); + $this->assertEquals(50, $data['percent']); + $this->assertEquals(1, $data['timeTaken']); + $this->assertEquals(1, $data['timeRemaining']); + $this->assertEquals('status', $data['text']); + + $adapter->finish(); + $output = $adapter->getLastOutput(); + + $matches = preg_match('##', $output, $result); + $this->assertEquals(1, $matches); + } +} + +class JsPushStub extends \Zend\ProgressBar\Adapter\JsPush +{ + protected $_lastOutput = null; + + public function getLastOutput() + { + return $this->_lastOutput; + } + + protected function _outputData($data) + { + $this->_lastOutput = $data; + } +} diff --git a/test/Adapter/MockupStream.php b/test/Adapter/MockupStream.php new file mode 100644 index 0000000..3f39b73 --- /dev/null +++ b/test/Adapter/MockupStream.php @@ -0,0 +1,102 @@ +test = $url["host"]; + $this->position = 0; + + self::$tests[$url["host"]] = ''; + return true; + } + + public function stream_read($count) + { + $ret = substr(self::$tests[$this->test], $this->position, $count); + $this->position += strlen($ret); + return $ret; + } + + public function stream_write($data) + { + $left = substr(self::$tests[$this->test], 0, $this->position); + $right = substr(self::$tests[$this->test], $this->position + strlen($data)); + self::$tests[$this->test] = $left . $data . $right; + $this->position += strlen($data); + return strlen($data); + } + + public function stream_tell() + { + return $this->position; + } + + public function stream_eof() + { + return $this->position >= strlen(self::$tests[$this->test]); + } + + public function stream_seek($offset, $whence) + { + switch ($whence) { + case SEEK_SET: + if ($offset < strlen(self::$tests[$this->test]) && $offset >= 0) { + $this->position = $offset; + return true; + } else { + return false; + } + break; + + case SEEK_CUR: + if ($offset >= 0) { + $this->position += $offset; + return true; + } else { + return false; + } + break; + + case SEEK_END: + if (strlen(self::$tests[$this->test]) + $offset >= 0) { + $this->position = strlen(self::$tests[$this->test]) + $offset; + return true; + } else { + return false; + } + break; + + default: + return false; + } + } + + public function __destruct() + { + unset(self::$tests[$this->test]); + } +} diff --git a/test/ProgressBarTest.php b/test/ProgressBarTest.php new file mode 100644 index 0000000..773ada1 --- /dev/null +++ b/test/ProgressBarTest.php @@ -0,0 +1,189 @@ +setExpectedException('Zend\ProgressBar\Exception\OutOfRangeException', '$max must be greater than $min'); + $progressBar = $this->_getProgressBar(1, 0); + } + + public function testPersistence() + { + $progressBar = $this->_getProgressBar(0, 100, 'foobar'); + $progressBar->update(25); + + $progressBar = $this->_getProgressBar(0, 100, 'foobar'); + $progressBar->update(); + $this->assertEquals(25, $progressBar->getCurrent()); + } + + public function testDefaultPercentage() + { + $progressBar = $this->_getProgressBar(0, 100); + $progressBar->update(25); + + $this->assertEquals(.25, $progressBar->getPercent()); + } + + public function testPositiveToPositivePercentage() + { + $progressBar = $this->_getProgressBar(10, 20); + $progressBar->update(12.5); + + $this->assertEquals(.25, $progressBar->getPercent()); + } + + public function testNegativeToPositivePercentage() + { + $progressBar = $this->_getProgressBar(-5, 5); + $progressBar->update(-2.5); + + $this->assertEquals(.25, $progressBar->getPercent()); + } + + public function testNegativeToNegativePercentage() + { + $progressBar = $this->_getProgressBar(-20, -10); + $progressBar->update(-17.5); + + $this->assertEquals(.25, $progressBar->getPercent()); + } + + public function testEtaCalculation() + { + $progressBar = $this->_getProgressBar(0, 100); + + $progressBar->sleep(3); + $progressBar->update(33); + $progressBar->sleep(3); + $progressBar->update(66); + + $this->assertEquals(3, $progressBar->getTimeRemaining()); + } + + public function testEtaZeroPercent() + { + $progressBar = $this->_getProgressBar(0, 100); + + $progressBar->sleep(5); + $progressBar->update(0); + + $this->assertEquals(null, $progressBar->getTimeRemaining()); + } + + protected function _getProgressBar($min, $max, $persistenceNamespace = null) + { + return new Stub(new MockUp(), $min, $max, $persistenceNamespace); + } +} + +class Stub extends \Zend\ProgressBar\ProgressBar +{ + public function sleep($seconds) + { + $this->startTime -= $seconds; + } + + public function getCurrent() + { + return $this->adapter->getCurrent(); + } + + public function getMax() + { + return $this->adapter->getMax(); + } + + public function getPercent() + { + return $this->adapter->getPercent(); + } + + public function getTimeTaken() + { + return $this->adapter->getTimeTaken(); + } + + public function getTimeRemaining() + { + return $this->adapter->getTimeRemaining(); + } + + public function getText() + { + return $this->adapter->getText(); + } +} + +class MockUp extends \Zend\ProgressBar\Adapter\AbstractAdapter +{ + protected $_current; + protected $_max; + protected $_percent; + protected $_timeTaken; + protected $_timeRemaining; + protected $_text; + + public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text) + { + $this->_current = $current; + $this->_max = $max; + $this->_percent = $percent; + $this->_timeTaken = $timeTaken; + $this->_timeRemaining = $timeRemaining; + $this->_text = $text; + } + + public function finish() + { + + } + + public function getCurrent() + { + return $this->_current; + } + + public function getMax() + { + return $this->_max; + } + + public function getPercent() + { + return $this->_percent; + } + + public function getTimeTaken() + { + return $this->_timeTaken; + } + + public function getTimeRemaining() + { + return $this->_timeRemaining; + } + + public function getText() + { + return $this->_text; + } +} diff --git a/test/bootstrap.php b/test/bootstrap.php new file mode 100644 index 0000000..efd3ae4 --- /dev/null +++ b/test/bootstrap.php @@ -0,0 +1,34 @@ + Date: Sat, 1 Sep 2012 20:40:03 +0200 Subject: [PATCH 2/2] Resolve more mismatched phpDoc --- src/ProgressBar.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ProgressBar.php b/src/ProgressBar.php index 08bb4eb..da76822 100644 --- a/src/ProgressBar.php +++ b/src/ProgressBar.php @@ -176,6 +176,7 @@ public function update($value = null, $text = null) /** * Update the progressbar to the next value * + * @param int $diff * @param string $text * @return void */