How to analyse a string using the php api - php

How is it possible to use this function using the PHP API. I didn't find a method for that.
curl -XGET 'localhost:9200/_analyze?analyzer=standard' -d 'this is a test'
I need to access it, because I need to have access to the query string calculating my score via script_score. The query string isn't analysed, of course. So I have to do that separately.
I know that's not a good solution, but I didn't find an alternative until now.

It's in the Indices name space:
/**
* $params['index'] = (string) The name of the index to scope the operation
* ['analyzer'] = (string) The name of the analyzer to use
* ['field'] = (string) Use the analyzer configured for this field (instead of passing the analyzer name)
* ['filters'] = (list) A comma-separated list of filters to use for the analysis
* ['prefer_local'] = (boolean) With `true`, specify that a local shard should be used if available, with `false`, use a random shard (default: true)
* ['text'] = (string) The text on which the analysis should be performed (when request body is not used)
* ['tokenizer'] = (string) The name of the tokenizer to use for the analysis
* ['format'] = (enum) Format of the output
* ['body'] = (enum) Format of the output
*
* #param $params array Associative array of parameters
*
* #return array
*/
public function analyze($params = array())
{
$index = $this->extractArgument($params, 'index');
$body = $this->extractArgument($params, 'body');
/** #var callback $endpointBuilder */
$endpointBuilder = $this->dicEndpoints;
/** #var \Elasticsearch\Endpoints\Indices\Analyze $endpoint */
$endpoint = $endpointBuilder('Indices\Analyze');
$endpoint->setIndex($index)
->setBody($body);
$endpoint->setParams($params);
$response = $endpoint->performRequest();
return $response['data'];
}
https://github.com/elasticsearch/elasticsearch-php/blob/master/src/Elasticsearch/Namespaces/IndicesNamespace.php

Related

Validate optional input GET parameters passed in through the querystring as integers in Symfony 3.4

In Symfony 3.4, is there a way to validate optional input GET parameters passed in through the querystring as integers?
If provided, I am using the $ownerId and $courseId to query the corresponding repositories, however the value needs to be an integer otherwise the query falls over.
This is what I have so far and it matches the docs, but it doesn't seem to force any validation or graceful handling of passing through http://www.crmpicco.co.uk/book-teeoff/belleisle/ayrshire/?ownerid=crmpicco&courseId=rfc1872, for example.
/**
* #Route(
* "/book-teeoff/{course}/{area}",
* name = "book_teeoff",
* requirements={"ownerId"="\d+","courseId"="\d+"},
* methods={"GET"}
* )
*
* #param Request $request
*
* #return Response
*/
public function bookTeeoffAction(Request $request): Response
{
// these are *optional*, but if provided need to be integers
$ownerId = $request->get('ownerId');
$courseId = $request->get('courseId');

PHP/Laravel: create JSON with a particular Key name

I am using imagick to get a number of pages and save it to json.
But I store the number as is: for example - 20.
I need to store the number with a key like this:
{
"pages": "20"
}
Here is the code example, that I have. $json - just a path to a created json file. $num - number of pages.
Storage::put(($json), $num);
Should I creat json first, and then somehow add key to a number and encode file?
/**
* Write the contents of a file.
*
* #param string $path
* #param string|resource $contents
* #param mixed $options
* #return bool
* #static
*/
public static function put($path, $contents, $options = array())
{
return \Illuminate\Filesystem\FilesystemAdapter::put($path, $contents, $options);
}
The second parameter to Storage::put is the raw contents you wish to store in the given path. So yes, you have to encode your metadata in your desired format first.
E.g.:
$data = ['pages' => $num];
Storage::put($jsonPath, json_encode($data));

Specify an array index type [duplicate]

This question already has answers here:
Best way to document Array options in PHPDoc?
(9 answers)
Closed 1 year ago.
How can I specify an array index and sub-index type? Note: I will use it with PHPStorm.
Array example:
function name ($options) {
// $options['length'] => integer
// $options['more'] => array
// $options['more']['test1'] => boolean
// $options['more']['test2'] => boolean
}
Example (that not works):
/**
* #param array $options
* #var int $length
* #var array $more
* #var bool $test1
* #var bool $test2
*/
In general, PhpStorm only support simple syntax, just as Sam has stated, e.g.
/**
* #param string[] $options
*/
The code above described parameter which is array of strings.
Install Options completion plugin -- it supports new proposed syntax for hashes (describing array keys and its' types) in PHPDoc: https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#7-describing-hashes
This plugin will add code completion for array keys.
<?php
class Element {
/**
* Initializes this class with the given options.
*
* #param array $options {
* #var bool $required Whether this element is required
* #var string $label The display name for this element
* }
*/
public function __construct(array $options = array())
{
// some code here
}
}
new Element(['label' => 'Bob', '|' ]);
// | Ctrl+Space will show supported attributes
NOTE: Main purpose of this plugin is to offer array keys completion -- I'm not sure how well it supports type resolutions for each of array elements (in case if they are different like in your example).
It looks like, according to the docs, that it's only possible to define an array as a set of one specific type (instead of setting a type for each index):
/**
* #param string[] $options
*/
The better solution would probably be to make $options a class, so length and test1 could be properties with default values and pre-defined types.

Auto-completion for Zend Form Elements

When creating form elements with Zend (using Zend Studio for Eclipse), I'd like some auto completion or hints. Here's what I'm thinking. I'm sure these exist, but I don't know how to get them.
I type createElement and auto-completes gives me the signature createElement($type, $name). Great, I select it.
but when I try to set the $type I don't get any hints like DateTextBox or ValidationTextBox. Being new, I see how this can be useful. What do you do to remember all the options?
for the array of attributes like require, invalidMessage, I'd like to get a list of those to choose from, and/or auto-complete when I start typing one.
// Date field
$date = $this->createElement('DateTextBox', 'date',
array('require' => 'true', 'invalidMessage' => 'Invalid date format')
);
$date->setLabel('date')->setRequired(true);
You have few options to help yourself, without waiting for any plugin:
learn it and remember ;)
extend your phpDoc blocks with all available options:
Example (to be honest I don't know if Eclipse supports html in phpDoc or even any text after variable name in #param, but it works fine in Netbeans):
/**
* [...]
* #param string $type Can be: <ul><li>DateTextBox</li><li>ValidationTextBox</li></ul>
* #param string $name Whatever
* #param array|Zend_Config $options Array with following keys: <ul><li>require</li><li>invalidMessage</li></ul>
* #return Zend_Form_Element
*/
public function createElement($type, $name, $options = null)
extend Zend class and create your own methods to simplify your work
Example:
class My_Zend_Form_Element extends Zend_Form_Element
{
public function createDateTextBox($name, $options = null)
{
return $this->createElement('DateTextBox', $name, $options);
}
}
declare some well named constants and provide some hint in phpDoc
Example: (type ZFE_OPTIONS and IDE should show hint with some constants to use as array keys)
/**
* Can be true or false
*/
define('ZFE_OPTIONS_REQUIRE','require');
create your own helper classes with methods to produce valid options array
Example:
class ZFE_Options
{
protected $opts = array();
/**
* #param bool $req
* #return ZFE_Options
*/
public function setRequired($req){
$this->opts['require'] = (bool)$req;
return $this;
}
/**
* #param string $txt
* #return ZFE_Options
*/
public function setInvalidMessage($txt){
$this->opts['invalidMessage'] = (string)$txt;
return $this;
}
/**
* #return array
*/
public function toArray(){
return $this->opts;
}
}
$zfe_options = new ZFE_Options();
$opts = $zfe_options
->setRequired(true)
->setInvalidMessage('Please provide valid email address')
->toArray();
That's not possible. It's not how autocompletion works. The hints you get are taken directly from ZF's code documentation. Nothing more, nothing less. Everything you see as hints is taken directly from the DocBlock and method signature, e.g.
/**
* Create an element
*
* Acts as a factory for creating elements. Elements created with this
* method will not be attached to the form, but will contain element
* settings as specified in the form object (including plugin loader
* prefix paths, default decorators, etc.).
*
* #param string $type
* #param string $name
* #param array|Zend_Config $options
* #return Zend_Form_Element
*/
public function createElement($type, $name, $options = null)
Eclipse can tell you to insert a string or an array and it will know that the method returns a Zend_Form_Element, but it cannot tell you what these strings should be.
The only place where I know something like what you describe exists is for CSS files. For some reason, when I type in display: it will give me an autocomplete box with possible values for this declaration. If you want more sophisticated autocomplete like this, consider filing this as a feature request to Zend.

How to document an accessor/mutator method in phpDoc/javaDoc?

Given a function which behaves as either a mutator or accessor depending on the arguments passed to it, like this:
// in PHP, you can pass any number of arguments to a function...
function cache($cacheName) {
$arguments = func_get_args();
if (count($arguments) >= 2) { // two arguments passed. MUTATOR.
$value = $arguments[1]; // use the second as the value
$this->cache[$cacheName] = $value; // *change* the stored value
} else { // 1 argument passed, ACCESSOR
return $this->cache[$cacheName]; // *get* the stored value
}
}
cache('foo', 'bar'); // nothing returned
cache('foo') // 'bar' returned
How do you document this in PHPDoc or a similar automated documentation creator? I had originally just written it like this:
/**
* Blah blah blah, you can use this as both a mutator and an accessor:
* As an accessor:
* #param $cacheName name of the variable to GET
* #return string the value...
*
* As a mutator:
* #param $cacheName name of the variable to SET
* #param $value the value to set
* #return void
*/
However, when this is run through phpDoc, it complains because there are 2 return tags, and the first #param $cacheName description is overwritten by the second.
Is there a way around this?
as you found out, you cannot document 2 different signatures of a single function. what you can do, however - if you use phpDocumentor -, is to document optional function parameters and multiple possible return types:
/**
* Blah blah blah, you can use this as both an accessor and a mutator, e.g.
* <code>cache('name') // get cache value</code>
* and
* <code>cache('name', 'value') // set new cache value</code>.
*
* #param string $cacheName name of the variable to GET|SET
* #param string $value optional new value
*
* #return string|void value of $cacheName or, in case of mutator, void
*/
for clarity, i would also include the usage example.

Categories