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

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

Related

I hit this error while integrating klaviyo with laravel

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, [])

Laravel show data from database and convert to json

i'm trying show data from database on laravel, but don't show anything in view blade. Every group hasMany lapangan(eng: court) data
$groups_resource = Groups::all();
$groups = [];
foreach($groups_resource as $group)
{
$g = new Groups();
$g->id_group = "Group_".$group['id_group'];
$g->name = $group['nama'];
$g->expanded = true;
$g->eventHeight = 25;
$g->children = array();
$groups[] = $g;
$lapangan_resource = Lapangan::with('groups')->orderBy('nama')->get();
foreach($lapangan_resource as $lapangan)
{
$l = new Lapangan();
$l->id_lapangan = $lapangan['id_lapangan'];
$l->name = $lapangan['nama_lapangan'];
$g->children[] = $l;
}
}
return json_encode($groups);
output
[{"id_group":"Group_1","name":"Lapangan Badminton","expanded":true,"eventHeight":25,"children":[]},{"id_group":"Group_2","name":"Lapangan Tenis","expanded":true,"eventHeight":25,"children":[]}]
There is no children output for every id_group
.what i want
{"id":"group_1","name":"Indoor","expanded":true,"eventHeight":25,"children":[
{"id":"1","name":"Court 1"},
{"id":"2","name":"Court 2"},
{"id":"3","name":"Court 3"},
{"id":"4","name":"Court 4"}]},
{"id":"group_2","name":"Outdoor","expanded":true,"eventHeight":25,"children":[
{"id":"11","name":"Court 5"},
{"id":"12","name":"Court 6"},
{"id":"13","name":"Court 7"},
{"id":"14","name":"Court 8"}]}
]
Any idea?
If you want to return a response in JSON format than you can use json() method as:
return response()->json($datagrup);
OR
To convert a model to JSON, you should use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON:
$user = App\User::find(1);
return $user->toJson();
Even though, you code seems to really fixed... I still feel the below code should work for you :)
I am not sure what exactly you mean by $datagroup[] = $dataresource? Do you want to add datagroup to dataresource or dataresource to datagroup... Your code shows something and the output desired is something else.
$datagroup = array_map(function($groups) use ($scheduler_resources) {
return [
'id' => $group['id_group'],
'name' => $group['nama'],
'expanded' => true,
'children' => $scheduler_resources->map(function($resource) {
return [
'id' => $resource->id_lapangan,
'name' => $resource->nama_lapangan,
];
}),
'eventHeight' => 25
];
}, $scheduler_groups);
echo json_encode($datagroup);
// or
// return response()->json($datagroup);
Note :- Please ensure $scheduler_resources is different for each $datagroup

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

Auto-increment in MongoDB with CodeIgniter Alex Bilbie library

First of all, sorry for my english and I'm beginning to study MongoDB. :)
I'm trying to insert a record using the CI library to MongoDB (https://github.com/alexbilbie/codeigniter-mongodb-library/tree/v2).
The insert works perfectly, but I can't insert using the recommended function to auto-increment getNextSequence (http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/).
I tried the following ways without success.
Controller:
$data = array('_id' => 'getNextSequence("myid")',
'name' => 'Test '.time(),
'email' => 'test#test.com');
$this->default_model->add($this->collection, $data);
Model:
function add($collection, $data){
return $this->mongo_db->insert($collection, $data);
}
This returns the string 'getNextSequence("relatoriosid")' as the "_id".
I also tried used the command function, like this:
Controller:
$query = 'db.collection.insert({_id: getNextSequence("myid"), name: "Test '.time().'"});';
$ret = $this->default_model->execute($query);
var_dump($ret);
Model:
function execute($query){
return $this->mongo_db->command($query);
}
This way, returns the error:
["errmsg"]=> string(136) "exception: JavaScript execution failed: ReferenceError: getNextSequence is not defined near 'quence("myid"), name: "Teste 1374' "
["code"]=> int(16722)
["ok"]=> float(0)
Has anyone implemented something similar?
Thanks in advance!
I have implemented once mongoDB in one of my project.
I had faced similar problem. But one important thing i remember that we can not modify _id. Its MongoDB inbuilt properly. Neither its good to have the auto-increament in MongoDB because you need to implement that manually.
I will recommend that have another column in structure, you can call it anything, which will be virtual unique/primary key for you, lets say that column name is data_id.
$data = array('data_id' => md5(timestamp() . "<your string>"),
'name' => 'Test '.time(),
'email' => 'test#test.com');
if we check the documentation, is specified that Generally in MongoDB, you would not use an auto-increment pattern for the _id field, or any field, because it does not scale for databases with large numbers of documents. Typically the default value ObjectId is more ideal for the _id. Here i am referring to this link.
Even on the same link, its specified that getNextSequence() we need to write it. Its not inbuilt function.
Hope this helps you.
I got that problem too here is my solution.
Add this function to appflow\application\libraries
public function getNextSequence($name = ""){
if (empty($name))
{
show_error("In order to retrieve documents from MongoDB, a collection name must be passed", 500);
}
try{
$collection_1 = 'counters';
$collection = $this->db->{$collection_1};
$result = $collection->findAndModify(
['_id' => $name],
['$inc' => ['seq' => 1]],
['seq' => true],
['new' => true, 'upsert' => true]
);
if (isset($result['seq']))
{
return $result['seq'];
}
else
{
return false;
}
}
catch (MongoCursorException $e)
{
if(isset($this->debug) == TRUE && $this->debug == TRUE)
{
show_error("MongoDB query failed: {$e->getMessage()}", 500);
}
else
{
show_error("MongoDB query failed.", 500);
}
}
}
This is the way to use.
$nextID = $this->mongo_db->getNextSequence("maindata_child");
$this->mongo_db->where(array('_id'=>$mongo_id))->push('maindata_child', array('id'=>$nextID,'data'=>$maindata_child))->update('main_data');
and don't forget to add collection "counters".
db.counters.insert(
{
_id: "userid",
seq: 0
}
)
PS. I'm use this library https://github.com/bcit-ci/CodeIgniter/wiki/Using-MongoDB-in-Codeigniter
Reference for solution : http://tbsmc.com/a/mwbwswmm-mongodb-how-to-insert-record-using-autoincrement-functionality.html

Categories