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
}
Related
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]);
}
}
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.
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
I have a Container:
$newContainer = new ContainerBuilder();
I load some parameters:
$loader = new YamlFileLoader($newContainer, new FileLocator(__DIR__.'/../Resources/config/newFolder'));
$loader->load('newParameters.yml');
And my container looks like this:
[parameters:protected] => Array
(
[exampleKey => Array
(
[parameter] => something value
[anotherParameter] => another value
)
)
Now i do the merge:
$container->merge($newContainer);
And my merge looks like this - print_r($container):
[parameters:protected] => Array
(
[existing] => Array
(
...
)
[existing2] => Array
(
...
)
[exampleKey => Array
(
[parameter] => something value
[anotherParameter] => another value
)
[existing3] => Array
(
...
)
)
How can merge my container so i have this??:
[parameters:protected] => Array
(
[existing] => Array
(
...
)
[existing2] => Array
(
...
[exampleKey => Array
(
[parameter] => something value
[anotherParameter] => another value
)
)
[existing3] => Array
(
...
)
)
Please help...
Dont use merge, use add():
$container->getParameterBag()
->add(array(
'existing2' => $newContainer->getParameterBag()->all()
));
I didnt know there are methods hidden after $container->getParameterBag(), you can use: ->all(), set(), has(), get() etc. Very useful. Thanks
I have an array which contains status objects, these status objects contain an array of like objects and also contain comment objects
My question is that now I have the objects in my array, how do I pull them back out? This is so I can save them to a db later on.
Thanks for your help
Andy
e.g.
Array
(
[0] => cStatus Object
(
[statusId:cStatus:private] => 123123123
[message:cStatus:private] => powpowpow
[updated_time:cStatus:private] => 2011-01-27T15:52:48+0000
[likes:cStatus:private] => Array
(
)
[comments:cStatus:private] => Comment Object
(
[commentId:Comment:private] => 123123123
[created_time:Comment:private] => 2011-01-30T20:18:50+0000
[message:Comment:private] => Kazam
[name:Comment:private] => Blue man
[createdBy:Comment:private] => 124124
[likes:Comment:private] => Array
(
)
)
)
[1] => cStatus Object
(
[statusId:cStatus:private] => 5125125
[message:cStatus:private] => Gawdam fruit and fibre is tasty :D
[updated_time:cStatus:private] => 2011-01-25T20:21:56+0000
[likes:cStatus:private] => Array
(
[0] => Like Object
(
[likeId:Like:private] => 120409086
[name:Like:private] => Jt
)
)
[comments:cStatus:private] => Array
(
)
)
[2] => cStatus Object
(
[statusId:cStatus:private] => 5215215
[message:cStatus:private] => Dear 2
[updated_time:cStatus:private] => 2011-01-18T08:28:50+0000
[likes:cStatus:private] => Array
(
[0] => Like Object
(
[likeId:Like:private] => 2456
[name:Like:private] => Edw2r
)
[1] => Like Object
(
[likeId:Like:private] => 2452412
[name:Like:private] => aw1
)
[2] => Like Object
(
[likeId:Like:private] => 12412411
[name:Like:private] => wqw
)
)
[comments:cStatus:private] => Array
(
)
)
)
You can use foreach and access properties of individual objects to be saved. I assume you are using getter and setter methods since all your properties are private. Using foreach provides the "as" keyword to make an alias for each individual object instance as the loop executes among them.
<?foreach($obj as $status){
$status_text = $status->getMessage();
//save this to database using your favored method;
$comments = $status->getComments();
//nest the foreach for all the comments to save them as well, if you like
foreach($comments as $comment){
//Save $comment here as well
}
}
?>
This is especially handy for complex nested objects like yours, since public methods and properties can be accessed by the individual iterator for easy action, like saving to the database.