0

I would like to create a command akeneo into my bundle who query my products like this.

So, after multiple test, i have always this error:

In ProductQueryBuilderFactory.php line 68:
Token cannot be null on the instantiation of the Product Query Builder.

Here is my code :

$pqbFactory =  $this->getApplication()->getKernel()->getContainer()->get('pim_catalog.query.product_query_builder_factory');
$pqb = $pqbFactory->create(['default_locale' => 'fr_FR', 'default_scope' => 'ecommerce']);  // error
Paul
  • 352
  • 3
  • 6
  • 17
  • Don't forget to give your Akeneo PIM version, response you receive may vary a lot depending on the version you use :) – grena Jun 21 '18 at 08:00

2 Answers2

2

The PQB needs to have an authenticated user to be able to apply right filters on the results. To authenticate a user in your command you can take inspiration from the get product command. We simply take a --username argument and manually add it to the token storage.

$userManager = $this->getContainer()->get('pim_user.manager');
$user = $userManager->findUserByUsername($username);

if (null === $user) {
    $output->writeln(sprintf('<error>Username "%s" is unknown<error>', $username));

   return false;
}

$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->getTokenStorage()->setToken($token);
Julien Sanchez
  • 843
  • 4
  • 12
2

To complete Julien's answer, note that this error comes only if you are using the Enterprise Edition (EE). Indeed, in the EE, we decorate the normal product_query_builder_factory to apply permission.

If you don't want to apply permission (and don't use any token), you can use the pim_catalog.query.product_query_builder_factory_without_permission:

<?php

require __DIR__.'/vendor/autoload.php';

$kernel = new AppKernel('dev', true);
$kernel->boot();

$pqbFactory =  $kernel->getContainer()->get('pim_catalog.query.product_query_builder_factory_without_permission');
$pqb = $pqbFactory->create(['default_locale' => 'fr_FR', 'default_scope' => 'ecommerce']);  // you won't have any error
grena
  • 1,011
  • 1
  • 10
  • 25