Skip to content

Instantly share code, notes, and snippets.

@gnutix
Last active March 14, 2024 04:53
Show Gist options
  • Save gnutix/e466679853230c833778341ad8067330 to your computer and use it in GitHub Desktop.
Save gnutix/e466679853230c833778341ad8067330 to your computer and use it in GitHub Desktop.
Custom Faker Provider for generating Symfony encoded password using UserPasswordEncoderInterface.
services:
_defaults:
autowire: true
autoconfigure: true
# Needed to autowire the first argument of the constructor for custom Faker providers
Faker\Generator: ~
App\Faker\Provider\:
resource: '%kernel.project_dir%/src/App/Faker/Provider'
public: true
tags: ['hautelook_alice.faker.provider']
hautelook/alice-bundle v1.4.1
nelmio/alice v2.3.1
symfony/symfony v3.3.0-BETA1
Symfony\Component\Security\Core\User\User:
member:
__construct: ['member', '<symfonyPassword("Symfony\Component\Security\Core\User\User", "member", "salt")>', ['ROLE_USER']]
admin:
__construct: ['admin', '<symfonyPassword("Symfony\Component\Security\Core\User\User", "admin", "salt")>', ['ROLE_ADMIN']]
<?php declare(strict_types=1); # src/App/Faker/Provider/SymfonyPasswordProvider.php
namespace App\Faker\Provider;
use Faker\Generator;
use Faker\Provider\Base;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
final class SymfonyPasswordProvider extends Base
{
/** @var EncoderFactoryInterface */
private $encoderFactory;
/**
* {@inheritdoc}
* @param EncoderFactoryInterface $encoderFactory
*/
public function __construct(Generator $generator, EncoderFactoryInterface $encoderFactory)
{
parent::__construct($generator);
$this->encoderFactory = $encoderFactory;
}
/**
* @param string $userClass
* @param string $plainPassword
* @param string|null $salt
*
* @return string
*/
public function symfonyPassword(string $userClass, string $plainPassword, string $salt = null): string
{
$password = $this->encoderFactory->getEncoder($userClass)->encodePassword($plainPassword, $salt);
return $this->generator->parse($password);
}
}
@gnutix
Copy link
Author

gnutix commented May 9, 2017

The , "salt" parameter in the fixtures is optional if you use bcrypt as encryption ($salt = null).

@Asenar
Copy link

Asenar commented May 18, 2021

Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment