From 86ad06def7ae1f3e8ea59b2f7c672c4831ada0d6 Mon Sep 17 00:00:00 2001 From: dhanabalan Date: Tue, 23 Sep 2025 09:42:57 +0530 Subject: [PATCH] Refactor readFiles method in SapFileController for improved error handling and code clarity --- app/Http/Controllers/SapFileController.php | 34 +++++++++++++++------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/app/Http/Controllers/SapFileController.php b/app/Http/Controllers/SapFileController.php index aeb103f..f4967b3 100644 --- a/app/Http/Controllers/SapFileController.php +++ b/app/Http/Controllers/SapFileController.php @@ -33,28 +33,42 @@ class SapFileController extends Controller $path = "/srv/pds.iotsignin.com/sapftp/In/"; // $files = scandir($path); + if (!is_dir($path) || !is_readable($path)) { + return response()->json([ + 'status' => 'error', + 'message' => 'Folder not accessible', + ], 500); + } - $path = '/srv/pds.iotsignin.com/sapftp/In/'; + $files = array_filter(scandir($path), function($file) use ($path) { + return $file !== '.' && $file !== '..' && is_file($path . $file) + && pathinfo($file, PATHINFO_EXTENSION) === 'txt'; + }); - $files = array_filter(scandir($path), fn($file) => - $file !== '.' && $file !== '..' && is_file($path . $file) && pathinfo($file, PATHINFO_EXTENSION) === 'txt' - ); + if (empty($files)) { + return response()->json([ + 'status' => 'error', + 'message' => 'No text files found', + ], 404); + } - $data = []; + $data = []; foreach ($files as $file) { + $filePath = $path . $file; + + // Read file content safely + $content = file_get_contents($filePath); + $data[] = [ 'filename' => $file, - 'content' => file_get_contents($path . $file), // plain text content + 'content' => $content, ]; - - // Optional: move processed file to Out - rename($path . $file, '/srv/pds.iotsignin.com/sapftp/Out/' . $file); } return response()->json([ 'status' => 'success', - 'files' => $data, + 'files' => $data, ]); }