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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
libgraviton/graviton | src/Graviton/DocumentBundle/Listener/RqlSearchNodeListener.php | RqlSearchNodeListener.onVisitNode | public function onVisitNode(VisitNodeEvent $event)
{
// any search?
if (!$event->getNode() instanceof SearchNode || $event->getNode()->isVisited()) {
return $event;
}
$this->node = $event->getNode();
$this->builder = $event->getBuilder();
$this->expr = $event->isExpr();
$this->className = $event->getClassName();
// which mode?
if ($this->getSearchMode() === self::SEARCHMODE_SOLR) {
$this->handleSearchSolr();
} else {
$this->handleSearchMongo();
}
$event->setBuilder($this->builder);
$event->setNode($this->node);
$event->setExprNode($this->exprNode);
return $event;
} | php | public function onVisitNode(VisitNodeEvent $event)
{
// any search?
if (!$event->getNode() instanceof SearchNode || $event->getNode()->isVisited()) {
return $event;
}
$this->node = $event->getNode();
$this->builder = $event->getBuilder();
$this->expr = $event->isExpr();
$this->className = $event->getClassName();
// which mode?
if ($this->getSearchMode() === self::SEARCHMODE_SOLR) {
$this->handleSearchSolr();
} else {
$this->handleSearchMongo();
}
$event->setBuilder($this->builder);
$event->setNode($this->node);
$event->setExprNode($this->exprNode);
return $event;
} | [
"public",
"function",
"onVisitNode",
"(",
"VisitNodeEvent",
"$",
"event",
")",
"{",
"// any search?",
"if",
"(",
"!",
"$",
"event",
"->",
"getNode",
"(",
")",
"instanceof",
"SearchNode",
"||",
"$",
"event",
"->",
"getNode",
"(",
")",
"->",
"isVisited",
"("... | gets called during the visit of a normal search node
@param VisitNodeEvent $event node event to visit
@return VisitNodeEvent event object | [
"gets",
"called",
"during",
"the",
"visit",
"of",
"a",
"normal",
"search",
"node"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/RqlSearchNodeListener.php#L89-L113 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/Listener/RqlSearchNodeListener.php | RqlSearchNodeListener.getSearchMode | private function getSearchMode()
{
$this->solrQuery->setClassName($this->className);
if ($this->solrQuery->isConfigured()) {
return self::SEARCHMODE_SOLR;
}
return self::SEARCHMODE_MONGO;
} | php | private function getSearchMode()
{
$this->solrQuery->setClassName($this->className);
if ($this->solrQuery->isConfigured()) {
return self::SEARCHMODE_SOLR;
}
return self::SEARCHMODE_MONGO;
} | [
"private",
"function",
"getSearchMode",
"(",
")",
"{",
"$",
"this",
"->",
"solrQuery",
"->",
"setClassName",
"(",
"$",
"this",
"->",
"className",
")",
";",
"if",
"(",
"$",
"this",
"->",
"solrQuery",
"->",
"isConfigured",
"(",
")",
")",
"{",
"return",
"... | returns which search backend to use
@return string search mode constant | [
"returns",
"which",
"search",
"backend",
"to",
"use"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/Listener/RqlSearchNodeListener.php#L211-L219 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/BundleGenerator.php | BundleGenerator.generate | public function generate($namespace, $bundle, $dir, $format)
{
$dir .= '/' . strtr($namespace, '\\', '/');
// make sure we have no trailing \ in namespace
if (substr($namespace, -1) == '\\') {
$namespace = substr($namespace, 0, -1);
}
$basename = $this->getBundleBaseName($bundle);
$parameters = array(
'namespace' => $namespace,
'bundle' => $bundle,
'format' => $format,
'bundle_basename' => $basename,
'extension_alias' => Container::underscore($basename),
);
$this->renderFile('bundle/Bundle.php.twig', $dir . '/' . $bundle . '.php', $parameters);
$this->renderFile(
'bundle/Extension.php.twig',
$dir . '/DependencyInjection/' . $basename . 'Extension.php',
$parameters
);
$this->renderFile('bundle/config.xml.twig', $dir . '/Resources/config/config.xml', $parameters);
if ('xml' === $format || 'annotation' === $format) {
$this->renderFile('bundle/services.xml.twig', $dir . '/Resources/config/services.xml', $parameters);
} else {
$this->renderFile(
'bundle/services.' . $format . '.twig',
$dir . '/Resources/config/services.' . $format,
$parameters
);
}
if ('annotation' != $format) {
$this->renderFile(
'bundle/routing.' . $format . '.twig',
$dir . '/Resources/config/routing.' . $format,
$parameters
);
}
} | php | public function generate($namespace, $bundle, $dir, $format)
{
$dir .= '/' . strtr($namespace, '\\', '/');
// make sure we have no trailing \ in namespace
if (substr($namespace, -1) == '\\') {
$namespace = substr($namespace, 0, -1);
}
$basename = $this->getBundleBaseName($bundle);
$parameters = array(
'namespace' => $namespace,
'bundle' => $bundle,
'format' => $format,
'bundle_basename' => $basename,
'extension_alias' => Container::underscore($basename),
);
$this->renderFile('bundle/Bundle.php.twig', $dir . '/' . $bundle . '.php', $parameters);
$this->renderFile(
'bundle/Extension.php.twig',
$dir . '/DependencyInjection/' . $basename . 'Extension.php',
$parameters
);
$this->renderFile('bundle/config.xml.twig', $dir . '/Resources/config/config.xml', $parameters);
if ('xml' === $format || 'annotation' === $format) {
$this->renderFile('bundle/services.xml.twig', $dir . '/Resources/config/services.xml', $parameters);
} else {
$this->renderFile(
'bundle/services.' . $format . '.twig',
$dir . '/Resources/config/services.' . $format,
$parameters
);
}
if ('annotation' != $format) {
$this->renderFile(
'bundle/routing.' . $format . '.twig',
$dir . '/Resources/config/routing.' . $format,
$parameters
);
}
} | [
"public",
"function",
"generate",
"(",
"$",
"namespace",
",",
"$",
"bundle",
",",
"$",
"dir",
",",
"$",
"format",
")",
"{",
"$",
"dir",
".=",
"'/'",
".",
"strtr",
"(",
"$",
"namespace",
",",
"'\\\\'",
",",
"'/'",
")",
";",
"// make sure we have no trai... | generate bundle code
@param string $namespace namspace name
@param string $bundle bundle name
@param string $dir bundle dir
@param string $format bundle condfig file format
@return void | [
"generate",
"bundle",
"code"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/BundleGenerator.php#L35-L79 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php | SolrDefinitionCompilerPass.process | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$solrFields = $document->getSolrFields();
if (is_array($solrFields) && !empty($solrFields)) {
$map[$document->getClass()] = $this->getSolrWeightString($solrFields);
}
}
$container->setParameter('graviton.document.solr.map', $map);
} | php | public function process(ContainerBuilder $container)
{
$this->documentMap = $container->get('graviton.document.map');
$map = [];
foreach ($this->documentMap->getDocuments() as $document) {
$solrFields = $document->getSolrFields();
if (is_array($solrFields) && !empty($solrFields)) {
$map[$document->getClass()] = $this->getSolrWeightString($solrFields);
}
}
$container->setParameter('graviton.document.solr.map', $map);
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"this",
"->",
"documentMap",
"=",
"$",
"container",
"->",
"get",
"(",
"'graviton.document.map'",
")",
";",
"$",
"map",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"th... | map with the weight string incorporated
@param ContainerBuilder $container container builder
@return void | [
"map",
"with",
"the",
"weight",
"string",
"incorporated"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php#L30-L43 | train |
libgraviton/graviton | src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php | SolrDefinitionCompilerPass.getSolrWeightString | private function getSolrWeightString(array $solrFields)
{
$weights = [];
foreach ($solrFields as $field) {
$weights[] = $field['name'].'^'.$field['weight'];
}
return implode(' ', $weights);
} | php | private function getSolrWeightString(array $solrFields)
{
$weights = [];
foreach ($solrFields as $field) {
$weights[] = $field['name'].'^'.$field['weight'];
}
return implode(' ', $weights);
} | [
"private",
"function",
"getSolrWeightString",
"(",
"array",
"$",
"solrFields",
")",
"{",
"$",
"weights",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"solrFields",
"as",
"$",
"field",
")",
"{",
"$",
"weights",
"[",
"]",
"=",
"$",
"field",
"[",
"'name'",
... | Returns the solr weight string
@param array $solrFields fields
@return string weight string | [
"Returns",
"the",
"solr",
"weight",
"string"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php#L52-L60 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Listener/RequestHostListener.php | RequestHostListener.onKernelRequest | public function onKernelRequest()
{
if (!is_null($this->host)) {
$this->router->getContext()->setHost($this->host);
}
if (!is_null($this->portHttp)) {
$this->router->getContext()->setHttpPort($this->portHttp);
}
if (!is_null($this->portHttps)) {
$this->router->getContext()->setHttpsPort($this->portHttps);
}
} | php | public function onKernelRequest()
{
if (!is_null($this->host)) {
$this->router->getContext()->setHost($this->host);
}
if (!is_null($this->portHttp)) {
$this->router->getContext()->setHttpPort($this->portHttp);
}
if (!is_null($this->portHttps)) {
$this->router->getContext()->setHttpsPort($this->portHttps);
}
} | [
"public",
"function",
"onKernelRequest",
"(",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"this",
"->",
"host",
")",
")",
"{",
"$",
"this",
"->",
"router",
"->",
"getContext",
"(",
")",
"->",
"setHost",
"(",
"$",
"this",
"->",
"host",
")",
";",
... | modify the router context params if configured
@return void | [
"modify",
"the",
"router",
"context",
"params",
"if",
"configured"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Listener/RequestHostListener.php#L68-L81 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.generate | public function generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$document
) {
$this->readServicesAndParams($bundleDir);
$basename = $this->getBundleBaseName($document);
if (!is_null($this->json)) {
$this->json->setNamespace($bundleNamespace);
}
// add more info to the fields array
$mapper = $this->mapper;
$fields = array_map(
function ($field) use ($mapper) {
return $mapper->map($field, $this->json);
},
$this->mapper->buildFields($this->json)
);
$parameters = $this->parameterBuilder
->reset()
->setParameter('document', $document)
->setParameter('base', $bundleNamespace)
->setParameter('bundle', $bundleName)
->setParameter('json', $this->json)
->setParameter('fields', $fields)
->setParameter('basename', $basename)
->setParameter('isrecordOriginFlagSet', $this->json->isRecordOriginFlagSet())
->setParameter('recordOriginModifiable', $this->json->isRecordOriginModifiable())
->setParameter('isVersioning', $this->json->isVersionedService())
->setParameter('collection', $this->json->getServiceCollection())
->setParameter('indexes', $this->json->getIndexes())
->setParameter('textIndexes', $this->json->getAllTextIndexes())
->setParameter('solrFields', $this->json->getSolrFields())
->setParameter('solrAggregate', $this->json->getSolrAggregate())
->getParameters();
$this->generateDocument($parameters, $bundleDir, $document);
$this->generateSerializer($parameters, $bundleDir, $document);
$this->generateModel($parameters, $bundleDir, $document);
if ($this->json instanceof JsonDefinition && $this->json->hasFixtures() === true) {
$this->generateFixtures($parameters, $bundleDir, $document);
}
if ($this->generateController) {
$this->generateController($parameters, $bundleDir, $document);
}
$this->persistServicesAndParams();
} | php | public function generate(
$bundleDir,
$bundleNamespace,
$bundleName,
$document
) {
$this->readServicesAndParams($bundleDir);
$basename = $this->getBundleBaseName($document);
if (!is_null($this->json)) {
$this->json->setNamespace($bundleNamespace);
}
// add more info to the fields array
$mapper = $this->mapper;
$fields = array_map(
function ($field) use ($mapper) {
return $mapper->map($field, $this->json);
},
$this->mapper->buildFields($this->json)
);
$parameters = $this->parameterBuilder
->reset()
->setParameter('document', $document)
->setParameter('base', $bundleNamespace)
->setParameter('bundle', $bundleName)
->setParameter('json', $this->json)
->setParameter('fields', $fields)
->setParameter('basename', $basename)
->setParameter('isrecordOriginFlagSet', $this->json->isRecordOriginFlagSet())
->setParameter('recordOriginModifiable', $this->json->isRecordOriginModifiable())
->setParameter('isVersioning', $this->json->isVersionedService())
->setParameter('collection', $this->json->getServiceCollection())
->setParameter('indexes', $this->json->getIndexes())
->setParameter('textIndexes', $this->json->getAllTextIndexes())
->setParameter('solrFields', $this->json->getSolrFields())
->setParameter('solrAggregate', $this->json->getSolrAggregate())
->getParameters();
$this->generateDocument($parameters, $bundleDir, $document);
$this->generateSerializer($parameters, $bundleDir, $document);
$this->generateModel($parameters, $bundleDir, $document);
if ($this->json instanceof JsonDefinition && $this->json->hasFixtures() === true) {
$this->generateFixtures($parameters, $bundleDir, $document);
}
if ($this->generateController) {
$this->generateController($parameters, $bundleDir, $document);
}
$this->persistServicesAndParams();
} | [
"public",
"function",
"generate",
"(",
"$",
"bundleDir",
",",
"$",
"bundleNamespace",
",",
"$",
"bundleName",
",",
"$",
"document",
")",
"{",
"$",
"this",
"->",
"readServicesAndParams",
"(",
"$",
"bundleDir",
")",
";",
"$",
"basename",
"=",
"$",
"this",
... | generate the resource with all its bits and parts
@param string $bundleDir bundle dir
@param string $bundleNamespace bundle namespace
@param string $bundleName bundle name
@param string $document document name
@return void | [
"generate",
"the",
"resource",
"with",
"all",
"its",
"bits",
"and",
"parts"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L123-L177 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.readServicesAndParams | protected function readServicesAndParams($bundleDir)
{
$this->servicesFile = $bundleDir.'/Resources/config/services.yml';
if ($this->fs->exists($this->servicesFile)) {
$this->services = Yaml::parseFile($this->servicesFile);
}
if (!isset($this->services['services'])) {
$this->services['services'] = [];
}
if (isset($this->services['parameters'])) {
$this->parameters['parameters'] = $this->services['parameters'];
unset($this->services['parameters']);
} else {
$this->parameters['parameters'] = [];
}
} | php | protected function readServicesAndParams($bundleDir)
{
$this->servicesFile = $bundleDir.'/Resources/config/services.yml';
if ($this->fs->exists($this->servicesFile)) {
$this->services = Yaml::parseFile($this->servicesFile);
}
if (!isset($this->services['services'])) {
$this->services['services'] = [];
}
if (isset($this->services['parameters'])) {
$this->parameters['parameters'] = $this->services['parameters'];
unset($this->services['parameters']);
} else {
$this->parameters['parameters'] = [];
}
} | [
"protected",
"function",
"readServicesAndParams",
"(",
"$",
"bundleDir",
")",
"{",
"$",
"this",
"->",
"servicesFile",
"=",
"$",
"bundleDir",
".",
"'/Resources/config/services.yml'",
";",
"if",
"(",
"$",
"this",
"->",
"fs",
"->",
"exists",
"(",
"$",
"this",
"... | reads the services.yml file
@param string $bundleDir bundle dir
@return void | [
"reads",
"the",
"services",
".",
"yml",
"file"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L186-L203 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.persistServicesAndParams | protected function persistServicesAndParams()
{
$this->filesystem->dumpFile(
$this->servicesFile,
Yaml::dump(array_merge($this->parameters, $this->services))
);
} | php | protected function persistServicesAndParams()
{
$this->filesystem->dumpFile(
$this->servicesFile,
Yaml::dump(array_merge($this->parameters, $this->services))
);
} | [
"protected",
"function",
"persistServicesAndParams",
"(",
")",
"{",
"$",
"this",
"->",
"filesystem",
"->",
"dumpFile",
"(",
"$",
"this",
"->",
"servicesFile",
",",
"Yaml",
"::",
"dump",
"(",
"array_merge",
"(",
"$",
"this",
"->",
"parameters",
",",
"$",
"t... | writes the services.yml file which includes the params
@return void | [
"writes",
"the",
"services",
".",
"yml",
"file",
"which",
"includes",
"the",
"params"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L210-L216 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.generateDocument | protected function generateDocument($parameters, $dir, $document)
{
// doctrine mapping normal class
$this->renderFile(
'document/Document.mongodb.yml.twig',
$dir . '/Resources/config/doctrine/' . $document . '.mongodb.yml',
$parameters
);
// doctrine mapping embedded
$this->renderFile(
'document/Document.mongodb.yml.twig',
$dir . '/Resources/config/doctrine/' . $document . 'Embedded.mongodb.yml',
array_merge(
$parameters,
[
'document' => $document.'Embedded',
'docType' => 'embeddedDocument'
]
)
);
$this->renderFile(
'document/Document.php.twig',
$dir . '/Document/' . $document . '.php',
$parameters
);
$this->renderFile(
'document/DocumentEmbedded.php.twig',
$dir . '/Document/' . $document . 'Embedded.php',
$parameters
);
$this->renderFile(
'document/DocumentBase.php.twig',
$dir . '/Document/' . $document . 'Base.php',
$parameters
);
$this->generateServices($parameters, $dir, $document);
} | php | protected function generateDocument($parameters, $dir, $document)
{
// doctrine mapping normal class
$this->renderFile(
'document/Document.mongodb.yml.twig',
$dir . '/Resources/config/doctrine/' . $document . '.mongodb.yml',
$parameters
);
// doctrine mapping embedded
$this->renderFile(
'document/Document.mongodb.yml.twig',
$dir . '/Resources/config/doctrine/' . $document . 'Embedded.mongodb.yml',
array_merge(
$parameters,
[
'document' => $document.'Embedded',
'docType' => 'embeddedDocument'
]
)
);
$this->renderFile(
'document/Document.php.twig',
$dir . '/Document/' . $document . '.php',
$parameters
);
$this->renderFile(
'document/DocumentEmbedded.php.twig',
$dir . '/Document/' . $document . 'Embedded.php',
$parameters
);
$this->renderFile(
'document/DocumentBase.php.twig',
$dir . '/Document/' . $document . 'Base.php',
$parameters
);
$this->generateServices($parameters, $dir, $document);
} | [
"protected",
"function",
"generateDocument",
"(",
"$",
"parameters",
",",
"$",
"dir",
",",
"$",
"document",
")",
"{",
"// doctrine mapping normal class",
"$",
"this",
"->",
"renderFile",
"(",
"'document/Document.mongodb.yml.twig'",
",",
"$",
"dir",
".",
"'/Resources... | generate document part of a resource
@param array $parameters twig parameters
@param string $dir base bundle dir
@param string $document document name
@return void | [
"generate",
"document",
"part",
"of",
"a",
"resource"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L227-L266 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.generateServices | protected function generateServices($parameters, $dir, $document)
{
$bundleParts = explode('\\', $parameters['base']);
$shortName = $bundleParts[0];
$shortBundle = $this->getBundleBaseName($bundleParts[1]);
$docName = implode(
'.',
array(
strtolower($shortName),
strtolower($shortBundle),
'document',
strtolower($parameters['document'])
)
);
$this->addParameter(
$parameters['base'] . 'Document\\' . $parameters['document'],
$docName . '.class'
);
$this->addService(
$docName,
null,
[],
null,
[],
null,
null,
'%'. $docName . '.class%'
);
$this->addParameter(
(array) $parameters['json']->getRoles(),
$docName . '.roles'
);
$repoName = implode(
'.',
array(
strtolower($shortName),
strtolower($shortBundle),
'repository',
strtolower($parameters['document'])
)
);
$this->addService(
$repoName,
null,
[],
null,
array(
array(
'type' => 'string',
'value' => $parameters['bundle'] . ':' . $document
)
),
'doctrine_mongodb.odm.default_document_manager',
'getRepository',
'Doctrine\ODM\MongoDB\DocumentRepository'
);
$this->addService(
$repoName . 'embedded',
null,
[],
null,
array(
array(
'type' => 'string',
'value' => $parameters['bundle'] . ':' . $document . 'Embedded'
)
),
'doctrine_mongodb.odm.default_document_manager',
'getRepository',
'Doctrine\ODM\MongoDB\DocumentRepository'
);
} | php | protected function generateServices($parameters, $dir, $document)
{
$bundleParts = explode('\\', $parameters['base']);
$shortName = $bundleParts[0];
$shortBundle = $this->getBundleBaseName($bundleParts[1]);
$docName = implode(
'.',
array(
strtolower($shortName),
strtolower($shortBundle),
'document',
strtolower($parameters['document'])
)
);
$this->addParameter(
$parameters['base'] . 'Document\\' . $parameters['document'],
$docName . '.class'
);
$this->addService(
$docName,
null,
[],
null,
[],
null,
null,
'%'. $docName . '.class%'
);
$this->addParameter(
(array) $parameters['json']->getRoles(),
$docName . '.roles'
);
$repoName = implode(
'.',
array(
strtolower($shortName),
strtolower($shortBundle),
'repository',
strtolower($parameters['document'])
)
);
$this->addService(
$repoName,
null,
[],
null,
array(
array(
'type' => 'string',
'value' => $parameters['bundle'] . ':' . $document
)
),
'doctrine_mongodb.odm.default_document_manager',
'getRepository',
'Doctrine\ODM\MongoDB\DocumentRepository'
);
$this->addService(
$repoName . 'embedded',
null,
[],
null,
array(
array(
'type' => 'string',
'value' => $parameters['bundle'] . ':' . $document . 'Embedded'
)
),
'doctrine_mongodb.odm.default_document_manager',
'getRepository',
'Doctrine\ODM\MongoDB\DocumentRepository'
);
} | [
"protected",
"function",
"generateServices",
"(",
"$",
"parameters",
",",
"$",
"dir",
",",
"$",
"document",
")",
"{",
"$",
"bundleParts",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"parameters",
"[",
"'base'",
"]",
")",
";",
"$",
"shortName",
"=",
"$",
"... | update xml services
@param array $parameters twig parameters
@param string $dir base bundle dir
@param string $document document name
@return void | [
"update",
"xml",
"services"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L277-L355 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.addService | protected function addService(
$id,
$parent = null,
array $calls = [],
$tag = null,
array $arguments = [],
$factoryService = null,
$factoryMethod = null,
$className = null
) {
$service = [];
$service['public'] = true;
// classname
if (is_null($className)) {
$className = '%' . $id . '.class%';
}
$service['class'] = $className;
// parent
if (!is_null($parent)) {
$service['parent'] = $parent;
}
// factory
if ($factoryService && $factoryMethod) {
$service['factory'] = [
'@'.$factoryService,
$factoryMethod
];
}
foreach ($arguments as $argument) {
if ($argument['type'] == 'service') {
$service['arguments'][] = '@'.$argument['id'];
} else {
$service['arguments'][] = $argument['value'];
}
}
// calls
foreach ($calls as $call) {
$service['calls'][] = [
$call['method'],
['@'.$call['service']]
];
}
// tags
if ($tag) {
$thisTag = [
'name' => $tag
];
if ($this->json instanceof JsonDefinition) {
$thisTag['collection'] = $this->json->getId();
// is this read only?
if ($this->json->isReadOnlyService()) {
$thisTag['read-only'] = true;
}
// router base defined?
$routerBase = $this->json->getRouterBase();
if ($routerBase !== false) {
$thisTag['router-base'] = $routerBase;
}
}
$service['tags'][] = $thisTag;
}
$this->services['services'][$id] = $service;
} | php | protected function addService(
$id,
$parent = null,
array $calls = [],
$tag = null,
array $arguments = [],
$factoryService = null,
$factoryMethod = null,
$className = null
) {
$service = [];
$service['public'] = true;
// classname
if (is_null($className)) {
$className = '%' . $id . '.class%';
}
$service['class'] = $className;
// parent
if (!is_null($parent)) {
$service['parent'] = $parent;
}
// factory
if ($factoryService && $factoryMethod) {
$service['factory'] = [
'@'.$factoryService,
$factoryMethod
];
}
foreach ($arguments as $argument) {
if ($argument['type'] == 'service') {
$service['arguments'][] = '@'.$argument['id'];
} else {
$service['arguments'][] = $argument['value'];
}
}
// calls
foreach ($calls as $call) {
$service['calls'][] = [
$call['method'],
['@'.$call['service']]
];
}
// tags
if ($tag) {
$thisTag = [
'name' => $tag
];
if ($this->json instanceof JsonDefinition) {
$thisTag['collection'] = $this->json->getId();
// is this read only?
if ($this->json->isReadOnlyService()) {
$thisTag['read-only'] = true;
}
// router base defined?
$routerBase = $this->json->getRouterBase();
if ($routerBase !== false) {
$thisTag['router-base'] = $routerBase;
}
}
$service['tags'][] = $thisTag;
}
$this->services['services'][$id] = $service;
} | [
"protected",
"function",
"addService",
"(",
"$",
"id",
",",
"$",
"parent",
"=",
"null",
",",
"array",
"$",
"calls",
"=",
"[",
"]",
",",
"$",
"tag",
"=",
"null",
",",
"array",
"$",
"arguments",
"=",
"[",
"]",
",",
"$",
"factoryService",
"=",
"null",... | add service to services.yml
@param string $id id of new service
@param string $parent parent for service
@param array $calls methodCalls to add
@param string $tag tag name or empty if no tag needed
@param array $arguments service arguments
@param string $factoryService factory service id
@param string $factoryMethod factory method name
@param string $className class name to override
@return void | [
"add",
"service",
"to",
"services",
".",
"yml"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L385-L458 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.generateSerializer | protected function generateSerializer(array $parameters, $dir, $document)
{
// @TODO in Embedded and document just render the differences..
$this->renderFile(
'serializer/Document.xml.twig',
$dir . '/Resources/config/serializer/Document.' . $document . 'Embedded.xml',
array_merge(
$parameters,
[
'document' => $document.'Embedded',
'noIdField' => true,
'realIdField' => true
]
)
);
foreach ($parameters['fields'] as $key => $field) {
if (substr($field['serializerType'], 0, 14) == 'array<Graviton' &&
strpos($field['serializerType'], '\\Entity') === false &&
$field['relType'] == 'embed'
) {
$parameters['fields'][$key]['serializerType'] = substr($field['serializerType'], 0, -1).'Embedded>';
} elseif (substr($field['serializerType'], 0, 8) == 'Graviton' &&
strpos($field['serializerType'], '\\Entity') === false &&
$field['relType'] == 'embed'
) {
$parameters['fields'][$key]['serializerType'] = $field['serializerType'].'Embedded';
}
}
$this->renderFile(
'serializer/Document.xml.twig',
$dir . '/Resources/config/serializer/Document.' . $document . '.xml',
array_merge(
$parameters,
[
'realIdField' => false
]
)
);
$this->renderFile(
'serializer/Document.xml.twig',
$dir . '/Resources/config/serializer/Document.' . $document . 'Base.xml',
array_merge(
$parameters,
[
'document' => $document.'Base',
'realIdField' => false
]
)
);
} | php | protected function generateSerializer(array $parameters, $dir, $document)
{
// @TODO in Embedded and document just render the differences..
$this->renderFile(
'serializer/Document.xml.twig',
$dir . '/Resources/config/serializer/Document.' . $document . 'Embedded.xml',
array_merge(
$parameters,
[
'document' => $document.'Embedded',
'noIdField' => true,
'realIdField' => true
]
)
);
foreach ($parameters['fields'] as $key => $field) {
if (substr($field['serializerType'], 0, 14) == 'array<Graviton' &&
strpos($field['serializerType'], '\\Entity') === false &&
$field['relType'] == 'embed'
) {
$parameters['fields'][$key]['serializerType'] = substr($field['serializerType'], 0, -1).'Embedded>';
} elseif (substr($field['serializerType'], 0, 8) == 'Graviton' &&
strpos($field['serializerType'], '\\Entity') === false &&
$field['relType'] == 'embed'
) {
$parameters['fields'][$key]['serializerType'] = $field['serializerType'].'Embedded';
}
}
$this->renderFile(
'serializer/Document.xml.twig',
$dir . '/Resources/config/serializer/Document.' . $document . '.xml',
array_merge(
$parameters,
[
'realIdField' => false
]
)
);
$this->renderFile(
'serializer/Document.xml.twig',
$dir . '/Resources/config/serializer/Document.' . $document . 'Base.xml',
array_merge(
$parameters,
[
'document' => $document.'Base',
'realIdField' => false
]
)
);
} | [
"protected",
"function",
"generateSerializer",
"(",
"array",
"$",
"parameters",
",",
"$",
"dir",
",",
"$",
"document",
")",
"{",
"// @TODO in Embedded and document just render the differences..",
"$",
"this",
"->",
"renderFile",
"(",
"'serializer/Document.xml.twig'",
",",... | generate serializer part of a resource
@param array $parameters twig parameters
@param string $dir base bundle dir
@param string $document document name
@return void | [
"generate",
"serializer",
"part",
"of",
"a",
"resource"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L469-L519 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.generateModel | protected function generateModel(array $parameters, $dir, $document)
{
$this->renderFile(
'model/Model.php.twig',
$dir . '/Model/' . $document . '.php',
$parameters
);
$this->renderFile(
'model/schema.json.twig',
$dir . '/Resources/config/schema/' . $document . '.json',
$parameters
);
// embedded versions
$this->renderFile(
'model/Model.php.twig',
$dir . '/Model/' . $document . 'Embedded.php',
array_merge($parameters, ['document' => $document.'Embedded'])
);
$this->renderFile(
'model/schema.json.twig',
$dir . '/Resources/config/schema/' . $document . 'Embedded.json',
array_merge($parameters, ['document' => $document.'Embedded'])
);
$bundleParts = explode('\\', $parameters['base']);
$shortName = strtolower($bundleParts[0]);
$shortBundle = strtolower(substr($bundleParts[1], 0, -6));
$paramName = implode('.', array($shortName, $shortBundle, 'model', strtolower($parameters['document'])));
$repoName = implode('.', array($shortName, $shortBundle, 'repository', strtolower($parameters['document'])));
$this->addParameter($parameters['base'] . 'Model\\' . $parameters['document'], $paramName . '.class');
// normal service
$this->addService(
$paramName,
'graviton.rest.model',
array(
[
'method' => 'setRepository',
'service' => $repoName
],
),
null
);
// embedded service
$this->addParameter(
$parameters['base'] . 'Model\\' . $parameters['document'] . 'Embedded',
$paramName . 'embedded.class'
);
$this->addService(
$paramName . 'embedded',
'graviton.rest.model',
array(
[
'method' => 'setRepository',
'service' => $repoName . 'embedded'
],
),
null
);
} | php | protected function generateModel(array $parameters, $dir, $document)
{
$this->renderFile(
'model/Model.php.twig',
$dir . '/Model/' . $document . '.php',
$parameters
);
$this->renderFile(
'model/schema.json.twig',
$dir . '/Resources/config/schema/' . $document . '.json',
$parameters
);
// embedded versions
$this->renderFile(
'model/Model.php.twig',
$dir . '/Model/' . $document . 'Embedded.php',
array_merge($parameters, ['document' => $document.'Embedded'])
);
$this->renderFile(
'model/schema.json.twig',
$dir . '/Resources/config/schema/' . $document . 'Embedded.json',
array_merge($parameters, ['document' => $document.'Embedded'])
);
$bundleParts = explode('\\', $parameters['base']);
$shortName = strtolower($bundleParts[0]);
$shortBundle = strtolower(substr($bundleParts[1], 0, -6));
$paramName = implode('.', array($shortName, $shortBundle, 'model', strtolower($parameters['document'])));
$repoName = implode('.', array($shortName, $shortBundle, 'repository', strtolower($parameters['document'])));
$this->addParameter($parameters['base'] . 'Model\\' . $parameters['document'], $paramName . '.class');
// normal service
$this->addService(
$paramName,
'graviton.rest.model',
array(
[
'method' => 'setRepository',
'service' => $repoName
],
),
null
);
// embedded service
$this->addParameter(
$parameters['base'] . 'Model\\' . $parameters['document'] . 'Embedded',
$paramName . 'embedded.class'
);
$this->addService(
$paramName . 'embedded',
'graviton.rest.model',
array(
[
'method' => 'setRepository',
'service' => $repoName . 'embedded'
],
),
null
);
} | [
"protected",
"function",
"generateModel",
"(",
"array",
"$",
"parameters",
",",
"$",
"dir",
",",
"$",
"document",
")",
"{",
"$",
"this",
"->",
"renderFile",
"(",
"'model/Model.php.twig'",
",",
"$",
"dir",
".",
"'/Model/'",
".",
"$",
"document",
".",
"'.php... | generate model part of a resource
@param array $parameters twig parameters
@param string $dir base bundle dir
@param string $document document name
@return void | [
"generate",
"model",
"part",
"of",
"a",
"resource"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L530-L593 | train |
libgraviton/graviton | src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php | ResourceGenerator.generateController | protected function generateController(array $parameters, $dir, $document)
{
$this->renderFile(
'controller/DocumentController.php.twig',
$dir . '/Controller/' . $document . 'Controller.php',
$parameters
);
$bundleParts = explode('\\', $parameters['base']);
$shortName = strtolower($bundleParts[0]);
$shortBundle = strtolower(substr($bundleParts[1], 0, -6));
$paramName = implode('.', array($shortName, $shortBundle, 'controller', strtolower($parameters['document'])));
$this->addParameter(
$parameters['base'] . 'Controller\\' . $parameters['document'] . 'Controller',
$paramName . '.class'
);
$this->addService(
$paramName,
$parameters['parent'],
array(
array(
'method' => 'setModel',
'service' => implode(
'.',
array($shortName, $shortBundle, 'model', strtolower($parameters['document']))
)
)
),
'graviton.rest'
);
} | php | protected function generateController(array $parameters, $dir, $document)
{
$this->renderFile(
'controller/DocumentController.php.twig',
$dir . '/Controller/' . $document . 'Controller.php',
$parameters
);
$bundleParts = explode('\\', $parameters['base']);
$shortName = strtolower($bundleParts[0]);
$shortBundle = strtolower(substr($bundleParts[1], 0, -6));
$paramName = implode('.', array($shortName, $shortBundle, 'controller', strtolower($parameters['document'])));
$this->addParameter(
$parameters['base'] . 'Controller\\' . $parameters['document'] . 'Controller',
$paramName . '.class'
);
$this->addService(
$paramName,
$parameters['parent'],
array(
array(
'method' => 'setModel',
'service' => implode(
'.',
array($shortName, $shortBundle, 'model', strtolower($parameters['document']))
)
)
),
'graviton.rest'
);
} | [
"protected",
"function",
"generateController",
"(",
"array",
"$",
"parameters",
",",
"$",
"dir",
",",
"$",
"document",
")",
"{",
"$",
"this",
"->",
"renderFile",
"(",
"'controller/DocumentController.php.twig'",
",",
"$",
"dir",
".",
"'/Controller/'",
".",
"$",
... | generate RESTful controllers ans service configs
@param array $parameters twig parameters
@param string $dir base bundle dir
@param string $document document name
@return void | [
"generate",
"RESTful",
"controllers",
"ans",
"service",
"configs"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php#L604-L636 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Listener/JsonExceptionListener.php | JsonExceptionListener.onKernelException | public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
// Should return a error 400 bad request
if ($exception instanceof ValidationException
|| $exception instanceof SyntaxErrorException) {
return;
}
// Some Exceptions have status code and if 400 it should be handled by them
if (method_exists($exception, 'getStatusCode')
&& (400 == (int)$exception->getStatusCode())) {
return;
}
$data = $this->decorateKnownCases($exception);
if (!is_array($data)) {
$data = [
'code' => $exception->getCode(),
'exceptionClass' => get_class($exception),
'message' => $exception->getMessage()
];
if ($exception->getPrevious() instanceof \Exception) {
$data['innerMessage'] = $exception->getPrevious()->getMessage();
}
}
if ($this->logger instanceof Logger) {
$this->logger->critical($exception);
}
$response = new JsonResponse($data);
$event->setResponse($response);
} | php | public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
// Should return a error 400 bad request
if ($exception instanceof ValidationException
|| $exception instanceof SyntaxErrorException) {
return;
}
// Some Exceptions have status code and if 400 it should be handled by them
if (method_exists($exception, 'getStatusCode')
&& (400 == (int)$exception->getStatusCode())) {
return;
}
$data = $this->decorateKnownCases($exception);
if (!is_array($data)) {
$data = [
'code' => $exception->getCode(),
'exceptionClass' => get_class($exception),
'message' => $exception->getMessage()
];
if ($exception->getPrevious() instanceof \Exception) {
$data['innerMessage'] = $exception->getPrevious()->getMessage();
}
}
if ($this->logger instanceof Logger) {
$this->logger->critical($exception);
}
$response = new JsonResponse($data);
$event->setResponse($response);
} | [
"public",
"function",
"onKernelException",
"(",
"GetResponseForExceptionEvent",
"$",
"event",
")",
"{",
"$",
"exception",
"=",
"$",
"event",
"->",
"getException",
"(",
")",
";",
"// Should return a error 400 bad request",
"if",
"(",
"$",
"exception",
"instanceof",
"... | Should not handle Validation Exceptions and only service exceptions
@param GetResponseForExceptionEvent $event Sf Event
@return void | [
"Should",
"not",
"handle",
"Validation",
"Exceptions",
"and",
"only",
"service",
"exceptions"
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Listener/JsonExceptionListener.php#L49-L85 | train |
libgraviton/graviton | src/Graviton/CoreBundle/Listener/JsonExceptionListener.php | JsonExceptionListener.decorateKnownCases | private function decorateKnownCases($exception)
{
if (
$exception instanceof \ErrorException &&
strpos($exception->getMessage(), 'Undefined index: $id') !== false
) {
return [
'code' => $exception->getCode(),
'message' => 'An incomplete internal MongoDB ref has been discovered that can not be rendered. '.
'Did you pass a select() RQL statement and shaved off on the wrong level? Try to select a level '.
'higher.'
];
} elseif (
$exception instanceof SerializationException &&
strpos($exception->getMessage(), 'Cannot serialize content class') !== false
) {
$error = $exception->getMessage();
$message = strpos($error, 'not be found.') !== false ?
substr($error, 0, strpos($error, 'not be found.')).'not be found.' : $error;
preg_match('/\bwith id: (.*);.*?\bdocument\\\(.*)".*?\bidentifier "(.*)"/is', $message, $matches);
if (array_key_exists(3, $matches)) {
$sentence = 'Internal Database reference error as been discovered. '.
'The object id: "%s" has a reference to document: "%s" with id: "%s" that could not be found.';
$message = sprintf($sentence, $matches[1], $matches[2], $matches[3]);
}
return [
'code' => $exception->getCode(),
'message' => $message
];
}
} | php | private function decorateKnownCases($exception)
{
if (
$exception instanceof \ErrorException &&
strpos($exception->getMessage(), 'Undefined index: $id') !== false
) {
return [
'code' => $exception->getCode(),
'message' => 'An incomplete internal MongoDB ref has been discovered that can not be rendered. '.
'Did you pass a select() RQL statement and shaved off on the wrong level? Try to select a level '.
'higher.'
];
} elseif (
$exception instanceof SerializationException &&
strpos($exception->getMessage(), 'Cannot serialize content class') !== false
) {
$error = $exception->getMessage();
$message = strpos($error, 'not be found.') !== false ?
substr($error, 0, strpos($error, 'not be found.')).'not be found.' : $error;
preg_match('/\bwith id: (.*);.*?\bdocument\\\(.*)".*?\bidentifier "(.*)"/is', $message, $matches);
if (array_key_exists(3, $matches)) {
$sentence = 'Internal Database reference error as been discovered. '.
'The object id: "%s" has a reference to document: "%s" with id: "%s" that could not be found.';
$message = sprintf($sentence, $matches[1], $matches[2], $matches[3]);
}
return [
'code' => $exception->getCode(),
'message' => $message
];
}
} | [
"private",
"function",
"decorateKnownCases",
"(",
"$",
"exception",
")",
"{",
"if",
"(",
"$",
"exception",
"instanceof",
"\\",
"ErrorException",
"&&",
"strpos",
"(",
"$",
"exception",
"->",
"getMessage",
"(",
")",
",",
"'Undefined index: $id'",
")",
"!==",
"fa... | Here we can pick up known cases that can happen and render a more detailed error message for the client.
It may be cumbersome, but it's good to detail error messages then just to let general error messages
generate support issues and work for us.
@param \Exception $exception exception
@return array|null either a error message array or null if the general should be displayed | [
"Here",
"we",
"can",
"pick",
"up",
"known",
"cases",
"that",
"can",
"happen",
"and",
"render",
"a",
"more",
"detailed",
"error",
"message",
"for",
"the",
"client",
".",
"It",
"may",
"be",
"cumbersome",
"but",
"it",
"s",
"good",
"to",
"detail",
"error",
... | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/CoreBundle/Listener/JsonExceptionListener.php#L96-L126 | train |
libgraviton/graviton | src/Graviton/ProxyBundle/DependencyInjection/GravitonProxyExtension.php | GravitonProxyExtension.load | public function load(array $configs, ContainerBuilder $container)
{
parent::load($configs, $container);
$configs = $this->processConfiguration(new Configuration(), $configs);
$sources = $container->hasParameter('graviton.proxy.sources') ?
$container->getParameter('graviton.proxy.sources') : [];
$container->setParameter('graviton.proxy.sources', array_merge_recursive($configs['sources'], $sources));
} | php | public function load(array $configs, ContainerBuilder $container)
{
parent::load($configs, $container);
$configs = $this->processConfiguration(new Configuration(), $configs);
$sources = $container->hasParameter('graviton.proxy.sources') ?
$container->getParameter('graviton.proxy.sources') : [];
$container->setParameter('graviton.proxy.sources', array_merge_recursive($configs['sources'], $sources));
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"parent",
"::",
"load",
"(",
"$",
"configs",
",",
"$",
"container",
")",
";",
"$",
"configs",
"=",
"$",
"this",
"->",
"processConfiguration",
... | Loads current configuration.
@param array $configs Set of configuration options
@param ContainerBuilder $container Instance of the SF2 container
@return void | [
"Loads",
"current",
"configuration",
"."
] | 5eccfb2fba31dadf659f0f55edeb1ebca403563e | https://github.com/libgraviton/graviton/blob/5eccfb2fba31dadf659f0f55edeb1ebca403563e/src/Graviton/ProxyBundle/DependencyInjection/GravitonProxyExtension.php#L40-L50 | train |
iherwig/wcmf | src/wcmf/lib/presentation/format/impl/HierarchicalFormat.php | HierarchicalFormat.deserializeHierarchy | private function deserializeHierarchy($values) {
if ($this->isSerializedNode($values)) {
// the values represent a node
$result = $this->deserializeNode($values);
$node = $result['node'];
$values = $result['data'];
$values[$node->getOID()->__toString()] = $node;
}
else {
foreach ($values as $key => $value) {
if (is_array($value) || is_object($value)) {
// array/object value
$result = $this->deserializeHierarchy($value);
// flatten the array, if the deserialization result is only an array
// with size 1 and the key is an oid (e.g. if a node was deserialized)
if (is_array($result) && sizeof($result) == 1 && ObjectId::isValid(key($result))) {
unset($values[$key]);
$values[key($result)] = current($result);
}
else {
$values[$key] = $result;
}
}
else {
// string value
$values[$key] = $value;
}
}
}
return $values;
} | php | private function deserializeHierarchy($values) {
if ($this->isSerializedNode($values)) {
// the values represent a node
$result = $this->deserializeNode($values);
$node = $result['node'];
$values = $result['data'];
$values[$node->getOID()->__toString()] = $node;
}
else {
foreach ($values as $key => $value) {
if (is_array($value) || is_object($value)) {
// array/object value
$result = $this->deserializeHierarchy($value);
// flatten the array, if the deserialization result is only an array
// with size 1 and the key is an oid (e.g. if a node was deserialized)
if (is_array($result) && sizeof($result) == 1 && ObjectId::isValid(key($result))) {
unset($values[$key]);
$values[key($result)] = current($result);
}
else {
$values[$key] = $result;
}
}
else {
// string value
$values[$key] = $value;
}
}
}
return $values;
} | [
"private",
"function",
"deserializeHierarchy",
"(",
"$",
"values",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isSerializedNode",
"(",
"$",
"values",
")",
")",
"{",
"// the values represent a node",
"$",
"result",
"=",
"$",
"this",
"->",
"deserializeNode",
"(",
... | Deserialize the given values recursively
@param $values
@return Array | [
"Deserialize",
"the",
"given",
"values",
"recursively"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/format/impl/HierarchicalFormat.php#L48-L78 | train |
iherwig/wcmf | src/wcmf/lib/presentation/format/impl/HierarchicalFormat.php | HierarchicalFormat.serializeHierarchy | private function serializeHierarchy($values) {
if ($this->isDeserializedNode($values)) {
// the values represent a node
$values = $this->serializeNode($values);
}
else {
if (is_array($values) || ($values instanceof \Traversable)) {
foreach ($values as $key => $value) {
if ($value != null && !is_scalar($value)) {
// array/object value
$result = $this->serializeHierarchy($value);
if (ObjectId::isValid($key)) {
$values = $result;
}
else {
$values[$key] = $result;
}
}
else {
// string value
$values[$key] = $value;
}
}
}
}
return $values;
} | php | private function serializeHierarchy($values) {
if ($this->isDeserializedNode($values)) {
// the values represent a node
$values = $this->serializeNode($values);
}
else {
if (is_array($values) || ($values instanceof \Traversable)) {
foreach ($values as $key => $value) {
if ($value != null && !is_scalar($value)) {
// array/object value
$result = $this->serializeHierarchy($value);
if (ObjectId::isValid($key)) {
$values = $result;
}
else {
$values[$key] = $result;
}
}
else {
// string value
$values[$key] = $value;
}
}
}
}
return $values;
} | [
"private",
"function",
"serializeHierarchy",
"(",
"$",
"values",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isDeserializedNode",
"(",
"$",
"values",
")",
")",
"{",
"// the values represent a node",
"$",
"values",
"=",
"$",
"this",
"->",
"serializeNode",
"(",
"... | Serialize the given values recursively
@param $values
@return Array | [
"Serialize",
"the",
"given",
"values",
"recursively"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/format/impl/HierarchicalFormat.php#L85-L111 | train |
skie/plum_search | src/FormParameter/SelectParameter.php | SelectParameter.formInputConfig | public function formInputConfig()
{
$formConfig = parent::formInputConfig();
if (!array_key_exists('options', $formConfig)) {
$options = $this->config('options');
$finder = $this->config('finder');
if (!empty($options) && is_array($options)) {
$formConfig['options'] = $options;
} elseif ($this->_allowedEmptyOptions()) {
} elseif (!empty($finder)) {
$formConfig['options'] = $finder;
}
}
return $formConfig;
} | php | public function formInputConfig()
{
$formConfig = parent::formInputConfig();
if (!array_key_exists('options', $formConfig)) {
$options = $this->config('options');
$finder = $this->config('finder');
if (!empty($options) && is_array($options)) {
$formConfig['options'] = $options;
} elseif ($this->_allowedEmptyOptions()) {
} elseif (!empty($finder)) {
$formConfig['options'] = $finder;
}
}
return $formConfig;
} | [
"public",
"function",
"formInputConfig",
"(",
")",
"{",
"$",
"formConfig",
"=",
"parent",
"::",
"formInputConfig",
"(",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"'options'",
",",
"$",
"formConfig",
")",
")",
"{",
"$",
"options",
"=",
"$",
"this... | Returns input config
@return array | [
"Returns",
"input",
"config"
] | 24d981e240bff7c15731981d6f9b3056abdaf80e | https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/FormParameter/SelectParameter.php#L74-L90 | train |
skie/plum_search | src/FormParameter/SelectParameter.php | SelectParameter._allowedEmptyOptions | protected function _allowedEmptyOptions()
{
$options = $this->config('options');
$allowEmptyOptions = $this->config('allowEmptyOptions');
return is_array($options) && !empty($allowEmptyOptions);
} | php | protected function _allowedEmptyOptions()
{
$options = $this->config('options');
$allowEmptyOptions = $this->config('allowEmptyOptions');
return is_array($options) && !empty($allowEmptyOptions);
} | [
"protected",
"function",
"_allowedEmptyOptions",
"(",
")",
"{",
"$",
"options",
"=",
"$",
"this",
"->",
"config",
"(",
"'options'",
")",
";",
"$",
"allowEmptyOptions",
"=",
"$",
"this",
"->",
"config",
"(",
"'allowEmptyOptions'",
")",
";",
"return",
"is_arra... | Check if empty options allowed
@return bool | [
"Check",
"if",
"empty",
"options",
"allowed"
] | 24d981e240bff7c15731981d6f9b3056abdaf80e | https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/FormParameter/SelectParameter.php#L97-L103 | train |
iherwig/wcmf | src/wcmf/lib/util/I18nUtil.php | I18nUtil.getMessages | public static function getMessages($directory, $exclude, $pattern, $depth=0) {
if ($depth == 0) {
self::$baseDir = $directory;
}
if (substr($directory, -1) != '/') {
$directory .= '/';
}
if (is_dir($directory)) {
$d = dir($directory);
$d->rewind();
while(false !== ($file = $d->read())) {
if($file != '.' && $file != '..' && !in_array($file, $exclude)) {
if (is_dir($directory.$file)) {
self::getMessages($directory.$file, $exclude, $pattern, ++$depth);
}
elseif (preg_match($pattern, $file)) {
$messages = self::getMessagesFromFile($directory.$file);
if (sizeof($messages) > 0) {
$key = str_replace(self::$baseDir, '', $directory.$file);
self::$result[$key] = $messages;
}
}
}
}
$d->close();
}
else {
throw new IllegalArgumentException("The directory '".$directory."' does not exist.");
}
return self::$result;
} | php | public static function getMessages($directory, $exclude, $pattern, $depth=0) {
if ($depth == 0) {
self::$baseDir = $directory;
}
if (substr($directory, -1) != '/') {
$directory .= '/';
}
if (is_dir($directory)) {
$d = dir($directory);
$d->rewind();
while(false !== ($file = $d->read())) {
if($file != '.' && $file != '..' && !in_array($file, $exclude)) {
if (is_dir($directory.$file)) {
self::getMessages($directory.$file, $exclude, $pattern, ++$depth);
}
elseif (preg_match($pattern, $file)) {
$messages = self::getMessagesFromFile($directory.$file);
if (sizeof($messages) > 0) {
$key = str_replace(self::$baseDir, '', $directory.$file);
self::$result[$key] = $messages;
}
}
}
}
$d->close();
}
else {
throw new IllegalArgumentException("The directory '".$directory."' does not exist.");
}
return self::$result;
} | [
"public",
"static",
"function",
"getMessages",
"(",
"$",
"directory",
",",
"$",
"exclude",
",",
"$",
"pattern",
",",
"$",
"depth",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"depth",
"==",
"0",
")",
"{",
"self",
"::",
"$",
"baseDir",
"=",
"$",
"directory"... | Get all messages from a directory recursively.
@param $directory The directory to search in
@param $exclude Array of directory names that are excluded from search
@param $pattern The pattern the names of the files to search in must match
@param $depth Internal use only
@return An assoziative array with the filenames as keys and the values as
array of strings.
@see I18nUtil::getMessagesFromFile | [
"Get",
"all",
"messages",
"from",
"a",
"directory",
"recursively",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/I18nUtil.php#L37-L68 | train |
iherwig/wcmf | src/wcmf/lib/util/I18nUtil.php | I18nUtil.createPHPLanguageFile | public static function createPHPLanguageFile($language, $messages) {
$fileUtil = new FileUtil();
// get locale directory
$config = ObjectFactory::getInstance('configuration');
$localeDir = $config->getDirectoryValue('localeDir', 'application');
$fileUtil->mkdirRec($localeDir);
$file = $localeDir.'messages_'.$language.'.php';
// backup old file
if (file_exists($file)) {
rename($file, $file.".bak");
}
$fh = fopen($file, "w");
// write header
$header = <<<EOT
<?php
\$messages_{$language} = [];
\$messages_{$language}[''] = '';
EOT;
fwrite($fh, $header."\n");
// write messages
foreach($messages as $message => $attributes) {
$lines = '// file(s): '.$attributes['files']."\n";
$lines .= "\$messages_".$language."['".str_replace("'", "\'", $message)."'] = '".str_replace("'", "\'", $attributes['translation'])."';"."\n";
fwrite($fh, $lines);
}
// write footer
$footer = <<<EOT
?>
EOT;
fwrite($fh, $footer."\n");
fclose($fh);
} | php | public static function createPHPLanguageFile($language, $messages) {
$fileUtil = new FileUtil();
// get locale directory
$config = ObjectFactory::getInstance('configuration');
$localeDir = $config->getDirectoryValue('localeDir', 'application');
$fileUtil->mkdirRec($localeDir);
$file = $localeDir.'messages_'.$language.'.php';
// backup old file
if (file_exists($file)) {
rename($file, $file.".bak");
}
$fh = fopen($file, "w");
// write header
$header = <<<EOT
<?php
\$messages_{$language} = [];
\$messages_{$language}[''] = '';
EOT;
fwrite($fh, $header."\n");
// write messages
foreach($messages as $message => $attributes) {
$lines = '// file(s): '.$attributes['files']."\n";
$lines .= "\$messages_".$language."['".str_replace("'", "\'", $message)."'] = '".str_replace("'", "\'", $attributes['translation'])."';"."\n";
fwrite($fh, $lines);
}
// write footer
$footer = <<<EOT
?>
EOT;
fwrite($fh, $footer."\n");
fclose($fh);
} | [
"public",
"static",
"function",
"createPHPLanguageFile",
"(",
"$",
"language",
",",
"$",
"messages",
")",
"{",
"$",
"fileUtil",
"=",
"new",
"FileUtil",
"(",
")",
";",
"// get locale directory",
"$",
"config",
"=",
"ObjectFactory",
"::",
"getInstance",
"(",
"'c... | Create a message file for use with the Message class. The file will
be created in the directory defined in configutation key 'localeDir' in
'application' section.
@param $language The language of the file (language code e.g. 'de')
@param $messages An assoziative array with the messages as keys
and assoziative array with keys 'translation' and 'files' (occurences of the message)
@return Boolean whether successful or not. | [
"Create",
"a",
"message",
"file",
"for",
"use",
"with",
"the",
"Message",
"class",
".",
"The",
"file",
"will",
"be",
"created",
"in",
"the",
"directory",
"defined",
"in",
"configutation",
"key",
"localeDir",
"in",
"application",
"section",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/I18nUtil.php#L118-L155 | train |
vufind-org/vufindharvest | src/ResponseProcessor/SimpleXmlResponseProcessor.php | SimpleXmlResponseProcessor.logBadXML | protected function logBadXML($xml)
{
$file = @fopen($this->badXmlLog, 'a');
if (!$file) {
throw new \Exception("Problem opening {$this->badXmlLog}.");
}
fputs($file, $xml . "\n\n");
fclose($file);
} | php | protected function logBadXML($xml)
{
$file = @fopen($this->badXmlLog, 'a');
if (!$file) {
throw new \Exception("Problem opening {$this->badXmlLog}.");
}
fputs($file, $xml . "\n\n");
fclose($file);
} | [
"protected",
"function",
"logBadXML",
"(",
"$",
"xml",
")",
"{",
"$",
"file",
"=",
"@",
"fopen",
"(",
"$",
"this",
"->",
"badXmlLog",
",",
"'a'",
")",
";",
"if",
"(",
"!",
"$",
"file",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Problem op... | Log a bad XML response.
@param string $xml Bad XML
@return void | [
"Log",
"a",
"bad",
"XML",
"response",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/ResponseProcessor/SimpleXmlResponseProcessor.php#L84-L92 | train |
vufind-org/vufindharvest | src/ResponseProcessor/SimpleXmlResponseProcessor.php | SimpleXmlResponseProcessor.sanitizeXml | protected function sanitizeXml($xml)
{
// Sanitize the XML if requested:
$newXML = trim(preg_replace($this->sanitizeRegex, ' ', $xml, -1, $count));
if ($count > 0 && $this->badXmlLog) {
$this->logBadXML($xml);
}
return $newXML;
} | php | protected function sanitizeXml($xml)
{
// Sanitize the XML if requested:
$newXML = trim(preg_replace($this->sanitizeRegex, ' ', $xml, -1, $count));
if ($count > 0 && $this->badXmlLog) {
$this->logBadXML($xml);
}
return $newXML;
} | [
"protected",
"function",
"sanitizeXml",
"(",
"$",
"xml",
")",
"{",
"// Sanitize the XML if requested:",
"$",
"newXML",
"=",
"trim",
"(",
"preg_replace",
"(",
"$",
"this",
"->",
"sanitizeRegex",
",",
"' '",
",",
"$",
"xml",
",",
"-",
"1",
",",
"$",
"count",... | Sanitize XML.
@param string $xml XML to sanitize
@return string | [
"Sanitize",
"XML",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/ResponseProcessor/SimpleXmlResponseProcessor.php#L101-L111 | train |
vufind-org/vufindharvest | src/ResponseProcessor/SimpleXmlResponseProcessor.php | SimpleXmlResponseProcessor.collectXmlErrors | protected function collectXmlErrors()
{
$callback = function ($e) {
return trim($e->message);
};
return implode('; ', array_map($callback, libxml_get_errors()));
} | php | protected function collectXmlErrors()
{
$callback = function ($e) {
return trim($e->message);
};
return implode('; ', array_map($callback, libxml_get_errors()));
} | [
"protected",
"function",
"collectXmlErrors",
"(",
")",
"{",
"$",
"callback",
"=",
"function",
"(",
"$",
"e",
")",
"{",
"return",
"trim",
"(",
"$",
"e",
"->",
"message",
")",
";",
"}",
";",
"return",
"implode",
"(",
"'; '",
",",
"array_map",
"(",
"$",... | Collect LibXML errors into a single string.
@return string | [
"Collect",
"LibXML",
"errors",
"into",
"a",
"single",
"string",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/ResponseProcessor/SimpleXmlResponseProcessor.php#L118-L124 | train |
vufind-org/vufindharvest | src/ResponseProcessor/SimpleXmlResponseProcessor.php | SimpleXmlResponseProcessor.process | public function process($xml)
{
// Sanitize if necessary:
if ($this->sanitize) {
$xml = $this->sanitizeXml($xml);
}
// Parse the XML (newer versions of LibXML require a special flag for
// large documents, and responses may be quite large):
$flags = LIBXML_VERSION >= 20900 ? LIBXML_PARSEHUGE : 0;
$oldSetting = libxml_use_internal_errors(true);
$result = simplexml_load_string($xml, null, $flags);
$errors = $this->collectXmlErrors();
libxml_use_internal_errors($oldSetting);
if (!$result) {
throw new \Exception('Problem loading XML: ' . $errors);
}
// If we got this far, we have a valid response:
return $result;
} | php | public function process($xml)
{
// Sanitize if necessary:
if ($this->sanitize) {
$xml = $this->sanitizeXml($xml);
}
// Parse the XML (newer versions of LibXML require a special flag for
// large documents, and responses may be quite large):
$flags = LIBXML_VERSION >= 20900 ? LIBXML_PARSEHUGE : 0;
$oldSetting = libxml_use_internal_errors(true);
$result = simplexml_load_string($xml, null, $flags);
$errors = $this->collectXmlErrors();
libxml_use_internal_errors($oldSetting);
if (!$result) {
throw new \Exception('Problem loading XML: ' . $errors);
}
// If we got this far, we have a valid response:
return $result;
} | [
"public",
"function",
"process",
"(",
"$",
"xml",
")",
"{",
"// Sanitize if necessary:",
"if",
"(",
"$",
"this",
"->",
"sanitize",
")",
"{",
"$",
"xml",
"=",
"$",
"this",
"->",
"sanitizeXml",
"(",
"$",
"xml",
")",
";",
"}",
"// Parse the XML (newer version... | Process an OAI-PMH response into a SimpleXML object. Throw an exception if
an error is detected.
@param string $xml Raw XML to process
@return mixed
@throws \Exception | [
"Process",
"an",
"OAI",
"-",
"PMH",
"response",
"into",
"a",
"SimpleXML",
"object",
".",
"Throw",
"an",
"exception",
"if",
"an",
"error",
"is",
"detected",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/ResponseProcessor/SimpleXmlResponseProcessor.php#L136-L156 | train |
iherwig/wcmf | src/wcmf/lib/model/PersistentIterator.php | PersistentIterator.save | public function save() {
$state = ['end' => $this->end, 'oidList' => $this->oidList, 'processedOidList' => $this->processedOidList,
'currentOID' => $this->currentOid, 'currentDepth' => $this->currentDepth, 'aggregationKinds' => $this->aggregationKinds];
$this->session->set($this->id, $state);
} | php | public function save() {
$state = ['end' => $this->end, 'oidList' => $this->oidList, 'processedOidList' => $this->processedOidList,
'currentOID' => $this->currentOid, 'currentDepth' => $this->currentDepth, 'aggregationKinds' => $this->aggregationKinds];
$this->session->set($this->id, $state);
} | [
"public",
"function",
"save",
"(",
")",
"{",
"$",
"state",
"=",
"[",
"'end'",
"=>",
"$",
"this",
"->",
"end",
",",
"'oidList'",
"=>",
"$",
"this",
"->",
"oidList",
",",
"'processedOidList'",
"=>",
"$",
"this",
"->",
"processedOidList",
",",
"'currentOID'... | Save the iterator state to the session | [
"Save",
"the",
"iterator",
"state",
"to",
"the",
"session"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/PersistentIterator.php#L68-L72 | train |
iherwig/wcmf | src/wcmf/lib/model/PersistentIterator.php | PersistentIterator.load | public static function load($id, $persistenceFacade, $session) {
// get state from session
$state = $session->get($id);
if ($state == null) {
return null;
}
// create instance
$instance = new PersistentIterator($id, $persistenceFacade, $session,
$state['currentOID']);
$instance->end = $state['end'];
$instance->oidList = $state['oidList'];
$instance->processedOidList = $state['processedOidList'];
$instance->currentDepth = $state['currentDepth'];
$instance->aggregationKinds = $state['aggregationKinds'];
return $instance;
} | php | public static function load($id, $persistenceFacade, $session) {
// get state from session
$state = $session->get($id);
if ($state == null) {
return null;
}
// create instance
$instance = new PersistentIterator($id, $persistenceFacade, $session,
$state['currentOID']);
$instance->end = $state['end'];
$instance->oidList = $state['oidList'];
$instance->processedOidList = $state['processedOidList'];
$instance->currentDepth = $state['currentDepth'];
$instance->aggregationKinds = $state['aggregationKinds'];
return $instance;
} | [
"public",
"static",
"function",
"load",
"(",
"$",
"id",
",",
"$",
"persistenceFacade",
",",
"$",
"session",
")",
"{",
"// get state from session",
"$",
"state",
"=",
"$",
"session",
"->",
"get",
"(",
"$",
"id",
")",
";",
"if",
"(",
"$",
"state",
"==",
... | Load an iterator state from the session
@param $id The unique iterator id used to store iterator's the state in the session
@param $persistenceFacade
@param $session
@return PersistentIterator instance holding the saved state or null if unique id is not found | [
"Load",
"an",
"iterator",
"state",
"from",
"the",
"session"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/PersistentIterator.php#L90-L105 | train |
iherwig/wcmf | src/wcmf/lib/model/PersistentIterator.php | PersistentIterator.addToQueue | protected function addToQueue($oidList, $depth) {
for ($i=sizeOf($oidList)-1; $i>=0; $i--) {
$this->oidList[] = [$oidList[$i], $depth];
}
} | php | protected function addToQueue($oidList, $depth) {
for ($i=sizeOf($oidList)-1; $i>=0; $i--) {
$this->oidList[] = [$oidList[$i], $depth];
}
} | [
"protected",
"function",
"addToQueue",
"(",
"$",
"oidList",
",",
"$",
"depth",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"sizeOf",
"(",
"$",
"oidList",
")",
"-",
"1",
";",
"$",
"i",
">=",
"0",
";",
"$",
"i",
"--",
")",
"{",
"$",
"this",
"->",
"oid... | Add object ids to the processing queue.
@param $oidList An array of object ids.
@param $depth The depth of the object ids in the tree. | [
"Add",
"object",
"ids",
"to",
"the",
"processing",
"queue",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/PersistentIterator.php#L196-L200 | train |
GW2Treasures/gw2api | src/V2/Bulk/BulkEndpoint.php | BulkEndpoint.many | public function many( array $ids = [] ) {
if( count( $ids ) === 0 ) {
return [];
}
$pages = array_chunk( $ids, $this->maxPageSize() );
$requests = [];
foreach( $pages as $page ) {
$requests[] = [ 'ids' => implode( ',', $page ) ];
}
$responses = $this->requestMany( $requests );
$result = [];
foreach( $responses as $response ) {
$result = array_merge( $result, $response->json() );
}
return $result;
} | php | public function many( array $ids = [] ) {
if( count( $ids ) === 0 ) {
return [];
}
$pages = array_chunk( $ids, $this->maxPageSize() );
$requests = [];
foreach( $pages as $page ) {
$requests[] = [ 'ids' => implode( ',', $page ) ];
}
$responses = $this->requestMany( $requests );
$result = [];
foreach( $responses as $response ) {
$result = array_merge( $result, $response->json() );
}
return $result;
} | [
"public",
"function",
"many",
"(",
"array",
"$",
"ids",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"ids",
")",
"===",
"0",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"pages",
"=",
"array_chunk",
"(",
"$",
"ids",
",",
"$",
"this"... | Multiple entries by ids.
@param string[]|int[] $ids
@return array | [
"Multiple",
"entries",
"by",
"ids",
"."
] | c8795af0c1d0a434b9e530f779d5a95786db2176 | https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Bulk/BulkEndpoint.php#L48-L68 | train |
vufind-org/vufindharvest | src/OaiPmh/Harvester.php | Harvester.launch | public function launch()
{
// Normalize sets setting to an array:
$sets = (array)$this->set;
if (empty($sets)) {
$sets = [null];
}
// Load last state, if applicable (used to recover from server failure).
if ($state = $this->stateManager->loadState()) {
$this->write("Found saved state; attempting to resume.\n");
list($resumeSet, $resumeToken, $this->startDate) = $state;
}
// Loop through all of the selected sets:
foreach ($sets as $set) {
// If we're resuming and there are multiple sets, find the right one.
if (isset($resumeToken) && $resumeSet != $set) {
continue;
}
// If we have a token to resume from, pick up there now...
if (isset($resumeToken)) {
$token = $resumeToken;
unset($resumeToken);
} else {
// ...otherwise, start harvesting at the requested date:
$token = $this->getRecordsByDate(
$this->startDate, $set, $this->harvestEndDate
);
}
// Keep harvesting as long as a resumption token is provided:
while ($token !== false) {
// Save current state in case we need to resume later:
$this->stateManager->saveState($set, $token, $this->startDate);
$token = $this->getRecordsByToken($token);
}
}
// If we made it this far, all was successful, so we should clean up
// the stored state.
$this->stateManager->clearState();
} | php | public function launch()
{
// Normalize sets setting to an array:
$sets = (array)$this->set;
if (empty($sets)) {
$sets = [null];
}
// Load last state, if applicable (used to recover from server failure).
if ($state = $this->stateManager->loadState()) {
$this->write("Found saved state; attempting to resume.\n");
list($resumeSet, $resumeToken, $this->startDate) = $state;
}
// Loop through all of the selected sets:
foreach ($sets as $set) {
// If we're resuming and there are multiple sets, find the right one.
if (isset($resumeToken) && $resumeSet != $set) {
continue;
}
// If we have a token to resume from, pick up there now...
if (isset($resumeToken)) {
$token = $resumeToken;
unset($resumeToken);
} else {
// ...otherwise, start harvesting at the requested date:
$token = $this->getRecordsByDate(
$this->startDate, $set, $this->harvestEndDate
);
}
// Keep harvesting as long as a resumption token is provided:
while ($token !== false) {
// Save current state in case we need to resume later:
$this->stateManager->saveState($set, $token, $this->startDate);
$token = $this->getRecordsByToken($token);
}
}
// If we made it this far, all was successful, so we should clean up
// the stored state.
$this->stateManager->clearState();
} | [
"public",
"function",
"launch",
"(",
")",
"{",
"// Normalize sets setting to an array:",
"$",
"sets",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"set",
";",
"if",
"(",
"empty",
"(",
"$",
"sets",
")",
")",
"{",
"$",
"sets",
"=",
"[",
"null",
"]",
";",... | Harvest all available documents.
@return void | [
"Harvest",
"all",
"available",
"documents",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Harvester.php#L159-L202 | train |
vufind-org/vufindharvest | src/OaiPmh/Harvester.php | Harvester.loadGranularity | protected function loadGranularity()
{
$this->write("Autodetecting date granularity... ");
$response = $this->sendRequest('Identify');
$this->granularity = (string)$response->Identify->granularity;
$this->writeLine("found {$this->granularity}.");
} | php | protected function loadGranularity()
{
$this->write("Autodetecting date granularity... ");
$response = $this->sendRequest('Identify');
$this->granularity = (string)$response->Identify->granularity;
$this->writeLine("found {$this->granularity}.");
} | [
"protected",
"function",
"loadGranularity",
"(",
")",
"{",
"$",
"this",
"->",
"write",
"(",
"\"Autodetecting date granularity... \"",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"sendRequest",
"(",
"'Identify'",
")",
";",
"$",
"this",
"->",
"granularity... | Load date granularity from the server.
@return void | [
"Load",
"date",
"granularity",
"from",
"the",
"server",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Harvester.php#L225-L231 | train |
vufind-org/vufindharvest | src/OaiPmh/Harvester.php | Harvester.checkResponseForErrors | protected function checkResponseForErrors($result)
{
// Detect errors and die if one is found:
if ($result->error) {
$attribs = $result->error->attributes();
// If this is a bad resumption token error and we're trying to
// restore a prior state, we should clean up.
if ($attribs['code'] == 'badResumptionToken'
&& $this->stateManager->loadState()
) {
$this->stateManager->clearState();
throw new \Exception(
"Token expired; removing last_state.txt. Please restart harvest."
);
}
throw new \Exception(
"OAI-PMH error -- code: {$attribs['code']}, " .
"value: {$result->error}"
);
}
} | php | protected function checkResponseForErrors($result)
{
// Detect errors and die if one is found:
if ($result->error) {
$attribs = $result->error->attributes();
// If this is a bad resumption token error and we're trying to
// restore a prior state, we should clean up.
if ($attribs['code'] == 'badResumptionToken'
&& $this->stateManager->loadState()
) {
$this->stateManager->clearState();
throw new \Exception(
"Token expired; removing last_state.txt. Please restart harvest."
);
}
throw new \Exception(
"OAI-PMH error -- code: {$attribs['code']}, " .
"value: {$result->error}"
);
}
} | [
"protected",
"function",
"checkResponseForErrors",
"(",
"$",
"result",
")",
"{",
"// Detect errors and die if one is found:",
"if",
"(",
"$",
"result",
"->",
"error",
")",
"{",
"$",
"attribs",
"=",
"$",
"result",
"->",
"error",
"->",
"attributes",
"(",
")",
";... | Check an OAI-PMH response for errors that need to be handled.
@param object $result OAI-PMH response (SimpleXML object)
@return void
@throws \Exception | [
"Check",
"an",
"OAI",
"-",
"PMH",
"response",
"for",
"errors",
"that",
"need",
"to",
"be",
"handled",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Harvester.php#L242-L263 | train |
vufind-org/vufindharvest | src/OaiPmh/Harvester.php | Harvester.getRecords | protected function getRecords($params)
{
// Make the OAI-PMH request:
$response = $this->sendRequest('ListRecords', $params);
// Save the records from the response:
if ($response->ListRecords->record) {
$this->writeLine(
'Processing ' . count($response->ListRecords->record) . " records..."
);
$endDate = $this->writer->write($response->ListRecords->record);
}
// If we have a resumption token, keep going; otherwise, we're done -- save
// the end date.
if (isset($response->ListRecords->resumptionToken)
&& !empty($response->ListRecords->resumptionToken)
) {
return $response->ListRecords->resumptionToken;
} elseif (isset($endDate) && $endDate > 0) {
$dateFormat = ($this->granularity == 'YYYY-MM-DD') ?
'Y-m-d' : 'Y-m-d\TH:i:s\Z';
$this->stateManager->saveDate(date($dateFormat, $endDate));
}
return false;
} | php | protected function getRecords($params)
{
// Make the OAI-PMH request:
$response = $this->sendRequest('ListRecords', $params);
// Save the records from the response:
if ($response->ListRecords->record) {
$this->writeLine(
'Processing ' . count($response->ListRecords->record) . " records..."
);
$endDate = $this->writer->write($response->ListRecords->record);
}
// If we have a resumption token, keep going; otherwise, we're done -- save
// the end date.
if (isset($response->ListRecords->resumptionToken)
&& !empty($response->ListRecords->resumptionToken)
) {
return $response->ListRecords->resumptionToken;
} elseif (isset($endDate) && $endDate > 0) {
$dateFormat = ($this->granularity == 'YYYY-MM-DD') ?
'Y-m-d' : 'Y-m-d\TH:i:s\Z';
$this->stateManager->saveDate(date($dateFormat, $endDate));
}
return false;
} | [
"protected",
"function",
"getRecords",
"(",
"$",
"params",
")",
"{",
"// Make the OAI-PMH request:",
"$",
"response",
"=",
"$",
"this",
"->",
"sendRequest",
"(",
"'ListRecords'",
",",
"$",
"params",
")",
";",
"// Save the records from the response:",
"if",
"(",
"$... | Harvest records using OAI-PMH.
@param array $params GET parameters for ListRecords method.
@return mixed Resumption token if provided, false if finished | [
"Harvest",
"records",
"using",
"OAI",
"-",
"PMH",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Harvester.php#L272-L297 | train |
vufind-org/vufindharvest | src/OaiPmh/Harvester.php | Harvester.getRecordsByDate | protected function getRecordsByDate($from = null, $set = null, $until = null)
{
$params = ['metadataPrefix' => $this->metadataPrefix];
if (!empty($from)) {
$params['from'] = $from;
}
if (!empty($set)) {
$params['set'] = $set;
}
if (!empty($until)) {
$params['until'] = $until;
}
return $this->getRecords($params);
} | php | protected function getRecordsByDate($from = null, $set = null, $until = null)
{
$params = ['metadataPrefix' => $this->metadataPrefix];
if (!empty($from)) {
$params['from'] = $from;
}
if (!empty($set)) {
$params['set'] = $set;
}
if (!empty($until)) {
$params['until'] = $until;
}
return $this->getRecords($params);
} | [
"protected",
"function",
"getRecordsByDate",
"(",
"$",
"from",
"=",
"null",
",",
"$",
"set",
"=",
"null",
",",
"$",
"until",
"=",
"null",
")",
"{",
"$",
"params",
"=",
"[",
"'metadataPrefix'",
"=>",
"$",
"this",
"->",
"metadataPrefix",
"]",
";",
"if",
... | Harvest records via OAI-PMH using date and set.
@param string $from Harvest start date (null for no specific start).
@param string $set Set to harvest (null for all records).
@param string $until Harvest end date (null for no specific end).
@return mixed Resumption token if provided, false if finished | [
"Harvest",
"records",
"via",
"OAI",
"-",
"PMH",
"using",
"date",
"and",
"set",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Harvester.php#L308-L321 | train |
iherwig/wcmf | src/wcmf/application/controller/AdminController.php | AdminController.clearCaches | protected function clearCaches() {
$config = $this->getConfiguration();
foreach($config->getSections() as $section) {
$sectionValues = $config->getSection($section, true);
if (isset($sectionValues['__class'])) {
$instance = ObjectFactory::getInstance($section);
if ($instance instanceof Cache) {
$instance->clearAll();
}
elseif ($instance instanceof View) {
$instance->clearCache();
}
}
}
} | php | protected function clearCaches() {
$config = $this->getConfiguration();
foreach($config->getSections() as $section) {
$sectionValues = $config->getSection($section, true);
if (isset($sectionValues['__class'])) {
$instance = ObjectFactory::getInstance($section);
if ($instance instanceof Cache) {
$instance->clearAll();
}
elseif ($instance instanceof View) {
$instance->clearCache();
}
}
}
} | [
"protected",
"function",
"clearCaches",
"(",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfiguration",
"(",
")",
";",
"foreach",
"(",
"$",
"config",
"->",
"getSections",
"(",
")",
"as",
"$",
"section",
")",
"{",
"$",
"sectionValues",
"=",
"$... | Clear all cache instances found in the configuration | [
"Clear",
"all",
"cache",
"instances",
"found",
"in",
"the",
"configuration"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/AdminController.php#L56-L70 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.getProxyObject | protected function getProxyObject(ObjectId $umi, $buildDepth) {
self::$logger->debug("Get proxy object for: ".$umi);
// local objects don't have a proxy
if (strlen($umi->getPrefix()) == 0) {
return null;
}
// check if the proxy object was loaded already
$proxy = $this->getRegisteredProxyObject($umi, $buildDepth);
// search the proxy object if requested for the first time
if (!$proxy) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$isRemoteCapableFacade = ($persistenceFacade instanceof RemoteCapablePersistenceFacadeImpl);
$oldState = true;
if ($isRemoteCapableFacade) {
$oldState = $persistenceFacade->isResolvingProxies();
$persistenceFacade->setResolveProxies(false);
}
$proxy = $persistenceFacade->loadFirstObject($umi->getType(), $buildDepth, [$umi->getType().'.umi' => $umi->toString()]);
if ($isRemoteCapableFacade) {
$persistenceFacade->setResolveProxies($oldState);
}
if (!$proxy) {
// the proxy has to be created
self::$logger->debug("Creating...");
$proxy = $persistenceFacade->create($umi->getType(), BuildDepth::SINGLE);
$proxy->setValue('umi', $umi);
$proxy->save();
}
$this->registerProxyObject($umi, $proxy, $buildDepth);
}
self::$logger->debug("Proxy oid: ".$proxy->getOID());
return $proxy;
} | php | protected function getProxyObject(ObjectId $umi, $buildDepth) {
self::$logger->debug("Get proxy object for: ".$umi);
// local objects don't have a proxy
if (strlen($umi->getPrefix()) == 0) {
return null;
}
// check if the proxy object was loaded already
$proxy = $this->getRegisteredProxyObject($umi, $buildDepth);
// search the proxy object if requested for the first time
if (!$proxy) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$isRemoteCapableFacade = ($persistenceFacade instanceof RemoteCapablePersistenceFacadeImpl);
$oldState = true;
if ($isRemoteCapableFacade) {
$oldState = $persistenceFacade->isResolvingProxies();
$persistenceFacade->setResolveProxies(false);
}
$proxy = $persistenceFacade->loadFirstObject($umi->getType(), $buildDepth, [$umi->getType().'.umi' => $umi->toString()]);
if ($isRemoteCapableFacade) {
$persistenceFacade->setResolveProxies($oldState);
}
if (!$proxy) {
// the proxy has to be created
self::$logger->debug("Creating...");
$proxy = $persistenceFacade->create($umi->getType(), BuildDepth::SINGLE);
$proxy->setValue('umi', $umi);
$proxy->save();
}
$this->registerProxyObject($umi, $proxy, $buildDepth);
}
self::$logger->debug("Proxy oid: ".$proxy->getOID());
return $proxy;
} | [
"protected",
"function",
"getProxyObject",
"(",
"ObjectId",
"$",
"umi",
",",
"$",
"buildDepth",
")",
"{",
"self",
"::",
"$",
"logger",
"->",
"debug",
"(",
"\"Get proxy object for: \"",
".",
"$",
"umi",
")",
";",
"// local objects don't have a proxy",
"if",
"(",
... | Get the proxy object for a remote object.
This method makes sure that a proxy for the given remote object exists.
If it does not exist, it will be created.
@param $umi The universal model id (oid with server prefix)
@param $buildDepth buildDepth One of the BUILDDEPTH constants or a number describing the number of generations to build (except BuildDepth::REQUIRED)
@return The proxy object. | [
"Get",
"the",
"proxy",
"object",
"for",
"a",
"remote",
"object",
".",
"This",
"method",
"makes",
"sure",
"that",
"a",
"proxy",
"for",
"the",
"given",
"remote",
"object",
"exists",
".",
"If",
"it",
"does",
"not",
"exist",
"it",
"will",
"be",
"created",
... | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L172-L207 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.registerProxyObject | protected function registerProxyObject(ObjectID $umi, PersistentObject $obj, $buildDepth) {
$oid = $obj->getOID();
if (strlen($oid->getPrefix()) > 0) {
self::$logger->debug("NOT A PROXY");
return;
}
$this->registerObject($umi, $obj, $buildDepth, self::PROXY_OBJECTS_SESSION_VARNAME);
} | php | protected function registerProxyObject(ObjectID $umi, PersistentObject $obj, $buildDepth) {
$oid = $obj->getOID();
if (strlen($oid->getPrefix()) > 0) {
self::$logger->debug("NOT A PROXY");
return;
}
$this->registerObject($umi, $obj, $buildDepth, self::PROXY_OBJECTS_SESSION_VARNAME);
} | [
"protected",
"function",
"registerProxyObject",
"(",
"ObjectID",
"$",
"umi",
",",
"PersistentObject",
"$",
"obj",
",",
"$",
"buildDepth",
")",
"{",
"$",
"oid",
"=",
"$",
"obj",
"->",
"getOID",
"(",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"oid",
"->",
... | Save a proxy object in the session.
@param $umi The universal model id (oid with server prefix)
@param $obj The proxy object.
@param $buildDepth The depth the object was loaded. | [
"Save",
"a",
"proxy",
"object",
"in",
"the",
"session",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L297-L304 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.registerRemoteObject | protected function registerRemoteObject(ObjectId $umi, PersistentObject $obj, $buildDepth) {
// TODO: fix caching remote objects (invalidate cache entry, if an association to the object changes)
return;
$this->registerObject($umi, $obj, $buildDepth, self::REMOTE_OBJECTS_SESSION_VARNAME);
} | php | protected function registerRemoteObject(ObjectId $umi, PersistentObject $obj, $buildDepth) {
// TODO: fix caching remote objects (invalidate cache entry, if an association to the object changes)
return;
$this->registerObject($umi, $obj, $buildDepth, self::REMOTE_OBJECTS_SESSION_VARNAME);
} | [
"protected",
"function",
"registerRemoteObject",
"(",
"ObjectId",
"$",
"umi",
",",
"PersistentObject",
"$",
"obj",
",",
"$",
"buildDepth",
")",
"{",
"// TODO: fix caching remote objects (invalidate cache entry, if an association to the object changes)",
"return",
";",
"$",
"t... | Save a remote object in the session.
@param $umi The universal model id (oid with server prefix)
@param $obj The remote object.
@param $buildDepth The depth the object was loaded. | [
"Save",
"a",
"remote",
"object",
"in",
"the",
"session",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L312-L317 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.registerObject | protected function registerObject(ObjectId $umi, PersistentObject $obj, $buildDepth, $varName) {
if ($buildDepth == 0) {
$buildDepth=BuildDepth::SINGLE;
}
// save the object in the session
$umiStr = $umi->toString();
$objects = $this->session->get($varName);
if (!isset($objects[$umiStr])) {
$objects[$umiStr] = [];
}
$objects[$umiStr][$buildDepth] = $obj;
$this->session->set($varName, $objects);
} | php | protected function registerObject(ObjectId $umi, PersistentObject $obj, $buildDepth, $varName) {
if ($buildDepth == 0) {
$buildDepth=BuildDepth::SINGLE;
}
// save the object in the session
$umiStr = $umi->toString();
$objects = $this->session->get($varName);
if (!isset($objects[$umiStr])) {
$objects[$umiStr] = [];
}
$objects[$umiStr][$buildDepth] = $obj;
$this->session->set($varName, $objects);
} | [
"protected",
"function",
"registerObject",
"(",
"ObjectId",
"$",
"umi",
",",
"PersistentObject",
"$",
"obj",
",",
"$",
"buildDepth",
",",
"$",
"varName",
")",
"{",
"if",
"(",
"$",
"buildDepth",
"==",
"0",
")",
"{",
"$",
"buildDepth",
"=",
"BuildDepth",
"... | Save a object in the given session variable.
@param $umi The universal model id (oid with server prefix)
@param $obj The object to register.
@param $buildDepth The depth the object was loaded.
@param $varName The session variable name. | [
"Save",
"a",
"object",
"in",
"the",
"given",
"session",
"variable",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L326-L338 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.getRegisteredProxyObject | protected function getRegisteredProxyObject(ObjectId $umi, $buildDepth) {
$proxy = $this->getRegisteredObject($umi, $buildDepth, self::PROXY_OBJECTS_SESSION_VARNAME);
return $proxy;
} | php | protected function getRegisteredProxyObject(ObjectId $umi, $buildDepth) {
$proxy = $this->getRegisteredObject($umi, $buildDepth, self::PROXY_OBJECTS_SESSION_VARNAME);
return $proxy;
} | [
"protected",
"function",
"getRegisteredProxyObject",
"(",
"ObjectId",
"$",
"umi",
",",
"$",
"buildDepth",
")",
"{",
"$",
"proxy",
"=",
"$",
"this",
"->",
"getRegisteredObject",
"(",
"$",
"umi",
",",
"$",
"buildDepth",
",",
"self",
"::",
"PROXY_OBJECTS_SESSION_... | Get a proxy object from the session.
@param $umi The universal model id (oid with server prefix)
@param $buildDepth The requested build depth.
@return The proxy object or null if not found. | [
"Get",
"a",
"proxy",
"object",
"from",
"the",
"session",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L346-L349 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.getRegisteredRemoteObject | protected function getRegisteredRemoteObject(ObjectId $umi, $buildDepth) {
$object = $this->getRegisteredObject($umi, $buildDepth, self::REMOTE_OBJECTS_SESSION_VARNAME);
return $object;
} | php | protected function getRegisteredRemoteObject(ObjectId $umi, $buildDepth) {
$object = $this->getRegisteredObject($umi, $buildDepth, self::REMOTE_OBJECTS_SESSION_VARNAME);
return $object;
} | [
"protected",
"function",
"getRegisteredRemoteObject",
"(",
"ObjectId",
"$",
"umi",
",",
"$",
"buildDepth",
")",
"{",
"$",
"object",
"=",
"$",
"this",
"->",
"getRegisteredObject",
"(",
"$",
"umi",
",",
"$",
"buildDepth",
",",
"self",
"::",
"REMOTE_OBJECTS_SESSI... | Get a remote object from the session.
@param $umi The universal model id (oid with server prefix)
@param $buildDepth The requested build depth.
@return The remote object or null if not found. | [
"Get",
"a",
"remote",
"object",
"from",
"the",
"session",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L357-L360 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.getRegisteredObject | protected function getRegisteredObject(ObjectId $umi, $buildDepth, $varName) {
if ($buildDepth == 0) {
$buildDepth=BuildDepth::SINGLE;
}
$umiStr = $umi->toString();
$objects = $this->session->get($varName);
if (isset($objects[$umiStr]) && isset($objects[$umiStr][$buildDepth])) {
return $objects[$umiStr][$buildDepth];
}
// check if an object with larger build depth was stored already
if ($buildDepth == BuildDepth::SINGLE) {
$existingDepths = array_keys($objects[$umiStr]);
foreach($existingDepths as $depth) {
if ($depth > 0 || $depth == BuildDepth::INFINITE) {
return $objects[$umiStr][$depth];
}
}
}
return null;
} | php | protected function getRegisteredObject(ObjectId $umi, $buildDepth, $varName) {
if ($buildDepth == 0) {
$buildDepth=BuildDepth::SINGLE;
}
$umiStr = $umi->toString();
$objects = $this->session->get($varName);
if (isset($objects[$umiStr]) && isset($objects[$umiStr][$buildDepth])) {
return $objects[$umiStr][$buildDepth];
}
// check if an object with larger build depth was stored already
if ($buildDepth == BuildDepth::SINGLE) {
$existingDepths = array_keys($objects[$umiStr]);
foreach($existingDepths as $depth) {
if ($depth > 0 || $depth == BuildDepth::INFINITE) {
return $objects[$umiStr][$depth];
}
}
}
return null;
} | [
"protected",
"function",
"getRegisteredObject",
"(",
"ObjectId",
"$",
"umi",
",",
"$",
"buildDepth",
",",
"$",
"varName",
")",
"{",
"if",
"(",
"$",
"buildDepth",
"==",
"0",
")",
"{",
"$",
"buildDepth",
"=",
"BuildDepth",
"::",
"SINGLE",
";",
"}",
"$",
... | Get a object from the given session variable.
@param $umi The universal model id (oid with server prefix)
@param $buildDepth The requested build depth.
@param $varName The session variable name
@return The object or null if not found. | [
"Get",
"a",
"object",
"from",
"the",
"given",
"session",
"variable",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L369-L388 | train |
iherwig/wcmf | src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php | RemoteCapablePersistenceFacade.makeUmis | protected function makeUmis($oids, $umiPrefix) {
$result = [];
foreach ($oids as $oid) {
if (strlen($oid->getPrefix()) == 0) {
$umi = new ObjectId($oid->getType(), $oid->getId(), $umiPrefix);
$result[] = $umi;
}
}
return $result;
} | php | protected function makeUmis($oids, $umiPrefix) {
$result = [];
foreach ($oids as $oid) {
if (strlen($oid->getPrefix()) == 0) {
$umi = new ObjectId($oid->getType(), $oid->getId(), $umiPrefix);
$result[] = $umi;
}
}
return $result;
} | [
"protected",
"function",
"makeUmis",
"(",
"$",
"oids",
",",
"$",
"umiPrefix",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"oids",
"as",
"$",
"oid",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"oid",
"->",
"getPrefix",
"(",
")",... | Replace all object ids in an array with the umis according to
the given umiPrefix.
@param $oids The array of oids
@param $umiPrefix The umi prefix
@return The array of umis | [
"Replace",
"all",
"object",
"ids",
"in",
"an",
"array",
"with",
"the",
"umis",
"according",
"to",
"the",
"given",
"umiPrefix",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/RemoteCapablePersistenceFacade.php#L397-L406 | train |
iherwig/wcmf | src/wcmf/lib/presentation/impl/DefaultRequestListener.php | DefaultRequestListener.listen | public function listen(ApplicationEvent $event) {
if ($event->getStage() == ApplicationEvent::BEFORE_ROUTE_ACTION) {
$request = $event->getRequest();
if ($request != null) {
$this->transformRequest($request);
}
}
else if ($event->getStage() == ApplicationEvent::AFTER_EXECUTE_CONTROLLER) {
$request = $event->getRequest();
$response = $event->getResponse();
if ($request != null && $response != null) {
$this->transformResponse($request, $response);
}
}
} | php | public function listen(ApplicationEvent $event) {
if ($event->getStage() == ApplicationEvent::BEFORE_ROUTE_ACTION) {
$request = $event->getRequest();
if ($request != null) {
$this->transformRequest($request);
}
}
else if ($event->getStage() == ApplicationEvent::AFTER_EXECUTE_CONTROLLER) {
$request = $event->getRequest();
$response = $event->getResponse();
if ($request != null && $response != null) {
$this->transformResponse($request, $response);
}
}
} | [
"public",
"function",
"listen",
"(",
"ApplicationEvent",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"event",
"->",
"getStage",
"(",
")",
"==",
"ApplicationEvent",
"::",
"BEFORE_ROUTE_ACTION",
")",
"{",
"$",
"request",
"=",
"$",
"event",
"->",
"getRequest",
"(... | Listen to ApplicationEvent
@param $event ApplicationEvent instance | [
"Listen",
"to",
"ApplicationEvent"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/impl/DefaultRequestListener.php#L40-L54 | train |
skie/plum_search | src/FormParameter/BaseParameter.php | BaseParameter._process | protected function _process()
{
$name = $this->config('field');
$this->value = $this->_registry->data($name);
$this->_processed = true;
} | php | protected function _process()
{
$name = $this->config('field');
$this->value = $this->_registry->data($name);
$this->_processed = true;
} | [
"protected",
"function",
"_process",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"config",
"(",
"'field'",
")",
";",
"$",
"this",
"->",
"value",
"=",
"$",
"this",
"->",
"_registry",
"->",
"data",
"(",
"$",
"name",
")",
";",
"$",
"this",
"... | process param parsing
@return void | [
"process",
"param",
"parsing"
] | 24d981e240bff7c15731981d6f9b3056abdaf80e | https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/FormParameter/BaseParameter.php#L111-L116 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/InifileConfiguration.php | InifileConfiguration.processFile | protected function processFile($filename, $configArray=[], $parsedFiles=[]) {
// avoid circular includes
if (!in_array($filename, $parsedFiles)) {
$parsedFiles[] = $filename;
$content = $this->parseIniFile($filename);
// process includes
$includes = $this->getConfigIncludes($content);
if ($includes) {
$this->processValue($includes);
foreach ($includes as $include) {
$result = $this->processFile($this->configPath.$include, $configArray, $parsedFiles);
$configArray = $this->configMerge($configArray, $result['config'], true);
$parsedFiles = $result['files'];
}
}
// process self
$configArray = $this->configMerge($configArray, $content, true);
}
return ['config' => $configArray, 'files' => $parsedFiles];
} | php | protected function processFile($filename, $configArray=[], $parsedFiles=[]) {
// avoid circular includes
if (!in_array($filename, $parsedFiles)) {
$parsedFiles[] = $filename;
$content = $this->parseIniFile($filename);
// process includes
$includes = $this->getConfigIncludes($content);
if ($includes) {
$this->processValue($includes);
foreach ($includes as $include) {
$result = $this->processFile($this->configPath.$include, $configArray, $parsedFiles);
$configArray = $this->configMerge($configArray, $result['config'], true);
$parsedFiles = $result['files'];
}
}
// process self
$configArray = $this->configMerge($configArray, $content, true);
}
return ['config' => $configArray, 'files' => $parsedFiles];
} | [
"protected",
"function",
"processFile",
"(",
"$",
"filename",
",",
"$",
"configArray",
"=",
"[",
"]",
",",
"$",
"parsedFiles",
"=",
"[",
"]",
")",
"{",
"// avoid circular includes\r",
"if",
"(",
"!",
"in_array",
"(",
"$",
"filename",
",",
"$",
"parsedFiles... | Process the given file recursively
@param $filename The filename
@param $configArray Configuration array
@param $parsedFiles Parsed files
@return Associative array with keys 'config' (configuration array) and 'files'
(array of parsed files) | [
"Process",
"the",
"given",
"file",
"recursively"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/InifileConfiguration.php#L174-L196 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/InifileConfiguration.php | InifileConfiguration.serialize | protected function serialize() {
if (!$this->isModified() && ($cacheFile = $this->getSerializeFilename($this->addedFiles))) {
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Serialize configuration: ".join(',', $this->addedFiles)." to file: ".$cacheFile);
}
$this->fileUtil->mkdirRec(dirname($cacheFile));
if ($fh = @fopen($cacheFile, "w")) {
if (@fwrite($fh, serialize(array_filter(get_object_vars($this), function($value, $name) {
return $name != 'comments'; // don't store comments
}, ARRAY_FILTER_USE_BOTH)))) {
@fclose($fh);
}
}
}
} | php | protected function serialize() {
if (!$this->isModified() && ($cacheFile = $this->getSerializeFilename($this->addedFiles))) {
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Serialize configuration: ".join(',', $this->addedFiles)." to file: ".$cacheFile);
}
$this->fileUtil->mkdirRec(dirname($cacheFile));
if ($fh = @fopen($cacheFile, "w")) {
if (@fwrite($fh, serialize(array_filter(get_object_vars($this), function($value, $name) {
return $name != 'comments'; // don't store comments
}, ARRAY_FILTER_USE_BOTH)))) {
@fclose($fh);
}
}
}
} | [
"protected",
"function",
"serialize",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isModified",
"(",
")",
"&&",
"(",
"$",
"cacheFile",
"=",
"$",
"this",
"->",
"getSerializeFilename",
"(",
"$",
"this",
"->",
"addedFiles",
")",
")",
")",
"{",
"if... | Store the instance in the file system. If the instance is modified, this call is ignored. | [
"Store",
"the",
"instance",
"in",
"the",
"file",
"system",
".",
"If",
"the",
"instance",
"is",
"modified",
"this",
"call",
"is",
"ignored",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/InifileConfiguration.php#L666-L680 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/InifileConfiguration.php | InifileConfiguration.unserialize | protected function unserialize($parsedFiles) {
if (!$this->isModified() && ($cacheFile = $this->getSerializeFilename($parsedFiles)) && file_exists($cacheFile)) {
$parsedFiles[] = __FILE__;
if (!$this->checkFileDate($parsedFiles, $cacheFile)) {
$vars = unserialize(file_get_contents($cacheFile));
// check if included ini files were updated since last cache time
$includes = $vars['containedFiles'];
if (is_array($includes)) {
if ($this->checkFileDate($includes, $cacheFile)) {
return false;
}
}
// everything is up-to-date
foreach($vars as $key => $val) {
$this->$key = $val;
}
return true;
}
}
return false;
} | php | protected function unserialize($parsedFiles) {
if (!$this->isModified() && ($cacheFile = $this->getSerializeFilename($parsedFiles)) && file_exists($cacheFile)) {
$parsedFiles[] = __FILE__;
if (!$this->checkFileDate($parsedFiles, $cacheFile)) {
$vars = unserialize(file_get_contents($cacheFile));
// check if included ini files were updated since last cache time
$includes = $vars['containedFiles'];
if (is_array($includes)) {
if ($this->checkFileDate($includes, $cacheFile)) {
return false;
}
}
// everything is up-to-date
foreach($vars as $key => $val) {
$this->$key = $val;
}
return true;
}
}
return false;
} | [
"protected",
"function",
"unserialize",
"(",
"$",
"parsedFiles",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isModified",
"(",
")",
"&&",
"(",
"$",
"cacheFile",
"=",
"$",
"this",
"->",
"getSerializeFilename",
"(",
"$",
"parsedFiles",
")",
")",
"&&",
... | Retrieve parsed ini data from the file system and update the current instance.
If the current instance is modified or any file given in parsedFiles
is newer than the serialized data, this call is ignored.
If InifileConfiguration class changed, the call will be ignored as well.
@param $parsedFiles An array of ini filenames that must be contained in the data.
@return Boolean whether the data could be retrieved or not | [
"Retrieve",
"parsed",
"ini",
"data",
"from",
"the",
"file",
"system",
"and",
"update",
"the",
"current",
"instance",
".",
"If",
"the",
"current",
"instance",
"is",
"modified",
"or",
"any",
"file",
"given",
"in",
"parsedFiles",
"is",
"newer",
"than",
"the",
... | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/InifileConfiguration.php#L690-L712 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/InifileConfiguration.php | InifileConfiguration.checkFileDate | protected function checkFileDate($fileList, $referenceFile) {
foreach ($fileList as $file) {
if (@filemtime($file) > @filemtime($referenceFile)) {
return true;
}
}
return false;
} | php | protected function checkFileDate($fileList, $referenceFile) {
foreach ($fileList as $file) {
if (@filemtime($file) > @filemtime($referenceFile)) {
return true;
}
}
return false;
} | [
"protected",
"function",
"checkFileDate",
"(",
"$",
"fileList",
",",
"$",
"referenceFile",
")",
"{",
"foreach",
"(",
"$",
"fileList",
"as",
"$",
"file",
")",
"{",
"if",
"(",
"@",
"filemtime",
"(",
"$",
"file",
")",
">",
"@",
"filemtime",
"(",
"$",
"r... | Check if one file in fileList is newer than the referenceFile.
@param $fileList An array of files
@param $referenceFile The file to check against
@return True, if one of the files is newer, false else | [
"Check",
"if",
"one",
"file",
"in",
"fileList",
"is",
"newer",
"than",
"the",
"referenceFile",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/InifileConfiguration.php#L735-L742 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/InifileConfiguration.php | InifileConfiguration.configChanged | protected function configChanged() {
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Configuration is changed");
}
if (ObjectFactory::isConfigured()) {
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Emitting change event");
}
ObjectFactory::getInstance('eventManager')->dispatch(ConfigChangeEvent::NAME,
new ConfigChangeEvent());
}
} | php | protected function configChanged() {
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Configuration is changed");
}
if (ObjectFactory::isConfigured()) {
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Emitting change event");
}
ObjectFactory::getInstance('eventManager')->dispatch(ConfigChangeEvent::NAME,
new ConfigChangeEvent());
}
} | [
"protected",
"function",
"configChanged",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"logger",
"->",
"isDebugEnabled",
"(",
")",
")",
"{",
"self",
"::",
"$",
"logger",
"->",
"debug",
"(",
"\"Configuration is changed\"",
")",
";",
"}",
"if",
"(",
"Objec... | Notify configuration change listeners | [
"Notify",
"configuration",
"change",
"listeners"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/InifileConfiguration.php#L747-L758 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/InifileConfiguration.php | InifileConfiguration.buildLookupTable | protected function buildLookupTable() {
$this->lookupTable = [];
foreach ($this->configArray as $section => $entry) {
// create section entry
$lookupSectionKey = strtolower($section.':');
$this->lookupTable[$lookupSectionKey] = [$section];
// create key entries
foreach ($entry as $key => $value) {
$lookupKey = strtolower($lookupSectionKey.$key);
$this->lookupTable[$lookupKey] = [$section, $key];
}
}
} | php | protected function buildLookupTable() {
$this->lookupTable = [];
foreach ($this->configArray as $section => $entry) {
// create section entry
$lookupSectionKey = strtolower($section.':');
$this->lookupTable[$lookupSectionKey] = [$section];
// create key entries
foreach ($entry as $key => $value) {
$lookupKey = strtolower($lookupSectionKey.$key);
$this->lookupTable[$lookupKey] = [$section, $key];
}
}
} | [
"protected",
"function",
"buildLookupTable",
"(",
")",
"{",
"$",
"this",
"->",
"lookupTable",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"configArray",
"as",
"$",
"section",
"=>",
"$",
"entry",
")",
"{",
"// create section entry\r",
"$",
"looku... | Build the internal lookup table | [
"Build",
"the",
"internal",
"lookup",
"table"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/InifileConfiguration.php#L763-L775 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/InifileConfiguration.php | InifileConfiguration.lookup | protected function lookup($section, $key=null) {
$lookupKey = strtolower($section).':'.strtolower($key);
if (isset($this->lookupTable[$lookupKey])) {
return $this->lookupTable[$lookupKey];
}
return null;
} | php | protected function lookup($section, $key=null) {
$lookupKey = strtolower($section).':'.strtolower($key);
if (isset($this->lookupTable[$lookupKey])) {
return $this->lookupTable[$lookupKey];
}
return null;
} | [
"protected",
"function",
"lookup",
"(",
"$",
"section",
",",
"$",
"key",
"=",
"null",
")",
"{",
"$",
"lookupKey",
"=",
"strtolower",
"(",
"$",
"section",
")",
".",
"':'",
".",
"strtolower",
"(",
"$",
"key",
")",
";",
"if",
"(",
"isset",
"(",
"$",
... | Lookup section and key.
@param $section The section to lookup
@param $key The key to lookup (optional)
@return Array with section as first entry and key as second or null if not found | [
"Lookup",
"section",
"and",
"key",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/InifileConfiguration.php#L783-L789 | train |
vufind-org/vufindharvest | src/OaiPmh/StateManager.php | StateManager.loadDate | public function loadDate()
{
return (file_exists($this->lastHarvestFile))
? trim(current(file($this->lastHarvestFile))) : null;
} | php | public function loadDate()
{
return (file_exists($this->lastHarvestFile))
? trim(current(file($this->lastHarvestFile))) : null;
} | [
"public",
"function",
"loadDate",
"(",
")",
"{",
"return",
"(",
"file_exists",
"(",
"$",
"this",
"->",
"lastHarvestFile",
")",
")",
"?",
"trim",
"(",
"current",
"(",
"file",
"(",
"$",
"this",
"->",
"lastHarvestFile",
")",
")",
")",
":",
"null",
";",
... | Retrieve the date from the "last harvested" file and use it as our start
date if it is available.
@return string | [
"Retrieve",
"the",
"date",
"from",
"the",
"last",
"harvested",
"file",
"and",
"use",
"it",
"as",
"our",
"start",
"date",
"if",
"it",
"is",
"available",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/StateManager.php#L94-L98 | train |
iherwig/wcmf | src/wcmf/lib/model/impl/AbstractNodeSerializer.php | AbstractNodeSerializer.getNodeTemplate | protected function getNodeTemplate($oid) {
// load object if existing to get the original data
$originalNode = $this->persistenceFacade->load($oid, BuildDepth::SINGLE);
// create the request node and copy the orignal data
$class = get_class($this->persistenceFacade->create($oid->getType(), BuildDepth::SINGLE));
$node = new $class;
if ($originalNode) {
$originalNode->copyValues($node);
}
return $node;
} | php | protected function getNodeTemplate($oid) {
// load object if existing to get the original data
$originalNode = $this->persistenceFacade->load($oid, BuildDepth::SINGLE);
// create the request node and copy the orignal data
$class = get_class($this->persistenceFacade->create($oid->getType(), BuildDepth::SINGLE));
$node = new $class;
if ($originalNode) {
$originalNode->copyValues($node);
}
return $node;
} | [
"protected",
"function",
"getNodeTemplate",
"(",
"$",
"oid",
")",
"{",
"// load object if existing to get the original data",
"$",
"originalNode",
"=",
"$",
"this",
"->",
"persistenceFacade",
"->",
"load",
"(",
"$",
"oid",
",",
"BuildDepth",
"::",
"SINGLE",
")",
"... | Get a Node instance based on the original values to merge the deserialized values into
@param $oid The object id of the Node
@return Node | [
"Get",
"a",
"Node",
"instance",
"based",
"on",
"the",
"original",
"values",
"to",
"merge",
"the",
"deserialized",
"values",
"into"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/impl/AbstractNodeSerializer.php#L40-L51 | train |
iherwig/wcmf | src/wcmf/lib/model/impl/AbstractNodeSerializer.php | AbstractNodeSerializer.deserializeValue | protected function deserializeValue(Node $node, $key, $value) {
if (!is_array($value)) {
// force set value to avoid exceptions in this stage
$node->setValue($key, $value, true);
}
else {
$role = $key;
if ($this->isMultiValued($node, $role)) {
// deserialize children
foreach($value as $childData) {
$this->deserializeNode($childData, $node, $role);
}
}
else {
$this->deserializeNode($value, $node, $role);
}
}
} | php | protected function deserializeValue(Node $node, $key, $value) {
if (!is_array($value)) {
// force set value to avoid exceptions in this stage
$node->setValue($key, $value, true);
}
else {
$role = $key;
if ($this->isMultiValued($node, $role)) {
// deserialize children
foreach($value as $childData) {
$this->deserializeNode($childData, $node, $role);
}
}
else {
$this->deserializeNode($value, $node, $role);
}
}
} | [
"protected",
"function",
"deserializeValue",
"(",
"Node",
"$",
"node",
",",
"$",
"key",
",",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"// force set value to avoid exceptions in this stage",
"$",
"node",
"->",
"set... | Deserialize a node value
@param $node Node instance
@param $key The value name or type if value is an array
@param $value The value or child data, if value is an array | [
"Deserialize",
"a",
"node",
"value"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/impl/AbstractNodeSerializer.php#L59-L76 | train |
iherwig/wcmf | src/wcmf/lib/model/impl/AbstractNodeSerializer.php | AbstractNodeSerializer.isMultiValued | protected function isMultiValued(Node $node, $role) {
$isMultiValued = false;
$mapper = $node->getMapper();
if ($mapper->hasRelation($role)) {
$relation = $mapper->getRelation($role);
$isMultiValued = $relation->isMultiValued();
}
return $isMultiValued;
} | php | protected function isMultiValued(Node $node, $role) {
$isMultiValued = false;
$mapper = $node->getMapper();
if ($mapper->hasRelation($role)) {
$relation = $mapper->getRelation($role);
$isMultiValued = $relation->isMultiValued();
}
return $isMultiValued;
} | [
"protected",
"function",
"isMultiValued",
"(",
"Node",
"$",
"node",
",",
"$",
"role",
")",
"{",
"$",
"isMultiValued",
"=",
"false",
";",
"$",
"mapper",
"=",
"$",
"node",
"->",
"getMapper",
"(",
")",
";",
"if",
"(",
"$",
"mapper",
"->",
"hasRelation",
... | Check if a relation is multi valued
@param $node The Node that has the relation
@param $role The role of the relation | [
"Check",
"if",
"a",
"relation",
"is",
"multi",
"valued"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/impl/AbstractNodeSerializer.php#L83-L91 | train |
iherwig/wcmf | src/wcmf/lib/persistence/AttributeDescription.php | AttributeDescription.matchTags | public function matchTags(array $tags=[], $matchMode='all') {
$numGivenTags = sizeof($tags);
if (sizeof($numGivenTags) == 0) {
return true;
}
$result = true;
$diff = sizeof(array_diff($tags, $this->tags));
switch ($matchMode) {
case 'all':
$result = ($diff == 0);
break;
case 'none':
$result = ($diff == $numGivenTags);
break;
case 'any':
$result = ($diff < $numGivenTags);
break;
}
return $result;
} | php | public function matchTags(array $tags=[], $matchMode='all') {
$numGivenTags = sizeof($tags);
if (sizeof($numGivenTags) == 0) {
return true;
}
$result = true;
$diff = sizeof(array_diff($tags, $this->tags));
switch ($matchMode) {
case 'all':
$result = ($diff == 0);
break;
case 'none':
$result = ($diff == $numGivenTags);
break;
case 'any':
$result = ($diff < $numGivenTags);
break;
}
return $result;
} | [
"public",
"function",
"matchTags",
"(",
"array",
"$",
"tags",
"=",
"[",
"]",
",",
"$",
"matchMode",
"=",
"'all'",
")",
"{",
"$",
"numGivenTags",
"=",
"sizeof",
"(",
"$",
"tags",
")",
";",
"if",
"(",
"sizeof",
"(",
"$",
"numGivenTags",
")",
"==",
"0... | Check if this attribute is tagged with the given application specific tags
@param $tags An array of tags that the attribute should match. Empty array results in true the given matchMode (default: empty array)
@param $matchMode One of 'all', 'none', 'any', defines how the attribute's tags should match the given tags (default: 'all')
@return True if the attribute tags satisfy the match mode, false else | [
"Check",
"if",
"this",
"attribute",
"is",
"tagged",
"with",
"the",
"given",
"application",
"specific",
"tags"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/AttributeDescription.php#L70-L89 | train |
iherwig/wcmf | src/wcmf/lib/security/impl/StaticPermissionManager.php | StaticPermissionManager.getConfigurationInstance | protected function getConfigurationInstance() {
// get config file to modify
$configFiles = $this->configuration->getConfigurations();
if (sizeof($configFiles) == 0) {
return false;
}
// create a writable configuration and modify the permission
$mainConfig = $configFiles[0];
$config = new InifileConfiguration(dirname($mainConfig).'/');
$config->addConfiguration(basename($mainConfig));
return [
'instance' => $config,
'file' => $mainConfig
];
} | php | protected function getConfigurationInstance() {
// get config file to modify
$configFiles = $this->configuration->getConfigurations();
if (sizeof($configFiles) == 0) {
return false;
}
// create a writable configuration and modify the permission
$mainConfig = $configFiles[0];
$config = new InifileConfiguration(dirname($mainConfig).'/');
$config->addConfiguration(basename($mainConfig));
return [
'instance' => $config,
'file' => $mainConfig
];
} | [
"protected",
"function",
"getConfigurationInstance",
"(",
")",
"{",
"// get config file to modify",
"$",
"configFiles",
"=",
"$",
"this",
"->",
"configuration",
"->",
"getConfigurations",
"(",
")",
";",
"if",
"(",
"sizeof",
"(",
"$",
"configFiles",
")",
"==",
"0... | Get the configuration instance and file that is used to store the permissions.
@return Associative array with keys 'instance' and 'file'. | [
"Get",
"the",
"configuration",
"instance",
"and",
"file",
"that",
"is",
"used",
"to",
"store",
"the",
"permissions",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/security/impl/StaticPermissionManager.php#L157-L172 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/PersistenceActionKeyProvider.php | PersistenceActionKeyProvider.getAllKeyValues | protected function getAllKeyValues() {
$keys = [];
// add temporary permission to allow to read entitys
$this->isLoadingKeys = true;
$permissionManager = ObjectFactory::getInstance('permissionManager');
$tmpPerm = $permissionManager->addTempPermission($this->entityType, '', PersistenceAction::READ);
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$objects = $persistenceFacade->loadObjects($this->entityType, BuildDepth::SINGLE);
$permissionManager->removeTempPermission($tmpPerm);
$this->isLoadingKeys = false;
foreach ($objects as $object) {
$key = ActionKey::createKey(
$object->getValue($this->valueMap['resource']),
$object->getValue($this->valueMap['context']),
$object->getValue($this->valueMap['action'])
);
$keys[$key] = $object->getValue($this->valueMap['value']);
}
return $keys;
} | php | protected function getAllKeyValues() {
$keys = [];
// add temporary permission to allow to read entitys
$this->isLoadingKeys = true;
$permissionManager = ObjectFactory::getInstance('permissionManager');
$tmpPerm = $permissionManager->addTempPermission($this->entityType, '', PersistenceAction::READ);
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$objects = $persistenceFacade->loadObjects($this->entityType, BuildDepth::SINGLE);
$permissionManager->removeTempPermission($tmpPerm);
$this->isLoadingKeys = false;
foreach ($objects as $object) {
$key = ActionKey::createKey(
$object->getValue($this->valueMap['resource']),
$object->getValue($this->valueMap['context']),
$object->getValue($this->valueMap['action'])
);
$keys[$key] = $object->getValue($this->valueMap['value']);
}
return $keys;
} | [
"protected",
"function",
"getAllKeyValues",
"(",
")",
"{",
"$",
"keys",
"=",
"[",
"]",
";",
"// add temporary permission to allow to read entitys",
"$",
"this",
"->",
"isLoadingKeys",
"=",
"true",
";",
"$",
"permissionManager",
"=",
"ObjectFactory",
"::",
"getInstan... | Get all key values from the storage
@return Associative array with action keys as keys | [
"Get",
"all",
"key",
"values",
"from",
"the",
"storage"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/PersistenceActionKeyProvider.php#L112-L131 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/PersistenceActionKeyProvider.php | PersistenceActionKeyProvider.getSingleKeyValue | protected function getSingleKeyValue($actionKey) {
$query = new ObjectQuery($this->entityType, __CLASS__.__METHOD__);
$tpl = $query->getObjectTemplate($this->entityType);
$actionKeyParams = ActionKey::parseKey($actionKey);
$tpl->setValue($this->valueMap['resource'], Criteria::asValue('=', $actionKeyParams['resource']));
$tpl->setValue($this->valueMap['context'], Criteria::asValue('=', $actionKeyParams['context']));
$tpl->setValue($this->valueMap['action'], Criteria::asValue('=', $actionKeyParams['action']));
$keys = $query->execute(BuildDepth::SINGLE);
if (sizeof($keys) > 0) {
return $keys[0]->getValue($this->valueMap['value']);
}
return null;
} | php | protected function getSingleKeyValue($actionKey) {
$query = new ObjectQuery($this->entityType, __CLASS__.__METHOD__);
$tpl = $query->getObjectTemplate($this->entityType);
$actionKeyParams = ActionKey::parseKey($actionKey);
$tpl->setValue($this->valueMap['resource'], Criteria::asValue('=', $actionKeyParams['resource']));
$tpl->setValue($this->valueMap['context'], Criteria::asValue('=', $actionKeyParams['context']));
$tpl->setValue($this->valueMap['action'], Criteria::asValue('=', $actionKeyParams['action']));
$keys = $query->execute(BuildDepth::SINGLE);
if (sizeof($keys) > 0) {
return $keys[0]->getValue($this->valueMap['value']);
}
return null;
} | [
"protected",
"function",
"getSingleKeyValue",
"(",
"$",
"actionKey",
")",
"{",
"$",
"query",
"=",
"new",
"ObjectQuery",
"(",
"$",
"this",
"->",
"entityType",
",",
"__CLASS__",
".",
"__METHOD__",
")",
";",
"$",
"tpl",
"=",
"$",
"query",
"->",
"getObjectTemp... | Get a single key value from the storage
@param $actionKey The action key
@return String | [
"Get",
"a",
"single",
"key",
"value",
"from",
"the",
"storage"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/PersistenceActionKeyProvider.php#L138-L150 | train |
iherwig/wcmf | src/wcmf/lib/config/impl/PersistenceActionKeyProvider.php | PersistenceActionKeyProvider.keyChanged | public function keyChanged(PersistenceEvent $event) {
$object = $event->getObject();
if ($object->getType() == $this->entityType) {
$cache = ObjectFactory::getInstance('dynamicCache');
$cache->clear($this->getId());
}
} | php | public function keyChanged(PersistenceEvent $event) {
$object = $event->getObject();
if ($object->getType() == $this->entityType) {
$cache = ObjectFactory::getInstance('dynamicCache');
$cache->clear($this->getId());
}
} | [
"public",
"function",
"keyChanged",
"(",
"PersistenceEvent",
"$",
"event",
")",
"{",
"$",
"object",
"=",
"$",
"event",
"->",
"getObject",
"(",
")",
";",
"if",
"(",
"$",
"object",
"->",
"getType",
"(",
")",
"==",
"$",
"this",
"->",
"entityType",
")",
... | Listen to PersistentEvent
@param $event PersistentEvent instance | [
"Listen",
"to",
"PersistentEvent"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/impl/PersistenceActionKeyProvider.php#L156-L162 | train |
iherwig/wcmf | src/wcmf/lib/service/impl/HTTPClient.php | HTTPClient.doLogin | protected function doLogin() {
if ($this->user) {
$request = ObjectFactory::getNewInstance('request');
$request->setAction('login');
$request->setValues([
'login' => $this->user['login'],
'password' => $this->user['password']
]);
$response = $this->doRemoteCall($request, true);
if ($response->getValue('success')) {
$this->sessionId = $response->getValue('sid');
return true;
}
}
else {
throw new \RuntimeException("Remote user required for remote call.");
}
} | php | protected function doLogin() {
if ($this->user) {
$request = ObjectFactory::getNewInstance('request');
$request->setAction('login');
$request->setValues([
'login' => $this->user['login'],
'password' => $this->user['password']
]);
$response = $this->doRemoteCall($request, true);
if ($response->getValue('success')) {
$this->sessionId = $response->getValue('sid');
return true;
}
}
else {
throw new \RuntimeException("Remote user required for remote call.");
}
} | [
"protected",
"function",
"doLogin",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"user",
")",
"{",
"$",
"request",
"=",
"ObjectFactory",
"::",
"getNewInstance",
"(",
"'request'",
")",
";",
"$",
"request",
"->",
"setAction",
"(",
"'login'",
")",
";",
"$... | Do the login request. If the request is successful,
the session id will be set.
@return True on success | [
"Do",
"the",
"login",
"request",
".",
"If",
"the",
"request",
"is",
"successful",
"the",
"session",
"id",
"will",
"be",
"set",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/impl/HTTPClient.php#L130-L147 | train |
iherwig/wcmf | src/wcmf/application/controller/CopyController.php | CopyController.copyNode | protected function copyNode(ObjectId $oid) {
$logger = $this->getLogger();
if ($logger->isDebugEnabled()) {
$logger->debug("Copying node ".$oid);
}
$persistenceFacade = $this->getPersistenceFacade();
// load the original node
$node = $persistenceFacade->load($oid);
if ($node == null) {
throw new PersistenceException("Can't load node '".$oid."'");
}
// check if we already have a copy of the node
$nodeCopy = $this->getCopy($node->getOID());
if ($nodeCopy == null) {
// if not, create it
$nodeCopy = $persistenceFacade->create($node->getType());
$node->copyValues($nodeCopy, false);
}
// save copy
$this->registerCopy($node, $nodeCopy);
if ($logger->isInfoEnabled()) {
$logger->info("Copied: ".$node->getOID()." to ".$nodeCopy->getOID());
}
if ($logger->isDebugEnabled()) {
$logger->debug($nodeCopy->__toString());
}
// create the connections to already copied relatives
// this must be done after saving the node in order to have a correct oid
$mapper = $node->getMapper();
$relations = $mapper->getRelations();
foreach ($relations as $relation) {
if ($relation->getOtherNavigability()) {
$otherRole = $relation->getOtherRole();
$relativeValue = $node->getValue($otherRole);
$relatives = $relation->isMultiValued() ? $relativeValue :
($relativeValue != null ? [$relativeValue] : []);
foreach ($relatives as $relative) {
$copiedRelative = $this->getCopy($relative->getOID());
if ($copiedRelative != null) {
$nodeCopy->addNode($copiedRelative, $otherRole);
if ($logger->isDebugEnabled()) {
$logger->debug("Added ".$copiedRelative->getOID()." to ".$nodeCopy->getOID());
$logger->debug($copiedRelative->__toString());
}
}
}
}
}
return $nodeCopy;
} | php | protected function copyNode(ObjectId $oid) {
$logger = $this->getLogger();
if ($logger->isDebugEnabled()) {
$logger->debug("Copying node ".$oid);
}
$persistenceFacade = $this->getPersistenceFacade();
// load the original node
$node = $persistenceFacade->load($oid);
if ($node == null) {
throw new PersistenceException("Can't load node '".$oid."'");
}
// check if we already have a copy of the node
$nodeCopy = $this->getCopy($node->getOID());
if ($nodeCopy == null) {
// if not, create it
$nodeCopy = $persistenceFacade->create($node->getType());
$node->copyValues($nodeCopy, false);
}
// save copy
$this->registerCopy($node, $nodeCopy);
if ($logger->isInfoEnabled()) {
$logger->info("Copied: ".$node->getOID()." to ".$nodeCopy->getOID());
}
if ($logger->isDebugEnabled()) {
$logger->debug($nodeCopy->__toString());
}
// create the connections to already copied relatives
// this must be done after saving the node in order to have a correct oid
$mapper = $node->getMapper();
$relations = $mapper->getRelations();
foreach ($relations as $relation) {
if ($relation->getOtherNavigability()) {
$otherRole = $relation->getOtherRole();
$relativeValue = $node->getValue($otherRole);
$relatives = $relation->isMultiValued() ? $relativeValue :
($relativeValue != null ? [$relativeValue] : []);
foreach ($relatives as $relative) {
$copiedRelative = $this->getCopy($relative->getOID());
if ($copiedRelative != null) {
$nodeCopy->addNode($copiedRelative, $otherRole);
if ($logger->isDebugEnabled()) {
$logger->debug("Added ".$copiedRelative->getOID()." to ".$nodeCopy->getOID());
$logger->debug($copiedRelative->__toString());
}
}
}
}
}
return $nodeCopy;
} | [
"protected",
"function",
"copyNode",
"(",
"ObjectId",
"$",
"oid",
")",
"{",
"$",
"logger",
"=",
"$",
"this",
"->",
"getLogger",
"(",
")",
";",
"if",
"(",
"$",
"logger",
"->",
"isDebugEnabled",
"(",
")",
")",
"{",
"$",
"logger",
"->",
"debug",
"(",
... | Create a copy of the node with the given object id. The returned
node is already persisted.
@param $oid The object id of the node to copy
@return The copied Node or null | [
"Create",
"a",
"copy",
"of",
"the",
"node",
"with",
"the",
"given",
"object",
"id",
".",
"The",
"returned",
"node",
"is",
"already",
"persisted",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/CopyController.php#L355-L409 | train |
iherwig/wcmf | src/wcmf/application/controller/CopyController.php | CopyController.getTargetNode | protected function getTargetNode(ObjectId $targetOID) {
if ($this->targetNode == null) {
// load parent node
$persistenceFacade = $this->getPersistenceFacade();
$targetNode = $persistenceFacade->load($targetOID);
$this->targetNode = $targetNode;
}
return $this->targetNode;
} | php | protected function getTargetNode(ObjectId $targetOID) {
if ($this->targetNode == null) {
// load parent node
$persistenceFacade = $this->getPersistenceFacade();
$targetNode = $persistenceFacade->load($targetOID);
$this->targetNode = $targetNode;
}
return $this->targetNode;
} | [
"protected",
"function",
"getTargetNode",
"(",
"ObjectId",
"$",
"targetOID",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"targetNode",
"==",
"null",
")",
"{",
"// load parent node",
"$",
"persistenceFacade",
"=",
"$",
"this",
"->",
"getPersistenceFacade",
"(",
")"... | Get the target node from the request parameter targetoid
@param $targetOID The object id of the target node
@return Node instance | [
"Get",
"the",
"target",
"node",
"from",
"the",
"request",
"parameter",
"targetoid"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/CopyController.php#L427-L435 | train |
iherwig/wcmf | src/wcmf/application/controller/CopyController.php | CopyController.registerCopy | protected function registerCopy(PersistentObject $origNode, PersistentObject $copyNode) {
// store oid in the registry
$registry = $this->getLocalSessionValue(self::OBJECT_MAP_VAR);
$registry[$origNode->getOID()->__toString()] = $copyNode->getOID()->__toString();
$this->setLocalSessionValue(self::OBJECT_MAP_VAR, $registry);
} | php | protected function registerCopy(PersistentObject $origNode, PersistentObject $copyNode) {
// store oid in the registry
$registry = $this->getLocalSessionValue(self::OBJECT_MAP_VAR);
$registry[$origNode->getOID()->__toString()] = $copyNode->getOID()->__toString();
$this->setLocalSessionValue(self::OBJECT_MAP_VAR, $registry);
} | [
"protected",
"function",
"registerCopy",
"(",
"PersistentObject",
"$",
"origNode",
",",
"PersistentObject",
"$",
"copyNode",
")",
"{",
"// store oid in the registry",
"$",
"registry",
"=",
"$",
"this",
"->",
"getLocalSessionValue",
"(",
"self",
"::",
"OBJECT_MAP_VAR",... | Register a copied node in the session for later reference
@param $origNode The original Node instance
@param $copyNode The copied Node instance | [
"Register",
"a",
"copied",
"node",
"in",
"the",
"session",
"for",
"later",
"reference"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/CopyController.php#L442-L447 | train |
iherwig/wcmf | src/wcmf/application/controller/CopyController.php | CopyController.updateCopyOIDs | protected function updateCopyOIDs(array $oidMap) {
$registry = $this->getLocalSessionValue(self::OBJECT_MAP_VAR);
// registry maybe deleted already if it's the last step
if ($registry) {
$flippedRegistry = array_flip($registry);
foreach ($oidMap as $oldOid => $newOid) {
if (isset($flippedRegistry[$oldOid])) {
$key = $flippedRegistry[$oldOid];
unset($flippedRegistry[$oldOid]);
$flippedRegistry[$newOid] = $key;
}
}
$registry = array_flip($flippedRegistry);
$this->setLocalSessionValue(self::OBJECT_MAP_VAR, $registry);
}
} | php | protected function updateCopyOIDs(array $oidMap) {
$registry = $this->getLocalSessionValue(self::OBJECT_MAP_VAR);
// registry maybe deleted already if it's the last step
if ($registry) {
$flippedRegistry = array_flip($registry);
foreach ($oidMap as $oldOid => $newOid) {
if (isset($flippedRegistry[$oldOid])) {
$key = $flippedRegistry[$oldOid];
unset($flippedRegistry[$oldOid]);
$flippedRegistry[$newOid] = $key;
}
}
$registry = array_flip($flippedRegistry);
$this->setLocalSessionValue(self::OBJECT_MAP_VAR, $registry);
}
} | [
"protected",
"function",
"updateCopyOIDs",
"(",
"array",
"$",
"oidMap",
")",
"{",
"$",
"registry",
"=",
"$",
"this",
"->",
"getLocalSessionValue",
"(",
"self",
"::",
"OBJECT_MAP_VAR",
")",
";",
"// registry maybe deleted already if it's the last step",
"if",
"(",
"$... | Update the copied object ids in the registry
@param $oidMap Map of changed object ids (key: old value, value: new value) | [
"Update",
"the",
"copied",
"object",
"ids",
"in",
"the",
"registry"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/CopyController.php#L453-L468 | train |
iherwig/wcmf | src/wcmf/application/controller/CopyController.php | CopyController.getCopyOID | protected function getCopyOID(ObjectId $origOID) {
$registry = $this->getLocalSessionValue(self::OBJECT_MAP_VAR);
// check if the oid exists in the registry
$oidStr = $origOID->__toString();
if (!isset($registry[$oidStr])) {
$logger = $this->getLogger();
if ($logger->isDebugEnabled()) {
$logger->debug("Copy of ".$oidStr." not found.");
}
return null;
}
$copyOID = ObjectId::parse($registry[$oidStr]);
return $copyOID;
} | php | protected function getCopyOID(ObjectId $origOID) {
$registry = $this->getLocalSessionValue(self::OBJECT_MAP_VAR);
// check if the oid exists in the registry
$oidStr = $origOID->__toString();
if (!isset($registry[$oidStr])) {
$logger = $this->getLogger();
if ($logger->isDebugEnabled()) {
$logger->debug("Copy of ".$oidStr." not found.");
}
return null;
}
$copyOID = ObjectId::parse($registry[$oidStr]);
return $copyOID;
} | [
"protected",
"function",
"getCopyOID",
"(",
"ObjectId",
"$",
"origOID",
")",
"{",
"$",
"registry",
"=",
"$",
"this",
"->",
"getLocalSessionValue",
"(",
"self",
"::",
"OBJECT_MAP_VAR",
")",
";",
"// check if the oid exists in the registry",
"$",
"oidStr",
"=",
"$",... | Get the object id of the copied node for a node id
@param $origOID The object id of the original node
@return ObjectId or null, if it does not exist already | [
"Get",
"the",
"object",
"id",
"of",
"the",
"copied",
"node",
"for",
"a",
"node",
"id"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/CopyController.php#L475-L490 | train |
iherwig/wcmf | src/wcmf/application/controller/CopyController.php | CopyController.getCopy | protected function getCopy(ObjectId $origOID) {
$copyOID = $this->getCopyOID($origOID);
if ($copyOID != null) {
$persistenceFacade = $this->getPersistenceFacade();
$nodeCopy = $persistenceFacade->load($copyOID);
return $nodeCopy;
}
else {
return null;
}
} | php | protected function getCopy(ObjectId $origOID) {
$copyOID = $this->getCopyOID($origOID);
if ($copyOID != null) {
$persistenceFacade = $this->getPersistenceFacade();
$nodeCopy = $persistenceFacade->load($copyOID);
return $nodeCopy;
}
else {
return null;
}
} | [
"protected",
"function",
"getCopy",
"(",
"ObjectId",
"$",
"origOID",
")",
"{",
"$",
"copyOID",
"=",
"$",
"this",
"->",
"getCopyOID",
"(",
"$",
"origOID",
")",
";",
"if",
"(",
"$",
"copyOID",
"!=",
"null",
")",
"{",
"$",
"persistenceFacade",
"=",
"$",
... | Get the copied node for a node id
@param $origOID The object id of the original node
@return Copied Node or null, if it does not exist already | [
"Get",
"the",
"copied",
"node",
"for",
"a",
"node",
"id"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/CopyController.php#L497-L507 | train |
iherwig/wcmf | src/wcmf/lib/search/impl/LuceneSearch.php | LuceneSearch.setIndexPath | public function setIndexPath($indexPath) {
$fileUtil = new FileUtil();
$this->indexPath = $fileUtil->realpath(WCMF_BASE.$indexPath).'/';
$fileUtil->mkdirRec($this->indexPath);
if (!is_writeable($this->indexPath)) {
throw new ConfigurationException("Index path '".$indexPath."' is not writeable.");
}
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Lucene index location: ".$this->indexPath);
}
} | php | public function setIndexPath($indexPath) {
$fileUtil = new FileUtil();
$this->indexPath = $fileUtil->realpath(WCMF_BASE.$indexPath).'/';
$fileUtil->mkdirRec($this->indexPath);
if (!is_writeable($this->indexPath)) {
throw new ConfigurationException("Index path '".$indexPath."' is not writeable.");
}
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Lucene index location: ".$this->indexPath);
}
} | [
"public",
"function",
"setIndexPath",
"(",
"$",
"indexPath",
")",
"{",
"$",
"fileUtil",
"=",
"new",
"FileUtil",
"(",
")",
";",
"$",
"this",
"->",
"indexPath",
"=",
"$",
"fileUtil",
"->",
"realpath",
"(",
"WCMF_BASE",
".",
"$",
"indexPath",
")",
".",
"'... | Set the path to the search index.
@param $indexPath Directory relative to main | [
"Set",
"the",
"path",
"to",
"the",
"search",
"index",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/search/impl/LuceneSearch.php#L88-L98 | train |
iherwig/wcmf | src/wcmf/lib/search/impl/LuceneSearch.php | LuceneSearch.afterCommit | public function afterCommit(TransactionEvent $event) {
if ($this->liveUpdate && $event->getPhase() == TransactionEvent::AFTER_COMMIT) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
// add inserted/updated objects
foreach (array_merge(array_values($event->getInsertedOids()), $event->getUpdatedOids()) as $oid) {
$object = $persistenceFacade->load(ObjectId::parse($oid));
if ($object) {
$this->addToIndex($object);
}
else {
self::$logger->warn("Could not index object with oid ".$oid." because it does not exist");
}
}
// remove deleted objects
foreach ($event->getDeletedOids() as $oid) {
$this->deleteFromIndex(ObjectId::parse($oid));
}
}
} | php | public function afterCommit(TransactionEvent $event) {
if ($this->liveUpdate && $event->getPhase() == TransactionEvent::AFTER_COMMIT) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
// add inserted/updated objects
foreach (array_merge(array_values($event->getInsertedOids()), $event->getUpdatedOids()) as $oid) {
$object = $persistenceFacade->load(ObjectId::parse($oid));
if ($object) {
$this->addToIndex($object);
}
else {
self::$logger->warn("Could not index object with oid ".$oid." because it does not exist");
}
}
// remove deleted objects
foreach ($event->getDeletedOids() as $oid) {
$this->deleteFromIndex(ObjectId::parse($oid));
}
}
} | [
"public",
"function",
"afterCommit",
"(",
"TransactionEvent",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"liveUpdate",
"&&",
"$",
"event",
"->",
"getPhase",
"(",
")",
"==",
"TransactionEvent",
"::",
"AFTER_COMMIT",
")",
"{",
"$",
"persistenceFacad... | Listen to TransactionEvents
@param $event TransactionEvent instance | [
"Listen",
"to",
"TransactionEvents"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/search/impl/LuceneSearch.php#L310-L328 | train |
iherwig/wcmf | src/wcmf/lib/search/impl/LuceneSearch.php | LuceneSearch.getIndex | private function getIndex($create = true) {
if (!$this->index || $create) {
$indexPath = $this->getIndexPath();
$analyzer = new LuceneUtf8Analyzer();
// add stop words filter
$stopWords = $this->getStopWords();
$stopWordsFilter = new StopWords($stopWords);
$analyzer->addFilter($stopWordsFilter);
Analyzer::setDefault($analyzer);
Wildcard::setMinPrefixLength(0);
QueryParser::setDefaultEncoding('UTF-8');
QueryParser::setDefaultOperator(QueryParser::B_AND);
try {
$this->index = Lucene::open($indexPath);
//$this->index->setMaxMergeDocs(5);
//$this->index->setMergeFactor(5);
}
catch (\Exception $ex) {
$this->index = $this->resetIndex();
}
}
return $this->index;
} | php | private function getIndex($create = true) {
if (!$this->index || $create) {
$indexPath = $this->getIndexPath();
$analyzer = new LuceneUtf8Analyzer();
// add stop words filter
$stopWords = $this->getStopWords();
$stopWordsFilter = new StopWords($stopWords);
$analyzer->addFilter($stopWordsFilter);
Analyzer::setDefault($analyzer);
Wildcard::setMinPrefixLength(0);
QueryParser::setDefaultEncoding('UTF-8');
QueryParser::setDefaultOperator(QueryParser::B_AND);
try {
$this->index = Lucene::open($indexPath);
//$this->index->setMaxMergeDocs(5);
//$this->index->setMergeFactor(5);
}
catch (\Exception $ex) {
$this->index = $this->resetIndex();
}
}
return $this->index;
} | [
"private",
"function",
"getIndex",
"(",
"$",
"create",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"index",
"||",
"$",
"create",
")",
"{",
"$",
"indexPath",
"=",
"$",
"this",
"->",
"getIndexPath",
"(",
")",
";",
"$",
"analyzer",
"=",
... | Get the search index.
@param $create Boolean whether to create the index, if it does not exist (default: _true_)
@return An instance of ZendSearch/SearchIndexInterface or null | [
"Get",
"the",
"search",
"index",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/search/impl/LuceneSearch.php#L335-L361 | train |
GW2Treasures/gw2api | src/V2/Endpoint/Continent/RegionEndpoint.php | RegionEndpoint.mapsOf | public function mapsOf( $region ) {
return new MapEndpoint( $this->api, $this->continent, $this->floor, $region );
} | php | public function mapsOf( $region ) {
return new MapEndpoint( $this->api, $this->continent, $this->floor, $region );
} | [
"public",
"function",
"mapsOf",
"(",
"$",
"region",
")",
"{",
"return",
"new",
"MapEndpoint",
"(",
"$",
"this",
"->",
"api",
",",
"$",
"this",
"->",
"continent",
",",
"$",
"this",
"->",
"floor",
",",
"$",
"region",
")",
";",
"}"
] | Get the regions maps.
@param int $region
@return MapEndpoint | [
"Get",
"the",
"regions",
"maps",
"."
] | c8795af0c1d0a434b9e530f779d5a95786db2176 | https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Endpoint/Continent/RegionEndpoint.php#L47-L49 | train |
iherwig/wcmf | src/wcmf/lib/presentation/link/LinkProcessor.php | LinkProcessor.processLinks | public static function processLinks($node, $base, LinkProcessorStrategy $strategy,
$recursive=true) {
if (!$node) {
return;
}
$invalidURLs = [];
$logger = LogManager::getLogger(__CLASS__);
// iterate over all node values
$iter = new NodeValueIterator($node, $recursive);
for($iter->rewind(); $iter->valid(); $iter->next()) {
$currentNode = $iter->currentNode();
$valueName = $iter->key();
$value = $currentNode->getValue($valueName);
$oldValue = $value;
// find links in texts
$urls = array_fill_keys(StringUtil::getUrls($value), 'embedded');
// find direct attribute urls
if (preg_match('/^[a-zA-Z]+:\/\//', $value) || InternalLink::isLink($value)) {
$urls[$value] = 'direct';
}
// process urls
foreach ($urls as $url => $type) {
// translate relative urls
if (!InternalLink::isLink($url) && !preg_match('/^#|^{|^$|^[a-zA-Z]+:\/\/|^javascript:|^mailto:/', $url) &&
@file_exists($url) === false) {
// translate relative links
$urlConv = URIUtil::translate($url, $base);
$value = self::replaceUrl($value, $url, $urlConv['absolute'], $type);
$url = $urlConv['absolute'];
}
// check url
$urlOK = self::checkUrl($url, $strategy);
if ($urlOK) {
$urlConv = null;
if (InternalLink::isLink($url)) {
// convert internal urls
$urlConv = self::convertInternalLink($url, $strategy);
}
elseif (preg_match('/^#/', $url)) {
// convert hash links
$urlConv = $strategy->getObjectUrl($node).$url;
}
if ($urlConv !== null) {
$value = self::replaceUrl($value, $url, $urlConv, $type);
}
}
else {
// invalid url
$logger->error("Invalid URL found: ".$url);
$oidStr = $currentNode->getOID()->__toString();
if (!isset($invalidURLs[$oidStr])) {
$invalidURLs[] = [];
}
$invalidURLs[$oidStr][] = $url;
$value = self::replaceUrl($value, $url, '#', $type);
}
}
if ($oldValue != $value) {
$currentNode->setValue($valueName, $value, true);
}
}
return $invalidURLs;
} | php | public static function processLinks($node, $base, LinkProcessorStrategy $strategy,
$recursive=true) {
if (!$node) {
return;
}
$invalidURLs = [];
$logger = LogManager::getLogger(__CLASS__);
// iterate over all node values
$iter = new NodeValueIterator($node, $recursive);
for($iter->rewind(); $iter->valid(); $iter->next()) {
$currentNode = $iter->currentNode();
$valueName = $iter->key();
$value = $currentNode->getValue($valueName);
$oldValue = $value;
// find links in texts
$urls = array_fill_keys(StringUtil::getUrls($value), 'embedded');
// find direct attribute urls
if (preg_match('/^[a-zA-Z]+:\/\//', $value) || InternalLink::isLink($value)) {
$urls[$value] = 'direct';
}
// process urls
foreach ($urls as $url => $type) {
// translate relative urls
if (!InternalLink::isLink($url) && !preg_match('/^#|^{|^$|^[a-zA-Z]+:\/\/|^javascript:|^mailto:/', $url) &&
@file_exists($url) === false) {
// translate relative links
$urlConv = URIUtil::translate($url, $base);
$value = self::replaceUrl($value, $url, $urlConv['absolute'], $type);
$url = $urlConv['absolute'];
}
// check url
$urlOK = self::checkUrl($url, $strategy);
if ($urlOK) {
$urlConv = null;
if (InternalLink::isLink($url)) {
// convert internal urls
$urlConv = self::convertInternalLink($url, $strategy);
}
elseif (preg_match('/^#/', $url)) {
// convert hash links
$urlConv = $strategy->getObjectUrl($node).$url;
}
if ($urlConv !== null) {
$value = self::replaceUrl($value, $url, $urlConv, $type);
}
}
else {
// invalid url
$logger->error("Invalid URL found: ".$url);
$oidStr = $currentNode->getOID()->__toString();
if (!isset($invalidURLs[$oidStr])) {
$invalidURLs[] = [];
}
$invalidURLs[$oidStr][] = $url;
$value = self::replaceUrl($value, $url, '#', $type);
}
}
if ($oldValue != $value) {
$currentNode->setValue($valueName, $value, true);
}
}
return $invalidURLs;
} | [
"public",
"static",
"function",
"processLinks",
"(",
"$",
"node",
",",
"$",
"base",
",",
"LinkProcessorStrategy",
"$",
"strategy",
",",
"$",
"recursive",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"$",
"node",
")",
"{",
"return",
";",
"}",
"$",
"invalidURL... | Check and convert links in the given node.
@param $node Node instance
@param $base The base url of relative links as seen from the executing script
@param $strategy The strategy used to check and create urls
@param recursive Boolean whether to process child nodes to (default: true)
@return Array of invalid urls | [
"Check",
"and",
"convert",
"links",
"in",
"the",
"given",
"node",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/link/LinkProcessor.php#L39-L106 | train |
iherwig/wcmf | src/wcmf/lib/presentation/link/LinkProcessor.php | LinkProcessor.replaceUrl | protected static function replaceUrl($value, $url, $urlConv, $type) {
if ($type == 'embedded') {
$value = str_replace('"'.$url.'"', '"'.$urlConv.'"', $value);
}
else {
$value = str_replace($url, $urlConv, $value);
}
return $value;
} | php | protected static function replaceUrl($value, $url, $urlConv, $type) {
if ($type == 'embedded') {
$value = str_replace('"'.$url.'"', '"'.$urlConv.'"', $value);
}
else {
$value = str_replace($url, $urlConv, $value);
}
return $value;
} | [
"protected",
"static",
"function",
"replaceUrl",
"(",
"$",
"value",
",",
"$",
"url",
",",
"$",
"urlConv",
",",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"type",
"==",
"'embedded'",
")",
"{",
"$",
"value",
"=",
"str_replace",
"(",
"'\"'",
".",
"$",
"ur... | Replace the url in the given value
@param $value
@param $url
@param $urlConv
@param $type embedded or direct
@return String | [
"Replace",
"the",
"url",
"in",
"the",
"given",
"value"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/link/LinkProcessor.php#L116-L124 | train |
iherwig/wcmf | src/wcmf/lib/presentation/link/LinkProcessor.php | LinkProcessor.convertInternalLink | protected static function convertInternalLink($url, LinkProcessorStrategy $strategy) {
$urlConv = $url;
if (InternalLink::isLink($url)) {
$oid = InternalLink::getReferencedOID($url);
if ($oid != null) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$object = $persistenceFacade->load($oid);
$urlConv = $strategy->getObjectUrl($object);
}
else {
$urlConv = '#';
}
$anchorOID = InternalLink::getAnchorOID($url);
if ($anchorOID != null) {
if (strrpos($urlConv) !== 0) {
$urlConv .= '#';
}
$urlConv .= $anchorOID;
}
else {
$anchorName = InternalLink::getAnchorName($url);
if ($anchorName != null) {
if (strrpos($urlConv) !== 0) {
$urlConv .= '#';
}
$urlConv .= $anchorName;
}
}
}
return $urlConv;
} | php | protected static function convertInternalLink($url, LinkProcessorStrategy $strategy) {
$urlConv = $url;
if (InternalLink::isLink($url)) {
$oid = InternalLink::getReferencedOID($url);
if ($oid != null) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$object = $persistenceFacade->load($oid);
$urlConv = $strategy->getObjectUrl($object);
}
else {
$urlConv = '#';
}
$anchorOID = InternalLink::getAnchorOID($url);
if ($anchorOID != null) {
if (strrpos($urlConv) !== 0) {
$urlConv .= '#';
}
$urlConv .= $anchorOID;
}
else {
$anchorName = InternalLink::getAnchorName($url);
if ($anchorName != null) {
if (strrpos($urlConv) !== 0) {
$urlConv .= '#';
}
$urlConv .= $anchorName;
}
}
}
return $urlConv;
} | [
"protected",
"static",
"function",
"convertInternalLink",
"(",
"$",
"url",
",",
"LinkProcessorStrategy",
"$",
"strategy",
")",
"{",
"$",
"urlConv",
"=",
"$",
"url",
";",
"if",
"(",
"InternalLink",
"::",
"isLink",
"(",
"$",
"url",
")",
")",
"{",
"$",
"oid... | Convert an internal link.
@param $url The url to convert
@param $strategy The strategy used to check and create urls
@return The converted url | [
"Convert",
"an",
"internal",
"link",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/link/LinkProcessor.php#L171-L201 | train |
iherwig/wcmf | src/wcmf/lib/service/SoapClient.php | SoapClient.call | public function call($method, $params=[]) {
$header = $this->generateWSSecurityHeader($this->user, $this->password);
$response = $this->__soapCall($method, sizeof($params) > 0 ? [$params] : [], null, $header);
// in document/literal style the "return" parameter holds the result
return property_exists($response, 'return') ? $response->return : $response;
} | php | public function call($method, $params=[]) {
$header = $this->generateWSSecurityHeader($this->user, $this->password);
$response = $this->__soapCall($method, sizeof($params) > 0 ? [$params] : [], null, $header);
// in document/literal style the "return" parameter holds the result
return property_exists($response, 'return') ? $response->return : $response;
} | [
"public",
"function",
"call",
"(",
"$",
"method",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"header",
"=",
"$",
"this",
"->",
"generateWSSecurityHeader",
"(",
"$",
"this",
"->",
"user",
",",
"$",
"this",
"->",
"password",
")",
";",
"$",
"re... | Call the given soap method
@param $method
@param $params (optional, default: empty array) | [
"Call",
"the",
"given",
"soap",
"method"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/SoapClient.php#L50-L55 | train |
iherwig/wcmf | src/wcmf/lib/service/SoapClient.php | SoapClient.__doRequest | public function __doRequest($request, $location, $action, $version, $oneway=0){
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Request:");
self::$logger->debug($request);
}
$response = trim(parent::__doRequest($request, $location, $action, $version, $oneway));
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Response:");
self::$logger->debug($response);
self::$logger->debug($this->getDebugInfos());
}
$parsedResponse = preg_replace('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/', "", $response);
// fix missing last e> caused by php's built-in webserver
if (preg_match('/^<\?xml/', $parsedResponse) && !preg_match('/e>$/', $parsedResponse)) {
$parsedResponse .= 'e>';
}
return $parsedResponse;
} | php | public function __doRequest($request, $location, $action, $version, $oneway=0){
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Request:");
self::$logger->debug($request);
}
$response = trim(parent::__doRequest($request, $location, $action, $version, $oneway));
if (self::$logger->isDebugEnabled()) {
self::$logger->debug("Response:");
self::$logger->debug($response);
self::$logger->debug($this->getDebugInfos());
}
$parsedResponse = preg_replace('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/', "", $response);
// fix missing last e> caused by php's built-in webserver
if (preg_match('/^<\?xml/', $parsedResponse) && !preg_match('/e>$/', $parsedResponse)) {
$parsedResponse .= 'e>';
}
return $parsedResponse;
} | [
"public",
"function",
"__doRequest",
"(",
"$",
"request",
",",
"$",
"location",
",",
"$",
"action",
",",
"$",
"version",
",",
"$",
"oneway",
"=",
"0",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"logger",
"->",
"isDebugEnabled",
"(",
")",
")",
"{",
"se... | Overridden in order to strip bom characters
@see SoapClient::__doRequest | [
"Overridden",
"in",
"order",
"to",
"strip",
"bom",
"characters"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/SoapClient.php#L61-L78 | train |
iherwig/wcmf | src/wcmf/lib/service/SoapClient.php | SoapClient.generateWSSecurityHeader | private function generateWSSecurityHeader($user, $password) {
$nonce = sha1(mt_rand());
$xml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="'.self::OASIS.'/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>'.$user.'</wsse:Username>
<wsse:Password Type="'.self::OASIS.'/oasis-200401-wss-username-token-profile-1.0#PasswordText">'.$password.'</wsse:Password>
<wsse:Nonce EncodingType="'.self::OASIS.'/oasis-200401-wss-soap-message-security-1.0#Base64Binary">'.$nonce.'</wsse:Nonce>
</wsse:UsernameToken>
</wsse:Security>';
return new \SoapHeader(self::OASIS.'/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', new \SoapVar($xml, XSD_ANYXML), true);
} | php | private function generateWSSecurityHeader($user, $password) {
$nonce = sha1(mt_rand());
$xml = '<wsse:Security SOAP-ENV:mustUnderstand="1" xmlns:wsse="'.self::OASIS.'/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<wsse:UsernameToken>
<wsse:Username>'.$user.'</wsse:Username>
<wsse:Password Type="'.self::OASIS.'/oasis-200401-wss-username-token-profile-1.0#PasswordText">'.$password.'</wsse:Password>
<wsse:Nonce EncodingType="'.self::OASIS.'/oasis-200401-wss-soap-message-security-1.0#Base64Binary">'.$nonce.'</wsse:Nonce>
</wsse:UsernameToken>
</wsse:Security>';
return new \SoapHeader(self::OASIS.'/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'Security', new \SoapVar($xml, XSD_ANYXML), true);
} | [
"private",
"function",
"generateWSSecurityHeader",
"(",
"$",
"user",
",",
"$",
"password",
")",
"{",
"$",
"nonce",
"=",
"sha1",
"(",
"mt_rand",
"(",
")",
")",
";",
"$",
"xml",
"=",
"'<wsse:Security SOAP-ENV:mustUnderstand=\"1\" xmlns:wsse=\"'",
".",
"self",
"::"... | Create the WS-Security authentication header for the given credentials
@param $user
@param $password
@return SoapHeader | [
"Create",
"the",
"WS",
"-",
"Security",
"authentication",
"header",
"for",
"the",
"given",
"credentials"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/SoapClient.php#L86-L96 | train |
iherwig/wcmf | src/wcmf/lib/service/SoapClient.php | SoapClient.getDebugInfos | public function getDebugInfos() {
$requestHeaders = $this->__getLastRequestHeaders();
$request = $this->__getLastRequest();
$responseHeaders = $this->__getLastResponseHeaders();
$response = $this->__getLastResponse();
$msg = '';
$msg .= "Request Headers:\n" . $requestHeaders . "\n";
$msg .= "Request:\n" . $request . "\n";
$msg .= "Response Headers:\n" . $responseHeaders . "\n";
$msg .= "Response:\n" . $response . "\n";
return $msg;
} | php | public function getDebugInfos() {
$requestHeaders = $this->__getLastRequestHeaders();
$request = $this->__getLastRequest();
$responseHeaders = $this->__getLastResponseHeaders();
$response = $this->__getLastResponse();
$msg = '';
$msg .= "Request Headers:\n" . $requestHeaders . "\n";
$msg .= "Request:\n" . $request . "\n";
$msg .= "Response Headers:\n" . $responseHeaders . "\n";
$msg .= "Response:\n" . $response . "\n";
return $msg;
} | [
"public",
"function",
"getDebugInfos",
"(",
")",
"{",
"$",
"requestHeaders",
"=",
"$",
"this",
"->",
"__getLastRequestHeaders",
"(",
")",
";",
"$",
"request",
"=",
"$",
"this",
"->",
"__getLastRequest",
"(",
")",
";",
"$",
"responseHeaders",
"=",
"$",
"thi... | Get informations about the last request. Available
if constructor options contain 'trace' => 1
@return String | [
"Get",
"informations",
"about",
"the",
"last",
"request",
".",
"Available",
"if",
"constructor",
"options",
"contain",
"trace",
"=",
">",
"1"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/SoapClient.php#L103-L116 | train |
heyday/silverstripe-versioneddataobjects | code/VersionedDataObjectDetailsForm.php | VersionedDataObjectDetailsForm_ItemRequest.doSaveAndQuit | public function doSaveAndQuit($data, $form)
{
$this->save($data, $form);
$controller = $this->getToplevelController();
$controller->getResponse()->addHeader("X-Pjax", "Content");
$controller->redirect($this->getBackLink());
} | php | public function doSaveAndQuit($data, $form)
{
$this->save($data, $form);
$controller = $this->getToplevelController();
$controller->getResponse()->addHeader("X-Pjax", "Content");
$controller->redirect($this->getBackLink());
} | [
"public",
"function",
"doSaveAndQuit",
"(",
"$",
"data",
",",
"$",
"form",
")",
"{",
"$",
"this",
"->",
"save",
"(",
"$",
"data",
",",
"$",
"form",
")",
";",
"$",
"controller",
"=",
"$",
"this",
"->",
"getToplevelController",
"(",
")",
";",
"$",
"c... | Override the doSaveAnQuit action from better buttons so that it uses the versioned way fo saving things.
@param $data
@param $form | [
"Override",
"the",
"doSaveAnQuit",
"action",
"from",
"better",
"buttons",
"so",
"that",
"it",
"uses",
"the",
"versioned",
"way",
"fo",
"saving",
"things",
"."
] | 30a07d976abd17baba9d9194ca176c82d72323ac | https://github.com/heyday/silverstripe-versioneddataobjects/blob/30a07d976abd17baba9d9194ca176c82d72323ac/code/VersionedDataObjectDetailsForm.php#L275-L281 | train |
silverstripe/silverstripe-dynamodb | code/Model/DynamoDbSession.php | DynamoDbSession.get | public static function get()
{
// Use DynamoDB for distributed session storage if it's configured
$awsDynamoDBSessionTable = Environment::getEnv('AWS_DYNAMODB_SESSION_TABLE');
if (!empty($awsDynamoDBSessionTable)) {
$awsRegionName = Environment::getEnv('AWS_REGION_NAME');
$awsDynamoDBEndpoint = Environment::getEnv('AWS_DYNAMODB_ENDPOINT');
$awsAccessKey = Environment::getEnv('AWS_ACCESS_KEY');
$awsSecretKey = Environment::getEnv('AWS_SECRET_KEY');
$dynamoOptions = array('region' => $awsRegionName);
// This endpoint can be set for locally testing DynamoDB.
// see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html
if (!empty($awsDynamoDBEndpoint)) {
$dynamoOptions['endpoint'] = $awsDynamoDBEndpoint;
}
if (!empty($awsAccessKey) && !empty($awsSecretKey)) {
$dynamoOptions['credentials']['key'] = $awsAccessKey;
$dynamoOptions['credentials']['secret'] = $awsSecretKey;
} else {
// cache credentials when IAM fetches the credentials from EC2 metadata service
// this will use doctrine/cache (included via composer) to do the actual caching into APCu
// http://docs.aws.amazon.com/aws-sdk-php/guide/latest/performance.html#cache-instance-profile-credentials
$dynamoOptions['credentials'] = new DoctrineCacheAdapter(new ApcuCache());
}
return new static($dynamoOptions, $awsDynamoDBSessionTable);
}
return null;
} | php | public static function get()
{
// Use DynamoDB for distributed session storage if it's configured
$awsDynamoDBSessionTable = Environment::getEnv('AWS_DYNAMODB_SESSION_TABLE');
if (!empty($awsDynamoDBSessionTable)) {
$awsRegionName = Environment::getEnv('AWS_REGION_NAME');
$awsDynamoDBEndpoint = Environment::getEnv('AWS_DYNAMODB_ENDPOINT');
$awsAccessKey = Environment::getEnv('AWS_ACCESS_KEY');
$awsSecretKey = Environment::getEnv('AWS_SECRET_KEY');
$dynamoOptions = array('region' => $awsRegionName);
// This endpoint can be set for locally testing DynamoDB.
// see http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html
if (!empty($awsDynamoDBEndpoint)) {
$dynamoOptions['endpoint'] = $awsDynamoDBEndpoint;
}
if (!empty($awsAccessKey) && !empty($awsSecretKey)) {
$dynamoOptions['credentials']['key'] = $awsAccessKey;
$dynamoOptions['credentials']['secret'] = $awsSecretKey;
} else {
// cache credentials when IAM fetches the credentials from EC2 metadata service
// this will use doctrine/cache (included via composer) to do the actual caching into APCu
// http://docs.aws.amazon.com/aws-sdk-php/guide/latest/performance.html#cache-instance-profile-credentials
$dynamoOptions['credentials'] = new DoctrineCacheAdapter(new ApcuCache());
}
return new static($dynamoOptions, $awsDynamoDBSessionTable);
}
return null;
} | [
"public",
"static",
"function",
"get",
"(",
")",
"{",
"// Use DynamoDB for distributed session storage if it's configured",
"$",
"awsDynamoDBSessionTable",
"=",
"Environment",
"::",
"getEnv",
"(",
"'AWS_DYNAMODB_SESSION_TABLE'",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"... | Get an instance of DynamoDbSession configured from the environment if available.
@return null|DynamoDbSession | [
"Get",
"an",
"instance",
"of",
"DynamoDbSession",
"configured",
"from",
"the",
"environment",
"if",
"available",
"."
] | 785c69771b37636515f6a3b0015d04eab1585ca8 | https://github.com/silverstripe/silverstripe-dynamodb/blob/785c69771b37636515f6a3b0015d04eab1585ca8/code/Model/DynamoDbSession.php#L45-L77 | train |
skie/plum_search | src/Model/Filter/AbstractFilter.php | AbstractFilter.apply | public function apply(Query $query, array $data)
{
if ($this->_applicable($data)) {
$field = $this->config('field');
if (is_string($field) && (strpos($field, '.') === false)) {
$field = $query->repository()->alias() . '.' . $field;
}
return $this->_buildQuery($query, $field, $this->_value($data), $data);
}
return $query;
} | php | public function apply(Query $query, array $data)
{
if ($this->_applicable($data)) {
$field = $this->config('field');
if (is_string($field) && (strpos($field, '.') === false)) {
$field = $query->repository()->alias() . '.' . $field;
}
return $this->_buildQuery($query, $field, $this->_value($data), $data);
}
return $query;
} | [
"public",
"function",
"apply",
"(",
"Query",
"$",
"query",
",",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_applicable",
"(",
"$",
"data",
")",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"config",
"(",
"'field'",
")",
";"... | Apply filter to query based on filter data
@param \Cake\ORM\Query $query Query.
@param array $data Filters values.
@return \Cake\ORM\Query | [
"Apply",
"filter",
"to",
"query",
"based",
"on",
"filter",
"data"
] | 24d981e240bff7c15731981d6f9b3056abdaf80e | https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/Model/Filter/AbstractFilter.php#L63-L75 | train |
skie/plum_search | src/Model/Filter/AbstractFilter.php | AbstractFilter._applicable | protected function _applicable($data)
{
$field = $this->config('name');
return $field && (!empty($data[$field]) || $this->_defaultDefined() || isset($data[$field]) && (string)$data[$field] !== '');
} | php | protected function _applicable($data)
{
$field = $this->config('name');
return $field && (!empty($data[$field]) || $this->_defaultDefined() || isset($data[$field]) && (string)$data[$field] !== '');
} | [
"protected",
"function",
"_applicable",
"(",
"$",
"data",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"config",
"(",
"'name'",
")",
";",
"return",
"$",
"field",
"&&",
"(",
"!",
"empty",
"(",
"$",
"data",
"[",
"$",
"field",
"]",
")",
"||",
"$"... | Check if filter applicable to query based on filter data
@param array $data Array of options as described above.
@return bool | [
"Check",
"if",
"filter",
"applicable",
"to",
"query",
"based",
"on",
"filter",
"data"
] | 24d981e240bff7c15731981d6f9b3056abdaf80e | https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/Model/Filter/AbstractFilter.php#L83-L88 | train |
skie/plum_search | src/Model/Filter/AbstractFilter.php | AbstractFilter._value | protected function _value($data)
{
$field = $this->config('name');
$value = $data[$field];
if (empty($value) && $this->_defaultDefined()) {
$value = $this->config('default');
}
return $value;
} | php | protected function _value($data)
{
$field = $this->config('name');
$value = $data[$field];
if (empty($value) && $this->_defaultDefined()) {
$value = $this->config('default');
}
return $value;
} | [
"protected",
"function",
"_value",
"(",
"$",
"data",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"config",
"(",
"'name'",
")",
";",
"$",
"value",
"=",
"$",
"data",
"[",
"$",
"field",
"]",
";",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
"&&... | Evaluate value of filter parameter
@param array $data Array of options as described above.
@return mixed | [
"Evaluate",
"value",
"of",
"filter",
"parameter"
] | 24d981e240bff7c15731981d6f9b3056abdaf80e | https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/Model/Filter/AbstractFilter.php#L119-L128 | train |
vufind-org/vufindharvest | src/OaiPmh/Communicator.php | Communicator.sendRequest | protected function sendRequest($verb, $params)
{
// Set up the request:
$this->client->resetParameters(false, false); // keep cookies/auth
$this->client->setUri($this->baseUrl);
// Load request parameters:
$query = $this->client->getRequest()->getQuery();
$query->set('verb', $verb);
foreach ($params as $key => $value) {
$query->set($key, $value);
}
// Perform request:
return $this->client->setMethod('GET')->send();
} | php | protected function sendRequest($verb, $params)
{
// Set up the request:
$this->client->resetParameters(false, false); // keep cookies/auth
$this->client->setUri($this->baseUrl);
// Load request parameters:
$query = $this->client->getRequest()->getQuery();
$query->set('verb', $verb);
foreach ($params as $key => $value) {
$query->set($key, $value);
}
// Perform request:
return $this->client->setMethod('GET')->send();
} | [
"protected",
"function",
"sendRequest",
"(",
"$",
"verb",
",",
"$",
"params",
")",
"{",
"// Set up the request:",
"$",
"this",
"->",
"client",
"->",
"resetParameters",
"(",
"false",
",",
"false",
")",
";",
"// keep cookies/auth",
"$",
"this",
"->",
"client",
... | Perform a single OAI-PMH request.
@param string $verb OAI-PMH verb to execute.
@param array $params GET parameters for ListRecords method.
@return string | [
"Perform",
"a",
"single",
"OAI",
"-",
"PMH",
"request",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Communicator.php#L92-L107 | train |
vufind-org/vufindharvest | src/OaiPmh/Communicator.php | Communicator.getOaiResponse | protected function getOaiResponse($verb, $params)
{
// Debug:
$this->write(
"Sending request: verb = {$verb}, params = " . print_r($params, true)
);
// Set up retry loop:
do {
$result = $this->sendRequest($verb, $params);
if ($result->getStatusCode() == 503) {
$delayHeader = $result->getHeaders()->get('Retry-After');
$delay = is_object($delayHeader)
? $delayHeader->getDeltaSeconds() : 0;
if ($delay > 0) {
$this->writeLine(
"Received 503 response; waiting {$delay} seconds..."
);
sleep($delay);
}
} elseif (!$result->isSuccess()) {
throw new \Exception('HTTP Error ' . $result->getStatusCode());
}
} while ($result->getStatusCode() == 503);
// If we got this far, there was no error -- send back response.
return $result->getBody();
} | php | protected function getOaiResponse($verb, $params)
{
// Debug:
$this->write(
"Sending request: verb = {$verb}, params = " . print_r($params, true)
);
// Set up retry loop:
do {
$result = $this->sendRequest($verb, $params);
if ($result->getStatusCode() == 503) {
$delayHeader = $result->getHeaders()->get('Retry-After');
$delay = is_object($delayHeader)
? $delayHeader->getDeltaSeconds() : 0;
if ($delay > 0) {
$this->writeLine(
"Received 503 response; waiting {$delay} seconds..."
);
sleep($delay);
}
} elseif (!$result->isSuccess()) {
throw new \Exception('HTTP Error ' . $result->getStatusCode());
}
} while ($result->getStatusCode() == 503);
// If we got this far, there was no error -- send back response.
return $result->getBody();
} | [
"protected",
"function",
"getOaiResponse",
"(",
"$",
"verb",
",",
"$",
"params",
")",
"{",
"// Debug:",
"$",
"this",
"->",
"write",
"(",
"\"Sending request: verb = {$verb}, params = \"",
".",
"print_r",
"(",
"$",
"params",
",",
"true",
")",
")",
";",
"// Set u... | Make an OAI-PMH request. Throw an exception if there is an error; return
an XML string on success.
@param string $verb OAI-PMH verb to execute.
@param array $params GET parameters for ListRecords method.
@return string | [
"Make",
"an",
"OAI",
"-",
"PMH",
"request",
".",
"Throw",
"an",
"exception",
"if",
"there",
"is",
"an",
"error",
";",
"return",
"an",
"XML",
"string",
"on",
"success",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Communicator.php#L118-L145 | train |
vufind-org/vufindharvest | src/OaiPmh/Communicator.php | Communicator.request | public function request($verb, $params = [])
{
$xml = $this->getOaiResponse($verb, $params);
return $this->responseProcessor
? $this->responseProcessor->process($xml) : $xml;
} | php | public function request($verb, $params = [])
{
$xml = $this->getOaiResponse($verb, $params);
return $this->responseProcessor
? $this->responseProcessor->process($xml) : $xml;
} | [
"public",
"function",
"request",
"(",
"$",
"verb",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"xml",
"=",
"$",
"this",
"->",
"getOaiResponse",
"(",
"$",
"verb",
",",
"$",
"params",
")",
";",
"return",
"$",
"this",
"->",
"responseProcessor",
... | Make an OAI-PMH request. Throw an exception if there is an error; return
the processed response on success.
@param string $verb OAI-PMH verb to execute.
@param array $params GET parameters for ListRecords method.
@return mixed | [
"Make",
"an",
"OAI",
"-",
"PMH",
"request",
".",
"Throw",
"an",
"exception",
"if",
"there",
"is",
"an",
"error",
";",
"return",
"the",
"processed",
"response",
"on",
"success",
"."
] | 43a42d1e2292fbba8974a26ace3d522551a1a88f | https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/Communicator.php#L156-L161 | train |
GW2Treasures/gw2api | src/V2/ApiResponse.php | ApiResponse.json | public function json( array $config = [] ) {
$options = isset($config['big_int_strings']) ? JSON_BIGINT_AS_STRING : 0;
return json_decode($this->response->getBody(), false, 512, $options);
} | php | public function json( array $config = [] ) {
$options = isset($config['big_int_strings']) ? JSON_BIGINT_AS_STRING : 0;
return json_decode($this->response->getBody(), false, 512, $options);
} | [
"public",
"function",
"json",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"=",
"isset",
"(",
"$",
"config",
"[",
"'big_int_strings'",
"]",
")",
"?",
"JSON_BIGINT_AS_STRING",
":",
"0",
";",
"return",
"json_decode",
"(",
"$",
"t... | Get the response as json object.
@param array $config
@return mixed | [
"Get",
"the",
"response",
"as",
"json",
"object",
"."
] | c8795af0c1d0a434b9e530f779d5a95786db2176 | https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/ApiResponse.php#L30-L33 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.setConnectionParams | public function setConnectionParams($params) {
$this->connectionParams = $params;
if (isset($this->connectionParams['dbPrefix'])) {
$this->dbPrefix = $this->connectionParams['dbPrefix'];
}
} | php | public function setConnectionParams($params) {
$this->connectionParams = $params;
if (isset($this->connectionParams['dbPrefix'])) {
$this->dbPrefix = $this->connectionParams['dbPrefix'];
}
} | [
"public",
"function",
"setConnectionParams",
"(",
"$",
"params",
")",
"{",
"$",
"this",
"->",
"connectionParams",
"=",
"$",
"params",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"connectionParams",
"[",
"'dbPrefix'",
"]",
")",
")",
"{",
"$",
"this",... | Set the connection parameters.
@param $params Initialization data given in an associative array with the following keys:
dbType, dbHostName, dbUserName, dbPassword, dbName
if dbPrefix is given it will be appended to every table string, which is
useful if different applications operate on the same database | [
"Set",
"the",
"connection",
"parameters",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L132-L137 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.getMapper | protected static function getMapper($type, $strict=true) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$mapper = $persistenceFacade->getMapper($type);
if ($strict && !($mapper instanceof RDBMapper)) {
throw new PersistenceException('Only PersistenceMappers of type RDBMapper are supported.');
}
return $mapper;
} | php | protected static function getMapper($type, $strict=true) {
$persistenceFacade = ObjectFactory::getInstance('persistenceFacade');
$mapper = $persistenceFacade->getMapper($type);
if ($strict && !($mapper instanceof RDBMapper)) {
throw new PersistenceException('Only PersistenceMappers of type RDBMapper are supported.');
}
return $mapper;
} | [
"protected",
"static",
"function",
"getMapper",
"(",
"$",
"type",
",",
"$",
"strict",
"=",
"true",
")",
"{",
"$",
"persistenceFacade",
"=",
"ObjectFactory",
"::",
"getInstance",
"(",
"'persistenceFacade'",
")",
";",
"$",
"mapper",
"=",
"$",
"persistenceFacade"... | Get the mapper for a Node and optionally check if it is a supported one.
@param $type The type of Node to get the mapper for
@param $strict Boolean indicating if the mapper must be an instance of RDBMapper (default true)
@return RDBMapper instance | [
"Get",
"the",
"mapper",
"for",
"a",
"Node",
"and",
"optionally",
"check",
"if",
"it",
"is",
"a",
"supported",
"one",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L174-L181 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.getSequenceMapper | protected function getSequenceMapper() {
if (self::$sequenceMapper == null) {
self::$sequenceMapper = self::getMapper(self::SEQUENCE_CLASS);
}
return self::$sequenceMapper;
} | php | protected function getSequenceMapper() {
if (self::$sequenceMapper == null) {
self::$sequenceMapper = self::getMapper(self::SEQUENCE_CLASS);
}
return self::$sequenceMapper;
} | [
"protected",
"function",
"getSequenceMapper",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"sequenceMapper",
"==",
"null",
")",
"{",
"self",
"::",
"$",
"sequenceMapper",
"=",
"self",
"::",
"getMapper",
"(",
"self",
"::",
"SEQUENCE_CLASS",
")",
";",
"}",
... | Get the sequence mapper
@return PersistenceMapper | [
"Get",
"the",
"sequence",
"mapper"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L266-L271 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.getNextId | protected function getNextId() {
try {
$sequenceMapper = $this->getSequenceMapper();
$sequenceTable = $sequenceMapper->getRealTableName();
$sequenceConn = $sequenceMapper->getConnection();
$tableName = strtolower($this->getRealTableName());
// run id sequence in it's own transaction, if supported
if (!$this->isFileDB) {
$sequenceConn->beginTransaction();
}
if ($this->idSelectStmt == null) {
$this->idSelectStmt = $sequenceConn->prepare("SELECT ".$this->quoteIdentifier("id").
" FROM ".$this->quoteIdentifier($sequenceTable)." WHERE ".
$this->quoteIdentifier("table")."=".$this->quoteValue($tableName));
}
if ($this->idInsertStmt == null) {
$this->idInsertStmt = $sequenceConn->prepare("INSERT INTO ".
$this->quoteIdentifier($sequenceTable)." (".$this->quoteIdentifier("id").
", ".$this->quoteIdentifier("table").") VALUES (1, ".
$this->quoteValue($tableName).")");
}
if ($this->idUpdateStmt == null) {
$this->idUpdateStmt = $sequenceConn->prepare("UPDATE ".$this->quoteIdentifier($sequenceTable).
" SET ".$this->quoteIdentifier("id")."=(".$this->quoteIdentifier("id")."+1) WHERE ".
$this->quoteIdentifier("table")."=".$this->quoteValue($tableName));
}
$this->idSelectStmt->execute();
$rows = $this->idSelectStmt->fetchAll(PDO::FETCH_ASSOC);
if (sizeof($rows) == 0) {
$this->idInsertStmt->execute();
$this->idInsertStmt->closeCursor();
$rows = [['id' => 1]];
}
$id = $rows[0]['id'];
$this->idUpdateStmt->execute();
$this->idUpdateStmt->closeCursor();
$this->idSelectStmt->closeCursor();
if (!$this->isFileDB) {
$sequenceConn->commit();
}
return $id;
}
catch (\Exception $ex) {
self::$logger->error("The next id query caused the following exception:\n".$ex->getMessage());
throw new PersistenceException("Error in persistent operation. See log file for details.");
}
} | php | protected function getNextId() {
try {
$sequenceMapper = $this->getSequenceMapper();
$sequenceTable = $sequenceMapper->getRealTableName();
$sequenceConn = $sequenceMapper->getConnection();
$tableName = strtolower($this->getRealTableName());
// run id sequence in it's own transaction, if supported
if (!$this->isFileDB) {
$sequenceConn->beginTransaction();
}
if ($this->idSelectStmt == null) {
$this->idSelectStmt = $sequenceConn->prepare("SELECT ".$this->quoteIdentifier("id").
" FROM ".$this->quoteIdentifier($sequenceTable)." WHERE ".
$this->quoteIdentifier("table")."=".$this->quoteValue($tableName));
}
if ($this->idInsertStmt == null) {
$this->idInsertStmt = $sequenceConn->prepare("INSERT INTO ".
$this->quoteIdentifier($sequenceTable)." (".$this->quoteIdentifier("id").
", ".$this->quoteIdentifier("table").") VALUES (1, ".
$this->quoteValue($tableName).")");
}
if ($this->idUpdateStmt == null) {
$this->idUpdateStmt = $sequenceConn->prepare("UPDATE ".$this->quoteIdentifier($sequenceTable).
" SET ".$this->quoteIdentifier("id")."=(".$this->quoteIdentifier("id")."+1) WHERE ".
$this->quoteIdentifier("table")."=".$this->quoteValue($tableName));
}
$this->idSelectStmt->execute();
$rows = $this->idSelectStmt->fetchAll(PDO::FETCH_ASSOC);
if (sizeof($rows) == 0) {
$this->idInsertStmt->execute();
$this->idInsertStmt->closeCursor();
$rows = [['id' => 1]];
}
$id = $rows[0]['id'];
$this->idUpdateStmt->execute();
$this->idUpdateStmt->closeCursor();
$this->idSelectStmt->closeCursor();
if (!$this->isFileDB) {
$sequenceConn->commit();
}
return $id;
}
catch (\Exception $ex) {
self::$logger->error("The next id query caused the following exception:\n".$ex->getMessage());
throw new PersistenceException("Error in persistent operation. See log file for details.");
}
} | [
"protected",
"function",
"getNextId",
"(",
")",
"{",
"try",
"{",
"$",
"sequenceMapper",
"=",
"$",
"this",
"->",
"getSequenceMapper",
"(",
")",
";",
"$",
"sequenceTable",
"=",
"$",
"sequenceMapper",
"->",
"getRealTableName",
"(",
")",
";",
"$",
"sequenceConn"... | Get a new id for inserting into the database
@return An id value. | [
"Get",
"a",
"new",
"id",
"for",
"inserting",
"into",
"the",
"database"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L277-L324 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.executeSql | public function executeSql($sql, $parameters=[]) {
if ($this->adapter == null) {
$this->connect();
}
try {
$stmt = $this->adapter->createStatement($sql, $parameters);
$results = $stmt->execute();
if ($results->isQueryResult()) {
return $results->getResource()->fetchAll();
}
else {
return $results->getAffectedRows();
}
}
catch (\Exception $ex) {
self::$logger->error("The query: ".$sql."\ncaused the following exception:\n".$ex->getMessage());
throw new PersistenceException("Error in persistent operation. See log file for details.");
}
} | php | public function executeSql($sql, $parameters=[]) {
if ($this->adapter == null) {
$this->connect();
}
try {
$stmt = $this->adapter->createStatement($sql, $parameters);
$results = $stmt->execute();
if ($results->isQueryResult()) {
return $results->getResource()->fetchAll();
}
else {
return $results->getAffectedRows();
}
}
catch (\Exception $ex) {
self::$logger->error("The query: ".$sql."\ncaused the following exception:\n".$ex->getMessage());
throw new PersistenceException("Error in persistent operation. See log file for details.");
}
} | [
"public",
"function",
"executeSql",
"(",
"$",
"sql",
",",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"adapter",
"==",
"null",
")",
"{",
"$",
"this",
"->",
"connect",
"(",
")",
";",
"}",
"try",
"{",
"$",
"stmt",
"=... | Execute a query on the connection.
@param $sql The SQL statement as string
@param $parameters An associative array of parameter name/values pairs to replace the placeholders with (optional, default: empty array)
@return If the query is a select, an array of associative arrays containing the selected data,
the number of affected rows else | [
"Execute",
"a",
"query",
"on",
"the",
"connection",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L370-L388 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.initRelations | private function initRelations() {
if ($this->relations == null) {
$this->relations = [];
$this->relations['all'] = array_values($this->getRelationDescriptions());
$this->relations['parent'] = [];
$this->relations['child'] = [];
$this->relations['undefined'] = [];
$this->relations['nm'] = [];
foreach ($this->relations['all'] as $relation) {
$hierarchyType = $relation->getHierarchyType();
$hierarchyKey = $hierarchyType == 'parent' || $hierarchyType == 'child' ?
$hierarchyType : 'undefined';
$this->relations[$hierarchyKey][] = $relation;
// also store relations to many to many objects, because
// they would be invisible otherwise
if ($relation instanceof RDBManyToManyRelationDescription) {
$nmRelation = $relation->getThisEndRelation();
$this->relations['nm'][$nmRelation->getOtherRole()] = $nmRelation;
}
}
}
} | php | private function initRelations() {
if ($this->relations == null) {
$this->relations = [];
$this->relations['all'] = array_values($this->getRelationDescriptions());
$this->relations['parent'] = [];
$this->relations['child'] = [];
$this->relations['undefined'] = [];
$this->relations['nm'] = [];
foreach ($this->relations['all'] as $relation) {
$hierarchyType = $relation->getHierarchyType();
$hierarchyKey = $hierarchyType == 'parent' || $hierarchyType == 'child' ?
$hierarchyType : 'undefined';
$this->relations[$hierarchyKey][] = $relation;
// also store relations to many to many objects, because
// they would be invisible otherwise
if ($relation instanceof RDBManyToManyRelationDescription) {
$nmRelation = $relation->getThisEndRelation();
$this->relations['nm'][$nmRelation->getOtherRole()] = $nmRelation;
}
}
}
} | [
"private",
"function",
"initRelations",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"relations",
"==",
"null",
")",
"{",
"$",
"this",
"->",
"relations",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"relations",
"[",
"'all'",
"]",
"=",
"array_values",
"(",... | Get the relation descriptions defined in the subclass and add them to internal arrays. | [
"Get",
"the",
"relation",
"descriptions",
"defined",
"in",
"the",
"subclass",
"and",
"add",
"them",
"to",
"internal",
"arrays",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L512-L535 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.loadObjectsFromQueryParts | protected function loadObjectsFromQueryParts($type, $buildDepth=BuildDepth::SINGLE, $criteria=null, $orderby=null, PagingInfo $pagingInfo=null) {
if ($buildDepth < 0 && !in_array($buildDepth, [BuildDepth::INFINITE, BuildDepth::SINGLE])) {
throw new IllegalArgumentException("Build depth not supported: $buildDepth");
}
// create query
$selectStmt = $this->getSelectSQL($criteria, null, null, $orderby, $pagingInfo);
$objects = $this->loadObjectsFromSQL($selectStmt, $buildDepth, $pagingInfo);
return $objects;
} | php | protected function loadObjectsFromQueryParts($type, $buildDepth=BuildDepth::SINGLE, $criteria=null, $orderby=null, PagingInfo $pagingInfo=null) {
if ($buildDepth < 0 && !in_array($buildDepth, [BuildDepth::INFINITE, BuildDepth::SINGLE])) {
throw new IllegalArgumentException("Build depth not supported: $buildDepth");
}
// create query
$selectStmt = $this->getSelectSQL($criteria, null, null, $orderby, $pagingInfo);
$objects = $this->loadObjectsFromSQL($selectStmt, $buildDepth, $pagingInfo);
return $objects;
} | [
"protected",
"function",
"loadObjectsFromQueryParts",
"(",
"$",
"type",
",",
"$",
"buildDepth",
"=",
"BuildDepth",
"::",
"SINGLE",
",",
"$",
"criteria",
"=",
"null",
",",
"$",
"orderby",
"=",
"null",
",",
"PagingInfo",
"$",
"pagingInfo",
"=",
"null",
")",
... | Load objects defined by several query parts.
@param $type The type of the object
@param $buildDepth One of the BUILDDEPTH constants or a number describing the number of generations to build
(except BuildDepth::REQUIRED, BuildDepth::PROXIES_ONLY) (default: BuildDepth::SINGLE)
@param $criteria An array of Criteria instances that define conditions on the type's attributes (optional, default: _null_)
@param $orderby An array holding names of attributes to order by, maybe appended with 'ASC', 'DESC' (optional, default: _null_)
@param $pagingInfo A reference PagingInfo instance (optional, default: _null_)
@return Array of PersistentObject instances | [
"Load",
"objects",
"defined",
"by",
"several",
"query",
"parts",
"."
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L885-L895 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.createObjectFromData | protected function createObjectFromData(array $data) {
// determine if we are loading or creating
$createFromLoadedData = (sizeof($data) > 0) ? true : false;
// initialize data and oid
$oid = null;
$initialData = $data;
if ($createFromLoadedData) {
$oid = $this->constructOID($initialData);
// cleanup data
foreach($initialData as $name => $value) {
if ($this->hasAttribute($name) || strpos($name, self::INTERNAL_VALUE_PREFIX) === 0) {
$value = $this->convertValueFromStorage($name, $value);
$initialData[$name] = $value;
}
else {
unset($initialData[$name]);
}
}
}
// construct object
$object = $this->createObject($oid, $initialData);
return $object;
} | php | protected function createObjectFromData(array $data) {
// determine if we are loading or creating
$createFromLoadedData = (sizeof($data) > 0) ? true : false;
// initialize data and oid
$oid = null;
$initialData = $data;
if ($createFromLoadedData) {
$oid = $this->constructOID($initialData);
// cleanup data
foreach($initialData as $name => $value) {
if ($this->hasAttribute($name) || strpos($name, self::INTERNAL_VALUE_PREFIX) === 0) {
$value = $this->convertValueFromStorage($name, $value);
$initialData[$name] = $value;
}
else {
unset($initialData[$name]);
}
}
}
// construct object
$object = $this->createObject($oid, $initialData);
return $object;
} | [
"protected",
"function",
"createObjectFromData",
"(",
"array",
"$",
"data",
")",
"{",
"// determine if we are loading or creating",
"$",
"createFromLoadedData",
"=",
"(",
"sizeof",
"(",
"$",
"data",
")",
">",
"0",
")",
"?",
"true",
":",
"false",
";",
"// initial... | Create an object of the mapper's type with the given attributes from the given data
@param $data An associative array with the attribute names as keys and the attribute values as values
@return PersistentObject | [
"Create",
"an",
"object",
"of",
"the",
"mapper",
"s",
"type",
"with",
"the",
"given",
"attributes",
"from",
"the",
"given",
"data"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L950-L974 | train |
iherwig/wcmf | src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php | AbstractRDBMapper.convertValueFromStorage | protected function convertValueFromStorage($valueName, $value) {
// filter values according to type
if ($this->hasAttribute($valueName)) {
$type = $this->getAttribute($valueName)->getType();
// integer
if (strpos(strtolower($type), 'int') === 0) {
$value = (strlen($value) == 0) ? null : intval($value);
}
}
return $value;
} | php | protected function convertValueFromStorage($valueName, $value) {
// filter values according to type
if ($this->hasAttribute($valueName)) {
$type = $this->getAttribute($valueName)->getType();
// integer
if (strpos(strtolower($type), 'int') === 0) {
$value = (strlen($value) == 0) ? null : intval($value);
}
}
return $value;
} | [
"protected",
"function",
"convertValueFromStorage",
"(",
"$",
"valueName",
",",
"$",
"value",
")",
"{",
"// filter values according to type",
"if",
"(",
"$",
"this",
"->",
"hasAttribute",
"(",
"$",
"valueName",
")",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"... | Convert value after retrieval from storage
@param $valueName
@param $value
@return Mixed | [
"Convert",
"value",
"after",
"retrieval",
"from",
"storage"
] | 2542b8d4139464d39a9a8ce8a954dfecf700c41b | https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L982-L992 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.