Skip to content
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
15 changes: 15 additions & 0 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace TwigBridge;

use Illuminate\View\Factory as LaravelFactory;
use Illuminate\View\ViewServiceProvider;
use InvalidArgumentException;
use Twig\Environment;
Expand All @@ -22,6 +23,7 @@
use Twig\Loader\ArrayLoader;
use Twig\Loader\ChainLoader;
use Twig\RuntimeLoader\ContainerRuntimeLoader;
use TwigBridge\View\Factory;

/**
* Bootstrap Laravel TwigBridge.
Expand Down Expand Up @@ -284,6 +286,19 @@ function () {
$this->app['config']->get('twigbridge.twig.globals', [])
);
});

$this->app->extend('view', function (LaravelFactory $view, $app) {
$factory = new Factory($view->getEngineResolver(), $view->getFinder(), $view->getDispatcher());

// We will also set the container instance on this view environment since the
// view composers may be classes registered in the container, which allows
// for great testable, flexible composers for the application developer.
$factory->setContainer($app);

$factory->share('app', $app);

return $factory;
});
}

/**
Expand Down
19 changes: 19 additions & 0 deletions src/View/Factory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace TwigBridge\View;

use Illuminate\View\Factory as LaravelFactory;
use TwigBridge\Engine\Twig;

class Factory extends LaravelFactory
{
protected function viewInstance($view, $path, $data)
{
$engine = $this->getEngineFromPath($path);
if ($engine instanceof Twig) {
return new View($this, $engine, $view, $path, $data);
}

return parent::viewInstance($view, $path, $data);
}
}
33 changes: 33 additions & 0 deletions src/View/View.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace TwigBridge\View;

use Illuminate\View\View as LaravelView;
use Throwable;

/**
* @property \TwigBridge\Engine\Twig $engine
*/
class View extends LaravelView
{
public function fragment($fragment)
{
try {
$this->factory->incrementRender();
$this->factory->callComposer($this);

/** @var \TwigBridge\Engine\Compiler */
$compiler = $this->engine->getCompiler();
$contents = $compiler->load($this->path)->renderBlock($fragment, $this->gatherData());

$this->factory->decrementRender();
$this->factory->flushStateIfDoneRendering();

return $contents;
} catch (Throwable $e) {
$this->factory->flushState();

throw $e;
}
}
}