[Symfony\Component\Debug\Exception\ContextErrorException] - mongodb

I'm making fixtures and when I try to load them I have an error. The relationship between Award and Movie is unidirectional, so I load first Award because it hasn't any reference. The error says:
[Symfony\Component\Debug\Exception\ContextErrorException] Warning: spl_object_hash()
expects parameter 1 to be object, array given in
/Users/benatespina/Development/filmboot.web/vendor/doctrine/mongodb-odm/lib/Doctrine/ODM‌/MongoDB/UnitOfWork.php line 1706.
This is my Fixture class:
namespace MyProject\MovieBundle\DataFixtures\MongoDB;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use MyProject\MovieBundle\Document\Award;
class Awards extends AbstractFixture implements OrderedFixtureInterface {
public function load(ObjectManager $manager) {
$awards = array(
array(
"name" => "Sitges",
"year" => "1992",
"category" => "Best director"
);
foreach ($awards as $i => $award) {
$document = new Award();
$document->setName ($award["name"]);
$document->setYear ($award["year"]);
$document->setCategory($award["category"]);
$manager->persist($document);
$this->addReference("award-" . $i, $award);
}
$manager->flush();
}
public function getOrder() {
return 1;
}
}

This exception has nothing to do with symfony2 or doctrine-fixtures - it's a generic PHP exception.
You are trying to use a variable $i that has never been defined in your addReference() call.
$this->addReference("award-" .$i, $award);

Related

How to capture by reference in rust macro

I have a macro to generate match arms:
macro_rules! sort_by {
( $query:ident, $sort_by:expr, { $( $name:pat => $column:path,)+ } ) => {
match $sort_by.column {
$(
$name => if $sort_by.descending {
$query = $query.order_by($column.desc());
} else {
$query = $query.order_by($column.asc());
},
)+
}
}
}
and I want to call it like this:
sort_by!(query, sort_by.unwrap_or(Sort::desc("id")), {
"id" => table::id,
"customerName" => table::customer_name,
});
But I'm getting an error:
sort_by!(query, &sort_by.unwrap_or(Sort::desc("id")), {
^^^^^^^ value moved here in previous iteration of loop
So I have to call it like this:
let sort = sort_by.unwrap_or(Sort::desc("id"));
sort_by!(query, &sort, {
"id" => table::id,
"customerName" => table::customer_name,
});
What should I change to be able to use the expression directly in the macro invocation?
Using a macro is equivalent to substituting the code it expands to into its call site. This means if the macro expansion contains $sort_by multiple times, the code will evaluate the expression you pass in as $sort_by multiple times. If the expression consumes some variable, this will be invalid.
This is in contrast to how function calls work. If you pass an expression to a function, it will be evaluated before calling the function, and only the result is passed to the function.
If this is the source of your problem, you can fix it by assigning $sort_by to a local variable inside your macro expansion, and only access the local variable subsequently:
macro_rules! sort_by {
($query:ident, $sort_by:expr, { $($name:pat => $column:path,)+ }) => {
let sort_by = $sort_by;
match sort_by.column {
$(
$name => if sort_by.descending {
$query = $query.order_by($column.desc());
} else {
$query = $query.order_by($column.asc());
},
)+
}
}
}
(Note that I could not test this, since your example is incomplete.)

DBIx::Class: sub resultset in Template Toolkit presented as an array, not a resultset

I am developing a Catalyst application using DBIx::Class and Template Toolkit; in the particular part I'm having issues with, I have a resultset obtained using by calling the following function in my ResultSet schema:
sub divisions_and_teams_in_season {
my ( $self, $season, $grid ) = #_;
return $self->search({
"division_seasons.season" => $season->id,
"division_seasons.fixtures_grid" => $grid->id,
}, {
prefetch => [
"division_seasons",
{
"team_seasons" => {
"team" => [{
"club" => "venue"
},
"home_night"
]
}
}
],
order_by => {
-asc => [ qw( division_seasons.rank team_seasons.grid_position club.short_name team.name ) ]
}
});
}
This returns the data as I would expect and I'm able to do the following in my Controller code to get back my resultset and iterate through the team_seasons:
my $divisions = [ $c->model("DB::Division")->divisions_and_teams_in_season($current_season, $c->stash->{grid}) ];
foreach my $division ( #{ $divisions } ) {
$c->log->debug( $division->team_seasons->grid_positions_filled ); # This works because $division->team_seasons is a resultset object
}
However, in my template (having stashed $divisions), I'm unable to access the grid_positions_filled object because division.team_seaons gives me an arrayref of team resultsets in that division:
[%
# Loop through our divisions
FOREACH division IN divisions;
CALL c.log.debug(division.team_seasons); # The output of this is something like: ARRAY(0x6f8318c)
END;
-%]
The output I get for the same debug log in my controller is more like a list of resultset objects:
TopTable::Model::DB::TeamSeason=HASH(0x6eea94c)
TopTable::Model::DB::TeamSeason=HASH(0x6f01834)
TopTable::Model::DB::TeamSeason=HASH(0x6ef5284)
TopTable::Model::DB::TeamSeason=HASH(0x6efec9c)
TopTable::Model::DB::TeamSeason=HASH(0x6ef4dc4)
TopTable::Model::DB::TeamSeason=HASH(0x6faf0ac)
TopTable::Model::DB::TeamSeason=HASH(0x6eefa04)
Hope all this makes sense! Does anyone know how I can get the behaviour from the controller into the template so that I can access methods on the team_season ResultSet?
Thank you very much in advance.
Try $self->search_rs rather than $self->search. "This method does the same exact thing as search() except it will always return a resultset, even in list context."
See the docs for more info.
The team_seasons accessor returns a resultset in scalar context, and an array of rows in list context. It seems that template toolkit code evaluates the accessor in list context.
As a work-around, DBIC installs a special accessor, postfixed with _rs that always returns a resultset regardless of context. So the following should work:
CALL c.log.debug(division.team_seasons_rs.grid_positions_filled);
This is documented under DBIx::Class::Relationship.

Registering Silex Providers Throwing Errors

Creating an App in Silex and trying to take the first few steps, one of which is setting up my services/providers.
I am currently loading these using a YAML file. I have also tried registering each individual like the docs say e.g.
$this->register( new TwigServiceProvider(),array() );
Here is my current bootstrap file(loading services from a file):
<?php
namespace App;
use Igorw\Silex\ConfigServiceProvider;
use Silex\Application as Silex;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpFoundation\Request;
class Bootstrap extends Silex
{
public function __construct()
{
$this['debug'] = true;
$this->registerDefaultParameters();
$this->registerDefaultServices();
$this->registerRoutes();
}
protected function registerDefaultParameters()
{
$paths = isset($this['base_path']) ? $this['base_path'] : array();
if (!isset($paths['base'])) {
$paths['base'] = realpath(__DIR__ . '/../');
}
$defaults = array(
'config' => $paths['base'] . '/App/Config',
'twig.path' => $paths['base'] . '/public/themes/base/templates'
);
foreach ($defaults as $key => $value) {
if (!isset($paths[$key])) {
$paths[$key] = $value;
}
}
$this['paths'] = $paths;
}
protected function registerDefaultServices()
{
$this->register( new ConfigServiceProvider($this['paths']['config'] . "/Services.yml") );
foreach($this['services'] as $serviceName => $serviceData)
{
$this->register( new $serviceData['class'],(array_key_exists('parameters',$serviceData)) ? $serviceData['parameters'] : array() );
}
}
protected function registerRoutes()
{
$this->register( new ConfigServiceProvider($this['paths']['config'] . "/Routes.yml") );
$collection = new RouteCollection();
foreach($this['routes'] as $key => $value)
{
$collection->add( $key, new Route(
$value['path'],
$value['defaults'],
array(),
array(),
null,
null,
$value['methods']
));
}
$this['routes'] = $collection;
}
}
My issue is:
With every provider i am receiving fatal errors like
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Identifier "this_is_an_identifier" is not defined.'
I'm receiving this errors loading the services from a file and manually. and its different for each provider e.g.
The error related to the twig provider is:
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Identifier "request_error" is not defined.'
Another one relating to Monolog is :
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Identifier "dispatcher" is not defined.
So its like every provider/service has something wrong which obviously isn't the case. So my question is why am i continuously receiving these errors? from what i can see im not doing anything wrong?
Heres my composer file just in case it's a version thing:
{
"name": "cranbri/cvcms",
"description": "Cranbri CV CMS Silex",
"minimum-stability": "dev",
"require": {
"silex/silex": "1.2.2",
"symfony/yaml": "2.6.1",
"igorw/config-service-provider": "1.2.2"
},
"autoload": {
"psr-4":{
"App\\": "App/"
}
}
}
This is stopping my development altogether so if anyone can give me any details it will be much appreciated. Cheers
I wasn't calling parent!!! therefore i have none of the values the parent class did hence why many of the $app variables were not set and couldn't be found

Perl Validation::Class messages

I've write a custom class inherited from Validation::Class to define all mixins I need
Then whenever i want to use these mixins in any class, I just inherited from the custom class.
Its works perfectly but I want to customize all error messages. Example:
message required => '%s is required';
So I don't have to write it in each validation field like this.
field username => {
required => 1,
messages{
required => '%s is required'
}
};
But it doesn't seems to work, it's still displaying original Validation::Class error message.
Can I override all messages I need in my costume class?
My custom class looks like this:
#Validation.pm
package Validation;
use Validation::Class;
use File::Spec ;
BEGIN {
my ($volume, $directory, $file) = File::Spec->splitpath(__FILE__);
push ( #INC,$directory );
}
our #ISA = qw(Validation::Class);
# hook
build sub {
my ($self, #args) = #_; # on instantiation
};
# I have tried to but the message in here , but it doesn't work
#message required => '%s is reuqired';
# data filter template
mixin filter => {
filters => [qw/trim strip/],
};
# data validation template
mixin basic => {
max_length => 255,
messages => {
max_length => 'Invalid %s',
}
};
This is the child class inherited from my Validation class
#Person.pm
package person;
# Inherit my custom class instead of Validation::Class
use Validation;
our #ISA = qw(Validation);
load role => 'Validation';
# I want to have this message in all inherited classes
# here is my problem .. this line will override required message with my custom message
# but I have many classes like this class
# is there anyway to delete this line and to write it in the parent class
# so every child can use this message without duplicating it in them
message required => '%s is reuqired';
# data validation rules
field username => {
mixin => 'filter',
mixin => 'basic',
required => 1
};
I found the solution for the messages
I have added a new mixin in the parent class (my custom Validation class) like this
mixin my_messages => {
messages => {
required => '%s is reuqired',
pattern => 'Ivalid character found in %s',
}
};
You can add as many messages as you can.
Then use the mixin inside all fields in any child class.
example
field username => {
default => '',
mixin => 'my_messages',
};
Note that my_messages mixin must be the last rule in the field.

Warning: spl_object_hash() expects parameter 1 to be object, array given in

I'm making fixtures and when I try to load them I have an error. The relationship between Award and Movie is unidirectional, so I load first Award because it hasn't any reference. The error says:
[Symfony\Component\Debug\Exception\ContextErrorException] Warning: spl_object_hash()
expects parameter 1 to be object, array given in
/Users/benatespina/Development/filmboot.web/vendor/doctrine/mongodb-odm/lib/Doctrine/ODM‌/MongoDB/UnitOfWork.php line 1706.
This is my Fixture class:
namespace MyProject\MovieBundle\DataFixtures\MongoDB;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use MyProject\MovieBundle\Document\Award;
class Awards extends AbstractFixture implements OrderedFixtureInterface {
public function load(ObjectManager $manager) {
$awards = array(
array(
"name" => "Sitges",
"year" => "1992",
"category" => "Best director"
);
foreach ($awards as $i => $award) {
$document = new Award();
$document->setName ($award["name"]);
$document->setYear ($award["year"]);
$document->setCategory($award["category"]);
$manager->persist($document);
$this->addReference("award-" . $i, $award);
}
$manager->flush();
}
public function getOrder() {
return 1;
}
}
The problem is in line:
$this->addReference("award-" . $i, $award);
You can't pass an array as rererence. You probably wanted this instead:
$this->addReference("award-" . $i, $document);