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 |
|---|---|---|---|---|---|---|---|---|---|---|
rcrowe/TwigBridge | src/Twig/Loader.php | Loader.normalizeName | protected function normalizeName($name)
{
if ($this->files->extension($name) === $this->extension) {
$name = substr($name, 0, - (strlen($this->extension) + 1));
}
return $name;
} | php | protected function normalizeName($name)
{
if ($this->files->extension($name) === $this->extension) {
$name = substr($name, 0, - (strlen($this->extension) + 1));
}
return $name;
} | [
"protected",
"function",
"normalizeName",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"files",
"->",
"extension",
"(",
"$",
"name",
")",
"===",
"$",
"this",
"->",
"extension",
")",
"{",
"$",
"name",
"=",
"substr",
"(",
"$",
"name",
",... | Normalize the Twig template name to a name the ViewFinder can use
@param string $name Template file name.
@return string The parsed name | [
"Normalize",
"the",
"Twig",
"template",
"name",
"to",
"a",
"name",
"the",
"ViewFinder",
"can",
"use"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Twig/Loader.php#L93-L100 |
rcrowe/TwigBridge | src/Twig/Loader.php | Loader.getSourceContext | public function getSourceContext($name)
{
$path = $this->findTemplate($name);
return new Source($this->files->get($path), $name, $path);
} | php | public function getSourceContext($name)
{
$path = $this->findTemplate($name);
return new Source($this->files->get($path), $name, $path);
} | [
"public",
"function",
"getSourceContext",
"(",
"$",
"name",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"findTemplate",
"(",
"$",
"name",
")",
";",
"return",
"new",
"Source",
"(",
"$",
"this",
"->",
"files",
"->",
"get",
"(",
"$",
"path",
")",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Twig/Loader.php#L119-L124 |
rcrowe/TwigBridge | src/Twig/Loader.php | Loader.isFresh | public function isFresh($name, $time)
{
return $this->files->lastModified($this->findTemplate($name)) <= $time;
} | php | public function isFresh($name, $time)
{
return $this->files->lastModified($this->findTemplate($name)) <= $time;
} | [
"public",
"function",
"isFresh",
"(",
"$",
"name",
",",
"$",
"time",
")",
"{",
"return",
"$",
"this",
"->",
"files",
"->",
"lastModified",
"(",
"$",
"this",
"->",
"findTemplate",
"(",
"$",
"name",
")",
")",
"<=",
"$",
"time",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Twig/Loader.php#L137-L140 |
rcrowe/TwigBridge | src/Extension/Laravel/Legacy/Facades.php | Facades.setShortcuts | public function setShortcuts(array $shortcuts)
{
$lowered = [];
foreach ($shortcuts as $from => $to) {
$lowered[strtolower($from)] = strtolower($to);
}
$this->shortcuts = $lowered;
} | php | public function setShortcuts(array $shortcuts)
{
$lowered = [];
foreach ($shortcuts as $from => $to) {
$lowered[strtolower($from)] = strtolower($to);
}
$this->shortcuts = $lowered;
} | [
"public",
"function",
"setShortcuts",
"(",
"array",
"$",
"shortcuts",
")",
"{",
"$",
"lowered",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"shortcuts",
"as",
"$",
"from",
"=>",
"$",
"to",
")",
"{",
"$",
"lowered",
"[",
"strtolower",
"(",
"$",
"from",
... | Set shortcuts to aliased classes.
@param array $shortcuts Shortcut to alias map.
@return void | [
"Set",
"shortcuts",
"to",
"aliased",
"classes",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Legacy/Facades.php#L114-L123 |
rcrowe/TwigBridge | src/Extension/Laravel/Legacy/Facades.php | Facades.getShortcut | public function getShortcut($name)
{
$key = strtolower($name);
return (array_key_exists($key, $this->shortcuts)) ? $this->shortcuts[$key] : $name;
} | php | public function getShortcut($name)
{
$key = strtolower($name);
return (array_key_exists($key, $this->shortcuts)) ? $this->shortcuts[$key] : $name;
} | [
"public",
"function",
"getShortcut",
"(",
"$",
"name",
")",
"{",
"$",
"key",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"return",
"(",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"shortcuts",
")",
")",
"?",
"$",
"this",
"->",
"... | Get the alias the shortcut points to.
@param string $name Twig function name.
@return string Either the alias or the name passed in if not found. | [
"Get",
"the",
"alias",
"the",
"shortcut",
"points",
"to",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Legacy/Facades.php#L142-L147 |
rcrowe/TwigBridge | src/Extension/Laravel/Legacy/Facades.php | Facades.getAliasParts | public function getAliasParts($name)
{
if (strpos($name, '_') !== false) {
$parts = explode('_', $name);
$parts = array_filter($parts); // Remove empty elements
if (count($parts) < 2) {
return false;
}
return [
$parts[0],
implode('_', array_slice($parts, 1))
];
}
return false;
} | php | public function getAliasParts($name)
{
if (strpos($name, '_') !== false) {
$parts = explode('_', $name);
$parts = array_filter($parts); // Remove empty elements
if (count($parts) < 2) {
return false;
}
return [
$parts[0],
implode('_', array_slice($parts, 1))
];
}
return false;
} | [
"public",
"function",
"getAliasParts",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"name",
",",
"'_'",
")",
"!==",
"false",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'_'",
",",
"$",
"name",
")",
";",
"$",
"parts",
"=",
"array_f... | Gets the class and method from the function name.
For the AliasLoader to handle the undefined function, the function must
be in the format class_method(). This function checks whether the function
meets that format.
@param string $name Function name.
@return array|bool Array containing class and method or FALSE if incorrect format. | [
"Gets",
"the",
"class",
"and",
"method",
"from",
"the",
"function",
"name",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Legacy/Facades.php#L160-L178 |
rcrowe/TwigBridge | src/Extension/Laravel/Legacy/Facades.php | Facades.getLookup | public function getLookup($name)
{
$name = strtolower($name);
return (array_key_exists($name, $this->lookup)) ? $this->lookup[$name] : false;
} | php | public function getLookup($name)
{
$name = strtolower($name);
return (array_key_exists($name, $this->lookup)) ? $this->lookup[$name] : false;
} | [
"public",
"function",
"getLookup",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"return",
"(",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"lookup",
")",
")",
"?",
"$",
"this",
"->",
"loo... | Looks in the lookup cache for the function.
Repeat calls to an undefined function are cached.
@param string $name Function name.
@return TwigFunction|false | [
"Looks",
"in",
"the",
"lookup",
"cache",
"for",
"the",
"function",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Legacy/Facades.php#L189-L194 |
rcrowe/TwigBridge | src/Extension/Laravel/Legacy/Facades.php | Facades.getFunction | public function getFunction($name)
{
$name = $this->getShortcut($name);
// Check if we have looked this alias up before
if ($function = $this->getLookup($name)) {
return $function;
}
// Get the class / method we are trying to call
$parts = $this->getAliasParts($name);
if ($parts === false) {
return false;
}
list($class, $method) = $parts;
$class = strtolower($class);
// Does that alias exist
if (array_key_exists($class, $this->aliases)) {
$class = $this->aliases[$class];
$function = new TwigFunction($name, $class.'::'.$method);
$this->setLookup($name, $function);
return $function;
}
return false;
} | php | public function getFunction($name)
{
$name = $this->getShortcut($name);
// Check if we have looked this alias up before
if ($function = $this->getLookup($name)) {
return $function;
}
// Get the class / method we are trying to call
$parts = $this->getAliasParts($name);
if ($parts === false) {
return false;
}
list($class, $method) = $parts;
$class = strtolower($class);
// Does that alias exist
if (array_key_exists($class, $this->aliases)) {
$class = $this->aliases[$class];
$function = new TwigFunction($name, $class.'::'.$method);
$this->setLookup($name, $function);
return $function;
}
return false;
} | [
"public",
"function",
"getFunction",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getShortcut",
"(",
"$",
"name",
")",
";",
"// Check if we have looked this alias up before",
"if",
"(",
"$",
"function",
"=",
"$",
"this",
"->",
"getLookup... | Allow Twig to call Aliased function from an undefined function.
@param string $name Undefined function name.
@return TwigFunction|false | [
"Allow",
"Twig",
"to",
"call",
"Aliased",
"function",
"from",
"an",
"undefined",
"function",
"."
] | train | https://github.com/rcrowe/TwigBridge/blob/b49db9f423170015b84993af09ab3e59bb677e0c/src/Extension/Laravel/Legacy/Facades.php#L216-L247 |
bzikarsky/gelf-php | src/Gelf/Encoder/CompressedJsonEncoder.php | CompressedJsonEncoder.encode | public function encode(MessageInterface $message)
{
$json = parent::encode($message);
return gzcompress($json, $this->compressionLevel);
} | php | public function encode(MessageInterface $message)
{
$json = parent::encode($message);
return gzcompress($json, $this->compressionLevel);
} | [
"public",
"function",
"encode",
"(",
"MessageInterface",
"$",
"message",
")",
"{",
"$",
"json",
"=",
"parent",
"::",
"encode",
"(",
"$",
"message",
")",
";",
"return",
"gzcompress",
"(",
"$",
"json",
",",
"$",
"this",
"->",
"compressionLevel",
")",
";",
... | Encodes a given message
@param MessageInterface $message
@return string | [
"Encodes",
"a",
"given",
"message"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Encoder/CompressedJsonEncoder.php#L50-L55 |
bzikarsky/gelf-php | src/Gelf/Publisher.php | Publisher.publish | public function publish(MessageInterface $message)
{
if (count($this->transports) == 0) {
throw new RuntimeException(
"Publisher requires at least one transport"
);
}
$reason = '';
if (!$this->messageValidator->validate($message, $reason)) {
throw new RuntimeException("Message is invalid: $reason");
}
foreach ($this->transports as $transport) {
/* @var $transport TransportInterface */
$transport->send($message);
}
} | php | public function publish(MessageInterface $message)
{
if (count($this->transports) == 0) {
throw new RuntimeException(
"Publisher requires at least one transport"
);
}
$reason = '';
if (!$this->messageValidator->validate($message, $reason)) {
throw new RuntimeException("Message is invalid: $reason");
}
foreach ($this->transports as $transport) {
/* @var $transport TransportInterface */
$transport->send($message);
}
} | [
"public",
"function",
"publish",
"(",
"MessageInterface",
"$",
"message",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"transports",
")",
"==",
"0",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Publisher requires at least one transport\"",
")",... | Publish a message over all defined transports
@param MessageInterface $message | [
"Publish",
"a",
"message",
"over",
"all",
"defined",
"transports"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Publisher.php#L61-L78 |
bzikarsky/gelf-php | src/Gelf/MessageValidator.php | MessageValidator.validate0100 | public function validate0100(MessageInterface $message, &$reason = "")
{
if (self::isEmpty($message->getHost())) {
$reason = "host not set";
return false;
}
if (self::isEmpty($message->getShortMessage())) {
$reason = "short-message not set";
return false;
}
if (self::isEmpty($message->getVersion())) {
$reason = "version not set";
return false;
}
if ($message->hasAdditional('id')) {
$reason = "additional field 'id' is not allowed";
return false;
}
return true;
} | php | public function validate0100(MessageInterface $message, &$reason = "")
{
if (self::isEmpty($message->getHost())) {
$reason = "host not set";
return false;
}
if (self::isEmpty($message->getShortMessage())) {
$reason = "short-message not set";
return false;
}
if (self::isEmpty($message->getVersion())) {
$reason = "version not set";
return false;
}
if ($message->hasAdditional('id')) {
$reason = "additional field 'id' is not allowed";
return false;
}
return true;
} | [
"public",
"function",
"validate0100",
"(",
"MessageInterface",
"$",
"message",
",",
"&",
"$",
"reason",
"=",
"\"\"",
")",
"{",
"if",
"(",
"self",
"::",
"isEmpty",
"(",
"$",
"message",
"->",
"getHost",
"(",
")",
")",
")",
"{",
"$",
"reason",
"=",
"\"h... | Validates a message according to 1.0 standard
@param MessageInterface $message
@param string &$reason reason for the validation fail
@return bool | [
"Validates",
"a",
"message",
"according",
"to",
"1",
".",
"0",
"standard"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/MessageValidator.php#L48-L75 |
bzikarsky/gelf-php | src/Gelf/MessageValidator.php | MessageValidator.validate0101 | public function validate0101(MessageInterface $message, &$reason = "")
{
// 1.1 incorporates 1.0 validation standar
if (!$this->validate0100($message, $reason)) {
return false;
}
foreach ($message->getAllAdditionals() as $key => $value) {
if (!preg_match('#^[\w\.\-]*$#', $key)) {
$reason = sprintf(
"additional key '%s' contains invalid characters",
$key
);
return false;
}
}
return true;
} | php | public function validate0101(MessageInterface $message, &$reason = "")
{
// 1.1 incorporates 1.0 validation standar
if (!$this->validate0100($message, $reason)) {
return false;
}
foreach ($message->getAllAdditionals() as $key => $value) {
if (!preg_match('#^[\w\.\-]*$#', $key)) {
$reason = sprintf(
"additional key '%s' contains invalid characters",
$key
);
return false;
}
}
return true;
} | [
"public",
"function",
"validate0101",
"(",
"MessageInterface",
"$",
"message",
",",
"&",
"$",
"reason",
"=",
"\"\"",
")",
"{",
"// 1.1 incorporates 1.0 validation standar",
"if",
"(",
"!",
"$",
"this",
"->",
"validate0100",
"(",
"$",
"message",
",",
"$",
"reas... | Validates a message according to 1.1 standard
@param MessageInterface $message
@param string &$reason
@return bool | [
"Validates",
"a",
"message",
"according",
"to",
"1",
".",
"1",
"standard"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/MessageValidator.php#L84-L103 |
bzikarsky/gelf-php | src/Gelf/Transport/SslOptions.php | SslOptions.toStreamContext | public function toStreamContext($serverName = null)
{
$sslContext = array(
'verify_peer' => (bool) $this->verifyPeer,
'allow_self_signed' => (bool) $this->allowSelfSigned
);
if (null !== $this->caFile) {
$sslContext['cafile'] = $this->caFile;
}
if (null !== $this->ciphers) {
$sslContext['ciphers'] = $this->ciphers;
}
if (null !== $serverName) {
$sslContext['SNI_enabled'] = true;
$sslContext[PHP_VERSION_ID < 50600 ? 'SNI_server_name' : 'peer_name'] = $serverName;
if ($this->verifyPeer) {
$sslContext[PHP_VERSION_ID < 50600 ? 'CN_match' : 'peer_name'] = $serverName;
}
}
return array('ssl' => $sslContext);
} | php | public function toStreamContext($serverName = null)
{
$sslContext = array(
'verify_peer' => (bool) $this->verifyPeer,
'allow_self_signed' => (bool) $this->allowSelfSigned
);
if (null !== $this->caFile) {
$sslContext['cafile'] = $this->caFile;
}
if (null !== $this->ciphers) {
$sslContext['ciphers'] = $this->ciphers;
}
if (null !== $serverName) {
$sslContext['SNI_enabled'] = true;
$sslContext[PHP_VERSION_ID < 50600 ? 'SNI_server_name' : 'peer_name'] = $serverName;
if ($this->verifyPeer) {
$sslContext[PHP_VERSION_ID < 50600 ? 'CN_match' : 'peer_name'] = $serverName;
}
}
return array('ssl' => $sslContext);
} | [
"public",
"function",
"toStreamContext",
"(",
"$",
"serverName",
"=",
"null",
")",
"{",
"$",
"sslContext",
"=",
"array",
"(",
"'verify_peer'",
"=>",
"(",
"bool",
")",
"$",
"this",
"->",
"verifyPeer",
",",
"'allow_self_signed'",
"=>",
"(",
"bool",
")",
"$",... | Returns a stream-context representation of this config
@param string|null $serverName
@return array<string,mixed> | [
"Returns",
"a",
"stream",
"-",
"context",
"representation",
"of",
"this",
"config"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/SslOptions.php#L139-L164 |
bzikarsky/gelf-php | src/Gelf/Transport/HttpTransport.php | HttpTransport.fromUrl | public static function fromUrl($url, SslOptions $sslOptions = null)
{
$parsed = parse_url($url);
// check it's a valid URL
if (false === $parsed || !isset($parsed['host']) || !isset($parsed['scheme'])) {
throw new \InvalidArgumentException("$url is not a valid URL");
}
// check it's http or https
$scheme = strtolower($parsed['scheme']);
if (!in_array($scheme, array('http', 'https'))) {
throw new \InvalidArgumentException("$url is not a valid http/https URL");
}
// setup defaults
$defaults = array('port' => 80, 'path' => '', 'user' => null, 'pass' => '');
// change some defaults for https
if ($scheme == 'https') {
$sslOptions = $sslOptions ?: new SslOptions();
$defaults['port'] = 443;
}
// merge defaults and real data and build transport
$parsed = array_merge($defaults, $parsed);
$transport = new static($parsed['host'], $parsed['port'], $parsed['path'], $sslOptions);
// add optional authentication
if ($parsed['user']) {
$transport->setAuthentication($parsed['user'], $parsed['pass']);
}
return $transport;
} | php | public static function fromUrl($url, SslOptions $sslOptions = null)
{
$parsed = parse_url($url);
// check it's a valid URL
if (false === $parsed || !isset($parsed['host']) || !isset($parsed['scheme'])) {
throw new \InvalidArgumentException("$url is not a valid URL");
}
// check it's http or https
$scheme = strtolower($parsed['scheme']);
if (!in_array($scheme, array('http', 'https'))) {
throw new \InvalidArgumentException("$url is not a valid http/https URL");
}
// setup defaults
$defaults = array('port' => 80, 'path' => '', 'user' => null, 'pass' => '');
// change some defaults for https
if ($scheme == 'https') {
$sslOptions = $sslOptions ?: new SslOptions();
$defaults['port'] = 443;
}
// merge defaults and real data and build transport
$parsed = array_merge($defaults, $parsed);
$transport = new static($parsed['host'], $parsed['port'], $parsed['path'], $sslOptions);
// add optional authentication
if ($parsed['user']) {
$transport->setAuthentication($parsed['user'], $parsed['pass']);
}
return $transport;
} | [
"public",
"static",
"function",
"fromUrl",
"(",
"$",
"url",
",",
"SslOptions",
"$",
"sslOptions",
"=",
"null",
")",
"{",
"$",
"parsed",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"// check it's a valid URL",
"if",
"(",
"false",
"===",
"$",
"parsed",
"|... | Creates a HttpTransport from a URI
Supports http and https schemes, port-, path- and auth-definitions
If the port is omitted 80 and 443 are used respectively.
If a username but no password is given, and empty password is used.
If a https URI is given, the provided SslOptions (with a fallback to
the default SslOptions) are used.
@param string $url
@param SslOptions|null $sslOptions
@return HttpTransport | [
"Creates",
"a",
"HttpTransport",
"from",
"a",
"URI"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/HttpTransport.php#L122-L156 |
bzikarsky/gelf-php | src/Gelf/Transport/HttpTransport.php | HttpTransport.setProxy | public function setProxy($proxyUri, $requestFullUri = false)
{
$this->proxyUri = $proxyUri;
$this->requestFullUri = $requestFullUri;
$this->socketClient->setContext($this->getContext());
} | php | public function setProxy($proxyUri, $requestFullUri = false)
{
$this->proxyUri = $proxyUri;
$this->requestFullUri = $requestFullUri;
$this->socketClient->setContext($this->getContext());
} | [
"public",
"function",
"setProxy",
"(",
"$",
"proxyUri",
",",
"$",
"requestFullUri",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"proxyUri",
"=",
"$",
"proxyUri",
";",
"$",
"this",
"->",
"requestFullUri",
"=",
"$",
"requestFullUri",
";",
"$",
"this",
"->",... | Enables HTTP proxy
@param $proxyUri
@param bool $requestFullUri | [
"Enables",
"HTTP",
"proxy"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/HttpTransport.php#L175-L181 |
bzikarsky/gelf-php | src/Gelf/Transport/HttpTransport.php | HttpTransport.send | public function send(MessageInterface $message)
{
$messageEncoder = $this->getMessageEncoder();
$rawMessage = $messageEncoder->encode($message);
$request = array(
sprintf("POST %s HTTP/1.1", $this->path),
sprintf("Host: %s:%d", $this->host, $this->port),
sprintf("Content-Length: %d", strlen($rawMessage)),
"Content-Type: application/json",
"Connection: Keep-Alive",
"Accept: */*"
);
if (null !== $this->authentication) {
$request[] = "Authorization: Basic " . base64_encode($this->authentication);
}
if ($messageEncoder instanceof CompressedJsonEncoder) {
$request[] = "Content-Encoding: gzip";
}
$request[] = ""; // blank line to separate headers from body
$request[] = $rawMessage;
$request = implode($request, "\r\n");
$byteCount = $this->socketClient->write($request);
$headers = $this->readResponseHeaders();
// if we don't have a HTTP/1.1 connection, or the server decided to close the connection
// we should do so as well. next read/write-attempt will open a new socket in this case.
if (strpos($headers, "HTTP/1.1") !== 0 || preg_match("!Connection:\s*Close!i", $headers)) {
$this->socketClient->close();
}
if (!preg_match("!^HTTP/1.\d 202 Accepted!i", $headers)) {
throw new RuntimeException(
sprintf(
"Graylog-Server didn't answer properly, expected 'HTTP/1.x 202 Accepted', response is '%s'",
trim($headers)
)
);
}
return $byteCount;
} | php | public function send(MessageInterface $message)
{
$messageEncoder = $this->getMessageEncoder();
$rawMessage = $messageEncoder->encode($message);
$request = array(
sprintf("POST %s HTTP/1.1", $this->path),
sprintf("Host: %s:%d", $this->host, $this->port),
sprintf("Content-Length: %d", strlen($rawMessage)),
"Content-Type: application/json",
"Connection: Keep-Alive",
"Accept: */*"
);
if (null !== $this->authentication) {
$request[] = "Authorization: Basic " . base64_encode($this->authentication);
}
if ($messageEncoder instanceof CompressedJsonEncoder) {
$request[] = "Content-Encoding: gzip";
}
$request[] = ""; // blank line to separate headers from body
$request[] = $rawMessage;
$request = implode($request, "\r\n");
$byteCount = $this->socketClient->write($request);
$headers = $this->readResponseHeaders();
// if we don't have a HTTP/1.1 connection, or the server decided to close the connection
// we should do so as well. next read/write-attempt will open a new socket in this case.
if (strpos($headers, "HTTP/1.1") !== 0 || preg_match("!Connection:\s*Close!i", $headers)) {
$this->socketClient->close();
}
if (!preg_match("!^HTTP/1.\d 202 Accepted!i", $headers)) {
throw new RuntimeException(
sprintf(
"Graylog-Server didn't answer properly, expected 'HTTP/1.x 202 Accepted', response is '%s'",
trim($headers)
)
);
}
return $byteCount;
} | [
"public",
"function",
"send",
"(",
"MessageInterface",
"$",
"message",
")",
"{",
"$",
"messageEncoder",
"=",
"$",
"this",
"->",
"getMessageEncoder",
"(",
")",
";",
"$",
"rawMessage",
"=",
"$",
"messageEncoder",
"->",
"encode",
"(",
"$",
"message",
")",
";"... | Sends a Message over this transport
@param MessageInterface $message
@return int the number of bytes sent | [
"Sends",
"a",
"Message",
"over",
"this",
"transport"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/HttpTransport.php#L190-L236 |
bzikarsky/gelf-php | src/Gelf/Message.php | Message.logLevelToPsr | final public static function logLevelToPsr($level)
{
$origLevel = $level;
if (is_numeric($level)) {
$level = intval($level);
if (isset(self::$psrLevels[$level])) {
return self::$psrLevels[$level];
}
} elseif (is_string($level)) {
$level = strtolower($level);
if (in_array($level, self::$psrLevels)) {
return $level;
}
}
throw new RuntimeException(
sprintf("Cannot convert log-level '%s' to psr-style", $origLevel)
);
} | php | final public static function logLevelToPsr($level)
{
$origLevel = $level;
if (is_numeric($level)) {
$level = intval($level);
if (isset(self::$psrLevels[$level])) {
return self::$psrLevels[$level];
}
} elseif (is_string($level)) {
$level = strtolower($level);
if (in_array($level, self::$psrLevels)) {
return $level;
}
}
throw new RuntimeException(
sprintf("Cannot convert log-level '%s' to psr-style", $origLevel)
);
} | [
"final",
"public",
"static",
"function",
"logLevelToPsr",
"(",
"$",
"level",
")",
"{",
"$",
"origLevel",
"=",
"$",
"level",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"level",
")",
")",
"{",
"$",
"level",
"=",
"intval",
"(",
"$",
"level",
")",
";",
"i... | Trys to convert a given log-level (psr or syslog) to
the psr representation
@param mixed $level
@return string | [
"Trys",
"to",
"convert",
"a",
"given",
"log",
"-",
"level",
"(",
"psr",
"or",
"syslog",
")",
"to",
"the",
"psr",
"representation"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Message.php#L74-L93 |
bzikarsky/gelf-php | src/Gelf/Message.php | Message.logLevelToSyslog | final public static function logLevelToSyslog($level)
{
$origLevel = $level;
if (is_numeric($level)) {
$level = intval($level);
if ($level < 8 && $level > -1) {
return $level;
}
} elseif (is_string($level)) {
$level = strtolower($level);
$syslogLevel = array_search($level, self::$psrLevels);
if (false !== $syslogLevel) {
return $syslogLevel;
}
}
throw new RuntimeException(
sprintf("Cannot convert log-level '%s' to syslog-style", $origLevel)
);
} | php | final public static function logLevelToSyslog($level)
{
$origLevel = $level;
if (is_numeric($level)) {
$level = intval($level);
if ($level < 8 && $level > -1) {
return $level;
}
} elseif (is_string($level)) {
$level = strtolower($level);
$syslogLevel = array_search($level, self::$psrLevels);
if (false !== $syslogLevel) {
return $syslogLevel;
}
}
throw new RuntimeException(
sprintf("Cannot convert log-level '%s' to syslog-style", $origLevel)
);
} | [
"final",
"public",
"static",
"function",
"logLevelToSyslog",
"(",
"$",
"level",
")",
"{",
"$",
"origLevel",
"=",
"$",
"level",
";",
"if",
"(",
"is_numeric",
"(",
"$",
"level",
")",
")",
"{",
"$",
"level",
"=",
"intval",
"(",
"$",
"level",
")",
";",
... | Trys to convert a given log-level (psr or syslog) to
the syslog representation
@param mxied
@return integer | [
"Trys",
"to",
"convert",
"a",
"given",
"log",
"-",
"level",
"(",
"psr",
"or",
"syslog",
")",
"to",
"the",
"syslog",
"representation"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Message.php#L102-L122 |
bzikarsky/gelf-php | src/Gelf/Logger.php | Logger.log | public function log($level, $rawMessage, array $context = array())
{
$message = $this->initMessage($level, $rawMessage, $context);
// add exception data if present
if (isset($context['exception'])
&& $context['exception'] instanceof Exception
) {
$this->initExceptionData($message, $context['exception']);
}
$this->publisher->publish($message);
} | php | public function log($level, $rawMessage, array $context = array())
{
$message = $this->initMessage($level, $rawMessage, $context);
// add exception data if present
if (isset($context['exception'])
&& $context['exception'] instanceof Exception
) {
$this->initExceptionData($message, $context['exception']);
}
$this->publisher->publish($message);
} | [
"public",
"function",
"log",
"(",
"$",
"level",
",",
"$",
"rawMessage",
",",
"array",
"$",
"context",
"=",
"array",
"(",
")",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"initMessage",
"(",
"$",
"level",
",",
"$",
"rawMessage",
",",
"$",
"con... | Publishes a given message and context with given level
@param mixed $level
@param mixed $rawMessage
@param array $context | [
"Publishes",
"a",
"given",
"message",
"and",
"context",
"with",
"given",
"level"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Logger.php#L68-L80 |
bzikarsky/gelf-php | src/Gelf/Logger.php | Logger.initMessage | protected function initMessage($level, $message, array $context)
{
// assert that message is a string, and interpolate placeholders
$message = (string) $message;
$context = $this->initContext($context);
$message = self::interpolate($message, $context);
// create message object
$messageObj = new Message();
$messageObj->setLevel($level);
$messageObj->setShortMessage($message);
$messageObj->setFacility($this->facility);
foreach ($this->getDefaultContext() as $key => $value) {
$messageObj->setAdditional($key, $value);
}
foreach ($context as $key => $value) {
$messageObj->setAdditional($key, $value);
}
return $messageObj;
} | php | protected function initMessage($level, $message, array $context)
{
// assert that message is a string, and interpolate placeholders
$message = (string) $message;
$context = $this->initContext($context);
$message = self::interpolate($message, $context);
// create message object
$messageObj = new Message();
$messageObj->setLevel($level);
$messageObj->setShortMessage($message);
$messageObj->setFacility($this->facility);
foreach ($this->getDefaultContext() as $key => $value) {
$messageObj->setAdditional($key, $value);
}
foreach ($context as $key => $value) {
$messageObj->setAdditional($key, $value);
}
return $messageObj;
} | [
"protected",
"function",
"initMessage",
"(",
"$",
"level",
",",
"$",
"message",
",",
"array",
"$",
"context",
")",
"{",
"// assert that message is a string, and interpolate placeholders",
"$",
"message",
"=",
"(",
"string",
")",
"$",
"message",
";",
"$",
"context"... | Initializes message-object
@param mixed $level
@param mixed $message
@param array $context
@return Message | [
"Initializes",
"message",
"-",
"object"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Logger.php#L146-L167 |
bzikarsky/gelf-php | src/Gelf/Logger.php | Logger.initContext | protected function initContext($context)
{
foreach ($context as $key => &$value) {
switch (gettype($value)) {
case 'string':
case 'integer':
case 'double':
// These types require no conversion
break;
case 'array':
case 'boolean':
$value = json_encode($value);
break;
case 'object':
if (method_exists($value, '__toString')) {
$value = (string)$value;
} else {
$value = '[object (' . get_class($value) . ')]';
}
break;
case 'NULL':
$value = 'NULL';
break;
default:
$value = '[' . gettype($value) . ']';
break;
}
}
return $context;
} | php | protected function initContext($context)
{
foreach ($context as $key => &$value) {
switch (gettype($value)) {
case 'string':
case 'integer':
case 'double':
// These types require no conversion
break;
case 'array':
case 'boolean':
$value = json_encode($value);
break;
case 'object':
if (method_exists($value, '__toString')) {
$value = (string)$value;
} else {
$value = '[object (' . get_class($value) . ')]';
}
break;
case 'NULL':
$value = 'NULL';
break;
default:
$value = '[' . gettype($value) . ']';
break;
}
}
return $context;
} | [
"protected",
"function",
"initContext",
"(",
"$",
"context",
")",
"{",
"foreach",
"(",
"$",
"context",
"as",
"$",
"key",
"=>",
"&",
"$",
"value",
")",
"{",
"switch",
"(",
"gettype",
"(",
"$",
"value",
")",
")",
"{",
"case",
"'string'",
":",
"case",
... | Initializes context array, ensuring all values are string-safe
@param array $context
@return array | [
"Initializes",
"context",
"array",
"ensuring",
"all",
"values",
"are",
"string",
"-",
"safe"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Logger.php#L175-L205 |
bzikarsky/gelf-php | src/Gelf/Logger.php | Logger.initExceptionData | protected function initExceptionData(Message $message, Exception $exception)
{
$message->setLine($exception->getLine());
$message->setFile($exception->getFile());
$longText = "";
do {
$longText .= sprintf(
"%s: %s (%d)\n\n%s\n",
get_class($exception),
$exception->getMessage(),
$exception->getCode(),
$exception->getTraceAsString()
);
$exception = $exception->getPrevious();
} while ($exception && $longText .= "\n--\n\n");
$message->setFullMessage($longText);
} | php | protected function initExceptionData(Message $message, Exception $exception)
{
$message->setLine($exception->getLine());
$message->setFile($exception->getFile());
$longText = "";
do {
$longText .= sprintf(
"%s: %s (%d)\n\n%s\n",
get_class($exception),
$exception->getMessage(),
$exception->getCode(),
$exception->getTraceAsString()
);
$exception = $exception->getPrevious();
} while ($exception && $longText .= "\n--\n\n");
$message->setFullMessage($longText);
} | [
"protected",
"function",
"initExceptionData",
"(",
"Message",
"$",
"message",
",",
"Exception",
"$",
"exception",
")",
"{",
"$",
"message",
"->",
"setLine",
"(",
"$",
"exception",
"->",
"getLine",
"(",
")",
")",
";",
"$",
"message",
"->",
"setFile",
"(",
... | Initializes Exceptiondata with given message
@param Message $message
@param Exception $exception | [
"Initializes",
"Exceptiondata",
"with",
"given",
"message"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Logger.php#L213-L233 |
bzikarsky/gelf-php | src/Gelf/Transport/IgnoreErrorTransportWrapper.php | IgnoreErrorTransportWrapper.send | public function send(Message $message)
{
try {
return $this->transport->send($message);
} catch (\Exception $e) {
$this->lastError = $e;
return 0;
}
} | php | public function send(Message $message)
{
try {
return $this->transport->send($message);
} catch (\Exception $e) {
$this->lastError = $e;
return 0;
}
} | [
"public",
"function",
"send",
"(",
"Message",
"$",
"message",
")",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"transport",
"->",
"send",
"(",
"$",
"message",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
... | Sends a Message over this transport.
@param Message $message
@return int the number of bytes sent | [
"Sends",
"a",
"Message",
"over",
"this",
"transport",
"."
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/IgnoreErrorTransportWrapper.php#L41-L49 |
bzikarsky/gelf-php | src/Gelf/Transport/TcpTransport.php | TcpTransport.send | public function send(Message $message)
{
$rawMessage = $this->getMessageEncoder()->encode($message) . "\0";
// send message in one packet
$this->socketClient->write($rawMessage);
return 1;
} | php | public function send(Message $message)
{
$rawMessage = $this->getMessageEncoder()->encode($message) . "\0";
// send message in one packet
$this->socketClient->write($rawMessage);
return 1;
} | [
"public",
"function",
"send",
"(",
"Message",
"$",
"message",
")",
"{",
"$",
"rawMessage",
"=",
"$",
"this",
"->",
"getMessageEncoder",
"(",
")",
"->",
"encode",
"(",
"$",
"message",
")",
".",
"\"\\0\"",
";",
"// send message in one packet",
"$",
"this",
"... | Sends a Message over this transport
@param Message $message
@return int the number of TCP packets sent | [
"Sends",
"a",
"Message",
"over",
"this",
"transport"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/TcpTransport.php#L91-L99 |
bzikarsky/gelf-php | src/Gelf/Transport/StreamSocketClient.php | StreamSocketClient.initSocket | protected static function initSocket($scheme, $host, $port, array $context)
{
$socketDescriptor = sprintf("%s://%s:%d", $scheme, $host, $port);
$socket = @stream_socket_client(
$socketDescriptor,
$errNo,
$errStr,
static::SOCKET_TIMEOUT,
\STREAM_CLIENT_CONNECT,
stream_context_create($context)
);
if ($socket === false) {
throw new RuntimeException(
sprintf(
"Failed to create socket-client for %s: %s (%s)",
$socketDescriptor,
$errStr,
$errNo
)
);
}
// set non-blocking for UDP
if (strcasecmp("udp", $scheme) == 0) {
stream_set_blocking($socket, 0);
}
return $socket;
} | php | protected static function initSocket($scheme, $host, $port, array $context)
{
$socketDescriptor = sprintf("%s://%s:%d", $scheme, $host, $port);
$socket = @stream_socket_client(
$socketDescriptor,
$errNo,
$errStr,
static::SOCKET_TIMEOUT,
\STREAM_CLIENT_CONNECT,
stream_context_create($context)
);
if ($socket === false) {
throw new RuntimeException(
sprintf(
"Failed to create socket-client for %s: %s (%s)",
$socketDescriptor,
$errStr,
$errNo
)
);
}
// set non-blocking for UDP
if (strcasecmp("udp", $scheme) == 0) {
stream_set_blocking($socket, 0);
}
return $socket;
} | [
"protected",
"static",
"function",
"initSocket",
"(",
"$",
"scheme",
",",
"$",
"host",
",",
"$",
"port",
",",
"array",
"$",
"context",
")",
"{",
"$",
"socketDescriptor",
"=",
"sprintf",
"(",
"\"%s://%s:%d\"",
",",
"$",
"scheme",
",",
"$",
"host",
",",
... | Initializes socket-client
@deprecated deprecated since v1.4.0
@param string $scheme like "udp" or "tcp"
@param string $host
@param integer $port
@param array $context
@return resource
@throws RuntimeException on connection-failure | [
"Initializes",
"socket",
"-",
"client"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/StreamSocketClient.php#L97-L126 |
bzikarsky/gelf-php | src/Gelf/Transport/StreamSocketClient.php | StreamSocketClient.buildSocket | private function buildSocket()
{
$socketDescriptor = sprintf(
"%s://%s:%d",
$this->scheme,
$this->host,
$this->port
);
$socket = @stream_socket_client(
$socketDescriptor,
$errNo,
$errStr,
$this->connectTimeout,
\STREAM_CLIENT_CONNECT,
stream_context_create($this->context)
);
if ($socket === false) {
throw new RuntimeException(
sprintf(
"Failed to create socket-client for %s: %s (%s)",
$socketDescriptor,
$errStr,
$errNo
)
);
}
// set non-blocking for UDP
if (strcasecmp("udp", $this->scheme) == 0) {
stream_set_blocking($socket, 0);
}
return $socket;
} | php | private function buildSocket()
{
$socketDescriptor = sprintf(
"%s://%s:%d",
$this->scheme,
$this->host,
$this->port
);
$socket = @stream_socket_client(
$socketDescriptor,
$errNo,
$errStr,
$this->connectTimeout,
\STREAM_CLIENT_CONNECT,
stream_context_create($this->context)
);
if ($socket === false) {
throw new RuntimeException(
sprintf(
"Failed to create socket-client for %s: %s (%s)",
$socketDescriptor,
$errStr,
$errNo
)
);
}
// set non-blocking for UDP
if (strcasecmp("udp", $this->scheme) == 0) {
stream_set_blocking($socket, 0);
}
return $socket;
} | [
"private",
"function",
"buildSocket",
"(",
")",
"{",
"$",
"socketDescriptor",
"=",
"sprintf",
"(",
"\"%s://%s:%d\"",
",",
"$",
"this",
"->",
"scheme",
",",
"$",
"this",
"->",
"host",
",",
"$",
"this",
"->",
"port",
")",
";",
"$",
"socket",
"=",
"@",
... | Internal function mimicking the behaviour of static::initSocket
which will get new functionality instead of the deprecated
"factory"
@return resource
@throws RuntimeException on connection-failure | [
"Internal",
"function",
"mimicking",
"the",
"behaviour",
"of",
"static",
"::",
"initSocket",
"which",
"will",
"get",
"new",
"functionality",
"instead",
"of",
"the",
"deprecated",
"factory"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/StreamSocketClient.php#L138-L173 |
bzikarsky/gelf-php | src/Gelf/Transport/StreamSocketClient.php | StreamSocketClient.write | public function write($buffer)
{
$buffer = (string) $buffer;
$bufLen = Binary::safeStrlen($buffer);
$socket = $this->getSocket();
$written = 0;
while ($written < $bufLen) {
// PHP's fwrite does not behave nice in regards to errors, so we wrap
// it with a temporary error handler and treat every warning/notice as
// a error
$failed = false;
$errorMessage = "Failed to write to socket";
set_error_handler(function ($errno, $errstr) use (&$failed, &$errorMessage) {
$failed = true;
$errorMessage .= ": $errstr ($errno)";
});
$byteCount = fwrite($socket, Binary::safeSubstr($buffer, $written));
restore_error_handler();
if ($byteCount === 0 && defined('HHVM_VERSION')) {
$failed = true;
}
if ($failed || $byteCount === false) {
throw new \RuntimeException($errorMessage);
}
$written += $byteCount;
}
return $written;
} | php | public function write($buffer)
{
$buffer = (string) $buffer;
$bufLen = Binary::safeStrlen($buffer);
$socket = $this->getSocket();
$written = 0;
while ($written < $bufLen) {
// PHP's fwrite does not behave nice in regards to errors, so we wrap
// it with a temporary error handler and treat every warning/notice as
// a error
$failed = false;
$errorMessage = "Failed to write to socket";
set_error_handler(function ($errno, $errstr) use (&$failed, &$errorMessage) {
$failed = true;
$errorMessage .= ": $errstr ($errno)";
});
$byteCount = fwrite($socket, Binary::safeSubstr($buffer, $written));
restore_error_handler();
if ($byteCount === 0 && defined('HHVM_VERSION')) {
$failed = true;
}
if ($failed || $byteCount === false) {
throw new \RuntimeException($errorMessage);
}
$written += $byteCount;
}
return $written;
} | [
"public",
"function",
"write",
"(",
"$",
"buffer",
")",
"{",
"$",
"buffer",
"=",
"(",
"string",
")",
"$",
"buffer",
";",
"$",
"bufLen",
"=",
"Binary",
"::",
"safeStrlen",
"(",
"$",
"buffer",
")",
";",
"$",
"socket",
"=",
"$",
"this",
"->",
"getSock... | Writes a given string to the socket and returns the
number of written bytes
@param string $buffer
@return int
@throws RuntimeException on write-failure | [
"Writes",
"a",
"given",
"string",
"to",
"the",
"socket",
"and",
"returns",
"the",
"number",
"of",
"written",
"bytes"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/StreamSocketClient.php#L200-L234 |
bzikarsky/gelf-php | src/Gelf/Transport/StreamSocketClient.php | StreamSocketClient.close | public function close()
{
if (!is_resource($this->socket)) {
return;
}
fclose($this->socket);
$this->socket = null;
} | php | public function close()
{
if (!is_resource($this->socket)) {
return;
}
fclose($this->socket);
$this->socket = null;
} | [
"public",
"function",
"close",
"(",
")",
"{",
"if",
"(",
"!",
"is_resource",
"(",
"$",
"this",
"->",
"socket",
")",
")",
"{",
"return",
";",
"}",
"fclose",
"(",
"$",
"this",
"->",
"socket",
")",
";",
"$",
"this",
"->",
"socket",
"=",
"null",
";",... | Closes underlying socket explicitly | [
"Closes",
"underlying",
"socket",
"explicitly"
] | train | https://github.com/bzikarsky/gelf-php/blob/2344540be1db5e882990d527588649e065efbde0/src/Gelf/Transport/StreamSocketClient.php#L251-L259 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculatorServiceProvider.php | VatCalculatorServiceProvider.publishConfig | protected function publishConfig()
{
// Publish config files
$this->publishes([
__DIR__.'/../../config/config.php' => config_path('vat_calculator.php'),
__DIR__.'/../../public/js/vat_calculator.js' => public_path('js/vat_calculator.js'),
]);
$this->publishes([
__DIR__.'/../../public/js/vat_calculator.js' => base_path('resources/assets/js/vat_calculator.js'),
], 'vatcalculator-spark');
} | php | protected function publishConfig()
{
// Publish config files
$this->publishes([
__DIR__.'/../../config/config.php' => config_path('vat_calculator.php'),
__DIR__.'/../../public/js/vat_calculator.js' => public_path('js/vat_calculator.js'),
]);
$this->publishes([
__DIR__.'/../../public/js/vat_calculator.js' => base_path('resources/assets/js/vat_calculator.js'),
], 'vatcalculator-spark');
} | [
"protected",
"function",
"publishConfig",
"(",
")",
"{",
"// Publish config files",
"$",
"this",
"->",
"publishes",
"(",
"[",
"__DIR__",
".",
"'/../../config/config.php'",
"=>",
"config_path",
"(",
"'vat_calculator.php'",
")",
",",
"__DIR__",
".",
"'/../../public/js/v... | Publish Teamwork configuration. | [
"Publish",
"Teamwork",
"configuration",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculatorServiceProvider.php#L40-L51 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculatorServiceProvider.php | VatCalculatorServiceProvider.registerVatCalculator | protected function registerVatCalculator()
{
$this->app->bind('vatcalculator', '\Mpociot\VatCalculator\VatCalculator');
$this->app->bind('\Mpociot\VatCalculator\VatCalculator', function ($app) {
$config = $app->make('Illuminate\Contracts\Config\Repository');
return new \Mpociot\VatCalculator\VatCalculator($config);
});
} | php | protected function registerVatCalculator()
{
$this->app->bind('vatcalculator', '\Mpociot\VatCalculator\VatCalculator');
$this->app->bind('\Mpociot\VatCalculator\VatCalculator', function ($app) {
$config = $app->make('Illuminate\Contracts\Config\Repository');
return new \Mpociot\VatCalculator\VatCalculator($config);
});
} | [
"protected",
"function",
"registerVatCalculator",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'vatcalculator'",
",",
"'\\Mpociot\\VatCalculator\\VatCalculator'",
")",
";",
"$",
"this",
"->",
"app",
"->",
"bind",
"(",
"'\\Mpociot\\VatCalculator\\VatC... | Register the application bindings.
@return void | [
"Register",
"the",
"application",
"bindings",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculatorServiceProvider.php#L70-L79 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculatorServiceProvider.php | VatCalculatorServiceProvider.registerFacade | public function registerFacade()
{
$this->app->booting(function () {
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('VatCalculator', 'Mpociot\VatCalculator\Facades\VatCalculator');
});
} | php | public function registerFacade()
{
$this->app->booting(function () {
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('VatCalculator', 'Mpociot\VatCalculator\Facades\VatCalculator');
});
} | [
"public",
"function",
"registerFacade",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"->",
"booting",
"(",
"function",
"(",
")",
"{",
"$",
"loader",
"=",
"\\",
"Illuminate",
"\\",
"Foundation",
"\\",
"AliasLoader",
"::",
"getInstance",
"(",
")",
";",
"$",
... | Register the vault facade without the user having to add it to the app.php file.
@return void | [
"Register",
"the",
"vault",
"facade",
"without",
"the",
"user",
"having",
"to",
"add",
"it",
"to",
"the",
"app",
".",
"php",
"file",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculatorServiceProvider.php#L86-L92 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.getClientIP | private function getClientIP()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
$clientIpAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']) {
$clientIpAddress = $_SERVER['REMOTE_ADDR'];
} else {
$clientIpAddress = '';
}
return $clientIpAddress;
} | php | private function getClientIP()
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
$clientIpAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']) {
$clientIpAddress = $_SERVER['REMOTE_ADDR'];
} else {
$clientIpAddress = '';
}
return $clientIpAddress;
} | [
"private",
"function",
"getClientIP",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_FOR'",
"]",
")",
"&&",
"$",
"_SERVER",
"[",
"'HTTP_X_FORWARDED_FOR'",
"]",
")",
"{",
"$",
"clientIpAddress",
"=",
"$",
"_SERVER",
"[",
"'H... | Finds the client IP address.
@return mixed | [
"Finds",
"the",
"client",
"IP",
"address",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L403-L414 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.getIPBasedCountry | public function getIPBasedCountry()
{
$ip = $this->getClientIP();
$url = self::GEOCODE_SERVICE_URL.$ip;
$result = file_get_contents($url);
switch ($result[0]) {
case '1':
$data = explode(';', $result);
return $data[1];
break;
default:
return false;
}
} | php | public function getIPBasedCountry()
{
$ip = $this->getClientIP();
$url = self::GEOCODE_SERVICE_URL.$ip;
$result = file_get_contents($url);
switch ($result[0]) {
case '1':
$data = explode(';', $result);
return $data[1];
break;
default:
return false;
}
} | [
"public",
"function",
"getIPBasedCountry",
"(",
")",
"{",
"$",
"ip",
"=",
"$",
"this",
"->",
"getClientIP",
"(",
")",
";",
"$",
"url",
"=",
"self",
"::",
"GEOCODE_SERVICE_URL",
".",
"$",
"ip",
";",
"$",
"result",
"=",
"file_get_contents",
"(",
"$",
"ur... | Returns the ISO 3166-1 alpha-2 two letter
country code for the client IP. If the
IP can't be resolved it returns false.
@return bool|string | [
"Returns",
"the",
"ISO",
"3166",
"-",
"1",
"alpha",
"-",
"2",
"two",
"letter",
"country",
"code",
"for",
"the",
"client",
"IP",
".",
"If",
"the",
"IP",
"can",
"t",
"be",
"resolved",
"it",
"returns",
"false",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L423-L437 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.shouldCollectVAT | public function shouldCollectVAT($countryCode)
{
$taxKey = 'vat_calculator.rules.'.strtoupper($countryCode);
return isset($this->taxRules[strtoupper($countryCode)]) || (isset($this->config) && $this->config->has($taxKey));
} | php | public function shouldCollectVAT($countryCode)
{
$taxKey = 'vat_calculator.rules.'.strtoupper($countryCode);
return isset($this->taxRules[strtoupper($countryCode)]) || (isset($this->config) && $this->config->has($taxKey));
} | [
"public",
"function",
"shouldCollectVAT",
"(",
"$",
"countryCode",
")",
"{",
"$",
"taxKey",
"=",
"'vat_calculator.rules.'",
".",
"strtoupper",
"(",
"$",
"countryCode",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"taxRules",
"[",
"strtoupper",
"(",
"... | Determines if you need to collect VAT for the given country code.
@param $countryCode
@return bool | [
"Determines",
"if",
"you",
"need",
"to",
"collect",
"VAT",
"for",
"the",
"given",
"country",
"code",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L446-L451 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.calculate | public function calculate($netPrice, $countryCode = null, $postalCode = null, $company = null, $type = null)
{
if ($countryCode) {
$this->setCountryCode($countryCode);
}
if ($postalCode) {
$this->setPostalCode($postalCode);
}
if (!is_null($company) && $company !== $this->isCompany()) {
$this->setCompany($company);
}
$this->netPrice = floatval($netPrice);
$this->taxRate = $this->getTaxRateForLocation($this->getCountryCode(), $this->getPostalCode(), $this->isCompany(), $type);
$this->taxValue = $this->taxRate * $this->netPrice;
$this->value = $this->netPrice + $this->taxValue;
return $this->value;
} | php | public function calculate($netPrice, $countryCode = null, $postalCode = null, $company = null, $type = null)
{
if ($countryCode) {
$this->setCountryCode($countryCode);
}
if ($postalCode) {
$this->setPostalCode($postalCode);
}
if (!is_null($company) && $company !== $this->isCompany()) {
$this->setCompany($company);
}
$this->netPrice = floatval($netPrice);
$this->taxRate = $this->getTaxRateForLocation($this->getCountryCode(), $this->getPostalCode(), $this->isCompany(), $type);
$this->taxValue = $this->taxRate * $this->netPrice;
$this->value = $this->netPrice + $this->taxValue;
return $this->value;
} | [
"public",
"function",
"calculate",
"(",
"$",
"netPrice",
",",
"$",
"countryCode",
"=",
"null",
",",
"$",
"postalCode",
"=",
"null",
",",
"$",
"company",
"=",
"null",
",",
"$",
"type",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"countryCode",
")",
"{",
... | Calculate the VAT based on the net price, country code and indication if the
customer is a company or not.
@param int|float $netPrice The net price to use for the calculation
@param null|string $countryCode The country code to use for the rate lookup
@param null|string $postalCode The postal code to use for the rate exception lookup
@param null|bool $company
@param null|string $type The type can be low or high
@return float | [
"Calculate",
"the",
"VAT",
"based",
"on",
"the",
"net",
"price",
"country",
"code",
"and",
"indication",
"if",
"the",
"customer",
"is",
"a",
"company",
"or",
"not",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L465-L482 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.getTaxRateForCountry | public function getTaxRateForCountry($countryCode, $company = false, $type = null)
{
return $this->getTaxRateForLocation($countryCode, null, $company, $type);
} | php | public function getTaxRateForCountry($countryCode, $company = false, $type = null)
{
return $this->getTaxRateForLocation($countryCode, null, $company, $type);
} | [
"public",
"function",
"getTaxRateForCountry",
"(",
"$",
"countryCode",
",",
"$",
"company",
"=",
"false",
",",
"$",
"type",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"getTaxRateForLocation",
"(",
"$",
"countryCode",
",",
"null",
",",
"$",
"compan... | Returns the tax rate for the given country code.
This method is used to allow backwards compatibility.
@param $countryCode
@param bool $company
@param string $type
@return float | [
"Returns",
"the",
"tax",
"rate",
"for",
"the",
"given",
"country",
"code",
".",
"This",
"method",
"is",
"used",
"to",
"allow",
"backwards",
"compatibility",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L598-L601 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.getTaxRateForLocation | public function getTaxRateForLocation($countryCode, $postalCode = null, $company = false, $type = null)
{
if ($company && strtoupper($countryCode) !== strtoupper($this->businessCountryCode)) {
return 0;
}
$taxKey = 'vat_calculator.rules.'.strtoupper($countryCode);
if (isset($this->config) && $this->config->has($taxKey)) {
return $this->config->get($taxKey, 0);
}
if (isset($this->postalCodeExceptions[$countryCode]) && $postalCode !== null) {
foreach ($this->postalCodeExceptions[$countryCode] as $postalCodeException) {
if (!preg_match($postalCodeException['postalCode'], $postalCode)) {
continue;
}
if (isset($postalCodeException['name'])) {
return $this->taxRules[$postalCodeException['code']]['exceptions'][$postalCodeException['name']];
}
return $this->taxRules[$postalCodeException['code']]['rate'];
}
}
if ($type !== null) {
return isset($this->taxRules[strtoupper($countryCode)]['rates'][$type]) ? $this->taxRules[strtoupper($countryCode)]['rates'][$type] : 0;
}
return isset($this->taxRules[strtoupper($countryCode)]['rate']) ? $this->taxRules[strtoupper($countryCode)]['rate'] : 0;
} | php | public function getTaxRateForLocation($countryCode, $postalCode = null, $company = false, $type = null)
{
if ($company && strtoupper($countryCode) !== strtoupper($this->businessCountryCode)) {
return 0;
}
$taxKey = 'vat_calculator.rules.'.strtoupper($countryCode);
if (isset($this->config) && $this->config->has($taxKey)) {
return $this->config->get($taxKey, 0);
}
if (isset($this->postalCodeExceptions[$countryCode]) && $postalCode !== null) {
foreach ($this->postalCodeExceptions[$countryCode] as $postalCodeException) {
if (!preg_match($postalCodeException['postalCode'], $postalCode)) {
continue;
}
if (isset($postalCodeException['name'])) {
return $this->taxRules[$postalCodeException['code']]['exceptions'][$postalCodeException['name']];
}
return $this->taxRules[$postalCodeException['code']]['rate'];
}
}
if ($type !== null) {
return isset($this->taxRules[strtoupper($countryCode)]['rates'][$type]) ? $this->taxRules[strtoupper($countryCode)]['rates'][$type] : 0;
}
return isset($this->taxRules[strtoupper($countryCode)]['rate']) ? $this->taxRules[strtoupper($countryCode)]['rate'] : 0;
} | [
"public",
"function",
"getTaxRateForLocation",
"(",
"$",
"countryCode",
",",
"$",
"postalCode",
"=",
"null",
",",
"$",
"company",
"=",
"false",
",",
"$",
"type",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"company",
"&&",
"strtoupper",
"(",
"$",
"countryCode... | Returns the tax rate for the given country code.
If a postal code is provided, it will try to lookup the different
postal code exceptions that are possible.
@param string $countryCode
@param string|null $postalCode
@param bool|false $company
@param string|null $type
@return float | [
"Returns",
"the",
"tax",
"rate",
"for",
"the",
"given",
"country",
"code",
".",
"If",
"a",
"postal",
"code",
"is",
"provided",
"it",
"will",
"try",
"to",
"lookup",
"the",
"different",
"postal",
"code",
"exceptions",
"that",
"are",
"possible",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L615-L643 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.isValidVATNumber | public function isValidVATNumber($vatNumber)
{
$details = self::getVATDetails($vatNumber);
if ($details) {
return $details->valid;
} else {
return false;
}
} | php | public function isValidVATNumber($vatNumber)
{
$details = self::getVATDetails($vatNumber);
if ($details) {
return $details->valid;
} else {
return false;
}
} | [
"public",
"function",
"isValidVATNumber",
"(",
"$",
"vatNumber",
")",
"{",
"$",
"details",
"=",
"self",
"::",
"getVATDetails",
"(",
"$",
"vatNumber",
")",
";",
"if",
"(",
"$",
"details",
")",
"{",
"return",
"$",
"details",
"->",
"valid",
";",
"}",
"els... | @param $vatNumber
@throws VATCheckUnavailableException
@return bool | [
"@param",
"$vatNumber"
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L660-L669 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.getVATDetails | public function getVATDetails($vatNumber)
{
$vatNumber = str_replace([' ', '-', '.', ','], '', trim($vatNumber));
$countryCode = substr($vatNumber, 0, 2);
$vatNumber = substr($vatNumber, 2);
$this->initSoapClient();
$client = $this->soapClient;
if ($client) {
try {
$result = $client->checkVat([
'countryCode' => $countryCode,
'vatNumber' => $vatNumber,
]);
return $result;
} catch (SoapFault $e) {
if (isset($this->config) && $this->config->get('vat_calculator.forward_soap_faults')) {
throw new VATCheckUnavailableException($e->getMessage(), $e->getCode(), $e->getPrevious());
}
return false;
}
}
throw new VATCheckUnavailableException('The VAT check service is currently unavailable. Please try again later.');
} | php | public function getVATDetails($vatNumber)
{
$vatNumber = str_replace([' ', '-', '.', ','], '', trim($vatNumber));
$countryCode = substr($vatNumber, 0, 2);
$vatNumber = substr($vatNumber, 2);
$this->initSoapClient();
$client = $this->soapClient;
if ($client) {
try {
$result = $client->checkVat([
'countryCode' => $countryCode,
'vatNumber' => $vatNumber,
]);
return $result;
} catch (SoapFault $e) {
if (isset($this->config) && $this->config->get('vat_calculator.forward_soap_faults')) {
throw new VATCheckUnavailableException($e->getMessage(), $e->getCode(), $e->getPrevious());
}
return false;
}
}
throw new VATCheckUnavailableException('The VAT check service is currently unavailable. Please try again later.');
} | [
"public",
"function",
"getVATDetails",
"(",
"$",
"vatNumber",
")",
"{",
"$",
"vatNumber",
"=",
"str_replace",
"(",
"[",
"' '",
",",
"'-'",
",",
"'.'",
",",
"','",
"]",
",",
"''",
",",
"trim",
"(",
"$",
"vatNumber",
")",
")",
";",
"$",
"countryCode",
... | @param $vatNumber
@throws VATCheckUnavailableException
@return object|false | [
"@param",
"$vatNumber"
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L678-L701 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/VatCalculator.php | VatCalculator.initSoapClient | public function initSoapClient()
{
if (is_object($this->soapClient) || $this->soapClient === false) {
return;
}
try {
$this->soapClient = new SoapClient(self::VAT_SERVICE_URL);
} catch (SoapFault $e) {
if (isset($this->config) && $this->config->get('vat_calculator.forward_soap_faults')) {
throw new VATCheckUnavailableException($e->getMessage(), $e->getCode(), $e->getPrevious());
}
$this->soapClient = false;
}
} | php | public function initSoapClient()
{
if (is_object($this->soapClient) || $this->soapClient === false) {
return;
}
try {
$this->soapClient = new SoapClient(self::VAT_SERVICE_URL);
} catch (SoapFault $e) {
if (isset($this->config) && $this->config->get('vat_calculator.forward_soap_faults')) {
throw new VATCheckUnavailableException($e->getMessage(), $e->getCode(), $e->getPrevious());
}
$this->soapClient = false;
}
} | [
"public",
"function",
"initSoapClient",
"(",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"this",
"->",
"soapClient",
")",
"||",
"$",
"this",
"->",
"soapClient",
"===",
"false",
")",
"{",
"return",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"soapClient",
... | @throws VATCheckUnavailableException
@return void | [
"@throws",
"VATCheckUnavailableException"
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/VatCalculator.php#L708-L722 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/Traits/BillableWithinTheEU.php | BillableWithinTheEU.setTaxForCountry | public function setTaxForCountry($countryCode, $company = false)
{
$this->userCountryCode = $countryCode;
$this->userIsCompany = $company;
return $this;
} | php | public function setTaxForCountry($countryCode, $company = false)
{
$this->userCountryCode = $countryCode;
$this->userIsCompany = $company;
return $this;
} | [
"public",
"function",
"setTaxForCountry",
"(",
"$",
"countryCode",
",",
"$",
"company",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"userCountryCode",
"=",
"$",
"countryCode",
";",
"$",
"this",
"->",
"userIsCompany",
"=",
"$",
"company",
";",
"return",
"$",... | @param string $countryCode
@param bool|false $company
@return $this | [
"@param",
"string",
"$countryCode",
"@param",
"bool|false",
"$company"
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/Traits/BillableWithinTheEU.php#L30-L36 |
mpociot/vat-calculator | src/Mpociot/VatCalculator/Validators/VatCalculatorValidatorExtension.php | VatCalculatorValidatorExtension.validateVatNumber | public function validateVatNumber($attribute, $value, $parameters, $validator)
{
$validator->setCustomMessages([
'vat_number' => $validator->getTranslator()->get('vatnumber-validator::validation.vat_number'),
]);
try {
return VatCalculator::isValidVATNumber($value);
} catch (VATCheckUnavailableException $e) {
return false;
}
} | php | public function validateVatNumber($attribute, $value, $parameters, $validator)
{
$validator->setCustomMessages([
'vat_number' => $validator->getTranslator()->get('vatnumber-validator::validation.vat_number'),
]);
try {
return VatCalculator::isValidVATNumber($value);
} catch (VATCheckUnavailableException $e) {
return false;
}
} | [
"public",
"function",
"validateVatNumber",
"(",
"$",
"attribute",
",",
"$",
"value",
",",
"$",
"parameters",
",",
"$",
"validator",
")",
"{",
"$",
"validator",
"->",
"setCustomMessages",
"(",
"[",
"'vat_number'",
"=>",
"$",
"validator",
"->",
"getTranslator",
... | Usage: vat_number.
@param string $attribute
@param mixed $value
@param array $parameters
@param $validator
@return bool | [
"Usage",
":",
"vat_number",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/Mpociot/VatCalculator/Validators/VatCalculatorValidatorExtension.php#L21-L32 |
mpociot/vat-calculator | src/controllers/Controller.php | Controller.getTaxRateForLocation | public function getTaxRateForLocation($countryCode = null, $postalCode = null)
{
return [
'tax_rate' => $this->calculator->getTaxRateForLocation($countryCode, $postalCode),
];
} | php | public function getTaxRateForLocation($countryCode = null, $postalCode = null)
{
return [
'tax_rate' => $this->calculator->getTaxRateForLocation($countryCode, $postalCode),
];
} | [
"public",
"function",
"getTaxRateForLocation",
"(",
"$",
"countryCode",
"=",
"null",
",",
"$",
"postalCode",
"=",
"null",
")",
"{",
"return",
"[",
"'tax_rate'",
"=>",
"$",
"this",
"->",
"calculator",
"->",
"getTaxRateForLocation",
"(",
"$",
"countryCode",
",",... | Returns the tax rate for the given country code and postal code.
@return \Illuminate\Http\Response | [
"Returns",
"the",
"tax",
"rate",
"for",
"the",
"given",
"country",
"code",
"and",
"postal",
"code",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/controllers/Controller.php#L29-L34 |
mpociot/vat-calculator | src/controllers/Controller.php | Controller.calculateGrossPrice | public function calculateGrossPrice(Request $request)
{
if (!$request->has('netPrice')) {
return Response::json([
'error' => "The 'netPrice' parameter is missing",
], 422);
}
$valid_vat_id = null;
$valid_company = false;
if ($request->has('vat_number')) {
$valid_company = $this->validateVATID($request->get('vat_number'));
$valid_company = $valid_company['is_valid'];
$valid_vat_id = $valid_company;
}
return [
'gross_price' => $this->calculator->calculate($request->get('netPrice'), $request->get('country'), $request->get('postal_code'), $valid_company),
'net_price' => $this->calculator->getNetPrice(),
'tax_rate' => $this->calculator->getTaxRate(),
'tax_value' => $this->calculator->getTaxValue(),
'valid_vat_id' => $valid_vat_id,
];
} | php | public function calculateGrossPrice(Request $request)
{
if (!$request->has('netPrice')) {
return Response::json([
'error' => "The 'netPrice' parameter is missing",
], 422);
}
$valid_vat_id = null;
$valid_company = false;
if ($request->has('vat_number')) {
$valid_company = $this->validateVATID($request->get('vat_number'));
$valid_company = $valid_company['is_valid'];
$valid_vat_id = $valid_company;
}
return [
'gross_price' => $this->calculator->calculate($request->get('netPrice'), $request->get('country'), $request->get('postal_code'), $valid_company),
'net_price' => $this->calculator->getNetPrice(),
'tax_rate' => $this->calculator->getTaxRate(),
'tax_value' => $this->calculator->getTaxValue(),
'valid_vat_id' => $valid_vat_id,
];
} | [
"public",
"function",
"calculateGrossPrice",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"$",
"request",
"->",
"has",
"(",
"'netPrice'",
")",
")",
"{",
"return",
"Response",
"::",
"json",
"(",
"[",
"'error'",
"=>",
"\"The 'netPrice' parameter i... | Returns the tax rate for the given country.
@param Request $request
@return \Illuminate\Http\Response | [
"Returns",
"the",
"tax",
"rate",
"for",
"the",
"given",
"country",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/controllers/Controller.php#L43-L66 |
mpociot/vat-calculator | src/controllers/Controller.php | Controller.validateVATID | public function validateVATID($vat_id)
{
try {
$isValid = $this->calculator->isValidVATNumber($vat_id);
$message = '';
} catch (VATCheckUnavailableException $e) {
$isValid = false;
$message = $e->getMessage();
}
return [
'vat_id' => $vat_id,
'is_valid' => $isValid,
'message' => $message,
];
} | php | public function validateVATID($vat_id)
{
try {
$isValid = $this->calculator->isValidVATNumber($vat_id);
$message = '';
} catch (VATCheckUnavailableException $e) {
$isValid = false;
$message = $e->getMessage();
}
return [
'vat_id' => $vat_id,
'is_valid' => $isValid,
'message' => $message,
];
} | [
"public",
"function",
"validateVATID",
"(",
"$",
"vat_id",
")",
"{",
"try",
"{",
"$",
"isValid",
"=",
"$",
"this",
"->",
"calculator",
"->",
"isValidVATNumber",
"(",
"$",
"vat_id",
")",
";",
"$",
"message",
"=",
"''",
";",
"}",
"catch",
"(",
"VATCheckU... | Returns the tax rate for the given country.
@param string $vat_id
@throws \Mpociot\VatCalculator\Exceptions\VATCheckUnavailableException
@return \Illuminate\Http\Response | [
"Returns",
"the",
"tax",
"rate",
"for",
"the",
"given",
"country",
"."
] | train | https://github.com/mpociot/vat-calculator/blob/5d7d98ce4f0757852e9d59b001d03c68d08fa653/src/controllers/Controller.php#L89-L104 |
psr7-sessions/storageless | src/Storageless/Http/SessionMiddleware.php | SessionMiddleware.fromSymmetricKeyDefaults | public static function fromSymmetricKeyDefaults(string $symmetricKey, int $expirationTime) : self
{
return new self(
new Signer\Hmac\Sha256(),
$symmetricKey,
$symmetricKey,
SetCookie::create(self::DEFAULT_COOKIE)
->withSecure(true)
->withHttpOnly(true)
->withSameSite(SameSite::lax())
->withPath('/'),
new Parser(),
$expirationTime,
new SystemClock()
);
} | php | public static function fromSymmetricKeyDefaults(string $symmetricKey, int $expirationTime) : self
{
return new self(
new Signer\Hmac\Sha256(),
$symmetricKey,
$symmetricKey,
SetCookie::create(self::DEFAULT_COOKIE)
->withSecure(true)
->withHttpOnly(true)
->withSameSite(SameSite::lax())
->withPath('/'),
new Parser(),
$expirationTime,
new SystemClock()
);
} | [
"public",
"static",
"function",
"fromSymmetricKeyDefaults",
"(",
"string",
"$",
"symmetricKey",
",",
"int",
"$",
"expirationTime",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"new",
"Signer",
"\\",
"Hmac",
"\\",
"Sha256",
"(",
")",
",",
"$",
"symm... | This constructor simplifies instantiation when using HTTPS (REQUIRED!) and symmetric key encryption | [
"This",
"constructor",
"simplifies",
"instantiation",
"when",
"using",
"HTTPS",
"(",
"REQUIRED!",
")",
"and",
"symmetric",
"key",
"encryption"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Http/SessionMiddleware.php#L96-L111 |
psr7-sessions/storageless | src/Storageless/Http/SessionMiddleware.php | SessionMiddleware.fromAsymmetricKeyDefaults | public static function fromAsymmetricKeyDefaults(
string $privateRsaKey,
string $publicRsaKey,
int $expirationTime
) : self {
return new self(
new Signer\Rsa\Sha256(),
$privateRsaKey,
$publicRsaKey,
SetCookie::create(self::DEFAULT_COOKIE)
->withSecure(true)
->withHttpOnly(true)
->withSameSite(SameSite::lax())
->withPath('/'),
new Parser(),
$expirationTime,
new SystemClock()
);
} | php | public static function fromAsymmetricKeyDefaults(
string $privateRsaKey,
string $publicRsaKey,
int $expirationTime
) : self {
return new self(
new Signer\Rsa\Sha256(),
$privateRsaKey,
$publicRsaKey,
SetCookie::create(self::DEFAULT_COOKIE)
->withSecure(true)
->withHttpOnly(true)
->withSameSite(SameSite::lax())
->withPath('/'),
new Parser(),
$expirationTime,
new SystemClock()
);
} | [
"public",
"static",
"function",
"fromAsymmetricKeyDefaults",
"(",
"string",
"$",
"privateRsaKey",
",",
"string",
"$",
"publicRsaKey",
",",
"int",
"$",
"expirationTime",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"new",
"Signer",
"\\",
"Rsa",
"\\",
... | This constructor simplifies instantiation when using HTTPS (REQUIRED!) and asymmetric key encryption
based on RSA keys | [
"This",
"constructor",
"simplifies",
"instantiation",
"when",
"using",
"HTTPS",
"(",
"REQUIRED!",
")",
"and",
"asymmetric",
"key",
"encryption",
"based",
"on",
"RSA",
"keys"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Http/SessionMiddleware.php#L117-L135 |
psr7-sessions/storageless | src/Storageless/Http/SessionMiddleware.php | SessionMiddleware.process | public function process(Request $request, RequestHandlerInterface $delegate) : Response
{
$token = $this->parseToken($request);
$sessionContainer = LazySession::fromContainerBuildingCallback(function () use ($token) : SessionInterface {
return $this->extractSessionContainer($token);
});
return $this->appendToken(
$sessionContainer,
$delegate->handle($request->withAttribute(self::SESSION_ATTRIBUTE, $sessionContainer)),
$token
);
} | php | public function process(Request $request, RequestHandlerInterface $delegate) : Response
{
$token = $this->parseToken($request);
$sessionContainer = LazySession::fromContainerBuildingCallback(function () use ($token) : SessionInterface {
return $this->extractSessionContainer($token);
});
return $this->appendToken(
$sessionContainer,
$delegate->handle($request->withAttribute(self::SESSION_ATTRIBUTE, $sessionContainer)),
$token
);
} | [
"public",
"function",
"process",
"(",
"Request",
"$",
"request",
",",
"RequestHandlerInterface",
"$",
"delegate",
")",
":",
"Response",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"parseToken",
"(",
"$",
"request",
")",
";",
"$",
"sessionContainer",
"=",
"L... | {@inheritdoc}
@throws \BadMethodCallException
@throws \InvalidArgumentException | [
"{",
"@inheritdoc",
"}"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Http/SessionMiddleware.php#L143-L155 |
psr7-sessions/storageless | src/Storageless/Http/SessionMiddleware.php | SessionMiddleware.parseToken | private function parseToken(Request $request) : ?Token
{
$cookies = $request->getCookieParams();
$cookieName = $this->defaultCookie->getName();
if (! isset($cookies[$cookieName])) {
return null;
}
try {
$token = $this->tokenParser->parse($cookies[$cookieName]);
} catch (\InvalidArgumentException $invalidToken) {
return null;
}
if (! $token->validate(new ValidationData())) {
return null;
}
return $token;
} | php | private function parseToken(Request $request) : ?Token
{
$cookies = $request->getCookieParams();
$cookieName = $this->defaultCookie->getName();
if (! isset($cookies[$cookieName])) {
return null;
}
try {
$token = $this->tokenParser->parse($cookies[$cookieName]);
} catch (\InvalidArgumentException $invalidToken) {
return null;
}
if (! $token->validate(new ValidationData())) {
return null;
}
return $token;
} | [
"private",
"function",
"parseToken",
"(",
"Request",
"$",
"request",
")",
":",
"?",
"Token",
"{",
"$",
"cookies",
"=",
"$",
"request",
"->",
"getCookieParams",
"(",
")",
";",
"$",
"cookieName",
"=",
"$",
"this",
"->",
"defaultCookie",
"->",
"getName",
"(... | Extract the token from the given request object | [
"Extract",
"the",
"token",
"from",
"the",
"given",
"request",
"object"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Http/SessionMiddleware.php#L160-L180 |
psr7-sessions/storageless | src/Storageless/Session/DefaultSessionData.php | DefaultSessionData.set | public function set(string $key, $value) : void
{
$this->data[$key] = self::convertValueToScalar($value);
} | php | public function set(string $key, $value) : void
{
$this->data[$key] = self::convertValueToScalar($value);
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"key",
",",
"$",
"value",
")",
":",
"void",
"{",
"$",
"this",
"->",
"data",
"[",
"$",
"key",
"]",
"=",
"self",
"::",
"convertValueToScalar",
"(",
"$",
"value",
")",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Session/DefaultSessionData.php#L94-L97 |
psr7-sessions/storageless | src/Storageless/Session/DefaultSessionData.php | DefaultSessionData.get | public function get(string $key, $default = null)
{
if (! $this->has($key)) {
return self::convertValueToScalar($default);
}
return $this->data[$key];
} | php | public function get(string $key, $default = null)
{
if (! $this->has($key)) {
return self::convertValueToScalar($default);
}
return $this->data[$key];
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"key",
",",
"$",
"default",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"has",
"(",
"$",
"key",
")",
")",
"{",
"return",
"self",
"::",
"convertValueToScalar",
"(",
"$",
"default",
")",
... | {@inheritDoc} | [
"{"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Session/DefaultSessionData.php#L102-L109 |
psr7-sessions/storageless | src/Storageless/Session/DefaultSessionData.php | DefaultSessionData.convertValueToScalar | private static function convertValueToScalar($value)
{
$jsonScalar = json_encode($value, JSON_PRESERVE_ZERO_FRACTION);
if (! is_string($jsonScalar)) {
// @TODO use PHP 7.3 and JSON_THROW_ON_ERROR instead? https://wiki.php.net/rfc/json_throw_on_error
throw new InvalidArgumentException(sprintf(
'Could not serialise given value %s due to %s (%s)',
var_export($value, true),
json_last_error_msg(),
json_last_error()
));
}
return json_decode($jsonScalar, true);
} | php | private static function convertValueToScalar($value)
{
$jsonScalar = json_encode($value, JSON_PRESERVE_ZERO_FRACTION);
if (! is_string($jsonScalar)) {
// @TODO use PHP 7.3 and JSON_THROW_ON_ERROR instead? https://wiki.php.net/rfc/json_throw_on_error
throw new InvalidArgumentException(sprintf(
'Could not serialise given value %s due to %s (%s)',
var_export($value, true),
json_last_error_msg(),
json_last_error()
));
}
return json_decode($jsonScalar, true);
} | [
"private",
"static",
"function",
"convertValueToScalar",
"(",
"$",
"value",
")",
"{",
"$",
"jsonScalar",
"=",
"json_encode",
"(",
"$",
"value",
",",
"JSON_PRESERVE_ZERO_FRACTION",
")",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"jsonScalar",
")",
")",
"{",
... | @param int|bool|string|float|mixed[]|object|\JsonSerializable|null $value
@return int|bool|string|float|mixed[] | [
"@param",
"int|bool|string|float|mixed",
"[]",
"|object|",
"\\",
"JsonSerializable|null",
"$value"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Session/DefaultSessionData.php#L164-L179 |
psr7-sessions/storageless | src/Storageless/Session/LazySession.php | LazySession.set | public function set(string $key, $value) : void
{
$this->getRealSession()->set($key, $value);
} | php | public function set(string $key, $value) : void
{
$this->getRealSession()->set($key, $value);
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"key",
",",
"$",
"value",
")",
":",
"void",
"{",
"$",
"this",
"->",
"getRealSession",
"(",
")",
"->",
"set",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/psr7-sessions/storageless/blob/3f1598234ed2c8df29fd3e02d32fca18da744613/src/Storageless/Session/LazySession.php#L54-L57 |
nunomaduro/laravel-console-menu | src/Menu.php | Menu.addOption | public function addOption($value, string $label): Menu
{
$this->addMenuItem(
new MenuOption(
$value,
$label,
function (CliMenu $menu) {
$this->result = $menu->getSelectedItem()->getValue();
$menu->close();
}
)
);
return $this;
} | php | public function addOption($value, string $label): Menu
{
$this->addMenuItem(
new MenuOption(
$value,
$label,
function (CliMenu $menu) {
$this->result = $menu->getSelectedItem()->getValue();
$menu->close();
}
)
);
return $this;
} | [
"public",
"function",
"addOption",
"(",
"$",
"value",
",",
"string",
"$",
"label",
")",
":",
"Menu",
"{",
"$",
"this",
"->",
"addMenuItem",
"(",
"new",
"MenuOption",
"(",
"$",
"value",
",",
"$",
"label",
",",
"function",
"(",
"CliMenu",
"$",
"menu",
... | Adds a new option.
@param mixed $value
@param string $label
@return \NunoMaduro\LaravelConsoleMenu\Menu | [
"Adds",
"a",
"new",
"option",
"."
] | train | https://github.com/nunomaduro/laravel-console-menu/blob/51579f17ee28e37861e297f03a10727465b57ab4/src/Menu.php#L59-L73 |
nunomaduro/laravel-console-menu | src/Menu.php | Menu.addOptions | public function addOptions(array $options): Menu
{
foreach ($options as $value => $label) {
$this->addOption($value, $label);
}
return $this;
} | php | public function addOptions(array $options): Menu
{
foreach ($options as $value => $label) {
$this->addOption($value, $label);
}
return $this;
} | [
"public",
"function",
"addOptions",
"(",
"array",
"$",
"options",
")",
":",
"Menu",
"{",
"foreach",
"(",
"$",
"options",
"as",
"$",
"value",
"=>",
"$",
"label",
")",
"{",
"$",
"this",
"->",
"addOption",
"(",
"$",
"value",
",",
"$",
"label",
")",
";... | Adds multiple options.
@param array $options
@return \NunoMaduro\LaravelConsoleMenu\Menu | [
"Adds",
"multiple",
"options",
"."
] | train | https://github.com/nunomaduro/laravel-console-menu/blob/51579f17ee28e37861e297f03a10727465b57ab4/src/Menu.php#L82-L89 |
nunomaduro/laravel-console-menu | src/Menu.php | Menu.addQuestion | public function addQuestion(string $label, string $placeholder = ''): Menu
{
$itemCallable = function (CliMenu $menu) use ($label, $placeholder) {
$result = $menu->askText()
->setPromptText($label)
->setPlaceholderText($placeholder)
->ask();
$this->result = $result->fetch();
$menu->close();
};
$this->addItem($label, $itemCallable);
return $this;
} | php | public function addQuestion(string $label, string $placeholder = ''): Menu
{
$itemCallable = function (CliMenu $menu) use ($label, $placeholder) {
$result = $menu->askText()
->setPromptText($label)
->setPlaceholderText($placeholder)
->ask();
$this->result = $result->fetch();
$menu->close();
};
$this->addItem($label, $itemCallable);
return $this;
} | [
"public",
"function",
"addQuestion",
"(",
"string",
"$",
"label",
",",
"string",
"$",
"placeholder",
"=",
"''",
")",
":",
"Menu",
"{",
"$",
"itemCallable",
"=",
"function",
"(",
"CliMenu",
"$",
"menu",
")",
"use",
"(",
"$",
"label",
",",
"$",
"placehol... | Add a question.
@param string $label
@param string $placeholder
@return \NunoMaduro\LaravelConsoleMenu\Menu | [
"Add",
"a",
"question",
"."
] | train | https://github.com/nunomaduro/laravel-console-menu/blob/51579f17ee28e37861e297f03a10727465b57ab4/src/Menu.php#L99-L115 |
FlowCommunications/JSONPath | src/Flow/JSONPath/JSONPath.php | JSONPath.find | public function find($expression)
{
$tokens = $this->parseTokens($expression);
$collectionData = [$this->data];
foreach ($tokens as $token) {
$filter = $token->buildFilter($this->options);
$filteredData = [];
foreach ($collectionData as $value) {
if (AccessHelper::isCollectionType($value)) {
$filteredValue = $filter->filter($value);
$filteredData = array_merge($filteredData, $filteredValue);
}
}
$collectionData = $filteredData;
}
return new static($collectionData, $this->options);
} | php | public function find($expression)
{
$tokens = $this->parseTokens($expression);
$collectionData = [$this->data];
foreach ($tokens as $token) {
$filter = $token->buildFilter($this->options);
$filteredData = [];
foreach ($collectionData as $value) {
if (AccessHelper::isCollectionType($value)) {
$filteredValue = $filter->filter($value);
$filteredData = array_merge($filteredData, $filteredValue);
}
}
$collectionData = $filteredData;
}
return new static($collectionData, $this->options);
} | [
"public",
"function",
"find",
"(",
"$",
"expression",
")",
"{",
"$",
"tokens",
"=",
"$",
"this",
"->",
"parseTokens",
"(",
"$",
"expression",
")",
";",
"$",
"collectionData",
"=",
"[",
"$",
"this",
"->",
"data",
"]",
";",
"foreach",
"(",
"$",
"tokens... | Evaluate an expression
@param $expression
@return static
@throws JSONPathException | [
"Evaluate",
"an",
"expression"
] | train | https://github.com/FlowCommunications/JSONPath/blob/3cd39484e3d945e8bd3648fa84eb605dc22abcbf/src/Flow/JSONPath/JSONPath.php#L37-L60 |
FlowCommunications/JSONPath | src/Flow/JSONPath/JSONPath.php | JSONPath.last | public function last()
{
$keys = AccessHelper::collectionKeys($this->data);
if (empty($keys)) {
return null;
}
$value = $this->data[end($keys)] ? $this->data[end($keys)] : null;
return AccessHelper::isCollectionType($value) ? new static($value, $this->options) : $value;
} | php | public function last()
{
$keys = AccessHelper::collectionKeys($this->data);
if (empty($keys)) {
return null;
}
$value = $this->data[end($keys)] ? $this->data[end($keys)] : null;
return AccessHelper::isCollectionType($value) ? new static($value, $this->options) : $value;
} | [
"public",
"function",
"last",
"(",
")",
"{",
"$",
"keys",
"=",
"AccessHelper",
"::",
"collectionKeys",
"(",
"$",
"this",
"->",
"data",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"keys",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"value",
"=",
"... | Evaluate an expression and return the last result
@return mixed | [
"Evaluate",
"an",
"expression",
"and",
"return",
"the",
"last",
"result"
] | train | https://github.com/FlowCommunications/JSONPath/blob/3cd39484e3d945e8bd3648fa84eb605dc22abcbf/src/Flow/JSONPath/JSONPath.php#L82-L93 |
FlowCommunications/JSONPath | src/Flow/JSONPath/JSONPath.php | JSONPath.firstKey | public function firstKey()
{
$keys = AccessHelper::collectionKeys($this->data);
if (empty($keys)) {
return null;
}
return $keys[0];
} | php | public function firstKey()
{
$keys = AccessHelper::collectionKeys($this->data);
if (empty($keys)) {
return null;
}
return $keys[0];
} | [
"public",
"function",
"firstKey",
"(",
")",
"{",
"$",
"keys",
"=",
"AccessHelper",
"::",
"collectionKeys",
"(",
"$",
"this",
"->",
"data",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"keys",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"ke... | Evaluate an expression and return the first key
@return mixed | [
"Evaluate",
"an",
"expression",
"and",
"return",
"the",
"first",
"key"
] | train | https://github.com/FlowCommunications/JSONPath/blob/3cd39484e3d945e8bd3648fa84eb605dc22abcbf/src/Flow/JSONPath/JSONPath.php#L99-L108 |
FlowCommunications/JSONPath | src/Flow/JSONPath/JSONPath.php | JSONPath.lastKey | public function lastKey()
{
$keys = AccessHelper::collectionKeys($this->data);
if (empty($keys) || end($keys) === false) {
return null;
}
return end($keys);
} | php | public function lastKey()
{
$keys = AccessHelper::collectionKeys($this->data);
if (empty($keys) || end($keys) === false) {
return null;
}
return end($keys);
} | [
"public",
"function",
"lastKey",
"(",
")",
"{",
"$",
"keys",
"=",
"AccessHelper",
"::",
"collectionKeys",
"(",
"$",
"this",
"->",
"data",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"keys",
")",
"||",
"end",
"(",
"$",
"keys",
")",
"===",
"false",
")",
... | Evaluate an expression and return the last key
@return mixed | [
"Evaluate",
"an",
"expression",
"and",
"return",
"the",
"last",
"key"
] | train | https://github.com/FlowCommunications/JSONPath/blob/3cd39484e3d945e8bd3648fa84eb605dc22abcbf/src/Flow/JSONPath/JSONPath.php#L114-L123 |
FlowCommunications/JSONPath | src/Flow/JSONPath/JSONPath.php | JSONPath.current | public function current()
{
$value = current($this->data);
return AccessHelper::isCollectionType($value) ? new static($value, $this->options) : $value;
} | php | public function current()
{
$value = current($this->data);
return AccessHelper::isCollectionType($value) ? new static($value, $this->options) : $value;
} | [
"public",
"function",
"current",
"(",
")",
"{",
"$",
"value",
"=",
"current",
"(",
"$",
"this",
"->",
"data",
")",
";",
"return",
"AccessHelper",
"::",
"isCollectionType",
"(",
"$",
"value",
")",
"?",
"new",
"static",
"(",
"$",
"value",
",",
"$",
"th... | Return the current element | [
"Return",
"the",
"current",
"element"
] | train | https://github.com/FlowCommunications/JSONPath/blob/3cd39484e3d945e8bd3648fa84eb605dc22abcbf/src/Flow/JSONPath/JSONPath.php#L191-L196 |
sonata-project/SonataBlockBundle | src/Form/Type/ServiceListType.php | ServiceListType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$manager = $this->manager;
$resolver->setRequired([
'context',
]);
$resolver->setDefaults([
'multiple' => false,
'expanded' => false,
'choices' => static function (Options $options, $previousValue) use ($manager) {
$types = [];
foreach ($manager->getServicesByContext($options['context'], $options['include_containers']) as $code => $service) {
$types[$code] = sprintf('%s - %s', $service->getName(), $code);
}
return $types;
},
'preferred_choices' => [],
'empty_data' => static function (Options $options) {
$multiple = isset($options['multiple']) && $options['multiple'];
$expanded = isset($options['expanded']) && $options['expanded'];
return $multiple || $expanded ? [] : '';
},
'empty_value' => static function (Options $options, $previousValue) {
$multiple = isset($options['multiple']) && $options['multiple'];
$expanded = isset($options['expanded']) && $options['expanded'];
return $multiple || $expanded || !isset($previousValue) ? null : '';
},
'error_bubbling' => false,
'include_containers' => false,
]);
} | php | public function configureOptions(OptionsResolver $resolver)
{
$manager = $this->manager;
$resolver->setRequired([
'context',
]);
$resolver->setDefaults([
'multiple' => false,
'expanded' => false,
'choices' => static function (Options $options, $previousValue) use ($manager) {
$types = [];
foreach ($manager->getServicesByContext($options['context'], $options['include_containers']) as $code => $service) {
$types[$code] = sprintf('%s - %s', $service->getName(), $code);
}
return $types;
},
'preferred_choices' => [],
'empty_data' => static function (Options $options) {
$multiple = isset($options['multiple']) && $options['multiple'];
$expanded = isset($options['expanded']) && $options['expanded'];
return $multiple || $expanded ? [] : '';
},
'empty_value' => static function (Options $options, $previousValue) {
$multiple = isset($options['multiple']) && $options['multiple'];
$expanded = isset($options['expanded']) && $options['expanded'];
return $multiple || $expanded || !isset($previousValue) ? null : '';
},
'error_bubbling' => false,
'include_containers' => false,
]);
} | [
"public",
"function",
"configureOptions",
"(",
"OptionsResolver",
"$",
"resolver",
")",
"{",
"$",
"manager",
"=",
"$",
"this",
"->",
"manager",
";",
"$",
"resolver",
"->",
"setRequired",
"(",
"[",
"'context'",
",",
"]",
")",
";",
"$",
"resolver",
"->",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Form/Type/ServiceListType.php#L61-L96 |
sonata-project/SonataBlockBundle | src/Block/Service/AbstractBlockService.php | AbstractBlockService.renderPrivateResponse | public function renderPrivateResponse($view, array $parameters = [], Response $response = null)
{
return $this->renderResponse($view, $parameters, $response)
->setTtl(0)
->setPrivate()
;
} | php | public function renderPrivateResponse($view, array $parameters = [], Response $response = null)
{
return $this->renderResponse($view, $parameters, $response)
->setTtl(0)
->setPrivate()
;
} | [
"public",
"function",
"renderPrivateResponse",
"(",
"$",
"view",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
",",
"Response",
"$",
"response",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"renderResponse",
"(",
"$",
"view",
",",
"$",
"paramete... | Returns a Response object that cannot be cacheable, this must be used if the Response is related to the user.
A good solution to make the page cacheable is to configure the block to be cached with javascript ...
@param string $view
@param array $parameters
@param Response $response
@return Response | [
"Returns",
"a",
"Response",
"object",
"that",
"cannot",
"be",
"cacheable",
"this",
"must",
"be",
"used",
"if",
"the",
"Response",
"is",
"related",
"to",
"the",
"user",
".",
"A",
"good",
"solution",
"to",
"make",
"the",
"page",
"cacheable",
"is",
"to",
"c... | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Service/AbstractBlockService.php#L79-L85 |
sonata-project/SonataBlockBundle | src/Block/Service/AbstractBlockService.php | AbstractBlockService.getCacheKeys | public function getCacheKeys(BlockInterface $block)
{
return [
'block_id' => $block->getId(),
'updated_at' => $block->getUpdatedAt() ? $block->getUpdatedAt()->format('U') : strtotime('now'),
];
} | php | public function getCacheKeys(BlockInterface $block)
{
return [
'block_id' => $block->getId(),
'updated_at' => $block->getUpdatedAt() ? $block->getUpdatedAt()->format('U') : strtotime('now'),
];
} | [
"public",
"function",
"getCacheKeys",
"(",
"BlockInterface",
"$",
"block",
")",
"{",
"return",
"[",
"'block_id'",
"=>",
"$",
"block",
"->",
"getId",
"(",
")",
",",
"'updated_at'",
"=>",
"$",
"block",
"->",
"getUpdatedAt",
"(",
")",
"?",
"$",
"block",
"->... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Service/AbstractBlockService.php#L107-L113 |
sonata-project/SonataBlockBundle | src/SonataBlockBundle.php | SonataBlockBundle.build | public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new TweakCompilerPass());
$container->addCompilerPass(new GlobalVariablesCompilerPass());
$this->registerFormMapping();
} | php | public function build(ContainerBuilder $container)
{
$container->addCompilerPass(new TweakCompilerPass());
$container->addCompilerPass(new GlobalVariablesCompilerPass());
$this->registerFormMapping();
} | [
"public",
"function",
"build",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"container",
"->",
"addCompilerPass",
"(",
"new",
"TweakCompilerPass",
"(",
")",
")",
";",
"$",
"container",
"->",
"addCompilerPass",
"(",
"new",
"GlobalVariablesCompilerPass"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/SonataBlockBundle.php#L27-L33 |
sonata-project/SonataBlockBundle | src/Block/BlockContextManager.php | BlockContextManager.addSettingsByType | public function addSettingsByType($type, array $settings, $replace = false)
{
$typeSettings = isset($this->settingsByType[$type]) ? $this->settingsByType[$type] : [];
if ($replace) {
$this->settingsByType[$type] = array_merge($typeSettings, $settings);
} else {
$this->settingsByType[$type] = array_merge($settings, $typeSettings);
}
} | php | public function addSettingsByType($type, array $settings, $replace = false)
{
$typeSettings = isset($this->settingsByType[$type]) ? $this->settingsByType[$type] : [];
if ($replace) {
$this->settingsByType[$type] = array_merge($typeSettings, $settings);
} else {
$this->settingsByType[$type] = array_merge($settings, $typeSettings);
}
} | [
"public",
"function",
"addSettingsByType",
"(",
"$",
"type",
",",
"array",
"$",
"settings",
",",
"$",
"replace",
"=",
"false",
")",
"{",
"$",
"typeSettings",
"=",
"isset",
"(",
"$",
"this",
"->",
"settingsByType",
"[",
"$",
"type",
"]",
")",
"?",
"$",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockContextManager.php#L82-L90 |
sonata-project/SonataBlockBundle | src/Block/BlockContextManager.php | BlockContextManager.addSettingsByClass | public function addSettingsByClass($class, array $settings, $replace = false)
{
$classSettings = isset($this->settingsByClass[$class]) ? $this->settingsByClass[$class] : [];
if ($replace) {
$this->settingsByClass[$class] = array_merge($classSettings, $settings);
} else {
$this->settingsByClass[$class] = array_merge($settings, $classSettings);
}
} | php | public function addSettingsByClass($class, array $settings, $replace = false)
{
$classSettings = isset($this->settingsByClass[$class]) ? $this->settingsByClass[$class] : [];
if ($replace) {
$this->settingsByClass[$class] = array_merge($classSettings, $settings);
} else {
$this->settingsByClass[$class] = array_merge($settings, $classSettings);
}
} | [
"public",
"function",
"addSettingsByClass",
"(",
"$",
"class",
",",
"array",
"$",
"settings",
",",
"$",
"replace",
"=",
"false",
")",
"{",
"$",
"classSettings",
"=",
"isset",
"(",
"$",
"this",
"->",
"settingsByClass",
"[",
"$",
"class",
"]",
")",
"?",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockContextManager.php#L95-L103 |
sonata-project/SonataBlockBundle | src/Block/BlockContextManager.php | BlockContextManager.get | public function get($meta, array $settings = [])
{
if (!$meta instanceof BlockInterface) {
$block = $this->blockLoader->load($meta);
if (\is_array($meta) && isset($meta['settings'])) {
// merge user settings
$settings = array_merge($meta['settings'], $settings);
}
} else {
$block = $meta;
}
if (!$block instanceof BlockInterface) {
return false;
}
$originalSettings = $settings;
try {
$settings = $this->resolve($block, array_merge($block->getSettings(), $settings));
} catch (ExceptionInterface $e) {
if ($this->logger) {
$this->logger->error(sprintf(
'[cms::blockContext] block.id=%s - error while resolving options - %s',
$block->getId(),
$e->getMessage()
));
}
$settings = $this->resolve($block, $settings);
}
$blockContext = new BlockContext($block, $settings);
$this->setDefaultExtraCacheKeys($blockContext, $originalSettings);
return $blockContext;
} | php | public function get($meta, array $settings = [])
{
if (!$meta instanceof BlockInterface) {
$block = $this->blockLoader->load($meta);
if (\is_array($meta) && isset($meta['settings'])) {
// merge user settings
$settings = array_merge($meta['settings'], $settings);
}
} else {
$block = $meta;
}
if (!$block instanceof BlockInterface) {
return false;
}
$originalSettings = $settings;
try {
$settings = $this->resolve($block, array_merge($block->getSettings(), $settings));
} catch (ExceptionInterface $e) {
if ($this->logger) {
$this->logger->error(sprintf(
'[cms::blockContext] block.id=%s - error while resolving options - %s',
$block->getId(),
$e->getMessage()
));
}
$settings = $this->resolve($block, $settings);
}
$blockContext = new BlockContext($block, $settings);
$this->setDefaultExtraCacheKeys($blockContext, $originalSettings);
return $blockContext;
} | [
"public",
"function",
"get",
"(",
"$",
"meta",
",",
"array",
"$",
"settings",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"meta",
"instanceof",
"BlockInterface",
")",
"{",
"$",
"block",
"=",
"$",
"this",
"->",
"blockLoader",
"->",
"load",
"(",
"$... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockContextManager.php#L120-L158 |
sonata-project/SonataBlockBundle | src/Block/BlockContextManager.php | BlockContextManager.setDefaultSettings | protected function setDefaultSettings(OptionsResolverInterface $optionsResolver, BlockInterface $block)
{
if (__CLASS__ !== \get_called_class()) {
@trigger_error(
'The '.__METHOD__.' is deprecated since version 2.3, to be renamed in 4.0.'
.' Use '.__CLASS__.'::configureSettings instead.',
E_USER_DEPRECATED
);
}
$this->configureSettings($optionsResolver, $block);
} | php | protected function setDefaultSettings(OptionsResolverInterface $optionsResolver, BlockInterface $block)
{
if (__CLASS__ !== \get_called_class()) {
@trigger_error(
'The '.__METHOD__.' is deprecated since version 2.3, to be renamed in 4.0.'
.' Use '.__CLASS__.'::configureSettings instead.',
E_USER_DEPRECATED
);
}
$this->configureSettings($optionsResolver, $block);
} | [
"protected",
"function",
"setDefaultSettings",
"(",
"OptionsResolverInterface",
"$",
"optionsResolver",
",",
"BlockInterface",
"$",
"block",
")",
"{",
"if",
"(",
"__CLASS__",
"!==",
"\\",
"get_called_class",
"(",
")",
")",
"{",
"@",
"trigger_error",
"(",
"'The '",... | NEXT_MAJOR: remove this method.
@param OptionsResolverInterface $optionsResolver
@param BlockInterface $block
@deprecated since version 2.3, to be renamed in 4.0.
Use the method configureSettings instead | [
"NEXT_MAJOR",
":",
"remove",
"this",
"method",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockContextManager.php#L169-L179 |
sonata-project/SonataBlockBundle | src/Block/BlockContextManager.php | BlockContextManager.setDefaultExtraCacheKeys | protected function setDefaultExtraCacheKeys(BlockContextInterface $blockContext, array $settings)
{
if (!$blockContext->getSetting('use_cache') || $blockContext->getSetting('ttl') <= 0) {
return;
}
$block = $blockContext->getBlock();
// type by block class
$class = ClassUtils::getClass($block);
$cacheServiceId = isset($this->cacheBlocks['by_class'][$class]) ? $this->cacheBlocks['by_class'][$class] : false;
// type by block service
if (!$cacheServiceId) {
$cacheServiceId = isset($this->cacheBlocks['by_type'][$block->getType()]) ? $this->cacheBlocks['by_type'][$block->getType()] : false;
}
if (!$cacheServiceId) {
// no context cache needed
return;
}
// do not add cache settings to extra_cache_keys
unset($settings['use_cache'], $settings['extra_cache_keys'], $settings['ttl']);
$extraCacheKeys = $blockContext->getSetting('extra_cache_keys');
// add context settings to extra_cache_keys
if (!isset($extraCacheKeys[self::CACHE_KEY])) {
$extraCacheKeys[self::CACHE_KEY] = $settings;
$blockContext->setSetting('extra_cache_keys', $extraCacheKeys);
}
} | php | protected function setDefaultExtraCacheKeys(BlockContextInterface $blockContext, array $settings)
{
if (!$blockContext->getSetting('use_cache') || $blockContext->getSetting('ttl') <= 0) {
return;
}
$block = $blockContext->getBlock();
// type by block class
$class = ClassUtils::getClass($block);
$cacheServiceId = isset($this->cacheBlocks['by_class'][$class]) ? $this->cacheBlocks['by_class'][$class] : false;
// type by block service
if (!$cacheServiceId) {
$cacheServiceId = isset($this->cacheBlocks['by_type'][$block->getType()]) ? $this->cacheBlocks['by_type'][$block->getType()] : false;
}
if (!$cacheServiceId) {
// no context cache needed
return;
}
// do not add cache settings to extra_cache_keys
unset($settings['use_cache'], $settings['extra_cache_keys'], $settings['ttl']);
$extraCacheKeys = $blockContext->getSetting('extra_cache_keys');
// add context settings to extra_cache_keys
if (!isset($extraCacheKeys[self::CACHE_KEY])) {
$extraCacheKeys[self::CACHE_KEY] = $settings;
$blockContext->setSetting('extra_cache_keys', $extraCacheKeys);
}
} | [
"protected",
"function",
"setDefaultExtraCacheKeys",
"(",
"BlockContextInterface",
"$",
"blockContext",
",",
"array",
"$",
"settings",
")",
"{",
"if",
"(",
"!",
"$",
"blockContext",
"->",
"getSetting",
"(",
"'use_cache'",
")",
"||",
"$",
"blockContext",
"->",
"g... | Adds context settings, to be able to rebuild a block context, to the
extra_cache_keys.
@param BlockContextInterface $blockContext
@param array $settings | [
"Adds",
"context",
"settings",
"to",
"be",
"able",
"to",
"rebuild",
"a",
"block",
"context",
"to",
"the",
"extra_cache_keys",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockContextManager.php#L214-L246 |
sonata-project/SonataBlockBundle | src/Block/BlockContextManager.php | BlockContextManager.resolve | private function resolve(BlockInterface $block, $settings)
{
$optionsResolver = new \Sonata\BlockBundle\Util\OptionsResolver();
$this->configureSettings($optionsResolver, $block);
$service = $this->blockService->get($block);
// Caching method reflection
// NEXT_MAJOR: Remove everything here
$serviceClass = \get_class($service);
if (!isset($this->reflectionCache[$serviceClass])) {
$reflector = new \ReflectionMethod($service, 'setDefaultSettings');
$isOldOverwritten = \get_class($service) === $reflector->getDeclaringClass()->getName();
// Prevention for service classes implementing directly the interface and not extends the new base class
if (!method_exists($service, 'configureSettings')) {
$isNewOverwritten = false;
} else {
$reflector = new \ReflectionMethod($service, 'configureSettings');
$isNewOverwritten = \get_class($service) === $reflector->getDeclaringClass()->getName();
}
$this->reflectionCache[$serviceClass] = [
'isOldOverwritten' => $isOldOverwritten,
'isNewOverwritten' => $isNewOverwritten,
];
}
// NEXT_MAJOR: Keep Only else case
if ($this->reflectionCache[$serviceClass]['isOldOverwritten'] && !$this->reflectionCache[$serviceClass]['isNewOverwritten']) {
@trigger_error(
'The Sonata\BlockBundle\Block\BlockServiceInterface::setDefaultSettings() method is deprecated'
.' since version 2.3 and will be removed in 4.0. Use configureSettings() instead.'
.' This method will be added to the BlockServiceInterface with SonataBlockBundle 4.0.',
E_USER_DEPRECATED
);
$service->setDefaultSettings($optionsResolver);
} else {
$service->configureSettings($optionsResolver);
}
return $optionsResolver->resolve($settings);
} | php | private function resolve(BlockInterface $block, $settings)
{
$optionsResolver = new \Sonata\BlockBundle\Util\OptionsResolver();
$this->configureSettings($optionsResolver, $block);
$service = $this->blockService->get($block);
// Caching method reflection
// NEXT_MAJOR: Remove everything here
$serviceClass = \get_class($service);
if (!isset($this->reflectionCache[$serviceClass])) {
$reflector = new \ReflectionMethod($service, 'setDefaultSettings');
$isOldOverwritten = \get_class($service) === $reflector->getDeclaringClass()->getName();
// Prevention for service classes implementing directly the interface and not extends the new base class
if (!method_exists($service, 'configureSettings')) {
$isNewOverwritten = false;
} else {
$reflector = new \ReflectionMethod($service, 'configureSettings');
$isNewOverwritten = \get_class($service) === $reflector->getDeclaringClass()->getName();
}
$this->reflectionCache[$serviceClass] = [
'isOldOverwritten' => $isOldOverwritten,
'isNewOverwritten' => $isNewOverwritten,
];
}
// NEXT_MAJOR: Keep Only else case
if ($this->reflectionCache[$serviceClass]['isOldOverwritten'] && !$this->reflectionCache[$serviceClass]['isNewOverwritten']) {
@trigger_error(
'The Sonata\BlockBundle\Block\BlockServiceInterface::setDefaultSettings() method is deprecated'
.' since version 2.3 and will be removed in 4.0. Use configureSettings() instead.'
.' This method will be added to the BlockServiceInterface with SonataBlockBundle 4.0.',
E_USER_DEPRECATED
);
$service->setDefaultSettings($optionsResolver);
} else {
$service->configureSettings($optionsResolver);
}
return $optionsResolver->resolve($settings);
} | [
"private",
"function",
"resolve",
"(",
"BlockInterface",
"$",
"block",
",",
"$",
"settings",
")",
"{",
"$",
"optionsResolver",
"=",
"new",
"\\",
"Sonata",
"\\",
"BlockBundle",
"\\",
"Util",
"\\",
"OptionsResolver",
"(",
")",
";",
"$",
"this",
"->",
"config... | @param BlockInterface $block
@param array $settings
@return array | [
"@param",
"BlockInterface",
"$block",
"@param",
"array",
"$settings"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockContextManager.php#L254-L297 |
sonata-project/SonataBlockBundle | src/Command/DebugBlocksCommand.php | DebugBlocksCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('context')) {
$services = $this->getBlockServiceManager()->getServicesByContext($input->getOption('context'));
} else {
$services = $this->getBlockServiceManager()->getServices();
}
foreach ($services as $code => $service) {
$resolver = new OptionsResolver();
// NEXT_MAJOR: Remove this check
if (method_exists($service, 'configureSettings')) {
$service->configureSettings($resolver);
} else {
$service->setDefaultSettings($resolver);
}
$settings = $resolver->resolve();
$output->writeln('');
$output->writeln(sprintf('<info>>> %s</info> (<comment>%s</comment>)', $service->getName(), $code));
foreach ($settings as $key => $val) {
$output->writeln(sprintf(' %-30s%s', $key, json_encode($val)));
}
}
$output->writeln('done!');
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('context')) {
$services = $this->getBlockServiceManager()->getServicesByContext($input->getOption('context'));
} else {
$services = $this->getBlockServiceManager()->getServices();
}
foreach ($services as $code => $service) {
$resolver = new OptionsResolver();
// NEXT_MAJOR: Remove this check
if (method_exists($service, 'configureSettings')) {
$service->configureSettings($resolver);
} else {
$service->setDefaultSettings($resolver);
}
$settings = $resolver->resolve();
$output->writeln('');
$output->writeln(sprintf('<info>>> %s</info> (<comment>%s</comment>)', $service->getName(), $code));
foreach ($settings as $key => $val) {
$output->writeln(sprintf(' %-30s%s', $key, json_encode($val)));
}
}
$output->writeln('done!');
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"if",
"(",
"$",
"input",
"->",
"getOption",
"(",
"'context'",
")",
")",
"{",
"$",
"services",
"=",
"$",
"this",
"->",
"getBlockServiceMan... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Command/DebugBlocksCommand.php#L39-L68 |
sonata-project/SonataBlockBundle | src/Profiler/DataCollector/BlockDataCollector.php | BlockDataCollector.collect | public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->blocks = $this->blocksHelper->getTraces();
// split into containers & real blocks
foreach ($this->blocks as $id => $block) {
if (!\is_array($block)) {
return; // something went wrong while collecting information
}
if ('_events' === $id) {
foreach ($block as $uniqid => $event) {
$this->events[$uniqid] = $event;
}
continue;
}
if (\in_array($block['type'], $this->containerTypes, true)) {
$this->containers[$id] = $block;
} else {
$this->realBlocks[$id] = $block;
}
}
} | php | public function collect(Request $request, Response $response, \Exception $exception = null)
{
$this->blocks = $this->blocksHelper->getTraces();
// split into containers & real blocks
foreach ($this->blocks as $id => $block) {
if (!\is_array($block)) {
return; // something went wrong while collecting information
}
if ('_events' === $id) {
foreach ($block as $uniqid => $event) {
$this->events[$uniqid] = $event;
}
continue;
}
if (\in_array($block['type'], $this->containerTypes, true)) {
$this->containers[$id] = $block;
} else {
$this->realBlocks[$id] = $block;
}
}
} | [
"public",
"function",
"collect",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"\\",
"Exception",
"$",
"exception",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"blocks",
"=",
"$",
"this",
"->",
"blocksHelper",
"->",
"getTraces",
"(... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Profiler/DataCollector/BlockDataCollector.php#L71-L95 |
sonata-project/SonataBlockBundle | src/Profiler/DataCollector/BlockDataCollector.php | BlockDataCollector.serialize | public function serialize()
{
$data = [
'blocks' => $this->blocks,
'containers' => $this->containers,
'realBlocks' => $this->realBlocks,
'events' => $this->events,
];
return serialize($data);
} | php | public function serialize()
{
$data = [
'blocks' => $this->blocks,
'containers' => $this->containers,
'realBlocks' => $this->realBlocks,
'events' => $this->events,
];
return serialize($data);
} | [
"public",
"function",
"serialize",
"(",
")",
"{",
"$",
"data",
"=",
"[",
"'blocks'",
"=>",
"$",
"this",
"->",
"blocks",
",",
"'containers'",
"=>",
"$",
"this",
"->",
"containers",
",",
"'realBlocks'",
"=>",
"$",
"this",
"->",
"realBlocks",
",",
"'events'... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Profiler/DataCollector/BlockDataCollector.php#L150-L160 |
sonata-project/SonataBlockBundle | src/Profiler/DataCollector/BlockDataCollector.php | BlockDataCollector.unserialize | public function unserialize($data)
{
$merged = unserialize($data);
$this->blocks = $merged['blocks'];
$this->containers = $merged['containers'];
$this->realBlocks = $merged['realBlocks'];
$this->events = $merged['events'];
} | php | public function unserialize($data)
{
$merged = unserialize($data);
$this->blocks = $merged['blocks'];
$this->containers = $merged['containers'];
$this->realBlocks = $merged['realBlocks'];
$this->events = $merged['events'];
} | [
"public",
"function",
"unserialize",
"(",
"$",
"data",
")",
"{",
"$",
"merged",
"=",
"unserialize",
"(",
"$",
"data",
")",
";",
"$",
"this",
"->",
"blocks",
"=",
"$",
"merged",
"[",
"'blocks'",
"]",
";",
"$",
"this",
"->",
"containers",
"=",
"$",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Profiler/DataCollector/BlockDataCollector.php#L165-L173 |
sonata-project/SonataBlockBundle | src/Block/Loader/ServiceLoader.php | ServiceLoader.load | public function load($configuration)
{
if (!\in_array($configuration['type'], $this->types, true)) {
throw new \RuntimeException(sprintf(
'The block type "%s" does not exist',
$configuration['type']
));
}
$block = new Block();
$block->setId(uniqid('', true));
$block->setType($configuration['type']);
$block->setEnabled(true);
$block->setCreatedAt(new \DateTime());
$block->setUpdatedAt(new \DateTime());
$block->setSettings($configuration['settings'] ?? []);
return $block;
} | php | public function load($configuration)
{
if (!\in_array($configuration['type'], $this->types, true)) {
throw new \RuntimeException(sprintf(
'The block type "%s" does not exist',
$configuration['type']
));
}
$block = new Block();
$block->setId(uniqid('', true));
$block->setType($configuration['type']);
$block->setEnabled(true);
$block->setCreatedAt(new \DateTime());
$block->setUpdatedAt(new \DateTime());
$block->setSettings($configuration['settings'] ?? []);
return $block;
} | [
"public",
"function",
"load",
"(",
"$",
"configuration",
")",
"{",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"configuration",
"[",
"'type'",
"]",
",",
"$",
"this",
"->",
"types",
",",
"true",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Loader/ServiceLoader.php#L49-L67 |
sonata-project/SonataBlockBundle | src/Exception/Strategy/StrategyManager.php | StrategyManager.setDefaultFilter | public function setDefaultFilter($name)
{
if (!\array_key_exists($name, $this->filters)) {
throw new \InvalidArgumentException(sprintf('Cannot set default exception filter "%s". It does not exist.', $name));
}
$this->defaultFilter = $name;
} | php | public function setDefaultFilter($name)
{
if (!\array_key_exists($name, $this->filters)) {
throw new \InvalidArgumentException(sprintf('Cannot set default exception filter "%s". It does not exist.', $name));
}
$this->defaultFilter = $name;
} | [
"public",
"function",
"setDefaultFilter",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"\\",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"filters",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'C... | Sets the default filter name.
@param string $name
@throws \InvalidArgumentException | [
"Sets",
"the",
"default",
"filter",
"name",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Strategy/StrategyManager.php#L88-L95 |
sonata-project/SonataBlockBundle | src/Exception/Strategy/StrategyManager.php | StrategyManager.setDefaultRenderer | public function setDefaultRenderer($name)
{
if (!\array_key_exists($name, $this->renderers)) {
throw new \InvalidArgumentException(sprintf('Cannot set default exception renderer "%s". It does not exist.', $name));
}
$this->defaultRenderer = $name;
} | php | public function setDefaultRenderer($name)
{
if (!\array_key_exists($name, $this->renderers)) {
throw new \InvalidArgumentException(sprintf('Cannot set default exception renderer "%s". It does not exist.', $name));
}
$this->defaultRenderer = $name;
} | [
"public",
"function",
"setDefaultRenderer",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"\\",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"renderers",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
... | Sets the default renderer name.
@param string $name
@throws \InvalidArgumentException | [
"Sets",
"the",
"default",
"renderer",
"name",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Strategy/StrategyManager.php#L104-L111 |
sonata-project/SonataBlockBundle | src/Exception/Strategy/StrategyManager.php | StrategyManager.handleException | public function handleException(\Exception $exception, BlockInterface $block, Response $response = null)
{
$response = $response ?: new Response();
$response->setPrivate();
$filter = $this->getBlockFilter($block);
if ($filter->handle($exception, $block)) {
$renderer = $this->getBlockRenderer($block);
$response = $renderer->render($exception, $block, $response);
}
// render empty block template?
return $response;
} | php | public function handleException(\Exception $exception, BlockInterface $block, Response $response = null)
{
$response = $response ?: new Response();
$response->setPrivate();
$filter = $this->getBlockFilter($block);
if ($filter->handle($exception, $block)) {
$renderer = $this->getBlockRenderer($block);
$response = $renderer->render($exception, $block, $response);
}
// render empty block template?
return $response;
} | [
"public",
"function",
"handleException",
"(",
"\\",
"Exception",
"$",
"exception",
",",
"BlockInterface",
"$",
"block",
",",
"Response",
"$",
"response",
"=",
"null",
")",
"{",
"$",
"response",
"=",
"$",
"response",
"?",
":",
"new",
"Response",
"(",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Strategy/StrategyManager.php#L116-L129 |
sonata-project/SonataBlockBundle | src/Exception/Strategy/StrategyManager.php | StrategyManager.getBlockRenderer | public function getBlockRenderer(BlockInterface $block)
{
$type = $block->getType();
$name = isset($this->blockRenderers[$type]) ? $this->blockRenderers[$type] : $this->defaultRenderer;
$service = $this->getRendererService($name);
if (!$service instanceof RendererInterface) {
throw new \RuntimeException(sprintf('The service "%s" is not an exception renderer', $name));
}
return $service;
} | php | public function getBlockRenderer(BlockInterface $block)
{
$type = $block->getType();
$name = isset($this->blockRenderers[$type]) ? $this->blockRenderers[$type] : $this->defaultRenderer;
$service = $this->getRendererService($name);
if (!$service instanceof RendererInterface) {
throw new \RuntimeException(sprintf('The service "%s" is not an exception renderer', $name));
}
return $service;
} | [
"public",
"function",
"getBlockRenderer",
"(",
"BlockInterface",
"$",
"block",
")",
"{",
"$",
"type",
"=",
"$",
"block",
"->",
"getType",
"(",
")",
";",
"$",
"name",
"=",
"isset",
"(",
"$",
"this",
"->",
"blockRenderers",
"[",
"$",
"type",
"]",
")",
... | Returns the exception renderer for given block.
@param BlockInterface $block
@throws \RuntimeException
@return RendererInterface | [
"Returns",
"the",
"exception",
"renderer",
"for",
"given",
"block",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Strategy/StrategyManager.php#L140-L152 |
sonata-project/SonataBlockBundle | src/Exception/Strategy/StrategyManager.php | StrategyManager.getBlockFilter | public function getBlockFilter(BlockInterface $block)
{
$type = $block->getType();
$name = isset($this->blockFilters[$type]) ? $this->blockFilters[$type] : $this->defaultFilter;
$service = $this->getFilterService($name);
if (!$service instanceof FilterInterface) {
throw new \RuntimeException(sprintf('The service "%s" is not an exception filter', $name));
}
return $service;
} | php | public function getBlockFilter(BlockInterface $block)
{
$type = $block->getType();
$name = isset($this->blockFilters[$type]) ? $this->blockFilters[$type] : $this->defaultFilter;
$service = $this->getFilterService($name);
if (!$service instanceof FilterInterface) {
throw new \RuntimeException(sprintf('The service "%s" is not an exception filter', $name));
}
return $service;
} | [
"public",
"function",
"getBlockFilter",
"(",
"BlockInterface",
"$",
"block",
")",
"{",
"$",
"type",
"=",
"$",
"block",
"->",
"getType",
"(",
")",
";",
"$",
"name",
"=",
"isset",
"(",
"$",
"this",
"->",
"blockFilters",
"[",
"$",
"type",
"]",
")",
"?",... | Returns the exception filter for given block.
@param BlockInterface $block
@throws \RuntimeException
@return FilterInterface | [
"Returns",
"the",
"exception",
"filter",
"for",
"given",
"block",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Strategy/StrategyManager.php#L163-L175 |
sonata-project/SonataBlockBundle | src/Exception/Strategy/StrategyManager.php | StrategyManager.getFilterService | protected function getFilterService($name)
{
if (!isset($this->filters[$name])) {
throw new \RuntimeException('The filter "%s" does not exist.');
}
return $this->container->get($this->filters[$name]);
} | php | protected function getFilterService($name)
{
if (!isset($this->filters[$name])) {
throw new \RuntimeException('The filter "%s" does not exist.');
}
return $this->container->get($this->filters[$name]);
} | [
"protected",
"function",
"getFilterService",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"filters",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'The filter \"%s\" does not exist.'",
... | Returns the filter service for given filter name.
@param string $name
@throws \RuntimeException
@return object | [
"Returns",
"the",
"filter",
"service",
"for",
"given",
"filter",
"name",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Strategy/StrategyManager.php#L186-L193 |
sonata-project/SonataBlockBundle | src/Exception/Strategy/StrategyManager.php | StrategyManager.getRendererService | protected function getRendererService($name)
{
if (!isset($this->renderers[$name])) {
throw new \RuntimeException('The renderer "%s" does not exist.');
}
return $this->container->get($this->renderers[$name]);
} | php | protected function getRendererService($name)
{
if (!isset($this->renderers[$name])) {
throw new \RuntimeException('The renderer "%s" does not exist.');
}
return $this->container->get($this->renderers[$name]);
} | [
"protected",
"function",
"getRendererService",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"renderers",
"[",
"$",
"name",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'The renderer \"%s\" does not exist... | Returns the renderer service for given renderer name.
@param string $name
@throws \RuntimeException
@return object | [
"Returns",
"the",
"renderer",
"service",
"for",
"given",
"renderer",
"name",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Strategy/StrategyManager.php#L204-L211 |
sonata-project/SonataBlockBundle | src/Block/Service/MenuBlockService.php | MenuBlockService.execute | public function execute(BlockContextInterface $blockContext, Response $response = null)
{
$responseSettings = [
'menu' => $this->getMenu($blockContext),
'menu_options' => $this->getMenuOptions($blockContext->getSettings()),
'block' => $blockContext->getBlock(),
'context' => $blockContext,
];
if ('private' === $blockContext->getSetting('cache_policy')) {
return $this->renderPrivateResponse($blockContext->getTemplate(), $responseSettings, $response);
}
return $this->renderResponse($blockContext->getTemplate(), $responseSettings, $response);
} | php | public function execute(BlockContextInterface $blockContext, Response $response = null)
{
$responseSettings = [
'menu' => $this->getMenu($blockContext),
'menu_options' => $this->getMenuOptions($blockContext->getSettings()),
'block' => $blockContext->getBlock(),
'context' => $blockContext,
];
if ('private' === $blockContext->getSetting('cache_policy')) {
return $this->renderPrivateResponse($blockContext->getTemplate(), $responseSettings, $response);
}
return $this->renderResponse($blockContext->getTemplate(), $responseSettings, $response);
} | [
"public",
"function",
"execute",
"(",
"BlockContextInterface",
"$",
"blockContext",
",",
"Response",
"$",
"response",
"=",
"null",
")",
"{",
"$",
"responseSettings",
"=",
"[",
"'menu'",
"=>",
"$",
"this",
"->",
"getMenu",
"(",
"$",
"blockContext",
")",
",",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Service/MenuBlockService.php#L94-L108 |
sonata-project/SonataBlockBundle | src/Block/Service/MenuBlockService.php | MenuBlockService.buildEditForm | public function buildEditForm(FormMapper $form, BlockInterface $block)
{
$form->add('settings', ImmutableArrayType::class, [
'keys' => $this->getFormSettingsKeys(),
'translation_domain' => 'SonataBlockBundle',
]);
} | php | public function buildEditForm(FormMapper $form, BlockInterface $block)
{
$form->add('settings', ImmutableArrayType::class, [
'keys' => $this->getFormSettingsKeys(),
'translation_domain' => 'SonataBlockBundle',
]);
} | [
"public",
"function",
"buildEditForm",
"(",
"FormMapper",
"$",
"form",
",",
"BlockInterface",
"$",
"block",
")",
"{",
"$",
"form",
"->",
"add",
"(",
"'settings'",
",",
"ImmutableArrayType",
"::",
"class",
",",
"[",
"'keys'",
"=>",
"$",
"this",
"->",
"getFo... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Service/MenuBlockService.php#L113-L119 |
sonata-project/SonataBlockBundle | src/Block/Service/MenuBlockService.php | MenuBlockService.validateBlock | public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
{
if (($name = $block->getSetting('menu_name')) && '' !== $name && !$this->menuProvider->has($name)) {
// If we specified a menu_name, check that it exists
$errorElement->with('menu_name')
->addViolation('sonata.block.menu.not_existing', ['%name%' => $name])
->end();
}
} | php | public function validateBlock(ErrorElement $errorElement, BlockInterface $block)
{
if (($name = $block->getSetting('menu_name')) && '' !== $name && !$this->menuProvider->has($name)) {
// If we specified a menu_name, check that it exists
$errorElement->with('menu_name')
->addViolation('sonata.block.menu.not_existing', ['%name%' => $name])
->end();
}
} | [
"public",
"function",
"validateBlock",
"(",
"ErrorElement",
"$",
"errorElement",
",",
"BlockInterface",
"$",
"block",
")",
"{",
"if",
"(",
"(",
"$",
"name",
"=",
"$",
"block",
"->",
"getSetting",
"(",
"'menu_name'",
")",
")",
"&&",
"''",
"!==",
"$",
"nam... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Service/MenuBlockService.php#L124-L132 |
sonata-project/SonataBlockBundle | src/Block/Service/MenuBlockService.php | MenuBlockService.configureSettings | public function configureSettings(OptionsResolver $resolver)
{
$resolver->setDefaults([
'title' => $this->getName(),
'cache_policy' => 'public',
'template' => '@SonataBlock/Block/block_core_menu.html.twig',
'menu_name' => '',
'safe_labels' => false,
'current_class' => 'active',
'first_class' => false,
'last_class' => false,
'current_uri' => null,
'menu_class' => 'list-group',
'children_class' => 'list-group-item',
'menu_template' => null,
]);
} | php | public function configureSettings(OptionsResolver $resolver)
{
$resolver->setDefaults([
'title' => $this->getName(),
'cache_policy' => 'public',
'template' => '@SonataBlock/Block/block_core_menu.html.twig',
'menu_name' => '',
'safe_labels' => false,
'current_class' => 'active',
'first_class' => false,
'last_class' => false,
'current_uri' => null,
'menu_class' => 'list-group',
'children_class' => 'list-group-item',
'menu_template' => null,
]);
} | [
"public",
"function",
"configureSettings",
"(",
"OptionsResolver",
"$",
"resolver",
")",
"{",
"$",
"resolver",
"->",
"setDefaults",
"(",
"[",
"'title'",
"=>",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"'cache_policy'",
"=>",
"'public'",
",",
"'template'",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Service/MenuBlockService.php#L137-L153 |
sonata-project/SonataBlockBundle | src/Block/Service/MenuBlockService.php | MenuBlockService.getMenuOptions | protected function getMenuOptions(array $settings)
{
$mapping = [
'current_class' => 'currentClass',
'first_class' => 'firstClass',
'last_class' => 'lastClass',
'safe_labels' => 'allow_safe_labels',
'menu_template' => 'template',
];
$options = [];
foreach ($settings as $key => $value) {
if (\array_key_exists($key, $mapping) && null !== $value) {
$options[$mapping[$key]] = $value;
}
}
return $options;
} | php | protected function getMenuOptions(array $settings)
{
$mapping = [
'current_class' => 'currentClass',
'first_class' => 'firstClass',
'last_class' => 'lastClass',
'safe_labels' => 'allow_safe_labels',
'menu_template' => 'template',
];
$options = [];
foreach ($settings as $key => $value) {
if (\array_key_exists($key, $mapping) && null !== $value) {
$options[$mapping[$key]] = $value;
}
}
return $options;
} | [
"protected",
"function",
"getMenuOptions",
"(",
"array",
"$",
"settings",
")",
"{",
"$",
"mapping",
"=",
"[",
"'current_class'",
"=>",
"'currentClass'",
",",
"'first_class'",
"=>",
"'firstClass'",
",",
"'last_class'",
"=>",
"'lastClass'",
",",
"'safe_labels'",
"=>... | Replaces setting keys with knp menu item options keys.
@param array $settings
@return array | [
"Replaces",
"setting",
"keys",
"with",
"knp",
"menu",
"item",
"options",
"keys",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/Service/MenuBlockService.php#L245-L264 |
sonata-project/SonataBlockBundle | src/DependencyInjection/SonataBlockExtension.php | SonataBlockExtension.getConfiguration | final public function getConfiguration(array $config, ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$defaultTemplates = [];
if (isset($bundles['SonataPageBundle'])) {
$defaultTemplates['@SonataPage/Block/block_container.html.twig'] = 'SonataPageBundle default template';
} else {
$defaultTemplates['@SonataBlock/Block/block_container.html.twig'] = 'SonataBlockBundle default template';
}
if (isset($bundles['SonataSeoBundle'])) {
$defaultTemplates['@SonataSeo/Block/block_social_container.html.twig'] = 'SonataSeoBundle (to contain social buttons)';
}
return new Configuration($defaultTemplates);
} | php | final public function getConfiguration(array $config, ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$defaultTemplates = [];
if (isset($bundles['SonataPageBundle'])) {
$defaultTemplates['@SonataPage/Block/block_container.html.twig'] = 'SonataPageBundle default template';
} else {
$defaultTemplates['@SonataBlock/Block/block_container.html.twig'] = 'SonataBlockBundle default template';
}
if (isset($bundles['SonataSeoBundle'])) {
$defaultTemplates['@SonataSeo/Block/block_social_container.html.twig'] = 'SonataSeoBundle (to contain social buttons)';
}
return new Configuration($defaultTemplates);
} | [
"final",
"public",
"function",
"getConfiguration",
"(",
"array",
"$",
"config",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"bundles",
"=",
"$",
"container",
"->",
"getParameter",
"(",
"'kernel.bundles'",
")",
";",
"$",
"defaultTemplates",
"=",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/DependencyInjection/SonataBlockExtension.php#L32-L48 |
sonata-project/SonataBlockBundle | src/DependencyInjection/SonataBlockExtension.php | SonataBlockExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$processor = new Processor();
$configuration = $this->getConfiguration($configs, $container);
$config = $processor->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('block.xml');
$loader->load('form.xml');
$loader->load('core.xml');
$loader->load('exception.xml');
$loader->load('commands.xml');
$this->fixConfigurationDeprecation($config);
$this->configureBlockContainers($container, $config);
$this->configureContext($container, $config);
$this->configureLoaderChain($container, $config);
$this->configureCache($container, $config);
$this->configureForm($container, $config);
$this->configureProfiler($container, $config);
$this->configureException($container, $config);
$this->configureMenus($container, $config);
if (\PHP_VERSION_ID < 70000) {
$this->configureClassesToCompile();
}
if (null === $config['templates']['block_base']) {
if (isset($bundles['SonataPageBundle'])) {
$config['templates']['block_base'] = '@SonataPage/Block/block_base.html.twig';
$config['templates']['block_container'] = '@SonataPage/Block/block_container.html.twig';
} else {
$config['templates']['block_base'] = '@SonataBlock/Block/block_base.html.twig';
$config['templates']['block_container'] = '@SonataBlock/Block/block_container.html.twig';
}
}
$container->getDefinition('sonata.block.twig.global')->replaceArgument(0, $config['templates']);
} | php | public function load(array $configs, ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
$processor = new Processor();
$configuration = $this->getConfiguration($configs, $container);
$config = $processor->processConfiguration($configuration, $configs);
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('block.xml');
$loader->load('form.xml');
$loader->load('core.xml');
$loader->load('exception.xml');
$loader->load('commands.xml');
$this->fixConfigurationDeprecation($config);
$this->configureBlockContainers($container, $config);
$this->configureContext($container, $config);
$this->configureLoaderChain($container, $config);
$this->configureCache($container, $config);
$this->configureForm($container, $config);
$this->configureProfiler($container, $config);
$this->configureException($container, $config);
$this->configureMenus($container, $config);
if (\PHP_VERSION_ID < 70000) {
$this->configureClassesToCompile();
}
if (null === $config['templates']['block_base']) {
if (isset($bundles['SonataPageBundle'])) {
$config['templates']['block_base'] = '@SonataPage/Block/block_base.html.twig';
$config['templates']['block_container'] = '@SonataPage/Block/block_container.html.twig';
} else {
$config['templates']['block_base'] = '@SonataBlock/Block/block_base.html.twig';
$config['templates']['block_container'] = '@SonataBlock/Block/block_container.html.twig';
}
}
$container->getDefinition('sonata.block.twig.global')->replaceArgument(0, $config['templates']);
} | [
"public",
"function",
"load",
"(",
"array",
"$",
"configs",
",",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"bundles",
"=",
"$",
"container",
"->",
"getParameter",
"(",
"'kernel.bundles'",
")",
";",
"$",
"processor",
"=",
"new",
"Processor",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/DependencyInjection/SonataBlockExtension.php#L53-L93 |
sonata-project/SonataBlockBundle | src/DependencyInjection/SonataBlockExtension.php | SonataBlockExtension.configureProfiler | public function configureProfiler(ContainerBuilder $container, array $config)
{
$container->setAlias('sonata.block.renderer', 'sonata.block.renderer.default');
if (!$config['profiler']['enabled']) {
return;
}
// add the block data collector
$definition = new Definition('Sonata\BlockBundle\Profiler\DataCollector\BlockDataCollector');
$definition->setPublic(false);
$definition->addTag('data_collector', ['id' => 'block', 'template' => $config['profiler']['template']]);
$definition->addArgument(new Reference('sonata.block.templating.helper'));
$definition->addArgument($config['container']['types']);
$container->setDefinition('sonata.block.data_collector', $definition);
} | php | public function configureProfiler(ContainerBuilder $container, array $config)
{
$container->setAlias('sonata.block.renderer', 'sonata.block.renderer.default');
if (!$config['profiler']['enabled']) {
return;
}
// add the block data collector
$definition = new Definition('Sonata\BlockBundle\Profiler\DataCollector\BlockDataCollector');
$definition->setPublic(false);
$definition->addTag('data_collector', ['id' => 'block', 'template' => $config['profiler']['template']]);
$definition->addArgument(new Reference('sonata.block.templating.helper'));
$definition->addArgument($config['container']['types']);
$container->setDefinition('sonata.block.data_collector', $definition);
} | [
"public",
"function",
"configureProfiler",
"(",
"ContainerBuilder",
"$",
"container",
",",
"array",
"$",
"config",
")",
"{",
"$",
"container",
"->",
"setAlias",
"(",
"'sonata.block.renderer'",
",",
"'sonata.block.renderer.default'",
")",
";",
"if",
"(",
"!",
"$",
... | Configures the block profiler.
@param ContainerBuilder $container Container
@param array $config Configuration | [
"Configures",
"the",
"block",
"profiler",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/DependencyInjection/SonataBlockExtension.php#L213-L229 |
sonata-project/SonataBlockBundle | src/DependencyInjection/SonataBlockExtension.php | SonataBlockExtension.configureException | public function configureException(ContainerBuilder $container, array $config)
{
// retrieve available filters
$filters = [];
foreach ($config['exception']['filters'] as $name => $filter) {
$filters[$name] = $filter;
}
// retrieve available renderers
$renderers = [];
foreach ($config['exception']['renderers'] as $name => $renderer) {
$renderers[$name] = $renderer;
}
// retrieve block customization
$blockFilters = [];
$blockRenderers = [];
foreach ($config['blocks'] as $service => $settings) {
if (isset($settings['exception'], $settings['exception']['filter'])) {
$blockFilters[$service] = $settings['exception']['filter'];
}
if (isset($settings['exception'], $settings['exception']['renderer'])) {
$blockRenderers[$service] = $settings['exception']['renderer'];
}
}
$definition = $container->getDefinition('sonata.block.exception.strategy.manager');
$definition->replaceArgument(1, $filters);
$definition->replaceArgument(2, $renderers);
$definition->replaceArgument(3, $blockFilters);
$definition->replaceArgument(4, $blockRenderers);
// retrieve default values
$defaultFilter = $config['exception']['default']['filter'];
$defaultRenderer = $config['exception']['default']['renderer'];
$definition->addMethodCall('setDefaultFilter', [$defaultFilter]);
$definition->addMethodCall('setDefaultRenderer', [$defaultRenderer]);
} | php | public function configureException(ContainerBuilder $container, array $config)
{
// retrieve available filters
$filters = [];
foreach ($config['exception']['filters'] as $name => $filter) {
$filters[$name] = $filter;
}
// retrieve available renderers
$renderers = [];
foreach ($config['exception']['renderers'] as $name => $renderer) {
$renderers[$name] = $renderer;
}
// retrieve block customization
$blockFilters = [];
$blockRenderers = [];
foreach ($config['blocks'] as $service => $settings) {
if (isset($settings['exception'], $settings['exception']['filter'])) {
$blockFilters[$service] = $settings['exception']['filter'];
}
if (isset($settings['exception'], $settings['exception']['renderer'])) {
$blockRenderers[$service] = $settings['exception']['renderer'];
}
}
$definition = $container->getDefinition('sonata.block.exception.strategy.manager');
$definition->replaceArgument(1, $filters);
$definition->replaceArgument(2, $renderers);
$definition->replaceArgument(3, $blockFilters);
$definition->replaceArgument(4, $blockRenderers);
// retrieve default values
$defaultFilter = $config['exception']['default']['filter'];
$defaultRenderer = $config['exception']['default']['renderer'];
$definition->addMethodCall('setDefaultFilter', [$defaultFilter]);
$definition->addMethodCall('setDefaultRenderer', [$defaultRenderer]);
} | [
"public",
"function",
"configureException",
"(",
"ContainerBuilder",
"$",
"container",
",",
"array",
"$",
"config",
")",
"{",
"// retrieve available filters",
"$",
"filters",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"config",
"[",
"'exception'",
"]",
"[",
"'fi... | Configure the exception parameters.
@param ContainerBuilder $container Container builder
@param array $config An array of configuration | [
"Configure",
"the",
"exception",
"parameters",
"."
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/DependencyInjection/SonataBlockExtension.php#L237-L274 |
sonata-project/SonataBlockBundle | src/Exception/Renderer/InlineDebugRenderer.php | InlineDebugRenderer.render | public function render(\Exception $exception, BlockInterface $block, Response $response = null)
{
$response = $response ?: new Response();
// enforce debug mode or ignore silently
if (!$this->debug) {
return $response;
}
$flattenException = FlattenException::create($exception);
$code = $flattenException->getStatusCode();
$parameters = [
'exception' => $flattenException,
'status_code' => $code,
'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '',
'logger' => false,
'currentContent' => false,
'block' => $block,
'forceStyle' => $this->forceStyle,
];
$content = $this->templating->render($this->template, $parameters);
$response->setContent($content);
return $response;
} | php | public function render(\Exception $exception, BlockInterface $block, Response $response = null)
{
$response = $response ?: new Response();
// enforce debug mode or ignore silently
if (!$this->debug) {
return $response;
}
$flattenException = FlattenException::create($exception);
$code = $flattenException->getStatusCode();
$parameters = [
'exception' => $flattenException,
'status_code' => $code,
'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '',
'logger' => false,
'currentContent' => false,
'block' => $block,
'forceStyle' => $this->forceStyle,
];
$content = $this->templating->render($this->template, $parameters);
$response->setContent($content);
return $response;
} | [
"public",
"function",
"render",
"(",
"\\",
"Exception",
"$",
"exception",
",",
"BlockInterface",
"$",
"block",
",",
"Response",
"$",
"response",
"=",
"null",
")",
"{",
"$",
"response",
"=",
"$",
"response",
"?",
":",
"new",
"Response",
"(",
")",
";",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Exception/Renderer/InlineDebugRenderer.php#L65-L91 |
sonata-project/SonataBlockBundle | src/Model/BaseBlock.php | BaseBlock.getSetting | public function getSetting($name, $default = null)
{
return isset($this->settings[$name]) ? $this->settings[$name] : $default;
} | php | public function getSetting($name, $default = null)
{
return isset($this->settings[$name]) ? $this->settings[$name] : $default;
} | [
"public",
"function",
"getSetting",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"settings",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"settings",
"[",
"$",
"name",
"]",
":",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Model/BaseBlock.php#L145-L148 |
sonata-project/SonataBlockBundle | src/Model/BaseBlock.php | BaseBlock.getTtl | public function getTtl()
{
if (!$this->getSetting('use_cache', true)) {
return 0;
}
$ttl = $this->getSetting('ttl', 86400);
foreach ($this->getChildren() as $block) {
$blockTtl = $block->getTtl();
$ttl = ($blockTtl < $ttl) ? $blockTtl : $ttl;
}
$this->ttl = $ttl;
return $this->ttl;
} | php | public function getTtl()
{
if (!$this->getSetting('use_cache', true)) {
return 0;
}
$ttl = $this->getSetting('ttl', 86400);
foreach ($this->getChildren() as $block) {
$blockTtl = $block->getTtl();
$ttl = ($blockTtl < $ttl) ? $blockTtl : $ttl;
}
$this->ttl = $ttl;
return $this->ttl;
} | [
"public",
"function",
"getTtl",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getSetting",
"(",
"'use_cache'",
",",
"true",
")",
")",
"{",
"return",
"0",
";",
"}",
"$",
"ttl",
"=",
"$",
"this",
"->",
"getSetting",
"(",
"'ttl'",
",",
"86400",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Model/BaseBlock.php#L259-L276 |
sonata-project/SonataBlockBundle | src/Cache/HttpCacheHandler.php | HttpCacheHandler.alterResponse | public function alterResponse(Response $response)
{
if (!$response->isCacheable()) {
// the controller flags the response as private so we keep it private!
return;
}
// no block has been rendered
if (null === $this->currentTtl) {
return;
}
// a block has a lower ttl that the current response, so we update the ttl to match
// the one provided in the block
if ($this->currentTtl < $response->getTtl()) {
$response->setTtl($this->currentTtl);
}
} | php | public function alterResponse(Response $response)
{
if (!$response->isCacheable()) {
// the controller flags the response as private so we keep it private!
return;
}
// no block has been rendered
if (null === $this->currentTtl) {
return;
}
// a block has a lower ttl that the current response, so we update the ttl to match
// the one provided in the block
if ($this->currentTtl < $response->getTtl()) {
$response->setTtl($this->currentTtl);
}
} | [
"public",
"function",
"alterResponse",
"(",
"Response",
"$",
"response",
")",
"{",
"if",
"(",
"!",
"$",
"response",
"->",
"isCacheable",
"(",
")",
")",
"{",
"// the controller flags the response as private so we keep it private!",
"return",
";",
"}",
"// no block has ... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Cache/HttpCacheHandler.php#L30-L47 |
sonata-project/SonataBlockBundle | src/Cache/HttpCacheHandler.php | HttpCacheHandler.updateMetadata | public function updateMetadata(Response $response, BlockContextInterface $blockContext = null)
{
if (null === $this->currentTtl) {
$this->currentTtl = $response->getTtl();
}
if (null !== $response->isCacheable() && $response->getTtl() < $this->currentTtl) {
$this->currentTtl = $response->getTtl();
}
} | php | public function updateMetadata(Response $response, BlockContextInterface $blockContext = null)
{
if (null === $this->currentTtl) {
$this->currentTtl = $response->getTtl();
}
if (null !== $response->isCacheable() && $response->getTtl() < $this->currentTtl) {
$this->currentTtl = $response->getTtl();
}
} | [
"public",
"function",
"updateMetadata",
"(",
"Response",
"$",
"response",
",",
"BlockContextInterface",
"$",
"blockContext",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"currentTtl",
")",
"{",
"$",
"this",
"->",
"currentTtl",
"=",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Cache/HttpCacheHandler.php#L52-L61 |
sonata-project/SonataBlockBundle | src/DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('sonata_block');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$node = $treeBuilder->root('sonata_block');
} else {
$node = $treeBuilder->getRootNode();
}
$node
->fixXmlConfig('default_context')
->fixXmlConfig('template')
->fixXmlConfig('block')
->fixXmlConfig('block_by_class')
->validate()
->always(static function ($value) {
foreach ($value['blocks'] as $name => &$block) {
if (0 === \count($block['contexts'])) {
$block['contexts'] = $value['default_contexts'];
}
}
if (isset($value['profiler']['container_types']) && !empty($value['profiler']['container_types'])
&& isset($value['container']['types']) && !empty($value['container']['types'])
&& 0 !== \count(array_diff($value['profiler']['container_types'], $value['container']['types']))) {
throw new \RuntimeException('You cannot have different config options for sonata_block.profiler.container_types and sonata_block.container.types; the first one is deprecated, in case of doubt use the latter');
}
return $value;
})
->end()
->children()
->arrayNode('profiler')
->addDefaultsIfNotSet()
->fixXmlConfig('container_type', 'container_types')
->children()
->scalarNode('enabled')->defaultValue('%kernel.debug%')->end()
->scalarNode('template')->defaultValue('@SonataBlock/Profiler/block.html.twig')->end()
->arrayNode('container_types')
->isRequired()
// add default value to well know users of BlockBundle
->defaultValue(['sonata.block.service.container', 'sonata.page.block.container', 'sonata.dashboard.block.container', 'cmf.block.container', 'cmf.block.slideshow'])
->prototype('scalar')->end()
->end()
->end()
->end()
->arrayNode('default_contexts')
->prototype('scalar')->end()
->end()
->scalarNode('context_manager')->defaultValue('sonata.block.context_manager.default')->end()
->arrayNode('http_cache')
->addDefaultsIfNotSet()
->children()
->scalarNode('handler')->defaultValue('sonata.block.cache.handler.default')->end()
->booleanNode('listener')->defaultTrue()->end()
->end()
->end()
->arrayNode('templates')
->addDefaultsIfNotSet()
->children()
->scalarNode('block_base')->defaultNull()->end()
->scalarNode('block_container')->defaultNull()->end()
->end()
->end()
->arrayNode('container')
->info('block container configuration')
->addDefaultsIfNotSet()
->fixXmlConfig('type', 'types')
->fixXmlConfig('template', 'templates')
->children()
->arrayNode('types')
->info('container service ids')
->isRequired()
// add default value to well know users of BlockBundle
->defaultValue(['sonata.block.service.container', 'sonata.page.block.container', 'sonata.dashboard.block.container', 'cmf.block.container', 'cmf.block.slideshow'])
->prototype('scalar')->end()
->end()
->arrayNode('templates')
->info('container templates')
->isRequired()
->defaultValue($this->defaultContainerTemplates)
->prototype('scalar')->end()
->end()
->end()
->end()
->arrayNode('blocks')
->info('configuration per block service')
->useAttributeAsKey('id')
->prototype('array')
->fixXmlConfig('context')
->fixXmlConfig('template')
->fixXmlConfig('setting')
->children()
->arrayNode('contexts')
->prototype('scalar')->end()
->end()
->arrayNode('templates')
->prototype('array')
->children()
->scalarNode('name')->cannotBeEmpty()->end()
->scalarNode('template')->cannotBeEmpty()->end()
->end()
->end()
->end()
->scalarNode('cache')->defaultValue('sonata.cache.noop')->end()
->arrayNode('settings')
->info('default settings')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->end()
->arrayNode('exception')
->children()
->scalarNode('filter')->defaultNull()->end()
->scalarNode('renderer')->defaultNull()->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('menus')
->info('KNP Menus available in sonata.block.menu block configuration')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->validate()
->always(static function ($value) {
if (\count($value) > 0) {
@trigger_error(
'The menus configuration key is deprecated since 3.3 and will be removed in 4.0.',
E_USER_DEPRECATED
);
}
return $value;
})
->end()
->end()
->arrayNode('blocks_by_class')
->info('configuration per block class')
->useAttributeAsKey('class')
->prototype('array')
->fixXmlConfig('setting')
->children()
->scalarNode('cache')->defaultValue('sonata.cache.noop')->end()
->arrayNode('settings')
->info('default settings')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->arrayNode('exception')
->addDefaultsIfNotSet()
->fixXmlConfig('filter')
->fixXmlConfig('renderer')
->children()
->arrayNode('default')
->addDefaultsIfNotSet()
->children()
->scalarNode('filter')->defaultValue('debug_only')->end()
->scalarNode('renderer')->defaultValue('throw')->end()
->end()
->end()
->arrayNode('filters')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->defaultValue([
'debug_only' => 'sonata.block.exception.filter.debug_only',
'ignore_block_exception' => 'sonata.block.exception.filter.ignore_block_exception',
'keep_all' => 'sonata.block.exception.filter.keep_all',
'keep_none' => 'sonata.block.exception.filter.keep_none',
])
->end()
->arrayNode('renderers')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->defaultValue([
'inline' => 'sonata.block.exception.renderer.inline',
'inline_debug' => 'sonata.block.exception.renderer.inline_debug',
'throw' => 'sonata.block.exception.renderer.throw',
])
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('sonata_block');
// Keep compatibility with symfony/config < 4.2
if (!method_exists($treeBuilder, 'getRootNode')) {
$node = $treeBuilder->root('sonata_block');
} else {
$node = $treeBuilder->getRootNode();
}
$node
->fixXmlConfig('default_context')
->fixXmlConfig('template')
->fixXmlConfig('block')
->fixXmlConfig('block_by_class')
->validate()
->always(static function ($value) {
foreach ($value['blocks'] as $name => &$block) {
if (0 === \count($block['contexts'])) {
$block['contexts'] = $value['default_contexts'];
}
}
if (isset($value['profiler']['container_types']) && !empty($value['profiler']['container_types'])
&& isset($value['container']['types']) && !empty($value['container']['types'])
&& 0 !== \count(array_diff($value['profiler']['container_types'], $value['container']['types']))) {
throw new \RuntimeException('You cannot have different config options for sonata_block.profiler.container_types and sonata_block.container.types; the first one is deprecated, in case of doubt use the latter');
}
return $value;
})
->end()
->children()
->arrayNode('profiler')
->addDefaultsIfNotSet()
->fixXmlConfig('container_type', 'container_types')
->children()
->scalarNode('enabled')->defaultValue('%kernel.debug%')->end()
->scalarNode('template')->defaultValue('@SonataBlock/Profiler/block.html.twig')->end()
->arrayNode('container_types')
->isRequired()
// add default value to well know users of BlockBundle
->defaultValue(['sonata.block.service.container', 'sonata.page.block.container', 'sonata.dashboard.block.container', 'cmf.block.container', 'cmf.block.slideshow'])
->prototype('scalar')->end()
->end()
->end()
->end()
->arrayNode('default_contexts')
->prototype('scalar')->end()
->end()
->scalarNode('context_manager')->defaultValue('sonata.block.context_manager.default')->end()
->arrayNode('http_cache')
->addDefaultsIfNotSet()
->children()
->scalarNode('handler')->defaultValue('sonata.block.cache.handler.default')->end()
->booleanNode('listener')->defaultTrue()->end()
->end()
->end()
->arrayNode('templates')
->addDefaultsIfNotSet()
->children()
->scalarNode('block_base')->defaultNull()->end()
->scalarNode('block_container')->defaultNull()->end()
->end()
->end()
->arrayNode('container')
->info('block container configuration')
->addDefaultsIfNotSet()
->fixXmlConfig('type', 'types')
->fixXmlConfig('template', 'templates')
->children()
->arrayNode('types')
->info('container service ids')
->isRequired()
// add default value to well know users of BlockBundle
->defaultValue(['sonata.block.service.container', 'sonata.page.block.container', 'sonata.dashboard.block.container', 'cmf.block.container', 'cmf.block.slideshow'])
->prototype('scalar')->end()
->end()
->arrayNode('templates')
->info('container templates')
->isRequired()
->defaultValue($this->defaultContainerTemplates)
->prototype('scalar')->end()
->end()
->end()
->end()
->arrayNode('blocks')
->info('configuration per block service')
->useAttributeAsKey('id')
->prototype('array')
->fixXmlConfig('context')
->fixXmlConfig('template')
->fixXmlConfig('setting')
->children()
->arrayNode('contexts')
->prototype('scalar')->end()
->end()
->arrayNode('templates')
->prototype('array')
->children()
->scalarNode('name')->cannotBeEmpty()->end()
->scalarNode('template')->cannotBeEmpty()->end()
->end()
->end()
->end()
->scalarNode('cache')->defaultValue('sonata.cache.noop')->end()
->arrayNode('settings')
->info('default settings')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->end()
->arrayNode('exception')
->children()
->scalarNode('filter')->defaultNull()->end()
->scalarNode('renderer')->defaultNull()->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('menus')
->info('KNP Menus available in sonata.block.menu block configuration')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->validate()
->always(static function ($value) {
if (\count($value) > 0) {
@trigger_error(
'The menus configuration key is deprecated since 3.3 and will be removed in 4.0.',
E_USER_DEPRECATED
);
}
return $value;
})
->end()
->end()
->arrayNode('blocks_by_class')
->info('configuration per block class')
->useAttributeAsKey('class')
->prototype('array')
->fixXmlConfig('setting')
->children()
->scalarNode('cache')->defaultValue('sonata.cache.noop')->end()
->arrayNode('settings')
->info('default settings')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->arrayNode('exception')
->addDefaultsIfNotSet()
->fixXmlConfig('filter')
->fixXmlConfig('renderer')
->children()
->arrayNode('default')
->addDefaultsIfNotSet()
->children()
->scalarNode('filter')->defaultValue('debug_only')->end()
->scalarNode('renderer')->defaultValue('throw')->end()
->end()
->end()
->arrayNode('filters')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->defaultValue([
'debug_only' => 'sonata.block.exception.filter.debug_only',
'ignore_block_exception' => 'sonata.block.exception.filter.ignore_block_exception',
'keep_all' => 'sonata.block.exception.filter.keep_all',
'keep_none' => 'sonata.block.exception.filter.keep_none',
])
->end()
->arrayNode('renderers')
->useAttributeAsKey('id')
->prototype('scalar')->end()
->defaultValue([
'inline' => 'sonata.block.exception.renderer.inline',
'inline_debug' => 'sonata.block.exception.renderer.inline_debug',
'throw' => 'sonata.block.exception.renderer.throw',
])
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | [
"public",
"function",
"getConfigTreeBuilder",
"(",
")",
"{",
"$",
"treeBuilder",
"=",
"new",
"TreeBuilder",
"(",
"'sonata_block'",
")",
";",
"// Keep compatibility with symfony/config < 4.2",
"if",
"(",
"!",
"method_exists",
"(",
"$",
"treeBuilder",
",",
"'getRootNode... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/DependencyInjection/Configuration.php#L43-L242 |
sonata-project/SonataBlockBundle | src/Block/BlockServiceManager.php | BlockServiceManager.get | public function get(BlockInterface $block)
{
$this->load($block->getType());
return $this->services[$block->getType()];
} | php | public function get(BlockInterface $block)
{
$this->load($block->getType());
return $this->services[$block->getType()];
} | [
"public",
"function",
"get",
"(",
"BlockInterface",
"$",
"block",
")",
"{",
"$",
"this",
"->",
"load",
"(",
"$",
"block",
"->",
"getType",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"services",
"[",
"$",
"block",
"->",
"getType",
"(",
")",
"]... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockServiceManager.php#L58-L63 |
sonata-project/SonataBlockBundle | src/Block/BlockServiceManager.php | BlockServiceManager.add | public function add($name, $service, $contexts = [])
{
$this->services[$name] = $service;
foreach ($contexts as $context) {
if (!\array_key_exists($context, $this->contexts)) {
$this->contexts[$context] = [];
}
$this->contexts[$context][] = $name;
}
} | php | public function add($name, $service, $contexts = [])
{
$this->services[$name] = $service;
foreach ($contexts as $context) {
if (!\array_key_exists($context, $this->contexts)) {
$this->contexts[$context] = [];
}
$this->contexts[$context][] = $name;
}
} | [
"public",
"function",
"add",
"(",
"$",
"name",
",",
"$",
"service",
",",
"$",
"contexts",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"services",
"[",
"$",
"name",
"]",
"=",
"$",
"service",
";",
"foreach",
"(",
"$",
"contexts",
"as",
"$",
"contex... | {@inheritdoc} | [
"{"
] | train | https://github.com/sonata-project/SonataBlockBundle/blob/476049cbb193c4cef741d031cf8e9cb056268af8/src/Block/BlockServiceManager.php#L84-L95 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.