www: Add try catch to avoid exception on missing database

This commit is contained in:
Samuel Ortion 2022-08-24 07:23:47 +02:00
parent 30b1b44876
commit 0d696c8399
4 changed files with 103 additions and 57 deletions

View File

@ -1,4 +1,5 @@
<?php <?php
namespace App\Controller; namespace App\Controller;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
@ -6,14 +7,18 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\AppBundle\ConnectionObservations; use App\AppBundle\ConnectionObservations;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Log\Logger;
class HomeController extends AbstractController class HomeController extends AbstractController
{ {
private ConnectionObservations $connection; private ConnectionObservations $connection;
private LoggerInterface $logger;
public function __construct(ConnectionObservations $connection) public function __construct(ConnectionObservations $connection, LoggerInterface $logger)
{ {
$this->connection = $connection; $this->connection = $connection;
$this->logger = $logger;
} }
/** /**
@ -27,16 +32,14 @@ class HomeController extends AbstractController
"charts" => $this->last_chart_generated(), "charts" => $this->last_chart_generated(),
]); ]);
} }
/** /**
* @Route("/about", name="about") * @Route("/about", name="about")
* @Route("/{_locale<%app.supported_locales%>}/about", name="about_i18n") * @Route("/{_locale<%app.supported_locales%>}/about", name="about_i18n")
*/ */
public function about() public function about()
{ {
return $this->render('about/index.html.twig', [ return $this->render('about/index.html.twig', []);
]);
} }
private function get_stats() private function get_stats()
@ -47,40 +50,55 @@ class HomeController extends AbstractController
return $stats; return $stats;
} }
private function get_most_recorded_species() private function get_most_recorded_species()
{ {
$species = [];
$sql = "SELECT `scientific_name`, `common_name`, COUNT(*) AS contact_count $sql = "SELECT `scientific_name`, `common_name`, COUNT(*) AS contact_count
FROM `taxon` FROM `taxon`
INNER JOIN `observation` INNER JOIN `observation`
ON `taxon`.`taxon_id` = `observation`.`taxon_id` ON `taxon`.`taxon_id` = `observation`.`taxon_id`
ORDER BY `contact_count` DESC LIMIT 1"; ORDER BY `contact_count` DESC LIMIT 1";
$stmt = $this->connection->prepare($sql); try {
$result = $stmt->executeQuery(); $stmt = $this->connection->prepare($sql);
$species = $result->fetchAllAssociative(); $result = $stmt->executeQuery();
return $species[0]; $species = $result->fetchAllAssociative()[0];
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
return $species;
} }
private function get_last_recorded_species() private function get_last_recorded_species()
{ {
$species = [];
$sql = "SELECT `scientific_name`, `common_name`, `date`, `audio_file`, `confidence` $sql = "SELECT `scientific_name`, `common_name`, `date`, `audio_file`, `confidence`
FROM `observation` FROM `observation`
INNER JOIN `taxon` INNER JOIN `taxon`
ON `observation`.`taxon_id` = `taxon`.`taxon_id` ON `observation`.`taxon_id` = `taxon`.`taxon_id`
ORDER BY `date` DESC LIMIT 1"; ORDER BY `date` DESC LIMIT 1";
$stmt = $this->connection->prepare($sql); try {
$result = $stmt->executeQuery(); $stmt = $this->connection->prepare($sql);
$species = $result->fetchAllAssociative(); $result = $stmt->executeQuery();
return $species[0]; $species = $result->fetchAllAssociative()[0];
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
return $species;
} }
private function last_chart_generated() { private function last_chart_generated()
{
$files = glob($this->getParameter('kernel.project_dir') . '/../var/charts/*.png'); $files = glob($this->getParameter('kernel.project_dir') . '/../var/charts/*.png');
usort($files, function($a, $b) { if (count($files) > 0) {
return filemtime($a) - filemtime($b); usort($files, function ($a, $b) {
}); return filemtime($a) - filemtime($b);
$last_chart = basename(array_pop($files)); });
return $last_chart;
$last_chart = basename(array_pop($files));
return $last_chart;
} else {
$this->logger->info("No charts found");
return "";
}
} }
}
}

View File

@ -6,15 +6,20 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\AppBundle\ConnectionObservations; use App\AppBundle\ConnectionObservations;
use Psr\Log\LoggerInterface;
class TodayController extends AbstractController class TodayController extends AbstractController
{ private ConnectionObservations $connection; {
private ConnectionObservations $connection;
private LoggerInterface $logger;
public function __construct(ConnectionObservations $connection) public function __construct(ConnectionObservations $connection, LoggerInterface $logger)
{ {
$this->connection = $connection; $this->connection = $connection;
$this->logger = $logger;
} }
/** /**
* @Route("/today", name="today") * @Route("/today", name="today")
* @Route("/{_locale<%app.supported_locales%>}/today", name="today_i18n") * @Route("/{_locale<%app.supported_locales%>}/today", name="today_i18n")
@ -88,28 +93,38 @@ class TodayController extends AbstractController
private function recorded_species_by_date($date) private function recorded_species_by_date($date)
{ {
$recorded_species = [];
$sql = "SELECT `taxon`.`taxon_id`, `scientific_name`, `common_name`, COUNT(*) AS `contact_count`, MAX(`confidence`) AS max_confidence $sql = "SELECT `taxon`.`taxon_id`, `scientific_name`, `common_name`, COUNT(*) AS `contact_count`, MAX(`confidence`) AS max_confidence
FROM observation FROM observation
INNER JOIN taxon INNER JOIN taxon
ON observation.taxon_id = taxon.taxon_id ON observation.taxon_id = taxon.taxon_id
WHERE strftime('%Y-%m-%d', `observation`.`date`) = :date WHERE strftime('%Y-%m-%d', `observation`.`date`) = :date
GROUP BY observation.taxon_id"; GROUP BY observation.taxon_id";
$stmt = $this->connection->prepare($sql); try {
$stmt->bindValue(':date', $date); $stmt = $this->connection->prepare($sql);
$result = $stmt->executeQuery(); $stmt->bindValue(':date', $date);
return $result->fetchAllAssociative(); $result = $stmt->executeQuery();
$recorded_species = $result->fetchAllAssociative();
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
return $recorded_species;
} }
private function recorded_species_by_id_and_date($id, $date) private function recorded_species_by_id_and_date($id, $date)
{ {
/* Get taxon even if there is no record this date */ /* Get taxon even if there is no record this date */
$sql = "SELECT * FROM `taxon` WHERE `taxon_id` = :id"; $sql = "SELECT * FROM `taxon` WHERE `taxon_id` = :id";
$stmt = $this->connection->prepare($sql); $taxon = [];
$stmt->bindValue(':id', $id); $stat = [];
$result = $stmt->executeQuery(); $records = [];
$taxon = $result->fetchAllAssociative()[0]; try {
if (!$taxon) { $stmt = $this->connection->prepare($sql);
return []; $stmt->bindValue(':id', $id);
$result = $stmt->executeQuery();
$taxon = $result->fetchAllAssociative()[0];
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
} }
/* Get daily stats */ /* Get daily stats */
$sql = "SELECT COUNT(*) AS `contact_count`, MAX(`confidence`) AS `max_confidence` $sql = "SELECT COUNT(*) AS `contact_count`, MAX(`confidence`) AS `max_confidence`
@ -118,33 +133,47 @@ class TodayController extends AbstractController
ON `taxon`.`taxon_id` = `observation`.`taxon_id` ON `taxon`.`taxon_id` = `observation`.`taxon_id`
WHERE strftime('%Y-%m-%d', `observation`.`date`) = :date WHERE strftime('%Y-%m-%d', `observation`.`date`) = :date
AND `observation`.`taxon_id` = :id"; AND `observation`.`taxon_id` = :id";
$stmt = $this->connection->prepare($sql); try {
$stmt->bindValue(':id', $id); $stmt = $this->connection->prepare($sql);
$stmt->bindValue(':date', $date); $stmt->bindValue(':id', $id);
$result = $stmt->executeQuery(); $stmt->bindValue(':date', $date);
$stat = $result->fetchAllAssociative(); $result = $stmt->executeQuery();
$stat = $result->fetchAllAssociative();
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
$sql = "SELECT * FROM `observation` $sql = "SELECT * FROM `observation`
WHERE `taxon_id` = :id WHERE `taxon_id` = :id
AND strftime('%Y-%m-%d', `observation`.`date`) = :date AND strftime('%Y-%m-%d', `observation`.`date`) = :date
ORDER BY `observation`.`date` ASC"; ORDER BY `observation`.`date` ASC";
$stmt = $this->connection->prepare($sql); try {
$stmt->bindValue(':id', $id); $stmt = $this->connection->prepare($sql);
$stmt->bindValue(':date', $date); $stmt->bindValue(':id', $id);
$result = $stmt->executeQuery(); $stmt->bindValue(':date', $date);
$records = $result->fetchAllAssociative(); $result = $stmt->executeQuery();
$records = $result->fetchAllAssociative();
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
return array("taxon" => $taxon, "stat" => $stat, "records" => $records); return array("taxon" => $taxon, "stat" => $stat, "records" => $records);
} }
private function best_confidence_today($id, $date) private function best_confidence_today($id, $date)
{ {
$best_confidence = 0;
$sql = "SELECT MAX(`confidence`) AS confidence $sql = "SELECT MAX(`confidence`) AS confidence
FROM `observation` FROM `observation`
WHERE strftime('%Y-%m-%d', `observation`.`date`) = :date WHERE strftime('%Y-%m-%d', `observation`.`date`) = :date
AND `taxon_id` = :id"; AND `taxon_id` = :id";
$stmt = $this->connection->prepare($sql); try {
$stmt->bindValue(':id', $id); $stmt = $this->connection->prepare($sql);
$stmt->bindValue(':date', $date); $stmt->bindValue(':id', $id);
$result = $stmt->executeQuery(); $stmt->bindValue(':date', $date);
return $result->fetchAllAssociative(); $result = $stmt->executeQuery();
$result->fetchAllAssociative();
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
return $best_confidence;
} }
} }

View File

@ -41,10 +41,9 @@
<li class="dropdown"> <li class="dropdown">
<span class="dropdown-toggle">{{ "Tools"|trans }}</span> <span class="dropdown-toggle">{{ "Tools"|trans }}</span>
<ul class="dropdown-content"> <ul class="dropdown-content">
{% include 'utils/nav-item.html.twig' with { <li><a href="/ttyd">
route: 'logs', {{ "Logs"|trans }}
text: 'View Logs'|trans </a></li>
} %}
{% include 'utils/nav-item.html.twig' with { {% include 'utils/nav-item.html.twig' with {
route: 'services_status', route: 'services_status',
text: 'Status'|trans text: 'Status'|trans

View File

@ -3,7 +3,7 @@
<ul> <ul>
<li class="most-recorded-species"> <li class="most-recorded-species">
{{ "Most recorded species" | trans }}: {{ "Most recorded species" | trans }}:
{% if stats["most-recorded-species"] is defined %} {% if stats["most-recorded-species"] is defined and stats["most-recorded-species"]|length > 0 %}
<span class="scientific-name"> <span class="scientific-name">
{{ stats["most-recorded-species"]["scientific_name"] }} {{ stats["most-recorded-species"]["scientific_name"] }}
</span> </span>
@ -19,7 +19,7 @@
</li> </li>
<li class="last-recorded-species"> <li class="last-recorded-species">
{{ "Last detected species" | trans }}: {{ "Last detected species" | trans }}:
{% if stats["last-detected-species"] is defined %} {% if stats["last-detected-species"] is defined and stats["last-detected-species"]|length > 0 %}
<span class="scientific-name"> <span class="scientific-name">
{{ stats["last-detected-species"]["scientific_name"] }} {{ stats["last-detected-species"]["scientific_name"] }}
</span> </span>