Getting data as array instead of stdClass in zf-rest - php

I'm using zf-rest for building my RESTful web apps. I have the following configurations:
'zf-rest' => [
Resource\FeedbackResource::class => [
'listener' => Resource\FeedbackResource::class,
'route_name' => 'api/rest/feedback',
'entity_http_methods' => [
],
'collection_http_methods' => [
'POST',
],
],
],
'zf-content-validation' => [
Resource\FeedbackResource::class => [
'use_raw_data' => false,
'allows_only_fields_in_filter' => true,
'POST' => Resource\FeedbackResource::class . '\\Validator',
],
],
'input_filter_specs' => [
Resource\FeedbackResource::class . '\\Validator' => [
Resource\FeedbackResource::PARAM_NAME => $inputFilterSpecForStrings,
Resource\FeedbackResource::PARAM_EMAIL => $inputFilterSpecForStrings,
],
],
Then I created the resource with the corresponding method:
class FeedbackResource extends AbstractResourceListener
{
public function create($data)
{
// do something
}
}
I posted a json string to the endpoint and everything works fine so far. But what I'm wondering about is that I will get $data as an object with the json data as attributes. I expected to get an assoziative array. Is this possible?

Related

Api/v1 does not exist in config when running php artisan serve

I would like to build an API that does a GET request to a third party API. I created a controller that houses this logic and registered this as an HTTP end point using the JsonApiRoute::server() facade. I am absolutely new to Laravel and PHP.
However when I run php artisan serve I get the error:
Server /api/v1 does not exist in config or is not a valid class.
This is my code in routes:
JsonApiRoute::server('/api/v1')
->prefix('/api/v1')
->resources(function ($server) {
$server->resource('retrieve');
});
This is the code I have in config-> json-api-default:
return [
'resolver' => \CloudCreativity\LaravelJsonApi\Resolver\ResolverFactory::class,
'namespace' => null,
'by-resource' => true,
'model-namespace' => null,
'resources' => [
'posts' => \App\Post::class,
],
'use-eloquent' => true,
'url' => [
'host' => null,
'namespace' => '/api/v1',
'name' => 'api:v1:',
],
'controllers' => [
'transactions' => true,
'connection' => null,
],
'jobs' => [
'resource' => 'queue-jobs',
'model' => \CloudCreativity\LaravelJsonApi\Queue\ClientJob::class,
],
'encoding' => [
'application/vnd.api+json',
],
'decoding' => [
'application/vnd.api+json',
],
'providers' => [],
];
and in my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class retrieve extends Controller
{
//
public function retrieveData(Request $request){
$response = Http::withHeaders([
'api-key' => '***',
])->get('https://data.mongodb-api.com/app/data-pkrpq/endpoint/getRandom');
return response()->json(['status'=> true,'data'=> json_decode($response->body()), 'Message'=>'Successfully retrieved'], 200);
}
}

Types cannot be provided in put mapping requests, unless the include_type_name parameter is set to true in lumen with elastic search 7.6.2

I am using https://github.com/basemkhirat/elasticsearch package.
In es.php file i have below indices
'indices' => [
'media' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 2,
'analysis' => [
'filter' => [
'custom_english_stemmer' => [
'type' => "stemmer",
'name' => "english"
],
"english_stop" => [
'type' => "stop",
'stopwords' => "_english_"
]
],
"analyzer" => [
'custom_lowercase_analyzer' => [
// 'type' => 'custom',
'tokenizer' => 'standard',
'filter' => [
'lowercase',
'english_stop',
"custom_english_stemmer"
]
]
]
]
],
'mappings' => [
'properties' => [
'id' => [
'type' => 'long',
'index' => false,
'doc_values' => false,
],
'title' => [
'type' => 'text',
"analyzer" => 'custom_lowercase_analyzer'
]
]
]
]
]
Now when php artisan es:indices:create is executed settings is created but mapping fails with an error message.
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Types cannot be provided in put mapping requests, unless the include_type_name parameter is set to true."
}
],
"type": "illegal_argument_exception",
"reason": "Types cannot be provided in put mapping requests, unless the include_type_name parameter is set to true."
},
"status": 400
}
How to fix this issue
You are providing type in your create index code, remove media type from your index, as types are deprecated, see the removal of types for more information.
Please note in Elasticsearch 7.X still you can do some workaround to have custom types by having include_type_name param but it's not preferred as types will be totally removed in upcoming Elasticsearch 8.X.
In order to use create your index with custom type like media(default is _doc mentioned in your screen-shot) in your case, you need to pass include_type_name=true to index creation, template, and mappings APIs as mentioned in this official ES blog

PHP Api Object Query

I'm having a bit of an issue with an API document I'm currently working with. The code I've been testing just doesn't seem to work, and I've been looking at it for that long now, I just cannot see where I'm going wrong.
API Documentation Screenshot here: https://ibb.co/CW4HRR9
// POST /package/{id}/web/ftpusers
$args = [
'update' => [
'ftp' => [
'id' => '12345',
'user' => ['Password' => 'Password123']
],
],
];
$response = $services_api->postWithFields("/package/".$test_domain_id."/web/ftpusers", $args);
echo '<pre>';
print_r($response);
echo '</pre>';
It just doesn't seem to work, and I'm guessing I'm doing something wrong where it states object and object[]
Looks like I was missing an array object as I've now got this working (extra array within 'ftp'
$args = [
'update'=> [
'ftp' => [
[
'id' => $info[0]->Id,
'user' => [
'Enabled' => true,
'Password' => 'Password123'
],
]
],
],
];

Elasticsearch in lumen giving empty Items in Resulted Data

I am working with Elasticsearch in lumen for simple search.
I followed Elastic search installation tutorial from : https://medium.com/#basemkhirat_88244/laravel-lumen-flexible-elasticsearch-query-builder-inspired-from-eloquent-bb5221c65af8
And In my controller.php
public function search() {
$users = \Basemkhirat\Elasticsearch\Facades\ES::index('user_index')->type("text")->body([
"query" => [
"bool" => [
"must" => [
[ "match" => [ "name" => "Leena Patel" ] ],
]
]
]
])->get();
dd($users);
}
And in my routes.php file
$app->get('/search', 'Controller#search');
My es.php configuration file :
return [
'default' => env('ELASTIC_CONNECTION', 'default'),
'connections' => [
'default' => [
'servers' => [
[
"host" => env("ELASTIC_HOST", "127.0.0.1"),
"port" => env("ELASTIC_PORT", 9200),
'user' => env('ELASTIC_USER', ''),
'pass' => env('ELASTIC_PASS', ''),
'scheme' => env('ELASTIC_SCHEME', 'http'),
]
],
'index' => env('ELASTIC_INDEX', 'user_index'),
// Elasticsearch handlers
// 'handler' => new MyCustomHandler(),
]
],
'indices' => [
'user_index' => [
"aliases" => [
"user_index_alias"
],
'settings' => [
"number_of_shards" => 1,
"number_of_replicas" => 0,
],
'mappings' => [
'users_schema' => [
"properties" => [
'name' => [
'type' => 'text'
]
]
]
]
]
]
];
When running /search link in browser it shows result array like
Basemkhirat\Elasticsearch\Collection Object
(
[items:protected] => Array
(
)
[total] => 0
[max_score] =>
[took] => 1
[timed_out] =>
[scroll_id] =>
[shards] => stdClass Object
(
[total] => 1
[successful] => 1
[skipped] => 0
[failed] => 0
)
)
My Question is Why My Items array is empty even though there is data with name = Leena Patel ?
Please help! I am learning ElasticSearch!
Edit :
My Database table users that contains column name with data Leena Patel SO i want this record in my items result
Please use below link for elastic search
https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/
then follow below steps for lumen
1) Move config directory to root alongside with app folder
vendor\elasticquent\elasticquent\src\config
2) Remove comment from `$app->withEloquent();` in bootstrap\app.php of lumen folder
3) Register elasticquent in app.php file of lumen folder as below
$app->configure('elasticquent');
4) Run command in your lumen folder
composer dump-autoload
After these steps you need to set route in web.php of lumen folder
for i.e.
use App\Article; // Use at top of web.php
$router->get('article', function() {
Article::createIndex($shards = null, $replicas = null); // Using this code create command
Article::reindex(); // Reindex article indices
$articles = Article::searchByQuery(['match' => ['title' => 'Android']]);
return $articles;
});

Zend Framework collection validation

I am using Zend Framework 3 and I'm trying to validate a form with a collection field.
My form has a field
$this->add([
'name' => 'domains',
'options' => [
'target_element' => [
'type' => Text::class
]
],
'type' => Collection::class
]);
When I submit the form I obtain something like this as POST data
[
'domains' => [
0 => 'first'
1 => 'second'
]
]
I am trying to validate this with a CollectionInputFilter like the following
$filter = new InputFilter();
$filter->add([
'type' => CollectionInputFilter::class,
'options' => [
'input_filter' => [
'validators' => [
[
'name' => Hostname::class
]
]
]
]
], 'domains');
$filter->setData($data);
but I obtain the exception Zend\InputFilter\CollectionInputFilter::setData expects each item in a collection to be an array or Traversable; invalid item in collection of type string detected.
What am I doing wrong?
I found out that the error was in using CollectionInputFilter. I should have been using ArrayInput instead.

Categories