From 3cfd1b66334588d9da2615f66430789d3f7ae17c Mon Sep 17 00:00:00 2001
From: "Hahn Axel (hahn)" <axel.hahn@unibe.ch>
Date: Wed, 16 Oct 2024 15:59:02 +0200
Subject: [PATCH] email catcher class: detect parse error when reading email
 data

---
 classes/emailcatcher.class.php | 29 ++++++++++++++++++++++++++++-
 1 file changed, 28 insertions(+), 1 deletion(-)

diff --git a/classes/emailcatcher.class.php b/classes/emailcatcher.class.php
index 54ca9a7..a417459 100644
--- a/classes/emailcatcher.class.php
+++ b/classes/emailcatcher.class.php
@@ -12,22 +12,36 @@
  * 
  * ----------------------------------------------------------------------
  * 2024-10-08  v0.1  initial version
+ * 2024-10-16  v0.2  detect parse error when reading email data
  * =======================================================================
  */
 
 class emailcatcher
 {
 
+    /**
+     * Filename for email data
+     * @var string
+     */
     protected string $sMailData='emaildata.txt';
 
+    /**
+     * Id of selected email
+     * @var string
+     */
     protected string $sId='';
+
+    /**
+     * Email data of the selected email
+     * @var array
+     */
     protected array $aSelectedEmail=[];
 
+    // ------------------------------------------------------------------
 
     public function __construct()
     {
         $this->sMailData=dirname(__DIR__) . '/data/' . $this->sMailData;
-        // $this->_readEmails();
     }
 
     // ------------------------------------------------------------------
@@ -37,6 +51,7 @@ class emailcatcher
     /**
      * Fetch email of a single email from stdin and store it.
      * It returns the return value of file_put_contents().
+     * used in php-sendmail.php
      * 
      * @return bool|int
      */
@@ -70,6 +85,11 @@ class emailcatcher
     // ------------------------------------------------------------------
 
 
+    /**
+     * Read all stored emails and return them as an array
+     * @param string $sEmail2Show  optional: id of email to show
+     * @return array
+     */
     protected function _readEmails(string $sEmail2Show=''): array
     {
         if(!file_exists($this->sMailData)){
@@ -77,7 +97,14 @@ class emailcatcher
         }
         foreach(file($this->sMailData) as $line) {
 
+            if (empty(trim($line))) {
+                continue;
+            }
             $aLinedata=json_decode($line, true);
+            if(!is_array($aLinedata)){
+                // echo "ERROR: unable to parse line as single json object: <code>$line</code>";
+                continue;
+            }
             [$sHead, $sBody] = explode("\r\n\r\n", $aLinedata['mail']);
             
             $sHead="\n$sHead";
-- 
GitLab