PHP/Laravel: create JSON with a particular Key name - php

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

Related

Extract creation date, last modified date and method name with regex from a string

Below a portion of code stored into a file named
Website.php
<?php
namespace AdamInChains;
class Website
{
/**
* 02.14.2019 13:24:59 creation date
* 02.14.2019 13:28:23 last modified date
* #param array $meta_tags
*
* #return string
*/
public function index(array $meta_tags) : string{}
/**
* 02.14.2019 13:45:59 creation date
* 02.14.2019 13:49:21 last modified date
* #param array $meta_tags
*
* #return string
*/
public function about(array $meta_tags) : string{}
/**
* 02.14.2019 14:01:52 creation date
* 02.14.2019 14:33:01 last modified date
* #param array $meta_tags
*
* #return string
*/
public function contact(array $meta_tags) : string{}
}
I need to extract creation date and last modified date
and then store the regex results into one array this way
$array = [
// method name
"index" => [
"creation_date"=>"02.14.2019 14:01:52",
"last_modified_date"=>"02.14.2019 13:28:23"
]
];
Basically when the user, in this case AdamInChains and you can see this from the namespace declaration, creates a new page on his Website, one new method, declared as the input page name, is added to the class and the dates are added to the doc comment for the method.
until now I'm able to extract just the methods names (see code below), but no success with the other tasks.
// regex pattern
$re = '/public function.(\w{0,})/m';
// file 'Website.php'
$str = file_get_contents('Website.php');
preg_match_all($re, $str, $matches);
// Print the entire match result
var_dump($matches);
This is the var_dump results and I'm happy with it
Anyone?
Here is a regex you can use for that:
(?<creationDate>\d{2}\.\d{2}\.\d{4}\s\d{2}:\d{2}:\d{2})\screation\sdate[^\Z]*?(?<modifiedDate>\d{2}\.\d{2}\.\d{4}\s\d{2}:\d{2}:\d{2})\slast\smodified\sdate[^\Z]*?public\sfunction\s(?<methodName>[^\(\s]+)
https://regex101.com/r/7wrrhj/1

How to analyse a string using the php api

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

How to doc a variable number of parameters

How do I doc a variable number of parameters? I am writing an application in PHP and JavaScript. Currently I have (in JavaScript):
/**
* Description
* #param {String} description
*/
function fn()
{
// arguments holds all strings.
}
So, how do I doc n-number of string params?
E.g. PhpDocumentor suggests using an ellipsis
/**
* Example of unlimited parameters.
* Returns a formatted var_dump for debugging purposes
* (since the recurrences of $v are not listed in the actual function signature in the code,
* you may wish to highlight they are "optional" in their description)
* #param string $s string to display
* #param mixed $v variable to display with var_dump()
* #param mixed $v,... unlimited OPTIONAL number of additional variables to display with var_dump()
*/
function fancy_debug($s,$v)
{

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.

What are the options for Doctrine's addColumn() migration method?

The API gives the code as:
public function up()
{
$this->addColumn('table_name', 'column_name', 'string', $options);
}
but there's no documentation for what can be included in the options array.
http://www.doctrine-project.org/Doctrine_Migration_Base/1_2#method_addcolumn
For people coming in: it looks like this is really defined from the Data Access Layer. Here is the list of options for columns from the DBAL docs: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/schema-representation.html
The documentation is wrong. Looking in Doctrine/Migration/base.php, you can see the following function prototype:
/**
* Add a add column change.
*
* #param string $tableName Name of the table
* #param string $columnName Name of the column
* #param string $type Type of the column
* #param string $length Length of the column
* #param array $options Array of options for the column
* #return void
*/
public function addColumn($tableName, $columnName, $type, $length = null, array $options = array())
So to add the length, you give it as the 4th parameter. I'm ignoring the options for the moment.
Following the "browse code" link on the top, you can follow the code to $options['length'] in Doctrine_Migration_Base::column() and the second parameter in Doctrine_Migration_Base::_addChange(). Check out the source code from time to time, it gives you an overview :)

Categories