DoctrineExtensions error - doctrine-orm

I'm trying to configure https://github.com/Atlantic18/DoctrineExtensions
with the instruction https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/annotations.md#em-setup
But I get an error:
The annotation "#Doctrine\ORM\Mapping\MappedSuperclass" in class Gedmo\Translatable\Entity\MappedSuperclass\AbstractTranslation does not exist, or could not be auto-loaded\MappedSuperclass" in class Gedmo\Translatable\Entity\MappedSuperclass\AbstractTranslation does not exist, or could not be auto-loaded.
My configs
define('DB_CONNECTION', "host= ....");
$file_text_lib = __DIR__ . "/../../vendor/autoload.php";
require_once($file_text_lib);
// bootstrap.php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Application;
use Doctrine\ORM\Version;
//use Doctrine\ORM\EntityManagerInterface;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
define(
"PARSE_CONNECTION_STRING_REGEXP",
"/(\s*host\s*=\s*(?P<host>[^\s]+)|\s*port\s*=\s*(?P<port>[\d]+)|\s*dbname\s*=\s*(?P<dbname>[^\s]+)|\s*user\s*=\s*(?P<user>[^\s]+)|\s*password\s*=\s*(?P<password>[^\s]+)\s*)*/"
);
$isDevMode = true;
// globally used cache driver, in production use APC or memcached
$cache = new Doctrine\Common\Cache\ArrayCache;
// standard annotation reader
$annotationReader = new Doctrine\Common\Annotations\AnnotationReader;
$cachedAnnotationReader = new Doctrine\Common\Annotations\CachedReader(
$annotationReader, // use reader
$cache // and a cache driver
);
// create a driver chain for metadata reading
$driverChain = new Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
// load superclass metadata mapping only, into driver chain
// also registers Gedmo annotations.NOTE: you can personalize it
Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM(
$driverChain, // our metadata driver chain, to hook into
$cachedAnnotationReader // our cached annotation reader
);
// now we want to register our application entities,
// for that we need another metadata driver used for Entity namespace
$ymlDriver = new Doctrine\ORM\Mapping\Driver\YamlDriver(array(__DIR__."/YAMLMetaConfiguration"));
$driverChain->addDriver($ymlDriver, 'SemanticPersistence\\Entities');
// general ORM configuration
$config = new Doctrine\ORM\Configuration;
$config->setProxyDir(__DIR__ . "/../Proxies");
$config->setProxyNamespace('SemanticPersistence\\Proxies');
$config->setAutoGenerateProxyClasses($isDevMode); // this can be based on production config.
// register metadata driver
$config->setMetadataDriverImpl($driverChain);
// use our already initialized cache driver
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
$evm = new Doctrine\Common\EventManager();
// timestampable
$timestampableListener = new Gedmo\Timestampable\TimestampableListener;
$timestampableListener->setAnnotationReader($cachedAnnotationReader);
$evm->addEventSubscriber($timestampableListener);
//$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/Entities"), $isDevMode, null, null, false);
// or if you prefer yaml or XML
//$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);
/*
$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/YAMLMetaConfiguration"), $isDevMode);
$config->setAutoGenerateProxyClasses(true);
$config->setProxyDir(__DIR__ . "/../Proxies");
$config->setProxyNamespace('SemanticPersistence\\Proxies');
*/
preg_match(
PARSE_CONNECTION_STRING_REGEXP,
DB_CONNECTION,
$matches
);
$dbParams = array(
'driver' => 'pdo_pgsql',
'user' => $matches['user'],
'password' => $matches['password'],
'host' => $matches['host'],
'dbname' => $matches['dbname'],
'charset' => 'UTF-8'
);
if (!empty($matches['port'])) {
$dbParams['port'] = $matches['port'];
}
$entityManager = Doctrine\ORM\EntityManager::create($dbParams, $config, $evm);
$helperSet = new HelperSet(array(
'db' => new ConnectionHelper($entityManager->getConnection()),
'em' => new EntityManagerHelper($entityManager),
'dialog' => new QuestionHelper(),
));
$commands = array(
// DBAL Commands
new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
// ORM Commands
new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
new \Doctrine\ORM\Tools\Console\Command\InfoCommand(),
//new \Doctrine\ORM\Tools\Console\Command\MappingDescribeCommand(),
);
$cli = new Application('Doctrine Command Line Interface', Version::VERSION);
$cli->setCatchExceptions(true);
$cli->setHelperSet($helperSet);
$cli->addCommands($commands);
$cli->run();
What am I doing wrong?

Forgot to ensure standard doctrine annotations are registered
Doctrine\Common\Annotations\AnnotationRegistry::registerFile(
__DIR__.'/../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'
);

Related

Creating index with alias

Sorry for the rudimentary question.I'm developing PHP small test class that manipulates AWS Elasticsearch Service.
<?php
namespace MyCompany\Aws;
use Elasticsearch\ClientBuilder;
class ElasticsearchApi {
private $client;
function __construct(string $hosts='', string $username='', string $password=''){
... //configure $this->client
}
/**
* Create index
* #param string $index
* #param array $body
* #return bool
*/
public function createIndex(string $index, array $body = []):bool{
$request = array(
'index' => $index,
'body' => $body
);
$ret = $this->client->indices()->create($request);
return $ret['acknowledged'];
}
}
And call createIndex function specifying alias as described at:
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
<?php
require 'vendor/autoload.php';
use MyCompany\Aws\ElasticsearchApi as ES;
$es = new ES();
$body = array('aliases'=>array(
'actions'=>array(
'add'=>array(
'alias'=>'sample-alias',
'index'=>'test-index'
)
)
));
$ret = $es->createIndex('test-index',$body);
var_dump($ret);
This operation normally ends:
PS D:\My_Documents\Proj\Elasticsearch\index-gen> php es-lib-test.php
bool(true)
PS D:\My_Documents\Proj\Elasticsearch\index-gen>
However the generated index does not seem to have alias.
What is wrong with createIndex parameter? I'm using version 7.8 of Elasticsearch on AWS.
Addendum
Based on the #Val 's suggestion, I changed the code as follows:
$body = array(
'aliases'=>array(
'sample-alias'=>array()
)
);
$ret = $es->createIndex('test-index',$body);
var_dump($ret);
However I got the following exception. Are there any mistakes?
PS D:\My_Documents\Proj\Elasticsearch\index-gen> php es-lib-test.php
PHP Fatal error: Uncaught Elasticsearch\Common\Exceptions\BadRequest400Exception: {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"No alias is specified"}],"type":"illegal_argument_exception","reason":"No alias is specified"},"status":400} in D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php:641
Stack trace:
#0 D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php(328): Elasticsearch\Connections\Connection->process4xxError(Array, Array, Array)
#2 D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\ezimuel\ringphp\src\Future\CompletedFutureValue.php(55): React\Promise\FulfilledPromise->then(Object(Closure), NULL, NULL)
#3 D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\ezimuel\ring in D:\My_Documents\Proj\Elasticsearch\index-gen\vendor\elasticsearch\elasticsearch\src\Elasticsearch\Connections\Connection.php on line 641
Your body should simply look like this:
$body = array('aliases' => array('sample-alias' => array()));
The syntax you're using is for the _aliases endpoint not for the index creation one.

OctoberCMS translation (with translate plugin) of preloaded list of records

question is very simple, is there a quick way to translate a preloaded list in db. For example list of towns/countries?
class SeedTownTable extends Seeder
public function run()
{
$town_list = array(
'Акко',
'Арад',
'Ариэль',
'Афула',
'Ашдод',
'Ашкелон',
'Бат-Ям',
'Бейт-Шеан',
'Бейт-Шемеш',
'Бейтар-Илит',
'Беэр-Шева',
'Бней-Брак',
'Герцлия',
'Гиват-Шмуэль',
'Кирьят-Малахи',
'Кирьят-Моцкин',
'Кирьят-Оно',
'Кирьят-Тивон',
'Кирьят-Хаим',
'Кирьят-Шмона',
'Кирьят-Ям',
'Кфар-Саба',
'Лод',
'Маале-Адумим',
'Маалот-Таршиха',
'Метула',
'Мигдаль-ха-Эмек',
'Модиин',
'Ход-ха-Шарон',
'Холон',
'Цфат',
'Эйлат',
'Эльад',
'Явне',
'Яффо'
);
foreach ( $town_list as $town ){
Town::create([
'name' => $town
]);
}
}
I made towns model with records without any backend controller.
And I want to translate this list.
thanks.
Add the translation to your data array and use setAttributeTranslated to add the translated version.
As mentioned in the Docs
// Gets a single translated attribute for a language
$user->getAttributeTranslated('name', 'fr');
// Sets a single translated attribute for a language
$user->setAttributeTranslated('name', 'Jean-Claude', 'fr');
Try
$town_list = array(
[
'name' => 'Town Name Default Lang',
'name-es' => 'Town Name in Spanish',
]
...
)
foreach ( $town_list as $town ){
$t = new TownModel();
$t->name = $town['name'];
$t->setAttributeTranslated('name', $town['name-es'], 'es');
$t->save();
}

How to mock a validator for unit testing

I have a method that validate an Object calling an external service:
public void Validate(IValidator<MyType> validator)
{
IMapper<MyType> mapper = new MyTypeMapper();
foreach (var element in this.Elements)
{
ValidationResult result = validator.Validate(myTypeInstance, mapper, new ValidationConfiguration());
if (result.IsValid)
// do something
else
// do something else
}
}
Now in my unit test I have a collection of elements. And I want that if an element have a given id number the Validate method should return another stub with validation messages:
// arrange
var myAggregate aggregate = ElementsNonValidated.Stub();
var mockedValidator = new Mock<IValidator<MyType>>();
mockedValidator.Setup(a => a.Validate(
It.Is<Mytype>(x => x.Id == Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301")),
new Mapper(),
new ValidationConfiguration()
)).Returns<ValidationResult>(x => x = new ValidationResult());
// act
myAggregate.Valida(mockedValidator.Object);
The problem is: When unit test starts and go forth till the real method validate still return result=null. Why? What's wrong with my mock?
The problem is here:
mockedValidator.Setup(a => a.Validate(
It.Is<Mytype>(x => x.Id == Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301")),
new Mapper(),
new ValidationConfiguration()
)).Returns<ValidationResult>(x => x = new ValidationResult());
You setup Validate to expect specific Mapper and ValidationResult instances, which of course do not match the instances used in your system under test. If you don't care what instance should be used for a parameter, use It.IsAny<>:
mockedValidator.Setup(a => a.Validate(
It.Is<Mytype>(x => x.Id == Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301")),
It.IsAny<Mapper>(),
It.IsAny<ValidationConfiguration>()
)).Returns<ValidationResult>(x => x = new ValidationResult());
This will return a new ValidationResult for any and every invocation to Validate where the object's Id is equal to that particular GUID.
The reason for the TargetParameterCountException is in your Returns statement, and is answered here.

Zf2 - How to set cookie

I found this topic Zend Framework 2 - Cookie Concept while I was searching for info about setting cookie in ZF2, but seems like information included in that topic are out of date.
I have tried following code:
public function indexAction()
{
$request = $this->getRequest()->getHeaders()->get('Set-Cookie')->foo = 'bar;
$response = $this->getResponse()->getCookie()->baz = 'test';
var_dump($_COOKIE);
...
return new ViewModel();
}
Both lines output warning:
Warning: Creating default object from empty value
I tried also:
public function indexAction()
{
$cookie = new SetCookie('test', 'value', 60*60*24); // Zend\Http\Header\SetCookie instance
$header = new Cookie(); // Zend\Http\Cookies instance
$header->addCookie($cookie);
...
return new ViewModel();
}
It doesn't return any error or warning, everything seems to be ok, but when I try var_dump($_COOKIE) it still shows null.
Yes, my browser has enable cookie.
Here is my solution which I'm currently using.
$cookie = new SetCookie('key', 'value', time() + 365 * 60 * 60 * 24); // now + 1 year
$headers = $this->getResponse()->getHeaders();
$headers->addHeader($cookie);

Zend Framework Reg Ex not working on update form

I have a client input form that has the following two reg expressions that works when creating a client but not when updating a client. The update form is a class that extends the crate form.
// Create text input for mobile
$mobile = new Zend_Form_Element_Text ('mobile');
$mobile->setLabel ('Mobile Number:')
->setDescription('Enter mobile in the format 353XXYYYYYYY')
->setOptions(array('size'=>'14'))
->setRequired(false)
->addValidator('Regex',false,array(
'pattern'=>'/^\d{12}$/',
'messages'=>array(
Zend_Validate_Regex::INVALID => '\'%value%\' Invalid mobile number it does not match the required format 353XXYYYYYYY',
Zend_Validate_Regex::NOT_MATCH =>'\'%value%\'does not match the required format 353XXXXXXXX')
)
)
->addFilter('HtmlEntities')
->addFilter('StringTrim');
// Create text input for landline
$landline = new Zend_Form_Element_Text ('landLine');
$landline->setLabel ('Phone Number:')
->setDescription('Enter phone number in the format +353(0) X YYY YYYZ')
->setOptions(array('size'=>'20'))
->setRequired(false)
->addValidator('StringLength', false, array('min' => 8))
->addValidator('Regex', false, array(
'pattern' => '/^\+353\(0\)\s\d\s\d{3}\s\d{3,4}$/',
'messages' => array(
Zend_Validate_Regex::INVALID =>
'\'%value%\' In valid Phone number does not match required number format +353(0) X YYY YYYZ',
Zend_Validate_Regex::NOT_MATCH =>
'\'%value%\' does not match required number format of +353(0) X YYY YYYZ'
)
))
->addFilter('HtmlEntities')
->addFilter('StringTrim');
When I enter an invalid mobile or land line number when creating a client the reg expression works and prevents the record from being saved.
However when I enter an invalid mobile or land line number when updating a client the reg expression fails and an 404 error occurs.
I think that the issue may be related to the get section of my update action within my controller as shown below but I can't figure out what is causing this as the route I have configured in my ini file retrieves the record as required.
public function updateAction(){
// generate input form
$form = new PetManager_Form_UpdateClient;
$this->view->form=$form;
/* if the requrest was made via post
test if the input is valid
retrieve current record
update values and save to DB */
if($form->isValid($this->getRequest()->getPost())){
$input=$form->getValues();
$client = Doctrine::getTable('PetManager_Model_Clients')
->find($input['clientid']);
$client->fromArray($input);
if($client->email=='')
{$client->email=NULL;}
if($client->mobile=='')
{$client->mobile=NULL;}
if($client->landLine=='')
{$client->landLine=NULL;}
if($client->address3=='')
{$client->address3=NULL;}
$client->save();
$sessionClient = new Zend_Session_Namespace('sessionClient');
$id = $client->clientid;
$fname = $client->firstName;
$lname = $client->lastName;
$sessionClient->clientid=$id;
$sessionClient->clientfName=$fname;
$sessionClient->clientlName=$lname;
$sessionClient->clientfName=$fname;
$this->_helper->getHelper('FlashMessenger')
->addMessage('The record for '.$fname.' '.$lname. ' was successfully updated.');
$this->_redirect('clients/client/success');
}else{
/* if GET request
set filters and validators for GET input
test if input is valid, retrieve requested
record and pree-populate the form */
$filters = array(
'id'=>array('HtmlEntities','StripTags','StringTrim')
);
$validators = array(
'id'=>array('NotEmpty','Int')
);
$input = new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$qry = Doctrine_Query::create()
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties co')
->where('c.clientid=?',$input->id);
$result = $qry->fetchArray();
if(count($result)==1){
$this->view->form->populate($result[0]);
}else{
throw new Zend_Controller_Action_Exception('Page not found',404);
}
}else{
throw new Zend_Controller_Action_Exception('Invalid Input');
}
}
}
All help greatly appreciated.
Ok I've sorted this I stupidly left out a check in my update action to see if the request was being made by post as this is the action defined in my form.
The corrected code is shown below in case this helps anyone else.
// action to update an individual clients details
public function updateAction()
{
// generate input form
$form = new PetManager_Form_UpdateClient;
$this->view->form=$form;
/* if the requrest was made via post
test if the input is valid
retrieve current record
update values and save to DB */
if ($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())){
$input=$form->getValues();
$client = Doctrine::getTable('PetManager_Model_Clients')
->find($input['clientid']);
$client->fromArray($input);
if($client->email=='')
{$client->email=NULL;}
if($client->mobile=='')
{$client->mobile=NULL;}
if($client->landLine=='')
{$client->landLine=NULL;}
if($client->address3=='')
{$client->address3=NULL;}
$client->save();
$sessionClient = new Zend_Session_Namespace('sessionClient');
$id = $client->clientid;
$fname = $client->firstName;
$lname = $client->lastName;
$sessionClient->clientid=$id;
$sessionClient->clientfName=$fname;
$sessionClient->clientlName=$lname;
$sessionClient->clientfName=$fname;
$this->_helper->getHelper('FlashMessenger')
->addMessage('The record for '.$fname.' '.$lname. ' was successfully updated.');
$this->_redirect('clients/client/success');
}
}else{
/* if GET request
set filters and validators for GET input
test if input is valid, retrieve requested
record and pree-populate the form */
$filters = array(
'id'=>array('HtmlEntities','StripTags','StringTrim')
);
$validators = array(
'id'=>array('NotEmpty','Int')
);
$input = new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$qry = Doctrine_Query::create()
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties co')
->where('c.clientID=?',$input->id);
$result = $qry->fetchArray();
if(count($result)==1){
$this->view->form->populate($result[0]);
}else{
$t=count($result);
throw new Zend_Controller_Action_Exception('Page not found',404);
}
}else{
throw new Zend_Controller_Action_Exception('Invalid Input');
}
}
}