Commit efd19243 authored by nirgendswo's avatar nirgendswo

adding new examples md-files

adding truncate for html
parent 443fed27
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class ViewHelperFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'App\ViewHelper';
}
}
<?php
namespace App\Helpers;
use DOMDocument;
/**
* Parser for Page
*
* @author Björn Hase
*/
class ViewHelper
{
const TRUNCATED_LENGTH = 150;
/**
* truncated html
*
* @param string $markdown
* @param integer $length
* @return string
*/
public function truncated($html, $length = self::TRUNCATED_LENGTH)
{
$result = '';
if (strlen($html) <= $length) {
$result = $html;
} else {
$dom = new DOMDocument();
$dom->loadHTML($html);
$dom->removeChild($dom->firstChild);
/*
* If your post is wrapped by a parent element with an id:
* $node = $dom->getElementById('id')->firstChild
* Otherwise skip <html> and <body> and grab the first element of your post
*/
$node = $dom->firstChild->firstChild->firstChild;
while(strlen($result) < $length) {
$result .= $dom->saveHTML($node);
$node = $node->nextSibling;
}
}
return $result;
}
}
......@@ -7,17 +7,14 @@ use Parsedown;
/**
* Single Page
*
*
* @author Björn Hase
*
*/
class PageModel
{
/* slug */
public $slug;
/* html */
public $html;
/* markdown */
public $markdown;
......@@ -31,7 +28,9 @@ class PageModel
/**
*
*
* @param array $meta
* @param string $slug
* @param array $data
* @param string $markdown
*/
public function __construct($slug = NULL, array $data, $markdown)
{
......@@ -41,12 +40,13 @@ class PageModel
}
/**
* [render description]
* getting html
*
* @return $string
*/
public function render()
public function html()
{
$parsedown = new Parsedown();
$this->html = $parsedown->text($this->markdown);
return $parsedown->text($this->markdown);
}
}
......@@ -22,17 +22,16 @@ class PageParser
*/
public function toObject($slug = NULL, $file)
{
preg_match(self::REGEX, $file, $data);
$page = NULL;
// if data isset
if (isset($data[0])) {
$markdown = preg_replace(self::REGEX, '', $file, 1);
$data = json_decode($data[0], true);
} else {
preg_match(self::REGEX, $file, $data);
$markdown = preg_replace(self::REGEX, '', $file, 1);
if (!isset($data[0])) {
throw Exception('PageParser - JSON in md-file is NULL');
}
// create page
$data = json_decode($data[0], true);
$page = new PageModel($slug, $data, $markdown);
return $page;
......
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\App;
class ViewHelperServiceProvider extends ServiceProvider
{
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind('App\ViewHelper', function() {
return new \App\Helpers\ViewHelper();
});
}
}
......@@ -4,6 +4,8 @@ namespace App\Repositories;
use Exception;
use Datetime;
use DirectoryIterator;
use ArrayObject;
use App\Facades\PageParserFacade as PageParser;
use App\Models\PageModel as Page;
......@@ -16,20 +18,25 @@ use App\Models\PageModel as Page;
*/
class PageRepository
{
/** ordering */
const ORDER_BY_ASC = 'asc';
const ORDER_BY_DESC = 'desc';
/** exceptions */
const EXCEPTION_FILE_NOT_FOUND = 'PageRepository - File not found';
// regex to get current filepath
/** regex to get current filepath */
const REGEX_FILEPATH = '/\..*+$/';
// path for md-files
/** directory for md-files */
private $repositoryPath;
// default parameters for find
/** default paramters */
private $parameters = [
'parent' => ''
];
// default options for find
/** default options */
private $options = [
'offset' => 0,
'limit' => 10
......@@ -62,32 +69,18 @@ class PageRepository
// and render markdown
if ($file) {
$page = PageParser::toObject($slug, $file);
$page->render();
}
return $page;
}
/**
* find pages
*
* @param [type] $filepath [description]
* @return [type] [description]
* @param
* @param string $datetime
*/
protected function getSlug($filepath)
{
$slug = str_replace('.md', '', $filepath);
$slug = str_replace($this->repositoryPath, '', $slug);
return $slug;
}
/**
* find pages
*
* @param
* @param string $datetime
*/
public function find($parameters = [], $options = [])
public function find($parameters = [], $options = [])
{
// merge with defaults
$parameters = array_merge($this->parameters, $parameters);
......@@ -97,60 +90,125 @@ class PageRepository
$path = $this->repositoryPath.'/'.$parameters['parent'];
unset($parameters['parent']);
// results of pages
$pages = [];
$pages = $this->getPages($path, $parameters);
// counter for page and offset
$i = 0;
$offset = 0;
return $pages;
}
// getting files from parent
foreach(glob($path.'*') as $filepath) {
/**
* calculate current page with offset and limit
*
* @param Array $parameters
* @param Array $options
* @return Array
*/
public function paginate(Array $parameters, Array $options)
{
$options = array_merge($this->options, $options);
$options['offset'] = ($options['page'] - 1) * $options['limit'];
unset($options['page']);
return $this->find($parameters, $options);
}
/**
*
* @param string $filePath
* @return string
*/
protected function parseSlug($filePathname)
{
$slug = str_replace('.md', '', $filePathname);
$slug = str_replace($this->repositoryPath, '', $slug);
return $slug;
}
/**
*
*
* @param string $filePath
* @param array $parameters
* @param array $options
* @return array
*/
protected function getPages($filePath, $parameters, $options = [])
{
$pages = [];
// @TODO is directory getting children
if (is_dir($filepath)) {
// create DirectoryIterator to search directory
$directoryIterator = new DirectoryIterator($filePath);
foreach($directoryIterator as $fileInfo) {
// skip if dot
if ($fileInfo->isDot()) {
continue;
}
$file = file_get_contents($filepath);
// @TODO recursiv for children
if ($fileInfo->isDir()) {
continue;
}
$slug = $this->getSlug($filepath);
// get file, parse slug and create object
$slug = $this->parseSlug($fileInfo->getPathname());
$file = file_get_contents($fileInfo->getPathname());
$page = PageParser::toObject($slug, $file);
// where to check if page, if page found, raise $i
$page = $this->where($parameters, $page);
// where
$page = $this->where($page, $parameters);
if ($page) {
if ($options['offset'] === 0 ||
($options['offset'] !== 0 && $offset >= $options['offset'])) {
$pages[] = $page;
$i++;
} else if ($options['offset'] !== 0) {
$offset++;
}
$pages[] = $page;
}
}
// break if limit is reached
if ($i >= $options['limit']) {
break;
}
// if there is more than one page and orderBy is set
if (count($pages) > 1 && isset($options['orderBy'])) {
$pages = $this->orderBy(
$pages,
key($options['orderBy']),
current($options['orderBy'])
);
}
return $pages;
}
$pages = $this->limit($pages, $options);
return $pages;
}
/**
* calculate current page with offset and limit
*
* @param Array $parameters
* @param Array $options
* @param $limit [description]
* @param integer $offset [description]
* @return Array
*/
public function pagination(Array $parameters, Array $options)
protected function limit($pages, $limit, $offset = 0)
{
$options['offset'] = ($options['page'] - 1) * $options['limit'];
unset($options['page']);
$results = [];
return $this->find($parameters, $options);
$i = 0;
$j = 0;
foreach($pages as $page) {
if ($page) {
if ($offset === 0 ||
($offset !== 0 && $j >= $offset)) {
$results[] = $page;
$i++;
} else if ($offset !== 0) {
$j++;
}
}
// break if limit is reached
if ($i >= $limit) {
break;
}
}
return $results;
}
/**
......@@ -160,7 +218,7 @@ class PageRepository
* @param Page $page
* @return mixed
*/
private function where($parameters, $page)
protected function where($page, $parameters)
{
$result = NULL;
......@@ -175,30 +233,71 @@ class PageRepository
return $result;
}
/**
* orderBy pages with usort
*
* @param array $pages
* @param string $key
* @param string $direction
* @return array
*/
protected function orderBy($pages, $key, $direction = self::ORDER_BY_ASC)
{
usort($pages, function($a, $b) use ($key) {
$result = 0;
if (isset($a->data[$key]) && isset($b->data[$key])) {
if ($direction === self::ORDER_BY_ASC) {
if ($a->data[$key] > $b->data[$key]) {
$result = 0;
}
} else if ($direction === self::ORDER_BY_DESC) {
if ($a->data[$key] < $b->data[$key]) {
$result = 1;
}
} else {
throw Exception('OrderBy - Direction '.$direction.' not found');
}
return $result;
} else {
throw Exception('OrderBy - Key in $page->data not found');
}
return $result;
});
return $pages;
}
/**
* get file with slug
* get file with slug from repository
*
* @param string $slug
* @param string $repositoryPath
* @return string
*/
private function getFile($slug = NULL, $repositoryPath)
private function getFile($slug, $repositoryPath)
{
// file
$file = NULL;
// path
$path = $repositoryPath.'/'.$slug.'.md';
// path of file, first try with slug
$filePath = $repositoryPath.'/'.$slug.'.md';
if (file_exists($path)) {
$file = file_get_contents($path);
if (file_exists($filePath)) {
$file = file_get_contents($filePath);
} else {
if ($slug !== '') {
$slug = '/'.$slug;
}
$path = $repositoryPath.$slug.'/index.md';
$filePath = $repositoryPath.$slug.'/index.md';
if (file_exists($path)) {
$file = file_get_contents($path);
if (file_exists($filePath)) {
$file = file_get_contents($filePath);
}
}
......
......@@ -78,6 +78,7 @@ $app->routeMiddleware([
$app->register(App\Providers\PageRepositoryServiceProvider::class);
$app->register(App\Providers\PageParserServiceProvider::class);
$app->register(App\Providers\ViewHelperServiceProvider::class);
/*
|--------------------------------------------------------------------------
......
{
"title": "At vero eos et accusam et justo duo dolores et ea rebum",
"view": "post",
"type": "post",
"publishedAt": "01-08-2016 12:10"
}
Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat.
Sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
Diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus.
{
"title": "Eos et accusam et justo duo dolores",
"view": "post",
"type": "post",
"publishedAt": "01-05-2016 12:10"
}
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
Sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
{
"title": "Et Eos accusam et justo duo dolores",
"view": "post",
"type": "post",
"publishedAt": "08-05-2016 12:10"
}
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
Sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
{
"title": "First",
"view": "post",
"type": "post",
"publishedAt": "01-05-2016 12:10"
}
Something is missing
{
"title": "Laoreet tincidunt ut dolore magna aliquam erat volutpat",
"view": "post",
"type": "post",
"publishedAt": "03-09-2016 14:03"
}
Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod.
Tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis.
{
"title": "Second",
"view": "post",
"type": "post",
"publishedAt": "01-08-2016 12:10"
}
Something is missing
{
"title": "Home",
"meta": {
"description": "This is Home"
},
"view": "page"
}
Home
{
"title": "Nix",
"meta": {
"description": "This is Home"
},
"view": "page"
}
dddd
{
"title": "Third",
"view": "post",
"type": "post",
"publishedAt": "01-09-2016 12:10"
}
Something is missing
{
"title": "Tincidunt ut laoreet dolore magna aliquam erat volutpat",
"view": "post",
"type": "post",
"publishedAt": "01-09-2016 12:10"
}
Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod.
Tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis.
{
"title": "Vero at eos et accusam et justo duo dolores et ea rebum",
"view": "post",
"type": "post",
"publishedAt": "23-10-2016 22:15"
}
Consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat
Sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
Diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus.
@extends('simple.layout')
@section('content')
{!! $page->html !!}
{!! $page->html() !!}
@endsection
......@@ -3,8 +3,12 @@
@section('content')
@inject('pageRepository', 'App\PageRepository')
@inject('pageService', 'App\PageService')
@inject('viewHelper', 'App\ViewHelper')
@foreach($pageRepository->pagination(['type' => 'post'], ['limit' => 2, 'page' => $pageService->getPage()]) as $post)
@foreach($pageRepository->paginate(
['type' => 'post'],
['orderBy' => ['publishedAt' => 'desc'], 'limit' => '5', 'page' => $pageService->getPage()]) as $post
)
<article class="post">
<header class="post__header">
<h2 class="post__title">
......@@ -22,7 +26,7 @@
@endif
</header>
<div class="post__content">
{!! $post->html !!}
{!! $viewHelper->truncated($post->html()) !!}
<a class="post__more" href="{{ $post->slug }}">
More
</a>
......
@extends('simple.layout')
@section('content')
{!! $page->html !!}
{!! $page->html() !!}
@endsection
@extends('simple.layout')
@section('content')
{!! $page->html !!}
{!! $page->html() !!}
@endsection
......@@ -17,12 +17,12 @@ $app->get('/', [
// get the hole url as slug
$app->group(['middleware' => 'parameters'], function() use ($app) {
$app->get('/{slug:[0-9\/a-z,]+}', [
$app->get('/{slug:[0-9\/a-z,-]+}', [
'as' => 'page.show', 'uses' => 'PageController@showAction'
]);
});
// any other router will be result in a 404
$app->get('{any}', function() {
return abort(404);
$app->get('{any}', function() use ($app) {
return redirect()->route('page.show', ['slug' => '404']);
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment