Access database in BeforeFeature - symfony

How do I access my database via doctrine in a BeforeFeature? I am unable to get my entity manager because my kernel is null...this is what I am trying:
/**
* #BeforeFeature
*/
public static function cleanDatabase(FeatureEvent $event)
{
$context = new FeatureContext(array());
$context->thereAreNoUsersInTheDatabase();
}
It tells me that I cannot get container from a non-object (the kernel). Why isn't KernelAwareInterface assigning the kernel when I manually create that FeatureContext?

KernelAwareInterface just provides a method "setKernel" method, you still have to call manually if you instantiate a new FeatureContext object

You can use FriendlyContext that provide you a "#reset-schema" annotation. See https://github.com/KnpLabs/FriendlyContexts/blob/master/doc/context-entity.md#reset-schema .
Do not hesitate to read the full documentation and the code that doesn't uses the SymfonyExtension.

Related

excluding tables with setExcludedDoctrineTables when loading fixtures with liip TestFixturesBundle

I'm trying to use Liip test bundle to load fixtures from code using the loadFixtures() method from FixturesTrait
However, I need to exclude the RESOURCE table that I don't want to be dropped in the process. If I understand correctly, this should be easy using the setExcludedDoctrineTables method according to the doc https://github.com/liip/LiipTestFixturesBundle/blob/master/doc/database.md
Unfortunately, when I run this code, the table RESOURCES gets dropped with all the others.
Can anybody see why ?
not sure if that's relevant but I'm using a mysql db in a separate docker container.
<?php
namespace App\Tests\Controller;
use Symfony\Component\Panther\PantherTestCase;
use Symfony\Component\Panther\Client;
use Facebook\WebDriver\WebDriverBy as By;
use Facebook\WebDriver\Exception\TimeoutException;
use Liip\FunctionalTestBundle\Test\WebTestCase;
use Symfony\Component\Panther\PantherTestCaseTrait;
use Liip\TestFixturesBundle\Test\FixturesTrait;
use App\Repository\UserRepository;
use App\DataFixtures\UserFixtures;
use App\DataFixtures\AccountFixtures;
abstract class AbstractPantherTest extends WebTestCase{
// use trait so we can combine Liip and Panther features
use PantherTestCaseTrait; // this is the magic. Panther is now available.
// provide fixtures loading feature
use FixturesTrait;
// #var Symfony\Component\Panther\Client
protected static $client;
//Initialize the test case
function setUp():void
{
static::bootKernel();
if(self::$client === null){
self::$client = self::createPantherClient(['browser' => PantherTestCase::FIREFOX]);
$this->setExcludedDoctrineTables(["RESOURCES"]);
$this->loadFixtures([
UserFixtures::class,
]);
// retrieve the test user
$userRepository = static::$container->get(UserRepository::class);
// retrieve the test user
$testUser = $userRepository->findOneByUsername('Administrator');
// simulate $testUser being logged in
self::doLogin($testUser->getUsername(), 'xxx');
}
}
}
Answering my own question as I just found out the issue. Sometimes a good night of sleep is all you need :)
So this code is actually working. The table RESOURCES got dropped because the setUp method was redefined in the concrete class implementing the test and that redefinition included another call to loadFixtures, but for a different data class and without the exclusion :
<?php
namespace App\Tests\Controller;
use App\DataFixtures\DiscountFixtures;
class DiscountControllerWebTest extends AbstractPantherTest
{
function setUp():void
{
parent::setUp();
$this->loadFixtures([
DiscountFixtures::class,
]);
}

Loggable capability for entity with trace of persistance place (location) - doctrine

Hi I am using Doctrine with DoctrineBehaviors bundle in order to log history of changes for entities. Everything is working fine except one thing. I will need information where is the location of change that is going to be saved. For example if that change happened in cron command or in front end controller by some user etc.
Logging class is looking like this (similar to this) :
/** service: "entity_logger" **/
class EntityLogger
{
/**
* #var EntityManager
*/
protected $em;
public function __construct(EntityManager $em = null)
{
$this->em = $em;
}
function __invoke($message)
{
$this->em->persist(new LogMessage($message));
$this->em->flush();
}
}
and it's set as service. So my question is how to manage information of location of change? I will need somehow to send beside entity that is going to be persist one more thing: location of that change. As I see it there are at least two options :
A) store value of location to that service "entity_logger" before persist/flush happens. Have property "location" inside service and put it into LogMessage obj. Something like:
$this->get('entity_logger')->setCurrentLocation("Cron for sync");
$this->em->persist($entityOne);
$this->em->flush();
B) get stack trace and see what class has call persist/flush and then see how to handle that information
First option requires editing of all current locations of persist and second one don't have that overhead but what is the better approach?
Is there even better way of doing that?
Thanks

Symfony2-entityManager inside an Entity

I am using Symfony version 2.7.6. I have created an entity named EmployeeBasicInfo having fields
firstname
lastname
identificationCode etc
I have created a callback function for validating Identification code in EmployeeBasicInfo entity itself which looks like
/**
* #Assert\Callback(groups={"edit_myinfo"})
*/
public function validateIdentificationCode(ExecutionContextInterface $context)
{
if ($this->getEmployeeFirstName() == 'fakename') {
$context->buildViolation('This name sounds totally fake!')
->atPath('employeeFirstName')
->addViolation();
}
}
and this callback function works properly
Actually I want such a callback functionality which checks identidfication code against database. I have added $em = $this->getDoctrine()->getManager(); inside the callback function and the error is like Attempted to call an undefined method named "getDoctrine" of class "XXX\EmployeeBundle\Entity\EmployeeBasicInfo".. Please advise me the effective way
Do not inject the EntityManager in your Entity. One basic concept of the DataMapper-Pattern is, that your entity does not have to know about your data source and its connectors.
I'd suggest to write a custom validation constraint, in which you inject the dependencies you need.
EntityManager, Repository to query, etc. Whatever service suits you.
Have a look at how to create custom constraint validators with dependencies
I would suggest you use a service to do this
class EmployeeUtility($connection)
{
public function __construct($conn) { $this->connection = $v; }
public function validateIdentificationCode($emloyeeId, $validationCode)
{
// Your code here
}
}
In your controller, you inject the service:
$employeeUtility = $this->get('employee.utility');
$employeeUtility->validateIdentificationCode(1,'GF38883dkDdW3373d');
Alternatively, add the code in a repository class.

Symfony 2: Static function [JMSTranslation]

I'm currently working on a project that the previous developer integrated with JMSTranslationBundle.
At this moment, I've did some modification to the application, one of them was to turn the menu to be highly dynamic. (Basically, the user logic of the application have 3 layers and each layer have their own menu).
The menu are stored into the database and accessible through the doctrine entity. To display the label, I store into the DB the "label code" which is used by JMSTranslationBundle as a key to identify it. The desc is by default empty until setted into the translation file. (editable with the _trans route).
Into the documentation of JMS, it is mentionned that one can implement TranslationContainerInterface so when the compilation of the translation file (who are XLIFF file currently) are done, each class implementing this will be called to return a list of Message objects. Here's my issue:
The function to implement is static, meaning that when call, my model Menu (who handle to logic of fetching throught Doctrine repo) is not loaded via the service manager. This means that I do not receive the repository object (since it's loaded by service and pass through the controller):
public function __construct(MenuRepository $objMenuRepo)...
The definition of the function I implements is:
static function getTranslationMessages(){ ... }
My question is: how can I obtain the doctrine (either manager or repository) within that static function . (Since this will be only called on translation initial generation and not by the site itsef, performance is not an issue I worry about).
Also: If anyone have better alternative to propose (that wouldn't involved getting rid of this translation bundle, trust me, it would take quite an amount of time right now), I'm opened to hear them.
Thank you :-)
If some of you are interested, I had to use an alternative solution.
Although it doesn't answer the question on how to use a service within a static context, it will help those who ran into the same issue I had when attempting to implement with JMSTranslation.
To implement the solution (to extract translation key from the database), I had to use the JMS\TranslationBundle\Translation\ExtractorInterface.
I have implement it under this format:
class TranslationRepositoriesExtractor implements ExtractorInterface{
//Loaded through the service container
public function __construct(EntityRepository $objRepositoryNeeded);
// Implementation of the interface ExtractorInterface.
// Within this function, I've used the EntityRepository received in the
// constructor to fetch the list of keys that would be use for translating
/**
* #return \JMS\TranslationBundle\Model\Message[]
*/
public function extract()
}
As you can notice, the extract function return an array of \JMS\TranslationBundle\Model\Message.
After implementing this function, you have to add your object as a service and make it recognizable by JMSTranslationBundle as an extractor. To do so:
<!-- Replace the id of the service, the class path, the id of the argument and the alias
named you want by the value you need in your application -->
<service id="idOrYourService" class="Path\Of\Class\TranslationRepositoriesExtractor">
<argument type="service" id="repository.needed" />
<tag name="jms_translation.extractor" alias="NameOfAlias" />
</service>
The alias tag is used within JMSTranslationBundle to recognize your class as an extractor.
Finally, when generating the files, I had to had to enable the extractor. This can be done via the config, but in my case, was done manually through the command line
php app/console translation:extract --enable-extractor=NameOfAlias en
// NameOfAlias is the same name as the one defined in the tag of your service
I hope I didn't forget any step (if so, feel free to reply in a comment and I'll update the answer).
Happy coding :-)
Using this input, I ended up coding this version of the extractor.
<?php
namespace MyBundle\Service;
use Doctrine\ORM\EntityManager;
use JMS\TranslationBundle\Model\Message;
use JMS\TranslationBundle\Model\MessageCatalogue;
use JMS\TranslationBundle\Translation\ExtractorInterface;
/**
* Extracts translatable strings from Doctrine entities
*
* #package MyBundle\Service
*/
class EntityTranslationExtractor implements ExtractorInterface
{
/**
* #var EntityManager
*/
private $entityManager;
/**
* EntityTranslationExtractor constructor.
*
* #param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* #return MessageCatalogue
*/
public function extract()
{
$messageCatalogue = new MessageCatalogue();
// Sample portion of the extraction
$translatableEntities = $this->entityManager->getRepository('MyBundle:MyEntity')->findAll();
foreach ($translatableEntities as $entity) {
$message = new Message($entity::class .'.'. $entity->getName(). '.name');
$message->setDesc(ucwords($entity->getName()));
$messageCatalogue->add($message);
}
return $messageCatalogue;
}
}

How do I access a repository from the bundle class in symfony2?

So, I'm using the bundle class to do most of my work as I dont need controllers (src\CSFs\QuicklinksBundle\CSFsQuicklinksBundle.php).
From the FrontController of another bundle, I get the quicklinks bundle, inject the container object into the bundle class (above) and then, within the bundle class, extract templating to return HTML, this works fine. However, I'm having trouble with repositories.
/**
* Get the container object, so we can use all the symfony2 fun stuffs
*/
public function injectContainer($cont)
{
// Template
$this->tpl = $cont->get('templating');
// EM
$this->em = $cont->get('doctrine')->getEntityManager();
}
/**
*
**/
public function doStuff()
{
$products = $this->em->getRepository('QuicklinksBundle:Quicklinks')
->getUsersWithQuicklinks();
}
The error I get is:
Unknown Entity namespace alias 'QuicklinksBundle'.
I have both the generated entity file and a repository class with the getUsersWithQuicklinks() method defined.
How do I get the entity manager to know about my repositories?
Thanks,
Mike
Change:
$this->em->getRepository('QuicklinksBundle:Quicklinks')
To:
$this->em->getRepository('CSFsQuicklinksBundle:Quicklinks')
And I'm assuming you have an Entity named 'Quicklinks'

Resources