I hit this error while integrating klaviyo with laravel - php

I'm using this package As SDK. So basically what I'm trying to achieve is to add the users to a list but with the consent status or email and SMS, What I found from one answer from my own question is this code. So I tried it but then it hit another error.
TypeError
Cannot access offset of type string on string
Code from #Ohgodwhy's answer.
public function chnages()
{
$client = new Klaviyo('Your_Private_apikey', 'Public_Api_key');
$customer_properties = [
'$email' => "someone#mailinator9.com",
'$first_name' => "Thomas9",
'$last_name' => "Jefferson",
'phone_number' => "1234567890"
];
$consents = [];
if (request()->get('sms_consent', false)) {
$consents['sms_consent'] = true;
}
if (request()->get('email_consent', false)) {
$consents['email_consent'] = true;
}
foreach ($consents as $type => $consented) {
if ($consented) {
$consents['$consent'] = array_merge(
data_get($consents, '$consent', []),
[explode('_', $type)[0]] //e.g. sms, email
);
}
}
$client->lists->addSubscribersToList('LIST_ID', array_merge($customer_properties, $consents));
}

$consents['$consent'] this is not going to work, array values can be either a variable OR a string but not a variable inside a string. Also, you don’t have $consent in your foreach, to check the $consents key value you need to do $consents[$type]
The same thing counts for data_get($consents, '$consent', []) which need to be data_get($consents, $consented, [])

Related

Why getPostParameters doesn't work on symfony 1.4?

I have a form in symfony 1.4 which are created for each competence. My forms was created with success. But when I try to save my form I can't. I go to see my action code and the function getPostParameters seem dosn't work. I use getParameterHolder to see what's wrong in my parameters but after I put the good value the getPostParameters function doesn't work.
This is what I get from getParameterHolder:
sfParameterHolder Object
([parameters:protected] => Array
(
[professionnal_competence] => Array
(
[rayon_competence3] => 24
[rayon_competence9] => 22
[rayon_competence19] => 32
)
[module] => professionnal_subregion
[action] => saveCompetenceRadius
)
)
And my function:
public function executeSaveCompetenceRadius(sfWebRequest $request) {
$user = $this->getUser()->getGuardUser();
$q = ProfessionnalCompetenceQuery::create()
->addSelect('pc.*')
->where('pc.professionnal_id= ?', $user->getId());
$res = $q->execute();
$values = $request->getPostParameters(['professionnal_competence']);
$test = $request->getParameterHolder();
var_dump($values); print_r($values); print_r($request->getParameterHolder());
exit;
foreach ($res as $professionnalCompetence) {
foreach ($values['professionnal_competence'] as $k => $val) {
if ($k == 'rayon_competence' . $professionnalCompetence->getCompetenceId()) {
$professionnalCompetence->setRayonCompetence($val);
$professionnalCompetence->save();
}
}
}
return $this->renderComponent('professionnal_subregion', 'competenceRadius');
// return "test";
//return $this->renderPartial('professionnal_subregion/competenceradius');
}
This is my form:
class ProfessionnalCompetenceRadiusForm extends BaseProfessionnalCompetenceForm {
public function configure()
{
unset($this['rayon_competence']);
$this->widgetSchema['rayon_competence'.$this->object->getCompetenceId()] = new sfWidgetFormSelectUISlider(array('max'=>50,'step'=>1));
$this->widgetSchema->setHelp('rayon_competence'.$this->object->getCompetenceId(),'en kilomètres');
$this->widgetSchema->setLabel('rayon_competence'.$this->object->getCompetenceId(),'rayon');
$this->setValidator('rayon_competence'.$this->object->getCompetenceId(), new sfValidatorInteger(array('max'=>50)));
}
}
Someone has an idea or can help me ?? Because I try lot of thing but without success. Thank in advance :).
I think the error hides in this line:
$values = $request->getPostParameters(['professionnal_competence']);
You're passing an array to a function that takes a string. Try removing the brackets around 'professionnal_competence'.
EDIT: Scratch that. getPostParameters takes no parameters. getPostParameter, on the other hand, takes two - the first of which is the field name - a string. So, your code should be:
$values = $request->getPostParameter('professionnal_competence');
The error is here:
$values = $request->getPostParameters(['professionnal_competence']);
The function sfWebRequest::getPostParameters doesn't actually take parameters.
You can either access this array with [...], or use getPostParameter, which allows "safe" deep access:
$val = $request->getPostParameter('a[b]');
// basically the same as, but with error checks:
$val = $request->getPostParameters()['a']['b'];

Phalcon PhP - is there an EOF for model::find

I'm writing a piece of code and in it I would like to know if the result of a find if empty or not. Here is my piece of code:
public function signatureAction()
{
$info = $this->session->get('current_quote');
$object_list = ApplicationSignatureFile::find(array('conditions' => 'application_id = ?1 AND quote_id = ?2',
'bind' => [
1 => $info['application_id'],
2 => $info['quote_id'],
]));
$this->view->setVar('object_list', $object_list);
if ($object_list) {
$this->view->setVar('has_files',true);
} else {
$this->view->setVar('has_files',false);
}
}
What I don't know yet if how to check if $object_list is EOF so I can set the has_files variable better. Currently it is not working. How can I do that in a controller and in a .volt view?
This is pretty strange actually. Using findFirst or any other ORM method returns false on fail, however using find does not.
A simple workaround in your case would be to use the count method on the result set:
$test = \Models\Objects::find([
'conditions' => 'is_active = 42'
]);
if ($test->count()) {
print('I have records with is_active = 42');
d($test->toArray());
} else {
print('I do not have any records with is_active = 42');
}

How to create data and return properly formatted json using ApiGility and RPC

I am using the RPC service of ApiGilty to return some data. I would like to double check whether or not this is the correct way of formatting and returning the data as I am not 100% sure of the correct process.
EDIT: To clarify
The data is being built from a number of entities:
main
main_extra
main_data
main_data_days
main_data_tiers
Is there a way to hit main and get all the sub entities? Currently I am building my data from scratch and returning an array.
My RPC Controller is as follows:
use My\Data\Controller\DataInterface;
use Zend\Mvc\Controller\AbstractActionController;
use ZF\ContentNegotiation\ViewModel;
class MyDataController extends AbstractActionController
{
const GENERAL_ERROR = 'api.rpc.my-data.my-data-controller';
public function __construct(
MyDataInterface $myData
)
{
$this->myData = $myData;
}
public function myDataAction()
{
$my_id = (int) $this->params()->fromRoute('my_id', 0);
if ($my_id == 0)
{
$data = $this->myData->getMyData();
} else
{
$data = $this->myData->getMyData($my_id);
}
$result = new ViewModel(array(
'data' => $data
));
return $result;
}
}
Now to create the data I am doing something like this:
public function getMyData( $my_id = null )
{
$returnArray = [];
$array1 = [
'key_1' => [1,2,3,4],
'key_2' => '123',
'key_3' => ['a','b','c']
];
$array2 = [
'key_1' => [1,2,3,4,5,6,7,8],
'key_2' => '123456',
'key_3' => ['a','b','c','d']
];
if ($my_id == 1) {
$array3 = ['some','or','other'];
} else {$array3 = []; }
$final_array = [
'data1' => $array1,
'data2' => $array2,
'data3' => $array3
];
$returnArray['data'] = $final_array;
$returnArray['success'] = 'true';
$returnArray['reason'] = '';
return $returnArray;
}
When checking with postman, I get the following:
Now since I have nothing to reference this against, my question is simply. Have I gone about this in the correct way and is this how the return code should be formatted?
Thanks!
Right now the Hal plugin is not used to render your result? You are responding a custom json object. Is this really what you want?
The response you currently return is not formatted according to HAL specifications. A proper HAL response should hold at least a _links key with a self href. It would be wrong to return this result with Content-Type headers set to application/hal+json. You should use application/json instead.
Here you can find documentation on how to respond HAL from an RPC-contoller.
I am not sure what you want to achieve but maybe you can be a bit more specific in your question so others can help out...
Doesn't look too bad, perhaps adhere to a standard such as jsend http://labs.omniti.com/labs/jsend or you could use hal-json, matthew weier o'phinney has a good blog post on this https://mwop.net/blog/2014-03-26-apigility-rpc-with-hal.html
Also you don't need to return a view model as you can just return an array and apigility will return JSON. You could also write a jsendViewModel if you go down that route.
Not exactly an answer but hope this helps you!

undefined variable when testing the store() using phpunit in laravel-4

SOLVED
I have route that does a POST route towards store() in the controller.
I'm trying to test if the action is working properly.
Controller:
public function store() {
$d= Input::json()->all();
//May need to check here if authorized
$foo= new Foo;
$d = array();
$d['name'] = $d['name'];
$d['address'] = $d['address'];
$d['nickname'] = $d['nickname'];
if($foo->validate($d))
{
$new_foo= $foo->create($d);
return Response::json(Foo::where('id','=',$new_foo->id)->first(),200);
}
else
{
return Response::json($foo->errors(),400);
}
}
Now I'm trying to test this using a new class called FooTest.php
Here is the function i'm currently trying to do to make the check work:
public function testFooCreation()
{
$jsonString = '{"address": "82828282", "email": "test#gmail.com", "name":"Tester"}';
$json = json_decode($jsonString);
$this->client->request('POST', 'foo');
$this->assertEquals($json, $this->client->getResponse());
}
when I run phpunit in my cmd, I get an error stating that "name" is undefined. I know i'm not actually passing anything to the request so I'm positive that nothing is actually being checked, but my question is how do I actually pass my json strings to check?
Everytime I put the $json inside the client request, it asks for an array, but when I convert my json string to an array, json_decode wants a string.
UPDATE
I was messing around with the passing of input data and I came across this:
$input = [
'name' => 'TESTNAME',
'address' => '299 TESTville',
'nickname' => 't'
];
Input::replace($input);
Auth::shouldReceive('attempt')
->with(array('name' => Input::get('name'),
'address' => Input::get('address'),
'nickname' => Input::get('nickname')))
->once()
->andReturn(true);
$response = $this->call('POST', 'foo', $input);
$content = $response->getContent();
$data = json_decode($response->getContent());
But whenever I run the test, i still get "name:undefined" It's still not passing the input i've created.
$d= Input::json()->all();
The above statement gets Input in $d.
$d = array();
Now the last statement again initialises $d as an empty new array.
So there is no: $['name'] . Hence, Undefined.
I think, that's the problem with the above code.
Hope it helps :)
I was able to pass the input into a POST route from the test.
public function testFooCreation(){
$json = '{"name":"Bar", "address":"FooLand", "nickname":"foobar"}';
$post = $this->action('POST', 'FooController#store', null, array(), array(), array(), $json);
if($this->assertTrue($this->client->getResponse()->isOk()) == true && $this->assertResponseStatus(201)){
echo "Test passed";
}
}
Turns out that in order for me to actually pass input into the controller through test POST, I have to pass it through the 7th parameter.
I hope this helps others.
of course you get an error , just look at your code
$aInputs = Input::json()->all();
//May need to check here if authorized
$foo= new Foo;
$d = array();
$d['name'] = $d['name'];
$d['address'] = $d['address'];
$d['nickname'] = $d['nickname'];
your assigning the array to it self, which is empty

PHP using an array in a Validation Class

On my site I have my register page, where a user inputs his information to register to my site.
When he does the I process the user inputted information. Now when processing it I'm using arrays to facilitate the process, and not have me write the same code over and over. For example, here is how I gather the user information and check it using a method in my validation class.
$data = array(
$_POST['firstname'] => "First Name",
$_POST['lastname'] => "Last Name"
);
foreach($data as $userInput => $fieldName) {
$validation = new Validation();
$result = $validation->checkEmpty($userInput, $fieldName);
}
Now this all works for me on my page, I'm able to check to see if the user left something empty on the register with the method "checkEmpty", which also returns an array of the fields left empty. I didn't show the method because it's not part of my problem. Now, here's my question, I want to also check the length of the fields. What would be a good way for me to do this without rewriting things over and over? Would I have to do another array?
I'm thinking something like this, maybe?
$data2 = array(
$_POST['firstname'] => 30,
$_POST['lastname'] => 35
),
foreach($data as $userInput => $limit) {
$result = $validation->checkLength($userInput, $limit);
}
But where I get stumped is, if one the inputted fields is too long, how do return which one it was if in the array I passed through I don't have the field name to which it belongs? I thought of a multi-dimensional array, but I'm not sure if that will work.
I would structure the the array completely differently, something like:
$config = array(
'firstname' => array('notEmpty' = true,
'limit' => 30),
'lastname' => array('notEmpty' = true,
'limit' => 35)
);
Then I would create a method validate that looks like this:
public function validate($config, $data) {
$error = array();
foreach($data as $field => $value) {
$c = $config[$field];
if(array_key_exists('notEmpty', $c)) {
if(!$this->checkEmpty($value)) {
$this->addError($error, $field, 'Must not be empty');
}
}
if(array_key_exists('limit', $c)) {
if(!$this->checkLength($value, $c['limit'])) {
$this->addError($error, $field, 'Must not be longer than' . $c['limit'] . ' characters');
}
}
/*...*/
}
return $error;
}
private function addError(&$error, $field, $msg) {
if(!array_key_exists($field, $error)) {
$error[$field] = array();
}
$error[$field][] = $msg;
}
Then you just call:
$validation = new Validation();
$errors = $validation->validate($config, $_POST);
and $errors will contain all error messages per field. You just need to to loop over them and print them next to the field.
Of course this code can (and should be!) improved. E.g. dynamic lookup of validation methods).
That said, I highly recommend to have a look at and use a ready made validation classes such as Zend_Validate
I would think using the field names as keys for your array may be a better approach. Then yeah, use a multi-dimensional array something like this.
$data = array(
'First Name' => array($_POST['firstname'], 30),
'Last Name' => array($_POST['lastname'], 35)
)
You gloss over the validation class, but I think its important. For one it should be used statically if it doesn't have any state. Theres no reason to be constructing it every single loop iteration like that!
Validation::checkEmpty($x);
AS for the length checking, id suggest you keep fields in Validation something like
protected $lengths = array( 'firstname' => 35, 'lastname' => 30, 'default' => 100);
and call it with
Validation::checkLength($userInput, $fieldName);
with a body like
protected static function checkLength($subject, $fieldType = 'default')
{
return strlen($subject) < self::$lengthTypes($fieldType);
//or self::$fields['lengthLimit'] if you are going to structure it like Felix suggest
}
You don't need me to tell you that a function lengthChecker($subject, $limit) is pretty pointless.
EDIT - restructuring like Felix suggested isn't a bad idea depending on how far you want tot ake this. His looks more extensible. If you are going to implement the addError you probably don't want the static design.

Categories