Symfony2 error : Case mismatch between loaded and declared class names: - symfony

I'm working on Symfony2 and i updated my project with composer.phar update
Now, when i check my site with app_dev.php i always have this error :
Case mismatch between loaded and declared class names: Blu\ProjectBun
dle\Entity\AccountRepository vs Blu\ProjectBundle\Entity\AccountRepos
itory
It's the same when i clear the dev cache, manually or not. I have nothing special in AccountRepository.php..
Any ideas ?
Edit : I already tried to add if ($name !== $class && 0 === strcasecmp($name, $class)) { in DebugClassLoader.php and no effect

Intent to var_dump($name) and var_dump($class) and strcasecmp($name, $class) to see why you enter in the condition.

though the answer was a typo in the class namespace, this errors occurs also if your entity is defined via xml, i.e. User.orm.xml, and you accidentally name the file lower-case, this will drive nuts the xml loader
create FooNamespace\BarBundle\Resources\config\User.orm.xml
create FooNamespace\BarBundle\Entity\User.php (class User { ... })

I had this problem and after trying all the solutions I found, no one of them worked for me. I am working with Symfony 2.8, Doctrine ORM and Sonata Admin Bundle and this exception appeared when I added an admin class (for a class related with the class showed in the exception message) and I tried to open it.
My mistake was I wrote the name of the database tables in lowercase in Doctrine annotations in the class related, check if you have it in uppercase:
ORM\ManyToOne(targetEntity="Product")

This is a known bug in Symfony2 :
https://github.com/symfony/symfony/commit/8e9cc35
It has been merged in 2.5 but not tagged yet (source)
To check if this is really the case for you, you might want to try modifying the src/Symfony/Component/Debug/DebugClassLoader.php file manually :
// Line 178
if ($name !== $class && 0 === strcasecmp($name, $class)) {
... and check if you still have the problem after clearing your cache

Please Add this if condition in DebugClassLoader.php File at line 177
if ($name === $class) {
if ($name !== $class && 0 === strcasecmp($name, $class)) {
throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: %s vs %s', $class, $name));
}
}
It will solve your problem
Location: root\Projectname\Symfony\vendor\symfony\symfony\src\Symfony\Component\Debug
thanks

Your controller name first word is lowercase in your routing.yml
usr_teacher_new:
path: /new
defaults: { _controller: CoreUserBundle:teacher:newteacher }
like teacher..
will be Teacher

Related

Silverstripe 4, How to solve database table conflict that maps to same database table

So I made a mistake and accidentally defined two classes that lead to the same database table
<?php
namespace Sca {
use SilverStripe\ORM\DataObject;
class Gallery extends DataObject {
private static $table_name = 'Gallery';
// ...
}
}
And the other class
<?php
namespace Sca {
use SilverStripe\ORM\DataObject;
class GalleryHolder extends DataObject {
private static $table_name = 'Gallery';
// ...
}
}
Then I ran /dev/build and the site crashed. Now the only thin I see is the apache error on apache log under /var/log/apache/..
[2019-08-05 23:36:32] error-log.ERROR: Uncaught Exception
LogicException: "Multiple classes ("Sca\GalleryHolder", "Sca\Gallery")
map to the same table: "Gallery"" at
/var/www/demo/sc2/vendor/silverstripe/framework/src/ORM/DataObjectSchema.php
line 299 {"exception":"[object] (LogicException(code: 0): Multiple
classes (\"Sca\GalleryHolder\", \"Sca\Gallery\") map to the same
table: \"Gallery\" at
/var/www/demo/sc2/vendor/silverstripe/framework/src/ORM/DataObjectSchema.php:299)"}
[]
I dumped the database and $ grep'ed the dirs with no success to find the place where there is defined GalleryHolder that leads to creating Gallery table for that class. No results. I also deleted the class file for GalleryHolder and ran again /dev/build but still gas that error and "Server error" screen when visiting from the web.
Is there any suggestions where to clear the cache or schema to resolve the conflict?
So I found a quick fix. I went to /var/www/demo/sc2/vendor/silverstripe/framework/src/ORM/DataObjectSchema.php:299
and commented out the lines that was throwing an error and added new line that modifies the table name if there is conflict. I reset changed these lines
if ($conflict) {
// throw new LogicException(
// "Multiple classes (\"{$class}\", \"{$conflict}\") map to the same table: \"{$table}\""
// );
$table = $table . '_dupl';
}
Then I was able to load the page again and it rebuilt the cache by it self and I uncomented previousley commented out lines at /var/www/demo/sc2/vendor/silverstripe/framework/src/ORM/DataObjectSchema.php:299 .

graphaware/neo4j-php-ogm event listeners

I recently created a new symfony project (3.1) with a dependency on graphaware/neo4j-php-ogm and neo4j/neo4j-bundle to manage my database.
Then I created a new Entity class named User with properties (login, password, ...) and I want to automatically set the current date before the flush event occurs (on preFlush).
I saw the PRE_FLUSH constant in neo4j-php-ogm/src/Events.php (https://github.com/graphaware/neo4j-php-ogm/blob/master/src/Events.php) but I haven't found any information about it in the documentation.
Well, my question is : Can we use this functionality in the actual version of the OGM ? If yes, do you have an example of the usage ?
Thank you for your help !
Yes you can, it is not documented you are right, I'll make sure it will be soon.
Integration test here : https://github.com/graphaware/neo4j-php-ogm/blob/master/tests/Integration/EventListenerIntegrationTest.php
First, You need create a class that will act as EventListener to the preFlush event of the EntityManager and a method reacting to the event :
<?php
namespace GraphAware\Neo4j\OGM\Tests\Integration\Listeners;
use GraphAware\Neo4j\OGM\Event\PreFlushEventArgs;
use GraphAware\Neo4j\OGM\Tests\Integration\Model\User;
class Timestamp
{
public function preFlush(PreFlushEventArgs $eventArgs)
{
$dt = new \DateTime("NOW", new \DateTimeZone("UTC"));
foreach ($eventArgs->getEntityManager()->getUnitOfWork()->getNodesScheduledForCreate() as $entity) {
if ($entity instanceof User) {
$entity->setUpdatedAt($dt);
}
}
}
}
Then you can register this event listener after having creating the entity manager :
/**
* #group pre-flush
*/
public function testPreFlushEvent()
{
$this->clearDb();
$this->em->getEventManager()->addEventListener(Events::PRE_FLUSH, new Timestamp());
$user = new User("ikwattro");
$this->em->persist($user);
$this->em->flush();
$this->assertNotNull($user->getUpdatedAt());
var_dump($user->getUpdatedAt());
}
Result of the test :
ikwattro#graphaware-team ~/d/g/p/ogm> ./vendor/bin/phpunit tests/ --group pre-flush
PHPUnit 5.6.2 by Sebastian Bergmann and contributors.
Runtime: PHP 5.6.27
Configuration: /Users/ikwattro/dev/graphaware/php/ogm/phpunit.xml.dist
. 1 / 1 (100%)int(1486763241)
Time: 378 ms, Memory: 5.00MB
OK (1 test, 1 assertion)
Result in the database :
Thank you a lot ! It's work perfectly. If anyone want to use it don't forget to type your property as "int". ;)

Is is possible to have symfony2 log missing translation strings so that I know what needs adding to my xilff files?

I have a symfony project in which I've been through my twig templates and added {% trans %}...{% endtrans %} or adding translations like {{ title|trans }} where appropriate. I've also added a messages.de.xliff file and that is working perfectly for the few translations I have tried.
Is there a way I can get a list of strings missing from my xliff file? It's quite hard to keep track of every translation as I add it. It seems like it should log a failure to get a translation in a log file somewhere, but I've been googling a while and can't find anything.
Hi Try following May Be helpful.
https://github.com/schmittjoh/JMSTranslationBundle/blob/master/Resources/doc/index.rst
Very powerful tool and definitely takes care of you problem.
This is a very crappy patch to apply in vendor/symfony that does what I need. Probably not to be run on a production server!
diff --git a/src/Symfony/Component/Translation/MessageCatalogue.php b/src/Symfony/Component/Translation/MessageCatalogue.php
index b55676f..98a5cba 100644
--- a/src/Symfony/Component/Translation/MessageCatalogue.php
+++ b/src/Symfony/Component/Translation/MessageCatalogue.php
## -128,6 +128,8 ## class MessageCatalogue implements MessageCatalogueInterface
return $this->fallbackCatalogue->get($id, $domain);
}
+ error_log('Translation not found: "' . $id . '"');
+
return $id;
}
My solution was to overwrite the Translator and MessageCatalogue classes.
Translator:
class RegisteringTranslator extends \Symfony\Component\Translation\Translator
{
protected function loadCatalogue($locale)
{
parent::loadCatalogue($locale);
if ( ! $this->catalogues[$locale] instanceof RegisteringMessageCatalogue) {
$registeringCatalogue = new RegisteringMessageCatalogue($locale);
$registeringCatalogue->addCatalogue($this->catalogues[$locale]);
$this->catalogues[$locale] = $registeringCatalogue;
}
}
}
Catalogue:
class RegisteringMessageCatalogue extends \Symfony\Component\Translation\MessageCatalogue
{
public function get($id, $domain = 'messages')
{
if ( ! $this->has($id, $domain)) {
error_log('Translation not found: "' . $id . '"');
}
return parent::get($id, $domain);
}
}
Of course you need to use the new Translator class.
Also not very nice because it uses the protected methods and properties of Translator class. But better than changing the Symfony code directly.
I know this is an old question, but I'm posting here just in case somebody still has the same problem.
Starting from Symfony 2.6, you'll find a very nice addition to the web debug toolbar that shows how many translations you're missing.
By clicking it, the profiler will display a detailed list of missing translation.
Works out of the box, without any configuration.
Normally you should be able to use the Symfony command debug:translation via app/console.
Something like this:
$ php app/console debug:translation --only-missing <locale> <Bundle Name>
A concrete example would be:
$ php app/console debug:translation --only-missing nl AppBundle
That would output:
----------- ---------- ------------------------------------------------------------------------------------------------------- ------------------------------------------
State Domain Id Message Preview (nl)
----------- ---------- ------------------------------------------------------------------------------------------------------- ------------------------------------------
missing messages Create a clean selection Create a clean selection
missing messages New Selection New Selection
missing messages login.labels.geoserver_url login.labels.geoserver_url

Implementing GeocodableBehavior in Symfony 1.4 (using Propel)

I'm trying to implement the GeocodableBehavior on a Symfony 1.4 (with Propel 1.6) project i'm working on, but until now it's a complete failure. I've tried to search if other people but I didn't found anything, like if I was the only one having troubles with this.
So, maybe I'm missing something very very easy, but following the instructions given on the GeocodableBehavior leads to nothing but errors, and I can't figure out where's the problem.
I followed instructions for the GeocodableBehavior (here -> http://www.propelorm.org/cookbook/geocodable-behavior.html)
This seems to work as i'm getting the latitude/longitude columns created on my model. Until then, it works fine.
Where things get a little more complicated is when trying to save an object with the GeocodableBehavior, there's problems with the Geocoder class.
(Documentation here -> https://github.com/willdurand/Geocoder)
My class is Point, referring to a geolocated point, an address. When creating a Point using sf admin generator, the behavior which is supposed to use some fields (street, postal_code, country, etc) to query the GoogleMaps api, just fails to use the Geocoder class.
Fatal error: Class 'Geocoder\Geocoder' not found in /var/www/vhosts/www._________.local/lib/model/om/BasePoint.php on line 3717
I put the Geocoder class in a lib/vendor/geocoder folder, I tried to use the autoload.yml file to load it, but nothing changes...
autoload:
geocoder:
name: geocoder
path: %SF_LIB_DIR%/vendor/geocoder
recursive: on
There's something i'm missing in how to load those classes in my sf project, and i can't find what. Geocoder package has an autoload.php file but i didn't manage to "load" it successfully...
Thanks in advance.
I know it's kinda giving up on the autoloader, but you could establish a register function in /config/ProjectConfiguration.class.php. The only downside is that you will need to add a call to the function before any block that uses Geocoder.
class ProjectConfiguration extends sfProjectConfiguration
{
static protected $geocoderLoaded = false;
static public function registerGeocoder()
{
if (self::$geocoderLoaded) {
return;
}
require_once sfConfig::get('sf_lib_dir') . '/vendor/geocoder/autoload.php';
self::$geocoderLoaded = true;
}
...
}
Then just execute ProjectConfiguration::registerGeocoder(); anywhere you'd need the class. It's more annoying than getting the autoloader to work, but it's at least dependable.
Did you check your autoload cache to see it there is something related to Geocoder?
/cache/[apps_name]/dev/config/config_autoload.yml.php
/cache/project_autoload.cache
Maybe, manually add the autoload in the /config/ProjectConfiguration.class.php:
class ProjectConfiguration extends sfProjectConfiguration
{
public function setup()
{
require_once sfConfig::get('sf_lib_dir').'/vendor/geocoder/src/autoload.php';
Using the built-in autoloader should be a working option, but you can also combine symfony's autoloader with a "PSR-0 enabled" one. Basically, this boils down to the following implementation:
public function setup()
{
// plugin stuff here
// register the new autoloader
spl_autoload_register(array($this, 'autoloadNamespace'));
}
public function autoloadNamespace($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\'))
{
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
// make sure that the path to Geocoder is correct
foreach(array(
sfConfig::get('sf_lib_dir').'/vendor/Geocoder/src' . DIRECTORY_SEPARATOR . $fileName . $className . '.php',
) as $fileName)
{
if (file_exists($fileName))
{
require $fileName;
return true;
}
}
return false;
}
With this additional autoloader, your application should be able to use Geocoder.

Can I include an optional config file in Symfony2?

I want to make a local config file, config_local.yml, that allows each development environment to be configured correctly without screwing up other people's dev environments. I want it to be a separate file so that I can "gitignore" it and know that nothing essential is missing from the project, while simultaneously not having the issue of git constantly telling me that config_dev.yml has new changes (and running the risk of someone committing those changes).
Right now, I have config_dev.yml doing
imports:
- { resource: config_local.yml }
which is great, unless the file doesn't exist (i.e. for a new clone of the repository).
My question is: Is there any way to make this include optional? I.e., If the file exists then import it, otherwise ignore it.
Edit: I was hoping for a syntax like:
imports:
- { resource: config.yml }
? { resource: config_local.yml }
I know this is a really old question, and I do think the approved solution is better I thought I would give a simpler solution which has the benefit of not changing any code
You can use the ignore_errors option, which won't display any errors if the file doesn't exist
imports:
- { resource: config_local.yml, ignore_errors: true }
Warning, if you DO have a syntax error in the file, it will also be ignored, so if you have unexpected results, check to make sure there is no syntax error or other error in the file.
There is another option.
on app/appKernel.php change the registerContainerConfiguration method to this :
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
$extrafiles = array (
__DIR__.'/config/config_local.yml',
);
foreach ($extrafiles as $filename) {
if (file_exists($filename) && is_readable($filename)) {
$loader->load($filename);
}
}
}
this way you have a global config_local.yml file that overwrites the config_env.yml files
A solution is to create a separate environment, which is explained in the Symfony2 cookbook. If you do not wish to create one, there is another way involving the creation of an extension.
// src/Acme/Bundle/AcmeDemo/DepencendyInjection/AcmeDemoExtension.php
namespace Acme\DemoBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class AcmeDemoExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
// All following files will be loaded from the configuration directory
// of your bundle. You may change the location to /app/ of course.
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
try
{
$loader->load('config_local.yml');
}
catch(\InvalidArgumentException $e)
{
// File was not found
}
}
}
Some digging in the Symfony code revealed me that YamlFileLoader::load() FileLocator::locate() will throw \InvalidArgumentException, if a file is not found. It is invoked by YamlFileLoader::load().
If you use the naming conventions, the extension will be automatically executed. For a more thorough explanation, visit this blog.
I tried both above answers but none did work for me.
i made a new environment: "local" that imports "dev", but as you can read here: There is no extension able to load the configuration for "web_profiler" you also had to hack the AppKernel class.
Further you couldnt set config_local.yml to .gitignore because the file is necessary in local env.
Since i had to hack the AppKernel anyway i tried the approach with the $extrafiles but that resulted in "ForbiddenOverwriteException"
So now what worked for me was a modification of the $extrafiles approach:
replace in app/AppKernel.php
$loader->load(__DIR__ . '/config/config_' . $this->getEnvironment() . '.yml');
with
if ($this->getEnvironment() == 'dev') {
$extrafiles = array(
__DIR__ . '/config/config_local.yml',
);
foreach ($extrafiles as $filename) {
if (file_exists($filename) && is_readable($filename)) {
$loader->load($filename);
}
}
} else {
$loader->load(__DIR__ . '/config/config_' . $this->getEnvironment() . '.yml');
}

Resources