Convert anonymous PHP function to work with PHP < 5.3 [duplicate] - php

This question already has answers here:
Convert anonymous function in PHP 5.3 into PHP 5.2 equivalent
(3 answers)
Closed 9 years ago.
I am having difficulty converting this PHP 5.3 introduced anonymous function to work with earlier versions of PHP.
The error which I am getting is:
Unexpected T_FUNCTION and thats on the $testResult. This is the anonymous function. Can anyone convert this to work with earlier versions of PHP. The code is inside a class.
Here is the code:
abstract class geocoder {
public $ch = null;
public $xd = null;
public $xp = null;
public function __construct() {
$this->ch = curl_init();
curl_setopt_array($this->ch, array (
CURLOPT_BINARYTRANSFER => true,
#CURLOPT_FAILONERROR => true,
CURLOPT_FOLLOWLOCATION => false,
#CURLOPT_FORBID_REUSE => true,
#CURLOPT_MUTE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 2,
#CURLOPT_COOKIEJAR => '/dev/null',
#CURLOPT_COOKIEFILE => '/dev/null',
#CURLOPT_INTERFACE => 'x.x.x.x',
CURLOPT_USERAGENT => 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5',
CURLOPT_HEADER => false));
}
public function doreq($u) {
curl_setopt($this->ch, CURLOPT_URL, $u);
return curl_exec($this->ch);
}
abstract public function dogeocode($q);
}
class geocodeGMaps extends geocoder {
public function __construct() {
parent::__construct();
#$this->xd = new DOMDocument();
#$this->xp = new DOMXpath($this->xd);
}
public function testResult(&$res) {
switch (true) {
case !$res:
return 'Remote call HTTP request failed';
case !($res = #json_decode($res, true)):
return 'Failed to parse JSON result';
case !isset($res['status']):
return 'Remote call returned NULL status';
case !($res['status'] == 'OK'):
return 'Remote call returned !OK status';
case !isset($res['results']):
case !isset($res['results'][0]):
return 'NULL or empty result set';
case !isset($res['results'][0]['geometry']['location_type']):
return 'NULL location type';
case !($res['results'][0]['geometry']['location_type'] == 'ROOFTOP'):
return '';
case !isset($res['results'][0]['geometry']['location']):
case !isset($res['results'][0]['geometry']['location']['lat']):
case !isset($res['results'][0]['geometry']['location']['lng']):
return 'No location returned in result';
default:
return NULL;
break;
}
return NULL;
}
public function dogeocode($q) {
$res = #$this->doreq("http://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($q) . "&sensor=false");
if ($testResult = testResult($res))
throw new Exception ($testResult);
$comp = array('query' => &$q);
$map = array(
'street_number' => 'street_number',
'route' => 'route',
'city' => 'locality',
'county' => 'administrative_area_level_2',
'state' => 'administrative_area_level_1',
'country' => 'country',
'zip' => 'postal_code');
if (isset($res['results'][0]['address_components'])) {
foreach ($res['results'][0]['address_components'] as &$v)
foreach ($map as $k => &$l)
if (in_array($l, $v['types']) && !isset($comp[$k]))
$comp[$k] = $v['long_name'];
}
return array ('formatted' => (isset($res['results'][0]['formatted_address']) ? $res['results'][0]['formatted_address'] : NULL),
'components' => &$comp,
'latlng' => array ($res['results'][0]['geometry']['location']['lat'],
$res['results'][0]['geometry']['location']['lng']));
}
}
Can anyone help in making this work in PHP 5.2?

Just do
function testResult(&$res) {
// ... code
}
And then:
if ($testResult = testResult($res))
throw new Exception ($testResult);
Edit:
Now that I can see this is in a class, you'll need to move the new testResult function out of dogeocode and make it a new method to prevent Fatal error: Cannot redeclare testResult(). You'll then access it using:
if ($restResult = $this->testResult($res))
throw new Exception ($testResult);

Related

Cloudflare API with PHP problems

I need to sent parameters for the function
Cloudflare\API\Endpoints\AccessRules::createRule()
public function createRule(
string $zoneID,
string $mode,
Configurations $configuration,
string $notes = null
): bool {
$options = [
'mode' => $mode,
'configuration' => $configuration->getArray()
];
if ($notes !== null) {
$options['notes'] = $notes;
}
$query = $this->adapter->post('zones/' . $zoneID . '/firewall/access_rules/rules', $options);
$this->body = json_decode($query->getBody());
if (isset($this->body->result->id)) {
return true;
}
return false;
}
My code:
$key = new Cloudflare\API\Auth\APIKey($userEmail, $api_key);
$adapter = new Cloudflare\API\Adapter\Guzzle($key);
$fw = new Cloudflare\API\Endpoints\AccessRules($adapter);
$configData= [
'target' => 'ip',
'value' => '1.2.3.4',
];
$result=$fw->createRule($zoneID,'block',$configData,"Auto block");
And my error:
Uncaught TypeError: Argument 3 passed to Cloudflare\API\Endpoints\AccessRules::createRule() must be an instance of Cloudflare\API\Configurations\Configurations, array given
I do $configData as a object - the same.
Could you tell me - how I should create instance in $configData
You should do this this way:
$configData = new Cloudflare\API\Configurations\AccessRules();
$configData->setIP('1.2.3.4');

laravel route findOrFail() problems

new with Laravel and I am trying to add a findOrFail on this specific route and it's giving me a hard time. What am I missing?
Route::get('/listing/{type}/{owner}/{id}/{address}', 'Properties\DisplayController#show');
Whats not working
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return Properties\DisplayController#show::findOrFail($id);
});
Error I am getting
Parse error: syntax error, unexpected '#', expecting ';'
controller/function I'm calling
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id);
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
Thanks for the help!
To return directly on route:
Route::get('/listing/{type}/{owner}/{id}/{address}', function ($id) {
return App\YourModel::findOrFail($id);
});
https://laravel.com/docs/5.3/eloquent#retrieving-single-models
Since the model is on another server that we connect to using GuzzleHTTP, I could not put findOfFail() on the model.
Here is the edit to the controller. Added in the ['http_errors' => false] which prevents guzzle from returning http errors, and then a if statement using getStatusCode() to find if it was a error 500 or not.
public function show($type, $own, $id, $address = null)
{
$page = (object) $this->template;
$page->breadcrumbs[] = array('url' => 'javascript://', 'text' => 'Property Search', 'attribute' => array('data-component' => 'back'));
// Now lets query our server
$client = new GuzzleHttp\Client(['verify' => false ]);
$response = $client->get( env('LISTINGS_SERVER', 'https://listings.homicity.com') . '/property/' . $id, ['http_errors' => false]);
if ($response->getStatusCode() == "500") {
abort(404);
}
else {
$page->content = Property::parseResult($response->getBody());
$page->title = strtoupper(trim($page->content->address));
$page->breadcrumbs[] = array('text' => $page->title);
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$currency = 'CAD';
$raw = $formatter->parseCurrency($page->content->price, $currency );
$page->content->mortgage = Mortgage::stage(
false,
$raw
);
return view('property.display', compact('page'));
}
}

Passing variables in phpunit

I'm trying to pass an array i created in my testcase into my function i want to test. Is it possible to create a vairable in the testcase and pass or mock it to the class/function i want to test?
is it possible to use something like this:
$this->object = array(//array code here);
$this->testclass->attachVar->getAllObjects($this->objects);
Here is my code:
class myClassTest extends \PHPUnit_Framework_TestCase {
protected function setUp(){
$this->testclass = new \stdClass();
$this->testclass = $this->getMockBuilder('library\ixPlanta\plantChange', $this->object)
->disableOriginalConstructor()
->getMock();
}
public function testGetAllObjects() {
$this->object = array(
'testdb' => array(
'testdb_michel' => array(
'dbname' => 'testdb',
'projectName' => 'testdb',
'projectID' => 'bd993d2b9478582f6d3b73cda00bd2a',
'mainProject' => 'test',
'search' => false,
'webgroup' => array(),
'locked' => false
)
)
);
$this->testclass->expects($this->once())
->method('GetAllObjects')
->with('testdb', false, "CHECKED")
->injectTo('object', $this->object)
->will();
$result = $this->testclass->getAllObjects('testdb', false, "CHECKED");
$this->assertTrue($result);
}
In the function testGetAllObjects() i created an array that i want to pass to the function i want to test
public function getAllObjects($company,$selected=false,$selectText='CHECKED'){
$objList = array();
$i = 0;
foreach($this->Objects[$company] as $key => $value){
$objList[$i] = array('value'=> $key,'name' => $value['projectName'], 'objectID' => $value['projectID']);
$objList[$i]['checked'] = '';
if($selected !== false && !is_array($selected) && $selected === $value['dbname']){
$objList[$i]['checked'] = $selectText;
}elseif($selected !== false && is_array($selected) && in_array($value['dbname'], $selected)){
$objList[$i]['checked'] = $selectText;
}
++$i;
}
return $objList;
}
The variable i want to pass to getAllObjects is $this->objects
I think you misunderstood mock objects. The purpose of mock objects is, to create a dummy object for any other class you don't want to test. Mocking a method means, to prevent another class from calling its actual logic. Instead, it is not executed and the mock just returns whatever you gave it.
To test your actual class you just instantiate it and call its method:
class myClassTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->testclass = new MyClass();
}
public function testGetAllObjects()
{
$this->testclass->object = array(
'testdb' => array(
'testdb_michel' => array(
'dbname' => 'testdb',
'projectName' => 'testdb',
'projectID' => 'bd993d2b9478582f6d3b73cda00bd2a',
'mainProject' => 'test',
'search' => false,
'webgroup' => array(),
'locked' => false
)
)
);
$result = $this->testclass->getAllObjects('testdb', false, "CHECKED");
$this->assertTrue($result);
}
}
Example of a mock:
Let's say your class contains some other object of the class Service which is injected through the constructor:
class MyClass {
protected $service;
public function __construct(Service $service) {
$this->service = $service;
}
public function myMethod($argument) {
$return = $this->service->callService($argument);
return $return;
}
}
And your Service object is something like this:
class Service{
public function callService($argument) {
if($argument === NULL) {
throw new \Exception("argument can't be NULL");
}
return true;
}
}
Now you could test MyClass with this method:
public function testMyClassMethod() {
$serviceMock = $this->getMockBuilder("Service")->getMock();
$serviceMock->expects($this->any())
->method("callService")
->will($this->returnValue(true));
$myClass = new MyClass($serviceMock);
$this->assertTrue($myClass->myMethod(NULL));
}
myMethod will still return true, although Service would normally throw an Exception if $argument is NULL. But because we mocked the method, it is never actually called and the mock object will return whatever we provided in ->will($this->returnValue()).

Symfony PHPUnit Test ( error 500 )

Im testing this function
/**
* #Route("/list", name="_clients")
* #Method("GET")
*/
public function ClientsAction()
{
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('InvoiceBundle:Clients')->findByUser($this->user());
if($data){
$Clients = array();
foreach($data as $v){
if($v->getCompanyId() != 0 ) {
$companyId = $v->getCompanyId();
} else {
$companyId = '';
}
if ($v->getClient() == 'person'){
$company = $v->getName().' '.$v->getLname();
} else {
$company = $v->getCompany();
}
$Clients[] = array(
'id' => $v->getId(),
'settings' => $company,
'companyId' => $companyId,
'client' => $v->getClient(),
'mobile' => $v->getMobile(),
'email' => $v->getEmail(),
'clientName' => $v->getClientName(),
'delivery' => $v->getDelivery(),
'ContactPerson' => $v->getContactPerson()
);
}
} else {
$Clients = array('data' => 'empty');
}
$response = new JsonResponse($Clients);
return $response;
}
The function it self runs correctly , but then i want to check if my 'Content-Type' is Json with this function
public function testClients()
{
$client = static::createClient();
$client->request('GET', '/clients/list');
$this->assertTrue(
$client->getResponse()->headers->contains(
'Content-Type',
'application/json'
)
);
}
with this i get a FALSE value.
Then i try to do a test for Status code
$this->assertSame(200, $client->getResponse()->getStatusCode());
With this i get error 500 instead of 200 OK
I understand that is why i get a FALSE value in my 'Content-Type' test but i cant get why.
Im doing all this according to the Symfony documentation.
May be i'm doing something wrong or is it just that you cant check the 'Content-Type'?
Any help would be appreciated!
JsonResponse does add the Content-Type header (application/json) so this should not be an issue.
I think the main issue is that you are missing $ on the client->request() line.
Edit :
Before the declaration of your class, did you add #Route("/clients") ?
Or, maybe the data returned by findByUser is not what you expected and calls to $v fail.

The second call stored procedures causes an error SQLSTATE[HY000]: General error: 2014 Cannot execute queries in zf2

This is my controller :
public function addAction()
{
if($this->getAuthService()->hasIdentity())
{
$this->layout('layout/adminDashboardLayout');
$request= $this->getRequest();
if($request->isPost())
{
$rowmaterial= new RowmaterialModel();
//Current User Id from Session
$session = new Container('user');
$userId = $session->offsetGet('userId');
$rowmaterial->setCode($request->getPost('category_alias'));
$rowmaterial->setCategory($request->getPost('category'));
$rowmaterial->setCreatedOn(date('Y-m-d H:i:s'));
$rowmaterial->setUpdatedOn(date('Y-m-d H:i:s'));
$rowmaterial->setCreatedBy($userId);
$this->getCategoryTable()->inserts($category);
}
$page = (int) $this->params()->fromRoute('page', 1);
$iteratorAdapter = new \Zend\Paginator\Adapter\ArrayAdapter(iterator_to_array($this->getRowmaterialTable()->fetchAll()));
$category = new \Zend\Paginator\Paginator($iteratorAdapter);
$viewModel= new ViewModel(array(
'fetchAllDatas' => $category->setCurrentPageNumber($page)->setItemCountPerPage('8'),
'categories' =>$this->getCategoryTable()->fetchAllCategoryStatusOn(),
'uom' => $this->getUomTable()->fetchAllUomStatusOn(),
'flashMessages' => $this->flashMessenger()->getMessages(),
));
return $viewModel;
}
else
{
$this->flashMessenger()->addMessage("Please Login");
return $this->redirect()->toRoute("admin");
}
This is my first Model file function :
public function fetchAllCategoryStatusOn()
{
$statement= $this->adapter->query("call fetchAllCategoryStatusOn()");
$result= $statement->execute();
return $result;
}
This is my second Model file function :
public function fetchAllUomStatusOn()
{
$statement= $this->adapter->query("call fetchAllUomStatusOn()");
$result= $statement->execute();
return $result;
}
At the time of calling this fetchAllUomStatusOn() Storedprocedure this error will show
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries
are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only
ever going to run against mysql, you may enable query buffering by setting the
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
This is my global.php file :
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=cp;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
I did lot of search I could not get correct answer, at last I get 'closeCursor()' function. I use this function this way ,
public function fetchAllUomStatusOn()
{
$statement= $this->adapter->query("call fetchAllUomStatusOn()");
$statement->closeCursor();
$result = $statement->execute();
return $result;
}
By using this function this error will get.
Fatal error: Call to undefined method Zend\Db\Adapter\Driver\Pdo\Statement::closeCursor() in /var/www/cp/module/Admin/src/Admin/Model/UomTable.php on line 100.
My php version is 5.4. So please help me... This is my first attempt with Stackoverflow. Sorry for my bad English.
I solved this error. Use iterator_to_array() function in controller.
public function addAction()
{
if($this->getAuthService()->hasIdentity())
{
$this->layout('layout/adminDashboardLayout');
$request= $this->getRequest();
if($request->isPost())
{
$rowmaterial= new RowmaterialModel();
//Current User Id from Session
$session = new Container('user');
$userId = $session->offsetGet('userId');
$rowmaterial->setCode($request->getPost('category_alias'));
$rowmaterial->setCategory($request->getPost('category'));
$rowmaterial->setCreatedOn(date('Y-m-d H:i:s'));
$rowmaterial->setUpdatedOn(date('Y-m-d H:i:s'));
$rowmaterial->setCreatedBy($userId);
$this->getCategoryTable()->inserts($category);
}
$page = (int) $this->params()->fromRoute('page', 1);
$iteratorAdapter = new \Zend\Paginator\Adapter\ArrayAdapter(iterator_to_array($this->getRowmaterialTable()->fetchAll()));
$category = new \Zend\Paginator\Paginator($iteratorAdapter);
$viewModel= new ViewModel(array(
'fetchAllDatas' => $category->setCurrentPageNumber($page)->setItemCountPerPage('8'),
'categories' => iterator_to_array($this->getCategoryTable()->fetchAllCategoryStatusOn()),
'uom' => iterator_to_array($this->getUomTable()->fetchAllUomStatusOn()),
'flashMessages' => $this->flashMessenger()->getMessages(),
));
return $viewModel;
}
else
{
$this->flashMessenger()->addMessage("Please Login");
return $this->redirect()->toRoute("admin");
}

Categories