A way to calculate DateTime intersection where NULL is possible - php

Background
I'm integrating Limesurvey with an application, where new survey tokens are added directly to the Limesurvey database. Before insertion can be done, I need to check that a given set of tokens (with validfrom and validuntil attributes) in Limesurvey does not intersect with a given range of dates (DateTime).
The problem
Since Limesurveys token validfrom and validuntil attributes can be NULL, a simple comparison of DateTime can't be done, or can it?
(A Limesurvey validfrom/validuntil NULL value implies "always")
What I have
A php class that checks if the Limesurvey attributes are NULL (or not), and returning a calculation of the intersection as needed.
Code: http://phpfiddle.org/main/code/3vp-j3b
(It's what's inside the foreach loop, lines 34-70, that are interesting here)
What I ask
Is there a way to improve/optimise this method, given that the comparison values are special?

You could replace null with a possible first and last date to ease comparing:
if (is_null($token['validfrom']) {
$token_validfrom = new DateTime('0000-01-01 00:00:00');
} else {
$token_validfrom = new DateTime($token['validfrom']);
}
if (is_null($token['validuntil']) {
$token_validuntil = new DateTime('9999-12-31 23:23:59');
} else {
$token_validuntil = new DateTime($token['validuntil']);
}
This way only your last line of comparison should be necessary:
return ($validfrom == $token_validfrom) || ($validfrom > $token_validfrom ? $validfrom < $token_validuntil : $token_validfrom < $validuntil);

Related

Wrong timestamp inserted when I call the update method on controller from another laravel app

I'm calling an update method from a laravel app unfortunately a wrong updated_at is inserted with one hour delta despite the timezone is the same on each sides
You can see the difference here between the result of a dump of the source datetime and the query on the other side, there is a difference of one hour :
Here is the code I use in order to call the remote controller:
$updatedIntranet = new DateTime($stagesIntranet[$key]->updated_at);
$stageSiteValueIndex = array_keys($stagesSiteIds,$id);
echo('id : '. $id);
$updatedsite = new DateTime($stagesSite[$stageSiteValueIndex[0]]->updated_at);
$diffTimestamps = $updatedIntranet->getTimestamp() - $updatedsite->getTimestamp();
echo '------- updated intranet ---------<br />';
dump($stageIntranet->updated_at);
echo '-------- updated site --------<br />';
dump($stagesSite[$stageSiteValueIndex[0]]->updated_at);
echo '--------diff--------<br />';
// site must be updated
if( $diffTimestamps != 0)
{
dump('delta : '.$diffTimestamps);
$countUpdated++;
$stageIntranet->id = $stageIntranet->id_stages;
unset($stageIntranet->id_stages);
$stageIntranetCleanUTF8 = $this->utf8ize($stageIntranet->toArray());
$stageIntranetJson = json_encode($stageIntranetCleanUTF8,JSON_UNESCAPED_UNICODE);
$updateResponse = $client->put(
$this->updateTarget.'/'.$stageIntranet->id,
[
'json'=>[$stageIntranetJson],
]
);
dd($updateResponse->getBody()->getContents());
}
So next time I launch the code delta should be 0 and unfortunately there is always 3600 seconds as you can see
I got the answer, it's a breaking change since Laravel 7 you must override the default Datetime serialization in your model, see : https://laravel.com/docs/7.x/upgrade#date-serialization

How to create solr document with String type using solarium query

I' creating solr document via solarium plugin in php.
But the all document is stored text_general data type except id field. text_general is the default datatype in solr system.
My doubt is why id field is only to stored string type as default.
And If any possible to add document with string type using solarium plugin.
My code part is here,
public function updateQuery() {
$update = $this->client2->createUpdate();
// create a new document for the data
$doc1 = $update->createDocument();
// $doc1->id = 123;
$doc1->name = 'value123';
$doc1->price = 364;
// and a second one
$doc2 = $update->createDocument();
// $doc2->id = 124;
$doc2->name = 'value124';
$doc2->price = 340;
// add the documents and a commit command to the update query
$update->addDocuments(array($doc1, $doc2));
$update->addCommit();
// this executes the query and returns the result
$result = $this->client2->update($update);
echo '<b>Update query executed</b><br/>';
echo 'Query status: ' . $result->getStatus(). '<br/>';
echo 'Query time: ' . $result->getQueryTime();
}
The result document for the above code is here,
{
"responseHeader":{
"status":0,
"QTime":2,
"params":{
"q":"*:*",
"_":"1562736411330"}},
"response":{"numFound":2,"start":0,"docs":[
{
"name":["value123"],
"price":[364],
"id":"873dfec0-4f9b-4d16-9579-a4d5be8fee85",
"_version_":1638647891775979520},
{
"name":["value124"],
"price":[340],
"id":"7228e92d-5ee6-4a09-bf12-78e24bdfa52a",
"_version_":1638647892102086656}]
}}
This depends on the field type defined in the schema for your Solr installation. It does not have anything to do with how you're sending data through Solarium.
In the schemaless mode, the id field is always set as a string, since a unique field can't be tokenized (well, it can, but it'll give weird, non-obvious errors).
In your case i'd suggest defining the price field as an integer/long field (if it's integers all the way) and the name field as a string field. Be aware that string fields only generate hits on exact matches, so in your case you'd have to search for value124 with exact casing to get a hit.
You can also adjust the multiValued property of the field when you define the fields explicitly. That way you get only the string back in the JSON structure instead of an array containing the string.

PHP SQLite - prepared statement misbehaves?

I have the following SQLite table
CREATE TABLE keywords
(
id INTEGER PRIMARY KEY,
lang INTEGER NOT NULL,
kwd TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
locs TEXT NOT NULL DEFAULT '{}'
);
CREATE UNIQUE INDEX kwd ON keywords(lang,kwd);
Working in PHP I typically need to insert keywords in this table, or update the row count if the keyword already exists. Take an example
$langs = array(0,1,2,3,4,5);
$kwds = array('noel,canard,foie gras','','','','','');
I now these data run through the following code
$len = count($langs);
$klen = count($kwds);
$klen = ($klen < $len)?$klen:$len;
$sqlite = new SQLite3('/path/to/keywords.sqlite');
$iStmt = $sqlite->prepare("INSERT OR IGNORE INTO keywords (lang,kwd)
VALUES(:lang,:kwd)");
$sStmt = $sqlite->prepare("SELECT rowid FROM keywords WHERE lang = :lang
AND kwd = :kwd");
if (!$iStmt || !$sStmt) return;
for($i=0;$i < $klen;$i++)
{
$keywords = $kwds[$i];
if (0 === strlen($keywords)) continue;
$lang = intval($langs[$i]);
$keywords = explode(',',$keywords);
for($j=0;$j < count($keywords);$j++)
{
$keyword = $keywords[$j];
if (0 === strlen($keyword)) continue;
$iStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
$iStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':lang',$lang,SQLITE3_INTEGER);
$sStmt->bindValue(':kwd',$keyword,SQLITE3_TEXT);
trigger_error($keyword);
$iStmt->execute();
$sqlite->exec("UPDATE keywords SET count = count + 1 WHERE lang =
'{$lang}' AND kwd = '{$keyword}';");
$rslt = $sStmt->execute();
trigger_error($sqlite->lastErrorMsg());
trigger_error(json_encode($rslt->fetchArray()));
}
}
which generates the following trigger_error output
Keyword: noel
Last error: not an error
SELECT Result: {"0":1,"id":1}
Keyword: canard
Last Error: not an error
SELECT Reult:false
Keyword:foiegras
Last Error: not an error
SELECT Result: false
From the SQLite command line I see that the three row entries are present and correct in the table with the id/rowid columns set to 1, 2 and 3 respectively. lastErrorMsg does not report an error and yet two of the three $rslt->fetchArray() statements are returning false as opposed to an array with rowid/id attributes. So what am I doing wrong here?
I investigated this a bit more and found the underlying case. In my original code the result from the first SQLite3::execute - $iStmt-execute() - was not being assigned to anything. I did not see any particular reason for fetching and interpreting that result. When I changed that line of code to read $rslt = $iStmt->execute() I got the expected result - the rowid/id of the three rows that get inserted was correctly reported.
It is as though internally the PHP SQLite3 extension buffers the result from SQLiteStatement::execute function calls. When I was skipping the assignment my next effort at running such a statement, $sStmt->execute() was in effect fetching the previous result. This is my interpretation without knowing the inner workings of the PHP SQLite3 extension. Perhaps someone who understands the extension better would like to comment.
Add $rslt = NONE; right after trigger_error(json_encode($rslt->fetchArray())); and the correct results appear.
FetchArray can only be called once and somehow php is not detecting that the variable has changed. I also played with changing bindValue to bindParam and moving that before the loop but that is unrelated to the main issue.
It is my opinion that my solution should not work unless there is a bug in php. I am too new at the language to feel confident in that opinion and would like help verifying it. Okay, not a bug, but a violation of the least surprise principle. The object still exists in memory so without finalizing it or resetting the variable, fetch array isn't triggering.

eBay LMS SoldReport Date Range?

I am using devbay's eBay SDK for PHP.
By default SoldReport is returning the last 30 days.
I'm trying to filter the date range to specify one-day/24 hour period.
I'm assuming I need to include a date range filter somewhere in the StartDownloadJobRequest call.
$startDownloadJobRequest = new BulkDataExchange\Types\StartDownloadJobRequest();
$startDownloadJobRequest->downloadJobType = 'SoldReport';
$startDownloadJobRequest->UUID = uniqid();
$startDownloadJobRequest->downloadRequestFilter = new BulkDataExchange\Types\DownloadRequestFilter();
$startDownloadJobRequest->downloadRequestFilter->activeInventoryReportFilter = $activeInventoryReportFilter;
I tried CreateTimeFrom and CreateTimeTo but received an Unknown property CreateTimeFrom error, so I do not believe I can use that for this request.
Anyone know how to filter date range in reports?
edit:
So it looks like startTime and endTime is apart of DownloadRequestFilter
DownloadRequestFilter DateTime
I thought something like this would work..
$datefilter = new BulkDataExchange\Types\DateFilter();
$datefilter->startTime = new DateTime('22-10-2016');
$datefilter->endTime = new DateTime('23-10-2016');
//
$startDownloadJobRequest->downloadRequestFilter->dateFilter = $datefilter;
but this doesn't work and I still get all results.

php strtotime function (2)

I started to learn PHP and have to find a mistake (maybe in this code):
if($newvalues["year"] != null)
$newvalues["year"] = date("Y-m-d", strtotime($newvalues["year"]."-01-01"));
The new date has to be saved in the array "$newvalues", but when I press the save button, it doesn't save anything. Only if the textfield "year" is empty, the other items can be saved.
Can anyone help me, please?
Thanks.
You're basically doing:
100 * 80 / 80
Just save it as
if($newvalues["year"] != null)
$newvalues["year"] .= "-01-01";
Or better yet, represent it as a DateTime object:
$newvalues = array("year" => 2012);
if ($newvalues["year"] != null) {
$newvalues["year"] = new DateTime("{$newvalues["year"]}-01-01");
}
var_dump($newvalues["year"]);
Using a DateTime object (And the DateTime family) gives you much better and more flexible control over your date/times.

Categories