repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
lexik/LexikTranslationBundle | Command/ExportTranslationsCommand.php | ExportTranslationsCommand.exportFile | protected function exportFile(FileInterface $file)
{
$rootDir = $this->input->getOption('export-path') ? $this->input->getOption('export-path') . '/' : $this->getContainer()->getParameter('kernel.root_dir');
$this->output->writeln(sprintf('<info># Exporting "%s/%s":</info>', $file->getPath(), $file->getName()));
$override = $this->input->getOption('override');
if (!$this->input->getOption('export-path')) {
// we only export updated translations in case of the file is located in vendor/
if ($override) {
$onlyUpdated = ('Resources/translations' !== $file->getPath());
} else {
$onlyUpdated = (false !== strpos($file->getPath(), 'vendor/'));
}
} else {
$onlyUpdated = !$override;
}
$translations = $this->getContainer()
->get('lexik_translation.translation_storage')
->getTranslationsFromFile($file, $onlyUpdated);
if (count($translations) < 1) {
$this->output->writeln('<comment>No translations to export.</comment>');
return;
}
$format = $this->input->getOption('format') ? $this->input->getOption('format') : $file->getExtention();
// we don't write vendors file, translations will be exported in %kernel.root_dir%/Resources/translations
if (false !== strpos($file->getPath(), 'vendor/') || $override) {
$outputPath = sprintf('%s/Resources/translations', $rootDir);
} else {
$outputPath = sprintf('%s/%s', $rootDir, $file->getPath());
}
$this->output->writeln(sprintf('<info># OutputPath "%s":</info>', $outputPath));
// ensure the path exists
if ($this->input->getOption('export-path')) {
/** @var Filesystem $fs */
$fs = $this->getContainer()->get('filesystem');
if (!$fs->exists($outputPath)) {
$fs->mkdir($outputPath);
}
}
$outputFile = sprintf('%s/%s.%s.%s', $outputPath, $file->getDomain(), $file->getLocale(), $format);
$this->output->writeln(sprintf('<info># OutputFile "%s":</info>', $outputFile));
$translations = $this->mergeExistingTranslations($file, $outputFile, $translations);
$this->doExport($outputFile, $translations, $format);
} | php | protected function exportFile(FileInterface $file)
{
$rootDir = $this->input->getOption('export-path') ? $this->input->getOption('export-path') . '/' : $this->getContainer()->getParameter('kernel.root_dir');
$this->output->writeln(sprintf('<info># Exporting "%s/%s":</info>', $file->getPath(), $file->getName()));
$override = $this->input->getOption('override');
if (!$this->input->getOption('export-path')) {
// we only export updated translations in case of the file is located in vendor/
if ($override) {
$onlyUpdated = ('Resources/translations' !== $file->getPath());
} else {
$onlyUpdated = (false !== strpos($file->getPath(), 'vendor/'));
}
} else {
$onlyUpdated = !$override;
}
$translations = $this->getContainer()
->get('lexik_translation.translation_storage')
->getTranslationsFromFile($file, $onlyUpdated);
if (count($translations) < 1) {
$this->output->writeln('<comment>No translations to export.</comment>');
return;
}
$format = $this->input->getOption('format') ? $this->input->getOption('format') : $file->getExtention();
// we don't write vendors file, translations will be exported in %kernel.root_dir%/Resources/translations
if (false !== strpos($file->getPath(), 'vendor/') || $override) {
$outputPath = sprintf('%s/Resources/translations', $rootDir);
} else {
$outputPath = sprintf('%s/%s', $rootDir, $file->getPath());
}
$this->output->writeln(sprintf('<info># OutputPath "%s":</info>', $outputPath));
// ensure the path exists
if ($this->input->getOption('export-path')) {
/** @var Filesystem $fs */
$fs = $this->getContainer()->get('filesystem');
if (!$fs->exists($outputPath)) {
$fs->mkdir($outputPath);
}
}
$outputFile = sprintf('%s/%s.%s.%s', $outputPath, $file->getDomain(), $file->getLocale(), $format);
$this->output->writeln(sprintf('<info># OutputFile "%s":</info>', $outputFile));
$translations = $this->mergeExistingTranslations($file, $outputFile, $translations);
$this->doExport($outputFile, $translations, $format);
} | [
"protected",
"function",
"exportFile",
"(",
"FileInterface",
"$",
"file",
")",
"{",
"$",
"rootDir",
"=",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'export-path'",
")",
"?",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'export-path'",
")"... | Get translations to export and export translations into a file.
@param FileInterface $file | [
"Get",
"translations",
"to",
"export",
"and",
"export",
"translations",
"into",
"a",
"file",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ExportTranslationsCommand.php#L83-L136 | train |
lexik/LexikTranslationBundle | Command/ExportTranslationsCommand.php | ExportTranslationsCommand.mergeExistingTranslations | protected function mergeExistingTranslations($file, $outputFile, $translations)
{
if (file_exists($outputFile)) {
$extension = pathinfo($outputFile, PATHINFO_EXTENSION);
$loader = $this->getContainer()->get('lexik_translation.translator')->getLoader($extension);
$messageCatalogue = $loader->load($outputFile, $file->getLocale(), $file->getDomain());
$translations = array_merge($messageCatalogue->all($file->getDomain()), $translations);
}
return $translations;
} | php | protected function mergeExistingTranslations($file, $outputFile, $translations)
{
if (file_exists($outputFile)) {
$extension = pathinfo($outputFile, PATHINFO_EXTENSION);
$loader = $this->getContainer()->get('lexik_translation.translator')->getLoader($extension);
$messageCatalogue = $loader->load($outputFile, $file->getLocale(), $file->getDomain());
$translations = array_merge($messageCatalogue->all($file->getDomain()), $translations);
}
return $translations;
} | [
"protected",
"function",
"mergeExistingTranslations",
"(",
"$",
"file",
",",
"$",
"outputFile",
",",
"$",
"translations",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"outputFile",
")",
")",
"{",
"$",
"extension",
"=",
"pathinfo",
"(",
"$",
"outputFile",
... | If the output file exists we merge existing translations with those from the database.
@param FileInterface $file
@param string $outputFile
@param array $translations
@return array | [
"If",
"the",
"output",
"file",
"exists",
"we",
"merge",
"existing",
"translations",
"with",
"those",
"from",
"the",
"database",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ExportTranslationsCommand.php#L146-L157 | train |
lexik/LexikTranslationBundle | Command/ExportTranslationsCommand.php | ExportTranslationsCommand.doExport | protected function doExport($outputFile, $translations, $format)
{
$this->output->writeln(sprintf('<comment>Output file: %s</comment>', $outputFile));
$this->output->write(sprintf('<comment>%d translations to export: </comment>', count($translations)));
try {
$exported = $this->getContainer()->get('lexik_translation.exporter_collector')->export(
$format,
$outputFile,
$translations
);
$this->output->writeln($exported ? '<comment>success</comment>' : '<error>fail</error>');
} catch (\Exception $e) {
$this->output->writeln(sprintf('<error>"%s"</error>', $e->getMessage()));
}
} | php | protected function doExport($outputFile, $translations, $format)
{
$this->output->writeln(sprintf('<comment>Output file: %s</comment>', $outputFile));
$this->output->write(sprintf('<comment>%d translations to export: </comment>', count($translations)));
try {
$exported = $this->getContainer()->get('lexik_translation.exporter_collector')->export(
$format,
$outputFile,
$translations
);
$this->output->writeln($exported ? '<comment>success</comment>' : '<error>fail</error>');
} catch (\Exception $e) {
$this->output->writeln(sprintf('<error>"%s"</error>', $e->getMessage()));
}
} | [
"protected",
"function",
"doExport",
"(",
"$",
"outputFile",
",",
"$",
"translations",
",",
"$",
"format",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"sprintf",
"(",
"'<comment>Output file: %s</comment>'",
",",
"$",
"outputFile",
")",
")",
... | Export translations.
@param string $outputFile
@param array $translations
@param string $format | [
"Export",
"translations",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ExportTranslationsCommand.php#L166-L182 | train |
lexik/LexikTranslationBundle | DependencyInjection/LexikTranslationExtension.php | LexikTranslationExtension.buildTranslationStorageDefinition | protected function buildTranslationStorageDefinition(ContainerBuilder $container, $storage, $objectManager)
{
$container->setParameter('lexik_translation.storage.type', $storage);
if (StorageInterface::STORAGE_ORM == $storage) {
$args = array(
new Reference('doctrine'),
(null === $objectManager) ? 'default' : $objectManager,
);
$this->createDoctrineMappingDriver($container, 'lexik_translation.orm.metadata.xml', '%doctrine.orm.metadata.xml.class%');
$metadataListener = new Definition();
$metadataListener->setClass('%lexik_translation.orm.listener.class%');
$metadataListener->addTag('doctrine.event_listener', array(
'event' => Events::loadClassMetadata,
));
$container->setDefinition('lexik_translation.orm.listener', $metadataListener);
} elseif (StorageInterface::STORAGE_MONGODB == $storage) {
$args = array(
new Reference('doctrine_mongodb'),
(null === $objectManager) ? 'default' : $objectManager,
);
$this->createDoctrineMappingDriver($container, 'lexik_translation.mongodb.metadata.xml', '%doctrine_mongodb.odm.metadata.xml.class%');
} elseif (StorageInterface::STORAGE_PROPEL == $storage) {
// In the Propel case the object_manager setting is used for the connection name
$args = array($objectManager);
} else {
throw new \RuntimeException(sprintf('Unsupported storage "%s".', $storage));
}
$args[] = array(
'trans_unit' => new Parameter(sprintf('lexik_translation.%s.trans_unit.class', $storage)),
'translation' => new Parameter(sprintf('lexik_translation.%s.translation.class', $storage)),
'file' => new Parameter(sprintf('lexik_translation.%s.file.class', $storage)),
);
$storageDefinition = new Definition();
$storageDefinition->setClass($container->getParameter(sprintf('lexik_translation.%s.translation_storage.class', $storage)));
$storageDefinition->setArguments($args);
$storageDefinition->setPublic(true);
$container->setDefinition('lexik_translation.translation_storage', $storageDefinition);
} | php | protected function buildTranslationStorageDefinition(ContainerBuilder $container, $storage, $objectManager)
{
$container->setParameter('lexik_translation.storage.type', $storage);
if (StorageInterface::STORAGE_ORM == $storage) {
$args = array(
new Reference('doctrine'),
(null === $objectManager) ? 'default' : $objectManager,
);
$this->createDoctrineMappingDriver($container, 'lexik_translation.orm.metadata.xml', '%doctrine.orm.metadata.xml.class%');
$metadataListener = new Definition();
$metadataListener->setClass('%lexik_translation.orm.listener.class%');
$metadataListener->addTag('doctrine.event_listener', array(
'event' => Events::loadClassMetadata,
));
$container->setDefinition('lexik_translation.orm.listener', $metadataListener);
} elseif (StorageInterface::STORAGE_MONGODB == $storage) {
$args = array(
new Reference('doctrine_mongodb'),
(null === $objectManager) ? 'default' : $objectManager,
);
$this->createDoctrineMappingDriver($container, 'lexik_translation.mongodb.metadata.xml', '%doctrine_mongodb.odm.metadata.xml.class%');
} elseif (StorageInterface::STORAGE_PROPEL == $storage) {
// In the Propel case the object_manager setting is used for the connection name
$args = array($objectManager);
} else {
throw new \RuntimeException(sprintf('Unsupported storage "%s".', $storage));
}
$args[] = array(
'trans_unit' => new Parameter(sprintf('lexik_translation.%s.trans_unit.class', $storage)),
'translation' => new Parameter(sprintf('lexik_translation.%s.translation.class', $storage)),
'file' => new Parameter(sprintf('lexik_translation.%s.file.class', $storage)),
);
$storageDefinition = new Definition();
$storageDefinition->setClass($container->getParameter(sprintf('lexik_translation.%s.translation_storage.class', $storage)));
$storageDefinition->setArguments($args);
$storageDefinition->setPublic(true);
$container->setDefinition('lexik_translation.translation_storage', $storageDefinition);
} | [
"protected",
"function",
"buildTranslationStorageDefinition",
"(",
"ContainerBuilder",
"$",
"container",
",",
"$",
"storage",
",",
"$",
"objectManager",
")",
"{",
"$",
"container",
"->",
"setParameter",
"(",
"'lexik_translation.storage.type'",
",",
"$",
"storage",
")"... | Build the 'lexik_translation.translation_storage' service definition.
@param ContainerBuilder $container
@param string $storage
@param string $objectManager
@throws \RuntimeException | [
"Build",
"the",
"lexik_translation",
".",
"translation_storage",
"service",
"definition",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/DependencyInjection/LexikTranslationExtension.php#L165-L211 | train |
lexik/LexikTranslationBundle | DependencyInjection/LexikTranslationExtension.php | LexikTranslationExtension.createDoctrineMappingDriver | protected function createDoctrineMappingDriver(ContainerBuilder $container, $driverId, $driverClass)
{
$driverDefinition = new Definition($driverClass, array(
array(realpath(__DIR__.'/../Resources/config/model') => 'Lexik\Bundle\TranslationBundle\Model'),
));
$driverDefinition->setPublic(false);
$container->setDefinition($driverId, $driverDefinition);
} | php | protected function createDoctrineMappingDriver(ContainerBuilder $container, $driverId, $driverClass)
{
$driverDefinition = new Definition($driverClass, array(
array(realpath(__DIR__.'/../Resources/config/model') => 'Lexik\Bundle\TranslationBundle\Model'),
));
$driverDefinition->setPublic(false);
$container->setDefinition($driverId, $driverDefinition);
} | [
"protected",
"function",
"createDoctrineMappingDriver",
"(",
"ContainerBuilder",
"$",
"container",
",",
"$",
"driverId",
",",
"$",
"driverClass",
")",
"{",
"$",
"driverDefinition",
"=",
"new",
"Definition",
"(",
"$",
"driverClass",
",",
"array",
"(",
"array",
"(... | Add a driver to load mapping of model classes.
@param ContainerBuilder $container
@param string $driverId
@param string $driverClass | [
"Add",
"a",
"driver",
"to",
"load",
"mapping",
"of",
"model",
"classes",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/DependencyInjection/LexikTranslationExtension.php#L220-L228 | train |
lexik/LexikTranslationBundle | DependencyInjection/LexikTranslationExtension.php | LexikTranslationExtension.buildDevServicesDefinition | protected function buildDevServicesDefinition(ContainerBuilder $container)
{
$container
->getDefinition('lexik_translation.data_grid.request_handler')
->addMethodCall('setProfiler', array(new Reference('profiler')));
$tokenFinderDefinition = new Definition();
$tokenFinderDefinition->setClass($container->getParameter('lexik_translation.token_finder.class'));
$tokenFinderDefinition->setArguments(array(
new Reference('profiler'),
new Parameter('lexik_translation.token_finder.limit'),
));
$container->setDefinition('lexik_translation.token_finder', $tokenFinderDefinition);
} | php | protected function buildDevServicesDefinition(ContainerBuilder $container)
{
$container
->getDefinition('lexik_translation.data_grid.request_handler')
->addMethodCall('setProfiler', array(new Reference('profiler')));
$tokenFinderDefinition = new Definition();
$tokenFinderDefinition->setClass($container->getParameter('lexik_translation.token_finder.class'));
$tokenFinderDefinition->setArguments(array(
new Reference('profiler'),
new Parameter('lexik_translation.token_finder.limit'),
));
$container->setDefinition('lexik_translation.token_finder', $tokenFinderDefinition);
} | [
"protected",
"function",
"buildDevServicesDefinition",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"container",
"->",
"getDefinition",
"(",
"'lexik_translation.data_grid.request_handler'",
")",
"->",
"addMethodCall",
"(",
"'setProfiler'",
",",
"array",
"(",
... | Load dev tools.
@param ContainerBuilder $container | [
"Load",
"dev",
"tools",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/DependencyInjection/LexikTranslationExtension.php#L235-L249 | train |
lexik/LexikTranslationBundle | Command/ImportTranslationsCommand.php | ImportTranslationsCommand.checkOptions | protected function checkOptions()
{
if ($this->input->getOption('only-vendors') && $this->input->getOption('globals')) {
throw new \LogicException('You cannot use "globals" and "only-vendors" at the same time.');
}
if ($this->input->getOption('import-path')
&& ($this->input->getOption('globals')
|| $this->input->getOption('merge')
|| $this->input->getOption('only-vendors'))) {
throw new \LogicException('You cannot use "globals", "merge" or "only-vendors" and "import-path" at the same time.');
}
} | php | protected function checkOptions()
{
if ($this->input->getOption('only-vendors') && $this->input->getOption('globals')) {
throw new \LogicException('You cannot use "globals" and "only-vendors" at the same time.');
}
if ($this->input->getOption('import-path')
&& ($this->input->getOption('globals')
|| $this->input->getOption('merge')
|| $this->input->getOption('only-vendors'))) {
throw new \LogicException('You cannot use "globals", "merge" or "only-vendors" and "import-path" at the same time.');
}
} | [
"protected",
"function",
"checkOptions",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'only-vendors'",
")",
"&&",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'globals'",
")",
")",
"{",
"throw",
"new",
"\\",
"L... | Checks if given options are compatible. | [
"Checks",
"if",
"given",
"options",
"are",
"compatible",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ImportTranslationsCommand.php#L141-L153 | train |
lexik/LexikTranslationBundle | Command/ImportTranslationsCommand.php | ImportTranslationsCommand.importComponentTranslationFiles | protected function importComponentTranslationFiles(array $locales, array $domains)
{
$classes = array(
'Symfony\Component\Validator\Validation' => '/Resources/translations',
'Symfony\Component\Form\Form' => '/Resources/translations',
'Symfony\Component\Security\Core\Exception\AuthenticationException' => '/../Resources/translations',
);
$dirs = array();
foreach ($classes as $namespace => $translationDir) {
$reflection = new \ReflectionClass($namespace);
$dirs[] = dirname($reflection->getFilename()) . $translationDir;
}
$finder = new Finder();
$finder->files()
->name($this->getFileNamePattern($locales, $domains))
->in($dirs);
$this->importTranslationFiles($finder->count() > 0 ? $finder : null);
} | php | protected function importComponentTranslationFiles(array $locales, array $domains)
{
$classes = array(
'Symfony\Component\Validator\Validation' => '/Resources/translations',
'Symfony\Component\Form\Form' => '/Resources/translations',
'Symfony\Component\Security\Core\Exception\AuthenticationException' => '/../Resources/translations',
);
$dirs = array();
foreach ($classes as $namespace => $translationDir) {
$reflection = new \ReflectionClass($namespace);
$dirs[] = dirname($reflection->getFilename()) . $translationDir;
}
$finder = new Finder();
$finder->files()
->name($this->getFileNamePattern($locales, $domains))
->in($dirs);
$this->importTranslationFiles($finder->count() > 0 ? $finder : null);
} | [
"protected",
"function",
"importComponentTranslationFiles",
"(",
"array",
"$",
"locales",
",",
"array",
"$",
"domains",
")",
"{",
"$",
"classes",
"=",
"array",
"(",
"'Symfony\\Component\\Validator\\Validation'",
"=>",
"'/Resources/translations'",
",",
"'Symfony\\Component... | Imports Symfony's components translation files.
@param array $locales
@param array $domains | [
"Imports",
"Symfony",
"s",
"components",
"translation",
"files",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ImportTranslationsCommand.php#L172-L192 | train |
lexik/LexikTranslationBundle | Command/ImportTranslationsCommand.php | ImportTranslationsCommand.importAppTranslationFiles | protected function importAppTranslationFiles(array $locales, array $domains)
{
if (Kernel::MAJOR_VERSION >= 4) {
$translationPath = $this->getApplication()->getKernel()->getProjectDir().'/translations';
$finder = $this->findTranslationsFiles($translationPath, $locales, $domains, false);
} else {
$finder = $this->findTranslationsFiles($this->getApplication()->getKernel()->getRootDir(), $locales, $domains);
}
$this->importTranslationFiles($finder);
} | php | protected function importAppTranslationFiles(array $locales, array $domains)
{
if (Kernel::MAJOR_VERSION >= 4) {
$translationPath = $this->getApplication()->getKernel()->getProjectDir().'/translations';
$finder = $this->findTranslationsFiles($translationPath, $locales, $domains, false);
} else {
$finder = $this->findTranslationsFiles($this->getApplication()->getKernel()->getRootDir(), $locales, $domains);
}
$this->importTranslationFiles($finder);
} | [
"protected",
"function",
"importAppTranslationFiles",
"(",
"array",
"$",
"locales",
",",
"array",
"$",
"domains",
")",
"{",
"if",
"(",
"Kernel",
"::",
"MAJOR_VERSION",
">=",
"4",
")",
"{",
"$",
"translationPath",
"=",
"$",
"this",
"->",
"getApplication",
"("... | Imports application translation files.
@param array $locales
@param array $domains | [
"Imports",
"application",
"translation",
"files",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ImportTranslationsCommand.php#L200-L209 | train |
lexik/LexikTranslationBundle | Command/ImportTranslationsCommand.php | ImportTranslationsCommand.importBundlesTranslationFiles | protected function importBundlesTranslationFiles(array $locales, array $domains, $global = false)
{
$bundles = $this->getApplication()->getKernel()->getBundles();
foreach ($bundles as $bundle) {
$this->importBundleTranslationFiles($bundle, $locales, $domains, $global);
}
} | php | protected function importBundlesTranslationFiles(array $locales, array $domains, $global = false)
{
$bundles = $this->getApplication()->getKernel()->getBundles();
foreach ($bundles as $bundle) {
$this->importBundleTranslationFiles($bundle, $locales, $domains, $global);
}
} | [
"protected",
"function",
"importBundlesTranslationFiles",
"(",
"array",
"$",
"locales",
",",
"array",
"$",
"domains",
",",
"$",
"global",
"=",
"false",
")",
"{",
"$",
"bundles",
"=",
"$",
"this",
"->",
"getApplication",
"(",
")",
"->",
"getKernel",
"(",
")... | Imports translation files form all bundles.
@param array $locales
@param array $domains
@param boolean $global | [
"Imports",
"translation",
"files",
"form",
"all",
"bundles",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ImportTranslationsCommand.php#L218-L225 | train |
lexik/LexikTranslationBundle | Command/ImportTranslationsCommand.php | ImportTranslationsCommand.importBundleTranslationFiles | protected function importBundleTranslationFiles(BundleInterface $bundle, $locales, $domains, $global = false)
{
$path = $bundle->getPath();
if ($global) {
$path = $this->getApplication()->getKernel()->getRootDir() . '/Resources/' . $bundle->getName() . '/translations';
$this->output->writeln('<info>*** Importing ' . $bundle->getName() . '`s translation files from ' . $path . ' ***</info>');
}
$this->output->writeln(sprintf('<info># %s:</info>', $bundle->getName()));
$finder = $this->findTranslationsFiles($path, $locales, $domains);
$this->importTranslationFiles($finder);
} | php | protected function importBundleTranslationFiles(BundleInterface $bundle, $locales, $domains, $global = false)
{
$path = $bundle->getPath();
if ($global) {
$path = $this->getApplication()->getKernel()->getRootDir() . '/Resources/' . $bundle->getName() . '/translations';
$this->output->writeln('<info>*** Importing ' . $bundle->getName() . '`s translation files from ' . $path . ' ***</info>');
}
$this->output->writeln(sprintf('<info># %s:</info>', $bundle->getName()));
$finder = $this->findTranslationsFiles($path, $locales, $domains);
$this->importTranslationFiles($finder);
} | [
"protected",
"function",
"importBundleTranslationFiles",
"(",
"BundleInterface",
"$",
"bundle",
",",
"$",
"locales",
",",
"$",
"domains",
",",
"$",
"global",
"=",
"false",
")",
"{",
"$",
"path",
"=",
"$",
"bundle",
"->",
"getPath",
"(",
")",
";",
"if",
"... | Imports translation files form the specific bundles.
@param BundleInterface $bundle
@param array $locales
@param array $domains
@param boolean $global | [
"Imports",
"translation",
"files",
"form",
"the",
"specific",
"bundles",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ImportTranslationsCommand.php#L235-L246 | train |
lexik/LexikTranslationBundle | Command/ImportTranslationsCommand.php | ImportTranslationsCommand.importTranslationFiles | protected function importTranslationFiles($finder)
{
if (!$finder instanceof Finder) {
$this->output->writeln('No file to import');
return;
}
$importer = $this->getContainer()->get('lexik_translation.importer.file');
$importer->setCaseInsensitiveInsert($this->input->getOption('case-insensitive'));
foreach ($finder as $file) {
$this->output->write(sprintf('Importing <comment>"%s"</comment> ... ', $file->getPathname()));
$number = $importer->import($file, $this->input->getOption('force'), $this->input->getOption('merge'));
$this->output->writeln(sprintf('%d translations', $number));
$skipped = $importer->getSkippedKeys();
if (count($skipped) > 0) {
$this->output->writeln(sprintf(' <error>[!]</error> The following keys has been skipped: "%s".', implode('", "', $skipped)));
}
}
} | php | protected function importTranslationFiles($finder)
{
if (!$finder instanceof Finder) {
$this->output->writeln('No file to import');
return;
}
$importer = $this->getContainer()->get('lexik_translation.importer.file');
$importer->setCaseInsensitiveInsert($this->input->getOption('case-insensitive'));
foreach ($finder as $file) {
$this->output->write(sprintf('Importing <comment>"%s"</comment> ... ', $file->getPathname()));
$number = $importer->import($file, $this->input->getOption('force'), $this->input->getOption('merge'));
$this->output->writeln(sprintf('%d translations', $number));
$skipped = $importer->getSkippedKeys();
if (count($skipped) > 0) {
$this->output->writeln(sprintf(' <error>[!]</error> The following keys has been skipped: "%s".', implode('", "', $skipped)));
}
}
} | [
"protected",
"function",
"importTranslationFiles",
"(",
"$",
"finder",
")",
"{",
"if",
"(",
"!",
"$",
"finder",
"instanceof",
"Finder",
")",
"{",
"$",
"this",
"->",
"output",
"->",
"writeln",
"(",
"'No file to import'",
")",
";",
"return",
";",
"}",
"$",
... | Imports some translations files.
@param Finder $finder | [
"Imports",
"some",
"translations",
"files",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Command/ImportTranslationsCommand.php#L253-L274 | train |
lexik/LexikTranslationBundle | EventDispatcher/CleanTranslationCacheListener.php | CleanTranslationCacheListener.isCacheExpired | private function isCacheExpired()
{
if (empty($this->cacheInterval)) {
return true;
}
$cache_file = $this->cacheDirectory.'/translations/cache_timestamp';
$cache_dir =$this->cacheDirectory.'/translations';
if ('\\' === DIRECTORY_SEPARATOR) {
$cache_file = strtr($cache_file, '/', '\\');
$cache_dir = strtr($cache_dir, '/', '\\');
}
if (!\is_dir($cache_dir)) {
\mkdir($cache_dir);
}
if (!\file_exists($cache_file)) {
\touch($cache_file);
return true;
}
$expired = false;
if ((\time() - \filemtime($cache_file)) > $this->cacheInterval) {
\file_put_contents($cache_file, \time());
$expired = true;
}
return $expired;
} | php | private function isCacheExpired()
{
if (empty($this->cacheInterval)) {
return true;
}
$cache_file = $this->cacheDirectory.'/translations/cache_timestamp';
$cache_dir =$this->cacheDirectory.'/translations';
if ('\\' === DIRECTORY_SEPARATOR) {
$cache_file = strtr($cache_file, '/', '\\');
$cache_dir = strtr($cache_dir, '/', '\\');
}
if (!\is_dir($cache_dir)) {
\mkdir($cache_dir);
}
if (!\file_exists($cache_file)) {
\touch($cache_file);
return true;
}
$expired = false;
if ((\time() - \filemtime($cache_file)) > $this->cacheInterval) {
\file_put_contents($cache_file, \time());
$expired = true;
}
return $expired;
} | [
"private",
"function",
"isCacheExpired",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"cacheInterval",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"cache_file",
"=",
"$",
"this",
"->",
"cacheDirectory",
".",
"'/translations/cache_timestamp'... | Checks if cache has expired
@return boolean | [
"Checks",
"if",
"cache",
"has",
"expired"
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/EventDispatcher/CleanTranslationCacheListener.php#L87-L113 | train |
lexik/LexikTranslationBundle | Controller/TranslationController.php | TranslationController.overviewAction | public function overviewAction()
{
/** @var StorageInterface $storage */
$storage = $this->get('lexik_translation.translation_storage');
$stats = $this->get('lexik_translation.overview.stats_aggregator')->getStats();
return $this->render('@LexikTranslation/Translation/overview.html.twig', array(
'layout' => $this->container->getParameter('lexik_translation.base_layout'),
'locales' => $this->getManagedLocales(),
'domains' => $storage->getTransUnitDomains(),
'latestTrans' => $storage->getLatestUpdatedAt(),
'stats' => $stats,
));
} | php | public function overviewAction()
{
/** @var StorageInterface $storage */
$storage = $this->get('lexik_translation.translation_storage');
$stats = $this->get('lexik_translation.overview.stats_aggregator')->getStats();
return $this->render('@LexikTranslation/Translation/overview.html.twig', array(
'layout' => $this->container->getParameter('lexik_translation.base_layout'),
'locales' => $this->getManagedLocales(),
'domains' => $storage->getTransUnitDomains(),
'latestTrans' => $storage->getLatestUpdatedAt(),
'stats' => $stats,
));
} | [
"public",
"function",
"overviewAction",
"(",
")",
"{",
"/** @var StorageInterface $storage */",
"$",
"storage",
"=",
"$",
"this",
"->",
"get",
"(",
"'lexik_translation.translation_storage'",
")",
";",
"$",
"stats",
"=",
"$",
"this",
"->",
"get",
"(",
"'lexik_trans... | Display an overview of the translation status per domain.
@return \Symfony\Component\HttpFoundation\Response | [
"Display",
"an",
"overview",
"of",
"the",
"translation",
"status",
"per",
"domain",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Controller/TranslationController.php#L24-L38 | train |
lexik/LexikTranslationBundle | Controller/TranslationController.php | TranslationController.gridAction | public function gridAction()
{
$tokens = null;
if ($this->container->getParameter('lexik_translation.dev_tools.enable')) {
$tokens = $this->get('lexik_translation.token_finder')->find();
}
return $this->render('@LexikTranslation/Translation/grid.html.twig', array(
'layout' => $this->container->getParameter('lexik_translation.base_layout'),
'inputType' => $this->container->getParameter('lexik_translation.grid_input_type'),
'autoCacheClean' => $this->container->getParameter('lexik_translation.auto_cache_clean'),
'toggleSimilar' => $this->container->getParameter('lexik_translation.grid_toggle_similar'),
'locales' => $this->getManagedLocales(),
'tokens' => $tokens,
));
} | php | public function gridAction()
{
$tokens = null;
if ($this->container->getParameter('lexik_translation.dev_tools.enable')) {
$tokens = $this->get('lexik_translation.token_finder')->find();
}
return $this->render('@LexikTranslation/Translation/grid.html.twig', array(
'layout' => $this->container->getParameter('lexik_translation.base_layout'),
'inputType' => $this->container->getParameter('lexik_translation.grid_input_type'),
'autoCacheClean' => $this->container->getParameter('lexik_translation.auto_cache_clean'),
'toggleSimilar' => $this->container->getParameter('lexik_translation.grid_toggle_similar'),
'locales' => $this->getManagedLocales(),
'tokens' => $tokens,
));
} | [
"public",
"function",
"gridAction",
"(",
")",
"{",
"$",
"tokens",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"container",
"->",
"getParameter",
"(",
"'lexik_translation.dev_tools.enable'",
")",
")",
"{",
"$",
"tokens",
"=",
"$",
"this",
"->",
"get",
... | Display the translation grid.
@return \Symfony\Component\HttpFoundation\Response | [
"Display",
"the",
"translation",
"grid",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Controller/TranslationController.php#L45-L60 | train |
lexik/LexikTranslationBundle | Controller/TranslationController.php | TranslationController.invalidateCacheAction | public function invalidateCacheAction(Request $request)
{
$this->get('lexik_translation.translator')->removeLocalesCacheFiles($this->getManagedLocales());
$message = $this->get('translator')->trans('translations.cache_removed', array(), 'LexikTranslationBundle');
if ($request->isXmlHttpRequest()) {
$this->checkCsrf();
return new JsonResponse(array('message' => $message));
}
$this->get('session')->getFlashBag()->add('success', $message);
return $this->redirect($this->generateUrl('lexik_translation_grid'));
} | php | public function invalidateCacheAction(Request $request)
{
$this->get('lexik_translation.translator')->removeLocalesCacheFiles($this->getManagedLocales());
$message = $this->get('translator')->trans('translations.cache_removed', array(), 'LexikTranslationBundle');
if ($request->isXmlHttpRequest()) {
$this->checkCsrf();
return new JsonResponse(array('message' => $message));
}
$this->get('session')->getFlashBag()->add('success', $message);
return $this->redirect($this->generateUrl('lexik_translation_grid'));
} | [
"public",
"function",
"invalidateCacheAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"get",
"(",
"'lexik_translation.translator'",
")",
"->",
"removeLocalesCacheFiles",
"(",
"$",
"this",
"->",
"getManagedLocales",
"(",
")",
")",
";",
"$",
... | Remove cache files for managed locales.
@return \Symfony\Component\HttpFoundation\RedirectResponse | [
"Remove",
"cache",
"files",
"for",
"managed",
"locales",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Controller/TranslationController.php#L67-L82 | train |
lexik/LexikTranslationBundle | Controller/TranslationController.php | TranslationController.newAction | public function newAction(Request $request)
{
$handler = $this->get('lexik_translation.form.handler.trans_unit');
$form = $this->createForm(TransUnitType::class, $handler->createFormData(), $handler->getFormOptions());
if ($handler->process($form, $request)) {
$message = $this->get('translator')->trans('translations.successfully_added', array(), 'LexikTranslationBundle');
$this->get('session')->getFlashBag()->add('success', $message);
$redirectUrl = $form->get('save_add')->isClicked() ? 'lexik_translation_new' : 'lexik_translation_grid';
return $this->redirect($this->generateUrl($redirectUrl));
}
return $this->render('@LexikTranslation/Translation/new.html.twig', array(
'layout' => $this->container->getParameter('lexik_translation.base_layout'),
'form' => $form->createView(),
));
} | php | public function newAction(Request $request)
{
$handler = $this->get('lexik_translation.form.handler.trans_unit');
$form = $this->createForm(TransUnitType::class, $handler->createFormData(), $handler->getFormOptions());
if ($handler->process($form, $request)) {
$message = $this->get('translator')->trans('translations.successfully_added', array(), 'LexikTranslationBundle');
$this->get('session')->getFlashBag()->add('success', $message);
$redirectUrl = $form->get('save_add')->isClicked() ? 'lexik_translation_new' : 'lexik_translation_grid';
return $this->redirect($this->generateUrl($redirectUrl));
}
return $this->render('@LexikTranslation/Translation/new.html.twig', array(
'layout' => $this->container->getParameter('lexik_translation.base_layout'),
'form' => $form->createView(),
));
} | [
"public",
"function",
"newAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"handler",
"=",
"$",
"this",
"->",
"get",
"(",
"'lexik_translation.form.handler.trans_unit'",
")",
";",
"$",
"form",
"=",
"$",
"this",
"->",
"createForm",
"(",
"TransUnitType",
... | Add a new trans unit with translation for managed locales.
@return \Symfony\Component\HttpFoundation\Response | [
"Add",
"a",
"new",
"trans",
"unit",
"with",
"translation",
"for",
"managed",
"locales",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Controller/TranslationController.php#L89-L109 | train |
lexik/LexikTranslationBundle | Translation/Exporter/XliffExporter.php | XliffExporter.addRootNodes | protected function addRootNodes(\DOMDocument $dom, $targetLanguage = null)
{
$xliff = $dom->appendChild($dom->createElement('xliff'));
$xliff->appendChild(new \DOMAttr('xmlns', 'urn:oasis:names:tc:xliff:document:1.2'));
$xliff->appendChild(new \DOMAttr('version', '1.2'));
$fileNode = $xliff->appendChild($dom->createElement('file'));
$fileNode->appendChild(new \DOMAttr('source-language', 'en'));
$fileNode->appendChild(new \DOMAttr('datatype', 'plaintext'));
$fileNode->appendChild(new \DOMAttr('original', 'file.ext'));
if (!is_null($targetLanguage)) {
$fileNode->appendChild(new \DOMAttr('target-language', $targetLanguage));
}
$bodyNode = $fileNode->appendChild($dom->createElement('body'));
return $bodyNode;
} | php | protected function addRootNodes(\DOMDocument $dom, $targetLanguage = null)
{
$xliff = $dom->appendChild($dom->createElement('xliff'));
$xliff->appendChild(new \DOMAttr('xmlns', 'urn:oasis:names:tc:xliff:document:1.2'));
$xliff->appendChild(new \DOMAttr('version', '1.2'));
$fileNode = $xliff->appendChild($dom->createElement('file'));
$fileNode->appendChild(new \DOMAttr('source-language', 'en'));
$fileNode->appendChild(new \DOMAttr('datatype', 'plaintext'));
$fileNode->appendChild(new \DOMAttr('original', 'file.ext'));
if (!is_null($targetLanguage)) {
$fileNode->appendChild(new \DOMAttr('target-language', $targetLanguage));
}
$bodyNode = $fileNode->appendChild($dom->createElement('body'));
return $bodyNode;
} | [
"protected",
"function",
"addRootNodes",
"(",
"\\",
"DOMDocument",
"$",
"dom",
",",
"$",
"targetLanguage",
"=",
"null",
")",
"{",
"$",
"xliff",
"=",
"$",
"dom",
"->",
"appendChild",
"(",
"$",
"dom",
"->",
"createElement",
"(",
"'xliff'",
")",
")",
";",
... | Add root nodes to a document.
@param \DOMDocument $dom
@param string|null $targetLanguage
@return \DOMElement | [
"Add",
"root",
"nodes",
"to",
"a",
"document",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Exporter/XliffExporter.php#L67-L85 | train |
lexik/LexikTranslationBundle | Translation/Exporter/XliffExporter.php | XliffExporter.createTranslationNode | protected function createTranslationNode(\DOMDocument $dom, $id, $key, $value)
{
$translationNode = $dom->createElement('trans-unit');
$translationNode->appendChild(new \DOMAttr('id', $id));
/**
* @see http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#approved
*/
if ($value != '') {
$translationNode->appendChild(new \DOMAttr('approved', 'yes'));
}
$source = $dom->createElement('source');
$source->appendChild($dom->createCDATASection($key));
$translationNode->appendChild($source);
$target = $dom->createElement('target');
$target->appendChild($dom->createCDATASection($value));
$translationNode->appendChild($target);
return $translationNode;
} | php | protected function createTranslationNode(\DOMDocument $dom, $id, $key, $value)
{
$translationNode = $dom->createElement('trans-unit');
$translationNode->appendChild(new \DOMAttr('id', $id));
/**
* @see http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html#approved
*/
if ($value != '') {
$translationNode->appendChild(new \DOMAttr('approved', 'yes'));
}
$source = $dom->createElement('source');
$source->appendChild($dom->createCDATASection($key));
$translationNode->appendChild($source);
$target = $dom->createElement('target');
$target->appendChild($dom->createCDATASection($value));
$translationNode->appendChild($target);
return $translationNode;
} | [
"protected",
"function",
"createTranslationNode",
"(",
"\\",
"DOMDocument",
"$",
"dom",
",",
"$",
"id",
",",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"translationNode",
"=",
"$",
"dom",
"->",
"createElement",
"(",
"'trans-unit'",
")",
";",
"$",
"tra... | Create a new trans-unit node.
@param \DOMDocument $dom
@param int $id
@param string $key
@param string $value
@return \DOMElement | [
"Create",
"a",
"new",
"trans",
"-",
"unit",
"node",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Exporter/XliffExporter.php#L96-L117 | train |
lexik/LexikTranslationBundle | Propel/TransUnit.php | TransUnit.filterNotBlankTranslations | public function filterNotBlankTranslations()
{
return array_filter($this->getTranslations()->getArrayCopy(), function (TranslationInterface $translation) {
$content = $translation->getContent();
return !empty($content);
});
} | php | public function filterNotBlankTranslations()
{
return array_filter($this->getTranslations()->getArrayCopy(), function (TranslationInterface $translation) {
$content = $translation->getContent();
return !empty($content);
});
} | [
"public",
"function",
"filterNotBlankTranslations",
"(",
")",
"{",
"return",
"array_filter",
"(",
"$",
"this",
"->",
"getTranslations",
"(",
")",
"->",
"getArrayCopy",
"(",
")",
",",
"function",
"(",
"TranslationInterface",
"$",
"translation",
")",
"{",
"$",
"... | Return translations with not blank content.
@return array | [
"Return",
"translations",
"with",
"not",
"blank",
"content",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Propel/TransUnit.php#L19-L26 | train |
lexik/LexikTranslationBundle | Translation/Translator.php | Translator.addDatabaseResources | public function addDatabaseResources()
{
$resources = array();
$file = sprintf('%s/database.resources.php', $this->options['cache_dir']);
$cache = new ConfigCache($file, $this->options['debug']);
if (!$cache->isFresh()) {
$event = new GetDatabaseResourcesEvent();
$this->container->get('event_dispatcher')->dispatch('lexik_translation.event.get_database_resources', $event);
$resources = $event->getResources();
$metadata = array();
foreach ($resources as $resource) {
$metadata[] = new DatabaseFreshResource($resource['locale'], $resource['domain']);
}
$content = sprintf("<?php return %s;", var_export($resources, true));
$cache->write($content, $metadata);
} else {
$resources = include $file;
}
foreach ($resources as $resource) {
$this->addResource('database', 'DB', $resource['locale'], $resource['domain']);
}
} | php | public function addDatabaseResources()
{
$resources = array();
$file = sprintf('%s/database.resources.php', $this->options['cache_dir']);
$cache = new ConfigCache($file, $this->options['debug']);
if (!$cache->isFresh()) {
$event = new GetDatabaseResourcesEvent();
$this->container->get('event_dispatcher')->dispatch('lexik_translation.event.get_database_resources', $event);
$resources = $event->getResources();
$metadata = array();
foreach ($resources as $resource) {
$metadata[] = new DatabaseFreshResource($resource['locale'], $resource['domain']);
}
$content = sprintf("<?php return %s;", var_export($resources, true));
$cache->write($content, $metadata);
} else {
$resources = include $file;
}
foreach ($resources as $resource) {
$this->addResource('database', 'DB', $resource['locale'], $resource['domain']);
}
} | [
"public",
"function",
"addDatabaseResources",
"(",
")",
"{",
"$",
"resources",
"=",
"array",
"(",
")",
";",
"$",
"file",
"=",
"sprintf",
"(",
"'%s/database.resources.php'",
",",
"$",
"this",
"->",
"options",
"[",
"'cache_dir'",
"]",
")",
";",
"$",
"cache",... | Add all resources available in database. | [
"Add",
"all",
"resources",
"available",
"in",
"database",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Translator.php#L23-L49 | train |
lexik/LexikTranslationBundle | Translation/Translator.php | Translator.removeCacheFile | public function removeCacheFile($locale)
{
$localeExploded = explode('_', $locale);
$finder = new Finder();
$finder->files()->in($this->options['cache_dir'])->name(sprintf( '/catalogue\.%s.*\.php$/', $localeExploded[0]));
$deleted = true;
foreach ($finder as $file) {
$path = $file->getRealPath();
$this->invalidateSystemCacheForFile($path);
$deleted = unlink($path);
$metadata = $path.'.meta';
if (file_exists($metadata)) {
$this->invalidateSystemCacheForFile($metadata);
unlink($metadata);
}
}
return $deleted;
} | php | public function removeCacheFile($locale)
{
$localeExploded = explode('_', $locale);
$finder = new Finder();
$finder->files()->in($this->options['cache_dir'])->name(sprintf( '/catalogue\.%s.*\.php$/', $localeExploded[0]));
$deleted = true;
foreach ($finder as $file) {
$path = $file->getRealPath();
$this->invalidateSystemCacheForFile($path);
$deleted = unlink($path);
$metadata = $path.'.meta';
if (file_exists($metadata)) {
$this->invalidateSystemCacheForFile($metadata);
unlink($metadata);
}
}
return $deleted;
} | [
"public",
"function",
"removeCacheFile",
"(",
"$",
"locale",
")",
"{",
"$",
"localeExploded",
"=",
"explode",
"(",
"'_'",
",",
"$",
"locale",
")",
";",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"finder",
"->",
"files",
"(",
")",
"->",
... | Remove the cache file corresponding to the given locale.
@param string $locale
@return boolean | [
"Remove",
"the",
"cache",
"file",
"corresponding",
"to",
"the",
"given",
"locale",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Translator.php#L57-L77 | train |
lexik/LexikTranslationBundle | Translation/Translator.php | Translator.removeLocalesCacheFiles | public function removeLocalesCacheFiles(array $locales)
{
foreach ($locales as $locale) {
$this->removeCacheFile($locale);
}
// also remove database.resources.php cache file
$file = sprintf('%s/database.resources.php', $this->options['cache_dir']);
if (file_exists($file)) {
$this->invalidateSystemCacheForFile($file);
unlink($file);
}
$metadata = $file.'.meta';
if (file_exists($metadata)) {
$this->invalidateSystemCacheForFile($metadata);
unlink($metadata);
}
} | php | public function removeLocalesCacheFiles(array $locales)
{
foreach ($locales as $locale) {
$this->removeCacheFile($locale);
}
// also remove database.resources.php cache file
$file = sprintf('%s/database.resources.php', $this->options['cache_dir']);
if (file_exists($file)) {
$this->invalidateSystemCacheForFile($file);
unlink($file);
}
$metadata = $file.'.meta';
if (file_exists($metadata)) {
$this->invalidateSystemCacheForFile($metadata);
unlink($metadata);
}
} | [
"public",
"function",
"removeLocalesCacheFiles",
"(",
"array",
"$",
"locales",
")",
"{",
"foreach",
"(",
"$",
"locales",
"as",
"$",
"locale",
")",
"{",
"$",
"this",
"->",
"removeCacheFile",
"(",
"$",
"locale",
")",
";",
"}",
"// also remove database.resources.... | Remove the cache file corresponding to each given locale.
@param array $locales | [
"Remove",
"the",
"cache",
"file",
"corresponding",
"to",
"each",
"given",
"locale",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Translator.php#L84-L102 | train |
lexik/LexikTranslationBundle | Translation/Translator.php | Translator.getFormats | public function getFormats()
{
$allFormats = array();
foreach ($this->loaderIds as $id => $formats) {
foreach ($formats as $format) {
if ('database' !== $format) {
$allFormats[] = $format;
}
}
}
return $allFormats;
} | php | public function getFormats()
{
$allFormats = array();
foreach ($this->loaderIds as $id => $formats) {
foreach ($formats as $format) {
if ('database' !== $format) {
$allFormats[] = $format;
}
}
}
return $allFormats;
} | [
"public",
"function",
"getFormats",
"(",
")",
"{",
"$",
"allFormats",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"loaderIds",
"as",
"$",
"id",
"=>",
"$",
"formats",
")",
"{",
"foreach",
"(",
"$",
"formats",
"as",
"$",
"format",
... | Returns all translations file formats.
@return array | [
"Returns",
"all",
"translations",
"file",
"formats",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Translator.php#L127-L140 | train |
lexik/LexikTranslationBundle | Translation/Translator.php | Translator.getLoader | public function getLoader($format)
{
$loader = null;
$i = 0;
$ids = array_keys($this->loaderIds);
while ($i < count($ids) && null === $loader) {
if (in_array($format, $this->loaderIds[$ids[$i]])) {
$loader = $this->container->get($ids[$i]);
}
$i++;
}
if (!($loader instanceof LoaderInterface)) {
throw new \RuntimeException(sprintf('No loader found for "%s" format.', $format));
}
return $loader;
} | php | public function getLoader($format)
{
$loader = null;
$i = 0;
$ids = array_keys($this->loaderIds);
while ($i < count($ids) && null === $loader) {
if (in_array($format, $this->loaderIds[$ids[$i]])) {
$loader = $this->container->get($ids[$i]);
}
$i++;
}
if (!($loader instanceof LoaderInterface)) {
throw new \RuntimeException(sprintf('No loader found for "%s" format.', $format));
}
return $loader;
} | [
"public",
"function",
"getLoader",
"(",
"$",
"format",
")",
"{",
"$",
"loader",
"=",
"null",
";",
"$",
"i",
"=",
"0",
";",
"$",
"ids",
"=",
"array_keys",
"(",
"$",
"this",
"->",
"loaderIds",
")",
";",
"while",
"(",
"$",
"i",
"<",
"count",
"(",
... | Returns a loader according to the given format.
@param string $format
@throws \RuntimeException
@return LoaderInterface | [
"Returns",
"a",
"loader",
"according",
"to",
"the",
"given",
"format",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Translator.php#L149-L167 | train |
lexik/LexikTranslationBundle | EventDispatcher/GetDatabaseResourcesListener.php | GetDatabaseResourcesListener.onGetDatabaseResources | public function onGetDatabaseResources(GetDatabaseResourcesEvent $event)
{
// prevent errors on command such as cache:clear if doctrine schema has not been updated yet
if (StorageInterface::STORAGE_ORM == $this->storageType && !$this->storage->translationsTablesExist()) {
$resources = array();
} else {
$resources = $this->storage->getTransUnitDomainsByLocale();
}
$event->setResources($resources);
} | php | public function onGetDatabaseResources(GetDatabaseResourcesEvent $event)
{
// prevent errors on command such as cache:clear if doctrine schema has not been updated yet
if (StorageInterface::STORAGE_ORM == $this->storageType && !$this->storage->translationsTablesExist()) {
$resources = array();
} else {
$resources = $this->storage->getTransUnitDomainsByLocale();
}
$event->setResources($resources);
} | [
"public",
"function",
"onGetDatabaseResources",
"(",
"GetDatabaseResourcesEvent",
"$",
"event",
")",
"{",
"// prevent errors on command such as cache:clear if doctrine schema has not been updated yet",
"if",
"(",
"StorageInterface",
"::",
"STORAGE_ORM",
"==",
"$",
"this",
"->",
... | Query the database to get translation resources and set it on the event.
@param GetDatabaseResourcesEvent $event | [
"Query",
"the",
"database",
"to",
"get",
"translation",
"resources",
"and",
"set",
"it",
"on",
"the",
"event",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/EventDispatcher/GetDatabaseResourcesListener.php#L38-L48 | train |
lexik/LexikTranslationBundle | Propel/TransUnitRepository.php | TransUnitRepository.filterTransUnitData | protected function filterTransUnitData($unitsData)
{
$cleaned = array();
foreach ($unitsData as $unit) {
/* @var $unit TransUnit */
$transUnit = array(
'id' => $unit['Id'],
'key' => $unit['Key'],
'domain' => $unit['Domain'],
'translations' => array(),
);
foreach ($unit['Translations'] as $translation) {
$transUnit['translations'][] = array(
'locale' => $translation['Locale'],
'content' => $translation['Content'],
);
}
$cleaned[] = $transUnit;
}
return $cleaned;
} | php | protected function filterTransUnitData($unitsData)
{
$cleaned = array();
foreach ($unitsData as $unit) {
/* @var $unit TransUnit */
$transUnit = array(
'id' => $unit['Id'],
'key' => $unit['Key'],
'domain' => $unit['Domain'],
'translations' => array(),
);
foreach ($unit['Translations'] as $translation) {
$transUnit['translations'][] = array(
'locale' => $translation['Locale'],
'content' => $translation['Content'],
);
}
$cleaned[] = $transUnit;
}
return $cleaned;
} | [
"protected",
"function",
"filterTransUnitData",
"(",
"$",
"unitsData",
")",
"{",
"$",
"cleaned",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"unitsData",
"as",
"$",
"unit",
")",
"{",
"/* @var $unit TransUnit */",
"$",
"transUnit",
"=",
"array",
"(",
... | Convert transUnit data with nested translations into the required format.
@param array|PropelArrayCollection $transUnitData
@return array | [
"Convert",
"transUnit",
"data",
"with",
"nested",
"translations",
"into",
"the",
"required",
"format",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Propel/TransUnitRepository.php#L259-L283 | train |
lexik/LexikTranslationBundle | Translation/Importer/FileImporter.php | FileImporter.import | public function import(\Symfony\Component\Finder\SplFileInfo $file, $forceUpdate = false, $merge = false)
{
$this->skippedKeys = array();
$imported = 0;
list($domain, $locale, $extention) = explode('.', $file->getFilename());
if (!isset($this->loaders[$extention])) {
throw new \RuntimeException(sprintf('No load found for "%s" format.', $extention));
}
$messageCatalogue = $this->loaders[$extention]->load($file->getPathname(), $locale, $domain);
$translationFile = $this->fileManager->getFor($file->getFilename(), $file->getPath());
$keys = array();
foreach ($messageCatalogue->all($domain) as $key => $content) {
if (!isset($content)) {
continue; // skip empty translation values
}
$normalizedKey = $this->caseInsensitiveInsert ? strtolower($key) : $key;
if (in_array($normalizedKey, $keys, true)) {
$this->skippedKeys[] = $key;
continue; // skip duplicate keys
}
$transUnit = $this->storage->getTransUnitByKeyAndDomain($key, $domain);
if (!($transUnit instanceof TransUnitInterface)) {
$transUnit = $this->transUnitManager->create($key, $domain);
}
$translation = $this->transUnitManager->addTranslation($transUnit, $locale, $content, $translationFile);
if ($translation instanceof TranslationInterface) {
$imported++;
} else if($forceUpdate) {
$translation = $this->transUnitManager->updateTranslation($transUnit, $locale, $content);
if ($translation instanceof Translation) {
$translation->setModifiedManually(false);
}
$imported++;
} else if($merge) {
$translation = $this->transUnitManager->updateTranslation($transUnit, $locale, $content, false, true);
if ($translation instanceof TranslationInterface) {
$imported++;
}
}
$keys[] = $normalizedKey;
// convert MongoTimestamp objects to time to don't get an error in:
// Doctrine\ODM\MongoDB\Mapping\Types\TimestampType::convertToDatabaseValue()
if ($transUnit instanceof TransUnitDocument) {
$transUnit->convertMongoTimestamp();
}
}
$this->storage->flush();
// clear only Lexik entities
foreach (array('file', 'trans_unit', 'translation') as $name) {
$this->storage->clear($this->storage->getModelClass($name));
}
return $imported;
} | php | public function import(\Symfony\Component\Finder\SplFileInfo $file, $forceUpdate = false, $merge = false)
{
$this->skippedKeys = array();
$imported = 0;
list($domain, $locale, $extention) = explode('.', $file->getFilename());
if (!isset($this->loaders[$extention])) {
throw new \RuntimeException(sprintf('No load found for "%s" format.', $extention));
}
$messageCatalogue = $this->loaders[$extention]->load($file->getPathname(), $locale, $domain);
$translationFile = $this->fileManager->getFor($file->getFilename(), $file->getPath());
$keys = array();
foreach ($messageCatalogue->all($domain) as $key => $content) {
if (!isset($content)) {
continue; // skip empty translation values
}
$normalizedKey = $this->caseInsensitiveInsert ? strtolower($key) : $key;
if (in_array($normalizedKey, $keys, true)) {
$this->skippedKeys[] = $key;
continue; // skip duplicate keys
}
$transUnit = $this->storage->getTransUnitByKeyAndDomain($key, $domain);
if (!($transUnit instanceof TransUnitInterface)) {
$transUnit = $this->transUnitManager->create($key, $domain);
}
$translation = $this->transUnitManager->addTranslation($transUnit, $locale, $content, $translationFile);
if ($translation instanceof TranslationInterface) {
$imported++;
} else if($forceUpdate) {
$translation = $this->transUnitManager->updateTranslation($transUnit, $locale, $content);
if ($translation instanceof Translation) {
$translation->setModifiedManually(false);
}
$imported++;
} else if($merge) {
$translation = $this->transUnitManager->updateTranslation($transUnit, $locale, $content, false, true);
if ($translation instanceof TranslationInterface) {
$imported++;
}
}
$keys[] = $normalizedKey;
// convert MongoTimestamp objects to time to don't get an error in:
// Doctrine\ODM\MongoDB\Mapping\Types\TimestampType::convertToDatabaseValue()
if ($transUnit instanceof TransUnitDocument) {
$transUnit->convertMongoTimestamp();
}
}
$this->storage->flush();
// clear only Lexik entities
foreach (array('file', 'trans_unit', 'translation') as $name) {
$this->storage->clear($this->storage->getModelClass($name));
}
return $imported;
} | [
"public",
"function",
"import",
"(",
"\\",
"Symfony",
"\\",
"Component",
"\\",
"Finder",
"\\",
"SplFileInfo",
"$",
"file",
",",
"$",
"forceUpdate",
"=",
"false",
",",
"$",
"merge",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"skippedKeys",
"=",
"array",
... | Import the given file and return the number of inserted translations.
@param \Symfony\Component\Finder\SplFileInfo $file
@param boolean $forceUpdate force update of the translations
@param boolean $merge merge translations
@return int | [
"Import",
"the",
"given",
"file",
"and",
"return",
"the",
"number",
"of",
"inserted",
"translations",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Importer/FileImporter.php#L92-L159 | train |
lexik/LexikTranslationBundle | Storage/DoctrineORMStorage.php | DoctrineORMStorage.translationsTablesExist | public function translationsTablesExist()
{
/** @var EntityManager $em */
$em = $this->getManager();
$connection = $em->getConnection();
// listDatabases() is not available for SQLite
if ('pdo_sqlite' !== $connection->getDriver()->getName()) {
// init a tmp connection without dbname/path/url in case it does not exist yet
$params = $connection->getParams();
if (isset($params['master'])) {
$params = $params['master'];
}
unset($params['dbname'], $params['path'], $params['url']);
$tmpConnection = DriverManager::getConnection($params);
try {
$dbExists = in_array($connection->getDatabase(), $tmpConnection->getSchemaManager()->listDatabases());
} catch (DBALException $e) {
$dbExists = false;
}
$tmpConnection->close();
if (!$dbExists) {
return false;
}
}
// checks tables exist
$tables = array(
$em->getClassMetadata($this->getModelClass('trans_unit'))->getTableName(),
$em->getClassMetadata($this->getModelClass('translation'))->getTableName(),
);
return $connection->getSchemaManager()->tablesExist($tables);
} | php | public function translationsTablesExist()
{
/** @var EntityManager $em */
$em = $this->getManager();
$connection = $em->getConnection();
// listDatabases() is not available for SQLite
if ('pdo_sqlite' !== $connection->getDriver()->getName()) {
// init a tmp connection without dbname/path/url in case it does not exist yet
$params = $connection->getParams();
if (isset($params['master'])) {
$params = $params['master'];
}
unset($params['dbname'], $params['path'], $params['url']);
$tmpConnection = DriverManager::getConnection($params);
try {
$dbExists = in_array($connection->getDatabase(), $tmpConnection->getSchemaManager()->listDatabases());
} catch (DBALException $e) {
$dbExists = false;
}
$tmpConnection->close();
if (!$dbExists) {
return false;
}
}
// checks tables exist
$tables = array(
$em->getClassMetadata($this->getModelClass('trans_unit'))->getTableName(),
$em->getClassMetadata($this->getModelClass('translation'))->getTableName(),
);
return $connection->getSchemaManager()->tablesExist($tables);
} | [
"public",
"function",
"translationsTablesExist",
"(",
")",
"{",
"/** @var EntityManager $em */",
"$",
"em",
"=",
"$",
"this",
"->",
"getManager",
"(",
")",
";",
"$",
"connection",
"=",
"$",
"em",
"->",
"getConnection",
"(",
")",
";",
"// listDatabases() is not a... | Returns true if translation tables exist.
@return boolean | [
"Returns",
"true",
"if",
"translation",
"tables",
"exist",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Storage/DoctrineORMStorage.php#L21-L57 | train |
lexik/LexikTranslationBundle | Model/TransUnit.php | TransUnit.setTranslations | public function setTranslations(Collection $collection)
{
$this->translations = new ArrayCollection();
foreach ($collection as $translation) {
$this->addTranslation($translation);
}
} | php | public function setTranslations(Collection $collection)
{
$this->translations = new ArrayCollection();
foreach ($collection as $translation) {
$this->addTranslation($translation);
}
} | [
"public",
"function",
"setTranslations",
"(",
"Collection",
"$",
"collection",
")",
"{",
"$",
"this",
"->",
"translations",
"=",
"new",
"ArrayCollection",
"(",
")",
";",
"foreach",
"(",
"$",
"collection",
"as",
"$",
"translation",
")",
"{",
"$",
"this",
"-... | Set translations collection
@param Collection $collection | [
"Set",
"translations",
"collection"
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Model/TransUnit.php#L173-L180 | train |
lexik/LexikTranslationBundle | Model/TransUnit.php | TransUnit.filterNotBlankTranslations | public function filterNotBlankTranslations()
{
return $this->getTranslations()->filter(function (TranslationInterface $translation) {
$content = $translation->getContent();
return !empty($content);
});
} | php | public function filterNotBlankTranslations()
{
return $this->getTranslations()->filter(function (TranslationInterface $translation) {
$content = $translation->getContent();
return !empty($content);
});
} | [
"public",
"function",
"filterNotBlankTranslations",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"getTranslations",
"(",
")",
"->",
"filter",
"(",
"function",
"(",
"TranslationInterface",
"$",
"translation",
")",
"{",
"$",
"content",
"=",
"$",
"translation",
"-... | Return transaltions with not blank content.
@return \Doctrine\Common\Collections\Collection | [
"Return",
"transaltions",
"with",
"not",
"blank",
"content",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Model/TransUnit.php#L187-L193 | train |
lexik/LexikTranslationBundle | Translation/Exporter/YamlExporter.php | YamlExporter.createMultiArray | protected function createMultiArray(array $translations)
{
$res = array();
foreach ($translations as $keyString => $value) {
$keys = explode('.', $keyString);
//$keyString might be "Hello world."
$keyLength = count($keys);
if ($keys[$keyLength - 1] == '') {
unset($keys[$keyLength - 1]);
$keys[$keyLength - 2] .= '.';
}
$this->addValueToMultiArray($res, $value, $keys);
}
return $res;
} | php | protected function createMultiArray(array $translations)
{
$res = array();
foreach ($translations as $keyString => $value) {
$keys = explode('.', $keyString);
//$keyString might be "Hello world."
$keyLength = count($keys);
if ($keys[$keyLength - 1] == '') {
unset($keys[$keyLength - 1]);
$keys[$keyLength - 2] .= '.';
}
$this->addValueToMultiArray($res, $value, $keys);
}
return $res;
} | [
"protected",
"function",
"createMultiArray",
"(",
"array",
"$",
"translations",
")",
"{",
"$",
"res",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"translations",
"as",
"$",
"keyString",
"=>",
"$",
"value",
")",
"{",
"$",
"keys",
"=",
"explode",
"... | Create a multi dimension array.
If you got a array like array('foo.bar.baz'=>'foobar') we will create an array like:
array('foo'=>array('bar'=>array('baz'=>'foobar')))
@param array $translations
@return array | [
"Create",
"a",
"multi",
"dimension",
"array",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Exporter/YamlExporter.php#L52-L70 | train |
lexik/LexikTranslationBundle | Translation/Exporter/YamlExporter.php | YamlExporter.flattenArray | protected function flattenArray($array, $prefix = '')
{
if (is_array($array)) {
foreach ($array as $key => $subarray) {
if (count($array) == 1) {
return $this->flattenArray($subarray, ($prefix == '' ? $prefix : $prefix.'.').$key);
}
$array[$key] = $this->flattenArray($subarray);
}
}
if ($prefix == '') {
return $array;
}
return array($prefix => $array);
} | php | protected function flattenArray($array, $prefix = '')
{
if (is_array($array)) {
foreach ($array as $key => $subarray) {
if (count($array) == 1) {
return $this->flattenArray($subarray, ($prefix == '' ? $prefix : $prefix.'.').$key);
}
$array[$key] = $this->flattenArray($subarray);
}
}
if ($prefix == '') {
return $array;
}
return array($prefix => $array);
} | [
"protected",
"function",
"flattenArray",
"(",
"$",
"array",
",",
"$",
"prefix",
"=",
"''",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"array",
")",
")",
"{",
"foreach",
"(",
"$",
"array",
"as",
"$",
"key",
"=>",
"$",
"subarray",
")",
"{",
"if",
"... | Make sure we flatten the array in the begnning to make a lower tree
@param mixed $array
@param string $prefix
@return mixed | [
"Make",
"sure",
"we",
"flatten",
"the",
"array",
"in",
"the",
"begnning",
"to",
"make",
"a",
"lower",
"tree"
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Translation/Exporter/YamlExporter.php#L110-L127 | train |
lexik/LexikTranslationBundle | Manager/FileManager.php | FileManager.getFileRelativePath | protected function getFileRelativePath($filePath)
{
$commonParts = array();
// replace window \ to work with /
$rootDir = (false !== strpos($this->rootDir, '\\')) ? str_replace('\\', '/', $this->rootDir) : $this->rootDir;
$antiSlash = false;
if (false !== strpos($filePath, '\\')) {
$filePath = str_replace('\\', '/', $filePath);
$antiSlash = true;
}
$rootDirParts = explode('/', $rootDir);
$filePathParts = explode('/', $filePath);
$i = 0;
while ($i < count($rootDirParts)) {
if (isset($rootDirParts[$i], $filePathParts[$i]) && $rootDirParts[$i] == $filePathParts[$i]) {
$commonParts[] = $rootDirParts[$i];
}
$i++;
}
$filePath = str_replace(implode('/', $commonParts).'/', '', $filePath);
$nbCommonParts = count($commonParts);
$nbRootParts = count($rootDirParts);
for ($i = $nbCommonParts; $i < $nbRootParts; $i++) {
$filePath = '../'.$filePath;
}
return $antiSlash ? str_replace('/', '\\', $filePath) : $filePath;
} | php | protected function getFileRelativePath($filePath)
{
$commonParts = array();
// replace window \ to work with /
$rootDir = (false !== strpos($this->rootDir, '\\')) ? str_replace('\\', '/', $this->rootDir) : $this->rootDir;
$antiSlash = false;
if (false !== strpos($filePath, '\\')) {
$filePath = str_replace('\\', '/', $filePath);
$antiSlash = true;
}
$rootDirParts = explode('/', $rootDir);
$filePathParts = explode('/', $filePath);
$i = 0;
while ($i < count($rootDirParts)) {
if (isset($rootDirParts[$i], $filePathParts[$i]) && $rootDirParts[$i] == $filePathParts[$i]) {
$commonParts[] = $rootDirParts[$i];
}
$i++;
}
$filePath = str_replace(implode('/', $commonParts).'/', '', $filePath);
$nbCommonParts = count($commonParts);
$nbRootParts = count($rootDirParts);
for ($i = $nbCommonParts; $i < $nbRootParts; $i++) {
$filePath = '../'.$filePath;
}
return $antiSlash ? str_replace('/', '\\', $filePath) : $filePath;
} | [
"protected",
"function",
"getFileRelativePath",
"(",
"$",
"filePath",
")",
"{",
"$",
"commonParts",
"=",
"array",
"(",
")",
";",
"// replace window \\ to work with /",
"$",
"rootDir",
"=",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"this",
"->",
"rootDir",
",",
... | Returns the relative according to the kernel.root_dir value.
@param string $filePath
@return string | [
"Returns",
"the",
"relative",
"according",
"to",
"the",
"kernel",
".",
"root_dir",
"value",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Manager/FileManager.php#L94-L128 | train |
lexik/LexikTranslationBundle | Util/DataGrid/DataGridRequestHandler.php | DataGridRequestHandler.getPage | public function getPage(Request $request)
{
$parameters = $this->fixParameters($request->query->all());
$transUnits = $this->storage->getTransUnitList(
$this->localeManager->getLocales(),
$request->query->get('rows', 20),
$request->query->get('page', 1),
$parameters
);
$count = $this->storage->countTransUnits($this->localeManager->getLocales(), $parameters);
return array($transUnits, $count);
} | php | public function getPage(Request $request)
{
$parameters = $this->fixParameters($request->query->all());
$transUnits = $this->storage->getTransUnitList(
$this->localeManager->getLocales(),
$request->query->get('rows', 20),
$request->query->get('page', 1),
$parameters
);
$count = $this->storage->countTransUnits($this->localeManager->getLocales(), $parameters);
return array($transUnits, $count);
} | [
"public",
"function",
"getPage",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"parameters",
"=",
"$",
"this",
"->",
"fixParameters",
"(",
"$",
"request",
"->",
"query",
"->",
"all",
"(",
")",
")",
";",
"$",
"transUnits",
"=",
"$",
"this",
"->",
"st... | Returns an array with the trans unit for the current page and the total of trans units
@param Request $request
@return array | [
"Returns",
"an",
"array",
"with",
"the",
"trans",
"unit",
"for",
"the",
"current",
"page",
"and",
"the",
"total",
"of",
"trans",
"units"
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Util/DataGrid/DataGridRequestHandler.php#L104-L118 | train |
lexik/LexikTranslationBundle | Util/DataGrid/DataGridRequestHandler.php | DataGridRequestHandler.getPageByToken | public function getPageByToken(Request $request, $token)
{
list($transUnits, $count) = $this->getByToken($token);
$parameters = $this->fixParameters($request->query->all());
return $this->filterTokenTranslations($transUnits, $count, $parameters);
} | php | public function getPageByToken(Request $request, $token)
{
list($transUnits, $count) = $this->getByToken($token);
$parameters = $this->fixParameters($request->query->all());
return $this->filterTokenTranslations($transUnits, $count, $parameters);
} | [
"public",
"function",
"getPageByToken",
"(",
"Request",
"$",
"request",
",",
"$",
"token",
")",
"{",
"list",
"(",
"$",
"transUnits",
",",
"$",
"count",
")",
"=",
"$",
"this",
"->",
"getByToken",
"(",
"$",
"token",
")",
";",
"$",
"parameters",
"=",
"$... | Returns an array with the trans unit for the current profile page.
@param Request $request
@param string $token
@return array | [
"Returns",
"an",
"array",
"with",
"the",
"trans",
"unit",
"for",
"the",
"current",
"profile",
"page",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Util/DataGrid/DataGridRequestHandler.php#L127-L134 | train |
lexik/LexikTranslationBundle | Util/DataGrid/DataGridRequestHandler.php | DataGridRequestHandler.getByToken | public function getByToken($token)
{
if (null === $this->profiler) {
throw new \RuntimeException('Invalid profiler instance.');
}
$profile = $this->profiler->loadProfile($token);
// In case no results were found
if (!$profile instanceof Profile) {
return array(array(), 0);
}
try {
/** @var TranslationDataCollector $collector */
$collector = $profile->getCollector('translation');
$messages = $collector->getMessages();
$transUnits = array();
foreach ($messages as $message) {
$transUnit = $this->storage->getTransUnitByKeyAndDomain($message['id'], $message['domain']);
if ($transUnit instanceof TransUnit) {
$transUnits[] = $transUnit;
} elseif (true === $this->createMissing) {
$transUnits[] = $transUnit = $this->transUnitManager->create($message['id'], $message['domain'], true);
}
// Also store the translation if profiler state was defined
if (!$transUnit->hasTranslation($message['locale']) && $message['state'] === DataCollectorTranslator::MESSAGE_DEFINED) {
$file = $this->fileManager->getFor(sprintf('%s.%s.%s', $message['domain'], $message['locale'], $this->defaultFileFormat));
$this->transUnitManager->addTranslation($transUnit, $message['locale'], $message['translation'], $file, true);
}
}
return array($transUnits, count($transUnits));
} catch (\InvalidArgumentException $e) {
// Translation collector is a 2.7 feature
return array(array(), 0);
}
} | php | public function getByToken($token)
{
if (null === $this->profiler) {
throw new \RuntimeException('Invalid profiler instance.');
}
$profile = $this->profiler->loadProfile($token);
// In case no results were found
if (!$profile instanceof Profile) {
return array(array(), 0);
}
try {
/** @var TranslationDataCollector $collector */
$collector = $profile->getCollector('translation');
$messages = $collector->getMessages();
$transUnits = array();
foreach ($messages as $message) {
$transUnit = $this->storage->getTransUnitByKeyAndDomain($message['id'], $message['domain']);
if ($transUnit instanceof TransUnit) {
$transUnits[] = $transUnit;
} elseif (true === $this->createMissing) {
$transUnits[] = $transUnit = $this->transUnitManager->create($message['id'], $message['domain'], true);
}
// Also store the translation if profiler state was defined
if (!$transUnit->hasTranslation($message['locale']) && $message['state'] === DataCollectorTranslator::MESSAGE_DEFINED) {
$file = $this->fileManager->getFor(sprintf('%s.%s.%s', $message['domain'], $message['locale'], $this->defaultFileFormat));
$this->transUnitManager->addTranslation($transUnit, $message['locale'], $message['translation'], $file, true);
}
}
return array($transUnits, count($transUnits));
} catch (\InvalidArgumentException $e) {
// Translation collector is a 2.7 feature
return array(array(), 0);
}
} | [
"public",
"function",
"getByToken",
"(",
"$",
"token",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"profiler",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Invalid profiler instance.'",
")",
";",
"}",
"$",
"profile",
"=",
"$",
"t... | Get a profile's translation messages based on a previous Profiler token.
@param string $token by which a Profile can be found in the Profiler
@return array with collection of TransUnits and it's count | [
"Get",
"a",
"profile",
"s",
"translation",
"messages",
"based",
"on",
"a",
"previous",
"Profiler",
"token",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Util/DataGrid/DataGridRequestHandler.php#L143-L186 | train |
lexik/LexikTranslationBundle | Util/DataGrid/DataGridRequestHandler.php | DataGridRequestHandler.updateFromRequest | public function updateFromRequest($id, Request $request)
{
$transUnit = $this->storage->getTransUnitById($id);
if (!$transUnit) {
throw new NotFoundHttpException(sprintf('No TransUnit found for "%s"', $id));
}
$translationsContent = array();
foreach ($this->localeManager->getLocales() as $locale) {
$translationsContent[$locale] = $request->request->get($locale);
}
$this->transUnitManager->updateTranslationsContent($transUnit, $translationsContent);
if ($transUnit instanceof TransUnitDocument) {
$transUnit->convertMongoTimestamp();
}
$this->storage->flush();
return $transUnit;
} | php | public function updateFromRequest($id, Request $request)
{
$transUnit = $this->storage->getTransUnitById($id);
if (!$transUnit) {
throw new NotFoundHttpException(sprintf('No TransUnit found for "%s"', $id));
}
$translationsContent = array();
foreach ($this->localeManager->getLocales() as $locale) {
$translationsContent[$locale] = $request->request->get($locale);
}
$this->transUnitManager->updateTranslationsContent($transUnit, $translationsContent);
if ($transUnit instanceof TransUnitDocument) {
$transUnit->convertMongoTimestamp();
}
$this->storage->flush();
return $transUnit;
} | [
"public",
"function",
"updateFromRequest",
"(",
"$",
"id",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"transUnit",
"=",
"$",
"this",
"->",
"storage",
"->",
"getTransUnitById",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"$",
"transUnit",
")",
"{",
... | Updates a trans unit from the request.
@param integer $id
@param Request $request
@throws NotFoundHttpException
@return \Lexik\Bundle\TranslationBundle\Model\TransUnit | [
"Updates",
"a",
"trans",
"unit",
"from",
"the",
"request",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Util/DataGrid/DataGridRequestHandler.php#L196-L218 | train |
lexik/LexikTranslationBundle | Manager/TransUnitManager.php | TransUnitManager.getTranslationFile | public function getTranslationFile(TransUnitInterface & $transUnit, $locale)
{
$file = null;
foreach ($transUnit->getTranslations() as $translation) {
if (null !== $file = $translation->getFile()) {
break;
}
}
//if we found a file
if ($file !== null) {
//make sure we got the correct file for this locale and domain
$name = sprintf('%s.%s.%s', $file->getDomain(), $locale, $file->getExtention());
$file = $this->fileManager->getFor($name, $this->kernelRootDir.DIRECTORY_SEPARATOR.$file->getPath());
}
return $file;
} | php | public function getTranslationFile(TransUnitInterface & $transUnit, $locale)
{
$file = null;
foreach ($transUnit->getTranslations() as $translation) {
if (null !== $file = $translation->getFile()) {
break;
}
}
//if we found a file
if ($file !== null) {
//make sure we got the correct file for this locale and domain
$name = sprintf('%s.%s.%s', $file->getDomain(), $locale, $file->getExtention());
$file = $this->fileManager->getFor($name, $this->kernelRootDir.DIRECTORY_SEPARATOR.$file->getPath());
}
return $file;
} | [
"public",
"function",
"getTranslationFile",
"(",
"TransUnitInterface",
"&",
"$",
"transUnit",
",",
"$",
"locale",
")",
"{",
"$",
"file",
"=",
"null",
";",
"foreach",
"(",
"$",
"transUnit",
"->",
"getTranslations",
"(",
")",
"as",
"$",
"translation",
")",
"... | Get the proper File for this TransUnit and locale
@param TransUnitInterface $transUnit
@param string $locale
@return FileInterface|null | [
"Get",
"the",
"proper",
"File",
"for",
"this",
"TransUnit",
"and",
"locale"
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Manager/TransUnitManager.php#L204-L221 | train |
lexik/LexikTranslationBundle | Util/DataGrid/DataGridFormatter.php | DataGridFormatter.format | protected function format($transUnits)
{
$formatted = array();
foreach ($transUnits as $transUnit) {
$formatted[] = $this->formatOne($transUnit);
}
return $formatted;
} | php | protected function format($transUnits)
{
$formatted = array();
foreach ($transUnits as $transUnit) {
$formatted[] = $this->formatOne($transUnit);
}
return $formatted;
} | [
"protected",
"function",
"format",
"(",
"$",
"transUnits",
")",
"{",
"$",
"formatted",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"transUnits",
"as",
"$",
"transUnit",
")",
"{",
"$",
"formatted",
"[",
"]",
"=",
"$",
"this",
"->",
"formatOne",
... | Format the tanslations list.
@param array $transUnits
@return array | [
"Format",
"the",
"tanslations",
"list",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Util/DataGrid/DataGridFormatter.php#L73-L82 | train |
lexik/LexikTranslationBundle | Util/DataGrid/DataGridFormatter.php | DataGridFormatter.formatOne | protected function formatOne($transUnit)
{
if (is_object($transUnit)) {
$transUnit = $this->toArray($transUnit);
} elseif (StorageInterface::STORAGE_MONGODB == $this->storage) {
$transUnit['id'] = $transUnit['_id']->{'$id'};
}
$formatted = array(
'_id' => $transUnit['id'],
'_domain' => $transUnit['domain'],
'_key' => $transUnit['key'],
);
// add locales in the same order as in managed_locales param
foreach ($this->localeManager->getLocales() as $locale) {
$formatted[$locale] = '';
}
// then fill locales value
foreach ($transUnit['translations'] as $translation) {
if (in_array($translation['locale'], $this->localeManager->getLocales())) {
$formatted[$translation['locale']] = $translation['content'];
}
}
return $formatted;
} | php | protected function formatOne($transUnit)
{
if (is_object($transUnit)) {
$transUnit = $this->toArray($transUnit);
} elseif (StorageInterface::STORAGE_MONGODB == $this->storage) {
$transUnit['id'] = $transUnit['_id']->{'$id'};
}
$formatted = array(
'_id' => $transUnit['id'],
'_domain' => $transUnit['domain'],
'_key' => $transUnit['key'],
);
// add locales in the same order as in managed_locales param
foreach ($this->localeManager->getLocales() as $locale) {
$formatted[$locale] = '';
}
// then fill locales value
foreach ($transUnit['translations'] as $translation) {
if (in_array($translation['locale'], $this->localeManager->getLocales())) {
$formatted[$translation['locale']] = $translation['content'];
}
}
return $formatted;
} | [
"protected",
"function",
"formatOne",
"(",
"$",
"transUnit",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"transUnit",
")",
")",
"{",
"$",
"transUnit",
"=",
"$",
"this",
"->",
"toArray",
"(",
"$",
"transUnit",
")",
";",
"}",
"elseif",
"(",
"StorageInter... | Format a single TransUnit.
@param array $transUnit
@return array | [
"Format",
"a",
"single",
"TransUnit",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Util/DataGrid/DataGridFormatter.php#L90-L117 | train |
lexik/LexikTranslationBundle | Util/DataGrid/DataGridFormatter.php | DataGridFormatter.toArray | protected function toArray(TransUnitInterface $transUnit)
{
$data = array(
'id' => $transUnit->getId(),
'domain' => $transUnit->getDomain(),
'key' => $transUnit->getKey(),
'translations' => array(),
);
foreach ($transUnit->getTranslations() as $translation) {
$data['translations'][] = array(
'locale' => $translation->getLocale(),
'content' => $translation->getContent(),
);
}
return $data;
} | php | protected function toArray(TransUnitInterface $transUnit)
{
$data = array(
'id' => $transUnit->getId(),
'domain' => $transUnit->getDomain(),
'key' => $transUnit->getKey(),
'translations' => array(),
);
foreach ($transUnit->getTranslations() as $translation) {
$data['translations'][] = array(
'locale' => $translation->getLocale(),
'content' => $translation->getContent(),
);
}
return $data;
} | [
"protected",
"function",
"toArray",
"(",
"TransUnitInterface",
"$",
"transUnit",
")",
"{",
"$",
"data",
"=",
"array",
"(",
"'id'",
"=>",
"$",
"transUnit",
"->",
"getId",
"(",
")",
",",
"'domain'",
"=>",
"$",
"transUnit",
"->",
"getDomain",
"(",
")",
",",... | Convert a trans unit into an array.
@param TransUnitInterface $transUnit
@return array | [
"Convert",
"a",
"trans",
"unit",
"into",
"an",
"array",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Util/DataGrid/DataGridFormatter.php#L125-L142 | train |
lexik/LexikTranslationBundle | Storage/PropelStorage.php | PropelStorage.getFileRepository | protected function getFileRepository()
{
if (null === $this->fileRepository) {
$this->fileRepository = new FileRepository($this->getConnection());
}
return $this->fileRepository;
} | php | protected function getFileRepository()
{
if (null === $this->fileRepository) {
$this->fileRepository = new FileRepository($this->getConnection());
}
return $this->fileRepository;
} | [
"protected",
"function",
"getFileRepository",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"fileRepository",
")",
"{",
"$",
"this",
"->",
"fileRepository",
"=",
"new",
"FileRepository",
"(",
"$",
"this",
"->",
"getConnection",
"(",
")",
")",... | Returns the File repository.
@return FileRepository | [
"Returns",
"the",
"File",
"repository",
"."
] | 91d18448a460a42b467be0b22ea5b47e11d42856 | https://github.com/lexik/LexikTranslationBundle/blob/91d18448a460a42b467be0b22ea5b47e11d42856/Storage/PropelStorage.php#L373-L380 | train |
Hanson/foundation-sdk | src/AbstractAPI.php | AbstractAPI.headerMiddleware | protected function headerMiddleware($headers)
{
return function (callable $handler) use ($headers) {
return function (RequestInterface $request, array $options) use ($handler, $headers) {
foreach ($headers as $key => $header) {
$request = $request->withHeader($key, $header);
}
return $handler($request, $options);
};
};
} | php | protected function headerMiddleware($headers)
{
return function (callable $handler) use ($headers) {
return function (RequestInterface $request, array $options) use ($handler, $headers) {
foreach ($headers as $key => $header) {
$request = $request->withHeader($key, $header);
}
return $handler($request, $options);
};
};
} | [
"protected",
"function",
"headerMiddleware",
"(",
"$",
"headers",
")",
"{",
"return",
"function",
"(",
"callable",
"$",
"handler",
")",
"use",
"(",
"$",
"headers",
")",
"{",
"return",
"function",
"(",
"RequestInterface",
"$",
"request",
",",
"array",
"$",
... | add headers.
@param $headers
@return \Closure | [
"add",
"headers",
"."
] | 22f6ad7be6a847ca6be9eb7d1852cebe64311bdd | https://github.com/Hanson/foundation-sdk/blob/22f6ad7be6a847ca6be9eb7d1852cebe64311bdd/src/AbstractAPI.php#L39-L50 | train |
Hanson/foundation-sdk | src/AbstractAccessToken.php | AbstractAccessToken.getToken | public function getToken($forceRefresh = false)
{
$cached = $this->getCache()->fetch($this->getCacheKey()) ?: $this->token;
if ($forceRefresh || empty($cached)) {
$result = $this->getTokenFromServer();
$this->checkTokenResponse($result);
$this->setToken(
$token = $result[$this->tokenJsonKey],
$this->expiresJsonKey ? $result[$this->expiresJsonKey] : null
);
return $token;
}
return $cached;
} | php | public function getToken($forceRefresh = false)
{
$cached = $this->getCache()->fetch($this->getCacheKey()) ?: $this->token;
if ($forceRefresh || empty($cached)) {
$result = $this->getTokenFromServer();
$this->checkTokenResponse($result);
$this->setToken(
$token = $result[$this->tokenJsonKey],
$this->expiresJsonKey ? $result[$this->expiresJsonKey] : null
);
return $token;
}
return $cached;
} | [
"public",
"function",
"getToken",
"(",
"$",
"forceRefresh",
"=",
"false",
")",
"{",
"$",
"cached",
"=",
"$",
"this",
"->",
"getCache",
"(",
")",
"->",
"fetch",
"(",
"$",
"this",
"->",
"getCacheKey",
"(",
")",
")",
"?",
":",
"$",
"this",
"->",
"toke... | Get token from cache.
@param bool $forceRefresh
@return string | [
"Get",
"token",
"from",
"cache",
"."
] | 22f6ad7be6a847ca6be9eb7d1852cebe64311bdd | https://github.com/Hanson/foundation-sdk/blob/22f6ad7be6a847ca6be9eb7d1852cebe64311bdd/src/AbstractAccessToken.php#L94-L113 | train |
Hanson/foundation-sdk | src/AbstractAccessToken.php | AbstractAccessToken.getCacheKey | public function getCacheKey()
{
if (is_null($this->cacheKey)) {
return $this->prefix.$this->appId;
}
return $this->cacheKey;
} | php | public function getCacheKey()
{
if (is_null($this->cacheKey)) {
return $this->prefix.$this->appId;
}
return $this->cacheKey;
} | [
"public",
"function",
"getCacheKey",
"(",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"cacheKey",
")",
")",
"{",
"return",
"$",
"this",
"->",
"prefix",
".",
"$",
"this",
"->",
"appId",
";",
"}",
"return",
"$",
"this",
"->",
"cacheKey",
... | Return the cache key mix with appId.
@return string | [
"Return",
"the",
"cache",
"key",
"mix",
"with",
"appId",
"."
] | 22f6ad7be6a847ca6be9eb7d1852cebe64311bdd | https://github.com/Hanson/foundation-sdk/blob/22f6ad7be6a847ca6be9eb7d1852cebe64311bdd/src/AbstractAccessToken.php#L191-L198 | train |
64robots/nova-fields | src/Http/Controllers/ComputedController.php | ComputedController.index | public function index(NovaRequest $request)
{
$fields = $request->newResource()->availableFields($request);
$rowField = $fields->firstWhere('component', 'nova-fields-row');
if (!$rowField) {
return '';
}
$fields = collect($rowField->fields);
$field = $fields->firstWhere('attribute', $request->field);
if (!property_exists($field, 'computeCallback') || !$field->computeCallback) {
return '';
}
return call_user_func($field->computeCallback, (object) $request->input('values'));
} | php | public function index(NovaRequest $request)
{
$fields = $request->newResource()->availableFields($request);
$rowField = $fields->firstWhere('component', 'nova-fields-row');
if (!$rowField) {
return '';
}
$fields = collect($rowField->fields);
$field = $fields->firstWhere('attribute', $request->field);
if (!property_exists($field, 'computeCallback') || !$field->computeCallback) {
return '';
}
return call_user_func($field->computeCallback, (object) $request->input('values'));
} | [
"public",
"function",
"index",
"(",
"NovaRequest",
"$",
"request",
")",
"{",
"$",
"fields",
"=",
"$",
"request",
"->",
"newResource",
"(",
")",
"->",
"availableFields",
"(",
"$",
"request",
")",
";",
"$",
"rowField",
"=",
"$",
"fields",
"->",
"firstWhere... | Compute the value.
@param \Laravel\Nova\Http\Requests\NovaRequest $request
@return mixed | [
"Compute",
"the",
"value",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/Http/Controllers/ComputedController.php#L15-L32 | train |
64robots/nova-fields | src/JSON.php | JSON.generateRules | protected function generateRules($rules)
{
return collect($rules)->mapWithKeys(function ($rules, $key) {
return [$this->attribute . '.' . $key => $rules];
})->toArray();
} | php | protected function generateRules($rules)
{
return collect($rules)->mapWithKeys(function ($rules, $key) {
return [$this->attribute . '.' . $key => $rules];
})->toArray();
} | [
"protected",
"function",
"generateRules",
"(",
"$",
"rules",
")",
"{",
"return",
"collect",
"(",
"$",
"rules",
")",
"->",
"mapWithKeys",
"(",
"function",
"(",
"$",
"rules",
",",
"$",
"key",
")",
"{",
"return",
"[",
"$",
"this",
"->",
"attribute",
".",
... | Generate field-specific validation rules.
@param array $rules
@return array | [
"Generate",
"field",
"-",
"specific",
"validation",
"rules",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/JSON.php#L127-L132 | train |
64robots/nova-fields | src/JSON.php | JSON.resolveForDisplay | public function resolveForDisplay($resource, $attribute = null)
{
$attribute = $attribute ?? $this->attribute;
$value = $resource->{$attribute};
$this->value = is_object($value) || is_array($value) ? $value : json_decode($value);
$this->fields->whereInstanceOf(Resolvable::class)->each->resolveForDisplay($this->value);
parent::resolve($resource, $attribute);
} | php | public function resolveForDisplay($resource, $attribute = null)
{
$attribute = $attribute ?? $this->attribute;
$value = $resource->{$attribute};
$this->value = is_object($value) || is_array($value) ? $value : json_decode($value);
$this->fields->whereInstanceOf(Resolvable::class)->each->resolveForDisplay($this->value);
parent::resolve($resource, $attribute);
} | [
"public",
"function",
"resolveForDisplay",
"(",
"$",
"resource",
",",
"$",
"attribute",
"=",
"null",
")",
"{",
"$",
"attribute",
"=",
"$",
"attribute",
"??",
"$",
"this",
"->",
"attribute",
";",
"$",
"value",
"=",
"$",
"resource",
"->",
"{",
"$",
"attr... | Resolve the field's value for display.
@param mixed $resource
@param string|null $attribute
@return void | [
"Resolve",
"the",
"field",
"s",
"value",
"for",
"display",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/JSON.php#L198-L209 | train |
64robots/nova-fields | src/Row.php | Row.getCreationRules | public function getCreationRules(NovaRequest $request)
{
$result = [];
foreach ($this->meta['fields'] as $field) {
$rules = $this->generateRules($field->getCreationRules($request));
$result = array_merge_recursive($result, $rules);
}
return array_merge_recursive(
parent::getCreationRules($request),
$result
);
} | php | public function getCreationRules(NovaRequest $request)
{
$result = [];
foreach ($this->meta['fields'] as $field) {
$rules = $this->generateRules($field->getCreationRules($request));
$result = array_merge_recursive($result, $rules);
}
return array_merge_recursive(
parent::getCreationRules($request),
$result
);
} | [
"public",
"function",
"getCreationRules",
"(",
"NovaRequest",
"$",
"request",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"meta",
"[",
"'fields'",
"]",
"as",
"$",
"field",
")",
"{",
"$",
"rules",
"=",
"$",
"this",
... | Get the creation rules for this field.
@param \Laravel\Nova\Http\Requests\NovaRequest $request
@return array|string | [
"Get",
"the",
"creation",
"rules",
"for",
"this",
"field",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/Row.php#L177-L190 | train |
64robots/nova-fields | src/Row.php | Row.jsonSerialize | public function jsonSerialize()
{
return array_merge(parent::jsonSerialize(), [
'sanitizedAttribute' => str_plural(kebab_case($this->attribute)),
'shouldShow' => $this->shouldBeExpanded(),
]);
} | php | public function jsonSerialize()
{
return array_merge(parent::jsonSerialize(), [
'sanitizedAttribute' => str_plural(kebab_case($this->attribute)),
'shouldShow' => $this->shouldBeExpanded(),
]);
} | [
"public",
"function",
"jsonSerialize",
"(",
")",
"{",
"return",
"array_merge",
"(",
"parent",
"::",
"jsonSerialize",
"(",
")",
",",
"[",
"'sanitizedAttribute'",
"=>",
"str_plural",
"(",
"kebab_case",
"(",
"$",
"this",
"->",
"attribute",
")",
")",
",",
"'shou... | Prepare the element for JSON serialization.
@return array | [
"Prepare",
"the",
"element",
"for",
"JSON",
"serialization",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/Row.php#L218-L224 | train |
64robots/nova-fields | src/Select.php | Select.displayUsingLabels | public function displayUsingLabels()
{
$this->displayUsing(function ($value) {
return collect($this->meta['options'])
->where('value', $value)
->first()['label'] ?? $value;
});
return $this->withMeta(['displayUsingLabels' => true]);
} | php | public function displayUsingLabels()
{
$this->displayUsing(function ($value) {
return collect($this->meta['options'])
->where('value', $value)
->first()['label'] ?? $value;
});
return $this->withMeta(['displayUsingLabels' => true]);
} | [
"public",
"function",
"displayUsingLabels",
"(",
")",
"{",
"$",
"this",
"->",
"displayUsing",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"collect",
"(",
"$",
"this",
"->",
"meta",
"[",
"'options'",
"]",
")",
"->",
"where",
"(",
"'value'",
... | Display values using their corresponding specified labels.
@return $this | [
"Display",
"values",
"using",
"their",
"corresponding",
"specified",
"labels",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/Select.php#L37-L46 | train |
64robots/nova-fields | src/Http/Controllers/AssociatableController.php | AssociatableController.index | public function index(NovaRequest $request)
{
$fields = $request->newResource()
->availableFields($request);
$field = $fields->firstWhere('attribute', $request->field);
if(!$field) {
$rowField = $fields->firstWhere('component', 'nova-fields-row');
$fields = collect($rowField->meta['fields']);
$field = $fields->firstWhere('attribute', $request->field);
}
$withTrashed = $this->shouldIncludeTrashed(
$request, $associatedResource = $field->resourceClass
);
return [
'resources' => $field->buildAssociatableQuery($request, $withTrashed)->get()
->mapInto($field->resourceClass)
->filter->authorizedToAdd($request, $request->model())
->map(function ($resource) use ($request, $field) {
return $field->formatAssociatableResource($request, $resource);
})->sortBy('display')->values(),
'softDeletes' => $associatedResource::softDeletes(),
'withTrashed' => $withTrashed,
];
} | php | public function index(NovaRequest $request)
{
$fields = $request->newResource()
->availableFields($request);
$field = $fields->firstWhere('attribute', $request->field);
if(!$field) {
$rowField = $fields->firstWhere('component', 'nova-fields-row');
$fields = collect($rowField->meta['fields']);
$field = $fields->firstWhere('attribute', $request->field);
}
$withTrashed = $this->shouldIncludeTrashed(
$request, $associatedResource = $field->resourceClass
);
return [
'resources' => $field->buildAssociatableQuery($request, $withTrashed)->get()
->mapInto($field->resourceClass)
->filter->authorizedToAdd($request, $request->model())
->map(function ($resource) use ($request, $field) {
return $field->formatAssociatableResource($request, $resource);
})->sortBy('display')->values(),
'softDeletes' => $associatedResource::softDeletes(),
'withTrashed' => $withTrashed,
];
} | [
"public",
"function",
"index",
"(",
"NovaRequest",
"$",
"request",
")",
"{",
"$",
"fields",
"=",
"$",
"request",
"->",
"newResource",
"(",
")",
"->",
"availableFields",
"(",
"$",
"request",
")",
";",
"$",
"field",
"=",
"$",
"fields",
"->",
"firstWhere",
... | List the available related resources for a given resource.
@param \Laravel\Nova\Http\Requests\NovaRequest $request
@return \Illuminate\Http\Response | [
"List",
"the",
"available",
"related",
"resources",
"for",
"a",
"given",
"resource",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/Http/Controllers/AssociatableController.php#L16-L43 | train |
64robots/nova-fields | src/BelongsTo.php | BelongsTo.formatAssociatableResource | public function formatAssociatableResource(NovaRequest $request, $resource)
{
$relation = explode(".", $this->groupedBy);
$groupedBy = count($relation) == 2
? $resource->{$relation[0]}->{$relation[1]}
: $resource->{$this->groupedBy};
return array_filter([
'groupedBy' => $groupedBy,
'avatar' => $resource->resolveAvatarUrl($request),
'display' => $this->formatDisplayValue($resource),
'value' => $resource->getKey(),
]);
} | php | public function formatAssociatableResource(NovaRequest $request, $resource)
{
$relation = explode(".", $this->groupedBy);
$groupedBy = count($relation) == 2
? $resource->{$relation[0]}->{$relation[1]}
: $resource->{$this->groupedBy};
return array_filter([
'groupedBy' => $groupedBy,
'avatar' => $resource->resolveAvatarUrl($request),
'display' => $this->formatDisplayValue($resource),
'value' => $resource->getKey(),
]);
} | [
"public",
"function",
"formatAssociatableResource",
"(",
"NovaRequest",
"$",
"request",
",",
"$",
"resource",
")",
"{",
"$",
"relation",
"=",
"explode",
"(",
"\".\"",
",",
"$",
"this",
"->",
"groupedBy",
")",
";",
"$",
"groupedBy",
"=",
"count",
"(",
"$",
... | Format the given associatable resource.
@param \Laravel\Nova\Http\Requests\NovaRequest $request
@param mixed $resource
@return array | [
"Format",
"the",
"given",
"associatable",
"resource",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/BelongsTo.php#L57-L71 | train |
64robots/nova-fields | src/BelongsTo.php | BelongsTo.meta | public function meta()
{
return array_merge([
'wrapperClasses' => $this->wrapperClasses,
'indexClasses' => $this->indexClasses,
'inputClasses' => $this->inputClasses,
'fieldClasses' => $this->fieldClasses,
'panelFieldClasses' => $this->panelFieldClasses,
'labelClasses' => $this->labelClasses,
'panelLabelClasses' => $this->panelLabelClasses,
'excerptClasses' => $this->excerptClasses,
'grouped' => !!$this->groupedBy,
'resourceName' => $this->resourceName,
'label' => forward_static_call([$this->resourceClass, 'label']),
'singularLabel' => forward_static_call([$this->resourceClass, 'singularLabel']),
'belongsToRelationship' => $this->belongsToRelationship,
'belongsToId' => $this->belongsToId,
'searchable' => $this->searchable,
'displayName' => $this->displayName,
], $this->meta);
} | php | public function meta()
{
return array_merge([
'wrapperClasses' => $this->wrapperClasses,
'indexClasses' => $this->indexClasses,
'inputClasses' => $this->inputClasses,
'fieldClasses' => $this->fieldClasses,
'panelFieldClasses' => $this->panelFieldClasses,
'labelClasses' => $this->labelClasses,
'panelLabelClasses' => $this->panelLabelClasses,
'excerptClasses' => $this->excerptClasses,
'grouped' => !!$this->groupedBy,
'resourceName' => $this->resourceName,
'label' => forward_static_call([$this->resourceClass, 'label']),
'singularLabel' => forward_static_call([$this->resourceClass, 'singularLabel']),
'belongsToRelationship' => $this->belongsToRelationship,
'belongsToId' => $this->belongsToId,
'searchable' => $this->searchable,
'displayName' => $this->displayName,
], $this->meta);
} | [
"public",
"function",
"meta",
"(",
")",
"{",
"return",
"array_merge",
"(",
"[",
"'wrapperClasses'",
"=>",
"$",
"this",
"->",
"wrapperClasses",
",",
"'indexClasses'",
"=>",
"$",
"this",
"->",
"indexClasses",
",",
"'inputClasses'",
"=>",
"$",
"this",
"->",
"in... | Get additional meta information to merge with the field payload.
@return array | [
"Get",
"additional",
"meta",
"information",
"to",
"merge",
"with",
"the",
"field",
"payload",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/BelongsTo.php#L160-L180 | train |
64robots/nova-fields | src/Configurable.php | Configurable.readOnly | public function readOnly($callback = null)
{
if (!$callback || (is_callable($callback) && call_user_func($callback))) {
return $this->withMeta(['readOnly' => true]);
}
return $this;
} | php | public function readOnly($callback = null)
{
if (!$callback || (is_callable($callback) && call_user_func($callback))) {
return $this->withMeta(['readOnly' => true]);
}
return $this;
} | [
"public",
"function",
"readOnly",
"(",
"$",
"callback",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"callback",
"||",
"(",
"is_callable",
"(",
"$",
"callback",
")",
"&&",
"call_user_func",
"(",
"$",
"callback",
")",
")",
")",
"{",
"return",
"$",
"thi... | Set the input as disabled.
@return $this | [
"Set",
"the",
"input",
"as",
"disabled",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/Configurable.php#L397-L403 | train |
64robots/nova-fields | src/Configurable.php | Configurable.resolveAttribute | protected function resolveAttribute($resource, $attribute)
{
$this->setResourceId(data_get($resource, 'id'));
return parent::resolveAttribute($resource, $attribute);
} | php | protected function resolveAttribute($resource, $attribute)
{
$this->setResourceId(data_get($resource, 'id'));
return parent::resolveAttribute($resource, $attribute);
} | [
"protected",
"function",
"resolveAttribute",
"(",
"$",
"resource",
",",
"$",
"attribute",
")",
"{",
"$",
"this",
"->",
"setResourceId",
"(",
"data_get",
"(",
"$",
"resource",
",",
"'id'",
")",
")",
";",
"return",
"parent",
"::",
"resolveAttribute",
"(",
"$... | Overriding the base method in order to grab the model ID.
@param mixed $resource The resource class
@param string $attribute The attribute of the resource
@return mixed | [
"Overriding",
"the",
"base",
"method",
"in",
"order",
"to",
"grab",
"the",
"model",
"ID",
"."
] | 0149e96d689f85f65ec3246a6976527b09a54148 | https://github.com/64robots/nova-fields/blob/0149e96d689f85f65ec3246a6976527b09a54148/src/Configurable.php#L444-L448 | train |
php-mod/curl | src/Curl/Curl.php | Curl.init | private function init()
{
$this->curl = curl_init();
$this->setUserAgent(self::USER_AGENT);
$this->setOpt(CURLINFO_HEADER_OUT, true);
$this->setOpt(CURLOPT_HEADER, false);
$this->setOpt(CURLOPT_RETURNTRANSFER, true);
$this->setOpt(CURLOPT_HEADERFUNCTION, array($this, 'addResponseHeaderLine'));
return $this;
} | php | private function init()
{
$this->curl = curl_init();
$this->setUserAgent(self::USER_AGENT);
$this->setOpt(CURLINFO_HEADER_OUT, true);
$this->setOpt(CURLOPT_HEADER, false);
$this->setOpt(CURLOPT_RETURNTRANSFER, true);
$this->setOpt(CURLOPT_HEADERFUNCTION, array($this, 'addResponseHeaderLine'));
return $this;
} | [
"private",
"function",
"init",
"(",
")",
"{",
"$",
"this",
"->",
"curl",
"=",
"curl_init",
"(",
")",
";",
"$",
"this",
"->",
"setUserAgent",
"(",
"self",
"::",
"USER_AGENT",
")",
";",
"$",
"this",
"->",
"setOpt",
"(",
"CURLINFO_HEADER_OUT",
",",
"true"... | Initializer for the curl resource.
Is called by the __construct() of the class or when the curl request is reset.
@return self | [
"Initializer",
"for",
"the",
"curl",
"resource",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L168-L177 | train |
php-mod/curl | src/Curl/Curl.php | Curl.addResponseHeaderLine | public function addResponseHeaderLine($curl, $header_line)
{
$trimmed_header = trim($header_line, "\r\n");
if ($trimmed_header === "") {
$this->response_header_continue = false;
} elseif (strtolower($trimmed_header) === 'http/1.1 100 continue') {
$this->response_header_continue = true;
} elseif (!$this->response_header_continue) {
$this->response_headers[] = $trimmed_header;
}
return strlen($header_line);
} | php | public function addResponseHeaderLine($curl, $header_line)
{
$trimmed_header = trim($header_line, "\r\n");
if ($trimmed_header === "") {
$this->response_header_continue = false;
} elseif (strtolower($trimmed_header) === 'http/1.1 100 continue') {
$this->response_header_continue = true;
} elseif (!$this->response_header_continue) {
$this->response_headers[] = $trimmed_header;
}
return strlen($header_line);
} | [
"public",
"function",
"addResponseHeaderLine",
"(",
"$",
"curl",
",",
"$",
"header_line",
")",
"{",
"$",
"trimmed_header",
"=",
"trim",
"(",
"$",
"header_line",
",",
"\"\\r\\n\"",
")",
";",
"if",
"(",
"$",
"trimmed_header",
"===",
"\"\"",
")",
"{",
"$",
... | Handle writing the response headers
@param resource $curl The current curl resource
@param string $header_line A line from the list of response headers
@return int Returns the length of the $header_line | [
"Handle",
"writing",
"the",
"response",
"headers"
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L187-L200 | train |
php-mod/curl | src/Curl/Curl.php | Curl.exec | protected function exec()
{
$this->response_headers = array();
$this->response = curl_exec($this->curl);
$this->curl_error_code = curl_errno($this->curl);
$this->curl_error_message = curl_error($this->curl);
$this->curl_error = !($this->getErrorCode() === 0);
$this->http_status_code = intval(curl_getinfo($this->curl, CURLINFO_HTTP_CODE));
$this->http_error = $this->isError();
$this->error = $this->curl_error || $this->http_error;
$this->error_code = $this->error ? ($this->curl_error ? $this->getErrorCode() : $this->getHttpStatus()) : 0;
$this->request_headers = preg_split('/\r\n/', curl_getinfo($this->curl, CURLINFO_HEADER_OUT), null, PREG_SPLIT_NO_EMPTY);
$this->http_error_message = $this->error ? (isset($this->response_headers['0']) ? $this->response_headers['0'] : '') : '';
$this->error_message = $this->curl_error ? $this->getErrorMessage() : $this->http_error_message;
return $this->error_code;
} | php | protected function exec()
{
$this->response_headers = array();
$this->response = curl_exec($this->curl);
$this->curl_error_code = curl_errno($this->curl);
$this->curl_error_message = curl_error($this->curl);
$this->curl_error = !($this->getErrorCode() === 0);
$this->http_status_code = intval(curl_getinfo($this->curl, CURLINFO_HTTP_CODE));
$this->http_error = $this->isError();
$this->error = $this->curl_error || $this->http_error;
$this->error_code = $this->error ? ($this->curl_error ? $this->getErrorCode() : $this->getHttpStatus()) : 0;
$this->request_headers = preg_split('/\r\n/', curl_getinfo($this->curl, CURLINFO_HEADER_OUT), null, PREG_SPLIT_NO_EMPTY);
$this->http_error_message = $this->error ? (isset($this->response_headers['0']) ? $this->response_headers['0'] : '') : '';
$this->error_message = $this->curl_error ? $this->getErrorMessage() : $this->http_error_message;
return $this->error_code;
} | [
"protected",
"function",
"exec",
"(",
")",
"{",
"$",
"this",
"->",
"response_headers",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"response",
"=",
"curl_exec",
"(",
"$",
"this",
"->",
"curl",
")",
";",
"$",
"this",
"->",
"curl_error_code",
"=",
... | Execute the curl request based on the respective settings.
@return int Returns the error code for the current curl request | [
"Execute",
"the",
"curl",
"request",
"based",
"on",
"the",
"respective",
"settings",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L209-L225 | train |
php-mod/curl | src/Curl/Curl.php | Curl.get | public function get($url, $data = array())
{
if (count($data) > 0) {
$this->setOpt(CURLOPT_URL, $url.'?'.http_build_query($data));
} else {
$this->setOpt(CURLOPT_URL, $url);
}
$this->setOpt(CURLOPT_HTTPGET, true);
$this->exec();
return $this;
} | php | public function get($url, $data = array())
{
if (count($data) > 0) {
$this->setOpt(CURLOPT_URL, $url.'?'.http_build_query($data));
} else {
$this->setOpt(CURLOPT_URL, $url);
}
$this->setOpt(CURLOPT_HTTPGET, true);
$this->exec();
return $this;
} | [
"public",
"function",
"get",
"(",
"$",
"url",
",",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"data",
")",
">",
"0",
")",
"{",
"$",
"this",
"->",
"setOpt",
"(",
"CURLOPT_URL",
",",
"$",
"url",
".",
"'?'",
"."... | Make a get request with optional data.
The get request has no body data, the data will be correctly added to the $url with the http_build_query() method.
@param string $url The url to make the get request for
@param array $data Optional arguments who are part of the url
@return self | [
"Make",
"a",
"get",
"request",
"with",
"optional",
"data",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L293-L303 | train |
php-mod/curl | src/Curl/Curl.php | Curl.post | public function post($url, $data = array())
{
$this->setOpt(CURLOPT_URL, $url);
$this->preparePayload($data);
$this->exec();
return $this;
} | php | public function post($url, $data = array())
{
$this->setOpt(CURLOPT_URL, $url);
$this->preparePayload($data);
$this->exec();
return $this;
} | [
"public",
"function",
"post",
"(",
"$",
"url",
",",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setOpt",
"(",
"CURLOPT_URL",
",",
"$",
"url",
")",
";",
"$",
"this",
"->",
"preparePayload",
"(",
"$",
"data",
")",
";",
"$",
... | Make a post request with optional post data.
@param string $url The url to make the post request
@param array $data Post data to pass to the url
@return self | [
"Make",
"a",
"post",
"request",
"with",
"optional",
"post",
"data",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L312-L318 | train |
php-mod/curl | src/Curl/Curl.php | Curl.put | public function put($url, $data = array(), $payload = false)
{
if (! empty($data)) {
if ($payload === false) {
$url .= '?'.http_build_query($data);
} else {
$this->preparePayload($data);
}
}
$this->setOpt(CURLOPT_URL, $url);
$this->setOpt(CURLOPT_CUSTOMREQUEST, 'PUT');
$this->exec();
return $this;
} | php | public function put($url, $data = array(), $payload = false)
{
if (! empty($data)) {
if ($payload === false) {
$url .= '?'.http_build_query($data);
} else {
$this->preparePayload($data);
}
}
$this->setOpt(CURLOPT_URL, $url);
$this->setOpt(CURLOPT_CUSTOMREQUEST, 'PUT');
$this->exec();
return $this;
} | [
"public",
"function",
"put",
"(",
"$",
"url",
",",
"$",
"data",
"=",
"array",
"(",
")",
",",
"$",
"payload",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"if",
"(",
"$",
"payload",
"===",
"false",
")",
"{"... | Make a put request with optional data.
The put request data can be either sent via payload or as get parameters of the string.
@param string $url The url to make the put request
@param array $data Optional data to pass to the $url
@param bool $payload Whether the data should be transmitted trough payload or as get parameters of the string
@return self | [
"Make",
"a",
"put",
"request",
"with",
"optional",
"data",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L330-L344 | train |
php-mod/curl | src/Curl/Curl.php | Curl.setCookie | public function setCookie($key, $value)
{
$this->_cookies[$key] = $value;
$this->setOpt(CURLOPT_COOKIE, http_build_query($this->_cookies, '', '; '));
return $this;
} | php | public function setCookie($key, $value)
{
$this->_cookies[$key] = $value;
$this->setOpt(CURLOPT_COOKIE, http_build_query($this->_cookies, '', '; '));
return $this;
} | [
"public",
"function",
"setCookie",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"$",
"this",
"->",
"_cookies",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"$",
"this",
"->",
"setOpt",
"(",
"CURLOPT_COOKIE",
",",
"http_build_query",
"(",
"$",
"this... | Set contents of HTTP Cookie header.
@param string $key The name of the cookie
@param string $value The value for the provided cookie name
@return self | [
"Set",
"contents",
"of",
"HTTP",
"Cookie",
"header",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L495-L500 | train |
php-mod/curl | src/Curl/Curl.php | Curl.reset | public function reset()
{
$this->close();
$this->_cookies = array();
$this->_headers = array();
$this->error = false;
$this->error_code = 0;
$this->error_message = null;
$this->curl_error = false;
$this->curl_error_code = 0;
$this->curl_error_message = null;
$this->http_error = false;
$this->http_status_code = 0;
$this->http_error_message = null;
$this->request_headers = null;
$this->response_headers = array();
$this->response = false;
$this->init();
return $this;
} | php | public function reset()
{
$this->close();
$this->_cookies = array();
$this->_headers = array();
$this->error = false;
$this->error_code = 0;
$this->error_message = null;
$this->curl_error = false;
$this->curl_error_code = 0;
$this->curl_error_message = null;
$this->http_error = false;
$this->http_status_code = 0;
$this->http_error_message = null;
$this->request_headers = null;
$this->response_headers = array();
$this->response = false;
$this->init();
return $this;
} | [
"public",
"function",
"reset",
"(",
")",
"{",
"$",
"this",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"_cookies",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"_headers",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"error",
"=",
"f... | Reset all curl options.
In order to make multiple requests with the same curl object all settings requires to be reset.
@return self | [
"Reset",
"all",
"curl",
"options",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L575-L594 | train |
php-mod/curl | src/Curl/Curl.php | Curl.getResponseHeaders | public function getResponseHeaders($headerKey = null)
{
$headers = array();
$headerKey = strtolower($headerKey);
foreach ($this->response_headers as $header) {
$parts = explode(":", $header, 2);
$key = isset($parts[0]) ? $parts[0] : null;
$value = isset($parts[1]) ? $parts[1] : null;
$headers[trim(strtolower($key))] = trim($value);
}
if ($headerKey) {
return isset($headers[$headerKey]) ? $headers[$headerKey] : false;
}
return $headers;
} | php | public function getResponseHeaders($headerKey = null)
{
$headers = array();
$headerKey = strtolower($headerKey);
foreach ($this->response_headers as $header) {
$parts = explode(":", $header, 2);
$key = isset($parts[0]) ? $parts[0] : null;
$value = isset($parts[1]) ? $parts[1] : null;
$headers[trim(strtolower($key))] = trim($value);
}
if ($headerKey) {
return isset($headers[$headerKey]) ? $headers[$headerKey] : false;
}
return $headers;
} | [
"public",
"function",
"getResponseHeaders",
"(",
"$",
"headerKey",
"=",
"null",
")",
"{",
"$",
"headers",
"=",
"array",
"(",
")",
";",
"$",
"headerKey",
"=",
"strtolower",
"(",
"$",
"headerKey",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"response_head... | Get a specific response header key or all values from the response headers array.
Usage example:
```php
$curl = (new Curl())->get('http://example.com');
echo $curl->getResponseHeaders('Content-Type');
```
Or in order to dump all keys with the given values use:
```php
$curl = (new Curl())->get('http://example.com');
var_dump($curl->getResponseHeaders());
```
@param string $headerKey Optional key to get from the array.
@return bool|string|array
@since 1.9 | [
"Get",
"a",
"specific",
"response",
"header",
"key",
"or",
"all",
"values",
"from",
"the",
"response",
"headers",
"array",
"."
] | 4c7cbc6d056afec339a706fff6f95741688b48b8 | https://github.com/php-mod/curl/blob/4c7cbc6d056afec339a706fff6f95741688b48b8/src/Curl/Curl.php#L693-L712 | train |
craftcms/aws-s3 | src/Volume.php | Volume.loadBucketList | public static function loadBucketList($keyId, $secret)
{
// Any region will do.
$config = self::_buildConfigArray($keyId, $secret, 'us-east-1');
$client = static::client($config);
$objects = $client->listBuckets();
if (empty($objects['Buckets'])) {
return [];
}
$buckets = $objects['Buckets'];
$bucketList = [];
foreach ($buckets as $bucket) {
try {
$region = $client->determineBucketRegion($bucket['Name']);
} catch (S3Exception $exception) {
// If a bucket cannot be accessed by the current policy, move along:
// https://github.com/craftcms/aws-s3/pull/29#issuecomment-468193410
continue;
}
$bucketList[] = [
'bucket' => $bucket['Name'],
'urlPrefix' => 'https://s3.'.$region.'.amazonaws.com/'.$bucket['Name'].'/',
'region' => $region
];
}
return $bucketList;
} | php | public static function loadBucketList($keyId, $secret)
{
// Any region will do.
$config = self::_buildConfigArray($keyId, $secret, 'us-east-1');
$client = static::client($config);
$objects = $client->listBuckets();
if (empty($objects['Buckets'])) {
return [];
}
$buckets = $objects['Buckets'];
$bucketList = [];
foreach ($buckets as $bucket) {
try {
$region = $client->determineBucketRegion($bucket['Name']);
} catch (S3Exception $exception) {
// If a bucket cannot be accessed by the current policy, move along:
// https://github.com/craftcms/aws-s3/pull/29#issuecomment-468193410
continue;
}
$bucketList[] = [
'bucket' => $bucket['Name'],
'urlPrefix' => 'https://s3.'.$region.'.amazonaws.com/'.$bucket['Name'].'/',
'region' => $region
];
}
return $bucketList;
} | [
"public",
"static",
"function",
"loadBucketList",
"(",
"$",
"keyId",
",",
"$",
"secret",
")",
"{",
"// Any region will do.",
"$",
"config",
"=",
"self",
"::",
"_buildConfigArray",
"(",
"$",
"keyId",
",",
"$",
"secret",
",",
"'us-east-1'",
")",
";",
"$",
"c... | Get the bucket list using the specified credentials.
@param $keyId
@param $secret
@return array
@throws \InvalidArgumentException | [
"Get",
"the",
"bucket",
"list",
"using",
"the",
"specified",
"credentials",
"."
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/Volume.php#L207-L241 | train |
craftcms/aws-s3 | src/Volume.php | Volume.detectFocalPoint | public function detectFocalPoint(string $filePath): array
{
$extension = StringHelper::toLowerCase(pathinfo($filePath, PATHINFO_EXTENSION));
if (!in_array($extension, ['jpeg', 'jpg', 'png'])) {
return [];
}
$client = new RekognitionClient($this->_getConfigArray());
$params = [
'Image' => [
'S3Object' => [
'Name' => $filePath,
'Bucket' => Craft::parseEnv($this->bucket),
],
],
];
$faceData = $client->detectFaces($params);
if (!empty($faceData['FaceDetails'])) {
$face = array_shift($faceData['FaceDetails']);
if ($face['Confidence'] > 80) {
$box = $face['BoundingBox'];
return [
number_format($box['Left'] + ($box['Width'] / 2), 4),
number_format($box['Top'] + ($box['Height'] / 2), 4),
];
}
}
return [];
} | php | public function detectFocalPoint(string $filePath): array
{
$extension = StringHelper::toLowerCase(pathinfo($filePath, PATHINFO_EXTENSION));
if (!in_array($extension, ['jpeg', 'jpg', 'png'])) {
return [];
}
$client = new RekognitionClient($this->_getConfigArray());
$params = [
'Image' => [
'S3Object' => [
'Name' => $filePath,
'Bucket' => Craft::parseEnv($this->bucket),
],
],
];
$faceData = $client->detectFaces($params);
if (!empty($faceData['FaceDetails'])) {
$face = array_shift($faceData['FaceDetails']);
if ($face['Confidence'] > 80) {
$box = $face['BoundingBox'];
return [
number_format($box['Left'] + ($box['Width'] / 2), 4),
number_format($box['Top'] + ($box['Height'] / 2), 4),
];
}
}
return [];
} | [
"public",
"function",
"detectFocalPoint",
"(",
"string",
"$",
"filePath",
")",
":",
"array",
"{",
"$",
"extension",
"=",
"StringHelper",
"::",
"toLowerCase",
"(",
"pathinfo",
"(",
"$",
"filePath",
",",
"PATHINFO_EXTENSION",
")",
")",
";",
"if",
"(",
"!",
"... | Attempt to detect focal point for a path on the bucket and return the
focal point position as an array of decimal parts
@param string $filePath
@return array | [
"Attempt",
"to",
"detect",
"focal",
"point",
"for",
"a",
"path",
"on",
"the",
"bucket",
"and",
"return",
"the",
"focal",
"point",
"position",
"as",
"an",
"array",
"of",
"decimal",
"parts"
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/Volume.php#L336-L369 | train |
craftcms/aws-s3 | src/Volume.php | Volume._subfolder | private function _subfolder(): string
{
if ($this->subfolder && ($subfolder = rtrim(Craft::parseEnv($this->subfolder), '/')) !== '') {
return $subfolder . '/';
}
return '';
} | php | private function _subfolder(): string
{
if ($this->subfolder && ($subfolder = rtrim(Craft::parseEnv($this->subfolder), '/')) !== '') {
return $subfolder . '/';
}
return '';
} | [
"private",
"function",
"_subfolder",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"subfolder",
"&&",
"(",
"$",
"subfolder",
"=",
"rtrim",
"(",
"Craft",
"::",
"parseEnv",
"(",
"$",
"this",
"->",
"subfolder",
")",
",",
"'/'",
")",
")",
... | Returns the parsed subfolder path
@return string|null | [
"Returns",
"the",
"parsed",
"subfolder",
"path"
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/Volume.php#L379-L385 | train |
craftcms/aws-s3 | src/Volume.php | Volume._cfPrefix | private function _cfPrefix(): string
{
if ($this->cfPrefix && ($cfPrefix = rtrim(Craft::parseEnv($this->cfPrefix), '/')) !== '') {
return $cfPrefix . '/';
}
return '';
} | php | private function _cfPrefix(): string
{
if ($this->cfPrefix && ($cfPrefix = rtrim(Craft::parseEnv($this->cfPrefix), '/')) !== '') {
return $cfPrefix . '/';
}
return '';
} | [
"private",
"function",
"_cfPrefix",
"(",
")",
":",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"cfPrefix",
"&&",
"(",
"$",
"cfPrefix",
"=",
"rtrim",
"(",
"Craft",
"::",
"parseEnv",
"(",
"$",
"this",
"->",
"cfPrefix",
")",
",",
"'/'",
")",
")",
"!=... | Returns the parsed CloudFront distribution prefix
@return string|null | [
"Returns",
"the",
"parsed",
"CloudFront",
"distribution",
"prefix"
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/Volume.php#L392-L398 | train |
craftcms/aws-s3 | src/Volume.php | Volume._getConfigArray | private function _getConfigArray()
{
$keyId = Craft::parseEnv($this->keyId);
$secret = Craft::parseEnv($this->secret);
$region = Craft::parseEnv($this->region);
return self::_buildConfigArray($keyId, $secret, $region);
} | php | private function _getConfigArray()
{
$keyId = Craft::parseEnv($this->keyId);
$secret = Craft::parseEnv($this->secret);
$region = Craft::parseEnv($this->region);
return self::_buildConfigArray($keyId, $secret, $region);
} | [
"private",
"function",
"_getConfigArray",
"(",
")",
"{",
"$",
"keyId",
"=",
"Craft",
"::",
"parseEnv",
"(",
"$",
"this",
"->",
"keyId",
")",
";",
"$",
"secret",
"=",
"Craft",
"::",
"parseEnv",
"(",
"$",
"this",
"->",
"secret",
")",
";",
"$",
"region"... | Get the config array for AWS Clients.
@return array | [
"Get",
"the",
"config",
"array",
"for",
"AWS",
"Clients",
"."
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/Volume.php#L415-L422 | train |
craftcms/aws-s3 | src/Volume.php | Volume._buildConfigArray | private static function _buildConfigArray($keyId = null, $secret = null, $region = null)
{
$config = [
'region' => $region,
'version' => 'latest'
];
if (empty($keyId) || empty($secret)) {
// Assume we're running on EC2 and we have an IAM role assigned. Kick back and relax.
} else {
$tokenKey = static::CACHE_KEY_PREFIX . md5($keyId . $secret);
$credentials = new Credentials($keyId, $secret);
if (Craft::$app->cache->exists($tokenKey)) {
$cached = Craft::$app->cache->get($tokenKey);
$credentials->unserialize($cached);
} else {
$config['credentials'] = $credentials;
$stsClient = new StsClient($config);
$result = $stsClient->getSessionToken(['DurationSeconds' => static::CACHE_DURATION_SECONDS]);
$credentials = $stsClient->createCredentials($result);
Craft::$app->cache->set($tokenKey, $credentials->serialize(), static::CACHE_DURATION_SECONDS);
}
// TODO Add support for different credential supply methods
$config['credentials'] = $credentials;
}
$client = Craft::createGuzzleClient();
$config['http_handler'] = new GuzzleHandler($client);
return $config;
} | php | private static function _buildConfigArray($keyId = null, $secret = null, $region = null)
{
$config = [
'region' => $region,
'version' => 'latest'
];
if (empty($keyId) || empty($secret)) {
// Assume we're running on EC2 and we have an IAM role assigned. Kick back and relax.
} else {
$tokenKey = static::CACHE_KEY_PREFIX . md5($keyId . $secret);
$credentials = new Credentials($keyId, $secret);
if (Craft::$app->cache->exists($tokenKey)) {
$cached = Craft::$app->cache->get($tokenKey);
$credentials->unserialize($cached);
} else {
$config['credentials'] = $credentials;
$stsClient = new StsClient($config);
$result = $stsClient->getSessionToken(['DurationSeconds' => static::CACHE_DURATION_SECONDS]);
$credentials = $stsClient->createCredentials($result);
Craft::$app->cache->set($tokenKey, $credentials->serialize(), static::CACHE_DURATION_SECONDS);
}
// TODO Add support for different credential supply methods
$config['credentials'] = $credentials;
}
$client = Craft::createGuzzleClient();
$config['http_handler'] = new GuzzleHandler($client);
return $config;
} | [
"private",
"static",
"function",
"_buildConfigArray",
"(",
"$",
"keyId",
"=",
"null",
",",
"$",
"secret",
"=",
"null",
",",
"$",
"region",
"=",
"null",
")",
"{",
"$",
"config",
"=",
"[",
"'region'",
"=>",
"$",
"region",
",",
"'version'",
"=>",
"'latest... | Build the config array based on a keyID and secret
@param $keyId
@param $secret
@param $region
@return array | [
"Build",
"the",
"config",
"array",
"based",
"on",
"a",
"keyID",
"and",
"secret"
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/Volume.php#L432-L464 | train |
craftcms/aws-s3 | src/controllers/DefaultController.php | DefaultController.actionLoadBucketData | public function actionLoadBucketData()
{
$this->requirePostRequest();
$this->requireAcceptsJson();
$request = Craft::$app->getRequest();
$keyId = Craft::parseEnv($request->getRequiredBodyParam('keyId'));
$secret = Craft::parseEnv($request->getRequiredBodyParam('secret'));
try {
return $this->asJson(Volume::loadBucketList($keyId, $secret));
} catch (\Throwable $e) {
return $this->asErrorJson($e->getMessage());
}
} | php | public function actionLoadBucketData()
{
$this->requirePostRequest();
$this->requireAcceptsJson();
$request = Craft::$app->getRequest();
$keyId = Craft::parseEnv($request->getRequiredBodyParam('keyId'));
$secret = Craft::parseEnv($request->getRequiredBodyParam('secret'));
try {
return $this->asJson(Volume::loadBucketList($keyId, $secret));
} catch (\Throwable $e) {
return $this->asErrorJson($e->getMessage());
}
} | [
"public",
"function",
"actionLoadBucketData",
"(",
")",
"{",
"$",
"this",
"->",
"requirePostRequest",
"(",
")",
";",
"$",
"this",
"->",
"requireAcceptsJson",
"(",
")",
";",
"$",
"request",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getRequest",
"(",
")",
";"... | Load bucket data for specified credentials.
@return Response | [
"Load",
"bucket",
"data",
"for",
"specified",
"credentials",
"."
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/controllers/DefaultController.php#L32-L46 | train |
craftcms/aws-s3 | src/migrations/m190131_214300_cleanup_config.php | m190131_214300_cleanup_config._convertVolumes | private function _convertVolumes()
{
$projectConfig = Craft::$app->getProjectConfig();
$schemaVersion = $projectConfig->get('plugins.aws-s3.schemaVersion', true);
$projectConfig->muteEvents = true;
$volumes = $projectConfig->get(Volumes::CONFIG_VOLUME_KEY, true) ?? [];
foreach ($volumes as $uid => &$volume) {
if ($volume['type'] === Volume::class && !empty($volume['settings']) && is_array($volume['settings']) && array_key_exists('urlPrefix', $volume['settings'])) {
$settings = $volume['settings'];
$hasUrls = !empty($volume['hasUrls']);
$url = ($hasUrls && !empty($settings['urlPrefix'])) ? $settings['urlPrefix'] : null;
//$settings['region'] = $settings['location'];
unset($settings['urlPrefix'], $settings['location'], $settings['storageClass']);
$volume['url'] = $url;
$volume['settings'] = $settings;
$this->update('{{%volumes}}', [
'settings' => Json::encode($settings),
'url' => $url,
], ['uid' => $uid]);
// If project config schema up to date, don't update project config
if (!version_compare($schemaVersion, '1.1', '>=')) {
$projectConfig->set(Volumes::CONFIG_VOLUME_KEY . '.' . $uid, $volume);
}
}
}
$projectConfig->muteEvents = false;
} | php | private function _convertVolumes()
{
$projectConfig = Craft::$app->getProjectConfig();
$schemaVersion = $projectConfig->get('plugins.aws-s3.schemaVersion', true);
$projectConfig->muteEvents = true;
$volumes = $projectConfig->get(Volumes::CONFIG_VOLUME_KEY, true) ?? [];
foreach ($volumes as $uid => &$volume) {
if ($volume['type'] === Volume::class && !empty($volume['settings']) && is_array($volume['settings']) && array_key_exists('urlPrefix', $volume['settings'])) {
$settings = $volume['settings'];
$hasUrls = !empty($volume['hasUrls']);
$url = ($hasUrls && !empty($settings['urlPrefix'])) ? $settings['urlPrefix'] : null;
//$settings['region'] = $settings['location'];
unset($settings['urlPrefix'], $settings['location'], $settings['storageClass']);
$volume['url'] = $url;
$volume['settings'] = $settings;
$this->update('{{%volumes}}', [
'settings' => Json::encode($settings),
'url' => $url,
], ['uid' => $uid]);
// If project config schema up to date, don't update project config
if (!version_compare($schemaVersion, '1.1', '>=')) {
$projectConfig->set(Volumes::CONFIG_VOLUME_KEY . '.' . $uid, $volume);
}
}
}
$projectConfig->muteEvents = false;
} | [
"private",
"function",
"_convertVolumes",
"(",
")",
"{",
"$",
"projectConfig",
"=",
"Craft",
"::",
"$",
"app",
"->",
"getProjectConfig",
"(",
")",
";",
"$",
"schemaVersion",
"=",
"$",
"projectConfig",
"->",
"get",
"(",
"'plugins.aws-s3.schemaVersion'",
",",
"t... | Converts any old school S3 volumes to this one
@return void | [
"Converts",
"any",
"old",
"school",
"S3",
"volumes",
"to",
"this",
"one"
] | c8288a7058d5ff0c62c7e80331acc6a4bd7055d9 | https://github.com/craftcms/aws-s3/blob/c8288a7058d5ff0c62c7e80331acc6a4bd7055d9/src/migrations/m190131_214300_cleanup_config.php#L54-L88 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.seed | public function seed($times, $name, array $attr = [])
{
$seeds = [];
for ($i = 0; $i < $times; $i++) {
$seeds[] = $this->create($name, $attr);
}
return $seeds;
} | php | public function seed($times, $name, array $attr = [])
{
$seeds = [];
for ($i = 0; $i < $times; $i++) {
$seeds[] = $this->create($name, $attr);
}
return $seeds;
} | [
"public",
"function",
"seed",
"(",
"$",
"times",
",",
"$",
"name",
",",
"array",
"$",
"attr",
"=",
"[",
"]",
")",
"{",
"$",
"seeds",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"times",
";",
"$",
"i",
"++"... | Creates and saves multiple versions of a model.
Under the hood, we're calling the create method over and over.
@param int $times The number of models to create.
@param string $name The model definition name.
@param array $attr The model attributes.
@return object[] | [
"Creates",
"and",
"saves",
"multiple",
"versions",
"of",
"a",
"model",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L82-L91 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.create | public function create($name, array $attr = [])
{
$model = $this->make($name, $attr, true);
$this->store->persist($model);
if ($this->triggerCallback($model, $name)) {
$this->store->persist($model);
}
return $model;
} | php | public function create($name, array $attr = [])
{
$model = $this->make($name, $attr, true);
$this->store->persist($model);
if ($this->triggerCallback($model, $name)) {
$this->store->persist($model);
}
return $model;
} | [
"public",
"function",
"create",
"(",
"$",
"name",
",",
"array",
"$",
"attr",
"=",
"[",
"]",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"make",
"(",
"$",
"name",
",",
"$",
"attr",
",",
"true",
")",
";",
"$",
"this",
"->",
"store",
"->",
"... | Creates and saves a model.
@param string $name The model definition name.
@param array $attr The model attributes.
@return object | [
"Creates",
"and",
"saves",
"a",
"model",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L101-L112 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.triggerCallback | protected function triggerCallback($model, $name)
{
$callback = $this->getDefinition($name)->getCallback();
if ($callback) {
$saved = $this->isPendingOrSaved($model);
return call_user_func($callback, $model, $saved) !== false;
}
return false;
} | php | protected function triggerCallback($model, $name)
{
$callback = $this->getDefinition($name)->getCallback();
if ($callback) {
$saved = $this->isPendingOrSaved($model);
return call_user_func($callback, $model, $saved) !== false;
}
return false;
} | [
"protected",
"function",
"triggerCallback",
"(",
"$",
"model",
",",
"$",
"name",
")",
"{",
"$",
"callback",
"=",
"$",
"this",
"->",
"getDefinition",
"(",
"$",
"name",
")",
"->",
"getCallback",
"(",
")",
";",
"if",
"(",
"$",
"callback",
")",
"{",
"$",... | Trigger the callback if we have one.
@param object $model The model instance.
@param string $name The model definition name.
@return bool | [
"Trigger",
"the",
"callback",
"if",
"we",
"have",
"one",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L122-L133 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.make | protected function make($name, array $attr, $save)
{
$definition = $this->getDefinition($name);
$model = $this->makeClass($definition->getClass(), $definition->getMaker());
// Make the object as saved so that other generators persist correctly
if ($save) {
$this->store->markPending($model);
}
// Get the attribute definitions
$attributes = array_merge($this->getDefinition($name)->getDefinitions(), $attr);
// Generate and save each attribute for the model
$this->generate($model, $attributes);
return $model;
} | php | protected function make($name, array $attr, $save)
{
$definition = $this->getDefinition($name);
$model = $this->makeClass($definition->getClass(), $definition->getMaker());
// Make the object as saved so that other generators persist correctly
if ($save) {
$this->store->markPending($model);
}
// Get the attribute definitions
$attributes = array_merge($this->getDefinition($name)->getDefinitions(), $attr);
// Generate and save each attribute for the model
$this->generate($model, $attributes);
return $model;
} | [
"protected",
"function",
"make",
"(",
"$",
"name",
",",
"array",
"$",
"attr",
",",
"$",
"save",
")",
"{",
"$",
"definition",
"=",
"$",
"this",
"->",
"getDefinition",
"(",
"$",
"name",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"makeClass",
"("... | Make an instance of a model.
@param string $name The model definition name.
@param array $attr The model attributes.
@param bool $save Are we saving, or just creating an instance?
@return object | [
"Make",
"an",
"instance",
"of",
"a",
"model",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L144-L161 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.isPendingOrSaved | public function isPendingOrSaved($model)
{
return $this->store->isSaved($model) || $this->store->isPending($model);
} | php | public function isPendingOrSaved($model)
{
return $this->store->isSaved($model) || $this->store->isPending($model);
} | [
"public",
"function",
"isPendingOrSaved",
"(",
"$",
"model",
")",
"{",
"return",
"$",
"this",
"->",
"store",
"->",
"isSaved",
"(",
"$",
"model",
")",
"||",
"$",
"this",
"->",
"store",
"->",
"isPending",
"(",
"$",
"model",
")",
";",
"}"
] | Is the object saved or will be saved?
@param object $model The model instance.
@return bool | [
"Is",
"the",
"object",
"saved",
"or",
"will",
"be",
"saved?"
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L193-L196 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.instance | public function instance($name, array $attr = [])
{
$model = $this->make($name, $attr, false);
$this->triggerCallback($model, $name);
return $model;
} | php | public function instance($name, array $attr = [])
{
$model = $this->make($name, $attr, false);
$this->triggerCallback($model, $name);
return $model;
} | [
"public",
"function",
"instance",
"(",
"$",
"name",
",",
"array",
"$",
"attr",
"=",
"[",
"]",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"make",
"(",
"$",
"name",
",",
"$",
"attr",
",",
"false",
")",
";",
"$",
"this",
"->",
"triggerCallback"... | Return an instance of the model.
This does not save it in the database. Use create for that.
@param string $name The model definition name.
@param array $attr The model attributes.
@return object | [
"Return",
"an",
"instance",
"of",
"the",
"model",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L220-L227 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.generate | protected function generate($model, array $attr = [])
{
foreach ($attr as $key => $kind) {
$value = $this->factory->generate($kind, $model, $this);
$setter = 'set'.ucfirst(static::camelize($key));
// check if there is a setter and use it instead
if (method_exists($model, $setter) && is_callable([$model, $setter])) {
$model->$setter($value);
} else {
$model->$key = $value;
}
}
} | php | protected function generate($model, array $attr = [])
{
foreach ($attr as $key => $kind) {
$value = $this->factory->generate($kind, $model, $this);
$setter = 'set'.ucfirst(static::camelize($key));
// check if there is a setter and use it instead
if (method_exists($model, $setter) && is_callable([$model, $setter])) {
$model->$setter($value);
} else {
$model->$key = $value;
}
}
} | [
"protected",
"function",
"generate",
"(",
"$",
"model",
",",
"array",
"$",
"attr",
"=",
"[",
"]",
")",
"{",
"foreach",
"(",
"$",
"attr",
"as",
"$",
"key",
"=>",
"$",
"kind",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"factory",
"->",
"genera... | Generate and set the model attributes.
@param object $model The model instance.
@param array $attr The model attributes.
@return void | [
"Generate",
"and",
"set",
"the",
"model",
"attributes",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L237-L251 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.define | public function define($name)
{
if (isset($this->definitions[$name])) {
throw new DefinitionAlreadyDefinedException($name);
}
if (strpos($name, ':') !== false) {
$group = current(explode(':', $name));
$class = str_replace($group.':', '', $name);
$this->definitions[$name] = clone $this->getDefinition($class);
$this->definitions[$name]->setGroup($group);
} else {
$this->definitions[$name] = new Definition($name);
}
return $this->definitions[$name];
} | php | public function define($name)
{
if (isset($this->definitions[$name])) {
throw new DefinitionAlreadyDefinedException($name);
}
if (strpos($name, ':') !== false) {
$group = current(explode(':', $name));
$class = str_replace($group.':', '', $name);
$this->definitions[$name] = clone $this->getDefinition($class);
$this->definitions[$name]->setGroup($group);
} else {
$this->definitions[$name] = new Definition($name);
}
return $this->definitions[$name];
} | [
"public",
"function",
"define",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"definitions",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"DefinitionAlreadyDefinedException",
"(",
"$",
"name",
")",
";",
"}",
"if",
"... | Define a new model definition.
Note that this method cannot be used to modify existing definitions.
Please use the getDefinition method for that.
@param string $name The model definition name.
@throws \League\FactoryMuffin\Exceptions\DefinitionAlreadyDefinedException
@return \League\FactoryMuffin\Definition | [
"Define",
"a",
"new",
"model",
"definition",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L293-L309 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.loadFactories | public function loadFactories($paths)
{
foreach ((array) $paths as $path) {
$real = realpath($path);
if (!$real) {
throw new DirectoryNotFoundException($path);
}
if (!is_dir($real)) {
throw new DirectoryNotFoundException($real);
}
$this->loadDirectory($real);
}
return $this;
} | php | public function loadFactories($paths)
{
foreach ((array) $paths as $path) {
$real = realpath($path);
if (!$real) {
throw new DirectoryNotFoundException($path);
}
if (!is_dir($real)) {
throw new DirectoryNotFoundException($real);
}
$this->loadDirectory($real);
}
return $this;
} | [
"public",
"function",
"loadFactories",
"(",
"$",
"paths",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"paths",
"as",
"$",
"path",
")",
"{",
"$",
"real",
"=",
"realpath",
"(",
"$",
"path",
")",
";",
"if",
"(",
"!",
"$",
"real",
")",
"{",
"... | Load the specified factories.
This method expects either a single path to a directory containing php
files, or an array of directory paths, and will "require" each file.
These files should be where you define your model definitions.
@param string|string[] $paths The directory path(s) to load.
@throws \League\FactoryMuffin\Exceptions\DirectoryNotFoundException
@return \League\FactoryMuffin\FactoryMuffin | [
"Load",
"the",
"specified",
"factories",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L324-L341 | train |
thephpleague/factory-muffin | src/FactoryMuffin.php | FactoryMuffin.loadDirectory | private function loadDirectory($path)
{
$directory = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($directory);
$files = new RegexIterator($iterator, '/^[^\.](?:(?!\/\.).)+?\.php$/i');
$fm = $this;
foreach ($files as $file) {
require $file->getPathName();
}
} | php | private function loadDirectory($path)
{
$directory = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($directory);
$files = new RegexIterator($iterator, '/^[^\.](?:(?!\/\.).)+?\.php$/i');
$fm = $this;
foreach ($files as $file) {
require $file->getPathName();
}
} | [
"private",
"function",
"loadDirectory",
"(",
"$",
"path",
")",
"{",
"$",
"directory",
"=",
"new",
"RecursiveDirectoryIterator",
"(",
"$",
"path",
")",
";",
"$",
"iterator",
"=",
"new",
"RecursiveIteratorIterator",
"(",
"$",
"directory",
")",
";",
"$",
"files... | Load all the files in a directory.
Each required file will have this instance available as "$fm".
@param string $path The directory path to load.
@return void | [
"Load",
"all",
"the",
"files",
"in",
"a",
"directory",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/FactoryMuffin.php#L352-L363 | train |
thephpleague/factory-muffin | src/Generators/GeneratorFactory.php | GeneratorFactory.generate | public function generate($kind, $model, FactoryMuffin $factoryMuffin)
{
$generator = $this->make($kind, $model, $factoryMuffin);
if ($generator) {
return $generator->generate();
}
return $kind;
} | php | public function generate($kind, $model, FactoryMuffin $factoryMuffin)
{
$generator = $this->make($kind, $model, $factoryMuffin);
if ($generator) {
return $generator->generate();
}
return $kind;
} | [
"public",
"function",
"generate",
"(",
"$",
"kind",
",",
"$",
"model",
",",
"FactoryMuffin",
"$",
"factoryMuffin",
")",
"{",
"$",
"generator",
"=",
"$",
"this",
"->",
"make",
"(",
"$",
"kind",
",",
"$",
"model",
",",
"$",
"factoryMuffin",
")",
";",
"... | Automatically generate the attribute we want.
@param string|callable $kind The kind of attribute.
@param object $model The model instance.
@param \League\FactoryMuffin\FactoryMuffin $factoryMuffin The factory muffin instance.
@return mixed | [
"Automatically",
"generate",
"the",
"attribute",
"we",
"want",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Generators/GeneratorFactory.php#L35-L44 | train |
thephpleague/factory-muffin | src/Generators/GeneratorFactory.php | GeneratorFactory.make | public function make($kind, $model, FactoryMuffin $factoryMuffin)
{
if (is_callable($kind)) {
return new CallableGenerator($kind, $model, $factoryMuffin);
}
if (is_string($kind) && strpos($kind, EntityGenerator::getPrefix()) === 0) {
return new EntityGenerator($kind, $model, $factoryMuffin);
}
if (is_string($kind) && strpos($kind, FactoryGenerator::getPrefix()) === 0) {
return new FactoryGenerator($kind, $model, $factoryMuffin);
}
} | php | public function make($kind, $model, FactoryMuffin $factoryMuffin)
{
if (is_callable($kind)) {
return new CallableGenerator($kind, $model, $factoryMuffin);
}
if (is_string($kind) && strpos($kind, EntityGenerator::getPrefix()) === 0) {
return new EntityGenerator($kind, $model, $factoryMuffin);
}
if (is_string($kind) && strpos($kind, FactoryGenerator::getPrefix()) === 0) {
return new FactoryGenerator($kind, $model, $factoryMuffin);
}
} | [
"public",
"function",
"make",
"(",
"$",
"kind",
",",
"$",
"model",
",",
"FactoryMuffin",
"$",
"factoryMuffin",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"kind",
")",
")",
"{",
"return",
"new",
"CallableGenerator",
"(",
"$",
"kind",
",",
"$",
"model... | Automatically make the generator class we need.
@param string|callable $kind The kind of attribute.
@param object $model The model instance.
@param \League\FactoryMuffin\FactoryMuffin $factoryMuffin The factory muffin instance.
@return \League\FactoryMuffin\Generators\GeneratorInterface|null | [
"Automatically",
"make",
"the",
"generator",
"class",
"we",
"need",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Generators/GeneratorFactory.php#L55-L68 | train |
thephpleague/factory-muffin | src/Stores/AbstractStore.php | AbstractStore.markSaved | public function markSaved($model)
{
$hash = spl_object_hash($model);
if (isset($this->pending[$hash])) {
unset($this->pending[$hash]);
}
$this->saved[$hash] = $model;
} | php | public function markSaved($model)
{
$hash = spl_object_hash($model);
if (isset($this->pending[$hash])) {
unset($this->pending[$hash]);
}
$this->saved[$hash] = $model;
} | [
"public",
"function",
"markSaved",
"(",
"$",
"model",
")",
"{",
"$",
"hash",
"=",
"spl_object_hash",
"(",
"$",
"model",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"pending",
"[",
"$",
"hash",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"thi... | Mark a model as saved.
@param object $model The model instance.
@return void | [
"Mark",
"a",
"model",
"as",
"saved",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Stores/AbstractStore.php#L138-L147 | train |
thephpleague/factory-muffin | src/Stores/AbstractStore.php | AbstractStore.deleteSaved | public function deleteSaved()
{
$exceptions = [];
while ($model = array_pop($this->saved)) {
try {
if (!$this->delete($model)) {
throw new DeleteFailedException(get_class($model));
}
} catch (Exception $e) {
$exceptions[] = $e;
}
}
// If we ran into any problems, throw the exception now
if ($exceptions) {
throw new DeletingFailedException($exceptions);
}
} | php | public function deleteSaved()
{
$exceptions = [];
while ($model = array_pop($this->saved)) {
try {
if (!$this->delete($model)) {
throw new DeleteFailedException(get_class($model));
}
} catch (Exception $e) {
$exceptions[] = $e;
}
}
// If we ran into any problems, throw the exception now
if ($exceptions) {
throw new DeletingFailedException($exceptions);
}
} | [
"public",
"function",
"deleteSaved",
"(",
")",
"{",
"$",
"exceptions",
"=",
"[",
"]",
";",
"while",
"(",
"$",
"model",
"=",
"array_pop",
"(",
"$",
"this",
"->",
"saved",
")",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"delete",
"(",... | Delete all the saved models.
@throws \League\FactoryMuffin\Exceptions\DeletingFailedException
@return void | [
"Delete",
"all",
"the",
"saved",
"models",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Stores/AbstractStore.php#L168-L186 | train |
thephpleague/factory-muffin | src/Generators/EntityGenerator.php | EntityGenerator.factory | private function factory($name)
{
if ($this->factoryMuffin->isPendingOrSaved($this->model)) {
return $this->factoryMuffin->create($name);
}
return $this->factoryMuffin->instance($name);
} | php | private function factory($name)
{
if ($this->factoryMuffin->isPendingOrSaved($this->model)) {
return $this->factoryMuffin->create($name);
}
return $this->factoryMuffin->instance($name);
} | [
"private",
"function",
"factory",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"factoryMuffin",
"->",
"isPendingOrSaved",
"(",
"$",
"this",
"->",
"model",
")",
")",
"{",
"return",
"$",
"this",
"->",
"factoryMuffin",
"->",
"create",
"(",
"$... | Create an instance of the model.
This model will be automatically saved to the database if the model we
are generating it for has been saved (the create function was used).
@param string $name The model definition name.
@return object | [
"Create",
"an",
"instance",
"of",
"the",
"model",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Generators/EntityGenerator.php#L90-L97 | train |
thephpleague/factory-muffin | src/Stores/RepositoryStore.php | RepositoryStore.flush | protected function flush()
{
$method = $this->methods['flush'];
if (!method_exists($this->storage, $method) || !is_callable([$this->storage, $method])) {
throw new FlushMethodNotFoundException(get_class($this->storage), $method);
}
$this->storage->$method();
return true;
} | php | protected function flush()
{
$method = $this->methods['flush'];
if (!method_exists($this->storage, $method) || !is_callable([$this->storage, $method])) {
throw new FlushMethodNotFoundException(get_class($this->storage), $method);
}
$this->storage->$method();
return true;
} | [
"protected",
"function",
"flush",
"(",
")",
"{",
"$",
"method",
"=",
"$",
"this",
"->",
"methods",
"[",
"'flush'",
"]",
";",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"this",
"->",
"storage",
",",
"$",
"method",
")",
"||",
"!",
"is_callable",
"(",
... | Flushes changes to storage.
@throws \League\FactoryMuffin\Exceptions\FlushMethodNotFoundException
@return bool | [
"Flushes",
"changes",
"to",
"storage",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Stores/RepositoryStore.php#L90-L101 | train |
thephpleague/factory-muffin | src/Exceptions/SaveFailedException.php | SaveFailedException.formatErrors | private function formatErrors($errors)
{
if ($errors) {
$errors = trim($errors);
if (in_array(substr($errors, -1), ['.', '!', '?'], true)) {
return $errors;
}
return $errors.'.';
}
} | php | private function formatErrors($errors)
{
if ($errors) {
$errors = trim($errors);
if (in_array(substr($errors, -1), ['.', '!', '?'], true)) {
return $errors;
}
return $errors.'.';
}
} | [
"private",
"function",
"formatErrors",
"(",
"$",
"errors",
")",
"{",
"if",
"(",
"$",
"errors",
")",
"{",
"$",
"errors",
"=",
"trim",
"(",
"$",
"errors",
")",
";",
"if",
"(",
"in_array",
"(",
"substr",
"(",
"$",
"errors",
",",
"-",
"1",
")",
",",
... | Format the given errors correctly.
We're stripping any trailing whitespace, and ensuring they end in a
punctuation character. If null is passed, then null is returned also.
@param string|null $errors
@return string|null | [
"Format",
"the",
"given",
"errors",
"correctly",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Exceptions/SaveFailedException.php#L69-L80 | train |
thephpleague/factory-muffin | src/Generators/FactoryGenerator.php | FactoryGenerator.getId | private function getId($model)
{
// Check to see if we can get an id via our defined methods
foreach (self::$methods as $method) {
if (method_exists($model, $method) && is_callable([$model, $method])) {
return $model->$method();
}
}
// Check to see if we can get an id via our defined properties
foreach (self::$properties as $property) {
if (isset($model->$property)) {
return $model->$property;
}
}
} | php | private function getId($model)
{
// Check to see if we can get an id via our defined methods
foreach (self::$methods as $method) {
if (method_exists($model, $method) && is_callable([$model, $method])) {
return $model->$method();
}
}
// Check to see if we can get an id via our defined properties
foreach (self::$properties as $property) {
if (isset($model->$property)) {
return $model->$property;
}
}
} | [
"private",
"function",
"getId",
"(",
"$",
"model",
")",
"{",
"// Check to see if we can get an id via our defined methods",
"foreach",
"(",
"self",
"::",
"$",
"methods",
"as",
"$",
"method",
")",
"{",
"if",
"(",
"method_exists",
"(",
"$",
"model",
",",
"$",
"m... | Get the model id.
@param object $model The model instance.
@return int|null | [
"Get",
"the",
"model",
"id",
"."
] | 0aa2575df3f693e4182b71459d744e93e86f3369 | https://github.com/thephpleague/factory-muffin/blob/0aa2575df3f693e4182b71459d744e93e86f3369/src/Generators/FactoryGenerator.php#L63-L78 | train |
j0k3r/graby | src/Monolog/Formatter/GrabyFormatter.php | GrabyFormatter.addRowWithLevel | private function addRowWithLevel($level, $th, $td = ' ', $escapeTd = true)
{
$th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8');
if ($escapeTd) {
$td = '<pre>' . htmlspecialchars($td, ENT_NOQUOTES, 'UTF-8') . '</pre>';
}
return "<tr style=\"padding: 4px;spacing: 0;text-align: left;\">\n<th style=\"background:" . $this->logLevels[$level] . "\" width=\"100px\">$th:</th>\n<td style=\"padding: 4px;spacing: 0;text-align: left;background: #eeeeee\">" . $td . "</td>\n</tr>";
} | php | private function addRowWithLevel($level, $th, $td = ' ', $escapeTd = true)
{
$th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8');
if ($escapeTd) {
$td = '<pre>' . htmlspecialchars($td, ENT_NOQUOTES, 'UTF-8') . '</pre>';
}
return "<tr style=\"padding: 4px;spacing: 0;text-align: left;\">\n<th style=\"background:" . $this->logLevels[$level] . "\" width=\"100px\">$th:</th>\n<td style=\"padding: 4px;spacing: 0;text-align: left;background: #eeeeee\">" . $td . "</td>\n</tr>";
} | [
"private",
"function",
"addRowWithLevel",
"(",
"$",
"level",
",",
"$",
"th",
",",
"$",
"td",
"=",
"' '",
",",
"$",
"escapeTd",
"=",
"true",
")",
"{",
"$",
"th",
"=",
"htmlspecialchars",
"(",
"$",
"th",
",",
"ENT_NOQUOTES",
",",
"'UTF-8'",
")",
";",
... | Creates an HTML table row with background cellon title cell.
@param int $level Error level
@param string $th Row header content
@param string $td Row standard cell content
@param bool $escapeTd false if td content must not be html escaped
@return string | [
"Creates",
"an",
"HTML",
"table",
"row",
"with",
"background",
"cellon",
"title",
"cell",
"."
] | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/Monolog/Formatter/GrabyFormatter.php#L69-L77 | train |
j0k3r/graby | src/SiteConfig/ConfigBuilder.php | ConfigBuilder.addToCache | public function addToCache($key, SiteConfig $config)
{
$key = strtolower($key);
if ('www.' === substr($key, 0, 4)) {
$key = substr($key, 4);
}
if ($config->cache_key) {
$key = $config->cache_key;
}
$this->cache[$key] = $config;
$this->logger->info('Cached site config with key: {key}', ['key' => $key]);
} | php | public function addToCache($key, SiteConfig $config)
{
$key = strtolower($key);
if ('www.' === substr($key, 0, 4)) {
$key = substr($key, 4);
}
if ($config->cache_key) {
$key = $config->cache_key;
}
$this->cache[$key] = $config;
$this->logger->info('Cached site config with key: {key}', ['key' => $key]);
} | [
"public",
"function",
"addToCache",
"(",
"$",
"key",
",",
"SiteConfig",
"$",
"config",
")",
"{",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"key",
")",
";",
"if",
"(",
"'www.'",
"===",
"substr",
"(",
"$",
"key",
",",
"0",
",",
"4",
")",
")",
"{",
... | Add the given SiteConfig to the cache.
@param string $key Key for the cache
@param SiteConfig $config Config to be cached | [
"Add",
"the",
"given",
"SiteConfig",
"to",
"the",
"cache",
"."
] | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/SiteConfig/ConfigBuilder.php#L66-L80 | train |
j0k3r/graby | src/SiteConfig/ConfigBuilder.php | ConfigBuilder.getCachedVersion | public function getCachedVersion($key)
{
$key = strtolower($key);
if ('www.' === substr($key, 0, 4)) {
$key = substr($key, 4);
}
if (\array_key_exists($key, $this->cache)) {
return $this->cache[$key];
}
return false;
} | php | public function getCachedVersion($key)
{
$key = strtolower($key);
if ('www.' === substr($key, 0, 4)) {
$key = substr($key, 4);
}
if (\array_key_exists($key, $this->cache)) {
return $this->cache[$key];
}
return false;
} | [
"public",
"function",
"getCachedVersion",
"(",
"$",
"key",
")",
"{",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"key",
")",
";",
"if",
"(",
"'www.'",
"===",
"substr",
"(",
"$",
"key",
",",
"0",
",",
"4",
")",
")",
"{",
"$",
"key",
"=",
"substr",
... | Determine if a Config is already cached.
If so, return it otherwise return false.
@param string $key Key for the cache
@return false|SiteConfig | [
"Determine",
"if",
"a",
"Config",
"is",
"already",
"cached",
".",
"If",
"so",
"return",
"it",
"otherwise",
"return",
"false",
"."
] | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/SiteConfig/ConfigBuilder.php#L90-L102 | train |
j0k3r/graby | src/SiteConfig/ConfigBuilder.php | ConfigBuilder.buildFromUrl | public function buildFromUrl($url, $addToCache = true)
{
// extract host name
$host = parse_url($url, PHP_URL_HOST);
return $this->buildForHost((string) $host, $addToCache);
} | php | public function buildFromUrl($url, $addToCache = true)
{
// extract host name
$host = parse_url($url, PHP_URL_HOST);
return $this->buildForHost((string) $host, $addToCache);
} | [
"public",
"function",
"buildFromUrl",
"(",
"$",
"url",
",",
"$",
"addToCache",
"=",
"true",
")",
"{",
"// extract host name",
"$",
"host",
"=",
"parse_url",
"(",
"$",
"url",
",",
"PHP_URL_HOST",
")",
";",
"return",
"$",
"this",
"->",
"buildForHost",
"(",
... | Build a config file from an url.
Use `buildForHost` if you already have the host.
@param string $url
@param bool $addToCache
@return SiteConfig | [
"Build",
"a",
"config",
"file",
"from",
"an",
"url",
".",
"Use",
"buildForHost",
"if",
"you",
"already",
"have",
"the",
"host",
"."
] | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/SiteConfig/ConfigBuilder.php#L123-L129 | train |
j0k3r/graby | src/SiteConfig/ConfigBuilder.php | ConfigBuilder.buildForHost | public function buildForHost($host, $addToCache = true)
{
$host = strtolower($host);
if ('www.' === substr($host, 0, 4)) {
$host = substr($host, 4);
}
// is merged version already cached?
$cachedSiteConfig = $this->getCachedVersion($host . '.merged');
if (false !== $cachedSiteConfig) {
$this->logger->info('Returning cached and merged site config for {host}', ['host' => $host]);
return $cachedSiteConfig;
}
// let's build it
$config = $this->loadSiteConfig($host);
if ($addToCache && false !== $config && false === $this->getCachedVersion($host)) {
$this->addToCache($host, $config);
}
// if no match, use defaults
if (false === $config) {
$config = $this->create();
}
// load global config?
$configGlobal = $this->loadSiteConfig('global', true);
if ($config->autodetect_on_failure() && false !== $configGlobal) {
$this->logger->info('Appending site config settings from global.txt');
$this->mergeConfig($config, $configGlobal);
if ($addToCache && false === $this->getCachedVersion('global')) {
$this->addToCache('global', $configGlobal);
}
}
// store copy of merged config
if ($addToCache) {
$config->cache_key = null;
$this->addToCache($host . '.merged', $config);
}
return $config;
} | php | public function buildForHost($host, $addToCache = true)
{
$host = strtolower($host);
if ('www.' === substr($host, 0, 4)) {
$host = substr($host, 4);
}
// is merged version already cached?
$cachedSiteConfig = $this->getCachedVersion($host . '.merged');
if (false !== $cachedSiteConfig) {
$this->logger->info('Returning cached and merged site config for {host}', ['host' => $host]);
return $cachedSiteConfig;
}
// let's build it
$config = $this->loadSiteConfig($host);
if ($addToCache && false !== $config && false === $this->getCachedVersion($host)) {
$this->addToCache($host, $config);
}
// if no match, use defaults
if (false === $config) {
$config = $this->create();
}
// load global config?
$configGlobal = $this->loadSiteConfig('global', true);
if ($config->autodetect_on_failure() && false !== $configGlobal) {
$this->logger->info('Appending site config settings from global.txt');
$this->mergeConfig($config, $configGlobal);
if ($addToCache && false === $this->getCachedVersion('global')) {
$this->addToCache('global', $configGlobal);
}
}
// store copy of merged config
if ($addToCache) {
$config->cache_key = null;
$this->addToCache($host . '.merged', $config);
}
return $config;
} | [
"public",
"function",
"buildForHost",
"(",
"$",
"host",
",",
"$",
"addToCache",
"=",
"true",
")",
"{",
"$",
"host",
"=",
"strtolower",
"(",
"$",
"host",
")",
";",
"if",
"(",
"'www.'",
"===",
"substr",
"(",
"$",
"host",
",",
"0",
",",
"4",
")",
")... | Build a config file from a host.
Use `buildFromUrl` if you have an url.
@param string $host Host, like en.wikipedia.org
@param bool $addToCache
@return SiteConfig | [
"Build",
"a",
"config",
"file",
"from",
"a",
"host",
".",
"Use",
"buildFromUrl",
"if",
"you",
"have",
"an",
"url",
"."
] | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/SiteConfig/ConfigBuilder.php#L140-L184 | train |
j0k3r/graby | src/SiteConfig/ConfigBuilder.php | ConfigBuilder.loadSiteConfig | public function loadSiteConfig($host, $exactHostMatch = false)
{
$host = strtolower($host);
if ('www.' === substr($host, 0, 4)) {
$host = substr($host, 4);
}
if (!$host || (\strlen($host) > 200) || !preg_match($this->config['hostname_regex'], ltrim($host, '.'))) {
return false;
}
$try = [$host];
// should we look for wildcard matches
// will try to see for a host without the first subdomain (fr.example.org & .example.org)
// @todo: should we look for all possible subdomain? (fr.m.example.org &.m.example.org & .example.org)
if (!$exactHostMatch) {
$split = explode('.', $host);
if (\count($split) > 1) {
// remove first subdomain
array_shift($split);
$try[] = '.' . implode('.', $split);
}
}
$config = new SiteConfig();
// look for site config file in primary folder
$this->logger->info('. looking for site config for {host} in primary folder', ['host' => $host]);
foreach ($try as $host) {
if ($cachedConfig = $this->getCachedVersion($host)) {
$this->logger->info('... site config for {host} already loaded in this request', ['host' => $host]);
return $cachedConfig;
}
// if we found site config, process it
if (isset($this->configFiles[$host . '.txt'])) {
$this->logger->info('... found site config {host}', ['host' => $host . '.txt']);
$configLines = file($this->configFiles[$host . '.txt'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// no lines ? we don't found config then
if (empty($configLines) || !\is_array($configLines)) {
return false;
}
$config = $this->parseLines($configLines);
$config->cache_key = $host;
break;
}
}
// append global config?
if ('global' !== $host && $config->autodetect_on_failure() && isset($this->configFiles['global.txt'])) {
$this->logger->info('Appending site config settings from global.txt');
$configGlobal = $this->loadSiteConfig('global', true);
if (false !== $configGlobal) {
$config = $this->mergeConfig($config, $configGlobal);
}
}
return $config;
} | php | public function loadSiteConfig($host, $exactHostMatch = false)
{
$host = strtolower($host);
if ('www.' === substr($host, 0, 4)) {
$host = substr($host, 4);
}
if (!$host || (\strlen($host) > 200) || !preg_match($this->config['hostname_regex'], ltrim($host, '.'))) {
return false;
}
$try = [$host];
// should we look for wildcard matches
// will try to see for a host without the first subdomain (fr.example.org & .example.org)
// @todo: should we look for all possible subdomain? (fr.m.example.org &.m.example.org & .example.org)
if (!$exactHostMatch) {
$split = explode('.', $host);
if (\count($split) > 1) {
// remove first subdomain
array_shift($split);
$try[] = '.' . implode('.', $split);
}
}
$config = new SiteConfig();
// look for site config file in primary folder
$this->logger->info('. looking for site config for {host} in primary folder', ['host' => $host]);
foreach ($try as $host) {
if ($cachedConfig = $this->getCachedVersion($host)) {
$this->logger->info('... site config for {host} already loaded in this request', ['host' => $host]);
return $cachedConfig;
}
// if we found site config, process it
if (isset($this->configFiles[$host . '.txt'])) {
$this->logger->info('... found site config {host}', ['host' => $host . '.txt']);
$configLines = file($this->configFiles[$host . '.txt'], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// no lines ? we don't found config then
if (empty($configLines) || !\is_array($configLines)) {
return false;
}
$config = $this->parseLines($configLines);
$config->cache_key = $host;
break;
}
}
// append global config?
if ('global' !== $host && $config->autodetect_on_failure() && isset($this->configFiles['global.txt'])) {
$this->logger->info('Appending site config settings from global.txt');
$configGlobal = $this->loadSiteConfig('global', true);
if (false !== $configGlobal) {
$config = $this->mergeConfig($config, $configGlobal);
}
}
return $config;
} | [
"public",
"function",
"loadSiteConfig",
"(",
"$",
"host",
",",
"$",
"exactHostMatch",
"=",
"false",
")",
"{",
"$",
"host",
"=",
"strtolower",
"(",
"$",
"host",
")",
";",
"if",
"(",
"'www.'",
"===",
"substr",
"(",
"$",
"host",
",",
"0",
",",
"4",
")... | Returns SiteConfig instance if an appropriate one is found, false otherwise.
by default if host is 'test.example.org' we will look for and load '.example.org.txt' if it exists.
@param string $host Host, like en.wikipedia.org
@param bool $exactHostMatch if true, we will not look for wildcard config matches
@return false|SiteConfig | [
"Returns",
"SiteConfig",
"instance",
"if",
"an",
"appropriate",
"one",
"is",
"found",
"false",
"otherwise",
".",
"by",
"default",
"if",
"host",
"is",
"test",
".",
"example",
".",
"org",
"we",
"will",
"look",
"for",
"and",
"load",
".",
"example",
".",
"or... | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/SiteConfig/ConfigBuilder.php#L213-L276 | train |
j0k3r/graby | src/SiteConfig/ConfigBuilder.php | ConfigBuilder.mergeConfig | public function mergeConfig(SiteConfig $currentConfig, SiteConfig $newConfig)
{
// check for commands where we accept multiple statements (no test_url)
foreach (['title', 'body', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'next_page_link', 'date', 'author', 'strip_attr'] as $var) {
// append array elements for this config variable from $newConfig to this config
$currentConfig->$var = array_unique(array_merge($currentConfig->$var, $newConfig->$var));
}
// special handling of if_page_contains directive
foreach (['single_page_link'] as $var) {
if (isset($currentConfig->if_page_contains[$var]) && isset($newConfig->if_page_contains[$var])) {
$currentConfig->if_page_contains[$var] = array_merge($newConfig->if_page_contains[$var], $currentConfig->if_page_contains[$var]);
} elseif (isset($newConfig->if_page_contains[$var])) {
$currentConfig->if_page_contains[$var] = $newConfig->if_page_contains[$var];
}
}
// check for single statement commands
// we do not overwrite existing non null values
foreach (['tidy', 'prune', 'parser', 'autodetect_on_failure', 'requires_login', 'skip_json_ld'] as $var) {
if ($currentConfig->$var === null) {
$currentConfig->$var = $newConfig->$var;
}
}
// treat find_string and replace_string separately (don't apply array_unique) (thanks fabrizio!)
foreach (['find_string', 'replace_string'] as $var) {
// append array elements for this config variable from $newConfig to this config
$currentConfig->$var = array_merge($currentConfig->$var, $newConfig->$var);
}
// merge http_header array from currentConfig into newConfig
// because final values override former values in case of named keys
$currentConfig->http_header = array_merge($newConfig->http_header, $currentConfig->http_header);
return $currentConfig;
} | php | public function mergeConfig(SiteConfig $currentConfig, SiteConfig $newConfig)
{
// check for commands where we accept multiple statements (no test_url)
foreach (['title', 'body', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'next_page_link', 'date', 'author', 'strip_attr'] as $var) {
// append array elements for this config variable from $newConfig to this config
$currentConfig->$var = array_unique(array_merge($currentConfig->$var, $newConfig->$var));
}
// special handling of if_page_contains directive
foreach (['single_page_link'] as $var) {
if (isset($currentConfig->if_page_contains[$var]) && isset($newConfig->if_page_contains[$var])) {
$currentConfig->if_page_contains[$var] = array_merge($newConfig->if_page_contains[$var], $currentConfig->if_page_contains[$var]);
} elseif (isset($newConfig->if_page_contains[$var])) {
$currentConfig->if_page_contains[$var] = $newConfig->if_page_contains[$var];
}
}
// check for single statement commands
// we do not overwrite existing non null values
foreach (['tidy', 'prune', 'parser', 'autodetect_on_failure', 'requires_login', 'skip_json_ld'] as $var) {
if ($currentConfig->$var === null) {
$currentConfig->$var = $newConfig->$var;
}
}
// treat find_string and replace_string separately (don't apply array_unique) (thanks fabrizio!)
foreach (['find_string', 'replace_string'] as $var) {
// append array elements for this config variable from $newConfig to this config
$currentConfig->$var = array_merge($currentConfig->$var, $newConfig->$var);
}
// merge http_header array from currentConfig into newConfig
// because final values override former values in case of named keys
$currentConfig->http_header = array_merge($newConfig->http_header, $currentConfig->http_header);
return $currentConfig;
} | [
"public",
"function",
"mergeConfig",
"(",
"SiteConfig",
"$",
"currentConfig",
",",
"SiteConfig",
"$",
"newConfig",
")",
"{",
"// check for commands where we accept multiple statements (no test_url)",
"foreach",
"(",
"[",
"'title'",
",",
"'body'",
",",
"'strip'",
",",
"'... | Append a configuration from to an existing one.
@param SiteConfig $currentConfig Current configuration
@param SiteConfig $newConfig New configuration to be merged
@return SiteConfig Merged config | [
"Append",
"a",
"configuration",
"from",
"to",
"an",
"existing",
"one",
"."
] | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/SiteConfig/ConfigBuilder.php#L286-L322 | train |
j0k3r/graby | src/SiteConfig/ConfigBuilder.php | ConfigBuilder.parseLines | public function parseLines(array $lines)
{
$config = new SiteConfig();
foreach ($lines as $line) {
$line = trim($line);
// skip comments, empty lines
if ('' === $line || '#' === $line[0]) {
continue;
}
// get command
$command = explode(':', $line, 2);
// if there's no colon ':', skip this line
if (2 !== \count($command)) {
continue;
}
$val = trim($command[1]);
$command = trim($command[0]);
if ('' === $command || '' === $val) {
continue;
}
// check for commands where we accept multiple statements
if (\in_array($command, ['title', 'body', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'next_page_link', 'test_url', 'find_string', 'replace_string', 'login_extra_fields', 'native_ad_clue', 'date', 'author', 'strip_attr'], true)) {
array_push($config->$command, $val);
// check for single statement commands that evaluate to true or false
} elseif (\in_array($command, ['tidy', 'prune', 'autodetect_on_failure', 'requires_login', 'skip_json_ld'], true)) {
$config->$command = ('yes' === $val || 'true' === $val);
// check for single statement commands stored as strings
} elseif (\in_array($command, ['parser', 'login_username_field', 'login_password_field', 'not_logged_in_xpath', 'login_uri', 'src_lazy_load_attr'], true)) {
$config->$command = $val;
// check for replace_string(find): replace
} elseif ((')' === substr($command, -1)) && preg_match('!^([a-z0-9_]+)\((.*?)\)$!i', $command, $match) && 'replace_string' === $match[1]) {
array_push($config->find_string, $match[2]);
array_push($config->replace_string, $val);
} elseif ((')' === substr($command, -1)) && preg_match('!^([a-z0-9_]+)\(([a-z0-9_-]+)\)$!i', $command, $match) && 'http_header' === $match[1] && \in_array(strtolower($match[2]), ['user-agent', 'referer', 'cookie', 'accept'], true)) {
$config->http_header[strtolower(trim($match[2]))] = $val;
// special treatment for if_page_contains
} elseif (\in_array($command, ['if_page_contains'], true)) {
$this->handleIfPageContainsCondition($config, $val);
}
}
return $config;
} | php | public function parseLines(array $lines)
{
$config = new SiteConfig();
foreach ($lines as $line) {
$line = trim($line);
// skip comments, empty lines
if ('' === $line || '#' === $line[0]) {
continue;
}
// get command
$command = explode(':', $line, 2);
// if there's no colon ':', skip this line
if (2 !== \count($command)) {
continue;
}
$val = trim($command[1]);
$command = trim($command[0]);
if ('' === $command || '' === $val) {
continue;
}
// check for commands where we accept multiple statements
if (\in_array($command, ['title', 'body', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'next_page_link', 'test_url', 'find_string', 'replace_string', 'login_extra_fields', 'native_ad_clue', 'date', 'author', 'strip_attr'], true)) {
array_push($config->$command, $val);
// check for single statement commands that evaluate to true or false
} elseif (\in_array($command, ['tidy', 'prune', 'autodetect_on_failure', 'requires_login', 'skip_json_ld'], true)) {
$config->$command = ('yes' === $val || 'true' === $val);
// check for single statement commands stored as strings
} elseif (\in_array($command, ['parser', 'login_username_field', 'login_password_field', 'not_logged_in_xpath', 'login_uri', 'src_lazy_load_attr'], true)) {
$config->$command = $val;
// check for replace_string(find): replace
} elseif ((')' === substr($command, -1)) && preg_match('!^([a-z0-9_]+)\((.*?)\)$!i', $command, $match) && 'replace_string' === $match[1]) {
array_push($config->find_string, $match[2]);
array_push($config->replace_string, $val);
} elseif ((')' === substr($command, -1)) && preg_match('!^([a-z0-9_]+)\(([a-z0-9_-]+)\)$!i', $command, $match) && 'http_header' === $match[1] && \in_array(strtolower($match[2]), ['user-agent', 'referer', 'cookie', 'accept'], true)) {
$config->http_header[strtolower(trim($match[2]))] = $val;
// special treatment for if_page_contains
} elseif (\in_array($command, ['if_page_contains'], true)) {
$this->handleIfPageContainsCondition($config, $val);
}
}
return $config;
} | [
"public",
"function",
"parseLines",
"(",
"array",
"$",
"lines",
")",
"{",
"$",
"config",
"=",
"new",
"SiteConfig",
"(",
")",
";",
"foreach",
"(",
"$",
"lines",
"as",
"$",
"line",
")",
"{",
"$",
"line",
"=",
"trim",
"(",
"$",
"line",
")",
";",
"//... | Parse line from the config file to build the config.
@param array $lines
@return SiteConfig | [
"Parse",
"line",
"from",
"the",
"config",
"file",
"to",
"build",
"the",
"config",
"."
] | 6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8 | https://github.com/j0k3r/graby/blob/6c1506f19d1bb876fb26bfc11e3e11a993eb7fe8/src/SiteConfig/ConfigBuilder.php#L331-L378 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.