Zend_Auth: Join Query Issue - zend-auth

I'm a new guy for zendframework. i am facing zend auth join query issue..
Here I attach my zend_auth login sample code.
My login information's are stored in two tables. I mean email address in separate table and password separate. Here I was try to join my table, but I am getting Following error...
Message: The supplied parameters to Zend_Auth_Adapter_DbTable
failed to produce a valid sql statement, please check table and column
names for validity.
Please advise me.
My code is here...
$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName(array('users','details'))
->setIdentityColumn('name')
->setCredentialColumn('pwd');
$name = 'test';
$pwd = '123';
$authAdapter->setIdentity($name)
->setCredential($pwd);
$select = $authAdapter->getDbSelect();
$select->where('pwd = 123')
->joinLeft( array('d' => 'details'),'d.id = users.id');
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);

Related

Complex QueryBuilder expresion in createQuery() with Sonata Admin

I'm using Symfony 4.2 and Sonata Admin bundle and I'm trying to display a specific list in one of my admin list view.
I want to display the lastest user by group. I created the SQL query and I'm now trying to translate it to QueryBuilder.
SELECT * FROM users
WHERE (created_at, group_id) IN (
SELECT MAX(created_at), group_id
FROM users
GROUP BY group_id)
My createQuery function in my Sonata Admin class :
public function createQuery($context = 'list')
{
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$expr = $em->getExpressionBuilder();
$subQuery = $em->createQueryBuilder()
->select('MAX(c.createdAt), c.group')
->from('ApiBundle:Configuration', 'c')
->groupBy('c.group')
->getDQL();
$query = parent::createQuery($context);
$alias = $query->getRootAlias();
$query->where($expr->in('('.$alias.'.createdAt, '.$alias.'.group)', $subQuery));
}
Unfortunately it is not working and I'm not sure it's the right way to do it.
I could make it work with only selecting the createdAt in the in() expression but it's not what I want to have at the end.
Here is the error I got.
[Syntax Error] line 0, col 77: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','
How can I make it work using QueryBuilder ?
Thank you.

Salesforce APEX Unit Test Error with REST Services / Error at SELECT of Case Object

I've succeeded to successfully construct a REST API using APEX language defined with an annotation: #RestResource.
I also wrote a matching Unit test procedure with #isTest annotation. The execution of the REST API triggered by a HTTP GET with two input parameters works well, while the Unit Test execution, returns a "null" value list resulting from the SOQL query shown below:
String mycase = inputs_case_number; // for ex. '00001026'
sObject[] sl2 = [SELECT Id, CaseNumber FROM Case WHERE CaseNumber = :mycase LIMIT 1];
The query returns:
VARIABLE_ASSIGNMENT [22]|sl2|[]|0x1ffefea6
I've also tried to execute it with a RunAs() method (see code below), using a dynamically created Salesforce test user, not anonymous, connected to a more powerful profile, but still receiving a "null" answer at the SOQL query. The new profile defines "View All" permission for Cases. Other SOQL queries to objects like: "User" and "UserRecordAccess" with very similar construction are working fine, both for REST APEX and Test APEX.
Is there a way to configure an access permission for Unit test (#isTest) to read the Case object and a few fields like: Id and CaseNumber. Is this error related to the "Tooling API" function and how can we fix this issue in the test procedure?
Code attachment: Unit Test Code
#isTest
private class MyRestResource1Test {
static testMethod void MyRestRequest() {
// generate temporary test user object and assign to running process
String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '#testorg.com';
Profile p = [SELECT Id FROM Profile WHERE Name='StandardTestUser'];
User pu = new User(Alias='standt',Email='standarduser#testorg.com',LastName='testing',EmailEncodingKey='UTF-8',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId=p.Id,TimeZoneSidKey='America/New_York',UserName=uniqueUserName);
System.RunAs(pu) {
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/sfcheckap/';
req.addParameter('useremail','testuserid#red.com');
req.addParameter('casenumber','00001026');
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = res;
System.debug('Current User assigned is: ' + UserInfo.getUserName());
System.debug('Current Profile assigned is: ' + UserInfo.getProfileId());
Test.startTest();
Map<String, Boolean> resultMap = MyRestResource1.doGet();
Test.stopTest();
Boolean debugflag = resultMap.get('accessPermission');
String debugflagstr = String.valueOf(debugflag);
System.assert(debugflagstr.contains('true'));
}
}
}
Found a solution path by using: #isTest(SeeAllData=true)
See article: "Using the isTest(SeeAllData=true) Annotation"
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_seealldata_using.htm

Getting current cart ID in prestashop

I am busy with a site built on Code Igniter that needs integration with Prestashop. In the site, when creating a user account, I save a "shop_id" to the database, which is then retrieved as a session variable when logging in.
I am using the Prestashop API to retrieve the customer successfully (using above "shop_id")
$xml = $this->PSWebService->get(
array('resource' => 'customers', 'id' => (int)$this->user['shop_id'])
);
This successfully returns the user in question, but there is no Cart IDs in this result.
Logging in to the back-end of my shop, I see that there are multiple carts associated with the logged in user.
My question is: How to I retrieve the LATEST cart ID using the API?
$userId = (int) $this->user['shop_id'];
$opt['resource'] = 'carts';
$xml = $this->PSWebService->get($opt);
$carts = $xml->carts->children();
foreach ($carts as $cart) {
$cartIds[] = $cart['id'];
}
for ($i = count($cartIds) - 1; $i > -1; $i--) {
$opt['id'] = $cartIds[$i];
$xml = $this->PSWebService->get($opt);
//since cart ids are descending the first found will be the latest
if ($xml->cart->id_customer == $userId) {
$latestCartId = $cartIds[$i];
break;
}
}
Kind of late, but I struggled a bit with this same problem and found a way to do it just from query, based on yenshirak's tip (since cart ids are descending the first found will be the latest).
I query the API directly using postman like this:
get all carts:
GET webserver/api/carts
get cart for customer:
GET webserver/api/carts?filter[id_customer]=1
get the most recent:
GET webserver/api/carts?filter[id_customer]=1&sort=[id_DESC]&limit=1
for a pretty print, you can also add params:
display=full&output_format=JSON
You can do this in php, I have not tested if the syntax is correct, but based on documentation it looks something like this:
$opt = array(
'resource' => 'carts',
'filter[id_customer]' => '[1]',
'sort' => '[id_DESC]',
'limit' => '1'
);
$xml = $webService->get($opt);

doctrine2: different way of querying, different results

Can someone explain, why I get different results?
$user = new UserEn();
$user->setName("test");
$em->persist($user);
$result1 = $em->find('UserEn', 'test');
$result2 = $em->getRepository('UserEn')->findBy(array('name'=>'test'));
$q = $em->createQuery('select u from UserEn u where u.name = :name');
$q->setParameter('name', 'test');
$result3 = $q->getResult();
Only $result1 holds $user, which is what I expected, and the others are null. What's wrong? (Please don't say that I need to call $em->flush(); )
Because Doctrine can't figure out that you are specifically requesting an User object which has name property set to test from the query, it queries the DB(ignoring caching mechanism), map resultset to entity object, load them in entity manager and return the array of entity object[s] if any data found. So there is no involvement of entity manager here. Things would be different if you used find($id) instead of findBy() because now Doctrine will check entity manager first, query DB if not found.
$result2
This returns an array that holds all entities with test as name:
$result2 = $em->getRepository('UserEn')->findBy(array('name'=>'test'));
In order to get only one record you should use findOneBy instead of findBy:
$result2 = $em->getRepository('UserEn')->findOneBy(array('name'=>'test'));
$result3
In the $result3 you should call $q->getSingleResult() instead of $q->getResult():
$result3 = $q->getSingleResult();

Get a random record from database/entity using CI2 + Doctrine2

The following would return the a random record with Doctrine:
$name = Doctrine::getTable('nametable')
->createQuery()
->select('name')
->orderBy('RAND()')
->fetchOne();
But I'm running CI2 + Doctrine2, and so it does not work Call to undefined method Doctrine::getTable()
I've tried
$data = $this->doctrine->em->getRepository('ORM\Project\Names')
->orderBy('RAND()')
->fetchOne();
But this does not work either: Uncaught exception 'BadMethodCallException' with message 'Undefined method 'orderBy'. The method name must start with either findBy or findOneBy!'
Perhaps findOneBy is what I want, but it expects an array.
Is there an elegant way to fetch a random record in this setup?
Edit:
This is what I've come up with:
$query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Femalenames u");
$result = $query->getSingleResult();
$highval = $result[1];
$random_name = rand(1,$highval);
$name = $this->doctrine->em->find('ORM\Dynasties2\Femalenames', $random_name);
$mother_name = $name->getName();
Surely there is a cleaner way??? Apparently there's no such thing as RAND() in CI2/Doctrine2, short of just writing a SQL query.
"orderBy" is not working when you try to access the repository. In this case you have to make a query with "createQuery" or the query builder "createQueryBuilder".
The other way is:
$data = $this->doctrine->em->getRepository('ORM\Project\Names')->findOneBy(array(
'field' => 'ASC or DESC'
));
Here you can test RAND instead ASC or DESC but i think the best way is to make a query.
You can define a function in your repository and make a query that you have all querys in your repo and not in your controller then your first example looks good.
This is what I've come up with:
$query = $this->doctrine->em->createQuery("select max(u.id) from ORM\Dynasties2\Femalenames u");
$result = $query->getSingleResult();
$highval = $result[1];
$random_name = rand(1,$highval);
$name = $this->doctrine->em->find('ORM\Dynasties2\Femalenames', $random_name);
$mother_name = $name->getName();
I assumed there was another way, but cannot discover it.