.editorconfig000064400000000470144760125730007233 0ustar00; This file is for unifying the coding style for different editors and IDEs. ; More information at http://editorconfig.org root = true [*] charset = utf-8 indent_size = 4 indent_style = space end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false .gitignore000064400000000067144760125730006550 0ustar00.idea/ .vscode/ .DS_Store/ composer.lock *.swp vendor/ .styleci.yml000064400000000015144760125730007026 0ustar00preset: psr2 .travis.yml000064400000000332144760125730006664 0ustar00language: php php: - 5.6.28 - 7.0 - 7.1 sudo: false install: - composer self-update - composer install --no-interaction --prefer-source script: - vendor/bin/phpunit -d memory_limit=1024M --coverage-textCHANGELOG.md000064400000002110144760125730006360 0ustar00# Changelog ## [1.1.2] - 2018-08-14 ### Changed - Resolved [#1](https://github.com/hidehalo/nanoid-php/issues/1) via: jenky (1): Update: fix version conflicts of random_compat2 in PHP5.6&PHP7 ## [1.1.1] - 2017-11-24 ### Changed - Sync with commits [Calculate mask based on alphabet length](https://github.com/ai/nanoid/commit/3e641fe06171f65cb22623e1c2ca98d9c74d97bd) - Sync with commits [Reverse loop, reuse var](https://github.com/ai/nanoid/commit/c42849cb80a302166fd8c9f188701d1012eeb7d4) - Sync with commits [Reduce default ID length. Issue](https://github.com/ai/nanoid/commit/3bdea68c75cbf639826fc1f21a66d13db643607b) - Sync with commits [Clean up alphabet limit reason](https://github.com/ai/nanoid/commit/a0c97caa1d6851e2d858a37e1c37c65930b325f4) ## [1.1.0] - 2017-09-17 ### Changed - Add example scripts - Add benchmark scripts - Rename `Client::generate(...)` to `Client::generateId(...)` - Add `Client::formatedId(...)` method - Improve code coverage to 100% - Add DOCs in source codes ## [1.0.0] - 2017-09-11 ### Changed - Make all stuff runing right CODE_OF_CONDUCT.md000064400000006223144760125730007357 0ustar00# Contributor Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make 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 `tianchen_cc@yeah.net`. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and 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/ CONTRIBUTING.md000064400000002435144760125730007012 0ustar00# Contributing Contributions are **welcome** and will be fully **credited**. We accept contributions via Pull Requests on [Github](https://github.com/hidehalo/nanoid-php). ## Pull Requests - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - Check the code style with ``$ composer check-style`` and fix it with ``$ composer fix-style``. - **Add tests!** - Your patch won't be accepted if it doesn't have tests. - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. - **Create feature branches** - Don't ask us to pull from your master branch. - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. ## Running Tests ``` bash $ composer test ``` **Happy coding**! ISSUE_TEMPLATE.md000064400000001315144760125730007262 0ustar00 ## Detailed description Provide a detailed description of the change or addition you are proposing. Make it clear if the issue is a bug, an enhancement or just a question. ## Context Why is this change important to you? How would you use it? How can it benefit other users? ## Possible implementation Not obligatory, but suggest an idea for implementing addition or change. ## Your environment Include as many relevant details about the environment you experienced the bug in and how to reproduce it. * Version used (e.g. PHP 5.6, HHVM 3): * Operating system and version (e.g. Ubuntu 16.04, Windows 7): * Link to your project: * ... * ... LICENSE.md000064400000002154144760125730006163 0ustar00# The MIT License (MIT) Copyright (c) 2017 hidehalo > 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. PULL_REQUEST_TEMPLATE.md000064400000003477144760125730010371 0ustar00 ## Description Describe your changes in detail. ## Motivation and context Why is this change required? What problem does it solve? If it fixes an open issue, please link to the issue here (if you write `fixes #num` or `closes #num`, the issue will be automatically closed when the pull is accepted.) ## How has this been tested? Please describe in detail how you tested your changes. Include details of your testing environment, and the tests you ran to see how your change affects other areas of the code, etc. ## Screenshots (if appropriate) ## Types of changes What types of changes does your code introduce? Put an `x` in all the boxes that apply: - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) ## Checklist: Go over all the following points, and put an `x` in all the boxes that apply. Please, please, please, don't send your pull request until all of the boxes are ticked. Once your pull request is created, it will trigger a build on our [continuous integration](http://www.phptherightway.com/#continuous-integration) server to make sure your [tests and code style pass](https://help.github.com/articles/about-required-status-checks/). - [ ] I have read the **[CONTRIBUTING](CONTRIBUTING.md)** document. - [ ] My pull request addresses exactly one patch/feature. - [ ] I have created a branch for this patch/feature. - [ ] Each individual commit in the pull request is meaningful. - [ ] I have added tests to cover my changes. - [ ] If my change requires a change to the documentation, I have updated it accordingly. If you're unsure about any of these, don't hesitate to ask. We're here to help! README.md000064400000005406144760125730006041 0ustar00# Nanoid-php [![Build Status](https://travis-ci.org/hidehalo/emoji.svg)](https://travis-ci.org/hidehalo/nanoid-php) > A tiny (179 bytes), secure URL-friendly unique string ID generator for JavaScript > > **Safe.** It uses cryptographically strong random APIs and guarantees a proper distribution of symbols. > > **Small.** Only 179 bytes (minified and gzipped). No dependencies. It uses Size Limit to control size. > > **Compact.** It uses more symbols than UUID (A-Za-z0-9_~) and has the same number of unique options in just 21 symbols instead of 36. Thanks awesome [ai](https://github.com/ai) and his [nanoid](https://github.com/ai/nanoid), this package is a copy in PHP! If you like nanoid and you want to use it in PHP, try me :D ## Install Via Composer ``` bash $composer require hidehalo/nanoid-php ``` ## Usage ### Normal > The main module uses URL-friendly symbols (A-Za-z0-9_~) and returns an ID with 21 characters (to have the same collisions probability as UUID v4). ``` php use Hidehalo\Nanoid\Client; use Hidehalo\Nanoid\GeneratorInterface; $client = new Client(); # default random generator echo $client->generateId($size = 21); # more safer random generator echo $client->generateId($size = 21, $mode = Client::MODE_DYNAMIC) ``` ### Custom Alphabet or Length ``` php echo $client->formatedId($alphabet = '0123456789abcdefg', $size = 21); ``` > Alphabet must contain 256 symbols or less. > Otherwise, the generator will not be secure. ### Custom Random Bytes Generator ``` php # PS: anonymous class is new feature when PHP_VERSION >= 7.0 echo $client->formatedId($alphabet = '0123456789abcdefg', $size = 21, new class implements GeneratorInterface { /** * @inheritDoc */ public function random($size) { //TODO: implemenation ... } }); ``` > `random` callback must accept the array size and return an array with random numbers. > > If you want to use the same URL-friendly symbols with `format`, > you can get default alphabet from the `url` module: Please see [`CoreInterface::random(...)`](src/CoreInterface.php) for the core random API prototype and notes ## Examples Please see [Examples](examples) for more information on detailed usage. ## Change log Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. ## Testing ``` bash $composer test ``` ## Contributing Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE_OF_CONDUCT](CODE_OF_CONDUCT.md) for details. ## Notice If you have any issues, just feel free and open it in this repository, thx! ## Credits - [ai](https://github.com/ai) - [hidehalo](https://github.com/hidehalo) - [All Contributors](https://github.com/hidehalo/nanoid-php/graphs/contributors) ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information.benchmark/benchmark.php000064400000001202144760125730011145 0ustar00formatedId($alphabet, 1); !isset($counter[$alpha]) and $counter[$alpha] = 0; isset($counter[$alpha]) and $counter[$alpha]++; } $timeFinished = microtime(true); $deltaTime = $timeFinished - $timeStated; ksort($counter); printf("Total time used: %.3f ms\n", 1e3 * $deltaTime); printf("AVG time used: %.3f ms\n", 1e3 * $deltaTime/$loop); echo "Result:".PHP_EOL; print_r($counter);composer.json000064400000002467144760125730007310 0ustar00{ "name": "hidehalo/nanoid-php", "type": "library", "description": "A copy of nanoid in PHP", "keywords": [ "hidehalo", "nanoid-php" ], "homepage": "https://github.com/hidehalo/nanoid-php", "license": "MIT", "authors": [ { "name": "hidehalo", "email": "tianchen_cc@yeah.net", "homepage": "https://github.com/hidehalo", "role": "Owner" } ], "require": { "php": "~5.6|~7.0", "paragonie/random_compat": ">=2.0" }, "require-dev": { "phpunit/phpunit" : ">=5.6", "squizlabs/php_codesniffer": "^2.3" }, "autoload": { "psr-4": { "Hidehalo\\Nanoid\\": "src" } }, "autoload-dev": { "psr-4": { "Hidehalo\\Nanoid\\Test\\": "tests" } }, "scripts": { "test": "phpunit", "check-style": "phpcs -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests", "fix-style": "phpcbf -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests" }, "extra": { "branch-alias": { "dev-master": "1.0-dev" } }, "config": { "sort-packages": true } } examples/basic_usage.php000064400000001471144760125730011354 0ustar00generateId($size); printf("%s\n", str_repeat('-', 64)); printf("That is nanoid.id: %s\n", $id); printf("%s\n", str_repeat('-', 64)); //@see https://github.com/ai/nanoid/blob/master/format.js $id = $nano->generateId($size, Client::MODE_DYNAMIC); printf("That is more safer nanoid.id: %s\n", $id); printf("%s\n", str_repeat('-', 64));examples/custom_formated.php000064400000001147144760125730012302 0ustar00formatedId($alphabet, 10); $dummyId = $nano->formatedId($alphabet, 10, new DummyGenerator); printf("Default nano ID: %s\n", $nanoId); printf("Formated nano ID: %s\n", $dummyId); phpunit.xml000064400000001776144760125730007001 0ustar00 tests src/ tests/ tests/ src/Client.php000064400000005451144760125730007300 0ustar00size = $size > 0 ? $size : 21; $this->generator = $generator?:new Generator(); $this->core = new Core(); $this->alphbet = CoreInterface::SAFE_SYMBOLS; } /** * Generate nanoid via optional modes * * @param integer $size * @param integer $mode Client::MODE_NORMAL|Client::MODE_DYNAMIC * @return string */ public function generateId($size = 0, $mode = self::MODE_NORMAL) { $size = $size>0? $size: $this->size; switch ($mode) { case self::MODE_DYNAMIC: return $this->core->random($this->generator, $size); default: return $this->normalRandom($size); } } /** * The original API of nanoid. Use it be careful, Please make sure * you have been implements your custom GeneratorInterface as correctly. * Otherwise use the build-in default random bytes generator * * @see https://github.com/ai/nanoid/blob/master/format.js * @see https://github.com/ai/nanoid/blob/master/generate.js * @param GeneratorInterface $generator * @param integer $size * @param string $alphabet default CoreInterface::SAFE_SYMBOLS * @return string */ public function formatedId($alphabet, $size, GeneratorInterface $generator = null) { $generator = $generator?:$this->generator; $alphabet = $alphabet?:CoreInterface::SAFE_SYMBOLS; return $this->core->random($generator, $size, $alphabet); } /** * Generate secure URL-friendly unique ID. * By default, ID will have 21 symbols to have same collisions probability * as UUID v4. * * @see https://github.com/ai/nanoid/blob/master/index.js * @param integer $size * @return string */ private function normalRandom($size) { $id = ''; while (1 <= $size--) { $rand = mt_rand()/(mt_getrandmax() + 1); $id .= $this->alphbet[$rand*64 | 0]; } return $id; } } src/Core.php000064400000001454144760125730006751 0ustar00random($step); for ($i = 1; $i <= $step; $i++) { $byte = $bytes[$i] & $mask; if (isset($alphabet[$byte])) { $id .= $alphabet[$byte]; if (strlen($id) === $size) { return $id; } } } } } } src/CoreInterface.php000064400000001166144760125730010572 0ustar00generateId($size); $this->assertEquals($size, strlen($normalRandom)); $dynamicRandom = $client->generateId($size, Client::MODE_DYNAMIC); $this->assertEquals($size, strlen($dynamicRandom)); $this->assertNotEquals($normalRandom, $dynamicRandom); $defaultRandom = $client->generateId(); $this->assertEquals(21, strlen($defaultRandom)); } /** * @group passed * @dataProvider clientProvider * @param Client $client */ public function testFormatedId(Client $client) { $size = 10; $alphabet = '0123456789abcdefghi'; $id = $client->formatedId($alphabet, $size); $this->assertEquals($size, strlen($id)); $dummyId = $client->formatedId($alphabet, $size, new DummyGenerator); $this->assertEquals($size, strlen($dummyId)); $this->assertNotEquals($id, $dummyId); } /** * Client Provider * * @return mixed */ public function clientProvider() { return [ [new Client()] ]; } } tests/CoreTest.php000064400000001501144760125730010155 0ustar00random($generator, $size, $alph); $this->assertEquals($size, strlen($ret)); } /** * Core Provider * * @return mixed */ public function coreProvider() { return [ [new Core(), new Generator()] ]; } } tests/GeneratorTest.php000064400000001224144760125730011215 0ustar00random($size); $this->assertEquals($size, count($ret)); } /** * Generator Provider * * @return mixed */ public function generatorProvider() { return [ [new Generator()] ]; } } tests/Support/DummyGenerator.php000064400000000523144760125730013046 0ustar00