Hey How Can i get any specific property from the whole object.
I have this query
$portfolios = $this->getDoctrine()
->getRepository('MunichInnovationGroupBundle:PmPortfolios')
->findBy(array('user' => '1'));
foreach ($portfolios as $portfolio){
if($portfolio.isDefault == true){
$default_portfolio = $portfolio;
}
echo $portfolio.name;
}
The complete object looks like this
MunichInnovationGroup\Bundle\Entity\PmPortfolios Object
(
[id:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => 991654b4-aa73-11e1-bdce-4a7b883b8e17
[portfolioName:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Umair Portfolio 1
[description:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Thsi is the description for Umairs portfolio 1
[permalink:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => premalink
[sharingCode:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => asdbnvg123dg
[shared:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] =>
[sharedPortfolioCalls:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] =>
[isDefault:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => 1
[user:MunichInnovationGroup\Bundle\Entity\PmPortfolios:private] => Proxies\MunichInnovationGroupBundleEntityUmUsersProxy Object
How can I get the isDefault value ?
Thanks in advance
If you have your entity set up correctly with all generated set/get methods, and isDefault is a private property (as it seems so from the var_dump) you can simply use
if($portfolio->getIsDefault())
For better method naming I would write a method in the entity:
public function isDefault() {
return $this->isDefault;
}
and then use
if($portfolio->isDefault())
Related
I have a class for configuration on my script and I implement the config. I then want to use the options as an object reference like the following, but not sure how to get it all the way to the final object field and also how to make it recognize sub arrays too
class Configuration {
public $cookies = array(
"cookie_prefix" => "site_",
"site_settings" => array(
"domain" => "somesite.com",
"https_only" => TRUE
),
"another_item" => "and some data too"
);
}
$config = new Configuration();
echo $config->cookies->cookie_prefix;
echo $config->cookies->site_settings->domain;
Right now it works if I do the following
echo $config->cookies['cookie_prefix'];
echo $config->cookies['site_settings']['domain'];
But I want it to be an object all the way down. Can't wrap my brain around this one for some reason?
I know this is easily done - I am just missing the way how...
I just passed the items in the __construct as json and its working the way I wanted now, duh.
public $cookies = array(
"cookie_prefix" => "site_",
"site_settings" => array(
"domain" => "somesite.com",
"https_only" => TRUE
),
"another_item" => "and some data too"
);
public function __construct() {
$this->cookies = json_decode(json_encode($this->cookies));
}
I'm pretty new to Phpspec testing and I don't know what is the correct way to test multiple scenarios when transforming a object to different response structure.
I need to check if price is correctly calculated. Here I have the Transformer spec test:
/**
* #dataProvider pricesProvider
*/
public function it_should_check_whether_the_prices_are_correct(
$priceWithoutVat,
$priceWithVat,
$vat,
Request $request,
Repository $repository
) {
$productIds = array(100001);
$result = array(
new Product(
'100001',
'MONSTER',
new Price(
$priceWithoutVat,
20,
'GBP',
null,
null
)
)
);
$expected = array(
array(
"productId" => "100001",
"brand" => "MONSTER",
"price" => array(
"amount" => $priceWithVat,
"vatAmount" => $vat,
"currencyCode" => "GBP",
"discountAmount" => (int)0
)
)
);
$repository->getResult(array(
Repository::FILTER_IDS => $productIds
))->willReturn($result);
$request->get('productIds')->willReturn(productIds);
/** #var SubjectSpec $transformedData */
$transformedData = $this->transform($request);
$transformedData->shouldEqual($expected);
}
public function pricesProvider()
{
return array(
array('123.456789', 14814, 2469),
array('60.00', 7200, 1200),
);
}
In my Transformer class I have a function which formats data to the correct format:
public function transform(Request $request)
{
$productIds = $request->get('productIds');
$productsResult = $this->repository->getResult(array(
Repository::FILTER_IDS => $productIds
));
$products = array();
foreach ($productsResult as $product) {
$products[] = $this->formatData($product);
}
return $products;
}
/**
* #param Product $product
* #return array
*/
private function formatData(Product $product)
{
return array(
'productId' => $product->getId(),
'brand' => $product->getBrandName(),
'price' => array(
'amount' => (int)bcmul($product->getPrice()->getAmountWithTax(), '100'),
'vatAmount' => (int)bcmul($product->getPrice()->getTaxAmount(), '100'),
'currencyCode' => $product->getPrice()->getCurrencyCode(),
'discountAmount' => (int)bcmul($product->getPrice()->getDiscountAmount(), '100')
)
);
}
The problem is, that I'm getting this error message:
316 - it should check whether the prices are correct
warning: bcmul() expects parameter 1 to be string, object given in
/src/AppBundle/Database/Entity/Product/Price/Price.php line 49
If I hard-code those values then the test is green. However I want to test varios prices and results, so I decided to use the dataProvider method.
But when dataProvider passes the $amountWithoutTax value, it's not string but PhpSpec\Wrapper\Collaborator class and because of this the bcmul fails.
If I change the $amountWithoutTax value to $priceWithoutVat->getWrappedObject() then Double\stdClass\P97 class is passed and because of this the bcmul fails.
How do I make this work? Is it some banality or did I completely misunderstood the concept of this?
I use https://github.com/coduo/phpspec-data-provider-extension and in composer.json have the following:
"require-dev": {
"phpspec/phpspec": "2.5.8",
"coduo/phpspec-data-provider-extension": "^1.0"
}
If getAmountWithTax() in your formatData method returns an instance of PhpSpec\Wrapper\Collaborator, it means that it returns a Prophecy mock builder instead of the actual mock, i.e. the one that you get by calling reveal() method. I don't know how your data provider looks like, but it seems that you're mocking your Price value objects instead of creating real instances thereof, and $product->getPrice() in your production code returns the wrong kind of object.
The solution would be either to create a real instance of the Price value object that's later returned by $product->getPrice() with new in the data provider, or by calling reveal() on that instance, like this (assuming $price is a mock object that comes from a type hinted parameter):
$product->getPrice()->willReturn($price->reveal());
I am trying to convert a PHP array object to an JSON.Following is the PHP Array Object;
Array
(
[0] => Project\Man\Model\Branch Object
(
[id:protected] => 123456
[name:protected] => Parent Branch
[type:protected] => services
)
)
I tried Serializing it but its not in a friendly readable object.
I tried the following:
json_encode
serialize
a:1:{i:0;O:23:"Project\Man\Model\Branch ":3:{s:5:"*id";s:36:"123456";s:7:"*name";s:20:"Parent Branch";s:7:"*type";s:8:"services";}}[{}]
I am trying for some solution where i can get JSON. any help.
If you just want json, you should only use json_encode(), not serialize().
Since your object properties are set as protected, they will however not be available when you encode the object whitout some additional help.
This is where the interface JsonSerializable comes into play.
You need to make sure that the object you want to encode implements the interface. Then you need to add a jsonSerialize() method to the class.
class Branch implements \JsonSerializable
{
protected $id;
protected $name;
protected $type;
// ... your class code
public function jsonSerialize()
{
// Return what you want to be encoded
return [
'id' => $this->id,
'name' => $this->name,
'type' => $this->type,
];
}
}
If you now pass this object through json_encode() and you'll get a json string with what our new method returns.
I am using Amazon MWS Reports PHP Library and Got badly struck when requesting api with following code
$parameters = array (
'Merchant' => MERCHANT_ID,
'MarketplaceWebService_Model_TypeList' => DEFAULT_REPORT_TYPE,
'MarketplaceWebService_Model_StatusList' => array(
'FieldValue' =>'_CANCELLED_' , )
// 'MWSAuthToken' => '<MWS Auth Token>', // Optional
);
$request = new MarketplaceWebService_Model_GetReportRequestListRequest($parameters);
in MarketplaceWebService_Model_GetReportRequestListRequestclass constructor, it is defined as
public function __construct($data = null)
{
$this->fields = array (
'ReportRequestIdList' => array('FieldValue' => null, 'FieldType' => 'MarketplaceWebService_Model_IdList'),
'ReportTypeList' => array('FieldValue' => null, 'FieldType' => 'MarketplaceWebService_Model_StatusList'),
.......
I am unable to understand how should I pass my variable value ? can't understand how 'MarketplaceWebService_Model_IdList' type of variable will be created and passed??
when I use scratchpad for this query, these two arguments are showing in the following way
&ReportRequestIdList.Id.1=49499499399 (DUMMY, INT VALUE)
&ReportTypeList.Type.1=_GET_FLAT_FILE_ORDERS_DATA_
I can't pass any of custom type (Class type variables at all, Unable to understand this)
use the IdList class in Report API to set the format of the id list.
$id_list = new MarketplaceWebService_Model_IdList();
$id_list->setId($x);
I'm trying to reach an element in an object array. But I couldn't succeed.
Let's think this as an object called $result
How can I reach maskedNumber?
Braintree_Result_Successful Object
(
[success] => 1
[_returnObjectName:private] => customer
[customer] => Braintree_Customer Object
(
[_attributes:protected] => Array
(
[creditCards] => Array
(
[0] => Braintree_CreditCard Object
(
[_attributes] => Array
(
[maskedNumber] => ***********5897
Since the _attributes property of Braintree_Customer is protected you will need to define an accessor method. The other _attributes property of Braintree_CreditCard also looks like it's supposed to be protected, so I've assumed an identical accessor should exist:
$cards = $object->customer->getAttribute('creditCards');
$number = $cards[0]->getAttribute('maskedNumber');
Accessor method to be placed in both classes:
function getAttribute($attribute) {
return $this->_attributes[$attribute];
}
Edit:
Just to improve upon my original answer a little, I would put some decent error checking in an actual accessor method.
function getAttribute($attribute) {
if (isset($this->_attributes[$attribute])) {
return $this->_attributes[$attribute];
}
return NULL;
}
You could also consider using the magic methods __get() and __set() to act as getters and setters.
I solved the problem by asking braintreepayments. They said that I could retrieve this data after I add user to braintree. But my solution is if I really needed this at the very beginning would be to take it with REGEX. For people who are looking for a great online payment company I suggest you to go with braintree
I know this is old, but this might help some.
Braintree has methods for returning the protected information that's returned from functions like Braintree_Customer::create();
$result = Braintree_Customer::create(array(
'firstName' => $_POST['first_name'],
'lastName' => $_POST['last_name'],
'email' => $_POST['email'],
'creditCard' => array(
'cardholderName' => $_POST['cardholder_name'],
'number' => $_POST['number'],
'expirationMonth' => $_POST['month'],
'expirationYear' => $_POST['year'],
'cvv' => $_POST['cvv'],
'billingAddress' => array(
'postalCode' => $_POST['postal_code']
)
)
));
var_dump($result->customer->__get('id'));
var_dump($result->customer->__get('creditCards'));
The _attributes of customer are protected, but the get function returns them.
This method does not require re-requesting data from Braintree.
try
$Result->customer->_attributes['creditCards'][0]->_attributes['maskedNumber']
with $result->customer you should get the *Braintree_Customer* Object and then in that object you should have methods to retrieve the cards as those methods are protected and cannot be accessed directly. Something like
$customer = $result->customer;
foreach($customer->getCreditCards() as $card)
{
echo $card->getMaskedNumber(); // You will need to create that method too
}
Example of getCreditCards method:
Class Braintree_Customer
{
protected $creditCards;
function getCreditCards()
{
return $creditCards;
}
...
}