PhpUnit: how to create examples of data structures for testing? - php

Say you have a method that receives an array as a parameter. That method does some manipulation with that array and then outputs a different array.
public function createArrayForX(array $myArray){
return $modifiedArray;
}
In order for me to test that the output has some values I need to create some sample cases for my input. It is a tedious work to create arrays manually, especially big ones.
public function testCreateArrayForX(){
$myArray = []; // **how do I easily create myArray here**
$this->assertContains("String that I want", $this->sampleClass->createArrayForX($myArray));
}
I tried something like var_dumping my array in the program, copying the result from var_dump and transforming it back to array (Convert var_dump of array back to array variable) and then edit it to make different tests. Is there a simple way or am I doing things wrong if I need this?
So my question is how do you easily create a skeleton for you sample input that you can then change to test different scenarios?

print(var_export($myArray, true));
in the program gave me what I need.

Related

Merge two PHP tags

I want to convert two different PHP tags into a single PHP tag.This may sound a little weird but recently I found a question like this and answer with correct marked.
I can't find I'm currently lost address.
My question:
for example;
$gates = array('t1','t2','t3',t4','t5');
$openGates-> and $gates merge.
Result:
$openGates->t1; or t2,t3.
If I remember correctly, the answer to the problem I found before was;
$openGates->{$gates}; like this. I not sure
How can I do that?
You seem to be confusing objects with arrays. Arrays simply contain data, unless you create them with keys also. Such as:
$gates = array('t1'=>true,'t2'=>false,'t3'=>"maybe",'t4'=>0,'t5'=>50);
Matthew Page is correct in that you should look up PHP OOP for a solution.
That being said, you can cast your array to an object providing it has both keys and values:
$gates = (object) array('t1'=>true,'t2'=>false,'t3'=>"maybe",'t4'=>0,'t5'=>50);
or
$openGates = (object) $gates;
This will allow you to access 'properties' of the object in the way you have demonstrated:
echo $openGates->t1;, for example. The -> operator only applies to objects, which are instances of classes, not arrays.
If you do cast your array to the type of object, be sure that you have both keys and values.
It's not simple for newbie programmer...
At first:
$gates = array('t1','t2','t3','t4','t5');
It's Array
$openGates->
This is class instance. Btw. You can retrieve class instance var like $className->varName
You can't simple merge array and class instance. But you can create new class instance variables by loop.
foreach($gates as $gateKey=>$gateVal) {
$openGates->$gatesVal = NULL;
}
But I think it's, in result should be like that:
$gates = array('t1'=>'opened','t2'=>'closed','t3'=>'closed','t4'=>'opened','t5'=>'opened');
foreach($gates as $gateKey=>$gateVal) {
$openGates->$gateKey = $gateVal;
}
echo $openGates->t1;
// or
foreach($gates as $key=>$val) {
echo $openGates->$key.PHP_EOL;
}
Btw you can simple set $openGates->gates = $gates; and call it like echo $openGates->gates['t1'];

Codeigniter accessing array values

I simply want to know how to access array elements retrieved from a database. I have the following code to get the names of each item in my database.
$plat_options = $this->db->get('tblplatform_options')->select('name')->result();
How do I go about accessing the name from the array $plat_options? Typically I would do $plat_options[0] for the first element in C#, how is this done in php/codeigniter?
In PHP/Codeigniter, can be done in the same way:
$plat_options[0] //if you have this element, usually is better to check if exists.
You can retrieve all the elements with foreach($plat_options as $option){...}
You can cast to object: https://www.kathirvel.com/php-convert-or-cast-array-to-object-object-to-array/
Or use a Codeigniter Helper (assuming you are using CI3): http://www.codeigniter.com/user_guide/helpers/array_helper.html
I recomend to know which is your array format and retrieve that way (if you don't know, you can do a: var_dump($plat_options) ) to know if is an associative array.
You can use the result_array() function:
$data = $plat_options->result_array();
echo($data[0]['name']);
or:
$data = array_shift($q->result_array());
echo($data['name']);
I extracted this last part from: Codeigniter $this->db->get(), how do I return values for a specific row? that you could check too.
If you don't know a lof of CI, the best you can do is do a simple tutorial to understand how the data + ActiveRecord works.
Hope it helps!

Alternative way of accessig an array within array in PHP

I'm trying to access an array within another array (basically, a two dimensional array). However, the usual way of doing this ($myarray[0][0]) doesn't work for me.
The reason is because I want to create a recursive function which, in each call, should dive deeper and deeper into a array (like, on first call it should look at $myarray[0], on second call it should look at $myarray[0][0] and so on).
Is there any alternative way of accessing an array within array?
Thanks.
Traverse the array by passing always a subarray of it to the recursive function.
function f(array &$arr)
{
// Some business logic ...
// Let's go into $arr[0]
if(is_array($arr[0]))
f($arr[0]);
}
f($myarray);

json_encode "not working" properly?

Of course, the subject is sort of tricky... I assume json_encode php function works perfectly.
But there must be something wrong on what I am doing.
I have a variable in my PHP program that actually contains data. Sort of structured data, as it is an object variable with all its attributes set properly.
But, magically, when I apply json_encode to that variable, it just doesn't "fills" the json object.
See the case below:
As you can see... the variable $test contains data.
Now, putting the focus on the whole json_encoder($test) thing, it just doesn't fills the "test" {} part of the json object.
It's definitely me doing something wrong. But... what?
Thanks a lot in advance.
Pedro
json_encode only works with public properties, it cannot take the private or protected attributes of an object and form a JSON representation without any help.
To serialize an object with all of its properties, you need to manually implement a function to do so. The official PHP documentation has a good example on how to do this here

Is there a version of the PHP array that is pass-by-reference?

I'm asking this because I'm working with a recursive function that generates a large array tree and the pass-by-copy aspect of the arrays are completely screwing with my head. I've tried using ArrayObject, but that's really an object, isn't it? None of the array_keys type array functions work with it, and json_encode doesn't understand that it's an array.
I'd like a version of the PHP array that feels, smells and looks like the normal array, but is pass-by-reference. Is there anything like that in PHP?
Woah woah hold up people; I'm well aware of the & symbol but that's what I'm trying to avoid. As my question specifies (^) I'm looking for a version of the PHP array that is pass-by-reference by default
I'd like a version of the PHP array that feels, smells and looks like
the normal array, but is pass-by-reference. Is there anything like
that in PHP?
No, There is nothing like that in PHP.
Json encode should be able to pass objects. But if you for some reason NEED an array, you can't use objects and then cast it as array before encoding to json?
<?php
$object = (object)array("number"=>1);
function addToTen($object){
if($object->number<10){
$object->number++;
addToTen($object);
}
}
addToTen($object);
echo json_encode((array)$object);
//echoes {"number":10} with or without casting it as an array
?>
You could also wrap your array in an object of course, like this:
$object = new stdClass;
$object->a = array();
function fillUpArray($object){
if(count($object->a)<10){
$object->a[] = "someValue";
fillUpArray($object);
}
}
fillUpArray($object);
echo json_encode($object->a);
//echoes ["someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue","someValue"]
I must admit though I don't entirely get what you're trying to accomplish here :S
Yes, see the PHP manual page: http://php.net/manual/en/language.references.pass.php
Stop using &references altogether, in php they get cumbersome pretty quickly, (being, unlike C pointers, almost transparent, the only way to check you're actually using a reference is by assigning junk to it and check the effect this has on a tree) and you don't seem willing to handle that level of subtlety.
(Nor to wrap it with an ArrayObject, apparently)
Are you aware objects ARE references?
Object-wrap every aspect of your tree and your life will instantly get less miserable.
I am not aware of any such built-in functionality in PHP that you ask. Also, you are quite reluctant to use references. Hmmm...you could send a request to the PHP dev team to include such stuff in PHP v6, along with unicode that is supposed to come, that would us all happy :).
However, can you use a class and assign your initial array to one of the class variables and then process it and get it back after the recursion. Not sure if that would work, but anyway here it is:
<?php
class noReference {
public $myData;
public function __construct( $data ) {
$this->myData = $data; // this is your initial array.
}
// this function works on the myData array and changes it.
public function myRecursiveFunction() {
// your code here
$this->myRecursiveFunction(); // called as per your logic
// your code here
}
public function getData() {
return $this->myData;
}
public function __destruct() {
unset( $this->myData );
}
}
$data = array(/*WHATEVER_PLEASES_YOU*/);
$noref = new noReference( $data );
// this will be your recuresive function
$noref->myRecursiveFunction();
//your data here
$result = $noref->getData();
?>
Let me know if this works. Cheers!
you can force php to pass things by reference by adding an &-sign to the parameter. read the documentation for more information.

Categories