Running Doctrine2 command-line utility inside Zend Framework2 - doctrine-orm

I've read this tutorial and I've tried to setup Doctrine2 inside a Zend2 project:
I've registered Doctrine2 as a dependency and installed it successfully
I've followed the tutorial to register doctrine entities path in the config in the two modules where I wish to have entities.
namespace MyNamespace;
return array(
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Doctrine/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
)
)
)
),
'view_manager' => array(
'template_path_stack' => array(
'PBT' => __DIR__ . '/../view'
),
),
);
I've declared a pretty simple entity:
namespace MyNamespace\Doctrine\Entity;
use Doctrine\ORM\Mapping as ORM;
class User
{
/**
* #ORM\Id
* #ORM\Column(type="integer", name="id");
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $_id;
/**
* #ORM\Column(type="string", name="email")
*/
protected $_email;
/**
* #ORM\Column(type="string", name="passwordHash")
*/
protected $_passwordHash;
}
I've run some doctrine command hoping that they would create the table in my database:
./vendor/bin/doctrine-module migrations:generate
Here the errors raised:
PHP Fatal error: Uncaught exception 'Zend\Mvc\Router\Exception\RuntimeException' with message 'Given route does not implement Console route interface' in PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/Console/SimpleRouteStack.php:81
Stack trace:
#0 PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/Console/SimpleRouteStack.php(51): Zend\Mvc\Router\Console\SimpleRouteStack->routeFromArray(Array)
#1 PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/SimpleRouteStack.php(140): Zend\Mvc\Router\Console\SimpleRouteStack->addRoute('home', Array)
#2 PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/SimpleRouteStack.php(84): Zend\Mvc\Router\SimpleRouteStack->addRoutes(Array)
#3 [internal function]: Zend\Mvc\Router\SimpleRouteStack::factory(Array)
#4 truncated mention to 'PROJECT_DIR' in PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 860
Fatal error: Uncaught exception 'Zend\Mvc\Router\Exception\RuntimeException' with message 'Given route does not implement Console route interface' in PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 860
Zend\Mvc\Router\Exception\RuntimeException: Given route does not implement Console route interface in PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/Console/SimpleRouteStack.php on line 81
Call Stack:
0.0001 633648 1. {main}() PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module:0
0.0458 650288 2. include('PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module.php') PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module:4
0.1666 878808 3. Zend\Mvc\Application::init() PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module.php:46
1.6689 5914064 4. Zend\Mvc\Application->bootstrap() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:254
1.6999 6515856 5. Zend\ServiceManager\ServiceManager->get() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:153
1.6999 6516648 6. Zend\ServiceManager\ServiceManager->create() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:481
1.6999 6516648 7. Zend\ServiceManager\ServiceManager->doCreate() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:557
1.6999 6516728 8. Zend\ServiceManager\ServiceManager->createFromFactory() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:598
1.7011 6537712 9. Zend\ServiceManager\ServiceManager->createServiceViaCallback() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:983
1.7011 6538200 10. call_user_func() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:853
1.7011 6538272 11. Zend\Mvc\Service\RouterFactory->createService() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:853
1.7013 6540728 12. call_user_func() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Service/RouterFactory.php:65
1.7058 6689416 13. Zend\Mvc\Router\SimpleRouteStack::factory() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Service/RouterFactory.php:65
1.7071 6742992 14. Zend\Mvc\Router\SimpleRouteStack->addRoutes() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/SimpleRouteStack.php:84
1.7071 6743848 15. Zend\Mvc\Router\Console\SimpleRouteStack->addRoute() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/SimpleRouteStack.php:140
1.7071 6743928 16. Zend\Mvc\Router\Console\SimpleRouteStack->routeFromArray() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Router/Console/SimpleRouteStack.php:51
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "Router"; no instance returned in PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php on line 860
Call Stack:
0.0001 633648 1. {main}() PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module:0
0.0458 650288 2. include('PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module.php') PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module:4
0.1666 878808 3. Zend\Mvc\Application::init() PROJECT_DIR/vendor/doctrine/doctrine-module/bin/doctrine-module.php:46
1.6689 5914064 4. Zend\Mvc\Application->bootstrap() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:254
1.6999 6515856 5. Zend\ServiceManager\ServiceManager->get() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:153
1.6999 6516648 6. Zend\ServiceManager\ServiceManager->create() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:481
1.6999 6516648 7. Zend\ServiceManager\ServiceManager->doCreate() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:557
1.6999 6516728 8. Zend\ServiceManager\ServiceManager->createFromFactory() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:598
1.7011 6537712 9. Zend\ServiceManager\ServiceManager->createServiceViaCallback() PROJECT_DIR/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:983
All brilliant or not ideas are welcomed... If you see how to fix the code display in my question, please... feel free!
EDIT : Added the complete errors dump. Please note that everything going through the web is working, just the command line is crashing.

This applies to Zend Framework 2.2.1. You can temporarily use a version 2.2.0 or lower.

There are at least two errors with you configuration:
First, at the error message states, there is a service called Router being requested from what appears to be a form factory. This is to do with your project configuration and unlikely to have anything to do with Doctrine.
Your entity isn't marked as an entity via the class-level annotation.
To fix #2 you need:
namespace MyNamespace\Doctrine\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class User
{
/// ...

Related

InvalidArgumentException: Unknown formatter while writing unit tests

I am writing phpUnit tests for our application, So for this I wrote a model factory, after that when I try to run the unit test then I am getting an error like " InvalidArgumentException: Unknown formatter 'publicId' ". I have declared table's all column names in my Model factory. Is it required to mention all columns in the factory?
ModelFactory.php
$factory->define(App\Campaign::class, function (Faker\Generator $faker) {
return [
'public_id' => $faker->publicId,
'client_id' => $faker->clientID,
'name' => $faker->name,
'criteria_age' => $faker->criteriaAge,
'criteria_state' => $faker->criteriaState,
'criteria_postcode' => $faker->criteriaPostcode,
'dncr_required' => $faker->dncrRequired,
'criteria_state' => $faker->criteriaState,
'active' => $faker->active,
'method' => $faker->method,
'server_parameters' => $faker->serverParameters,
'parameter_mapping' => $faker->parameterMapping,
];
});
\tests\Unit\Campaign\CampaignTest.php
namespace Tests\Unit\Campaign;
use App\Campaign;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class CampaignTest extends TestCase
{
use DatabaseTransactions;
public function testCampaignCreation()
{
factory(\App\Campaign::class)->create(['name' => 'tinku']);
$this->seeInDatabase('campaigns', ['name' => 'tinku']);
}
}
after running "phpunit tests/Unit/Campaign/CampaignTest.php" I got this error "InvalidArgumentException: Unknown formatter 'publicId'". I am new to Laravel I know there is a procedure to create factories but I couldn't figure out. Hope someone helps. Thanks.
The formatter is from Faker not Laravel and you can only use Faker formatters Faker ships with.
The error message just tells you that there is no such formatter named publicId. For a list of all Faker formatters please see: https://github.com/fzaninotto/Faker#formatters
If you compare that list with the formatters you've used in your example it becomes more and more obvious that you confused the formatters with some database properties, most likely a translation failure from an existing example? But I think you will know better and this hopefully gives you the information you need to continue setting up your test-case.

cakephp 2.6 controller test case throwing MissingActionException on duplicate testAction()-call

I hope anyone can help me out with my testing environment.
my setup
I am implementing unit tests based on phpunit 3.7.22 with the cake release 2.6.9. Running on ubuntu 12.04 LTS with PHP 5.4.43-1 and postgresql 9.1.
I immplemented controller tests mocking cakes Auth Component to have a user in the session, since my tests depent on that. My controllers return json results, since its an API for a JS-based frontend. I call my controller methods using the testAction() call of a generated controller.
<?php
App::uses('RequesttypesController', 'Svc.Controller');
class RequesttypesWithResultControllerTest extends ControllerTestCase
{
public $fixtures = array(
'app.requesttype',
'app.user',
'app.privilege',
'app.groupsprivilege',
'app.groupsuser',
'app.groupscompany',
'app.company',
);
/**
* Mock the requesttype object so that it can return results depending on the desired outcome
*
* #see CakeTestCase::setUp()
*/
public function setUp()
{
parent::setUp();
$this->controller = $this->generate('Svc.Requesttypes', array(
'models' => array(
'Requesttype'
),
'components' => array(
'Auth' => array(
'user'
),
'Session',
'RequestHandler'
)
));
$this->controller->Auth->staticExpects($this->any())
->method('user')
->will($this->returnValue(array(
'id' => 123,
'username' => 'myTestUser',
'company' => 'myTestCompany',
'usertype_id' => '456',
))
);
$authResult = $this->controller->Auth->user();
}
public function tearDown()
{
parent::tearDown();
unset($this->controller);
}
/**
* A logged in user produces a number of requesttypes
*/
public function testLoggedInUser()
{
$result = $this->testAction('/svc/requesttypes/getMyRequesttypes', array('return' => 'vars'));
$this->assertNotEmpty($this->vars, 'Did not receive webservice response');
$this->assertTrue(isset($this->vars['data']['code']), 'Received invalid webservice response');
$this->assertEqual($this->vars['data']['code'], SvcAppController::RESPONSE_CODE_SUCCESS);
}
}
?>
This test passes without errors. Now I want to test my controller-action with different setups, for example users with a different usertype, from a different company, and so on. If I now create a second test-method in my RequesttypesWithResultControllerTest-class, calling the same testAction-url, i get a MissingActionException saying:
"Action RequesttypesController::() could not be found."
It seems that the testAction calls an empty controller-action, even if the action-url is passed as a parameter. I tried reinitializing the controller by nulling it and calling $this->generate() again, but this does not help either.
Of course I can help myself out by creating an own test-controller for every test ending up in a bunch of duplicate test-code, but this somehow seems not right to me.
Am I misusing the test-environment or how can this exception be explained? Any ideas?
Thanks in advance for sharing my headache!
After some further code debugging we finally found the error. We accidently changed the require statement of the last line of the /Config/routes.php file to a require_once because of some "Class already defined Exceptions" thrown in the test-environment.
Wrong routes.php:
require_once CAKE . 'Config' . DS . 'routes.php';
For the application itself that made no difference, since the routes are only needed to be initialized once per request. But in a test-environment, the routes are reinitialized several times, which was not possible anymore with the require_once include.
This is how the line is supposed to look like, which it does by default:
Correct routes.php:
require CAKE . 'Config' . DS . 'routes.php';

OpenCart PHP unexpected T_DOUBLE_ARROW

I'm getting this error when I try to go to my site. The last thing I did was uninstall one blog extension and installed a new one.
Error:
Parse error: syntax error, unexpected T_DOUBLE_ARROW in /home/mcflipp/public_html/vqmod/vqcache/vq2-catalog_controller_common_header.php on line 341
The code on that line is:
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
'id' => $category['category_id']. '_' . $child['category_id'],
And the code that matches in the catalog/controller/common/header.php is:
$children_data[] = array(
'name' => $child['name'],
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
'id' => $category['category_id']. '_' . $child['category_id'],
'children_level_2' => $children_data_level_2,
);
The syntax looks correct to me, so I'm not sure what needs to be changed. I appreciate any help!
Well, looking at your code, I can see a problem in this part of the file:
// Level 1
$this->data['categories'][] = array(
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
}
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id']),
'id' => $category['category_id']. '_' . $child['category_id'],
'children_level_2' => $children_data_level_2,
);
}
This one looks like incorrect vQmod replacement/addition to a file... Either you have applied a version of extension that does not support your version of OC or you have made some manual changes to the file that vQmod is trying to inject. It could be also possible that the extensions itself is malfunctioning. Check the vQmod XML file for this extension and identify the piece that is responsible for this concrete injection.
Hint: using an advanced PHP IDE can help to point to basic PHP syntax errors (e.g. like this above) by highlighting and marking the erroneous place in red (I am using NetBeans for example).

doctrine 2 returns errror 'proxy directory must be writable'

i am using doctrine 2 with Zendframework 2
i am trying to return an object but keep getting this error:
Your proxy directory must be writable
this is my query:
$this->getEntityManager()
->getRepository('Messages\Entity\Messages')
->findOneBy(array('id' => 6,
'receiverId' => 16
));
However, the same query return an array without any problems re:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select(array('u'))
->from('Messages\Entity\Messages','u')
->where('u.id = :id')
->andWhere('u.receiverUserId = :receiverId')
->setParameter('receiverId',16)
->setParameter('id',(int)6);
$query = $qb->getQuery();
return $data = $query->getArrayResult();
If you are using Setup::createAnnotationMetadataConfiguration you can simply fix it by
Create the following directory in your project root. data/DoctrineORMModule/Proxy
chmod -R 755 data/DoctrineORMModule/Proxy
In your bootstrap include the path to the data directory as in:
Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/src/models"), $this->isDevMode, "data/DoctrineORMModule/Proxy")
That fixed it for me.
Proxies are simple classes which extends your actual entities and used internally by doctrine to hydrate associations of your entities by lazy-loading them. Doctrine decides to use or not to use a proxy instances on runtime for different situations and it really depends on your queries and associations in your entities. You may want to read about this subject in-depth at official documentation.
In your case, doctrine trying to generate a proxy class for your Messages entity but your proxy directory is simply not writable as error output's said.
This seems like misconfiguration of DoctineModule. (Assuming that you are using DoctrineORMModule to integrate doctrine with ZF2) Doctrine needs a writeable directory to put that generated proxy classes. For ZF2's view, data directory on application root perfectly fits for this requirement.
Make sure existence of the line below in your public/index.php:
chdir(dirname(__DIR__));
and try to use a configuration like this:
<?php
/**
* module/Application/config/module.config.php
*/
return array(
'router' => array(
// ...
),
// ...
'doctrine' => array(
'driver' => array(
//...
),
/**
* Generating proxies on runtime and using array cache instead of apc(u)
* greatly reduces the performance. So, you may want to override
* this settings on production environment.
*/
'configuration' => array(
'orm_default' => array(
'metadata_cache' => 'array',
'query_cache' => 'array',
'result_cache' => 'array',
'hydration_cache' => 'array',
'generate_proxies' => true,
'proxy_dir' => 'data/DoctrineORMModule/Proxy',
'proxy_namespace' => 'DoctrineORMModule\Proxy',
),
),
)
);
If you are using Fedora 24, enter the following commands:
semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/YOUR_SITE/data';
restorecon -v '/var/www/html/YOUR_SITE/data'
With this, you are changing the label of the /var/www/html and giving write permission to httpd.

Doctrine findBy with OR condition

Is it possible to use OR statement in Doctrine findBy() method?
I know that given array is interpreted as case1 AND case2...
Like this
$this->repos['notif']->findBy(array('status' => 1, 'status' => 2, 'status' => 3);
Stands for
SELECT * FROM `notif` WHERE status=1 AND status=2 AND status=3;
Now I need something to stand for:
SELECT * FROM `notif` WHERE status=1 OR status=2 OR status=3;
Is there a way to get all cases?
You can write:
$this->repos['notif']->findBy(array('status' => array(1, 2, 3)));
and that should work too.
I know that this is old question. Anyways, it's possible to use Criteria for the complex queries (in Doctrine 2 at least):
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria
->orWhere($criteria->expr()->contains('domains', 'a'))
->orWhere($criteria->expr()->contains('domains', 'b'));
$groups = $em
->getRepository('Group')
->matching($criteria);
As far as I know this is not a supported feature by Doctrine to use IN() queries with findby. You could do two things:
Implement a findByStatus(array $statusTypes) method in your (custom) 'notif' repository class. If you like this approach I can give you a example.
Convert your findBy to the following:
$qb = $this->repos['notif']->createQueryBuilder('n');
$data = $qb->where($qb->expr()->in('status', array(1,2,3)))->getQuery()->getResult();
That should work either :)
If you are using MongoDB and need more complex queries, like "less than" linked together with OR, but cannot use a query builder, this also works with this syntax:
->findBy(array(
'$or' => array(
array('foo' => array('$lt' => 1234)),
array('$and' => array(
array('bar' => 45678),
array('baz' => array('$lt' => 89013))
))
)
));
Or as a solution for your question:
->findBy(array(
'$or' => array(
array('status' => 1),
array('status' => 2),
array('status' => 3),
)
));