/** * {@inheritdoc} */ public function loadClassMetadata(ClassMetadata $metadata) { if (null === $this->classes) { if (!stream_is_local($this->file)) { throw new MappingException(sprintf('This is not a local file "%s".', $this->file)); } if (null === $this->yamlParser) { $this->yamlParser = new Parser(); } $classes = $this->yamlParser->parse(file_get_contents($this->file)); if (empty($classes)) { return false; } // not an array if (!is_array($classes)) { throw new MappingException(sprintf('The file "%s" must contain a YAML array.', $this->file)); } $this->classes = $classes; } if (isset($this->classes[$metadata->getClassName()])) { $yaml = $this->classes[$metadata->getClassName()]; if (isset($yaml['attributes']) && is_array($yaml['attributes'])) { foreach ($yaml['attributes'] as $attribute => $data) { if (isset($data['groups'])) { foreach ($data['groups'] as $group) { $metadata->addAttributeGroup($attribute, $group); } } } } return true; } return false; }
/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { $messages = array(); if (!stream_is_local($resource)) { throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $resource)); } try { $file = new \SplFileObject($resource, 'rb'); } catch (\RuntimeException $e) { throw new \InvalidArgumentException(sprintf('Error opening file "%s".', $resource)); } $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY); $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape); foreach ($file as $data) { if (substr($data[0], 0, 1) === '#') { continue; } if (!isset($data[1])) { continue; } if (count($data) == 2) { $messages[$data[0]] = $data[1]; } else { continue; } } $catalogue = parent::load($messages, $locale, $domain); $catalogue->addResource(new FileResource($resource)); return $catalogue; }
/** * Copies and transforms a file. * * This method only copies the file if the origin file is newer than the target file. * * By default, if the target already exists, it is not overridden. * * @param string $originFile The original filename * @param string $targetFile The target filename * @param boolean $override Whether to override an existing file or not * * @throws IOException When copy fails */ public function copy($originFile, $targetFile, $override = false) { if (stream_is_local($originFile) && !is_file($originFile)) { throw new IOException(sprintf('Failed to copy %s because file does not exist', $originFile)); } $this->mkdir(dirname($targetFile)); if (!$override && is_file($targetFile)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } else { $doCopy = true; } if (!$doCopy) { return; } $event = new FileCopyEvent($originFile, $targetFile); $event = $this->event_dispatcher->dispatch(FilesystemEvents::COPY, $event); $originFile = $event->getSource(); $targetFile = $event->getTarget(); if ($event->isModified()) { file_put_contents($targetFile, $event->getContent()); return; } // No listeners modified the file, so just copy it (original behaviour & code) // https://bugs.php.net/bug.php?id=64634 $source = fopen($originFile, 'r'); $target = fopen($targetFile, 'w+'); stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy %s to %s', $originFile, $targetFile)); } }
/** * * {@inheritdoc} * */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!is_dir($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } try { $rb = new \ResourceBundle($locale, $resource); } catch (\Exception $e) { // HHVM compatibility: constructor throws on invalid resource $rb = null; } if (!$rb) { throw new InvalidResourceException(sprintf('Cannot load resource "%s"', $resource)); } elseif (intl_is_failure($rb->getErrorCode())) { throw new InvalidResourceException($rb->getErrorMessage(), $rb->getErrorCode()); } $messages = $this->flatten($rb); $catalogue = new MessageCatalogue($locale); $catalogue->add($messages, $domain); if (class_exists('Symfony\\Component\\Config\\Resource\\DirectoryResource')) { $catalogue->addResource(new DirectoryResource($resource)); } return $catalogue; }
/** * Loads a Yaml file. * * @param string $file A Yaml file path * @param string|null $type The resource type * * @return RouteCollection A RouteCollection instance * * @throws \InvalidArgumentException When a route can't be parsed because YAML is invalid * * @api */ public function load($file, $type = null) { $path = $this->locator->locate($file); if (!stream_is_local($path)) { throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path)); } if (!file_exists($path)) { throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path)); } if (null === $this->yamlParser) { $this->yamlParser = new YamlParser(); } $config = $this->yamlParser->parse(file_get_contents($path)); $collection = new RouteCollection(); $collection->addResource(new FileResource($path)); // empty file if (null === $config) { return $collection; } // not an array if (!is_array($config)) { throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path)); } foreach ($config as $name => $config) { $this->validate($config, $name, $path); if (isset($config['resource'])) { $this->parseImport($collection, $config, $path, $file); } else { $this->parseRoute($collection, $name, $config, $path); } } return $collection; }
/** * {@inheritdoc} */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } try { $messages = Neon\Neon::decode(file_get_contents($resource)); } catch (Nette\Utils\NeonException $e) { throw new InvalidResourceException(sprintf("Error parsing Neon: %s", $e->getMessage()), 0, $e); } catch (Nette\Neon\Exception $e) { throw new InvalidResourceException(sprintf("Error parsing Neon: %s", $e->getMessage()), 0, $e); } if (empty($messages)) { $messages = array(); } if (!is_array($messages)) { throw new InvalidResourceException(sprintf('The file "%s" must contain a Neon array.', $resource)); } $catalogue = parent::load($messages, $locale, $domain); $catalogue->addResource(new FileResource($resource)); return $catalogue; }
/** * (non-PHPDoc) * * @see \phpbu\App\Backup\Sync::sync() * @param \phpbu\App\Backup\Target $target * @param \phpbu\App\Result $result * @throws \phpbu\App\Backup\Sync\Exception */ public function sync(Target $target, Result $result) { $sourcePath = $target->getPathname(); $dropboxPath = $this->path . $target->getFilename(); $client = new DropboxApi\Client($this->token, "phpbu/1.1.0"); $pathError = DropboxApi\Path::findErrorNonRoot($dropboxPath); if (substr(__FILE__, 0, 7) == 'phar://') { DropboxApi\RootCertificates::useExternalPaths(); } if ($pathError !== null) { throw new Exception(sprintf('Invalid \'dropbox-path\': %s', $pathError)); } $size = null; if (stream_is_local($sourcePath)) { $size = filesize($sourcePath); } try { $fp = fopen($sourcePath, 'rb'); $res = $client->uploadFile($dropboxPath, DropboxApi\WriteMode::add(), $fp, $size); fclose($fp); } catch (\Exception $e) { throw new Exception($e->getMessage(), null, $e); } $result->debug('upload: done (' . $res['size'] . ')'); }
/** * Loads a JSON file * * @param string $file A JSON file path * @param string|null $type The resource type * * @return RouteCollection * * @throws InvalidArgumentException When the JSON is invalid */ public function load($file, $type = null) { $path = $this->locator->locate($file); if (!stream_is_local($path)) { $message = sprintf('This is not a local file "%s"', $path); throw new InvalidArgumentException($message); } if (!file_exists($path)) { $message = sprintf('File "%s" not found', $path); throw new InvalidArgumentException($message); } $parsedConfig = json_decode(file_get_contents($path), true); $collection = new RouteCollection(); $collection->addResource(new FileResource($path)); // empty file if ($parsedConfig === null) { return $collection; } // not an array if (!is_array($parsedConfig)) { $message = sprintf('The file "%s" must contain a JSON object', $path); throw new InvalidArgumentException($message); } foreach ($parsedConfig as $name => $config) { $this->validate($config, $name, $path); if (isset($config['resource'])) { $this->parseImport($collection, $config, $path, $file); } else { $this->parseRoute($collection, $name, $config, $path); } } return $collection; }
/** * @param string $file * @return array */ protected function loadFile($file) { if (!class_exists('Symfony\\Component\\Yaml\\Parser')) { throw new \RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.'); } if (!stream_is_local($file)) { throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $file)); } if (!file_exists($file)) { throw new \InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); } if (null === $this->yamlParser) { $this->yamlParser = new Parser(); } try { $config = $this->yamlParser->parse(file_get_contents($file)); if (!is_array($config)) { throw new \InvalidArgumentException(sprintf('The contents of the file "%s" is not an array.', $file)); } } catch (ParseException $e) { throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e); } $this->app->parseParameters($config); return $config; }
/** * {@inheritdoc} */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } $messages = array(); try { $file = new \SplFileObject($resource, 'rb'); } catch (\RuntimeException $e) { throw new NotFoundResourceException(sprintf('Error opening file "%s".', $resource), 0, $e); } $file->setFlags(\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY); $file->setCsvControl($this->delimiter, $this->enclosure, $this->escape); foreach ($file as $data) { if ('#' !== substr($data[0], 0, 1) && isset($data[1]) && 2 === count($data)) { $messages[$data[0]] = $data[1]; } } $catalogue = parent::load($messages, $locale, $domain); if (class_exists('Symfony\\Component\\Config\\Resource\\FileResource')) { $catalogue->addResource(new FileResource($resource)); } return $catalogue; }
/** * Copies a file. * * This method only copies the file if the origin file is newer than the target file. * * By default, if the target already exists, it is not overridden. * * @param string $originFile The original filename * @param string $targetFile The target filename * @param bool $override Whether to override an existing file or not * * @throws FileNotFoundException When originFile doesn't exist * @throws IOException When copy fails */ public function copy($originFile, $targetFile, $override = false) { if (stream_is_local($originFile) && !is_file($originFile)) { throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile); } $this->mkdir(dirname($targetFile)); if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } else { $doCopy = true; } if ($doCopy) { // https://bugs.php.net/bug.php?id=64634 if (false === ($source = @fopen($originFile, 'r'))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile); } if (false === ($target = @fopen($targetFile, 'w'))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile); } stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile); } } }
/** * Copies a file. * * This method only copies the file if the origin file is newer than the target file. * * By default, if the target already exists, it is not overridden. * * @param string $originFile The original filename * @param string $targetFile The target filename * @param bool $override Whether to override an existing file or not * * @throws IOException When copy fails */ public function copy($originFile, $targetFile, $override = false) { if (stream_is_local($originFile) && !is_file($originFile)) { throw new IOException(sprintf('Failed to copy %s because file not exists', $originFile)); } $this->mkdir(dirname($targetFile)); if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } else { $doCopy = true; } if ($doCopy) { // https://bugs.php.net/bug.php?id=64634 $source = fopen($originFile, 'r'); // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default $target = fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true)))); stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy %s to %s', $originFile, $targetFile)); } } }
/** * Copies a file or directory. * @return void * @throws Nette\IOException */ public static function copy($source, $dest, $overwrite = TRUE) { if (stream_is_local($source) && !file_exists($source)) { throw new Nette\IOException("File or directory '{$source}' not found."); } elseif (!$overwrite && file_exists($dest)) { throw new Nette\InvalidStateException("File or directory '{$dest}' already exists."); } elseif (is_dir($source)) { static::createDir($dest); foreach (new \FilesystemIterator($dest) as $item) { static::delete($item); } foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) { if ($item->isDir()) { static::createDir($dest . '/' . $iterator->getSubPathName()); } else { static::copy($item, $dest . '/' . $iterator->getSubPathName()); } } } else { static::createDir(dirname($dest)); if (@stream_copy_to_stream(fopen($source, 'r'), fopen($dest, 'w')) === FALSE) { // @ is escalated to exception throw new Nette\IOException("Unable to copy file '{$source}' to '{$dest}'."); } } }
/** * Disk constructor. * @param string $path * @throws DiskException */ public function __construct(string $path = ".") { // Check if provided path is local stream if (!stream_is_local($path)) { throw DiskException::diskInit("Path to disk must be a local directory"); } // Check if path is a symbolic link if (@is_link($path) === true) { throw DiskException::diskInit("Path to disk cannot be a symbolic link"); } // Resolve path $realPath = @realpath($path); // Check if path couldn't be resolved if (!$realPath) { // Create directory $this->createDir($path, 0777); $realPath = @realpath($path); } // Set resolved path $path = $realPath; // Confirm if path leads to a directory if (!$path || !@is_dir($path)) { throw DiskException::diskInit("Disk must be provided with path to a directory"); } // Set path variable for this instance // Disk path must have a trailing DIRECTORY_SEPARATOR $this->path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; // Check and set privileges $this->privilegeRead = @is_readable($this->path) ? true : false; $this->privilegeWrite = @is_writable($this->path) ? true : false; if (!$this->privilegeRead && !$this->privilegeWrite) { // Doesn't have both read/write privileges throw DiskException::diskInit("Disk doesn't have read and write privileges"); } }
/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } list($xml, $encoding) = $this->parseFile($resource); $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2'); $catalogue = new MessageCatalogue($locale); foreach ($xml->xpath('//xliff:trans-unit') as $translation) { $attributes = $translation->attributes(); if (!(isset($attributes['resname']) || isset($translation->source))) { continue; } $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source; // If the xlf file has another encoding specified, try to convert it because // simple_xml will always return utf-8 encoded values $target = $this->utf8ToCharset((string) (isset($translation->target) ? $translation->target : $source), $encoding); $catalogue->set((string) $source, $target, $domain); $metadata = array(); if ($notes = $this->parseNotesMetadata($translation->note, $encoding)) { $metadata['notes'] = $notes; } if ($translation->target->attributes()) { $metadata['target-attributes'] = $translation->target->attributes(); } $catalogue->setMetadata((string) $source, $metadata, $domain); } if (class_exists('Symfony\\Component\\Config\\Resource\\FileResource')) { $catalogue->addResource(new FileResource($resource)); } return $catalogue; }
public function copy($originFile, $targetFile, $override = false) { if (stream_is_local($originFile) && !is_file($originFile)) { throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile); } $this->mkdir(dirname($targetFile)); $doCopy = true; if (!$override && null === parse_url($originFile, PHP_URL_HOST) && is_file($targetFile)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } if ($doCopy) { if (false === ($source = @fopen($originFile, 'r'))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile); } if (false === ($target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true)))))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile); } $bytesCopied = stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile); } @chmod($targetFile, fileperms($targetFile) | fileperms($originFile) & 0111); if (stream_is_local($originFile) && $bytesCopied !== ($bytesOrigin = filesize($originFile))) { throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile); } } }
/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } list($xml, $encoding) = $this->parseFile($resource); $xml->registerXPathNamespace('xliff', 'urn:oasis:names:tc:xliff:document:1.2'); $catalogue = new MessageCatalogue($locale); foreach ($xml->xpath('//xliff:trans-unit') as $translation) { $attributes = $translation->attributes(); if (!(isset($attributes['resname']) || isset($translation->source)) || !isset($translation->target)) { continue; } $source = isset($attributes['resname']) && $attributes['resname'] ? $attributes['resname'] : $translation->source; $target = (string) $translation->target; // If the xlf file has another encoding specified, try to convert it because // simple_xml will always return utf-8 encoded values if ('UTF-8' !== $encoding && !empty($encoding)) { if (function_exists('mb_convert_encoding')) { $target = mb_convert_encoding($target, $encoding, 'UTF-8'); } elseif (function_exists('iconv')) { $target = iconv('UTF-8', $encoding, $target); } else { throw new \RuntimeException('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).'); } } $catalogue->set((string) $source, $target, $domain); } $catalogue->addResource(new FileResource($resource)); return $catalogue; }
/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } try { $dom = XmlUtils::loadFile($resource); } catch (\InvalidArgumentException $e) { throw new InvalidResourceException(sprintf('Unable to load "%s".', $resource), $e->getCode(), $e); } $internalErrors = libxml_use_internal_errors(true); libxml_clear_errors(); $xpath = new \DOMXPath($dom); $nodes = $xpath->evaluate('//TS/context/name[text()="' . $domain . '"]'); $catalogue = new MessageCatalogue($locale); if ($nodes->length == 1) { $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message'); foreach ($translations as $translation) { $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue; if (!empty($translationValue)) { $catalogue->set((string) $translation->getElementsByTagName('source')->item(0)->nodeValue, $translationValue, $domain); } $translation = $translation->nextSibling; } $catalogue->addResource(new FileResource($resource)); } libxml_use_internal_errors($internalErrors); return $catalogue; }
/** * Copies a file. * * This method only copies the file if the origin file is newer than the target file. * * By default, if the target already exists, it is not overridden. * * @param string $originFile The original filename * @param string $targetFile The target filename * @param bool $override Whether to override an existing file or not * * @throws FileNotFoundException When originFile doesn't exist * @throws IOException When copy fails */ public function copy($originFile, $targetFile, $override = false) { if (stream_is_local($originFile) && !is_file($originFile)) { throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile); } $this->mkdir(dirname($targetFile)); if (!$override && is_file($targetFile) && null === parse_url($originFile, PHP_URL_HOST)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } else { $doCopy = true; } if ($doCopy) { // https://bugs.php.net/bug.php?id=64634 if (false === ($source = @fopen($originFile, 'r'))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile); } // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default if (false === ($target = @fopen($targetFile, 'w', null, stream_context_create(array('ftp' => array('overwrite' => true)))))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile); } $bytesCopied = stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile); } if (stream_is_local($originFile) && $bytesCopied !== filesize($originFile)) { throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s %g bytes copied".', $originFile, $targetFile, $bytesCopied), 0, null, $originFile); } } }
public function generate() { if (PHP_SAPI != 'cli') { throw new \Exception("This script only can be used in CLI"); } $config = $this->config->database; system('/usr/bin/mysqldump -u ' . $config->username . ' -p' . $config->password . ' -r /tmp/phosphorum.sql ' . $config->dbname); system('bzip2 /tmp/phosphorum.sql'); $sourcePath = '/tmp/phosphorum.sql.bz2'; if (!file_exists($sourcePath)) { throw new \Exception("Backup could not be created"); } list($accessToken, $host) = AuthInfo::loadFromJsonFile(APP_PATH . '/app/config/backup.auth'); $client = new Client($accessToken, "phosphorum", null, $host); $dropboxPath = '/phosphorum.sql.bz2'; $pathError = Path::findErrorNonRoot($dropboxPath); if ($pathError !== null) { throw new \Exception("Invalid <dropbox-path>: {$pathError}"); } try { $client->delete($dropboxPath); } catch (\Exception $e) { // ... } $size = null; if (\stream_is_local($sourcePath)) { $size = \filesize($sourcePath); } $fp = fopen($sourcePath, "rb"); $client->uploadFile($dropboxPath, WriteMode::add(), $fp, $size); fclose($fp); @unlink($sourcePath); }
/** * {@inheritdoc} */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } if (!class_exists('Symfony\\Component\\Yaml\\Parser')) { throw new \LogicException('Loading translations from the YAML format requires the Symfony Yaml component.'); } if (null === $this->yamlParser) { $this->yamlParser = new YamlParser(); } try { $messages = $this->yamlParser->parse(file_get_contents($resource)); } catch (ParseException $e) { throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e); } // empty file if (null === $messages) { $messages = array(); } // not an array if (!is_array($messages)) { throw new InvalidResourceException(sprintf('The file "%s" must contain a YAML array.', $resource)); } $catalogue = parent::load($messages, $locale, $domain); if (class_exists('Symfony\\Component\\Config\\Resource\\FileResource')) { $catalogue->addResource(new FileResource($resource)); } return $catalogue; }
/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } if (null === $this->yamlParser) { $this->yamlParser = new YamlParser(); } try { $messages = $this->yamlParser->parse(file_get_contents($resource)); } catch (ParseException $e) { throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e); } // empty file if (null === $messages) { $messages = array(); } // not an array if (!is_array($messages)) { throw new InvalidResourceException(sprintf('The file "%s" must contain a YAML array.', $resource)); } $catalogue = parent::load($messages, $locale, $domain); $catalogue->addResource(new FileResource($resource)); return $catalogue; }
/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } $dom = new \DOMDocument(); $current = libxml_use_internal_errors(true); if (!@$dom->load($resource, defined('LIBXML_COMPACT') ? LIBXML_COMPACT : 0)) { throw new InvalidResourceException(implode("\n", $this->getXmlErrors())); } $xpath = new \DOMXPath($dom); $nodes = $xpath->evaluate('//TS/context/name[text()="' . $domain . '"]'); $catalogue = new MessageCatalogue($locale); if ($nodes->length == 1) { $translations = $nodes->item(0)->nextSibling->parentNode->parentNode->getElementsByTagName('message'); foreach ($translations as $translation) { $translationValue = (string) $translation->getElementsByTagName('translation')->item(0)->nodeValue; if (!empty($translationValue)) { $catalogue->set((string) $translation->getElementsByTagName('source')->item(0)->nodeValue, $translationValue, $domain); } $translation = $translation->nextSibling; } $catalogue->addResource(new FileResource($resource)); } libxml_use_internal_errors($current); return $catalogue; }
public function getAssets($resource, $previousContext = null) { if (!is_string($resource)) { throw new InvalidResourceException('Expected string filename as resource', $resource); } elseif (!is_file($resource) || !is_readable($resource) || !stream_is_local($resource)) { throw new InvalidResourceException('File not found, not readable or not local', $resource); } if ($previousContext !== null) { if (!is_array($previousContext) || !isset($previousContext['modified_at']) || !is_int($previousContext['modified_at']) || !isset($previousContext['assets']) || !is_array($previousContext['assets'])) { throw new InvalidContextException('Expected context with int `modified_at` and array `assets`', $previousContext); } if ($previousContext['modified_at'] === filemtime($resource)) { $assetResult = new AssetResult(); $assetResult->setAssets($previousContext['assets']); $assetResult->setContext($previousContext); return $assetResult; } } try { $tokens = $this->twig->tokenize(file_get_contents($resource), $resource); $node = $this->twig->parse($tokens); } catch (SyntaxException $exception) { $this->errorHandler->processException(new ResourceParsingException('Got twig syntax exception while parsing', 0, $exception)); return new AssetResult(); } $assets = $this->loadNode($node, $resource); $assetResult = new AssetResult(); $assetResult->setAssets($assets); $assetResult->setContext(array('modified_at' => filemtime($resource), 'assets' => $assets)); return $assetResult; }
/** * @inheritdoc */ public function canParse(string $file) : bool { if (false === stream_is_local($file)) { return false; } return 1 === preg_match(self::REGEX, $file); }
/** * Validates a file argument. * * @param string $file * * @throws \InvalidArgumentException */ protected function validateArgument($file) { if (!stream_is_local($file)) { throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $file)); } if (!file_exists($file)) { throw new \InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); } }
/** * Reprocess stream metadata */ protected function rebuildCache() { $this->cache = stream_get_meta_data($this->stream); $this->cache[self::STREAM_TYPE] = strtolower($this->cache[self::STREAM_TYPE]); $this->cache[self::WRAPPER_TYPE] = strtolower($this->cache[self::WRAPPER_TYPE]); $this->cache[self::IS_LOCAL] = stream_is_local($this->stream); $this->cache[self::IS_READABLE] = isset(self::$readWriteHash['read'][$this->cache['mode']]); $this->cache[self::IS_WRITABLE] = isset(self::$readWriteHash['write'][$this->cache['mode']]); }
/** * @param string $path */ public function loadFromPath($path) { if ($path === null || empty($path) || stream_is_local($path) && !file_exists($path)) { throw new \RuntimeException('Invalid path or stream handler is not supported.'); } $document = new \DOMDocument('1.0', 'UTF-8'); $document->load($path); $this->load($document); }
/** * {@inheritdoc} */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource)); } if (!file_exists($resource)) { throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource)); } return parent::load(require $resource, $locale, $domain); }
/** * {@inheritdoc} * * @api */ public function load($resource, $locale, $domain = 'messages') { if (!stream_is_local($resource)) { throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $resource)); } $messages = (require $resource); $catalogue = parent::load($messages, $locale, $domain); $catalogue->addResource(new FileResource($resource)); return $catalogue; }