Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LinkGenerator: extract interface #273

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"nette/component-model": "^3.0",
"nette/http": "^3.0.2",
"nette/routing": "~3.0.0",
"nette/utils": "^3.2"
"nette/utils": "^3.2.1"
},
"suggest": {
"nette/forms": "Allows to use Nette\\Application\\UI\\Form",
Expand Down
33 changes: 17 additions & 16 deletions src/Application/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use Nette;
use Nette\Routing\Router;
use Nette\Utils\Arrays;


/**
Expand All @@ -30,22 +31,22 @@ class Application
public $errorPresenter;

/** @var callable[]&(callable(Application $sender): void)[]; Occurs before the application loads presenter */
public $onStartup;
public $onStartup = [];

/** @var callable[]&(callable(Application $sender, \Throwable $e = null): void)[]; Occurs before the application shuts down */
public $onShutdown;
public $onShutdown = [];

/** @var callable[]&(callable(Application $sender, Request $request): void)[]; Occurs when a new request is received */
public $onRequest;
public $onRequest = [];

/** @var callable[]&(callable(Application $sender, IPresenter $presenter): void)[]; Occurs when a presenter is created */
public $onPresenter;
public $onPresenter = [];

/** @var callable[]&(callable(Application $sender, Response $response): void)[]; Occurs when a new response is ready for dispatch */
public $onResponse;
public $onResponse = [];

/** @var callable[]&(callable(Application $sender, \Throwable $e): void)[]; Occurs when an unhandled exception occurs in the application */
public $onError;
public $onError = [];

/** @var Request[] */
private $requests = [];
Expand Down Expand Up @@ -85,23 +86,23 @@ public function __construct(
public function run(): void
{
try {
$this->onStartup($this);
Arrays::invoke($this->onStartup, $this);
$this->processRequest($this->createInitialRequest());
$this->onShutdown($this);
Arrays::invoke($this->onShutdown, $this);

} catch (\Throwable $e) {
$this->onError($this, $e);
Arrays::invoke($this->onError, $this, $e);
if ($this->catchExceptions && $this->errorPresenter) {
try {
$this->processException($e);
$this->onShutdown($this, $e);
Arrays::invoke($this->onShutdown, $this, $e);
return;

} catch (\Throwable $e) {
$this->onError($this, $e);
Arrays::invoke($this->onError, $this, $e);
}
}
$this->onShutdown($this, $e);
Arrays::invoke($this->onShutdown, $this, $e);
throw $e;
}
}
Expand Down Expand Up @@ -140,7 +141,7 @@ public function processRequest(Request $request): void
}

$this->requests[] = $request;
$this->onRequest($this, $request);
Arrays::invoke($this->onRequest, $this, $request);

if (
!$request->isMethod($request::FORWARD)
Expand All @@ -156,15 +157,15 @@ public function processRequest(Request $request): void
? $e
: new BadRequestException($e->getMessage(), 0, $e);
}
$this->onPresenter($this, $this->presenter);
Arrays::invoke($this->onPresenter, $this, $this->presenter);
$response = $this->presenter->run(clone $request);

if ($response instanceof Responses\ForwardResponse) {
$request = $response->getRequest();
goto process;
}

$this->onResponse($this, $response);
Arrays::invoke($this->onResponse, $this, $response);
$response->send($this->httpRequest, $this->httpResponse);
}

Expand All @@ -178,7 +179,7 @@ public function processException(\Throwable $e): void
$this->httpResponse->setCode($e instanceof BadRequestException ? ($e->getHttpCode() ?: 404) : 500);
}

$args = ['exception' => $e, 'request' => end($this->requests) ?: null];
$args = ['exception' => $e, 'request' => Arrays::last($this->requests) ?: null];
if ($this->presenter instanceof UI\Presenter) {
try {
$this->presenter->forward(":$this->errorPresenter:", $args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
/**
* Link generator.
*/
final class LinkGenerator
final class DefaultLinkGenerator implements ILinkGenerator
{
use Nette\SmartObject;

Expand Down Expand Up @@ -93,7 +93,7 @@ public function link(string $dest, array $params = []): string
}


public function withReferenceUrl(string $url): self
public function withReferenceUrl(string $url): ILinkGenerator
{
return new self(
$this->router,
Expand Down
26 changes: 26 additions & 0 deletions src/Application/ILinkGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/

declare(strict_types=1);

namespace Nette\Application;


/**
* Link generator.
*/
interface ILinkGenerator
{
/**
* Generates URL to presenter.
* @param string $dest in format "[[[module:]presenter:]action] [#fragment]"
* @throws UI\InvalidLinkException
*/
public function link(string $dest, array $params = []): string;

public function withReferenceUrl(string $url): ILinkGenerator;
}
16 changes: 14 additions & 2 deletions src/Application/UI/Component.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ abstract class Component extends Nette\ComponentModel\Container implements Signa
use Nette\ComponentModel\ArrayAccess;

/** @var callable[]&(callable(Component $sender): void)[]; Occurs when component is attached to presenter */
public $onAnchor;
public $onAnchor = [];

/** @var array */
protected $params = [];
Expand Down Expand Up @@ -73,12 +73,24 @@ public function getUniqueId(): string
}



protected function createComponent(string $name): ?Nette\ComponentModel\IComponent
{
$res = parent::createComponent($name);
if (!$res instanceof SignalReceiver && !$res instanceof StatePersistent) {
$type = get_class($res);
trigger_error("It seems that component '$name' of type $type is not intended to for in the Presenter.", E_USER_NOTICE);
}
return $res;
}


protected function validateParent(Nette\ComponentModel\IContainer $parent): void
{
parent::validateParent($parent);
$this->monitor(Presenter::class, function (Presenter $presenter): void {
$this->loadState($presenter->popGlobalParameters($this->getUniqueId()));
$this->onAnchor($this);
Nette\Utils\Arrays::invoke($this->onAnchor, $this);
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/Application/UI/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
class Form extends Nette\Forms\Form implements SignalReceiver
{
/** @var callable[]&(callable(Form $sender): void)[]; Occurs when form is attached to presenter */
public $onAnchor;
public $onAnchor = [];

/** @var bool */
private $sameSiteProtection = true;
Expand Down Expand Up @@ -57,7 +57,7 @@ protected function validateParent(Nette\ComponentModel\IContainer $parent): void
}
}

$this->onAnchor($this);
Nette\Utils\Arrays::invoke($this->onAnchor, $this);
});
}

Expand Down
17 changes: 9 additions & 8 deletions src/Application/UI/Presenter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Nette\Application\Helpers;
use Nette\Application\Responses;
use Nette\Http;
use Nette\Utils\Arrays;


/**
Expand Down Expand Up @@ -49,13 +50,13 @@ abstract class Presenter extends Control implements Application\IPresenter
public $invalidLinkMode;

/** @var callable[]&(callable(Presenter $sender): void)[]; Occurs when the presenter is starting */
public $onStartup;
public $onStartup = [];

/** @var callable[]&(callable(Presenter $sender): void)[]; Occurs when the presenter is rendering after beforeRender */
public $onRender;
public $onRender = [];

/** @var callable[]&(callable(Presenter $sender, Response $response): void)[]; Occurs when the presenter is shutting down */
public $onShutdown;
public $onShutdown = [];

/** @var bool automatically call canonicalize() */
public $autoCanonicalize = true;
Expand Down Expand Up @@ -203,7 +204,7 @@ public function run(Application\Request $request): Application\Response

$this->initGlobalParameters();
$this->checkRequirements(static::getReflection());
$this->onStartup($this);
Arrays::invoke($this->onStartup, $this);
$this->startup();
if (!$this->startupCheck) {
$class = static::getReflection()->getMethod('startup')->getDeclaringClass()->getName();
Expand All @@ -230,7 +231,7 @@ public function run(Application\Request $request): Application\Response

// RENDERING VIEW
$this->beforeRender();
$this->onRender($this);
Arrays::invoke($this->onRender, $this);
// calls $this->render<View>()
$this->tryCall(static::formatRenderMethod($this->view), $this->params);
$this->afterRender();
Expand Down Expand Up @@ -268,7 +269,7 @@ public function run(Application\Request $request): Application\Response
$this->response = new Responses\VoidResponse;
}

$this->onShutdown($this, $this->response);
Arrays::invoke($this->onShutdown, $this, $this->response);
$this->shutdown($this->response);

return $this->response;
Expand Down Expand Up @@ -462,7 +463,7 @@ public function sendTemplate(Template $template = null): void
}

if (!$template->getFile()) {
$file = strtr(reset($files), '/', DIRECTORY_SEPARATOR);
$file = strtr(Arrays::first($files), '/', DIRECTORY_SEPARATOR);
$this->error("Page not found. Missing template '$file'.");
}
}
Expand All @@ -488,7 +489,7 @@ public function findLayoutTemplateFile(): ?string
}

if ($this->layout) {
$file = strtr(reset($files), '/', DIRECTORY_SEPARATOR);
$file = strtr(Arrays::first($files), '/', DIRECTORY_SEPARATOR);
throw new Nette\FileNotFoundException("Layout not found. Missing template '$file'.");
}
return null;
Expand Down
3 changes: 2 additions & 1 deletion src/Bridges/ApplicationDI/ApplicationExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,8 @@ public function loadConfiguration()
}

$builder->addDefinition($this->prefix('linkGenerator'))
->setFactory(Nette\Application\LinkGenerator::class, [
->setType(Nette\Application\ILinkGenerator::class)
->setFactory(Nette\Application\DefaultLinkGenerator::class, [
1 => new Definitions\Statement([new Definitions\Statement('@Nette\Http\IRequest::getUrl'), 'withoutUserInfo']),
]);

Expand Down
57 changes: 43 additions & 14 deletions src/Bridges/ApplicationDI/LatteExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

use Latte;
use Nette;
use Nette\Bridges\ApplicationLatte;
use Nette\Schema\Expect;
use Tracy;


/**
Expand All @@ -29,20 +32,18 @@ public function __construct(string $tempDir, bool $debugMode = false)
{
$this->tempDir = $tempDir;
$this->debugMode = $debugMode;
}

$this->config = new class {
/** @var bool */
public $xhtml = false;

/** @var string[] */
public $macros = [];

/** @var ?string */
public $templateClass;

/** @var bool */
public $strictTypes = false;
};
public function getConfigSchema(): Nette\Schema\Schema
{
return Expect::structure([
'debugger' => Expect::anyOf(true, false, 'all'),
'xhtml' => Expect::bool(false)->deprecated(),
'macros' => Expect::arrayOf('string'),
'templateClass' => Expect::string(),
'strictTypes' => Expect::bool(false),
]);
}


Expand All @@ -56,7 +57,7 @@ public function loadConfiguration()
$builder = $this->getContainerBuilder();

$latteFactory = $builder->addFactoryDefinition($this->prefix('latteFactory'))
->setImplement(Nette\Bridges\ApplicationLatte\LatteFactory::class)
->setImplement(ApplicationLatte\LatteFactory::class)
->getResultDefinition()
->setFactory(Latte\Engine::class)
->addSetup('setTempDirectory', [$this->tempDir])
Expand All @@ -70,7 +71,7 @@ public function loadConfiguration()

$builder->addDefinition($this->prefix('templateFactory'))
->setType(Nette\Application\UI\TemplateFactory::class)
->setFactory(Nette\Bridges\ApplicationLatte\TemplateFactory::class)
->setFactory(ApplicationLatte\TemplateFactory::class)
->setArguments(['templateClass' => $config->templateClass]);

foreach ($config->macros as $macro) {
Expand All @@ -84,6 +85,34 @@ public function loadConfiguration()
}


public function beforeCompile()
{
$builder = $this->getContainerBuilder();

if (
$this->debugMode
&& ($this->config->debugger ?? $builder->getByType(Tracy\Bar::class))
&& class_exists(Latte\Bridges\Tracy\LattePanel::class)
) {
$factory = $builder->getDefinition($this->prefix('templateFactory'));
$factory->addSetup([self::class, 'initLattePanel'], [$factory, 'all' => $this->config->debugger === 'all']);
}
}


public static function initLattePanel(ApplicationLatte\TemplateFactory $factory, Tracy\Bar $bar, bool $all = false)
{
$factory->onCreate[] = function (ApplicationLatte\Template $template) use ($bar, $all) {
if ($all || $template->control instanceof Nette\Application\UI\Presenter) {
$bar->addPanel(new Latte\Bridges\Tracy\LattePanel(
$template->getLatte(),
$all ? (new \ReflectionObject($template->control))->getShortName() : ''
));
}
};
}


public function addMacro(string $macro): void
{
$builder = $this->getContainerBuilder();
Expand Down
Loading