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
doctrine/skeleton-mapper
lib/Doctrine/SkeletonMapper/Persister/BasicObjectPersister.php
BasicObjectPersister.prepareUpdateChangeSet
public function prepareUpdateChangeSet($object, ChangeSet $changeSet) : array { if (! $object instanceof PersistableInterface) { throw new InvalidArgumentException(sprintf('%s must implement PersistableInterface.', get_class($object))); } return $object->prepareUpdateChangeSet($changeSet); }
php
public function prepareUpdateChangeSet($object, ChangeSet $changeSet) : array { if (! $object instanceof PersistableInterface) { throw new InvalidArgumentException(sprintf('%s must implement PersistableInterface.', get_class($object))); } return $object->prepareUpdateChangeSet($changeSet); }
[ "public", "function", "prepareUpdateChangeSet", "(", "$", "object", ",", "ChangeSet", "$", "changeSet", ")", ":", "array", "{", "if", "(", "!", "$", "object", "instanceof", "PersistableInterface", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprin...
Prepares an object changeset for update. @param object $object @return mixed[]
[ "Prepares", "an", "object", "changeset", "for", "update", "." ]
478c0fafcdc2df37159193b74fedaf89643891eb
https://github.com/doctrine/skeleton-mapper/blob/478c0fafcdc2df37159193b74fedaf89643891eb/lib/Doctrine/SkeletonMapper/Persister/BasicObjectPersister.php#L70-L77
train
doctrine/skeleton-mapper
lib/Doctrine/SkeletonMapper/Persister/BasicObjectPersister.php
BasicObjectPersister.assignIdentifier
public function assignIdentifier($object, array $identifier) : void { if (! $object instanceof IdentifiableInterface) { throw new InvalidArgumentException(sprintf('%s must implement IdentifiableInterface.', get_class($object))); } $object->assignIdentifier($identifier); }
php
public function assignIdentifier($object, array $identifier) : void { if (! $object instanceof IdentifiableInterface) { throw new InvalidArgumentException(sprintf('%s must implement IdentifiableInterface.', get_class($object))); } $object->assignIdentifier($identifier); }
[ "public", "function", "assignIdentifier", "(", "$", "object", ",", "array", "$", "identifier", ")", ":", "void", "{", "if", "(", "!", "$", "object", "instanceof", "IdentifiableInterface", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(...
Assign identifier to object. @param object $object @param mixed[] $identifier
[ "Assign", "identifier", "to", "object", "." ]
478c0fafcdc2df37159193b74fedaf89643891eb
https://github.com/doctrine/skeleton-mapper/blob/478c0fafcdc2df37159193b74fedaf89643891eb/lib/Doctrine/SkeletonMapper/Persister/BasicObjectPersister.php#L85-L92
train
doctrine/skeleton-mapper
lib/Doctrine/SkeletonMapper/UnitOfWork.php
UnitOfWork.commit
public function commit() : void { $this->eventDispatcher->dispatchPreFlush(); if ($this->objectsToPersist === [] && $this->objectsToUpdate === [] && $this->objectsToRemove === [] ) { return; // Nothing to do. } $objects = array_merge( $this->objectsToPersist, $this->objectsToUpdate, $this->objectsToRemove ); $this->eventDispatcher->dispatchPreFlushLifecycleCallbacks($objects); $this->eventDispatcher->dispatchOnFlush(); $this->persister->executePersists(); $this->persister->executeUpdates(); $this->persister->executeRemoves(); $this->eventDispatcher->dispatchPostFlush(); $this->objectsToPersist = []; $this->objectsToUpdate = []; $this->objectsToRemove = []; $this->objectChangeSets = new ChangeSets(); }
php
public function commit() : void { $this->eventDispatcher->dispatchPreFlush(); if ($this->objectsToPersist === [] && $this->objectsToUpdate === [] && $this->objectsToRemove === [] ) { return; // Nothing to do. } $objects = array_merge( $this->objectsToPersist, $this->objectsToUpdate, $this->objectsToRemove ); $this->eventDispatcher->dispatchPreFlushLifecycleCallbacks($objects); $this->eventDispatcher->dispatchOnFlush(); $this->persister->executePersists(); $this->persister->executeUpdates(); $this->persister->executeRemoves(); $this->eventDispatcher->dispatchPostFlush(); $this->objectsToPersist = []; $this->objectsToUpdate = []; $this->objectsToRemove = []; $this->objectChangeSets = new ChangeSets(); }
[ "public", "function", "commit", "(", ")", ":", "void", "{", "$", "this", "->", "eventDispatcher", "->", "dispatchPreFlush", "(", ")", ";", "if", "(", "$", "this", "->", "objectsToPersist", "===", "[", "]", "&&", "$", "this", "->", "objectsToUpdate", "===...
Commit the contents of the unit of work.
[ "Commit", "the", "contents", "of", "the", "unit", "of", "work", "." ]
478c0fafcdc2df37159193b74fedaf89643891eb
https://github.com/doctrine/skeleton-mapper/blob/478c0fafcdc2df37159193b74fedaf89643891eb/lib/Doctrine/SkeletonMapper/UnitOfWork.php#L177-L207
train
doctrine/skeleton-mapper
lib/Doctrine/SkeletonMapper/UnitOfWork.php
UnitOfWork.propertyChanged
public function propertyChanged($object, $propertyName, $oldValue, $newValue) : void { if (! $this->isInIdentityMap($object)) { return; } if (! $this->isScheduledForUpdate($object)) { $this->update($object); } $this->objectChangeSets->addObjectChange( $object, new Change($propertyName, $oldValue, $newValue) ); }
php
public function propertyChanged($object, $propertyName, $oldValue, $newValue) : void { if (! $this->isInIdentityMap($object)) { return; } if (! $this->isScheduledForUpdate($object)) { $this->update($object); } $this->objectChangeSets->addObjectChange( $object, new Change($propertyName, $oldValue, $newValue) ); }
[ "public", "function", "propertyChanged", "(", "$", "object", ",", "$", "propertyName", ",", "$", "oldValue", ",", "$", "newValue", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "isInIdentityMap", "(", "$", "object", ")", ")", "{", "return",...
Notifies this UnitOfWork of a property change in an object. @param object $object The entity that owns the property. @param string $propertyName The name of the property that changed. @param mixed $oldValue The old value of the property. @param mixed $newValue The new value of the property.
[ "Notifies", "this", "UnitOfWork", "of", "a", "property", "change", "in", "an", "object", "." ]
478c0fafcdc2df37159193b74fedaf89643891eb
https://github.com/doctrine/skeleton-mapper/blob/478c0fafcdc2df37159193b74fedaf89643891eb/lib/Doctrine/SkeletonMapper/UnitOfWork.php#L267-L281
train
doctrine/skeleton-mapper
lib/Doctrine/SkeletonMapper/Event/PreUpdateEventArgs.php
PreUpdateEventArgs.getOldValue
public function getOldValue(string $field) { $change = $this->objectChangeSet->getFieldChange($field); if ($change !== null) { return $change->getOldValue(); } }
php
public function getOldValue(string $field) { $change = $this->objectChangeSet->getFieldChange($field); if ($change !== null) { return $change->getOldValue(); } }
[ "public", "function", "getOldValue", "(", "string", "$", "field", ")", "{", "$", "change", "=", "$", "this", "->", "objectChangeSet", "->", "getFieldChange", "(", "$", "field", ")", ";", "if", "(", "$", "change", "!==", "null", ")", "{", "return", "$",...
Gets the old value of the changeset of the changed field. @return mixed
[ "Gets", "the", "old", "value", "of", "the", "changeset", "of", "the", "changed", "field", "." ]
478c0fafcdc2df37159193b74fedaf89643891eb
https://github.com/doctrine/skeleton-mapper/blob/478c0fafcdc2df37159193b74fedaf89643891eb/lib/Doctrine/SkeletonMapper/Event/PreUpdateEventArgs.php#L52-L59
train
doctrine/skeleton-mapper
lib/Doctrine/SkeletonMapper/Event/PreUpdateEventArgs.php
PreUpdateEventArgs.getNewValue
public function getNewValue(string $field) { $change = $this->objectChangeSet->getFieldChange($field); if ($change !== null) { return $change->getNewValue(); } }
php
public function getNewValue(string $field) { $change = $this->objectChangeSet->getFieldChange($field); if ($change !== null) { return $change->getNewValue(); } }
[ "public", "function", "getNewValue", "(", "string", "$", "field", ")", "{", "$", "change", "=", "$", "this", "->", "objectChangeSet", "->", "getFieldChange", "(", "$", "field", ")", ";", "if", "(", "$", "change", "!==", "null", ")", "{", "return", "$",...
Gets the new value of the changeset of the changed field. @return mixed
[ "Gets", "the", "new", "value", "of", "the", "changeset", "of", "the", "changed", "field", "." ]
478c0fafcdc2df37159193b74fedaf89643891eb
https://github.com/doctrine/skeleton-mapper/blob/478c0fafcdc2df37159193b74fedaf89643891eb/lib/Doctrine/SkeletonMapper/Event/PreUpdateEventArgs.php#L66-L73
train
doctrine/skeleton-mapper
lib/Doctrine/SkeletonMapper/ObjectRepository/ObjectRepository.php
ObjectRepository.findAll
public function findAll() : array { $objectsData = $this->objectDataRepository->findAll(); $objects = []; foreach ($objectsData as $objectData) { $object = $this->getOrCreateObject($objectData); if ($object === null) { throw new InvalidArgumentException('Could not create object.'); } $objects[] = $object; } return $objects; }
php
public function findAll() : array { $objectsData = $this->objectDataRepository->findAll(); $objects = []; foreach ($objectsData as $objectData) { $object = $this->getOrCreateObject($objectData); if ($object === null) { throw new InvalidArgumentException('Could not create object.'); } $objects[] = $object; } return $objects; }
[ "public", "function", "findAll", "(", ")", ":", "array", "{", "$", "objectsData", "=", "$", "this", "->", "objectDataRepository", "->", "findAll", "(", ")", ";", "$", "objects", "=", "[", "]", ";", "foreach", "(", "$", "objectsData", "as", "$", "object...
Finds all objects in the repository. @return object[] The objects.
[ "Finds", "all", "objects", "in", "the", "repository", "." ]
478c0fafcdc2df37159193b74fedaf89643891eb
https://github.com/doctrine/skeleton-mapper/blob/478c0fafcdc2df37159193b74fedaf89643891eb/lib/Doctrine/SkeletonMapper/ObjectRepository/ObjectRepository.php#L90-L106
train
Elao/WebProfilerExtraBundle
DataCollector/AsseticDataCollector.php
AsseticDataCollector.collect
public function collect(Request $request, Response $response, \Exception $exception = null) { $collections = array(); foreach ($this->getAssetManager()->getNames() as $name) { $collection = $this->getAssetManager()->get($name); $assets = array(); $filters = array(); foreach ($collection->all() as $asset) { $assets[] = $asset->getSourcePath(); } foreach ($collection->getFilters() as $filter) { $filters[] = get_class($filter); } $collections[$name] = array( 'target' => $collection->getTargetPath(), 'assets' => $assets, 'filters' => $filters ); } $this->data['collections'] = $collections; }
php
public function collect(Request $request, Response $response, \Exception $exception = null) { $collections = array(); foreach ($this->getAssetManager()->getNames() as $name) { $collection = $this->getAssetManager()->get($name); $assets = array(); $filters = array(); foreach ($collection->all() as $asset) { $assets[] = $asset->getSourcePath(); } foreach ($collection->getFilters() as $filter) { $filters[] = get_class($filter); } $collections[$name] = array( 'target' => $collection->getTargetPath(), 'assets' => $assets, 'filters' => $filters ); } $this->data['collections'] = $collections; }
[ "public", "function", "collect", "(", "Request", "$", "request", ",", "Response", "$", "response", ",", "\\", "Exception", "$", "exception", "=", "null", ")", "{", "$", "collections", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "get...
Collect assets informations from Assetic Asset Manager @param Request $request The Request Object @param Response $response The Response Object @param \Exception $exception Exception
[ "Collect", "assets", "informations", "from", "Assetic", "Asset", "Manager" ]
edbcd31a3e0b0940b0ed0301d467f2419280d679
https://github.com/Elao/WebProfilerExtraBundle/blob/edbcd31a3e0b0940b0ed0301d467f2419280d679/DataCollector/AsseticDataCollector.php#L45-L70
train
Elao/WebProfilerExtraBundle
DataCollector/ContainerDataCollector.php
ContainerDataCollector.collect
public function collect(Request $request, Response $response, \Exception $exception = null) { $parameters = array(); $services = array(); $this->loadContainerBuilder(); if ($this->containerBuilder !== false) { foreach ($this->containerBuilder->getParameterBag()->all() as $key => $value) { $service = substr($key, 0, strpos($key, '.')); if (!isset($parameters[$service])) { $parameters[$service] = array(); } $parameters[$service][$key] = $value; } $serviceIds = $this->containerBuilder->getServiceIds(); foreach ($serviceIds as $serviceId) { $definition = $this->resolveServiceDefinition($serviceId); if ($definition instanceof Definition && $definition->isPublic()) { $services[$serviceId] = array('class' => $definition->getClass()); } elseif ($definition instanceof Alias) { $services[$serviceId] = array('alias' => $definition); } else { continue; // We don't want private services } } ksort($services); ksort($parameters); } $this->data['parameters'] = $parameters; $this->data['services'] = $services; }
php
public function collect(Request $request, Response $response, \Exception $exception = null) { $parameters = array(); $services = array(); $this->loadContainerBuilder(); if ($this->containerBuilder !== false) { foreach ($this->containerBuilder->getParameterBag()->all() as $key => $value) { $service = substr($key, 0, strpos($key, '.')); if (!isset($parameters[$service])) { $parameters[$service] = array(); } $parameters[$service][$key] = $value; } $serviceIds = $this->containerBuilder->getServiceIds(); foreach ($serviceIds as $serviceId) { $definition = $this->resolveServiceDefinition($serviceId); if ($definition instanceof Definition && $definition->isPublic()) { $services[$serviceId] = array('class' => $definition->getClass()); } elseif ($definition instanceof Alias) { $services[$serviceId] = array('alias' => $definition); } else { continue; // We don't want private services } } ksort($services); ksort($parameters); } $this->data['parameters'] = $parameters; $this->data['services'] = $services; }
[ "public", "function", "collect", "(", "Request", "$", "request", ",", "Response", "$", "response", ",", "\\", "Exception", "$", "exception", "=", "null", ")", "{", "$", "parameters", "=", "array", "(", ")", ";", "$", "services", "=", "array", "(", ")",...
Collect information about services and parameters from the cached dumped xml container @param Request $request The Request Object @param Response $response The Response Object @param \Exception $exception The Exception
[ "Collect", "information", "about", "services", "and", "parameters", "from", "the", "cached", "dumped", "xml", "container" ]
edbcd31a3e0b0940b0ed0301d467f2419280d679
https://github.com/Elao/WebProfilerExtraBundle/blob/edbcd31a3e0b0940b0ed0301d467f2419280d679/DataCollector/ContainerDataCollector.php#L68-L102
train
Elao/WebProfilerExtraBundle
DataCollector/RoutingDataCollector.php
RoutingDataCollector.collect
public function collect(Request $request, Response $response, \Exception $exception = null) { $collection = $this->router->getRouteCollection(); $_ressources = $collection->getResources(); $_routes = $collection->all(); $routes = array(); $ressources = array(); foreach ($_ressources as $ressource) { $ressources[] = array( 'type' => get_class($ressource), 'path' => $ressource->__toString() ); } foreach ($_routes as $routeName => $route) { $defaults = $route->getDefaults(); $requirements = $route->getRequirements(); $controller = isset($defaults['_controller']) ? $defaults['_controller'] : 'unknown'; $routes[$routeName] = array( 'name' => $routeName, 'pattern' => $route->getPath(), 'controller' => $controller, 'method' => isset($requirements['_method']) ? $requirements['_method'] : 'ANY', ); } ksort($routes); $this->data['matchRoute'] = $request->attributes->get('_route'); $this->data['routes'] = $routes; $this->data['ressources'] = $ressources; }
php
public function collect(Request $request, Response $response, \Exception $exception = null) { $collection = $this->router->getRouteCollection(); $_ressources = $collection->getResources(); $_routes = $collection->all(); $routes = array(); $ressources = array(); foreach ($_ressources as $ressource) { $ressources[] = array( 'type' => get_class($ressource), 'path' => $ressource->__toString() ); } foreach ($_routes as $routeName => $route) { $defaults = $route->getDefaults(); $requirements = $route->getRequirements(); $controller = isset($defaults['_controller']) ? $defaults['_controller'] : 'unknown'; $routes[$routeName] = array( 'name' => $routeName, 'pattern' => $route->getPath(), 'controller' => $controller, 'method' => isset($requirements['_method']) ? $requirements['_method'] : 'ANY', ); } ksort($routes); $this->data['matchRoute'] = $request->attributes->get('_route'); $this->data['routes'] = $routes; $this->data['ressources'] = $ressources; }
[ "public", "function", "collect", "(", "Request", "$", "request", ",", "Response", "$", "response", ",", "\\", "Exception", "$", "exception", "=", "null", ")", "{", "$", "collection", "=", "$", "this", "->", "router", "->", "getRouteCollection", "(", ")", ...
Collects the Information on the Route @param Request $request The Request Object @param Response $response The Response Object @param \Exception $exception The Exception
[ "Collects", "the", "Information", "on", "the", "Route" ]
edbcd31a3e0b0940b0ed0301d467f2419280d679
https://github.com/Elao/WebProfilerExtraBundle/blob/edbcd31a3e0b0940b0ed0301d467f2419280d679/DataCollector/RoutingDataCollector.php#L47-L79
train
Elao/WebProfilerExtraBundle
DataCollector/TwigDataCollector.php
TwigDataCollector.collect
public function collect(Request $request, Response $response, \Exception $exception = null) { $filters = array(); $tests = array(); $extensions = array(); $functions = array(); foreach ($this->getTwig()->getExtensions() as $extensionName => $extension) { $extensions[] = array( 'name' => $extensionName, 'class' => get_class($extension) ); foreach ($extension->getFilters() as $filterName => $filter) { if ($filter instanceof \Twig_FilterInterface) { $call = $filter->compile(); if (is_array($call) && is_callable($call)) { $call = 'Method '.$call[1].' of an object '.get_class($call[0]); } } else { $call = $filter->getName(); } $filters[] = array( 'name' => $filterName, 'extension' => $extensionName, 'call' => $call, ); } foreach ($extension->getTests() as $testName => $test) { if ($test instanceof \Twig_TestInterface) { $call = $test->compile(); } else { $call = $test->getName(); } $tests[] = array( 'name' => $testName, 'extension' => $extensionName, 'call' => $call, ); } foreach ($extension->getFunctions() as $functionName => $function) { if ($function instanceof \Twig_FunctionInterface) { $call = $function->compile(); } else { $call = $function->getName(); } $functions[] = array( 'name' => $functionName, 'extension' => $extensionName, 'call' => $call, ); } } $globals = array(); foreach ($this->getTwig()->getGlobals() as $globalName => $global) { $globals[] = array( 'name' => $globalName, 'value' => $this->getVarDump($global), ); } $this->data['globals'] = $globals; $this->data['extensions'] = $extensions; $this->data['tests'] = $tests; $this->data['filters'] = $filters; $this->data['functions'] = $functions; }
php
public function collect(Request $request, Response $response, \Exception $exception = null) { $filters = array(); $tests = array(); $extensions = array(); $functions = array(); foreach ($this->getTwig()->getExtensions() as $extensionName => $extension) { $extensions[] = array( 'name' => $extensionName, 'class' => get_class($extension) ); foreach ($extension->getFilters() as $filterName => $filter) { if ($filter instanceof \Twig_FilterInterface) { $call = $filter->compile(); if (is_array($call) && is_callable($call)) { $call = 'Method '.$call[1].' of an object '.get_class($call[0]); } } else { $call = $filter->getName(); } $filters[] = array( 'name' => $filterName, 'extension' => $extensionName, 'call' => $call, ); } foreach ($extension->getTests() as $testName => $test) { if ($test instanceof \Twig_TestInterface) { $call = $test->compile(); } else { $call = $test->getName(); } $tests[] = array( 'name' => $testName, 'extension' => $extensionName, 'call' => $call, ); } foreach ($extension->getFunctions() as $functionName => $function) { if ($function instanceof \Twig_FunctionInterface) { $call = $function->compile(); } else { $call = $function->getName(); } $functions[] = array( 'name' => $functionName, 'extension' => $extensionName, 'call' => $call, ); } } $globals = array(); foreach ($this->getTwig()->getGlobals() as $globalName => $global) { $globals[] = array( 'name' => $globalName, 'value' => $this->getVarDump($global), ); } $this->data['globals'] = $globals; $this->data['extensions'] = $extensions; $this->data['tests'] = $tests; $this->data['filters'] = $filters; $this->data['functions'] = $functions; }
[ "public", "function", "collect", "(", "Request", "$", "request", ",", "Response", "$", "response", ",", "\\", "Exception", "$", "exception", "=", "null", ")", "{", "$", "filters", "=", "array", "(", ")", ";", "$", "tests", "=", "array", "(", ")", ";"...
Collect information from Twig @param Request $request The Request Object @param Response $response The Response Object @param \Exception $exception The Exception
[ "Collect", "information", "from", "Twig" ]
edbcd31a3e0b0940b0ed0301d467f2419280d679
https://github.com/Elao/WebProfilerExtraBundle/blob/edbcd31a3e0b0940b0ed0301d467f2419280d679/DataCollector/TwigDataCollector.php#L46-L118
train
Elao/WebProfilerExtraBundle
DataCollector/TwigDataCollector.php
TwigDataCollector.collectTemplateData
public function collectTemplateData($templateName, $parameters, $templatePath = null) { $collectedParameters = array(); foreach ($parameters as $name => $value) { $collectedParameters[$name] = array( 'type' => in_array(gettype($value), array('object', 'resource')) ? get_class($value) : gettype($value), 'value' => in_array(gettype($value), array('object', 'resource', 'array')) ? null : $value, ); } $this->data['templates'][] = array( 'name' => $templateName, 'path' => $templatePath, 'parameters' => $collectedParameters ); }
php
public function collectTemplateData($templateName, $parameters, $templatePath = null) { $collectedParameters = array(); foreach ($parameters as $name => $value) { $collectedParameters[$name] = array( 'type' => in_array(gettype($value), array('object', 'resource')) ? get_class($value) : gettype($value), 'value' => in_array(gettype($value), array('object', 'resource', 'array')) ? null : $value, ); } $this->data['templates'][] = array( 'name' => $templateName, 'path' => $templatePath, 'parameters' => $collectedParameters ); }
[ "public", "function", "collectTemplateData", "(", "$", "templateName", ",", "$", "parameters", ",", "$", "templatePath", "=", "null", ")", "{", "$", "collectedParameters", "=", "array", "(", ")", ";", "foreach", "(", "$", "parameters", "as", "$", "name", "...
Collects data on the twig templates rendered @param mixed $templateName The template name @param array $parameters The array of parameters passed to the template @param array $templatePath The template path
[ "Collects", "data", "on", "the", "twig", "templates", "rendered" ]
edbcd31a3e0b0940b0ed0301d467f2419280d679
https://github.com/Elao/WebProfilerExtraBundle/blob/edbcd31a3e0b0940b0ed0301d467f2419280d679/DataCollector/TwigDataCollector.php#L145-L160
train
Elao/WebProfilerExtraBundle
DataCollector/TwigDataCollector.php
TwigDataCollector.getVarDump
protected function getVarDump($var) { $varType = gettype($var); switch ($varType) { case 'boolean': case 'integer': case 'double': case 'NULL': case 'ressource': return print_r($var, 1); case 'string': return (250 < strlen($var)) ? substr($var, 0, 250).'...' : $var; case 'object': return 'Object instance of ' . get_class($var); case 'array': $formated_array = array(); foreach ($var as $key => $value) { $formated_array[$key] = $this->getVarDump($value); } return print_r($formated_array, 1); } }
php
protected function getVarDump($var) { $varType = gettype($var); switch ($varType) { case 'boolean': case 'integer': case 'double': case 'NULL': case 'ressource': return print_r($var, 1); case 'string': return (250 < strlen($var)) ? substr($var, 0, 250).'...' : $var; case 'object': return 'Object instance of ' . get_class($var); case 'array': $formated_array = array(); foreach ($var as $key => $value) { $formated_array[$key] = $this->getVarDump($value); } return print_r($formated_array, 1); } }
[ "protected", "function", "getVarDump", "(", "$", "var", ")", "{", "$", "varType", "=", "gettype", "(", "$", "var", ")", ";", "switch", "(", "$", "varType", ")", "{", "case", "'boolean'", ":", "case", "'integer'", ":", "case", "'double'", ":", "case", ...
Returns var_dump like of a variable but avoiding flood dumping @return string Formated var_dump
[ "Returns", "var_dump", "like", "of", "a", "variable", "but", "avoiding", "flood", "dumping" ]
edbcd31a3e0b0940b0ed0301d467f2419280d679
https://github.com/Elao/WebProfilerExtraBundle/blob/edbcd31a3e0b0940b0ed0301d467f2419280d679/DataCollector/TwigDataCollector.php#L290-L313
train
blongden/hal
src/HalLinkContainer.php
HalLinkContainer.get
public function get($rel) { if (array_key_exists($rel, $this)) { return $this[$rel]; } if (isset($this['curies'])) { foreach ($this['curies'] as $link) { $prefix = strstr($link->getUri(), '{rel}', true); if (strpos($rel, $prefix) === 0) { // looks like it is $shortrel = substr($rel, strlen($prefix)); $attrs = $link->getAttributes(); $curie = "{$attrs['name']}:$shortrel"; if (isset($this[$curie])) { return $this[$curie]; } } } } return false; }
php
public function get($rel) { if (array_key_exists($rel, $this)) { return $this[$rel]; } if (isset($this['curies'])) { foreach ($this['curies'] as $link) { $prefix = strstr($link->getUri(), '{rel}', true); if (strpos($rel, $prefix) === 0) { // looks like it is $shortrel = substr($rel, strlen($prefix)); $attrs = $link->getAttributes(); $curie = "{$attrs['name']}:$shortrel"; if (isset($this[$curie])) { return $this[$curie]; } } } } return false; }
[ "public", "function", "get", "(", "$", "rel", ")", "{", "if", "(", "array_key_exists", "(", "$", "rel", ",", "$", "this", ")", ")", "{", "return", "$", "this", "[", "$", "rel", "]", ";", "}", "if", "(", "isset", "(", "$", "this", "[", "'curies'...
Retrieve a link from the container by rel. Also resolve any curie links if they are set. @param string $rel The link relation required. @return array|bool Link if found. Otherwise false.
[ "Retrieve", "a", "link", "from", "the", "container", "by", "rel", ".", "Also", "resolve", "any", "curie", "links", "if", "they", "are", "set", "." ]
84ddd8b5db2cc07cae7f14c72838bd1d0042ddce
https://github.com/blongden/hal/blob/84ddd8b5db2cc07cae7f14c72838bd1d0042ddce/src/HalLinkContainer.php#L32-L54
train
php-enqueue/fs
LegacyFilesystemLock.php
LockHandler.lock
public function lock($blocking = false) { if ($this->handle) { return true; } $error = null; // Silence error reporting set_error_handler(function ($errno, $msg) use (&$error) { $error = $msg; }); if (!$this->handle = fopen($this->file, 'r')) { if ($this->handle = fopen($this->file, 'x')) { chmod($this->file, 0444); } elseif (!$this->handle = fopen($this->file, 'r')) { usleep(100); // Give some time for chmod() to complete $this->handle = fopen($this->file, 'r'); } } restore_error_handler(); if (!$this->handle) { throw new IOException($error, 0, null, $this->file); } // On Windows, even if PHP doc says the contrary, LOCK_NB works, see // https://bugs.php.net/54129 if (!flock($this->handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) { fclose($this->handle); $this->handle = null; return false; } return true; }
php
public function lock($blocking = false) { if ($this->handle) { return true; } $error = null; // Silence error reporting set_error_handler(function ($errno, $msg) use (&$error) { $error = $msg; }); if (!$this->handle = fopen($this->file, 'r')) { if ($this->handle = fopen($this->file, 'x')) { chmod($this->file, 0444); } elseif (!$this->handle = fopen($this->file, 'r')) { usleep(100); // Give some time for chmod() to complete $this->handle = fopen($this->file, 'r'); } } restore_error_handler(); if (!$this->handle) { throw new IOException($error, 0, null, $this->file); } // On Windows, even if PHP doc says the contrary, LOCK_NB works, see // https://bugs.php.net/54129 if (!flock($this->handle, LOCK_EX | ($blocking ? 0 : LOCK_NB))) { fclose($this->handle); $this->handle = null; return false; } return true; }
[ "public", "function", "lock", "(", "$", "blocking", "=", "false", ")", "{", "if", "(", "$", "this", "->", "handle", ")", "{", "return", "true", ";", "}", "$", "error", "=", "null", ";", "// Silence error reporting", "set_error_handler", "(", "function", ...
Lock the resource. @param bool $blocking Wait until the lock is released @throws IOException If the lock file could not be created or opened @return bool Returns true if the lock was acquired, false otherwise
[ "Lock", "the", "resource", "." ]
b22188fca607fb7897c97bb4592d11d7eaaa60fe
https://github.com/php-enqueue/fs/blob/b22188fca607fb7897c97bb4592d11d7eaaa60fe/LegacyFilesystemLock.php#L135-L172
train
php-enqueue/fs
LegacyFilesystemLock.php
LockHandler.release
public function release() { if ($this->handle) { flock($this->handle, LOCK_UN | LOCK_NB); fclose($this->handle); $this->handle = null; } }
php
public function release() { if ($this->handle) { flock($this->handle, LOCK_UN | LOCK_NB); fclose($this->handle); $this->handle = null; } }
[ "public", "function", "release", "(", ")", "{", "if", "(", "$", "this", "->", "handle", ")", "{", "flock", "(", "$", "this", "->", "handle", ",", "LOCK_UN", "|", "LOCK_NB", ")", ";", "fclose", "(", "$", "this", "->", "handle", ")", ";", "$", "thi...
Release the resource.
[ "Release", "the", "resource", "." ]
b22188fca607fb7897c97bb4592d11d7eaaa60fe
https://github.com/php-enqueue/fs/blob/b22188fca607fb7897c97bb4592d11d7eaaa60fe/LegacyFilesystemLock.php#L177-L184
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.compile
public function compile($vars = array()) { $out = $this->render($vars); $outputFile = $this->getOutputFile(); $destinationDir = dirname($outputFile); if (!is_dir($destinationDir)) { mkdir($destinationDir, 0777, true); } if (!is_dir($outputFile)) { file_put_contents($outputFile, $out); } else { throw new \RuntimeException(sprintf( 'Output path "%s" is directory.', $outputFile)); } return $out; }
php
public function compile($vars = array()) { $out = $this->render($vars); $outputFile = $this->getOutputFile(); $destinationDir = dirname($outputFile); if (!is_dir($destinationDir)) { mkdir($destinationDir, 0777, true); } if (!is_dir($outputFile)) { file_put_contents($outputFile, $out); } else { throw new \RuntimeException(sprintf( 'Output path "%s" is directory.', $outputFile)); } return $out; }
[ "public", "function", "compile", "(", "$", "vars", "=", "array", "(", ")", ")", "{", "$", "out", "=", "$", "this", "->", "render", "(", "$", "vars", ")", ";", "$", "outputFile", "=", "$", "this", "->", "getOutputFile", "(", ")", ";", "$", "destin...
Create static version of a concrete page @param array $vars List of variables passed to template engine @return \Phrozn\Site\View
[ "Create", "static", "version", "of", "a", "concrete", "page" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L126-L144
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.getOutputFile
public function getOutputFile() { if (!$this->outputFile) { $path = new OutputFile($this); $this->setOutputFile($path->get()); } return $this->outputFile; }
php
public function getOutputFile() { if (!$this->outputFile) { $path = new OutputFile($this); $this->setOutputFile($path->get()); } return $this->outputFile; }
[ "public", "function", "getOutputFile", "(", ")", "{", "if", "(", "!", "$", "this", "->", "outputFile", ")", "{", "$", "path", "=", "new", "OutputFile", "(", "$", "this", ")", ";", "$", "this", "->", "setOutputFile", "(", "$", "path", "->", "get", "...
Get output file path @return string
[ "Get", "output", "file", "path" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L224-L232
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.getParam
public function getParam($param, $default = null) { try { $this->parse(); $value = $this->getParams($param, null); } catch (\Exception $e) { // skip error on file read problems, just return default value } if (isset($value)) { return $value; } else { return $default; } }
php
public function getParam($param, $default = null) { try { $this->parse(); $value = $this->getParams($param, null); } catch (\Exception $e) { // skip error on file read problems, just return default value } if (isset($value)) { return $value; } else { return $default; } }
[ "public", "function", "getParam", "(", "$", "param", ",", "$", "default", "=", "null", ")", "{", "try", "{", "$", "this", "->", "parse", "(", ")", ";", "$", "value", "=", "$", "this", "->", "getParams", "(", "$", "param", ",", "null", ")", ";", ...
Get param value @param string $param Parameter name to obtain value for @param mixed $default Default parameter value, if non found in FM @return mixed
[ "Get", "param", "value" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L339-L352
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.getParams
public function getParams($param = null, $default = array()) { $params = array(); $params['page'] = $this->getFrontMatter(); $params['site'] = $this->getSiteConfig(); $params['phr'] = $this->getAppConfig(); $params['current'] = array(); $inputFile = $this->getInputFile(); $pos = strpos($inputFile, '/entries'); if (false !== $pos) { $params['current']['phr_template'] = substr($this->getInputFile(), $pos + 8 + 1); } // also create merged configuration if (isset($params['page'], $params['site'])) { $params['this'] = array_merge($params['page'], $params['site'], $params['current']); } else { $params['this'] = $params['current']; } if (null !== $param) { $params = $this->locateParam($params, $param); } return isset($params) ? $params : $default; }
php
public function getParams($param = null, $default = array()) { $params = array(); $params['page'] = $this->getFrontMatter(); $params['site'] = $this->getSiteConfig(); $params['phr'] = $this->getAppConfig(); $params['current'] = array(); $inputFile = $this->getInputFile(); $pos = strpos($inputFile, '/entries'); if (false !== $pos) { $params['current']['phr_template'] = substr($this->getInputFile(), $pos + 8 + 1); } // also create merged configuration if (isset($params['page'], $params['site'])) { $params['this'] = array_merge($params['page'], $params['site'], $params['current']); } else { $params['this'] = $params['current']; } if (null !== $param) { $params = $this->locateParam($params, $param); } return isset($params) ? $params : $default; }
[ "public", "function", "getParams", "(", "$", "param", "=", "null", ",", "$", "default", "=", "array", "(", ")", ")", "{", "$", "params", "=", "array", "(", ")", ";", "$", "params", "[", "'page'", "]", "=", "$", "this", "->", "getFrontMatter", "(", ...
Get view parameters from both front matter and general site options @param string $param Parameter to get value for. Levels are separated with dots @param string $default Default value to fetch if param is not found @return array
[ "Get", "view", "parameters", "from", "both", "front", "matter", "and", "general", "site", "options" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L362-L388
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.getFrontMatter
public function getFrontMatter() { if (null === $this->frontMatter) { $this->parse(); } if (null === $this->frontMatter) { $this->frontMatter = array(); } return $this->frontMatter; }
php
public function getFrontMatter() { if (null === $this->frontMatter) { $this->parse(); } if (null === $this->frontMatter) { $this->frontMatter = array(); } return $this->frontMatter; }
[ "public", "function", "getFrontMatter", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "frontMatter", ")", "{", "$", "this", "->", "parse", "(", ")", ";", "}", "if", "(", "null", "===", "$", "this", "->", "frontMatter", ")", "{", "$", ...
Get YAML front matter from input view @return array
[ "Get", "YAML", "front", "matter", "from", "input", "view" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L455-L464
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.applyLayout
protected function applyLayout($content, $vars) { $layoutName = $this->getParam('page.layout', ViewFactory::DEFAULT_LAYOUT_SCRIPT); $inputFile = $this->getInputFile(); $inputFile = str_replace('\\', '/', $inputFile); $pos = strpos($inputFile, '/entries'); // make sure that input path is normalized to root entries directory if (false !== $pos) { $inputFile = substr($inputFile, 0, $pos + 8) . '/entry'; } $layoutPath = realpath(dirname($inputFile) . '/../layouts/' . $layoutName); $factory = new ViewFactory($layoutPath); $layout = $factory->create(); // essentially layout is Site\View as well $layout->hasLayout(false); // no nested layouts $vars['content'] = $content; $vars['entry'] = $vars['page']; return $layout->render($vars); }
php
protected function applyLayout($content, $vars) { $layoutName = $this->getParam('page.layout', ViewFactory::DEFAULT_LAYOUT_SCRIPT); $inputFile = $this->getInputFile(); $inputFile = str_replace('\\', '/', $inputFile); $pos = strpos($inputFile, '/entries'); // make sure that input path is normalized to root entries directory if (false !== $pos) { $inputFile = substr($inputFile, 0, $pos + 8) . '/entry'; } $layoutPath = realpath(dirname($inputFile) . '/../layouts/' . $layoutName); $factory = new ViewFactory($layoutPath); $layout = $factory->create(); // essentially layout is Site\View as well $layout->hasLayout(false); // no nested layouts $vars['content'] = $content; $vars['entry'] = $vars['page']; return $layout->render($vars); }
[ "protected", "function", "applyLayout", "(", "$", "content", ",", "$", "vars", ")", "{", "$", "layoutName", "=", "$", "this", "->", "getParam", "(", "'page.layout'", ",", "ViewFactory", "::", "DEFAULT_LAYOUT_SCRIPT", ")", ";", "$", "inputFile", "=", "$", "...
Two step view is used. View to wrap is provided with content variable. @param string $content View text to wrap into layout @param array $vars List of variables passed to processors @return string
[ "Two", "step", "view", "is", "used", ".", "View", "to", "wrap", "is", "provided", "with", "content", "variable", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L501-L523
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.parse
private function parse() { if (isset($this->template, $this->frontMatter)) { return $this; } $source = $this->readSourceFile(); $parts = preg_split('/[\n]*[-]{3}[\n]/', $source, 2); if (count($parts) === 2) { $this->frontMatter = Yaml::parse($parts[0]); $this->template = trim($parts[1]); } else { $this->frontMatter = array(); $this->template = trim($source); } return $this; }
php
private function parse() { if (isset($this->template, $this->frontMatter)) { return $this; } $source = $this->readSourceFile(); $parts = preg_split('/[\n]*[-]{3}[\n]/', $source, 2); if (count($parts) === 2) { $this->frontMatter = Yaml::parse($parts[0]); $this->template = trim($parts[1]); } else { $this->frontMatter = array(); $this->template = trim($source); } return $this; }
[ "private", "function", "parse", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "template", ",", "$", "this", "->", "frontMatter", ")", ")", "{", "return", "$", "this", ";", "}", "$", "source", "=", "$", "this", "->", "readSourceFile", "...
Parses input file into front matter and actual template content @return \Phrozn\Site\View
[ "Parses", "input", "file", "into", "front", "matter", "and", "actual", "template", "content" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L546-L564
train
Pawka/phrozn
Phrozn/Site/View/Base.php
Base.readSourceFile
private function readSourceFile() { if (null == $this->source) { $path = $this->getInputFile(); if (null === $path) { throw new \RuntimeException("View input file not specified."); } try { $this->source = \file_get_contents($path); } catch (\Exception $e) { throw new \RuntimeException(sprintf('View "%s" file can not be read', $path)); } } return $this->source; }
php
private function readSourceFile() { if (null == $this->source) { $path = $this->getInputFile(); if (null === $path) { throw new \RuntimeException("View input file not specified."); } try { $this->source = \file_get_contents($path); } catch (\Exception $e) { throw new \RuntimeException(sprintf('View "%s" file can not be read', $path)); } } return $this->source; }
[ "private", "function", "readSourceFile", "(", ")", "{", "if", "(", "null", "==", "$", "this", "->", "source", ")", "{", "$", "path", "=", "$", "this", "->", "getInputFile", "(", ")", ";", "if", "(", "null", "===", "$", "path", ")", "{", "throw", ...
Read input file @return string
[ "Read", "input", "file" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Base.php#L571-L585
train
Pawka/phrozn
Phrozn/Site/View/Less.php
Less.setInputFile
public function setInputFile($path) { parent::setInputFile($path); $processors = $this->getProcessors(); if (count($processors)) { $options = array( 'phr_template_filename' => basename($path), 'phr_template_dir' => dirname($path), ); $processor = array_pop($processors); $processor->setConfig($options); } return $this; }
php
public function setInputFile($path) { parent::setInputFile($path); $processors = $this->getProcessors(); if (count($processors)) { $options = array( 'phr_template_filename' => basename($path), 'phr_template_dir' => dirname($path), ); $processor = array_pop($processors); $processor->setConfig($options); } return $this; }
[ "public", "function", "setInputFile", "(", "$", "path", ")", "{", "parent", "::", "setInputFile", "(", "$", "path", ")", ";", "$", "processors", "=", "$", "this", "->", "getProcessors", "(", ")", ";", "if", "(", "count", "(", "$", "processors", ")", ...
Set input file path. Overriden to update processor options. @param string $file Path to file @return \Phrozn\Site\View
[ "Set", "input", "file", "path", ".", "Overriden", "to", "update", "processor", "options", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Less.php#L66-L79
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Callback/Base.php
Base.readLine
public function readLine() { if (null !== $this->unitTestData) { return $this->unitTestData; } else { $outputter = new PlainOutputter(); $reader = new Reader(); return $reader ->setOutputter($outputter) ->readLine("Type 'yes' to continue: "); } }
php
public function readLine() { if (null !== $this->unitTestData) { return $this->unitTestData; } else { $outputter = new PlainOutputter(); $reader = new Reader(); return $reader ->setOutputter($outputter) ->readLine("Type 'yes' to continue: "); } }
[ "public", "function", "readLine", "(", ")", "{", "if", "(", "null", "!==", "$", "this", "->", "unitTestData", ")", "{", "return", "$", "this", "->", "unitTestData", ";", "}", "else", "{", "$", "outputter", "=", "new", "PlainOutputter", "(", ")", ";", ...
Read-line either from STDIN or mock unit test data @return string
[ "Read", "-", "line", "either", "from", "STDIN", "or", "mock", "unit", "test", "data" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Callback/Base.php#L177-L188
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Callback/Base.php
Base.getRealCommandName
private function getRealCommandName($file) { $iter = CommandLine\Commands::getInstance(); $commands = array(); foreach ($iter as $name => $data) { $commands[$name] = $data; } ksort($commands); if (!file_exists($file)) { foreach ($commands as $command) { if (is_array($command["command"]["aliases"]) && in_array($file, $command["command"]["aliases"])) { return $command["command"]["name"]; } } } return $file; }
php
private function getRealCommandName($file) { $iter = CommandLine\Commands::getInstance(); $commands = array(); foreach ($iter as $name => $data) { $commands[$name] = $data; } ksort($commands); if (!file_exists($file)) { foreach ($commands as $command) { if (is_array($command["command"]["aliases"]) && in_array($file, $command["command"]["aliases"])) { return $command["command"]["name"]; } } } return $file; }
[ "private", "function", "getRealCommandName", "(", "$", "file", ")", "{", "$", "iter", "=", "CommandLine", "\\", "Commands", "::", "getInstance", "(", ")", ";", "$", "commands", "=", "array", "(", ")", ";", "foreach", "(", "$", "iter", "as", "$", "name"...
Search if an alias exists for this command @param string $file Command name (could be an alias) @return string The real command file name
[ "Search", "if", "an", "alias", "exists", "for", "this", "command" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Callback/Base.php#L210-L228
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Callback/Base.php
Base.combine
protected function combine($file, $verbose = false) { $file = $this->getRealCommandName($file); $config = $this->getConfig(); $file = $config['paths']['configs'] . 'commands/' . $file . '.yml'; $data = Yaml::parse($file); if ($data === $file) { return false; } $docs = $data['docs']; $command = $data['command']; $out = ''; $out .= sprintf("%s: %s\n", $docs['name'], $docs['summary']); $out .= 'usage: ' . trim($docs['usage']) . "\n"; $out .= "\n " . $this->pre($docs['description']) . "\n"; $hasOptions = false; if (isset($command['options']) && count($command['options'])) { $out .= "Available options:\n"; foreach ($command['options'] as $opt) { $spaces = str_repeat(' ', 30 - strlen($opt['doc_name'])); $out .= " {$opt['doc_name']} {$spaces} : {$opt['description']}\n"; } $hasOptions = true; } if (isset($command['arguments']) && count($command['arguments'])) { $out .= $hasOptions ? "\n": ""; $out .= "Valid arguments:\n"; foreach ($command['arguments'] as $arg) { $spaces = str_repeat(' ', 30 - strlen($arg['help_name'])); $out .= " {$arg['help_name']} {$spaces} : {$arg['description']}\n"; } } if (isset($command['commands']) && count($command['commands'])) { $out .= "Valid commands:\n"; foreach ($command['commands'] as $subcommand) { $spaces = str_repeat(' ', 30 - strlen($subcommand['name'])); $out .= " {$subcommand['name']} {$spaces} : {$subcommand['description']}\n"; } } if ($verbose) { if (isset($docs['extradesc'])) { $out .= "\nExtended Documentation:"; $out .= "\n " . $this->pre(trim($docs['extradesc'])) . "\n"; } if (isset($docs['examples'])) { $out .= "\nExamples:"; $out .= "\n " . $this->pre(trim($docs['examples'])) . "\n"; } } else { $out .= "\nUse help with -v or --verbose option to get more information.\n"; } return $out; }
php
protected function combine($file, $verbose = false) { $file = $this->getRealCommandName($file); $config = $this->getConfig(); $file = $config['paths']['configs'] . 'commands/' . $file . '.yml'; $data = Yaml::parse($file); if ($data === $file) { return false; } $docs = $data['docs']; $command = $data['command']; $out = ''; $out .= sprintf("%s: %s\n", $docs['name'], $docs['summary']); $out .= 'usage: ' . trim($docs['usage']) . "\n"; $out .= "\n " . $this->pre($docs['description']) . "\n"; $hasOptions = false; if (isset($command['options']) && count($command['options'])) { $out .= "Available options:\n"; foreach ($command['options'] as $opt) { $spaces = str_repeat(' ', 30 - strlen($opt['doc_name'])); $out .= " {$opt['doc_name']} {$spaces} : {$opt['description']}\n"; } $hasOptions = true; } if (isset($command['arguments']) && count($command['arguments'])) { $out .= $hasOptions ? "\n": ""; $out .= "Valid arguments:\n"; foreach ($command['arguments'] as $arg) { $spaces = str_repeat(' ', 30 - strlen($arg['help_name'])); $out .= " {$arg['help_name']} {$spaces} : {$arg['description']}\n"; } } if (isset($command['commands']) && count($command['commands'])) { $out .= "Valid commands:\n"; foreach ($command['commands'] as $subcommand) { $spaces = str_repeat(' ', 30 - strlen($subcommand['name'])); $out .= " {$subcommand['name']} {$spaces} : {$subcommand['description']}\n"; } } if ($verbose) { if (isset($docs['extradesc'])) { $out .= "\nExtended Documentation:"; $out .= "\n " . $this->pre(trim($docs['extradesc'])) . "\n"; } if (isset($docs['examples'])) { $out .= "\nExamples:"; $out .= "\n " . $this->pre(trim($docs['examples'])) . "\n"; } } else { $out .= "\nUse help with -v or --verbose option to get more information.\n"; } return $out; }
[ "protected", "function", "combine", "(", "$", "file", ",", "$", "verbose", "=", "false", ")", "{", "$", "file", "=", "$", "this", "->", "getRealCommandName", "(", "$", "file", ")", ";", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ...
Combine command documentation @param string $file Command file to combine @param boolean $verbose Whether to provide full documentation or just summary @return string
[ "Combine", "command", "documentation" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Callback/Base.php#L238-L299
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Callback/Base.php
Base.getPathArgument
protected function getPathArgument($name, $realpath = true, $command = null) { if (null == $command) { $command = $this->getParseResult()->command; } $path = isset($command->args[$name]) ? $command->args[$name] : \getcwd(); if (!$this->isAbsolute($path)) { // not an absolute path $path = \getcwd() . '/./' . $path; } if ($realpath) { $path = realpath($path); } return $path; }
php
protected function getPathArgument($name, $realpath = true, $command = null) { if (null == $command) { $command = $this->getParseResult()->command; } $path = isset($command->args[$name]) ? $command->args[$name] : \getcwd(); if (!$this->isAbsolute($path)) { // not an absolute path $path = \getcwd() . '/./' . $path; } if ($realpath) { $path = realpath($path); } return $path; }
[ "protected", "function", "getPathArgument", "(", "$", "name", ",", "$", "realpath", "=", "true", ",", "$", "command", "=", "null", ")", "{", "if", "(", "null", "==", "$", "command", ")", "{", "$", "command", "=", "$", "this", "->", "getParseResult", ...
Extract path argument or fallback to cwd @param string $name Name of the path argument @param boolean $realpath Whether to apply realpath() to path @param \Console_CommandLine_Result $command Command line result to use @return string
[ "Extract", "path", "argument", "or", "fallback", "to", "cwd" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Callback/Base.php#L369-L385
train
Pawka/phrozn
Phrozn/Autoloader.php
Autoloader.getLoader
public function getLoader() { if (null === $this->loader) { if (strpos('@PHP-BIN@', '@PHP-BIN') === 0) { $base = dirname(__FILE__) . '/'; set_include_path($base . PATH_SEPARATOR . get_include_path()); } else { $base = '@PEAR-DIR@/Phrozn/'; } //Autoload candidates. $dirs = array($base . '..', getcwd()); foreach ($dirs as $dir) { $file = $dir . '/vendor/autoload.php'; if (file_exists($file)) { $this->loader = include $file; break; } } if (null === $this->loader) { throw new \RuntimeException("Unable to locate autoloader."); } } return $this->loader; }
php
public function getLoader() { if (null === $this->loader) { if (strpos('@PHP-BIN@', '@PHP-BIN') === 0) { $base = dirname(__FILE__) . '/'; set_include_path($base . PATH_SEPARATOR . get_include_path()); } else { $base = '@PEAR-DIR@/Phrozn/'; } //Autoload candidates. $dirs = array($base . '..', getcwd()); foreach ($dirs as $dir) { $file = $dir . '/vendor/autoload.php'; if (file_exists($file)) { $this->loader = include $file; break; } } if (null === $this->loader) { throw new \RuntimeException("Unable to locate autoloader."); } } return $this->loader; }
[ "public", "function", "getLoader", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "loader", ")", "{", "if", "(", "strpos", "(", "'@PHP-BIN@'", ",", "'@PHP-BIN'", ")", "===", "0", ")", "{", "$", "base", "=", "dirname", "(", "__FILE__", ...
Get auto-loader instance @return \Composer\Autoload\ClassLoader
[ "Get", "auto", "-", "loader", "instance" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Autoloader.php#L62-L89
train
Pawka/phrozn
Phrozn/Autoloader.php
Autoloader.getPaths
public function getPaths() { if (strpos('@PHP-BIN@', '@PHP-BIN') === 0) { $dataDir = dirname(__FILE__) . '/../'; $phpDir = dirname(__FILE__) . '/'; } else { $dataDir = '@DATA-DIR@/Phrozn/'; $phpDir = '@PEAR-DIR@/Phrozn/'; } return array( 'data_dir' => $dataDir, 'php_dir' => $phpDir, 'configs' => $dataDir . 'configs/', 'skeleton' => $dataDir . 'skeleton/', 'library' => $phpDir, ); }
php
public function getPaths() { if (strpos('@PHP-BIN@', '@PHP-BIN') === 0) { $dataDir = dirname(__FILE__) . '/../'; $phpDir = dirname(__FILE__) . '/'; } else { $dataDir = '@DATA-DIR@/Phrozn/'; $phpDir = '@PEAR-DIR@/Phrozn/'; } return array( 'data_dir' => $dataDir, 'php_dir' => $phpDir, 'configs' => $dataDir . 'configs/', 'skeleton' => $dataDir . 'skeleton/', 'library' => $phpDir, ); }
[ "public", "function", "getPaths", "(", ")", "{", "if", "(", "strpos", "(", "'@PHP-BIN@'", ",", "'@PHP-BIN'", ")", "===", "0", ")", "{", "$", "dataDir", "=", "dirname", "(", "__FILE__", ")", ".", "'/../'", ";", "$", "phpDir", "=", "dirname", "(", "__F...
Get base paths required to load extra resources @return array
[ "Get", "base", "paths", "required", "to", "load", "extra", "resources" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Autoloader.php#L96-L112
train
Pawka/phrozn
Phrozn/Site/Base.php
Base.getOutputDir
public function getOutputDir() { // override output directory using site config file $config = $this->getSiteConfig(); if (isset($config['site']['output'])) { $this->setOutputDir($config['site']['output']); } return $this->outputDir; }
php
public function getOutputDir() { // override output directory using site config file $config = $this->getSiteConfig(); if (isset($config['site']['output'])) { $this->setOutputDir($config['site']['output']); } return $this->outputDir; }
[ "public", "function", "getOutputDir", "(", ")", "{", "// override output directory using site config file", "$", "config", "=", "$", "this", "->", "getSiteConfig", "(", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "'site'", "]", "[", "'output'", "]",...
Get output directory path @return string
[ "Get", "output", "directory", "path" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/Base.php#L125-L133
train
Pawka/phrozn
Phrozn/Site/Base.php
Base.getSiteConfig
public function getSiteConfig() { if (null === $this->siteConfig) { $configFile = realpath($this->getInputDir() . '/config.yml'); $this->siteConfig = Yaml::parse($configFile); } return $this->siteConfig; }
php
public function getSiteConfig() { if (null === $this->siteConfig) { $configFile = realpath($this->getInputDir() . '/config.yml'); $this->siteConfig = Yaml::parse($configFile); } return $this->siteConfig; }
[ "public", "function", "getSiteConfig", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "siteConfig", ")", "{", "$", "configFile", "=", "realpath", "(", "$", "this", "->", "getInputDir", "(", ")", ".", "'/config.yml'", ")", ";", "$", "this",...
Get site configuration @return array
[ "Get", "site", "configuration" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/Base.php#L200-L207
train
Pawka/phrozn
Phrozn/Site/Base.php
Base.buildQueue
protected function buildQueue() { // guess the base path with Phrozn project $projectDir = $this->getProjectDir(); $outputDir = $this->getOutputDir(); $config = $this->getSiteConfig(); // configure skip files options $skipToken = '-!SKIP!-'; $folders = array( 'entries', 'styles', 'scripts' ); foreach ($folders as $folder) { $dir = new \RecursiveDirectoryIterator($projectDir . '/' . $folder); $it = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST); foreach ($it as $item) { $baseName = $item->getBaseName(); if (isset($config['skip'])) { $baseName = preg_replace($config['skip'], array_fill(0, count($config['skip']), $skipToken), $baseName); if (strpos($baseName, $skipToken) !== false) { continue; } } if ($item->isFile()) { try { $factory = new View\Factory($item->getRealPath()); $factory->setInputRootDir($projectDir); $view = $factory->create(); $view ->setSiteConfig($this->getSiteConfig()) ->setOutputDir($outputDir); $this->views[] = $view; } catch (\Exception $e) { $this->getOutputter() ->stderr(str_replace($projectDir, '', $item->getRealPath()) . ': ' . $e->getMessage()); } } } } return $this; }
php
protected function buildQueue() { // guess the base path with Phrozn project $projectDir = $this->getProjectDir(); $outputDir = $this->getOutputDir(); $config = $this->getSiteConfig(); // configure skip files options $skipToken = '-!SKIP!-'; $folders = array( 'entries', 'styles', 'scripts' ); foreach ($folders as $folder) { $dir = new \RecursiveDirectoryIterator($projectDir . '/' . $folder); $it = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST); foreach ($it as $item) { $baseName = $item->getBaseName(); if (isset($config['skip'])) { $baseName = preg_replace($config['skip'], array_fill(0, count($config['skip']), $skipToken), $baseName); if (strpos($baseName, $skipToken) !== false) { continue; } } if ($item->isFile()) { try { $factory = new View\Factory($item->getRealPath()); $factory->setInputRootDir($projectDir); $view = $factory->create(); $view ->setSiteConfig($this->getSiteConfig()) ->setOutputDir($outputDir); $this->views[] = $view; } catch (\Exception $e) { $this->getOutputter() ->stderr(str_replace($projectDir, '', $item->getRealPath()) . ': ' . $e->getMessage()); } } } } return $this; }
[ "protected", "function", "buildQueue", "(", ")", "{", "// guess the base path with Phrozn project", "$", "projectDir", "=", "$", "this", "->", "getProjectDir", "(", ")", ";", "$", "outputDir", "=", "$", "this", "->", "getOutputDir", "(", ")", ";", "$", "config...
Create list of views to be created @return \Phrozn\Site
[ "Create", "list", "of", "views", "to", "be", "created" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/Base.php#L214-L256
train
Pawka/phrozn
Phrozn/Site/Base.php
Base.getProjectDir
protected function getProjectDir() { $dir = rtrim($this->getInputDir(), '/'); if (is_dir($dir . '/.phrozn')) { $dir .= '/.phrozn/'; } // see if we have entries folder present if (!is_dir($dir . '/entries')) { throw new \RuntimeException('Entries folder not found'); } return $dir; }
php
protected function getProjectDir() { $dir = rtrim($this->getInputDir(), '/'); if (is_dir($dir . '/.phrozn')) { $dir .= '/.phrozn/'; } // see if we have entries folder present if (!is_dir($dir . '/entries')) { throw new \RuntimeException('Entries folder not found'); } return $dir; }
[ "protected", "function", "getProjectDir", "(", ")", "{", "$", "dir", "=", "rtrim", "(", "$", "this", "->", "getInputDir", "(", ")", ",", "'/'", ")", ";", "if", "(", "is_dir", "(", "$", "dir", ".", "'/.phrozn'", ")", ")", "{", "$", "dir", ".=", "'...
Guess directory with Phrozn project using input directory @return string
[ "Guess", "directory", "with", "Phrozn", "project", "using", "input", "directory" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/Base.php#L263-L276
train
Pawka/phrozn
Phrozn/Provider/Factory.php
Factory.create
public function create($type, $data) { // try to see if we have user defined plugin $class = 'PhroznPlugin\\Provider\\' . ucfirst($type); if (!class_exists($class)) { $class = 'Phrozn\\Provider\\' . ucfirst($type); if (!class_exists($class)) { throw new \RuntimeException("Provider of type '{$type}' not found.."); } } $object = new $class; $object->setConfig($data); return $object; }
php
public function create($type, $data) { // try to see if we have user defined plugin $class = 'PhroznPlugin\\Provider\\' . ucfirst($type); if (!class_exists($class)) { $class = 'Phrozn\\Provider\\' . ucfirst($type); if (!class_exists($class)) { throw new \RuntimeException("Provider of type '{$type}' not found.."); } } $object = new $class; $object->setConfig($data); return $object; }
[ "public", "function", "create", "(", "$", "type", ",", "$", "data", ")", "{", "// try to see if we have user defined plugin", "$", "class", "=", "'PhroznPlugin\\\\Provider\\\\'", ".", "ucfirst", "(", "$", "type", ")", ";", "if", "(", "!", "class_exists", "(", ...
Create provider instance @param string $type Provider typ to initialize @param mixed $data Provider data return \Phrozn\Provider
[ "Create", "provider", "instance" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Provider/Factory.php#L41-L54
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Parser.php
Parser.configureCommand
private function configureCommand($paths, $config) { // options foreach ($config['command']['options'] as $name => $option) { $this->addOption($name, $option); } // commands $commands = CommandLine\Commands::getInstance() ->setPath($paths['configs'] . 'commands'); foreach ($commands as $name => $data) { $this->registerCommand($name, $data); } return $this; }
php
private function configureCommand($paths, $config) { // options foreach ($config['command']['options'] as $name => $option) { $this->addOption($name, $option); } // commands $commands = CommandLine\Commands::getInstance() ->setPath($paths['configs'] . 'commands'); foreach ($commands as $name => $data) { $this->registerCommand($name, $data); } return $this; }
[ "private", "function", "configureCommand", "(", "$", "paths", ",", "$", "config", ")", "{", "// options", "foreach", "(", "$", "config", "[", "'command'", "]", "[", "'options'", "]", "as", "$", "name", "=>", "$", "option", ")", "{", "$", "this", "->", ...
Fine tune main command by adding subcommands @para array $paths Paths to various Phrozn directories @param array $config Loaded contents of phrozn.yml @return \Phrozn\Runner\Command
[ "Fine", "tune", "main", "command", "by", "adding", "subcommands" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Parser.php#L63-L79
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Parser.php
Parser.registerCommand
private function registerCommand( $name, $data, \Console_CommandLine_Command $parent = null) { $command = isset($data['command']) ? $data['command'] : $data; if (null === $parent) { $cmd = $this->addCommand($name, $command); } else { $cmd = $parent->addCommand($name, $command); } // command arguments $args = isset($command['arguments']) ? $command['arguments'] : array(); foreach ($args as $name => $argument) { $cmd->addArgument($name, $argument); } // command options $opts = isset($command['options']) ? $command['options'] : array(); foreach ($opts as $name => $option) { $cmd->addOption($name, $option); } // commands actions (sub-commands) $subs = isset($command['commands']) ? $command['commands'] : array(); foreach ($subs as $name => $data) { $this->registerCommand($name, $data, $cmd); } }
php
private function registerCommand( $name, $data, \Console_CommandLine_Command $parent = null) { $command = isset($data['command']) ? $data['command'] : $data; if (null === $parent) { $cmd = $this->addCommand($name, $command); } else { $cmd = $parent->addCommand($name, $command); } // command arguments $args = isset($command['arguments']) ? $command['arguments'] : array(); foreach ($args as $name => $argument) { $cmd->addArgument($name, $argument); } // command options $opts = isset($command['options']) ? $command['options'] : array(); foreach ($opts as $name => $option) { $cmd->addOption($name, $option); } // commands actions (sub-commands) $subs = isset($command['commands']) ? $command['commands'] : array(); foreach ($subs as $name => $data) { $this->registerCommand($name, $data, $cmd); } }
[ "private", "function", "registerCommand", "(", "$", "name", ",", "$", "data", ",", "\\", "Console_CommandLine_Command", "$", "parent", "=", "null", ")", "{", "$", "command", "=", "isset", "(", "$", "data", "[", "'command'", "]", ")", "?", "$", "data", ...
Register given command using array of options @param string $name Command name @param array $data Array of command initializing options @param \Console_CommandLine_Command $parent If sub-command is being added, provide parent @return void
[ "Register", "given", "command", "using", "array", "of", "options" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Parser.php#L99-L123
train
Pawka/phrozn
Phrozn/Site/View/Markdown.php
Markdown.render
public function render($vars = array()) { $view = parent::render($vars); if ($this->hasLayout()) { // inject global site and front matter options into template $vars = array_merge_recursive($vars, $this->getParams()); $view = $this->applyLayout($view, $vars); } return $view; }
php
public function render($vars = array()) { $view = parent::render($vars); if ($this->hasLayout()) { // inject global site and front matter options into template $vars = array_merge_recursive($vars, $this->getParams()); $view = $this->applyLayout($view, $vars); } return $view; }
[ "public", "function", "render", "(", "$", "vars", "=", "array", "(", ")", ")", "{", "$", "view", "=", "parent", "::", "render", "(", "$", "vars", ")", ";", "if", "(", "$", "this", "->", "hasLayout", "(", ")", ")", "{", "// inject global site and fron...
Render view. Markdown views are rendered within layout. @param array $vars List of variables passed to text processors @return string
[ "Render", "view", ".", "Markdown", "views", "are", "rendered", "within", "layout", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Markdown.php#L59-L68
train
Pawka/phrozn
Phrozn/Site/View/OutputPath/Base.php
Base.getInputFileExtension
protected function getInputFileExtension($includeDot = true) { $extension = pathinfo($this->getView()->getInputFile(), PATHINFO_EXTENSION); if ($includeDot && $extension != '') { return '.' . $extension; } return $extension; }
php
protected function getInputFileExtension($includeDot = true) { $extension = pathinfo($this->getView()->getInputFile(), PATHINFO_EXTENSION); if ($includeDot && $extension != '') { return '.' . $extension; } return $extension; }
[ "protected", "function", "getInputFileExtension", "(", "$", "includeDot", "=", "true", ")", "{", "$", "extension", "=", "pathinfo", "(", "$", "this", "->", "getView", "(", ")", "->", "getInputFile", "(", ")", ",", "PATHINFO_EXTENSION", ")", ";", "if", "(",...
Get the file extension for the input file @return string
[ "Get", "the", "file", "extension", "for", "the", "input", "file" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/OutputPath/Base.php#L94-L103
train
Pawka/phrozn
Phrozn/Config.php
Config.updatePaths
public function updatePaths() { if (isset($this->configs['paths'])) { $paths = Loader::getInstance()->getPaths(); foreach ($this->configs['paths'] as $key => $file) { $file = str_replace('@PEAR-DIR@', $paths['php_dir'], $file); $file = str_replace('@DATA-DIR@', $paths['data_dir'], $file); $this->configs['paths'][$key] = $file; } } return $this; }
php
public function updatePaths() { if (isset($this->configs['paths'])) { $paths = Loader::getInstance()->getPaths(); foreach ($this->configs['paths'] as $key => $file) { $file = str_replace('@PEAR-DIR@', $paths['php_dir'], $file); $file = str_replace('@DATA-DIR@', $paths['data_dir'], $file); $this->configs['paths'][$key] = $file; } } return $this; }
[ "public", "function", "updatePaths", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "configs", "[", "'paths'", "]", ")", ")", "{", "$", "paths", "=", "Loader", "::", "getInstance", "(", ")", "->", "getPaths", "(", ")", ";", "foreach", "...
Make sure that absolute application path is prepended to config paths @return \Phrozn\Config
[ "Make", "sure", "that", "absolute", "application", "path", "is", "prepended", "to", "config", "paths" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Config.php#L120-L131
train
Pawka/phrozn
Phrozn/Registry/Dao/Base.php
Base.setContainer
public function setContainer(\Phrozn\Registry\Container $container = null) { $this->container = $container; return $this; }
php
public function setContainer(\Phrozn\Registry\Container $container = null) { $this->container = $container; return $this; }
[ "public", "function", "setContainer", "(", "\\", "Phrozn", "\\", "Registry", "\\", "Container", "$", "container", "=", "null", ")", "{", "$", "this", "->", "container", "=", "$", "container", ";", "return", "$", "this", ";", "}" ]
Set registry container. @param \Phrozn\Registry\Container $container Registry container @return \Phrozn\Has\Container
[ "Set", "registry", "container", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Dao/Base.php#L73-L77
train
Pawka/phrozn
Phrozn/Registry/Dao/Base.php
Base.setProjectPath
public function setProjectPath($path) { if (!($path instanceof \Phrozn\Path\Project)) { $path = new ProjectPath($path); } $this->projectPath = $path->get(); // calculate path return $this; }
php
public function setProjectPath($path) { if (!($path instanceof \Phrozn\Path\Project)) { $path = new ProjectPath($path); } $this->projectPath = $path->get(); // calculate path return $this; }
[ "public", "function", "setProjectPath", "(", "$", "path", ")", "{", "if", "(", "!", "(", "$", "path", "instanceof", "\\", "Phrozn", "\\", "Path", "\\", "Project", ")", ")", "{", "$", "path", "=", "new", "ProjectPath", "(", "$", "path", ")", ";", "}...
Set project path. @param string $path Project path. @return \Phrozn\Has\ProjectPath
[ "Set", "project", "path", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Dao/Base.php#L96-L104
train
Pawka/phrozn
Phrozn/Site/View/Factory.php
Factory.create
public function create() { $ext = pathinfo($this->getInputFile(), PATHINFO_EXTENSION); $type = $ext ? : self::DEFAULT_VIEW_TYPE; return $this->constructFile($type); }
php
public function create() { $ext = pathinfo($this->getInputFile(), PATHINFO_EXTENSION); $type = $ext ? : self::DEFAULT_VIEW_TYPE; return $this->constructFile($type); }
[ "public", "function", "create", "(", ")", "{", "$", "ext", "=", "pathinfo", "(", "$", "this", "->", "getInputFile", "(", ")", ",", "PATHINFO_EXTENSION", ")", ";", "$", "type", "=", "$", "ext", "?", ":", "self", "::", "DEFAULT_VIEW_TYPE", ";", "return",...
Depending on internal configuration and concrete type, create view return \Phrozn\Site\View\Factory
[ "Depending", "on", "internal", "configuration", "and", "concrete", "type", "create", "view" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Factory.php#L75-L82
train
Pawka/phrozn
Phrozn/Site/View/Factory.php
Factory.setInputFile
public function setInputFile($path) { if (null !== $path) { if (!is_readable($path)) { throw new \RuntimeException("View source file cannot be read: {$path}"); } $this->inputFile = $path; } return $this; }
php
public function setInputFile($path) { if (null !== $path) { if (!is_readable($path)) { throw new \RuntimeException("View source file cannot be read: {$path}"); } $this->inputFile = $path; } return $this; }
[ "public", "function", "setInputFile", "(", "$", "path", ")", "{", "if", "(", "null", "!==", "$", "path", ")", "{", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"View source file cannot b...
Set input file path @param string $path Path to file @return \Phrozn\Site\View\Factory
[ "Set", "input", "file", "path" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Factory.php#L114-L124
train
Pawka/phrozn
Phrozn/Site/View/Factory.php
Factory.constructFile
private function constructFile($type) { // try to see if we have user defined plugin $class = 'PhroznPlugin\\Site\\View\\' . ucfirst($type); if (!class_exists($class)) { $class = 'Phrozn\\Site\\View\\' . ucfirst($type); if (!class_exists($class)) { //throw new \RuntimeException("View of type '{$type}' not found.."); $class = 'Phrozn\\Site\\View\\Plain'; } } $object = new $class; $object->setInputRootDir($this->getInputRootDir()); $object->setInputFile($this->getInputFile()); return $object; }
php
private function constructFile($type) { // try to see if we have user defined plugin $class = 'PhroznPlugin\\Site\\View\\' . ucfirst($type); if (!class_exists($class)) { $class = 'Phrozn\\Site\\View\\' . ucfirst($type); if (!class_exists($class)) { //throw new \RuntimeException("View of type '{$type}' not found.."); $class = 'Phrozn\\Site\\View\\Plain'; } } $object = new $class; $object->setInputRootDir($this->getInputRootDir()); $object->setInputFile($this->getInputFile()); return $object; }
[ "private", "function", "constructFile", "(", "$", "type", ")", "{", "// try to see if we have user defined plugin", "$", "class", "=", "'PhroznPlugin\\\\Site\\\\View\\\\'", ".", "ucfirst", "(", "$", "type", ")", ";", "if", "(", "!", "class_exists", "(", "$", "clas...
Create and return view of a given type @param string $type File type to load @return \Phrozn\Site\View
[ "Create", "and", "return", "view", "of", "a", "given", "type" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Site/View/Factory.php#L143-L158
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Commands.php
Commands.getIterator
private function getIterator() { if (null === $this->getPath()) { throw new \RuntimeException('Commands config path not set'); } if (null === $this->it) { $this->it = new \DirectoryIterator($this->getPath()); } return $this->it; }
php
private function getIterator() { if (null === $this->getPath()) { throw new \RuntimeException('Commands config path not set'); } if (null === $this->it) { $this->it = new \DirectoryIterator($this->getPath()); } return $this->it; }
[ "private", "function", "getIterator", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "getPath", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Commands config path not set'", ")", ";", "}", "if", "(", "null", "===", "$"...
Get DirecotryIterator to commands config path @return \DirectoryIterator
[ "Get", "DirecotryIterator", "to", "commands", "config", "path" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Commands.php#L141-L150
train
Pawka/phrozn
Phrozn/Provider/LoadFromFile.php
LoadFromFile.get
public function get() { $config = $this->getConfig(); if (!isset($config['input'])) { throw new \RuntimeException('No input file provided.'); } $path = $this->getProjectPath() . '/' . $config['input']; if (!is_readable($path)) { throw new \RuntimeException(sprintf('Input file "%s" not found.', $path)); } return file_get_contents($path); }
php
public function get() { $config = $this->getConfig(); if (!isset($config['input'])) { throw new \RuntimeException('No input file provided.'); } $path = $this->getProjectPath() . '/' . $config['input']; if (!is_readable($path)) { throw new \RuntimeException(sprintf('Input file "%s" not found.', $path)); } return file_get_contents($path); }
[ "public", "function", "get", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "config", "[", "'input'", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'No inpu...
Get generated content @return mixed
[ "Get", "generated", "content" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Provider/LoadFromFile.php#L39-L50
train
Pawka/phrozn
Phrozn/Runner/CommandLine/Reader.php
Reader.readLine
public function readLine($prompt) { $this ->getOutputter() ->stdout($prompt); $out = fgets($this->getHandle()); $this->getOutputter()->stdout("\n"); return rtrim($out); }
php
public function readLine($prompt) { $this ->getOutputter() ->stdout($prompt); $out = fgets($this->getHandle()); $this->getOutputter()->stdout("\n"); return rtrim($out); }
[ "public", "function", "readLine", "(", "$", "prompt", ")", "{", "$", "this", "->", "getOutputter", "(", ")", "->", "stdout", "(", "$", "prompt", ")", ";", "$", "out", "=", "fgets", "(", "$", "this", "->", "getHandle", "(", ")", ")", ";", "$", "th...
Get line from standard input @param string $prompt Input prompt @return string
[ "Get", "line", "from", "standard", "input" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine/Reader.php#L85-L93
train
Pawka/phrozn
Phrozn/Registry/Container.php
Container.setDao
public function setDao(\Phrozn\Registry\Dao $dao) { $this->dao = $dao; if ($dao instanceof Dao) { $dao->setContainer($this); } return $this; }
php
public function setDao(\Phrozn\Registry\Dao $dao) { $this->dao = $dao; if ($dao instanceof Dao) { $dao->setContainer($this); } return $this; }
[ "public", "function", "setDao", "(", "\\", "Phrozn", "\\", "Registry", "\\", "Dao", "$", "dao", ")", "{", "$", "this", "->", "dao", "=", "$", "dao", ";", "if", "(", "$", "dao", "instanceof", "Dao", ")", "{", "$", "dao", "->", "setContainer", "(", ...
Set DAO. @param \Phrozn\Registry\Dao $dao Data access object @return \Phrozn\Has\Dao
[ "Set", "DAO", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Container.php#L104-L111
train
Pawka/phrozn
Phrozn/Registry/Container.php
Container.get
public function get($name) { if (!isset($this->values[$name])) { return null; } return $this->values[$name]; }
php
public function get($name) { if (!isset($this->values[$name])) { return null; } return $this->values[$name]; }
[ "public", "function", "get", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "values", "[", "$", "name", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "values", "[", "$", "name", "]", ...
Get property value @param string $name Property name @return mixed
[ "Get", "property", "value" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Container.php#L190-L196
train
Pawka/phrozn
Phrozn/Runner/CommandLine.php
CommandLine.parse
private function parse() { $opts = $this->result->options; $commandName = $this->result->command_name; $command = null; $optionSet = $argumentSet = false; // special treatment for -h --help main command options if ($opts['help'] === true) { $commandName = 'help'; } if ($commandName) { $configFile = $this->paths['configs'] . 'commands/' . $commandName . '.yml'; $command = new Command($configFile); } // check if any option is set // basically check for --version -v --help -h options foreach ($opts as $name => $value) { if ($value === true) { $optionSet = true; break; } } // fire up subcommand if (isset($command['callback'])) { $this->invoke($command['callback'], $command); } if ($commandName === false && $optionSet === false && $argumentSet === false) { $this->parser->outputter->stdout("Type 'phrozn help' for usage.\n"); } }
php
private function parse() { $opts = $this->result->options; $commandName = $this->result->command_name; $command = null; $optionSet = $argumentSet = false; // special treatment for -h --help main command options if ($opts['help'] === true) { $commandName = 'help'; } if ($commandName) { $configFile = $this->paths['configs'] . 'commands/' . $commandName . '.yml'; $command = new Command($configFile); } // check if any option is set // basically check for --version -v --help -h options foreach ($opts as $name => $value) { if ($value === true) { $optionSet = true; break; } } // fire up subcommand if (isset($command['callback'])) { $this->invoke($command['callback'], $command); } if ($commandName === false && $optionSet === false && $argumentSet === false) { $this->parser->outputter->stdout("Type 'phrozn help' for usage.\n"); } }
[ "private", "function", "parse", "(", ")", "{", "$", "opts", "=", "$", "this", "->", "result", "->", "options", ";", "$", "commandName", "=", "$", "this", "->", "result", "->", "command_name", ";", "$", "command", "=", "null", ";", "$", "optionSet", "...
Parse input and invoke necessary processor callback @return void
[ "Parse", "input", "and", "invoke", "necessary", "processor", "callback" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Runner/CommandLine.php#L103-L137
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.compileImport
protected function compileImport($rawPath, $out) { if ($rawPath[0] == "string") { $path = $this->compileStringContent($rawPath); if ($path = $this->findImport($path)) { $this->importFile($path, $out); return true; } return false; } if ($rawPath[0] == "list") { // handle a list of strings if (count($rawPath[2]) == 0) return false; foreach ($rawPath[2] as $path) { if ($path[0] != "string") return false; } foreach ($rawPath[2] as $path) { $this->compileImport($path, $out); } return true; } return false; }
php
protected function compileImport($rawPath, $out) { if ($rawPath[0] == "string") { $path = $this->compileStringContent($rawPath); if ($path = $this->findImport($path)) { $this->importFile($path, $out); return true; } return false; } if ($rawPath[0] == "list") { // handle a list of strings if (count($rawPath[2]) == 0) return false; foreach ($rawPath[2] as $path) { if ($path[0] != "string") return false; } foreach ($rawPath[2] as $path) { $this->compileImport($path, $out); } return true; } return false; }
[ "protected", "function", "compileImport", "(", "$", "rawPath", ",", "$", "out", ")", "{", "if", "(", "$", "rawPath", "[", "0", "]", "==", "\"string\"", ")", "{", "$", "path", "=", "$", "this", "->", "compileStringContent", "(", "$", "rawPath", ")", "...
returns true if the value was something that could be imported
[ "returns", "true", "if", "the", "value", "was", "something", "that", "could", "be", "imported" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L420-L443
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.normalizeNumber
protected function normalizeNumber($number) { list(, $value, $unit) = $number; if (isset(self::$unitTable["in"][$unit])) { $conv = self::$unitTable["in"][$unit]; return array("number", $value / $conv, "in"); } return $number; }
php
protected function normalizeNumber($number) { list(, $value, $unit) = $number; if (isset(self::$unitTable["in"][$unit])) { $conv = self::$unitTable["in"][$unit]; return array("number", $value / $conv, "in"); } return $number; }
[ "protected", "function", "normalizeNumber", "(", "$", "number", ")", "{", "list", "(", ",", "$", "value", ",", "$", "unit", ")", "=", "$", "number", ";", "if", "(", "isset", "(", "self", "::", "$", "unitTable", "[", "\"in\"", "]", "[", "$", "unit",...
just does physical lengths for now
[ "just", "does", "physical", "lengths", "for", "now" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L853-L860
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.extractInterpolation
protected function extractInterpolation($list) { $items = $list[2]; foreach ($items as $i => $item) { if ($item[0] == "interpolate") { $before = array("list", $list[1], array_slice($items, 0, $i)); $after = array("list", $list[1], array_slice($items, $i + 1)); return array("interpolated", $item, $before, $after); } } return $list; }
php
protected function extractInterpolation($list) { $items = $list[2]; foreach ($items as $i => $item) { if ($item[0] == "interpolate") { $before = array("list", $list[1], array_slice($items, 0, $i)); $after = array("list", $list[1], array_slice($items, $i + 1)); return array("interpolated", $item, $before, $after); } } return $list; }
[ "protected", "function", "extractInterpolation", "(", "$", "list", ")", "{", "$", "items", "=", "$", "list", "[", "2", "]", ";", "foreach", "(", "$", "items", "as", "$", "i", "=>", "$", "item", ")", "{", "if", "(", "$", "item", "[", "0", "]", "...
doesn't need to be recursive, compileValue will handle that
[ "doesn", "t", "need", "to", "be", "recursive", "compileValue", "will", "handle", "that" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L1092-L1102
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.multiplySelectors
protected function multiplySelectors($env) { $envs = array(); while (null !== $env) { if (!empty($env->selectors)) { $envs[] = $env; } $env = $env->parent; }; $selectors = array(); $parentSelectors = array(array()); while ($env = array_pop($envs)) { $selectors = array(); foreach ($env->selectors as $selector) { foreach ($parentSelectors as $parent) { $selectors[] = $this->joinSelectors($parent, $selector); } } $parentSelectors = $selectors; } return $selectors; }
php
protected function multiplySelectors($env) { $envs = array(); while (null !== $env) { if (!empty($env->selectors)) { $envs[] = $env; } $env = $env->parent; }; $selectors = array(); $parentSelectors = array(array()); while ($env = array_pop($envs)) { $selectors = array(); foreach ($env->selectors as $selector) { foreach ($parentSelectors as $parent) { $selectors[] = $this->joinSelectors($parent, $selector); } } $parentSelectors = $selectors; } return $selectors; }
[ "protected", "function", "multiplySelectors", "(", "$", "env", ")", "{", "$", "envs", "=", "array", "(", ")", ";", "while", "(", "null", "!==", "$", "env", ")", "{", "if", "(", "!", "empty", "(", "$", "env", "->", "selectors", ")", ")", "{", "$",...
find the final set of selectors
[ "find", "the", "final", "set", "of", "selectors" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L1105-L1127
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.joinSelectors
protected function joinSelectors($parent, $child) { $setSelf = false; $out = array(); foreach ($child as $part) { $newPart = array(); foreach ($part as $p) { if ($p == self::$selfSelector) { $setSelf = true; foreach ($parent as $i => $parentPart) { if ($i > 0) { $out[] = $newPart; $newPart = array(); } foreach ($parentPart as $pp) { $newPart[] = $pp; } } } else { $newPart[] = $p; } } $out[] = $newPart; } return $setSelf ? $out : array_merge($parent, $child); }
php
protected function joinSelectors($parent, $child) { $setSelf = false; $out = array(); foreach ($child as $part) { $newPart = array(); foreach ($part as $p) { if ($p == self::$selfSelector) { $setSelf = true; foreach ($parent as $i => $parentPart) { if ($i > 0) { $out[] = $newPart; $newPart = array(); } foreach ($parentPart as $pp) { $newPart[] = $pp; } } } else { $newPart[] = $p; } } $out[] = $newPart; } return $setSelf ? $out : array_merge($parent, $child); }
[ "protected", "function", "joinSelectors", "(", "$", "parent", ",", "$", "child", ")", "{", "$", "setSelf", "=", "false", ";", "$", "out", "=", "array", "(", ")", ";", "foreach", "(", "$", "child", "as", "$", "part", ")", "{", "$", "newPart", "=", ...
looks for & to replace, or append parent before child
[ "looks", "for", "&", "to", "replace", "or", "append", "parent", "before", "child" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L1130-L1157
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.coerceList
protected function coerceList($item, $delim = ",") { if (!is_null($item) && $item[0] == "list") { return $item; } return array("list", $delim, is_null($item) ? array(): array($item)); }
php
protected function coerceList($item, $delim = ",") { if (!is_null($item) && $item[0] == "list") { return $item; } return array("list", $delim, is_null($item) ? array(): array($item)); }
[ "protected", "function", "coerceList", "(", "$", "item", ",", "$", "delim", "=", "\",\"", ")", "{", "if", "(", "!", "is_null", "(", "$", "item", ")", "&&", "$", "item", "[", "0", "]", "==", "\"list\"", ")", "{", "return", "$", "item", ";", "}", ...
convert something to list
[ "convert", "something", "to", "list" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L1189-L1195
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.findImport
protected function findImport($url) { $urls = array(); // for "normal" scss imports (ignore vanilla css and external requests) if (!preg_match('/\.css|^http:\/\/$/', $url)) { // try both normal and the _partial filename $urls = array($url, preg_replace('/[^\/]+$/', '_\0', $url)); } foreach ($this->importPaths as $dir) { if (is_string($dir)) { // check urls for normal import paths foreach ($urls as $full) { $full = $dir . (!empty($dir) && substr($dir, -1) != '/' ? '/' : '') . $full; if ($this->fileExists($file = $full.'.scss') || $this->fileExists($file = $full)) { return $file; } } } else { // check custom callback for import path $file = call_user_func($dir,$url,$this); if ($file !== null) { return $file; } } } return null; }
php
protected function findImport($url) { $urls = array(); // for "normal" scss imports (ignore vanilla css and external requests) if (!preg_match('/\.css|^http:\/\/$/', $url)) { // try both normal and the _partial filename $urls = array($url, preg_replace('/[^\/]+$/', '_\0', $url)); } foreach ($this->importPaths as $dir) { if (is_string($dir)) { // check urls for normal import paths foreach ($urls as $full) { $full = $dir . (!empty($dir) && substr($dir, -1) != '/' ? '/' : '') . $full; if ($this->fileExists($file = $full.'.scss') || $this->fileExists($file = $full)) { return $file; } } } else { // check custom callback for import path $file = call_user_func($dir,$url,$this); if ($file !== null) { return $file; } } } return null; }
[ "protected", "function", "findImport", "(", "$", "url", ")", "{", "$", "urls", "=", "array", "(", ")", ";", "// for \"normal\" scss imports (ignore vanilla css and external requests)", "if", "(", "!", "preg_match", "(", "'/\\.css|^http:\\/\\/$/'", ",", "$", "url", "...
results the file path for an import url if it exists
[ "results", "the", "file", "path", "for", "an", "import", "url", "if", "it", "exists" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L1363-L1396
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scssc.toRGB
function toRGB($H, $S, $L) { $H = $H % 360; if ($H < 0) $H += 360; $S = min(100, max(0, $S)); $L = min(100, max(0, $L)); $H = $H / 360; $S = $S / 100; $L = $L / 100; if ($S == 0) { $r = $g = $b = $L; } else { $temp2 = $L < 0.5 ? $L*(1.0 + $S) : $L + $S - $L * $S; $temp1 = 2.0 * $L - $temp2; $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2); $g = $this->toRGB_helper($H, $temp1, $temp2); $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2); } $out = array('color', $r*255, $g*255, $b*255); return $out; }
php
function toRGB($H, $S, $L) { $H = $H % 360; if ($H < 0) $H += 360; $S = min(100, max(0, $S)); $L = min(100, max(0, $L)); $H = $H / 360; $S = $S / 100; $L = $L / 100; if ($S == 0) { $r = $g = $b = $L; } else { $temp2 = $L < 0.5 ? $L*(1.0 + $S) : $L + $S - $L * $S; $temp1 = 2.0 * $L - $temp2; $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2); $g = $this->toRGB_helper($H, $temp1, $temp2); $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2); } $out = array('color', $r*255, $g*255, $b*255); return $out; }
[ "function", "toRGB", "(", "$", "H", ",", "$", "S", ",", "$", "L", ")", "{", "$", "H", "=", "$", "H", "%", "360", ";", "if", "(", "$", "H", "<", "0", ")", "$", "H", "+=", "360", ";", "$", "S", "=", "min", "(", "100", ",", "max", "(", ...
H from 0 to 360, S and L from 0 to 100
[ "H", "from", "0", "to", "360", "S", "and", "L", "from", "0", "to", "100" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L1596-L1623
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scss_parser.selector
protected function selector(&$out) { $selector = array(); while (true) { if ($this->match('[>+~]+', $m)) { $selector[] = array($m[0]); } elseif ($this->selectorSingle($part)) { $selector[] = $part; $this->whitespace(); } else { break; } } if (count($selector) == 0) { return false; } $out = $selector; return true; }
php
protected function selector(&$out) { $selector = array(); while (true) { if ($this->match('[>+~]+', $m)) { $selector[] = array($m[0]); } elseif ($this->selectorSingle($part)) { $selector[] = $part; $this->whitespace(); } else { break; } } if (count($selector) == 0) { return false; } $out = $selector; return true; }
[ "protected", "function", "selector", "(", "&", "$", "out", ")", "{", "$", "selector", "=", "array", "(", ")", ";", "while", "(", "true", ")", "{", "if", "(", "$", "this", "->", "match", "(", "'[>+~]+'", ",", "$", "m", ")", ")", "{", "$", "selec...
whitespace separated list of selectorSingle
[ "whitespace", "separated", "list", "of", "selectorSingle" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L3365-L3386
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scss_parser.whitespace
protected function whitespace() { $gotWhite = false; while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) { if ($this->insertComments) { if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { $this->append(array("comment", $m[1])); $this->commentsSeen[$this->count] = true; } } $this->count += strlen($m[0]); $gotWhite = true; } return $gotWhite; }
php
protected function whitespace() { $gotWhite = false; while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) { if ($this->insertComments) { if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { $this->append(array("comment", $m[1])); $this->commentsSeen[$this->count] = true; } } $this->count += strlen($m[0]); $gotWhite = true; } return $gotWhite; }
[ "protected", "function", "whitespace", "(", ")", "{", "$", "gotWhite", "=", "false", ";", "while", "(", "preg_match", "(", "self", "::", "$", "whitePattern", ",", "$", "this", "->", "buffer", ",", "$", "m", ",", "null", ",", "$", "this", "->", "count...
match some whitespace
[ "match", "some", "whitespace" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L3626-L3639
train
Pawka/phrozn
Phrozn/Vendor/Extra/scss.inc.php
scss_formatter_nested.adjustAllChildren
public function adjustAllChildren($block) { // flatten empty nested blocks $children = array(); foreach ($block->children as $i => $child) { if (empty($child->lines) && empty($child->children)) { if (isset($block->children[$i + 1])) { $block->children[$i + 1]->depth = $child->depth; } continue; } $children[] = $child; } $count = count($children); for ($i = 0; $i < $count; $i++) { $depth = $children[$i]->depth; $j = $i + 1; if (isset($children[$j]) && $depth < $children[$j]->depth) { $childDepth = $children[$j]->depth; for (; $j < $count; $j++) { if ($depth < $children[$j]->depth && $childDepth >= $children[$j]->depth) { $children[$j]->depth = $depth + 1; } } } } $block->children = $children; // make relative to parent foreach ($block->children as $child) { $this->adjustAllChildren($child); $child->depth = $child->depth - $block->depth; } }
php
public function adjustAllChildren($block) { // flatten empty nested blocks $children = array(); foreach ($block->children as $i => $child) { if (empty($child->lines) && empty($child->children)) { if (isset($block->children[$i + 1])) { $block->children[$i + 1]->depth = $child->depth; } continue; } $children[] = $child; } $count = count($children); for ($i = 0; $i < $count; $i++) { $depth = $children[$i]->depth; $j = $i + 1; if (isset($children[$j]) && $depth < $children[$j]->depth) { $childDepth = $children[$j]->depth; for (; $j < $count; $j++) { if ($depth < $children[$j]->depth && $childDepth >= $children[$j]->depth) { $children[$j]->depth = $depth + 1; } } } } $block->children = $children; // make relative to parent foreach ($block->children as $child) { $this->adjustAllChildren($child); $child->depth = $child->depth - $block->depth; } }
[ "public", "function", "adjustAllChildren", "(", "$", "block", ")", "{", "// flatten empty nested blocks", "$", "children", "=", "array", "(", ")", ";", "foreach", "(", "$", "block", "->", "children", "as", "$", "i", "=>", "$", "child", ")", "{", "if", "(...
adjust the depths of all children, depth first
[ "adjust", "the", "depths", "of", "all", "children", "depth", "first" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Vendor/Extra/scss.inc.php#L3735-L3769
train
Pawka/phrozn
Phrozn/Registry/Dao/Serialized.php
Serialized.save
public function save() { if ($path = $this->getProjectPath()) { $path .= '/' . $this->getOutputFile(); file_put_contents($path, serialize($this->getContainer())); } else { throw new \RuntimeException('No project path provided.'); } return $this; }
php
public function save() { if ($path = $this->getProjectPath()) { $path .= '/' . $this->getOutputFile(); file_put_contents($path, serialize($this->getContainer())); } else { throw new \RuntimeException('No project path provided.'); } return $this; }
[ "public", "function", "save", "(", ")", "{", "if", "(", "$", "path", "=", "$", "this", "->", "getProjectPath", "(", ")", ")", "{", "$", "path", ".=", "'/'", ".", "$", "this", "->", "getOutputFile", "(", ")", ";", "file_put_contents", "(", "$", "pat...
Save current registry container @return \Phorzn\Registry\Dao
[ "Save", "current", "registry", "container" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Dao/Serialized.php#L42-L51
train
Pawka/phrozn
Phrozn/Registry/Dao/Serialized.php
Serialized.read
public function read() { $path = $this->getProjectPath() . '/' . $this->getOutputFile(); if (!is_readable($path)) { $this->getContainer()->setValues(null); return $this->getContainer(); } $newContainer = unserialize(file_get_contents($path)); return $newContainer; }
php
public function read() { $path = $this->getProjectPath() . '/' . $this->getOutputFile(); if (!is_readable($path)) { $this->getContainer()->setValues(null); return $this->getContainer(); } $newContainer = unserialize(file_get_contents($path)); return $newContainer; }
[ "public", "function", "read", "(", ")", "{", "$", "path", "=", "$", "this", "->", "getProjectPath", "(", ")", ".", "'/'", ".", "$", "this", "->", "getOutputFile", "(", ")", ";", "if", "(", "!", "is_readable", "(", "$", "path", ")", ")", "{", "$",...
Read registry data into container. @return \Phrozn\Registry\Container
[ "Read", "registry", "data", "into", "container", "." ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Registry/Dao/Serialized.php#L58-L67
train
Pawka/phrozn
Phrozn/Processor/Twig.php
Twig.getLoader
protected function getLoader() { $config = $this->getConfig(); $chain = new \Twig_Loader_Chain(); // use template's own directory to search for templates $paths = array($config['phr_template_dir']); // inject common paths $projectPath = new ProjectPath($config['phr_template_dir']); if ($projectPath = $projectPath->get()) { $paths[] = $projectPath . DIRECTORY_SEPARATOR . 'layouts'; $paths[] = $projectPath; } $chain->addLoader(new \Twig_Loader_Filesystem($paths)); // add string template loader, which is responsible for loading templates // and removing front-matter $chain->addLoader(new \Phrozn\Twig\Loader\String); return $chain; }
php
protected function getLoader() { $config = $this->getConfig(); $chain = new \Twig_Loader_Chain(); // use template's own directory to search for templates $paths = array($config['phr_template_dir']); // inject common paths $projectPath = new ProjectPath($config['phr_template_dir']); if ($projectPath = $projectPath->get()) { $paths[] = $projectPath . DIRECTORY_SEPARATOR . 'layouts'; $paths[] = $projectPath; } $chain->addLoader(new \Twig_Loader_Filesystem($paths)); // add string template loader, which is responsible for loading templates // and removing front-matter $chain->addLoader(new \Phrozn\Twig\Loader\String); return $chain; }
[ "protected", "function", "getLoader", "(", ")", "{", "$", "config", "=", "$", "this", "->", "getConfig", "(", ")", ";", "$", "chain", "=", "new", "\\", "Twig_Loader_Chain", "(", ")", ";", "// use template's own directory to search for templates", "$", "paths", ...
Get template loader chain @return \Twig_LoaderInterface
[ "Get", "template", "loader", "chain" ]
e46659c281986e5883559e8e2990c86de7484652
https://github.com/Pawka/phrozn/blob/e46659c281986e5883559e8e2990c86de7484652/Phrozn/Processor/Twig.php#L105-L126
train
joomla-framework/session
Session.php
Session.set
public function set($name, $value = null, $namespace = 'default') { // Add prefix to namespace to avoid collisions $namespace = '__' . $namespace; if ($this->getState() !== 'active') { return; } $old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null; if ($value === null) { unset($_SESSION[$namespace][$name]); } else { $_SESSION[$namespace][$name] = $value; } return $old; }
php
public function set($name, $value = null, $namespace = 'default') { // Add prefix to namespace to avoid collisions $namespace = '__' . $namespace; if ($this->getState() !== 'active') { return; } $old = isset($_SESSION[$namespace][$name]) ? $_SESSION[$namespace][$name] : null; if ($value === null) { unset($_SESSION[$namespace][$name]); } else { $_SESSION[$namespace][$name] = $value; } return $old; }
[ "public", "function", "set", "(", "$", "name", ",", "$", "value", "=", "null", ",", "$", "namespace", "=", "'default'", ")", "{", "// Add prefix to namespace to avoid collisions", "$", "namespace", "=", "'__'", ".", "$", "namespace", ";", "if", "(", "$", "...
Set data into the session store. @param string $name Name of a variable. @param mixed $value Value of a variable. @param string $namespace Namespace to use, default to 'default' {@deprecated 2.0 Namespace support will be removed.} @return mixed Old value of a variable. @since 1.0
[ "Set", "data", "into", "the", "session", "store", "." ]
d721b3e59388432091bfd17f828e278d6641a77e
https://github.com/joomla-framework/session/blob/d721b3e59388432091bfd17f828e278d6641a77e/Session.php#L459-L481
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.handle
public function handle() { Deprecation::notice('5.0', 'handle() will be removed. Use addToCampaign or Form directly'); $object = $this->getObject($this->data['ID'], $this->data['ClassName']); if (empty($this->data['Campaign'])) { return $this->Form($object)->forTemplate(); } else { return $this->addToCampaign($object, $this->data['Campaign']); } }
php
public function handle() { Deprecation::notice('5.0', 'handle() will be removed. Use addToCampaign or Form directly'); $object = $this->getObject($this->data['ID'], $this->data['ClassName']); if (empty($this->data['Campaign'])) { return $this->Form($object)->forTemplate(); } else { return $this->addToCampaign($object, $this->data['Campaign']); } }
[ "public", "function", "handle", "(", ")", "{", "Deprecation", "::", "notice", "(", "'5.0'", ",", "'handle() will be removed. Use addToCampaign or Form directly'", ")", ";", "$", "object", "=", "$", "this", "->", "getObject", "(", "$", "this", "->", "data", "[", ...
Perform the action. Either returns a Form or performs the action, as per the class doc @return DBHTMLText|HTTPResponse
[ "Perform", "the", "action", ".", "Either", "returns", "a", "Form", "or", "performs", "the", "action", "as", "per", "the", "class", "doc" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L99-L109
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getAvailableChangeSets
protected function getAvailableChangeSets() { return ChangeSet::get() ->filter('State', ChangeSet::STATE_OPEN) ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return $item->canView(); }); }
php
protected function getAvailableChangeSets() { return ChangeSet::get() ->filter('State', ChangeSet::STATE_OPEN) ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return $item->canView(); }); }
[ "protected", "function", "getAvailableChangeSets", "(", ")", "{", "return", "ChangeSet", "::", "get", "(", ")", "->", "filter", "(", "'State'", ",", "ChangeSet", "::", "STATE_OPEN", ")", "->", "filterByCallback", "(", "function", "(", "$", "item", ")", "{", ...
Get what ChangeSets are available for an item to be added to by this user @return ArrayList|ChangeSet[]
[ "Get", "what", "ChangeSets", "are", "available", "for", "an", "item", "to", "be", "added", "to", "by", "this", "user" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L116-L124
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getInChangeSets
protected function getInChangeSets($object) { $inChangeSetIDs = array_unique(ChangeSetItem::get_for_object($object)->column('ChangeSetID')); if ($inChangeSetIDs > 0) { $changeSets = $this->getAvailableChangeSets()->filter([ 'ID' => $inChangeSetIDs, 'State' => ChangeSet::STATE_OPEN ]); } else { $changeSets = new ArrayList(); } return $changeSets; }
php
protected function getInChangeSets($object) { $inChangeSetIDs = array_unique(ChangeSetItem::get_for_object($object)->column('ChangeSetID')); if ($inChangeSetIDs > 0) { $changeSets = $this->getAvailableChangeSets()->filter([ 'ID' => $inChangeSetIDs, 'State' => ChangeSet::STATE_OPEN ]); } else { $changeSets = new ArrayList(); } return $changeSets; }
[ "protected", "function", "getInChangeSets", "(", "$", "object", ")", "{", "$", "inChangeSetIDs", "=", "array_unique", "(", "ChangeSetItem", "::", "get_for_object", "(", "$", "object", ")", "->", "column", "(", "'ChangeSetID'", ")", ")", ";", "if", "(", "$", ...
Get changesets that a given object is already in @param DataObject @return ArrayList[ChangeSet]
[ "Get", "changesets", "that", "a", "given", "object", "is", "already", "in" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L132-L145
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.Form
public function Form($object) { $inChangeSets = $this->getInChangeSets($object); $inChangeSetIDs = $inChangeSets->column('ID'); // Get changesets that can be added to $candidateChangeSets = $this->getAvailableChangeSets(); if ($inChangeSetIDs) { $candidateChangeSets = $candidateChangeSets->exclude('ID', $inChangeSetIDs); } $canCreate = ChangeSet::singleton()->canCreate(); $message = $this->getFormAlert($inChangeSets, $candidateChangeSets, $canCreate); $fields = new FieldList(array_filter([ $message ? LiteralField::create("AlertMessages", $message) : null, HiddenField::create('ID', null, $object->ID), HiddenField::create('ClassName', null, $object->baseClass()) ])); // Add fields based on available options $showSelect = $candidateChangeSets->count() > 0; if ($showSelect) { $campaignDropdown = DropdownField::create( 'Campaign', _t(__CLASS__ . '.AddToCampaignAvailableLabel', 'Available campaigns'), $candidateChangeSets ) ->setEmptyString(_t(__CLASS__ . '.AddToCampaignFormFieldLabel', 'Select a Campaign')) ->addExtraClass('noborder') ->addExtraClass('no-chosen'); $fields->push($campaignDropdown); // Show visibilty toggle of other create field if ($canCreate) { $addCampaignSelect = CheckboxField::create('AddNewSelect', _t( __CLASS__ . '.ADD_TO_A_NEW_CAMPAIGN', 'Add to a new campaign' )) ->setAttribute('data-shows', 'NewTitle') ->setSchemaData(['data' => ['shows' => 'NewTitle']]); $fields->push($addCampaignSelect); } } if ($canCreate) { $placeholder = _t(__CLASS__ . '.CREATE_NEW_PLACEHOLDER', 'Enter campaign name'); $createBox = TextField::create( 'NewTitle', _t(__CLASS__ . '.CREATE_NEW', 'Create a new campaign') ) ->setAttribute('placeholder', $placeholder) ->setSchemaData(['attributes' => ['placeholder' => $placeholder]]); $fields->push($createBox); } $actions = FieldList::create(); if ($canCreate || $showSelect) { $actions->push( AddToCampaignHandler_FormAction::create() ->setTitle(_t(__CLASS__ . '.AddToCampaignAddAction', 'Add')) ->addExtraClass('add-to-campaign__action') ); } $form = Form::create( $this->controller, $this->name, $fields, $actions, AddToCampaignValidator::create() ); $form->setHTMLID('Form_EditForm_AddToCampaign'); $form->addExtraClass('form--no-dividers add-to-campaign__form'); return $form; }
php
public function Form($object) { $inChangeSets = $this->getInChangeSets($object); $inChangeSetIDs = $inChangeSets->column('ID'); // Get changesets that can be added to $candidateChangeSets = $this->getAvailableChangeSets(); if ($inChangeSetIDs) { $candidateChangeSets = $candidateChangeSets->exclude('ID', $inChangeSetIDs); } $canCreate = ChangeSet::singleton()->canCreate(); $message = $this->getFormAlert($inChangeSets, $candidateChangeSets, $canCreate); $fields = new FieldList(array_filter([ $message ? LiteralField::create("AlertMessages", $message) : null, HiddenField::create('ID', null, $object->ID), HiddenField::create('ClassName', null, $object->baseClass()) ])); // Add fields based on available options $showSelect = $candidateChangeSets->count() > 0; if ($showSelect) { $campaignDropdown = DropdownField::create( 'Campaign', _t(__CLASS__ . '.AddToCampaignAvailableLabel', 'Available campaigns'), $candidateChangeSets ) ->setEmptyString(_t(__CLASS__ . '.AddToCampaignFormFieldLabel', 'Select a Campaign')) ->addExtraClass('noborder') ->addExtraClass('no-chosen'); $fields->push($campaignDropdown); // Show visibilty toggle of other create field if ($canCreate) { $addCampaignSelect = CheckboxField::create('AddNewSelect', _t( __CLASS__ . '.ADD_TO_A_NEW_CAMPAIGN', 'Add to a new campaign' )) ->setAttribute('data-shows', 'NewTitle') ->setSchemaData(['data' => ['shows' => 'NewTitle']]); $fields->push($addCampaignSelect); } } if ($canCreate) { $placeholder = _t(__CLASS__ . '.CREATE_NEW_PLACEHOLDER', 'Enter campaign name'); $createBox = TextField::create( 'NewTitle', _t(__CLASS__ . '.CREATE_NEW', 'Create a new campaign') ) ->setAttribute('placeholder', $placeholder) ->setSchemaData(['attributes' => ['placeholder' => $placeholder]]); $fields->push($createBox); } $actions = FieldList::create(); if ($canCreate || $showSelect) { $actions->push( AddToCampaignHandler_FormAction::create() ->setTitle(_t(__CLASS__ . '.AddToCampaignAddAction', 'Add')) ->addExtraClass('add-to-campaign__action') ); } $form = Form::create( $this->controller, $this->name, $fields, $actions, AddToCampaignValidator::create() ); $form->setHTMLID('Form_EditForm_AddToCampaign'); $form->addExtraClass('form--no-dividers add-to-campaign__form'); return $form; }
[ "public", "function", "Form", "(", "$", "object", ")", "{", "$", "inChangeSets", "=", "$", "this", "->", "getInChangeSets", "(", "$", "object", ")", ";", "$", "inChangeSetIDs", "=", "$", "inChangeSets", "->", "column", "(", "'ID'", ")", ";", "// Get chan...
Builds a Form that mirrors the parent editForm, but with an extra field to collect the ChangeSet ID @param DataObject $object The object we're going to be adding to whichever ChangeSet is chosen @return Form
[ "Builds", "a", "Form", "that", "mirrors", "the", "parent", "editForm", "but", "with", "an", "extra", "field", "to", "collect", "the", "ChangeSet", "ID" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L203-L278
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.addToCampaign
public function addToCampaign($object, $data) { // Extract $campaignID from $data $campaignID = $this->getOrCreateCampaign($data); /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($campaignID); if (!$changeSet) { throw new ValidationException(_t( __CLASS__ . '.ErrorNotFound', 'That {Type} couldn\'t be found', ['Type' => 'Campaign'] )); } if (!$changeSet->canEdit()) { throw new ValidationException(_t( __CLASS__ . '.ErrorCampaignPermissionDenied', 'It seems you don\'t have the necessary permissions to add {ObjectTitle} to {CampaignTitle}', [ 'ObjectTitle' => $object->Title, 'CampaignTitle' => $changeSet->Title ] )); } $changeSet->addObject($object); $request = $this->controller->getRequest(); $message = _t( __CLASS__ . '.Success', 'Successfully added <strong>{ObjectTitle}</strong> to <strong>{CampaignTitle}</strong>', [ 'ObjectTitle' => Convert::raw2xml($object->Title), 'CampaignTitle' => Convert::raw2xml($changeSet->Title) ] ); if ($request->getHeader('X-Formschema-Request')) { return $message; } elseif (Director::is_ajax()) { $response = new HTTPResponse($message, 200); $response->addHeader('Content-Type', 'text/html; charset=utf-8'); return $response; } else { return $this->controller->redirectBack(); } }
php
public function addToCampaign($object, $data) { // Extract $campaignID from $data $campaignID = $this->getOrCreateCampaign($data); /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($campaignID); if (!$changeSet) { throw new ValidationException(_t( __CLASS__ . '.ErrorNotFound', 'That {Type} couldn\'t be found', ['Type' => 'Campaign'] )); } if (!$changeSet->canEdit()) { throw new ValidationException(_t( __CLASS__ . '.ErrorCampaignPermissionDenied', 'It seems you don\'t have the necessary permissions to add {ObjectTitle} to {CampaignTitle}', [ 'ObjectTitle' => $object->Title, 'CampaignTitle' => $changeSet->Title ] )); } $changeSet->addObject($object); $request = $this->controller->getRequest(); $message = _t( __CLASS__ . '.Success', 'Successfully added <strong>{ObjectTitle}</strong> to <strong>{CampaignTitle}</strong>', [ 'ObjectTitle' => Convert::raw2xml($object->Title), 'CampaignTitle' => Convert::raw2xml($changeSet->Title) ] ); if ($request->getHeader('X-Formschema-Request')) { return $message; } elseif (Director::is_ajax()) { $response = new HTTPResponse($message, 200); $response->addHeader('Content-Type', 'text/html; charset=utf-8'); return $response; } else { return $this->controller->redirectBack(); } }
[ "public", "function", "addToCampaign", "(", "$", "object", ",", "$", "data", ")", "{", "// Extract $campaignID from $data", "$", "campaignID", "=", "$", "this", "->", "getOrCreateCampaign", "(", "$", "data", ")", ";", "/** @var ChangeSet $changeSet */", "$", "chan...
Performs the actual action of adding the object to the ChangeSet, once the ChangeSet ID is known @param DataObject $object The object to add to the ChangeSet @param array|int $data Post data for this campaign form, or the ID of the campaign to add to @return HTTPResponse @throws ValidationException
[ "Performs", "the", "actual", "action", "of", "adding", "the", "object", "to", "the", "ChangeSet", "once", "the", "ChangeSet", "ID", "is", "known" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L288-L336
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getFormAlert
protected function getFormAlert($inChangeSets, $candidateChangeSets, $canCreate) { // In a subset of changesets if ($inChangeSets->count() > 0 && $candidateChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabel', 'Heads up, this item is already in campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // In all changesets if ($inChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabelAll', 'Heads up, this item is already in ALL campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // Create only if ($candidateChangeSets->count() === 0 && $canCreate) { return sprintf( '<div class="alert alert-info">%s</div>', _t( __CLASS__ . '.NO_CAMPAIGNS', "You currently don't have any campaigns. " . "You can edit campaign details later in the Campaigns section." ) ); } // Can't select or create if ($candidateChangeSets->count() === 0 && !$canCreate) { return sprintf( '<div class="alert alert-warning">%s</div>', _t( __CLASS__ . '.NO_CREATE', "Oh no! You currently don't have any campaigns created. " . "Your current login does not have privileges to create campaigns. " . "Campaigns can only be created by users with Campaigns section rights." ) ); } return null; }
php
protected function getFormAlert($inChangeSets, $candidateChangeSets, $canCreate) { // In a subset of changesets if ($inChangeSets->count() > 0 && $candidateChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabel', 'Heads up, this item is already in campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // In all changesets if ($inChangeSets->count() > 0) { return sprintf( '<div class="alert alert-info"><strong>%s</strong><br/>%s</div>', _t( __CLASS__ . '.AddToCampaignInChangsetLabelAll', 'Heads up, this item is already in ALL campaign(s):' ), Convert::raw2xml(implode(', ', $inChangeSets->column('Name'))) ); } // Create only if ($candidateChangeSets->count() === 0 && $canCreate) { return sprintf( '<div class="alert alert-info">%s</div>', _t( __CLASS__ . '.NO_CAMPAIGNS', "You currently don't have any campaigns. " . "You can edit campaign details later in the Campaigns section." ) ); } // Can't select or create if ($candidateChangeSets->count() === 0 && !$canCreate) { return sprintf( '<div class="alert alert-warning">%s</div>', _t( __CLASS__ . '.NO_CREATE', "Oh no! You currently don't have any campaigns created. " . "Your current login does not have privileges to create campaigns. " . "Campaigns can only be created by users with Campaigns section rights." ) ); } return null; }
[ "protected", "function", "getFormAlert", "(", "$", "inChangeSets", ",", "$", "candidateChangeSets", ",", "$", "canCreate", ")", "{", "// In a subset of changesets", "if", "(", "$", "inChangeSets", "->", "count", "(", ")", ">", "0", "&&", "$", "candidateChangeSet...
Get descriptive alert to display at the top of the form @param ArrayList $inChangeSets List of changesets this item exists in @param ArrayList $candidateChangeSets List of changesets this item could be added to @param bool $canCreate @return string
[ "Get", "descriptive", "alert", "to", "display", "at", "the", "top", "of", "the", "form" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L346-L397
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.getOrCreateCampaign
protected function getOrCreateCampaign($data) { // Create new campaign if selected if (is_array($data) && !empty($data['AddNewSelect']) // Explicitly click "Add to a new campaign" || (is_array($data) && !isset($data['Campaign']) && isset($data['NewTitle'])) // This is the only option ) { // Permission if (!ChangeSet::singleton()->canCreate()) { throw $this->validationResult( _t(__CLASS__ . '.CREATE_DENIED', 'You do not have permission to create campaigns') ); } // Check title is valid $title = $data['NewTitle']; if (empty($title)) { throw $this->validationResult( _t(__CLASS__ . '.MISSING_TITLE', 'Campaign name is required'), 'NewTitle' ); } // Prevent duplicates $hasExistingName = Changeset::get() ->filter('Name:nocase', $title) ->count() > 0; if ($hasExistingName) { throw $this->validationResult( _t( 'SilverStripe\\CampaignAdmin\\CampaignAdmin.ERROR_DUPLICATE_NAME', 'Name "{Name}" already exists', ['Name' => $title] ), 'NewTitle' ); } // Create and return $campaign = ChangeSet::create(); $campaign->Name = $title; $campaign->write(); return $campaign->ID; } // Get selected campaign ID $campaignID = null; if (is_array($data) && !empty($data['Campaign'])) { $campaignID = $data['Campaign']; } elseif (is_numeric($data)) { $campaignID = (int)$data; } if (empty($campaignID)) { throw $this->validationResult(_t(__CLASS__ . '.NONE_SELECTED', 'No campaign selected')); } return $campaignID; }
php
protected function getOrCreateCampaign($data) { // Create new campaign if selected if (is_array($data) && !empty($data['AddNewSelect']) // Explicitly click "Add to a new campaign" || (is_array($data) && !isset($data['Campaign']) && isset($data['NewTitle'])) // This is the only option ) { // Permission if (!ChangeSet::singleton()->canCreate()) { throw $this->validationResult( _t(__CLASS__ . '.CREATE_DENIED', 'You do not have permission to create campaigns') ); } // Check title is valid $title = $data['NewTitle']; if (empty($title)) { throw $this->validationResult( _t(__CLASS__ . '.MISSING_TITLE', 'Campaign name is required'), 'NewTitle' ); } // Prevent duplicates $hasExistingName = Changeset::get() ->filter('Name:nocase', $title) ->count() > 0; if ($hasExistingName) { throw $this->validationResult( _t( 'SilverStripe\\CampaignAdmin\\CampaignAdmin.ERROR_DUPLICATE_NAME', 'Name "{Name}" already exists', ['Name' => $title] ), 'NewTitle' ); } // Create and return $campaign = ChangeSet::create(); $campaign->Name = $title; $campaign->write(); return $campaign->ID; } // Get selected campaign ID $campaignID = null; if (is_array($data) && !empty($data['Campaign'])) { $campaignID = $data['Campaign']; } elseif (is_numeric($data)) { $campaignID = (int)$data; } if (empty($campaignID)) { throw $this->validationResult(_t(__CLASS__ . '.NONE_SELECTED', 'No campaign selected')); } return $campaignID; }
[ "protected", "function", "getOrCreateCampaign", "(", "$", "data", ")", "{", "// Create new campaign if selected", "if", "(", "is_array", "(", "$", "data", ")", "&&", "!", "empty", "(", "$", "data", "[", "'AddNewSelect'", "]", ")", "// Explicitly click \"Add to a n...
Find or build campaign from posted data @param array|int $data @return int @throws ValidationException
[ "Find", "or", "build", "campaign", "from", "posted", "data" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L406-L462
train
silverstripe/silverstripe-campaign-admin
src/AddToCampaignHandler.php
AddToCampaignHandler.validationResult
protected function validationResult($message, $field = null) { $error = ValidationResult::create() ->addFieldError($field, $message); return new ValidationException($error); }
php
protected function validationResult($message, $field = null) { $error = ValidationResult::create() ->addFieldError($field, $message); return new ValidationException($error); }
[ "protected", "function", "validationResult", "(", "$", "message", ",", "$", "field", "=", "null", ")", "{", "$", "error", "=", "ValidationResult", "::", "create", "(", ")", "->", "addFieldError", "(", "$", "field", ",", "$", "message", ")", ";", "return"...
Raise validation error @param string $message @param string $field @return ValidationException
[ "Raise", "validation", "error" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/AddToCampaignHandler.php#L471-L476
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.readCampaigns
public function readCampaigns() { $response = new HTTPResponse(); $response->addHeader('Content-Type', 'application/json'); $hal = $this->getListResource(); $response->setBody(json_encode($hal)); return $response; }
php
public function readCampaigns() { $response = new HTTPResponse(); $response->addHeader('Content-Type', 'application/json'); $hal = $this->getListResource(); $response->setBody(json_encode($hal)); return $response; }
[ "public", "function", "readCampaigns", "(", ")", "{", "$", "response", "=", "new", "HTTPResponse", "(", ")", ";", "$", "response", "->", "addHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "$", "hal", "=", "$", "this", "->", "getListRe...
REST endpoint to get a list of campaigns. @return HTTPResponse
[ "REST", "endpoint", "to", "get", "a", "list", "of", "campaigns", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L190-L197
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getListResource
protected function getListResource() { $items = $this->getListItems(); $count = $items->count(); /** @var string $treeClass */ $treeClass = $this->config()->get('tree_class'); $hal = [ 'count' => $count, 'total' => $count, '_links' => [ 'self' => [ 'href' => $this->Link('items') ] ], '_embedded' => [$treeClass => []] ]; /** @var ChangeSet $item */ foreach ($items as $item) { $sync = $this->shouldCampaignSync($item); $resource = $this->getChangeSetResource($item, $sync); $hal['_embedded'][$treeClass][] = $resource; } return $hal; }
php
protected function getListResource() { $items = $this->getListItems(); $count = $items->count(); /** @var string $treeClass */ $treeClass = $this->config()->get('tree_class'); $hal = [ 'count' => $count, 'total' => $count, '_links' => [ 'self' => [ 'href' => $this->Link('items') ] ], '_embedded' => [$treeClass => []] ]; /** @var ChangeSet $item */ foreach ($items as $item) { $sync = $this->shouldCampaignSync($item); $resource = $this->getChangeSetResource($item, $sync); $hal['_embedded'][$treeClass][] = $resource; } return $hal; }
[ "protected", "function", "getListResource", "(", ")", "{", "$", "items", "=", "$", "this", "->", "getListItems", "(", ")", ";", "$", "count", "=", "$", "items", "->", "count", "(", ")", ";", "/** @var string $treeClass */", "$", "treeClass", "=", "$", "t...
Get list contained as a hal wrapper @return array
[ "Get", "list", "contained", "as", "a", "hal", "wrapper" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L235-L258
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getChangeSetResource
protected function getChangeSetResource(ChangeSet $changeSet, $sync = false) { $stateLabel = sprintf( '<span class="campaign-status campaign-status--%s"></span>%s', $changeSet->State, $changeSet->getStateLabel() ); $hal = [ '_links' => [ 'self' => [ 'href' => $this->SetLink($changeSet->ID) ] ], 'ID' => $changeSet->ID, 'Name' => $changeSet->Name, 'Created' => $changeSet->Created, 'LastEdited' => $changeSet->LastEdited, 'State' => $changeSet->State, 'StateLabel' => [ 'html' => $stateLabel ], 'IsInferred' => $changeSet->IsInferred, 'canEdit' => $changeSet->canEdit(), 'canPublish' => false, '_embedded' => ['items' => []], 'placeholderGroups' => $this->getPlaceholderGroups(), ]; // Before presenting the changeset to the client, // synchronise it with new changes. try { if ($sync) { $changeSet->sync(); } $hal['PublishedLabel'] = $changeSet->getPublishedLabel() ?: '-'; $hal['Details'] = $changeSet->getDetails(); $hal['canPublish'] = $changeSet->canPublish() && $changeSet->hasChanges(); foreach ($changeSet->Changes() as $changeSetItem) { if (!$changeSetItem) { continue; } /** @var ChangesetItem $changeSetItem */ $resource = $this->getChangeSetItemResource($changeSetItem); if (!empty($resource)) { $hal['_embedded']['items'][] = $resource; } } // An unexpected data exception means that the database is corrupt } catch (UnexpectedDataException $e) { $hal['PublishedLabel'] = '-'; $hal['Details'] = 'Corrupt database! ' . $e->getMessage(); $hal['canPublish'] = false; } return $hal; }
php
protected function getChangeSetResource(ChangeSet $changeSet, $sync = false) { $stateLabel = sprintf( '<span class="campaign-status campaign-status--%s"></span>%s', $changeSet->State, $changeSet->getStateLabel() ); $hal = [ '_links' => [ 'self' => [ 'href' => $this->SetLink($changeSet->ID) ] ], 'ID' => $changeSet->ID, 'Name' => $changeSet->Name, 'Created' => $changeSet->Created, 'LastEdited' => $changeSet->LastEdited, 'State' => $changeSet->State, 'StateLabel' => [ 'html' => $stateLabel ], 'IsInferred' => $changeSet->IsInferred, 'canEdit' => $changeSet->canEdit(), 'canPublish' => false, '_embedded' => ['items' => []], 'placeholderGroups' => $this->getPlaceholderGroups(), ]; // Before presenting the changeset to the client, // synchronise it with new changes. try { if ($sync) { $changeSet->sync(); } $hal['PublishedLabel'] = $changeSet->getPublishedLabel() ?: '-'; $hal['Details'] = $changeSet->getDetails(); $hal['canPublish'] = $changeSet->canPublish() && $changeSet->hasChanges(); foreach ($changeSet->Changes() as $changeSetItem) { if (!$changeSetItem) { continue; } /** @var ChangesetItem $changeSetItem */ $resource = $this->getChangeSetItemResource($changeSetItem); if (!empty($resource)) { $hal['_embedded']['items'][] = $resource; } } // An unexpected data exception means that the database is corrupt } catch (UnexpectedDataException $e) { $hal['PublishedLabel'] = '-'; $hal['Details'] = 'Corrupt database! ' . $e->getMessage(); $hal['canPublish'] = false; } return $hal; }
[ "protected", "function", "getChangeSetResource", "(", "ChangeSet", "$", "changeSet", ",", "$", "sync", "=", "false", ")", "{", "$", "stateLabel", "=", "sprintf", "(", "'<span class=\"campaign-status campaign-status--%s\"></span>%s'", ",", "$", "changeSet", "->", "Stat...
Build item resource from a changeset @param ChangeSet $changeSet @param bool $sync Set to true to force async of this changeset @return array
[ "Build", "item", "resource", "from", "a", "changeset" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L267-L323
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getChangeSetItemResource
protected function getChangeSetItemResource(ChangeSetItem $changeSetItem) { $baseClass = DataObject::getSchema()->baseDataClass($changeSetItem->ObjectClass); $baseSingleton = DataObject::singleton($baseClass); // Allow items to opt out of being displayed in changesets if ($baseSingleton->config()->get('hide_in_campaigns')) { return []; } $thumbnailWidth = (int)$this->config()->get('thumbnail_width'); $thumbnailHeight = (int)$this->config()->get('thumbnail_height'); $hal = [ '_links' => [ 'self' => [ 'id' => $changeSetItem->ID, 'href' => $this->ItemLink($changeSetItem->ID) ] ], 'ID' => $changeSetItem->ID, 'Created' => $changeSetItem->Created, 'LastEdited' => $changeSetItem->LastEdited, 'Title' => $changeSetItem->getTitle(), 'ChangeType' => $changeSetItem->getChangeType(), 'Added' => $changeSetItem->Added, 'ObjectClass' => $changeSetItem->ObjectClass, 'ObjectID' => $changeSetItem->ObjectID, 'BaseClass' => $baseClass, 'Singular' => $baseSingleton->i18n_singular_name(), 'Plural' => $baseSingleton->i18n_plural_name(), 'Thumbnail' => $changeSetItem->ThumbnailURL($thumbnailWidth, $thumbnailHeight), ]; // Get preview urls $previews = $changeSetItem->getPreviewLinks(); if ($previews) { $hal['_links']['preview'] = $previews; } // Get edit link $editLink = $changeSetItem->CMSEditLink(); if ($editLink) { $hal['_links']['edit'] = [ 'href' => $editLink, ]; } // Depending on whether the object was added implicitly or explicitly, set // other related objects. if ($changeSetItem->Added === ChangeSetItem::IMPLICITLY) { $referencedItems = $changeSetItem->ReferencedBy(); $referencedBy = []; foreach ($referencedItems as $referencedItem) { $referencedBy[] = [ 'href' => $this->SetLink($referencedItem->ID), 'ChangeSetItemID' => $referencedItem->ID ]; } if ($referencedBy) { $hal['_links']['referenced_by'] = $referencedBy; } } $referToItems = $changeSetItem->References(); $referTo = []; foreach ($referToItems as $referToItem) { $referTo[] = [ 'ChangeSetItemID' => $referToItem->ID, ]; } $hal['_links']['references'] = $referTo; return $hal; }
php
protected function getChangeSetItemResource(ChangeSetItem $changeSetItem) { $baseClass = DataObject::getSchema()->baseDataClass($changeSetItem->ObjectClass); $baseSingleton = DataObject::singleton($baseClass); // Allow items to opt out of being displayed in changesets if ($baseSingleton->config()->get('hide_in_campaigns')) { return []; } $thumbnailWidth = (int)$this->config()->get('thumbnail_width'); $thumbnailHeight = (int)$this->config()->get('thumbnail_height'); $hal = [ '_links' => [ 'self' => [ 'id' => $changeSetItem->ID, 'href' => $this->ItemLink($changeSetItem->ID) ] ], 'ID' => $changeSetItem->ID, 'Created' => $changeSetItem->Created, 'LastEdited' => $changeSetItem->LastEdited, 'Title' => $changeSetItem->getTitle(), 'ChangeType' => $changeSetItem->getChangeType(), 'Added' => $changeSetItem->Added, 'ObjectClass' => $changeSetItem->ObjectClass, 'ObjectID' => $changeSetItem->ObjectID, 'BaseClass' => $baseClass, 'Singular' => $baseSingleton->i18n_singular_name(), 'Plural' => $baseSingleton->i18n_plural_name(), 'Thumbnail' => $changeSetItem->ThumbnailURL($thumbnailWidth, $thumbnailHeight), ]; // Get preview urls $previews = $changeSetItem->getPreviewLinks(); if ($previews) { $hal['_links']['preview'] = $previews; } // Get edit link $editLink = $changeSetItem->CMSEditLink(); if ($editLink) { $hal['_links']['edit'] = [ 'href' => $editLink, ]; } // Depending on whether the object was added implicitly or explicitly, set // other related objects. if ($changeSetItem->Added === ChangeSetItem::IMPLICITLY) { $referencedItems = $changeSetItem->ReferencedBy(); $referencedBy = []; foreach ($referencedItems as $referencedItem) { $referencedBy[] = [ 'href' => $this->SetLink($referencedItem->ID), 'ChangeSetItemID' => $referencedItem->ID ]; } if ($referencedBy) { $hal['_links']['referenced_by'] = $referencedBy; } } $referToItems = $changeSetItem->References(); $referTo = []; foreach ($referToItems as $referToItem) { $referTo[] = [ 'ChangeSetItemID' => $referToItem->ID, ]; } $hal['_links']['references'] = $referTo; return $hal; }
[ "protected", "function", "getChangeSetItemResource", "(", "ChangeSetItem", "$", "changeSetItem", ")", "{", "$", "baseClass", "=", "DataObject", "::", "getSchema", "(", ")", "->", "baseDataClass", "(", "$", "changeSetItem", "->", "ObjectClass", ")", ";", "$", "ba...
Build item resource from a changesetitem @param ChangeSetItem $changeSetItem @return array
[ "Build", "item", "resource", "from", "a", "changesetitem" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L331-L403
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.getListItems
protected function getListItems() { $changesets = ChangeSet::get(); // Filter out published items if disabled if (!$this->config()->get('show_published')) { $changesets = $changesets->filter('State', ChangeSet::STATE_OPEN); } // Filter out automatically created changesets if (!$this->config()->get('show_inferred')) { $changesets = $changesets->filter('IsInferred', 0); } return $changesets ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return ($item->canView()); }); }
php
protected function getListItems() { $changesets = ChangeSet::get(); // Filter out published items if disabled if (!$this->config()->get('show_published')) { $changesets = $changesets->filter('State', ChangeSet::STATE_OPEN); } // Filter out automatically created changesets if (!$this->config()->get('show_inferred')) { $changesets = $changesets->filter('IsInferred', 0); } return $changesets ->filterByCallback(function ($item) { /** @var ChangeSet $item */ return ($item->canView()); }); }
[ "protected", "function", "getListItems", "(", ")", "{", "$", "changesets", "=", "ChangeSet", "::", "get", "(", ")", ";", "// Filter out published items if disabled", "if", "(", "!", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'show_published'", ...
Gets viewable list of campaigns @return SS_List
[ "Gets", "viewable", "list", "of", "campaigns" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L410-L426
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.readCampaign
public function readCampaign(HTTPRequest $request) { $response = new HTTPResponse(); $accepts = $request->getAcceptMimetypes(); //accept 'text/json' for legacy reasons if (in_array('application/json', $accepts) || in_array('text/json', $accepts)) { $response->addHeader('Content-Type', 'application/json'); if (!$request->param('Name')) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($request->param('ID')); if (!$changeSet) { return (new HTTPResponse(null, 404)); } if (!$changeSet->canView()) { return (new HTTPResponse(null, 403)); } $body = json_encode($this->getChangeSetResource($changeSet, true)); return (new HTTPResponse($body, 200)) ->addHeader('Content-Type', 'application/json'); } else { return $this->index($request); } }
php
public function readCampaign(HTTPRequest $request) { $response = new HTTPResponse(); $accepts = $request->getAcceptMimetypes(); //accept 'text/json' for legacy reasons if (in_array('application/json', $accepts) || in_array('text/json', $accepts)) { $response->addHeader('Content-Type', 'application/json'); if (!$request->param('Name')) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $changeSet */ $changeSet = ChangeSet::get()->byID($request->param('ID')); if (!$changeSet) { return (new HTTPResponse(null, 404)); } if (!$changeSet->canView()) { return (new HTTPResponse(null, 403)); } $body = json_encode($this->getChangeSetResource($changeSet, true)); return (new HTTPResponse($body, 200)) ->addHeader('Content-Type', 'application/json'); } else { return $this->index($request); } }
[ "public", "function", "readCampaign", "(", "HTTPRequest", "$", "request", ")", "{", "$", "response", "=", "new", "HTTPResponse", "(", ")", ";", "$", "accepts", "=", "$", "request", "->", "getAcceptMimetypes", "(", ")", ";", "//accept 'text/json' for legacy reaso...
REST endpoint to get a campaign. @param HTTPRequest $request @return HTTPResponse
[ "REST", "endpoint", "to", "get", "a", "campaign", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L436-L464
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.removeCampaignItem
public function removeCampaignItem(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $campaignID = $request->param('CampaignID'); $itemID = $request->param('ItemID'); if (!$campaignID || !is_numeric($campaignID) || !$itemID || !is_numeric($itemID)) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $campaign */ $campaign = ChangeSet::get()->byID($campaignID); /** @var ChangeSetItem $item */ $item = ChangeSetItem::get()->byID($itemID); if (!$campaign || !$item) { return (new HTTPResponse(null, 404)); } $campaign->removeObject($item->Object()); return (new HTTPResponse(null, 204)); }
php
public function removeCampaignItem(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $campaignID = $request->param('CampaignID'); $itemID = $request->param('ItemID'); if (!$campaignID || !is_numeric($campaignID) || !$itemID || !is_numeric($itemID)) { return (new HTTPResponse(null, 400)); } /** @var ChangeSet $campaign */ $campaign = ChangeSet::get()->byID($campaignID); /** @var ChangeSetItem $item */ $item = ChangeSetItem::get()->byID($itemID); if (!$campaign || !$item) { return (new HTTPResponse(null, 404)); } $campaign->removeObject($item->Object()); return (new HTTPResponse(null, 204)); }
[ "public", "function", "removeCampaignItem", "(", "HTTPRequest", "$", "request", ")", "{", "// Check security ID", "if", "(", "!", "SecurityToken", "::", "inst", "(", ")", "->", "checkRequest", "(", "$", "request", ")", ")", "{", "return", "new", "HTTPResponse"...
REST endpoint to delete a campaign item. @param HTTPRequest $request @return HTTPResponse
[ "REST", "endpoint", "to", "delete", "a", "campaign", "item", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L473-L502
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.deleteCampaign
public function deleteCampaign(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $id = $request->param('ID'); if (!$id || !is_numeric($id)) { return (new HTTPResponse(null, 400)); } $record = ChangeSet::get()->byID($id); if (!$record) { return (new HTTPResponse(null, 404)); } if (!$record->canDelete()) { return (new HTTPResponse(null, 403)); } $record->delete(); return (new HTTPResponse(null, 204)); }
php
public function deleteCampaign(HTTPRequest $request) { // Check security ID if (!SecurityToken::inst()->checkRequest($request)) { return new HTTPResponse(null, 400); } $id = $request->param('ID'); if (!$id || !is_numeric($id)) { return (new HTTPResponse(null, 400)); } $record = ChangeSet::get()->byID($id); if (!$record) { return (new HTTPResponse(null, 404)); } if (!$record->canDelete()) { return (new HTTPResponse(null, 403)); } $record->delete(); return (new HTTPResponse(null, 204)); }
[ "public", "function", "deleteCampaign", "(", "HTTPRequest", "$", "request", ")", "{", "// Check security ID", "if", "(", "!", "SecurityToken", "::", "inst", "(", ")", "->", "checkRequest", "(", "$", "request", ")", ")", "{", "return", "new", "HTTPResponse", ...
REST endpoint to delete a campaign. @param HTTPRequest $request @return HTTPResponse
[ "REST", "endpoint", "to", "delete", "a", "campaign", "." ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L511-L535
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.campaignEditForm
public function campaignEditForm($request) { // Get ID either from posted back value, or url parameter if (!$request) { $this->httpError(400); return null; } $id = $request->param('ID'); if (!$id) { $this->httpError(400); return null; } return $this->getCampaignEditForm($id); }
php
public function campaignEditForm($request) { // Get ID either from posted back value, or url parameter if (!$request) { $this->httpError(400); return null; } $id = $request->param('ID'); if (!$id) { $this->httpError(400); return null; } return $this->getCampaignEditForm($id); }
[ "public", "function", "campaignEditForm", "(", "$", "request", ")", "{", "// Get ID either from posted back value, or url parameter", "if", "(", "!", "$", "request", ")", "{", "$", "this", "->", "httpError", "(", "400", ")", ";", "return", "null", ";", "}", "$...
Url handler for edit form @param HTTPRequest $request @return Form
[ "Url", "handler", "for", "edit", "form" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L585-L598
train
silverstripe/silverstripe-campaign-admin
src/CampaignAdmin.php
CampaignAdmin.shouldCampaignSync
protected function shouldCampaignSync(ChangeSet $item) { // Don't sync published changesets if ($item->State !== ChangeSet::STATE_OPEN) { return false; } // Get sync threshold $syncOlderThan = DBDatetime::now()->getTimestamp() - $this->config()->get('sync_expires'); /** @var DBDatetime $lastSynced */ $lastSynced = $item->dbObject('LastSynced'); return !$lastSynced || $lastSynced->getTimestamp() < $syncOlderThan; }
php
protected function shouldCampaignSync(ChangeSet $item) { // Don't sync published changesets if ($item->State !== ChangeSet::STATE_OPEN) { return false; } // Get sync threshold $syncOlderThan = DBDatetime::now()->getTimestamp() - $this->config()->get('sync_expires'); /** @var DBDatetime $lastSynced */ $lastSynced = $item->dbObject('LastSynced'); return !$lastSynced || $lastSynced->getTimestamp() < $syncOlderThan; }
[ "protected", "function", "shouldCampaignSync", "(", "ChangeSet", "$", "item", ")", "{", "// Don't sync published changesets", "if", "(", "$", "item", "->", "State", "!==", "ChangeSet", "::", "STATE_OPEN", ")", "{", "return", "false", ";", "}", "// Get sync thresho...
Check if the given campaign should be synced before view @param ChangeSet $item @return bool
[ "Check", "if", "the", "given", "campaign", "should", "be", "synced", "before", "view" ]
c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5
https://github.com/silverstripe/silverstripe-campaign-admin/blob/c5ca8fd5a5afc7f4dc25dbe61fdbf847d73889f5/src/CampaignAdmin.php#L844-L856
train
spiral/database
src/Query/SelectQuery.php
SelectQuery.runChunks
public function runChunks(int $limit, callable $callback) { $count = $this->count(); //To keep original query untouched $select = clone $this; $select->limit($limit); $offset = 0; while ($offset + $limit <= $count) { $result = call_user_func_array( $callback, [$select->offset($offset)->getIterator(), $offset, $count] ); if ($result === false) { //Stop iteration return; } $offset += $limit; } }
php
public function runChunks(int $limit, callable $callback) { $count = $this->count(); //To keep original query untouched $select = clone $this; $select->limit($limit); $offset = 0; while ($offset + $limit <= $count) { $result = call_user_func_array( $callback, [$select->offset($offset)->getIterator(), $offset, $count] ); if ($result === false) { //Stop iteration return; } $offset += $limit; } }
[ "public", "function", "runChunks", "(", "int", "$", "limit", ",", "callable", "$", "callback", ")", "{", "$", "count", "=", "$", "this", "->", "count", "(", ")", ";", "//To keep original query untouched", "$", "select", "=", "clone", "$", "this", ";", "$...
Iterate thought result using smaller data chinks with defined size and walk function. Example: $select->chunked(100, function(PDOResult $result, $offset, $count) { dump($result); }); You must return FALSE from walk function to stop chunking. @param int $limit @param callable $callback
[ "Iterate", "thought", "result", "using", "smaller", "data", "chinks", "with", "defined", "size", "and", "walk", "function", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/SelectQuery.php#L290-L312
train
spiral/database
src/Query/SelectQuery.php
SelectQuery.fetchAll
public function fetchAll(): array { $st = $this->run(); try { return $st->fetchAll(\PDO::FETCH_ASSOC); } finally { $st->close(); } }
php
public function fetchAll(): array { $st = $this->run(); try { return $st->fetchAll(\PDO::FETCH_ASSOC); } finally { $st->close(); } }
[ "public", "function", "fetchAll", "(", ")", ":", "array", "{", "$", "st", "=", "$", "this", "->", "run", "(", ")", ";", "try", "{", "return", "$", "st", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "}", "finally", "{", "$", ...
Request all results as array. @return array
[ "Request", "all", "results", "as", "array", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/SelectQuery.php#L428-L436
train
spiral/database
src/Statement.php
Statement.bind
public function bind($columnID, &$variable): Statement { if (is_numeric($columnID)) { //PDO columns are 1-indexed $columnID = $columnID + 1; } $this->bindColumn($columnID, $variable); return $this; }
php
public function bind($columnID, &$variable): Statement { if (is_numeric($columnID)) { //PDO columns are 1-indexed $columnID = $columnID + 1; } $this->bindColumn($columnID, $variable); return $this; }
[ "public", "function", "bind", "(", "$", "columnID", ",", "&", "$", "variable", ")", ":", "Statement", "{", "if", "(", "is_numeric", "(", "$", "columnID", ")", ")", "{", "//PDO columns are 1-indexed", "$", "columnID", "=", "$", "columnID", "+", "1", ";", ...
Bind a column value to a PHP variable. Aliased to bindParam. @param int|string $columnID Column number (0 - first column) @param mixed $variable @return self|$this
[ "Bind", "a", "column", "value", "to", "a", "PHP", "variable", ".", "Aliased", "to", "bindParam", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Statement.php#L38-L48
train
spiral/database
src/Query/AbstractQuery.php
AbstractQuery.flattenParameters
protected function flattenParameters(array $parameters): array { $result = []; foreach ($parameters as $parameter) { if ($parameter instanceof BuilderInterface) { $result = array_merge($result, $parameter->getParameters()); continue; } $result[] = $parameter; } return $result; }
php
protected function flattenParameters(array $parameters): array { $result = []; foreach ($parameters as $parameter) { if ($parameter instanceof BuilderInterface) { $result = array_merge($result, $parameter->getParameters()); continue; } $result[] = $parameter; } return $result; }
[ "protected", "function", "flattenParameters", "(", "array", "$", "parameters", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "parameters", "as", "$", "parameter", ")", "{", "if", "(", "$", "parameter", "instanceof", "Bui...
Expand all QueryBuilder parameters to create flatten list. @param array $parameters @return array
[ "Expand", "all", "QueryBuilder", "parameters", "to", "create", "flatten", "list", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/AbstractQuery.php#L112-L125
train
spiral/database
src/Query/Interpolator.php
Interpolator.interpolate
public static function interpolate(string $query, array $parameters = []): string { if (empty($parameters)) { return $query; } //Flattening $parameters = self::flattenParameters($parameters); //Let's prepare values so they looks better foreach ($parameters as $index => $parameter) { $value = self::resolveValue($parameter); if (is_numeric($index)) { $query = self::replaceOnce('?', $value, $query); } else { $query = str_replace($index, $value, $query); } } return $query; }
php
public static function interpolate(string $query, array $parameters = []): string { if (empty($parameters)) { return $query; } //Flattening $parameters = self::flattenParameters($parameters); //Let's prepare values so they looks better foreach ($parameters as $index => $parameter) { $value = self::resolveValue($parameter); if (is_numeric($index)) { $query = self::replaceOnce('?', $value, $query); } else { $query = str_replace($index, $value, $query); } } return $query; }
[ "public", "static", "function", "interpolate", "(", "string", "$", "query", ",", "array", "$", "parameters", "=", "[", "]", ")", ":", "string", "{", "if", "(", "empty", "(", "$", "parameters", ")", ")", "{", "return", "$", "query", ";", "}", "//Flatt...
Helper method used to interpolate SQL query with set of parameters, must be used only for development purposes and never for real query! @param string $query @param ParameterInterface[] $parameters Parameters to be binded into query. Named list are supported. @return string
[ "Helper", "method", "used", "to", "interpolate", "SQL", "query", "with", "set", "of", "parameters", "must", "be", "used", "only", "for", "development", "purposes", "and", "never", "for", "real", "query!" ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Interpolator.php#L30-L52
train
spiral/database
src/Query/Interpolator.php
Interpolator.resolveValue
protected static function resolveValue($parameter): string { if ($parameter instanceof ParameterInterface) { return self::resolveValue($parameter->getValue()); } switch (gettype($parameter)) { case 'boolean': return $parameter ? 'true' : 'false'; case 'integer': return strval($parameter + 0); case 'NULL': return 'NULL'; case 'double': return sprintf('%F', $parameter); case 'string': return "'" . addcslashes($parameter, "'") . "'"; case 'object': if (method_exists($parameter, '__toString')) { return "'" . addcslashes((string)$parameter, "'") . "'"; } if ($parameter instanceof \DateTime) { //Let's process dates different way return "'" . $parameter->format(\DateTime::ISO8601) . "'"; } } return '[UNRESOLVED]'; }
php
protected static function resolveValue($parameter): string { if ($parameter instanceof ParameterInterface) { return self::resolveValue($parameter->getValue()); } switch (gettype($parameter)) { case 'boolean': return $parameter ? 'true' : 'false'; case 'integer': return strval($parameter + 0); case 'NULL': return 'NULL'; case 'double': return sprintf('%F', $parameter); case 'string': return "'" . addcslashes($parameter, "'") . "'"; case 'object': if (method_exists($parameter, '__toString')) { return "'" . addcslashes((string)$parameter, "'") . "'"; } if ($parameter instanceof \DateTime) { //Let's process dates different way return "'" . $parameter->format(\DateTime::ISO8601) . "'"; } } return '[UNRESOLVED]'; }
[ "protected", "static", "function", "resolveValue", "(", "$", "parameter", ")", ":", "string", "{", "if", "(", "$", "parameter", "instanceof", "ParameterInterface", ")", "{", "return", "self", "::", "resolveValue", "(", "$", "parameter", "->", "getValue", "(", ...
Get parameter value. @param mixed $parameter @return string
[ "Get", "parameter", "value", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Query/Interpolator.php#L100-L134
train
spiral/database
src/Driver/Driver.php
Driver.connect
public function connect() { if (!$this->isConnected()) { $this->pdo = $this->createPDO(); $this->pdo->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [Statement::class]); } }
php
public function connect() { if (!$this->isConnected()) { $this->pdo = $this->createPDO(); $this->pdo->setAttribute(\PDO::ATTR_STATEMENT_CLASS, [Statement::class]); } }
[ "public", "function", "connect", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isConnected", "(", ")", ")", "{", "$", "this", "->", "pdo", "=", "$", "this", "->", "createPDO", "(", ")", ";", "$", "this", "->", "pdo", "->", "setAttribute", "(...
Force driver connection. @throws DriverException
[ "Force", "driver", "connection", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L160-L166
train
spiral/database
src/Driver/Driver.php
Driver.execute
public function execute(string $query, array $parameters = []): int { return $this->statement($query, $parameters)->rowCount(); }
php
public function execute(string $query, array $parameters = []): int { return $this->statement($query, $parameters)->rowCount(); }
[ "public", "function", "execute", "(", "string", "$", "query", ",", "array", "$", "parameters", "=", "[", "]", ")", ":", "int", "{", "return", "$", "this", "->", "statement", "(", "$", "query", ",", "$", "parameters", ")", "->", "rowCount", "(", ")", ...
Execute query and return number of affected rows. @param string $query @param array $parameters @return int @throws StatementException
[ "Execute", "query", "and", "return", "number", "of", "affected", "rows", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L231-L234
train
spiral/database
src/Driver/Driver.php
Driver.statement
protected function statement(string $query, array $parameters = [], bool $retry = null): Statement { if (is_null($retry)) { $retry = $this->options['reconnect']; } try { $flatten = $this->flattenParameters($parameters); //Mounting all input parameters $statement = $this->bindParameters($this->prepare($query), $flatten); $statement->execute(); if ($this->isProfiling()) { $this->getLogger()->info( Interpolator::interpolate($query, $parameters), compact('query', 'parameters') ); } } catch (\PDOException $e) { $queryString = Interpolator::interpolate($query, $parameters); $this->getLogger()->error($queryString, compact('query', 'parameters')); $this->getLogger()->alert($e->getMessage()); //Converting exception into query or integrity exception $e = $this->mapException($e, $queryString); if ( $e instanceof StatementException\ConnectionException && $this->transactionLevel === 0 && $retry ) { // retrying return $this->statement($query, $parameters, false); } throw $e; } return $statement; }
php
protected function statement(string $query, array $parameters = [], bool $retry = null): Statement { if (is_null($retry)) { $retry = $this->options['reconnect']; } try { $flatten = $this->flattenParameters($parameters); //Mounting all input parameters $statement = $this->bindParameters($this->prepare($query), $flatten); $statement->execute(); if ($this->isProfiling()) { $this->getLogger()->info( Interpolator::interpolate($query, $parameters), compact('query', 'parameters') ); } } catch (\PDOException $e) { $queryString = Interpolator::interpolate($query, $parameters); $this->getLogger()->error($queryString, compact('query', 'parameters')); $this->getLogger()->alert($e->getMessage()); //Converting exception into query or integrity exception $e = $this->mapException($e, $queryString); if ( $e instanceof StatementException\ConnectionException && $this->transactionLevel === 0 && $retry ) { // retrying return $this->statement($query, $parameters, false); } throw $e; } return $statement; }
[ "protected", "function", "statement", "(", "string", "$", "query", ",", "array", "$", "parameters", "=", "[", "]", ",", "bool", "$", "retry", "=", "null", ")", ":", "Statement", "{", "if", "(", "is_null", "(", "$", "retry", ")", ")", "{", "$", "ret...
Create instance of PDOStatement using provided SQL query and set of parameters and execute it. Will attempt singular reconnect. @param string $query @param array $parameters Parameters to be binded into query. @param bool|null $retry @return Statement @throws StatementException
[ "Create", "instance", "of", "PDOStatement", "using", "provided", "SQL", "query", "and", "set", "of", "parameters", "and", "execute", "it", ".", "Will", "attempt", "singular", "reconnect", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L266-L306
train
spiral/database
src/Driver/Driver.php
Driver.bindParameters
protected function bindParameters(Statement $statement, array $parameters): Statement { foreach ($parameters as $index => $parameter) { if (is_numeric($index)) { //Numeric, @see http://php.net/manual/en/pdostatement.bindparam.php $statement->bindValue($index + 1, $parameter->getValue(), $parameter->getType()); } else { //Named $statement->bindValue($index, $parameter->getValue(), $parameter->getType()); } } return $statement; }
php
protected function bindParameters(Statement $statement, array $parameters): Statement { foreach ($parameters as $index => $parameter) { if (is_numeric($index)) { //Numeric, @see http://php.net/manual/en/pdostatement.bindparam.php $statement->bindValue($index + 1, $parameter->getValue(), $parameter->getType()); } else { //Named $statement->bindValue($index, $parameter->getValue(), $parameter->getType()); } } return $statement; }
[ "protected", "function", "bindParameters", "(", "Statement", "$", "statement", ",", "array", "$", "parameters", ")", ":", "Statement", "{", "foreach", "(", "$", "parameters", "as", "$", "index", "=>", "$", "parameter", ")", "{", "if", "(", "is_numeric", "(...
Bind parameters into statement. @param Statement $statement @param ParameterInterface[] $parameters Named hash of ParameterInterface. @return Statement
[ "Bind", "parameters", "into", "statement", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L389-L402
train
spiral/database
src/Driver/Driver.php
Driver.isolationLevel
protected function isolationLevel(string $level) { if (!empty($level)) { $this->isProfiling() && $this->getLogger()->info("Set transaction isolation level to '{$level}'"); $this->execute("SET TRANSACTION ISOLATION LEVEL {$level}"); } }
php
protected function isolationLevel(string $level) { if (!empty($level)) { $this->isProfiling() && $this->getLogger()->info("Set transaction isolation level to '{$level}'"); $this->execute("SET TRANSACTION ISOLATION LEVEL {$level}"); } }
[ "protected", "function", "isolationLevel", "(", "string", "$", "level", ")", "{", "if", "(", "!", "empty", "(", "$", "level", ")", ")", "{", "$", "this", "->", "isProfiling", "(", ")", "&&", "$", "this", "->", "getLogger", "(", ")", "->", "info", "...
Set transaction isolation level, this feature may not be supported by specific database driver. @param string $level
[ "Set", "transaction", "isolation", "level", "this", "feature", "may", "not", "be", "supported", "by", "specific", "database", "driver", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L514-L520
train
spiral/database
src/Driver/Driver.php
Driver.createPDO
protected function createPDO(): PDO { return new PDO( $this->options['connection'] ?? $this->options['dsn'], $this->options['username'], $this->options['password'], $this->options['options'] ); }
php
protected function createPDO(): PDO { return new PDO( $this->options['connection'] ?? $this->options['dsn'], $this->options['username'], $this->options['password'], $this->options['options'] ); }
[ "protected", "function", "createPDO", "(", ")", ":", "PDO", "{", "return", "new", "PDO", "(", "$", "this", "->", "options", "[", "'connection'", "]", "??", "$", "this", "->", "options", "[", "'dsn'", "]", ",", "$", "this", "->", "options", "[", "'use...
Create instance of configured PDO class. @return PDO
[ "Create", "instance", "of", "configured", "PDO", "class", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L588-L596
train
spiral/database
src/Driver/Driver.php
Driver.formatDatetime
protected function formatDatetime(\DateTimeInterface $value): string { try { $datetime = new \DateTimeImmutable('now', $this->getTimezone()); } catch (\Exception $e) { throw new DriverException($e->getMessage(), $e->getCode(), $e); } return $datetime->setTimestamp($value->getTimestamp())->format(static::DATETIME); }
php
protected function formatDatetime(\DateTimeInterface $value): string { try { $datetime = new \DateTimeImmutable('now', $this->getTimezone()); } catch (\Exception $e) { throw new DriverException($e->getMessage(), $e->getCode(), $e); } return $datetime->setTimestamp($value->getTimestamp())->format(static::DATETIME); }
[ "protected", "function", "formatDatetime", "(", "\\", "DateTimeInterface", "$", "value", ")", ":", "string", "{", "try", "{", "$", "datetime", "=", "new", "\\", "DateTimeImmutable", "(", "'now'", ",", "$", "this", "->", "getTimezone", "(", ")", ")", ";", ...
Convert DateTime object into local database representation. Driver will automatically force needed timezone. @param \DateTimeInterface $value @return string @throws DriverException
[ "Convert", "DateTime", "object", "into", "local", "database", "representation", ".", "Driver", "will", "automatically", "force", "needed", "timezone", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/Driver/Driver.php#L623-L632
train
spiral/database
src/DatabaseManager.php
DatabaseManager.getDatabases
public function getDatabases(): array { $names = array_unique(array_merge(array_keys($this->databases), array_keys($this->config->getDatabases()))); $result = []; foreach ($names as $name) { $result[] = $this->database($name); } return $result; }
php
public function getDatabases(): array { $names = array_unique(array_merge(array_keys($this->databases), array_keys($this->config->getDatabases()))); $result = []; foreach ($names as $name) { $result[] = $this->database($name); } return $result; }
[ "public", "function", "getDatabases", "(", ")", ":", "array", "{", "$", "names", "=", "array_unique", "(", "array_merge", "(", "array_keys", "(", "$", "this", "->", "databases", ")", ",", "array_keys", "(", "$", "this", "->", "config", "->", "getDatabases"...
Get all databases. @return Database[] @throws DatabaseException
[ "Get", "all", "databases", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/DatabaseManager.php#L124-L134
train
spiral/database
src/DatabaseManager.php
DatabaseManager.database
public function database(string $database = null): DatabaseInterface { if (empty($database)) { $database = $this->config->getDefaultDatabase(); } //Spiral support ability to link multiple virtual databases together using aliases $database = $this->config->resolveAlias($database); if (isset($this->databases[$database])) { return $this->databases[$database]; } if (!$this->config->hasDatabase($database)) { throw new DBALException( "Unable to create Database, no presets for '{$database}' found" ); } return $this->databases[$database] = $this->makeDatabase( $this->config->getDatabase($database) ); }
php
public function database(string $database = null): DatabaseInterface { if (empty($database)) { $database = $this->config->getDefaultDatabase(); } //Spiral support ability to link multiple virtual databases together using aliases $database = $this->config->resolveAlias($database); if (isset($this->databases[$database])) { return $this->databases[$database]; } if (!$this->config->hasDatabase($database)) { throw new DBALException( "Unable to create Database, no presets for '{$database}' found" ); } return $this->databases[$database] = $this->makeDatabase( $this->config->getDatabase($database) ); }
[ "public", "function", "database", "(", "string", "$", "database", "=", "null", ")", ":", "DatabaseInterface", "{", "if", "(", "empty", "(", "$", "database", ")", ")", "{", "$", "database", "=", "$", "this", "->", "config", "->", "getDefaultDatabase", "("...
Get Database associated with a given database alias or automatically created one. @param string|null $database @return Database|DatabaseInterface @throws DBALException
[ "Get", "Database", "associated", "with", "a", "given", "database", "alias", "or", "automatically", "created", "one", "." ]
93a6010feadf24a41af39c46346737d5c532e57f
https://github.com/spiral/database/blob/93a6010feadf24a41af39c46346737d5c532e57f/src/DatabaseManager.php#L144-L166
train