php stdClass object duplicate - php

I am creating a stdobject that is sent to to a wsdl wevservice via SOAP with a _soapcall.
It works when I send only one parameter but, sometimes i need to send 2 parameters under the same tag and I dont know hot to make it. Let me explain a little.
I create 2 std objects:
Object 1
$sObject4->PropertyToSearchName = 'State';
$sObject4->SearchComparer = 'Equals';
$sObject4->Value = new SoapVar(2, XSD_INT, 'int','http://www.w3.org/2001/XMLSchema');
$sObject3->SearchObject = $sObject4;
Object 2
$sObject41->PropertyToSearchName = 'ProviderId';
$sObject41->SearchComparer = 'Equals';
$sObject41->Value = new SoapVar(21, XSD_INT, 'int','http://www.w3.org/2001/XMLSchema');
$sObject31->SearchObject = $sObject41;
So i need to merge this 2 objects so i end up having something like:
[ListOfSearchObjects] => stdClass Object
(
[SearchObject] => stdClass Object
(
[PropertyToSearchName] => State
[SearchComparer] => Equals
[Value] => SoapVar Object
(
[enc_type] => 135
[enc_value] => 2
[enc_stype] => int
[enc_ns] => http://www.w3.org/2001/XMLSchema
)
)
[SearchObject] => stdClass Object
(
[PropertyToSearchName] => ProviderId
[SearchComparer] => Equals
[Value] => SoapVar Object
(
[enc_type] => 135
[enc_value] => 21
[enc_stype] => int
[enc_ns] => http://www.w3.org/2001/XMLSchema
)
)
)
The created soap need to look like this with 2 [SearchObject]:
<ns3:ListOfSearchObjects>
<ns3:SearchObject>
<ns3:PropertyToSearchName>State</ns3:PropertyToSearchName>
<ns3:SearchComparer>Equals</ns3:SearchComparer>
<ns3:Value xsi:type="xsd:int">2</ns3:Value>
</ns3:SearchObject>
<ns3:SearchObject>
<ns3:PropertyToSearchName>Providerid</ns3:PropertyToSearchName>
<ns3:SearchComparer>Equals</ns3:SearchComparer>
<ns3:Value xsi:type="xsd:int">21</ns3:Value>
</ns3:SearchObject>
</ns3:ListOfSearchObjects>

If your method defined in the wsdl allows you to send multiple SearchObjects it should do the work for you when you pass it two:
$args = array( $SearchObj1, $SearchObj2 )
$res = $client->__soapCall( 'ListOfSearchObjects', $args );

Related

PHP read first item in object array

I have my code in PHP which is returning this Array of data:
GoCardlessPro\Core\ListResponse Object
(
[records] => Array
(
[0] => GoCardlessPro\Resources\Mandate Object
(
[model_name:protected] => Mandate
[created_at:protected] => 2017-04-01T16:49:09.642Z
[id:protected] => ID001
[links:protected] => stdClass Object
(
[customer_bank_account] => CB001
[creditor] => CR001
[customer] => CU001
)
[metadata:protected] => stdClass Object
(
)
[next_possible_charge_date:protected] => 2017-04-06
[payments_require_approval:protected] =>
[reference:protected] => RE001
[scheme:protected] => bacs
[status:protected] => active
[data:GoCardlessPro\Resources\BaseResource:private] => stdClass Object
(
[id] => 123
[created_at] => 2017-04-01T16:49:09.642Z
[reference] => RE001
[status] => active
[scheme] => bacs
[next_possible_charge_date] => 2017-04-06
[payments_require_approval] =>
[metadata] => stdClass Object
(
)
[links] => stdClass Object
(
[customer_bank_account] => 001
[creditor] => CR001
[customer] => CU001
)
)
[api_response] =>
)
)
)
I want to be able to read the ID of the first item in therecords array.
This data is contained inside a variable called $GC_Mandate;
I have tried these:
echo $GC_Mandate->records->{0}->id;
echo $GC_Mandate->records->0->id;
echo $GC_Mandate->records->[0]->id;
$GC_Mandate = $GC_Mandate->records;
echo $GC_Mandate->{0}->id;
But none will return the data
To get the first record, the syntax you need is $GC_Mandate->records[ 0 ].
However, that object is a GoCardlessPro\Resources\Mandate object and its member id is protected1, so we'd need to know the interface of GoCardlessPro\Resources\Mandate (its public methods1), to know if we can somehow retrieve the value of id.
My guess would be getId(), so the full syntax would become
$GC_Mandate->records[ 0 ]->getId()
But, that's just a guess. You'd have to look into the documentation/class definition of GoCardlessPro\Resources\Mandate, to be sure if you can retrieve id.
Turns out (provided I'm linking to the correct github repository) you can do:
$GC_Mandate->records[ 0 ]->id
since GoCardlessPro\Resources\Mandate extends GoCardlessPro\Resources\BaseResource, which exposes the protected members through GoCardlessPro\Resources\BaseResource::__get()2.
1. visibility in PHP
2. magic methods in PHP
I can't comment so I guess I'll have to post.
You should try to print_r($GC_Mandate); and see what it gives out and then go from there.
Try $GC_Mandate->records[0]->__get('id')
it will return all data ..for perticulat data put this in foreach loop
print_r($GC_Mandate['records']);

Cycling an array and delete item

I need help :)
I've to code a script that, cycling through an array inside an array , delete an element if in XXX field there isn't value (is NULL ).
My array is:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[0] => stdClass Object ( [name] => minnie [email] => blabla#gmail.com [XXX] => )
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
In this example the item [0] has no value in XXX value so my output array will be:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
i hope that you can help me :)
You could use a nested foreach() Loop to cycle through the Data and then perform some tests, which on failing, guarantees that it is safe to unset the pertinent variable. Here's how:
<?php
// WE SIMULATE SOME DATA TO POPULATE THE ARRAY, ONLY FOR TESTING PURPOSES
$objDate = new stdClass();
$objRez1 = new stdClass();
$objRez2 = new stdClass();
$objRez1->name = "minnie";
$objRez1->email = "blabla#gmail.com";
$objRez1->XXX = null;
$objRez2->name = null;
$objRez2->email = "fddd#gmail.it";
$objRez2->XXX = 0.88451100;
$objDate->sec = 1468503103;
$objDate->usec = 0;
// IN THE END WE NOW HAVE A SAMPLE ARRAY (SIMULATED) TO WORK WITH.
$arrData = array(
'idCampaign' => 3,
'idIT' => 322,
'recipients' => array(
$objRez1,
$objRez2
),
'date' =>$objDate,
);
// LOOP THROUGH THE ARRAY OF DATA THAT YOU HAVE
// NOTICE THE &$data IN THE LOOP CONSTRUCT...
// THIS IS NECESSARY FOR REFERENCING WHEN WE UNSET VARIABLES WITHIN THE LOOP
foreach($arrData as $key=>&$data){
// SINCE THE XXX KEY IS STORED IN THE 'recipients' ARRAY,
// WE CHECK IF THE CURRENT KEY IS 'recipients' & THAT $data IS AN ARRAY
if($key == "recipients" && is_array($data)){
// NOW WE LOOP THROUGH THE DATA WHEREIN THE 'XXX' KEY LIVES
foreach($data as $obj){
// IF THE VALUE OF THE XXX KEY IS NULL OR NOT SET,
// WE SIMPLY UNSET IT...
if(!$obj->XXX){
unset($obj->XXX);
}
}
}
}
var_dump($arrData);
You can verify the Results HERE.
Hope this could offer you a little tip on how to implement it rightly on your own...
This should do the job
foreach($arrayOfObjects as $index => $object){
if(!isset($object->xxx) || empty($object->xxx)){
unset($arrayOfObjects[$index]);
}
}

How to transform the results of a stored procedure in to a list of object then convert to json in CI?

I am using CodeIgniter 2.2.6 + DataMapper, I have a question regarding how to transform the results of a stored procedure into DataMapper Models, then convert them to json.
I have a model called Event:
class Event extends DataMapper {
var $table = 'EVENT'; // map to EVENT table
}
with the following code, I can easily get the top 10 Event:
$event = new Event();
$event->get( 10, 0 );
$event->all_to_json(); //this convert the result to json following the table structure
Now I have a stored procedure getSpecialEvent(), the result of this SP has exactly same structure as Table EVENT,
With the followng code, I do get the content but they are in Array format:
$sql = "call getSpecialEvent()";
$event = new Event();
$event = $this->db->query ($sql);
print_r ($event->result_array());
this will returned some thing like this:
Array
(
[0] => Array
(
[event_id] => 11
[title] => Test1
...
)
[1] => Array
(
[event_id] => 2
[title] => Test1
...
)
)
if I use this
foreach ( $event as $obj ) {
print_r($obj);
}
I get empty array:
Array
(
)
Array
(
)
then I tried
print_r ($event->result());
it returns
Array
(
[0] => stdClass Object
(
[event_id] => 11
[title] => Test1
...
)
[1] => stdClass Object
(
[event_id] => 2
[title] => Test2
...
)
}
I used some code found on internet to cast stdClass Object to Event, it looks like ok, but when I call to_json() method, it doesn't work.
function objectToObject($instance, $className) {
return unserialize(sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(strstr(serialize($instance), '"'), ':')
));
}
foreach ( $event->result() as $obj ) {
$newObj = $this->objectToObject($obj, "Event");
print_r ($newObj);
print_r ($newObj->to_json());
}
I printed he casted object, here it is:
Event Object
(
[table] => EVENT
[error] =>
[stored] =>
[model] =>
[primary_key] => id
[valid] =>
[cascade_delete] => 1
[fields] => Array
(
)
[all] => Array
(
)
[parent] => Array
(
)
[validation] => Array
(
)
[has_many] => Array
(
)
[has_one] => Array
(
)
[production_cache] =>
[free_result_threshold] => 100
[default_order_by] =>
[_validated:protected] =>
[_force_validation:protected] =>
[_instantiations:protected] =>
[_field_tracking:protected] =>
[_query_related:protected] => Array
(
)
[_include_join_fields:protected] =>
[_force_save_as_new:protected] =>
[_where_group_started:protected] =>
[_group_count:protected] => 0
[event_id] => 11
[title] => test11
...
)
but $newObj->to_json() returns empty
Array
(
)
Array
(
)
if I do a small test
$event = new Event ();
$event->event_id = 13;
$event->title = "xxxxx";
echo json_encode($event->to_json());
I do get:
{"event_id":13,"title":"xxxxx"....}
I don't know why the casted object doesn't work with to_json?
It seems to be a limitation, the casted DataMapper object (Event here) is not taken as a real DataMapper object, then I create a method in Event to export the needed info to aother pure object model and use json_encode(), this works.

Codeception check several elements with same locator

I have several elements on my page with same locator.
Example:
<div.test-info><a>Test1</a></div>
<div.test-info><a>Test2</a></div>
<div.test-info><a>Test3</a></div>
<div.test-info><a>Test4</a></div>
There maybe 20 or more elements on the page.
In python, I tested this with FOR loop, which run through array of elements, grabbed by 'findElemenets' method.
My problem is that i don't know how to do this with Codeception.
I found method '_findElements' but it returns Facebook\WebDriver\Remote\RemoteWebElement instances.
Like :
Array
(
[0] => Facebook\WebDriver\Remote\RemoteWebElement Object
(
[executor:protected] => Facebook\WebDriver\Remote\RemoteExecuteMethod Object
(
[driver:Facebook\WebDriver\Remote\RemoteExecuteMethod:private] => Facebook\WebDriver\Remote\RemoteWebDriver Object
(
[executor:protected] => Facebook\WebDriver\Remote\HttpCommandExecutor Object
(
[url:protected] => http://127.0.0.1:4444/wd/hub
[curl:protected] => Resource id #326
)
[sessionID:protected] => 109595b5-f094-4824-ac10-fc7d6353b799
[mouse:protected] =>
[keyboard:protected] =>
[touch:protected] =>
[executeMethod:protected] => Facebook\WebDriver\Remote\RemoteExecuteMethod Object
*RECURSION*
)
)
[id:protected] => 0
[fileDetector:protected] => Facebook\WebDriver\Remote\UselessFileDetector Object
(
)
)
[1] => Facebook\WebDriver\Remote\RemoteWebElement Object
(
[executor:protected] => Facebook\WebDriver\Remote\RemoteExecuteMethod Object
(
[driver:Facebook\WebDriver\Remote\RemoteExecuteMethod:private] => Facebook\WebDriver\Remote\RemoteWebDriver Object
(
[executor:protected] => Facebook\WebDriver\Remote\HttpCommandExecutor Object
(
[url:protected] => http://127.0.0.1:4444/wd/hub
[curl:protected] => Resource id #326
)
[sessionID:protected] => 109595b5-f094-4824-ac10-fc7d6353b799
[mouse:protected] =>
[keyboard:protected] =>
[touch:protected] =>
[executeMethod:protected] => Facebook\WebDriver\Remote\RemoteExecuteMethod Object
*RECURSION*
)
)
[id:protected] => 1
[fileDetector:protected] => Facebook\WebDriver\Remote\UselessFileDetector Object
(
)
)
)
How can I operate with this data, or is there another good way to resolve my problem ?
If you want to get content of divs, use grabMultiple method, it returns array of strings.
$I->grabMultiple('div.test-info a')
$elements = $I->_findElements('div.test-info a');
foreach($elements as $element)
{
*do some testing* for example $element->click();
}
the methods you can use for the RemoteWebElement, see http://facebook.github.io/php-webdriver/classes/RemoteWebElement.html
Here is working solution:
$allLinks = $I->grabMultiple('.readmore'); //grab all clickable links
for( $i = 0; $i<sizeof($allLinks); $i++ ) { //iterate through a loop
$I->click($allLinks[$i]); //click each link
}

Convert Stripe API response to JSON using stripe-php library

I'm accessing customer data from the Stripe API, which I'd like to convert to JSON. Usually I'd convert an object to an array and use json_encode() but I don't seem able to in this case, even when trying to access the nested arrays.
This is the response I'm trying to convert to json:
Stripe_Customer Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[id] => cus_2dVcTSc6ZtHQcv
[object] => customer
[created] => 1380101320
[livemode] =>
[description] => Bristol : John Doe
[email] => someone6#gmail.com
[delinquent] =>
[metadata] => Array
(
)
[subscription] =>
[discount] =>
[account_balance] => 0
[cards] => Stripe_List Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[object] => list
[count] => 1
[url] => /v1/customers/cus_2dVcTSc6ZtHQcv/cards
[data] => Array
(
[0] => Stripe_Object Object
(
[_apiKey:protected] => MY_KEY_IS_HERE
[_values:protected] => Array
(
[id] => card_2dVcLabLlKkOys
[object] => card
[last4] => 4242
[type] => Visa
[exp_month] => 5
[exp_year] => 2014
[fingerprint] => NzDd6OkHnfElGUif
[customer] => cus_2dVcTSc6ZtHQcv
[country] => US
[name] => John Doe
[address_line1] =>
[address_line2] =>
[address_city] =>
[address_state] =>
[address_zip] =>
[address_country] =>
[cvc_check] => pass
[address_line1_check] =>
[address_zip_check] =>
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
)
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
[default_card] => card_2dVcLabLlKkOys
)
[_unsavedValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_transientValues:protected] => Stripe_Util_Set Object
(
[_elts:Stripe_Util_Set:private] => Array
(
)
)
[_retrieveOptions:protected] => Array
(
)
)
Any help greatly appreciated!
PHP has reserved all method names with a double underscore prefix for future use. See https://www.php.net/manual/en/language.oop5.magic.php
Currently, in the latest php-stripe library, you can convert the Stripe Object to JSON by simpl calling **->toJSON().
[PREVIOUSLY]
All objects created by the Stripe PHP API library can be converted to JSON with their __toJSON() methods.
Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
$customer_json = $customer->__toJSON();
There is also a __toArray($recursive=false) method. Remember to set true as argument otherwise you will get an array filled with stripe objects.
Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$customer = Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
$customer_array = $customer->__toArray(true);
The attributes of Stripe_Objects can be accessed like this:
$customer->attribute;
So to get the customer's card's last4, you can do this:
$customer->default_card->last4;
However, you'll need to make sure you have the default_card attribute populated. You can retrieve the default_card object at the same time as the rest of the customer by passing the expand argument:
$customer = Stripe_Customer::retrieve(array(
"id" => "cus_2dVcTSc6ZtHQcv",
"expand" => array("default_card")
));
On the latest version, You can use echo $customer->toJSON(); to get the output as JSON.
I have done this way
`Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
$stripe_response= Stripe_Customer::create(array(
"card" => $token,
"plan" => $plan,
));
//Encoding stripe response to json
$resposnse_json_ecoded= json_encode($stripe_response);
//decoding ecoded respose
$response_decoded = json_decode($resposnse_json_ecoded, true);
//get data in first level
$account_id=$response_decoded['id'];
$individual = $response_decoded['individual'];
//get data in second level
$person_id=$individual['id'];`
If, like me, you arrived here looking for the python 2.7 solution, simply cast the stripe_object to str(). This triggers the object's inner __str__() function which converts the object into a JSON string.
E.g.
charge = stripe.Charge....
print str(charge)
Your top level object contains other object instances - the cast to (array) affects only the top level element. You might need to recursively walk down - but I'd do it differently here given that the classes are serializable:
$transfer = serialize($myobject);
What are you going to do with the otherwise JSONified data?
If you're going to transfer an object without the class information you might try to use Reflection:
abstract class Object {
/**
* initialize an object from matching properties of another object
*/
protected function cloneInstance($obj) {
if (is_object($obj)) {
$srfl = new ReflectionObject($obj);
$drfl = new ReflectionObject($this);
$sprops = $srfl->getProperties();
foreach ($sprops as $sprop) {
$sprop->setAccessible(true);
$name = $sprop->getName();
if ($drfl->hasProperty($name)) {
$value = $sprop->getValue($obj);
$propDest = $drfl->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($this,$value);
}
}
}
else
Log::error('Request to clone instance %s failed - parameter is not an object', array(get_class($this)));
return $this;
}
public function stdClass() {
$trg = (object)array();
$srfl = new ReflectionObject($this);
$sprops = $srfl->getProperties();
foreach ($sprops as $sprop) {
if (!$sprop->isStatic()) {
$sprop->setAccessible(true);
$name = $sprop->getName();
$value = $sprop->getValue($this);
$trg->$name = $value;
}
}
return $trg;
}
}
This is the base class of most of my transferrable classes. It creates a stdClass object from a class, or initializes a class from a stdClass object. You might easily adopt this to your own needs (e.g. create an array).
This is already in a JSON format so you do need to convert it again into json_encode()
just pass it into your script

Categories