Load a template by path

@param   string  $url      The template url
@throws \InvalidArgumentException If the template could not be located
@throws \RuntimeException         If the template could not be loaded
@return KTemplateAbstract
348381
public function loadFile($url)
    {
        //Locate the template
        $locator = $this->getObject('template.locator.factory')->createLocator($url);

        if (!$file = $locator->locate($url)) {
            throw new InvalidArgumentException(sprintf('The template "%s" cannot be located.', $url));
        }

        //Load the template
        if(!$source = file_get_contents($file)) {
            throw new RuntimeException(sprintf('The template "%s" cannot be loaded.', $file));
        }

        $this->_source = $source;

        return $this;
    }
359590
public function expand($url)
    {
        try {
            return $this->driver->expand($url);
        } catch (BadResponseException $e) {
            throw new Exceptions\InvalidResponseException($e->getMessage());
        } catch (InvalidApiResponseException $e) {
            throw new Exceptions\InvalidResponseException($e->getMessage());
        }
    }
187190
public function load(TemplateReferenceInterface $template)
    {
        $key = hash('sha256', $template->getLogicalName());
        $dir = $this->dir.\DIRECTORY_SEPARATOR.substr($key, 0, 2);
        $file = substr($key, 2).'.tpl';
        $path = $dir.\DIRECTORY_SEPARATOR.$file;

        if (is_file($path)) {
            if (null !== $this->logger) {
                $this->logger->debug('Fetching template from cache.', ['name' => $template->get('name')]);
            }

            return new FileStorage($path);
        }

        if (false === $storage = $this->loader->load($template)) {
            return false;
        }

        $content = $storage->getContent();

        if (!is_dir($dir) && !@mkdir($dir, 0777, true) && !is_dir($dir)) {
            throw new \RuntimeException(sprintf('Cache Loader was not able to create directory "%s"', $dir));
        }

        file_put_contents($path, $content);

        if (null !== $this->logger) {
            $this->logger->debug('Storing template in cache.', ['name' => $template->get('name')]);
        }

        return new FileStorage($path);
    }
647972
protected static function getTemplate($path)
    {
        if(file_exists($path))
            $template = file_get_contents($path);
        elseif(file_exists(__DIR__ . '/templates/' . $path))
            $template = file_get_contents(__DIR__ . '/templates/' . $path);
        else
            throw new \InvalidArgumentException('Template file not found.');

        return $template;
    }
756301
public function setUrl(string $url) : Request
    {
        $components = parse_url($url);

        if ($components === false) {
            throw new \InvalidArgumentException('The URL provided is not valid.');
        }

        if (! isset($components['scheme'])) {
            throw new \InvalidArgumentException('The URL must have a scheme.');
        }

        $scheme = strtolower($components['scheme']);

        if ($scheme !== 'http' && $scheme !== 'https') {
            throw new \InvalidArgumentException(sprintf('The URL scheme "%s" is not acceptable.', $scheme));
        }

        $isSecure = ($scheme === 'https');

        if (! isset($components['host'])) {
            throw new \InvalidArgumentException('The URL must have a host name.');
        }

        $host = $components['host'];

        if (isset($components['port'])) {
            $port = $components['port'];
            $hostHeader = $host . ':' . $port;
        } else {
            $port = ($isSecure ? 443 : 80);
            $hostHeader = $host;
        }

        $this->path = isset($components['path']) ? $components['path'] : '/';
        $requestUri = $this->path;

        if (isset($components['query'])) {
            $this->queryString = $components['query'];
            parse_str($this->queryString, $this->query);
            $requestUri .= '?' . $this->queryString;
        } else {
            $this->queryString = '';
            $this->query = [];
        }

        $this->setHeader('Host', $hostHeader);

        $this->host = $host;
        $this->port = $port;
        $this->isSecure = $isSecure;
        $this->requestUri = $requestUri;

        return $this;
    }
1164404
public function load($file)
    {
        if (!is_string($file) || !file_exists($file)) {
            throw new InvalidArgumentException('File must be a valid file.');
        }

        $data = include $file;

        if (!is_array($data)) {
            throw new RuntimeException('File did not return an array.');
        }

        return $this->set($data);
    }
890547
public static function createFromUrl($url)
    {
        $instance = new static();

        if (self::$generic_file->fetchUrl($url, null, $instance)) {
            return $instance;
        }

        return;
    }
309937
public static function isHttp(string $url)
    {
        $url = UrlHelper::validateUrl($url);

        $parsedUrl = parse_url($url);
        if ($parsedUrl === false) {
            throw new InvalidArgumentException("The provided url is not valid: $url");
        }

        return $parsedUrl["scheme"] === UrlHelper::HTTP_SCHEME;
    }
1263207
protected function initialize($url)
    {
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $parsedUrl = parse_url($url);

        if (false === filter_var($url, FILTER_VALIDATE_URL) || false === $parsedUrl) {
            throw new InvalidArgumentException(sprintf('URL "%s" seriously malformed.', $url));
        }

        $parsedUrl = $parsedUrl + [
                'scheme' => '',
                'host' => '',
                'port' => null,
                'user' => '',
                'pass' => '',
                'path' => '',
                'fragment' => '',
                'query' => ''
            ];

        $this->scheme = $this->filterScheme($parsedUrl['scheme']);
        $this->host = $this->filterHost($parsedUrl['host']);
        $this->port = $this->filterPort($parsedUrl['port']);
        $this->path = $this->filterPath($parsedUrl['path']);
        $this->query = $this->filterQuery($parsedUrl['query']);
        $this->fragment = $this->filterFragment($parsedUrl['fragment']);

        if ($parsedUrl['user']) {
            if ($parsedUrl['pass']) {
                $this->userInfo = $parsedUrl['user'] . ':' . $parsedUrl['pass'];
            } else {
                $this->userInfo = $parsedUrl['user'];
            }
        }
    }
241466
protected function load($name)
    {
        if ($name instanceof Template) {
            return $name;
        }

        try {
            return $this->environment->loadTemplate((string) $name);
        } catch (LoaderError $e) {
            throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
        }
    }
483488
private function loadImageFromURL($url)
    {
        $image = $this->fetchImageContentFromURL($url);

        if (empty($image)) {
            return;
        }

        if (Utils::isJPGResource($image)) {
            $this->filename = $url;
            $this->extension = 'jpg';
            $this->type = IMAGETYPE_JPEG;
        }

        if (Utils::isPNGResource($image)) {
            $this->filename = $url;
            $this->extension = 'png';
            $this->type = IMAGETYPE_PNG;
        }

        $this->from = 'external';
        $this->resource = imagecreatefromstring($image);
        $this->width = $this->boxWidth = imagesx($this->resource);
        $this->height = $this->boxHeight = imagesy($this->resource);
    }
1372912
public function setUrl($url)
    {
        if (!is_null($url) && !$url instanceof KHttpUrl) {
            throw new InvalidArgumentException('Invalid url type.');
        }

        $this->url = $url;
        return $this;
    }
34335
public function addUrl(Url $url)
    {
        if ($this->isFull()) {
            throw new \RuntimeException('The urlset limit has been exceeded');
        }

        $urlXml = $url->toXml();
        $this->appendXML($urlXml);

        //add unknown custom namespaces
        $this->customNamespaces = array_merge($this->customNamespaces, $url->getCustomNamespaces());

        //---------------------
        //Check limits
        if ($this->countItems++ >= self::LIMIT_ITEMS) {
            $this->limitItemsReached = true;
        }

        $urlLength = strlen($urlXml);
        $this->countBytes += $urlLength;

        if ($this->countBytes + $urlLength + strlen($this->getStructureXml()) > self::LIMIT_BYTES) {
            //we suppose the next url is almost the same length and cannot be added
            //plus we keep 500kB (@see self::LIMIT_BYTES)
            //... beware of numerous images set in url
            $this->limitBytesReached = true;
        }
        //---------------------
    }
657645
public function setUrl($url)
    {
        // validate url
        if (filter_var($url, FILTER_VALIDATE_URL)) {
            $this->url = $url;
        } else {
            throw new InvalidUrlException('"' . $url . '" is not a valid URL');
        }

        return $this;
    }
828599
private function loadXML($url) {
		if (!file_exists($url)) {
			throw new \n2n\log4php\LoggerException("File [$url] does not exist.");
		}

		libxml_clear_errors();
		$oldValue = libxml_use_internal_errors(true);
		
		// Load XML
		$xml = @simplexml_load_file($url);
		if ($xml === false) {
			
			$errorStr = "";
			foreach(libxml_get_errors() as $error) {
				$errorStr .= "[" . $error->file . "] line " . $error->line . " : " . $error->message;
			}
			
			throw new \n2n\log4php\LoggerException("Error loading configuration file: " . trim($errorStr));
		}
		
		libxml_clear_errors();
		libxml_use_internal_errors($oldValue);
		
		return $xml;
	}
196414
public function findByUrl($url)
    {
        $this->url = $url;
        $url = RouterHelper::normalizeUrl($url);

        /**
         * @event cms.router.beforeRoute
         * Fires before the CMS Router handles a route
         *
         * Example usage:
         *
         *     Event::listen('cms.router.beforeRoute', function ((string) $url, (\Cms\Classes\Router) $thisRouterInstance) {
         *         return \Cms\Classes\Page::loadCached('trick-theme-code', 'page-file-name');
         *     });
         *
         */
        $apiResult = Event::fire('cms.router.beforeRoute', [$url, $this], true);
        if ($apiResult !== null) {
            return $apiResult;
        }

        for ($pass = 1; $pass <= 2; $pass++) {
            $fileName = null;
            $urlList = [];

            $cacheable = Config::get('cms.enableRoutesCache');
            if ($cacheable) {
                $fileName = $this->getCachedUrlFileName($url, $urlList);
                if (is_array($fileName)) {
                    list($fileName, $this->parameters) = $fileName;
                }
            }

            /*
             * Find the page by URL and cache the route
             */
            if (!$fileName) {
                $router = $this->getRouterObject();
                if ($router->match($url)) {
                    $this->parameters = $router->getParameters();

                    $fileName = $router->matchedRoute();

                    if ($cacheable) {
                        if (!$urlList || !is_array($urlList)) {
                            $urlList = [];
                        }

                        $urlList[$url] = !empty($this->parameters)
                            ? [$fileName, $this->parameters]
                            : $fileName;

                        $key = $this->getUrlListCacheKey();
                        Cache::put(
                            $key,
                            base64_encode(serialize($urlList)),
                            Config::get('cms.urlCacheTtl', 1)
                        );
                    }
                }
            }

            /*
             * Return the page
             */
            if ($fileName) {
                if (($page = Page::loadCached($this->theme, $fileName)) === null) {
                    /*
                     * If the page was not found on the disk, clear the URL cache
                     * and repeat the routing process.
                     */
                    if ($pass == 1) {
                        $this->clearCache();
                        continue;
                    }

                    return null;
                }

                return $page;
            }

            return null;
        }
    }
460768
public function loadFile($path)
    {
        if (!is_string($path)) {
            throw new InvalidArgumentException(
                'File must be a string'
            );
        }

        if (!file_exists($path)) {
            throw new InvalidArgumentException(
                sprintf('File "%s" does not exist', $path)
            );
        }

        $ext = pathinfo($path, PATHINFO_EXTENSION);
        switch ($ext) {
            case 'php':
                return $this->loadPhpFile($path);

            case 'json':
                return $this->loadJsonFile($path);

            case 'ini':
                return $this->loadIniFile($path);

            case 'yml':
            case 'yaml':
                return $this->loadYamlFile($path);
        }

        $validConfigExts = [ 'ini', 'json', 'php', 'yml' ];
        throw new InvalidArgumentException(sprintf(
            'Unsupported file format for "%s"; must be one of "%s"',
            $path,
            implode('", "', $validConfigExts)
        ));
    }