How to get the public objects - php

I'm working on PHP with Rackspace API, this is what I have used here:
$file->setContent(fopen('sites/default/files/rackspace/' . $end_element, 'r+'));
$cdnUrl = $file->getPublicUrl();
print_r($cdnUrl);
And its returning me the below mentioned structure.
Guzzle\Http\Url Object
(
[scheme:protected] => http
[host:protected] => something.r2.cf3.rackcdn.com
[port:protected] =>
[username:protected] =>
[password:protected] =>
[path:protected] => /something-abc.jpg
[fragment:protected] =>
[query:protected] => Guzzle\Http\QueryString Object
(
[fieldSeparator:protected] => &
[valueSeparator:protected] => =
[urlEncode:protected] => RFC 3986
[aggregator:protected] =>
[data:protected] => Array
(
)
)
)
What I need here is something like this:
Guzzle\Http\Url Object
(
[scheme] => http
[host] => something.r2.cf3.rackcdn.com
[port] =>
[username] =>
[password] =>
[path] => /something-abc.jpg
[fragment] =>
[query] => Guzzle\Http\QueryString Object
(
[fieldSeparator] => &
[valueSeparator] => =
[urlEncode] => RFC 3986
[aggregator] =>
[data] => Array
(
)
)
)
So that at least I can use those objects, any suggestions?

It is a Guzzle\Http\Url object, and you will not be able to access its protected or private properties. The class is defined here, so you can use any of the public methods to access its state.
You can also cast it to a string like so:
$stringUrl = (string) $url;
Or access other stuff:
$host = $url->getHost(); // something.r2.cf3.rackcdn.com
$scheme = $url->getScheme(); // http
$port = $url->getPort();
$path = $url->getPath(); // something-abc.jpg
The query is represented by another object, Guzzle\Http\QueryString:
$query = $url->getQuery();
For more info on object visibility, please consult the official docs.

Related

php - Accessing json array object

I have a JSON array object in which I am trying to append an array to one of the fields.
{"email":"bar#foo.org","password":"password","devices":{}}
print_r($arr) gives me:
Array ( [0] => {
"email":"bar#foo.org",
"password":"password",
"devices":{}
}
[1] => {
"email":"bar2#foo.org",
"password":"password",
"devices":{}
}
)
where $device_info is an array of structure:
array(
"number" => $phoneNumber,
"type" => "CellPhone",
"config" => array(
"batteryLevel" => 100,
"Lowbatterylevel" => 10,
)
I am trying to do this:
array_push($arr[$i]["devices"],$device_info);
which throws an error "Warning: Illegal string offset 'devices' "
I saw some other similar questions in StackOverflow but the solutions didn't work. Can someone point out what I'm doing wrong here? Thanks in advance.
You are not looking closely enough at your original JSON String or the full output from your print_r()
That is an Object containing properties and devices property is an object as well that contains it own properies
Here is some sample code to get your going
$s = '{"email":"bar#foo.org","password":"password","devices":{}}';
$j = json_decode($s);
$o = new stdClass();
$o->number = 999;
$o->type = "CellPhone";
$o->config = array("batteryLevel" => 100,"Lowbatterylevel" => 10);
$j->devices = $o;
print_r($j);
echo json_encode($j);
Results are
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 999
[type] => CellPhone
[config] => Array
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":999,"type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}
To me this looks like you confuse objects and arrays in your approach...
That json encoded string you posted does not encode an array but an object. So you have to treat it as such. Take a look at this simple demonstration code:
<?php
$payload = [
"number" => '01234567890',
"type" => "CellPhone",
"config" => [
"batteryLevel" => 100,
"Lowbatterylevel" => 10
]
];
$input = '{"email":"bar#foo.org","password":"password","devices":{}}';
$data = json_decode($input);
$data->devices = $payload;
$output = json_encode($data);
print_r(json_decode($output));
print_r($output);
The output ob above obviously is:
stdClass Object
(
[email] => bar#foo.org
[password] => password
[devices] => stdClass Object
(
[number] => 01234567890
[type] => CellPhone
[config] => stdClass Object
(
[batteryLevel] => 100
[Lowbatterylevel] => 10
)
)
)
{"email":"bar#foo.org","password":"password","devices":{"number":"01234567890","type":"CellPhone","config":{"batteryLevel":100,"Lowbatterylevel":10}}}

Session container not working in zf2?

I have seen many questions on StackOverflow and I have this code
use Zend\Session\Container;
class IndexController extends AbstractActionController {
public function indexAction() {
$userSession = new Container('user');
$userSession->username = 'Sandhya';
return new ViewModel();
}
}
When I am printing the $userSession container in the controller it is giving me this output
Zend\Session\Container Object (
[name:protected] => user
[manager:protected] => Zend\Session\SessionManager Object (
[defaultDestroyOptions:protected] => Array (
[send_expire_cookie] => 1
[clear_storage] =>
)
[name:protected] =>
[validatorChain:protected] =>
[config:protected] => Zend\Session\Config\SessionConfig Object (
[phpErrorCode:protected] =>
[phpErrorMessage:protected] =>
[rememberMeSeconds:protected] => 240
[serializeHandler:protected] =>
[validCacheLimiters:protected] => Array (
[0] => nocache
[1] => public
[2] => private
[3] => private_no_expire
)
[validHashBitsPerCharacters:protected] => Array (
[0] => 4
[1] => 5
[2] => 6
)
[validHashFunctions:protected] =>
[name:protected] =>
[savePath:protected] =>
[cookieLifetime:protected] => 2592000
[cookiePath:protected] =>
[cookieDomain:protected] =>
[cookieSecure:protected] =>
[cookieHttpOnly:protected] => 1
[useCookies:protected] => 1
[options:protected] => Array (
[gc_maxlifetime] => 2592000
)
)
[defaultConfigClass:protected] => Zend\Session\Config\SessionConfig
[storage:protected] => Zend\Session\Storage\SessionArrayStorage Object (
)
[defaultStorageClass:protected] => Zend\Session\Storage\SessionArrayStorage
[saveHandler:protected] =>
)
[storage:protected] => Array ( )
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => name
[1] => manager
[2] => storage
[3] => flag
[4] => iteratorClass
[5] => protectedProperties
)
)
It means there is nothing like username...
But when I am printing the S_SESSION it gives me this output...
Array (
[__ZF] => Array (
[_REQUEST_ACCESS_TIME] => 1429081041.81
)
[user] => Zend\Stdlib\ArrayObject Object (
[storage:protected] => Array (
[username] => Sandhya
)
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => storage
[1] => flag
[2] => iteratorClass
[3] => protectedProperties
)
)
)
There is a field username...
But when I am trying to get the $_SESSION in view it gives me the same output as above..
The problem is I am not able to get the username in both the container as well as in $_SESSION.
I need it in the controllers.
what can be the problem need help? Thank you.
I think you have to work on your configuration.
You have to setup a common SessionManager to manage handling of your session information.
Something like this:
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
Container::setDefaultManager($sessionManager);
I would suggest registering your SessionManager config in your ServiceManager instance and then use it throughout the application.
'service_manager' => array(
'factories' => array(
'session_manager' => 'My\Factory\SessionManagerFactory'
)
)
You can then get your SessionManager in any controller:
$sessionManager = $this->serviceLocator->get('session_manager');
And if you create a new Container it will use your common/default SessionManager instance automatically so all will be managed in one place.
$userSession = new Container('user');
$userSession->getManager() === $this->serviceLocator->get('session_manager') // true
On how to register your session_manager I will refer to the official ZF2 documentation.
You can use the following code:
$userSession = new Container('user');
//To check the session variable in zf2:
if($userSession->offsetExists('username')){
//Your logic after check condition
}
This will return true or false on the basis of session exist or not.
//To get the value of session:
echo $user->offsetGet('username');
Above code will return the value of session index username.
Instead of $userSession->username = 'Sandhya'; you can use below code:
$user->offsetSet('username','Sandhya');
This is zf2 standard, which is used by session container in zf2.
you can just get your username from session in controllers.
$userSession = new Container('user');
$username = $userSession->username ;
var_dump($username); //Sandhya
it work for me . try it !

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

php stdClass object duplicate

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 );

How to print protected object in php

I am doing the login using twitter oauth functionality. I am getting the following object from $client = $token->getHttpClient($config) method:
Zend_Oauth_Client Object
(
[_config:protected] => Zend_Oauth_Config Object
(
[_signatureMethod:protected] => HMAC-SHA1
[_requestScheme:protected] => header
[_requestMethod:protected] => POST
[_version:protected] => 1.0
[_callbackUrl:protected] => http://roomstayssvn.com/register/twittercallback
[_siteUrl:protected] => http://twitter.com/oauth
[_requestTokenUrl:protected] =>
[_accessTokenUrl:protected] =>
[_authorizeUrl:protected] =>
[_consumerKey:protected] => b04fuaxLR2d035FN8tTkQ
[_consumerSecret:protected] => NGPPovdXDnSpivNoMNIgA609ZJIB8GVKGgs6yEF8A
[_rsaPrivateKey:protected] =>
[_rsaPublicKey:protected] =>
[_token:protected] => Zend_Oauth_Token_Access Object
(
[_params:protected] => Array
(
[oauth_token] => 299516752-tksjJZUR7Q2gwrDRDpLOLCrYhySTGWz1SBwTKcRU
[oauth_token_secret] => 7S9R2FLuB0GT4vvy0GerThUnpkbSTeSalURib48Sx20
[user_id] => 299516752
[screen_name] => jogkunal5
)
)
.....
..... and so on
I want to print user_id and screen_name. How can I print it?
Following should work
$user_id = $client->getToken()->getParam('user_id');
$screen_name = $client->getToken()->getParam('screen_name');
Zend_Oauth_Client::__call() proxies any method of Zend_Oauth_Config.
Zend_Oauth_Config::getToken() returns Zend_Oauth_Token
Zend_Oauth_Token::getParam() gets the value for a parameter
Read the docs from here.
Its better you use a Good IDE that supports Zend framework.

Categories