polisplexity.tech/app/Services/SectionService.php

75 lines
2.5 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\App;
class SectionService {
private $language = 'es'; // Default language set as private attribute
private $role = 'default';
private $filePaths;
public function __construct() {
$this->language = App::getLocale();
$this->role = session('user_role');
$this->setFilePaths();
}
public function setLanguage($language) {
$this->language = $language;
$this->setFilePaths(); // Update file paths when language changes
}
private function setFilePaths() {
$basePath = "app/json/roles/$this->role/{$this->language}/";
$this->filePaths = [
'services' => $basePath . 'section_services.json',
'news' => $basePath . 'section_news.json',
'products' => $basePath . 'section_products.json',
'hero' => $basePath . 'section_hero.json',
'villain' => $basePath . 'section_villain.json',
];
}
public function hero() {
return $this->loadJsonData($this->heroFilePath);
}
public function features() {
return [
'firstRow' => $this->loadJsonData($this->featuresAFilePath),
'thirdRow' => $this->loadJsonData($this->featuresBFilePath)
];
}
private function loadJsonData($filePath,$methodName) {
$jsonFilePath = storage_path($filePath);
if (!file_exists($jsonFilePath)) {
// If file does not exist, use default role and language
$this->role = 'default';
$this->language = 'en';
$this->setFilePaths(); // Update file paths with default role and language
$filePath = $this->filePaths[$methodName];
$jsonFilePath = storage_path($filePath);
}
if (!file_exists($jsonFilePath)) {
// If default file also does not exist, return an empty array
return [];
}
$jsonData = file_get_contents($jsonFilePath);
return json_decode($jsonData, true);
}
public function get($methodName) {
$methodName = strtolower($methodName); // Ensure method name is in the correct case
if (array_key_exists($methodName, $this->filePaths)) {
return $this->loadJsonData($this->filePaths[$methodName],$methodName);
}
throw new \Exception("Method '{$methodName}' not found or not associated with a file path");
}
}