1<?php 2 3namespace Tightenco\Ziggy; 4 5use Illuminate\Routing\Router; 6use function array_key_exists; 7 8class BladeRouteGenerator 9{ 10 public static $generated; 11 12 public $routePayload; 13 14 private $baseDomain; 15 private $basePort; 16 private $baseUrl; 17 private $baseProtocol; 18 private $router; 19 20 public function __construct(Router $router) 21 { 22 $this->router = $router; 23 } 24 25 public function getRoutePayload($group = false) 26 { 27 return RoutePayload::compile($this->router, $group); 28 } 29 30 public function generate($group = false, $nonce = false) 31 { 32 $json = $this->getRoutePayload($group)->toJson(); 33 $nonce = $nonce ? ' nonce="' . $nonce . '"' : ''; 34 35 if (static::$generated) { 36 return $this->generateMergeJavascript($json, $nonce); 37 } 38 39 $this->prepareDomain(); 40 41 $routeFunction = $this->getRouteFunction(); 42 43 $defaultParameters = method_exists(app('url'), 'getDefaultParameters') ? json_encode(app('url')->getDefaultParameters()) : '[]'; 44 45 static::$generated = true; 46 47 return <<<EOT 48<script type="text/javascript"{$nonce}> 49 var Ziggy = { 50 namedRoutes: $json, 51 baseUrl: '{$this->baseUrl}', 52 baseProtocol: '{$this->baseProtocol}', 53 baseDomain: '{$this->baseDomain}', 54 basePort: {$this->basePort}, 55 defaultParameters: $defaultParameters 56 }; 57 58 $routeFunction 59</script> 60EOT; 61 } 62 63 private function generateMergeJavascript($json, $nonce) 64 { 65 return <<<EOT 66<script type="text/javascript"{$nonce}> 67 (function() { 68 var routes = $json; 69 70 for (var name in routes) { 71 Ziggy.namedRoutes[name] = routes[name]; 72 } 73 })(); 74</script> 75EOT; 76 } 77 78 private function getRouteFilePath() 79 { 80 $isMin = app()->isLocal() ? '' : '.min'; 81 return __DIR__ . "/../dist/js/route{$isMin}.js"; 82 } 83 84 private function getRouteFunction() 85 { 86 if (config()->get('ziggy.skip-route-function')) { 87 return ''; 88 } 89 return file_get_contents($this->getRouteFilePath()); 90 } 91 92 private function prepareDomain() 93 { 94 $url = url('/'); 95 $parsedUrl = parse_url($url); 96 97 $this->baseUrl = $url . '/'; 98 $this->baseProtocol = array_key_exists('scheme', $parsedUrl) ? $parsedUrl['scheme'] : 'http'; 99 $this->baseDomain = array_key_exists('host', $parsedUrl) ? $parsedUrl['host'] : ''; 100 $this->basePort = array_key_exists('port', $parsedUrl) ? $parsedUrl['port'] : 'false'; 101 } 102} 103