Quick and dirty caching.
@return DOM of a parsed user file
@throws Exception
339385
private static Document getUserDocument() throws Exception {
        if (userDoc == null || userFileParsed != userFile.lastModified() || userFileBytesLoaded != userFile.length()) {
            synchronized(XmlUsersFileModule.class) {
                if (userDoc == null || userFileParsed != userFile.lastModified() || userFileBytesLoaded != userFile.length()) {
                    userDoc = DataUtils.getDocumentFromFile(userFile);
                    userFileParsed = userFile.lastModified();
                    userFileBytesLoaded = userFile.length();
                }
            }
        }
        return userDoc;
    }
946068
private function resolveCache()
    {
        if (!$this->filesystem->exists($this->cacheFile)) {
            throw new \RuntimeException(sprintf(
                'The file "%s" can\'t be parsed!',
                $this->cacheFile
            ));
        }

        return unserialize(file_get_contents($this->cacheFile));
    }
692934
protected function read()
	{
		if( $this->useCache )
		{
			$fileName	= $this->pathCache.basename( $this->fileName ).".cache";
			if( file_exists( $fileName ) && file_exists( $this->fileName ) && filemtime( $fileName ) == filemtime( $this->pathConfig.$this->fileName ) )
			{
				return $this->readCache( $fileName );
			}
			else
			{
				$this->readWDDX();
				return $this->writeCache( $fileName );
			}
		}
		return $this->readWDDX();

	}
390849
public function postIndex()
	{
		if ( ! Input::hasFile('file'))
		{
			return Response::json(array('error' => 'File is required'), 400);
		}

		$contents = trim(File::get(Input::file('file')->getRealPath()));

		if (substr($contents, 0, 3) !== '---')
		{
			throw new Exception('Bad Markdown Formatting');
		}

		if ( ! ($pos = strpos($contents, '---', 3)))
		{
			throw new Exception('Bad Markdown Formatting');
		}

		$frontMatter = trim(substr($contents, 3, $pos - 3));
		$contents = trim(substr($contents, $pos + 3));

		$yaml = new Parser();

		$fields = $yaml->parse($frontMatter);

		return Response::json(array(
			'fields' => $fields,
			'content' => $contents
		));
	}
165530
private function getRepository()
    {
        if (!file_exists($this->storage)) {
            throw new \Exception('Tokens storage file not found.');
        }

        $file = file_get_contents($this->storage);
        return json_decode($file);
    }
998988
protected Method getParse(Class cls) throws Exception {
    Method meth = methodCache.get(cls);
    if (null == meth) {
      meth = cls.getMethod("parseFrom", new Class[]{ byte[].class });
      methodCache.put(cls, meth);
    }
    return meth;
  }
172867
private CmsXmlContent getContentDocument(CmsFile file, boolean fromCache) throws CmsXmlException {

        CmsXmlContent content = null;
        if (fromCache) {
            content = getSessionCache().getCacheXmlContent(file.getStructureId());
        }
        if (content == null) {
            content = CmsXmlContentFactory.unmarshal(getCmsObject(), file);
            getSessionCache().setCacheXmlContent(file.getStructureId(), content);
        }
        return content;
    }
334033
@Override
	protected String getElementIdTemplate() {
		ResourceRef rr = getResourceRef();
		if(rr != null) {
			String path = rr.getPath().toString();
			int slashBefore;
			if(path.endsWith(Path.SEPARATOR_STRING)) {
				slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR, path.length() - 2);
			} else {
				slashBefore = path.lastIndexOf(Path.SEPARATOR_CHAR);
			}
			String filename = path.substring(slashBefore + 1);
			if(filename.isEmpty()) throw new IllegalArgumentException("Invalid filename for file: " + path);
			// Strip extension if will not leave empty
			int lastDot = filename.lastIndexOf('.');
			if(lastDot > 0) filename = filename.substring(0, lastDot);
			return filename;
		}
		throw new IllegalStateException("Path not set");
	}
1069416
private function generateCacheFile()
    {
        $previousErrorSetting = libxml_use_internal_errors(true);
        libxml_clear_errors();
        if (@$this->domDocument->schemaValidate($this->xmlSchemaFile)) {
            $this->domDocument->preserveWhiteSpace = false;
            // Reload the XML to strip whitespace from XIncluded XML.
            $this->domDocument->loadXML($this->domDocument->saveXML());

            $xslDocument = new DOMDocument('1.0', 'UTF-8');
            $xslDocument->load(__DIR__.'/Resources/xsl/flexmodel-cache.xsl');

            $processor = new XSLTProcessor();
            $processor->setParameter('', 'checksum', md5($this->domDocument->saveXML()));
            $processor->importStyleSheet($xslDocument);
            $processor->registerPHPFunctions();

            $configuration = $processor->transformToXML($this->domDocument);
            file_put_contents($this->getCacheFile(), $configuration);

            $this->loadConfiguration(false);
        } else {
            $errors = libxml_get_errors();
            foreach ($errors as $error) {
                trigger_error(sprintf('Line %s: %s in "%s"', $error->line, trim($error->message), $error->file), E_USER_WARNING);
            }
            libxml_clear_errors();
        }
        libxml_use_internal_errors($previousErrorSetting);
    }
13265
public int process() throws Exception {
        int changed = 0;
        for (File child : files) {
            changed += (processFile(child) != null ? 1 : 0);
        }
        return changed;
    }
1180001
static function retrieveUserCacheFromFile( $filePath, $mtime, $userId )
    {
        $userCache = include( $filePath );

        // check that the returned array is not corrupted
        if ( is_array( $userCache )
          && isset( $userCache['info'] )
          && isset( $userCache['info'][$userId] )
          && is_numeric( $userCache['info'][$userId]['contentobject_id'] )
          && isset( $userCache['groups'] )
          && isset( $userCache['roles'] )
          && isset( $userCache['role_limitations'] )
          && isset( $userCache['access_array'] )
          && isset( $userCache['discount_rules'] ) )
        {
            return $userCache;
        }

        eZDebug::writeError( 'Cache file ' . $filePath . ' is corrupted, forcing generation.', __METHOD__ );
        return new eZClusterFileFailure( 1, 'Cache file ' . $filePath . ' is corrupted, forcing generation.' );
    }
288764
private final synchronized CacheElement getCacheElement(String userid) {
        String m = getCacheAbbrev() + " getCacheElement() ";
        CacheElement cacheElement = null;
        String key = getKey(userid);
        logger.debug(m + "key==" + key);
        if (cache.containsKey(key)) {
            logger.debug(m + "cache already has element");
        } else {
            logger.debug(m + "cache does not have element; create and put");
            CacheElement itemtemp =
                    new CacheElement(userid, getCacheId(), getCacheAbbrev());
            cache.put(key, itemtemp);
        }
        cacheElement = (CacheElement) cache.get(key);
        if (cacheElement == null) {
            logger.error(m + "cache does not contain element");
        } else {
            logger.debug(m + "element retrieved from cache successfully");
        }
        return cacheElement;
    }
404498
public function getPayload()
    {
        if (!$this->token) {
            throw new \RuntimeException('Token is mandatory.');
        }

        $descriptionNode = $this->appendDescriptionNode();
        $this->appendTagNode($descriptionNode);
        $this->appendTokenNode($descriptionNode);
        $this->appendTemplateNode($descriptionNode);
        $this->appendAdditionalNode($descriptionNode);

        $this->dom->formatOutput = true;

        return $this->dom->saveXML();
    }
790769
public function loadData()
    {
        $this->filePath = "{$this->cacheDir}/{$this->cacheFile}";
        $this->validateConfig();
        $urls = $this->prepareUrls($this->filePath, $this->urls, $this->forceRefresh, $this->cacheOnly);

        // we need at least one location
        if (!count($urls)) {
            throw new SyncException(
                'No location(s) available to sync from',
                $this->errors
            );
        }

        // cycle urls until valid data is found
        while (count($urls) && empty($validData)) {
            $nextUrl = array_shift($urls);
            if ($this->getData($nextUrl)) {
                $validData = true;
            }
        }

        // we should have valid data at this point
        if (!$this->parser->isValid() || empty($validData)) {
            throw new SyncException(
                'Unable to download data or data invalid',
                $this->errors
            );
        }

        return $this->parser->getParsedData();
    }
660450
public function setFromUrl()
    {
        // Cache?
        $cacheRebuild = true;
        if ($this->options->cache) {
            $cacheKey = md5($this->get());
            $cacheData = $this->cache->get($cacheKey);

            if (!empty($cacheData)) {
                $cacheRebuild = false;
                $this->set($cacheData);
            }
        }

        // Get dom
        if ($cacheRebuild) {
            $dom = new \PHPHtmlParser\Dom;
            $dom->load($this->url, $this->PHPHtmlParserOptions);
            $element = $dom->find($this->selector)[0];

            if (!empty($element)) {
                // Filter?
                if (!empty($this->filter->selector)) {
                    $newElement = new \PHPHtmlParser\Dom;
                    $newElement->load($element->outerHtml, $this->PHPHtmlParserOptions);
                    $filter = $newElement->find($this->filter->selector);

                    if (!empty($filter)) {
                        $i = 0;
                        foreach ($filter as $item) {
                            if ($i >= $this->filter->length) {
                                $item->delete();
                            }
                            $i++;
                        }
                    }
                    unset($filter);

                    $html = $newElement->outerHtml;

                } else {
                    $html = $element->outerHtml;
                }

                $this->set($html);

                if ($this->options->cache && !empty($cacheKey)) {
                    $this->cache->set($cacheKey, $html);
                }
            }
        }

        return $this;
    }
337859
public function getContent($uri, $selector, $debug = FALSE, $lifetime = 3600) {
		$cacheIdentifier = sha1($uri . $selector);
		$buffer = $this->cache->get($cacheIdentifier);

		if($buffer === FALSE) {
			libxml_use_internal_errors(TRUE);
			$domDocument = new \DOMDocument();
			$domDocument->loadHTMLFile($uri, LIBXML_NOERROR|LIBXML_NOWARNING);
			$this->detectBaseUri($domDocument, $uri);
			$this->fixRelativeUris($domDocument, 'a', 'href');
			$this->fixRelativeUris($domDocument, 'img', 'src');
			$node = $domDocument->getElementById($selector);
			$buffer = $domDocument->saveHTML($node);
			libxml_clear_errors();
			libxml_use_internal_errors(FALSE);
			$this->cache->set($cacheIdentifier, $buffer, array(sha1($uri)), $lifetime);
		}

		return $buffer;
	}
109573
private File detectHomeDir() throws Exception {
    String path = getClass().getProtectionDomain().getCodeSource().getLocation().getFile();
    path = URLDecoder.decode(path, "UTF-8");
    return new File(path).getParentFile().getParentFile().getCanonicalFile();
  }