├── .github ├── ISSUE_TEMPLATE.md └── workflows │ ├── run-linting.yml │ └── run-tests.yml ├── .php-cs-fixer.php ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── UPGRADING.md ├── composer.json ├── phpcs.xml └── src └── UniqueCodes.php /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | - Package version: #.#.# 2 | - PHP version: 3 | 4 | ### Description: 5 | 6 | 7 | ### Steps To Reproduce: 8 | -------------------------------------------------------------------------------- /.github/workflows/run-linting.yml: -------------------------------------------------------------------------------- 1 | name: run-linting 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | run-linting: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Update apt 13 | run: sudo apt-get update --fix-missing 14 | 15 | - name: Checkout code 16 | uses: actions/checkout@v3 17 | 18 | - name: Setup PHP 19 | uses: shivammathur/setup-php@v2 20 | with: 21 | php-version: 8.4 22 | 23 | - name: Get Composer cache cirectory 24 | id: composer-cache 25 | run: | 26 | echo "::set-output name=dir::$(composer config cache-files-dir)" 27 | 28 | - name: Cache Composer packages 29 | uses: actions/cache@v3 30 | with: 31 | path: ${{ steps.composer-cache.outputs.dir }} 32 | key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} 33 | restore-keys: | 34 | ${{ runner.os }}-composer- 35 | 36 | - name: Install dependencies 37 | run: | 38 | composer install --prefer-dist --no-interaction --no-suggest 39 | 40 | - name: Execute linting 41 | run: | 42 | PHP_CS_FIXER_IGNORE_ENV=1 vendor/bin/php-cs-fixer fix --dry-run 43 | vendor/bin/phpcs --colors --report-full 44 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | run-tests: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | fail-fast: false 12 | matrix: 13 | php: [7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4] 14 | dependency-version: [prefer-lowest, prefer-stable] 15 | 16 | name: PHP ${{ matrix.php }} - ${{ matrix.dependency-version }} 17 | 18 | steps: 19 | - name: Update apt 20 | run: sudo apt-get update --fix-missing 21 | 22 | - name: Checkout code 23 | uses: actions/checkout@v3 24 | 25 | - name: Setup PHP 26 | uses: shivammathur/setup-php@v2 27 | with: 28 | php-version: ${{ matrix.php }} 29 | coverage: xdebug 30 | 31 | - name: Get Composer cache cirectory 32 | id: composer-cache 33 | run: | 34 | echo "::set-output name=dir::$(composer config cache-files-dir)" 35 | 36 | - name: Cache Composer packages 37 | uses: actions/cache@v3 38 | with: 39 | path: ${{ steps.composer-cache.outputs.dir }} 40 | key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} 41 | restore-keys: | 42 | ${{ runner.os }}-composer- 43 | 44 | - name: Install dependencies 45 | run: | 46 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest 47 | 48 | - name: Execute tests 49 | run: vendor/bin/phpunit --coverage-text --coverage-clover=coverage.clover 50 | -------------------------------------------------------------------------------- /.php-cs-fixer.php: -------------------------------------------------------------------------------- 1 | true, 9 | // Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one. 10 | // 'align_multiline_comment' => true, 11 | // Each element of an array must be indented exactly once. 12 | 'array_indentation' => true, 13 | // PHP arrays should be declared using the configured syntax. 14 | 'array_syntax' => ['syntax' => 'short'], 15 | // Binary operators should be surrounded by space as configured. 16 | 'binary_operator_spaces' => true, 17 | // Ensure there is no code on the same line as the PHP open tag and it is followed by a blank line. 18 | 'blank_line_after_opening_tag' => true, 19 | // An empty line feed must precede any configured statement. 20 | 'blank_line_before_statement' => true, 21 | // A single space or none should be between cast and variable. 22 | 'cast_spaces' => true, 23 | // Class, trait and interface elements must be separated with one blank line. 24 | 'class_attributes_separation' => true, 25 | // Remove extra spaces in a nullable typehint. 26 | 'compact_nullable_typehint' => true, 27 | // Concatenation should be spaced according configuration. 28 | 'concat_space' => ['spacing' => 'one'], 29 | // Add curly braces to indirect variables to make them clear to understand. 30 | // Requires PHP >= 7.0. 31 | 'explicit_indirect_variable' => true, 32 | // Converts implicit variables into explicit ones in double-quoted strings or heredoc syntax. 33 | 'explicit_string_variable' => true, 34 | // Transforms imported FQCN parameters and return types in function arguments to short version. 35 | 'fully_qualified_strict_types' => true, 36 | // Add missing space between function's argument and its typehint. 37 | 'function_typehint_space' => true, 38 | // Pre- or post-increment and decrement operators should be used if possible. 39 | 'increment_style' => ['style' => 'post'], 40 | // Ensure there is no code on the same line as the PHP open tag. 41 | 'linebreak_after_opening_tag' => true, 42 | // Cast should be written in lower case. 43 | 'lowercase_cast' => true, 44 | // Class static references `self`, `static` and `parent` MUST be in lower case. 45 | 'lowercase_static_reference' => true, 46 | // Magic constants should be referred to using the correct casing. 47 | 'magic_constant_casing' => true, 48 | // Magic method definitions and calls must be using the correct casing. 49 | 'magic_method_casing' => true, 50 | // Method chaining MUST be properly indented. 51 | // Method chaining with different levels of indentation is not supported. 52 | 'method_chaining_indentation' => true, 53 | // DocBlocks must start with two asterisks, multiline comments must start with a single asterisk, after the opening slash. 54 | // Both must end with a single asterisk before the closing slash. 55 | 'multiline_comment_opening_closing' => true, 56 | // Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls. 57 | 'multiline_whitespace_before_semicolons' => true, 58 | // Function defined by PHP should be called using the correct casing. 59 | 'native_function_casing' => true, 60 | // All instances created with new keyword must be followed by braces. 61 | 'new_with_braces' => true, 62 | // Replace control structure alternative syntax to use braces. 63 | 'no_alternative_syntax' => true, 64 | // There should be no empty lines after class opening brace. 65 | 'no_blank_lines_after_class_opening' => true, 66 | // There should not be blank lines between docblock and the documented element. 67 | 'no_blank_lines_after_phpdoc' => true, 68 | // There should not be empty PHPDoc blocks. 69 | 'no_empty_phpdoc' => true, 70 | // Remove useless semicolon statements. 71 | 'no_empty_statement' => true, 72 | // Removes extra blank lines and/or blank lines following configuration. 73 | 'no_extra_blank_lines' => ['tokens' => ['break', 'continue', 'curly_brace_block', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'throw', 'use', 'use_trait', 'switch', 'case', 'default']], 74 | // Remove leading slashes in `use` clauses. 75 | 'no_leading_import_slash' => true, 76 | // The namespace declaration line shouldn't contain leading whitespace. 77 | 'no_leading_namespace_whitespace' => true, 78 | // Operator `=>` should not be surrounded by multi-line whitespaces. 79 | 'no_multiline_whitespace_around_double_arrow' => true, 80 | // Short cast `bool` using double exclamation mark should not be used. 81 | 'no_short_bool_cast' => true, 82 | // Single-line whitespace before closing semicolon are prohibited. 83 | 'no_singleline_whitespace_before_semicolons' => true, 84 | // There MUST NOT be spaces around offset braces. 85 | 'no_spaces_around_offset' => true, 86 | // Remove trailing commas in list function calls. 87 | 'no_trailing_comma_in_list_call' => true, 88 | // PHP single-line arrays should not have trailing comma. 89 | 'no_trailing_comma_in_singleline_array' => true, 90 | // Removes unneeded parentheses around control statements. 91 | 'no_unneeded_control_parentheses' => true, 92 | // Unused `use` statements must be removed. 93 | 'no_unused_imports' => true, 94 | // There should not be useless `else` cases. 95 | 'no_useless_else' => true, 96 | // There should not be an empty `return` statement at the end of a function. 97 | 'no_useless_return' => true, 98 | // In array declaration, there MUST NOT be a whitespace before each comma. 99 | 'no_whitespace_before_comma_in_array' => true, 100 | // Remove trailing whitespace at the end of blank lines. 101 | 'no_whitespace_in_blank_line' => true, 102 | // Array index should always be written by using square braces. 103 | 'normalize_index_brace' => true, 104 | // Logical NOT operators (`!`) should have one trailing whitespace. 105 | 'not_operator_with_successor_space' => true, 106 | // There should not be space before or after object `T_OBJECT_OPERATOR` `->`. 107 | 'object_operator_without_whitespace' => true, 108 | // Ordering `use` statements. 109 | 'ordered_imports' => ['sort_algorithm' => 'alpha'], 110 | // Enforce camel (or snake) case for PHPUnit test methods, following configuration. 111 | 'php_unit_method_casing' => ['case' => 'snake_case'], 112 | // All items of the given phpdoc tags must be either left-aligned or (by default) aligned vertically. 113 | 'phpdoc_align' => ['align' => 'left'], 114 | // PHPDoc annotation descriptions should not be a sentence. 115 | 'phpdoc_annotation_without_dot' => true, 116 | // Docblocks should have the same indentation as the documented subject. 117 | 'phpdoc_indent' => true, 118 | // Fix PHPDoc inline tags, make `@inheritdoc` always inline. 119 | // `@access` annotations should be omitted from PHPDoc. 120 | 'phpdoc_no_access' => true, 121 | // No alias PHPDoc tags should be used. 122 | 'phpdoc_no_alias_tag' => true, 123 | // `@package` and `@subpackage` annotations should be omitted from PHPDoc. 124 | 'phpdoc_no_package' => true, 125 | // Classy that does not inherit must not have `@inheritdoc` tags. 126 | 'phpdoc_no_useless_inheritdoc' => true, 127 | // Annotations in PHPDoc should be ordered so that `@param` annotations come first, then `@throws` annotations, then `@return` annotations. 128 | 'phpdoc_order' => true, 129 | // The type of `@return` annotations of methods returning a reference to itself must the configured one. 130 | 'phpdoc_return_self_reference' => true, 131 | // Scalar types should always be written in the same form. 132 | // `int` not `integer`, `bool` not `boolean`, `float` not `real` or `double`. 133 | 'phpdoc_scalar' => true, 134 | // Annotations in PHPDoc should be grouped together so that annotations of the same type immediately follow each other, and annotations of a different type are separated by a single blank line. 135 | 'phpdoc_separation' => true, 136 | // Single line `@var` PHPDoc should have proper spacing. 137 | 'phpdoc_single_line_var_spacing' => true, 138 | // PHPDoc summary should end in either a full stop, exclamation mark, or question mark. 139 | 'phpdoc_summary' => true, 140 | // Docblocks should only be used on structural elements. 141 | 'phpdoc_to_comment' => true, 142 | // PHPDoc should start and end with content, excluding the very first and last line of the docblocks. 143 | 'phpdoc_trim' => true, 144 | // Removes extra blank lines after summary and after description in PHPDoc. 145 | 'phpdoc_trim_consecutive_blank_line_separation' => true, 146 | // The correct case must be used for standard PHP types in PHPDoc. 147 | 'phpdoc_types' => true, 148 | // Sorts PHPDoc types. 149 | 'phpdoc_types_order' => ['null_adjustment' => 'always_last'], 150 | // `@var` and `@type` annotations should not contain the variable name. 151 | 'phpdoc_var_without_name' => true, 152 | // There should be one or no space before colon, and one space after it in return type declarations, according to configuration. 153 | 'return_type_declaration' => ['space_before' => 'one'], 154 | // Instructions must be terminated with a semicolon. 155 | 'semicolon_after_instruction' => true, 156 | // Cast `(boolean)` and `(integer)` should be written as `(bool)` and `(int)`, `(double)` and `(real)` as `(float)`, `(binary)` as `(string)`. 157 | 'short_scalar_cast' => true, 158 | // There should be exactly one blank line before a namespace declaration. 159 | 'single_blank_line_before_namespace' => true, 160 | // Convert double quotes to single quotes for simple strings. 161 | 'single_quote' => ['strings_containing_single_quote_chars' => true], 162 | // Fix whitespace after a semicolon. 163 | 'space_after_semicolon' => true, 164 | // Increment and decrement operators should be used if possible. 165 | 'standardize_increment' => true, 166 | // Replace all `<>` with `!=`. 167 | 'standardize_not_equals' => true, 168 | // Standardize spaces around ternary operator. 169 | 'ternary_operator_spaces' => true, 170 | // Use `null` coalescing operator `??` where possible. 171 | // Requires PHP >= 7.0. 172 | 'ternary_to_null_coalescing' => true, 173 | // PHP multi-line arrays should have a trailing comma. 174 | 'trailing_comma_in_multiline' => true, 175 | // Arrays should be formatted like function/method arguments, without leading or trailing single line space. 176 | 'trim_array_spaces' => true, 177 | // Unary operators should be placed adjacent to their operands. 178 | 'unary_operator_spaces' => true, 179 | // In array declaration, there MUST be a whitespace after each comma. 180 | 'whitespace_after_comma_in_array' => true, 181 | // Force Fully-Qualified Class Name in docblocks 182 | 'AdamWojs/phpdoc_force_fqcn_fixer' => true, 183 | ]; 184 | 185 | $finder = Finder::create() 186 | ->notPath('bootstrap') 187 | ->notPath('storage') 188 | ->notPath('vendor') 189 | ->in(__DIR__) 190 | ->name('*.php') 191 | ->name('_ide_helper') 192 | ->notName('*.blade.php') 193 | ->ignoreDotFiles(true) 194 | ->ignoreVCS(true); 195 | 196 | return (new Config()) 197 | ->registerCustomFixers([ 198 | new ForceFQCNFixer(), 199 | ]) 200 | ->setRules($rules) 201 | ->setFinder($finder); 202 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `unique-codes` will be documented in this file 4 | 5 | ## 3.1.0 - 2024-12-12 6 | 7 | - Added: PHP 8.4 support ([#14](https://github.com/wotzebra/unique-codes/pull/14)) 8 | 9 | ## 3.0.0 - 2024-09-28 10 | 11 | - Changed: Change namespace from 'NextApps' to 'Wotz' ([#13](https://github.com/wotzebra/unique-codes/pull/13)) 12 | 13 | ## 2.3.2 - 2024-05-13 14 | 15 | - Fixed: Implicit conversion deprecation warning when converting float to int ([#ebd6914](https://github.com/wotzebra/unique-codes/commit/ebd6914f7bf1c843a9cf5ab888e454503400db22)) 16 | 17 | ## 2.3.1 - 2024-05-13 18 | 19 | - Fixed: Implicit conversion deprecation warning when converting float to int ([#12](https://github.com/wotzebra/unique-codes/pull/12)) 20 | 21 | ## 2.3.0 - 2023-12-15 22 | 23 | - Added: PHP 8.3 support ([#11](https://github.com/wotzebra/unique-codes/pull/11)) 24 | 25 | ## 2.2.0 - 2023-02-19 26 | 27 | - Add PHP 8.2 support ([#10](https://github.com/wotzebra/unique-codes/pull/10)) 28 | 29 | ## 2.1.0 - 2022-02-24 30 | 31 | - Add PHP 8.1 support ([#7](https://github.com/wotzebra/unique-codes/pull/7)) 32 | 33 | ## 2.0.0 - 2021-02-03 34 | 35 | - Fixed bugs that could cause duplicate code generation (and added more tests) ([#3](https://github.com/wotzebra/unique-codes/pull/3), [#4](https://github.com/wotzebra/unique-codes/pull/4)) 36 | 37 | ## 1.1.0 - 2021-01-19 38 | 39 | - Add PHP 8 support and switch to Github actions ([#1](https://github.com/wotzebra/unique-codes/pull/1)) 40 | 41 | ## 1.0.0 - 2020-04-19 42 | 43 | - Initial release 44 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **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](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Günther Debrauwer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Unique Codes 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/wotz/unique-codes.svg?style=flat-square)](https://packagist.org/packages/wotz/unique-codes) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/wotz/unique-codes.svg?style=flat-square)](https://packagist.org/packages/wotz/unique-codes) 5 | 6 | This package generates unique, random-looking codes. These codes can be used for vouchers, coupons, ... 7 | You can now generate thousands or millions of codes without having to check if a code has already been generated in the past. 8 | 9 | ``` php 10 | use Wotz\UniqueCodes\UniqueCodes; 11 | 12 | // Generate 100 unique codes for numbers 1 to 100 13 | $codes = (new UniqueCodes()) 14 | ->setObfuscatingPrime(9006077) 15 | ->setMaxPrime(7230323) 16 | ->setCharacters('LQJCKZMWDPTSXRGANYVBHF') 17 | ->setLength(6) 18 | ->generate(1, 100); 19 | 20 | // Result: LWXNHJ (1), LACSVK (2), QLNMNM (3), ... , LYMJHL (100), QJVBVJ (101), LQXGQC (102), ... , LJQ5DJ (7230320), LC17CS (7230321), LZ8J8H (7230322) 21 | ``` 22 | 23 | ## Installation 24 | 25 | You can install the package via composer: 26 | 27 | ```bash 28 | composer require wotz/unique-codes 29 | ``` 30 | > Do not use v1 of this package, as it contains bugs. If you currently use v1, you should upgrade to v2 (Read the upgrading guide!). 31 | 32 | ## Usage 33 | 34 | ### Generate() method 35 | 36 | To generate unique codes, you provide a start and end number. It will generate codes using the numbers in that range. Each number will always generate the same unique, random-looking code. This means you should ensure you never use the same numbers again. This could be achieved by saving which number ranges you already used or by always using the next auto-incrementing id in your codes database table. 37 | 38 | If a lot of codes need to be generated at the same time, it can cause a lot of memory usage. In order to prevent this, a [Generator](https://www.php.net/manual/en/class.generator.php) is returned by default. If you want an array instead, you can set the third parameter of the `generate` method to `true`. If you want to generate one code based on one number, you only have to set the first parameter of the `generate` method. 39 | 40 | ```php 41 | // Returns generator to create codes for numbers 1 to 100. 42 | ->generate(1, 100); 43 | 44 | // Returns array with created codes for numbers 1 to 100. 45 | ->generate(1, 100, true); 46 | 47 | // Returns string with created code for number 100. 48 | ->generate(100); 49 | ``` 50 | 51 | ### Setters 52 | 53 | Certain setters are required to generate unique codes: 54 | * `setObfuscatingPrime()` 55 | * `setMaxPrime()` 56 | * `setCharacters()` 57 | * `setLength()` 58 | 59 | #### setObfuscatingPrime($number) 60 | 61 | This prime number is used to obfuscate a number between 1 and the max prime number. This prime number must be bigger than your max prime number (which you provide to the `setMaxPrime` method). 62 | 63 | #### setMaxPrime($number) 64 | 65 | The max prime determines the maximum amount of unique codes you can generate. If you provide `101`, then you can generate codes from 1 to 100. 66 | This prime number must be smaller than the prime number you provide to the `setObfuscatingPrime` method. 67 | 68 | #### setCharacters($string) 69 | 70 | The character list contains all the characters that can be used to build a unique code. 71 | 72 | #### setLength($number) 73 | 74 | The length of each unique code. 75 | 76 | #### setPrefix($string) 77 | 78 | The prefix of each unique code. 79 | 80 | #### setSuffix($string) 81 | 82 | The suffix of each unique code. 83 | 84 | #### setDelimiter($string, $number) 85 | 86 | The code can be split in different pieces and glued together using the specified delimiter. 87 | 88 | ## How does it work? 89 | 90 | The code generation consists of 2 steps: 91 | - Obfuscating sequential numbers 92 | - Encoding the obfuscated number 93 | 94 | #### Obfuscating sequential numbers 95 | 96 | If you encode sequential numbers, you will still see that the encoded strings are sequential. To remove the sequential nature, we use 'modular multiplicative inverse'. 97 | 98 | You define the upper limit of your range. This determines the maximum number you can obfuscate. Then every number is mapped to a unique obfuscated number between 1 and the upper limit. You multiply the input number with a random (larger) prime number, and you determine the remainder of the division of your multiplied input number by the upper limit of the range. 99 | 100 | ``` 101 | $obfuscatedNumber = ($inputNumber * $obfuscatingPrimeNumber) % $maxPrimeNumber 102 | ``` 103 | 104 | #### Encoding the obfuscated number 105 | 106 | In the next step, the obfuscated number is encoded to string. This is just a base conversion using division and modulo. 107 | 108 | ## Testing 109 | 110 | ``` bash 111 | composer test 112 | ``` 113 | 114 | ## Linting 115 | 116 | ```bash 117 | composer lint 118 | ``` 119 | 120 | ## Changelog 121 | 122 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 123 | 124 | ## Contributing 125 | 126 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 127 | 128 | ## Credits 129 | 130 | - [Günther Debrauwer](https://github.com/gdebrauwer) 131 | - [All Contributors](../../contributors) 132 | 133 | This package is heavily inspired by 2 articles written by Jim Mischel: 134 | - [How to generate unique “random-looking” keys 135 | ](https://web.archive.org/web/20170730030023/http://blog.mischel.com/2017/06/20/how-to-generate-random-looking-keys/) 136 | - [How not to generate unique codes](https://web.archive.org/web/20170823111437/http://blog.mischel.com/2017/05/30/how-not-to-generate-unique-codes/) 137 | 138 | ## License 139 | 140 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 141 | -------------------------------------------------------------------------------- /UPGRADING.md: -------------------------------------------------------------------------------- 1 | # Upgrading 2 | 3 | ## From v2 to v3 4 | 5 | - Install `wotz/unique-codes` instead of `nextapps/unique-codes` 6 | - Replace all occurrences of `NextApps\UniqueCodes` namespace with new `Wotz\UniqueCodes` namespace 7 | 8 | ## From v1 to v2 9 | 10 | - The `setPrime` method has been renamed to `setObfuscatingPrime'`. The number you provide to this method should also be larger than the prime number you provide to the `setMaxPrime` number. 11 | - You should change the code length you use (if you can not regenerate all the codes you created in v1). If you generate code using a number in v2 you will not receive the same code as in v1. This means there could be collisions between your v1 and v2 codes. Changing the code length of your v2 codes will prevent such collisions. 12 | - The encoding mechanism in v1 could sometimes generate duplicates because it tried to prevent duplicate characters in the encoded result. This logic has been removed, which also means that codes will now contain duplicate characters. If you don't want that, you could always just skip the numbers that are converted in a unique code with duplicate characters. 13 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wotz/unique-codes", 3 | "description": "Generate unique, random-looking codes", 4 | "keywords": [ 5 | "unique codes", 6 | "voucher codes", 7 | "coupon codes" 8 | ], 9 | "homepage": "https://github.com/wotzebra/unique-codes", 10 | "license": "MIT", 11 | "type": "library", 12 | "authors": [ 13 | { 14 | "name": "Günther Debrauwer", 15 | "email": "gunther.debrauwer@whoownsthezebra.be", 16 | "role": "Developer" 17 | } 18 | ], 19 | "require": { 20 | "php": "^7.3|^7.4|^8.0|^8.1|^8.2|^8.3|^8.4" 21 | }, 22 | "require-dev": { 23 | "adamwojs/php-cs-fixer-phpdoc-force-fqcn": "^2.0", 24 | "friendsofphp/php-cs-fixer": "^3.0", 25 | "phpunit/phpunit": "^9.0", 26 | "squizlabs/php_codesniffer": "^3.6" 27 | }, 28 | "autoload": { 29 | "psr-4": { 30 | "Wotz\\UniqueCodes\\": "src" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "Wotz\\UniqueCodes\\Tests\\": "tests" 36 | } 37 | }, 38 | "scripts": { 39 | "test": "vendor/bin/phpunit", 40 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage", 41 | "lint": "vendor/bin/php-cs-fixer fix && vendor/bin/phpcs --colors --report-full", 42 | "lint-dry": "vendor/bin/php-cs-fixer fix --dry-run && vendor/bin/phpcs --colors --report-full" 43 | }, 44 | "config": { 45 | "sort-packages": true 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | The PSR2 coding standard. 4 | 5 | 6 | 7 | 8 | */**/tests 9 | 10 | 11 | 12 | */**/tests 13 | 14 | 15 | 16 | */**/tests 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | src/ 26 | tests/ 27 | 28 | vendor/ 29 | 30 | -------------------------------------------------------------------------------- /src/UniqueCodes.php: -------------------------------------------------------------------------------- 1 | obfuscatingPrime = $obfuscatingPrime; 75 | 76 | return $this; 77 | } 78 | 79 | /** 80 | * Set the max prime number. 81 | * 82 | * @param int $maxPrime 83 | * 84 | * @return self 85 | */ 86 | public function setMaxPrime(int $maxPrime) 87 | { 88 | $this->maxPrime = $maxPrime; 89 | 90 | return $this; 91 | } 92 | 93 | /** 94 | * Set the suffix. 95 | * 96 | * @param string $suffix 97 | * 98 | * @return self 99 | */ 100 | public function setSuffix(string $suffix) 101 | { 102 | $this->suffix = $suffix; 103 | 104 | return $this; 105 | } 106 | 107 | /** 108 | * Set the prefix. 109 | * 110 | * @param string $prefix 111 | * 112 | * @return self 113 | */ 114 | public function setPrefix(string $prefix) 115 | { 116 | $this->prefix = $prefix; 117 | 118 | return $this; 119 | } 120 | 121 | /** 122 | * Set the delimiter. 123 | * 124 | * @param string $delimiter 125 | * @param int|null $splitLength 126 | * 127 | * @return self 128 | */ 129 | public function setDelimiter(string $delimiter, int $splitLength = null) 130 | { 131 | $this->delimiter = $delimiter; 132 | $this->splitLength = $splitLength; 133 | 134 | return $this; 135 | } 136 | 137 | /** 138 | * Set the characters. 139 | * 140 | * @param array|string $characters 141 | * 142 | * @return self 143 | */ 144 | public function setCharacters($characters) 145 | { 146 | if (is_array($characters)) { 147 | $characters = implode('', $characters); 148 | } 149 | 150 | $this->characters = $characters; 151 | 152 | return $this; 153 | } 154 | 155 | /** 156 | * Set the length. 157 | * 158 | * @param int $length 159 | * 160 | * @return self 161 | */ 162 | public function setLength(int $length) 163 | { 164 | $this->length = $length; 165 | 166 | return $this; 167 | } 168 | 169 | /** 170 | * Generate the necessary amount of codes. 171 | * 172 | * @param int $start 173 | * @param int|null $end 174 | * @param bool $toArray 175 | * 176 | * @return array|\Generator|string 177 | */ 178 | public function generate(int $start, int $end = null, bool $toArray = false) 179 | { 180 | $this->validateInput($start, $end); 181 | 182 | $generator = (function () use ($start, $end) { 183 | for ($i = $start; $i <= ($end ?? $start); $i++) { 184 | $number = $this->obfuscateNumber($i); 185 | $string = $this->encodeNumber($number); 186 | 187 | yield $this->constructCode($string); 188 | } 189 | })(); 190 | 191 | if ($end === null) { 192 | return iterator_to_array($generator)[0]; 193 | } 194 | 195 | if ($toArray) { 196 | return iterator_to_array($generator); 197 | } 198 | 199 | return $generator; 200 | } 201 | 202 | /** 203 | * Map number to a unique other number smaller than the max prime number. 204 | * 205 | * @param int $number 206 | * 207 | * @return int 208 | */ 209 | protected function obfuscateNumber(int $number) 210 | { 211 | return ($number * $this->obfuscatingPrime) % $this->maxPrime; 212 | } 213 | 214 | /** 215 | * Encode number into characters. 216 | * 217 | * @param int $number 218 | * 219 | * @return string 220 | */ 221 | protected function encodeNumber(int $number) 222 | { 223 | $string = ''; 224 | $characters = $this->characters; 225 | 226 | for ($i = 0; $i < $this->length; $i++) { 227 | $digit = intval($number) % strlen($characters); 228 | 229 | $string = $characters[$digit] . $string; 230 | 231 | $number = $number / strlen($characters); 232 | } 233 | 234 | return $string; 235 | } 236 | 237 | /** 238 | * Construct the code. 239 | * 240 | * @param string $string 241 | * 242 | * @return string 243 | */ 244 | protected function constructCode($string) 245 | { 246 | $code = ''; 247 | 248 | if ($this->prefix !== null) { 249 | $code .= $this->prefix . $this->delimiter; 250 | } 251 | 252 | if ($this->splitLength !== null) { 253 | $code .= implode($this->delimiter, str_split($string, $this->splitLength)); 254 | } else { 255 | $code .= $string; 256 | } 257 | 258 | if ($this->suffix !== null) { 259 | $code .= $this->delimiter . $this->suffix; 260 | } 261 | 262 | return $code; 263 | } 264 | 265 | /** 266 | * Check if all property values are valid. 267 | * 268 | * @param int $start 269 | * @param int|null $end 270 | * 271 | * @throws \RuntimeException 272 | * 273 | * @return void 274 | */ 275 | protected function validateInput(int $start, int $end = null) 276 | { 277 | if (empty($this->obfuscatingPrime)) { 278 | throw new RuntimeException('Obfuscating prime number must be specified'); 279 | } 280 | 281 | if (empty($this->maxPrime)) { 282 | throw new RuntimeException('Max prime number must be specified'); 283 | } 284 | 285 | if (empty($this->characters)) { 286 | throw new RuntimeException('Character list must be specified'); 287 | } 288 | 289 | if (empty($this->length)) { 290 | throw new RuntimeException('Length must be specified'); 291 | } 292 | 293 | if ($this->obfuscatingPrime <= $this->maxPrime) { 294 | throw new RuntimeException('Obfuscating prime number must be larger than the max prime number'); 295 | } 296 | 297 | if (count(array_unique(str_split($this->characters))) !== strlen($this->characters)) { 298 | throw new RuntimeException('The character list can not contain duplicates'); 299 | } 300 | 301 | if ($this->getMaximumUniqueCodes() <= $this->maxPrime) { 302 | throw new RuntimeException( 303 | 'The length of the code is too short or the character list is too small ' . 304 | 'to create the number of unique codes equal to the max prime number' 305 | ); 306 | } 307 | 308 | if ($start <= 0) { 309 | throw new RuntimeException('The start number must be bigger than zero'); 310 | } 311 | 312 | if ($end !== null && $end >= $this->maxPrime) { 313 | throw new RuntimeException('The end number can not be bigger or equal to the max prime number'); 314 | } 315 | } 316 | 317 | /** 318 | * Get the maximum amount of unique codes that can create based the characters. 319 | * 320 | * @return int 321 | */ 322 | protected function getMaximumUniqueCodes() 323 | { 324 | return pow(strlen($this->characters), $this->length); 325 | } 326 | } 327 | --------------------------------------------------------------------------------