PHPackages                             vivait/string-generator-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. vivait/string-generator-bundle

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

vivait/string-generator-bundle
==============================

Generate random strings for IDs or keys using property annotations

4.0.1(6y ago)1759.4k7[3 issues](https://github.com/vivait/StringGeneratorBundle/issues)MITPHPPHP &gt;=7.1

Since Dec 1Pushed 5y ago7 watchersCompare

[ Source](https://github.com/vivait/StringGeneratorBundle)[ Packagist](https://packagist.org/packages/vivait/string-generator-bundle)[ RSS](/packages/vivait-string-generator-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (7)Versions (18)Used By (0)

StringGeneratorBundle
=====================

[](#stringgeneratorbundle)

[![Build Status](https://camo.githubusercontent.com/e3a85e114019017e922124345e83ead390e5cdb701f6158e778acb0f18257e3e/68747470733a2f2f7472617669732d63692e6f72672f7669766169742f537472696e6747656e657261746f7242756e646c652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/vivait/StringGeneratorBundle)

This bundle allows you to automatically generate a unique random string on an entity property, useful for creating keys. Using Doctrine's `prePersist` callback, StringGenerator adds the generated string to a property before the entity is persisted. It also checks whether the string is unique to that property (just in case) and if not, quietly generates a new string.

Install
-------

[](#install)

Run: `composer require vivait/string-generator-bundle:^3.0` to install the bundle.

If you are using PHP 5.3 or 5.4 you can use the legacy version`vivait/string-generator-bundle:^1.1`

[*Check latest releases*](https://github.com/vivait/StringGeneratorBundle/releases)

Update your `AppKernel`:

```
public function registerBundles()
{
    $bundles = array(
        ...
        new Vivait\StringGeneratorBundle\VivaitStringGeneratorBundle(),
}
```

Bundled generators
------------------

[](#bundled-generators)

### `StringGenerator`

[](#stringgenerator)

Generates a random string based on a pool or characters. Defaults:

```
@Generate(generator="string", options={"length"=8, "chars"="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "prefix"=""})
```

### `SecureStringGenerator`

[](#securestringgenerator)

Generates a secure random string using [ircmaxell's RandomLib](https://github.com/ircmaxell/RandomLib). The library provides three different strengths of strings(currently `high` is unavailable), `low` and `medium`. Defaults:

```
@Generate(generator="secure_string", options={"length"=32, "chars"="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "strength"="medium"})
```

### `SecureBytesGenerator`

[](#securebytesgenerator)

Generates a secure random byte string using the `Symfony\Component\Security\Core\Util\SecureRandom` class. Defaults:

```
@Generate(generator="secure_bytes", options={"length"=8})
```

### `UuidStringGenerator`

[](#uuidstringgenerator)

***For use this generator you should require the package `ramsey/uuid` in your application.***

For generating a UUID:

```
@Generate(generator="uuid_string", options={"version"=4})
```

You can use also namespaced versions (v3 and v5). For example with the v5:

```
@Generate(generator="uuid_string", options={"version"=5}, namespace="my_namespace")
```

Usage
-----

[](#usage)

Add the `@Generate(generator="generator_name")` annotation to an entity property (where `generator_name` is the name of a generator defined in the configuration).

`generator` is a required property of the annotation.

```
use Vivait\StringGeneratorBundle\Annotation\GeneratorAnnotation as Generate;

/**
 * Api
 *
 * @ORM\Table()
 * @ORM\Entity()
 */
class Api
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="guid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="api_id", type="string", nullable=false)
     * @Generate(generator="string")
     */
    private $api_key;
```

### Options

[](#options)

Generators that implement `ConfigurableGeneratorInterface`, such as the bundled generators have options which can be configured.

To do this, set the options parameter on the annotation:

```
@Generate(generator="string", options={"length"=32, "chars"="ABCDEFG"})
```

### Callbacks

[](#callbacks)

It's possible to define callbacks on the `Generator` class that you are using. For example, with the bundled StringGenerator, you may wish to set the a prefix on the generated string

This can be achieved by setting the `callbacks` option. For example:

```
@Generate(generator="my_generator", callbacks={"setPrefix"="VIVA_"})
```

Here, `setChars()` is called in the `StringGenerator` class, passing `ABCDEFG` as a parameter.

It's even possible to set a callback value dynamically:

```
/**
 * @var string
 *
 * @ORM\Column(name="short_id", type="string", length=255, nullable=false)
 * @Generate(generator="string", options={"length"=32}, callbacks={"setPrefix"="getPrefix"})
 */
private $short_id;

public function getPrefix()
{
    return $this->getType(); //"default"
}
```

In this case `StringGenerator::setPrefix("default")` will be called

### Unique

[](#unique)

Setting `unique` is boolean and tell if the string must be unique or not, by default `true`

```
@Generate(generator="secure_bytes", unique=false)
```

### Override

[](#override)

By default, `override` is set to true, so a string is always generated for a property. However, by setting `override` to false, only null properties will have a string generated for them.

```
@Generate(generator="string", override=false)
```

Custom generators
-----------------

[](#custom-generators)

You can use your own generators by implementing `GeneratorInterface` and defining the generator in your `services.yml` file with the tag `vivait_generator.generator` and an `alias`, which will be used to identify the Generator in annotations.

```
vivait_generator.generator.secure_bytes:
    class: Vivait\StringGeneratorBundle\Generator\SecureBytesGenerator
    tags:
        - { name: vivait_generator.generator, alias: 'secure_bytes' }
```

To create configurable generators, implement `ConfigurableGeneratorInterface`. This interface uses [`Symfony\Component\OptionsResolver\OptionsResolver`](http://symfony.com/doc/current/components/options_resolver.html) to set the generator configuration.

Set default options:

```
/**
 * @param OptionsResolver $resolver
 */
public function getDefaultOptions(OptionsResolver $resolver)
{
  $resolver->setDefaults(
      [
        'chars'  => $this->chars,
        'length' => $this->length,
        'prefix' => $this->prefix,
      ]
  );
}
```

Do something with options:

```
/**
 * @param array $options
 */
public function setOptions(array $options)
{
    $this->chars  = $options['chars'];
    $this->length = $options['length'];
    $this->prefix = $options['prefix'];
}
```

Upgrading from version 1 to version 2
-------------------------------------

[](#upgrading-from-version-1-to-version-2)

Defining generators in configuration was deprecated in version 2 in favour of service definitions, so they must be removed.

1. For any **CUSTOM** generators you have added, you must now define them as services with a `vivait_generator.generator` tag and an `alias` attribute. You will **not** need to do this for the bundled default generators.

    ```
    my_generator:
        class: App\Generator\MyGenerator
        tags:
            - { name: vivait_generator.generator, alias: 'my_generator' }
    ```
2. Remove all `vivait_string_generator` configuration from your project

Upgrading from version 2 to version 3
-------------------------------------

[](#upgrading-from-version-2-to-version-3)

1. Remove all `vivait_string_generator` configuration from your project if not already gone as it will no longer be recognised.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance16

Infrequent updates — may be unmaintained

Popularity36

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor3

3 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~118 days

Recently: every ~168 days

Total

16

Last Release

2400d ago

Major Versions

0.1 → 1.02014-12-02

1.2.3 → 2.0.02017-04-12

2.1.1 → 3.0.02018-08-03

3.0.x-dev → 4.0.02018-11-09

PHP version history (3 changes)0.1PHP &gt;=5.3.3

2.0.0PHP &gt;=5.5.3

4.0.0PHP &gt;=7.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/da5c482ef5aa8f8c955a5f02b5da2ccd7e11b325380d20707881efd6164e8701?d=identicon)[robincawser](/maintainers/robincawser)

![](https://www.gravatar.com/avatar/e951e64fe319138045c10cf13c76e276a68b3ee4416acb58c4fd2be4e7af0040?d=identicon)[kieljohn](/maintainers/kieljohn)

![](https://www.gravatar.com/avatar/69b7a2b44dd490af24dea8ebf3bade15057a27dafbfa31057742c548be5fa0f3?d=identicon)[LewisW](/maintainers/LewisW)

---

Top Contributors

[![terox](https://avatars.githubusercontent.com/u/252005?v=4)](https://github.com/terox "terox (25 commits)")[![rcwsr](https://avatars.githubusercontent.com/u/1541207?v=4)](https://github.com/rcwsr "rcwsr (21 commits)")[![mayeco](https://avatars.githubusercontent.com/u/369490?v=4)](https://github.com/mayeco "mayeco (19 commits)")[![leightonthomas](https://avatars.githubusercontent.com/u/14091070?v=4)](https://github.com/leightonthomas "leightonthomas (9 commits)")[![kieljohn](https://avatars.githubusercontent.com/u/1641880?v=4)](https://github.com/kieljohn "kieljohn (7 commits)")[![Brunty](https://avatars.githubusercontent.com/u/1573273?v=4)](https://github.com/Brunty "Brunty (6 commits)")[![LewisW](https://avatars.githubusercontent.com/u/17803?v=4)](https://github.com/LewisW "LewisW (5 commits)")[![scrutinizer-auto-fixer](https://avatars.githubusercontent.com/u/6253494?v=4)](https://github.com/scrutinizer-auto-fixer "scrutinizer-auto-fixer (2 commits)")[![zittix](https://avatars.githubusercontent.com/u/818748?v=4)](https://github.com/zittix "zittix (1 commits)")

### Embed Badge

![Health badge](/badges/vivait-string-generator-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/vivait-string-generator-bundle/health.svg)](https://phpackages.com/packages/vivait-string-generator-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M647](/packages/sylius-sylius)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[symfony/ux-toggle-password

Toggle visibility of password inputs for Symfony Forms

26508.0k5](/packages/symfony-ux-toggle-password)[netgen/layouts-core

Netgen Layouts enables you to build and manage complex web pages in a simpler way and with less coding. This is the core of Netgen Layouts, its heart and soul.

3689.4k10](/packages/netgen-layouts-core)[symfony/ux-cropperjs

Cropper.js integration for Symfony

19280.3k3](/packages/symfony-ux-cropperjs)[netgen/content-browser

Netgen Content Browser is a Symfony bundle that provides an interface which selects items from any kind of backend and returns the IDs of selected items back to the calling code.

14112.1k8](/packages/netgen-content-browser)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
