Darkstarone
Darkstarone

Reputation: 4730

Symfony 3 Datafixtures using parameter.yml values

I'm using LDAP in my User data fixtures and I don't want to hardcode the LDAP login options. Initially, I tried this:

$options = array(
            'host' => '%ldap_host%',
            'port' => '%ldap_port%',
            'useSsl' => true,
            'username' => '%ldap_username%',
            'password' => '%ldap_password%',
            'baseDn' => '%ldap_baseDn_users%'
        ); 

But that didn't work. I did some research and realized I needed to include the container in my fixtures. However, it's at this point I'm unsure what my next step is.

As I understand it I need to use the container and it's get method to get the service containing the parameters, but I don't know what that is:

$this->container->get('parameters');

Doesn't work, so I'm wondering what I should use.

My full datafixture is as follows:

class LoadFOSUsers extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }


    public function load(ObjectManager $manager)
    {
        $this->container->get('parameters');

        // Not sure how to access param values. 
        $options = array(
            'host' => '%ldap_host%',
            'port' => '%ldap_port%',
            'useSsl' => true,
            'username' => '%ldap_username%',
            'password' => '%ldap_password%',
            'baseDn' => '%ldap_baseDn_users%'
        );

        $ldap = new Ldap($options);
        $ldap->bind();

        $baseDn = '%ldap_baseDn_users%';
        $filter = '(&(&(ObjectClass=user))(samaccountname=*))';
        $attributes=['samaccountname', 'dn', 'mail','memberof'];
        $result = $ldap->searchEntries($filter, $baseDn, Ldap::SEARCH_SCOPE_SUB, $attributes);

        foreach ($result as $item) {
            echo $item["dn"] . ': ' . $item['samaccountname'][0] . PHP_EOL;
        }
    }

    public function getOrder()
    {
        // the order in which fixtures will be loaded
        // the lower the number, the sooner that this fixture is loaded
        return 8;
    }
}

Upvotes: 3

Views: 1409

Answers (1)

Mateusz Sip
Mateusz Sip

Reputation: 1280

You just have to fetch them from container via getParameter('name') or get them all in a bag via getParameterBag().

So:

    $options = array(
        'host' => $this->container->getParameter('ldap_host'),
        'port' => $this->container->getParameter('ldap_port'),
        'useSsl' => true,
        'username' => $this->container->getParameter('ldap_username'),
        'password' => $this->container->getParameter('ldap_password'),
        'baseDn' => $this->container->getParameter('ldap_baseDn_users')
    );

etc.

Upvotes: 4

Related Questions