Symfony2 Error: No mapping file found named - doctrine

I am using Symfony2 and when i try to generate the schema ($ php app/console doctrine:generate:schema) i got an error..
[Doctrine\ORM\Mapping\MappingException]
No mapping file found named 'xxx.UserBundle.Entity.User.php' for class 'xxx\UserBundle\Entity\User'.
I only have 2 Bundles in the proyect:
UserBundle
FileBundle
I connect the FileBundle with the UserBundle with this code:
/**
* #ORM\ManyToOne(targetEntity="xxx\UserBundle\Entity\User")
**/
protected $user;
The headers of the files are something like this:
namespace xx\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
**/
class User
{ ###...###}
FileBundle is very similar..
Thanks!

You are mixing Doctrine mapping formats, you have annotations and at least one XML file in Resources/config/doctrine
From the symfony docs:
"A bundle can accept only one metadata definition format. For example,
it's not possible to mix YAML metadata definitions with annotated PHP
entity class definitions."
So the solution is:
You cannot mix different Doctrine mapping formats in a given bundle. So either use annotations for all entities or use XML for all.

It is somehow strange to me that you're using PHPDriver for ORM and not AnnotationDriver, since your database info in classes is in annotations.
Anyhow, if php app/console doctrine:mapping:info command gives you only 1 entity that means that your other bundle containing User class is not loaded in app/AppKernel.php file. Load your UserBundle by adding line
new xxx\UserBundle\xxxUserBundle(),
to the $bundles array in registerBundles() function. After that, this function should look something like this:
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
new xx\FileBundle\xxFileBundle(),
new xxx\UserBundle\xxxUserBundle(),
);
if (in_array($this->getEnvironment(), array('dev', 'test'))) {
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
Of course, change 'xx' and 'xxx' with your real names.
Hope this helps.

I agree with #ilanco 100%. In addition, the solution is to REMOVE any .xml file in folder, for example:
C:\xampp\htdocs\localxyz\src\AppBundle/Resources/config/doctrine/Comment.orm.xml
these xml files created when you run such command:
C:\xampp\htdocs\localxyz>php app/console doctrine:mapping:import --force AppBundle xml
Dung.

Good day,
Although I know that this has been posted years ago, but will just like to post my answer here, perhaps it could help someone :)
just simply clear the cache, it works for me though
php bin/console cache:clear
Thanks

I can't think of a reason why this is happening but I will take a leap here.
Try editing your config.yml. doctrine section should look like this:
doctrine:
dbal:
default_connection: my_connection_name
connections:
fmefb:
host: %database_host%
dbname: %database_name%
user: %database_user%
password: %database_password%
driver: %database_driver%
port: %database_port%
charset: UTF8
orm:
default_entity_manager: my_entity_manager
entity_managers:
my_entity_manager:
connection: my_connection_name
mappings:
CompanyNameSiteBundle: ~
CompanyNameAdminBundle: ~
CompanyNameSomethingElse: ~
Notice the mappings list on the bottom. All bundles which are "linked" are included here.
Hope this helps....

Related

Kreait\Firebase\Exception\Database\DatabaseError 404 Not Found

I am new to Laravel so i have been trying to connect Laravel to a Firebase Realtime database but i am getting this error Kreait\Firebase\Exception\Database\DatabaseError
404 Not Found . I have the Service account in the controllers directory and properly referenced in the Firebase controller.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Kreait\Firebase;
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Database;
class FirebaseController extends Controller
{
$factory = (new Factory)->withServiceAccount(__DIR__.'/myServiceAccount.json');
$database = $factory->createDatabase();
$newPost = $database->getReference('myrealtime-default-rtdb/blog/posts')->push(['title' => 'Post title','body' => 'This should probably be longer.']);
echo"<pre>";
print_r($newPost->getvalue());
}
}
}
Using the new Factory pattern won't work (it's already handled by the Laravel Service Provider).
Personally I'd recommend using the app() helper. It's quite easy but before that make sure you've followed the installation process in the documentation. You might've missed something
Here's a link to that: https://github.com/kreait/laravel-firebase
Also make sure you include both the path to your Service Account json file and the database URL for your project in your .env file (I prefer using this method personally)
So in your .env file you should have something like
FIREBASE_CREDENTIALS = path_to_your_service_account_file.json
FIREBASE_DATABASE_URL= https://your-project-url.firebaseio.com/
(you can find this url when you open RealTime databases in your firebase console)
If you don't use auto-discovery make sure to add Kreait\Laravel\Firebase\ServiceProvider::class to your providers in the config/app.php file
run a vendor publish
Then in your controller you could have something like this
namespace App\Http\Controllers;
class FirebaseController extends Controller {
//
protected $database;
public function __construct()
{
$this->database = app('firebase.database');
}
public function index(){
$new_post = $this->database->getReference('your-reference')>push(["title" =>"something"]);
} }
Remember: on Linux, place Firebase config files etc. in a folder that user 'apache' can read! So, for example, do not place such files in /home/myname/firebase.json. Even if you do chmod 777 firebase.json, this file may not be accessible by user 'apache', hence the 404.
Then you do not need to use env variables.
$factory = (new Factory())->withServiceAccount(DIR.'/vendor/firebase-adminsdk.json');

count(): Parameter must be an array or an object that implements Countable

I'm facing strange case. I face an error in production env not while in dev it's working fine.
Development:
Laravel 5.4.28
PHP 7.0.13
MYSQL 5.7.17
Production:
Laravel 5.4.28
PHP 7.2.1
MYSQL 5.7.20
In implementation code. I used:
namespace App;
use Illuminate\Support\Facades\Storage;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
class Artwork extends Model
{
use Searchable;
In development it works fine. But in production it gives me this error:
count(): Parameter must be an array or an object that implements Countable
in Builder.php (line 936)
as you can see in this pic:
Any idea what is the reason behind this? and how to fix?
Put this code at the beginning of your route file, it will work fine
if(version_compare(PHP_VERSION, '7.2.0', '>=')) {
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
}
This is a documented change in PHP 7.2. You need to either update Laravel to 5.6 or downgrade PHP to version 7.1.
Replace
$originalWhereCount = count($query->wheres);
by
$originalWhereCount = count((array)$query->wheres);
in
\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php
I was facing similar issue in Laravel 5.6. Where I was getting error for object based array. I knew that data in that particular variable will always remain object so i used to convert the object to array. Here is code sample:
$objectData = (array)$objectData;
echo "Total Elements in array are: ".count($objectData);
My server was on PHP 7.1 when I updated to PHP 7.2 I got the same issue.
After searching I found why this occurs. (This occurs because of a PHP update.).
so in my case, the error is solved by typecasting.
I just update all code where I used to count
Before
//this is before
count($adminDetails)
After updated
//after update all i typecast all the code where i used count
count((array)$adminDetails)
Goodluck
This error occurs because you are using a higher PHP version and your Laravel application is on an older PHP version.
✅ Simple solution:
Open: app/Providers/AppServiceProvider.php
And in: public function register() { ... } function add following code:
if(version_compare(PHP_VERSION, '7.2.0', '>=')) {
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
}
In php 7.2+ count does not work on relation objects, you need to use:
$model->relation()->exists()
Not this (less than php 7.2):
count($model->relation)
i ran into the same problem (PHP 7.2 + Laravel 5.3) but i don't see any "good" answers here. For me, the problem occurs when i tried to start a Builder from a scope method on the model: SomeModel::forUser() calls scopeForUser(). Trying to build a new Query, it trips on a count($this->wheres) that gets no initial value (null). Because the magic static call to the scope starts the builder, no other conditions have been placed in the object so the property is still null at that point.
i thought it's worth sharing my solution first, then perspective on why i consider it better than Ben's answer. It's not personal, i just disagree.
Solution
i took a cue from this answer about overriding some of the core Illuminate\Database classes...
Extend Illuminate\Database\Eloquent\Model
Mine is App\Overrides\Database\Eloquent\Model
Extend Illuminate\Database\Eloquent\Builder
Mine is App\Overrides\Database\Eloquent\Builder
Extend Illuminate\Database\Query\Builder
Can you guess? App\Overrides\Database\Query\Builder
Tell Laravel to use YOUR Eloquent\Model:
config/app.php 'aliases' array, replace the 'Eloquent' value
with your Eloquent\Model FQN
My Model:
namespace App\Overrides\Database\Eloquent;
/*
* Notes:
* * Using replacement Query\Builder with ALIAS
* * Use of Builder in this class is MY Eloquent\Builder
*/
use App\Overrides\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Eloquent\Model as EloquentModel;
class Model extends EloquentModel
{
public function newEloquentBuilder($query)
{
return new Builder($query);
}
protected function newBaseQueryBuilder()
{
$conn = $this->getConnection();
$grammar = $conn->getQueryGrammar();
return new QueryBuilder($conn, $grammar, $conn->getPostProcessor());
}
}
My Eloquent\Builder:
namespace App\Overrides\Database\Eloquent;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
class Builder extends EloquentBuilder
{
public function __construct($query)
{
parent::__construct($query);
/*
* FIX #1: Set properties treated AS arrays
* to empty arrays on construct.
*/
$this->wheres = [];
// Any other properties treated as arrays should also be initialized.
}
}
My Query\Builder:
namespace App\Overrides\Database\Query;
use Illuminate\Database\Query\Builder as QueryBuilder;
class Builder extends QueryBuilder
{
public function __construct()
{
parent::__construct(...func_get_args());
/*
* FIX #2: Set properties treated AS arrays
* to empty arrays on construct.
*/
$this->wheres = [];
// Any other properties treated as arrays should also be initialized.
}
}
This safely preserves the framework's functionality, since the only actual change you're making is initializing properties that should have been in the first place. Everything else will pass instanceof checks used for dynamic loading and dependency injection.
Opinion
While i agree with #ben-harold about every comment he made saying "NEVER edit vendor code," i disagree with the "solution." It's an oversimplification to a much more complex problem.
Upgrade Laravel: to ensure support for PHP 7.2, jumping up several minor versions - if not major releases - is impractical for a lot of teams. As a long term objective, yes of course. As something i can do to get rid of the bug for my deadline? Nope. Upgrading takes a lot of planning and frequently a lot of rewrites as structures, names, and functionality change. It's something to prioritize, but not a need-it-now answer.
Downgrade PHP: same problem. Downgrading into PHP 5.x means A) PHP is EOL, which may be a deal breaker for a lot of customers who have security policies, and B) any usage of PHP 7.x language features have to be scrapped. As with upgrading the framework this is very likely to cause a lot of headaches. It's also an even less useful solution, since walking backward in the language just puts you farther behind and will require more long-term effort.
place the below line ob code before the class name in your controllers
if (version_compare(PHP_VERSION, '7.2.0', '>=')) {
// Ignores notices and reports all other kinds... and warnings
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
// error_reporting(E_ALL ^ E_WARNING); // Maybe this is enough
}
I was facing the same issue with an external created table (Not using migration or command),
After creating the model, I just assigned a table name, but the problem was in my model protected $fillable where I assign string instead of array and error occurred.
There is 2 possible solution for that.
Assign an array to your protected $fillable = ['filed1', 'filed2'];
Remove protected $fillable completely (Not Recommended)
class Abc extends Model
{
protected $table = 'cities';
protected $fillable = ['field1','field2', ...];
}
Model looking for countable parameter:
class ClassName extend Model {
protected $fillable=['column_name']; // column in DB of Model is in array
}
Before
count($collection['colors'])
Error:Expected type 'Countable|array'. Found 'string'
After
count((array)$collection['colors'])
It works for me!
'vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php' to:
$originalWhereCount = is_array($query->wheres) ? count($query->wheres) : 0;
I;m using laravel 6.x
for this case you can use this way:
$id = \DB::table('xxxx')->where('id', $id)->count();
I Solve this in Laravel 5.6
// in controller
public function index()
{
$todos = Todo::all();
return view('todos.index')->with(['todos' => $todos]);
}
// in view page
#if(count($todos) > 0)
#foreach($todos as $todo)
<div class="well">
<h3>{{$todo->text}}</h3>
<span class="label label-danger">{{$todo->due}}</span>
</div>
#endforeach
#endif

Doctrine behavior *translation entity error: No identifier/primary key specified for Entity

After taking a src/bundle version of my bundle that makes use of the Knp translatable of the doctrine/behavior bundle. In the original bundle I everything works.
But when calling :
app/console doctrine:schema:validate
it would throw an error:
No identifier/primary key specified for Entity
Its deprecated way as said at knp behaviors documentation.
Add new Knp\DoctrineBehaviors\Bundle\DoctrineBehaviorsBundle(), to AppKernel.php
The problem seem to have been with the listeners not loading.
adding to config.yml
- { resource: ../../vendor/knplabs/doctrine-behaviors/config/orm-services.yml }
did the trick :)
Or the new way to modify AppKernel:
class AppKernel
{
function registerBundles()
{
$bundles = array(
//...
new Knp\DoctrineBehaviors\Bundle\DoctrineBehaviorsBundle(),
//...
);
//...
return $bundles;
}
}
You can also register them using doctrine2 api:
<?php
$em->getEventManager()->addEventSubscriber(new \Knp\DoctrineBehaviors\ORM\Translatable\TranslatableSubscriber);
// register more if needed
see: https://github.com/KnpLabs/DoctrineBehaviors#subscribers

How to override FOSUserBundle's EmailConfirmationListener

I activated user confirmation for FOSUserBundle. But I don't want to take the response from the original listener
$url = $this->router->generate('fos_user_registration_check_email');
$event->setResponse(new RedirectResponse($url));
I want to chose another route. I tried to extend the EventListener
namespace Acme\MyBundle\EventListener;
use FOS\UserBundle\EventListener\EmailConfirmationListener as BaseListener;
// ...
class EmailConfirmationListener extends BaseListener
{
public function onRegistrationSuccess(FormEvent $event)
{
$url = $this->router->generate('fos_user_registration_check_email');
$event->setResponse(new RedirectResponse($url));
}
}
Unfortunately, EventListeners don't seem to be extendable, just as Controllers or Forms are. (Just in case you wonder: of course my bundle is a child of the FOSUserBundle.)
So I want to avoid editing those two lines directly in the vendor folder (as it would be very bad practice to do so!). So what are my ways out of this calamity?
Just override the service fos_user.listener.email_confirmation by creating a service with the same name in your config.yml ...
# app/config/config.yml
services:
fos_user.listener.email_confirmation:
class: "Acme\MyBundle\EventListener\EmailConfirmationListener"
arguments: ["#fos_user.mailer", "#fos_user.util.token_generator", "#router", "#session"]
tags:
- { name: kernel.event_subscriber }
... or even cleaner - create a parameter that's being used by your service:
parameters:
my.funky_parameter.class: "Acme\MyBundle\EventListener\EmailConfirmationListener"
services:
fos_user.listener.email_confirmation:
class: "%my.funky_parameter.class%"
# ...
... or inside your bundle's xml/yml/php configuration file loaded by the bundle's extension. Make sure your bundle is being registered after FOSUserBundle in AppKernel.php when choosing this way.
... or the best method:
change the original service's class name in a compiler pass as the documentation chapter How to Override any Part of a Bundle suggests.
Maybe take a dive into the chapter How to work with Compiler Passes before choosing this option.

Symfony 1.4: Override doctrine:build-schema command

Is it possible to override a Symfony 1.4 CLI command?
More specifically, I was wondering if it's possible to override this command:
php symfony doctrine:build-schema
What I want to do is to add a new option in the database.yml file for each connection I find in it.
The option I want to add is a package option
So, an hypothetical connection could be:
all:
doctrine:
class: sfDoctrineDatabase
package: myPackageOption
param:
dsn: 'mysql:host=localhost;dbname=my_db_name'
username: db_user
password: db_password
If it would be possible, where can i find the code to override?
I suggest you to use some shell script that pre-generate the databses.yml and then auto-invoque the php symfony doctrine:build-schema. Something like:
build.sh, in project root folder:
#!/bin/bash
cp config/databases_1.yml config/databases.yml
php symfony doctrine:build
then, type ./build.sh (after added execution permissions) in your console.
The copy/replace of multiple databases_xxx.yml it's the easiest example. But you can do any processing you want.
If you don't know about shell scripting, you can do the file modification even with a php script, so your build.sh should looks like:
#!/bin/bash
php pregenerate_databases.php
php symfony doctrine:build
I'm trying to override the task but I can't make it work, but:
You can create your own task that inherits the doctrine task and do your stuff:
in lib/task add sfDoctrineBuildSchemaCustomTask.class.php:
class sfDoctrineBuildSchemaCustomTask extends sfDoctrineBuildSchemaTask
{
/**
* #see sfTask
*/
protected function configure()
{
$this->addOptions(array(
new sfCommandOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'The application name', true),
new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
));
$this->namespace = 'doctrine';
$this->name = 'build-schema-custom';
$this->briefDescription = 'Creates a schema from an existing database';
$this->detailedDescription = <<<EOF
The [doctrine:build-schema|INFO] task introspects a database to create a schema:
[./symfony doctrine:build-schema|INFO]
The task creates a yml file in [config/doctrine|COMMENT]
EOF;
}
/**
* #see sfTask
*/
protected function execute($arguments = array(), $options = array())
{
// do your stuff before original call
parent::execute($arguments,$options);
// do your stuff after original call
}
}
Then, you can call php symfony doctrine:build-schema-custom, and go!
Or, maybe, you can edit the original task located in lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/task/sfDoctrineBuildSchemaTask.class.php

Resources