en_btr_backend/app/Http/Controllers/CommentaryController.php

89 lines
2.3 KiB
PHP

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\Traits\BookXmlFilesTrait;
use GrahamCampbell\Markdown\Facades\Markdown;
class CommentaryController extends Controller
{
use BookXmlFilesTrait;
/**
* @return string
*/
private function getStoragePath() : string
{
return storage_path() . '/en_bc/';
}
/**
* @param Request $request
* @param $book
* @param $chapter
* @return mixed
*/
public function chapter(Request $request, $book, $chapter)
{
$book = $this->fixBookName($book);
$filepath = $this->getStoragePath()
. strtolower(self::$bookXmlFiles[$book]) . '/'
. $this->prepChapterName($chapter);
if (file_exists($filepath)) {
return Markdown::convertToHtml($this->fixRelativeUrlPaths(file_get_contents($filepath)));
}
}
/**
* @param Request $request
* @param $article
* @return mixed
*/
public function article(Request $request, $article)
{
$filepath = $this->getStoragePath() . 'articles/' . strtolower($article) . '.md';
if (file_exists($filepath)) {
return Markdown::convertToHtml($this->fixRelativeUrlPaths(file_get_contents($filepath)));
} else {
return "File " . $filepath . " NOT FOUND.";
}
}
/**
* Book names we get from the FE will have space between the number and the title: 1 corinthians
* which needs to be removed.
*
* @param string $bookName
* @return string
*/
private function fixBookName(string $bookName) : string
{
if (is_numeric(substr($bookName, 0, 1))) {
return strtolower(substr($bookName, 0, 1) . ltrim(substr($bookName, 1)));
} else {
return strtolower($bookName);
}
}
/**
* @param string $chapterName
* @return string
*/
private function prepChapterName(string $chapterName) : string
{
if (strtolower($chapterName) === "intro") {
return 'intro.md';
} else {
return sprintf("%02d.md", $chapterName);
}
}
private function fixRelativeUrlPaths($markdown) : string
{
return preg_replace("#\[(.*?)\]\([ \t]*../articles/([a-zA-Z]*)\.md[ \t]*\)#", "[$1](/commentary/articles/$2)", $markdown);
}
}