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
ClassPreloader/ClassPreloader
src/ClassPreloader.php
ClassPreloader.getCode
public function getCode($file, $comments = true) { if (!is_string($file) || empty($file)) { throw new RuntimeException('Invalid filename provided.'); } if (!is_readable($file)) { throw new RuntimeException("Cannot open $file for reading."); } if ($comments) { $content = file_get_contents($file); } else { $content = php_strip_whitespace($file); } $parsed = $this->parser->parse($content); $stmts = $this->traverser->traverseFile($parsed, $file); $pretty = $this->printer->prettyPrint($stmts); $pretty = preg_replace( '#^(<\?php)?[\s]*(/\*\*?.*?\*/)?[\s]*(declare[\s]*\([\s]*strict_types[\s]*=[\s]*1[\s]*\);)?#s', '', $pretty ); return $this->getCodeWrappedIntoNamespace($parsed, $pretty); }
php
public function getCode($file, $comments = true) { if (!is_string($file) || empty($file)) { throw new RuntimeException('Invalid filename provided.'); } if (!is_readable($file)) { throw new RuntimeException("Cannot open $file for reading."); } if ($comments) { $content = file_get_contents($file); } else { $content = php_strip_whitespace($file); } $parsed = $this->parser->parse($content); $stmts = $this->traverser->traverseFile($parsed, $file); $pretty = $this->printer->prettyPrint($stmts); $pretty = preg_replace( '#^(<\?php)?[\s]*(/\*\*?.*?\*/)?[\s]*(declare[\s]*\([\s]*strict_types[\s]*=[\s]*1[\s]*\);)?#s', '', $pretty ); return $this->getCodeWrappedIntoNamespace($parsed, $pretty); }
[ "public", "function", "getCode", "(", "$", "file", ",", "$", "comments", "=", "true", ")", "{", "if", "(", "!", "is_string", "(", "$", "file", ")", "||", "empty", "(", "$", "file", ")", ")", "{", "throw", "new", "RuntimeException", "(", "'Invalid filename provided.'", ")", ";", "}", "if", "(", "!", "is_readable", "(", "$", "file", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Cannot open $file for reading.\"", ")", ";", "}", "if", "(", "$", "comments", ")", "{", "$", "content", "=", "file_get_contents", "(", "$", "file", ")", ";", "}", "else", "{", "$", "content", "=", "php_strip_whitespace", "(", "$", "file", ")", ";", "}", "$", "parsed", "=", "$", "this", "->", "parser", "->", "parse", "(", "$", "content", ")", ";", "$", "stmts", "=", "$", "this", "->", "traverser", "->", "traverseFile", "(", "$", "parsed", ",", "$", "file", ")", ";", "$", "pretty", "=", "$", "this", "->", "printer", "->", "prettyPrint", "(", "$", "stmts", ")", ";", "$", "pretty", "=", "preg_replace", "(", "'#^(<\\?php)?[\\s]*(/\\*\\*?.*?\\*/)?[\\s]*(declare[\\s]*\\([\\s]*strict_types[\\s]*=[\\s]*1[\\s]*\\);)?#s'", ",", "''", ",", "$", "pretty", ")", ";", "return", "$", "this", "->", "getCodeWrappedIntoNamespace", "(", "$", "parsed", ",", "$", "pretty", ")", ";", "}" ]
Get a pretty printed string of code from a file while applying visitors. @param string $file @throws \RuntimeException @return string
[ "Get", "a", "pretty", "printed", "string", "of", "code", "from", "a", "file", "while", "applying", "visitors", "." ]
train
https://github.com/ClassPreloader/ClassPreloader/blob/4729e438e0ada350f91148e7d4bb9809342575ff/src/ClassPreloader.php#L111-L138
ClassPreloader/ClassPreloader
src/ClassPreloader.php
ClassPreloader.getCodeWrappedIntoNamespace
protected function getCodeWrappedIntoNamespace(array $parsed, $pretty) { if ($this->parsedCodeHasNamespaces($parsed)) { $pretty = preg_replace('/^\s*(namespace.*);/im', '${1} {', $pretty, 1)."\n}\n"; } else { $pretty = sprintf("namespace {\n%s\n}\n", $pretty); } return preg_replace('/(?<!.)[\r\n]+/', '', $pretty); }
php
protected function getCodeWrappedIntoNamespace(array $parsed, $pretty) { if ($this->parsedCodeHasNamespaces($parsed)) { $pretty = preg_replace('/^\s*(namespace.*);/im', '${1} {', $pretty, 1)."\n}\n"; } else { $pretty = sprintf("namespace {\n%s\n}\n", $pretty); } return preg_replace('/(?<!.)[\r\n]+/', '', $pretty); }
[ "protected", "function", "getCodeWrappedIntoNamespace", "(", "array", "$", "parsed", ",", "$", "pretty", ")", "{", "if", "(", "$", "this", "->", "parsedCodeHasNamespaces", "(", "$", "parsed", ")", ")", "{", "$", "pretty", "=", "preg_replace", "(", "'/^\\s*(namespace.*);/im'", ",", "'${1} {'", ",", "$", "pretty", ",", "1", ")", ".", "\"\\n}\\n\"", ";", "}", "else", "{", "$", "pretty", "=", "sprintf", "(", "\"namespace {\\n%s\\n}\\n\"", ",", "$", "pretty", ")", ";", "}", "return", "preg_replace", "(", "'/(?<!.)[\\r\\n]+/'", ",", "''", ",", "$", "pretty", ")", ";", "}" ]
Wrap the code into a namespace. @param array $parsed @param string $pretty @return string
[ "Wrap", "the", "code", "into", "a", "namespace", "." ]
train
https://github.com/ClassPreloader/ClassPreloader/blob/4729e438e0ada350f91148e7d4bb9809342575ff/src/ClassPreloader.php#L148-L157
ClassPreloader/ClassPreloader
src/ClassPreloader.php
ClassPreloader.parsedCodeHasNamespaces
protected function parsedCodeHasNamespaces(array $parsed) { // Namespaces can only be on first level in the code, // so we make only check on it. $node = array_filter( $parsed, function ($value) { return $value instanceof NamespaceNode; } ); return !empty($node); }
php
protected function parsedCodeHasNamespaces(array $parsed) { // Namespaces can only be on first level in the code, // so we make only check on it. $node = array_filter( $parsed, function ($value) { return $value instanceof NamespaceNode; } ); return !empty($node); }
[ "protected", "function", "parsedCodeHasNamespaces", "(", "array", "$", "parsed", ")", "{", "// Namespaces can only be on first level in the code,", "// so we make only check on it.", "$", "node", "=", "array_filter", "(", "$", "parsed", ",", "function", "(", "$", "value", ")", "{", "return", "$", "value", "instanceof", "NamespaceNode", ";", "}", ")", ";", "return", "!", "empty", "(", "$", "node", ")", ";", "}" ]
Check parsed code for having namespaces. @param array $parsed @return bool
[ "Check", "parsed", "code", "for", "having", "namespaces", "." ]
train
https://github.com/ClassPreloader/ClassPreloader/blob/4729e438e0ada350f91148e7d4bb9809342575ff/src/ClassPreloader.php#L166-L178
sebastiaanluca/php-pipe-operator
src/Item.php
Item.pipe
public function pipe($callback, ...$arguments) { if (! is_callable($callback)) { return new PipeProxy($this, $callback); } // Call the piped method $this->value = $callback(...$this->addValueToArguments($arguments)); // Allow method chaining return $this; }
php
public function pipe($callback, ...$arguments) { if (! is_callable($callback)) { return new PipeProxy($this, $callback); } // Call the piped method $this->value = $callback(...$this->addValueToArguments($arguments)); // Allow method chaining return $this; }
[ "public", "function", "pipe", "(", "$", "callback", ",", "...", "$", "arguments", ")", "{", "if", "(", "!", "is_callable", "(", "$", "callback", ")", ")", "{", "return", "new", "PipeProxy", "(", "$", "this", ",", "$", "callback", ")", ";", "}", "// Call the piped method", "$", "this", "->", "value", "=", "$", "callback", "(", "...", "$", "this", "->", "addValueToArguments", "(", "$", "arguments", ")", ")", ";", "// Allow method chaining", "return", "$", "this", ";", "}" ]
Perform an operation on the current value. @param callable|string|object $callback @param array ...$arguments @return \SebastiaanLuca\PipeOperator\Item|\SebastiaanLuca\PipeOperator\PipeProxy
[ "Perform", "an", "operation", "on", "the", "current", "value", "." ]
train
https://github.com/sebastiaanluca/php-pipe-operator/blob/2dc72409863020fcb2afb86daf118131b12bfcdd/src/Item.php#L45-L56
sebastiaanluca/php-pipe-operator
src/Item.php
Item.addValueToArguments
public function addValueToArguments(array $arguments) : array { // If the caller hasn't explicitly specified where they want the value // to be added, we will add it as the first value. Otherwise we will // replace all occurrences of PIPED_VALUE with the original value. if (! in_array(PIPED_VALUE, $arguments, true)) { return array_merge([$this->value], $arguments); } return array_map(function ($argument) { return $argument === PIPED_VALUE ? $this->value : $argument; }, $arguments); }
php
public function addValueToArguments(array $arguments) : array { // If the caller hasn't explicitly specified where they want the value // to be added, we will add it as the first value. Otherwise we will // replace all occurrences of PIPED_VALUE with the original value. if (! in_array(PIPED_VALUE, $arguments, true)) { return array_merge([$this->value], $arguments); } return array_map(function ($argument) { return $argument === PIPED_VALUE ? $this->value : $argument; }, $arguments); }
[ "public", "function", "addValueToArguments", "(", "array", "$", "arguments", ")", ":", "array", "{", "// If the caller hasn't explicitly specified where they want the value", "// to be added, we will add it as the first value. Otherwise we will", "// replace all occurrences of PIPED_VALUE with the original value.", "if", "(", "!", "in_array", "(", "PIPED_VALUE", ",", "$", "arguments", ",", "true", ")", ")", "{", "return", "array_merge", "(", "[", "$", "this", "->", "value", "]", ",", "$", "arguments", ")", ";", "}", "return", "array_map", "(", "function", "(", "$", "argument", ")", "{", "return", "$", "argument", "===", "PIPED_VALUE", "?", "$", "this", "->", "value", ":", "$", "argument", ";", "}", ",", "$", "arguments", ")", ";", "}" ]
Add the given value to the list of arguments. @param array $arguments @return array
[ "Add", "the", "given", "value", "to", "the", "list", "of", "arguments", "." ]
train
https://github.com/sebastiaanluca/php-pipe-operator/blob/2dc72409863020fcb2afb86daf118131b12bfcdd/src/Item.php#L65-L78
klarna/kco_rest_php
src/Klarna/Rest/Transport/Connector.php
Connector.createRequest
public function createRequest($url, $method = 'GET', array $headers = [], $body = null) { $headers = array_merge($headers, ['User-Agent' => strval($this->userAgent)]); return new Request($method, $url, $headers, $body); }
php
public function createRequest($url, $method = 'GET', array $headers = [], $body = null) { $headers = array_merge($headers, ['User-Agent' => strval($this->userAgent)]); return new Request($method, $url, $headers, $body); }
[ "public", "function", "createRequest", "(", "$", "url", ",", "$", "method", "=", "'GET'", ",", "array", "$", "headers", "=", "[", "]", ",", "$", "body", "=", "null", ")", "{", "$", "headers", "=", "array_merge", "(", "$", "headers", ",", "[", "'User-Agent'", "=>", "strval", "(", "$", "this", "->", "userAgent", ")", "]", ")", ";", "return", "new", "Request", "(", "$", "method", ",", "$", "url", ",", "$", "headers", ",", "$", "body", ")", ";", "}" ]
Creates a request object. @param string $url URL @param string $method HTTP method @return RequestInterface
[ "Creates", "a", "request", "object", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Transport/Connector.php#L102-L106
klarna/kco_rest_php
src/Klarna/Rest/Transport/Connector.php
Connector.send
public function send(RequestInterface $request, array $options = []) { $options['auth'] = [$this->merchantId, $this->sharedSecret, 'basic']; try { return $this->client->send($request, $options); } catch (RequestException $e) { if (!$e->hasResponse()) { throw $e; } $response = $e->getResponse(); if (!in_array('application/json', $response->getHeader('Content-Type'))) { throw $e; } $data = \json_decode($response->getBody(), true); if (!is_array($data) || !array_key_exists('error_code', $data)) { throw $e; } throw new ConnectorException($data, $e); } }
php
public function send(RequestInterface $request, array $options = []) { $options['auth'] = [$this->merchantId, $this->sharedSecret, 'basic']; try { return $this->client->send($request, $options); } catch (RequestException $e) { if (!$e->hasResponse()) { throw $e; } $response = $e->getResponse(); if (!in_array('application/json', $response->getHeader('Content-Type'))) { throw $e; } $data = \json_decode($response->getBody(), true); if (!is_array($data) || !array_key_exists('error_code', $data)) { throw $e; } throw new ConnectorException($data, $e); } }
[ "public", "function", "send", "(", "RequestInterface", "$", "request", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "options", "[", "'auth'", "]", "=", "[", "$", "this", "->", "merchantId", ",", "$", "this", "->", "sharedSecret", ",", "'basic'", "]", ";", "try", "{", "return", "$", "this", "->", "client", "->", "send", "(", "$", "request", ",", "$", "options", ")", ";", "}", "catch", "(", "RequestException", "$", "e", ")", "{", "if", "(", "!", "$", "e", "->", "hasResponse", "(", ")", ")", "{", "throw", "$", "e", ";", "}", "$", "response", "=", "$", "e", "->", "getResponse", "(", ")", ";", "if", "(", "!", "in_array", "(", "'application/json'", ",", "$", "response", "->", "getHeader", "(", "'Content-Type'", ")", ")", ")", "{", "throw", "$", "e", ";", "}", "$", "data", "=", "\\", "json_decode", "(", "$", "response", "->", "getBody", "(", ")", ",", "true", ")", ";", "if", "(", "!", "is_array", "(", "$", "data", ")", "||", "!", "array_key_exists", "(", "'error_code'", ",", "$", "data", ")", ")", "{", "throw", "$", "e", ";", "}", "throw", "new", "ConnectorException", "(", "$", "data", ",", "$", "e", ")", ";", "}", "}" ]
Sends the request. @param RequestInterface $request Request to send @param string[] $options Request options @throws ConnectorException If the API returned an error response @throws RequestException When an error is encountered @throws \LogicException When the adapter does not populate a response @return ResponseInterface
[ "Sends", "the", "request", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Transport/Connector.php#L120-L145
klarna/kco_rest_php
src/Klarna/Rest/Transport/Connector.php
Connector.create
public static function create( $merchantId, $sharedSecret, $baseUrl = self::EU_BASE_URL, UserAgentInterface $userAgent = null ) { $client = new Client(['base_uri' => $baseUrl]); return new static($client, $merchantId, $sharedSecret, $userAgent); }
php
public static function create( $merchantId, $sharedSecret, $baseUrl = self::EU_BASE_URL, UserAgentInterface $userAgent = null ) { $client = new Client(['base_uri' => $baseUrl]); return new static($client, $merchantId, $sharedSecret, $userAgent); }
[ "public", "static", "function", "create", "(", "$", "merchantId", ",", "$", "sharedSecret", ",", "$", "baseUrl", "=", "self", "::", "EU_BASE_URL", ",", "UserAgentInterface", "$", "userAgent", "=", "null", ")", "{", "$", "client", "=", "new", "Client", "(", "[", "'base_uri'", "=>", "$", "baseUrl", "]", ")", ";", "return", "new", "static", "(", "$", "client", ",", "$", "merchantId", ",", "$", "sharedSecret", ",", "$", "userAgent", ")", ";", "}" ]
Factory method to create a connector instance. @param string $merchantId Merchant ID @param string $sharedSecret Shared secret @param string $baseUrl Base URL for HTTP requests @param UserAgentInterface $userAgent HTTP user agent to identify the client @return self
[ "Factory", "method", "to", "create", "a", "connector", "instance", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Transport/Connector.php#L177-L186
klarna/kco_rest_php
src/Klarna/Rest/Settlements/Reports.php
Reports.getCSVPayoutsSummaryReport
public function getCSVPayoutsSummaryReport(array $params = []) { return $this->get(self::$path . '/payouts-summary-with-transactions?' . http_build_query($params)) ->status('200') ->contentType('text/csv') ->getBody(); }
php
public function getCSVPayoutsSummaryReport(array $params = []) { return $this->get(self::$path . '/payouts-summary-with-transactions?' . http_build_query($params)) ->status('200') ->contentType('text/csv') ->getBody(); }
[ "public", "function", "getCSVPayoutsSummaryReport", "(", "array", "$", "params", "=", "[", "]", ")", "{", "return", "$", "this", "->", "get", "(", "self", "::", "$", "path", ".", "'/payouts-summary-with-transactions?'", ".", "http_build_query", "(", "$", "params", ")", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'text/csv'", ")", "->", "getBody", "(", ")", ";", "}" ]
Returns CSV summary. @param array $params Additional query params to filter payouts. @see https://developers.klarna.com/api/#settlements-api-get-payouts-summary-report-with-transactions @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return string CSV Summary report
[ "Returns", "CSV", "summary", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Settlements/Reports.php#L121-L127
klarna/kco_rest_php
src/Klarna/Rest/Checkout/Order.php
Order.update
public function update(array $data) { $response = $this->post($this->getLocation(), $data) ->status('200') ->contentType('application/json') ->getJson(); $this->exchangeArray($response); return $this; }
php
public function update(array $data) { $response = $this->post($this->getLocation(), $data) ->status('200') ->contentType('application/json') ->getJson(); $this->exchangeArray($response); return $this; }
[ "public", "function", "update", "(", "array", "$", "data", ")", "{", "$", "response", "=", "$", "this", "->", "post", "(", "$", "this", "->", "getLocation", "(", ")", ",", "$", "data", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "$", "this", "->", "exchangeArray", "(", "$", "response", ")", ";", "return", "$", "this", ";", "}" ]
Updates the resource. @param array $data Update data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return self
[ "Updates", "the", "resource", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Checkout/Order.php#L103-L113
klarna/kco_rest_php
src/Klarna/Rest/Payments/Orders.php
Orders.create
public function create(array $data) { return $this->post($this->getLocation() . '/order', $data) ->status('200') ->contentType('application/json') ->getJson(); }
php
public function create(array $data) { return $this->post($this->getLocation() . '/order', $data) ->status('200') ->contentType('application/json') ->getJson(); }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "return", "$", "this", "->", "post", "(", "$", "this", "->", "getLocation", "(", ")", ".", "'/order'", ",", "$", "data", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "}" ]
Creates the resource. @param array $data Creation data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return array Order data
[ "Creates", "the", "resource", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Payments/Orders.php#L84-L90
klarna/kco_rest_php
src/Klarna/Rest/Payments/Orders.php
Orders.generateToken
public function generateToken(array $data) { $response = $this->post($this->getLocation() . '/customer-token', $data) ->status('200') ->contentType('application/json') ->getJson(); return $response; }
php
public function generateToken(array $data) { $response = $this->post($this->getLocation() . '/customer-token', $data) ->status('200') ->contentType('application/json') ->getJson(); return $response; }
[ "public", "function", "generateToken", "(", "array", "$", "data", ")", "{", "$", "response", "=", "$", "this", "->", "post", "(", "$", "this", "->", "getLocation", "(", ")", ".", "'/customer-token'", ",", "$", "data", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "return", "$", "response", ";", "}" ]
Generates consumer token. @param array $data Token data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return array Token data
[ "Generates", "consumer", "token", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Payments/Orders.php#L129-L137
klarna/kco_rest_php
src/Klarna/Rest/CustomerToken/Tokens.php
Tokens.createOrder
public function createOrder(array $data, $klarnaIdempotencyKey = null) { $headers = ['Content-Type' => 'application/json']; if (!is_null($klarnaIdempotencyKey)) { $headers['Klarna-Idempotency-Key'] = $klarnaIdempotencyKey; } return $this->request( 'POST', $this->getLocation() . '/order', $headers, $data !== null ? \json_encode($data) : null ) ->status('200') ->contentType('application/json') ->getJson(); }
php
public function createOrder(array $data, $klarnaIdempotencyKey = null) { $headers = ['Content-Type' => 'application/json']; if (!is_null($klarnaIdempotencyKey)) { $headers['Klarna-Idempotency-Key'] = $klarnaIdempotencyKey; } return $this->request( 'POST', $this->getLocation() . '/order', $headers, $data !== null ? \json_encode($data) : null ) ->status('200') ->contentType('application/json') ->getJson(); }
[ "public", "function", "createOrder", "(", "array", "$", "data", ",", "$", "klarnaIdempotencyKey", "=", "null", ")", "{", "$", "headers", "=", "[", "'Content-Type'", "=>", "'application/json'", "]", ";", "if", "(", "!", "is_null", "(", "$", "klarnaIdempotencyKey", ")", ")", "{", "$", "headers", "[", "'Klarna-Idempotency-Key'", "]", "=", "$", "klarnaIdempotencyKey", ";", "}", "return", "$", "this", "->", "request", "(", "'POST'", ",", "$", "this", "->", "getLocation", "(", ")", ".", "'/order'", ",", "$", "headers", ",", "$", "data", "!==", "null", "?", "\\", "json_encode", "(", "$", "data", ")", ":", "null", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "}" ]
Creates order using Customer Token. @param array $data Order data @param string $klarnaIdempotencyKey Idempotency Key @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return array created order data
[ "Creates", "order", "using", "Customer", "Token", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/CustomerToken/Tokens.php#L77-L93
klarna/kco_rest_php
src/Klarna/Rest/OrderManagement/Order.php
Order.fetch
public function fetch() { parent::fetch(); // Convert captures data to Capture[] $captures = []; foreach ($this['captures'] as $capture) { $captureId = $capture[Capture::ID_FIELD]; $object = new Capture( $this->connector, $this->getLocation(), $captureId ); $object->exchangeArray($capture); $captures[] = $object; } $this['captures'] = $captures; // Convert refunds data to Refund[] if (isset($this['refunds'])) { $refunds = []; foreach ($this['refunds'] as $refund) { $refundId = null; if (isset($refund[Refund::ID_FIELD])) { $refundId = $refund[Refund::ID_FIELD]; } $object = new Refund( $this->connector, $this->getLocation(), $refundId ); $object->exchangeArray($refund); $refunds[] = $object; } $this['refunds'] = $refunds; } return $this; }
php
public function fetch() { parent::fetch(); // Convert captures data to Capture[] $captures = []; foreach ($this['captures'] as $capture) { $captureId = $capture[Capture::ID_FIELD]; $object = new Capture( $this->connector, $this->getLocation(), $captureId ); $object->exchangeArray($capture); $captures[] = $object; } $this['captures'] = $captures; // Convert refunds data to Refund[] if (isset($this['refunds'])) { $refunds = []; foreach ($this['refunds'] as $refund) { $refundId = null; if (isset($refund[Refund::ID_FIELD])) { $refundId = $refund[Refund::ID_FIELD]; } $object = new Refund( $this->connector, $this->getLocation(), $refundId ); $object->exchangeArray($refund); $refunds[] = $object; } $this['refunds'] = $refunds; } return $this; }
[ "public", "function", "fetch", "(", ")", "{", "parent", "::", "fetch", "(", ")", ";", "// Convert captures data to Capture[]", "$", "captures", "=", "[", "]", ";", "foreach", "(", "$", "this", "[", "'captures'", "]", "as", "$", "capture", ")", "{", "$", "captureId", "=", "$", "capture", "[", "Capture", "::", "ID_FIELD", "]", ";", "$", "object", "=", "new", "Capture", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ",", "$", "captureId", ")", ";", "$", "object", "->", "exchangeArray", "(", "$", "capture", ")", ";", "$", "captures", "[", "]", "=", "$", "object", ";", "}", "$", "this", "[", "'captures'", "]", "=", "$", "captures", ";", "// Convert refunds data to Refund[]", "if", "(", "isset", "(", "$", "this", "[", "'refunds'", "]", ")", ")", "{", "$", "refunds", "=", "[", "]", ";", "foreach", "(", "$", "this", "[", "'refunds'", "]", "as", "$", "refund", ")", "{", "$", "refundId", "=", "null", ";", "if", "(", "isset", "(", "$", "refund", "[", "Refund", "::", "ID_FIELD", "]", ")", ")", "{", "$", "refundId", "=", "$", "refund", "[", "Refund", "::", "ID_FIELD", "]", ";", "}", "$", "object", "=", "new", "Refund", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ",", "$", "refundId", ")", ";", "$", "object", "->", "exchangeArray", "(", "$", "refund", ")", ";", "$", "refunds", "[", "]", "=", "$", "object", ";", "}", "$", "this", "[", "'refunds'", "]", "=", "$", "refunds", ";", "}", "return", "$", "this", ";", "}" ]
Fetches the order. @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return self
[ "Fetches", "the", "order", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/OrderManagement/Order.php#L80-L125
klarna/kco_rest_php
src/Klarna/Rest/OrderManagement/Order.php
Order.refund
public function refund(array $data) { $refund = new Refund($this->connector, $this->getLocation()); $refund->create($data); return $refund; }
php
public function refund(array $data) { $refund = new Refund($this->connector, $this->getLocation()); $refund->create($data); return $refund; }
[ "public", "function", "refund", "(", "array", "$", "data", ")", "{", "$", "refund", "=", "new", "Refund", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ")", ";", "$", "refund", "->", "create", "(", "$", "data", ")", ";", "return", "$", "refund", ";", "}" ]
Refunds an amount of a captured order. @param array $data Refund data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return Refund
[ "Refunds", "an", "amount", "of", "a", "captured", "order", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/OrderManagement/Order.php#L253-L259
klarna/kco_rest_php
src/Klarna/Rest/OrderManagement/Order.php
Order.createCapture
public function createCapture(array $data) { $capture = new Capture($this->connector, $this->getLocation()); $capture->create($data); $this['captures'][] = $capture; return $capture; }
php
public function createCapture(array $data) { $capture = new Capture($this->connector, $this->getLocation()); $capture->create($data); $this['captures'][] = $capture; return $capture; }
[ "public", "function", "createCapture", "(", "array", "$", "data", ")", "{", "$", "capture", "=", "new", "Capture", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ")", ";", "$", "capture", "->", "create", "(", "$", "data", ")", ";", "$", "this", "[", "'captures'", "]", "[", "]", "=", "$", "capture", ";", "return", "$", "capture", ";", "}" ]
Capture all or part of an order. @param array $data Capture data @see Capture::create() For more information on how to create a capture @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return Capture
[ "Capture", "all", "or", "part", "of", "an", "order", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/OrderManagement/Order.php#L294-L303
klarna/kco_rest_php
src/Klarna/Rest/OrderManagement/Order.php
Order.fetchCapture
public function fetchCapture($captureId) { if ($this->offsetExists('captures')) { foreach ($this['captures'] as $capture) { if ($capture->getId() !== $captureId) { continue; } return $capture->fetch(); } } $capture = new Capture($this->connector, $this->getLocation(), $captureId); $capture->fetch(); $this['captures'][] = $capture; return $capture; }
php
public function fetchCapture($captureId) { if ($this->offsetExists('captures')) { foreach ($this['captures'] as $capture) { if ($capture->getId() !== $captureId) { continue; } return $capture->fetch(); } } $capture = new Capture($this->connector, $this->getLocation(), $captureId); $capture->fetch(); $this['captures'][] = $capture; return $capture; }
[ "public", "function", "fetchCapture", "(", "$", "captureId", ")", "{", "if", "(", "$", "this", "->", "offsetExists", "(", "'captures'", ")", ")", "{", "foreach", "(", "$", "this", "[", "'captures'", "]", "as", "$", "capture", ")", "{", "if", "(", "$", "capture", "->", "getId", "(", ")", "!==", "$", "captureId", ")", "{", "continue", ";", "}", "return", "$", "capture", "->", "fetch", "(", ")", ";", "}", "}", "$", "capture", "=", "new", "Capture", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ",", "$", "captureId", ")", ";", "$", "capture", "->", "fetch", "(", ")", ";", "$", "this", "[", "'captures'", "]", "[", "]", "=", "$", "capture", ";", "return", "$", "capture", ";", "}" ]
Fetches the specified capture. @param string $captureId Capture ID @see Capture::fetch() For more information on how to fetch a capture @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return Capture
[ "Fetches", "the", "specified", "capture", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/OrderManagement/Order.php#L321-L339
klarna/kco_rest_php
src/Klarna/Rest/OrderManagement/Order.php
Order.fetchRefund
public function fetchRefund($refundId) { if ($this->offsetExists('refunds')) { foreach ($this['refunds'] as $refund) { if ($refund->getId() !== $refundId) { continue; } return $refund; } } $refund = new Refund($this->connector, $this->getLocation(), $refundId); $refund->fetch(); $this['refunds'][] = $refund; return $refund; }
php
public function fetchRefund($refundId) { if ($this->offsetExists('refunds')) { foreach ($this['refunds'] as $refund) { if ($refund->getId() !== $refundId) { continue; } return $refund; } } $refund = new Refund($this->connector, $this->getLocation(), $refundId); $refund->fetch(); $this['refunds'][] = $refund; return $refund; }
[ "public", "function", "fetchRefund", "(", "$", "refundId", ")", "{", "if", "(", "$", "this", "->", "offsetExists", "(", "'refunds'", ")", ")", "{", "foreach", "(", "$", "this", "[", "'refunds'", "]", "as", "$", "refund", ")", "{", "if", "(", "$", "refund", "->", "getId", "(", ")", "!==", "$", "refundId", ")", "{", "continue", ";", "}", "return", "$", "refund", ";", "}", "}", "$", "refund", "=", "new", "Refund", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ",", "$", "refundId", ")", ";", "$", "refund", "->", "fetch", "(", ")", ";", "$", "this", "[", "'refunds'", "]", "[", "]", "=", "$", "refund", ";", "return", "$", "refund", ";", "}" ]
Fetches the specified refund. @param string $refundId Refund ID @see Refund::fetch() For more information on how to fetch a refund @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return Refund
[ "Fetches", "the", "specified", "refund", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/OrderManagement/Order.php#L357-L375
klarna/kco_rest_php
src/Klarna/Rest/OrderManagement/Order.php
Order.fetchCaptures
public function fetchCaptures() { $captures = new Capture($this->connector, $this->getLocation()); $captures = $captures->fetch()->getArrayCopy(); foreach ($captures as $id => $capture) { $captures[$id] = new Capture($this->connector, $this->getLocation(), $capture['capture_id']); $captures[$id]->exchangeArray($capture); } return $captures; }
php
public function fetchCaptures() { $captures = new Capture($this->connector, $this->getLocation()); $captures = $captures->fetch()->getArrayCopy(); foreach ($captures as $id => $capture) { $captures[$id] = new Capture($this->connector, $this->getLocation(), $capture['capture_id']); $captures[$id]->exchangeArray($capture); } return $captures; }
[ "public", "function", "fetchCaptures", "(", ")", "{", "$", "captures", "=", "new", "Capture", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ")", ";", "$", "captures", "=", "$", "captures", "->", "fetch", "(", ")", "->", "getArrayCopy", "(", ")", ";", "foreach", "(", "$", "captures", "as", "$", "id", "=>", "$", "capture", ")", "{", "$", "captures", "[", "$", "id", "]", "=", "new", "Capture", "(", "$", "this", "->", "connector", ",", "$", "this", "->", "getLocation", "(", ")", ",", "$", "capture", "[", "'capture_id'", "]", ")", ";", "$", "captures", "[", "$", "id", "]", "->", "exchangeArray", "(", "$", "capture", ")", ";", "}", "return", "$", "captures", ";", "}" ]
Fetches all captures. @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return Capture[]
[ "Fetches", "all", "captures", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/OrderManagement/Order.php#L389-L399
klarna/kco_rest_php
src/Klarna/Rest/MerchantCardService/VCCSettlements.php
VCCSettlements.create
public function create(array $data) { $response = $this->post(self::$path, $data) ->status('201') ->contentType('application/json') ->getJson(); return $response; }
php
public function create(array $data) { $response = $this->post(self::$path, $data) ->status('201') ->contentType('application/json') ->getJson(); return $response; }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "$", "response", "=", "$", "this", "->", "post", "(", "self", "::", "$", "path", ",", "$", "data", ")", "->", "status", "(", "'201'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "return", "$", "response", ";", "}" ]
Creates a new settlement. @param array $data Creation data @see https://developers.klarna.com/api/#merchant-card-service-api-create-a-new-settlement @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return array Settlement data
[ "Creates", "a", "new", "settlement", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/MerchantCardService/VCCSettlements.php#L79-L87
klarna/kco_rest_php
src/Klarna/Rest/MerchantCardService/VCCSettlements.php
VCCSettlements.retrieveSettlement
public function retrieveSettlement($settlementId, $keyId) { $response = $this->request( 'GET', self::$path . "/$settlementId", ['KeyId' => $keyId] )->status('200') ->contentType('application/json') ->getJson(); return $response; }
php
public function retrieveSettlement($settlementId, $keyId) { $response = $this->request( 'GET', self::$path . "/$settlementId", ['KeyId' => $keyId] )->status('200') ->contentType('application/json') ->getJson(); return $response; }
[ "public", "function", "retrieveSettlement", "(", "$", "settlementId", ",", "$", "keyId", ")", "{", "$", "response", "=", "$", "this", "->", "request", "(", "'GET'", ",", "self", "::", "$", "path", ".", "\"/$settlementId\"", ",", "[", "'KeyId'", "=>", "$", "keyId", "]", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "return", "$", "response", ";", "}" ]
Retrieve an existing settlement. @see https://developers.klarna.com/api/#hosted-payment-page-api-distribute-link-to-the-hpp-session @param array $data Distribute data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return array Settlement data
[ "Retrieve", "an", "existing", "settlement", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/MerchantCardService/VCCSettlements.php#L105-L116
klarna/kco_rest_php
src/Klarna/Rest/MerchantCardService/VCCSettlements.php
VCCSettlements.retrieveOrderSettlement
public function retrieveOrderSettlement($orderId, $keyId) { $response = $this->request( 'GET', self::$path . "/order/$orderId", ['KeyId' => $keyId] )->status('200') ->contentType('application/json') ->getJson(); return $response; }
php
public function retrieveOrderSettlement($orderId, $keyId) { $response = $this->request( 'GET', self::$path . "/order/$orderId", ['KeyId' => $keyId] )->status('200') ->contentType('application/json') ->getJson(); return $response; }
[ "public", "function", "retrieveOrderSettlement", "(", "$", "orderId", ",", "$", "keyId", ")", "{", "$", "response", "=", "$", "this", "->", "request", "(", "'GET'", ",", "self", "::", "$", "path", ".", "\"/order/$orderId\"", ",", "[", "'KeyId'", "=>", "$", "keyId", "]", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "return", "$", "response", ";", "}" ]
Retrieves a settled order's settlement. @see https://developers.klarna.com/api/#hosted-payment-page-api-distribute-link-to-the-hpp-session @param array $data Distribute data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return array Order's settlement data
[ "Retrieves", "a", "settled", "order", "s", "settlement", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/MerchantCardService/VCCSettlements.php#L134-L145
klarna/kco_rest_php
src/Klarna/Rest/Transport/UserAgent.php
UserAgent.setField
public function setField($key, $name, $version = '', array $options = []) { $field = [ 'name' => $name ]; if (!empty($version)) { $field['version'] = $version; } if (!empty($options)) { $field['options'] = $options; } $this->fields[$key] = $field; return $this; }
php
public function setField($key, $name, $version = '', array $options = []) { $field = [ 'name' => $name ]; if (!empty($version)) { $field['version'] = $version; } if (!empty($options)) { $field['options'] = $options; } $this->fields[$key] = $field; return $this; }
[ "public", "function", "setField", "(", "$", "key", ",", "$", "name", ",", "$", "version", "=", "''", ",", "array", "$", "options", "=", "[", "]", ")", "{", "$", "field", "=", "[", "'name'", "=>", "$", "name", "]", ";", "if", "(", "!", "empty", "(", "$", "version", ")", ")", "{", "$", "field", "[", "'version'", "]", "=", "$", "version", ";", "}", "if", "(", "!", "empty", "(", "$", "options", ")", ")", "{", "$", "field", "[", "'options'", "]", "=", "$", "options", ";", "}", "$", "this", "->", "fields", "[", "$", "key", "]", "=", "$", "field", ";", "return", "$", "this", ";", "}" ]
Sets the specified field. @param string $key Component key, e.g. 'Language' @param string $name Component name, e.g. 'PHP' @param string $version Version identifier, e.g. '5.4.10' @param array $options Additional information @return self
[ "Sets", "the", "specified", "field", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Transport/UserAgent.php#L57-L74
klarna/kco_rest_php
src/Klarna/Rest/Transport/UserAgent.php
UserAgent.createDefault
public static function createDefault() { $agent = new static(); $options = ['Guzzle/' . ClientInterface::VERSION]; if (extension_loaded('curl')) { $options[] = 'curl/' . curl_version()['version']; } return $agent ->setField('Library', static::NAME, static::VERSION, $options) ->setField('OS', php_uname('s'), php_uname('r')) ->setField('Language', 'PHP', phpversion()); }
php
public static function createDefault() { $agent = new static(); $options = ['Guzzle/' . ClientInterface::VERSION]; if (extension_loaded('curl')) { $options[] = 'curl/' . curl_version()['version']; } return $agent ->setField('Library', static::NAME, static::VERSION, $options) ->setField('OS', php_uname('s'), php_uname('r')) ->setField('Language', 'PHP', phpversion()); }
[ "public", "static", "function", "createDefault", "(", ")", "{", "$", "agent", "=", "new", "static", "(", ")", ";", "$", "options", "=", "[", "'Guzzle/'", ".", "ClientInterface", "::", "VERSION", "]", ";", "if", "(", "extension_loaded", "(", "'curl'", ")", ")", "{", "$", "options", "[", "]", "=", "'curl/'", ".", "curl_version", "(", ")", "[", "'version'", "]", ";", "}", "return", "$", "agent", "->", "setField", "(", "'Library'", ",", "static", "::", "NAME", ",", "static", "::", "VERSION", ",", "$", "options", ")", "->", "setField", "(", "'OS'", ",", "php_uname", "(", "'s'", ")", ",", "php_uname", "(", "'r'", ")", ")", "->", "setField", "(", "'Language'", ",", "'PHP'", ",", "phpversion", "(", ")", ")", ";", "}" ]
Creates the default user agent. @return self
[ "Creates", "the", "default", "user", "agent", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Transport/UserAgent.php#L109-L122
klarna/kco_rest_php
src/Klarna/Rest/HostedPaymentPage/Sessions.php
Sessions.disable
public function disable() { if (empty($this[static::ID_FIELD])) { throw new \RuntimeException('HPP Session ID is not defined'); } $this->delete($this->getLocation()) ->status('204'); return $this; }
php
public function disable() { if (empty($this[static::ID_FIELD])) { throw new \RuntimeException('HPP Session ID is not defined'); } $this->delete($this->getLocation()) ->status('204'); return $this; }
[ "public", "function", "disable", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "[", "static", "::", "ID_FIELD", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'HPP Session ID is not defined'", ")", ";", "}", "$", "this", "->", "delete", "(", "$", "this", "->", "getLocation", "(", ")", ")", "->", "status", "(", "'204'", ")", ";", "return", "$", "this", ";", "}" ]
Disables HPP session. @see https://developers.klarna.com/api/#hosted-payment-page-api-disable-hpp-session @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If sessionId was not specified when creating a resource @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return self
[ "Disables", "HPP", "session", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/HostedPaymentPage/Sessions.php#L98-L108
klarna/kco_rest_php
src/Klarna/Rest/InstantShopping/ButtonKeys.php
ButtonKeys.update
public function update(array $data) { if (empty($this[static::ID_FIELD])) { throw new \RuntimeException(static::ID_FIELD . ' property is not defined'); } return $this->put($this->getLocation(), $data) ->status('200') ->contentType('application/json') ->getJson(); }
php
public function update(array $data) { if (empty($this[static::ID_FIELD])) { throw new \RuntimeException(static::ID_FIELD . ' property is not defined'); } return $this->put($this->getLocation(), $data) ->status('200') ->contentType('application/json') ->getJson(); }
[ "public", "function", "update", "(", "array", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "this", "[", "static", "::", "ID_FIELD", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "static", "::", "ID_FIELD", ".", "' property is not defined'", ")", ";", "}", "return", "$", "this", "->", "put", "(", "$", "this", "->", "getLocation", "(", ")", ",", "$", "data", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "}" ]
Updates the setup options for a specific button key. @param array $data Update data @see https://developers.klarna.com/api/#instant-shopping-api-update-the-setup-options-for-a-specific-button-key @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the API replies with an unexpected response @throws \RuntimeException If key was not specified when creating a resource @throws \LogicException When Guzzle cannot populate the response @return array Button properties
[ "Updates", "the", "setup", "options", "for", "a", "specific", "button", "key", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/InstantShopping/ButtonKeys.php#L100-L110
klarna/kco_rest_php
src/Klarna/Rest/Payments/Sessions.php
Sessions.create
public function create(array $data) { $response = $this->post(self::$path, $data) ->status('200') ->contentType('application/json'); $this->exchangeArray($response->getJson()); // Payments API does not send Location header after creating a new session. // Use workaround to set new location. $this->setLocation(self::$path . '/' . $this->getId()); return $this; }
php
public function create(array $data) { $response = $this->post(self::$path, $data) ->status('200') ->contentType('application/json'); $this->exchangeArray($response->getJson()); // Payments API does not send Location header after creating a new session. // Use workaround to set new location. $this->setLocation(self::$path . '/' . $this->getId()); return $this; }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "$", "response", "=", "$", "this", "->", "post", "(", "self", "::", "$", "path", ",", "$", "data", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", ";", "$", "this", "->", "exchangeArray", "(", "$", "response", "->", "getJson", "(", ")", ")", ";", "// Payments API does not send Location header after creating a new session.", "// Use workaround to set new location.", "$", "this", "->", "setLocation", "(", "self", "::", "$", "path", ".", "'/'", ".", "$", "this", "->", "getId", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Creates the resource. @param array $data Creation data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return self
[ "Creates", "the", "resource", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Payments/Sessions.php#L75-L88
klarna/kco_rest_php
src/Klarna/Rest/OrderManagement/Capture.php
Capture.create
public function create(array $data) { $url = $this->post($this->getLocation(), $data) ->status('201') ->getLocation(); $this->setLocation($url); return $this; }
php
public function create(array $data) { $url = $this->post($this->getLocation(), $data) ->status('201') ->getLocation(); $this->setLocation($url); return $this; }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "$", "url", "=", "$", "this", "->", "post", "(", "$", "this", "->", "getLocation", "(", ")", ",", "$", "data", ")", "->", "status", "(", "'201'", ")", "->", "getLocation", "(", ")", ";", "$", "this", "->", "setLocation", "(", "$", "url", ")", ";", "return", "$", "this", ";", "}" ]
Creates the resource. @param array $data Creation data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return self
[ "Creates", "the", "resource", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/OrderManagement/Capture.php#L80-L89
klarna/kco_rest_php
src/Klarna/Rest/InstantShopping/Orders.php
Orders.decline
public function decline(array $data = null) { $this->delete($this->getLocation(), $data) ->status('204'); return $this; }
php
public function decline(array $data = null) { $this->delete($this->getLocation(), $data) ->status('204'); return $this; }
[ "public", "function", "decline", "(", "array", "$", "data", "=", "null", ")", "{", "$", "this", "->", "delete", "(", "$", "this", "->", "getLocation", "(", ")", ",", "$", "data", ")", "->", "status", "(", "'204'", ")", ";", "return", "$", "this", ";", "}" ]
Declines an authorized order identified by the authorization token. @codingStandardsIgnoreStart @see https://developers.klarna.com/api/#instant-shopping-api-declines-an-authorized-order-identified-by-the-authorization-token @codingStandardsIgnoreEnd @param array $data Decline data @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException If the location header is missing @throws \RuntimeException If the API replies with an unexpected response @throws \LogicException When Guzzle cannot populate the response @return self
[ "Declines", "an", "authorized", "order", "identified", "by", "the", "authorization", "token", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/InstantShopping/Orders.php#L94-L100
klarna/kco_rest_php
src/Klarna/Rest/Settlements/Payouts.php
Payouts.getAllPayouts
public function getAllPayouts(array $params = []) { return $this->get(self::$path . '?' . http_build_query($params)) ->status('200') ->contentType('application/json') ->getJson(); }
php
public function getAllPayouts(array $params = []) { return $this->get(self::$path . '?' . http_build_query($params)) ->status('200') ->contentType('application/json') ->getJson(); }
[ "public", "function", "getAllPayouts", "(", "array", "$", "params", "=", "[", "]", ")", "{", "return", "$", "this", "->", "get", "(", "self", "::", "$", "path", ".", "'?'", ".", "http_build_query", "(", "$", "params", ")", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "}" ]
Returns a collection of payouts. @param array $params Additional query params to filter payouts. @see https://developers.klarna.com/api/#settlements-api-get-all-payouts @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return array Payouts data
[ "Returns", "a", "collection", "of", "payouts", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Settlements/Payouts.php#L105-L111
klarna/kco_rest_php
src/Klarna/Rest/Resource.php
Resource.fetch
public function fetch() { $data = $this->get($this->getLocation()) ->status('200') ->contentType('application/json') ->getJson(); $this->exchangeArray($data); return $this; }
php
public function fetch() { $data = $this->get($this->getLocation()) ->status('200') ->contentType('application/json') ->getJson(); $this->exchangeArray($data); return $this; }
[ "public", "function", "fetch", "(", ")", "{", "$", "data", "=", "$", "this", "->", "get", "(", "$", "this", "->", "getLocation", "(", ")", ")", "->", "status", "(", "'200'", ")", "->", "contentType", "(", "'application/json'", ")", "->", "getJson", "(", ")", ";", "$", "this", "->", "exchangeArray", "(", "$", "data", ")", ";", "return", "$", "this", ";", "}" ]
Fetches the resource. @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \RuntimeException On an unexpected API response @throws \RuntimeException If the response content type is not JSON @throws \InvalidArgumentException If the JSON cannot be parsed @throws \LogicException When Guzzle cannot populate the response @return self
[ "Fetches", "the", "resource", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Resource.php#L114-L124
klarna/kco_rest_php
src/Klarna/Rest/Resource.php
Resource.request
protected function request($method, $url, array $headers = [], $body = '') { $debug = getenv('DEBUG_SDK') || defined('DEBUG_SDK'); $request = $this->connector->createRequest($url, $method, $headers, $body); if ($debug) { $clientConfig = $this->connector->getClient()->getConfig(); $baseUri = isset($clientConfig['base_uri']) ? $clientConfig['base_uri'] : ''; $debugHeaders = $request->getHeaders(); $debugHeaders = json_encode($debugHeaders); echo <<<DEBUG_BODY DEBUG MODE: Request >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {$method} : {$baseUri}{$url} Headers : $debugHeaders Body : {$request->getBody()} \n DEBUG_BODY; } $response = $this->connector->send($request); if ($debug) { $debugHeaders = json_encode($response->getHeaders()); echo <<<DEBUG_BODY DEBUG MODE: Response <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Headers : $debugHeaders Body : {$response->getBody()} \n DEBUG_BODY; } return new ResponseValidator($response); }
php
protected function request($method, $url, array $headers = [], $body = '') { $debug = getenv('DEBUG_SDK') || defined('DEBUG_SDK'); $request = $this->connector->createRequest($url, $method, $headers, $body); if ($debug) { $clientConfig = $this->connector->getClient()->getConfig(); $baseUri = isset($clientConfig['base_uri']) ? $clientConfig['base_uri'] : ''; $debugHeaders = $request->getHeaders(); $debugHeaders = json_encode($debugHeaders); echo <<<DEBUG_BODY DEBUG MODE: Request >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {$method} : {$baseUri}{$url} Headers : $debugHeaders Body : {$request->getBody()} \n DEBUG_BODY; } $response = $this->connector->send($request); if ($debug) { $debugHeaders = json_encode($response->getHeaders()); echo <<<DEBUG_BODY DEBUG MODE: Response <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Headers : $debugHeaders Body : {$response->getBody()} \n DEBUG_BODY; } return new ResponseValidator($response); }
[ "protected", "function", "request", "(", "$", "method", ",", "$", "url", ",", "array", "$", "headers", "=", "[", "]", ",", "$", "body", "=", "''", ")", "{", "$", "debug", "=", "getenv", "(", "'DEBUG_SDK'", ")", "||", "defined", "(", "'DEBUG_SDK'", ")", ";", "$", "request", "=", "$", "this", "->", "connector", "->", "createRequest", "(", "$", "url", ",", "$", "method", ",", "$", "headers", ",", "$", "body", ")", ";", "if", "(", "$", "debug", ")", "{", "$", "clientConfig", "=", "$", "this", "->", "connector", "->", "getClient", "(", ")", "->", "getConfig", "(", ")", ";", "$", "baseUri", "=", "isset", "(", "$", "clientConfig", "[", "'base_uri'", "]", ")", "?", "$", "clientConfig", "[", "'base_uri'", "]", ":", "''", ";", "$", "debugHeaders", "=", "$", "request", "->", "getHeaders", "(", ")", ";", "$", "debugHeaders", "=", "json_encode", "(", "$", "debugHeaders", ")", ";", "echo", " <<<DEBUG_BODY\nDEBUG MODE: Request\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n {$method} : {$baseUri}{$url}\nHeaders : $debugHeaders\n Body : {$request->getBody()}\n\\n\nDEBUG_BODY", ";", "}", "$", "response", "=", "$", "this", "->", "connector", "->", "send", "(", "$", "request", ")", ";", "if", "(", "$", "debug", ")", "{", "$", "debugHeaders", "=", "json_encode", "(", "$", "response", "->", "getHeaders", "(", ")", ")", ";", "echo", " <<<DEBUG_BODY\nDEBUG MODE: Response\n<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\nHeaders : $debugHeaders\n Body : {$response->getBody()}\n\\n\nDEBUG_BODY", ";", "}", "return", "new", "ResponseValidator", "(", "$", "response", ")", ";", "}" ]
Sends a HTTP request to the specified url. @param string $method HTTP method, e.g. 'GET' @param string $url Request destination @param array $headers @param string $body @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \LogicException When Guzzle cannot populate the response' @return ResponseValidator When the API replies with an error response
[ "Sends", "a", "HTTP", "request", "to", "the", "specified", "url", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Resource.php#L140-L174
klarna/kco_rest_php
src/Klarna/Rest/Resource.php
Resource.delete
protected function delete($url, array $data = null) { return $this->request( 'DELETE', $url, ['Content-Type' => 'application/json'], $data !== null ? json_encode($data) : null ); }
php
protected function delete($url, array $data = null) { return $this->request( 'DELETE', $url, ['Content-Type' => 'application/json'], $data !== null ? json_encode($data) : null ); }
[ "protected", "function", "delete", "(", "$", "url", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "request", "(", "'DELETE'", ",", "$", "url", ",", "[", "'Content-Type'", "=>", "'application/json'", "]", ",", "$", "data", "!==", "null", "?", "json_encode", "(", "$", "data", ")", ":", "null", ")", ";", "}" ]
Sends a HTTP DELETE request to the specified url. @param string $url Request destination @param array $data Data to be JSON encoded @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \LogicException When Guzzle cannot populate the response @return ResponseValidator
[ "Sends", "a", "HTTP", "DELETE", "request", "to", "the", "specified", "url", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Resource.php#L204-L212
klarna/kco_rest_php
src/Klarna/Rest/Resource.php
Resource.post
protected function post($url, array $data = null) { return $this->request( 'POST', $url, ['Content-Type' => 'application/json'], $data !== null ? \json_encode($data) : null ); }
php
protected function post($url, array $data = null) { return $this->request( 'POST', $url, ['Content-Type' => 'application/json'], $data !== null ? \json_encode($data) : null ); }
[ "protected", "function", "post", "(", "$", "url", ",", "array", "$", "data", "=", "null", ")", "{", "return", "$", "this", "->", "request", "(", "'POST'", ",", "$", "url", ",", "[", "'Content-Type'", "=>", "'application/json'", "]", ",", "$", "data", "!==", "null", "?", "\\", "json_encode", "(", "$", "data", ")", ":", "null", ")", ";", "}" ]
Sends a HTTP POST request to the specified url. @param string $url Request destination @param array $data Data to be JSON encoded @throws ConnectorException When the API replies with an error response @throws RequestException When an error is encountered @throws \LogicException When Guzzle cannot populate the response @return ResponseValidator
[ "Sends", "a", "HTTP", "POST", "request", "to", "the", "specified", "url", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Resource.php#L260-L268
klarna/kco_rest_php
src/Klarna/Rest/Transport/ResponseValidator.php
ResponseValidator.status
public function status($status) { $httpStatus = (string) $this->response->getStatusCode(); if (is_array($status) && !in_array($httpStatus, $status)) { throw new \RuntimeException( "Unexpected response status code: {$httpStatus}" ); } if (is_string($status) && $httpStatus !== $status) { throw new \RuntimeException( "Unexpected response status code: {$httpStatus}" ); } return $this; }
php
public function status($status) { $httpStatus = (string) $this->response->getStatusCode(); if (is_array($status) && !in_array($httpStatus, $status)) { throw new \RuntimeException( "Unexpected response status code: {$httpStatus}" ); } if (is_string($status) && $httpStatus !== $status) { throw new \RuntimeException( "Unexpected response status code: {$httpStatus}" ); } return $this; }
[ "public", "function", "status", "(", "$", "status", ")", "{", "$", "httpStatus", "=", "(", "string", ")", "$", "this", "->", "response", "->", "getStatusCode", "(", ")", ";", "if", "(", "is_array", "(", "$", "status", ")", "&&", "!", "in_array", "(", "$", "httpStatus", ",", "$", "status", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Unexpected response status code: {$httpStatus}\"", ")", ";", "}", "if", "(", "is_string", "(", "$", "status", ")", "&&", "$", "httpStatus", "!==", "$", "status", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Unexpected response status code: {$httpStatus}\"", ")", ";", "}", "return", "$", "this", ";", "}" ]
Asserts the HTTP response status code. @param string|string[] $status Expected status code(s) @throws \RuntimeException If status code does not match @return self
[ "Asserts", "the", "HTTP", "response", "status", "code", "." ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Transport/ResponseValidator.php#L65-L81
klarna/kco_rest_php
src/Klarna/Rest/Transport/ResponseValidator.php
ResponseValidator.contentType
public function contentType($mediaType) { if (!$this->response->hasHeader('Content-Type')) { throw new \RuntimeException('Response is missing a Content-Type header'); } $contentType = $this->response->getHeader('Content-Type'); $mediaFound = false; foreach ($contentType as $type) { if (preg_match('#' . $mediaType . '#', $type)) { $mediaFound = true; break; } } if (!$mediaFound) { throw new \RuntimeException( 'Unexpected Content-Type header received: ' . implode(',', $contentType) . '. Expected: ' . $mediaType ); } return $this; }
php
public function contentType($mediaType) { if (!$this->response->hasHeader('Content-Type')) { throw new \RuntimeException('Response is missing a Content-Type header'); } $contentType = $this->response->getHeader('Content-Type'); $mediaFound = false; foreach ($contentType as $type) { if (preg_match('#' . $mediaType . '#', $type)) { $mediaFound = true; break; } } if (!$mediaFound) { throw new \RuntimeException( 'Unexpected Content-Type header received: ' . implode(',', $contentType) . '. Expected: ' . $mediaType ); } return $this; }
[ "public", "function", "contentType", "(", "$", "mediaType", ")", "{", "if", "(", "!", "$", "this", "->", "response", "->", "hasHeader", "(", "'Content-Type'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Response is missing a Content-Type header'", ")", ";", "}", "$", "contentType", "=", "$", "this", "->", "response", "->", "getHeader", "(", "'Content-Type'", ")", ";", "$", "mediaFound", "=", "false", ";", "foreach", "(", "$", "contentType", "as", "$", "type", ")", "{", "if", "(", "preg_match", "(", "'#'", ".", "$", "mediaType", ".", "'#'", ",", "$", "type", ")", ")", "{", "$", "mediaFound", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "mediaFound", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unexpected Content-Type header received: '", ".", "implode", "(", "','", ",", "$", "contentType", ")", ".", "'. Expected: '", ".", "$", "mediaType", ")", ";", "}", "return", "$", "this", ";", "}" ]
Asserts the Content-Type header. Checks partial matching. Validation PASSES in the following cases: Content-Type: application/json $mediaType = 'application/json' Content-Type: application/json; charset=utf-8 $mediaType = 'application/json' Validation FAILS in the following cases: Content-Type: plain/text $mediaType = 'application/json' Content-Type: application/json; charset=utf-8 $mediaType = 'application/json; charset=cp-1251' @param string $mediaType Expected media type. RegExp rules can be used. @throws \RuntimeException If Content-Type header is missing @throws \RuntimeException If Content-Type header does not match @return self
[ "Asserts", "the", "Content", "-", "Type", "header", ".", "Checks", "partial", "matching", ".", "Validation", "PASSES", "in", "the", "following", "cases", ":", "Content", "-", "Type", ":", "application", "/", "json", "$mediaType", "=", "application", "/", "json" ]
train
https://github.com/klarna/kco_rest_php/blob/237efa8ccf1934525f8eff47c99aac830543c0e5/src/Klarna/Rest/Transport/ResponseValidator.php#L106-L128
consolidation/self-update
src/SelfUpdateCommand.php
SelfUpdateCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { if (empty(\Phar::running())) { throw new \Exception(self::SELF_UPDATE_COMMAND_NAME . ' only works when running the phar version of ' . $this->applicationName . '.'); } $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; $programName = basename($localFilename); $tempFilename = dirname($localFilename) . '/' . basename($localFilename, '.phar') . '-temp.phar'; // check for permissions in local filesystem before start connection process if (! is_writable($tempDirectory = dirname($tempFilename))) { throw new \Exception( $programName . ' update failed: the "' . $tempDirectory . '" directory used to download the temp file could not be written' ); } if (! is_writable($localFilename)) { throw new \Exception( $programName . ' update failed: the "' . $localFilename . '" file could not be written (execute with sudo)' ); } list( $latest, $downloadUrl ) = $this->getLatestReleaseFromGithub(); if ($this->currentVersion == $latest) { $output->writeln('No update available'); return; } $fs = new sfFilesystem(); $output->writeln('Downloading ' . $this->applicationName . ' (' . $this->gitHubRepository . ') ' . $latest); $fs->copy($downloadUrl, $tempFilename); $output->writeln('Download finished'); try { \error_reporting(E_ALL); // supress notices @chmod($tempFilename, 0777 & ~umask()); // test the phar validity $phar = new \Phar($tempFilename); // free the variable to unlock the file unset($phar); @rename($tempFilename, $localFilename); $output->writeln('<info>Successfully updated ' . $programName . '</info>'); $this->_exit(); } catch (\Exception $e) { @unlink($tempFilename); if (! $e instanceof \UnexpectedValueException && ! $e instanceof \PharException) { throw $e; } $output->writeln('<error>The download is corrupted (' . $e->getMessage() . ').</error>'); $output->writeln('<error>Please re-run the self-update command to try again.</error>'); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { if (empty(\Phar::running())) { throw new \Exception(self::SELF_UPDATE_COMMAND_NAME . ' only works when running the phar version of ' . $this->applicationName . '.'); } $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; $programName = basename($localFilename); $tempFilename = dirname($localFilename) . '/' . basename($localFilename, '.phar') . '-temp.phar'; // check for permissions in local filesystem before start connection process if (! is_writable($tempDirectory = dirname($tempFilename))) { throw new \Exception( $programName . ' update failed: the "' . $tempDirectory . '" directory used to download the temp file could not be written' ); } if (! is_writable($localFilename)) { throw new \Exception( $programName . ' update failed: the "' . $localFilename . '" file could not be written (execute with sudo)' ); } list( $latest, $downloadUrl ) = $this->getLatestReleaseFromGithub(); if ($this->currentVersion == $latest) { $output->writeln('No update available'); return; } $fs = new sfFilesystem(); $output->writeln('Downloading ' . $this->applicationName . ' (' . $this->gitHubRepository . ') ' . $latest); $fs->copy($downloadUrl, $tempFilename); $output->writeln('Download finished'); try { \error_reporting(E_ALL); // supress notices @chmod($tempFilename, 0777 & ~umask()); // test the phar validity $phar = new \Phar($tempFilename); // free the variable to unlock the file unset($phar); @rename($tempFilename, $localFilename); $output->writeln('<info>Successfully updated ' . $programName . '</info>'); $this->_exit(); } catch (\Exception $e) { @unlink($tempFilename); if (! $e instanceof \UnexpectedValueException && ! $e instanceof \PharException) { throw $e; } $output->writeln('<error>The download is corrupted (' . $e->getMessage() . ').</error>'); $output->writeln('<error>Please re-run the self-update command to try again.</error>'); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "if", "(", "empty", "(", "\\", "Phar", "::", "running", "(", ")", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "self", "::", "SELF_UPDATE_COMMAND_NAME", ".", "' only works when running the phar version of '", ".", "$", "this", "->", "applicationName", ".", "'.'", ")", ";", "}", "$", "localFilename", "=", "realpath", "(", "$", "_SERVER", "[", "'argv'", "]", "[", "0", "]", ")", "?", ":", "$", "_SERVER", "[", "'argv'", "]", "[", "0", "]", ";", "$", "programName", "=", "basename", "(", "$", "localFilename", ")", ";", "$", "tempFilename", "=", "dirname", "(", "$", "localFilename", ")", ".", "'/'", ".", "basename", "(", "$", "localFilename", ",", "'.phar'", ")", ".", "'-temp.phar'", ";", "// check for permissions in local filesystem before start connection process", "if", "(", "!", "is_writable", "(", "$", "tempDirectory", "=", "dirname", "(", "$", "tempFilename", ")", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "$", "programName", ".", "' update failed: the \"'", ".", "$", "tempDirectory", ".", "'\" directory used to download the temp file could not be written'", ")", ";", "}", "if", "(", "!", "is_writable", "(", "$", "localFilename", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "$", "programName", ".", "' update failed: the \"'", ".", "$", "localFilename", ".", "'\" file could not be written (execute with sudo)'", ")", ";", "}", "list", "(", "$", "latest", ",", "$", "downloadUrl", ")", "=", "$", "this", "->", "getLatestReleaseFromGithub", "(", ")", ";", "if", "(", "$", "this", "->", "currentVersion", "==", "$", "latest", ")", "{", "$", "output", "->", "writeln", "(", "'No update available'", ")", ";", "return", ";", "}", "$", "fs", "=", "new", "sfFilesystem", "(", ")", ";", "$", "output", "->", "writeln", "(", "'Downloading '", ".", "$", "this", "->", "applicationName", ".", "' ('", ".", "$", "this", "->", "gitHubRepository", ".", "') '", ".", "$", "latest", ")", ";", "$", "fs", "->", "copy", "(", "$", "downloadUrl", ",", "$", "tempFilename", ")", ";", "$", "output", "->", "writeln", "(", "'Download finished'", ")", ";", "try", "{", "\\", "error_reporting", "(", "E_ALL", ")", ";", "// supress notices", "@", "chmod", "(", "$", "tempFilename", ",", "0777", "&", "~", "umask", "(", ")", ")", ";", "// test the phar validity", "$", "phar", "=", "new", "\\", "Phar", "(", "$", "tempFilename", ")", ";", "// free the variable to unlock the file", "unset", "(", "$", "phar", ")", ";", "@", "rename", "(", "$", "tempFilename", ",", "$", "localFilename", ")", ";", "$", "output", "->", "writeln", "(", "'<info>Successfully updated '", ".", "$", "programName", ".", "'</info>'", ")", ";", "$", "this", "->", "_exit", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "@", "unlink", "(", "$", "tempFilename", ")", ";", "if", "(", "!", "$", "e", "instanceof", "\\", "UnexpectedValueException", "&&", "!", "$", "e", "instanceof", "\\", "PharException", ")", "{", "throw", "$", "e", ";", "}", "$", "output", "->", "writeln", "(", "'<error>The download is corrupted ('", ".", "$", "e", "->", "getMessage", "(", ")", ".", "').</error>'", ")", ";", "$", "output", "->", "writeln", "(", "'<error>Please re-run the self-update command to try again.</error>'", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/consolidation/self-update/blob/a283a41a2edf23104b6be95674e840aa623d519a/src/SelfUpdateCommand.php#L81-L140
exussum12/coverageChecker
src/Loaders/PhpStan.php
PhpStan.parseLines
public function parseLines(): array { $filename = ''; $lineNumber = 0; while (($line = fgets($this->file)) !== false) { $filename = $this->checkForFilename($line, $filename); if ($lineNumber = $this->getLineNumber($line, $lineNumber)) { $error = $this->getMessage($line); if ($this->isExtendedMessage($line)) { $this->appendError($filename, $lineNumber, $error); continue; } $this->handleRelatedError($filename, $lineNumber, $error); $this->addError($filename, $lineNumber, $error); } } $this->trimLines(); return array_keys($this->invalidLines); }
php
public function parseLines(): array { $filename = ''; $lineNumber = 0; while (($line = fgets($this->file)) !== false) { $filename = $this->checkForFilename($line, $filename); if ($lineNumber = $this->getLineNumber($line, $lineNumber)) { $error = $this->getMessage($line); if ($this->isExtendedMessage($line)) { $this->appendError($filename, $lineNumber, $error); continue; } $this->handleRelatedError($filename, $lineNumber, $error); $this->addError($filename, $lineNumber, $error); } } $this->trimLines(); return array_keys($this->invalidLines); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "filename", "=", "''", ";", "$", "lineNumber", "=", "0", ";", "while", "(", "(", "$", "line", "=", "fgets", "(", "$", "this", "->", "file", ")", ")", "!==", "false", ")", "{", "$", "filename", "=", "$", "this", "->", "checkForFilename", "(", "$", "line", ",", "$", "filename", ")", ";", "if", "(", "$", "lineNumber", "=", "$", "this", "->", "getLineNumber", "(", "$", "line", ",", "$", "lineNumber", ")", ")", "{", "$", "error", "=", "$", "this", "->", "getMessage", "(", "$", "line", ")", ";", "if", "(", "$", "this", "->", "isExtendedMessage", "(", "$", "line", ")", ")", "{", "$", "this", "->", "appendError", "(", "$", "filename", ",", "$", "lineNumber", ",", "$", "error", ")", ";", "continue", ";", "}", "$", "this", "->", "handleRelatedError", "(", "$", "filename", ",", "$", "lineNumber", ",", "$", "error", ")", ";", "$", "this", "->", "addError", "(", "$", "filename", ",", "$", "lineNumber", ",", "$", "error", ")", ";", "}", "}", "$", "this", "->", "trimLines", "(", ")", ";", "return", "array_keys", "(", "$", "this", "->", "invalidLines", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/PhpStan.php#L38-L58
exussum12/coverageChecker
src/Loaders/PhpStan.php
PhpStan.getErrorsOnLine
public function getErrorsOnLine(string $file, int $lineNumber) { $errors = []; if (isset($this->invalidLines[$file][$lineNumber])) { $errors = $this->invalidLines[$file][$lineNumber]; } return $errors; }
php
public function getErrorsOnLine(string $file, int $lineNumber) { $errors = []; if (isset($this->invalidLines[$file][$lineNumber])) { $errors = $this->invalidLines[$file][$lineNumber]; } return $errors; }
[ "public", "function", "getErrorsOnLine", "(", "string", "$", "file", ",", "int", "$", "lineNumber", ")", "{", "$", "errors", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "invalidLines", "[", "$", "file", "]", "[", "$", "lineNumber", "]", ")", ")", "{", "$", "errors", "=", "$", "this", "->", "invalidLines", "[", "$", "file", "]", "[", "$", "lineNumber", "]", ";", "}", "return", "$", "errors", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/PhpStan.php#L63-L71
exussum12/coverageChecker
src/Loaders/Humbug.php
Humbug.parseLines
public function parseLines(): array { $this->invalidLines = []; foreach ($this->errorMethods as $failures) { foreach ($this->json->$failures as $errors) { $fileName = $errors->file; $lineNumber = $errors->line; $error = "Failed on $failures check"; if (!empty($errors->diff)) { $error .= "\nDiff:\n" . $errors->diff; } $this->invalidLines[$fileName][$lineNumber] = $error; } } return array_keys($this->invalidLines); }
php
public function parseLines(): array { $this->invalidLines = []; foreach ($this->errorMethods as $failures) { foreach ($this->json->$failures as $errors) { $fileName = $errors->file; $lineNumber = $errors->line; $error = "Failed on $failures check"; if (!empty($errors->diff)) { $error .= "\nDiff:\n" . $errors->diff; } $this->invalidLines[$fileName][$lineNumber] = $error; } } return array_keys($this->invalidLines); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "this", "->", "invalidLines", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "errorMethods", "as", "$", "failures", ")", "{", "foreach", "(", "$", "this", "->", "json", "->", "$", "failures", "as", "$", "errors", ")", "{", "$", "fileName", "=", "$", "errors", "->", "file", ";", "$", "lineNumber", "=", "$", "errors", "->", "line", ";", "$", "error", "=", "\"Failed on $failures check\"", ";", "if", "(", "!", "empty", "(", "$", "errors", "->", "diff", ")", ")", "{", "$", "error", ".=", "\"\\nDiff:\\n\"", ".", "$", "errors", "->", "diff", ";", "}", "$", "this", "->", "invalidLines", "[", "$", "fileName", "]", "[", "$", "lineNumber", "]", "=", "$", "error", ";", "}", "}", "return", "array_keys", "(", "$", "this", "->", "invalidLines", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Humbug.php#L45-L62
exussum12/coverageChecker
src/Loaders/Clover.php
Clover.parseLines
public function parseLines(): array { $this->coveredLines = []; $reader = new XMLReader; $reader->open($this->file); $currentFile = ''; while ($reader->read()) { $currentFile = $this->checkForNewFiles($reader, $currentFile); $this->handleStatement($reader, $currentFile); } return array_keys($this->coveredLines); }
php
public function parseLines(): array { $this->coveredLines = []; $reader = new XMLReader; $reader->open($this->file); $currentFile = ''; while ($reader->read()) { $currentFile = $this->checkForNewFiles($reader, $currentFile); $this->handleStatement($reader, $currentFile); } return array_keys($this->coveredLines); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "this", "->", "coveredLines", "=", "[", "]", ";", "$", "reader", "=", "new", "XMLReader", ";", "$", "reader", "->", "open", "(", "$", "this", "->", "file", ")", ";", "$", "currentFile", "=", "''", ";", "while", "(", "$", "reader", "->", "read", "(", ")", ")", "{", "$", "currentFile", "=", "$", "this", "->", "checkForNewFiles", "(", "$", "reader", ",", "$", "currentFile", ")", ";", "$", "this", "->", "handleStatement", "(", "$", "reader", ",", "$", "currentFile", ")", ";", "}", "return", "array_keys", "(", "$", "this", "->", "coveredLines", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Clover.php#L35-L48
exussum12/coverageChecker
src/Loaders/Generic.php
Generic.parseLines
public function parseLines(): array { $handle = fopen($this->file, 'r'); while (($line = fgets($handle)) !== false) { if (!$this->checkForFile($line)) { continue; } $this->addError($line); } return array_keys($this->errors); }
php
public function parseLines(): array { $handle = fopen($this->file, 'r'); while (($line = fgets($handle)) !== false) { if (!$this->checkForFile($line)) { continue; } $this->addError($line); } return array_keys($this->errors); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "handle", "=", "fopen", "(", "$", "this", "->", "file", ",", "'r'", ")", ";", "while", "(", "(", "$", "line", "=", "fgets", "(", "$", "handle", ")", ")", "!==", "false", ")", "{", "if", "(", "!", "$", "this", "->", "checkForFile", "(", "$", "line", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "addError", "(", "$", "line", ")", ";", "}", "return", "array_keys", "(", "$", "this", "->", "errors", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Generic.php#L37-L49
exussum12/coverageChecker
src/Loaders/PhpMd.php
PhpMd.parseLines
public function parseLines(): array { $this->errors = []; $this->errorRanges = []; $reader = new XMLReader; $reader->open($this->file); $currentFile = ""; while ($reader->read()) { $currentFile = $this->checkForNewFile($reader, $currentFile); $this->checkForViolation($reader, $currentFile); } return array_keys($this->errors); }
php
public function parseLines(): array { $this->errors = []; $this->errorRanges = []; $reader = new XMLReader; $reader->open($this->file); $currentFile = ""; while ($reader->read()) { $currentFile = $this->checkForNewFile($reader, $currentFile); $this->checkForViolation($reader, $currentFile); } return array_keys($this->errors); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "this", "->", "errors", "=", "[", "]", ";", "$", "this", "->", "errorRanges", "=", "[", "]", ";", "$", "reader", "=", "new", "XMLReader", ";", "$", "reader", "->", "open", "(", "$", "this", "->", "file", ")", ";", "$", "currentFile", "=", "\"\"", ";", "while", "(", "$", "reader", "->", "read", "(", ")", ")", "{", "$", "currentFile", "=", "$", "this", "->", "checkForNewFile", "(", "$", "reader", ",", "$", "currentFile", ")", ";", "$", "this", "->", "checkForViolation", "(", "$", "reader", ",", "$", "currentFile", ")", ";", "}", "return", "array_keys", "(", "$", "this", "->", "errors", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/PhpMd.php#L41-L54
exussum12/coverageChecker
src/Loaders/Jacoco.php
Jacoco.parseLines
public function parseLines(): array { $this->coveredLines = []; $reader = new XMLReader; $reader->open($this->file); $currentNamespace = ''; $currentFile = ''; while ($reader->read()) { $currentNamespace = $this->findNamespace($reader, $currentNamespace); $currentFile = $this->findFile($reader, $currentNamespace, $currentFile); $this->addLine($reader, $currentFile); } return array_keys($this->coveredLines); }
php
public function parseLines(): array { $this->coveredLines = []; $reader = new XMLReader; $reader->open($this->file); $currentNamespace = ''; $currentFile = ''; while ($reader->read()) { $currentNamespace = $this->findNamespace($reader, $currentNamespace); $currentFile = $this->findFile($reader, $currentNamespace, $currentFile); $this->addLine($reader, $currentFile); } return array_keys($this->coveredLines); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "this", "->", "coveredLines", "=", "[", "]", ";", "$", "reader", "=", "new", "XMLReader", ";", "$", "reader", "->", "open", "(", "$", "this", "->", "file", ")", ";", "$", "currentNamespace", "=", "''", ";", "$", "currentFile", "=", "''", ";", "while", "(", "$", "reader", "->", "read", "(", ")", ")", "{", "$", "currentNamespace", "=", "$", "this", "->", "findNamespace", "(", "$", "reader", ",", "$", "currentNamespace", ")", ";", "$", "currentFile", "=", "$", "this", "->", "findFile", "(", "$", "reader", ",", "$", "currentNamespace", ",", "$", "currentFile", ")", ";", "$", "this", "->", "addLine", "(", "$", "reader", ",", "$", "currentFile", ")", ";", "}", "return", "array_keys", "(", "$", "this", "->", "coveredLines", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Jacoco.php#L16-L33
exussum12/coverageChecker
src/FileMatchers/FileMapper.php
FileMapper.match
public function match(string $needle, array $haystack): string { foreach ($haystack as $file) { if ($this->checkMapping($file, $needle)) { return $file; } } throw new FileNotFound(); }
php
public function match(string $needle, array $haystack): string { foreach ($haystack as $file) { if ($this->checkMapping($file, $needle)) { return $file; } } throw new FileNotFound(); }
[ "public", "function", "match", "(", "string", "$", "needle", ",", "array", "$", "haystack", ")", ":", "string", "{", "foreach", "(", "$", "haystack", "as", "$", "file", ")", "{", "if", "(", "$", "this", "->", "checkMapping", "(", "$", "file", ",", "$", "needle", ")", ")", "{", "return", "$", "file", ";", "}", "}", "throw", "new", "FileNotFound", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/FileMatchers/FileMapper.php#L31-L40
exussum12/coverageChecker
src/Loaders/Psalm.php
Psalm.parseLines
public function parseLines(): array { $this->errors = []; $this->errorRanges = []; $reader = new XMLReader; $reader->open($this->file); while ($reader->read()) { if ($this->isElementBeginning($reader, 'item')) { $this->parseItem($reader); } } return array_keys($this->errors); }
php
public function parseLines(): array { $this->errors = []; $this->errorRanges = []; $reader = new XMLReader; $reader->open($this->file); while ($reader->read()) { if ($this->isElementBeginning($reader, 'item')) { $this->parseItem($reader); } } return array_keys($this->errors); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "this", "->", "errors", "=", "[", "]", ";", "$", "this", "->", "errorRanges", "=", "[", "]", ";", "$", "reader", "=", "new", "XMLReader", ";", "$", "reader", "->", "open", "(", "$", "this", "->", "file", ")", ";", "while", "(", "$", "reader", "->", "read", "(", ")", ")", "{", "if", "(", "$", "this", "->", "isElementBeginning", "(", "$", "reader", ",", "'item'", ")", ")", "{", "$", "this", "->", "parseItem", "(", "$", "reader", ")", ";", "}", "}", "return", "array_keys", "(", "$", "this", "->", "errors", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Psalm.php#L43-L57
exussum12/coverageChecker
src/Loaders/Psalm.php
Psalm.getErrorsOnLine
public function getErrorsOnLine(string $file, int $lineNumber) { $errors = []; foreach ($this->errorRanges[$file] as $number => $error) { if (( $error['start'] <= $lineNumber && $error['end'] >= $lineNumber )) { $errors[] = $error['error']; unset($this->errorRanges[$file][$number]); } } return $errors; }
php
public function getErrorsOnLine(string $file, int $lineNumber) { $errors = []; foreach ($this->errorRanges[$file] as $number => $error) { if (( $error['start'] <= $lineNumber && $error['end'] >= $lineNumber )) { $errors[] = $error['error']; unset($this->errorRanges[$file][$number]); } } return $errors; }
[ "public", "function", "getErrorsOnLine", "(", "string", "$", "file", ",", "int", "$", "lineNumber", ")", "{", "$", "errors", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "errorRanges", "[", "$", "file", "]", "as", "$", "number", "=>", "$", "error", ")", "{", "if", "(", "(", "$", "error", "[", "'start'", "]", "<=", "$", "lineNumber", "&&", "$", "error", "[", "'end'", "]", ">=", "$", "lineNumber", ")", ")", "{", "$", "errors", "[", "]", "=", "$", "error", "[", "'error'", "]", ";", "unset", "(", "$", "this", "->", "errorRanges", "[", "$", "file", "]", "[", "$", "number", "]", ")", ";", "}", "}", "return", "$", "errors", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Psalm.php#L62-L76
exussum12/coverageChecker
src/Loaders/PhpCs.php
PhpCs.parseLines
public function parseLines(): array { $this->invalidLines = []; foreach ($this->json->files as $fileName => $file) { foreach ($file->messages as $message) { $this->addInvalidLine($fileName, $message); } } return array_unique(array_merge( array_keys($this->invalidLines), array_keys($this->invalidFiles), array_keys($this->invalidRanges) )); }
php
public function parseLines(): array { $this->invalidLines = []; foreach ($this->json->files as $fileName => $file) { foreach ($file->messages as $message) { $this->addInvalidLine($fileName, $message); } } return array_unique(array_merge( array_keys($this->invalidLines), array_keys($this->invalidFiles), array_keys($this->invalidRanges) )); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "this", "->", "invalidLines", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "json", "->", "files", "as", "$", "fileName", "=>", "$", "file", ")", "{", "foreach", "(", "$", "file", "->", "messages", "as", "$", "message", ")", "{", "$", "this", "->", "addInvalidLine", "(", "$", "fileName", ",", "$", "message", ")", ";", "}", "}", "return", "array_unique", "(", "array_merge", "(", "array_keys", "(", "$", "this", "->", "invalidLines", ")", ",", "array_keys", "(", "$", "this", "->", "invalidFiles", ")", ",", "array_keys", "(", "$", "this", "->", "invalidRanges", ")", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/PhpCs.php#L81-L95
exussum12/coverageChecker
src/Loaders/PhpCs.php
PhpCs.getErrorsOnLine
public function getErrorsOnLine(string $file, int $lineNumber) { $errors = []; if (!empty($this->invalidFiles[$file])) { $errors = $this->invalidFiles[$file]; } if (!empty($this->invalidLines[$file][$lineNumber])) { $errors = array_merge($errors, $this->invalidLines[$file][$lineNumber]); } $errors = array_merge($errors, $this->getRangeErrors($file, $lineNumber)); return $errors; }
php
public function getErrorsOnLine(string $file, int $lineNumber) { $errors = []; if (!empty($this->invalidFiles[$file])) { $errors = $this->invalidFiles[$file]; } if (!empty($this->invalidLines[$file][$lineNumber])) { $errors = array_merge($errors, $this->invalidLines[$file][$lineNumber]); } $errors = array_merge($errors, $this->getRangeErrors($file, $lineNumber)); return $errors; }
[ "public", "function", "getErrorsOnLine", "(", "string", "$", "file", ",", "int", "$", "lineNumber", ")", "{", "$", "errors", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "invalidFiles", "[", "$", "file", "]", ")", ")", "{", "$", "errors", "=", "$", "this", "->", "invalidFiles", "[", "$", "file", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "invalidLines", "[", "$", "file", "]", "[", "$", "lineNumber", "]", ")", ")", "{", "$", "errors", "=", "array_merge", "(", "$", "errors", ",", "$", "this", "->", "invalidLines", "[", "$", "file", "]", "[", "$", "lineNumber", "]", ")", ";", "}", "$", "errors", "=", "array_merge", "(", "$", "errors", ",", "$", "this", "->", "getRangeErrors", "(", "$", "file", ",", "$", "lineNumber", ")", ")", ";", "return", "$", "errors", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/PhpCs.php#L100-L114
exussum12/coverageChecker
src/Loaders/CodeClimate.php
CodeClimate.parseLines
public function parseLines(): array { foreach ($this->file as $line) { $this->addError($line); } return array_keys($this->errors); }
php
public function parseLines(): array { foreach ($this->file as $line) { $this->addError($line); } return array_keys($this->errors); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "foreach", "(", "$", "this", "->", "file", "as", "$", "line", ")", "{", "$", "this", "->", "addError", "(", "$", "line", ")", ";", "}", "return", "array_keys", "(", "$", "this", "->", "errors", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/CodeClimate.php#L35-L42
exussum12/coverageChecker
src/Loaders/Checkstyle.php
Checkstyle.parseLines
public function parseLines(): array { $this->coveredLines = []; $reader = new XMLReader; $reader->open($this->file); $currentFile = ''; while ($reader->read()) { $currentFile = $this->handleFile($reader, $currentFile); $this->handleErrors($reader, $currentFile); } return array_keys($this->coveredLines); }
php
public function parseLines(): array { $this->coveredLines = []; $reader = new XMLReader; $reader->open($this->file); $currentFile = ''; while ($reader->read()) { $currentFile = $this->handleFile($reader, $currentFile); $this->handleErrors($reader, $currentFile); } return array_keys($this->coveredLines); }
[ "public", "function", "parseLines", "(", ")", ":", "array", "{", "$", "this", "->", "coveredLines", "=", "[", "]", ";", "$", "reader", "=", "new", "XMLReader", ";", "$", "reader", "->", "open", "(", "$", "this", "->", "file", ")", ";", "$", "currentFile", "=", "''", ";", "while", "(", "$", "reader", "->", "read", "(", ")", ")", "{", "$", "currentFile", "=", "$", "this", "->", "handleFile", "(", "$", "reader", ",", "$", "currentFile", ")", ";", "$", "this", "->", "handleErrors", "(", "$", "reader", ",", "$", "currentFile", ")", ";", "}", "return", "array_keys", "(", "$", "this", "->", "coveredLines", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Checkstyle.php#L35-L48
exussum12/coverageChecker
src/Loaders/Checkstyle.php
Checkstyle.getErrorsOnLine
public function getErrorsOnLine(string $file, int $line) { $errors = []; if (isset($this->coveredLines[$file][$line])) { $errors = $this->coveredLines[$file][$line]; } return $errors; }
php
public function getErrorsOnLine(string $file, int $line) { $errors = []; if (isset($this->coveredLines[$file][$line])) { $errors = $this->coveredLines[$file][$line]; } return $errors; }
[ "public", "function", "getErrorsOnLine", "(", "string", "$", "file", ",", "int", "$", "line", ")", "{", "$", "errors", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "coveredLines", "[", "$", "file", "]", "[", "$", "line", "]", ")", ")", "{", "$", "errors", "=", "$", "this", "->", "coveredLines", "[", "$", "file", "]", "[", "$", "line", "]", ";", "}", "return", "$", "errors", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/Loaders/Checkstyle.php#L53-L61
exussum12/coverageChecker
src/FileMatchers/EndsWith.php
EndsWith.fileEndsWith
protected function fileEndsWith(string $haystack, string $needle): bool { $length = strlen($needle); if (strlen($haystack) < $length) { return $this->fileEndsWith($needle, $haystack); } $haystack = str_replace('\\', '/', $haystack); $needle = str_replace('\\', '/', $needle); return (substr($haystack, -$length) === $needle); }
php
protected function fileEndsWith(string $haystack, string $needle): bool { $length = strlen($needle); if (strlen($haystack) < $length) { return $this->fileEndsWith($needle, $haystack); } $haystack = str_replace('\\', '/', $haystack); $needle = str_replace('\\', '/', $needle); return (substr($haystack, -$length) === $needle); }
[ "protected", "function", "fileEndsWith", "(", "string", "$", "haystack", ",", "string", "$", "needle", ")", ":", "bool", "{", "$", "length", "=", "strlen", "(", "$", "needle", ")", ";", "if", "(", "strlen", "(", "$", "haystack", ")", "<", "$", "length", ")", "{", "return", "$", "this", "->", "fileEndsWith", "(", "$", "needle", ",", "$", "haystack", ")", ";", "}", "$", "haystack", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "haystack", ")", ";", "$", "needle", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "needle", ")", ";", "return", "(", "substr", "(", "$", "haystack", ",", "-", "$", "length", ")", "===", "$", "needle", ")", ";", "}" ]
Find if two strings end in the same way
[ "Find", "if", "two", "strings", "end", "in", "the", "same", "way" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/FileMatchers/EndsWith.php#L31-L42
exussum12/coverageChecker
src/CoverageCheck.php
CoverageCheck.getCoveredLines
public function getCoveredLines(): array { $this->getDiff(); $coveredFiles = $this->fileChecker->parseLines(); $this->uncoveredLines = []; $this->coveredLines = []; $diffFiles = array_keys($this->cache->diff); foreach ($diffFiles as $file) { $matchedFile = $this->findFile($file, $coveredFiles); if ($matchedFile !== '') { $this->matchLines($file, $matchedFile); } } return [ 'uncoveredLines' => $this->uncoveredLines, 'coveredLines' => $this->coveredLines, ]; }
php
public function getCoveredLines(): array { $this->getDiff(); $coveredFiles = $this->fileChecker->parseLines(); $this->uncoveredLines = []; $this->coveredLines = []; $diffFiles = array_keys($this->cache->diff); foreach ($diffFiles as $file) { $matchedFile = $this->findFile($file, $coveredFiles); if ($matchedFile !== '') { $this->matchLines($file, $matchedFile); } } return [ 'uncoveredLines' => $this->uncoveredLines, 'coveredLines' => $this->coveredLines, ]; }
[ "public", "function", "getCoveredLines", "(", ")", ":", "array", "{", "$", "this", "->", "getDiff", "(", ")", ";", "$", "coveredFiles", "=", "$", "this", "->", "fileChecker", "->", "parseLines", "(", ")", ";", "$", "this", "->", "uncoveredLines", "=", "[", "]", ";", "$", "this", "->", "coveredLines", "=", "[", "]", ";", "$", "diffFiles", "=", "array_keys", "(", "$", "this", "->", "cache", "->", "diff", ")", ";", "foreach", "(", "$", "diffFiles", "as", "$", "file", ")", "{", "$", "matchedFile", "=", "$", "this", "->", "findFile", "(", "$", "file", ",", "$", "coveredFiles", ")", ";", "if", "(", "$", "matchedFile", "!==", "''", ")", "{", "$", "this", "->", "matchLines", "(", "$", "file", ",", "$", "matchedFile", ")", ";", "}", "}", "return", "[", "'uncoveredLines'", "=>", "$", "this", "->", "uncoveredLines", ",", "'coveredLines'", "=>", "$", "this", "->", "coveredLines", ",", "]", ";", "}" ]
array of uncoveredLines and coveredLines
[ "array", "of", "uncoveredLines", "and", "coveredLines" ]
train
https://github.com/exussum12/coverageChecker/blob/5e35f5da7352675bdba8e802664c987097b32af1/src/CoverageCheck.php#L63-L83
richsage/RMSPushNotificationsBundle
DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $this->root = $treeBuilder->root("rms_push_notifications"); $this->addAndroid(); $this->addiOS(); $this->addMac(); $this->addBlackberry(); $this->addWindowsphone(); return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $this->root = $treeBuilder->root("rms_push_notifications"); $this->addAndroid(); $this->addiOS(); $this->addMac(); $this->addBlackberry(); $this->addWindowsphone(); return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", ")", ";", "$", "this", "->", "root", "=", "$", "treeBuilder", "->", "root", "(", "\"rms_push_notifications\"", ")", ";", "$", "this", "->", "addAndroid", "(", ")", ";", "$", "this", "->", "addiOS", "(", ")", ";", "$", "this", "->", "addMac", "(", ")", ";", "$", "this", "->", "addBlackberry", "(", ")", ";", "$", "this", "->", "addWindowsphone", "(", ")", ";", "return", "$", "treeBuilder", ";", "}" ]
Generates the configuration tree builder. @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
[ "Generates", "the", "configuration", "tree", "builder", "." ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/Configuration.php#L20-L32
richsage/RMSPushNotificationsBundle
DependencyInjection/Configuration.php
Configuration.addAndroid
protected function addAndroid() { $this->root-> children()-> arrayNode("android")-> canBeUnset()-> children()-> scalarNode("timeout")->defaultValue(5)->end()-> // WARNING: These 3 fields as they are, outside of the c2dm array // are deprecrated in favour of using the c2dm array configuration // At present these will be overriden by anything supplied // in the c2dm array scalarNode("username")->defaultValue("")->end()-> scalarNode("password")->defaultValue("")->end()-> scalarNode("source")->defaultValue("")->end()-> arrayNode("c2dm")-> canBeUnset()-> children()-> scalarNode("username")->isRequired()->end()-> scalarNode("password")->isRequired()->end()-> scalarNode("source")->defaultValue("")->end()-> end()-> end()-> arrayNode("gcm")-> canBeUnset()-> children()-> scalarNode("api_key")->isRequired()->cannotBeEmpty()->end()-> booleanNode("use_multi_curl")->defaultValue(true)->end()-> booleanNode("dry_run")->defaultFalse()->end()-> end()-> end()-> end()-> end()-> end() ; }
php
protected function addAndroid() { $this->root-> children()-> arrayNode("android")-> canBeUnset()-> children()-> scalarNode("timeout")->defaultValue(5)->end()-> // WARNING: These 3 fields as they are, outside of the c2dm array // are deprecrated in favour of using the c2dm array configuration // At present these will be overriden by anything supplied // in the c2dm array scalarNode("username")->defaultValue("")->end()-> scalarNode("password")->defaultValue("")->end()-> scalarNode("source")->defaultValue("")->end()-> arrayNode("c2dm")-> canBeUnset()-> children()-> scalarNode("username")->isRequired()->end()-> scalarNode("password")->isRequired()->end()-> scalarNode("source")->defaultValue("")->end()-> end()-> end()-> arrayNode("gcm")-> canBeUnset()-> children()-> scalarNode("api_key")->isRequired()->cannotBeEmpty()->end()-> booleanNode("use_multi_curl")->defaultValue(true)->end()-> booleanNode("dry_run")->defaultFalse()->end()-> end()-> end()-> end()-> end()-> end() ; }
[ "protected", "function", "addAndroid", "(", ")", "{", "$", "this", "->", "root", "->", "children", "(", ")", "->", "arrayNode", "(", "\"android\"", ")", "->", "canBeUnset", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "\"timeout\"", ")", "->", "defaultValue", "(", "5", ")", "->", "end", "(", ")", "->", "// WARNING: These 3 fields as they are, outside of the c2dm array", "// are deprecrated in favour of using the c2dm array configuration", "// At present these will be overriden by anything supplied", "// in the c2dm array", "scalarNode", "(", "\"username\"", ")", "->", "defaultValue", "(", "\"\"", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"password\"", ")", "->", "defaultValue", "(", "\"\"", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"source\"", ")", "->", "defaultValue", "(", "\"\"", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "\"c2dm\"", ")", "->", "canBeUnset", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "\"username\"", ")", "->", "isRequired", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"password\"", ")", "->", "isRequired", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"source\"", ")", "->", "defaultValue", "(", "\"\"", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "\"gcm\"", ")", "->", "canBeUnset", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "\"api_key\"", ")", "->", "isRequired", "(", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "\"use_multi_curl\"", ")", "->", "defaultValue", "(", "true", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "\"dry_run\"", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "}" ]
Android configuration
[ "Android", "configuration" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/Configuration.php#L37-L75
richsage/RMSPushNotificationsBundle
DependencyInjection/Configuration.php
Configuration.addApple
private function addApple($os) { $config = $this->root-> children()-> arrayNode($os)-> children()-> scalarNode("timeout")->defaultValue(60)->end()-> booleanNode("sandbox")->defaultFalse()->end()-> scalarNode("pem")->cannotBeEmpty()->end()-> scalarNode("passphrase")->defaultValue("")->end()-> scalarNode('json_unescaped_unicode')->defaultFalse(); if (method_exists($config,'info')) { $config = $config->info('PHP >= 5.4.0 and each messaged must be UTF-8 encoding'); } $config->end()-> end()-> end()-> end() ; }
php
private function addApple($os) { $config = $this->root-> children()-> arrayNode($os)-> children()-> scalarNode("timeout")->defaultValue(60)->end()-> booleanNode("sandbox")->defaultFalse()->end()-> scalarNode("pem")->cannotBeEmpty()->end()-> scalarNode("passphrase")->defaultValue("")->end()-> scalarNode('json_unescaped_unicode')->defaultFalse(); if (method_exists($config,'info')) { $config = $config->info('PHP >= 5.4.0 and each messaged must be UTF-8 encoding'); } $config->end()-> end()-> end()-> end() ; }
[ "private", "function", "addApple", "(", "$", "os", ")", "{", "$", "config", "=", "$", "this", "->", "root", "->", "children", "(", ")", "->", "arrayNode", "(", "$", "os", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "\"timeout\"", ")", "->", "defaultValue", "(", "60", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "\"sandbox\"", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"pem\"", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"passphrase\"", ")", "->", "defaultValue", "(", "\"\"", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'json_unescaped_unicode'", ")", "->", "defaultFalse", "(", ")", ";", "if", "(", "method_exists", "(", "$", "config", ",", "'info'", ")", ")", "{", "$", "config", "=", "$", "config", "->", "info", "(", "'PHP >= 5.4.0 and each messaged must be UTF-8 encoding'", ")", ";", "}", "$", "config", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "}" ]
Generic Apple Configuration
[ "Generic", "Apple", "Configuration" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/Configuration.php#L96-L115
richsage/RMSPushNotificationsBundle
DependencyInjection/Configuration.php
Configuration.addBlackberry
protected function addBlackberry() { $this->root-> children()-> arrayNode("blackberry")-> children()-> scalarNode("timeout")->defaultValue(5)->end()-> booleanNode("evaluation")->defaultFalse()->end()-> scalarNode("app_id")->isRequired()->cannotBeEmpty()->end()-> scalarNode("password")->isRequired()->cannotBeEmpty()->end()-> end()-> end()-> end() ; }
php
protected function addBlackberry() { $this->root-> children()-> arrayNode("blackberry")-> children()-> scalarNode("timeout")->defaultValue(5)->end()-> booleanNode("evaluation")->defaultFalse()->end()-> scalarNode("app_id")->isRequired()->cannotBeEmpty()->end()-> scalarNode("password")->isRequired()->cannotBeEmpty()->end()-> end()-> end()-> end() ; }
[ "protected", "function", "addBlackberry", "(", ")", "{", "$", "this", "->", "root", "->", "children", "(", ")", "->", "arrayNode", "(", "\"blackberry\"", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "\"timeout\"", ")", "->", "defaultValue", "(", "5", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "\"evaluation\"", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"app_id\"", ")", "->", "isRequired", "(", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "\"password\"", ")", "->", "isRequired", "(", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "}" ]
Blackberry configuration
[ "Blackberry", "configuration" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/Configuration.php#L120-L134
richsage/RMSPushNotificationsBundle
DependencyInjection/Configuration.php
Configuration.addWindowsphone
protected function addWindowsphone() { $this->root-> children()-> arrayNode('windowsphone')-> children()-> scalarNode("timeout")->defaultValue(5)->end()-> end()-> end()-> end() ; }
php
protected function addWindowsphone() { $this->root-> children()-> arrayNode('windowsphone')-> children()-> scalarNode("timeout")->defaultValue(5)->end()-> end()-> end()-> end() ; }
[ "protected", "function", "addWindowsphone", "(", ")", "{", "$", "this", "->", "root", "->", "children", "(", ")", "->", "arrayNode", "(", "'windowsphone'", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "\"timeout\"", ")", "->", "defaultValue", "(", "5", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "}" ]
Windows Phone configuration
[ "Windows", "Phone", "configuration" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/Configuration.php#L139-L150
richsage/RMSPushNotificationsBundle
Service/OS/BlackberryNotification.php
BlackberryNotification.send
public function send(MessageInterface $message) { if (!$message instanceof BlackberryMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by Blackberry", get_class($message))); } return $this->doSend($message); }
php
public function send(MessageInterface $message) { if (!$message instanceof BlackberryMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by Blackberry", get_class($message))); } return $this->doSend($message); }
[ "public", "function", "send", "(", "MessageInterface", "$", "message", ")", "{", "if", "(", "!", "$", "message", "instanceof", "BlackberryMessage", ")", "{", "throw", "new", "InvalidMessageTypeException", "(", "sprintf", "(", "\"Message type '%s' not supported by Blackberry\"", ",", "get_class", "(", "$", "message", ")", ")", ")", ";", "}", "return", "$", "this", "->", "doSend", "(", "$", "message", ")", ";", "}" ]
Sends a Blackberry Push message @param \RMS\PushNotificationsBundle\Message\MessageInterface $message @throws \RMS\PushNotificationsBundle\Exception\InvalidMessageTypeException @return bool
[ "Sends", "a", "Blackberry", "Push", "message" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/BlackberryNotification.php#L75-L82
richsage/RMSPushNotificationsBundle
Service/OS/BlackberryNotification.php
BlackberryNotification.doSend
protected function doSend(BlackberryMessage $message) { $separator = "mPsbVQo0a68eIL3OAxnm"; $body = $this->constructMessageBody($message, $separator); $browser = new Browser(new Curl()); $browser->getClient()->setTimeout($this->timeout); $listener = new BasicAuthListener($this->appID, $this->password); $browser->addListener($listener); $url = "https://pushapi.na.blackberry.com/mss/PD_pushRequest"; if ($this->evaluation) { $url = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest"; } $headers = array(); $headers[] = "Content-Type: multipart/related; boundary={$separator}; type=application/xml"; $headers[] = "Accept: text/html, *"; $headers[] = "Connection: Keep-Alive"; $response = $browser->post($url, $headers, $body); return $this->parseResponse($response); }
php
protected function doSend(BlackberryMessage $message) { $separator = "mPsbVQo0a68eIL3OAxnm"; $body = $this->constructMessageBody($message, $separator); $browser = new Browser(new Curl()); $browser->getClient()->setTimeout($this->timeout); $listener = new BasicAuthListener($this->appID, $this->password); $browser->addListener($listener); $url = "https://pushapi.na.blackberry.com/mss/PD_pushRequest"; if ($this->evaluation) { $url = "https://pushapi.eval.blackberry.com/mss/PD_pushRequest"; } $headers = array(); $headers[] = "Content-Type: multipart/related; boundary={$separator}; type=application/xml"; $headers[] = "Accept: text/html, *"; $headers[] = "Connection: Keep-Alive"; $response = $browser->post($url, $headers, $body); return $this->parseResponse($response); }
[ "protected", "function", "doSend", "(", "BlackberryMessage", "$", "message", ")", "{", "$", "separator", "=", "\"mPsbVQo0a68eIL3OAxnm\"", ";", "$", "body", "=", "$", "this", "->", "constructMessageBody", "(", "$", "message", ",", "$", "separator", ")", ";", "$", "browser", "=", "new", "Browser", "(", "new", "Curl", "(", ")", ")", ";", "$", "browser", "->", "getClient", "(", ")", "->", "setTimeout", "(", "$", "this", "->", "timeout", ")", ";", "$", "listener", "=", "new", "BasicAuthListener", "(", "$", "this", "->", "appID", ",", "$", "this", "->", "password", ")", ";", "$", "browser", "->", "addListener", "(", "$", "listener", ")", ";", "$", "url", "=", "\"https://pushapi.na.blackberry.com/mss/PD_pushRequest\"", ";", "if", "(", "$", "this", "->", "evaluation", ")", "{", "$", "url", "=", "\"https://pushapi.eval.blackberry.com/mss/PD_pushRequest\"", ";", "}", "$", "headers", "=", "array", "(", ")", ";", "$", "headers", "[", "]", "=", "\"Content-Type: multipart/related; boundary={$separator}; type=application/xml\"", ";", "$", "headers", "[", "]", "=", "\"Accept: text/html, *\"", ";", "$", "headers", "[", "]", "=", "\"Connection: Keep-Alive\"", ";", "$", "response", "=", "$", "browser", "->", "post", "(", "$", "url", ",", "$", "headers", ",", "$", "body", ")", ";", "return", "$", "this", "->", "parseResponse", "(", "$", "response", ")", ";", "}" ]
Does the actual sending @param \RMS\PushNotificationsBundle\Message\BlackberryMessage $message @return bool
[ "Does", "the", "actual", "sending" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/BlackberryNotification.php#L90-L111
richsage/RMSPushNotificationsBundle
Service/OS/BlackberryNotification.php
BlackberryNotification.constructMessageBody
protected function constructMessageBody(BlackberryMessage $message, $separator) { $data = ""; $messageID = microtime(true); $data .= "--" . $separator . "\r\n"; $data .= "Content-Type: application/xml; charset=UTF-8\r\n\r\n"; $data .= $this->getXMLBody($message, $messageID) . "\r\n"; $data .= "--" . $separator . "\r\n"; $data .= "Content-Type: text/plain\r\n"; $data .= "Push-Message-ID: {$messageID}\r\n\r\n"; if (is_array($message->getMessageBody())) { $data .= json_encode($message->getMessageBody()); } else { $data .= $message->getMessageBody(); } $data .= "\r\n"; $data .= "--" . $separator . "--\r\n"; return $data; }
php
protected function constructMessageBody(BlackberryMessage $message, $separator) { $data = ""; $messageID = microtime(true); $data .= "--" . $separator . "\r\n"; $data .= "Content-Type: application/xml; charset=UTF-8\r\n\r\n"; $data .= $this->getXMLBody($message, $messageID) . "\r\n"; $data .= "--" . $separator . "\r\n"; $data .= "Content-Type: text/plain\r\n"; $data .= "Push-Message-ID: {$messageID}\r\n\r\n"; if (is_array($message->getMessageBody())) { $data .= json_encode($message->getMessageBody()); } else { $data .= $message->getMessageBody(); } $data .= "\r\n"; $data .= "--" . $separator . "--\r\n"; return $data; }
[ "protected", "function", "constructMessageBody", "(", "BlackberryMessage", "$", "message", ",", "$", "separator", ")", "{", "$", "data", "=", "\"\"", ";", "$", "messageID", "=", "microtime", "(", "true", ")", ";", "$", "data", ".=", "\"--\"", ".", "$", "separator", ".", "\"\\r\\n\"", ";", "$", "data", ".=", "\"Content-Type: application/xml; charset=UTF-8\\r\\n\\r\\n\"", ";", "$", "data", ".=", "$", "this", "->", "getXMLBody", "(", "$", "message", ",", "$", "messageID", ")", ".", "\"\\r\\n\"", ";", "$", "data", ".=", "\"--\"", ".", "$", "separator", ".", "\"\\r\\n\"", ";", "$", "data", ".=", "\"Content-Type: text/plain\\r\\n\"", ";", "$", "data", ".=", "\"Push-Message-ID: {$messageID}\\r\\n\\r\\n\"", ";", "if", "(", "is_array", "(", "$", "message", "->", "getMessageBody", "(", ")", ")", ")", "{", "$", "data", ".=", "json_encode", "(", "$", "message", "->", "getMessageBody", "(", ")", ")", ";", "}", "else", "{", "$", "data", ".=", "$", "message", "->", "getMessageBody", "(", ")", ";", "}", "$", "data", ".=", "\"\\r\\n\"", ";", "$", "data", ".=", "\"--\"", ".", "$", "separator", ".", "\"--\\r\\n\"", ";", "return", "$", "data", ";", "}" ]
Builds the actual body of the message @param \RMS\PushNotificationsBundle\Message\BlackberryMessage $message @param $separator @return string
[ "Builds", "the", "actual", "body", "of", "the", "message" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/BlackberryNotification.php#L120-L140
richsage/RMSPushNotificationsBundle
Service/OS/BlackberryNotification.php
BlackberryNotification.parseResponse
protected function parseResponse(\Buzz\Message\Response $response) { if (null !== $response->getStatusCode() && $response->getStatusCode() != 200) { return false; } $doc = new \DOMDocument(); $doc->loadXML($response->getContent()); $elems = $doc->getElementsByTagName("response-result"); if (!$elems->length) { $this->logger->error('Response is empty'); return false; } $responseElement = $elems->item(0); if ($responseElement->getAttribute("code") != "1001") { $this->logger->error($responseElement->getAttribute("code"). ' : '. $responseElement->getAttribute("desc")); } return ($responseElement->getAttribute("code") == "1001"); }
php
protected function parseResponse(\Buzz\Message\Response $response) { if (null !== $response->getStatusCode() && $response->getStatusCode() != 200) { return false; } $doc = new \DOMDocument(); $doc->loadXML($response->getContent()); $elems = $doc->getElementsByTagName("response-result"); if (!$elems->length) { $this->logger->error('Response is empty'); return false; } $responseElement = $elems->item(0); if ($responseElement->getAttribute("code") != "1001") { $this->logger->error($responseElement->getAttribute("code"). ' : '. $responseElement->getAttribute("desc")); } return ($responseElement->getAttribute("code") == "1001"); }
[ "protected", "function", "parseResponse", "(", "\\", "Buzz", "\\", "Message", "\\", "Response", "$", "response", ")", "{", "if", "(", "null", "!==", "$", "response", "->", "getStatusCode", "(", ")", "&&", "$", "response", "->", "getStatusCode", "(", ")", "!=", "200", ")", "{", "return", "false", ";", "}", "$", "doc", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "doc", "->", "loadXML", "(", "$", "response", "->", "getContent", "(", ")", ")", ";", "$", "elems", "=", "$", "doc", "->", "getElementsByTagName", "(", "\"response-result\"", ")", ";", "if", "(", "!", "$", "elems", "->", "length", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "'Response is empty'", ")", ";", "return", "false", ";", "}", "$", "responseElement", "=", "$", "elems", "->", "item", "(", "0", ")", ";", "if", "(", "$", "responseElement", "->", "getAttribute", "(", "\"code\"", ")", "!=", "\"1001\"", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "$", "responseElement", "->", "getAttribute", "(", "\"code\"", ")", ".", "' : '", ".", "$", "responseElement", "->", "getAttribute", "(", "\"desc\"", ")", ")", ";", "}", "return", "(", "$", "responseElement", "->", "getAttribute", "(", "\"code\"", ")", "==", "\"1001\"", ")", ";", "}" ]
Handles and parses the response Returns a value indicating success/fail @param \Buzz\Message\Response $response @return bool
[ "Handles", "and", "parses", "the", "response", "Returns", "a", "value", "indicating", "success", "/", "fail" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/BlackberryNotification.php#L149-L167
richsage/RMSPushNotificationsBundle
Service/OS/BlackberryNotification.php
BlackberryNotification.getXMLBody
private function getXMLBody(BlackberryMessage $message, $messageID) { $deliverBefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+5 minutes')); $impl = new \DOMImplementation(); $dtd = $impl->createDocumentType( "pap", "-//WAPFORUM//DTD PAP 2.1//EN", "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd" ); $doc = $impl->createDocument("", "", $dtd); // Build it centre-out $pm = $doc->createElement("push-message"); $pm->setAttribute("push-id", $messageID); $pm->setAttribute("deliver-before-timestamp", $deliverBefore); $pm->setAttribute("source-reference", $this->appID); $qos = $doc->createElement("quality-of-service"); $qos->setAttribute("delivery-method", "unconfirmed"); $add = $doc->createElement("address"); $add->setAttribute("address-value", $message->getDeviceIdentifier()); $pm->appendChild($add); $pm->appendChild($qos); $pap = $doc->createElement("pap"); $pap->appendChild($pm); $doc->appendChild($pap); return $doc->saveXML(); }
php
private function getXMLBody(BlackberryMessage $message, $messageID) { $deliverBefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+5 minutes')); $impl = new \DOMImplementation(); $dtd = $impl->createDocumentType( "pap", "-//WAPFORUM//DTD PAP 2.1//EN", "http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd" ); $doc = $impl->createDocument("", "", $dtd); // Build it centre-out $pm = $doc->createElement("push-message"); $pm->setAttribute("push-id", $messageID); $pm->setAttribute("deliver-before-timestamp", $deliverBefore); $pm->setAttribute("source-reference", $this->appID); $qos = $doc->createElement("quality-of-service"); $qos->setAttribute("delivery-method", "unconfirmed"); $add = $doc->createElement("address"); $add->setAttribute("address-value", $message->getDeviceIdentifier()); $pm->appendChild($add); $pm->appendChild($qos); $pap = $doc->createElement("pap"); $pap->appendChild($pm); $doc->appendChild($pap); return $doc->saveXML(); }
[ "private", "function", "getXMLBody", "(", "BlackberryMessage", "$", "message", ",", "$", "messageID", ")", "{", "$", "deliverBefore", "=", "gmdate", "(", "'Y-m-d\\TH:i:s\\Z'", ",", "strtotime", "(", "'+5 minutes'", ")", ")", ";", "$", "impl", "=", "new", "\\", "DOMImplementation", "(", ")", ";", "$", "dtd", "=", "$", "impl", "->", "createDocumentType", "(", "\"pap\"", ",", "\"-//WAPFORUM//DTD PAP 2.1//EN\"", ",", "\"http://www.openmobilealliance.org/tech/DTD/pap_2.1.dtd\"", ")", ";", "$", "doc", "=", "$", "impl", "->", "createDocument", "(", "\"\"", ",", "\"\"", ",", "$", "dtd", ")", ";", "// Build it centre-out", "$", "pm", "=", "$", "doc", "->", "createElement", "(", "\"push-message\"", ")", ";", "$", "pm", "->", "setAttribute", "(", "\"push-id\"", ",", "$", "messageID", ")", ";", "$", "pm", "->", "setAttribute", "(", "\"deliver-before-timestamp\"", ",", "$", "deliverBefore", ")", ";", "$", "pm", "->", "setAttribute", "(", "\"source-reference\"", ",", "$", "this", "->", "appID", ")", ";", "$", "qos", "=", "$", "doc", "->", "createElement", "(", "\"quality-of-service\"", ")", ";", "$", "qos", "->", "setAttribute", "(", "\"delivery-method\"", ",", "\"unconfirmed\"", ")", ";", "$", "add", "=", "$", "doc", "->", "createElement", "(", "\"address\"", ")", ";", "$", "add", "->", "setAttribute", "(", "\"address-value\"", ",", "$", "message", "->", "getDeviceIdentifier", "(", ")", ")", ";", "$", "pm", "->", "appendChild", "(", "$", "add", ")", ";", "$", "pm", "->", "appendChild", "(", "$", "qos", ")", ";", "$", "pap", "=", "$", "doc", "->", "createElement", "(", "\"pap\"", ")", ";", "$", "pap", "->", "appendChild", "(", "$", "pm", ")", ";", "$", "doc", "->", "appendChild", "(", "$", "pap", ")", ";", "return", "$", "doc", "->", "saveXML", "(", ")", ";", "}" ]
Create the XML body that accompanies the actual push data @param $messageID @return string
[ "Create", "the", "XML", "body", "that", "accompanies", "the", "actual", "push", "data" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/BlackberryNotification.php#L175-L204
richsage/RMSPushNotificationsBundle
Service/OS/AndroidGCMNotification.php
AndroidGCMNotification.send
public function send(MessageInterface $message) { if (!$message instanceof AndroidMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by GCM", get_class($message))); } if (!$message->isGCM()) { throw new InvalidMessageTypeException("Non-GCM messages not supported by the Android GCM sender"); } $headers = array( "Authorization: key=" . $this->apiKey, "Content-Type: application/json", ); $data = array_merge( $message->getGCMOptions(), array("data" => $message->getData()) ); if ($this->useDryRun) { $data['dry_run'] = true; } // Perform the calls (in parallel) $this->responses = array(); $gcmIdentifiers = $message->getGCMIdentifiers(); if (count($message->getGCMIdentifiers()) == 1) { $data['to'] = $gcmIdentifiers[0]; $this->responses[] = $this->browser->post($this->apiURL, $headers, json_encode($data)); } else { // Chunk number of registration IDs according to the maximum allowed by GCM $chunks = array_chunk($message->getGCMIdentifiers(), $this->registrationIdMaxCount); foreach ($chunks as $registrationIDs) { $data['registration_ids'] = $registrationIDs; $this->responses[] = $this->browser->post($this->apiURL, $headers, json_encode($data)); } } // If we're using multiple concurrent connections via MultiCurl // then we should flush all requests if ($this->browser->getClient() instanceof MultiCurl) { $this->browser->getClient()->flush(); } // Determine success foreach ($this->responses as $response) { $message = json_decode($response->getContent()); if ($message === null || $message->success == 0 || $message->failure > 0) { if ($message == null) { $this->logger->error($response->getContent()); } else { foreach ($message->results as $result) { if (isset($result->error)) { $this->logger->error($result->error); } } } return false; } } return true; }
php
public function send(MessageInterface $message) { if (!$message instanceof AndroidMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by GCM", get_class($message))); } if (!$message->isGCM()) { throw new InvalidMessageTypeException("Non-GCM messages not supported by the Android GCM sender"); } $headers = array( "Authorization: key=" . $this->apiKey, "Content-Type: application/json", ); $data = array_merge( $message->getGCMOptions(), array("data" => $message->getData()) ); if ($this->useDryRun) { $data['dry_run'] = true; } // Perform the calls (in parallel) $this->responses = array(); $gcmIdentifiers = $message->getGCMIdentifiers(); if (count($message->getGCMIdentifiers()) == 1) { $data['to'] = $gcmIdentifiers[0]; $this->responses[] = $this->browser->post($this->apiURL, $headers, json_encode($data)); } else { // Chunk number of registration IDs according to the maximum allowed by GCM $chunks = array_chunk($message->getGCMIdentifiers(), $this->registrationIdMaxCount); foreach ($chunks as $registrationIDs) { $data['registration_ids'] = $registrationIDs; $this->responses[] = $this->browser->post($this->apiURL, $headers, json_encode($data)); } } // If we're using multiple concurrent connections via MultiCurl // then we should flush all requests if ($this->browser->getClient() instanceof MultiCurl) { $this->browser->getClient()->flush(); } // Determine success foreach ($this->responses as $response) { $message = json_decode($response->getContent()); if ($message === null || $message->success == 0 || $message->failure > 0) { if ($message == null) { $this->logger->error($response->getContent()); } else { foreach ($message->results as $result) { if (isset($result->error)) { $this->logger->error($result->error); } } } return false; } } return true; }
[ "public", "function", "send", "(", "MessageInterface", "$", "message", ")", "{", "if", "(", "!", "$", "message", "instanceof", "AndroidMessage", ")", "{", "throw", "new", "InvalidMessageTypeException", "(", "sprintf", "(", "\"Message type '%s' not supported by GCM\"", ",", "get_class", "(", "$", "message", ")", ")", ")", ";", "}", "if", "(", "!", "$", "message", "->", "isGCM", "(", ")", ")", "{", "throw", "new", "InvalidMessageTypeException", "(", "\"Non-GCM messages not supported by the Android GCM sender\"", ")", ";", "}", "$", "headers", "=", "array", "(", "\"Authorization: key=\"", ".", "$", "this", "->", "apiKey", ",", "\"Content-Type: application/json\"", ",", ")", ";", "$", "data", "=", "array_merge", "(", "$", "message", "->", "getGCMOptions", "(", ")", ",", "array", "(", "\"data\"", "=>", "$", "message", "->", "getData", "(", ")", ")", ")", ";", "if", "(", "$", "this", "->", "useDryRun", ")", "{", "$", "data", "[", "'dry_run'", "]", "=", "true", ";", "}", "// Perform the calls (in parallel)", "$", "this", "->", "responses", "=", "array", "(", ")", ";", "$", "gcmIdentifiers", "=", "$", "message", "->", "getGCMIdentifiers", "(", ")", ";", "if", "(", "count", "(", "$", "message", "->", "getGCMIdentifiers", "(", ")", ")", "==", "1", ")", "{", "$", "data", "[", "'to'", "]", "=", "$", "gcmIdentifiers", "[", "0", "]", ";", "$", "this", "->", "responses", "[", "]", "=", "$", "this", "->", "browser", "->", "post", "(", "$", "this", "->", "apiURL", ",", "$", "headers", ",", "json_encode", "(", "$", "data", ")", ")", ";", "}", "else", "{", "// Chunk number of registration IDs according to the maximum allowed by GCM", "$", "chunks", "=", "array_chunk", "(", "$", "message", "->", "getGCMIdentifiers", "(", ")", ",", "$", "this", "->", "registrationIdMaxCount", ")", ";", "foreach", "(", "$", "chunks", "as", "$", "registrationIDs", ")", "{", "$", "data", "[", "'registration_ids'", "]", "=", "$", "registrationIDs", ";", "$", "this", "->", "responses", "[", "]", "=", "$", "this", "->", "browser", "->", "post", "(", "$", "this", "->", "apiURL", ",", "$", "headers", ",", "json_encode", "(", "$", "data", ")", ")", ";", "}", "}", "// If we're using multiple concurrent connections via MultiCurl", "// then we should flush all requests", "if", "(", "$", "this", "->", "browser", "->", "getClient", "(", ")", "instanceof", "MultiCurl", ")", "{", "$", "this", "->", "browser", "->", "getClient", "(", ")", "->", "flush", "(", ")", ";", "}", "// Determine success", "foreach", "(", "$", "this", "->", "responses", "as", "$", "response", ")", "{", "$", "message", "=", "json_decode", "(", "$", "response", "->", "getContent", "(", ")", ")", ";", "if", "(", "$", "message", "===", "null", "||", "$", "message", "->", "success", "==", "0", "||", "$", "message", "->", "failure", ">", "0", ")", "{", "if", "(", "$", "message", "==", "null", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "$", "response", "->", "getContent", "(", ")", ")", ";", "}", "else", "{", "foreach", "(", "$", "message", "->", "results", "as", "$", "result", ")", "{", "if", "(", "isset", "(", "$", "result", "->", "error", ")", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "$", "result", "->", "error", ")", ";", "}", "}", "}", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Sends the data to the given registration IDs via the GCM server @param \RMS\PushNotificationsBundle\Message\MessageInterface $message @throws \RMS\PushNotificationsBundle\Exception\InvalidMessageTypeException @return bool
[ "Sends", "the", "data", "to", "the", "given", "registration", "IDs", "via", "the", "GCM", "server" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AndroidGCMNotification.php#L97-L160
richsage/RMSPushNotificationsBundle
Device/iOS/Feedback.php
Feedback.unpack
public function unpack($data) { $token = unpack("N1timestamp/n1length/H*token", $data); $this->timestamp = $token["timestamp"]; $this->tokenLength = $token["length"]; $this->uuid = $token["token"]; return $this; }
php
public function unpack($data) { $token = unpack("N1timestamp/n1length/H*token", $data); $this->timestamp = $token["timestamp"]; $this->tokenLength = $token["length"]; $this->uuid = $token["token"]; return $this; }
[ "public", "function", "unpack", "(", "$", "data", ")", "{", "$", "token", "=", "unpack", "(", "\"N1timestamp/n1length/H*token\"", ",", "$", "data", ")", ";", "$", "this", "->", "timestamp", "=", "$", "token", "[", "\"timestamp\"", "]", ";", "$", "this", "->", "tokenLength", "=", "$", "token", "[", "\"length\"", "]", ";", "$", "this", "->", "uuid", "=", "$", "token", "[", "\"token\"", "]", ";", "return", "$", "this", ";", "}" ]
Unpacks the APNS data into the required fields @param $data @return \RMS\PushNotificationsBundle\Device\iOS\Feedback
[ "Unpacks", "the", "APNS", "data", "into", "the", "required", "fields" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Device/iOS/Feedback.php#L17-L25
richsage/RMSPushNotificationsBundle
DependencyInjection/RMSPushNotificationsExtension.php
RMSPushNotificationsExtension.load
public function load(array $configs, ContainerBuilder $container) { $this->container = $container; $this->kernelRootDir = $container->getParameterBag()->get("kernel.root_dir"); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $this->setInitialParams(); if (isset($config["android"])) { $this->setAndroidConfig($config); $loader->load('android.xml'); } if (isset($config["ios"])) { $this->setiOSConfig($config); $loader->load('ios.xml'); } if (isset($config["mac"])) { $this->setMacConfig($config); $loader->load('mac.xml'); } if (isset($config["blackberry"])) { $this->setBlackberryConfig($config); $loader->load('blackberry.xml'); } if (isset($config['windowsphone'])) { $this->setWindowsphoneConfig($config); $loader->load('windowsphone.xml'); } }
php
public function load(array $configs, ContainerBuilder $container) { $this->container = $container; $this->kernelRootDir = $container->getParameterBag()->get("kernel.root_dir"); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $this->setInitialParams(); if (isset($config["android"])) { $this->setAndroidConfig($config); $loader->load('android.xml'); } if (isset($config["ios"])) { $this->setiOSConfig($config); $loader->load('ios.xml'); } if (isset($config["mac"])) { $this->setMacConfig($config); $loader->load('mac.xml'); } if (isset($config["blackberry"])) { $this->setBlackberryConfig($config); $loader->load('blackberry.xml'); } if (isset($config['windowsphone'])) { $this->setWindowsphoneConfig($config); $loader->load('windowsphone.xml'); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "this", "->", "container", "=", "$", "container", ";", "$", "this", "->", "kernelRootDir", "=", "$", "container", "->", "getParameterBag", "(", ")", "->", "get", "(", "\"kernel.root_dir\"", ")", ";", "$", "loader", "=", "new", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "$", "loader", "->", "load", "(", "'services.xml'", ")", ";", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "config", "=", "$", "this", "->", "processConfiguration", "(", "$", "configuration", ",", "$", "configs", ")", ";", "$", "this", "->", "setInitialParams", "(", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "\"android\"", "]", ")", ")", "{", "$", "this", "->", "setAndroidConfig", "(", "$", "config", ")", ";", "$", "loader", "->", "load", "(", "'android.xml'", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "\"ios\"", "]", ")", ")", "{", "$", "this", "->", "setiOSConfig", "(", "$", "config", ")", ";", "$", "loader", "->", "load", "(", "'ios.xml'", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "\"mac\"", "]", ")", ")", "{", "$", "this", "->", "setMacConfig", "(", "$", "config", ")", ";", "$", "loader", "->", "load", "(", "'mac.xml'", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "\"blackberry\"", "]", ")", ")", "{", "$", "this", "->", "setBlackberryConfig", "(", "$", "config", ")", ";", "$", "loader", "->", "load", "(", "'blackberry.xml'", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'windowsphone'", "]", ")", ")", "{", "$", "this", "->", "setWindowsphoneConfig", "(", "$", "config", ")", ";", "$", "loader", "->", "load", "(", "'windowsphone.xml'", ")", ";", "}", "}" ]
Loads any resources/services we need @param array $configs @param \Symfony\Component\DependencyInjection\ContainerBuilder $container @return void
[ "Loads", "any", "resources", "/", "services", "we", "need" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/RMSPushNotificationsExtension.php#L29-L61
richsage/RMSPushNotificationsBundle
DependencyInjection/RMSPushNotificationsExtension.php
RMSPushNotificationsExtension.setInitialParams
protected function setInitialParams() { $this->container->setParameter("rms_push_notifications.android.enabled", false); $this->container->setParameter("rms_push_notifications.ios.enabled", false); $this->container->setParameter("rms_push_notifications.mac.enabled", false); }
php
protected function setInitialParams() { $this->container->setParameter("rms_push_notifications.android.enabled", false); $this->container->setParameter("rms_push_notifications.ios.enabled", false); $this->container->setParameter("rms_push_notifications.mac.enabled", false); }
[ "protected", "function", "setInitialParams", "(", ")", "{", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.enabled\"", ",", "false", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.ios.enabled\"", ",", "false", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.mac.enabled\"", ",", "false", ")", ";", "}" ]
Initial enabling
[ "Initial", "enabling" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/RMSPushNotificationsExtension.php#L66-L71
richsage/RMSPushNotificationsBundle
DependencyInjection/RMSPushNotificationsExtension.php
RMSPushNotificationsExtension.setAndroidConfig
protected function setAndroidConfig(array $config) { $this->container->setParameter("rms_push_notifications.android.enabled", true); $this->container->setParameter("rms_push_notifications.android.c2dm.enabled", true); // C2DM $username = $config["android"]["username"]; $password = $config["android"]["password"]; $source = $config["android"]["source"]; $timeout = $config["android"]["timeout"]; if (isset($config["android"]["c2dm"])) { $username = $config["android"]["c2dm"]["username"]; $password = $config["android"]["c2dm"]["password"]; $source = $config["android"]["c2dm"]["source"]; } $this->container->setParameter("rms_push_notifications.android.timeout", $timeout); $this->container->setParameter("rms_push_notifications.android.c2dm.username", $username); $this->container->setParameter("rms_push_notifications.android.c2dm.password", $password); $this->container->setParameter("rms_push_notifications.android.c2dm.source", $source); // GCM $this->container->setParameter("rms_push_notifications.android.gcm.enabled", isset($config["android"]["gcm"])); if (isset($config["android"]["gcm"])) { $this->container->setParameter("rms_push_notifications.android.gcm.api_key", $config["android"]["gcm"]["api_key"]); $this->container->setParameter("rms_push_notifications.android.gcm.use_multi_curl", $config["android"]["gcm"]["use_multi_curl"]); $this->container->setParameter('rms_push_notifications.android.gcm.dry_run', $config["android"]["gcm"]["dry_run"]); } }
php
protected function setAndroidConfig(array $config) { $this->container->setParameter("rms_push_notifications.android.enabled", true); $this->container->setParameter("rms_push_notifications.android.c2dm.enabled", true); // C2DM $username = $config["android"]["username"]; $password = $config["android"]["password"]; $source = $config["android"]["source"]; $timeout = $config["android"]["timeout"]; if (isset($config["android"]["c2dm"])) { $username = $config["android"]["c2dm"]["username"]; $password = $config["android"]["c2dm"]["password"]; $source = $config["android"]["c2dm"]["source"]; } $this->container->setParameter("rms_push_notifications.android.timeout", $timeout); $this->container->setParameter("rms_push_notifications.android.c2dm.username", $username); $this->container->setParameter("rms_push_notifications.android.c2dm.password", $password); $this->container->setParameter("rms_push_notifications.android.c2dm.source", $source); // GCM $this->container->setParameter("rms_push_notifications.android.gcm.enabled", isset($config["android"]["gcm"])); if (isset($config["android"]["gcm"])) { $this->container->setParameter("rms_push_notifications.android.gcm.api_key", $config["android"]["gcm"]["api_key"]); $this->container->setParameter("rms_push_notifications.android.gcm.use_multi_curl", $config["android"]["gcm"]["use_multi_curl"]); $this->container->setParameter('rms_push_notifications.android.gcm.dry_run', $config["android"]["gcm"]["dry_run"]); } }
[ "protected", "function", "setAndroidConfig", "(", "array", "$", "config", ")", "{", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.enabled\"", ",", "true", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.c2dm.enabled\"", ",", "true", ")", ";", "// C2DM", "$", "username", "=", "$", "config", "[", "\"android\"", "]", "[", "\"username\"", "]", ";", "$", "password", "=", "$", "config", "[", "\"android\"", "]", "[", "\"password\"", "]", ";", "$", "source", "=", "$", "config", "[", "\"android\"", "]", "[", "\"source\"", "]", ";", "$", "timeout", "=", "$", "config", "[", "\"android\"", "]", "[", "\"timeout\"", "]", ";", "if", "(", "isset", "(", "$", "config", "[", "\"android\"", "]", "[", "\"c2dm\"", "]", ")", ")", "{", "$", "username", "=", "$", "config", "[", "\"android\"", "]", "[", "\"c2dm\"", "]", "[", "\"username\"", "]", ";", "$", "password", "=", "$", "config", "[", "\"android\"", "]", "[", "\"c2dm\"", "]", "[", "\"password\"", "]", ";", "$", "source", "=", "$", "config", "[", "\"android\"", "]", "[", "\"c2dm\"", "]", "[", "\"source\"", "]", ";", "}", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.timeout\"", ",", "$", "timeout", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.c2dm.username\"", ",", "$", "username", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.c2dm.password\"", ",", "$", "password", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.c2dm.source\"", ",", "$", "source", ")", ";", "// GCM", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.gcm.enabled\"", ",", "isset", "(", "$", "config", "[", "\"android\"", "]", "[", "\"gcm\"", "]", ")", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "\"android\"", "]", "[", "\"gcm\"", "]", ")", ")", "{", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.gcm.api_key\"", ",", "$", "config", "[", "\"android\"", "]", "[", "\"gcm\"", "]", "[", "\"api_key\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.android.gcm.use_multi_curl\"", ",", "$", "config", "[", "\"android\"", "]", "[", "\"gcm\"", "]", "[", "\"use_multi_curl\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "'rms_push_notifications.android.gcm.dry_run'", ",", "$", "config", "[", "\"android\"", "]", "[", "\"gcm\"", "]", "[", "\"dry_run\"", "]", ")", ";", "}", "}" ]
Sets Android config into container @param array $config
[ "Sets", "Android", "config", "into", "container" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/RMSPushNotificationsExtension.php#L78-L105
richsage/RMSPushNotificationsBundle
DependencyInjection/RMSPushNotificationsExtension.php
RMSPushNotificationsExtension.setAppleConfig
protected function setAppleConfig(array $config, $os) { $supportedAppleOS = array("mac", "ios"); //Check if the OS is supported if (!in_array($os, $supportedAppleOS, true)) { throw new \RuntimeException(sprintf('This Apple OS "%s" is not supported', $os)); } $pemFile = null; if (isset($config[$os]["pem"])) { // If PEM is set, it must be a real file if (realpath($config[$os]["pem"])) { // Absolute path $pemFile = $config[$os]["pem"]; } elseif (realpath($this->kernelRootDir.DIRECTORY_SEPARATOR.$config[$os]["pem"]) ) { // Relative path $pemFile = $this->kernelRootDir.DIRECTORY_SEPARATOR.$config[$os]["pem"]; } else { // path isn't valid throw new \RuntimeException(sprintf('Pem file "%s" not found.', $config[$os]["pem"])); } } if ($config[$os]['json_unescaped_unicode']) { // Not support JSON_UNESCAPED_UNICODE option if (!version_compare(PHP_VERSION, '5.4.0', '>=')) { throw new \LogicException(sprintf( 'Can\'t use JSON_UNESCAPED_UNICODE option. This option can use only PHP Version >= 5.4.0. Your version: %s', PHP_VERSION )); } } $this->container->setParameter(sprintf('rms_push_notifications.%s.enabled', $os), true); $this->container->setParameter(sprintf('rms_push_notifications.%s.timeout', $os), $config[$os]["timeout"]); $this->container->setParameter(sprintf('rms_push_notifications.%s.sandbox', $os), $config[$os]["sandbox"]); $this->container->setParameter(sprintf('rms_push_notifications.%s.pem', $os), $pemFile); $this->container->setParameter(sprintf('rms_push_notifications.%s.passphrase', $os), $config[$os]["passphrase"]); $this->container->setParameter(sprintf('rms_push_notifications.%s.json_unescaped_unicode', $os), (bool) $config[$os]['json_unescaped_unicode']); }
php
protected function setAppleConfig(array $config, $os) { $supportedAppleOS = array("mac", "ios"); //Check if the OS is supported if (!in_array($os, $supportedAppleOS, true)) { throw new \RuntimeException(sprintf('This Apple OS "%s" is not supported', $os)); } $pemFile = null; if (isset($config[$os]["pem"])) { // If PEM is set, it must be a real file if (realpath($config[$os]["pem"])) { // Absolute path $pemFile = $config[$os]["pem"]; } elseif (realpath($this->kernelRootDir.DIRECTORY_SEPARATOR.$config[$os]["pem"]) ) { // Relative path $pemFile = $this->kernelRootDir.DIRECTORY_SEPARATOR.$config[$os]["pem"]; } else { // path isn't valid throw new \RuntimeException(sprintf('Pem file "%s" not found.', $config[$os]["pem"])); } } if ($config[$os]['json_unescaped_unicode']) { // Not support JSON_UNESCAPED_UNICODE option if (!version_compare(PHP_VERSION, '5.4.0', '>=')) { throw new \LogicException(sprintf( 'Can\'t use JSON_UNESCAPED_UNICODE option. This option can use only PHP Version >= 5.4.0. Your version: %s', PHP_VERSION )); } } $this->container->setParameter(sprintf('rms_push_notifications.%s.enabled', $os), true); $this->container->setParameter(sprintf('rms_push_notifications.%s.timeout', $os), $config[$os]["timeout"]); $this->container->setParameter(sprintf('rms_push_notifications.%s.sandbox', $os), $config[$os]["sandbox"]); $this->container->setParameter(sprintf('rms_push_notifications.%s.pem', $os), $pemFile); $this->container->setParameter(sprintf('rms_push_notifications.%s.passphrase', $os), $config[$os]["passphrase"]); $this->container->setParameter(sprintf('rms_push_notifications.%s.json_unescaped_unicode', $os), (bool) $config[$os]['json_unescaped_unicode']); }
[ "protected", "function", "setAppleConfig", "(", "array", "$", "config", ",", "$", "os", ")", "{", "$", "supportedAppleOS", "=", "array", "(", "\"mac\"", ",", "\"ios\"", ")", ";", "//Check if the OS is supported", "if", "(", "!", "in_array", "(", "$", "os", ",", "$", "supportedAppleOS", ",", "true", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'This Apple OS \"%s\" is not supported'", ",", "$", "os", ")", ")", ";", "}", "$", "pemFile", "=", "null", ";", "if", "(", "isset", "(", "$", "config", "[", "$", "os", "]", "[", "\"pem\"", "]", ")", ")", "{", "// If PEM is set, it must be a real file", "if", "(", "realpath", "(", "$", "config", "[", "$", "os", "]", "[", "\"pem\"", "]", ")", ")", "{", "// Absolute path", "$", "pemFile", "=", "$", "config", "[", "$", "os", "]", "[", "\"pem\"", "]", ";", "}", "elseif", "(", "realpath", "(", "$", "this", "->", "kernelRootDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "config", "[", "$", "os", "]", "[", "\"pem\"", "]", ")", ")", "{", "// Relative path", "$", "pemFile", "=", "$", "this", "->", "kernelRootDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "config", "[", "$", "os", "]", "[", "\"pem\"", "]", ";", "}", "else", "{", "// path isn't valid", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Pem file \"%s\" not found.'", ",", "$", "config", "[", "$", "os", "]", "[", "\"pem\"", "]", ")", ")", ";", "}", "}", "if", "(", "$", "config", "[", "$", "os", "]", "[", "'json_unescaped_unicode'", "]", ")", "{", "// Not support JSON_UNESCAPED_UNICODE option", "if", "(", "!", "version_compare", "(", "PHP_VERSION", ",", "'5.4.0'", ",", "'>='", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Can\\'t use JSON_UNESCAPED_UNICODE option. This option can use only PHP Version >= 5.4.0. Your version: %s'", ",", "PHP_VERSION", ")", ")", ";", "}", "}", "$", "this", "->", "container", "->", "setParameter", "(", "sprintf", "(", "'rms_push_notifications.%s.enabled'", ",", "$", "os", ")", ",", "true", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "sprintf", "(", "'rms_push_notifications.%s.timeout'", ",", "$", "os", ")", ",", "$", "config", "[", "$", "os", "]", "[", "\"timeout\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "sprintf", "(", "'rms_push_notifications.%s.sandbox'", ",", "$", "os", ")", ",", "$", "config", "[", "$", "os", "]", "[", "\"sandbox\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "sprintf", "(", "'rms_push_notifications.%s.pem'", ",", "$", "os", ")", ",", "$", "pemFile", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "sprintf", "(", "'rms_push_notifications.%s.passphrase'", ",", "$", "os", ")", ",", "$", "config", "[", "$", "os", "]", "[", "\"passphrase\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "sprintf", "(", "'rms_push_notifications.%s.json_unescaped_unicode'", ",", "$", "os", ")", ",", "(", "bool", ")", "$", "config", "[", "$", "os", "]", "[", "'json_unescaped_unicode'", "]", ")", ";", "}" ]
Sets Apple config into container @param array $config @param $os @throws \RuntimeException @throws \LogicException
[ "Sets", "Apple", "config", "into", "container" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/RMSPushNotificationsExtension.php#L135-L174
richsage/RMSPushNotificationsBundle
DependencyInjection/RMSPushNotificationsExtension.php
RMSPushNotificationsExtension.setBlackberryConfig
protected function setBlackberryConfig(array $config) { $this->container->setParameter("rms_push_notifications.blackberry.enabled", true); $this->container->setParameter("rms_push_notifications.blackberry.timeout", $config["blackberry"]["timeout"]); $this->container->setParameter("rms_push_notifications.blackberry.evaluation", $config["blackberry"]["evaluation"]); $this->container->setParameter("rms_push_notifications.blackberry.app_id", $config["blackberry"]["app_id"]); $this->container->setParameter("rms_push_notifications.blackberry.password", $config["blackberry"]["password"]); }
php
protected function setBlackberryConfig(array $config) { $this->container->setParameter("rms_push_notifications.blackberry.enabled", true); $this->container->setParameter("rms_push_notifications.blackberry.timeout", $config["blackberry"]["timeout"]); $this->container->setParameter("rms_push_notifications.blackberry.evaluation", $config["blackberry"]["evaluation"]); $this->container->setParameter("rms_push_notifications.blackberry.app_id", $config["blackberry"]["app_id"]); $this->container->setParameter("rms_push_notifications.blackberry.password", $config["blackberry"]["password"]); }
[ "protected", "function", "setBlackberryConfig", "(", "array", "$", "config", ")", "{", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.blackberry.enabled\"", ",", "true", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.blackberry.timeout\"", ",", "$", "config", "[", "\"blackberry\"", "]", "[", "\"timeout\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.blackberry.evaluation\"", ",", "$", "config", "[", "\"blackberry\"", "]", "[", "\"evaluation\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.blackberry.app_id\"", ",", "$", "config", "[", "\"blackberry\"", "]", "[", "\"app_id\"", "]", ")", ";", "$", "this", "->", "container", "->", "setParameter", "(", "\"rms_push_notifications.blackberry.password\"", ",", "$", "config", "[", "\"blackberry\"", "]", "[", "\"password\"", "]", ")", ";", "}" ]
Sets Blackberry config into container @param array $config
[ "Sets", "Blackberry", "config", "into", "container" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/RMSPushNotificationsExtension.php#L181-L188
richsage/RMSPushNotificationsBundle
Service/OS/AndroidNotification.php
AndroidNotification.send
public function send(MessageInterface $message) { if (!$message instanceof AndroidMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by C2DM", get_class($message))); } if ($this->getAuthToken()) { $headers[] = "Authorization: GoogleLogin auth=" . $this->authToken; $data = $message->getMessageBody(); $buzz = new Browser(); $buzz->getClient()->setVerifyPeer(false); $buzz->getClient()->setTimeout($this->timeout); $response = $buzz->post("https://android.apis.google.com/c2dm/send", $headers, http_build_query($data)); return preg_match("/^id=/", $response->getContent()) > 0; } return false; }
php
public function send(MessageInterface $message) { if (!$message instanceof AndroidMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by C2DM", get_class($message))); } if ($this->getAuthToken()) { $headers[] = "Authorization: GoogleLogin auth=" . $this->authToken; $data = $message->getMessageBody(); $buzz = new Browser(); $buzz->getClient()->setVerifyPeer(false); $buzz->getClient()->setTimeout($this->timeout); $response = $buzz->post("https://android.apis.google.com/c2dm/send", $headers, http_build_query($data)); return preg_match("/^id=/", $response->getContent()) > 0; } return false; }
[ "public", "function", "send", "(", "MessageInterface", "$", "message", ")", "{", "if", "(", "!", "$", "message", "instanceof", "AndroidMessage", ")", "{", "throw", "new", "InvalidMessageTypeException", "(", "sprintf", "(", "\"Message type '%s' not supported by C2DM\"", ",", "get_class", "(", "$", "message", ")", ")", ")", ";", "}", "if", "(", "$", "this", "->", "getAuthToken", "(", ")", ")", "{", "$", "headers", "[", "]", "=", "\"Authorization: GoogleLogin auth=\"", ".", "$", "this", "->", "authToken", ";", "$", "data", "=", "$", "message", "->", "getMessageBody", "(", ")", ";", "$", "buzz", "=", "new", "Browser", "(", ")", ";", "$", "buzz", "->", "getClient", "(", ")", "->", "setVerifyPeer", "(", "false", ")", ";", "$", "buzz", "->", "getClient", "(", ")", "->", "setTimeout", "(", "$", "this", "->", "timeout", ")", ";", "$", "response", "=", "$", "buzz", "->", "post", "(", "\"https://android.apis.google.com/c2dm/send\"", ",", "$", "headers", ",", "http_build_query", "(", "$", "data", ")", ")", ";", "return", "preg_match", "(", "\"/^id=/\"", ",", "$", "response", "->", "getContent", "(", ")", ")", ">", "0", ";", "}", "return", "false", ";", "}" ]
Sends a C2DM message This assumes that a valid auth token can be obtained @param \RMS\PushNotificationsBundle\Message\MessageInterface $message @throws \RMS\PushNotificationsBundle\Exception\InvalidMessageTypeException @return bool
[ "Sends", "a", "C2DM", "message", "This", "assumes", "that", "a", "valid", "auth", "token", "can", "be", "obtained" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AndroidNotification.php#L73-L92
richsage/RMSPushNotificationsBundle
Service/OS/AndroidNotification.php
AndroidNotification.getAuthToken
protected function getAuthToken() { $data = array( "Email" => $this->username, "Passwd" => $this->password, "accountType" => "HOSTED_OR_GOOGLE", "source" => $this->source, "service" => "ac2dm" ); $buzz = new Browser(); $buzz->getClient()->setVerifyPeer(false); $buzz->getClient()->setTimeout($this->timeout); $response = $buzz->post("https://www.google.com/accounts/ClientLogin", array(), http_build_query($data)); if ($response->getStatusCode() !== 200) { return false; } preg_match("/Auth=([a-z0-9_\-]+)/i", $response->getContent(), $matches); $this->authToken = $matches[1]; return true; }
php
protected function getAuthToken() { $data = array( "Email" => $this->username, "Passwd" => $this->password, "accountType" => "HOSTED_OR_GOOGLE", "source" => $this->source, "service" => "ac2dm" ); $buzz = new Browser(); $buzz->getClient()->setVerifyPeer(false); $buzz->getClient()->setTimeout($this->timeout); $response = $buzz->post("https://www.google.com/accounts/ClientLogin", array(), http_build_query($data)); if ($response->getStatusCode() !== 200) { return false; } preg_match("/Auth=([a-z0-9_\-]+)/i", $response->getContent(), $matches); $this->authToken = $matches[1]; return true; }
[ "protected", "function", "getAuthToken", "(", ")", "{", "$", "data", "=", "array", "(", "\"Email\"", "=>", "$", "this", "->", "username", ",", "\"Passwd\"", "=>", "$", "this", "->", "password", ",", "\"accountType\"", "=>", "\"HOSTED_OR_GOOGLE\"", ",", "\"source\"", "=>", "$", "this", "->", "source", ",", "\"service\"", "=>", "\"ac2dm\"", ")", ";", "$", "buzz", "=", "new", "Browser", "(", ")", ";", "$", "buzz", "->", "getClient", "(", ")", "->", "setVerifyPeer", "(", "false", ")", ";", "$", "buzz", "->", "getClient", "(", ")", "->", "setTimeout", "(", "$", "this", "->", "timeout", ")", ";", "$", "response", "=", "$", "buzz", "->", "post", "(", "\"https://www.google.com/accounts/ClientLogin\"", ",", "array", "(", ")", ",", "http_build_query", "(", "$", "data", ")", ")", ";", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", ")", "{", "return", "false", ";", "}", "preg_match", "(", "\"/Auth=([a-z0-9_\\-]+)/i\"", ",", "$", "response", "->", "getContent", "(", ")", ",", "$", "matches", ")", ";", "$", "this", "->", "authToken", "=", "$", "matches", "[", "1", "]", ";", "return", "true", ";", "}" ]
Gets a valid authentication token @return bool
[ "Gets", "a", "valid", "authentication", "token" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AndroidNotification.php#L99-L121
richsage/RMSPushNotificationsBundle
DependencyInjection/Compiler/AddHandlerPass.php
AddHandlerPass.process
public function process(ContainerBuilder $container) { $service = $container->getDefinition("rms_push_notifications"); foreach ($container->findTaggedServiceIds("rms_push_notifications.handler") as $id => $attributes) { if (!isset($attributes[0]["osType"])) { throw new \LogicException("Handler {$id} requires an osType attribute"); } $definition = $container->getDefinition($id); // Get reflection class for validate handler try { $class = $definition->getClass(); // Class is parameter if (strpos($class, '%') === 0) { $class = $container->getParameter(trim($class, '%')); } $refClass = new \ReflectionClass($class); } catch (\ReflectionException $ref) { // Class not found or other reflection error throw new \RuntimeException(sprintf( 'Can\'t compile notification handler by service id "%s".', $id ), 0, $ref); } catch (ParameterNotFoundException $paramNotFound) { // Parameter not found in service container throw new \RuntimeException(sprintf( 'Can\'t compile notification handler by service id "%s".', $id ), 0, $paramNotFound); } // Required interface $requiredInterface = 'RMS\\PushNotificationsBundle\\Service\\OS\\OSNotificationServiceInterface'; if (!$refClass->implementsInterface($requiredInterface)) { throw new \UnexpectedValueException(sprintf( 'Notification service "%s" by id "%s" must be implements "%s" interface!' , $refClass->getName(), $id, $requiredInterface )); } // Add handler to service notifications storage $service->addMethodCall("addHandler", array($attributes[0]["osType"], new Reference($id))); } }
php
public function process(ContainerBuilder $container) { $service = $container->getDefinition("rms_push_notifications"); foreach ($container->findTaggedServiceIds("rms_push_notifications.handler") as $id => $attributes) { if (!isset($attributes[0]["osType"])) { throw new \LogicException("Handler {$id} requires an osType attribute"); } $definition = $container->getDefinition($id); // Get reflection class for validate handler try { $class = $definition->getClass(); // Class is parameter if (strpos($class, '%') === 0) { $class = $container->getParameter(trim($class, '%')); } $refClass = new \ReflectionClass($class); } catch (\ReflectionException $ref) { // Class not found or other reflection error throw new \RuntimeException(sprintf( 'Can\'t compile notification handler by service id "%s".', $id ), 0, $ref); } catch (ParameterNotFoundException $paramNotFound) { // Parameter not found in service container throw new \RuntimeException(sprintf( 'Can\'t compile notification handler by service id "%s".', $id ), 0, $paramNotFound); } // Required interface $requiredInterface = 'RMS\\PushNotificationsBundle\\Service\\OS\\OSNotificationServiceInterface'; if (!$refClass->implementsInterface($requiredInterface)) { throw new \UnexpectedValueException(sprintf( 'Notification service "%s" by id "%s" must be implements "%s" interface!' , $refClass->getName(), $id, $requiredInterface )); } // Add handler to service notifications storage $service->addMethodCall("addHandler", array($attributes[0]["osType"], new Reference($id))); } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "service", "=", "$", "container", "->", "getDefinition", "(", "\"rms_push_notifications\"", ")", ";", "foreach", "(", "$", "container", "->", "findTaggedServiceIds", "(", "\"rms_push_notifications.handler\"", ")", "as", "$", "id", "=>", "$", "attributes", ")", "{", "if", "(", "!", "isset", "(", "$", "attributes", "[", "0", "]", "[", "\"osType\"", "]", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "\"Handler {$id} requires an osType attribute\"", ")", ";", "}", "$", "definition", "=", "$", "container", "->", "getDefinition", "(", "$", "id", ")", ";", "// Get reflection class for validate handler", "try", "{", "$", "class", "=", "$", "definition", "->", "getClass", "(", ")", ";", "// Class is parameter", "if", "(", "strpos", "(", "$", "class", ",", "'%'", ")", "===", "0", ")", "{", "$", "class", "=", "$", "container", "->", "getParameter", "(", "trim", "(", "$", "class", ",", "'%'", ")", ")", ";", "}", "$", "refClass", "=", "new", "\\", "ReflectionClass", "(", "$", "class", ")", ";", "}", "catch", "(", "\\", "ReflectionException", "$", "ref", ")", "{", "// Class not found or other reflection error", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Can\\'t compile notification handler by service id \"%s\".'", ",", "$", "id", ")", ",", "0", ",", "$", "ref", ")", ";", "}", "catch", "(", "ParameterNotFoundException", "$", "paramNotFound", ")", "{", "// Parameter not found in service container", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Can\\'t compile notification handler by service id \"%s\".'", ",", "$", "id", ")", ",", "0", ",", "$", "paramNotFound", ")", ";", "}", "// Required interface", "$", "requiredInterface", "=", "'RMS\\\\PushNotificationsBundle\\\\Service\\\\OS\\\\OSNotificationServiceInterface'", ";", "if", "(", "!", "$", "refClass", "->", "implementsInterface", "(", "$", "requiredInterface", ")", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "sprintf", "(", "'Notification service \"%s\" by id \"%s\" must be implements \"%s\" interface!'", ",", "$", "refClass", "->", "getName", "(", ")", ",", "$", "id", ",", "$", "requiredInterface", ")", ")", ";", "}", "// Add handler to service notifications storage", "$", "service", "->", "addMethodCall", "(", "\"addHandler\"", ",", "array", "(", "$", "attributes", "[", "0", "]", "[", "\"osType\"", "]", ",", "new", "Reference", "(", "$", "id", ")", ")", ")", ";", "}", "}" ]
Processes any handlers tagged accordingly @param ContainerBuilder $container @return void
[ "Processes", "any", "handlers", "tagged", "accordingly" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/DependencyInjection/Compiler/AddHandlerPass.php#L20-L67
richsage/RMSPushNotificationsBundle
Message/AppleMessage.php
AppleMessage.setData
public function setData($data) { if (!is_array($data)) { throw new \InvalidArgumentException(sprintf('Messages custom data must be array, "%s" given.', gettype($data))); } if (array_key_exists("aps", $data)) { unset($data["aps"]); } foreach ($data as $key => $value) { $this->addCustomData($key, $value); } return $this; }
php
public function setData($data) { if (!is_array($data)) { throw new \InvalidArgumentException(sprintf('Messages custom data must be array, "%s" given.', gettype($data))); } if (array_key_exists("aps", $data)) { unset($data["aps"]); } foreach ($data as $key => $value) { $this->addCustomData($key, $value); } return $this; }
[ "public", "function", "setData", "(", "$", "data", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Messages custom data must be array, \"%s\" given.'", ",", "gettype", "(", "$", "data", ")", ")", ")", ";", "}", "if", "(", "array_key_exists", "(", "\"aps\"", ",", "$", "data", ")", ")", "{", "unset", "(", "$", "data", "[", "\"aps\"", "]", ")", ";", "}", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "addCustomData", "(", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets any custom data for the APS body @param array $data
[ "Sets", "any", "custom", "data", "for", "the", "APS", "body" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Message/AppleMessage.php#L90-L105
richsage/RMSPushNotificationsBundle
Message/AppleMessage.php
AppleMessage.addCustomData
public function addCustomData($key, $value) { if ($key == 'aps') { throw new \LogicException('Can\'t replace "aps" data. Please call to setMessage, if your want replace message text.'); } if (is_object($value)) { if (interface_exists('JsonSerializable') && !$value instanceof \stdClass && !$value instanceof \JsonSerializable) { throw new \InvalidArgumentException(sprintf( 'Object %s::%s must be implements JsonSerializable interface for next serialize data.', get_class($value), spl_object_hash($value) )); } } $this->customData[$key] = $value; return $this; }
php
public function addCustomData($key, $value) { if ($key == 'aps') { throw new \LogicException('Can\'t replace "aps" data. Please call to setMessage, if your want replace message text.'); } if (is_object($value)) { if (interface_exists('JsonSerializable') && !$value instanceof \stdClass && !$value instanceof \JsonSerializable) { throw new \InvalidArgumentException(sprintf( 'Object %s::%s must be implements JsonSerializable interface for next serialize data.', get_class($value), spl_object_hash($value) )); } } $this->customData[$key] = $value; return $this; }
[ "public", "function", "addCustomData", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "$", "key", "==", "'aps'", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Can\\'t replace \"aps\" data. Please call to setMessage, if your want replace message text.'", ")", ";", "}", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "if", "(", "interface_exists", "(", "'JsonSerializable'", ")", "&&", "!", "$", "value", "instanceof", "\\", "stdClass", "&&", "!", "$", "value", "instanceof", "\\", "JsonSerializable", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Object %s::%s must be implements JsonSerializable interface for next serialize data.'", ",", "get_class", "(", "$", "value", ")", ",", "spl_object_hash", "(", "$", "value", ")", ")", ")", ";", "}", "}", "$", "this", "->", "customData", "[", "$", "key", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Add custom data @param string $key @param mixed $value
[ "Add", "custom", "data" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Message/AppleMessage.php#L113-L131
richsage/RMSPushNotificationsBundle
Message/AppleMessage.php
AppleMessage.getMessageBody
public function getMessageBody() { $payloadBody = $this->apsBody; if (!empty($this->customData)) { $payloadBody = array_merge($payloadBody, $this->customData); } return $payloadBody; }
php
public function getMessageBody() { $payloadBody = $this->apsBody; if (!empty($this->customData)) { $payloadBody = array_merge($payloadBody, $this->customData); } return $payloadBody; }
[ "public", "function", "getMessageBody", "(", ")", "{", "$", "payloadBody", "=", "$", "this", "->", "apsBody", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "customData", ")", ")", "{", "$", "payloadBody", "=", "array_merge", "(", "$", "payloadBody", ",", "$", "this", "->", "customData", ")", ";", "}", "return", "$", "payloadBody", ";", "}" ]
Gets the full message body to send to APN @return array
[ "Gets", "the", "full", "message", "body", "to", "send", "to", "APN" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Message/AppleMessage.php#L148-L156
richsage/RMSPushNotificationsBundle
Message/AppleMessage.php
AppleMessage.isMdmMessage
public function isMdmMessage($isMdmMessage = null) { if ($isMdmMessage === null) { return $this->isMdmMessage; } $this->isMdmMessage = (bool) $isMdmMessage; }
php
public function isMdmMessage($isMdmMessage = null) { if ($isMdmMessage === null) { return $this->isMdmMessage; } $this->isMdmMessage = (bool) $isMdmMessage; }
[ "public", "function", "isMdmMessage", "(", "$", "isMdmMessage", "=", "null", ")", "{", "if", "(", "$", "isMdmMessage", "===", "null", ")", "{", "return", "$", "this", "->", "isMdmMessage", ";", "}", "$", "this", "->", "isMdmMessage", "=", "(", "bool", ")", "$", "isMdmMessage", ";", "}" ]
@param null|bool $isMdmMessage @return bool|null
[ "@param", "null|bool", "$isMdmMessage" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Message/AppleMessage.php#L292-L299
richsage/RMSPushNotificationsBundle
Service/Notifications.php
Notifications.send
public function send(MessageInterface $message) { if (!$this->supports($message->getTargetOS())) { throw new \RuntimeException("OS type {$message->getTargetOS()} not supported"); } return $this->handlers[$message->getTargetOS()]->send($message); }
php
public function send(MessageInterface $message) { if (!$this->supports($message->getTargetOS())) { throw new \RuntimeException("OS type {$message->getTargetOS()} not supported"); } return $this->handlers[$message->getTargetOS()]->send($message); }
[ "public", "function", "send", "(", "MessageInterface", "$", "message", ")", "{", "if", "(", "!", "$", "this", "->", "supports", "(", "$", "message", "->", "getTargetOS", "(", ")", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"OS type {$message->getTargetOS()} not supported\"", ")", ";", "}", "return", "$", "this", "->", "handlers", "[", "$", "message", "->", "getTargetOS", "(", ")", "]", "->", "send", "(", "$", "message", ")", ";", "}" ]
Sends a message to a device, identified by the OS and the supplied device token @param \RMS\PushNotificationsBundle\Message\MessageInterface $message @throws \RuntimeException @return bool
[ "Sends", "a", "message", "to", "a", "device", "identified", "by", "the", "OS", "and", "the", "supplied", "device", "token" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/Notifications.php#L33-L40
richsage/RMSPushNotificationsBundle
Service/Notifications.php
Notifications.addHandler
public function addHandler($osType, $service) { if (!isset($this->handlers[$osType])) { $this->handlers[$osType] = $service; } }
php
public function addHandler($osType, $service) { if (!isset($this->handlers[$osType])) { $this->handlers[$osType] = $service; } }
[ "public", "function", "addHandler", "(", "$", "osType", ",", "$", "service", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "handlers", "[", "$", "osType", "]", ")", ")", "{", "$", "this", "->", "handlers", "[", "$", "osType", "]", "=", "$", "service", ";", "}", "}" ]
Adds a handler @param $osType @param $service
[ "Adds", "a", "handler" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/Notifications.php#L48-L53
richsage/RMSPushNotificationsBundle
Service/Notifications.php
Notifications.getResponses
public function getResponses($osType) { if (!isset($this->handlers[$osType])) { throw new \RuntimeException("OS type {$osType} not supported"); } if (!method_exists($this->handlers[$osType], 'getResponses')) { throw new \RuntimeException("Handler for OS type {$osType} not supported getResponses() method"); } return $this->handlers[$osType]->getResponses(); }
php
public function getResponses($osType) { if (!isset($this->handlers[$osType])) { throw new \RuntimeException("OS type {$osType} not supported"); } if (!method_exists($this->handlers[$osType], 'getResponses')) { throw new \RuntimeException("Handler for OS type {$osType} not supported getResponses() method"); } return $this->handlers[$osType]->getResponses(); }
[ "public", "function", "getResponses", "(", "$", "osType", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "handlers", "[", "$", "osType", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"OS type {$osType} not supported\"", ")", ";", "}", "if", "(", "!", "method_exists", "(", "$", "this", "->", "handlers", "[", "$", "osType", "]", ",", "'getResponses'", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Handler for OS type {$osType} not supported getResponses() method\"", ")", ";", "}", "return", "$", "this", "->", "handlers", "[", "$", "osType", "]", "->", "getResponses", "(", ")", ";", "}" ]
Get responses from handler @param string $osType @return array @throws \RuntimeException
[ "Get", "responses", "from", "handler" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/Notifications.php#L62-L73
richsage/RMSPushNotificationsBundle
Service/Notifications.php
Notifications.setAPNSPemAsString
public function setAPNSPemAsString($pemContent, $passphrase) { if (isset($this->handlers[Types::OS_IOS]) && $this->handlers[Types::OS_IOS] instanceof AppleNotification) { /** @var AppleNotification $appleNotification */ $appleNotification = $this->handlers[Types::OS_IOS]; $appleNotification->setPemAsString($pemContent, $passphrase); } }
php
public function setAPNSPemAsString($pemContent, $passphrase) { if (isset($this->handlers[Types::OS_IOS]) && $this->handlers[Types::OS_IOS] instanceof AppleNotification) { /** @var AppleNotification $appleNotification */ $appleNotification = $this->handlers[Types::OS_IOS]; $appleNotification->setPemAsString($pemContent, $passphrase); } }
[ "public", "function", "setAPNSPemAsString", "(", "$", "pemContent", ",", "$", "passphrase", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "handlers", "[", "Types", "::", "OS_IOS", "]", ")", "&&", "$", "this", "->", "handlers", "[", "Types", "::", "OS_IOS", "]", "instanceof", "AppleNotification", ")", "{", "/** @var AppleNotification $appleNotification */", "$", "appleNotification", "=", "$", "this", "->", "handlers", "[", "Types", "::", "OS_IOS", "]", ";", "$", "appleNotification", "->", "setPemAsString", "(", "$", "pemContent", ",", "$", "passphrase", ")", ";", "}", "}" ]
Set Apple Push Notification Service pem as string. Service won't use pem file passed by config anymore. @param $pemContent string @param $passphrase
[ "Set", "Apple", "Push", "Notification", "Service", "pem", "as", "string", ".", "Service", "won", "t", "use", "pem", "file", "passed", "by", "config", "anymore", "." ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/Notifications.php#L95-L101
richsage/RMSPushNotificationsBundle
Message/AndroidMessage.php
AndroidMessage.getMessageBody
public function getMessageBody() { $data = array( "registration_id" => $this->identifier, "collapse_key" => $this->collapseKey, "data.message" => $this->message, ); if (!empty($this->data)) { $data = array_merge($data, $this->data); } return $data; }
php
public function getMessageBody() { $data = array( "registration_id" => $this->identifier, "collapse_key" => $this->collapseKey, "data.message" => $this->message, ); if (!empty($this->data)) { $data = array_merge($data, $this->data); } return $data; }
[ "public", "function", "getMessageBody", "(", ")", "{", "$", "data", "=", "array", "(", "\"registration_id\"", "=>", "$", "this", "->", "identifier", ",", "\"collapse_key\"", "=>", "$", "this", "->", "collapseKey", ",", "\"data.message\"", "=>", "$", "this", "->", "message", ",", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "data", ")", ")", "{", "$", "data", "=", "array_merge", "(", "$", "data", ",", "$", "this", "->", "data", ")", ";", "}", "return", "$", "data", ";", "}" ]
Gets the message body to send This is primarily used in C2DM @return array
[ "Gets", "the", "message", "body", "to", "send", "This", "is", "primarily", "used", "in", "C2DM" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Message/AndroidMessage.php#L107-L119
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.send
public function send(MessageInterface $message) { if (!$message instanceof AppleMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by APN", get_class($message))); } $apnURL = "ssl://gateway.push.apple.com:2195"; if ($this->useSandbox) { $apnURL = "ssl://gateway.sandbox.push.apple.com:2195"; } $messageId = ++$this->lastMessageId; if ($message->isMdmMessage()) { if ($message->getToken() == '') { throw new InvalidMessageTypeException(sprintf("Message type '%s' is a MDM message but 'token' is missing", get_class($message))); } if ($message->getPushMagicToken() == '') { throw new InvalidMessageTypeException(sprintf("Message type '%s' is a MDM message but 'pushMagicToken' is missing", get_class($message))); } $this->messages[$messageId] = $this->createMdmPayload($message->getToken(), $message->getPushMagicToken()); } else { $this->messages[$messageId] = $this->createPayload($messageId, $message->getExpiry(), $message->getDeviceIdentifier(), $message->getMessageBody()); } $errors = $this->sendMessages($messageId, $apnURL); return !$errors; }
php
public function send(MessageInterface $message) { if (!$message instanceof AppleMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by APN", get_class($message))); } $apnURL = "ssl://gateway.push.apple.com:2195"; if ($this->useSandbox) { $apnURL = "ssl://gateway.sandbox.push.apple.com:2195"; } $messageId = ++$this->lastMessageId; if ($message->isMdmMessage()) { if ($message->getToken() == '') { throw new InvalidMessageTypeException(sprintf("Message type '%s' is a MDM message but 'token' is missing", get_class($message))); } if ($message->getPushMagicToken() == '') { throw new InvalidMessageTypeException(sprintf("Message type '%s' is a MDM message but 'pushMagicToken' is missing", get_class($message))); } $this->messages[$messageId] = $this->createMdmPayload($message->getToken(), $message->getPushMagicToken()); } else { $this->messages[$messageId] = $this->createPayload($messageId, $message->getExpiry(), $message->getDeviceIdentifier(), $message->getMessageBody()); } $errors = $this->sendMessages($messageId, $apnURL); return !$errors; }
[ "public", "function", "send", "(", "MessageInterface", "$", "message", ")", "{", "if", "(", "!", "$", "message", "instanceof", "AppleMessage", ")", "{", "throw", "new", "InvalidMessageTypeException", "(", "sprintf", "(", "\"Message type '%s' not supported by APN\"", ",", "get_class", "(", "$", "message", ")", ")", ")", ";", "}", "$", "apnURL", "=", "\"ssl://gateway.push.apple.com:2195\"", ";", "if", "(", "$", "this", "->", "useSandbox", ")", "{", "$", "apnURL", "=", "\"ssl://gateway.sandbox.push.apple.com:2195\"", ";", "}", "$", "messageId", "=", "++", "$", "this", "->", "lastMessageId", ";", "if", "(", "$", "message", "->", "isMdmMessage", "(", ")", ")", "{", "if", "(", "$", "message", "->", "getToken", "(", ")", "==", "''", ")", "{", "throw", "new", "InvalidMessageTypeException", "(", "sprintf", "(", "\"Message type '%s' is a MDM message but 'token' is missing\"", ",", "get_class", "(", "$", "message", ")", ")", ")", ";", "}", "if", "(", "$", "message", "->", "getPushMagicToken", "(", ")", "==", "''", ")", "{", "throw", "new", "InvalidMessageTypeException", "(", "sprintf", "(", "\"Message type '%s' is a MDM message but 'pushMagicToken' is missing\"", ",", "get_class", "(", "$", "message", ")", ")", ")", ";", "}", "$", "this", "->", "messages", "[", "$", "messageId", "]", "=", "$", "this", "->", "createMdmPayload", "(", "$", "message", "->", "getToken", "(", ")", ",", "$", "message", "->", "getPushMagicToken", "(", ")", ")", ";", "}", "else", "{", "$", "this", "->", "messages", "[", "$", "messageId", "]", "=", "$", "this", "->", "createPayload", "(", "$", "messageId", ",", "$", "message", "->", "getExpiry", "(", ")", ",", "$", "message", "->", "getDeviceIdentifier", "(", ")", ",", "$", "message", "->", "getMessageBody", "(", ")", ")", ";", "}", "$", "errors", "=", "$", "this", "->", "sendMessages", "(", "$", "messageId", ",", "$", "apnURL", ")", ";", "return", "!", "$", "errors", ";", "}" ]
Send a MDM or notification message @param \RMS\PushNotificationsBundle\Message\MessageInterface|\RMS\PushNotificationsBundle\Service\OS\MessageInterface $message @throws \RuntimeException @throws \RMS\PushNotificationsBundle\Exception\InvalidMessageTypeException @return bool
[ "Send", "a", "MDM", "or", "notification", "message" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L167-L197
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.sendMessages
protected function sendMessages($firstMessageId, $apnURL) { $errors = array(); // Loop through all messages starting from the given ID $messagesCount = count($this->messages); for ($currentMessageId = $firstMessageId; $currentMessageId < $messagesCount; $currentMessageId++) { // Send the message $result = $this->writeApnStream($apnURL, $this->messages[$currentMessageId]); // Check if there is an error result if (is_array($result)) { // Close the apn stream in case of Shutdown status code. if ($result['status'] === self::APNS_SHUTDOWN_CODE) { $this->closeApnStream($apnURL); } $this->responses[] = $result; // Resend all messages that were sent after the failed message $this->sendMessages($result['identifier']+1, $apnURL); $errors[] = $result; if ($this->logger) { $this->logger->error(json_encode($result)); } } else { $this->responses[] = true; } } return $errors; }
php
protected function sendMessages($firstMessageId, $apnURL) { $errors = array(); // Loop through all messages starting from the given ID $messagesCount = count($this->messages); for ($currentMessageId = $firstMessageId; $currentMessageId < $messagesCount; $currentMessageId++) { // Send the message $result = $this->writeApnStream($apnURL, $this->messages[$currentMessageId]); // Check if there is an error result if (is_array($result)) { // Close the apn stream in case of Shutdown status code. if ($result['status'] === self::APNS_SHUTDOWN_CODE) { $this->closeApnStream($apnURL); } $this->responses[] = $result; // Resend all messages that were sent after the failed message $this->sendMessages($result['identifier']+1, $apnURL); $errors[] = $result; if ($this->logger) { $this->logger->error(json_encode($result)); } } else { $this->responses[] = true; } } return $errors; }
[ "protected", "function", "sendMessages", "(", "$", "firstMessageId", ",", "$", "apnURL", ")", "{", "$", "errors", "=", "array", "(", ")", ";", "// Loop through all messages starting from the given ID", "$", "messagesCount", "=", "count", "(", "$", "this", "->", "messages", ")", ";", "for", "(", "$", "currentMessageId", "=", "$", "firstMessageId", ";", "$", "currentMessageId", "<", "$", "messagesCount", ";", "$", "currentMessageId", "++", ")", "{", "// Send the message", "$", "result", "=", "$", "this", "->", "writeApnStream", "(", "$", "apnURL", ",", "$", "this", "->", "messages", "[", "$", "currentMessageId", "]", ")", ";", "// Check if there is an error result", "if", "(", "is_array", "(", "$", "result", ")", ")", "{", "// Close the apn stream in case of Shutdown status code.", "if", "(", "$", "result", "[", "'status'", "]", "===", "self", "::", "APNS_SHUTDOWN_CODE", ")", "{", "$", "this", "->", "closeApnStream", "(", "$", "apnURL", ")", ";", "}", "$", "this", "->", "responses", "[", "]", "=", "$", "result", ";", "// Resend all messages that were sent after the failed message", "$", "this", "->", "sendMessages", "(", "$", "result", "[", "'identifier'", "]", "+", "1", ",", "$", "apnURL", ")", ";", "$", "errors", "[", "]", "=", "$", "result", ";", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "json_encode", "(", "$", "result", ")", ")", ";", "}", "}", "else", "{", "$", "this", "->", "responses", "[", "]", "=", "true", ";", "}", "}", "return", "$", "errors", ";", "}" ]
Send all notification messages starting from the given ID @param int $firstMessageId @param string $apnURL @throws \RuntimeException @throws \RMS\PushNotificationsBundle\Exception\InvalidMessageTypeException @return int
[ "Send", "all", "notification", "messages", "starting", "from", "the", "given", "ID" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L208-L238
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.writeApnStream
protected function writeApnStream($apnURL, $payload) { // Get the correct Apn stream and send data $fp = $this->getApnStream($apnURL); $response = (strlen($payload) === @fwrite($fp, $payload, strlen($payload))); // Check if there is responsedata to read $readStreams = array($fp); $null = NULL; $streamsReadyToRead = @stream_select($readStreams, $null, $null, 1, 0); if ($streamsReadyToRead > 0) { // Unpack error response data and set as the result $response = @unpack("Ccommand/Cstatus/Nidentifier", fread($fp, 6)); $this->closeApnStream($apnURL); } // Will contain true if writing succeeded and no error is returned yet return $response; }
php
protected function writeApnStream($apnURL, $payload) { // Get the correct Apn stream and send data $fp = $this->getApnStream($apnURL); $response = (strlen($payload) === @fwrite($fp, $payload, strlen($payload))); // Check if there is responsedata to read $readStreams = array($fp); $null = NULL; $streamsReadyToRead = @stream_select($readStreams, $null, $null, 1, 0); if ($streamsReadyToRead > 0) { // Unpack error response data and set as the result $response = @unpack("Ccommand/Cstatus/Nidentifier", fread($fp, 6)); $this->closeApnStream($apnURL); } // Will contain true if writing succeeded and no error is returned yet return $response; }
[ "protected", "function", "writeApnStream", "(", "$", "apnURL", ",", "$", "payload", ")", "{", "// Get the correct Apn stream and send data", "$", "fp", "=", "$", "this", "->", "getApnStream", "(", "$", "apnURL", ")", ";", "$", "response", "=", "(", "strlen", "(", "$", "payload", ")", "===", "@", "fwrite", "(", "$", "fp", ",", "$", "payload", ",", "strlen", "(", "$", "payload", ")", ")", ")", ";", "// Check if there is responsedata to read", "$", "readStreams", "=", "array", "(", "$", "fp", ")", ";", "$", "null", "=", "NULL", ";", "$", "streamsReadyToRead", "=", "@", "stream_select", "(", "$", "readStreams", ",", "$", "null", ",", "$", "null", ",", "1", ",", "0", ")", ";", "if", "(", "$", "streamsReadyToRead", ">", "0", ")", "{", "// Unpack error response data and set as the result", "$", "response", "=", "@", "unpack", "(", "\"Ccommand/Cstatus/Nidentifier\"", ",", "fread", "(", "$", "fp", ",", "6", ")", ")", ";", "$", "this", "->", "closeApnStream", "(", "$", "apnURL", ")", ";", "}", "// Will contain true if writing succeeded and no error is returned yet", "return", "$", "response", ";", "}" ]
Write data to the apn stream that is associated with the given apn URL @param string $apnURL @param string $payload @throws \RuntimeException @return mixed
[ "Write", "data", "to", "the", "apn", "stream", "that", "is", "associated", "with", "the", "given", "apn", "URL" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L248-L266
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.getApnStream
protected function getApnStream($apnURL) { if (!isset($this->apnStreams[$apnURL])) { // No stream found, setup a new stream $ctx = $this->getStreamContext(); $this->apnStreams[$apnURL] = stream_socket_client($apnURL, $err, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $ctx); if (!$this->apnStreams[$apnURL]) { throw new \RuntimeException("Couldn't connect to APN server. Error no $err: $errstr"); } // Reduce buffering and blocking if (function_exists("stream_set_read_buffer")) { stream_set_read_buffer($this->apnStreams[$apnURL], 6); } stream_set_write_buffer($this->apnStreams[$apnURL], 0); stream_set_blocking($this->apnStreams[$apnURL], 0); } return $this->apnStreams[$apnURL]; }
php
protected function getApnStream($apnURL) { if (!isset($this->apnStreams[$apnURL])) { // No stream found, setup a new stream $ctx = $this->getStreamContext(); $this->apnStreams[$apnURL] = stream_socket_client($apnURL, $err, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $ctx); if (!$this->apnStreams[$apnURL]) { throw new \RuntimeException("Couldn't connect to APN server. Error no $err: $errstr"); } // Reduce buffering and blocking if (function_exists("stream_set_read_buffer")) { stream_set_read_buffer($this->apnStreams[$apnURL], 6); } stream_set_write_buffer($this->apnStreams[$apnURL], 0); stream_set_blocking($this->apnStreams[$apnURL], 0); } return $this->apnStreams[$apnURL]; }
[ "protected", "function", "getApnStream", "(", "$", "apnURL", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ")", ")", "{", "// No stream found, setup a new stream", "$", "ctx", "=", "$", "this", "->", "getStreamContext", "(", ")", ";", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", "=", "stream_socket_client", "(", "$", "apnURL", ",", "$", "err", ",", "$", "errstr", ",", "$", "this", "->", "timeout", ",", "STREAM_CLIENT_CONNECT", ",", "$", "ctx", ")", ";", "if", "(", "!", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Couldn't connect to APN server. Error no $err: $errstr\"", ")", ";", "}", "// Reduce buffering and blocking", "if", "(", "function_exists", "(", "\"stream_set_read_buffer\"", ")", ")", "{", "stream_set_read_buffer", "(", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ",", "6", ")", ";", "}", "stream_set_write_buffer", "(", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ",", "0", ")", ";", "stream_set_blocking", "(", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ",", "0", ")", ";", "}", "return", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ";", "}" ]
Get an apn stream associated with the given apn URL, create one if necessary @param string $apnURL @throws \RuntimeException @return resource
[ "Get", "an", "apn", "stream", "associated", "with", "the", "given", "apn", "URL", "create", "one", "if", "necessary" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L275-L294
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.closeApnStream
protected function closeApnStream($apnURL) { if (isset($this->apnStreams[$apnURL])) { // Stream found, close the stream fclose($this->apnStreams[$apnURL]); unset($this->apnStreams[$apnURL]); } }
php
protected function closeApnStream($apnURL) { if (isset($this->apnStreams[$apnURL])) { // Stream found, close the stream fclose($this->apnStreams[$apnURL]); unset($this->apnStreams[$apnURL]); } }
[ "protected", "function", "closeApnStream", "(", "$", "apnURL", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ")", ")", "{", "// Stream found, close the stream", "fclose", "(", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ")", ";", "unset", "(", "$", "this", "->", "apnStreams", "[", "$", "apnURL", "]", ")", ";", "}", "}" ]
Close the apn stream associated with the given apn URL @param string $apnURL
[ "Close", "the", "apn", "stream", "associated", "with", "the", "given", "apn", "URL" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L301-L308
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.getStreamContext
protected function getStreamContext() { $pem = $this->pemPath; $passphrase = $this->passphrase; // Create cache pem file if needed if (!empty($this->pemContent)) { $filename = $this->cachedir . self::APNS_CERTIFICATE_FILE; $fs = new Filesystem(); $fs->mkdir(dirname($filename)); file_put_contents($filename, $this->pemContent); // Now we use this file as pem $pem = $filename; $passphrase = $this->pemContentPassphrase; } $ctx = stream_context_create(); stream_context_set_option($ctx, "ssl", "local_cert", $pem); if (strlen($passphrase)) { stream_context_set_option($ctx, "ssl", "passphrase", $passphrase); } return $ctx; }
php
protected function getStreamContext() { $pem = $this->pemPath; $passphrase = $this->passphrase; // Create cache pem file if needed if (!empty($this->pemContent)) { $filename = $this->cachedir . self::APNS_CERTIFICATE_FILE; $fs = new Filesystem(); $fs->mkdir(dirname($filename)); file_put_contents($filename, $this->pemContent); // Now we use this file as pem $pem = $filename; $passphrase = $this->pemContentPassphrase; } $ctx = stream_context_create(); stream_context_set_option($ctx, "ssl", "local_cert", $pem); if (strlen($passphrase)) { stream_context_set_option($ctx, "ssl", "passphrase", $passphrase); } return $ctx; }
[ "protected", "function", "getStreamContext", "(", ")", "{", "$", "pem", "=", "$", "this", "->", "pemPath", ";", "$", "passphrase", "=", "$", "this", "->", "passphrase", ";", "// Create cache pem file if needed", "if", "(", "!", "empty", "(", "$", "this", "->", "pemContent", ")", ")", "{", "$", "filename", "=", "$", "this", "->", "cachedir", ".", "self", "::", "APNS_CERTIFICATE_FILE", ";", "$", "fs", "=", "new", "Filesystem", "(", ")", ";", "$", "fs", "->", "mkdir", "(", "dirname", "(", "$", "filename", ")", ")", ";", "file_put_contents", "(", "$", "filename", ",", "$", "this", "->", "pemContent", ")", ";", "// Now we use this file as pem", "$", "pem", "=", "$", "filename", ";", "$", "passphrase", "=", "$", "this", "->", "pemContentPassphrase", ";", "}", "$", "ctx", "=", "stream_context_create", "(", ")", ";", "stream_context_set_option", "(", "$", "ctx", ",", "\"ssl\"", ",", "\"local_cert\"", ",", "$", "pem", ")", ";", "if", "(", "strlen", "(", "$", "passphrase", ")", ")", "{", "stream_context_set_option", "(", "$", "ctx", ",", "\"ssl\"", ",", "\"passphrase\"", ",", "$", "passphrase", ")", ";", "}", "return", "$", "ctx", ";", "}" ]
Gets a stream context set up for SSL using our PEM file and passphrase @return resource
[ "Gets", "a", "stream", "context", "set", "up", "for", "SSL", "using", "our", "PEM", "file", "and", "passphrase" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L316-L341
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.createPayload
protected function createPayload($messageId, $expiry, $token, $message) { if ($this->jsonUnescapedUnicode) { // Validate PHP version if (!version_compare(PHP_VERSION, '5.4.0', '>=')) { throw new \LogicException(sprintf( 'Can\'t use JSON_UNESCAPED_UNICODE option on PHP %s. Support PHP >= 5.4.0', PHP_VERSION )); } // WARNING: // Set otpion JSON_UNESCAPED_UNICODE is violation // of RFC 4627 // Because required validate charsets (Must be UTF-8) $encoding = mb_detect_encoding($message['aps']['alert']); if ($encoding != 'UTF-8' && $encoding != 'ASCII') { throw new \InvalidArgumentException(sprintf( 'Message must be UTF-8 encoding, "%s" given.', mb_detect_encoding($message['aps']['alert']) )); } $jsonBody = json_encode($message, JSON_UNESCAPED_UNICODE); } else { $jsonBody = json_encode($message); } $token = preg_replace("/[^0-9A-Fa-f]/", "", $token); $payload = chr(1) . pack("N", $messageId) . pack("N", $expiry) . pack("n", 32) . pack("H*", $token) . pack("n", strlen($jsonBody)) . $jsonBody; return $payload; }
php
protected function createPayload($messageId, $expiry, $token, $message) { if ($this->jsonUnescapedUnicode) { // Validate PHP version if (!version_compare(PHP_VERSION, '5.4.0', '>=')) { throw new \LogicException(sprintf( 'Can\'t use JSON_UNESCAPED_UNICODE option on PHP %s. Support PHP >= 5.4.0', PHP_VERSION )); } // WARNING: // Set otpion JSON_UNESCAPED_UNICODE is violation // of RFC 4627 // Because required validate charsets (Must be UTF-8) $encoding = mb_detect_encoding($message['aps']['alert']); if ($encoding != 'UTF-8' && $encoding != 'ASCII') { throw new \InvalidArgumentException(sprintf( 'Message must be UTF-8 encoding, "%s" given.', mb_detect_encoding($message['aps']['alert']) )); } $jsonBody = json_encode($message, JSON_UNESCAPED_UNICODE); } else { $jsonBody = json_encode($message); } $token = preg_replace("/[^0-9A-Fa-f]/", "", $token); $payload = chr(1) . pack("N", $messageId) . pack("N", $expiry) . pack("n", 32) . pack("H*", $token) . pack("n", strlen($jsonBody)) . $jsonBody; return $payload; }
[ "protected", "function", "createPayload", "(", "$", "messageId", ",", "$", "expiry", ",", "$", "token", ",", "$", "message", ")", "{", "if", "(", "$", "this", "->", "jsonUnescapedUnicode", ")", "{", "// Validate PHP version", "if", "(", "!", "version_compare", "(", "PHP_VERSION", ",", "'5.4.0'", ",", "'>='", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "sprintf", "(", "'Can\\'t use JSON_UNESCAPED_UNICODE option on PHP %s. Support PHP >= 5.4.0'", ",", "PHP_VERSION", ")", ")", ";", "}", "// WARNING:", "// Set otpion JSON_UNESCAPED_UNICODE is violation", "// of RFC 4627", "// Because required validate charsets (Must be UTF-8)", "$", "encoding", "=", "mb_detect_encoding", "(", "$", "message", "[", "'aps'", "]", "[", "'alert'", "]", ")", ";", "if", "(", "$", "encoding", "!=", "'UTF-8'", "&&", "$", "encoding", "!=", "'ASCII'", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Message must be UTF-8 encoding, \"%s\" given.'", ",", "mb_detect_encoding", "(", "$", "message", "[", "'aps'", "]", "[", "'alert'", "]", ")", ")", ")", ";", "}", "$", "jsonBody", "=", "json_encode", "(", "$", "message", ",", "JSON_UNESCAPED_UNICODE", ")", ";", "}", "else", "{", "$", "jsonBody", "=", "json_encode", "(", "$", "message", ")", ";", "}", "$", "token", "=", "preg_replace", "(", "\"/[^0-9A-Fa-f]/\"", ",", "\"\"", ",", "$", "token", ")", ";", "$", "payload", "=", "chr", "(", "1", ")", ".", "pack", "(", "\"N\"", ",", "$", "messageId", ")", ".", "pack", "(", "\"N\"", ",", "$", "expiry", ")", ".", "pack", "(", "\"n\"", ",", "32", ")", ".", "pack", "(", "\"H*\"", ",", "$", "token", ")", ".", "pack", "(", "\"n\"", ",", "strlen", "(", "$", "jsonBody", ")", ")", ".", "$", "jsonBody", ";", "return", "$", "payload", ";", "}" ]
Creates the full payload for the notification @param int $messageId @param string $expiry @param string $token @param array $message @return string @throws \LogicException @throws \InvalidArgumentException
[ "Creates", "the", "full", "payload", "for", "the", "notification" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L356-L389
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.createMdmPayload
public function createMdmPayload($token, $magicPushToken) { $jsonPayload = json_encode(array('mdm' => $magicPushToken)); $payload = chr(0) . chr(0) . chr(32) . base64_decode($token) . chr(0) . chr(strlen($jsonPayload)) . $jsonPayload; return $payload; }
php
public function createMdmPayload($token, $magicPushToken) { $jsonPayload = json_encode(array('mdm' => $magicPushToken)); $payload = chr(0) . chr(0) . chr(32) . base64_decode($token) . chr(0) . chr(strlen($jsonPayload)) . $jsonPayload; return $payload; }
[ "public", "function", "createMdmPayload", "(", "$", "token", ",", "$", "magicPushToken", ")", "{", "$", "jsonPayload", "=", "json_encode", "(", "array", "(", "'mdm'", "=>", "$", "magicPushToken", ")", ")", ";", "$", "payload", "=", "chr", "(", "0", ")", ".", "chr", "(", "0", ")", ".", "chr", "(", "32", ")", ".", "base64_decode", "(", "$", "token", ")", ".", "chr", "(", "0", ")", ".", "chr", "(", "strlen", "(", "$", "jsonPayload", ")", ")", ".", "$", "jsonPayload", ";", "return", "$", "payload", ";", "}" ]
Creates a MDM payload @param string $token @param string $magicPushToken @return string
[ "Creates", "a", "MDM", "payload" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L399-L406
richsage/RMSPushNotificationsBundle
Service/OS/AppleNotification.php
AppleNotification.removeCachedPemFile
private function removeCachedPemFile() { $fs = new Filesystem(); $filename = $this->cachedir . self::APNS_CERTIFICATE_FILE; if ($fs->exists(dirname($filename))) { $fs->remove(dirname($filename)); } }
php
private function removeCachedPemFile() { $fs = new Filesystem(); $filename = $this->cachedir . self::APNS_CERTIFICATE_FILE; if ($fs->exists(dirname($filename))) { $fs->remove(dirname($filename)); } }
[ "private", "function", "removeCachedPemFile", "(", ")", "{", "$", "fs", "=", "new", "Filesystem", "(", ")", ";", "$", "filename", "=", "$", "this", "->", "cachedir", ".", "self", "::", "APNS_CERTIFICATE_FILE", ";", "if", "(", "$", "fs", "->", "exists", "(", "dirname", "(", "$", "filename", ")", ")", ")", "{", "$", "fs", "->", "remove", "(", "dirname", "(", "$", "filename", ")", ")", ";", "}", "}" ]
Remove cache pem file
[ "Remove", "cache", "pem", "file" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/OS/AppleNotification.php#L446-L453
richsage/RMSPushNotificationsBundle
Service/iOSFeedback.php
iOSFeedback.getDeviceUUIDs
public function getDeviceUUIDs() { if (!strlen($this->pem)) { throw new \RuntimeException("PEM not provided"); } $feedbackURL = "ssl://feedback.push.apple.com:2196"; if ($this->sandbox) { $feedbackURL = "ssl://feedback.sandbox.push.apple.com:2196"; } $data = ""; $ctx = $this->getStreamContext(); $fp = stream_socket_client($feedbackURL, $err, $errstr, $this->timeout, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { throw new \RuntimeException("Couldn't connect to APNS Feedback service. Error no $err: $errstr"); } while (!feof($fp)) { $data .= fread($fp, 4096); } fclose($fp); if (!strlen($data)) { return array(); } $feedbacks = array(); $items = str_split($data, 38); foreach ($items as $item) { $feedback = new Feedback(); $feedbacks[] = $feedback->unpack($item); } return $feedbacks; }
php
public function getDeviceUUIDs() { if (!strlen($this->pem)) { throw new \RuntimeException("PEM not provided"); } $feedbackURL = "ssl://feedback.push.apple.com:2196"; if ($this->sandbox) { $feedbackURL = "ssl://feedback.sandbox.push.apple.com:2196"; } $data = ""; $ctx = $this->getStreamContext(); $fp = stream_socket_client($feedbackURL, $err, $errstr, $this->timeout, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { throw new \RuntimeException("Couldn't connect to APNS Feedback service. Error no $err: $errstr"); } while (!feof($fp)) { $data .= fread($fp, 4096); } fclose($fp); if (!strlen($data)) { return array(); } $feedbacks = array(); $items = str_split($data, 38); foreach ($items as $item) { $feedback = new Feedback(); $feedbacks[] = $feedback->unpack($item); } return $feedbacks; }
[ "public", "function", "getDeviceUUIDs", "(", ")", "{", "if", "(", "!", "strlen", "(", "$", "this", "->", "pem", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"PEM not provided\"", ")", ";", "}", "$", "feedbackURL", "=", "\"ssl://feedback.push.apple.com:2196\"", ";", "if", "(", "$", "this", "->", "sandbox", ")", "{", "$", "feedbackURL", "=", "\"ssl://feedback.sandbox.push.apple.com:2196\"", ";", "}", "$", "data", "=", "\"\"", ";", "$", "ctx", "=", "$", "this", "->", "getStreamContext", "(", ")", ";", "$", "fp", "=", "stream_socket_client", "(", "$", "feedbackURL", ",", "$", "err", ",", "$", "errstr", ",", "$", "this", "->", "timeout", ",", "STREAM_CLIENT_CONNECT", "|", "STREAM_CLIENT_PERSISTENT", ",", "$", "ctx", ")", ";", "if", "(", "!", "$", "fp", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Couldn't connect to APNS Feedback service. Error no $err: $errstr\"", ")", ";", "}", "while", "(", "!", "feof", "(", "$", "fp", ")", ")", "{", "$", "data", ".=", "fread", "(", "$", "fp", ",", "4096", ")", ";", "}", "fclose", "(", "$", "fp", ")", ";", "if", "(", "!", "strlen", "(", "$", "data", ")", ")", "{", "return", "array", "(", ")", ";", "}", "$", "feedbacks", "=", "array", "(", ")", ";", "$", "items", "=", "str_split", "(", "$", "data", ",", "38", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "feedback", "=", "new", "Feedback", "(", ")", ";", "$", "feedbacks", "[", "]", "=", "$", "feedback", "->", "unpack", "(", "$", "item", ")", ";", "}", "return", "$", "feedbacks", ";", "}" ]
Gets an array of device UUID unregistration details from the APN feedback service @throws \RuntimeException @return array
[ "Gets", "an", "array", "of", "device", "UUID", "unregistration", "details", "from", "the", "APN", "feedback", "service" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/iOSFeedback.php#L60-L93
richsage/RMSPushNotificationsBundle
Service/iOSFeedback.php
iOSFeedback.getStreamContext
protected function getStreamContext() { $ctx = stream_context_create(); stream_context_set_option($ctx, "ssl", "local_cert", $this->pem); if (strlen($this->passphrase)) { stream_context_set_option($ctx, "ssl", "passphrase", $this->passphrase); } return $ctx; }
php
protected function getStreamContext() { $ctx = stream_context_create(); stream_context_set_option($ctx, "ssl", "local_cert", $this->pem); if (strlen($this->passphrase)) { stream_context_set_option($ctx, "ssl", "passphrase", $this->passphrase); } return $ctx; }
[ "protected", "function", "getStreamContext", "(", ")", "{", "$", "ctx", "=", "stream_context_create", "(", ")", ";", "stream_context_set_option", "(", "$", "ctx", ",", "\"ssl\"", ",", "\"local_cert\"", ",", "$", "this", "->", "pem", ")", ";", "if", "(", "strlen", "(", "$", "this", "->", "passphrase", ")", ")", "{", "stream_context_set_option", "(", "$", "ctx", ",", "\"ssl\"", ",", "\"passphrase\"", ",", "$", "this", "->", "passphrase", ")", ";", "}", "return", "$", "ctx", ";", "}" ]
Gets a stream context set up for SSL using our PEM file and passphrase @return resource
[ "Gets", "a", "stream", "context", "set", "up", "for", "SSL", "using", "our", "PEM", "file", "and", "passphrase" ]
train
https://github.com/richsage/RMSPushNotificationsBundle/blob/3432bca679f93f9658a9f7666ca56d4a389c7855/Service/iOSFeedback.php#L101-L111
madwizard-thomas/webauthn-server
src/Config/WebAuthnConfiguration.php
WebAuthnConfiguration.setAllowedAlgorithms
public function setAllowedAlgorithms(array $algorithms) : void { $validList = []; foreach ($algorithms as $algorithm) { if (!\is_int($algorithm)) { throw new ConfigurationException('Algorithms should be integer constants from the COSEAlgorithm enumeratons.'); } if (!\in_array($algorithm, self::SUPPORTED_ALGORITHMS, true)) { throw new ConfigurationException(sprintf('Unsupported algorithm "%d".', $algorithm)); } $validList[] = $algorithm; } $this->algorithms = $validList; }
php
public function setAllowedAlgorithms(array $algorithms) : void { $validList = []; foreach ($algorithms as $algorithm) { if (!\is_int($algorithm)) { throw new ConfigurationException('Algorithms should be integer constants from the COSEAlgorithm enumeratons.'); } if (!\in_array($algorithm, self::SUPPORTED_ALGORITHMS, true)) { throw new ConfigurationException(sprintf('Unsupported algorithm "%d".', $algorithm)); } $validList[] = $algorithm; } $this->algorithms = $validList; }
[ "public", "function", "setAllowedAlgorithms", "(", "array", "$", "algorithms", ")", ":", "void", "{", "$", "validList", "=", "[", "]", ";", "foreach", "(", "$", "algorithms", "as", "$", "algorithm", ")", "{", "if", "(", "!", "\\", "is_int", "(", "$", "algorithm", ")", ")", "{", "throw", "new", "ConfigurationException", "(", "'Algorithms should be integer constants from the COSEAlgorithm enumeratons.'", ")", ";", "}", "if", "(", "!", "\\", "in_array", "(", "$", "algorithm", ",", "self", "::", "SUPPORTED_ALGORITHMS", ",", "true", ")", ")", "{", "throw", "new", "ConfigurationException", "(", "sprintf", "(", "'Unsupported algorithm \"%d\".'", ",", "$", "algorithm", ")", ")", ";", "}", "$", "validList", "[", "]", "=", "$", "algorithm", ";", "}", "$", "this", "->", "algorithms", "=", "$", "validList", ";", "}" ]
Sets which algorithms are allowed for the credentials that are created. Array of constants from the COSEAlgorithm enumeration (e.g. COSEAlgorithm::ES256) @param int[] $algorithms @throws ConfigurationException @see CoseAlgorithm
[ "Sets", "which", "algorithms", "are", "allowed", "for", "the", "credentials", "that", "are", "created", ".", "Array", "of", "constants", "from", "the", "COSEAlgorithm", "enumeration", "(", "e", ".", "g", ".", "COSEAlgorithm", "::", "ES256", ")" ]
train
https://github.com/madwizard-thomas/webauthn-server/blob/6a9041e1216d266bca4150422dc80adcdb3c6d73/src/Config/WebAuthnConfiguration.php#L163-L177
madwizard-thomas/webauthn-server
src/Server/AbstractVerifier.php
AbstractVerifier.verifyOrigin
protected function verifyOrigin(string $origin, Origin $rpOrigin) : bool { try { $clientOrigin = Origin::parse($origin); } catch (ParseException $e) { throw new VerificationException('Client has specified an invalid origin.', 0, $e); } return $clientOrigin->equals($rpOrigin); }
php
protected function verifyOrigin(string $origin, Origin $rpOrigin) : bool { try { $clientOrigin = Origin::parse($origin); } catch (ParseException $e) { throw new VerificationException('Client has specified an invalid origin.', 0, $e); } return $clientOrigin->equals($rpOrigin); }
[ "protected", "function", "verifyOrigin", "(", "string", "$", "origin", ",", "Origin", "$", "rpOrigin", ")", ":", "bool", "{", "try", "{", "$", "clientOrigin", "=", "Origin", "::", "parse", "(", "$", "origin", ")", ";", "}", "catch", "(", "ParseException", "$", "e", ")", "{", "throw", "new", "VerificationException", "(", "'Client has specified an invalid origin.'", ",", "0", ",", "$", "e", ")", ";", "}", "return", "$", "clientOrigin", "->", "equals", "(", "$", "rpOrigin", ")", ";", "}" ]
TODO: move?
[ "TODO", ":", "move?" ]
train
https://github.com/madwizard-thomas/webauthn-server/blob/6a9041e1216d266bca4150422dc80adcdb3c6d73/src/Server/AbstractVerifier.php#L18-L27
madwizard-thomas/webauthn-server
src/Format/ByteBuffer.php
ByteBuffer.getFloatVal
public function getFloatVal(int $offset) : float { if ($offset < 0 || ($offset + 4) > $this->length) { throw new ByteBufferException('Invalid offset'); } return unpack('G', $this->data, $offset)[1]; }
php
public function getFloatVal(int $offset) : float { if ($offset < 0 || ($offset + 4) > $this->length) { throw new ByteBufferException('Invalid offset'); } return unpack('G', $this->data, $offset)[1]; }
[ "public", "function", "getFloatVal", "(", "int", "$", "offset", ")", ":", "float", "{", "if", "(", "$", "offset", "<", "0", "||", "(", "$", "offset", "+", "4", ")", ">", "$", "this", "->", "length", ")", "{", "throw", "new", "ByteBufferException", "(", "'Invalid offset'", ")", ";", "}", "return", "unpack", "(", "'G'", ",", "$", "this", "->", "data", ",", "$", "offset", ")", "[", "1", "]", ";", "}" ]
TODO: float fixed size?
[ "TODO", ":", "float", "fixed", "size?" ]
train
https://github.com/madwizard-thomas/webauthn-server/blob/6a9041e1216d266bca4150422dc80adcdb3c6d73/src/Format/ByteBuffer.php#L136-L142
madwizard-thomas/webauthn-server
src/Json/JsonConverter.php
JsonConverter.decodeCredential
public static function decodeCredential(string $json, string $responseType) : PublicKeyCredential { $decoded = json_decode($json, true, 10); if ($decoded === false) { throw new ParseException('Failed to decode PublicKeyCredential Json'); } if (($decoded['type'] ?? null) !== PublicKeyCredentialType::PUBLIC_KEY) { throw new ParseException("Expecting type 'public-key'"); } if (empty($decoded['id'])) { throw new ParseException('Missing id in json data'); } $id = $decoded['id']; if (!is_string($id)) { throw new ParseException('Id in json data should be string'); } $rawId = Base64UrlEncoding::decode($id); $responseData = $decoded['response'] ?? null; if (!is_array($responseData)) { throw new ParseException('Expecting array data for response'); } $response = self::decodeResponse($responseData, $responseType); // TODO: clientExtensionResults return new PublicKeyCredential(new ByteBuffer($rawId), $response); }
php
public static function decodeCredential(string $json, string $responseType) : PublicKeyCredential { $decoded = json_decode($json, true, 10); if ($decoded === false) { throw new ParseException('Failed to decode PublicKeyCredential Json'); } if (($decoded['type'] ?? null) !== PublicKeyCredentialType::PUBLIC_KEY) { throw new ParseException("Expecting type 'public-key'"); } if (empty($decoded['id'])) { throw new ParseException('Missing id in json data'); } $id = $decoded['id']; if (!is_string($id)) { throw new ParseException('Id in json data should be string'); } $rawId = Base64UrlEncoding::decode($id); $responseData = $decoded['response'] ?? null; if (!is_array($responseData)) { throw new ParseException('Expecting array data for response'); } $response = self::decodeResponse($responseData, $responseType); // TODO: clientExtensionResults return new PublicKeyCredential(new ByteBuffer($rawId), $response); }
[ "public", "static", "function", "decodeCredential", "(", "string", "$", "json", ",", "string", "$", "responseType", ")", ":", "PublicKeyCredential", "{", "$", "decoded", "=", "json_decode", "(", "$", "json", ",", "true", ",", "10", ")", ";", "if", "(", "$", "decoded", "===", "false", ")", "{", "throw", "new", "ParseException", "(", "'Failed to decode PublicKeyCredential Json'", ")", ";", "}", "if", "(", "(", "$", "decoded", "[", "'type'", "]", "??", "null", ")", "!==", "PublicKeyCredentialType", "::", "PUBLIC_KEY", ")", "{", "throw", "new", "ParseException", "(", "\"Expecting type 'public-key'\"", ")", ";", "}", "if", "(", "empty", "(", "$", "decoded", "[", "'id'", "]", ")", ")", "{", "throw", "new", "ParseException", "(", "'Missing id in json data'", ")", ";", "}", "$", "id", "=", "$", "decoded", "[", "'id'", "]", ";", "if", "(", "!", "is_string", "(", "$", "id", ")", ")", "{", "throw", "new", "ParseException", "(", "'Id in json data should be string'", ")", ";", "}", "$", "rawId", "=", "Base64UrlEncoding", "::", "decode", "(", "$", "id", ")", ";", "$", "responseData", "=", "$", "decoded", "[", "'response'", "]", "??", "null", ";", "if", "(", "!", "is_array", "(", "$", "responseData", ")", ")", "{", "throw", "new", "ParseException", "(", "'Expecting array data for response'", ")", ";", "}", "$", "response", "=", "self", "::", "decodeResponse", "(", "$", "responseData", ",", "$", "responseType", ")", ";", "// TODO: clientExtensionResults", "return", "new", "PublicKeyCredential", "(", "new", "ByteBuffer", "(", "$", "rawId", ")", ",", "$", "response", ")", ";", "}" ]
Parses a JSON string containing a credential returned from the JS credential API's credentials.get or credentials.create. The JSOn structure matches the PublicKeyCredential interface from the WebAuthn specifications closely but since it contains ArrayBuffers it cannot be directly converted to a JSON equivalent. Fields that are ArrayBuffers are assumed to be base64url encoded. Also, the response field of the PublicKeyCredential can contain either an attestation or assertion response. To determine which one to parse the $responseType parameter must be set to 'attestation' or 'assertion'. The required JSON structure is: ``` { "type": "public-key", "id": "base64url encoded ArrayBuffer", "response" : << authenticator response >>, "getClientExtensionResults" : << output of credential.getClientExtensionResults() >> } ``` Where the authenticator response for attestation is: ``` { attestationObject: "base64url encoded ArrayBuffer" } ``` and for assertion response is: ``` { authenticatorData : "base64url encoded ArrayBuffer", signature: "base64url encoded ArrayBuffer", userHandle: "base64url encoded ArrayBuffer" } ``` @param string $json @param string $responseType Expected type of response in the public key's response field. Either 'attestation' for attestation responses or 'assertion' for assertion responses. @return PublicKeyCredential @throws ParseException @see https://www.w3.org/TR/webauthn/#publickeycredential
[ "Parses", "a", "JSON", "string", "containing", "a", "credential", "returned", "from", "the", "JS", "credential", "API", "s", "credentials", ".", "get", "or", "credentials", ".", "create", ".", "The", "JSOn", "structure", "matches", "the", "PublicKeyCredential", "interface", "from", "the", "WebAuthn", "specifications", "closely", "but", "since", "it", "contains", "ArrayBuffers", "it", "cannot", "be", "directly", "converted", "to", "a", "JSON", "equivalent", ".", "Fields", "that", "are", "ArrayBuffers", "are", "assumed", "to", "be", "base64url", "encoded", "." ]
train
https://github.com/madwizard-thomas/webauthn-server/blob/6a9041e1216d266bca4150422dc80adcdb3c6d73/src/Json/JsonConverter.php#L79-L111
madwizard-thomas/webauthn-server
src/Crypto/RsaKey.php
RsaKey.compactIntegerBuffer
private function compactIntegerBuffer(ByteBuffer $buffer) { $length = $buffer->getLength(); $raw = $buffer->getBinaryString(); for ($i = 0; $i < ($length - 1); $i++) { if (ord($raw[$i]) !== 0) { break; } } if ($i !== 0) { return new ByteBuffer(\substr($raw, $i)); } return $buffer; }
php
private function compactIntegerBuffer(ByteBuffer $buffer) { $length = $buffer->getLength(); $raw = $buffer->getBinaryString(); for ($i = 0; $i < ($length - 1); $i++) { if (ord($raw[$i]) !== 0) { break; } } if ($i !== 0) { return new ByteBuffer(\substr($raw, $i)); } return $buffer; }
[ "private", "function", "compactIntegerBuffer", "(", "ByteBuffer", "$", "buffer", ")", "{", "$", "length", "=", "$", "buffer", "->", "getLength", "(", ")", ";", "$", "raw", "=", "$", "buffer", "->", "getBinaryString", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "(", "$", "length", "-", "1", ")", ";", "$", "i", "++", ")", "{", "if", "(", "ord", "(", "$", "raw", "[", "$", "i", "]", ")", "!==", "0", ")", "{", "break", ";", "}", "}", "if", "(", "$", "i", "!==", "0", ")", "{", "return", "new", "ByteBuffer", "(", "\\", "substr", "(", "$", "raw", ",", "$", "i", ")", ")", ";", "}", "return", "$", "buffer", ";", "}" ]
Removes all leading zero bytes from a ByteBuffer, but keeps one zero byte if it is the only byte left and the original buffer did not have zero length. @param ByteBuffer $buffer @return ByteBuffer
[ "Removes", "all", "leading", "zero", "bytes", "from", "a", "ByteBuffer", "but", "keeps", "one", "zero", "byte", "if", "it", "is", "the", "only", "byte", "left", "and", "the", "original", "buffer", "did", "not", "have", "zero", "length", "." ]
train
https://github.com/madwizard-thomas/webauthn-server/blob/6a9041e1216d266bca4150422dc80adcdb3c6d73/src/Crypto/RsaKey.php#L84-L97
madwizard-thomas/webauthn-server
src/Web/Origin.php
Origin.parse
public static function parse(string $origin) : Origin { [$scheme, $host, $port] = self::parseElements($origin); if (!self::isValidHost($host)) { throw new ParseException(sprintf("Invalid host name '%s'.", $host)); } if ($port === null) { $port = self::defaultPort($scheme); } if ($port === 0 || $port >= 2 ** 16) { throw new ParseException(sprintf('Invalid port number %d.', $port)); } return new Origin($scheme, $host, $port); }
php
public static function parse(string $origin) : Origin { [$scheme, $host, $port] = self::parseElements($origin); if (!self::isValidHost($host)) { throw new ParseException(sprintf("Invalid host name '%s'.", $host)); } if ($port === null) { $port = self::defaultPort($scheme); } if ($port === 0 || $port >= 2 ** 16) { throw new ParseException(sprintf('Invalid port number %d.', $port)); } return new Origin($scheme, $host, $port); }
[ "public", "static", "function", "parse", "(", "string", "$", "origin", ")", ":", "Origin", "{", "[", "$", "scheme", ",", "$", "host", ",", "$", "port", "]", "=", "self", "::", "parseElements", "(", "$", "origin", ")", ";", "if", "(", "!", "self", "::", "isValidHost", "(", "$", "host", ")", ")", "{", "throw", "new", "ParseException", "(", "sprintf", "(", "\"Invalid host name '%s'.\"", ",", "$", "host", ")", ")", ";", "}", "if", "(", "$", "port", "===", "null", ")", "{", "$", "port", "=", "self", "::", "defaultPort", "(", "$", "scheme", ")", ";", "}", "if", "(", "$", "port", "===", "0", "||", "$", "port", ">=", "2", "**", "16", ")", "{", "throw", "new", "ParseException", "(", "sprintf", "(", "'Invalid port number %d.'", ",", "$", "port", ")", ")", ";", "}", "return", "new", "Origin", "(", "$", "scheme", ",", "$", "host", ",", "$", "port", ")", ";", "}" ]
TODO: stricter parsing/canonalization according to spec
[ "TODO", ":", "stricter", "parsing", "/", "canonalization", "according", "to", "spec" ]
train
https://github.com/madwizard-thomas/webauthn-server/blob/6a9041e1216d266bca4150422dc80adcdb3c6d73/src/Web/Origin.php#L36-L51