Laravel PHP cannot get try-catch to work with DB updated - php

I have a video file to probe with the use of FFPROBE, I'm trying to catch the error so that instead of just throwing the error it updates the DB row first, setting it to state 2 (processed 0 = default, processed 0 = done, processed 2 = error).
I've tried this first:
$user = Auth::user()->id;
$video = Video::find($videoUploaded->video->id);
$playlist = $video->playlist->id;
...
try {
//Line 39 $seconds
$seconds = $ffprobe->format(config('cf.video_disk') . "/$user/$playlist/$video->ts_name")->get('duration');
} catch (\Exeption $err) {
$video->processed = 2;
$video->name = $err->getMessage();
$video->url = $err->getMessage();
$video->update();
event(new VideoUpdated($video));
return $err->getMessage();
}
And also suppressing the error with # and moving the DB update in the try:
try {
//Line 39 $seconds
$seconds = #$ffprobe->format(config('wondermark.video_disk') . "/$user/$playlist/$video->ts_name")->get('duration'); //Line 39
if (FALSE === $seconds) {
$video->processed = 2;
$video->name = $err->getMessage();
$video->url = $err->getMessage();
$video->update();
}
} catch (\Exeption $err) {
event(new VideoUpdated($video));
return $err->getMessage();
}
Both return the error on line #39 (see above comment) and the DB does not get updated :(

It seems there's only a mistake in spelling Exception, So i guess this will work:
try {
$seconds = $ffprobe->format(config('cf.video_disk') . "/$user/$playlist/$video->ts_name")->get('duration');
// if no errors
} catch (\Exception $err) {
// if error happens
return $err->getMessage();
}
And it is more recommended that you catch throwables (PHP: Throwable - Manual) instead of exceptions:
try {
$seconds = $ffprobe->format(config('cf.video_disk') . "/$user/$playlist/$video->ts_name")->get('duration');
// if no errors
} catch (\Throwable $throwable) {
// if error happens
return $throwable->getMessage();
}

Related

Getting Message Threads, modfied after [date]

The Why?
I'm playing around with the GMAIL api, for a minor project at work
The Wanted Result
What I'm trying to get from the Gmail API, is all message threads modfied after a certain timestamp/date.
What do i have so far
So far i manage to get all threads created after a certain date - by using the standart gmail search queries see - https://support.google.com/mail/answer/7190.
The Problem
It's great i can get all the Message Threads after a certain date, but the problem is when i have my queried set as:
after:[todays date - 7 days)
This will show me all Message Threads, up to 7 days ago - but what when i have a Message Thread, created 8 days ago and still getting updated?. What is my best option to get all message threads, modified from now to 7 days ago?
Checking all message threads, all the time is not an option :)
The code
$client = getClient();
$oService = new Google_Service_Gmail($client);
$sUser = 'me';
$tsMailsAfter = '1554280000';
$sIn = 'INBOX';
//before;, after:, in:(inbox, sent)
$aThreads = getlistThread($oService, $sUser, 'after:'.$tsMailsAfter.' in:'.$sIn);
function getlistThread($service, $userId, $aQuery = '')
{
$threads = array();
$pageToken = NULL;
do
{
try
{
$opt_param = array();
if ($pageToken)
{
$opt_param['pageToken'] = $pageToken;
}
$opt_param['q'] = $aQuery;
$threadsResponse = $service->users_threads->listUsersThreads($userId, $opt_param);
if($threadsResponse->getThreads())
{
$threads = array_merge($threads, $threadsResponse->getThreads());
$pageToken = $threadsResponse->getNextPageToken();
}
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
$pageToken = NULL;
}
}
while ($pageToken);
return $threads;
}
i solved my issue by just using a search query (with :after) on ->listUsersMessages() and then collecting the ID's in an array(). Its not the most optimal solution, having a search query :modified_after would be the best solution - this solution defiantly works for my purpose:)
function listThreadsToUpdate($service, $userId, $sQuery = '')
{
$pageToken = NULL;
$messages = array();
$opt_param = array();
do
{
try
{
if ($pageToken)
{
$opt_param['pageToken'] = $pageToken;
}
$opt_param['q'] = $sQuery;
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages())
{
$aMessages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
$aThreadsToUpdate = array();
if(isset($aMessages) && !empty($aMessages))
{
foreach ($aMessages as $oMessage)
{
$aThreadsToUpdate[] = $oMessage->getThreadId();
}
}
return array_unique($aThreadsToUpdate);
}

Value of variable changes in while-loop

Me and all my live contact are stunned by phenomenom where a variable value changes in other side ow while. Before 2nd loop value is correct, but inside 2nd loop value is incorrect.
Here's the actual code.
try {
$yhteys = new PDO('mysql:host=localhost;dbname=XXXX', 'YYYY', 'ZZZZ');
} catch (PDOException $e) {
die("VIRHE: " . $e->getMessage());
}
$yhteys->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$yhteys->exec("SET NAMES utf8");
$kysely = $yhteys->prepare('SELECT viite FROM hakija WHERE vaihe = 1 ');
$kysely->execute();
$file = fopen("tilit.csv","r");
while(! feof($file)) {
$tilirivi=fgetcsv($file,100,";");
if ($tilirivi[4] < 0) continue;
$viiteviesti = substr($tilirivi[3], 1);
//print "Viiteviesti1: $viiteviesti\n"; produces correct print
while ($rivi = $kysely->fetch()) {
//print "Viiteviesti2: $viiteviesti\n"; produces incorrect print
$kantaviite=$rivi["viite"];
if ($viiteviesti == $kantaviite ) {
$asetus = $yhteys->prepare("UPDATE hakija SET vaihe=2 WHERE viite='$viiteviesti' ");
$asetus->execute();
}
}
}
How is this possible and how should I correct my code?
'column' is a reserved variable name according to this article:
http://hockinson.com/programmer-web-designer-denver-co-usa.php?s=43
which might cause unexpected results.
It came up that for some reason $kysely-fecth() didn't return any content. I got the code working and here's solution:
try {
$yhteys = new PDO('mysql:host=localhost;dbname=XXXX', 'YYYY', 'ZZZZ');
} catch (PDOException $e) {
die("VIRHE: " . $e->getMessage());
}
$yhteys->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$yhteys->exec("SET NAMES utf8");
$kysely = $yhteys->prepare('SELECT viite FROM hakija WHERE vaihe = 1 ');
$kysely->execute();
$kysely->setFetchMode(PDO::FETCH_NUM);
$result = $kysely->fetchAll();
$file = fopen("tilit.csv","r");
while(! feof($file)) {
$tilirivi=fgetcsv($file,100,";");
if ($tilirivi[4] < 10) continue;
$viiteviesti = substr($tilirivi[3], 1);
foreach ($result as $rivi) {
foreach ($rivi as $kantaviite) {
if ($viiteviesti == $kantaviite ) {
$asetus = $yhteys->prepare("UPDATE hakija SET vaihe=2 WHERE viite='$viiteviesti' ");
$asetus->execute();
}
}
}
}

Zend Search Lucene case insensitive search doesn't work

I've got a Search class, which has
public function __construct($isNewIndex = false) {
setlocale(LC_CTYPE, 'ru_RU.UTF-8');
$analyzer = new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive();
$morphy = new Isi_Search_Lucene_Analysis_TokenFilter_Morphy('ru_RU');
$analyzer->addFilter($morphy);
Zend_Search_Lucene_Analysis_Analyzer::setDefault($analyzer);
Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding('utf-8');
//if it's true, then it creates new folder to the path in $_indexFieles;
if ($isNewIndex) {
$this->_indexes[$this->_key] = Zend_Search_Lucene::create(Yii::getPathOfAlias('application.' . $this->_indexFiles), true);
} else {
$this->_indexes[$this->_key] = Zend_Search_Lucene::open(Yii::getPathOfAlias('application.' . $this->_indexFiles));
}
}
public function find($query, $eventId)
{
try
{
Zend_Search_Lucene_Search_QueryParser::setDefaultOperator(Zend_Search_Lucene_Search_QueryParser::B_AND);
$query = "($query) AND (event_id:$eventId)";
Zend_Search_Lucene::setResultSetLimit(self::ACCREDITATION_LIMIT);
return $this->_indexes[$this->_key]->find("{$query}");
}
catch (Zend_Search_Lucene_Search_QueryParserException $e)
{
echo "Query syntax error: " . $e->getMessage() . "\n";
}
catch (Exception $e)
{
echo $e->getMessage(). "\n";
}
}
I've got a record with name Test, when I'm looking for Test it works, but can't find this record with request test
Code example:
$s = new Search();
$s->find('test', 1232);//no results
I found a solution, the problem was that I was saving fields (name, etc.) as keyword, I changed it to text, and now it's working perfectly.

Form not validate at Symfony side, what could be possible wrong?

I have this code in my controller:
/**
* #Secure(roles="IS_AUTHENTICATED_FULLY")
* #Route("/rpni/registro/producto/1/guardar", name="productoGuardarPasoUno")
* #Method("POST")
*/
public function guardarPaso1Action(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$response['success'] = false;
$status = 400;
if ($request->isXmlHttpRequest()) {
$productoSolicitudRequest = $request->request->get('productoSolicitud');
$entProductoSolicitud = $em->getRepository("AppBundle:ProductoSolicitud")->find($session->get('productoSolicitudId'));
$entProducto = $em->getRepository("AppBundle:Producto")->find($productoSolicitudRequest['producto']['nombre']);
$entCondicionProducto = $em->getRepository("AppBundle:CondicionProducto")->find($productoSolicitudRequest['condicion_producto']);
$entFinalidadProducto = $em->getRepository("AppBundle:FinalidadProducto")->find($productoSolicitudRequest['finalidad_producto']);
$entProcedenciaProducto = $em->getRepository("AppBundle:ProcedenciaProducto")->find($productoSolicitudRequest['procedencia_producto']);
$entSolicitudUsuario = $em->getRepository("AppBundle:SolicitudUsuario")->find($session->get('solicitudUsuarioId'));
if ($entProductoSolicitud)
{
$entProductoSolicitud->setProducto($entProducto);
$entProductoSolicitud->setCondicionProducto($entCondicionProducto);
$entProductoSolicitud->setFinalidadProducto($entFinalidadProducto);
$entProductoSolicitud->setProcedenciaProducto($entProcedenciaProducto);
$entProductoSolicitud->setSolicitudUsuario($entSolicitudUsuario);
try {
$em->flush();
} catch (\Exception $e) {
$response['error'] = $e->getMessage();
return new JsonResponse($response, $status);
}
} else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
if ($formProductoSolicitud->isValid())
{
try {
$em->persist($newEntProductoSolicitud);
$em->flush();
$session->set('productoSolicitudId', $newEntProductoSolicitud->getId());
$session->set('productoId', $entProducto->getId());
$response['success'] = true;
// Debug: remover cuando se termine el Bundle
$response['productoSolicitudId'] = $session->get('productoSolicitudId');
$response['productoId'] = $session->get('productoId');
$status = 200;
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
$response['error'] = $this->get('translator')->trans('formularioNoValido');
$response['formError'] = $this->getFormErrors($formProductoSolicitud);
return new JsonResponse($response, $status);
}
}
return new JsonResponse($response, $status);
}
}
Which I'm trying to use for create and for update purposes. When I send the form through Ajax I get this response from Symfony2:
{
"success":false,
"error":"formularioNoValido",
"formError":{
"producto":{
"nombre":[
]
},
"lote":[
],
"procedencia_producto":[
],
"finalidad_producto":[
],
"condicion_producto":[
]
}
}
And nothing else to give me a clue. The weird part is that checking Post tab in Firebug give me this output:
Parameters application/x-www-form-urlencodedDo not sort
productoSolicitud[_token] wC_MAeVs7ZAGSpkvLYux6RKrLq46aivxXxiCZr6pNeU
productoSolicitud[condici... 1
productoSolicitud[finalid... 1
productoSolicitud[lote] 11
productoSolicitud[procede... 1
productoSolicitud[product... 4
Source
productoSolicitud%5Bproducto%5D%5Bnombre%5D=4&productoSolicitud%5Bprocedencia_producto%5D=1&productoSolicitud%5Bfinalidad_producto%5D=1&productoSolicitud%5Bcondicion_producto%5D=1&productoSolicitud%5Blote%5D=11&productoSolicitud%5B_token%5D=wC_MAeVs7ZAGSpkvLYux6RKrLq46aivxXxiCZr6pNeU
See the image below:
So, where the error is? Why form is not valid? Any clue? Advise?
If I'm not mistaken, your action only returns that response from this else statement :
else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
if ($formProductoSolicitud->isValid())
{
try {
$em->persist($newEntProductoSolicitud);
$em->flush();
$session->set('productoSolicitudId', $newEntProductoSolicitud->getId());
$session->set('productoId', $entProducto->getId());
$response['success'] = true;
// Debug: remover cuando se termine el Bundle
$response['productoSolicitudId'] = $session->get('productoSolicitudId');
$response['productoId'] = $session->get('productoId');
$status = 200;
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
$response['error'] = $this->get('translator')->trans('formularioNoValido');
$response['formError'] = $this->getFormErrors($formProductoSolicitud);
return new JsonResponse($response, $status);
}
}
I find it weird that you're checking your form's validity right after you created it from a new instance of ProductoSolicitud, is that really what you want to do ? Shouldn't you make this validity check in the case you got some data from the request ?
Maybe something like this :
if ($entProductoSolicitud)
{
$entProductoSolicitud->setProducto($entProducto);
$entProductoSolicitud->setCondicionProducto($entCondicionProducto);
$entProductoSolicitud->setFinalidadProducto($entFinalidadProducto);
$entProductoSolicitud->setProcedenciaProducto($entProcedenciaProducto);
$entProductoSolicitud->setSolicitudUsuario($entSolicitudUsuario);
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $entProductoSolicitud);
if ($formProductoSolicitud->isValid()) {
try {
$em->flush();
} catch (\Exception $e) {
$response['error'] = $e->getMessage();
return new JsonResponse($response, $status);
}
}
}
But I might have just misunderstood the problem :S
Well, since I found where the issue was I'll answer myself so others won't make the same mistake. At my code I never tell the form to handle the request so there is where the issue is. The code in the else turns in to this:
} else {
$newEntProductoSolicitud = new Entity\ProductoSolicitud();
$formProductoSolicitud = $this->createForm(new Form\ProductoSolicitudForm(), $newEntProductoSolicitud);
$formProductoSolicitud->handleRequest($request);
if ($formProductoSolicitud->isValid())
{
...
} catch (Exception $ex) {
$response['error'] = $ex->getMessage();
return new JsonResponse($response, $status);
}
} else {
....
}
}
return new JsonResponse($response, $status);
}
}
That's all, happy coding!!

Drive API request sometimes returns an object another time an array - PHP

I'm doing a little page that lists all files that are in google drive. In the first time I do the authentication and save the refresh token + user id and email and then I list all the files. To get the information I do this:
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$list=$files->getItems();
$result = array_merge($result,$list);
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
And it works, but if the user refresh the page, I have do refresh the access token (getting the refresh token from db) and then proceed to do the same as above. In this case that code gives me an error because this time I get an associative array when I do:
$files = $service->files->listFiles($parameters);
To make it work I need to change the code to:
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$list=$files['items'];
$result = array_merge($result,$list);
$pageToken = $files['nextPageToken'];
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
This shouldn't happen but I have no idea what's wrong.
From the relevant php source of the class, I guess I found what makes you trouble.
Look at Google_DriveService.php:
// ~Line 119
public function listFiles($optParams = array()) {
$params = array();
$params = array_merge($params, $optParams);
$data = $this->__call('list', array($params));
if ($this->useObjects()) { // THIS CALL HERE
return new Google_FileList($data);
} else {
return $data;
}
}
It checks if you want to work with objects, or not: $this->useObjects().
This method is defined in the super class, Google_ServiceResource.php:
// ~Line 180
public function useObjects() {
global $apiConfig;
return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
}
This tells me, that when you configure your service, you will have to set 'use_object' to true.

Categories