Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
blat committed Jul 31, 2022
0 parents commit 0304512
Show file tree
Hide file tree
Showing 5 changed files with 282 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
composer.lock
vendor
80 changes: 80 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Slim Framework Plates View

This is a Slim Framework view helper built on top of the Plates templating component. You can use this component to create and render templates in your Slim Framework application.

## Install

Via [Composer](https://getcomposer.org/)

```bash
$ composer require blat/slim-plates
```

Requires Slim Framework 4, Plates 3 and PHP 7.4 or newer.

## Usage

```php
use DI\Container;
use Slim\Factory\AppFactory;
use Slim\Views\Plates;
use Slim\Views\PlatesExtension;

require __DIR__ . '/vendor/autoload.php';

// Create Container
$container = new Container();
AppFactory::setContainer($container);

// Set Plates View in Container
$container->set('view', function () {
return new Plates(__DIR__ . '/../templates');
});

// Create App
$app = AppFactory::create();

// Add Plates Extension Middleware
$app->add(new PlatesExtension($app));

// Define named route
$app->get('/hello/{name}', function ($request, $response, $args) {
return $this->get('view')->render($response, 'profile', [
'name' => $args['name']
]);
})->setName('profile');

// Run app
$app->run();
```

## Custom template functions

`PlatesExtension` provides these functions to your Plates templates:

* `urlFor()` - returns the URL for a given route. e.g.: /hello/world
* `fullUrFor()` - returns the URL for a given route. e.g.: http://www.example.com/hello/world
* `isCurrentUrl()` - returns true is the provided route name and parameters are valid for the current path.
* `currentUrl()` - returns the current path, with or without the query string.
* `basePath()` - returns the base path.

You can use `urlFor` to generate complete URLs to any Slim application named route and use `isCurrentUrl` to determine if you need to mark a link as active as shown in this example Plates template:

```php
<?php $this->layout('template') ?>

<h1>User List</h1>
<ul>
<li><a href="<?= $this->urlFor('profile', ['name' => 'josh']) ?>" <?php if ($this->isCurrentUrl('profile', ['name' => 'josh']): ?>}class="active"<?php endif ?>}>Josh</a></li>
<li><a href="<?= $this->urlFor('profile', ['name' => 'andrew']) ?>">Andrew</a></li>
</ul>
```

## The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

26 changes: 26 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "blat/slim-plates",
"type": "library",
"description": "Slim Framework 4 view helper built on top of the Plates templating component",
"keywords": ["slim","framework","view","template","templating","plates"],
"license": "MIT",
"authors": [
{
"name": "Mickael BLATIERE",
"email": "[email protected]",
"homepage": "https://blizzart.net"
}
],
"require": {
"league/plates": "^3.4",
"php": "^7.4 || ^8.0",
"psr/http-message": "^1.0",
"slim/slim": "^4.10"
},
"autoload": {
"psr-4": {
"Slim\\Views\\": "src"
}
}
}

51 changes: 51 additions & 0 deletions src/Plates.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Slim\Views;

use League\Plates\Engine;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class Plates
{
protected Engine $engine;

/**
* @param ...mixed $settings
*/
public function __construct(...$settings)
{
$this->engine = new Engine(...$settings);
}

/**
* Access forward to Engine methods
*
* @param string $name
* @param array $args
*
* @return mixed
*/
public function __call(string $name, array $args): mixed
{
return call_user_func_array([$this->engine, $name], $args);
}

/**
* Output rendered template
*
* @param ResponseInterface $response
* @param string $template Template pathname relative to templates directory
* @param array<string, mixed> $data Associative array of template variables
*
* @return ResponseInterface
*/
public function render(ResponseInterface $response, string $template, array $data = []): ResponseInterface
{
$output = $this->engine->render($template, $data);
$response->getBody()->write($output);
return $response;
}

}
123 changes: 123 additions & 0 deletions src/PlatesExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
<?php

namespace Slim\Views;

use League\Plates\Engine;
use League\Plates\Extension\ExtensionInterface;
use Psr\Http\Message\UriInterface;
use Psr\Http\Server\MiddlewareInterface;
use Slim\App;

class PlatesExtension implements ExtensionInterface, MiddlewareInterface
{

protected App $app;
protected UriInterface $uri;

/**
* PlatesExtension constructor.
*
* @param App $app
*/
public function __construct(App $app)
{
$this->app = $app;
}

/**
* Process an incoming server request.
*
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
*
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->uri = $request->getUri();
$this->app->getContainer()->get('view')->loadExtension($this);
return $handler->handle($request);
}

/**
* @param Engine $engine
*/
public function register(Engine $engine)
{
foreach (['urlFor', 'fullUrlFor', 'isCurrentUrl', 'getCurrentUrl', 'getBasePath'] as $name) {
$engine->registerFunction($name, [$this, $name]);
}
}

/**
* Get the url for a named route
*
* @param string $routeName Route name
* @param array<string, string> $data Route placeholders
* @param array<string, string> $queryParams Query parameters
*
* @return string
*/
public function urlFor(string $routeName, array $data = [], array $queryParams = []): string
{
return $this->app->getRouteCollector()->getRouteParser()->urlFor($routeName, $data, $queryParams);
}

/**
* Get the full url for a named route
*
* @param string $routeName Route name
* @param array<string, string> $data Route placeholders
* @param array<string, string> $queryParams Query parameters
*
* @return string
*/
public function fullUrlFor(string $routeName, array $data = [], array $queryParams = []): string
{
return $this->app->getRouteCollector()->getRouteParser()->fullUrlFor($this->uri, $routeName, $data, $queryParams);
}

/**
* @param string $routeName Route name
* @param array<string, string> $data Route placeholders
*
* @return bool
*/
public function isCurrentUrl(string $routeName, array $data = []): bool
{
$currentUrl = $this->getBasePath() . $this->uri->getPath();
$result = $this->app->getRouteCollector()->getRouteParser()->urlFor($routeName, $data);

return $result === $currentUrl;
}

/**
* Get current path on given Uri
*
* @param bool $withQueryString
*
* @return string
*/
public function getCurrentUrl(bool $withQueryString = false): string
{
$currentUrl = $this->getBasePath() . $this->uri->getPath();
$query = $this->uri->getQuery();

if ($withQueryString && !empty($query)) {
$currentUrl .= '?' . $query;
}

return $currentUrl;
}

/**
* Get the base path
*
* @return string
*/
public function getBasePath(): string
{
return $this->app->getBasePath();
}

}

0 comments on commit 0304512

Please sign in to comment.