repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
ezsystems/ezplatform-http-cache
spec/EventSubscriber/RestKernelViewSubscriberSpec.php
RestKernelViewSubscriberSpec.it_does_nothing_on_rest_content_type_group_ref_draft
public function it_does_nothing_on_rest_content_type_group_ref_draft( GetResponseForControllerResultEvent $event, Request $request, ParameterBag $attributes, ContentTypeGroupRefList $restValue, ContentType $contentType, ContentTypeGroup $contentTypeGroup, TagHandler $tagHandler ) { $request->isMethodCacheable()->willReturn(true); $attributes->get('is_rest_request')->willReturn(true); $contentType->beConstructedWith([['status' => ContentType::STATUS_DRAFT]]); $restValue->contentType = $contentType; $restValue->contentTypeGroups = [$contentTypeGroup]; $event->getControllerResult()->willReturn($restValue); $tagHandler->addTags(new AnyValueToken())->shouldNotBecalled(); $event->setControllerResult()->shouldNotBecalled(); $this->tagUIRestResult($event); }
php
public function it_does_nothing_on_rest_content_type_group_ref_draft( GetResponseForControllerResultEvent $event, Request $request, ParameterBag $attributes, ContentTypeGroupRefList $restValue, ContentType $contentType, ContentTypeGroup $contentTypeGroup, TagHandler $tagHandler ) { $request->isMethodCacheable()->willReturn(true); $attributes->get('is_rest_request')->willReturn(true); $contentType->beConstructedWith([['status' => ContentType::STATUS_DRAFT]]); $restValue->contentType = $contentType; $restValue->contentTypeGroups = [$contentTypeGroup]; $event->getControllerResult()->willReturn($restValue); $tagHandler->addTags(new AnyValueToken())->shouldNotBecalled(); $event->setControllerResult()->shouldNotBecalled(); $this->tagUIRestResult($event); }
[ "public", "function", "it_does_nothing_on_rest_content_type_group_ref_draft", "(", "GetResponseForControllerResultEvent", "$", "event", ",", "Request", "$", "request", ",", "ParameterBag", "$", "attributes", ",", "ContentTypeGroupRefList", "$", "restValue", ",", "ContentType", "$", "contentType", ",", "ContentTypeGroup", "$", "contentTypeGroup", ",", "TagHandler", "$", "tagHandler", ")", "{", "$", "request", "->", "isMethodCacheable", "(", ")", "->", "willReturn", "(", "true", ")", ";", "$", "attributes", "->", "get", "(", "'is_rest_request'", ")", "->", "willReturn", "(", "true", ")", ";", "$", "contentType", "->", "beConstructedWith", "(", "[", "[", "'status'", "=>", "ContentType", "::", "STATUS_DRAFT", "]", "]", ")", ";", "$", "restValue", "->", "contentType", "=", "$", "contentType", ";", "$", "restValue", "->", "contentTypeGroups", "=", "[", "$", "contentTypeGroup", "]", ";", "$", "event", "->", "getControllerResult", "(", ")", "->", "willReturn", "(", "$", "restValue", ")", ";", "$", "tagHandler", "->", "addTags", "(", "new", "AnyValueToken", "(", ")", ")", "->", "shouldNotBecalled", "(", ")", ";", "$", "event", "->", "setControllerResult", "(", ")", "->", "shouldNotBecalled", "(", ")", ";", "$", "this", "->", "tagUIRestResult", "(", "$", "event", ")", ";", "}" ]
ContentTypeGroupRefList
[ "ContentTypeGroupRefList" ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/spec/EventSubscriber/RestKernelViewSubscriberSpec.php#L181-L203
ezsystems/ezplatform-http-cache
spec/EventSubscriber/RestKernelViewSubscriberSpec.php
RestKernelViewSubscriberSpec.it_writes_tags_on_rest_content_type_group_list
public function it_writes_tags_on_rest_content_type_group_list( GetResponseForControllerResultEvent $event, Request $request, ParameterBag $attributes, ContentTypeGroupList $restValue, ContentTypeGroup $contentTypeGroup, TagHandler $tagHandler ) { $request->isMethodCacheable()->willReturn(true); $attributes->get('is_rest_request')->willReturn(true); $contentTypeGroup->beConstructedWith([['id' => 2]]); $restValue->contentTypeGroups = [$contentTypeGroup]; $event->getControllerResult()->willReturn($restValue); $tagHandler->addTags(['type-group-2'])->shouldBecalled(); $event->setControllerResult(new TypeToken(CachedValue::class))->shouldBecalled(); $this->tagUIRestResult($event); }
php
public function it_writes_tags_on_rest_content_type_group_list( GetResponseForControllerResultEvent $event, Request $request, ParameterBag $attributes, ContentTypeGroupList $restValue, ContentTypeGroup $contentTypeGroup, TagHandler $tagHandler ) { $request->isMethodCacheable()->willReturn(true); $attributes->get('is_rest_request')->willReturn(true); $contentTypeGroup->beConstructedWith([['id' => 2]]); $restValue->contentTypeGroups = [$contentTypeGroup]; $event->getControllerResult()->willReturn($restValue); $tagHandler->addTags(['type-group-2'])->shouldBecalled(); $event->setControllerResult(new TypeToken(CachedValue::class))->shouldBecalled(); $this->tagUIRestResult($event); }
[ "public", "function", "it_writes_tags_on_rest_content_type_group_list", "(", "GetResponseForControllerResultEvent", "$", "event", ",", "Request", "$", "request", ",", "ParameterBag", "$", "attributes", ",", "ContentTypeGroupList", "$", "restValue", ",", "ContentTypeGroup", "$", "contentTypeGroup", ",", "TagHandler", "$", "tagHandler", ")", "{", "$", "request", "->", "isMethodCacheable", "(", ")", "->", "willReturn", "(", "true", ")", ";", "$", "attributes", "->", "get", "(", "'is_rest_request'", ")", "->", "willReturn", "(", "true", ")", ";", "$", "contentTypeGroup", "->", "beConstructedWith", "(", "[", "[", "'id'", "=>", "2", "]", "]", ")", ";", "$", "restValue", "->", "contentTypeGroups", "=", "[", "$", "contentTypeGroup", "]", ";", "$", "event", "->", "getControllerResult", "(", ")", "->", "willReturn", "(", "$", "restValue", ")", ";", "$", "tagHandler", "->", "addTags", "(", "[", "'type-group-2'", "]", ")", "->", "shouldBecalled", "(", ")", ";", "$", "event", "->", "setControllerResult", "(", "new", "TypeToken", "(", "CachedValue", "::", "class", ")", ")", "->", "shouldBecalled", "(", ")", ";", "$", "this", "->", "tagUIRestResult", "(", "$", "event", ")", ";", "}" ]
ContentTypeGroupList
[ "ContentTypeGroupList" ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/spec/EventSubscriber/RestKernelViewSubscriberSpec.php#L234-L253
ezsystems/ezplatform-http-cache
spec/EventSubscriber/RestKernelViewSubscriberSpec.php
RestKernelViewSubscriberSpec.it_writes_tags_on_rest_version_list
public function it_writes_tags_on_rest_version_list( GetResponseForControllerResultEvent $event, Request $request, ParameterBag $attributes, VersionList $restValue, VersionInfo $versionInfo, ContentInfo $contentInfo, TagHandler $tagHandler ) { $request->isMethodCacheable()->willReturn(true); $attributes->get('is_rest_request')->willReturn(true); $contentInfo->beConstructedWith([['id' => 33]]); $versionInfo->beConstructedWith([['contentInfo' => $contentInfo]]); $restValue->versions = [$versionInfo]; $event->getControllerResult()->willReturn($restValue); $tagHandler->addTags(['content-33', 'content-versions-33'])->shouldBecalled(); $event->setControllerResult(new TypeToken(CachedValue::class))->shouldBecalled(); $this->tagUIRestResult($event); }
php
public function it_writes_tags_on_rest_version_list( GetResponseForControllerResultEvent $event, Request $request, ParameterBag $attributes, VersionList $restValue, VersionInfo $versionInfo, ContentInfo $contentInfo, TagHandler $tagHandler ) { $request->isMethodCacheable()->willReturn(true); $attributes->get('is_rest_request')->willReturn(true); $contentInfo->beConstructedWith([['id' => 33]]); $versionInfo->beConstructedWith([['contentInfo' => $contentInfo]]); $restValue->versions = [$versionInfo]; $event->getControllerResult()->willReturn($restValue); $tagHandler->addTags(['content-33', 'content-versions-33'])->shouldBecalled(); $event->setControllerResult(new TypeToken(CachedValue::class))->shouldBecalled(); $this->tagUIRestResult($event); }
[ "public", "function", "it_writes_tags_on_rest_version_list", "(", "GetResponseForControllerResultEvent", "$", "event", ",", "Request", "$", "request", ",", "ParameterBag", "$", "attributes", ",", "VersionList", "$", "restValue", ",", "VersionInfo", "$", "versionInfo", ",", "ContentInfo", "$", "contentInfo", ",", "TagHandler", "$", "tagHandler", ")", "{", "$", "request", "->", "isMethodCacheable", "(", ")", "->", "willReturn", "(", "true", ")", ";", "$", "attributes", "->", "get", "(", "'is_rest_request'", ")", "->", "willReturn", "(", "true", ")", ";", "$", "contentInfo", "->", "beConstructedWith", "(", "[", "[", "'id'", "=>", "33", "]", "]", ")", ";", "$", "versionInfo", "->", "beConstructedWith", "(", "[", "[", "'contentInfo'", "=>", "$", "contentInfo", "]", "]", ")", ";", "$", "restValue", "->", "versions", "=", "[", "$", "versionInfo", "]", ";", "$", "event", "->", "getControllerResult", "(", ")", "->", "willReturn", "(", "$", "restValue", ")", ";", "$", "tagHandler", "->", "addTags", "(", "[", "'content-33'", ",", "'content-versions-33'", "]", ")", "->", "shouldBecalled", "(", ")", ";", "$", "event", "->", "setControllerResult", "(", "new", "TypeToken", "(", "CachedValue", "::", "class", ")", ")", "->", "shouldBecalled", "(", ")", ";", "$", "this", "->", "tagUIRestResult", "(", "$", "event", ")", ";", "}" ]
VersionList
[ "VersionList" ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/spec/EventSubscriber/RestKernelViewSubscriberSpec.php#L258-L279
ezsystems/ezplatform-http-cache
src/EventListener/ConditionallyRemoveVaryHeaderListener.php
ConditionallyRemoveVaryHeaderListener.onKernelResponse
public function onKernelResponse(FilterResponseEvent $event) { if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) { return; } if (!in_array($event->getRequest()->get('_route'), $this->routes)) { return; } $response = $event->getResponse(); $varyHeaders = $response->headers->get('vary', null, false); foreach ($this->userIdentifierHeaders as $removableVary) { unset($varyHeaders[array_search(strtolower($removableVary), $varyHeaders)]); } $response->setVary($varyHeaders, true); }
php
public function onKernelResponse(FilterResponseEvent $event) { if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) { return; } if (!in_array($event->getRequest()->get('_route'), $this->routes)) { return; } $response = $event->getResponse(); $varyHeaders = $response->headers->get('vary', null, false); foreach ($this->userIdentifierHeaders as $removableVary) { unset($varyHeaders[array_search(strtolower($removableVary), $varyHeaders)]); } $response->setVary($varyHeaders, true); }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "event", ")", "{", "if", "(", "HttpKernelInterface", "::", "MASTER_REQUEST", "!=", "$", "event", "->", "getRequestType", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", "in_array", "(", "$", "event", "->", "getRequest", "(", ")", "->", "get", "(", "'_route'", ")", ",", "$", "this", "->", "routes", ")", ")", "{", "return", ";", "}", "$", "response", "=", "$", "event", "->", "getResponse", "(", ")", ";", "$", "varyHeaders", "=", "$", "response", "->", "headers", "->", "get", "(", "'vary'", ",", "null", ",", "false", ")", ";", "foreach", "(", "$", "this", "->", "userIdentifierHeaders", "as", "$", "removableVary", ")", "{", "unset", "(", "$", "varyHeaders", "[", "array_search", "(", "strtolower", "(", "$", "removableVary", ")", ",", "$", "varyHeaders", ")", "]", ")", ";", "}", "$", "response", "->", "setVary", "(", "$", "varyHeaders", ",", "true", ")", ";", "}" ]
Remove Vary headers for matched routes. @param FilterResponseEvent $event
[ "Remove", "Vary", "headers", "for", "matched", "routes", "." ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/EventListener/ConditionallyRemoveVaryHeaderListener.php#L48-L65
ezsystems/ezplatform-http-cache
src/PurgeClient/VarnishProxyClientFactory.php
VarnishProxyClientFactory.buildProxyClient
public function buildProxyClient(array $servers, $baseUrl) { $allServers = array(); foreach ($servers as $server) { if (!$this->dynamicSettingParser->isDynamicSetting($server)) { $allServers[] = $server; continue; } $settings = $this->dynamicSettingParser->parseDynamicSetting($server); $configuredServers = $this->configResolver->getParameter( $settings['param'], $settings['namespace'], $settings['scope'] ); $allServers = array_merge($allServers, (array)$configuredServers); } $class = $this->proxyClientClass; return new $class($allServers, $baseUrl); }
php
public function buildProxyClient(array $servers, $baseUrl) { $allServers = array(); foreach ($servers as $server) { if (!$this->dynamicSettingParser->isDynamicSetting($server)) { $allServers[] = $server; continue; } $settings = $this->dynamicSettingParser->parseDynamicSetting($server); $configuredServers = $this->configResolver->getParameter( $settings['param'], $settings['namespace'], $settings['scope'] ); $allServers = array_merge($allServers, (array)$configuredServers); } $class = $this->proxyClientClass; return new $class($allServers, $baseUrl); }
[ "public", "function", "buildProxyClient", "(", "array", "$", "servers", ",", "$", "baseUrl", ")", "{", "$", "allServers", "=", "array", "(", ")", ";", "foreach", "(", "$", "servers", "as", "$", "server", ")", "{", "if", "(", "!", "$", "this", "->", "dynamicSettingParser", "->", "isDynamicSetting", "(", "$", "server", ")", ")", "{", "$", "allServers", "[", "]", "=", "$", "server", ";", "continue", ";", "}", "$", "settings", "=", "$", "this", "->", "dynamicSettingParser", "->", "parseDynamicSetting", "(", "$", "server", ")", ";", "$", "configuredServers", "=", "$", "this", "->", "configResolver", "->", "getParameter", "(", "$", "settings", "[", "'param'", "]", ",", "$", "settings", "[", "'namespace'", "]", ",", "$", "settings", "[", "'scope'", "]", ")", ";", "$", "allServers", "=", "array_merge", "(", "$", "allServers", ",", "(", "array", ")", "$", "configuredServers", ")", ";", "}", "$", "class", "=", "$", "this", "->", "proxyClientClass", ";", "return", "new", "$", "class", "(", "$", "allServers", ",", "$", "baseUrl", ")", ";", "}" ]
Builds the proxy client, taking dynamically defined servers into account. @param array $servers @param string $baseUrl @return \FOS\HttpCache\ProxyClient\Varnish
[ "Builds", "the", "proxy", "client", "taking", "dynamically", "defined", "servers", "into", "account", "." ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/PurgeClient/VarnishProxyClientFactory.php#L54-L75
ezsystems/ezplatform-http-cache
src/SignalSlot/DeleteContentSlot.php
DeleteContentSlot.generateTags
protected function generateTags(Signal $signal) { $tags = parent::generateTags($signal); foreach ($signal->affectedLocationIds as $locationId) { $tags[] = 'path-' . $locationId; } return $tags; }
php
protected function generateTags(Signal $signal) { $tags = parent::generateTags($signal); foreach ($signal->affectedLocationIds as $locationId) { $tags[] = 'path-' . $locationId; } return $tags; }
[ "protected", "function", "generateTags", "(", "Signal", "$", "signal", ")", "{", "$", "tags", "=", "parent", "::", "generateTags", "(", "$", "signal", ")", ";", "foreach", "(", "$", "signal", "->", "affectedLocationIds", "as", "$", "locationId", ")", "{", "$", "tags", "[", "]", "=", "'path-'", ".", "$", "locationId", ";", "}", "return", "$", "tags", ";", "}" ]
@param \eZ\Publish\Core\SignalSlot\Signal\ContentService\DeleteContentSignal $signal @todo Missing parent, however it would be clener if kernel emmited cascading Delete Location signals on affected locations instead.
[ "@param", "\\", "eZ", "\\", "Publish", "\\", "Core", "\\", "SignalSlot", "\\", "Signal", "\\", "ContentService", "\\", "DeleteContentSignal", "$signal" ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/SignalSlot/DeleteContentSlot.php#L24-L32
ezsystems/ezplatform-http-cache
src/Controller/InvalidateTokenController.php
InvalidateTokenController.isFromTrustedProxy
private function isFromTrustedProxy(Request $request) { return $request->getTrustedProxies() && IpUtils::checkIp($request->server->get('REMOTE_ADDR'), $request->getTrustedProxies()); }
php
private function isFromTrustedProxy(Request $request) { return $request->getTrustedProxies() && IpUtils::checkIp($request->server->get('REMOTE_ADDR'), $request->getTrustedProxies()); }
[ "private", "function", "isFromTrustedProxy", "(", "Request", "$", "request", ")", "{", "return", "$", "request", "->", "getTrustedProxies", "(", ")", "&&", "IpUtils", "::", "checkIp", "(", "$", "request", "->", "server", "->", "get", "(", "'REMOTE_ADDR'", ")", ",", "$", "request", "->", "getTrustedProxies", "(", ")", ")", ";", "}" ]
Request::isFromTrustedProxy is private in Symfony <3.1, so this is a re-implementation of it. @param Request $request @return bool
[ "Request", "::", "isFromTrustedProxy", "is", "private", "in", "Symfony", "<3", ".", "1", "so", "this", "is", "a", "re", "-", "implementation", "of", "it", "." ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/Controller/InvalidateTokenController.php#L52-L55
ezsystems/ezplatform-http-cache
src/PurgeClient/VarnishPurgeClient.php
VarnishPurgeClient.addPurgeAuthHeader
private function addPurgeAuthHeader(array $headers) { if ($this->configResolver->hasParameter(self::INVALIDATE_TOKEN_PARAM) && null !== ($token = $this->configResolver->getParameter(self::INVALIDATE_TOKEN_PARAM)) ) { $headers[self::INVALIDATE_TOKEN_PARAM_NAME] = $token; } return $headers; }
php
private function addPurgeAuthHeader(array $headers) { if ($this->configResolver->hasParameter(self::INVALIDATE_TOKEN_PARAM) && null !== ($token = $this->configResolver->getParameter(self::INVALIDATE_TOKEN_PARAM)) ) { $headers[self::INVALIDATE_TOKEN_PARAM_NAME] = $token; } return $headers; }
[ "private", "function", "addPurgeAuthHeader", "(", "array", "$", "headers", ")", "{", "if", "(", "$", "this", "->", "configResolver", "->", "hasParameter", "(", "self", "::", "INVALIDATE_TOKEN_PARAM", ")", "&&", "null", "!==", "(", "$", "token", "=", "$", "this", "->", "configResolver", "->", "getParameter", "(", "self", "::", "INVALIDATE_TOKEN_PARAM", ")", ")", ")", "{", "$", "headers", "[", "self", "::", "INVALIDATE_TOKEN_PARAM_NAME", "]", "=", "$", "token", ";", "}", "return", "$", "headers", ";", "}" ]
Adds an Authentication header for Purge. @param array $headers @return array
[ "Adds", "an", "Authentication", "header", "for", "Purge", "." ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/PurgeClient/VarnishPurgeClient.php#L89-L98
ezsystems/ezplatform-http-cache
src/SignalSlot/AbstractContentSlot.php
AbstractContentSlot.generateTags
protected function generateTags(Signal $signal) { $tags = []; if (isset($signal->contentId)) { // self in all forms (also without locations) $tags[] = 'content-' . $signal->contentId; // reverse relations $tags[] = 'relation-' . $signal->contentId; } if (isset($signal->locationId)) { // self $tags[] = 'location-' . $signal->locationId; // direct children $tags[] = 'parent-' . $signal->locationId; // reverse location relations $tags[] = 'relation-location-' . $signal->locationId; } if (isset($signal->parentLocationId)) { // direct parent $tags[] = 'location-' . $signal->parentLocationId; // direct siblings $tags[] = 'parent-' . $signal->parentLocationId; } return $tags; }
php
protected function generateTags(Signal $signal) { $tags = []; if (isset($signal->contentId)) { // self in all forms (also without locations) $tags[] = 'content-' . $signal->contentId; // reverse relations $tags[] = 'relation-' . $signal->contentId; } if (isset($signal->locationId)) { // self $tags[] = 'location-' . $signal->locationId; // direct children $tags[] = 'parent-' . $signal->locationId; // reverse location relations $tags[] = 'relation-location-' . $signal->locationId; } if (isset($signal->parentLocationId)) { // direct parent $tags[] = 'location-' . $signal->parentLocationId; // direct siblings $tags[] = 'parent-' . $signal->parentLocationId; } return $tags; }
[ "protected", "function", "generateTags", "(", "Signal", "$", "signal", ")", "{", "$", "tags", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "signal", "->", "contentId", ")", ")", "{", "// self in all forms (also without locations)", "$", "tags", "[", "]", "=", "'content-'", ".", "$", "signal", "->", "contentId", ";", "// reverse relations", "$", "tags", "[", "]", "=", "'relation-'", ".", "$", "signal", "->", "contentId", ";", "}", "if", "(", "isset", "(", "$", "signal", "->", "locationId", ")", ")", "{", "// self", "$", "tags", "[", "]", "=", "'location-'", ".", "$", "signal", "->", "locationId", ";", "// direct children", "$", "tags", "[", "]", "=", "'parent-'", ".", "$", "signal", "->", "locationId", ";", "// reverse location relations", "$", "tags", "[", "]", "=", "'relation-location-'", ".", "$", "signal", "->", "locationId", ";", "}", "if", "(", "isset", "(", "$", "signal", "->", "parentLocationId", ")", ")", "{", "// direct parent", "$", "tags", "[", "]", "=", "'location-'", ".", "$", "signal", "->", "parentLocationId", ";", "// direct siblings", "$", "tags", "[", "]", "=", "'parent-'", ".", "$", "signal", "->", "parentLocationId", ";", "}", "return", "$", "tags", ";", "}" ]
Default provides tags to clear content, relation, location, parent and sibling cache. Overload and call parent for tree operations where you also need to clear whole path. @param \eZ\Publish\Core\SignalSlot\Signal $signal @return array
[ "Default", "provides", "tags", "to", "clear", "content", "relation", "location", "parent", "and", "sibling", "cache", "." ]
train
https://github.com/ezsystems/ezplatform-http-cache/blob/54d6c0b10c60e9e041d8900e519aa46dc3656f0a/src/SignalSlot/AbstractContentSlot.php#L30-L58
thepinecode/i18n
src/I18nServiceProvider.php
I18nServiceProvider.boot
public function boot() { // Publish the assets $this->publishes([ __DIR__.'/../resources/js' => resource_path('js/vendor'), ]); // Register the @translations blade directive Blade::directive('translations', function ($key) { return sprintf('<script>window[%s] = %s</script>', $key ?: "'translations'", $this->translations()); }); }
php
public function boot() { // Publish the assets $this->publishes([ __DIR__.'/../resources/js' => resource_path('js/vendor'), ]); // Register the @translations blade directive Blade::directive('translations', function ($key) { return sprintf('<script>window[%s] = %s</script>', $key ?: "'translations'", $this->translations()); }); }
[ "public", "function", "boot", "(", ")", "{", "// Publish the assets", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../resources/js'", "=>", "resource_path", "(", "'js/vendor'", ")", ",", "]", ")", ";", "// Register the @translations blade directive", "Blade", "::", "directive", "(", "'translations'", ",", "function", "(", "$", "key", ")", "{", "return", "sprintf", "(", "'<script>window[%s] = %s</script>'", ",", "$", "key", "?", ":", "\"'translations'\"", ",", "$", "this", "->", "translations", "(", ")", ")", ";", "}", ")", ";", "}" ]
Bootstrap any application services. @return void
[ "Bootstrap", "any", "application", "services", "." ]
train
https://github.com/thepinecode/i18n/blob/16190cf8aaaaca5f1ca09a79482d58893b7df342/src/I18nServiceProvider.php#L18-L29
thepinecode/i18n
src/I18nServiceProvider.php
I18nServiceProvider.translations
protected function translations() { $translations = collect($this->getFiles(resource_path('lang/')))->flatMap(function ($file) { return [ ($translation = $file->getBasename('.php')) => trans($translation), ]; }); return $translations->merge($this->packageTranslations()); }
php
protected function translations() { $translations = collect($this->getFiles(resource_path('lang/')))->flatMap(function ($file) { return [ ($translation = $file->getBasename('.php')) => trans($translation), ]; }); return $translations->merge($this->packageTranslations()); }
[ "protected", "function", "translations", "(", ")", "{", "$", "translations", "=", "collect", "(", "$", "this", "->", "getFiles", "(", "resource_path", "(", "'lang/'", ")", ")", ")", "->", "flatMap", "(", "function", "(", "$", "file", ")", "{", "return", "[", "(", "$", "translation", "=", "$", "file", "->", "getBasename", "(", "'.php'", ")", ")", "=>", "trans", "(", "$", "translation", ")", ",", "]", ";", "}", ")", ";", "return", "$", "translations", "->", "merge", "(", "$", "this", "->", "packageTranslations", "(", ")", ")", ";", "}" ]
Get the translations. @return \Illuminate\Support\Collection
[ "Get", "the", "translations", "." ]
train
https://github.com/thepinecode/i18n/blob/16190cf8aaaaca5f1ca09a79482d58893b7df342/src/I18nServiceProvider.php#L36-L45
thepinecode/i18n
src/I18nServiceProvider.php
I18nServiceProvider.packageTranslations
protected function packageTranslations() { return collect($this->app['translator']->getLoader()->namespaces())->flatMap(function ($path, $namespace) { return [ ($namespace .= '::') => collect($this->getFiles($path))->flatMap(function ($file) use ($namespace) { return [ ($translation = $file->getBasename('.php')) => trans($namespace . $translation), ]; }), ]; })->filter(function ($translations) { return $translations->isNotEmpty(); }); }
php
protected function packageTranslations() { return collect($this->app['translator']->getLoader()->namespaces())->flatMap(function ($path, $namespace) { return [ ($namespace .= '::') => collect($this->getFiles($path))->flatMap(function ($file) use ($namespace) { return [ ($translation = $file->getBasename('.php')) => trans($namespace . $translation), ]; }), ]; })->filter(function ($translations) { return $translations->isNotEmpty(); }); }
[ "protected", "function", "packageTranslations", "(", ")", "{", "return", "collect", "(", "$", "this", "->", "app", "[", "'translator'", "]", "->", "getLoader", "(", ")", "->", "namespaces", "(", ")", ")", "->", "flatMap", "(", "function", "(", "$", "path", ",", "$", "namespace", ")", "{", "return", "[", "(", "$", "namespace", ".=", "'::'", ")", "=>", "collect", "(", "$", "this", "->", "getFiles", "(", "$", "path", ")", ")", "->", "flatMap", "(", "function", "(", "$", "file", ")", "use", "(", "$", "namespace", ")", "{", "return", "[", "(", "$", "translation", "=", "$", "file", "->", "getBasename", "(", "'.php'", ")", ")", "=>", "trans", "(", "$", "namespace", ".", "$", "translation", ")", ",", "]", ";", "}", ")", ",", "]", ";", "}", ")", "->", "filter", "(", "function", "(", "$", "translations", ")", "{", "return", "$", "translations", "->", "isNotEmpty", "(", ")", ";", "}", ")", ";", "}" ]
Get the translations. @return \Illuminate\Support\Collection
[ "Get", "the", "translations", "." ]
train
https://github.com/thepinecode/i18n/blob/16190cf8aaaaca5f1ca09a79482d58893b7df342/src/I18nServiceProvider.php#L52-L65
thepinecode/i18n
src/I18nServiceProvider.php
I18nServiceProvider.getFiles
protected function getFiles($path) { $path = Str::finish($path, '/'); if (file_exists($path . App::getLocale())) { return File::files($path . App::getLocale()); } elseif (file_exists($path . config('app.fallback_locale'))) { return File::files($path . config('app.fallback_locale')); } return []; }
php
protected function getFiles($path) { $path = Str::finish($path, '/'); if (file_exists($path . App::getLocale())) { return File::files($path . App::getLocale()); } elseif (file_exists($path . config('app.fallback_locale'))) { return File::files($path . config('app.fallback_locale')); } return []; }
[ "protected", "function", "getFiles", "(", "$", "path", ")", "{", "$", "path", "=", "Str", "::", "finish", "(", "$", "path", ",", "'/'", ")", ";", "if", "(", "file_exists", "(", "$", "path", ".", "App", "::", "getLocale", "(", ")", ")", ")", "{", "return", "File", "::", "files", "(", "$", "path", ".", "App", "::", "getLocale", "(", ")", ")", ";", "}", "elseif", "(", "file_exists", "(", "$", "path", ".", "config", "(", "'app.fallback_locale'", ")", ")", ")", "{", "return", "File", "::", "files", "(", "$", "path", ".", "config", "(", "'app.fallback_locale'", ")", ")", ";", "}", "return", "[", "]", ";", "}" ]
Get the files for the given locale. @param string $path @return array
[ "Get", "the", "files", "for", "the", "given", "locale", "." ]
train
https://github.com/thepinecode/i18n/blob/16190cf8aaaaca5f1ca09a79482d58893b7df342/src/I18nServiceProvider.php#L73-L84
googlearchive/firebase-token-generator-php
src/TokenGenerator.php
TokenGenerator.setOption
public function setOption($name, $value) { if (!array_key_exists($name, $this->options)) { throw new TokenException( sprintf( 'Unsupported option "%s". Valid options are: %s', $name, implode(', ', array_keys($this->options)) ) ); } switch ($name) { case 'admin': case 'debug': if (!is_bool($value)) { throw new TokenException( sprintf('Invalid option "%s". Expected %s, but %s given', $name, 'bool', gettype($value)) ); } break; case 'expires': case 'notBefore': if (!is_int($value) && !($value instanceof \DateTime)) { throw new TokenException( sprintf( 'Invalid option "%s". Expected %s, but %s given', $name, 'int or DateTime', gettype($value) ) ); } if (is_int($value)) { $value = \DateTime::createFromFormat('U', $value); } break; } $this->options[$name] = $value; return $this; }
php
public function setOption($name, $value) { if (!array_key_exists($name, $this->options)) { throw new TokenException( sprintf( 'Unsupported option "%s". Valid options are: %s', $name, implode(', ', array_keys($this->options)) ) ); } switch ($name) { case 'admin': case 'debug': if (!is_bool($value)) { throw new TokenException( sprintf('Invalid option "%s". Expected %s, but %s given', $name, 'bool', gettype($value)) ); } break; case 'expires': case 'notBefore': if (!is_int($value) && !($value instanceof \DateTime)) { throw new TokenException( sprintf( 'Invalid option "%s". Expected %s, but %s given', $name, 'int or DateTime', gettype($value) ) ); } if (is_int($value)) { $value = \DateTime::createFromFormat('U', $value); } break; } $this->options[$name] = $value; return $this; }
[ "public", "function", "setOption", "(", "$", "name", ",", "$", "value", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "this", "->", "options", ")", ")", "{", "throw", "new", "TokenException", "(", "sprintf", "(", "'Unsupported option \"%s\". Valid options are: %s'", ",", "$", "name", ",", "implode", "(", "', '", ",", "array_keys", "(", "$", "this", "->", "options", ")", ")", ")", ")", ";", "}", "switch", "(", "$", "name", ")", "{", "case", "'admin'", ":", "case", "'debug'", ":", "if", "(", "!", "is_bool", "(", "$", "value", ")", ")", "{", "throw", "new", "TokenException", "(", "sprintf", "(", "'Invalid option \"%s\". Expected %s, but %s given'", ",", "$", "name", ",", "'bool'", ",", "gettype", "(", "$", "value", ")", ")", ")", ";", "}", "break", ";", "case", "'expires'", ":", "case", "'notBefore'", ":", "if", "(", "!", "is_int", "(", "$", "value", ")", "&&", "!", "(", "$", "value", "instanceof", "\\", "DateTime", ")", ")", "{", "throw", "new", "TokenException", "(", "sprintf", "(", "'Invalid option \"%s\". Expected %s, but %s given'", ",", "$", "name", ",", "'int or DateTime'", ",", "gettype", "(", "$", "value", ")", ")", ")", ";", "}", "if", "(", "is_int", "(", "$", "value", ")", ")", "{", "$", "value", "=", "\\", "DateTime", "::", "createFromFormat", "(", "'U'", ",", "$", "value", ")", ";", "}", "break", ";", "}", "$", "this", "->", "options", "[", "$", "name", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Sets an option. @param string $name The option name. @param mixed $value The option value. @throws TokenException If an invalid option has been given. @return static
[ "Sets", "an", "option", "." ]
train
https://github.com/googlearchive/firebase-token-generator-php/blob/4a7ab75c8e976c55399cfc6df1d436bed236c802/src/TokenGenerator.php#L116-L155
googlearchive/firebase-token-generator-php
src/TokenGenerator.php
TokenGenerator.create
public function create() { $this->validate(); $claims = $this->processOptions(); $claims['d'] = $this->data; $claims['v'] = 0; $claims['iat'] = time(); try { $token = JWT::encode($claims, $this->secret, 'HS256'); } catch (\Exception $e) { throw new TokenException($e->getMessage(), null, $e); } if (($tokenSize = mb_strlen($token, '8bit')) > static::MAX_TOKEN_SIZE) { throw new TokenException( sprintf('The generated token is larger than %d bytes (%d)', static::MAX_TOKEN_SIZE, $tokenSize) ); } return $token; }
php
public function create() { $this->validate(); $claims = $this->processOptions(); $claims['d'] = $this->data; $claims['v'] = 0; $claims['iat'] = time(); try { $token = JWT::encode($claims, $this->secret, 'HS256'); } catch (\Exception $e) { throw new TokenException($e->getMessage(), null, $e); } if (($tokenSize = mb_strlen($token, '8bit')) > static::MAX_TOKEN_SIZE) { throw new TokenException( sprintf('The generated token is larger than %d bytes (%d)', static::MAX_TOKEN_SIZE, $tokenSize) ); } return $token; }
[ "public", "function", "create", "(", ")", "{", "$", "this", "->", "validate", "(", ")", ";", "$", "claims", "=", "$", "this", "->", "processOptions", "(", ")", ";", "$", "claims", "[", "'d'", "]", "=", "$", "this", "->", "data", ";", "$", "claims", "[", "'v'", "]", "=", "0", ";", "$", "claims", "[", "'iat'", "]", "=", "time", "(", ")", ";", "try", "{", "$", "token", "=", "JWT", "::", "encode", "(", "$", "claims", ",", "$", "this", "->", "secret", ",", "'HS256'", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "TokenException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "null", ",", "$", "e", ")", ";", "}", "if", "(", "(", "$", "tokenSize", "=", "mb_strlen", "(", "$", "token", ",", "'8bit'", ")", ")", ">", "static", "::", "MAX_TOKEN_SIZE", ")", "{", "throw", "new", "TokenException", "(", "sprintf", "(", "'The generated token is larger than %d bytes (%d)'", ",", "static", "::", "MAX_TOKEN_SIZE", ",", "$", "tokenSize", ")", ")", ";", "}", "return", "$", "token", ";", "}" ]
Creates the token. @throws TokenException If the token couldn't be generated or is invalid. @return string The JWT token.
[ "Creates", "the", "token", "." ]
train
https://github.com/googlearchive/firebase-token-generator-php/blob/4a7ab75c8e976c55399cfc6df1d436bed236c802/src/TokenGenerator.php#L164-L186
googlearchive/firebase-token-generator-php
src/TokenGenerator.php
TokenGenerator.processOptions
private function processOptions() { $claims = []; foreach ($this->options as $name => $value) { switch ($name) { case 'expires': if ($value instanceof \DateTime) { $claims['exp'] = $value->getTimestamp(); } break; case 'notBefore': if ($value instanceof \DateTime) { $claims['nbf'] = $value->getTimestamp(); } break; default: $claims[$name] = $value; break; } } return $claims; }
php
private function processOptions() { $claims = []; foreach ($this->options as $name => $value) { switch ($name) { case 'expires': if ($value instanceof \DateTime) { $claims['exp'] = $value->getTimestamp(); } break; case 'notBefore': if ($value instanceof \DateTime) { $claims['nbf'] = $value->getTimestamp(); } break; default: $claims[$name] = $value; break; } } return $claims; }
[ "private", "function", "processOptions", "(", ")", "{", "$", "claims", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "options", "as", "$", "name", "=>", "$", "value", ")", "{", "switch", "(", "$", "name", ")", "{", "case", "'expires'", ":", "if", "(", "$", "value", "instanceof", "\\", "DateTime", ")", "{", "$", "claims", "[", "'exp'", "]", "=", "$", "value", "->", "getTimestamp", "(", ")", ";", "}", "break", ";", "case", "'notBefore'", ":", "if", "(", "$", "value", "instanceof", "\\", "DateTime", ")", "{", "$", "claims", "[", "'nbf'", "]", "=", "$", "value", "->", "getTimestamp", "(", ")", ";", "}", "break", ";", "default", ":", "$", "claims", "[", "$", "name", "]", "=", "$", "value", ";", "break", ";", "}", "}", "return", "$", "claims", ";", "}" ]
Parses provided options into a claims array. @return array The claims.
[ "Parses", "provided", "options", "into", "a", "claims", "array", "." ]
train
https://github.com/googlearchive/firebase-token-generator-php/blob/4a7ab75c8e976c55399cfc6df1d436bed236c802/src/TokenGenerator.php#L193-L216
googlearchive/firebase-token-generator-php
src/TokenGenerator.php
TokenGenerator.validate
private function validate() { if (false === $this->options['admin'] && !array_key_exists('uid', $this->data)) { throw new TokenException('No uid provided in data and admin option not set.'); } if (array_key_exists('uid', $this->data)) { $this->validateUid($this->data['uid']); } }
php
private function validate() { if (false === $this->options['admin'] && !array_key_exists('uid', $this->data)) { throw new TokenException('No uid provided in data and admin option not set.'); } if (array_key_exists('uid', $this->data)) { $this->validateUid($this->data['uid']); } }
[ "private", "function", "validate", "(", ")", "{", "if", "(", "false", "===", "$", "this", "->", "options", "[", "'admin'", "]", "&&", "!", "array_key_exists", "(", "'uid'", ",", "$", "this", "->", "data", ")", ")", "{", "throw", "new", "TokenException", "(", "'No uid provided in data and admin option not set.'", ")", ";", "}", "if", "(", "array_key_exists", "(", "'uid'", ",", "$", "this", "->", "data", ")", ")", "{", "$", "this", "->", "validateUid", "(", "$", "this", "->", "data", "[", "'uid'", "]", ")", ";", "}", "}" ]
Validates the combination of data and options. @throws TokenException If the combination of data and options is invalid.
[ "Validates", "the", "combination", "of", "data", "and", "options", "." ]
train
https://github.com/googlearchive/firebase-token-generator-php/blob/4a7ab75c8e976c55399cfc6df1d436bed236c802/src/TokenGenerator.php#L223-L232
googlearchive/firebase-token-generator-php
src/TokenGenerator.php
TokenGenerator.validateUid
private function validateUid($uid) { if (!is_string($uid)) { throw new TokenException(sprintf('The uid must be a string, %s given.', gettype($uid))); } $uidSize = mb_strlen($uid, '8bit'); if ($uidSize > static::MAX_UID_SIZE) { throw new TokenException( sprintf('The provided uid is longer than %d bytes (%d).', static::MAX_UID_SIZE, $uidSize) ); } if (0 === $uidSize) { throw new TokenException('The provided uid is empty.'); } }
php
private function validateUid($uid) { if (!is_string($uid)) { throw new TokenException(sprintf('The uid must be a string, %s given.', gettype($uid))); } $uidSize = mb_strlen($uid, '8bit'); if ($uidSize > static::MAX_UID_SIZE) { throw new TokenException( sprintf('The provided uid is longer than %d bytes (%d).', static::MAX_UID_SIZE, $uidSize) ); } if (0 === $uidSize) { throw new TokenException('The provided uid is empty.'); } }
[ "private", "function", "validateUid", "(", "$", "uid", ")", "{", "if", "(", "!", "is_string", "(", "$", "uid", ")", ")", "{", "throw", "new", "TokenException", "(", "sprintf", "(", "'The uid must be a string, %s given.'", ",", "gettype", "(", "$", "uid", ")", ")", ")", ";", "}", "$", "uidSize", "=", "mb_strlen", "(", "$", "uid", ",", "'8bit'", ")", ";", "if", "(", "$", "uidSize", ">", "static", "::", "MAX_UID_SIZE", ")", "{", "throw", "new", "TokenException", "(", "sprintf", "(", "'The provided uid is longer than %d bytes (%d).'", ",", "static", "::", "MAX_UID_SIZE", ",", "$", "uidSize", ")", ")", ";", "}", "if", "(", "0", "===", "$", "uidSize", ")", "{", "throw", "new", "TokenException", "(", "'The provided uid is empty.'", ")", ";", "}", "}" ]
Validates an uid. @param string $uid The uid. @throws TokenException If the uid is invalid.
[ "Validates", "an", "uid", "." ]
train
https://github.com/googlearchive/firebase-token-generator-php/blob/4a7ab75c8e976c55399cfc6df1d436bed236c802/src/TokenGenerator.php#L241-L258
Sylius/Registry
src/PrioritizedServiceRegistry.php
PrioritizedServiceRegistry.register
public function register($service, int $priority = 0): void { $this->assertServiceHaveType($service); $this->services->insert($service, $priority); }
php
public function register($service, int $priority = 0): void { $this->assertServiceHaveType($service); $this->services->insert($service, $priority); }
[ "public", "function", "register", "(", "$", "service", ",", "int", "$", "priority", "=", "0", ")", ":", "void", "{", "$", "this", "->", "assertServiceHaveType", "(", "$", "service", ")", ";", "$", "this", "->", "services", "->", "insert", "(", "$", "service", ",", "$", "priority", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/Sylius/Registry/blob/0f3e6caeb8a8f397905e4a590beca1d8a123e160/src/PrioritizedServiceRegistry.php#L58-L62
Sylius/Registry
src/PrioritizedServiceRegistry.php
PrioritizedServiceRegistry.unregister
public function unregister($service): void { if (!$this->has($service)) { throw new NonExistingServiceException($this->context, gettype($service), array_keys($this->services->toArray())); } $this->services->remove($service); }
php
public function unregister($service): void { if (!$this->has($service)) { throw new NonExistingServiceException($this->context, gettype($service), array_keys($this->services->toArray())); } $this->services->remove($service); }
[ "public", "function", "unregister", "(", "$", "service", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "service", ")", ")", "{", "throw", "new", "NonExistingServiceException", "(", "$", "this", "->", "context", ",", "gettype", "(", "$", "service", ")", ",", "array_keys", "(", "$", "this", "->", "services", "->", "toArray", "(", ")", ")", ")", ";", "}", "$", "this", "->", "services", "->", "remove", "(", "$", "service", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/Sylius/Registry/blob/0f3e6caeb8a8f397905e4a590beca1d8a123e160/src/PrioritizedServiceRegistry.php#L67-L74
Sylius/Registry
src/PrioritizedServiceRegistry.php
PrioritizedServiceRegistry.has
public function has($service): bool { $this->assertServiceHaveType($service); return $this->services->contains($service); }
php
public function has($service): bool { $this->assertServiceHaveType($service); return $this->services->contains($service); }
[ "public", "function", "has", "(", "$", "service", ")", ":", "bool", "{", "$", "this", "->", "assertServiceHaveType", "(", "$", "service", ")", ";", "return", "$", "this", "->", "services", "->", "contains", "(", "$", "service", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/Sylius/Registry/blob/0f3e6caeb8a8f397905e4a590beca1d8a123e160/src/PrioritizedServiceRegistry.php#L79-L84
Sylius/Registry
src/ServiceRegistry.php
ServiceRegistry.register
public function register(string $identifier, $service): void { if ($this->has($identifier)) { throw new ExistingServiceException($this->context, $identifier); } if (!is_object($service)) { throw new \InvalidArgumentException(sprintf('%s needs to be an object, %s given.', ucfirst($this->context), gettype($service))); } if (!$service instanceof $this->className) { throw new \InvalidArgumentException( sprintf('%s needs to be of type "%s", "%s" given.', ucfirst($this->context), $this->className, get_class($service)) ); } $this->services[$identifier] = $service; }
php
public function register(string $identifier, $service): void { if ($this->has($identifier)) { throw new ExistingServiceException($this->context, $identifier); } if (!is_object($service)) { throw new \InvalidArgumentException(sprintf('%s needs to be an object, %s given.', ucfirst($this->context), gettype($service))); } if (!$service instanceof $this->className) { throw new \InvalidArgumentException( sprintf('%s needs to be of type "%s", "%s" given.', ucfirst($this->context), $this->className, get_class($service)) ); } $this->services[$identifier] = $service; }
[ "public", "function", "register", "(", "string", "$", "identifier", ",", "$", "service", ")", ":", "void", "{", "if", "(", "$", "this", "->", "has", "(", "$", "identifier", ")", ")", "{", "throw", "new", "ExistingServiceException", "(", "$", "this", "->", "context", ",", "$", "identifier", ")", ";", "}", "if", "(", "!", "is_object", "(", "$", "service", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'%s needs to be an object, %s given.'", ",", "ucfirst", "(", "$", "this", "->", "context", ")", ",", "gettype", "(", "$", "service", ")", ")", ")", ";", "}", "if", "(", "!", "$", "service", "instanceof", "$", "this", "->", "className", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'%s needs to be of type \"%s\", \"%s\" given.'", ",", "ucfirst", "(", "$", "this", "->", "context", ")", ",", "$", "this", "->", "className", ",", "get_class", "(", "$", "service", ")", ")", ")", ";", "}", "$", "this", "->", "services", "[", "$", "identifier", "]", "=", "$", "service", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/Sylius/Registry/blob/0f3e6caeb8a8f397905e4a590beca1d8a123e160/src/ServiceRegistry.php#L55-L72
Sylius/Registry
src/ServiceRegistry.php
ServiceRegistry.unregister
public function unregister(string $identifier): void { if (!$this->has($identifier)) { throw new NonExistingServiceException($this->context, $identifier, array_keys($this->services)); } unset($this->services[$identifier]); }
php
public function unregister(string $identifier): void { if (!$this->has($identifier)) { throw new NonExistingServiceException($this->context, $identifier, array_keys($this->services)); } unset($this->services[$identifier]); }
[ "public", "function", "unregister", "(", "string", "$", "identifier", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "has", "(", "$", "identifier", ")", ")", "{", "throw", "new", "NonExistingServiceException", "(", "$", "this", "->", "context", ",", "$", "identifier", ",", "array_keys", "(", "$", "this", "->", "services", ")", ")", ";", "}", "unset", "(", "$", "this", "->", "services", "[", "$", "identifier", "]", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/Sylius/Registry/blob/0f3e6caeb8a8f397905e4a590beca1d8a123e160/src/ServiceRegistry.php#L77-L84
esbenp/heimdal
src/ExceptionHandler.php
ExceptionHandler.report
public function report(Exception $e) { parent::report($e); $this->reportResponses = []; if ($this->shouldntReport($e)) { return $this->reportResponses; } $reporters = $this->config['reporters']; foreach ($reporters as $key => $reporter) { $class = !isset($reporter['class']) ? null : $reporter['class']; if ( is_null($class) || !class_exists($class) || !in_array(ReporterInterface::class, class_implements($class)) ) { throw new InvalidArgumentException( sprintf( "%s: %s is not a valid reporter class.", $key, $class ) ); } $config = isset($reporter['config']) && is_array($reporter['config']) ? $reporter['config'] : []; // $this->container->make($class)($config) fails php <= 5.4 $reporterFactory = $this->container->make($class); $reporterInstance = $reporterFactory($config); $this->reportResponses[$key] = $reporterInstance->report($e); } }
php
public function report(Exception $e) { parent::report($e); $this->reportResponses = []; if ($this->shouldntReport($e)) { return $this->reportResponses; } $reporters = $this->config['reporters']; foreach ($reporters as $key => $reporter) { $class = !isset($reporter['class']) ? null : $reporter['class']; if ( is_null($class) || !class_exists($class) || !in_array(ReporterInterface::class, class_implements($class)) ) { throw new InvalidArgumentException( sprintf( "%s: %s is not a valid reporter class.", $key, $class ) ); } $config = isset($reporter['config']) && is_array($reporter['config']) ? $reporter['config'] : []; // $this->container->make($class)($config) fails php <= 5.4 $reporterFactory = $this->container->make($class); $reporterInstance = $reporterFactory($config); $this->reportResponses[$key] = $reporterInstance->report($e); } }
[ "public", "function", "report", "(", "Exception", "$", "e", ")", "{", "parent", "::", "report", "(", "$", "e", ")", ";", "$", "this", "->", "reportResponses", "=", "[", "]", ";", "if", "(", "$", "this", "->", "shouldntReport", "(", "$", "e", ")", ")", "{", "return", "$", "this", "->", "reportResponses", ";", "}", "$", "reporters", "=", "$", "this", "->", "config", "[", "'reporters'", "]", ";", "foreach", "(", "$", "reporters", "as", "$", "key", "=>", "$", "reporter", ")", "{", "$", "class", "=", "!", "isset", "(", "$", "reporter", "[", "'class'", "]", ")", "?", "null", ":", "$", "reporter", "[", "'class'", "]", ";", "if", "(", "is_null", "(", "$", "class", ")", "||", "!", "class_exists", "(", "$", "class", ")", "||", "!", "in_array", "(", "ReporterInterface", "::", "class", ",", "class_implements", "(", "$", "class", ")", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "\"%s: %s is not a valid reporter class.\"", ",", "$", "key", ",", "$", "class", ")", ")", ";", "}", "$", "config", "=", "isset", "(", "$", "reporter", "[", "'config'", "]", ")", "&&", "is_array", "(", "$", "reporter", "[", "'config'", "]", ")", "?", "$", "reporter", "[", "'config'", "]", ":", "[", "]", ";", "// $this->container->make($class)($config) fails php <= 5.4", "$", "reporterFactory", "=", "$", "this", "->", "container", "->", "make", "(", "$", "class", ")", ";", "$", "reporterInstance", "=", "$", "reporterFactory", "(", "$", "config", ")", ";", "$", "this", "->", "reportResponses", "[", "$", "key", "]", "=", "$", "reporterInstance", "->", "report", "(", "$", "e", ")", ";", "}", "}" ]
Report @param Exception $e @throws Exception @returns void
[ "Report" ]
train
https://github.com/esbenp/heimdal/blob/6cb406b2acd2c4cec948099a9855a0f5a1aed437/src/ExceptionHandler.php#L43-L80
esbenp/heimdal
src/ExceptionHandler.php
ExceptionHandler.render
public function render($request, Exception $e) { $response = $this->generateExceptionResponse($request, $e); if ($this->config['add_cors_headers']) { if (!class_exists(CorsService::class)) { throw new InvalidArgumentException( 'asm89/stack-cors has not been installed. Optimus\Heimdal needs it for adding CORS headers to response.' ); } /** @var CorsService $cors */ $cors = $this->container->make(CorsService::class); $cors->addActualRequestHeaders($response, $request); } return $response; }
php
public function render($request, Exception $e) { $response = $this->generateExceptionResponse($request, $e); if ($this->config['add_cors_headers']) { if (!class_exists(CorsService::class)) { throw new InvalidArgumentException( 'asm89/stack-cors has not been installed. Optimus\Heimdal needs it for adding CORS headers to response.' ); } /** @var CorsService $cors */ $cors = $this->container->make(CorsService::class); $cors->addActualRequestHeaders($response, $request); } return $response; }
[ "public", "function", "render", "(", "$", "request", ",", "Exception", "$", "e", ")", "{", "$", "response", "=", "$", "this", "->", "generateExceptionResponse", "(", "$", "request", ",", "$", "e", ")", ";", "if", "(", "$", "this", "->", "config", "[", "'add_cors_headers'", "]", ")", "{", "if", "(", "!", "class_exists", "(", "CorsService", "::", "class", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'asm89/stack-cors has not been installed. Optimus\\Heimdal needs it for adding CORS headers to response.'", ")", ";", "}", "/** @var CorsService $cors */", "$", "cors", "=", "$", "this", "->", "container", "->", "make", "(", "CorsService", "::", "class", ")", ";", "$", "cors", "->", "addActualRequestHeaders", "(", "$", "response", ",", "$", "request", ")", ";", "}", "return", "$", "response", ";", "}" ]
Render @param \Illuminate\Http\Request $request @param Exception $e @return \Symfony\Component\HttpFoundation\Response
[ "Render" ]
train
https://github.com/esbenp/heimdal/blob/6cb406b2acd2c4cec948099a9855a0f5a1aed437/src/ExceptionHandler.php#L89-L106
esbenp/heimdal
src/ExceptionHandler.php
ExceptionHandler.generateExceptionResponse
private function generateExceptionResponse($request, Exception $e) { $formatters = $this->config['formatters']; // :: notation will otherwise not work for PHP <= 5.6 $responseFactoryClass = $this->config['response_factory']; // Allow users to have a base formatter for every response. $response = $responseFactoryClass::make($e); foreach($formatters as $exceptionType => $formatter) { if (!($e instanceof $exceptionType)) { continue; } if ( !class_exists($formatter) || !(new ReflectionClass($formatter))->isSubclassOf(new ReflectionClass(BaseFormatter::class)) ) { throw new InvalidArgumentException( sprintf( "%s is not a valid formatter class.", $formatter ) ); } $formatterInstance = new $formatter($this->config, $this->debug); $formatterInstance->format($response, $e, $this->reportResponses); break; } return $response; }
php
private function generateExceptionResponse($request, Exception $e) { $formatters = $this->config['formatters']; // :: notation will otherwise not work for PHP <= 5.6 $responseFactoryClass = $this->config['response_factory']; // Allow users to have a base formatter for every response. $response = $responseFactoryClass::make($e); foreach($formatters as $exceptionType => $formatter) { if (!($e instanceof $exceptionType)) { continue; } if ( !class_exists($formatter) || !(new ReflectionClass($formatter))->isSubclassOf(new ReflectionClass(BaseFormatter::class)) ) { throw new InvalidArgumentException( sprintf( "%s is not a valid formatter class.", $formatter ) ); } $formatterInstance = new $formatter($this->config, $this->debug); $formatterInstance->format($response, $e, $this->reportResponses); break; } return $response; }
[ "private", "function", "generateExceptionResponse", "(", "$", "request", ",", "Exception", "$", "e", ")", "{", "$", "formatters", "=", "$", "this", "->", "config", "[", "'formatters'", "]", ";", "// :: notation will otherwise not work for PHP <= 5.6", "$", "responseFactoryClass", "=", "$", "this", "->", "config", "[", "'response_factory'", "]", ";", "// Allow users to have a base formatter for every response.", "$", "response", "=", "$", "responseFactoryClass", "::", "make", "(", "$", "e", ")", ";", "foreach", "(", "$", "formatters", "as", "$", "exceptionType", "=>", "$", "formatter", ")", "{", "if", "(", "!", "(", "$", "e", "instanceof", "$", "exceptionType", ")", ")", "{", "continue", ";", "}", "if", "(", "!", "class_exists", "(", "$", "formatter", ")", "||", "!", "(", "new", "ReflectionClass", "(", "$", "formatter", ")", ")", "->", "isSubclassOf", "(", "new", "ReflectionClass", "(", "BaseFormatter", "::", "class", ")", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "\"%s is not a valid formatter class.\"", ",", "$", "formatter", ")", ")", ";", "}", "$", "formatterInstance", "=", "new", "$", "formatter", "(", "$", "this", "->", "config", ",", "$", "this", "->", "debug", ")", ";", "$", "formatterInstance", "->", "format", "(", "$", "response", ",", "$", "e", ",", "$", "this", "->", "reportResponses", ")", ";", "break", ";", "}", "return", "$", "response", ";", "}" ]
Generate exception response @param $request @param Exception $e @return mixed
[ "Generate", "exception", "response" ]
train
https://github.com/esbenp/heimdal/blob/6cb406b2acd2c4cec948099a9855a0f5a1aed437/src/ExceptionHandler.php#L115-L149
willvincent/laravel-rateable
src/Rateable/Rating.php
Rating.user
public function user() { $userClassName = Config::get('auth.model'); if (is_null($userClassName)) { $userClassName = Config::get('auth.providers.users.model'); } return $this->belongsTo($userClassName); }
php
public function user() { $userClassName = Config::get('auth.model'); if (is_null($userClassName)) { $userClassName = Config::get('auth.providers.users.model'); } return $this->belongsTo($userClassName); }
[ "public", "function", "user", "(", ")", "{", "$", "userClassName", "=", "Config", "::", "get", "(", "'auth.model'", ")", ";", "if", "(", "is_null", "(", "$", "userClassName", ")", ")", "{", "$", "userClassName", "=", "Config", "::", "get", "(", "'auth.providers.users.model'", ")", ";", "}", "return", "$", "this", "->", "belongsTo", "(", "$", "userClassName", ")", ";", "}" ]
Rating belongs to a user. @return User
[ "Rating", "belongs", "to", "a", "user", "." ]
train
https://github.com/willvincent/laravel-rateable/blob/010bcbf8d12cec79ba106d85ad7baeae48faa96c/src/Rateable/Rating.php#L28-L36
willvincent/laravel-rateable
src/commands/MigrationCommand.php
MigrationCommand.handle
public function handle() { $this->info('Tables: ratings'); $this->line(''); $this->comment('A migration that creates a "ratings" table will be created in the `database/migrations` directory'); $this->line(''); if ($this->confirm("Proceed with the migration creation?")) { $this->line(''); $this->info("Creating migration..."); $this->line(''); if ($this->createMigration()) { $this->info("Migration successfully created!"); } else { $this->error( "Coudn't create migration.\n Check the write permissions". " within the `database/migrations` directory." ); } $this->line(''); } }
php
public function handle() { $this->info('Tables: ratings'); $this->line(''); $this->comment('A migration that creates a "ratings" table will be created in the `database/migrations` directory'); $this->line(''); if ($this->confirm("Proceed with the migration creation?")) { $this->line(''); $this->info("Creating migration..."); $this->line(''); if ($this->createMigration()) { $this->info("Migration successfully created!"); } else { $this->error( "Coudn't create migration.\n Check the write permissions". " within the `database/migrations` directory." ); } $this->line(''); } }
[ "public", "function", "handle", "(", ")", "{", "$", "this", "->", "info", "(", "'Tables: ratings'", ")", ";", "$", "this", "->", "line", "(", "''", ")", ";", "$", "this", "->", "comment", "(", "'A migration that creates a \"ratings\" table will be created in the `database/migrations` directory'", ")", ";", "$", "this", "->", "line", "(", "''", ")", ";", "if", "(", "$", "this", "->", "confirm", "(", "\"Proceed with the migration creation?\"", ")", ")", "{", "$", "this", "->", "line", "(", "''", ")", ";", "$", "this", "->", "info", "(", "\"Creating migration...\"", ")", ";", "$", "this", "->", "line", "(", "''", ")", ";", "if", "(", "$", "this", "->", "createMigration", "(", ")", ")", "{", "$", "this", "->", "info", "(", "\"Migration successfully created!\"", ")", ";", "}", "else", "{", "$", "this", "->", "error", "(", "\"Coudn't create migration.\\n Check the write permissions\"", ".", "\" within the `database/migrations` directory.\"", ")", ";", "}", "$", "this", "->", "line", "(", "''", ")", ";", "}", "}" ]
Execute the console command.
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/willvincent/laravel-rateable/blob/010bcbf8d12cec79ba106d85ad7baeae48faa96c/src/commands/MigrationCommand.php#L32-L55
willvincent/laravel-rateable
src/commands/MigrationCommand.php
MigrationCommand.createMigration
protected function createMigration() { $migration_file = database_path('migrations').'/'.date('Y_m_d_His').'_create_ratings_table.php'; if (! file_exists($migration_file) && $fs = fopen($migration_file, 'x')) { fwrite($fs, file_get_contents(__DIR__.'/../migrations/create_ratings_table.php')); fclose($fs); return true; } return false; }
php
protected function createMigration() { $migration_file = database_path('migrations').'/'.date('Y_m_d_His').'_create_ratings_table.php'; if (! file_exists($migration_file) && $fs = fopen($migration_file, 'x')) { fwrite($fs, file_get_contents(__DIR__.'/../migrations/create_ratings_table.php')); fclose($fs); return true; } return false; }
[ "protected", "function", "createMigration", "(", ")", "{", "$", "migration_file", "=", "database_path", "(", "'migrations'", ")", ".", "'/'", ".", "date", "(", "'Y_m_d_His'", ")", ".", "'_create_ratings_table.php'", ";", "if", "(", "!", "file_exists", "(", "$", "migration_file", ")", "&&", "$", "fs", "=", "fopen", "(", "$", "migration_file", ",", "'x'", ")", ")", "{", "fwrite", "(", "$", "fs", ",", "file_get_contents", "(", "__DIR__", ".", "'/../migrations/create_ratings_table.php'", ")", ")", ";", "fclose", "(", "$", "fs", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Create the migration. @return bool
[ "Create", "the", "migration", "." ]
train
https://github.com/willvincent/laravel-rateable/blob/010bcbf8d12cec79ba106d85ad7baeae48faa96c/src/commands/MigrationCommand.php#L62-L73
inacho/php-credit-card-validator
src/CreditCard.php
CreditCard.creditCardType
protected static function creditCardType($number) { foreach (self::$cards as $type => $card) { if (preg_match($card['pattern'], $number)) { return $type; } } return ''; }
php
protected static function creditCardType($number) { foreach (self::$cards as $type => $card) { if (preg_match($card['pattern'], $number)) { return $type; } } return ''; }
[ "protected", "static", "function", "creditCardType", "(", "$", "number", ")", "{", "foreach", "(", "self", "::", "$", "cards", "as", "$", "type", "=>", "$", "card", ")", "{", "if", "(", "preg_match", "(", "$", "card", "[", "'pattern'", "]", ",", "$", "number", ")", ")", "{", "return", "$", "type", ";", "}", "}", "return", "''", ";", "}" ]
---------------------------------------------------------
[ "---------------------------------------------------------" ]
train
https://github.com/inacho/php-credit-card-validator/blob/af3bab9af09dd159fbd23815ab08b1092d7fa963/src/CreditCard.php#L153-L162
fxpio/foxy
Asset/AssetPackage.php
AssetPackage.getInstalledDependencies
public function getInstalledDependencies() { $installedAssets = array(); if (isset($this->package[self::SECTION_DEPENDENCIES]) && \is_array($this->package[self::SECTION_DEPENDENCIES])) { foreach ($this->package[self::SECTION_DEPENDENCIES] as $dependency => $version) { if (0 === strpos($dependency, self::COMPOSER_PREFIX)) { $installedAssets[$dependency] = $version; } } } return $installedAssets; }
php
public function getInstalledDependencies() { $installedAssets = array(); if (isset($this->package[self::SECTION_DEPENDENCIES]) && \is_array($this->package[self::SECTION_DEPENDENCIES])) { foreach ($this->package[self::SECTION_DEPENDENCIES] as $dependency => $version) { if (0 === strpos($dependency, self::COMPOSER_PREFIX)) { $installedAssets[$dependency] = $version; } } } return $installedAssets; }
[ "public", "function", "getInstalledDependencies", "(", ")", "{", "$", "installedAssets", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "package", "[", "self", "::", "SECTION_DEPENDENCIES", "]", ")", "&&", "\\", "is_array", "(", "$", "this", "->", "package", "[", "self", "::", "SECTION_DEPENDENCIES", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "package", "[", "self", "::", "SECTION_DEPENDENCIES", "]", "as", "$", "dependency", "=>", "$", "version", ")", "{", "if", "(", "0", "===", "strpos", "(", "$", "dependency", ",", "self", "::", "COMPOSER_PREFIX", ")", ")", "{", "$", "installedAssets", "[", "$", "dependency", "]", "=", "$", "version", ";", "}", "}", "}", "return", "$", "installedAssets", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AssetPackage.php#L86-L99
fxpio/foxy
Asset/AssetPackage.php
AssetPackage.addNewDependencies
public function addNewDependencies(array $dependencies) { $installedAssets = $this->getInstalledDependencies(); $existingPackages = array(); foreach ($dependencies as $name => $path) { if (isset($installedAssets[$name])) { $existingPackages[] = $name; } else { $this->package[self::SECTION_DEPENDENCIES][$name] = 'file:./'.\dirname($path); } } $this->orderPackages(self::SECTION_DEPENDENCIES); $this->orderPackages(self::SECTION_DEV_DEPENDENCIES); return $existingPackages; }
php
public function addNewDependencies(array $dependencies) { $installedAssets = $this->getInstalledDependencies(); $existingPackages = array(); foreach ($dependencies as $name => $path) { if (isset($installedAssets[$name])) { $existingPackages[] = $name; } else { $this->package[self::SECTION_DEPENDENCIES][$name] = 'file:./'.\dirname($path); } } $this->orderPackages(self::SECTION_DEPENDENCIES); $this->orderPackages(self::SECTION_DEV_DEPENDENCIES); return $existingPackages; }
[ "public", "function", "addNewDependencies", "(", "array", "$", "dependencies", ")", "{", "$", "installedAssets", "=", "$", "this", "->", "getInstalledDependencies", "(", ")", ";", "$", "existingPackages", "=", "array", "(", ")", ";", "foreach", "(", "$", "dependencies", "as", "$", "name", "=>", "$", "path", ")", "{", "if", "(", "isset", "(", "$", "installedAssets", "[", "$", "name", "]", ")", ")", "{", "$", "existingPackages", "[", "]", "=", "$", "name", ";", "}", "else", "{", "$", "this", "->", "package", "[", "self", "::", "SECTION_DEPENDENCIES", "]", "[", "$", "name", "]", "=", "'file:./'", ".", "\\", "dirname", "(", "$", "path", ")", ";", "}", "}", "$", "this", "->", "orderPackages", "(", "self", "::", "SECTION_DEPENDENCIES", ")", ";", "$", "this", "->", "orderPackages", "(", "self", "::", "SECTION_DEV_DEPENDENCIES", ")", ";", "return", "$", "existingPackages", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AssetPackage.php#L104-L121
fxpio/foxy
Asset/AssetPackage.php
AssetPackage.removeUnusedDependencies
public function removeUnusedDependencies(array $dependencies) { $installedAssets = $this->getInstalledDependencies(); $removeDependencies = array_diff_key($installedAssets, $dependencies); foreach ($removeDependencies as $dependency => $version) { unset($this->package[self::SECTION_DEPENDENCIES][$dependency]); } return $this; }
php
public function removeUnusedDependencies(array $dependencies) { $installedAssets = $this->getInstalledDependencies(); $removeDependencies = array_diff_key($installedAssets, $dependencies); foreach ($removeDependencies as $dependency => $version) { unset($this->package[self::SECTION_DEPENDENCIES][$dependency]); } return $this; }
[ "public", "function", "removeUnusedDependencies", "(", "array", "$", "dependencies", ")", "{", "$", "installedAssets", "=", "$", "this", "->", "getInstalledDependencies", "(", ")", ";", "$", "removeDependencies", "=", "array_diff_key", "(", "$", "installedAssets", ",", "$", "dependencies", ")", ";", "foreach", "(", "$", "removeDependencies", "as", "$", "dependency", "=>", "$", "version", ")", "{", "unset", "(", "$", "this", "->", "package", "[", "self", "::", "SECTION_DEPENDENCIES", "]", "[", "$", "dependency", "]", ")", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AssetPackage.php#L126-L136
fxpio/foxy
Asset/AssetPackage.php
AssetPackage.injectRequiredKeys
protected function injectRequiredKeys(RootPackageInterface $rootPackage) { if (!isset($this->package['license']) && \count($rootPackage->getLicense()) > 0) { $license = current($rootPackage->getLicense()); if ('proprietary' === $license) { if (!isset($this->package['private'])) { $this->package['private'] = true; } } else { $this->package['license'] = $license; } } }
php
protected function injectRequiredKeys(RootPackageInterface $rootPackage) { if (!isset($this->package['license']) && \count($rootPackage->getLicense()) > 0) { $license = current($rootPackage->getLicense()); if ('proprietary' === $license) { if (!isset($this->package['private'])) { $this->package['private'] = true; } } else { $this->package['license'] = $license; } } }
[ "protected", "function", "injectRequiredKeys", "(", "RootPackageInterface", "$", "rootPackage", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "package", "[", "'license'", "]", ")", "&&", "\\", "count", "(", "$", "rootPackage", "->", "getLicense", "(", ")", ")", ">", "0", ")", "{", "$", "license", "=", "current", "(", "$", "rootPackage", "->", "getLicense", "(", ")", ")", ";", "if", "(", "'proprietary'", "===", "$", "license", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "package", "[", "'private'", "]", ")", ")", "{", "$", "this", "->", "package", "[", "'private'", "]", "=", "true", ";", "}", "}", "else", "{", "$", "this", "->", "package", "[", "'license'", "]", "=", "$", "license", ";", "}", "}", "}" ]
Inject the required keys for asset package defined in root composer package. @param RootPackageInterface $rootPackage The composer root package
[ "Inject", "the", "required", "keys", "for", "asset", "package", "defined", "in", "root", "composer", "package", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AssetPackage.php#L143-L156
fxpio/foxy
Asset/AssetPackage.php
AssetPackage.orderPackages
protected function orderPackages($section) { if (isset($this->package[$section]) && \is_array($this->package[$section])) { ksort($this->package[$section], SORT_STRING); } }
php
protected function orderPackages($section) { if (isset($this->package[$section]) && \is_array($this->package[$section])) { ksort($this->package[$section], SORT_STRING); } }
[ "protected", "function", "orderPackages", "(", "$", "section", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "package", "[", "$", "section", "]", ")", "&&", "\\", "is_array", "(", "$", "this", "->", "package", "[", "$", "section", "]", ")", ")", "{", "ksort", "(", "$", "this", "->", "package", "[", "$", "section", "]", ",", "SORT_STRING", ")", ";", "}", "}" ]
Order the packages section. @param string $section The package section
[ "Order", "the", "packages", "section", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AssetPackage.php#L163-L168
fxpio/foxy
Fallback/ComposerFallback.php
ComposerFallback.save
public function save() { $rm = $this->composer->getRepositoryManager(); $im = $this->composer->getInstallationManager(); $composerFile = Factory::getComposerFile(); $lockFile = str_replace('.json', '.lock', $composerFile); $locker = new Locker($this->io, new JsonFile($lockFile, null, $this->io), $rm, $im, file_get_contents($composerFile)); try { $lock = $locker->getLockData(); $this->lock = PackageUtil::loadLockPackages($lock); } catch (\LogicException $e) { $this->lock = array(); } return $this; }
php
public function save() { $rm = $this->composer->getRepositoryManager(); $im = $this->composer->getInstallationManager(); $composerFile = Factory::getComposerFile(); $lockFile = str_replace('.json', '.lock', $composerFile); $locker = new Locker($this->io, new JsonFile($lockFile, null, $this->io), $rm, $im, file_get_contents($composerFile)); try { $lock = $locker->getLockData(); $this->lock = PackageUtil::loadLockPackages($lock); } catch (\LogicException $e) { $this->lock = array(); } return $this; }
[ "public", "function", "save", "(", ")", "{", "$", "rm", "=", "$", "this", "->", "composer", "->", "getRepositoryManager", "(", ")", ";", "$", "im", "=", "$", "this", "->", "composer", "->", "getInstallationManager", "(", ")", ";", "$", "composerFile", "=", "Factory", "::", "getComposerFile", "(", ")", ";", "$", "lockFile", "=", "str_replace", "(", "'.json'", ",", "'.lock'", ",", "$", "composerFile", ")", ";", "$", "locker", "=", "new", "Locker", "(", "$", "this", "->", "io", ",", "new", "JsonFile", "(", "$", "lockFile", ",", "null", ",", "$", "this", "->", "io", ")", ",", "$", "rm", ",", "$", "im", ",", "file_get_contents", "(", "$", "composerFile", ")", ")", ";", "try", "{", "$", "lock", "=", "$", "locker", "->", "getLockData", "(", ")", ";", "$", "this", "->", "lock", "=", "PackageUtil", "::", "loadLockPackages", "(", "$", "lock", ")", ";", "}", "catch", "(", "\\", "LogicException", "$", "e", ")", "{", "$", "this", "->", "lock", "=", "array", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/ComposerFallback.php#L97-L113
fxpio/foxy
Fallback/ComposerFallback.php
ComposerFallback.restore
public function restore() { if (!$this->config->get('fallback-composer')) { return; } $this->io->write('<info>Fallback to previous state for Composer</info>'); $hasLock = $this->restoreLockData(); if ($hasLock) { $this->restorePreviousLockFile(); } else { $this->fs->remove($this->composer->getConfig()->get('vendor-dir')); } }
php
public function restore() { if (!$this->config->get('fallback-composer')) { return; } $this->io->write('<info>Fallback to previous state for Composer</info>'); $hasLock = $this->restoreLockData(); if ($hasLock) { $this->restorePreviousLockFile(); } else { $this->fs->remove($this->composer->getConfig()->get('vendor-dir')); } }
[ "public", "function", "restore", "(", ")", "{", "if", "(", "!", "$", "this", "->", "config", "->", "get", "(", "'fallback-composer'", ")", ")", "{", "return", ";", "}", "$", "this", "->", "io", "->", "write", "(", "'<info>Fallback to previous state for Composer</info>'", ")", ";", "$", "hasLock", "=", "$", "this", "->", "restoreLockData", "(", ")", ";", "if", "(", "$", "hasLock", ")", "{", "$", "this", "->", "restorePreviousLockFile", "(", ")", ";", "}", "else", "{", "$", "this", "->", "fs", "->", "remove", "(", "$", "this", "->", "composer", "->", "getConfig", "(", ")", "->", "get", "(", "'vendor-dir'", ")", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/ComposerFallback.php#L118-L132
fxpio/foxy
Fallback/ComposerFallback.php
ComposerFallback.restoreLockData
protected function restoreLockData() { $this->composer->getLocker()->setLockData( $this->getLockValue('packages', array()), $this->getLockValue('packages-dev'), $this->getLockValue('platform', array()), $this->getLockValue('platform-dev', array()), $this->getLockValue('aliases', array()), $this->getLockValue('minimum-stability'), $this->getLockValue('stability-flags', array()), $this->getLockValue('prefer-stable', false), $this->getLockValue('prefer-lowest', false), $this->getLockValue('platform-overrides', array()) ); return $this->composer->getLocker()->isLocked(); }
php
protected function restoreLockData() { $this->composer->getLocker()->setLockData( $this->getLockValue('packages', array()), $this->getLockValue('packages-dev'), $this->getLockValue('platform', array()), $this->getLockValue('platform-dev', array()), $this->getLockValue('aliases', array()), $this->getLockValue('minimum-stability'), $this->getLockValue('stability-flags', array()), $this->getLockValue('prefer-stable', false), $this->getLockValue('prefer-lowest', false), $this->getLockValue('platform-overrides', array()) ); return $this->composer->getLocker()->isLocked(); }
[ "protected", "function", "restoreLockData", "(", ")", "{", "$", "this", "->", "composer", "->", "getLocker", "(", ")", "->", "setLockData", "(", "$", "this", "->", "getLockValue", "(", "'packages'", ",", "array", "(", ")", ")", ",", "$", "this", "->", "getLockValue", "(", "'packages-dev'", ")", ",", "$", "this", "->", "getLockValue", "(", "'platform'", ",", "array", "(", ")", ")", ",", "$", "this", "->", "getLockValue", "(", "'platform-dev'", ",", "array", "(", ")", ")", ",", "$", "this", "->", "getLockValue", "(", "'aliases'", ",", "array", "(", ")", ")", ",", "$", "this", "->", "getLockValue", "(", "'minimum-stability'", ")", ",", "$", "this", "->", "getLockValue", "(", "'stability-flags'", ",", "array", "(", ")", ")", ",", "$", "this", "->", "getLockValue", "(", "'prefer-stable'", ",", "false", ")", ",", "$", "this", "->", "getLockValue", "(", "'prefer-lowest'", ",", "false", ")", ",", "$", "this", "->", "getLockValue", "(", "'platform-overrides'", ",", "array", "(", ")", ")", ")", ";", "return", "$", "this", "->", "composer", "->", "getLocker", "(", ")", "->", "isLocked", "(", ")", ";", "}" ]
Restore the data of lock file. @return bool
[ "Restore", "the", "data", "of", "lock", "file", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/ComposerFallback.php#L139-L155
fxpio/foxy
Fallback/ComposerFallback.php
ComposerFallback.restorePreviousLockFile
protected function restorePreviousLockFile() { $config = $this->composer->getConfig(); list($preferSource, $preferDist) = ConsoleUtil::getPreferredInstallOptions($config, $this->input); $optimize = $this->input->getOption('optimize-autoloader') || $config->get('optimize-autoloader'); $authoritative = $this->input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcu = $this->input->getOption('apcu-autoloader') || $config->get('apcu-autoloader'); $this->getInstaller() ->setVerbose($this->input->getOption('verbose')) ->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode(!$this->input->getOption('no-dev')) ->setDumpAutoloader(!$this->input->getOption('no-autoloader')) ->setRunScripts(false) ->setSkipSuggest(true) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu) ->setIgnorePlatformRequirements($this->input->getOption('ignore-platform-reqs')) ->run() ; }
php
protected function restorePreviousLockFile() { $config = $this->composer->getConfig(); list($preferSource, $preferDist) = ConsoleUtil::getPreferredInstallOptions($config, $this->input); $optimize = $this->input->getOption('optimize-autoloader') || $config->get('optimize-autoloader'); $authoritative = $this->input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcu = $this->input->getOption('apcu-autoloader') || $config->get('apcu-autoloader'); $this->getInstaller() ->setVerbose($this->input->getOption('verbose')) ->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode(!$this->input->getOption('no-dev')) ->setDumpAutoloader(!$this->input->getOption('no-autoloader')) ->setRunScripts(false) ->setSkipSuggest(true) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu) ->setIgnorePlatformRequirements($this->input->getOption('ignore-platform-reqs')) ->run() ; }
[ "protected", "function", "restorePreviousLockFile", "(", ")", "{", "$", "config", "=", "$", "this", "->", "composer", "->", "getConfig", "(", ")", ";", "list", "(", "$", "preferSource", ",", "$", "preferDist", ")", "=", "ConsoleUtil", "::", "getPreferredInstallOptions", "(", "$", "config", ",", "$", "this", "->", "input", ")", ";", "$", "optimize", "=", "$", "this", "->", "input", "->", "getOption", "(", "'optimize-autoloader'", ")", "||", "$", "config", "->", "get", "(", "'optimize-autoloader'", ")", ";", "$", "authoritative", "=", "$", "this", "->", "input", "->", "getOption", "(", "'classmap-authoritative'", ")", "||", "$", "config", "->", "get", "(", "'classmap-authoritative'", ")", ";", "$", "apcu", "=", "$", "this", "->", "input", "->", "getOption", "(", "'apcu-autoloader'", ")", "||", "$", "config", "->", "get", "(", "'apcu-autoloader'", ")", ";", "$", "this", "->", "getInstaller", "(", ")", "->", "setVerbose", "(", "$", "this", "->", "input", "->", "getOption", "(", "'verbose'", ")", ")", "->", "setPreferSource", "(", "$", "preferSource", ")", "->", "setPreferDist", "(", "$", "preferDist", ")", "->", "setDevMode", "(", "!", "$", "this", "->", "input", "->", "getOption", "(", "'no-dev'", ")", ")", "->", "setDumpAutoloader", "(", "!", "$", "this", "->", "input", "->", "getOption", "(", "'no-autoloader'", ")", ")", "->", "setRunScripts", "(", "false", ")", "->", "setSkipSuggest", "(", "true", ")", "->", "setOptimizeAutoloader", "(", "$", "optimize", ")", "->", "setClassMapAuthoritative", "(", "$", "authoritative", ")", "->", "setApcuAutoloader", "(", "$", "apcu", ")", "->", "setIgnorePlatformRequirements", "(", "$", "this", "->", "input", "->", "getOption", "(", "'ignore-platform-reqs'", ")", ")", "->", "run", "(", ")", ";", "}" ]
Restore the PHP dependencies with the previous lock file.
[ "Restore", "the", "PHP", "dependencies", "with", "the", "previous", "lock", "file", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/ComposerFallback.php#L160-L182
fxpio/foxy
Fallback/ComposerFallback.php
ComposerFallback.getLockValue
private function getLockValue($key, $default = null) { return isset($this->lock[$key]) ? $this->lock[$key] : $default; }
php
private function getLockValue($key, $default = null) { return isset($this->lock[$key]) ? $this->lock[$key] : $default; }
[ "private", "function", "getLockValue", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "return", "isset", "(", "$", "this", "->", "lock", "[", "$", "key", "]", ")", "?", "$", "this", "->", "lock", "[", "$", "key", "]", ":", "$", "default", ";", "}" ]
Get the lock value. @param string $key The key @param null|mixed $default The default value @return null|mixed
[ "Get", "the", "lock", "value", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/ComposerFallback.php#L192-L195
fxpio/foxy
Fallback/ComposerFallback.php
ComposerFallback.getInstaller
private function getInstaller() { return null !== $this->installer ? $this->installer : Installer::create($this->io, $this->composer); }
php
private function getInstaller() { return null !== $this->installer ? $this->installer : Installer::create($this->io, $this->composer); }
[ "private", "function", "getInstaller", "(", ")", "{", "return", "null", "!==", "$", "this", "->", "installer", "?", "$", "this", "->", "installer", ":", "Installer", "::", "create", "(", "$", "this", "->", "io", ",", "$", "this", "->", "composer", ")", ";", "}" ]
Get the installer. @return Installer
[ "Get", "the", "installer", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/ComposerFallback.php#L202-L205
fxpio/foxy
Json/JsonFormatter.php
JsonFormatter.getArrayKeys
public static function getArrayKeys($content) { preg_match_all(self::ARRAY_KEYS_REGEX, trim($content), $matches); return !empty($matches) ? $matches[1] : array(); }
php
public static function getArrayKeys($content) { preg_match_all(self::ARRAY_KEYS_REGEX, trim($content), $matches); return !empty($matches) ? $matches[1] : array(); }
[ "public", "static", "function", "getArrayKeys", "(", "$", "content", ")", "{", "preg_match_all", "(", "self", "::", "ARRAY_KEYS_REGEX", ",", "trim", "(", "$", "content", ")", ",", "$", "matches", ")", ";", "return", "!", "empty", "(", "$", "matches", ")", "?", "$", "matches", "[", "1", "]", ":", "array", "(", ")", ";", "}" ]
Get the list of keys to be retained with an array representation if they are empty. @param string $content The content @return string[]
[ "Get", "the", "list", "of", "keys", "to", "be", "retained", "with", "an", "array", "representation", "if", "they", "are", "empty", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Json/JsonFormatter.php#L34-L39
fxpio/foxy
Json/JsonFormatter.php
JsonFormatter.getIndent
public static function getIndent($content) { $indent = self::DEFAULT_INDENT; preg_match(self::INDENT_REGEX, trim($content), $matches); if (!empty($matches)) { $indent = \strlen($matches[1]); } return $indent; }
php
public static function getIndent($content) { $indent = self::DEFAULT_INDENT; preg_match(self::INDENT_REGEX, trim($content), $matches); if (!empty($matches)) { $indent = \strlen($matches[1]); } return $indent; }
[ "public", "static", "function", "getIndent", "(", "$", "content", ")", "{", "$", "indent", "=", "self", "::", "DEFAULT_INDENT", ";", "preg_match", "(", "self", "::", "INDENT_REGEX", ",", "trim", "(", "$", "content", ")", ",", "$", "matches", ")", ";", "if", "(", "!", "empty", "(", "$", "matches", ")", ")", "{", "$", "indent", "=", "\\", "strlen", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "return", "$", "indent", ";", "}" ]
Get the indent of file. @param string $content The content @return int
[ "Get", "the", "indent", "of", "file", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Json/JsonFormatter.php#L48-L58
fxpio/foxy
Json/JsonFormatter.php
JsonFormatter.format
public static function format($json, array $arrayKeys = array(), $indent = self::DEFAULT_INDENT, $formatJson = true) { if ($formatJson) { $json = ComposerJsonFormatter::format($json, true, true); } if (4 !== $indent) { $json = str_replace(' ', sprintf('%'.$indent.'s', ''), $json); } return self::replaceArrayByMap($json, $arrayKeys); }
php
public static function format($json, array $arrayKeys = array(), $indent = self::DEFAULT_INDENT, $formatJson = true) { if ($formatJson) { $json = ComposerJsonFormatter::format($json, true, true); } if (4 !== $indent) { $json = str_replace(' ', sprintf('%'.$indent.'s', ''), $json); } return self::replaceArrayByMap($json, $arrayKeys); }
[ "public", "static", "function", "format", "(", "$", "json", ",", "array", "$", "arrayKeys", "=", "array", "(", ")", ",", "$", "indent", "=", "self", "::", "DEFAULT_INDENT", ",", "$", "formatJson", "=", "true", ")", "{", "if", "(", "$", "formatJson", ")", "{", "$", "json", "=", "ComposerJsonFormatter", "::", "format", "(", "$", "json", ",", "true", ",", "true", ")", ";", "}", "if", "(", "4", "!==", "$", "indent", ")", "{", "$", "json", "=", "str_replace", "(", "' '", ",", "sprintf", "(", "'%'", ".", "$", "indent", ".", "'s'", ",", "''", ")", ",", "$", "json", ")", ";", "}", "return", "self", "::", "replaceArrayByMap", "(", "$", "json", ",", "$", "arrayKeys", ")", ";", "}" ]
Format the data in JSON. @param string $json The original JSON @param string[] $arrayKeys The list of keys to be retained with an array representation if they are empty @param int $indent The space count for indent @param bool $formatJson Check if the json must be formatted @return string
[ "Format", "the", "data", "in", "JSON", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Json/JsonFormatter.php#L70-L81
fxpio/foxy
Json/JsonFormatter.php
JsonFormatter.replaceArrayByMap
private static function replaceArrayByMap($json, array $arrayKeys) { preg_match_all(self::ARRAY_KEYS_REGEX, $json, $matches, PREG_SET_ORDER); foreach ($matches as $match) { if (!\in_array($match[1], $arrayKeys, true)) { $replace = str_replace('[]', '{}', $match[0]); $json = str_replace($match[0], $replace, $json); } } return $json; }
php
private static function replaceArrayByMap($json, array $arrayKeys) { preg_match_all(self::ARRAY_KEYS_REGEX, $json, $matches, PREG_SET_ORDER); foreach ($matches as $match) { if (!\in_array($match[1], $arrayKeys, true)) { $replace = str_replace('[]', '{}', $match[0]); $json = str_replace($match[0], $replace, $json); } } return $json; }
[ "private", "static", "function", "replaceArrayByMap", "(", "$", "json", ",", "array", "$", "arrayKeys", ")", "{", "preg_match_all", "(", "self", "::", "ARRAY_KEYS_REGEX", ",", "$", "json", ",", "$", "matches", ",", "PREG_SET_ORDER", ")", ";", "foreach", "(", "$", "matches", "as", "$", "match", ")", "{", "if", "(", "!", "\\", "in_array", "(", "$", "match", "[", "1", "]", ",", "$", "arrayKeys", ",", "true", ")", ")", "{", "$", "replace", "=", "str_replace", "(", "'[]'", ",", "'{}'", ",", "$", "match", "[", "0", "]", ")", ";", "$", "json", "=", "str_replace", "(", "$", "match", "[", "0", "]", ",", "$", "replace", ",", "$", "json", ")", ";", "}", "}", "return", "$", "json", ";", "}" ]
Replace the empty array by empty map. @param string $json The original JSON @param string[] $arrayKeys The list of keys to be retained with an array representation if they are empty @return string
[ "Replace", "the", "empty", "array", "by", "empty", "map", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Json/JsonFormatter.php#L91-L103
fxpio/foxy
Config/ConfigBuilder.php
ConfigBuilder.build
public static function build(Composer $composer, array $defaults = array(), $io = null) { $config = self::getConfigBase($composer, $io); return new Config($config, $defaults); }
php
public static function build(Composer $composer, array $defaults = array(), $io = null) { $config = self::getConfigBase($composer, $io); return new Config($config, $defaults); }
[ "public", "static", "function", "build", "(", "Composer", "$", "composer", ",", "array", "$", "defaults", "=", "array", "(", ")", ",", "$", "io", "=", "null", ")", "{", "$", "config", "=", "self", "::", "getConfigBase", "(", "$", "composer", ",", "$", "io", ")", ";", "return", "new", "Config", "(", "$", "config", ",", "$", "defaults", ")", ";", "}" ]
Build the config of plugin. @param Composer $composer The composer @param array $defaults The default values @param null|IOInterface $io The composer input/output @return Config
[ "Build", "the", "config", "of", "plugin", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Config/ConfigBuilder.php#L34-L39
fxpio/foxy
Config/ConfigBuilder.php
ConfigBuilder.getConfigBase
private static function getConfigBase(Composer $composer, $io = null) { $globalPackageConfig = self::getGlobalConfig($composer, 'composer', $io); $globalConfig = self::getGlobalConfig($composer, 'config', $io); $packageConfig = $composer->getPackage()->getConfig(); $packageConfig = isset($packageConfig['foxy']) && \is_array($packageConfig['foxy']) ? $packageConfig['foxy'] : array(); return array_merge($globalPackageConfig, $globalConfig, $packageConfig); }
php
private static function getConfigBase(Composer $composer, $io = null) { $globalPackageConfig = self::getGlobalConfig($composer, 'composer', $io); $globalConfig = self::getGlobalConfig($composer, 'config', $io); $packageConfig = $composer->getPackage()->getConfig(); $packageConfig = isset($packageConfig['foxy']) && \is_array($packageConfig['foxy']) ? $packageConfig['foxy'] : array(); return array_merge($globalPackageConfig, $globalConfig, $packageConfig); }
[ "private", "static", "function", "getConfigBase", "(", "Composer", "$", "composer", ",", "$", "io", "=", "null", ")", "{", "$", "globalPackageConfig", "=", "self", "::", "getGlobalConfig", "(", "$", "composer", ",", "'composer'", ",", "$", "io", ")", ";", "$", "globalConfig", "=", "self", "::", "getGlobalConfig", "(", "$", "composer", ",", "'config'", ",", "$", "io", ")", ";", "$", "packageConfig", "=", "$", "composer", "->", "getPackage", "(", ")", "->", "getConfig", "(", ")", ";", "$", "packageConfig", "=", "isset", "(", "$", "packageConfig", "[", "'foxy'", "]", ")", "&&", "\\", "is_array", "(", "$", "packageConfig", "[", "'foxy'", "]", ")", "?", "$", "packageConfig", "[", "'foxy'", "]", ":", "array", "(", ")", ";", "return", "array_merge", "(", "$", "globalPackageConfig", ",", "$", "globalConfig", ",", "$", "packageConfig", ")", ";", "}" ]
Get the base of data. @param Composer $composer The composer @param null|IOInterface $io The composer input/output @return array
[ "Get", "the", "base", "of", "data", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Config/ConfigBuilder.php#L49-L59
fxpio/foxy
Util/ComposerUtil.php
ComposerUtil.validateVersion
public static function validateVersion($requiredVersion, $composerVersion) { if (false === strpos($composerVersion, '@') && !version_compare($composerVersion, $requiredVersion, '>=')) { $msg = 'Foxy requires the Composer\'s minimum version "%s", current version is "%s"'; throw new RuntimeException(sprintf($msg, $requiredVersion, $composerVersion)); } }
php
public static function validateVersion($requiredVersion, $composerVersion) { if (false === strpos($composerVersion, '@') && !version_compare($composerVersion, $requiredVersion, '>=')) { $msg = 'Foxy requires the Composer\'s minimum version "%s", current version is "%s"'; throw new RuntimeException(sprintf($msg, $requiredVersion, $composerVersion)); } }
[ "public", "static", "function", "validateVersion", "(", "$", "requiredVersion", ",", "$", "composerVersion", ")", "{", "if", "(", "false", "===", "strpos", "(", "$", "composerVersion", ",", "'@'", ")", "&&", "!", "version_compare", "(", "$", "composerVersion", ",", "$", "requiredVersion", ",", "'>='", ")", ")", "{", "$", "msg", "=", "'Foxy requires the Composer\\'s minimum version \"%s\", current version is \"%s\"'", ";", "throw", "new", "RuntimeException", "(", "sprintf", "(", "$", "msg", ",", "$", "requiredVersion", ",", "$", "composerVersion", ")", ")", ";", "}", "}" ]
Validate the composer version. @param string $requiredVersion The composer required version @param string $composerVersion The composer version
[ "Validate", "the", "composer", "version", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/ComposerUtil.php#L29-L36
fxpio/foxy
Asset/NpmManager.php
NpmManager.actionWhenComposerDependenciesAreAlreadyInstalled
protected function actionWhenComposerDependenciesAreAlreadyInstalled($names) { foreach ($names as $name) { $this->fs->remove(self::NODE_MODULES_PATH.'/'.$name); } }
php
protected function actionWhenComposerDependenciesAreAlreadyInstalled($names) { foreach ($names as $name) { $this->fs->remove(self::NODE_MODULES_PATH.'/'.$name); } }
[ "protected", "function", "actionWhenComposerDependenciesAreAlreadyInstalled", "(", "$", "names", ")", "{", "foreach", "(", "$", "names", "as", "$", "name", ")", "{", "$", "this", "->", "fs", "->", "remove", "(", "self", "::", "NODE_MODULES_PATH", ".", "'/'", ".", "$", "name", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/NpmManager.php#L64-L69
fxpio/foxy
Util/PackageUtil.php
PackageUtil.loadLockPackages
public static function loadLockPackages(array $lockData) { $loader = new ArrayLoader(); $lockData = static::loadLockPackage($loader, $lockData); $lockData = static::loadLockPackage($loader, $lockData, true); $lockData = static::convertLockAlias($lockData); return $lockData; }
php
public static function loadLockPackages(array $lockData) { $loader = new ArrayLoader(); $lockData = static::loadLockPackage($loader, $lockData); $lockData = static::loadLockPackage($loader, $lockData, true); $lockData = static::convertLockAlias($lockData); return $lockData; }
[ "public", "static", "function", "loadLockPackages", "(", "array", "$", "lockData", ")", "{", "$", "loader", "=", "new", "ArrayLoader", "(", ")", ";", "$", "lockData", "=", "static", "::", "loadLockPackage", "(", "$", "loader", ",", "$", "lockData", ")", ";", "$", "lockData", "=", "static", "::", "loadLockPackage", "(", "$", "loader", ",", "$", "lockData", ",", "true", ")", ";", "$", "lockData", "=", "static", "::", "convertLockAlias", "(", "$", "lockData", ")", ";", "return", "$", "lockData", ";", "}" ]
Load all packages in the lock data of locker. @param array $lockData The lock data of locker @return array The lock data
[ "Load", "all", "packages", "in", "the", "lock", "data", "of", "locker", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/PackageUtil.php#L31-L39
fxpio/foxy
Util/PackageUtil.php
PackageUtil.loadLockPackage
public static function loadLockPackage(ArrayLoader $loader, array $lockData, $dev = false) { $key = $dev ? 'packages-dev' : 'packages'; if (isset($lockData[$key])) { foreach ($lockData[$key] as $i => $package) { $package = $loader->load($package); $lockData[$key][$i] = $package instanceof AliasPackage ? $package->getAliasOf() : $package; } } return $lockData; }
php
public static function loadLockPackage(ArrayLoader $loader, array $lockData, $dev = false) { $key = $dev ? 'packages-dev' : 'packages'; if (isset($lockData[$key])) { foreach ($lockData[$key] as $i => $package) { $package = $loader->load($package); $lockData[$key][$i] = $package instanceof AliasPackage ? $package->getAliasOf() : $package; } } return $lockData; }
[ "public", "static", "function", "loadLockPackage", "(", "ArrayLoader", "$", "loader", ",", "array", "$", "lockData", ",", "$", "dev", "=", "false", ")", "{", "$", "key", "=", "$", "dev", "?", "'packages-dev'", ":", "'packages'", ";", "if", "(", "isset", "(", "$", "lockData", "[", "$", "key", "]", ")", ")", "{", "foreach", "(", "$", "lockData", "[", "$", "key", "]", "as", "$", "i", "=>", "$", "package", ")", "{", "$", "package", "=", "$", "loader", "->", "load", "(", "$", "package", ")", ";", "$", "lockData", "[", "$", "key", "]", "[", "$", "i", "]", "=", "$", "package", "instanceof", "AliasPackage", "?", "$", "package", "->", "getAliasOf", "(", ")", ":", "$", "package", ";", "}", "}", "return", "$", "lockData", ";", "}" ]
Load the packages in the packages section of the locker load data. @param ArrayLoader $loader The package loader @param array $lockData The lock data of locker @param bool $dev Check if the dev packages must be loaded @return array The lock data
[ "Load", "the", "packages", "in", "the", "packages", "section", "of", "the", "locker", "load", "data", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/PackageUtil.php#L50-L62
fxpio/foxy
Util/PackageUtil.php
PackageUtil.convertLockAlias
public static function convertLockAlias(array $lockData) { if (isset($lockData['aliases'])) { $aliases = array(); foreach ($lockData['aliases'] as $i => $config) { $aliases[$config['package']][$config['version']] = array( 'alias' => $config['alias'], 'alias_normalized' => $config['alias_normalized'], ); } $lockData['aliases'] = $aliases; } return $lockData; }
php
public static function convertLockAlias(array $lockData) { if (isset($lockData['aliases'])) { $aliases = array(); foreach ($lockData['aliases'] as $i => $config) { $aliases[$config['package']][$config['version']] = array( 'alias' => $config['alias'], 'alias_normalized' => $config['alias_normalized'], ); } $lockData['aliases'] = $aliases; } return $lockData; }
[ "public", "static", "function", "convertLockAlias", "(", "array", "$", "lockData", ")", "{", "if", "(", "isset", "(", "$", "lockData", "[", "'aliases'", "]", ")", ")", "{", "$", "aliases", "=", "array", "(", ")", ";", "foreach", "(", "$", "lockData", "[", "'aliases'", "]", "as", "$", "i", "=>", "$", "config", ")", "{", "$", "aliases", "[", "$", "config", "[", "'package'", "]", "]", "[", "$", "config", "[", "'version'", "]", "]", "=", "array", "(", "'alias'", "=>", "$", "config", "[", "'alias'", "]", ",", "'alias_normalized'", "=>", "$", "config", "[", "'alias_normalized'", "]", ",", ")", ";", "}", "$", "lockData", "[", "'aliases'", "]", "=", "$", "aliases", ";", "}", "return", "$", "lockData", ";", "}" ]
Convert the package aliases of the locker load data. @param array $lockData The lock data of locker @return array The lock data
[ "Convert", "the", "package", "aliases", "of", "the", "locker", "load", "data", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/PackageUtil.php#L71-L87
fxpio/foxy
Fallback/AssetFallback.php
AssetFallback.save
public function save() { if (file_exists($this->path) && is_file($this->path)) { $this->originalContent = file_get_contents($this->path); } return $this; }
php
public function save() { if (file_exists($this->path) && is_file($this->path)) { $this->originalContent = file_get_contents($this->path); } return $this; }
[ "public", "function", "save", "(", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "path", ")", "&&", "is_file", "(", "$", "this", "->", "path", ")", ")", "{", "$", "this", "->", "originalContent", "=", "file_get_contents", "(", "$", "this", "->", "path", ")", ";", "}", "return", "$", "this", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/AssetFallback.php#L61-L68
fxpio/foxy
Fallback/AssetFallback.php
AssetFallback.restore
public function restore() { if (!$this->config->get('fallback-asset')) { return; } $this->io->write('<info>Fallback to previous state for the Asset package</info>'); $this->fs->remove($this->path); if (null !== $this->originalContent) { file_put_contents($this->path, $this->originalContent); } }
php
public function restore() { if (!$this->config->get('fallback-asset')) { return; } $this->io->write('<info>Fallback to previous state for the Asset package</info>'); $this->fs->remove($this->path); if (null !== $this->originalContent) { file_put_contents($this->path, $this->originalContent); } }
[ "public", "function", "restore", "(", ")", "{", "if", "(", "!", "$", "this", "->", "config", "->", "get", "(", "'fallback-asset'", ")", ")", "{", "return", ";", "}", "$", "this", "->", "io", "->", "write", "(", "'<info>Fallback to previous state for the Asset package</info>'", ")", ";", "$", "this", "->", "fs", "->", "remove", "(", "$", "this", "->", "path", ")", ";", "if", "(", "null", "!==", "$", "this", "->", "originalContent", ")", "{", "file_put_contents", "(", "$", "this", "->", "path", ",", "$", "this", "->", "originalContent", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Fallback/AssetFallback.php#L73-L85
fxpio/foxy
Json/JsonFile.php
JsonFile.write
public function write(array $hash, $options = 448) { self::$encodeArrayKeys = $this->getArrayKeys(); self::$encodeIndent = $this->getIndent(); parent::write($hash, $options); self::$encodeArrayKeys = array(); self::$encodeIndent = JsonFormatter::DEFAULT_INDENT; }
php
public function write(array $hash, $options = 448) { self::$encodeArrayKeys = $this->getArrayKeys(); self::$encodeIndent = $this->getIndent(); parent::write($hash, $options); self::$encodeArrayKeys = array(); self::$encodeIndent = JsonFormatter::DEFAULT_INDENT; }
[ "public", "function", "write", "(", "array", "$", "hash", ",", "$", "options", "=", "448", ")", "{", "self", "::", "$", "encodeArrayKeys", "=", "$", "this", "->", "getArrayKeys", "(", ")", ";", "self", "::", "$", "encodeIndent", "=", "$", "this", "->", "getIndent", "(", ")", ";", "parent", "::", "write", "(", "$", "hash", ",", "$", "options", ")", ";", "self", "::", "$", "encodeArrayKeys", "=", "array", "(", ")", ";", "self", "::", "$", "encodeIndent", "=", "JsonFormatter", "::", "DEFAULT_INDENT", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Json/JsonFile.php#L86-L93
fxpio/foxy
Json/JsonFile.php
JsonFile.encode
public static function encode($data, $options = 448) { $result = parent::encode($data, $options); return JsonFormatter::format($result, self::$encodeArrayKeys, self::$encodeIndent, false); }
php
public static function encode($data, $options = 448) { $result = parent::encode($data, $options); return JsonFormatter::format($result, self::$encodeArrayKeys, self::$encodeIndent, false); }
[ "public", "static", "function", "encode", "(", "$", "data", ",", "$", "options", "=", "448", ")", "{", "$", "result", "=", "parent", "::", "encode", "(", "$", "data", ",", "$", "options", ")", ";", "return", "JsonFormatter", "::", "format", "(", "$", "result", ",", "self", "::", "$", "encodeArrayKeys", ",", "self", "::", "$", "encodeIndent", ",", "false", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Json/JsonFile.php#L98-L103
fxpio/foxy
Json/JsonFile.php
JsonFile.parseOriginalContent
private function parseOriginalContent() { $content = $this->exists() ? file_get_contents($this->getPath()) : ''; $this->arrayKeys = JsonFormatter::getArrayKeys($content); $this->indent = JsonFormatter::getIndent($content); }
php
private function parseOriginalContent() { $content = $this->exists() ? file_get_contents($this->getPath()) : ''; $this->arrayKeys = JsonFormatter::getArrayKeys($content); $this->indent = JsonFormatter::getIndent($content); }
[ "private", "function", "parseOriginalContent", "(", ")", "{", "$", "content", "=", "$", "this", "->", "exists", "(", ")", "?", "file_get_contents", "(", "$", "this", "->", "getPath", "(", ")", ")", ":", "''", ";", "$", "this", "->", "arrayKeys", "=", "JsonFormatter", "::", "getArrayKeys", "(", "$", "content", ")", ";", "$", "this", "->", "indent", "=", "JsonFormatter", "::", "getIndent", "(", "$", "content", ")", ";", "}" ]
Parse the original content.
[ "Parse", "the", "original", "content", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Json/JsonFile.php#L108-L113
fxpio/foxy
Util/ConsoleUtil.php
ConsoleUtil.getInput
public static function getInput(IOInterface $io) { $ref = new \ReflectionClass($io); if ($ref->hasProperty('input')) { $prop = $ref->getProperty('input'); $prop->setAccessible(true); $input = $prop->getValue($io); if ($input instanceof InputInterface) { return $input; } } return new ArgvInput(); }
php
public static function getInput(IOInterface $io) { $ref = new \ReflectionClass($io); if ($ref->hasProperty('input')) { $prop = $ref->getProperty('input'); $prop->setAccessible(true); $input = $prop->getValue($io); if ($input instanceof InputInterface) { return $input; } } return new ArgvInput(); }
[ "public", "static", "function", "getInput", "(", "IOInterface", "$", "io", ")", "{", "$", "ref", "=", "new", "\\", "ReflectionClass", "(", "$", "io", ")", ";", "if", "(", "$", "ref", "->", "hasProperty", "(", "'input'", ")", ")", "{", "$", "prop", "=", "$", "ref", "->", "getProperty", "(", "'input'", ")", ";", "$", "prop", "->", "setAccessible", "(", "true", ")", ";", "$", "input", "=", "$", "prop", "->", "getValue", "(", "$", "io", ")", ";", "if", "(", "$", "input", "instanceof", "InputInterface", ")", "{", "return", "$", "input", ";", "}", "}", "return", "new", "ArgvInput", "(", ")", ";", "}" ]
Get the console input. @param IOInterface $io The IO @return InputInterface
[ "Get", "the", "console", "input", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/ConsoleUtil.php#L33-L48
fxpio/foxy
Config/Config.php
Config.getArray
public function getArray($key, array $default = array()) { $value = $this->get($key, null); return null !== $value ? (array) $value : (array) $default; }
php
public function getArray($key, array $default = array()) { $value = $this->get($key, null); return null !== $value ? (array) $value : (array) $default; }
[ "public", "function", "getArray", "(", "$", "key", ",", "array", "$", "default", "=", "array", "(", ")", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "key", ",", "null", ")", ";", "return", "null", "!==", "$", "value", "?", "(", "array", ")", "$", "value", ":", "(", "array", ")", "$", "default", ";", "}" ]
Get the array config value. @param string $key The config key @param array $default The default value @return array
[ "Get", "the", "array", "config", "value", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Config/Config.php#L58-L63
fxpio/foxy
Config/Config.php
Config.get
public function get($key, $default = null) { if (\array_key_exists($key, $this->cacheEnv)) { return $this->cacheEnv[$key]; } $envKey = $this->convertEnvKey($key); $envValue = getenv($envKey); if (false !== $envValue) { return $this->cacheEnv[$key] = $this->convertEnvValue($envValue, $envKey); } $defaultValue = $this->getDefaultValue($key, $default); return \array_key_exists($key, $this->config) ? $this->getByManager($key, $this->config[$key], $defaultValue) : $defaultValue; }
php
public function get($key, $default = null) { if (\array_key_exists($key, $this->cacheEnv)) { return $this->cacheEnv[$key]; } $envKey = $this->convertEnvKey($key); $envValue = getenv($envKey); if (false !== $envValue) { return $this->cacheEnv[$key] = $this->convertEnvValue($envValue, $envKey); } $defaultValue = $this->getDefaultValue($key, $default); return \array_key_exists($key, $this->config) ? $this->getByManager($key, $this->config[$key], $defaultValue) : $defaultValue; }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "if", "(", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "cacheEnv", ")", ")", "{", "return", "$", "this", "->", "cacheEnv", "[", "$", "key", "]", ";", "}", "$", "envKey", "=", "$", "this", "->", "convertEnvKey", "(", "$", "key", ")", ";", "$", "envValue", "=", "getenv", "(", "$", "envKey", ")", ";", "if", "(", "false", "!==", "$", "envValue", ")", "{", "return", "$", "this", "->", "cacheEnv", "[", "$", "key", "]", "=", "$", "this", "->", "convertEnvValue", "(", "$", "envValue", ",", "$", "envKey", ")", ";", "}", "$", "defaultValue", "=", "$", "this", "->", "getDefaultValue", "(", "$", "key", ",", "$", "default", ")", ";", "return", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "config", ")", "?", "$", "this", "->", "getByManager", "(", "$", "key", ",", "$", "this", "->", "config", "[", "$", "key", "]", ",", "$", "defaultValue", ")", ":", "$", "defaultValue", ";", "}" ]
Get the config value. @param string $key The config key @param null|mixed $default The default value @return null|mixed
[ "Get", "the", "config", "value", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Config/Config.php#L73-L91
fxpio/foxy
Config/Config.php
Config.convertJson
private function convertJson($value, $environmentVariable) { $value = json_decode($value, true); if (json_last_error()) { throw new RuntimeException(sprintf('The "%s" environment variable isn\'t a valid JSON', $environmentVariable)); } return $value; }
php
private function convertJson($value, $environmentVariable) { $value = json_decode($value, true); if (json_last_error()) { throw new RuntimeException(sprintf('The "%s" environment variable isn\'t a valid JSON', $environmentVariable)); } return $value; }
[ "private", "function", "convertJson", "(", "$", "value", ",", "$", "environmentVariable", ")", "{", "$", "value", "=", "json_decode", "(", "$", "value", ",", "true", ")", ";", "if", "(", "json_last_error", "(", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'The \"%s\" environment variable isn\\'t a valid JSON'", ",", "$", "environmentVariable", ")", ")", ";", "}", "return", "$", "value", ";", "}" ]
Convert the value of environment variable into a json array. @param string $value The value of environment variable @param string $environmentVariable The environment variable name @return array
[ "Convert", "the", "value", "of", "environment", "variable", "into", "a", "json", "array", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Config/Config.php#L198-L207
fxpio/foxy
Config/Config.php
Config.getDefaultValue
private function getDefaultValue($key, $default = null) { $value = null === $default && \array_key_exists($key, $this->defaults) ? $this->defaults[$key] : $default; return $this->getByManager($key, $value, $default); }
php
private function getDefaultValue($key, $default = null) { $value = null === $default && \array_key_exists($key, $this->defaults) ? $this->defaults[$key] : $default; return $this->getByManager($key, $value, $default); }
[ "private", "function", "getDefaultValue", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "value", "=", "null", "===", "$", "default", "&&", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "defaults", ")", "?", "$", "this", "->", "defaults", "[", "$", "key", "]", ":", "$", "default", ";", "return", "$", "this", "->", "getByManager", "(", "$", "key", ",", "$", "value", ",", "$", "default", ")", ";", "}" ]
Get the configured default value or custom default value. @param string $key The config key @param null|mixed $default The default value @return null|mixed
[ "Get", "the", "configured", "default", "value", "or", "custom", "default", "value", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Config/Config.php#L217-L224
fxpio/foxy
Config/Config.php
Config.getByManager
private function getByManager($key, $value, $default = null) { if (0 === strpos($key, 'manager-') && \is_array($value)) { $manager = $manager = $this->get('manager', ''); $value = \array_key_exists($manager, $value) ? $value[$manager] : $default; } return $value; }
php
private function getByManager($key, $value, $default = null) { if (0 === strpos($key, 'manager-') && \is_array($value)) { $manager = $manager = $this->get('manager', ''); $value = \array_key_exists($manager, $value) ? $value[$manager] : $default; } return $value; }
[ "private", "function", "getByManager", "(", "$", "key", ",", "$", "value", ",", "$", "default", "=", "null", ")", "{", "if", "(", "0", "===", "strpos", "(", "$", "key", ",", "'manager-'", ")", "&&", "\\", "is_array", "(", "$", "value", ")", ")", "{", "$", "manager", "=", "$", "manager", "=", "$", "this", "->", "get", "(", "'manager'", ",", "''", ")", ";", "$", "value", "=", "\\", "array_key_exists", "(", "$", "manager", ",", "$", "value", ")", "?", "$", "value", "[", "$", "manager", "]", ":", "$", "default", ";", "}", "return", "$", "value", ";", "}" ]
Get the value defined by the manager name in the key. @param string $key The config key @param array|mixed $value The value @param null|mixed $default The default value @return null|mixed
[ "Get", "the", "value", "defined", "by", "the", "manager", "name", "in", "the", "key", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Config/Config.php#L235-L246
fxpio/foxy
Asset/AbstractAssetManager.php
AbstractAssetManager.validate
public function validate() { $this->executor->execute($this->getVersionCommand(), $version); $version = trim($version); $constraintVersion = $this->config->get('manager-version'); if ('' === $version) { throw new RuntimeException(sprintf('The binary of "%s" must be installed', $this->getName())); } if ($constraintVersion) { $parser = new VersionParser(); $constraint = $parser->parseConstraints($constraintVersion); if (!$constraint->matches(new Constraint('=', $version))) { throw new RuntimeException(sprintf('The installed %s version "%s" doesn\'t match with the constraint version "%s"', $this->getName(), $version, $constraintVersion)); } } }
php
public function validate() { $this->executor->execute($this->getVersionCommand(), $version); $version = trim($version); $constraintVersion = $this->config->get('manager-version'); if ('' === $version) { throw new RuntimeException(sprintf('The binary of "%s" must be installed', $this->getName())); } if ($constraintVersion) { $parser = new VersionParser(); $constraint = $parser->parseConstraints($constraintVersion); if (!$constraint->matches(new Constraint('=', $version))) { throw new RuntimeException(sprintf('The installed %s version "%s" doesn\'t match with the constraint version "%s"', $this->getName(), $version, $constraintVersion)); } } }
[ "public", "function", "validate", "(", ")", "{", "$", "this", "->", "executor", "->", "execute", "(", "$", "this", "->", "getVersionCommand", "(", ")", ",", "$", "version", ")", ";", "$", "version", "=", "trim", "(", "$", "version", ")", ";", "$", "constraintVersion", "=", "$", "this", "->", "config", "->", "get", "(", "'manager-version'", ")", ";", "if", "(", "''", "===", "$", "version", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'The binary of \"%s\" must be installed'", ",", "$", "this", "->", "getName", "(", ")", ")", ")", ";", "}", "if", "(", "$", "constraintVersion", ")", "{", "$", "parser", "=", "new", "VersionParser", "(", ")", ";", "$", "constraint", "=", "$", "parser", "->", "parseConstraints", "(", "$", "constraintVersion", ")", ";", "if", "(", "!", "$", "constraint", "->", "matches", "(", "new", "Constraint", "(", "'='", ",", "$", "version", ")", ")", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'The installed %s version \"%s\" doesn\\'t match with the constraint version \"%s\"'", ",", "$", "this", "->", "getName", "(", ")", ",", "$", "version", ",", "$", "constraintVersion", ")", ")", ";", "}", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AbstractAssetManager.php#L151-L169
fxpio/foxy
Asset/AbstractAssetManager.php
AbstractAssetManager.addDependencies
public function addDependencies(RootPackageInterface $rootPackage, array $dependencies) { $assetPackage = new AssetPackage($rootPackage, new JsonFile($this->getPackageName(), null, $this->io)); $assetPackage->removeUnusedDependencies($dependencies); $alreadyInstalledDependencies = $assetPackage->addNewDependencies($dependencies); $this->actionWhenComposerDependenciesAreAlreadyInstalled($alreadyInstalledDependencies); $this->io->write('<info>Merging Composer dependencies in the asset package</info>'); return $assetPackage->write(); }
php
public function addDependencies(RootPackageInterface $rootPackage, array $dependencies) { $assetPackage = new AssetPackage($rootPackage, new JsonFile($this->getPackageName(), null, $this->io)); $assetPackage->removeUnusedDependencies($dependencies); $alreadyInstalledDependencies = $assetPackage->addNewDependencies($dependencies); $this->actionWhenComposerDependenciesAreAlreadyInstalled($alreadyInstalledDependencies); $this->io->write('<info>Merging Composer dependencies in the asset package</info>'); return $assetPackage->write(); }
[ "public", "function", "addDependencies", "(", "RootPackageInterface", "$", "rootPackage", ",", "array", "$", "dependencies", ")", "{", "$", "assetPackage", "=", "new", "AssetPackage", "(", "$", "rootPackage", ",", "new", "JsonFile", "(", "$", "this", "->", "getPackageName", "(", ")", ",", "null", ",", "$", "this", "->", "io", ")", ")", ";", "$", "assetPackage", "->", "removeUnusedDependencies", "(", "$", "dependencies", ")", ";", "$", "alreadyInstalledDependencies", "=", "$", "assetPackage", "->", "addNewDependencies", "(", "$", "dependencies", ")", ";", "$", "this", "->", "actionWhenComposerDependenciesAreAlreadyInstalled", "(", "$", "alreadyInstalledDependencies", ")", ";", "$", "this", "->", "io", "->", "write", "(", "'<info>Merging Composer dependencies in the asset package</info>'", ")", ";", "return", "$", "assetPackage", "->", "write", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AbstractAssetManager.php#L174-L184
fxpio/foxy
Asset/AbstractAssetManager.php
AbstractAssetManager.run
public function run() { if (true !== $this->config->get('run-asset-manager')) { return 0; } $updatable = $this->isUpdatable(); $info = sprintf('<info>%s %s dependencies</info>', $updatable ? 'Updating' : 'Installing', $this->getName()); $this->io->write($info); $timeout = ProcessExecutor::getTimeout(); ProcessExecutor::setTimeout($this->config->get('manager-timeout')); $cmd = $updatable ? $this->getUpdateCommand() : $this->getInstallCommand(); $res = (int) $this->executor->execute($cmd); ProcessExecutor::setTimeout($timeout); if ($res > 0 && null !== $this->fallback) { $this->fallback->restore(); } return $res; }
php
public function run() { if (true !== $this->config->get('run-asset-manager')) { return 0; } $updatable = $this->isUpdatable(); $info = sprintf('<info>%s %s dependencies</info>', $updatable ? 'Updating' : 'Installing', $this->getName()); $this->io->write($info); $timeout = ProcessExecutor::getTimeout(); ProcessExecutor::setTimeout($this->config->get('manager-timeout')); $cmd = $updatable ? $this->getUpdateCommand() : $this->getInstallCommand(); $res = (int) $this->executor->execute($cmd); ProcessExecutor::setTimeout($timeout); if ($res > 0 && null !== $this->fallback) { $this->fallback->restore(); } return $res; }
[ "public", "function", "run", "(", ")", "{", "if", "(", "true", "!==", "$", "this", "->", "config", "->", "get", "(", "'run-asset-manager'", ")", ")", "{", "return", "0", ";", "}", "$", "updatable", "=", "$", "this", "->", "isUpdatable", "(", ")", ";", "$", "info", "=", "sprintf", "(", "'<info>%s %s dependencies</info>'", ",", "$", "updatable", "?", "'Updating'", ":", "'Installing'", ",", "$", "this", "->", "getName", "(", ")", ")", ";", "$", "this", "->", "io", "->", "write", "(", "$", "info", ")", ";", "$", "timeout", "=", "ProcessExecutor", "::", "getTimeout", "(", ")", ";", "ProcessExecutor", "::", "setTimeout", "(", "$", "this", "->", "config", "->", "get", "(", "'manager-timeout'", ")", ")", ";", "$", "cmd", "=", "$", "updatable", "?", "$", "this", "->", "getUpdateCommand", "(", ")", ":", "$", "this", "->", "getInstallCommand", "(", ")", ";", "$", "res", "=", "(", "int", ")", "$", "this", "->", "executor", "->", "execute", "(", "$", "cmd", ")", ";", "ProcessExecutor", "::", "setTimeout", "(", "$", "timeout", ")", ";", "if", "(", "$", "res", ">", "0", "&&", "null", "!==", "$", "this", "->", "fallback", ")", "{", "$", "this", "->", "fallback", "->", "restore", "(", ")", ";", "}", "return", "$", "res", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AbstractAssetManager.php#L189-L210
fxpio/foxy
Asset/AbstractAssetManager.php
AbstractAssetManager.buildCommand
protected function buildCommand($defaultBin, $action, $command) { $bin = $this->config->get('manager-bin', $defaultBin); $bin = Platform::isWindows() ? str_replace('/', '\\', $bin) : $bin; $gOptions = trim($this->config->get('manager-options', '')); $options = trim($this->config->get('manager-'.$action.'-options', '')); return $bin.' '.$command .(empty($gOptions) ? '' : ' '.$gOptions) .(empty($options) ? '' : ' '.$options); }
php
protected function buildCommand($defaultBin, $action, $command) { $bin = $this->config->get('manager-bin', $defaultBin); $bin = Platform::isWindows() ? str_replace('/', '\\', $bin) : $bin; $gOptions = trim($this->config->get('manager-options', '')); $options = trim($this->config->get('manager-'.$action.'-options', '')); return $bin.' '.$command .(empty($gOptions) ? '' : ' '.$gOptions) .(empty($options) ? '' : ' '.$options); }
[ "protected", "function", "buildCommand", "(", "$", "defaultBin", ",", "$", "action", ",", "$", "command", ")", "{", "$", "bin", "=", "$", "this", "->", "config", "->", "get", "(", "'manager-bin'", ",", "$", "defaultBin", ")", ";", "$", "bin", "=", "Platform", "::", "isWindows", "(", ")", "?", "str_replace", "(", "'/'", ",", "'\\\\'", ",", "$", "bin", ")", ":", "$", "bin", ";", "$", "gOptions", "=", "trim", "(", "$", "this", "->", "config", "->", "get", "(", "'manager-options'", ",", "''", ")", ")", ";", "$", "options", "=", "trim", "(", "$", "this", "->", "config", "->", "get", "(", "'manager-'", ".", "$", "action", ".", "'-options'", ",", "''", ")", ")", ";", "return", "$", "bin", ".", "' '", ".", "$", "command", ".", "(", "empty", "(", "$", "gOptions", ")", "?", "''", ":", "' '", ".", "$", "gOptions", ")", ".", "(", "empty", "(", "$", "options", ")", "?", "''", ":", "' '", ".", "$", "options", ")", ";", "}" ]
Build the command with binary and command options. @param string $defaultBin The default binary of command if option isn't defined @param string $action The command action to retrieve the options in config @param string $command The command @return string
[ "Build", "the", "command", "with", "binary", "and", "command", "options", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Asset/AbstractAssetManager.php#L231-L241
fxpio/foxy
Util/AssetUtil.php
AssetUtil.getPath
public static function getPath(InstallationManager $installationManager, AssetManagerInterface $assetManager, PackageInterface $package, array $configPackages = array()) { $path = null; if (static::isAsset($package, $configPackages)) { $installPath = $installationManager->getInstallPath($package); $filename = $installPath.'/'.$assetManager->getPackageName(); $path = file_exists($filename) ? str_replace('\\', '/', realpath($filename)) : null; } return $path; }
php
public static function getPath(InstallationManager $installationManager, AssetManagerInterface $assetManager, PackageInterface $package, array $configPackages = array()) { $path = null; if (static::isAsset($package, $configPackages)) { $installPath = $installationManager->getInstallPath($package); $filename = $installPath.'/'.$assetManager->getPackageName(); $path = file_exists($filename) ? str_replace('\\', '/', realpath($filename)) : null; } return $path; }
[ "public", "static", "function", "getPath", "(", "InstallationManager", "$", "installationManager", ",", "AssetManagerInterface", "$", "assetManager", ",", "PackageInterface", "$", "package", ",", "array", "$", "configPackages", "=", "array", "(", ")", ")", "{", "$", "path", "=", "null", ";", "if", "(", "static", "::", "isAsset", "(", "$", "package", ",", "$", "configPackages", ")", ")", "{", "$", "installPath", "=", "$", "installationManager", "->", "getInstallPath", "(", "$", "package", ")", ";", "$", "filename", "=", "$", "installPath", ".", "'/'", ".", "$", "assetManager", "->", "getPackageName", "(", ")", ";", "$", "path", "=", "file_exists", "(", "$", "filename", ")", "?", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "realpath", "(", "$", "filename", ")", ")", ":", "null", ";", "}", "return", "$", "path", ";", "}" ]
Get the path of asset file. @param InstallationManager $installationManager The installation manager @param AssetManagerInterface $assetManager The asset manager @param PackageInterface $package The package @param array $configPackages The packages defined in config @return null|string
[ "Get", "the", "path", "of", "asset", "file", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/AssetUtil.php#L49-L60
fxpio/foxy
Util/AssetUtil.php
AssetUtil.isAsset
public static function isAsset(PackageInterface $package, array $configPackages = array()) { $projectConfig = self::getProjectActivation($package, $configPackages); $enabled = false !== $projectConfig; return $enabled && (static::hasExtraActivation($package) || static::hasPluginDependency($package->getRequires()) || static::hasPluginDependency($package->getDevRequires()) || true === $projectConfig); }
php
public static function isAsset(PackageInterface $package, array $configPackages = array()) { $projectConfig = self::getProjectActivation($package, $configPackages); $enabled = false !== $projectConfig; return $enabled && (static::hasExtraActivation($package) || static::hasPluginDependency($package->getRequires()) || static::hasPluginDependency($package->getDevRequires()) || true === $projectConfig); }
[ "public", "static", "function", "isAsset", "(", "PackageInterface", "$", "package", ",", "array", "$", "configPackages", "=", "array", "(", ")", ")", "{", "$", "projectConfig", "=", "self", "::", "getProjectActivation", "(", "$", "package", ",", "$", "configPackages", ")", ";", "$", "enabled", "=", "false", "!==", "$", "projectConfig", ";", "return", "$", "enabled", "&&", "(", "static", "::", "hasExtraActivation", "(", "$", "package", ")", "||", "static", "::", "hasPluginDependency", "(", "$", "package", "->", "getRequires", "(", ")", ")", "||", "static", "::", "hasPluginDependency", "(", "$", "package", "->", "getDevRequires", "(", ")", ")", "||", "true", "===", "$", "projectConfig", ")", ";", "}" ]
Check if the package is available for Foxy. @param PackageInterface $package The package @param array $configPackages The packages defined in config @return bool
[ "Check", "if", "the", "package", "is", "available", "for", "Foxy", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/AssetUtil.php#L70-L79
fxpio/foxy
Util/AssetUtil.php
AssetUtil.hasExtraActivation
public static function hasExtraActivation(PackageInterface $package) { $extra = $package->getExtra(); return isset($extra['foxy']) && true === $extra['foxy']; }
php
public static function hasExtraActivation(PackageInterface $package) { $extra = $package->getExtra(); return isset($extra['foxy']) && true === $extra['foxy']; }
[ "public", "static", "function", "hasExtraActivation", "(", "PackageInterface", "$", "package", ")", "{", "$", "extra", "=", "$", "package", "->", "getExtra", "(", ")", ";", "return", "isset", "(", "$", "extra", "[", "'foxy'", "]", ")", "&&", "true", "===", "$", "extra", "[", "'foxy'", "]", ";", "}" ]
Check if foxy is enabled in extra section of package. @param PackageInterface $package The package @return bool
[ "Check", "if", "foxy", "is", "enabled", "in", "extra", "section", "of", "package", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/AssetUtil.php#L88-L93
fxpio/foxy
Util/AssetUtil.php
AssetUtil.hasPluginDependency
public static function hasPluginDependency(array $requires) { $assets = false; foreach ($requires as $require) { if ('foxy/foxy' === $require->getTarget()) { $assets = true; break; } } return $assets; }
php
public static function hasPluginDependency(array $requires) { $assets = false; foreach ($requires as $require) { if ('foxy/foxy' === $require->getTarget()) { $assets = true; break; } } return $assets; }
[ "public", "static", "function", "hasPluginDependency", "(", "array", "$", "requires", ")", "{", "$", "assets", "=", "false", ";", "foreach", "(", "$", "requires", "as", "$", "require", ")", "{", "if", "(", "'foxy/foxy'", "===", "$", "require", "->", "getTarget", "(", ")", ")", "{", "$", "assets", "=", "true", ";", "break", ";", "}", "}", "return", "$", "assets", ";", "}" ]
Check if the package contains assets. @param Link[] $requires The require links @return bool
[ "Check", "if", "the", "package", "contains", "assets", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/AssetUtil.php#L102-L115
fxpio/foxy
Util/AssetUtil.php
AssetUtil.formatPackage
public static function formatPackage(PackageInterface $package, $packageName, array $packageValue) { $packageValue['name'] = $packageName; if (!isset($packageValue['version'])) { $extra = $package->getExtra(); $version = $package->getPrettyVersion(); if (0 === strpos($version, 'dev-') && isset($extra['branch-alias'][$version])) { $version = $extra['branch-alias'][$version]; } $packageValue['version'] = self::formatVersion(str_replace('-dev', '', $version)); } return $packageValue; }
php
public static function formatPackage(PackageInterface $package, $packageName, array $packageValue) { $packageValue['name'] = $packageName; if (!isset($packageValue['version'])) { $extra = $package->getExtra(); $version = $package->getPrettyVersion(); if (0 === strpos($version, 'dev-') && isset($extra['branch-alias'][$version])) { $version = $extra['branch-alias'][$version]; } $packageValue['version'] = self::formatVersion(str_replace('-dev', '', $version)); } return $packageValue; }
[ "public", "static", "function", "formatPackage", "(", "PackageInterface", "$", "package", ",", "$", "packageName", ",", "array", "$", "packageValue", ")", "{", "$", "packageValue", "[", "'name'", "]", "=", "$", "packageName", ";", "if", "(", "!", "isset", "(", "$", "packageValue", "[", "'version'", "]", ")", ")", "{", "$", "extra", "=", "$", "package", "->", "getExtra", "(", ")", ";", "$", "version", "=", "$", "package", "->", "getPrettyVersion", "(", ")", ";", "if", "(", "0", "===", "strpos", "(", "$", "version", ",", "'dev-'", ")", "&&", "isset", "(", "$", "extra", "[", "'branch-alias'", "]", "[", "$", "version", "]", ")", ")", "{", "$", "version", "=", "$", "extra", "[", "'branch-alias'", "]", "[", "$", "version", "]", ";", "}", "$", "packageValue", "[", "'version'", "]", "=", "self", "::", "formatVersion", "(", "str_replace", "(", "'-dev'", ",", "''", ",", "$", "version", ")", ")", ";", "}", "return", "$", "packageValue", ";", "}" ]
Format the asset package. @param PackageInterface $package The composer package @param string $packageName The package name @param array $packageValue The package value @return array
[ "Format", "the", "asset", "package", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/AssetUtil.php#L139-L155
fxpio/foxy
Util/AssetUtil.php
AssetUtil.formatVersion
private static function formatVersion($version) { $version = str_replace(array('x', 'X', '*'), '0', $version); $exp = explode('.', $version); if (($size = \count($exp)) < 3) { for ($i = $size; $i < 3; ++$i) { $exp[] = '0'; } } return $exp[0].'.'.$exp[1].'.'.$exp[2]; }
php
private static function formatVersion($version) { $version = str_replace(array('x', 'X', '*'), '0', $version); $exp = explode('.', $version); if (($size = \count($exp)) < 3) { for ($i = $size; $i < 3; ++$i) { $exp[] = '0'; } } return $exp[0].'.'.$exp[1].'.'.$exp[2]; }
[ "private", "static", "function", "formatVersion", "(", "$", "version", ")", "{", "$", "version", "=", "str_replace", "(", "array", "(", "'x'", ",", "'X'", ",", "'*'", ")", ",", "'0'", ",", "$", "version", ")", ";", "$", "exp", "=", "explode", "(", "'.'", ",", "$", "version", ")", ";", "if", "(", "(", "$", "size", "=", "\\", "count", "(", "$", "exp", ")", ")", "<", "3", ")", "{", "for", "(", "$", "i", "=", "$", "size", ";", "$", "i", "<", "3", ";", "++", "$", "i", ")", "{", "$", "exp", "[", "]", "=", "'0'", ";", "}", "}", "return", "$", "exp", "[", "0", "]", ".", "'.'", ".", "$", "exp", "[", "1", "]", ".", "'.'", ".", "$", "exp", "[", "2", "]", ";", "}" ]
Format the version for the asset package. @param string $version The branch alias version @return string
[ "Format", "the", "version", "for", "the", "asset", "package", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/AssetUtil.php#L164-L176
fxpio/foxy
Util/AssetUtil.php
AssetUtil.getProjectActivation
private static function getProjectActivation(PackageInterface $package, array $configPackages) { $name = $package->getName(); $value = null; foreach ($configPackages as $pattern => $activation) { if (\is_int($pattern) && \is_string($activation)) { $pattern = $activation; $activation = true; } if ((0 === strpos($pattern, '/') && preg_match($pattern, $name)) || fnmatch($pattern, $name)) { $value = $activation; break; } } return $value; }
php
private static function getProjectActivation(PackageInterface $package, array $configPackages) { $name = $package->getName(); $value = null; foreach ($configPackages as $pattern => $activation) { if (\is_int($pattern) && \is_string($activation)) { $pattern = $activation; $activation = true; } if ((0 === strpos($pattern, '/') && preg_match($pattern, $name)) || fnmatch($pattern, $name)) { $value = $activation; break; } } return $value; }
[ "private", "static", "function", "getProjectActivation", "(", "PackageInterface", "$", "package", ",", "array", "$", "configPackages", ")", "{", "$", "name", "=", "$", "package", "->", "getName", "(", ")", ";", "$", "value", "=", "null", ";", "foreach", "(", "$", "configPackages", "as", "$", "pattern", "=>", "$", "activation", ")", "{", "if", "(", "\\", "is_int", "(", "$", "pattern", ")", "&&", "\\", "is_string", "(", "$", "activation", ")", ")", "{", "$", "pattern", "=", "$", "activation", ";", "$", "activation", "=", "true", ";", "}", "if", "(", "(", "0", "===", "strpos", "(", "$", "pattern", ",", "'/'", ")", "&&", "preg_match", "(", "$", "pattern", ",", "$", "name", ")", ")", "||", "fnmatch", "(", "$", "pattern", ",", "$", "name", ")", ")", "{", "$", "value", "=", "$", "activation", ";", "break", ";", "}", "}", "return", "$", "value", ";", "}" ]
Get the activation of the package defined in the project config. @param PackageInterface $package The package @param array $configPackages The packages defined in config @return null|bool returns NULL, if the package isn't defined in the project config
[ "Get", "the", "activation", "of", "the", "package", "defined", "in", "the", "project", "config", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Util/AssetUtil.php#L186-L205
fxpio/foxy
Solver/Solver.php
Solver.solve
public function solve(Composer $composer, IOInterface $io) { if (!$this->config->get('enabled')) { return; } $dispatcher = $composer->getEventDispatcher(); $packages = $composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages(); $vendorDir = $composer->getConfig()->get('vendor-dir'); $assetDir = $this->config->get('composer-asset-dir', $vendorDir.'/foxy/composer-asset/'); $dispatcher->dispatch(FoxyEvents::PRE_SOLVE, new PreSolveEvent($assetDir, $packages)); $this->fs->remove($assetDir); $assets = $this->getAssets($composer, $assetDir, $packages); $this->assetManager->addDependencies($composer->getPackage(), $assets); $res = $this->assetManager->run(); $dispatcher->dispatch(FoxyEvents::POST_SOLVE, new PostSolveEvent($assetDir, $packages, $res)); if ($res > 0 && $this->composerFallback) { $this->composerFallback->restore(); throw new \RuntimeException('The asset manager ended with an error'); } }
php
public function solve(Composer $composer, IOInterface $io) { if (!$this->config->get('enabled')) { return; } $dispatcher = $composer->getEventDispatcher(); $packages = $composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages(); $vendorDir = $composer->getConfig()->get('vendor-dir'); $assetDir = $this->config->get('composer-asset-dir', $vendorDir.'/foxy/composer-asset/'); $dispatcher->dispatch(FoxyEvents::PRE_SOLVE, new PreSolveEvent($assetDir, $packages)); $this->fs->remove($assetDir); $assets = $this->getAssets($composer, $assetDir, $packages); $this->assetManager->addDependencies($composer->getPackage(), $assets); $res = $this->assetManager->run(); $dispatcher->dispatch(FoxyEvents::POST_SOLVE, new PostSolveEvent($assetDir, $packages, $res)); if ($res > 0 && $this->composerFallback) { $this->composerFallback->restore(); throw new \RuntimeException('The asset manager ended with an error'); } }
[ "public", "function", "solve", "(", "Composer", "$", "composer", ",", "IOInterface", "$", "io", ")", "{", "if", "(", "!", "$", "this", "->", "config", "->", "get", "(", "'enabled'", ")", ")", "{", "return", ";", "}", "$", "dispatcher", "=", "$", "composer", "->", "getEventDispatcher", "(", ")", ";", "$", "packages", "=", "$", "composer", "->", "getRepositoryManager", "(", ")", "->", "getLocalRepository", "(", ")", "->", "getCanonicalPackages", "(", ")", ";", "$", "vendorDir", "=", "$", "composer", "->", "getConfig", "(", ")", "->", "get", "(", "'vendor-dir'", ")", ";", "$", "assetDir", "=", "$", "this", "->", "config", "->", "get", "(", "'composer-asset-dir'", ",", "$", "vendorDir", ".", "'/foxy/composer-asset/'", ")", ";", "$", "dispatcher", "->", "dispatch", "(", "FoxyEvents", "::", "PRE_SOLVE", ",", "new", "PreSolveEvent", "(", "$", "assetDir", ",", "$", "packages", ")", ")", ";", "$", "this", "->", "fs", "->", "remove", "(", "$", "assetDir", ")", ";", "$", "assets", "=", "$", "this", "->", "getAssets", "(", "$", "composer", ",", "$", "assetDir", ",", "$", "packages", ")", ";", "$", "this", "->", "assetManager", "->", "addDependencies", "(", "$", "composer", "->", "getPackage", "(", ")", ",", "$", "assets", ")", ";", "$", "res", "=", "$", "this", "->", "assetManager", "->", "run", "(", ")", ";", "$", "dispatcher", "->", "dispatch", "(", "FoxyEvents", "::", "POST_SOLVE", ",", "new", "PostSolveEvent", "(", "$", "assetDir", ",", "$", "packages", ",", "$", "res", ")", ")", ";", "if", "(", "$", "res", ">", "0", "&&", "$", "this", "->", "composerFallback", ")", "{", "$", "this", "->", "composerFallback", "->", "restore", "(", ")", ";", "throw", "new", "\\", "RuntimeException", "(", "'The asset manager ended with an error'", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Solver/Solver.php#L88-L111
fxpio/foxy
Solver/Solver.php
Solver.getAssets
protected function getAssets(Composer $composer, $assetDir, array $packages) { $installationManager = $composer->getInstallationManager(); $configPackages = $this->config->getArray('enable-packages'); $assets = array(); foreach ($packages as $package) { $filename = AssetUtil::getPath($installationManager, $this->assetManager, $package, $configPackages); if (null !== $filename) { list($packageName, $packagePath) = $this->getMockPackagePath($package, $assetDir, $filename); $assets[$packageName] = $packagePath; } } $assetsEvent = new GetAssetsEvent($assetDir, $packages, $assets); $composer->getEventDispatcher()->dispatch(FoxyEvents::GET_ASSETS, $assetsEvent); return $assetsEvent->getAssets(); }
php
protected function getAssets(Composer $composer, $assetDir, array $packages) { $installationManager = $composer->getInstallationManager(); $configPackages = $this->config->getArray('enable-packages'); $assets = array(); foreach ($packages as $package) { $filename = AssetUtil::getPath($installationManager, $this->assetManager, $package, $configPackages); if (null !== $filename) { list($packageName, $packagePath) = $this->getMockPackagePath($package, $assetDir, $filename); $assets[$packageName] = $packagePath; } } $assetsEvent = new GetAssetsEvent($assetDir, $packages, $assets); $composer->getEventDispatcher()->dispatch(FoxyEvents::GET_ASSETS, $assetsEvent); return $assetsEvent->getAssets(); }
[ "protected", "function", "getAssets", "(", "Composer", "$", "composer", ",", "$", "assetDir", ",", "array", "$", "packages", ")", "{", "$", "installationManager", "=", "$", "composer", "->", "getInstallationManager", "(", ")", ";", "$", "configPackages", "=", "$", "this", "->", "config", "->", "getArray", "(", "'enable-packages'", ")", ";", "$", "assets", "=", "array", "(", ")", ";", "foreach", "(", "$", "packages", "as", "$", "package", ")", "{", "$", "filename", "=", "AssetUtil", "::", "getPath", "(", "$", "installationManager", ",", "$", "this", "->", "assetManager", ",", "$", "package", ",", "$", "configPackages", ")", ";", "if", "(", "null", "!==", "$", "filename", ")", "{", "list", "(", "$", "packageName", ",", "$", "packagePath", ")", "=", "$", "this", "->", "getMockPackagePath", "(", "$", "package", ",", "$", "assetDir", ",", "$", "filename", ")", ";", "$", "assets", "[", "$", "packageName", "]", "=", "$", "packagePath", ";", "}", "}", "$", "assetsEvent", "=", "new", "GetAssetsEvent", "(", "$", "assetDir", ",", "$", "packages", ",", "$", "assets", ")", ";", "$", "composer", "->", "getEventDispatcher", "(", ")", "->", "dispatch", "(", "FoxyEvents", "::", "GET_ASSETS", ",", "$", "assetsEvent", ")", ";", "return", "$", "assetsEvent", "->", "getAssets", "(", ")", ";", "}" ]
Get the package of asset dependencies. @param Composer $composer The composer @param string $assetDir The asset directory @param PackageInterface[] $packages The package dependencies @return array[]
[ "Get", "the", "package", "of", "asset", "dependencies", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Solver/Solver.php#L122-L141
fxpio/foxy
Solver/Solver.php
Solver.getMockPackagePath
protected function getMockPackagePath(PackageInterface $package, $assetDir, $filename) { $packageName = AssetUtil::getName($package); $packagePath = rtrim($assetDir, '/').'/'.$package->getName(); $newFilename = $packagePath.'/'.basename($filename); mkdir($packagePath, 0777, true); copy($filename, $newFilename); $jsonFile = new JsonFile($newFilename); $packageValue = AssetUtil::formatPackage($package, $packageName, (array) $jsonFile->read()); $jsonFile->write($packageValue); return array($packageName, $this->fs->findShortestPath(getcwd(), $newFilename)); }
php
protected function getMockPackagePath(PackageInterface $package, $assetDir, $filename) { $packageName = AssetUtil::getName($package); $packagePath = rtrim($assetDir, '/').'/'.$package->getName(); $newFilename = $packagePath.'/'.basename($filename); mkdir($packagePath, 0777, true); copy($filename, $newFilename); $jsonFile = new JsonFile($newFilename); $packageValue = AssetUtil::formatPackage($package, $packageName, (array) $jsonFile->read()); $jsonFile->write($packageValue); return array($packageName, $this->fs->findShortestPath(getcwd(), $newFilename)); }
[ "protected", "function", "getMockPackagePath", "(", "PackageInterface", "$", "package", ",", "$", "assetDir", ",", "$", "filename", ")", "{", "$", "packageName", "=", "AssetUtil", "::", "getName", "(", "$", "package", ")", ";", "$", "packagePath", "=", "rtrim", "(", "$", "assetDir", ",", "'/'", ")", ".", "'/'", ".", "$", "package", "->", "getName", "(", ")", ";", "$", "newFilename", "=", "$", "packagePath", ".", "'/'", ".", "basename", "(", "$", "filename", ")", ";", "mkdir", "(", "$", "packagePath", ",", "0777", ",", "true", ")", ";", "copy", "(", "$", "filename", ",", "$", "newFilename", ")", ";", "$", "jsonFile", "=", "new", "JsonFile", "(", "$", "newFilename", ")", ";", "$", "packageValue", "=", "AssetUtil", "::", "formatPackage", "(", "$", "package", ",", "$", "packageName", ",", "(", "array", ")", "$", "jsonFile", "->", "read", "(", ")", ")", ";", "$", "jsonFile", "->", "write", "(", "$", "packageValue", ")", ";", "return", "array", "(", "$", "packageName", ",", "$", "this", "->", "fs", "->", "findShortestPath", "(", "getcwd", "(", ")", ",", "$", "newFilename", ")", ")", ";", "}" ]
Get the path of the mock package. @param PackageInterface $package The package dependency @param string $assetDir The asset directory @param string $filename The filename of asset package @return string[] The package name and the relative package path from the current directory
[ "Get", "the", "path", "of", "the", "mock", "package", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Solver/Solver.php#L152-L166
fxpio/foxy
Foxy.php
Foxy.activate
public function activate(Composer $composer, IOInterface $io) { ComposerUtil::validateVersion(static::REQUIRED_COMPOSER_VERSION, Composer::VERSION); $input = ConsoleUtil::getInput($io); $config = ConfigBuilder::build($composer, self::$defaultConfig, $io); $executor = new ProcessExecutor($io); $fs = new Filesystem($executor); $assetManager = $this->getAssetManager($io, $config, $executor, $fs); $assetFallback = new AssetFallback($io, $config, $assetManager->getPackageName(), $fs); $composerFallback = new ComposerFallback($composer, $io, $config, $input, $fs); $this->solver = new Solver($assetManager, $config, $fs, $composerFallback); $assetFallback->save(); $composerFallback->save(); $assetManager->setFallback($assetFallback); if ($config->get('enabled')) { $assetManager->validate(); } }
php
public function activate(Composer $composer, IOInterface $io) { ComposerUtil::validateVersion(static::REQUIRED_COMPOSER_VERSION, Composer::VERSION); $input = ConsoleUtil::getInput($io); $config = ConfigBuilder::build($composer, self::$defaultConfig, $io); $executor = new ProcessExecutor($io); $fs = new Filesystem($executor); $assetManager = $this->getAssetManager($io, $config, $executor, $fs); $assetFallback = new AssetFallback($io, $config, $assetManager->getPackageName(), $fs); $composerFallback = new ComposerFallback($composer, $io, $config, $input, $fs); $this->solver = new Solver($assetManager, $config, $fs, $composerFallback); $assetFallback->save(); $composerFallback->save(); $assetManager->setFallback($assetFallback); if ($config->get('enabled')) { $assetManager->validate(); } }
[ "public", "function", "activate", "(", "Composer", "$", "composer", ",", "IOInterface", "$", "io", ")", "{", "ComposerUtil", "::", "validateVersion", "(", "static", "::", "REQUIRED_COMPOSER_VERSION", ",", "Composer", "::", "VERSION", ")", ";", "$", "input", "=", "ConsoleUtil", "::", "getInput", "(", "$", "io", ")", ";", "$", "config", "=", "ConfigBuilder", "::", "build", "(", "$", "composer", ",", "self", "::", "$", "defaultConfig", ",", "$", "io", ")", ";", "$", "executor", "=", "new", "ProcessExecutor", "(", "$", "io", ")", ";", "$", "fs", "=", "new", "Filesystem", "(", "$", "executor", ")", ";", "$", "assetManager", "=", "$", "this", "->", "getAssetManager", "(", "$", "io", ",", "$", "config", ",", "$", "executor", ",", "$", "fs", ")", ";", "$", "assetFallback", "=", "new", "AssetFallback", "(", "$", "io", ",", "$", "config", ",", "$", "assetManager", "->", "getPackageName", "(", ")", ",", "$", "fs", ")", ";", "$", "composerFallback", "=", "new", "ComposerFallback", "(", "$", "composer", ",", "$", "io", ",", "$", "config", ",", "$", "input", ",", "$", "fs", ")", ";", "$", "this", "->", "solver", "=", "new", "Solver", "(", "$", "assetManager", ",", "$", "config", ",", "$", "fs", ",", "$", "composerFallback", ")", ";", "$", "assetFallback", "->", "save", "(", ")", ";", "$", "composerFallback", "->", "save", "(", ")", ";", "$", "assetManager", "->", "setFallback", "(", "$", "assetFallback", ")", ";", "if", "(", "$", "config", "->", "get", "(", "'enabled'", ")", ")", "{", "$", "assetManager", "->", "validate", "(", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Foxy.php#L95-L114
fxpio/foxy
Foxy.php
Foxy.solveAssets
public function solveAssets(Event $event) { $this->solver->setUpdatable(false !== strpos($event->getName(), 'update')); $this->solver->solve($event->getComposer(), $event->getIO()); }
php
public function solveAssets(Event $event) { $this->solver->setUpdatable(false !== strpos($event->getName(), 'update')); $this->solver->solve($event->getComposer(), $event->getIO()); }
[ "public", "function", "solveAssets", "(", "Event", "$", "event", ")", "{", "$", "this", "->", "solver", "->", "setUpdatable", "(", "false", "!==", "strpos", "(", "$", "event", "->", "getName", "(", ")", ",", "'update'", ")", ")", ";", "$", "this", "->", "solver", "->", "solve", "(", "$", "event", "->", "getComposer", "(", ")", ",", "$", "event", "->", "getIO", "(", ")", ")", ";", "}" ]
Solve the assets. @param Event $event The composer script event
[ "Solve", "the", "assets", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Foxy.php#L131-L135
fxpio/foxy
Foxy.php
Foxy.getAssetManager
protected function getAssetManager(IOInterface $io, Config $config, ProcessExecutor $executor, Filesystem $fs) { $manager = $config->get('manager'); foreach (self::$assetManagers as $class) { $am = new $class($io, $config, $executor, $fs); if ($am instanceof AssetManagerInterface && $manager === $am->getName()) { return $am; } } throw new RuntimeException(sprintf('The asset manager "%s" doesn\'t exist', $manager)); }
php
protected function getAssetManager(IOInterface $io, Config $config, ProcessExecutor $executor, Filesystem $fs) { $manager = $config->get('manager'); foreach (self::$assetManagers as $class) { $am = new $class($io, $config, $executor, $fs); if ($am instanceof AssetManagerInterface && $manager === $am->getName()) { return $am; } } throw new RuntimeException(sprintf('The asset manager "%s" doesn\'t exist', $manager)); }
[ "protected", "function", "getAssetManager", "(", "IOInterface", "$", "io", ",", "Config", "$", "config", ",", "ProcessExecutor", "$", "executor", ",", "Filesystem", "$", "fs", ")", "{", "$", "manager", "=", "$", "config", "->", "get", "(", "'manager'", ")", ";", "foreach", "(", "self", "::", "$", "assetManagers", "as", "$", "class", ")", "{", "$", "am", "=", "new", "$", "class", "(", "$", "io", ",", "$", "config", ",", "$", "executor", ",", "$", "fs", ")", ";", "if", "(", "$", "am", "instanceof", "AssetManagerInterface", "&&", "$", "manager", "===", "$", "am", "->", "getName", "(", ")", ")", "{", "return", "$", "am", ";", "}", "}", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'The asset manager \"%s\" doesn\\'t exist'", ",", "$", "manager", ")", ")", ";", "}" ]
Get the asset manager. @param IOInterface $io The IO @param Config $config The config @param ProcessExecutor $executor The process executor @param Filesystem $fs The composer filesystem @throws RuntimeException When the asset manager is not found @return AssetManagerInterface
[ "Get", "the", "asset", "manager", "." ]
train
https://github.com/fxpio/foxy/blob/d067b843252c5816ed52378d8d37e0addb0e02c1/Foxy.php#L149-L162
botman/driver-web
src/WebDriver.php
WebDriver.matchesRequest
public function matchesRequest() { return Collection::make($this->config->get('matchingData'))->diffAssoc($this->event)->isEmpty(); }
php
public function matchesRequest() { return Collection::make($this->config->get('matchingData'))->diffAssoc($this->event)->isEmpty(); }
[ "public", "function", "matchesRequest", "(", ")", "{", "return", "Collection", "::", "make", "(", "$", "this", "->", "config", "->", "get", "(", "'matchingData'", ")", ")", "->", "diffAssoc", "(", "$", "this", "->", "event", ")", "->", "isEmpty", "(", ")", ";", "}" ]
Determine if the request is for this driver. @return bool
[ "Determine", "if", "the", "request", "is", "for", "this", "driver", "." ]
train
https://github.com/botman/driver-web/blob/98f10f4d8180b9bc3c031c94c6b1ded3d821da2b/src/WebDriver.php#L73-L76
botman/driver-web
src/WebDriver.php
WebDriver.typesAndWaits
public function typesAndWaits(IncomingMessage $matchingMessage, float $seconds) { $this->replies[] = [ 'message' => TypingIndicator::create($seconds), 'additionalParameters' => [], ]; }
php
public function typesAndWaits(IncomingMessage $matchingMessage, float $seconds) { $this->replies[] = [ 'message' => TypingIndicator::create($seconds), 'additionalParameters' => [], ]; }
[ "public", "function", "typesAndWaits", "(", "IncomingMessage", "$", "matchingMessage", ",", "float", "$", "seconds", ")", "{", "$", "this", "->", "replies", "[", "]", "=", "[", "'message'", "=>", "TypingIndicator", "::", "create", "(", "$", "seconds", ")", ",", "'additionalParameters'", "=>", "[", "]", ",", "]", ";", "}" ]
Send a typing indicator and wait for the given amount of seconds. @param IncomingMessage $matchingMessage @param float $seconds @return mixed
[ "Send", "a", "typing", "indicator", "and", "wait", "for", "the", "given", "amount", "of", "seconds", "." ]
train
https://github.com/botman/driver-web/blob/98f10f4d8180b9bc3c031c94c6b1ded3d821da2b/src/WebDriver.php#L96-L102
botman/driver-web
src/WebDriver.php
WebDriver.getMessages
public function getMessages() { if (empty($this->messages)) { $message = $this->event->get('message'); $userId = $this->event->get('userId'); $sender = $this->event->get('sender', $userId); $incomingMessage = new IncomingMessage($message, $sender, $userId, $this->payload); $incomingMessage = $this->addAttachments($incomingMessage); $this->messages = [$incomingMessage]; } return $this->messages; }
php
public function getMessages() { if (empty($this->messages)) { $message = $this->event->get('message'); $userId = $this->event->get('userId'); $sender = $this->event->get('sender', $userId); $incomingMessage = new IncomingMessage($message, $sender, $userId, $this->payload); $incomingMessage = $this->addAttachments($incomingMessage); $this->messages = [$incomingMessage]; } return $this->messages; }
[ "public", "function", "getMessages", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "messages", ")", ")", "{", "$", "message", "=", "$", "this", "->", "event", "->", "get", "(", "'message'", ")", ";", "$", "userId", "=", "$", "this", "->", "event", "->", "get", "(", "'userId'", ")", ";", "$", "sender", "=", "$", "this", "->", "event", "->", "get", "(", "'sender'", ",", "$", "userId", ")", ";", "$", "incomingMessage", "=", "new", "IncomingMessage", "(", "$", "message", ",", "$", "sender", ",", "$", "userId", ",", "$", "this", "->", "payload", ")", ";", "$", "incomingMessage", "=", "$", "this", "->", "addAttachments", "(", "$", "incomingMessage", ")", ";", "$", "this", "->", "messages", "=", "[", "$", "incomingMessage", "]", ";", "}", "return", "$", "this", "->", "messages", ";", "}" ]
Retrieve the chat message. @return array
[ "Retrieve", "the", "chat", "message", "." ]
train
https://github.com/botman/driver-web/blob/98f10f4d8180b9bc3c031c94c6b1ded3d821da2b/src/WebDriver.php#L143-L158
botman/driver-web
src/WebDriver.php
WebDriver.messagesHandled
public function messagesHandled() { $messages = $this->buildReply($this->replies); // Reset replies $this->replies = []; Response::create(json_encode([ 'status' => $this->replyStatusCode, 'messages' => $messages, ]), $this->replyStatusCode, [ 'Content-Type' => 'application/json', 'Access-Control-Allow-Credentials' => true, 'Access-Control-Allow-Origin' => '*', ])->send(); }
php
public function messagesHandled() { $messages = $this->buildReply($this->replies); // Reset replies $this->replies = []; Response::create(json_encode([ 'status' => $this->replyStatusCode, 'messages' => $messages, ]), $this->replyStatusCode, [ 'Content-Type' => 'application/json', 'Access-Control-Allow-Credentials' => true, 'Access-Control-Allow-Origin' => '*', ])->send(); }
[ "public", "function", "messagesHandled", "(", ")", "{", "$", "messages", "=", "$", "this", "->", "buildReply", "(", "$", "this", "->", "replies", ")", ";", "// Reset replies", "$", "this", "->", "replies", "=", "[", "]", ";", "Response", "::", "create", "(", "json_encode", "(", "[", "'status'", "=>", "$", "this", "->", "replyStatusCode", ",", "'messages'", "=>", "$", "messages", ",", "]", ")", ",", "$", "this", "->", "replyStatusCode", ",", "[", "'Content-Type'", "=>", "'application/json'", ",", "'Access-Control-Allow-Credentials'", "=>", "true", ",", "'Access-Control-Allow-Origin'", "=>", "'*'", ",", "]", ")", "->", "send", "(", ")", ";", "}" ]
Send out message response.
[ "Send", "out", "message", "response", "." ]
train
https://github.com/botman/driver-web/blob/98f10f4d8180b9bc3c031c94c6b1ded3d821da2b/src/WebDriver.php#L228-L243
botman/driver-web
src/WebDriver.php
WebDriver.addAttachments
protected function addAttachments($incomingMessage) { $attachment = $this->event->get('attachment'); if ($attachment === self::ATTACHMENT_IMAGE) { $images = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new Image($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(Image::PATTERN); $incomingMessage->setImages($images); } elseif ($attachment === self::ATTACHMENT_AUDIO) { $audio = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new Audio($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(Audio::PATTERN); $incomingMessage->setAudio($audio); } elseif ($attachment === self::ATTACHMENT_VIDEO) { $videos = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new Video($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(Video::PATTERN); $incomingMessage->setVideos($videos); } elseif ($attachment === self::ATTACHMENT_FILE) { $files = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new File($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(File::PATTERN); $incomingMessage->setFiles($files); } return $incomingMessage; }
php
protected function addAttachments($incomingMessage) { $attachment = $this->event->get('attachment'); if ($attachment === self::ATTACHMENT_IMAGE) { $images = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new Image($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(Image::PATTERN); $incomingMessage->setImages($images); } elseif ($attachment === self::ATTACHMENT_AUDIO) { $audio = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new Audio($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(Audio::PATTERN); $incomingMessage->setAudio($audio); } elseif ($attachment === self::ATTACHMENT_VIDEO) { $videos = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new Video($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(Video::PATTERN); $incomingMessage->setVideos($videos); } elseif ($attachment === self::ATTACHMENT_FILE) { $files = $this->files->map(function ($file) { if ($file instanceof UploadedFile) { $path = $file->getRealPath(); } else { $path = $file['tmp_name']; } return new File($this->getDataURI($path)); })->values()->toArray(); $incomingMessage->setText(File::PATTERN); $incomingMessage->setFiles($files); } return $incomingMessage; }
[ "protected", "function", "addAttachments", "(", "$", "incomingMessage", ")", "{", "$", "attachment", "=", "$", "this", "->", "event", "->", "get", "(", "'attachment'", ")", ";", "if", "(", "$", "attachment", "===", "self", "::", "ATTACHMENT_IMAGE", ")", "{", "$", "images", "=", "$", "this", "->", "files", "->", "map", "(", "function", "(", "$", "file", ")", "{", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "$", "path", "=", "$", "file", "->", "getRealPath", "(", ")", ";", "}", "else", "{", "$", "path", "=", "$", "file", "[", "'tmp_name'", "]", ";", "}", "return", "new", "Image", "(", "$", "this", "->", "getDataURI", "(", "$", "path", ")", ")", ";", "}", ")", "->", "values", "(", ")", "->", "toArray", "(", ")", ";", "$", "incomingMessage", "->", "setText", "(", "Image", "::", "PATTERN", ")", ";", "$", "incomingMessage", "->", "setImages", "(", "$", "images", ")", ";", "}", "elseif", "(", "$", "attachment", "===", "self", "::", "ATTACHMENT_AUDIO", ")", "{", "$", "audio", "=", "$", "this", "->", "files", "->", "map", "(", "function", "(", "$", "file", ")", "{", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "$", "path", "=", "$", "file", "->", "getRealPath", "(", ")", ";", "}", "else", "{", "$", "path", "=", "$", "file", "[", "'tmp_name'", "]", ";", "}", "return", "new", "Audio", "(", "$", "this", "->", "getDataURI", "(", "$", "path", ")", ")", ";", "}", ")", "->", "values", "(", ")", "->", "toArray", "(", ")", ";", "$", "incomingMessage", "->", "setText", "(", "Audio", "::", "PATTERN", ")", ";", "$", "incomingMessage", "->", "setAudio", "(", "$", "audio", ")", ";", "}", "elseif", "(", "$", "attachment", "===", "self", "::", "ATTACHMENT_VIDEO", ")", "{", "$", "videos", "=", "$", "this", "->", "files", "->", "map", "(", "function", "(", "$", "file", ")", "{", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "$", "path", "=", "$", "file", "->", "getRealPath", "(", ")", ";", "}", "else", "{", "$", "path", "=", "$", "file", "[", "'tmp_name'", "]", ";", "}", "return", "new", "Video", "(", "$", "this", "->", "getDataURI", "(", "$", "path", ")", ")", ";", "}", ")", "->", "values", "(", ")", "->", "toArray", "(", ")", ";", "$", "incomingMessage", "->", "setText", "(", "Video", "::", "PATTERN", ")", ";", "$", "incomingMessage", "->", "setVideos", "(", "$", "videos", ")", ";", "}", "elseif", "(", "$", "attachment", "===", "self", "::", "ATTACHMENT_FILE", ")", "{", "$", "files", "=", "$", "this", "->", "files", "->", "map", "(", "function", "(", "$", "file", ")", "{", "if", "(", "$", "file", "instanceof", "UploadedFile", ")", "{", "$", "path", "=", "$", "file", "->", "getRealPath", "(", ")", ";", "}", "else", "{", "$", "path", "=", "$", "file", "[", "'tmp_name'", "]", ";", "}", "return", "new", "File", "(", "$", "this", "->", "getDataURI", "(", "$", "path", ")", ")", ";", "}", ")", "->", "values", "(", ")", "->", "toArray", "(", ")", ";", "$", "incomingMessage", "->", "setText", "(", "File", "::", "PATTERN", ")", ";", "$", "incomingMessage", "->", "setFiles", "(", "$", "files", ")", ";", "}", "return", "$", "incomingMessage", ";", "}" ]
Add potential attachments to the message object. @param IncomingMessage $incomingMessage @return IncomingMessage
[ "Add", "potential", "attachments", "to", "the", "message", "object", "." ]
train
https://github.com/botman/driver-web/blob/98f10f4d8180b9bc3c031c94c6b1ded3d821da2b/src/WebDriver.php#L272-L327
botman/driver-web
src/Providers/WebServiceProvider.php
WebServiceProvider.boot
public function boot() { if (! $this->isRunningInBotManStudio()) { $this->loadDrivers(); $this->publishes([ __DIR__.'/../../stubs/web.php' => config_path('botman/web.php'), ]); $this->mergeConfigFrom(__DIR__.'/../../stubs/web.php', 'botman.web'); } $this->loadRoutesFrom(__DIR__.'/../Laravel/routes.php'); $this->loadViewsFrom(__DIR__.'/../Laravel/views', 'botman-web'); $this->publishes([ __DIR__.'/../Laravel/views' => resource_path('views/vendor/botman-web'), ]); }
php
public function boot() { if (! $this->isRunningInBotManStudio()) { $this->loadDrivers(); $this->publishes([ __DIR__.'/../../stubs/web.php' => config_path('botman/web.php'), ]); $this->mergeConfigFrom(__DIR__.'/../../stubs/web.php', 'botman.web'); } $this->loadRoutesFrom(__DIR__.'/../Laravel/routes.php'); $this->loadViewsFrom(__DIR__.'/../Laravel/views', 'botman-web'); $this->publishes([ __DIR__.'/../Laravel/views' => resource_path('views/vendor/botman-web'), ]); }
[ "public", "function", "boot", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isRunningInBotManStudio", "(", ")", ")", "{", "$", "this", "->", "loadDrivers", "(", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../../stubs/web.php'", "=>", "config_path", "(", "'botman/web.php'", ")", ",", "]", ")", ";", "$", "this", "->", "mergeConfigFrom", "(", "__DIR__", ".", "'/../../stubs/web.php'", ",", "'botman.web'", ")", ";", "}", "$", "this", "->", "loadRoutesFrom", "(", "__DIR__", ".", "'/../Laravel/routes.php'", ")", ";", "$", "this", "->", "loadViewsFrom", "(", "__DIR__", ".", "'/../Laravel/views'", ",", "'botman-web'", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../Laravel/views'", "=>", "resource_path", "(", "'views/vendor/botman-web'", ")", ",", "]", ")", ";", "}" ]
Perform post-registration booting of services. @return void
[ "Perform", "post", "-", "registration", "booting", "of", "services", "." ]
train
https://github.com/botman/driver-web/blob/98f10f4d8180b9bc3c031c94c6b1ded3d821da2b/src/Providers/WebServiceProvider.php#L17-L34
sonata-project/SonataNotificationBundle
src/Command/CleanupCommand.php
CleanupCommand.execute
public function execute(InputInterface $input, OutputInterface $output) { $output->write('<info>Starting ... </info>'); $this->getBackend()->cleanup(); $output->writeln('done!'); }
php
public function execute(InputInterface $input, OutputInterface $output) { $output->write('<info>Starting ... </info>'); $this->getBackend()->cleanup(); $output->writeln('done!'); }
[ "public", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "output", "->", "write", "(", "'<info>Starting ... </info>'", ")", ";", "$", "this", "->", "getBackend", "(", ")", "->", "cleanup", "(", ")", ";", "$", "output", "->", "writeln", "(", "'done!'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Command/CleanupCommand.php#L35-L42
sonata-project/SonataNotificationBundle
src/Backend/AMQPBackendDispatcher.php
AMQPBackendDispatcher.getChannel
public function getChannel() { @trigger_error(sprintf('The method %s is deprecated since version 3.3 and will be removed in 4.0. Use %s::getContext() instead.', __METHOD__, __CLASS__), E_USER_DEPRECATED); if (!$this->channel) { if (!$this->context instanceof \Enqueue\AmqpLib\AmqpContext) { throw new \LogicException('The BC layer works only if enqueue/amqp-lib lib is being used.'); } // load context $this->getContext(); /** @var \Enqueue\AmqpLib\AmqpContext $context */ $context = $this->getContext(); $this->channel = $context->getLibChannel(); $this->connection = $this->channel->getConnection(); } return $this->channel; }
php
public function getChannel() { @trigger_error(sprintf('The method %s is deprecated since version 3.3 and will be removed in 4.0. Use %s::getContext() instead.', __METHOD__, __CLASS__), E_USER_DEPRECATED); if (!$this->channel) { if (!$this->context instanceof \Enqueue\AmqpLib\AmqpContext) { throw new \LogicException('The BC layer works only if enqueue/amqp-lib lib is being used.'); } // load context $this->getContext(); /** @var \Enqueue\AmqpLib\AmqpContext $context */ $context = $this->getContext(); $this->channel = $context->getLibChannel(); $this->connection = $this->channel->getConnection(); } return $this->channel; }
[ "public", "function", "getChannel", "(", ")", "{", "@", "trigger_error", "(", "sprintf", "(", "'The method %s is deprecated since version 3.3 and will be removed in 4.0. Use %s::getContext() instead.'", ",", "__METHOD__", ",", "__CLASS__", ")", ",", "E_USER_DEPRECATED", ")", ";", "if", "(", "!", "$", "this", "->", "channel", ")", "{", "if", "(", "!", "$", "this", "->", "context", "instanceof", "\\", "Enqueue", "\\", "AmqpLib", "\\", "AmqpContext", ")", "{", "throw", "new", "\\", "LogicException", "(", "'The BC layer works only if enqueue/amqp-lib lib is being used.'", ")", ";", "}", "// load context", "$", "this", "->", "getContext", "(", ")", ";", "/** @var \\Enqueue\\AmqpLib\\AmqpContext $context */", "$", "context", "=", "$", "this", "->", "getContext", "(", ")", ";", "$", "this", "->", "channel", "=", "$", "context", "->", "getLibChannel", "(", ")", ";", "$", "this", "->", "connection", "=", "$", "this", "->", "channel", "->", "getConnection", "(", ")", ";", "}", "return", "$", "this", "->", "channel", ";", "}" ]
@deprecated since 3.2, will be removed in 4.x @return AMQPChannel
[ "@deprecated", "since", "3", ".", "2", "will", "be", "removed", "in", "4", ".", "x" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackendDispatcher.php#L83-L103
sonata-project/SonataNotificationBundle
src/Backend/AMQPBackendDispatcher.php
AMQPBackendDispatcher.getBackend
public function getBackend($type) { if (!$this->backendsInitialized) { foreach ($this->backends as $backend) { $backend['backend']->initialize(); } $this->backendsInitialized = true; } $default = null; if (0 === \count($this->queues)) { foreach ($this->backends as $backend) { if ('default' === $backend['type']) { return $backend['backend']; } } } foreach ($this->backends as $backend) { if ('all' === $type && '' === $backend['type']) { return $backend['backend']; } if ($backend['type'] === $type) { return $backend['backend']; } if ($backend['type'] === $this->defaultQueue) { $default = $backend['backend']; } } if (null === $default) { throw new BackendNotFoundException('Could not find a message backend for the type '.$type); } return $default; }
php
public function getBackend($type) { if (!$this->backendsInitialized) { foreach ($this->backends as $backend) { $backend['backend']->initialize(); } $this->backendsInitialized = true; } $default = null; if (0 === \count($this->queues)) { foreach ($this->backends as $backend) { if ('default' === $backend['type']) { return $backend['backend']; } } } foreach ($this->backends as $backend) { if ('all' === $type && '' === $backend['type']) { return $backend['backend']; } if ($backend['type'] === $type) { return $backend['backend']; } if ($backend['type'] === $this->defaultQueue) { $default = $backend['backend']; } } if (null === $default) { throw new BackendNotFoundException('Could not find a message backend for the type '.$type); } return $default; }
[ "public", "function", "getBackend", "(", "$", "type", ")", "{", "if", "(", "!", "$", "this", "->", "backendsInitialized", ")", "{", "foreach", "(", "$", "this", "->", "backends", "as", "$", "backend", ")", "{", "$", "backend", "[", "'backend'", "]", "->", "initialize", "(", ")", ";", "}", "$", "this", "->", "backendsInitialized", "=", "true", ";", "}", "$", "default", "=", "null", ";", "if", "(", "0", "===", "\\", "count", "(", "$", "this", "->", "queues", ")", ")", "{", "foreach", "(", "$", "this", "->", "backends", "as", "$", "backend", ")", "{", "if", "(", "'default'", "===", "$", "backend", "[", "'type'", "]", ")", "{", "return", "$", "backend", "[", "'backend'", "]", ";", "}", "}", "}", "foreach", "(", "$", "this", "->", "backends", "as", "$", "backend", ")", "{", "if", "(", "'all'", "===", "$", "type", "&&", "''", "===", "$", "backend", "[", "'type'", "]", ")", "{", "return", "$", "backend", "[", "'backend'", "]", ";", "}", "if", "(", "$", "backend", "[", "'type'", "]", "===", "$", "type", ")", "{", "return", "$", "backend", "[", "'backend'", "]", ";", "}", "if", "(", "$", "backend", "[", "'type'", "]", "===", "$", "this", "->", "defaultQueue", ")", "{", "$", "default", "=", "$", "backend", "[", "'backend'", "]", ";", "}", "}", "if", "(", "null", "===", "$", "default", ")", "{", "throw", "new", "BackendNotFoundException", "(", "'Could not find a message backend for the type '", ".", "$", "type", ")", ";", "}", "return", "$", "default", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackendDispatcher.php#L150-L188
sonata-project/SonataNotificationBundle
src/Backend/AMQPBackendDispatcher.php
AMQPBackendDispatcher.getStatus
public function getStatus() { try { $this->getContext(); $output = $this->getApiQueueStatus(); $checked = 0; $missingConsumers = []; foreach ($this->queues as $queue) { foreach ($output as $q) { if ($q['name'] === $queue['queue']) { ++$checked; if (0 === $q['consumers']) { $missingConsumers[] = $queue['queue']; } } } } if ($checked !== \count($this->queues)) { return new Failure( 'Not all queues for the available notification types registered in the rabbitmq broker. ' .'Are the consumer commands running?' ); } if (\count($missingConsumers) > 0) { return new Failure( 'There are no rabbitmq consumers running for the queues: '.implode(', ', $missingConsumers) ); } } catch (\Exception $e) { return new Failure($e->getMessage()); } return new Success('Channel is running (RabbitMQ) and consumers for all queues available.'); }
php
public function getStatus() { try { $this->getContext(); $output = $this->getApiQueueStatus(); $checked = 0; $missingConsumers = []; foreach ($this->queues as $queue) { foreach ($output as $q) { if ($q['name'] === $queue['queue']) { ++$checked; if (0 === $q['consumers']) { $missingConsumers[] = $queue['queue']; } } } } if ($checked !== \count($this->queues)) { return new Failure( 'Not all queues for the available notification types registered in the rabbitmq broker. ' .'Are the consumer commands running?' ); } if (\count($missingConsumers) > 0) { return new Failure( 'There are no rabbitmq consumers running for the queues: '.implode(', ', $missingConsumers) ); } } catch (\Exception $e) { return new Failure($e->getMessage()); } return new Success('Channel is running (RabbitMQ) and consumers for all queues available.'); }
[ "public", "function", "getStatus", "(", ")", "{", "try", "{", "$", "this", "->", "getContext", "(", ")", ";", "$", "output", "=", "$", "this", "->", "getApiQueueStatus", "(", ")", ";", "$", "checked", "=", "0", ";", "$", "missingConsumers", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "queues", "as", "$", "queue", ")", "{", "foreach", "(", "$", "output", "as", "$", "q", ")", "{", "if", "(", "$", "q", "[", "'name'", "]", "===", "$", "queue", "[", "'queue'", "]", ")", "{", "++", "$", "checked", ";", "if", "(", "0", "===", "$", "q", "[", "'consumers'", "]", ")", "{", "$", "missingConsumers", "[", "]", "=", "$", "queue", "[", "'queue'", "]", ";", "}", "}", "}", "}", "if", "(", "$", "checked", "!==", "\\", "count", "(", "$", "this", "->", "queues", ")", ")", "{", "return", "new", "Failure", "(", "'Not all queues for the available notification types registered in the rabbitmq broker. '", ".", "'Are the consumer commands running?'", ")", ";", "}", "if", "(", "\\", "count", "(", "$", "missingConsumers", ")", ">", "0", ")", "{", "return", "new", "Failure", "(", "'There are no rabbitmq consumers running for the queues: '", ".", "implode", "(", "', '", ",", "$", "missingConsumers", ")", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "new", "Failure", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "return", "new", "Success", "(", "'Channel is running (RabbitMQ) and consumers for all queues available.'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackendDispatcher.php#L213-L249
sonata-project/SonataNotificationBundle
src/Backend/AMQPBackendDispatcher.php
AMQPBackendDispatcher.getApiQueueStatus
protected function getApiQueueStatus() { if (!class_exists(GuzzleClient::class)) { throw new \RuntimeException( 'The guzzle http client library is required to run rabbitmq health checks. ' .'Make sure to add guzzlehttp/guzzle to your composer.json.' ); } $client = new GuzzleClient(); $client->setConfig(['curl.options' => [CURLOPT_CONNECTTIMEOUT_MS => 3000]]); $request = $client->get(sprintf('%s/queues', $this->settings['console_url'])); $request->setAuth($this->settings['user'], $this->settings['pass']); return json_decode($request->send()->getBody(true), true); }
php
protected function getApiQueueStatus() { if (!class_exists(GuzzleClient::class)) { throw new \RuntimeException( 'The guzzle http client library is required to run rabbitmq health checks. ' .'Make sure to add guzzlehttp/guzzle to your composer.json.' ); } $client = new GuzzleClient(); $client->setConfig(['curl.options' => [CURLOPT_CONNECTTIMEOUT_MS => 3000]]); $request = $client->get(sprintf('%s/queues', $this->settings['console_url'])); $request->setAuth($this->settings['user'], $this->settings['pass']); return json_decode($request->send()->getBody(true), true); }
[ "protected", "function", "getApiQueueStatus", "(", ")", "{", "if", "(", "!", "class_exists", "(", "GuzzleClient", "::", "class", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'The guzzle http client library is required to run rabbitmq health checks. '", ".", "'Make sure to add guzzlehttp/guzzle to your composer.json.'", ")", ";", "}", "$", "client", "=", "new", "GuzzleClient", "(", ")", ";", "$", "client", "->", "setConfig", "(", "[", "'curl.options'", "=>", "[", "CURLOPT_CONNECTTIMEOUT_MS", "=>", "3000", "]", "]", ")", ";", "$", "request", "=", "$", "client", "->", "get", "(", "sprintf", "(", "'%s/queues'", ",", "$", "this", "->", "settings", "[", "'console_url'", "]", ")", ")", ";", "$", "request", "->", "setAuth", "(", "$", "this", "->", "settings", "[", "'user'", "]", ",", "$", "this", "->", "settings", "[", "'pass'", "]", ")", ";", "return", "json_decode", "(", "$", "request", "->", "send", "(", ")", "->", "getBody", "(", "true", ")", ",", "true", ")", ";", "}" ]
Calls the rabbitmq management api /api/<vhost>/queues endpoint to list the available queues. @see http://hg.rabbitmq.com/rabbitmq-management/raw-file/3646dee55e02/priv/www-api/help.html @return array
[ "Calls", "the", "rabbitmq", "management", "api", "/", "api", "/", "<vhost", ">", "/", "queues", "endpoint", "to", "list", "the", "available", "queues", "." ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Backend/AMQPBackendDispatcher.php#L282-L297
sonata-project/SonataNotificationBundle
src/DependencyInjection/SonataNotificationExtension.php
SonataNotificationExtension.load
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $this->checkConfiguration($config); /* * NEXT_MAJOR: Remove the check for ServiceClosureArgument as well as core_legacy.xml. */ if (class_exists(ServiceClosureArgument::class)) { $loader->load('core.xml'); } else { $loader->load('core_legacy.xml'); } $loader->load('backend.xml'); $loader->load('consumer.xml'); $loader->load('command.xml'); $bundles = $container->getParameter('kernel.bundles'); if ('sonata.notification.backend.doctrine' === $config['backend']) { $loader->load('doctrine_orm.xml'); $loader->load('selector.xml'); $loader->load('event.xml'); if (isset($bundles['FOSRestBundle'], $bundles['NelmioApiDocBundle'])) { $loader->load('api_controllers.xml'); $loader->load('api_form.xml'); } // for now, only support for ORM if ($config['admin']['enabled'] && isset($bundles['SonataDoctrineORMAdminBundle'])) { $loader->load('admin.xml'); } } if ($config['consumers']['register_default']) { $loader->load('default_consumers.xml'); } if (isset($bundles['LiipMonitorBundle'])) { $loader->load('checkmonitor.xml'); } $container->setAlias('sonata.notification.backend', $config['backend']); // NEXT_MAJOR: remove this getter when requiring sf3.4+ $container->getAlias('sonata.notification.backend')->setPublic(true); $container->setParameter('sonata.notification.backend', $config['backend']); $this->registerDoctrineMapping($config); $this->registerParameters($container, $config); $this->configureBackends($container, $config); $this->configureClass($container, $config); $this->configureListeners($container, $config); $this->configureAdmin($container, $config); }
php
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $this->checkConfiguration($config); /* * NEXT_MAJOR: Remove the check for ServiceClosureArgument as well as core_legacy.xml. */ if (class_exists(ServiceClosureArgument::class)) { $loader->load('core.xml'); } else { $loader->load('core_legacy.xml'); } $loader->load('backend.xml'); $loader->load('consumer.xml'); $loader->load('command.xml'); $bundles = $container->getParameter('kernel.bundles'); if ('sonata.notification.backend.doctrine' === $config['backend']) { $loader->load('doctrine_orm.xml'); $loader->load('selector.xml'); $loader->load('event.xml'); if (isset($bundles['FOSRestBundle'], $bundles['NelmioApiDocBundle'])) { $loader->load('api_controllers.xml'); $loader->load('api_form.xml'); } // for now, only support for ORM if ($config['admin']['enabled'] && isset($bundles['SonataDoctrineORMAdminBundle'])) { $loader->load('admin.xml'); } } if ($config['consumers']['register_default']) { $loader->load('default_consumers.xml'); } if (isset($bundles['LiipMonitorBundle'])) { $loader->load('checkmonitor.xml'); } $container->setAlias('sonata.notification.backend', $config['backend']); // NEXT_MAJOR: remove this getter when requiring sf3.4+ $container->getAlias('sonata.notification.backend')->setPublic(true); $container->setParameter('sonata.notification.backend', $config['backend']); $this->registerDoctrineMapping($config); $this->registerParameters($container, $config); $this->configureBackends($container, $config); $this->configureClass($container, $config); $this->configureListeners($container, $config); $this->configureAdmin($container, $config); }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "config", "=", "$", "this", "->", "processConfiguration", "(", "$", "configuration", ",", "$", "configs", ")", ";", "$", "loader", "=", "new", "Loader", "\\", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "$", "this", "->", "checkConfiguration", "(", "$", "config", ")", ";", "/*\n * NEXT_MAJOR: Remove the check for ServiceClosureArgument as well as core_legacy.xml.\n */", "if", "(", "class_exists", "(", "ServiceClosureArgument", "::", "class", ")", ")", "{", "$", "loader", "->", "load", "(", "'core.xml'", ")", ";", "}", "else", "{", "$", "loader", "->", "load", "(", "'core_legacy.xml'", ")", ";", "}", "$", "loader", "->", "load", "(", "'backend.xml'", ")", ";", "$", "loader", "->", "load", "(", "'consumer.xml'", ")", ";", "$", "loader", "->", "load", "(", "'command.xml'", ")", ";", "$", "bundles", "=", "$", "container", "->", "getParameter", "(", "'kernel.bundles'", ")", ";", "if", "(", "'sonata.notification.backend.doctrine'", "===", "$", "config", "[", "'backend'", "]", ")", "{", "$", "loader", "->", "load", "(", "'doctrine_orm.xml'", ")", ";", "$", "loader", "->", "load", "(", "'selector.xml'", ")", ";", "$", "loader", "->", "load", "(", "'event.xml'", ")", ";", "if", "(", "isset", "(", "$", "bundles", "[", "'FOSRestBundle'", "]", ",", "$", "bundles", "[", "'NelmioApiDocBundle'", "]", ")", ")", "{", "$", "loader", "->", "load", "(", "'api_controllers.xml'", ")", ";", "$", "loader", "->", "load", "(", "'api_form.xml'", ")", ";", "}", "// for now, only support for ORM", "if", "(", "$", "config", "[", "'admin'", "]", "[", "'enabled'", "]", "&&", "isset", "(", "$", "bundles", "[", "'SonataDoctrineORMAdminBundle'", "]", ")", ")", "{", "$", "loader", "->", "load", "(", "'admin.xml'", ")", ";", "}", "}", "if", "(", "$", "config", "[", "'consumers'", "]", "[", "'register_default'", "]", ")", "{", "$", "loader", "->", "load", "(", "'default_consumers.xml'", ")", ";", "}", "if", "(", "isset", "(", "$", "bundles", "[", "'LiipMonitorBundle'", "]", ")", ")", "{", "$", "loader", "->", "load", "(", "'checkmonitor.xml'", ")", ";", "}", "$", "container", "->", "setAlias", "(", "'sonata.notification.backend'", ",", "$", "config", "[", "'backend'", "]", ")", ";", "// NEXT_MAJOR: remove this getter when requiring sf3.4+", "$", "container", "->", "getAlias", "(", "'sonata.notification.backend'", ")", "->", "setPublic", "(", "true", ")", ";", "$", "container", "->", "setParameter", "(", "'sonata.notification.backend'", ",", "$", "config", "[", "'backend'", "]", ")", ";", "$", "this", "->", "registerDoctrineMapping", "(", "$", "config", ")", ";", "$", "this", "->", "registerParameters", "(", "$", "container", ",", "$", "config", ")", ";", "$", "this", "->", "configureBackends", "(", "$", "container", ",", "$", "config", ")", ";", "$", "this", "->", "configureClass", "(", "$", "container", ",", "$", "config", ")", ";", "$", "this", "->", "configureListeners", "(", "$", "container", ",", "$", "config", ")", ";", "$", "this", "->", "configureAdmin", "(", "$", "container", ",", "$", "config", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/DependencyInjection/SonataNotificationExtension.php#L38-L97
sonata-project/SonataNotificationBundle
src/DependencyInjection/SonataNotificationExtension.php
SonataNotificationExtension.configureDoctrineBackends
protected function configureDoctrineBackends(ContainerBuilder $container, array $config, $checkLevel, $pause, $maxAge, $batchSize) { $queues = $config['queues']; $qBackends = []; $definition = $container->getDefinition('sonata.notification.backend.doctrine'); // no queue defined, set a default one if (0 === \count($queues)) { $queues = [[ 'queue' => 'default', 'default' => true, 'types' => [], ]]; } $defaultSet = false; $declaredQueues = []; foreach ($queues as $pos => &$queue) { if (\in_array($queue['queue'], $declaredQueues, true)) { throw new \RuntimeException('The doctrine backend does not support 2 identicals queue name, please rename one queue'); } $declaredQueues[] = $queue['queue']; // make the configuration compatible with old code and rabbitmq if (isset($queue['routing_key']) && \strlen($queue['routing_key']) > 0) { $queue['types'] = [$queue['routing_key']]; } if (empty($queue['types']) && false === $queue['default']) { throw new \RuntimeException('You cannot declared a doctrine queue with no type defined with default = false'); } if (!empty($queue['types']) && true === $queue['default']) { throw new \RuntimeException('You cannot declared a doctrine queue with types defined with default = true'); } $id = $this->createDoctrineQueueBackend($container, $definition->getArgument(0), $checkLevel, $pause, $maxAge, $batchSize, $queue['queue'], $queue['types']); $qBackends[$pos] = [ 'types' => $queue['types'], 'backend' => new Reference($id), ]; if (true === $queue['default']) { if (true === $defaultSet) { throw new \RuntimeException('You can only set one doctrine default queue in your sonata notification configuration.'); } $defaultSet = true; $defaultQueue = $queue['queue']; } } if (false === $defaultSet) { throw new \RuntimeException('You need to specify a valid default queue for the doctrine backend!'); } $definition ->replaceArgument(1, $queues) ->replaceArgument(2, $defaultQueue) ->replaceArgument(3, $qBackends) ; }
php
protected function configureDoctrineBackends(ContainerBuilder $container, array $config, $checkLevel, $pause, $maxAge, $batchSize) { $queues = $config['queues']; $qBackends = []; $definition = $container->getDefinition('sonata.notification.backend.doctrine'); // no queue defined, set a default one if (0 === \count($queues)) { $queues = [[ 'queue' => 'default', 'default' => true, 'types' => [], ]]; } $defaultSet = false; $declaredQueues = []; foreach ($queues as $pos => &$queue) { if (\in_array($queue['queue'], $declaredQueues, true)) { throw new \RuntimeException('The doctrine backend does not support 2 identicals queue name, please rename one queue'); } $declaredQueues[] = $queue['queue']; // make the configuration compatible with old code and rabbitmq if (isset($queue['routing_key']) && \strlen($queue['routing_key']) > 0) { $queue['types'] = [$queue['routing_key']]; } if (empty($queue['types']) && false === $queue['default']) { throw new \RuntimeException('You cannot declared a doctrine queue with no type defined with default = false'); } if (!empty($queue['types']) && true === $queue['default']) { throw new \RuntimeException('You cannot declared a doctrine queue with types defined with default = true'); } $id = $this->createDoctrineQueueBackend($container, $definition->getArgument(0), $checkLevel, $pause, $maxAge, $batchSize, $queue['queue'], $queue['types']); $qBackends[$pos] = [ 'types' => $queue['types'], 'backend' => new Reference($id), ]; if (true === $queue['default']) { if (true === $defaultSet) { throw new \RuntimeException('You can only set one doctrine default queue in your sonata notification configuration.'); } $defaultSet = true; $defaultQueue = $queue['queue']; } } if (false === $defaultSet) { throw new \RuntimeException('You need to specify a valid default queue for the doctrine backend!'); } $definition ->replaceArgument(1, $queues) ->replaceArgument(2, $defaultQueue) ->replaceArgument(3, $qBackends) ; }
[ "protected", "function", "configureDoctrineBackends", "(", "ContainerBuilder", "$", "container", ",", "array", "$", "config", ",", "$", "checkLevel", ",", "$", "pause", ",", "$", "maxAge", ",", "$", "batchSize", ")", "{", "$", "queues", "=", "$", "config", "[", "'queues'", "]", ";", "$", "qBackends", "=", "[", "]", ";", "$", "definition", "=", "$", "container", "->", "getDefinition", "(", "'sonata.notification.backend.doctrine'", ")", ";", "// no queue defined, set a default one", "if", "(", "0", "===", "\\", "count", "(", "$", "queues", ")", ")", "{", "$", "queues", "=", "[", "[", "'queue'", "=>", "'default'", ",", "'default'", "=>", "true", ",", "'types'", "=>", "[", "]", ",", "]", "]", ";", "}", "$", "defaultSet", "=", "false", ";", "$", "declaredQueues", "=", "[", "]", ";", "foreach", "(", "$", "queues", "as", "$", "pos", "=>", "&", "$", "queue", ")", "{", "if", "(", "\\", "in_array", "(", "$", "queue", "[", "'queue'", "]", ",", "$", "declaredQueues", ",", "true", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'The doctrine backend does not support 2 identicals queue name, please rename one queue'", ")", ";", "}", "$", "declaredQueues", "[", "]", "=", "$", "queue", "[", "'queue'", "]", ";", "// make the configuration compatible with old code and rabbitmq", "if", "(", "isset", "(", "$", "queue", "[", "'routing_key'", "]", ")", "&&", "\\", "strlen", "(", "$", "queue", "[", "'routing_key'", "]", ")", ">", "0", ")", "{", "$", "queue", "[", "'types'", "]", "=", "[", "$", "queue", "[", "'routing_key'", "]", "]", ";", "}", "if", "(", "empty", "(", "$", "queue", "[", "'types'", "]", ")", "&&", "false", "===", "$", "queue", "[", "'default'", "]", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'You cannot declared a doctrine queue with no type defined with default = false'", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "queue", "[", "'types'", "]", ")", "&&", "true", "===", "$", "queue", "[", "'default'", "]", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'You cannot declared a doctrine queue with types defined with default = true'", ")", ";", "}", "$", "id", "=", "$", "this", "->", "createDoctrineQueueBackend", "(", "$", "container", ",", "$", "definition", "->", "getArgument", "(", "0", ")", ",", "$", "checkLevel", ",", "$", "pause", ",", "$", "maxAge", ",", "$", "batchSize", ",", "$", "queue", "[", "'queue'", "]", ",", "$", "queue", "[", "'types'", "]", ")", ";", "$", "qBackends", "[", "$", "pos", "]", "=", "[", "'types'", "=>", "$", "queue", "[", "'types'", "]", ",", "'backend'", "=>", "new", "Reference", "(", "$", "id", ")", ",", "]", ";", "if", "(", "true", "===", "$", "queue", "[", "'default'", "]", ")", "{", "if", "(", "true", "===", "$", "defaultSet", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'You can only set one doctrine default queue in your sonata notification configuration.'", ")", ";", "}", "$", "defaultSet", "=", "true", ";", "$", "defaultQueue", "=", "$", "queue", "[", "'queue'", "]", ";", "}", "}", "if", "(", "false", "===", "$", "defaultSet", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'You need to specify a valid default queue for the doctrine backend!'", ")", ";", "}", "$", "definition", "->", "replaceArgument", "(", "1", ",", "$", "queues", ")", "->", "replaceArgument", "(", "2", ",", "$", "defaultQueue", ")", "->", "replaceArgument", "(", "3", ",", "$", "qBackends", ")", ";", "}" ]
@param ContainerBuilder $container @param array $config @param bool $checkLevel @param int $pause @param int $maxAge @param int $batchSize @throws \RuntimeException
[ "@param", "ContainerBuilder", "$container", "@param", "array", "$config", "@param", "bool", "$checkLevel", "@param", "int", "$pause", "@param", "int", "$maxAge", "@param", "int", "$batchSize" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/DependencyInjection/SonataNotificationExtension.php#L236-L300
sonata-project/SonataNotificationBundle
src/DependencyInjection/SonataNotificationExtension.php
SonataNotificationExtension.createDoctrineQueueBackend
protected function createDoctrineQueueBackend(ContainerBuilder $container, $manager, $checkLevel, $pause, $maxAge, $batchSize, $key, array $types = []) { if ('' === $key) { $id = 'sonata.notification.backend.doctrine.default_'.$this->amqpCounter++; } else { $id = 'sonata.notification.backend.doctrine.'.$key; } $definition = new Definition(MessageManagerBackend::class, [$manager, $checkLevel, $pause, $maxAge, $batchSize, $types]); $definition->setPublic(false); $container->setDefinition($id, $definition); return $id; }
php
protected function createDoctrineQueueBackend(ContainerBuilder $container, $manager, $checkLevel, $pause, $maxAge, $batchSize, $key, array $types = []) { if ('' === $key) { $id = 'sonata.notification.backend.doctrine.default_'.$this->amqpCounter++; } else { $id = 'sonata.notification.backend.doctrine.'.$key; } $definition = new Definition(MessageManagerBackend::class, [$manager, $checkLevel, $pause, $maxAge, $batchSize, $types]); $definition->setPublic(false); $container->setDefinition($id, $definition); return $id; }
[ "protected", "function", "createDoctrineQueueBackend", "(", "ContainerBuilder", "$", "container", ",", "$", "manager", ",", "$", "checkLevel", ",", "$", "pause", ",", "$", "maxAge", ",", "$", "batchSize", ",", "$", "key", ",", "array", "$", "types", "=", "[", "]", ")", "{", "if", "(", "''", "===", "$", "key", ")", "{", "$", "id", "=", "'sonata.notification.backend.doctrine.default_'", ".", "$", "this", "->", "amqpCounter", "++", ";", "}", "else", "{", "$", "id", "=", "'sonata.notification.backend.doctrine.'", ".", "$", "key", ";", "}", "$", "definition", "=", "new", "Definition", "(", "MessageManagerBackend", "::", "class", ",", "[", "$", "manager", ",", "$", "checkLevel", ",", "$", "pause", ",", "$", "maxAge", ",", "$", "batchSize", ",", "$", "types", "]", ")", ";", "$", "definition", "->", "setPublic", "(", "false", ")", ";", "$", "container", "->", "setDefinition", "(", "$", "id", ",", "$", "definition", ")", ";", "return", "$", "id", ";", "}" ]
@param ContainerBuilder $container @param string $manager @param bool $checkLevel @param int $pause @param int $maxAge @param int $batchSize @param string $key @param array $types @return string
[ "@param", "ContainerBuilder", "$container", "@param", "string", "$manager", "@param", "bool", "$checkLevel", "@param", "int", "$pause", "@param", "int", "$maxAge", "@param", "int", "$batchSize", "@param", "string", "$key", "@param", "array", "$types" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/DependencyInjection/SonataNotificationExtension.php#L314-L328
sonata-project/SonataNotificationBundle
src/DependencyInjection/SonataNotificationExtension.php
SonataNotificationExtension.createAMQPBackend
protected function createAMQPBackend(ContainerBuilder $container, $exchange, $name, $recover, $key = '', $deadLetterExchange = null, $deadLetterRoutingKey = null, $ttl = null, $prefetchCount = null) { $id = 'sonata.notification.backend.rabbitmq.'.$this->amqpCounter++; $definition = new Definition( AMQPBackend::class, [ $exchange, $name, $recover, $key, $deadLetterExchange, $deadLetterRoutingKey, $ttl, $prefetchCount, ] ); $definition->setPublic(false); $container->setDefinition($id, $definition); return $id; }
php
protected function createAMQPBackend(ContainerBuilder $container, $exchange, $name, $recover, $key = '', $deadLetterExchange = null, $deadLetterRoutingKey = null, $ttl = null, $prefetchCount = null) { $id = 'sonata.notification.backend.rabbitmq.'.$this->amqpCounter++; $definition = new Definition( AMQPBackend::class, [ $exchange, $name, $recover, $key, $deadLetterExchange, $deadLetterRoutingKey, $ttl, $prefetchCount, ] ); $definition->setPublic(false); $container->setDefinition($id, $definition); return $id; }
[ "protected", "function", "createAMQPBackend", "(", "ContainerBuilder", "$", "container", ",", "$", "exchange", ",", "$", "name", ",", "$", "recover", ",", "$", "key", "=", "''", ",", "$", "deadLetterExchange", "=", "null", ",", "$", "deadLetterRoutingKey", "=", "null", ",", "$", "ttl", "=", "null", ",", "$", "prefetchCount", "=", "null", ")", "{", "$", "id", "=", "'sonata.notification.backend.rabbitmq.'", ".", "$", "this", "->", "amqpCounter", "++", ";", "$", "definition", "=", "new", "Definition", "(", "AMQPBackend", "::", "class", ",", "[", "$", "exchange", ",", "$", "name", ",", "$", "recover", ",", "$", "key", ",", "$", "deadLetterExchange", ",", "$", "deadLetterRoutingKey", ",", "$", "ttl", ",", "$", "prefetchCount", ",", "]", ")", ";", "$", "definition", "->", "setPublic", "(", "false", ")", ";", "$", "container", "->", "setDefinition", "(", "$", "id", ",", "$", "definition", ")", ";", "return", "$", "id", ";", "}" ]
@param ContainerBuilder $container @param string $exchange @param string $name @param string $recover @param string $key @param string $deadLetterExchange @param string $deadLetterRoutingKey @param int|null $ttl @param int|null $prefetchCount @return string
[ "@param", "ContainerBuilder", "$container", "@param", "string", "$exchange", "@param", "string", "$name", "@param", "string", "$recover", "@param", "string", "$key", "@param", "string", "$deadLetterExchange", "@param", "string", "$deadLetterRoutingKey", "@param", "int|null", "$ttl", "@param", "int|null", "$prefetchCount" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/DependencyInjection/SonataNotificationExtension.php#L440-L461
sonata-project/SonataNotificationBundle
src/DependencyInjection/SonataNotificationExtension.php
SonataNotificationExtension.getQueuesParameters
private function getQueuesParameters($name, array $queues) { $params = array_unique(array_map(static function ($q) use ($name) { return $q[$name]; }, $queues)); $idx = array_search(null, $params, true); if (false !== $idx) { unset($params[$idx]); } return $params; }
php
private function getQueuesParameters($name, array $queues) { $params = array_unique(array_map(static function ($q) use ($name) { return $q[$name]; }, $queues)); $idx = array_search(null, $params, true); if (false !== $idx) { unset($params[$idx]); } return $params; }
[ "private", "function", "getQueuesParameters", "(", "$", "name", ",", "array", "$", "queues", ")", "{", "$", "params", "=", "array_unique", "(", "array_map", "(", "static", "function", "(", "$", "q", ")", "use", "(", "$", "name", ")", "{", "return", "$", "q", "[", "$", "name", "]", ";", "}", ",", "$", "queues", ")", ")", ";", "$", "idx", "=", "array_search", "(", "null", ",", "$", "params", ",", "true", ")", ";", "if", "(", "false", "!==", "$", "idx", ")", "{", "unset", "(", "$", "params", "[", "$", "idx", "]", ")", ";", "}", "return", "$", "params", ";", "}" ]
@param string $name @param array $queues @return string[]
[ "@param", "string", "$name", "@param", "array", "$queues" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/DependencyInjection/SonataNotificationExtension.php#L469-L481
sonata-project/SonataNotificationBundle
src/Event/DoctrineOptimizeListener.php
DoctrineOptimizeListener.iterate
public function iterate(IterateEvent $event) { foreach ($this->doctrine->getManagers() as $name => $manager) { if (!$manager->isOpen()) { throw new \RuntimeException(sprintf('The doctrine manager: %s is closed', $name)); } $manager->getUnitOfWork()->clear(); } }
php
public function iterate(IterateEvent $event) { foreach ($this->doctrine->getManagers() as $name => $manager) { if (!$manager->isOpen()) { throw new \RuntimeException(sprintf('The doctrine manager: %s is closed', $name)); } $manager->getUnitOfWork()->clear(); } }
[ "public", "function", "iterate", "(", "IterateEvent", "$", "event", ")", "{", "foreach", "(", "$", "this", "->", "doctrine", "->", "getManagers", "(", ")", "as", "$", "name", "=>", "$", "manager", ")", "{", "if", "(", "!", "$", "manager", "->", "isOpen", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'The doctrine manager: %s is closed'", ",", "$", "name", ")", ")", ";", "}", "$", "manager", "->", "getUnitOfWork", "(", ")", "->", "clear", "(", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Event/DoctrineOptimizeListener.php#L43-L52
sonata-project/SonataNotificationBundle
src/Command/ListHandlerCommand.php
ListHandlerCommand.execute
public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('<info>List of consumers available</info>'); foreach ($this->getMetadata() as $type => $ids) { foreach ($ids as $id) { $output->writeln(sprintf('<info>%s</info> - <comment>%s</comment>', $type, $id)); } } $output->writeln(' done!'); }
php
public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('<info>List of consumers available</info>'); foreach ($this->getMetadata() as $type => $ids) { foreach ($ids as $id) { $output->writeln(sprintf('<info>%s</info> - <comment>%s</comment>', $type, $id)); } } $output->writeln(' done!'); }
[ "public", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "output", "->", "writeln", "(", "'<info>List of consumers available</info>'", ")", ";", "foreach", "(", "$", "this", "->", "getMetadata", "(", ")", "as", "$", "type", "=>", "$", "ids", ")", "{", "foreach", "(", "$", "ids", "as", "$", "id", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'<info>%s</info> - <comment>%s</comment>'", ",", "$", "type", ",", "$", "id", ")", ")", ";", "}", "}", "$", "output", "->", "writeln", "(", "' done!'", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Command/ListHandlerCommand.php#L34-L44
sonata-project/SonataNotificationBundle
src/Controller/MessageAdminController.php
MessageAdminController.batchActionPublish
public function batchActionPublish(ProxyQueryInterface $query) { if (false === $this->admin->isGranted('EDIT')) { throw new AccessDeniedException(); } foreach ($query->execute() as $message) { $message = $this->getMessageManager()->restart($message); $this->getBackend()->publish($message); } return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters())); }
php
public function batchActionPublish(ProxyQueryInterface $query) { if (false === $this->admin->isGranted('EDIT')) { throw new AccessDeniedException(); } foreach ($query->execute() as $message) { $message = $this->getMessageManager()->restart($message); $this->getBackend()->publish($message); } return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters())); }
[ "public", "function", "batchActionPublish", "(", "ProxyQueryInterface", "$", "query", ")", "{", "if", "(", "false", "===", "$", "this", "->", "admin", "->", "isGranted", "(", "'EDIT'", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "foreach", "(", "$", "query", "->", "execute", "(", ")", "as", "$", "message", ")", "{", "$", "message", "=", "$", "this", "->", "getMessageManager", "(", ")", "->", "restart", "(", "$", "message", ")", ";", "$", "this", "->", "getBackend", "(", ")", "->", "publish", "(", "$", "message", ")", ";", "}", "return", "new", "RedirectResponse", "(", "$", "this", "->", "admin", "->", "generateUrl", "(", "'list'", ",", "$", "this", "->", "admin", "->", "getFilterParameters", "(", ")", ")", ")", ";", "}" ]
@param ProxyQueryInterface $query @throws AccessDeniedException @return RedirectResponse
[ "@param", "ProxyQueryInterface", "$query" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Controller/MessageAdminController.php#L32-L45
sonata-project/SonataNotificationBundle
src/Controller/MessageAdminController.php
MessageAdminController.batchActionCancelled
public function batchActionCancelled(ProxyQueryInterface $query) { if (false === $this->admin->isGranted('EDIT')) { throw new AccessDeniedException(); } foreach ($query->execute() as $message) { $this->getMessageManager()->cancel($message); } return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters())); }
php
public function batchActionCancelled(ProxyQueryInterface $query) { if (false === $this->admin->isGranted('EDIT')) { throw new AccessDeniedException(); } foreach ($query->execute() as $message) { $this->getMessageManager()->cancel($message); } return new RedirectResponse($this->admin->generateUrl('list', $this->admin->getFilterParameters())); }
[ "public", "function", "batchActionCancelled", "(", "ProxyQueryInterface", "$", "query", ")", "{", "if", "(", "false", "===", "$", "this", "->", "admin", "->", "isGranted", "(", "'EDIT'", ")", ")", "{", "throw", "new", "AccessDeniedException", "(", ")", ";", "}", "foreach", "(", "$", "query", "->", "execute", "(", ")", "as", "$", "message", ")", "{", "$", "this", "->", "getMessageManager", "(", ")", "->", "cancel", "(", "$", "message", ")", ";", "}", "return", "new", "RedirectResponse", "(", "$", "this", "->", "admin", "->", "generateUrl", "(", "'list'", ",", "$", "this", "->", "admin", "->", "getFilterParameters", "(", ")", ")", ")", ";", "}" ]
@param ProxyQueryInterface $query @throws AccessDeniedException @return RedirectResponse
[ "@param", "ProxyQueryInterface", "$query" ]
train
https://github.com/sonata-project/SonataNotificationBundle/blob/cee2d046ba355129c3d77751fd6c7dbeb2c80ec7/src/Controller/MessageAdminController.php#L54-L65