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
basvandorst/StravaPHP
src/Strava/API/Client.php
Client.getRoute
public function getRoute($id) { try { return $this->service->getRoute($id); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
php
public function getRoute($id) { try { return $this->service->getRoute($id); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
[ "public", "function", "getRoute", "(", "$", "id", ")", "{", "try", "{", "return", "$", "this", "->", "service", "->", "getRoute", "(", "$", "id", ")", ";", "}", "catch", "(", "ServiceException", "$", "e", ")", "{", "throw", "new", "ClientException", ...
Get route details @link https://strava.github.io/api/v3/routes/#list @param int $id @return array @throws Exception
[ "Get", "route", "details" ]
train
https://github.com/basvandorst/StravaPHP/blob/5b2b2a9246434273e5a7b8e9d0333765e0fcafbf/src/Strava/API/Client.php#L645-L652
basvandorst/StravaPHP
src/Strava/API/Client.php
Client.getSegment
public function getSegment($id) { try { return $this->service->getSegment($id); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
php
public function getSegment($id) { try { return $this->service->getSegment($id); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
[ "public", "function", "getSegment", "(", "$", "id", ")", "{", "try", "{", "return", "$", "this", "->", "service", "->", "getSegment", "(", "$", "id", ")", ";", "}", "catch", "(", "ServiceException", "$", "e", ")", "{", "throw", "new", "ClientException"...
Retrieve a segment @link https://strava.github.io/api/v3/segments/#retrieve @param int $id @return array @throws Exception
[ "Retrieve", "a", "segment" ]
train
https://github.com/basvandorst/StravaPHP/blob/5b2b2a9246434273e5a7b8e9d0333765e0fcafbf/src/Strava/API/Client.php#L662-L669
basvandorst/StravaPHP
src/Strava/API/Client.php
Client.getSegmentLeaderboard
public function getSegmentLeaderboard($id, $gender = null, $age_group = null, $weight_class = null, $following = null, $club_id = null, $date_range = null, $context_entries = null, $page = null, $per_page = null) { try { return $this->service->getSegmentLeaderboard($id, $gender, $age_group, $weight_class, $following, $club_id, $date_range, $context_entries, $page, $per_page); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
php
public function getSegmentLeaderboard($id, $gender = null, $age_group = null, $weight_class = null, $following = null, $club_id = null, $date_range = null, $context_entries = null, $page = null, $per_page = null) { try { return $this->service->getSegmentLeaderboard($id, $gender, $age_group, $weight_class, $following, $club_id, $date_range, $context_entries, $page, $per_page); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
[ "public", "function", "getSegmentLeaderboard", "(", "$", "id", ",", "$", "gender", "=", "null", ",", "$", "age_group", "=", "null", ",", "$", "weight_class", "=", "null", ",", "$", "following", "=", "null", ",", "$", "club_id", "=", "null", ",", "$", ...
Segment leaderboards @link https://strava.github.io/api/v3/segments/#leaderboard @param int $id @param string $gender @param string $age_group @param string $weight_class @param boolean $following @param int $club_id @param string $date_range @param int $context_entries @param int $page @param int $per_page @return array @throws Exception
[ "Segment", "leaderboards" ]
train
https://github.com/basvandorst/StravaPHP/blob/5b2b2a9246434273e5a7b8e9d0333765e0fcafbf/src/Strava/API/Client.php#L688-L695
basvandorst/StravaPHP
src/Strava/API/Client.php
Client.getSegmentExplorer
public function getSegmentExplorer($bounds, $activity_type = 'riding', $min_cat = null, $max_cat = null) { try { return $this->service->getSegmentExplorer($bounds, $activity_type, $min_cat, $max_cat); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
php
public function getSegmentExplorer($bounds, $activity_type = 'riding', $min_cat = null, $max_cat = null) { try { return $this->service->getSegmentExplorer($bounds, $activity_type, $min_cat, $max_cat); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
[ "public", "function", "getSegmentExplorer", "(", "$", "bounds", ",", "$", "activity_type", "=", "'riding'", ",", "$", "min_cat", "=", "null", ",", "$", "max_cat", "=", "null", ")", "{", "try", "{", "return", "$", "this", "->", "service", "->", "getSegmen...
Segment explorer @link https://strava.github.io/api/v3/segments/#explore @param string $bounds @param string $activity_type @param int $min_cat @param int $max_cat @return array @throws Exception
[ "Segment", "explorer" ]
train
https://github.com/basvandorst/StravaPHP/blob/5b2b2a9246434273e5a7b8e9d0333765e0fcafbf/src/Strava/API/Client.php#L708-L715
basvandorst/StravaPHP
src/Strava/API/Client.php
Client.getSegmentEffort
public function getSegmentEffort($id, $athlete_id = null, $start_date_local = null, $end_date_local = null, $page = null, $per_page = null) { try { return $this->service->getSegmentEffort($id, $athlete_id, $start_date_local, $end_date_local, $page, $per_page); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
php
public function getSegmentEffort($id, $athlete_id = null, $start_date_local = null, $end_date_local = null, $page = null, $per_page = null) { try { return $this->service->getSegmentEffort($id, $athlete_id, $start_date_local, $end_date_local, $page, $per_page); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
[ "public", "function", "getSegmentEffort", "(", "$", "id", ",", "$", "athlete_id", "=", "null", ",", "$", "start_date_local", "=", "null", ",", "$", "end_date_local", "=", "null", ",", "$", "page", "=", "null", ",", "$", "per_page", "=", "null", ")", "{...
List efforts filtered by athlete and/or a date range @link https://strava.github.io/api/v3/segments/#efforts @param int $id @param int $athlete_id @param string $start_date_local @param string $end_date_local @param int $page @param int $per_page @return array @throws Exception
[ "List", "efforts", "filtered", "by", "athlete", "and", "/", "or", "a", "date", "range" ]
train
https://github.com/basvandorst/StravaPHP/blob/5b2b2a9246434273e5a7b8e9d0333765e0fcafbf/src/Strava/API/Client.php#L730-L737
basvandorst/StravaPHP
src/Strava/API/Client.php
Client.getStreamsActivity
public function getStreamsActivity($id, $types, $resolution = null, $series_type = 'distance') { try { return $this->service->getStreamsActivity($id, $types, $resolution, $series_type); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
php
public function getStreamsActivity($id, $types, $resolution = null, $series_type = 'distance') { try { return $this->service->getStreamsActivity($id, $types, $resolution, $series_type); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
[ "public", "function", "getStreamsActivity", "(", "$", "id", ",", "$", "types", ",", "$", "resolution", "=", "null", ",", "$", "series_type", "=", "'distance'", ")", "{", "try", "{", "return", "$", "this", "->", "service", "->", "getStreamsActivity", "(", ...
Retrieve activity streams @link https://strava.github.io/api/v3/streams/#activity @param int $id @param string $types @param string $resolution @param string $series_type @return array @throws Exception
[ "Retrieve", "activity", "streams" ]
train
https://github.com/basvandorst/StravaPHP/blob/5b2b2a9246434273e5a7b8e9d0333765e0fcafbf/src/Strava/API/Client.php#L750-L757
basvandorst/StravaPHP
src/Strava/API/Client.php
Client.getStreamsRoute
public function getStreamsRoute($id) { try { return $this->service->getStreamsRoute($id); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
php
public function getStreamsRoute($id) { try { return $this->service->getStreamsRoute($id); } catch (ServiceException $e) { throw new ClientException('[SERVICE] ' . $e->getMessage()); } }
[ "public", "function", "getStreamsRoute", "(", "$", "id", ")", "{", "try", "{", "return", "$", "this", "->", "service", "->", "getStreamsRoute", "(", "$", "id", ")", ";", "}", "catch", "(", "ServiceException", "$", "e", ")", "{", "throw", "new", "Client...
Retrieve route streams @link https://strava.github.io/api/v3/streams/#routes @param int $id @return array @throws Exception
[ "Retrieve", "route", "streams" ]
train
https://github.com/basvandorst/StravaPHP/blob/5b2b2a9246434273e5a7b8e9d0333765e0fcafbf/src/Strava/API/Client.php#L806-L813
laravelista/lumen-vendor-publish
src/VendorPublishCommand.php
VendorPublishCommand.fire
public function fire() { $tags = $this->option('tag'); $tags = $tags ?: [null]; foreach ($tags as $tag) { $this->publishTag($tag); } }
php
public function fire() { $tags = $this->option('tag'); $tags = $tags ?: [null]; foreach ($tags as $tag) { $this->publishTag($tag); } }
[ "public", "function", "fire", "(", ")", "{", "$", "tags", "=", "$", "this", "->", "option", "(", "'tag'", ")", ";", "$", "tags", "=", "$", "tags", "?", ":", "[", "null", "]", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", ...
Execute the console command. @return void
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/laravelista/lumen-vendor-publish/blob/7c5e2466a3ded609f4ea9f1da4e45d5963aa1682/src/VendorPublishCommand.php#L65-L74
laravelista/lumen-vendor-publish
src/VendorPublishCommand.php
VendorPublishCommand.publishDirectory
protected function publishDirectory($from, $to) { $manager = new MountManager([ 'from' => new Flysystem(new LocalAdapter($from)), 'to' => new Flysystem(new LocalAdapter($to)), ]); foreach ($manager->listContents('from://', true) as $file) { if ($file['type'] === 'file' && (!$manager->has('to://' . $file['path']) || $this->option('force'))) { $manager->put('to://' . $file['path'], $manager->read('from://' . $file['path'])); } } $this->status($from, $to, 'Directory'); }
php
protected function publishDirectory($from, $to) { $manager = new MountManager([ 'from' => new Flysystem(new LocalAdapter($from)), 'to' => new Flysystem(new LocalAdapter($to)), ]); foreach ($manager->listContents('from://', true) as $file) { if ($file['type'] === 'file' && (!$manager->has('to://' . $file['path']) || $this->option('force'))) { $manager->put('to://' . $file['path'], $manager->read('from://' . $file['path'])); } } $this->status($from, $to, 'Directory'); }
[ "protected", "function", "publishDirectory", "(", "$", "from", ",", "$", "to", ")", "{", "$", "manager", "=", "new", "MountManager", "(", "[", "'from'", "=>", "new", "Flysystem", "(", "new", "LocalAdapter", "(", "$", "from", ")", ")", ",", "'to'", "=>"...
Publish the directory to the given directory. @param string $from @param string $to @return void
[ "Publish", "the", "directory", "to", "the", "given", "directory", "." ]
train
https://github.com/laravelista/lumen-vendor-publish/blob/7c5e2466a3ded609f4ea9f1da4e45d5963aa1682/src/VendorPublishCommand.php#L130-L144
awurth/SlimValidation
src/ValidatorExtension.php
ValidatorExtension.getFunctions
public function getFunctions() { return [ new TwigFunction($this->functionNames['error'], [$this, 'getError']), new TwigFunction($this->functionNames['errors'], [$this, 'getErrors']), new TwigFunction($this->functionNames['has_error'], [$this, 'hasError']), new TwigFunction($this->functionNames['has_errors'], [$this, 'hasErrors']), new TwigFunction($this->functionNames['val'], [$this, 'getValue']) ]; }
php
public function getFunctions() { return [ new TwigFunction($this->functionNames['error'], [$this, 'getError']), new TwigFunction($this->functionNames['errors'], [$this, 'getErrors']), new TwigFunction($this->functionNames['has_error'], [$this, 'hasError']), new TwigFunction($this->functionNames['has_errors'], [$this, 'hasErrors']), new TwigFunction($this->functionNames['val'], [$this, 'getValue']) ]; }
[ "public", "function", "getFunctions", "(", ")", "{", "return", "[", "new", "TwigFunction", "(", "$", "this", "->", "functionNames", "[", "'error'", "]", ",", "[", "$", "this", ",", "'getError'", "]", ")", ",", "new", "TwigFunction", "(", "$", "this", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/ValidatorExtension.php#L58-L67
awurth/SlimValidation
src/ValidatorExtension.php
ValidatorExtension.getError
public function getError($key, $index = null, $group = null) { return $this->validator->getError($key, $index, $group); }
php
public function getError($key, $index = null, $group = null) { return $this->validator->getError($key, $index, $group); }
[ "public", "function", "getError", "(", "$", "key", ",", "$", "index", "=", "null", ",", "$", "group", "=", "null", ")", "{", "return", "$", "this", "->", "validator", "->", "getError", "(", "$", "key", ",", "$", "index", ",", "$", "group", ")", "...
Gets the first validation error of a parameter. @param string $key @param string $index @param string $group @return string
[ "Gets", "the", "first", "validation", "error", "of", "a", "parameter", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/ValidatorExtension.php#L78-L81
awurth/SlimValidation
src/ValidatorExtension.php
ValidatorExtension.getErrors
public function getErrors($key = null, $group = null) { return $this->validator->getErrors($key, $group); }
php
public function getErrors($key = null, $group = null) { return $this->validator->getErrors($key, $group); }
[ "public", "function", "getErrors", "(", "$", "key", "=", "null", ",", "$", "group", "=", "null", ")", "{", "return", "$", "this", "->", "validator", "->", "getErrors", "(", "$", "key", ",", "$", "group", ")", ";", "}" ]
Gets validation errors. @param string $key @param string $group @return string[]
[ "Gets", "validation", "errors", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/ValidatorExtension.php#L91-L94
awurth/SlimValidation
src/ValidatorExtension.php
ValidatorExtension.hasError
public function hasError($key, $group = null) { return !empty($this->validator->getErrors($key, $group)); }
php
public function hasError($key, $group = null) { return !empty($this->validator->getErrors($key, $group)); }
[ "public", "function", "hasError", "(", "$", "key", ",", "$", "group", "=", "null", ")", "{", "return", "!", "empty", "(", "$", "this", "->", "validator", "->", "getErrors", "(", "$", "key", ",", "$", "group", ")", ")", ";", "}" ]
Tells whether there are validation errors for a parameter. @param string $key @param string $group @return bool
[ "Tells", "whether", "there", "are", "validation", "errors", "for", "a", "parameter", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/ValidatorExtension.php#L117-L120
awurth/SlimValidation
src/Validator.php
Validator.array
public function array(array $array, array $rules, string $group = null, array $messages = [], $default = null): self { foreach ($rules as $key => $options) { $this->validateInput( $array[$key] ?? $default, new Configuration($options, $key, $group, $default), $messages ); } return $this; }
php
public function array(array $array, array $rules, string $group = null, array $messages = [], $default = null): self { foreach ($rules as $key => $options) { $this->validateInput( $array[$key] ?? $default, new Configuration($options, $key, $group, $default), $messages ); } return $this; }
[ "public", "function", "array", "(", "array", "$", "array", ",", "array", "$", "rules", ",", "string", "$", "group", "=", "null", ",", "array", "$", "messages", "=", "[", "]", ",", "$", "default", "=", "null", ")", ":", "self", "{", "foreach", "(", ...
Validates an array with the given rules. @param array $array @param AllOf[]|array $rules @param string|null $group @param string[] $messages @param mixed|null $default @return self
[ "Validates", "an", "array", "with", "the", "given", "rules", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L91-L102
awurth/SlimValidation
src/Validator.php
Validator.object
public function object($object, array $rules, string $group = null, array $messages = [], $default = null): self { if (!is_object($object)) { throw new InvalidArgumentException('The first argument should be an object'); } foreach ($rules as $property => $options) { $this->validateInput( $this->getPropertyValue($object, $property, $default), new Configuration($options, $property, $group, $default), $messages ); } return $this; }
php
public function object($object, array $rules, string $group = null, array $messages = [], $default = null): self { if (!is_object($object)) { throw new InvalidArgumentException('The first argument should be an object'); } foreach ($rules as $property => $options) { $this->validateInput( $this->getPropertyValue($object, $property, $default), new Configuration($options, $property, $group, $default), $messages ); } return $this; }
[ "public", "function", "object", "(", "$", "object", ",", "array", "$", "rules", ",", "string", "$", "group", "=", "null", ",", "array", "$", "messages", "=", "[", "]", ",", "$", "default", "=", "null", ")", ":", "self", "{", "if", "(", "!", "is_o...
Validates an objects properties with the given rules. @param object $object @param AllOf[]|array $rules @param string|null $group @param string[] $messages @param mixed|null $default @return self
[ "Validates", "an", "objects", "properties", "with", "the", "given", "rules", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L115-L130
awurth/SlimValidation
src/Validator.php
Validator.request
public function request(Request $request, array $rules, string $group = null, array $messages = [], $default = null): self { foreach ($rules as $param => $options) { $this->validateInput( $this->getRequestParam($request, $param, $default), new Configuration($options, $param, $group, $default), $messages ); } return $this; }
php
public function request(Request $request, array $rules, string $group = null, array $messages = [], $default = null): self { foreach ($rules as $param => $options) { $this->validateInput( $this->getRequestParam($request, $param, $default), new Configuration($options, $param, $group, $default), $messages ); } return $this; }
[ "public", "function", "request", "(", "Request", "$", "request", ",", "array", "$", "rules", ",", "string", "$", "group", "=", "null", ",", "array", "$", "messages", "=", "[", "]", ",", "$", "default", "=", "null", ")", ":", "self", "{", "foreach", ...
Validates request parameters with the given rules. @param Request $request @param AllOf[]|array $rules @param string|null $group @param string[] $messages @param mixed|null $default @return self
[ "Validates", "request", "parameters", "with", "the", "given", "rules", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L143-L154
awurth/SlimValidation
src/Validator.php
Validator.validate
public function validate($input, array $rules, string $group = null, array $messages = [], $default = null): self { if ($input instanceof Request) { return $this->request($input, $rules, $group, $messages, $default); } elseif (is_array($input)) { return $this->array($input, $rules, $group, $messages, $default); } elseif (is_object($input)) { return $this->object($input, $rules, $group, $messages, $default); } return $this->value($input, $rules, null, $group, $messages); }
php
public function validate($input, array $rules, string $group = null, array $messages = [], $default = null): self { if ($input instanceof Request) { return $this->request($input, $rules, $group, $messages, $default); } elseif (is_array($input)) { return $this->array($input, $rules, $group, $messages, $default); } elseif (is_object($input)) { return $this->object($input, $rules, $group, $messages, $default); } return $this->value($input, $rules, null, $group, $messages); }
[ "public", "function", "validate", "(", "$", "input", ",", "array", "$", "rules", ",", "string", "$", "group", "=", "null", ",", "array", "$", "messages", "=", "[", "]", ",", "$", "default", "=", "null", ")", ":", "self", "{", "if", "(", "$", "inp...
{@inheritdoc}
[ "{" ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L159-L170
awurth/SlimValidation
src/Validator.php
Validator.value
public function value($value, $rules, string $key, string $group = null, array $messages = []): self { return $this->validateInput($value, new Configuration($rules, $key, $group), $messages); }
php
public function value($value, $rules, string $key, string $group = null, array $messages = []): self { return $this->validateInput($value, new Configuration($rules, $key, $group), $messages); }
[ "public", "function", "value", "(", "$", "value", ",", "$", "rules", ",", "string", "$", "key", ",", "string", "$", "group", "=", "null", ",", "array", "$", "messages", "=", "[", "]", ")", ":", "self", "{", "return", "$", "this", "->", "validateInp...
Validates a single value with the given rules. @param mixed $value @param AllOf|array $rules @param string $key @param string|null $group @param string[] $messages @return self
[ "Validates", "a", "single", "value", "with", "the", "given", "rules", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L183-L186
awurth/SlimValidation
src/Validator.php
Validator.addError
public function addError(string $key, string $message, string $group = null): self { if (!empty($group)) { $this->errors[$group][$key][] = $message; } else { $this->errors[$key][] = $message; } return $this; }
php
public function addError(string $key, string $message, string $group = null): self { if (!empty($group)) { $this->errors[$group][$key][] = $message; } else { $this->errors[$key][] = $message; } return $this; }
[ "public", "function", "addError", "(", "string", "$", "key", ",", "string", "$", "message", ",", "string", "$", "group", "=", "null", ")", ":", "self", "{", "if", "(", "!", "empty", "(", "$", "group", ")", ")", "{", "$", "this", "->", "errors", "...
Adds a validation error. @param string $key @param string $message @param string|null $group @return self
[ "Adds", "a", "validation", "error", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L207-L216
awurth/SlimValidation
src/Validator.php
Validator.getError
public function getError(string $key, $index = null, $group = null) { if (null === $index) { return $this->getFirstError($key, $group); } if (!empty($group)) { return $this->errors[$group][$key][$index] ?? ''; } return $this->errors[$key][$index] ?? ''; }
php
public function getError(string $key, $index = null, $group = null) { if (null === $index) { return $this->getFirstError($key, $group); } if (!empty($group)) { return $this->errors[$group][$key][$index] ?? ''; } return $this->errors[$key][$index] ?? ''; }
[ "public", "function", "getError", "(", "string", "$", "key", ",", "$", "index", "=", "null", ",", "$", "group", "=", "null", ")", "{", "if", "(", "null", "===", "$", "index", ")", "{", "return", "$", "this", "->", "getFirstError", "(", "$", "key", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L243-L254
awurth/SlimValidation
src/Validator.php
Validator.getErrors
public function getErrors(string $key = null, string $group = null): array { if (!empty($key)) { if (!empty($group)) { return $this->errors[$group][$key] ?? []; } return $this->errors[$key] ?? []; } return $this->errors; }
php
public function getErrors(string $key = null, string $group = null): array { if (!empty($key)) { if (!empty($group)) { return $this->errors[$group][$key] ?? []; } return $this->errors[$key] ?? []; } return $this->errors; }
[ "public", "function", "getErrors", "(", "string", "$", "key", "=", "null", ",", "string", "$", "group", "=", "null", ")", ":", "array", "{", "if", "(", "!", "empty", "(", "$", "key", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "group", ")...
{@inheritdoc}
[ "{" ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L259-L270
awurth/SlimValidation
src/Validator.php
Validator.getFirstError
public function getFirstError(string $key, string $group = null) { if (!empty($group)) { if (isset($this->errors[$group][$key])) { $first = array_slice($this->errors[$group][$key], 0, 1); return array_shift($first); } } if (isset($this->errors[$key])) { $first = array_slice($this->errors[$key], 0, 1); return array_shift($first); } return ''; }
php
public function getFirstError(string $key, string $group = null) { if (!empty($group)) { if (isset($this->errors[$group][$key])) { $first = array_slice($this->errors[$group][$key], 0, 1); return array_shift($first); } } if (isset($this->errors[$key])) { $first = array_slice($this->errors[$key], 0, 1); return array_shift($first); } return ''; }
[ "public", "function", "getFirstError", "(", "string", "$", "key", ",", "string", "$", "group", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "group", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "errors", "[", "$", "grou...
Gets the first error of a parameter. @param string $key @param string|null $group @return string
[ "Gets", "the", "first", "error", "of", "a", "parameter", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L280-L297
awurth/SlimValidation
src/Validator.php
Validator.getValue
public function getValue(string $key, string $group = null) { if (!empty($group)) { return $this->values[$group][$key] ?? null; } return $this->values[$key] ?? null; }
php
public function getValue(string $key, string $group = null) { if (!empty($group)) { return $this->values[$group][$key] ?? null; } return $this->values[$key] ?? null; }
[ "public", "function", "getValue", "(", "string", "$", "key", ",", "string", "$", "group", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "group", ")", ")", "{", "return", "$", "this", "->", "values", "[", "$", "group", "]", "[", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L302-L309
awurth/SlimValidation
src/Validator.php
Validator.getValues
public function getValues(string $group = null) { if (!empty($group)) { return $this->values[$group] ?? []; } return $this->values; }
php
public function getValues(string $group = null) { if (!empty($group)) { return $this->values[$group] ?? []; } return $this->values; }
[ "public", "function", "getValues", "(", "string", "$", "group", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "group", ")", ")", "{", "return", "$", "this", "->", "values", "[", "$", "group", "]", "??", "[", "]", ";", "}", "return", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L314-L321
awurth/SlimValidation
src/Validator.php
Validator.setDefaultMessage
public function setDefaultMessage(string $rule, string $message): self { $this->defaultMessages[$rule] = $message; return $this; }
php
public function setDefaultMessage(string $rule, string $message): self { $this->defaultMessages[$rule] = $message; return $this; }
[ "public", "function", "setDefaultMessage", "(", "string", "$", "rule", ",", "string", "$", "message", ")", ":", "self", "{", "$", "this", "->", "defaultMessages", "[", "$", "rule", "]", "=", "$", "message", ";", "return", "$", "this", ";", "}" ]
Sets the default error message for a validation rule. @param string $rule @param string $message @return self
[ "Sets", "the", "default", "error", "message", "for", "a", "validation", "rule", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L364-L369
awurth/SlimValidation
src/Validator.php
Validator.setErrors
public function setErrors(array $errors, string $key = null, string $group = null): self { if (!empty($group)) { if (!empty($key)) { $this->errors[$group][$key] = $errors; } else { $this->errors[$group] = $errors; } } elseif (!empty($key)) { $this->errors[$key] = $errors; } else { $this->errors = $errors; } return $this; }
php
public function setErrors(array $errors, string $key = null, string $group = null): self { if (!empty($group)) { if (!empty($key)) { $this->errors[$group][$key] = $errors; } else { $this->errors[$group] = $errors; } } elseif (!empty($key)) { $this->errors[$key] = $errors; } else { $this->errors = $errors; } return $this; }
[ "public", "function", "setErrors", "(", "array", "$", "errors", ",", "string", "$", "key", "=", "null", ",", "string", "$", "group", "=", "null", ")", ":", "self", "{", "if", "(", "!", "empty", "(", "$", "group", ")", ")", "{", "if", "(", "!", ...
Sets validation errors. @param string[] $errors @param string|null $key @param string|null $group @return self
[ "Sets", "validation", "errors", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L394-L409
awurth/SlimValidation
src/Validator.php
Validator.setValue
public function setValue(string $key, $value, string $group = null): self { if (!empty($group)) { $this->values[$group][$key] = $value; } else { $this->values[$key] = $value; } return $this; }
php
public function setValue(string $key, $value, string $group = null): self { if (!empty($group)) { $this->values[$group][$key] = $value; } else { $this->values[$key] = $value; } return $this; }
[ "public", "function", "setValue", "(", "string", "$", "key", ",", "$", "value", ",", "string", "$", "group", "=", "null", ")", ":", "self", "{", "if", "(", "!", "empty", "(", "$", "group", ")", ")", "{", "$", "this", "->", "values", "[", "$", "...
Sets the value of a parameter. @param string $key @param mixed $value @param string|null $group @return self
[ "Sets", "the", "value", "of", "a", "parameter", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L434-L443
awurth/SlimValidation
src/Validator.php
Validator.setValues
public function setValues(array $values, string $group = null): self { foreach ($values as $key => $value) { $this->setValue($key, $value, $group); } return $this; }
php
public function setValues(array $values, string $group = null): self { foreach ($values as $key => $value) { $this->setValue($key, $value, $group); } return $this; }
[ "public", "function", "setValues", "(", "array", "$", "values", ",", "string", "$", "group", "=", "null", ")", ":", "self", "{", "foreach", "(", "$", "values", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "setValue", "(", "$",...
Sets values of validated data. @param array $values @param string|null $group @return self
[ "Sets", "values", "of", "validated", "data", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L453-L460
awurth/SlimValidation
src/Validator.php
Validator.getPropertyValue
protected function getPropertyValue($object, string $propertyName, $default = null) { if (!is_object($object)) { throw new InvalidArgumentException('The first argument should be an object'); } if (!property_exists($object, $propertyName)) { return $default; } try { $reflectionProperty = new ReflectionProperty($object, $propertyName); $reflectionProperty->setAccessible(true); return $reflectionProperty->getValue($object); } catch (ReflectionException $e) { return $default; } }
php
protected function getPropertyValue($object, string $propertyName, $default = null) { if (!is_object($object)) { throw new InvalidArgumentException('The first argument should be an object'); } if (!property_exists($object, $propertyName)) { return $default; } try { $reflectionProperty = new ReflectionProperty($object, $propertyName); $reflectionProperty->setAccessible(true); return $reflectionProperty->getValue($object); } catch (ReflectionException $e) { return $default; } }
[ "protected", "function", "getPropertyValue", "(", "$", "object", ",", "string", "$", "propertyName", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "is_object", "(", "$", "object", ")", ")", "{", "throw", "new", "InvalidArgumentException", "("...
Gets the value of a property of an object. @param object $object @param string $propertyName @param mixed|null $default @return mixed
[ "Gets", "the", "value", "of", "a", "property", "of", "an", "object", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L471-L489
awurth/SlimValidation
src/Validator.php
Validator.getRequestParam
protected function getRequestParam(Request $request, $key, $default = null) { $postParams = $request->getParsedBody(); $getParams = $request->getQueryParams(); $result = $default; if (is_array($postParams) && isset($postParams[$key])) { $result = $postParams[$key]; } elseif (is_object($postParams) && property_exists($postParams, $key)) { $result = $postParams->$key; } elseif (isset($getParams[$key])) { $result = $getParams[$key]; } elseif (isset($_FILES[$key])) { $result = $_FILES[$key]; } return $result; }
php
protected function getRequestParam(Request $request, $key, $default = null) { $postParams = $request->getParsedBody(); $getParams = $request->getQueryParams(); $result = $default; if (is_array($postParams) && isset($postParams[$key])) { $result = $postParams[$key]; } elseif (is_object($postParams) && property_exists($postParams, $key)) { $result = $postParams->$key; } elseif (isset($getParams[$key])) { $result = $getParams[$key]; } elseif (isset($_FILES[$key])) { $result = $_FILES[$key]; } return $result; }
[ "protected", "function", "getRequestParam", "(", "Request", "$", "request", ",", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "postParams", "=", "$", "request", "->", "getParsedBody", "(", ")", ";", "$", "getParams", "=", "$", "request", ...
Fetches a request parameter's value from the body or query string (in that order). @param Request $request @param string $key @param string|null $default @return mixed
[ "Fetches", "a", "request", "parameter", "s", "value", "from", "the", "body", "or", "query", "string", "(", "in", "that", "order", ")", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L500-L517
awurth/SlimValidation
src/Validator.php
Validator.getRulesNames
protected function getRulesNames(AllOf $rules): array { $rulesNames = []; foreach ($rules->getRules() as $rule) { try { $rulesNames[] = lcfirst((new ReflectionClass($rule))->getShortName()); } catch (ReflectionException $e) { } } return $rulesNames; }
php
protected function getRulesNames(AllOf $rules): array { $rulesNames = []; foreach ($rules->getRules() as $rule) { try { $rulesNames[] = lcfirst((new ReflectionClass($rule))->getShortName()); } catch (ReflectionException $e) { } } return $rulesNames; }
[ "protected", "function", "getRulesNames", "(", "AllOf", "$", "rules", ")", ":", "array", "{", "$", "rulesNames", "=", "[", "]", ";", "foreach", "(", "$", "rules", "->", "getRules", "(", ")", "as", "$", "rule", ")", "{", "try", "{", "$", "rulesNames",...
Gets the name of all rules of a group of rules. @param AllOf $rules @return string[]
[ "Gets", "the", "name", "of", "all", "rules", "of", "a", "group", "of", "rules", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L526-L537
awurth/SlimValidation
src/Validator.php
Validator.handleValidationException
protected function handleValidationException(NestedValidationException $e, Configuration $config, array $messages = []) { if ($config->hasMessage()) { $this->setErrors([$config->getMessage()], $config->getKey(), $config->getGroup()); } else { $this->storeErrors($e, $config, $messages); } }
php
protected function handleValidationException(NestedValidationException $e, Configuration $config, array $messages = []) { if ($config->hasMessage()) { $this->setErrors([$config->getMessage()], $config->getKey(), $config->getGroup()); } else { $this->storeErrors($e, $config, $messages); } }
[ "protected", "function", "handleValidationException", "(", "NestedValidationException", "$", "e", ",", "Configuration", "$", "config", ",", "array", "$", "messages", "=", "[", "]", ")", "{", "if", "(", "$", "config", "->", "hasMessage", "(", ")", ")", "{", ...
Handles a validation exception. @param NestedValidationException $e @param Configuration $config @param string[] $messages
[ "Handles", "a", "validation", "exception", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L546-L553
awurth/SlimValidation
src/Validator.php
Validator.mergeMessages
protected function mergeMessages(array $errors): array { $errors = array_filter(call_user_func_array('array_merge', $errors)); return $this->showValidationRules ? $errors : array_values($errors); }
php
protected function mergeMessages(array $errors): array { $errors = array_filter(call_user_func_array('array_merge', $errors)); return $this->showValidationRules ? $errors : array_values($errors); }
[ "protected", "function", "mergeMessages", "(", "array", "$", "errors", ")", ":", "array", "{", "$", "errors", "=", "array_filter", "(", "call_user_func_array", "(", "'array_merge'", ",", "$", "errors", ")", ")", ";", "return", "$", "this", "->", "showValidat...
Merges default messages, global messages and individual messages. @param array $errors @return string[]
[ "Merges", "default", "messages", "global", "messages", "and", "individual", "messages", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L562-L567
awurth/SlimValidation
src/Validator.php
Validator.storeErrors
protected function storeErrors(NestedValidationException $e, Configuration $config, array $messages = []) { $errors = [ $e->findMessages($this->getRulesNames($config->getValidationRules())) ]; // If default messages are defined if (!empty($this->defaultMessages)) { $errors[] = $e->findMessages($this->defaultMessages); } // If global messages are defined if (!empty($messages)) { $errors[] = $e->findMessages($messages); } // If individual messages are defined if ($config->hasMessages()) { $errors[] = $e->findMessages($config->getMessages()); } $this->setErrors($this->mergeMessages($errors), $config->getKey(), $config->getGroup()); }
php
protected function storeErrors(NestedValidationException $e, Configuration $config, array $messages = []) { $errors = [ $e->findMessages($this->getRulesNames($config->getValidationRules())) ]; // If default messages are defined if (!empty($this->defaultMessages)) { $errors[] = $e->findMessages($this->defaultMessages); } // If global messages are defined if (!empty($messages)) { $errors[] = $e->findMessages($messages); } // If individual messages are defined if ($config->hasMessages()) { $errors[] = $e->findMessages($config->getMessages()); } $this->setErrors($this->mergeMessages($errors), $config->getKey(), $config->getGroup()); }
[ "protected", "function", "storeErrors", "(", "NestedValidationException", "$", "e", ",", "Configuration", "$", "config", ",", "array", "$", "messages", "=", "[", "]", ")", "{", "$", "errors", "=", "[", "$", "e", "->", "findMessages", "(", "$", "this", "-...
Sets error messages after validation. @param NestedValidationException $e @param Configuration $config @param string[] $messages
[ "Sets", "error", "messages", "after", "validation", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L576-L598
awurth/SlimValidation
src/Validator.php
Validator.validateInput
protected function validateInput($input, Configuration $config, array $messages = []): self { try { $config->getValidationRules()->assert($input); } catch (NestedValidationException $e) { $this->handleValidationException($e, $config, $messages); } return $this->setValue($config->getKey(), $input, $config->getGroup()); }
php
protected function validateInput($input, Configuration $config, array $messages = []): self { try { $config->getValidationRules()->assert($input); } catch (NestedValidationException $e) { $this->handleValidationException($e, $config, $messages); } return $this->setValue($config->getKey(), $input, $config->getGroup()); }
[ "protected", "function", "validateInput", "(", "$", "input", ",", "Configuration", "$", "config", ",", "array", "$", "messages", "=", "[", "]", ")", ":", "self", "{", "try", "{", "$", "config", "->", "getValidationRules", "(", ")", "->", "assert", "(", ...
Executes the validation of a value and handles errors. @param mixed $input @param Configuration $config @param string[] $messages @return self
[ "Executes", "the", "validation", "of", "a", "value", "and", "handles", "errors", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Validator.php#L609-L618
awurth/SlimValidation
src/Configuration.php
Configuration.setOptions
public function setOptions(array $options) { $availableOptions = [ 'default', 'group', 'key', 'message', 'messages', 'rules' ]; foreach ($availableOptions as $option) { if (isset($options[$option])) { $this->$option = $options[$option]; } } }
php
public function setOptions(array $options) { $availableOptions = [ 'default', 'group', 'key', 'message', 'messages', 'rules' ]; foreach ($availableOptions as $option) { if (isset($options[$option])) { $this->$option = $options[$option]; } } }
[ "public", "function", "setOptions", "(", "array", "$", "options", ")", "{", "$", "availableOptions", "=", "[", "'default'", ",", "'group'", ",", "'key'", ",", "'message'", ",", "'messages'", ",", "'rules'", "]", ";", "foreach", "(", "$", "availableOptions", ...
Sets options from an array. @param array $options
[ "Sets", "options", "from", "an", "array", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Configuration.php#L232-L248
awurth/SlimValidation
src/Configuration.php
Configuration.validateOptions
public function validateOptions() { if (!$this->rules instanceof AllOf) { throw new InvalidArgumentException('Validation rules are missing or invalid'); } if (!$this->hasKey()) { throw new InvalidArgumentException('A key must be set'); } if ($this->hasMessage() && !is_string($this->message)) { throw new InvalidArgumentException(sprintf('Expected custom message to be of type string, %s given', gettype($this->message))); } }
php
public function validateOptions() { if (!$this->rules instanceof AllOf) { throw new InvalidArgumentException('Validation rules are missing or invalid'); } if (!$this->hasKey()) { throw new InvalidArgumentException('A key must be set'); } if ($this->hasMessage() && !is_string($this->message)) { throw new InvalidArgumentException(sprintf('Expected custom message to be of type string, %s given', gettype($this->message))); } }
[ "public", "function", "validateOptions", "(", ")", "{", "if", "(", "!", "$", "this", "->", "rules", "instanceof", "AllOf", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Validation rules are missing or invalid'", ")", ";", "}", "if", "(", "!", "$...
Verifies that all mandatory options are set and valid.
[ "Verifies", "that", "all", "mandatory", "options", "are", "set", "and", "valid", "." ]
train
https://github.com/awurth/SlimValidation/blob/33bf40e48272d3917344a1e34626b183e81e4482/src/Configuration.php#L263-L276
apigee/apigee-client-php
src/Api/Monetization/Controller/ListingHelperTrait.php
ListingHelperTrait.getRawList
protected function getRawList(UriInterface $uri): array { $response = $this->getClient()->get($uri); $responseArray = $this->responseToArray($response); // Ignore entity type key from response, ex.: product. return reset($responseArray); }
php
protected function getRawList(UriInterface $uri): array { $response = $this->getClient()->get($uri); $responseArray = $this->responseToArray($response); // Ignore entity type key from response, ex.: product. return reset($responseArray); }
[ "protected", "function", "getRawList", "(", "UriInterface", "$", "uri", ")", ":", "array", "{", "$", "response", "=", "$", "this", "->", "getClient", "(", ")", "->", "get", "(", "$", "uri", ")", ";", "$", "responseArray", "=", "$", "this", "->", "res...
Returns a raw API response as an array of a listing API endpoint. @param \Psr\Http\Message\UriInterface $uri URI of the endpoint where the request should be sent. @return array API response as an array.
[ "Returns", "a", "raw", "API", "response", "as", "an", "array", "of", "a", "listing", "API", "endpoint", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/ListingHelperTrait.php#L43-L50
apigee/apigee-client-php
src/Structure/BaseObject.php
BaseObject.cloneArray
private function cloneArray(array &$array): void { foreach ($array as $key => $value) { if (is_object($value)) { $array[$key] = clone $value; } if (is_array($value)) { $this->cloneArray($array[$key]); } } }
php
private function cloneArray(array &$array): void { foreach ($array as $key => $value) { if (is_object($value)) { $array[$key] = clone $value; } if (is_array($value)) { $this->cloneArray($array[$key]); } } }
[ "private", "function", "cloneArray", "(", "array", "&", "$", "array", ")", ":", "void", "{", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "$", "array", "["...
Deep clone for arrays. @param array $array
[ "Deep", "clone", "for", "arrays", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Structure/BaseObject.php#L89-L99
apigee/apigee-client-php
src/Client.php
Client.configureOptions
protected function configureOptions(OptionsResolver $resolver): void { // We set object properties' _default_ values to null to ensure we do not create unnecessary objects. $resolver->setDefaults([ static::CONFIG_USER_AGENT_PREFIX => null, static::CONFIG_HTTP_CLIENT_BUILDER => null, static::CONFIG_JOURNAL => null, static::CONFIG_URI_FACTORY => null, static::CONFIG_REQUEST_FACTORY => null, static::CONFIG_ERROR_FORMATTER => null, static::CONFIG_RETRY_PLUGIN_CONFIG => null, ]); $resolver->setAllowedTypes(static::CONFIG_USER_AGENT_PREFIX, ['null', 'string']); $resolver->setAllowedTypes(static::CONFIG_HTTP_CLIENT_BUILDER, ['null', '\Apigee\Edge\HttpClient\Utility\BuilderInterface']); $resolver->setAllowedTypes(static::CONFIG_JOURNAL, ['null', '\Apigee\Edge\HttpClient\Utility\JournalInterface']); $resolver->setAllowedTypes(static::CONFIG_URI_FACTORY, ['null', '\Http\Message\UriFactory']); $resolver->setAllowedTypes(static::CONFIG_REQUEST_FACTORY, ['null', '\Http\Message\RequestFactory']); $resolver->setAllowedTypes(static::CONFIG_ERROR_FORMATTER, ['null', '\Http\Message\Formatter']); $resolver->setAllowedTypes(static::CONFIG_RETRY_PLUGIN_CONFIG, ['null', 'array']); }
php
protected function configureOptions(OptionsResolver $resolver): void { // We set object properties' _default_ values to null to ensure we do not create unnecessary objects. $resolver->setDefaults([ static::CONFIG_USER_AGENT_PREFIX => null, static::CONFIG_HTTP_CLIENT_BUILDER => null, static::CONFIG_JOURNAL => null, static::CONFIG_URI_FACTORY => null, static::CONFIG_REQUEST_FACTORY => null, static::CONFIG_ERROR_FORMATTER => null, static::CONFIG_RETRY_PLUGIN_CONFIG => null, ]); $resolver->setAllowedTypes(static::CONFIG_USER_AGENT_PREFIX, ['null', 'string']); $resolver->setAllowedTypes(static::CONFIG_HTTP_CLIENT_BUILDER, ['null', '\Apigee\Edge\HttpClient\Utility\BuilderInterface']); $resolver->setAllowedTypes(static::CONFIG_JOURNAL, ['null', '\Apigee\Edge\HttpClient\Utility\JournalInterface']); $resolver->setAllowedTypes(static::CONFIG_URI_FACTORY, ['null', '\Http\Message\UriFactory']); $resolver->setAllowedTypes(static::CONFIG_REQUEST_FACTORY, ['null', '\Http\Message\RequestFactory']); $resolver->setAllowedTypes(static::CONFIG_ERROR_FORMATTER, ['null', '\Http\Message\Formatter']); $resolver->setAllowedTypes(static::CONFIG_RETRY_PLUGIN_CONFIG, ['null', 'array']); }
[ "protected", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", ":", "void", "{", "// We set object properties' _default_ values to null to ensure we do not create unnecessary objects.", "$", "resolver", "->", "setDefaults", "(", "[", "static", "::", ...
Sets default for supported configuration options. @param \Symfony\Component\OptionsResolver\OptionsResolver $resolver Option resolver.
[ "Sets", "default", "for", "supported", "configuration", "options", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Client.php#L250-L269
apigee/apigee-client-php
src/Client.php
Client.getDefaultPlugins
protected function getDefaultPlugins(): array { // Alters requests, adds base path and authentication. $firstPlugins = [ new BaseUriPlugin($this->getBaseUri(), ['replace' => true]), new HeaderDefaultsPlugin($this->getDefaultHeaders()), ]; if ($this->authentication) { $firstPlugins[] = new AuthenticationPlugin($this->authentication); } // Acts based on response data. // (Retry plugin should be added here if it will be used.) $middlePlugins = [ new HistoryPlugin($this->journal), ]; if (null !== $this->retryPluginConfig) { if (!isset($this->retryPluginConfig['exception_decider'])) { $this->retryPluginConfig['exception_decider'] = function (RequestInterface $request, Exception $e) { // When Oauth authentication is in use retry decider should ignore // OauthAuthenticationException. if (!$e instanceof OauthAuthenticationException) { // Do not retry API calls that failed with // client error. if ($e instanceof ApiResponseException && $e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 500) { return false; } return true; } return false; }; } $middlePlugins[] = new RetryPlugin($this->retryPluginConfig); } if ($this->authentication instanceof Oauth) { $middlePlugins[] = new RetryOauthAuthenticationPlugin($this->authentication); } // Alters, analyzes responses. $finalPlugins = [ new ResponseHandlerPlugin($this->errorFormatter), ]; return array_merge($firstPlugins, $middlePlugins, $finalPlugins); }
php
protected function getDefaultPlugins(): array { // Alters requests, adds base path and authentication. $firstPlugins = [ new BaseUriPlugin($this->getBaseUri(), ['replace' => true]), new HeaderDefaultsPlugin($this->getDefaultHeaders()), ]; if ($this->authentication) { $firstPlugins[] = new AuthenticationPlugin($this->authentication); } // Acts based on response data. // (Retry plugin should be added here if it will be used.) $middlePlugins = [ new HistoryPlugin($this->journal), ]; if (null !== $this->retryPluginConfig) { if (!isset($this->retryPluginConfig['exception_decider'])) { $this->retryPluginConfig['exception_decider'] = function (RequestInterface $request, Exception $e) { // When Oauth authentication is in use retry decider should ignore // OauthAuthenticationException. if (!$e instanceof OauthAuthenticationException) { // Do not retry API calls that failed with // client error. if ($e instanceof ApiResponseException && $e->getResponse()->getStatusCode() >= 400 && $e->getResponse()->getStatusCode() < 500) { return false; } return true; } return false; }; } $middlePlugins[] = new RetryPlugin($this->retryPluginConfig); } if ($this->authentication instanceof Oauth) { $middlePlugins[] = new RetryOauthAuthenticationPlugin($this->authentication); } // Alters, analyzes responses. $finalPlugins = [ new ResponseHandlerPlugin($this->errorFormatter), ]; return array_merge($firstPlugins, $middlePlugins, $finalPlugins); }
[ "protected", "function", "getDefaultPlugins", "(", ")", ":", "array", "{", "// Alters requests, adds base path and authentication.", "$", "firstPlugins", "=", "[", "new", "BaseUriPlugin", "(", "$", "this", "->", "getBaseUri", "(", ")", ",", "[", "'replace'", "=>", ...
Returns default plugins used by the underlying HTTP client. Call order of default plugins for sending a request (only those plugins listed that actually does something): Request -> PluginClient -> BaseUriPlugin -> HeaderDefaultsPlugin -> HttpClient Call order of default plugins for processing a response (only those plugins listed that actually does something): HttpClient -> ResponseHandlerPlugin -> RetryOauthAuthenticationPlugin -> HistoryPlugin -> Response @return \Http\Client\Common\Plugin[]
[ "Returns", "default", "plugins", "used", "by", "the", "underlying", "HTTP", "client", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Client.php#L295-L344
apigee/apigee-client-php
src/Client.php
Client.resolveConfiguration
private function resolveConfiguration(array $options = []): void { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $options = $resolver->resolve($options); $this->userAgentPrefix = $options[static::CONFIG_USER_AGENT_PREFIX]; $this->httpClientBuilder = $options[static::CONFIG_HTTP_CLIENT_BUILDER] ?: new Builder(); $this->uriFactory = $options[static::CONFIG_URI_FACTORY] ?: UriFactoryDiscovery::find(); $this->requestFactory = $options[static::CONFIG_REQUEST_FACTORY] ?: MessageFactoryDiscovery::find(); $this->journal = $options[static::CONFIG_JOURNAL] ?: new Journal(); $this->errorFormatter = $options[static::CONFIG_ERROR_FORMATTER]; $this->retryPluginConfig = $options[static::CONFIG_RETRY_PLUGIN_CONFIG]; }
php
private function resolveConfiguration(array $options = []): void { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $options = $resolver->resolve($options); $this->userAgentPrefix = $options[static::CONFIG_USER_AGENT_PREFIX]; $this->httpClientBuilder = $options[static::CONFIG_HTTP_CLIENT_BUILDER] ?: new Builder(); $this->uriFactory = $options[static::CONFIG_URI_FACTORY] ?: UriFactoryDiscovery::find(); $this->requestFactory = $options[static::CONFIG_REQUEST_FACTORY] ?: MessageFactoryDiscovery::find(); $this->journal = $options[static::CONFIG_JOURNAL] ?: new Journal(); $this->errorFormatter = $options[static::CONFIG_ERROR_FORMATTER]; $this->retryPluginConfig = $options[static::CONFIG_RETRY_PLUGIN_CONFIG]; }
[ "private", "function", "resolveConfiguration", "(", "array", "$", "options", "=", "[", "]", ")", ":", "void", "{", "$", "resolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "this", "->", "configureOptions", "(", "$", "resolver", ")", ";", "$", ...
Resolve configuration options. @param array $options Array of configuration options.
[ "Resolve", "configuration", "options", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Client.php#L367-L379
apigee/apigee-client-php
src/Api/Management/Normalizer/AppNormalizer.php
AppNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); // Remove properties that saved to attributes on apps. unset($normalized->displayName); unset($normalized->description); return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); // Remove properties that saved to attributes on apps. unset($normalized->displayName); unset($normalized->description); return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var object $normalized */", "$", "normalized", "=", "parent", "::", "normalize", "(", "$", "object", ",", ...
@inheritdoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Normalizer/AppNormalizer.php#L44-L53
apigee/apigee-client-php
src/Exception/ApiResponseException.php
ApiResponseException.parseErrorResponse
private function parseErrorResponse(ResponseInterface $response): array { $error = [ 'code' => null, 'message' => null, ]; // Try to parse Edge error message and error code from the response body. $contentTypeHeader = $response->getHeaderLine('Content-Type'); if ($contentTypeHeader && false !== strpos($contentTypeHeader, 'application/json')) { $array = json_decode((string) $response->getBody(), true); if (JSON_ERROR_NONE === json_last_error()) { if (array_key_exists('fault', $array)) { $error['message'] = $array['fault']['faultstring'] ?? null; $error['code'] = $array['fault']['detail']['errorcode'] ?? null; } else { if (array_key_exists('code', $array)) { $error['code'] = $array['code']; } if (array_key_exists('message', $array)) { // It could happen that the returned message by // Apigee Edge is also an array. $error['message'] = is_array($array['message']) ? json_encode($array['message']) : $array['message']; } } } } return $error; }
php
private function parseErrorResponse(ResponseInterface $response): array { $error = [ 'code' => null, 'message' => null, ]; // Try to parse Edge error message and error code from the response body. $contentTypeHeader = $response->getHeaderLine('Content-Type'); if ($contentTypeHeader && false !== strpos($contentTypeHeader, 'application/json')) { $array = json_decode((string) $response->getBody(), true); if (JSON_ERROR_NONE === json_last_error()) { if (array_key_exists('fault', $array)) { $error['message'] = $array['fault']['faultstring'] ?? null; $error['code'] = $array['fault']['detail']['errorcode'] ?? null; } else { if (array_key_exists('code', $array)) { $error['code'] = $array['code']; } if (array_key_exists('message', $array)) { // It could happen that the returned message by // Apigee Edge is also an array. $error['message'] = is_array($array['message']) ? json_encode($array['message']) : $array['message']; } } } } return $error; }
[ "private", "function", "parseErrorResponse", "(", "ResponseInterface", "$", "response", ")", ":", "array", "{", "$", "error", "=", "[", "'code'", "=>", "null", ",", "'message'", "=>", "null", ",", "]", ";", "// Try to parse Edge error message and error code from the...
Tries to extract Apigee Edge error code and message from a response. @param \Psr\Http\Message\ResponseInterface $response API response. @return array An associative array where keys are "code" and "message" and their values are either string or null.
[ "Tries", "to", "extract", "Apigee", "Edge", "error", "code", "and", "message", "from", "a", "response", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Exception/ApiResponseException.php#L104-L132
apigee/apigee-client-php
src/Api/Monetization/Controller/ApiProductController.php
ApiProductController.getEligibleProducts
private function getEligibleProducts(string $type, string $entityId): array { $products = []; foreach ($this->getRawList($this->client->getUriFactory()->createUri("/mint/organizations/{$this->organization}/{$type}/{$entityId}/eligible-products")) as $item) { /** @var \Apigee\Edge\Api\Monetization\Entity\ApiProductInterface $product */ $product = $this->entitySerializer->denormalize($item, $this->getEntityClass()); $products[$product->id()] = $product; } return $products; }
php
private function getEligibleProducts(string $type, string $entityId): array { $products = []; foreach ($this->getRawList($this->client->getUriFactory()->createUri("/mint/organizations/{$this->organization}/{$type}/{$entityId}/eligible-products")) as $item) { /** @var \Apigee\Edge\Api\Monetization\Entity\ApiProductInterface $product */ $product = $this->entitySerializer->denormalize($item, $this->getEntityClass()); $products[$product->id()] = $product; } return $products; }
[ "private", "function", "getEligibleProducts", "(", "string", "$", "type", ",", "string", "$", "entityId", ")", ":", "array", "{", "$", "products", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getRawList", "(", "$", "this", "->", "client", "-...
Returns eligible products of a developer or a company. @param string $type Either "developers" or "companies". @param string $entityId Id of a developer or company. @return \Apigee\Edge\Api\Monetization\Entity\ApiProductInterface[] List of eligible API products. @psalm-suppress PossiblyNullArrayOffset id() is not null.
[ "Returns", "eligible", "products", "of", "a", "developer", "or", "a", "company", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/ApiProductController.php#L78-L88
apigee/apigee-client-php
src/Api/Management/Normalizer/CompanyMembershipNormalizer.php
CompanyMembershipNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { $normalized = [ 'developer' => [], ]; /** @var \Apigee\Edge\Api\Management\Structure\CompanyMembership $object */ foreach ($object->getMembers() as $member => $role) { $normalized['developer'][] = (object) ['email' => $member, 'role' => $role]; } return (object) $normalized; }
php
public function normalize($object, $format = null, array $context = []) { $normalized = [ 'developer' => [], ]; /** @var \Apigee\Edge\Api\Management\Structure\CompanyMembership $object */ foreach ($object->getMembers() as $member => $role) { $normalized['developer'][] = (object) ['email' => $member, 'role' => $role]; } return (object) $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "normalized", "=", "[", "'developer'", "=>", "[", "]", ",", "]", ";", "/** @var \\Apigee\\Edge\\Api\\Manag...
@inheritdoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Normalizer/CompanyMembershipNormalizer.php#L32-L43
apigee/apigee-client-php
src/Normalizer/PropertiesPropertyNormalizer.php
PropertiesPropertyNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { $return = [ 'property' => parent::normalize($object, $format, $context), ]; return (object) $return; }
php
public function normalize($object, $format = null, array $context = []) { $return = [ 'property' => parent::normalize($object, $format, $context), ]; return (object) $return; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "return", "=", "[", "'property'", "=>", "parent", "::", "normalize", "(", "$", "object", ",", "$", "...
Transforms JSON representation of properties property to compatible with what Edge accepts. @inheritdoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "Transforms", "JSON", "representation", "of", "properties", "property", "to", "compatible", "with", "what", "Edge", "accepts", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Normalizer/PropertiesPropertyNormalizer.php#L36-L43
apigee/apigee-client-php
src/Controller/EntityListingControllerTrait.php
EntityListingControllerTrait.responseArrayToArrayOfEntities
protected function responseArrayToArrayOfEntities(array $responseArray, string $keyGetter = 'id'): array { $entities = []; foreach ($responseArray as $item) { /** @var \Apigee\Edge\Entity\EntityInterface $tmp */ $tmp = $this->getEntitySerializer()->denormalize($item, $this->getEntityClass()); $entities[$tmp->{$keyGetter}()] = $tmp; } return $entities; }
php
protected function responseArrayToArrayOfEntities(array $responseArray, string $keyGetter = 'id'): array { $entities = []; foreach ($responseArray as $item) { /** @var \Apigee\Edge\Entity\EntityInterface $tmp */ $tmp = $this->getEntitySerializer()->denormalize($item, $this->getEntityClass()); $entities[$tmp->{$keyGetter}()] = $tmp; } return $entities; }
[ "protected", "function", "responseArrayToArrayOfEntities", "(", "array", "$", "responseArray", ",", "string", "$", "keyGetter", "=", "'id'", ")", ":", "array", "{", "$", "entities", "=", "[", "]", ";", "foreach", "(", "$", "responseArray", "as", "$", "item",...
Parse an API response array to array of entity objects. @param array $responseArray API response as an array without the entity type key, ex.: developer, apiproduct, etc. @param string $keyGetter Getter method on the entity that should be used as array key. Default is id(). @return \Apigee\Edge\Entity\EntityInterface[] Array of entity objects.
[ "Parse", "an", "API", "response", "array", "to", "array", "of", "entity", "objects", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/EntityListingControllerTrait.php#L42-L53
apigee/apigee-client-php
src/Api/Monetization/Normalizer/LegalEntityNormalizer.php
LegalEntityNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); if ($object instanceof DeveloperInterface) { $normalized->isCompany = false; } elseif ($object instanceof CompanyInterface) { $normalized->isCompany = true; } return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); if ($object instanceof DeveloperInterface) { $normalized->isCompany = false; } elseif ($object instanceof CompanyInterface) { $normalized->isCompany = true; } return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var object $normalized */", "$", "normalized", "=", "parent", "::", "normalize", "(", "$", "object", ",", ...
@inheritDoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/LegalEntityNormalizer.php#L52-L64
apigee/apigee-client-php
src/Api/Monetization/Controller/RatePlanController.php
RatePlanController.createNewRevision
public function createNewRevision(RatePlanRevisionInterface $entity): void { $payload = $this->getEntitySerializer()->serialize($entity, 'json'); $response = $this->getClient()->post($this->getEntityEndpointUri($entity->getPreviousRatePlanRevision()->id()) . '/revision', $payload); $this->getEntitySerializer()->setPropertiesFromResponse($response, $entity); }
php
public function createNewRevision(RatePlanRevisionInterface $entity): void { $payload = $this->getEntitySerializer()->serialize($entity, 'json'); $response = $this->getClient()->post($this->getEntityEndpointUri($entity->getPreviousRatePlanRevision()->id()) . '/revision', $payload); $this->getEntitySerializer()->setPropertiesFromResponse($response, $entity); }
[ "public", "function", "createNewRevision", "(", "RatePlanRevisionInterface", "$", "entity", ")", ":", "void", "{", "$", "payload", "=", "$", "this", "->", "getEntitySerializer", "(", ")", "->", "serialize", "(", "$", "entity", ",", "'json'", ")", ";", "$", ...
@inheritdoc Use RatePlanRevisionBuilder that makes it easier way to create new rate plan revisions. @psalm-suppress PossiblyNullArgument - id is not null in this context.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/RatePlanController.php#L94-L99
apigee/apigee-client-php
src/Normalizer/ObjectNormalizer.php
ObjectNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { $asArray = $this->objectNormalizer->normalize($object, $this->format, $context); // Exclude null values from the output, even if PATCH is not supported on Apigee Edge // sending a smaller portion of data in POST/PUT is always a good practice. $asArray = array_filter($asArray, function ($value) { return !is_null($value); }); ksort($asArray); return (object) $asArray; }
php
public function normalize($object, $format = null, array $context = []) { $asArray = $this->objectNormalizer->normalize($object, $this->format, $context); // Exclude null values from the output, even if PATCH is not supported on Apigee Edge // sending a smaller portion of data in POST/PUT is always a good practice. $asArray = array_filter($asArray, function ($value) { return !is_null($value); }); ksort($asArray); return (object) $asArray; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "asArray", "=", "$", "this", "->", "objectNormalizer", "->", "normalize", "(", "$", "object", ",", "$"...
@inheritdoc @psalm-suppress InvalidReturnType stdClass is also an object. @psalm-suppress PossiblyInvalidArgument First argument of array_filter is always an array.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Normalizer/ObjectNormalizer.php#L96-L107
apigee/apigee-client-php
src/Api/Monetization/Normalizer/RatePlanNormalizer.php
RatePlanNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); // Fix the start- and end date of the rate plan if the organization's // timezone is different from the default PHP timezone. /** @var \Apigee\Edge\Api\Monetization\Entity\RatePlanInterface $object */ if (null === $object->getPackage()) { throw new UninitializedPropertyException($object, 'package', 'Apigee\Edge\Api\Monetization\Entity\ApiPackageInterface'); } if (null === $object->getPackage()->getOrganization()) { throw new UninitializedPropertyException($object->getPackage(), 'organization', 'Apigee\Edge\Api\Monetization\Entity\OrganizationProfileInterface'); } $this->fixTimeZoneOnNormalization($object, $normalized, $object->getPackage()->getOrganization()->getTimezone()); return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); // Fix the start- and end date of the rate plan if the organization's // timezone is different from the default PHP timezone. /** @var \Apigee\Edge\Api\Monetization\Entity\RatePlanInterface $object */ if (null === $object->getPackage()) { throw new UninitializedPropertyException($object, 'package', 'Apigee\Edge\Api\Monetization\Entity\ApiPackageInterface'); } if (null === $object->getPackage()->getOrganization()) { throw new UninitializedPropertyException($object->getPackage(), 'organization', 'Apigee\Edge\Api\Monetization\Entity\OrganizationProfileInterface'); } $this->fixTimeZoneOnNormalization($object, $normalized, $object->getPackage()->getOrganization()->getTimezone()); return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var object $normalized */", "$", "normalized", "=", "parent", "::", "normalize", "(", "$", "object", ",", ...
@inheritDoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/RatePlanNormalizer.php#L54-L73
apigee/apigee-client-php
src/Controller/EntityCreateOperationControllerTrait.php
EntityCreateOperationControllerTrait.buildEntityCreatePayload
protected function buildEntityCreatePayload(EntityInterface $entity, array $context = []): string { return $this->getEntitySerializer()->serialize($entity, 'json', $context); }
php
protected function buildEntityCreatePayload(EntityInterface $entity, array $context = []): string { return $this->getEntitySerializer()->serialize($entity, 'json', $context); }
[ "protected", "function", "buildEntityCreatePayload", "(", "EntityInterface", "$", "entity", ",", "array", "$", "context", "=", "[", "]", ")", ":", "string", "{", "return", "$", "this", "->", "getEntitySerializer", "(", ")", "->", "serialize", "(", "$", "enti...
Serializes the entity to a JSON payload for the request. @param \Apigee\Edge\Entity\EntityInterface $entity Entity to be serialized. @param array $context Context for the serializer. @return string JSON payload for the request.
[ "Serializes", "the", "entity", "to", "a", "JSON", "payload", "for", "the", "request", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/EntityCreateOperationControllerTrait.php#L56-L59
apigee/apigee-client-php
src/Api/Management/Structure/CompanyMembership.php
CompanyMembership.setMember
public function setMember(string $email, ?string $role = null): array { $this->members[$email] = $role; return $this->members; }
php
public function setMember(string $email, ?string $role = null): array { $this->members[$email] = $role; return $this->members; }
[ "public", "function", "setMember", "(", "string", "$", "email", ",", "?", "string", "$", "role", "=", "null", ")", ":", "array", "{", "$", "this", "->", "members", "[", "$", "email", "]", "=", "$", "role", ";", "return", "$", "this", "->", "members...
Add developer or modify developer role in a membership. @param string $email Developer email address. @param string|null $role Developer role. @return array An associate array where developer email addresses are the keys and developer roles are the values. The value can be null if a developer has no role in a company.
[ "Add", "developer", "or", "modify", "developer", "role", "in", "a", "membership", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Structure/CompanyMembership.php#L72-L77
apigee/apigee-client-php
src/Api/Monetization/Denormalizer/RatePlanDenormalizerFactory.php
RatePlanDenormalizerFactory.denormalize
public function denormalize($data, $class, $format = null, array $context = []) { foreach ($this->denormalizers as $denormalizer) { // Return the result from the first denormalizer that can // denormalize this. if ($denormalizer->supportsDenormalization($data, $class, $format)) { return $denormalizer->denormalize($data, $class, $format, $context); } } }
php
public function denormalize($data, $class, $format = null, array $context = []) { foreach ($this->denormalizers as $denormalizer) { // Return the result from the first denormalizer that can // denormalize this. if ($denormalizer->supportsDenormalization($data, $class, $format)) { return $denormalizer->denormalize($data, $class, $format, $context); } } }
[ "public", "function", "denormalize", "(", "$", "data", ",", "$", "class", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "foreach", "(", "$", "this", "->", "denormalizers", "as", "$", "denormalizer", ")", "{",...
@inheritDoc @psalm-suppress InvalidNullableReturnType - There are going to be at least one denormalizer always that can denormalize data here.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Denormalizer/RatePlanDenormalizerFactory.php#L56-L65
apigee/apigee-client-php
src/Normalizer/CredentialProductNormalizer.php
CredentialProductNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /* @var \Apigee\Edge\Structure\CredentialProductInterface $object */ return (object) [ 'apiproduct' => $object->getApiproduct(), 'status' => $object->getStatus(), ]; }
php
public function normalize($object, $format = null, array $context = []) { /* @var \Apigee\Edge\Structure\CredentialProductInterface $object */ return (object) [ 'apiproduct' => $object->getApiproduct(), 'status' => $object->getStatus(), ]; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/* @var \\Apigee\\Edge\\Structure\\CredentialProductInterface $object */", "return", "(", "object", ")", "[", "'apiprodu...
@inheritdoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Normalizer/CredentialProductNormalizer.php#L35-L42
apigee/apigee-client-php
src/Api/Monetization/Normalizer/LegalEntityRatePlanNormalizer.php
LegalEntityRatePlanNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); $normalized->type = RatePlanInterface::TYPE_DEVELOPER; return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); $normalized->type = RatePlanInterface::TYPE_DEVELOPER; return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var object $normalized */", "$", "normalized", "=", "parent", "::", "normalize", "(", "$", "object", ",", ...
@inheritDoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/LegalEntityRatePlanNormalizer.php#L31-L38
apigee/apigee-client-php
src/Api/Monetization/Utility/TimezoneFixerHelperTrait.php
TimezoneFixerHelperTrait.fixTimeZoneOnNormalization
protected function fixTimeZoneOnNormalization($object, $normalized, \DateTimeZone $orgTimezone): void { // Change timezone of all normalized dates to organization's current // timezone if it is different than the default PHP timezone. if (date_default_timezone_get() !== $orgTimezone->getName()) { $ro = new \ReflectionObject($object); // @psalm-suppress required since symfony/serializer >= 4.2.0 // @see https://github.com/symfony/symfony/pull/28709 /** @psalm-suppress InvalidArgument */ $dateDenormalizer = new DateTimeNormalizer(EntityInterface::DATE_FORMAT, $orgTimezone); foreach ($ro->getProperties() as $property) { $property->setAccessible(true); $value = $property->getValue($object); if ($value instanceof \DateTimeImmutable) { $normalized->{$property->getName()} = $dateDenormalizer->normalize($value, \DateTimeImmutable::class); } } } }
php
protected function fixTimeZoneOnNormalization($object, $normalized, \DateTimeZone $orgTimezone): void { // Change timezone of all normalized dates to organization's current // timezone if it is different than the default PHP timezone. if (date_default_timezone_get() !== $orgTimezone->getName()) { $ro = new \ReflectionObject($object); // @psalm-suppress required since symfony/serializer >= 4.2.0 // @see https://github.com/symfony/symfony/pull/28709 /** @psalm-suppress InvalidArgument */ $dateDenormalizer = new DateTimeNormalizer(EntityInterface::DATE_FORMAT, $orgTimezone); foreach ($ro->getProperties() as $property) { $property->setAccessible(true); $value = $property->getValue($object); if ($value instanceof \DateTimeImmutable) { $normalized->{$property->getName()} = $dateDenormalizer->normalize($value, \DateTimeImmutable::class); } } } }
[ "protected", "function", "fixTimeZoneOnNormalization", "(", "$", "object", ",", "$", "normalized", ",", "\\", "DateTimeZone", "$", "orgTimezone", ")", ":", "void", "{", "// Change timezone of all normalized dates to organization's current", "// timezone if it is different than ...
Fixes the timezone of all DateTimeImmutable objects before the entity is being sent to Apigee Edge. It process object properties non-recursively because it gets called on nested object automatically. @param object $object The object that has been normalized. @param $normalized The normalized object. @param \DateTimeZone $orgTimezone Timezone of the organization retrieved from the organization profile.
[ "Fixes", "the", "timezone", "of", "all", "DateTimeImmutable", "objects", "before", "the", "entity", "is", "being", "sent", "to", "Apigee", "Edge", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Utility/TimezoneFixerHelperTrait.php#L43-L61
apigee/apigee-client-php
src/Api/Monetization/Utility/TimezoneFixerHelperTrait.php
TimezoneFixerHelperTrait.fixTimeZoneOnDenormalization
protected function fixTimeZoneOnDenormalization($object, $denormalized, \DateTimeZone $orgTimezone): void { // Change timezone of all date objects to organization's current // timezone if it is different than the default PHP timezone. if (date_default_timezone_get() !== $orgTimezone->getName()) { $ro = new \ReflectionObject($denormalized); // @psalm-suppress required since symfony/serializer >= 4.2.0 // @see https://github.com/symfony/symfony/pull/28709 /** @psalm-suppress InvalidArgument */ $dateDenormalizer = new DateTimeNormalizer(EntityInterface::DATE_FORMAT, $orgTimezone); foreach ($object as $prop_name => $prop_value) { if ($ro->hasProperty($prop_name)) { $property = $ro->getProperty($prop_name); $property->setAccessible(true); $value = $property->getValue($denormalized); if ($value instanceof \DateTimeImmutable) { $property->setValue($denormalized, $dateDenormalizer->denormalize($prop_value, \DateTimeImmutable::class)); } } } } }
php
protected function fixTimeZoneOnDenormalization($object, $denormalized, \DateTimeZone $orgTimezone): void { // Change timezone of all date objects to organization's current // timezone if it is different than the default PHP timezone. if (date_default_timezone_get() !== $orgTimezone->getName()) { $ro = new \ReflectionObject($denormalized); // @psalm-suppress required since symfony/serializer >= 4.2.0 // @see https://github.com/symfony/symfony/pull/28709 /** @psalm-suppress InvalidArgument */ $dateDenormalizer = new DateTimeNormalizer(EntityInterface::DATE_FORMAT, $orgTimezone); foreach ($object as $prop_name => $prop_value) { if ($ro->hasProperty($prop_name)) { $property = $ro->getProperty($prop_name); $property->setAccessible(true); $value = $property->getValue($denormalized); if ($value instanceof \DateTimeImmutable) { $property->setValue($denormalized, $dateDenormalizer->denormalize($prop_value, \DateTimeImmutable::class)); } } } } }
[ "protected", "function", "fixTimeZoneOnDenormalization", "(", "$", "object", ",", "$", "denormalized", ",", "\\", "DateTimeZone", "$", "orgTimezone", ")", ":", "void", "{", "// Change timezone of all date objects to organization's current", "// timezone if it is different than ...
Corrects the timezone on all DateTimeImmutable objects if the organization's current timezone is not the default UTC. It process object properties non-recursively because it gets called on nested object automatically. @param object $object The object that got denormalized. @param object $denormalized The denormalized object. @param \DateTimeZone $orgTimezone Timezone of the organization retrieved from the organization profile.
[ "Corrects", "the", "timezone", "on", "all", "DateTimeImmutable", "objects", "if", "the", "organization", "s", "current", "timezone", "is", "not", "the", "default", "UTC", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Utility/TimezoneFixerHelperTrait.php#L77-L99
apigee/apigee-client-php
src/HttpClient/Plugin/RetryOauthAuthenticationPlugin.php
RetryOauthAuthenticationPlugin.handleRequest
public function handleRequest(RequestInterface $request, callable $next, callable $first) { return $next($request)->then(function (ResponseInterface $response) { return $response; }, function (Exception $exception) use ($request, $next, $first) { if ($exception instanceof OauthAccessTokenAuthenticationException) { // Mark access token as expired and with that ensure that the authentication plugin gets a new // access token. $this->auth->getTokenStorage()->markExpired(); $promise = $first($request); return $promise->wait(); } throw $exception; }); }
php
public function handleRequest(RequestInterface $request, callable $next, callable $first) { return $next($request)->then(function (ResponseInterface $response) { return $response; }, function (Exception $exception) use ($request, $next, $first) { if ($exception instanceof OauthAccessTokenAuthenticationException) { // Mark access token as expired and with that ensure that the authentication plugin gets a new // access token. $this->auth->getTokenStorage()->markExpired(); $promise = $first($request); return $promise->wait(); } throw $exception; }); }
[ "public", "function", "handleRequest", "(", "RequestInterface", "$", "request", ",", "callable", "$", "next", ",", "callable", "$", "first", ")", "{", "return", "$", "next", "(", "$", "request", ")", "->", "then", "(", "function", "(", "ResponseInterface", ...
@inheritdoc @see Oauth::getAccessToken() @psalm-suppress InvalidThrow - Exception with interface can be thrown.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/HttpClient/Plugin/RetryOauthAuthenticationPlugin.php#L55-L71
apigee/apigee-client-php
src/Api/Management/Normalizer/AppCredentialNormalizer.php
AppCredentialNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); // Taking special care of null as a credential's expiresAt property value. // @see \Apigee\Edge\Api\Management\Entity\AppCredential::$expiresAt if (!isset($normalized->expiresAt)) { $normalized->expiresAt = -1; } return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); // Taking special care of null as a credential's expiresAt property value. // @see \Apigee\Edge\Api\Management\Entity\AppCredential::$expiresAt if (!isset($normalized->expiresAt)) { $normalized->expiresAt = -1; } return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var object $normalized */", "$", "normalized", "=", "parent", "::", "normalize", "(", "$", "object", ",", ...
@inheritdoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Normalizer/AppCredentialNormalizer.php#L44-L55
apigee/apigee-client-php
src/Denormalizer/AttributesPropertyDenormalizer.php
AttributesPropertyDenormalizer.denormalize
public function denormalize($data, $class, $format = null, array $context = []) { $flatten = []; foreach ($data as $key => $item) { if (is_object($item)) { // $data came from the EntityNormalizer. $flatten[$item->name] = $item->value; } else { $flatten[$key] = $item; } } $data = $flatten; return parent::denormalize($data, $class, $format, $context); }
php
public function denormalize($data, $class, $format = null, array $context = []) { $flatten = []; foreach ($data as $key => $item) { if (is_object($item)) { // $data came from the EntityNormalizer. $flatten[$item->name] = $item->value; } else { $flatten[$key] = $item; } } $data = $flatten; return parent::denormalize($data, $class, $format, $context); }
[ "public", "function", "denormalize", "(", "$", "data", ",", "$", "class", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "flatten", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "key", ...
Transforms input data to our internal representation. Acceptable inputs: - Edge response format: $data = [{'name' => 'foo', 'value' => 'bar'}, {'name' => 'bar', 'value' => 'baz'}] (from the EntityNormalizer for example) - Internal representation of attributes: ['foo' => 'bar', 'bar' => 'baz'] @inheritdoc
[ "Transforms", "input", "data", "to", "our", "internal", "representation", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Denormalizer/AttributesPropertyDenormalizer.php#L51-L65
apigee/apigee-client-php
src/Utility/ResponseToArrayHelper.php
ResponseToArrayHelper.responseToArray
protected function responseToArray(ResponseInterface $response): array { if ($response->getHeaderLine('Content-Type') && 0 === strpos($response->getHeaderLine('Content-Type'), 'application/json')) { try { return (array) $this->jsonDecoder()->decode((string) $response->getBody(), 'json'); } catch (\UnexpectedValueException $e) { throw new InvalidJsonException( $e->getMessage(), $response, $this->getClient()->getJournal()->getLastRequest() ); } } throw new ApiResponseException( $response, $this->getClient()->getJournal()->getLastRequest(), sprintf('Unable to parse response with %s type. Response body: %s', $response->getHeaderLine('Content-Type') ?: 'unknown', (string) $response->getBody()) ); }
php
protected function responseToArray(ResponseInterface $response): array { if ($response->getHeaderLine('Content-Type') && 0 === strpos($response->getHeaderLine('Content-Type'), 'application/json')) { try { return (array) $this->jsonDecoder()->decode((string) $response->getBody(), 'json'); } catch (\UnexpectedValueException $e) { throw new InvalidJsonException( $e->getMessage(), $response, $this->getClient()->getJournal()->getLastRequest() ); } } throw new ApiResponseException( $response, $this->getClient()->getJournal()->getLastRequest(), sprintf('Unable to parse response with %s type. Response body: %s', $response->getHeaderLine('Content-Type') ?: 'unknown', (string) $response->getBody()) ); }
[ "protected", "function", "responseToArray", "(", "ResponseInterface", "$", "response", ")", ":", "array", "{", "if", "(", "$", "response", "->", "getHeaderLine", "(", "'Content-Type'", ")", "&&", "0", "===", "strpos", "(", "$", "response", "->", "getHeaderLine...
Decodes an Apigee Edge API response to an associative array. The SDK only works with JSON responses, but let's be prepared for the unexpected. @param \Psr\Http\Message\ResponseInterface $response @throws \RuntimeException If response can not be decoded, because the input format is unknown. @throws \Apigee\Edge\Exception\InvalidJsonException If there was an error with decoding a JSON response. @return array
[ "Decodes", "an", "Apigee", "Edge", "API", "response", "to", "an", "associative", "array", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Utility/ResponseToArrayHelper.php#L43-L62
apigee/apigee-client-php
src/Api/Monetization/Denormalizer/RatePlanDenormalizer.php
RatePlanDenormalizer.denormalize
public function denormalize($data, $class, $format = null, array $context = []) { /** @var \Apigee\Edge\Api\Monetization\Entity\RatePlanInterface $entity */ $entity = parent::denormalize($data, $class, $format, $context); $this->fixTimeZoneOnDenormalization($data, $entity, $entity->getOrganization()->getTimezone()); return $entity; }
php
public function denormalize($data, $class, $format = null, array $context = []) { /** @var \Apigee\Edge\Api\Monetization\Entity\RatePlanInterface $entity */ $entity = parent::denormalize($data, $class, $format, $context); $this->fixTimeZoneOnDenormalization($data, $entity, $entity->getOrganization()->getTimezone()); return $entity; }
[ "public", "function", "denormalize", "(", "$", "data", ",", "$", "class", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var \\Apigee\\Edge\\Api\\Monetization\\Entity\\RatePlanInterface $entity */", "$", "entity", "="...
@inheritdoc @psalm-suppress PossiblyNullReference - Organization should not be null here.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Denormalizer/RatePlanDenormalizer.php#L57-L65
apigee/apigee-client-php
src/Api/Monetization/Normalizer/RatePlanNormalizerFactory.php
RatePlanNormalizerFactory.normalize
public function normalize($object, $format = null, array $context = []) { foreach ($this->normalizers as $normalizer) { // Return the result from the first denormalizer that can // denormalize this. if ($normalizer->supportsNormalization($object, $format)) { return $normalizer->normalize($object, $format, $context); } } }
php
public function normalize($object, $format = null, array $context = []) { foreach ($this->normalizers as $normalizer) { // Return the result from the first denormalizer that can // denormalize this. if ($normalizer->supportsNormalization($object, $format)) { return $normalizer->normalize($object, $format, $context); } } }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "foreach", "(", "$", "this", "->", "normalizers", "as", "$", "normalizer", ")", "{", "// Return the result from...
@inheritDoc @psalm-suppress InvalidNullableReturnType - There are going to be at least one normalizer always that can normalize data here.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/RatePlanNormalizerFactory.php#L56-L65
apigee/apigee-client-php
src/PropertyAccess/PropertyAccessorDecorator.php
PropertyAccessorDecorator.processTypeErrorOnGetValue
private static function processTypeErrorOnGetValue($object, string $property, \TypeError $error): void { if (0 !== strpos($error->getMessage(), 'Return value of ')) { return; } $pos = strpos($error->getMessage(), $delim = 'must be of the type ') ?: (strpos($error->getMessage(), $delim = 'must be an instance of ') ?: strpos($error->getMessage(), $delim = 'must implement interface ')); if (false !== $pos) { $ro = new \ReflectionObject($object); $rp = $ro->getProperty($property); $rp->setAccessible(true); $pos += strlen($delim); $actualValue = $rp->getValue($object); $expectedType = substr($error->getMessage(), $pos, (int) strpos($error->getMessage(), ',', $pos) - $pos); if (null === $actualValue) { throw new UninitializedPropertyException($object, $property, $expectedType); } $actualType = \is_object($actualValue) ? \get_class($actualValue) : \gettype($actualValue); // Until we are using strongly typed variables this should not happen. throw new UnexpectedValueException($object, $property, $expectedType, $actualType); } }
php
private static function processTypeErrorOnGetValue($object, string $property, \TypeError $error): void { if (0 !== strpos($error->getMessage(), 'Return value of ')) { return; } $pos = strpos($error->getMessage(), $delim = 'must be of the type ') ?: (strpos($error->getMessage(), $delim = 'must be an instance of ') ?: strpos($error->getMessage(), $delim = 'must implement interface ')); if (false !== $pos) { $ro = new \ReflectionObject($object); $rp = $ro->getProperty($property); $rp->setAccessible(true); $pos += strlen($delim); $actualValue = $rp->getValue($object); $expectedType = substr($error->getMessage(), $pos, (int) strpos($error->getMessage(), ',', $pos) - $pos); if (null === $actualValue) { throw new UninitializedPropertyException($object, $property, $expectedType); } $actualType = \is_object($actualValue) ? \get_class($actualValue) : \gettype($actualValue); // Until we are using strongly typed variables this should not happen. throw new UnexpectedValueException($object, $property, $expectedType, $actualType); } }
[ "private", "static", "function", "processTypeErrorOnGetValue", "(", "$", "object", ",", "string", "$", "property", ",", "\\", "TypeError", "$", "error", ")", ":", "void", "{", "if", "(", "0", "!==", "strpos", "(", "$", "error", "->", "getMessage", "(", "...
Processes type error exception on value get. Throws better, more meaningful exception if a value is uninitialised or initialized with an incorrect value on an object. Based on PropertyAccessor::throwInvalidArgumentException(). @param object $object @param string $property @param \TypeError $error @see \Symfony\Component\PropertyAccess\PropertyAccessor::throwInvalidArgumentException()
[ "Processes", "type", "error", "exception", "on", "value", "get", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/PropertyAccess/PropertyAccessorDecorator.php#L134-L158
apigee/apigee-client-php
src/PropertyAccess/PropertyAccessorDecorator.php
PropertyAccessorDecorator.processTypeErrorOnSetValue
private static function processTypeErrorOnSetValue($message, $trace, $i): void { if (0 !== strpos($message, 'Argument ')) { return; } if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && array_key_exists(0, $trace[$i]['args'])) { $pos = strpos($message, $delim = 'must be of the type ') ?: (strpos($message, $delim = 'must be an instance of ') ?: strpos($message, $delim = 'must implement interface ')); if (false !== $pos) { $pos += \strlen($delim); $type = $trace[$i]['args'][0]; $type = \is_object($type) ? \get_class($type) : \gettype($type); throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given.', substr($message, $pos, (int) strpos($message, ',', $pos) - $pos), $type)); } } }
php
private static function processTypeErrorOnSetValue($message, $trace, $i): void { if (0 !== strpos($message, 'Argument ')) { return; } if (isset($trace[$i]['file']) && __FILE__ === $trace[$i]['file'] && array_key_exists(0, $trace[$i]['args'])) { $pos = strpos($message, $delim = 'must be of the type ') ?: (strpos($message, $delim = 'must be an instance of ') ?: strpos($message, $delim = 'must implement interface ')); if (false !== $pos) { $pos += \strlen($delim); $type = $trace[$i]['args'][0]; $type = \is_object($type) ? \get_class($type) : \gettype($type); throw new InvalidArgumentException(sprintf('Expected argument of type "%s", "%s" given.', substr($message, $pos, (int) strpos($message, ',', $pos) - $pos), $type)); } } }
[ "private", "static", "function", "processTypeErrorOnSetValue", "(", "$", "message", ",", "$", "trace", ",", "$", "i", ")", ":", "void", "{", "if", "(", "0", "!==", "strpos", "(", "$", "message", ",", "'Argument '", ")", ")", "{", "return", ";", "}", ...
Processes type error exception on value set. Copy-paste of PropertyAccessor::throwInvalidArgumentException() because it is private. @param $message @param $trace @param $i @see \Symfony\Component\PropertyAccess\PropertyAccessor::throwInvalidArgumentException()
[ "Processes", "type", "error", "exception", "on", "value", "set", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/PropertyAccess/PropertyAccessorDecorator.php#L172-L188
apigee/apigee-client-php
src/Api/Monetization/Controller/AcceptedRatePlanController.php
AcceptedRatePlanController.updateSubscription
public function updateSubscription(AcceptedRatePlanInterface $acceptedRatePlan, ?bool $suppressWarning = null, ?bool $waveTerminationCharge = null): void { $payload = $this->getEntitySerializer()->serialize($acceptedRatePlan, 'json', $this->buildContextForEntityTransformerInCreate()); $tmp = json_decode($payload, true); if (null !== $suppressWarning) { $tmp['suppressWarning'] = $suppressWarning ? 'true' : 'false'; } if (null !== $waveTerminationCharge) { $tmp['waveTerminationCharge'] = $waveTerminationCharge ? 'true' : 'false'; } $this->alterRequestPayload($tmp, $acceptedRatePlan); $payload = json_encode($tmp); // Update an existing entity. $response = $this->client->put($this->getEntityEndpointUri($acceptedRatePlan->id()), $payload); $this->getEntitySerializer()->setPropertiesFromResponse($response, $acceptedRatePlan); }
php
public function updateSubscription(AcceptedRatePlanInterface $acceptedRatePlan, ?bool $suppressWarning = null, ?bool $waveTerminationCharge = null): void { $payload = $this->getEntitySerializer()->serialize($acceptedRatePlan, 'json', $this->buildContextForEntityTransformerInCreate()); $tmp = json_decode($payload, true); if (null !== $suppressWarning) { $tmp['suppressWarning'] = $suppressWarning ? 'true' : 'false'; } if (null !== $waveTerminationCharge) { $tmp['waveTerminationCharge'] = $waveTerminationCharge ? 'true' : 'false'; } $this->alterRequestPayload($tmp, $acceptedRatePlan); $payload = json_encode($tmp); // Update an existing entity. $response = $this->client->put($this->getEntityEndpointUri($acceptedRatePlan->id()), $payload); $this->getEntitySerializer()->setPropertiesFromResponse($response, $acceptedRatePlan); }
[ "public", "function", "updateSubscription", "(", "AcceptedRatePlanInterface", "$", "acceptedRatePlan", ",", "?", "bool", "$", "suppressWarning", "=", "null", ",", "?", "bool", "$", "waveTerminationCharge", "=", "null", ")", ":", "void", "{", "$", "payload", "=",...
@inheritDoc @psalm-suppress PossiblyNullArgument - id is not null in this context.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/AcceptedRatePlanController.php#L114-L129
apigee/apigee-client-php
src/Api/Monetization/Controller/AcceptedRatePlanController.php
AcceptedRatePlanController.getAcceptedRatePlans
private function getAcceptedRatePlans(array $query_params = []): array { $entities = []; foreach ($this->getRawList($this->getAcceptedRatePlansEndpoint()->withQuery(http_build_query($query_params))) as $item) { /** @var \Apigee\Edge\Entity\EntityInterface $tmp */ $tmp = $this->getEntitySerializer()->denormalize( $item, AcceptedRatePlanInterface::class, 'json' ); $entities[$tmp->id()] = $tmp; } return $entities; }
php
private function getAcceptedRatePlans(array $query_params = []): array { $entities = []; foreach ($this->getRawList($this->getAcceptedRatePlansEndpoint()->withQuery(http_build_query($query_params))) as $item) { /** @var \Apigee\Edge\Entity\EntityInterface $tmp */ $tmp = $this->getEntitySerializer()->denormalize( $item, AcceptedRatePlanInterface::class, 'json' ); $entities[$tmp->id()] = $tmp; } return $entities; }
[ "private", "function", "getAcceptedRatePlans", "(", "array", "$", "query_params", "=", "[", "]", ")", ":", "array", "{", "$", "entities", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getRawList", "(", "$", "this", "->", "getAcceptedRatePlansEndp...
Helper function for listing accepted rate plans. @param array $query_params Additional query parameters. @return \Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface[] @psalm-suppress PossiblyNullArrayOffset - id() does not return null here.
[ "Helper", "function", "for", "listing", "accepted", "rate", "plans", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/AcceptedRatePlanController.php#L171-L186
apigee/apigee-client-php
src/Api/Monetization/Normalizer/CompanyPaymentTransactionNormalizer.php
CompanyPaymentTransactionNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); $normalized->developer->isCompany = true; return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); $normalized->developer->isCompany = true; return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var object $normalized */", "$", "normalized", "=", "parent", "::", "normalize", "(", "$", "object", ",", ...
@inheritDoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/CompanyPaymentTransactionNormalizer.php#L50-L57
apigee/apigee-client-php
src/Denormalizer/EdgeDateDenormalizer.php
EdgeDateDenormalizer.denormalize
public function denormalize($data, $class, $format = null, array $context = []) { // Handle -1 in expiresAt property of AppCredential. if ($data < 0) { return null; } $context[$this->normalizer::FORMAT_KEY] = 'U'; $context[$this->normalizer::TIMEZONE_KEY] = new \DateTimeZone('UTC'); return $this->normalizer->denormalize(intval($data / 1000), $class, $format, $context); }
php
public function denormalize($data, $class, $format = null, array $context = []) { // Handle -1 in expiresAt property of AppCredential. if ($data < 0) { return null; } $context[$this->normalizer::FORMAT_KEY] = 'U'; $context[$this->normalizer::TIMEZONE_KEY] = new \DateTimeZone('UTC'); return $this->normalizer->denormalize(intval($data / 1000), $class, $format, $context); }
[ "public", "function", "denormalize", "(", "$", "data", ",", "$", "class", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "// Handle -1 in expiresAt property of AppCredential.", "if", "(", "$", "data", "<", "0", ")",...
@inheritdoc @return object|null @psalm-suppress ImplementedReturnTypeMismatch - We have to return null, even if it not officially supported by the overridden class.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Denormalizer/EdgeDateDenormalizer.php#L54-L64
apigee/apigee-client-php
src/Controller/EntityUpdateOperationControllerTrait.php
EntityUpdateOperationControllerTrait.update
public function update(EntityInterface $entity): void { $uri = $this->getEntityEndpointUri($entity->id()); $response = $this->getClient()->put( $uri, $this->getEntitySerializer()->serialize($entity, 'json') ); $this->getEntitySerializer()->setPropertiesFromResponse($response, $entity); }
php
public function update(EntityInterface $entity): void { $uri = $this->getEntityEndpointUri($entity->id()); $response = $this->getClient()->put( $uri, $this->getEntitySerializer()->serialize($entity, 'json') ); $this->getEntitySerializer()->setPropertiesFromResponse($response, $entity); }
[ "public", "function", "update", "(", "EntityInterface", "$", "entity", ")", ":", "void", "{", "$", "uri", "=", "$", "this", "->", "getEntityEndpointUri", "(", "$", "entity", "->", "id", "(", ")", ")", ";", "$", "response", "=", "$", "this", "->", "ge...
@inheritdoc @psalm-suppress PossiblyNullArgument $entity->id() is not null here.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/EntityUpdateOperationControllerTrait.php#L39-L47
apigee/apigee-client-php
src/HttpClient/Plugin/Authentication/Oauth.php
Oauth.authClient
protected function authClient(): ClientInterface { return new Client(new BasicAuth($this->clientId, $this->clientSecret), $this->auth_server); }
php
protected function authClient(): ClientInterface { return new Client(new BasicAuth($this->clientId, $this->clientSecret), $this->auth_server); }
[ "protected", "function", "authClient", "(", ")", ":", "ClientInterface", "{", "return", "new", "Client", "(", "new", "BasicAuth", "(", "$", "this", "->", "clientId", ",", "$", "this", "->", "clientSecret", ")", ",", "$", "this", "->", "auth_server", ")", ...
Returns a pre-configured client for authorization API calls. @return \Apigee\Edge\ClientInterface
[ "Returns", "a", "pre", "-", "configured", "client", "for", "authorization", "API", "calls", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/HttpClient/Plugin/Authentication/Oauth.php#L151-L154
apigee/apigee-client-php
src/HttpClient/Plugin/Authentication/Oauth.php
Oauth.getAccessToken
private function getAccessToken(): void { if ($this->tokenStorage->getRefreshToken()) { $body = [ 'grant_type' => 'refresh_token', 'refresh_token' => $this->tokenStorage->getRefreshToken(), ]; } else { $body = [ 'grant_type' => 'password', 'username' => $this->username, 'password' => $this->password, ]; if (!empty($this->mfaToken)) { $body['mfa_token'] = $this->mfaToken; } if (!empty($this->scope)) { $body['scope'] = $this->scope; } } try { $response = $this->authClient()->post('', http_build_query($body), ['Content-Type' => 'application/x-www-form-urlencoded']); $this->tokenStorage->saveToken(json_decode((string) $response->getBody(), true)); } catch (OauthRefreshTokenExpiredException $e) { // Clear data in token storage because refresh token has expired. $this->tokenStorage->removeToken(); // Try to automatically get a new access token by sending client // id and secret. $this->getAccessToken(); } catch (Exception $e) { throw new OauthAuthenticationException($e->getMessage(), $e->getCode(), $e); } }
php
private function getAccessToken(): void { if ($this->tokenStorage->getRefreshToken()) { $body = [ 'grant_type' => 'refresh_token', 'refresh_token' => $this->tokenStorage->getRefreshToken(), ]; } else { $body = [ 'grant_type' => 'password', 'username' => $this->username, 'password' => $this->password, ]; if (!empty($this->mfaToken)) { $body['mfa_token'] = $this->mfaToken; } if (!empty($this->scope)) { $body['scope'] = $this->scope; } } try { $response = $this->authClient()->post('', http_build_query($body), ['Content-Type' => 'application/x-www-form-urlencoded']); $this->tokenStorage->saveToken(json_decode((string) $response->getBody(), true)); } catch (OauthRefreshTokenExpiredException $e) { // Clear data in token storage because refresh token has expired. $this->tokenStorage->removeToken(); // Try to automatically get a new access token by sending client // id and secret. $this->getAccessToken(); } catch (Exception $e) { throw new OauthAuthenticationException($e->getMessage(), $e->getCode(), $e); } }
[ "private", "function", "getAccessToken", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "tokenStorage", "->", "getRefreshToken", "(", ")", ")", "{", "$", "body", "=", "[", "'grant_type'", "=>", "'refresh_token'", ",", "'refresh_token'", "=>", "$...
Retrieves access token and saves it to the token storage. @psalm-suppress InvalidCatch - Exception by interface can be caught in PHP >= 7.1.
[ "Retrieves", "access", "token", "and", "saves", "it", "to", "the", "token", "storage", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/HttpClient/Plugin/Authentication/Oauth.php#L161-L194
apigee/apigee-client-php
src/Api/Monetization/Denormalizer/AcceptedRatePlanDenormalizer.php
AcceptedRatePlanDenormalizer.denormalize
public function denormalize($data, $class, $format = null, array $context = []) { /** @var \Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface $denormalized */ $denormalized = parent::denormalize($data, $class, $format, $context); $this->fixTimeZoneOnDenormalization($data, $denormalized, $denormalized->getRatePlan()->getPackage()->getOrganization()->getTimezone()); return $denormalized; }
php
public function denormalize($data, $class, $format = null, array $context = []) { /** @var \Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface $denormalized */ $denormalized = parent::denormalize($data, $class, $format, $context); $this->fixTimeZoneOnDenormalization($data, $denormalized, $denormalized->getRatePlan()->getPackage()->getOrganization()->getTimezone()); return $denormalized; }
[ "public", "function", "denormalize", "(", "$", "data", ",", "$", "class", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var \\Apigee\\Edge\\Api\\Monetization\\Entity\\AcceptedRatePlanInterface $denormalized */", "$", "...
@inheritDoc @psalm-suppress PossiblyNullReference - getPackage() can only return null when a rate plan is created. It does not return null here.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Denormalizer/AcceptedRatePlanDenormalizer.php#L35-L43
apigee/apigee-client-php
src/Api/Monetization/Normalizer/EntityNormalizer.php
EntityNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { $normalized = (array) parent::normalize($object, $format, $context); $entityReferenceProperties = $this->getNestedObjectProperties($object); if (!empty($entityReferenceProperties)) { foreach ($entityReferenceProperties as $entityProperty => $normalizedProperty) { // Ensure we do not send the complete referenced entity object // only the referenced entity id. if (isset($normalized[$normalizedProperty]->id)) { $normalized[$normalizedProperty] = [ 'id' => $normalized[$normalizedProperty]->id, ]; } } } // Set missing ids of referenced entities passed by controllers. // Ex.: in case of entity create. // @see \Apigee\Edge\Api\Monetization\Controller\EntityCreateOperationControllerTrait::buildContextForEntityTransformerInCreate() if (!empty($context[self::MINT_ENTITY_REFERENCE_PROPERTY_VALUES])) { foreach ($context[self::MINT_ENTITY_REFERENCE_PROPERTY_VALUES] as $entityProperty => $value) { if (!isset($normalized[$entityProperty]['id'])) { $normalized[$entityProperty] = [ 'id' => $value, ]; } } } return (object) $normalized; }
php
public function normalize($object, $format = null, array $context = []) { $normalized = (array) parent::normalize($object, $format, $context); $entityReferenceProperties = $this->getNestedObjectProperties($object); if (!empty($entityReferenceProperties)) { foreach ($entityReferenceProperties as $entityProperty => $normalizedProperty) { // Ensure we do not send the complete referenced entity object // only the referenced entity id. if (isset($normalized[$normalizedProperty]->id)) { $normalized[$normalizedProperty] = [ 'id' => $normalized[$normalizedProperty]->id, ]; } } } // Set missing ids of referenced entities passed by controllers. // Ex.: in case of entity create. // @see \Apigee\Edge\Api\Monetization\Controller\EntityCreateOperationControllerTrait::buildContextForEntityTransformerInCreate() if (!empty($context[self::MINT_ENTITY_REFERENCE_PROPERTY_VALUES])) { foreach ($context[self::MINT_ENTITY_REFERENCE_PROPERTY_VALUES] as $entityProperty => $value) { if (!isset($normalized[$entityProperty]['id'])) { $normalized[$entityProperty] = [ 'id' => $value, ]; } } } return (object) $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "normalized", "=", "(", "array", ")", "parent", "::", "normalize", "(", "$", "object", ",", "$", "fo...
@inheritdoc @psalm-suppress InvalidReturnType stdClass is also an object.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/EntityNormalizer.php#L64-L96
apigee/apigee-client-php
src/Api/Monetization/Normalizer/EntityNormalizer.php
EntityNormalizer.getNestedObjectProperties
protected function getNestedObjectProperties($object): array { $entityReferenceProperties = []; $ro = new \ReflectionObject($object); foreach ($ro->getProperties() as $property) { $property->setAccessible(true); $value = $property->getValue($object); if (is_object($value) && $value instanceof NestedObjectReferenceInterface) { if ($this->nameConverter) { $normalizedPropertyName = $this->nameConverter->normalize($property->getName()); } else { $normalizedPropertyName = $property->getName(); } $entityReferenceProperties[$property->getName()] = $normalizedPropertyName; } } return $entityReferenceProperties; }
php
protected function getNestedObjectProperties($object): array { $entityReferenceProperties = []; $ro = new \ReflectionObject($object); foreach ($ro->getProperties() as $property) { $property->setAccessible(true); $value = $property->getValue($object); if (is_object($value) && $value instanceof NestedObjectReferenceInterface) { if ($this->nameConverter) { $normalizedPropertyName = $this->nameConverter->normalize($property->getName()); } else { $normalizedPropertyName = $property->getName(); } $entityReferenceProperties[$property->getName()] = $normalizedPropertyName; } } return $entityReferenceProperties; }
[ "protected", "function", "getNestedObjectProperties", "(", "$", "object", ")", ":", "array", "{", "$", "entityReferenceProperties", "=", "[", "]", ";", "$", "ro", "=", "new", "\\", "ReflectionObject", "(", "$", "object", ")", ";", "foreach", "(", "$", "ro"...
Returns a list of properties on an object that contain references (nested objects) to another objects. In case of these properties there is no need to send the complete nested object to the Monetization API when a new entity is created or updated, it is enough to send only the id of the referenced object. (Sending the id of the referenced object is required.) It does not support array object properties, those should be handled in child classes. @param object $object @return array An associative array of properties that contain nested object references. Array keys are the (internal) property names on an object and values are the normalized (external) property names that should be sent to Apigee Edge.
[ "Returns", "a", "list", "of", "properties", "on", "an", "object", "that", "contain", "references", "(", "nested", "objects", ")", "to", "another", "objects", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/EntityNormalizer.php#L119-L137
apigee/apigee-client-php
src/Api/Management/Controller/AttributesAwareEntityControllerTrait.php
AttributesAwareEntityControllerTrait.getEntityAttributesUri
protected function getEntityAttributesUri(string $entityId): UriInterface { $uri = $this->getEntityEndpointUri($entityId)->withPath( $this->getEntityEndpointUri($entityId) . '/attributes' ); return $uri; }
php
protected function getEntityAttributesUri(string $entityId): UriInterface { $uri = $this->getEntityEndpointUri($entityId)->withPath( $this->getEntityEndpointUri($entityId) . '/attributes' ); return $uri; }
[ "protected", "function", "getEntityAttributesUri", "(", "string", "$", "entityId", ")", ":", "UriInterface", "{", "$", "uri", "=", "$", "this", "->", "getEntityEndpointUri", "(", "$", "entityId", ")", "->", "withPath", "(", "$", "this", "->", "getEntityEndpoin...
Returns the base URI of an entity type's attributes. @param string $entityId @return UriInterface
[ "Returns", "the", "base", "URI", "of", "an", "entity", "type", "s", "attributes", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/AttributesAwareEntityControllerTrait.php#L114-L121
apigee/apigee-client-php
src/Api/Management/Controller/AttributesAwareEntityControllerTrait.php
AttributesAwareEntityControllerTrait.getEntityAttributeUri
protected function getEntityAttributeUri(string $entityId, string $name): UriInterface { $uri = $this->getEntityAttributesUri($entityId)->withPath( $this->getEntityAttributesUri($entityId) . '/' . $name ); return $uri; }
php
protected function getEntityAttributeUri(string $entityId, string $name): UriInterface { $uri = $this->getEntityAttributesUri($entityId)->withPath( $this->getEntityAttributesUri($entityId) . '/' . $name ); return $uri; }
[ "protected", "function", "getEntityAttributeUri", "(", "string", "$", "entityId", ",", "string", "$", "name", ")", ":", "UriInterface", "{", "$", "uri", "=", "$", "this", "->", "getEntityAttributesUri", "(", "$", "entityId", ")", "->", "withPath", "(", "$", ...
Returns an URI to an entity's attribute. @param string $entityId @param string $name @return UriInterface
[ "Returns", "an", "URI", "to", "an", "entity", "s", "attribute", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/AttributesAwareEntityControllerTrait.php#L131-L138
apigee/apigee-client-php
src/Api/Monetization/Normalizer/RatePlanRateNormalizer.php
RatePlanRateNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); if ($object instanceof RatePlanRateRevShare) { $normalized->type = RatePlanRate::TYPE_REVSHARE; } else { $normalized->type = RatePlanRate::TYPE_RATECARD; } return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); if ($object instanceof RatePlanRateRevShare) { $normalized->type = RatePlanRate::TYPE_REVSHARE; } else { $normalized->type = RatePlanRate::TYPE_RATECARD; } return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var object $normalized */", "$", "normalized", "=", "parent", "::", "normalize", "(", "$", "object", ",", ...
@inheritDoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/RatePlanRateNormalizer.php#L33-L44
apigee/apigee-client-php
src/HttpClient/Utility/Journal.php
Journal.addSuccess
public function addSuccess(RequestInterface $request, ResponseInterface $response): void { $this->lastRequest = $request; $this->lastResponse = $response; $this->success = true; }
php
public function addSuccess(RequestInterface $request, ResponseInterface $response): void { $this->lastRequest = $request; $this->lastResponse = $response; $this->success = true; }
[ "public", "function", "addSuccess", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", ":", "void", "{", "$", "this", "->", "lastRequest", "=", "$", "request", ";", "$", "this", "->", "lastResponse", "=", "$", "response"...
Record a successful call. @param \Psr\Http\Message\RequestInterface $request Request use to make the call @param \Psr\Http\Message\ResponseInterface $response Response returned by the call
[ "Record", "a", "successful", "call", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/HttpClient/Utility/Journal.php#L58-L63
apigee/apigee-client-php
src/HttpClient/Utility/Journal.php
Journal.addFailure
public function addFailure(RequestInterface $request, Exception $exception): void { $this->lastRequest = $request; $this->lastException = $exception; }
php
public function addFailure(RequestInterface $request, Exception $exception): void { $this->lastRequest = $request; $this->lastException = $exception; }
[ "public", "function", "addFailure", "(", "RequestInterface", "$", "request", ",", "Exception", "$", "exception", ")", ":", "void", "{", "$", "this", "->", "lastRequest", "=", "$", "request", ";", "$", "this", "->", "lastException", "=", "$", "exception", "...
Record a failed call. @param \Psr\Http\Message\RequestInterface $request Request use to make the call @param \Http\Client\Exception $exception Exception returned by the call
[ "Record", "a", "failed", "call", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/HttpClient/Utility/Journal.php#L71-L75
apigee/apigee-client-php
src/Api/Monetization/Normalizer/ApiPackageNormalizer.php
ApiPackageNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { $normalized = (array) parent::normalize($object, $format, $context); // Do not send redundant API product information to Apigee Edge, the // id of a referenced API product is enough. foreach ($normalized['product'] as $id => $data) { $normalized['product'][$id] = (object) ['id' => $data->id]; } return (object) $normalized; }
php
public function normalize($object, $format = null, array $context = []) { $normalized = (array) parent::normalize($object, $format, $context); // Do not send redundant API product information to Apigee Edge, the // id of a referenced API product is enough. foreach ($normalized['product'] as $id => $data) { $normalized['product'][$id] = (object) ['id' => $data->id]; } return (object) $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "$", "normalized", "=", "(", "array", ")", "parent", "::", "normalize", "(", "$", "object", ",", "$", "fo...
@inheritDoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/ApiPackageNormalizer.php#L50-L61
apigee/apigee-client-php
src/Api/Management/Controller/StatsController.php
StatsController.getMetrics
public function getMetrics(StatsQueryInterface $query, ?string $optimized = 'js'): array { $query_params = [ '_optimized' => $optimized, ] + $this->normalizer->normalize($query); $uri = $this->getBaseEndpointUri()->withQuery(http_build_query($query_params)); $response = $this->responseToArray($this->client->get($uri)); return $response['Response']; }
php
public function getMetrics(StatsQueryInterface $query, ?string $optimized = 'js'): array { $query_params = [ '_optimized' => $optimized, ] + $this->normalizer->normalize($query); $uri = $this->getBaseEndpointUri()->withQuery(http_build_query($query_params)); $response = $this->responseToArray($this->client->get($uri)); return $response['Response']; }
[ "public", "function", "getMetrics", "(", "StatsQueryInterface", "$", "query", ",", "?", "string", "$", "optimized", "=", "'js'", ")", ":", "array", "{", "$", "query_params", "=", "[", "'_optimized'", "=>", "$", "optimized", ",", "]", "+", "$", "this", "-...
@inheritdoc @psalm-suppress InvalidOperand - $this->normalizer->normalize() always returns an array.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/StatsController.php#L78-L87
apigee/apigee-client-php
src/Api/Management/Controller/StatsController.php
StatsController.getOptimisedMetrics
public function getOptimisedMetrics(StatsQueryInterface $query): array { $response = $this->getMetrics($query, 'js'); // If no analytics data returned for a given criteria just return. if (empty($response['stats'])) { return $response; } if (null !== $query->getTimeUnit()) { $originalTimeUnits = $response['TimeUnit']; $response['TimeUnit'] = $this->fillGapsInTimeUnitsData( $query->getTimeRange(), $query->getTimeUnit(), $query->getTsAscending() ); $this->fillGapsInMetricsData( $query->getTsAscending(), $response['TimeUnit'], $originalTimeUnits, $response['stats']['data'] ); } return $response; }
php
public function getOptimisedMetrics(StatsQueryInterface $query): array { $response = $this->getMetrics($query, 'js'); // If no analytics data returned for a given criteria just return. if (empty($response['stats'])) { return $response; } if (null !== $query->getTimeUnit()) { $originalTimeUnits = $response['TimeUnit']; $response['TimeUnit'] = $this->fillGapsInTimeUnitsData( $query->getTimeRange(), $query->getTimeUnit(), $query->getTsAscending() ); $this->fillGapsInMetricsData( $query->getTsAscending(), $response['TimeUnit'], $originalTimeUnits, $response['stats']['data'] ); } return $response; }
[ "public", "function", "getOptimisedMetrics", "(", "StatsQueryInterface", "$", "query", ")", ":", "array", "{", "$", "response", "=", "$", "this", "->", "getMetrics", "(", "$", "query", ",", "'js'", ")", ";", "// If no analytics data returned for a given criteria jus...
Gets API message count. The additional optimization on the returned data happens in the SDK. The SDK fills the gaps between returned time units and analytics numbers in the returned response of Apigee Edge. If no analytics data returned for a given criteria it does not fill in results with zeros, it just returns the original response. (This method also asks optimized response from Apigee Edge too.) @param StatsQueryInterface $query Stats query object. @throws \Moment\MomentException @throws \InvalidArgumentException Find more information in fillGapsInTimeUnitsData() method. @return array Response as associative array. @psalm-suppress PossiblyNullArgument - $query->getTimeUnit() is not null.
[ "Gets", "API", "message", "count", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/StatsController.php#L109-L132
apigee/apigee-client-php
src/Api/Management/Controller/StatsController.php
StatsController.getMetricsByDimensions
public function getMetricsByDimensions(array $dimensions, StatsQueryInterface $query, ?string $optimized = 'js'): array { $query_params = [ '_optimized' => $optimized, ] + $this->normalizer->normalize($query); $path = $this->getBaseEndpointUri()->getPath() . implode(',', $dimensions); $uri = $this->getBaseEndpointUri()->withPath($path) ->withQuery(http_build_query($query_params)); $response = $this->responseToArray($this->client->get($uri)); return $response['Response']; }
php
public function getMetricsByDimensions(array $dimensions, StatsQueryInterface $query, ?string $optimized = 'js'): array { $query_params = [ '_optimized' => $optimized, ] + $this->normalizer->normalize($query); $path = $this->getBaseEndpointUri()->getPath() . implode(',', $dimensions); $uri = $this->getBaseEndpointUri()->withPath($path) ->withQuery(http_build_query($query_params)); $response = $this->responseToArray($this->client->get($uri)); return $response['Response']; }
[ "public", "function", "getMetricsByDimensions", "(", "array", "$", "dimensions", ",", "StatsQueryInterface", "$", "query", ",", "?", "string", "$", "optimized", "=", "'js'", ")", ":", "array", "{", "$", "query_params", "=", "[", "'_optimized'", "=>", "$", "o...
@inheritdoc @psalm-suppress InvalidOperand - $this->normalizer->normalize() always returns an array.
[ "@inheritdoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/StatsController.php#L139-L150
apigee/apigee-client-php
src/Api/Management/Controller/StatsController.php
StatsController.getOptimizedMetricsByDimensions
public function getOptimizedMetricsByDimensions(array $dimensions, StatsQueryInterface $query): array { $response = $this->getMetricsByDimensions($dimensions, $query, 'js'); // If no analytics data returned for a given criteria just return. if (empty($response['stats'])) { return $response; } if (null !== $query->getTimeUnit()) { $originalTimeUnits = $response['TimeUnit']; $response['TimeUnit'] = $this->fillGapsInTimeUnitsData( $query->getTimeRange(), $query->getTimeUnit(), $query->getTsAscending() ); foreach ($response['stats']['data'] as $key => $dimension) { $this->fillGapsInMetricsData( $query->getTsAscending(), $response['TimeUnit'], $originalTimeUnits, $response['stats']['data'][$key]['metric'] ); } } return $response; }
php
public function getOptimizedMetricsByDimensions(array $dimensions, StatsQueryInterface $query): array { $response = $this->getMetricsByDimensions($dimensions, $query, 'js'); // If no analytics data returned for a given criteria just return. if (empty($response['stats'])) { return $response; } if (null !== $query->getTimeUnit()) { $originalTimeUnits = $response['TimeUnit']; $response['TimeUnit'] = $this->fillGapsInTimeUnitsData( $query->getTimeRange(), $query->getTimeUnit(), $query->getTsAscending() ); foreach ($response['stats']['data'] as $key => $dimension) { $this->fillGapsInMetricsData( $query->getTsAscending(), $response['TimeUnit'], $originalTimeUnits, $response['stats']['data'][$key]['metric'] ); } } return $response; }
[ "public", "function", "getOptimizedMetricsByDimensions", "(", "array", "$", "dimensions", ",", "StatsQueryInterface", "$", "query", ")", ":", "array", "{", "$", "response", "=", "$", "this", "->", "getMetricsByDimensions", "(", "$", "dimensions", ",", "$", "quer...
Gets optimized metrics organized by dimensions. The additional optimization on the returned data happens in the SDK. The SDK fills the gaps between time units and analytics numbers in the returned response of Apigee Edge. If no analytics data returned for a given criteria it does not fill in results with zeros, it just returns the original response. (This method also asks optimized response from Apigee Edge too.) @param array $dimensions Array of dimensions. @param StatsQueryInterface $query Stats query object. @throws \Moment\MomentException @throws \InvalidArgumentException Find more information in fillGapsInTimeUnitsData() method. @return array Response as associative array. @psalm-suppress PossiblyNullArgument - $query->getTimeUnit() is not null.
[ "Gets", "optimized", "metrics", "organized", "by", "dimensions", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/StatsController.php#L174-L199
apigee/apigee-client-php
src/Api/Management/Controller/StatsController.php
StatsController.fillGapsInTimeUnitsData
private function fillGapsInTimeUnitsData(Period $period, string $timeUnit, bool $tsAscending) { // Moment library does not validate time units that being passed just falls back to the default behavior // automatically. We do want to let this library's users know that they have provided an invalid time // unit to this function and they should rather use the "non-optimized" methods from the controller for // retrieving data for these time periods. if (in_array($timeUnit, ['decade', 'century', 'millennium'])) { throw new \InvalidArgumentException("The {$timeUnit} time unit is not supported by the https://github.com/fightbulc/moment.php library."); } $allTimeUnits = []; // Fix time unit for correct time interval calculation. $startDate = new Moment('@' . $period->getStartDate()->getTimestamp()); $endDate = new Moment('@' . $period->getEndDate()->getTimestamp()); // Returned intervals by Apigee Edge are always inclusive-inclusive. $startDate->startOf($timeUnit); $endDate->endOf($timeUnit); $period = new Period($startDate, $endDate); $timeUnit = '1 ' . $timeUnit; /** @var \DateTime $dateTime */ foreach ($period->getDatePeriod($timeUnit) as $dateTime) { $allTimeUnits[] = $dateTime->getTimestamp() * 1000; } return $tsAscending ? $allTimeUnits : array_reverse($allTimeUnits); }
php
private function fillGapsInTimeUnitsData(Period $period, string $timeUnit, bool $tsAscending) { // Moment library does not validate time units that being passed just falls back to the default behavior // automatically. We do want to let this library's users know that they have provided an invalid time // unit to this function and they should rather use the "non-optimized" methods from the controller for // retrieving data for these time periods. if (in_array($timeUnit, ['decade', 'century', 'millennium'])) { throw new \InvalidArgumentException("The {$timeUnit} time unit is not supported by the https://github.com/fightbulc/moment.php library."); } $allTimeUnits = []; // Fix time unit for correct time interval calculation. $startDate = new Moment('@' . $period->getStartDate()->getTimestamp()); $endDate = new Moment('@' . $period->getEndDate()->getTimestamp()); // Returned intervals by Apigee Edge are always inclusive-inclusive. $startDate->startOf($timeUnit); $endDate->endOf($timeUnit); $period = new Period($startDate, $endDate); $timeUnit = '1 ' . $timeUnit; /** @var \DateTime $dateTime */ foreach ($period->getDatePeriod($timeUnit) as $dateTime) { $allTimeUnits[] = $dateTime->getTimestamp() * 1000; } return $tsAscending ? $allTimeUnits : array_reverse($allTimeUnits); }
[ "private", "function", "fillGapsInTimeUnitsData", "(", "Period", "$", "period", ",", "string", "$", "timeUnit", ",", "bool", "$", "tsAscending", ")", "{", "// Moment library does not validate time units that being passed just falls back to the default behavior", "// automatically...
Fills the gaps between returned time units in the response of Apigee Edge. When there were no metric data for a time unit (hour, day, etc.) then those are missing from Apigee Edge response. This utility function fixes this problem. @param Period $period Original time range from StatsQuery. @param string $timeUnit Time unit from StatsQuery. @param bool $tsAscending @throws \InvalidArgumentException If time unit is not supported by the Moment library. @throws \Moment\MomentException @return array Array of time units in the given period.
[ "Fills", "the", "gaps", "between", "returned", "time", "units", "in", "the", "response", "of", "Apigee", "Edge", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/StatsController.php#L237-L261
apigee/apigee-client-php
src/Api/Management/Controller/StatsController.php
StatsController.fillGapsInMetricsData
private function fillGapsInMetricsData(bool $tsAscending, array $allTimeUnits, array $originalTimeUnits, array &$metricsData): void { $zeroArray = array_fill_keys($allTimeUnits, 0); foreach ($metricsData as $key => $metric) { $metricsData[$key]['values'] = array_combine($originalTimeUnits, $metric['values']); $metricsData[$key]['values'] += $zeroArray; if ($tsAscending) { ksort($metricsData[$key]['values']); } else { krsort($metricsData[$key]['values']); } // Keep original numerical indexes. $metricsData[$key]['values'] = array_values($metricsData[$key]['values']); } }
php
private function fillGapsInMetricsData(bool $tsAscending, array $allTimeUnits, array $originalTimeUnits, array &$metricsData): void { $zeroArray = array_fill_keys($allTimeUnits, 0); foreach ($metricsData as $key => $metric) { $metricsData[$key]['values'] = array_combine($originalTimeUnits, $metric['values']); $metricsData[$key]['values'] += $zeroArray; if ($tsAscending) { ksort($metricsData[$key]['values']); } else { krsort($metricsData[$key]['values']); } // Keep original numerical indexes. $metricsData[$key]['values'] = array_values($metricsData[$key]['values']); } }
[ "private", "function", "fillGapsInMetricsData", "(", "bool", "$", "tsAscending", ",", "array", "$", "allTimeUnits", ",", "array", "$", "originalTimeUnits", ",", "array", "&", "$", "metricsData", ")", ":", "void", "{", "$", "zeroArray", "=", "array_fill_keys", ...
Fills the gaps between returned analytics numbers in the response of Apigee Edge. Apigee Edge does not returns zeros for those time units (hours, days, etc.) when there were no metric data. @param bool $tsAscending TsAscending from StatsQuery. @param array $allTimeUnits All time units in the given time interval. @param array $originalTimeUnits Returned time units by Apigee Edge. @param array $metricsData Returned metrics data by Apigee Edge.
[ "Fills", "the", "gaps", "between", "returned", "analytics", "numbers", "in", "the", "response", "of", "Apigee", "Edge", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Management/Controller/StatsController.php#L277-L291
apigee/apigee-client-php
src/Api/Monetization/Builder/RatePlanRevisionBuilder.php
RatePlanRevisionBuilder.buildRatePlanRevision
public static function buildRatePlanRevision(RatePlanInterface $ratePlan, DateTimeImmutable $startDate): RatePlanRevisionInterface { if ($ratePlan->getStartDate()->getTimestamp() >= $startDate->getTimestamp()) { throw new InvalidArgumentException("Start date should not be earlier than parent rate plan's start date."); } $ratePlanSerializer = new RatePlanSerializer(); // Normalize the parent rate plan to an array. // We have to normalize all "nested" entity references recursively // with their dedicated serializer because only their ids are being // returned by the rate plan serializer (as it should be) by default. /** @var object $normalized */ $normalized = $ratePlanSerializer->normalize($ratePlan); $normalized->organization = (new OrganizationProfileSerializer())->normalize($ratePlan->getOrganization()); $normalized->currency = (new EntitySerializer())->normalize($ratePlan->getCurrency()); $normalized->currency->organization = $normalized->organization; $normalized->monetizationPackage = (new ApiPackageSerializer())->normalize($ratePlan->getPackage()); $normalized->monetizationPackage->organization = $normalized->organization; foreach ($normalized->ratePlanDetails as $detail) { $detail->currency = clone $normalized->currency; $detail->organization = clone $normalized->organization; } // We do not need the "parent" rate plan of the "parent" rate plan for // this API call. if ($ratePlan instanceof RatePlanRevisionInterface) { unset($normalized->parentRatePlan); } // Set the "parent" rate plan for the new revision. $normalized->parentRatePlan = clone $normalized; // Id of the rate plan revision will be provided by Apigee Edge. unset($normalized->id); // Remove the end date inherited from the parent rate plan because // it may overlap with the new start date. unset($normalized->endDate); // Create a new rate plan revision from the "copy" of parent rate plan. // We have to disable the type enforcement because an empty "addresses" // array is being passed to the organization which causes failures. // @see Apigee\Edge\Api\Monetization\Entity\OrganizationAwareEntity // @see https://github.com/symfony/symfony/issues/28161 /** @var \Apigee\Edge\Api\Monetization\Entity\RatePlanRevisionInterface $revision */ $revision = $ratePlanSerializer->denormalize($normalized, RatePlanInterface::class, null, [ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]); $revision->setStartDate($startDate); return $revision; }
php
public static function buildRatePlanRevision(RatePlanInterface $ratePlan, DateTimeImmutable $startDate): RatePlanRevisionInterface { if ($ratePlan->getStartDate()->getTimestamp() >= $startDate->getTimestamp()) { throw new InvalidArgumentException("Start date should not be earlier than parent rate plan's start date."); } $ratePlanSerializer = new RatePlanSerializer(); // Normalize the parent rate plan to an array. // We have to normalize all "nested" entity references recursively // with their dedicated serializer because only their ids are being // returned by the rate plan serializer (as it should be) by default. /** @var object $normalized */ $normalized = $ratePlanSerializer->normalize($ratePlan); $normalized->organization = (new OrganizationProfileSerializer())->normalize($ratePlan->getOrganization()); $normalized->currency = (new EntitySerializer())->normalize($ratePlan->getCurrency()); $normalized->currency->organization = $normalized->organization; $normalized->monetizationPackage = (new ApiPackageSerializer())->normalize($ratePlan->getPackage()); $normalized->monetizationPackage->organization = $normalized->organization; foreach ($normalized->ratePlanDetails as $detail) { $detail->currency = clone $normalized->currency; $detail->organization = clone $normalized->organization; } // We do not need the "parent" rate plan of the "parent" rate plan for // this API call. if ($ratePlan instanceof RatePlanRevisionInterface) { unset($normalized->parentRatePlan); } // Set the "parent" rate plan for the new revision. $normalized->parentRatePlan = clone $normalized; // Id of the rate plan revision will be provided by Apigee Edge. unset($normalized->id); // Remove the end date inherited from the parent rate plan because // it may overlap with the new start date. unset($normalized->endDate); // Create a new rate plan revision from the "copy" of parent rate plan. // We have to disable the type enforcement because an empty "addresses" // array is being passed to the organization which causes failures. // @see Apigee\Edge\Api\Monetization\Entity\OrganizationAwareEntity // @see https://github.com/symfony/symfony/issues/28161 /** @var \Apigee\Edge\Api\Monetization\Entity\RatePlanRevisionInterface $revision */ $revision = $ratePlanSerializer->denormalize($normalized, RatePlanInterface::class, null, [ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true]); $revision->setStartDate($startDate); return $revision; }
[ "public", "static", "function", "buildRatePlanRevision", "(", "RatePlanInterface", "$", "ratePlan", ",", "DateTimeImmutable", "$", "startDate", ")", ":", "RatePlanRevisionInterface", "{", "if", "(", "$", "ratePlan", "->", "getStartDate", "(", ")", "->", "getTimestam...
Creates a new rate plan revision object from an existing rate plan (revision). The end date of the new rate plan revision is not set even if it was set on the "parent" rate plan. @param \Apigee\Edge\Api\Monetization\Entity\RatePlanInterface $ratePlan "Parent" rate plan. @param \DateTimeImmutable $startDate Start date of the rate plan revision. @throws \InvalidArgumentException If the provided start date is earlier than the start date of the "parent" rate plan. @return \Apigee\Edge\Api\Monetization\Entity\RatePlanRevisionInterface New rate plan revision.
[ "Creates", "a", "new", "rate", "plan", "revision", "object", "from", "an", "existing", "rate", "plan", "(", "revision", ")", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Builder/RatePlanRevisionBuilder.php#L56-L99
apigee/apigee-client-php
src/Api/Monetization/Controller/PrepaidBalanceController.php
PrepaidBalanceController.setupRecurringPayments
public function setupRecurringPayments(string $currencyCode, string $paymentProviderId, float $replenishAmount, float $recurringAmount): BalanceInterface { $response = $this->client->post( $this->getBaseEndpointUri()->withPath("{$this->getBaseEndpointUri()->getPath()}/recurring-setup")->withQuery(http_build_query(['supportedCurrencyId' => $currencyCode])), (string) json_encode((object) [ 'providerId' => $paymentProviderId, 'isRecurring' => 'true', 'replenishAmount' => $replenishAmount, 'recurringAmount' => $recurringAmount, ]) ); return $this->entitySerializer->deserialize( (string) $response->getBody(), $this->getEntityClass(), 'json' ); }
php
public function setupRecurringPayments(string $currencyCode, string $paymentProviderId, float $replenishAmount, float $recurringAmount): BalanceInterface { $response = $this->client->post( $this->getBaseEndpointUri()->withPath("{$this->getBaseEndpointUri()->getPath()}/recurring-setup")->withQuery(http_build_query(['supportedCurrencyId' => $currencyCode])), (string) json_encode((object) [ 'providerId' => $paymentProviderId, 'isRecurring' => 'true', 'replenishAmount' => $replenishAmount, 'recurringAmount' => $recurringAmount, ]) ); return $this->entitySerializer->deserialize( (string) $response->getBody(), $this->getEntityClass(), 'json' ); }
[ "public", "function", "setupRecurringPayments", "(", "string", "$", "currencyCode", ",", "string", "$", "paymentProviderId", ",", "float", "$", "replenishAmount", ",", "float", "$", "recurringAmount", ")", ":", "BalanceInterface", "{", "$", "response", "=", "$", ...
Enables and modifies recurring payment settings. @param string $currencyCode @param string $paymentProviderId @param float $replenishAmount @param float $recurringAmount @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
[ "Enables", "and", "modifies", "recurring", "payment", "settings", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/PrepaidBalanceController.php#L110-L127
apigee/apigee-client-php
src/Api/Monetization/Controller/PrepaidBalanceController.php
PrepaidBalanceController.disableRecurringPayments
public function disableRecurringPayments(string $currencyCode, string $paymentProviderId): BalanceInterface { $response = $this->client->post( $this->getBaseEndpointUri()->withPath("{$this->getBaseEndpointUri()->getPath()}/recurring-setup")->withQuery(http_build_query(['supportedCurrencyId' => $currencyCode])), (string) json_encode((object) [ 'providerId' => $paymentProviderId, 'chargePerUsage' => 'true', ]) ); return $this->entitySerializer->deserialize( (string) $response->getBody(), $this->getEntityClass(), 'json' ); }
php
public function disableRecurringPayments(string $currencyCode, string $paymentProviderId): BalanceInterface { $response = $this->client->post( $this->getBaseEndpointUri()->withPath("{$this->getBaseEndpointUri()->getPath()}/recurring-setup")->withQuery(http_build_query(['supportedCurrencyId' => $currencyCode])), (string) json_encode((object) [ 'providerId' => $paymentProviderId, 'chargePerUsage' => 'true', ]) ); return $this->entitySerializer->deserialize( (string) $response->getBody(), $this->getEntityClass(), 'json' ); }
[ "public", "function", "disableRecurringPayments", "(", "string", "$", "currencyCode", ",", "string", "$", "paymentProviderId", ")", ":", "BalanceInterface", "{", "$", "response", "=", "$", "this", "->", "client", "->", "post", "(", "$", "this", "->", "getBaseE...
Deactivate recurring payments. @param string $currencyCode @param string $paymentProviderId @return \Apigee\Edge\Api\Monetization\Entity\BalanceInterface
[ "Deactivate", "recurring", "payments", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/PrepaidBalanceController.php#L137-L152
apigee/apigee-client-php
src/Api/Monetization/Controller/PrepaidBalanceController.php
PrepaidBalanceController.listPrepaidBalances
private function listPrepaidBalances(\DateTimeImmutable $billingMonth, ?string $currencyCode = null): array { $query_params = [ 'billingMonth' => strtoupper($billingMonth->format('F')), 'billingYear' => $billingMonth->format('Y'), ]; if (null !== $currencyCode) { $query_params['supportedCurrencyId'] = $currencyCode; } $balances = []; foreach ($this->getRawList($this->getPrepaidBalanceEndpoint()->withQuery(http_build_query($query_params))) as $item) { /** @var \Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface $balance */ $balance = $this->prepaidBalanceSerializer->denormalize($item, $this->prepaidBalanceClass); $balances[$balance->id()] = $balance; } return $balances; }
php
private function listPrepaidBalances(\DateTimeImmutable $billingMonth, ?string $currencyCode = null): array { $query_params = [ 'billingMonth' => strtoupper($billingMonth->format('F')), 'billingYear' => $billingMonth->format('Y'), ]; if (null !== $currencyCode) { $query_params['supportedCurrencyId'] = $currencyCode; } $balances = []; foreach ($this->getRawList($this->getPrepaidBalanceEndpoint()->withQuery(http_build_query($query_params))) as $item) { /** @var \Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface $balance */ $balance = $this->prepaidBalanceSerializer->denormalize($item, $this->prepaidBalanceClass); $balances[$balance->id()] = $balance; } return $balances; }
[ "private", "function", "listPrepaidBalances", "(", "\\", "DateTimeImmutable", "$", "billingMonth", ",", "?", "string", "$", "currencyCode", "=", "null", ")", ":", "array", "{", "$", "query_params", "=", "[", "'billingMonth'", "=>", "strtoupper", "(", "$", "bil...
Helper function which returns prepaid balances.. @param \DateTimeImmutable $billingMonth @param string|null $currencyCode @return \Apigee\Edge\Api\Monetization\Entity\PrepaidBalanceInterface[] @psalm-suppress PossiblyNullArrayOffset - id() does not return null here.
[ "Helper", "function", "which", "returns", "prepaid", "balances", ".." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Controller/PrepaidBalanceController.php#L204-L222
apigee/apigee-client-php
src/Api/Monetization/Normalizer/AcceptedRatePlanNormalizer.php
AcceptedRatePlanNormalizer.normalize
public function normalize($object, $format = null, array $context = []) { /** @var \Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface $object */ /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); $this->fixTimeZoneOnNormalization($object, $normalized, $object->getRatePlan()->getPackage()->getOrganization()->getTimezone()); return $normalized; }
php
public function normalize($object, $format = null, array $context = []) { /** @var \Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface $object */ /** @var object $normalized */ $normalized = parent::normalize($object, $format, $context); $this->fixTimeZoneOnNormalization($object, $normalized, $object->getRatePlan()->getPackage()->getOrganization()->getTimezone()); return $normalized; }
[ "public", "function", "normalize", "(", "$", "object", ",", "$", "format", "=", "null", ",", "array", "$", "context", "=", "[", "]", ")", "{", "/** @var \\Apigee\\Edge\\Api\\Monetization\\Entity\\AcceptedRatePlanInterface $object */", "/** @var object $normalized */", "$"...
@inheritDoc @psalm-suppress InvalidReturnType Returning an object here is required for creating a valid Apigee Edge request.
[ "@inheritDoc" ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Api/Monetization/Normalizer/AcceptedRatePlanNormalizer.php#L34-L42
apigee/apigee-client-php
src/Controller/PaginationHelperTrait.php
PaginationHelperTrait.listEntities
protected function listEntities(PagerInterface $pager = null, array $query_params = [], string $key_provider = 'id'): array { /** @var \Apigee\Edge\Api\Management\Entity\OrganizationInterface $organization */ $organization = $this->getOrganizationController()->load($this->getOrganisationName()); $isCpsEnabled = $organization->getPropertyValue('features.isCpsEnabled'); if ($isCpsEnabled) { return $this->listEntitiesWithCps($pager, $query_params, $key_provider); } else { $this->triggerCpsSimulationNotice($pager); return $this->listEntitiesWithoutCps($pager, $query_params, $key_provider); } }
php
protected function listEntities(PagerInterface $pager = null, array $query_params = [], string $key_provider = 'id'): array { /** @var \Apigee\Edge\Api\Management\Entity\OrganizationInterface $organization */ $organization = $this->getOrganizationController()->load($this->getOrganisationName()); $isCpsEnabled = $organization->getPropertyValue('features.isCpsEnabled'); if ($isCpsEnabled) { return $this->listEntitiesWithCps($pager, $query_params, $key_provider); } else { $this->triggerCpsSimulationNotice($pager); return $this->listEntitiesWithoutCps($pager, $query_params, $key_provider); } }
[ "protected", "function", "listEntities", "(", "PagerInterface", "$", "pager", "=", "null", ",", "array", "$", "query_params", "=", "[", "]", ",", "string", "$", "key_provider", "=", "'id'", ")", ":", "array", "{", "/** @var \\Apigee\\Edge\\Api\\Management\\Entity\...
Loads paginated list of entities from Apigee Edge. @param \Apigee\Edge\Structure\PagerInterface|null $pager Pager. @param array $query_params Additional query parameters. @param string $key_provider Getter method on the entity that should provide a unique array key. @return \Apigee\Edge\Entity\EntityInterface[] Array of entity objects.
[ "Loads", "paginated", "list", "of", "entities", "from", "Apigee", "Edge", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/PaginationHelperTrait.php#L106-L119
apigee/apigee-client-php
src/Controller/PaginationHelperTrait.php
PaginationHelperTrait.listEntityIds
protected function listEntityIds(PagerInterface $pager = null, array $query_params = []): array { /** @var \Apigee\Edge\Api\Management\Entity\OrganizationInterface $organization */ $organization = $this->getOrganizationController()->load($this->getOrganisationName()); $isCpsEnabled = $organization->getPropertyValue('features.isCpsEnabled'); if ($isCpsEnabled) { return $this->listEntityIdsWithCps($pager, $query_params); } else { $this->triggerCpsSimulationNotice($pager); return $this->listEntityIdsWithoutCps($pager, $query_params); } }
php
protected function listEntityIds(PagerInterface $pager = null, array $query_params = []): array { /** @var \Apigee\Edge\Api\Management\Entity\OrganizationInterface $organization */ $organization = $this->getOrganizationController()->load($this->getOrganisationName()); $isCpsEnabled = $organization->getPropertyValue('features.isCpsEnabled'); if ($isCpsEnabled) { return $this->listEntityIdsWithCps($pager, $query_params); } else { $this->triggerCpsSimulationNotice($pager); return $this->listEntityIdsWithoutCps($pager, $query_params); } }
[ "protected", "function", "listEntityIds", "(", "PagerInterface", "$", "pager", "=", "null", ",", "array", "$", "query_params", "=", "[", "]", ")", ":", "array", "{", "/** @var \\Apigee\\Edge\\Api\\Management\\Entity\\OrganizationInterface $organization */", "$", "organiza...
Loads entity ids from Apigee Edge. @param \Apigee\Edge\Structure\PagerInterface|null $pager Pager. @param array $query_params Additional query parameters. @return string[] Array of entity ids.
[ "Loads", "entity", "ids", "from", "Apigee", "Edge", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/PaginationHelperTrait.php#L132-L145
apigee/apigee-client-php
src/Controller/PaginationHelperTrait.php
PaginationHelperTrait.listEntitiesWithCps
private function listEntitiesWithCps(PagerInterface $pager = null, array $query_params = [], string $key_provider = 'id'): array { $query_params = [ 'expand' => 'true', ] + $query_params; if ($pager) { $responseArray = $this->getResultsInRange($pager, $query_params); // Ignore entity type key from response, ex.: developer, // apiproduct, etc. $responseArray = reset($responseArray); return $this->responseArrayToArrayOfEntities($responseArray, $key_provider); } else { // Pass an empty pager to load all entities. $responseArray = $this->getResultsInRange($this->createPager(), $query_params); // Ignore entity type key from response, ex.: developer, apiproduct, // etc. $responseArray = reset($responseArray); if (empty($responseArray)) { return []; } $entities = $this->responseArrayToArrayOfEntities($responseArray, $key_provider); $lastEntity = end($entities); $lastId = $lastEntity->{$key_provider}(); do { $tmp = $this->getResultsInRange($this->createPager(0, $lastId), $query_params); // Ignore entity type key from response, ex.: developer, // apiproduct, etc. $tmp = reset($tmp); // Remove the first item from the list because it is the same // as the last item of $entities at this moment. // Apigee Edge response always starts with the requested entity // (startKey). array_shift($tmp); $tmpEntities = $this->responseArrayToArrayOfEntities($tmp, $key_provider); if (count($tmpEntities) > 0) { // The returned entity array is keyed by entity id which // is unique so we can do this. $entities += $tmpEntities; $lastEntity = end($tmpEntities); $lastId = $lastEntity->{$key_provider}(); } else { $lastId = false; } } while ($lastId); return $entities; } }
php
private function listEntitiesWithCps(PagerInterface $pager = null, array $query_params = [], string $key_provider = 'id'): array { $query_params = [ 'expand' => 'true', ] + $query_params; if ($pager) { $responseArray = $this->getResultsInRange($pager, $query_params); // Ignore entity type key from response, ex.: developer, // apiproduct, etc. $responseArray = reset($responseArray); return $this->responseArrayToArrayOfEntities($responseArray, $key_provider); } else { // Pass an empty pager to load all entities. $responseArray = $this->getResultsInRange($this->createPager(), $query_params); // Ignore entity type key from response, ex.: developer, apiproduct, // etc. $responseArray = reset($responseArray); if (empty($responseArray)) { return []; } $entities = $this->responseArrayToArrayOfEntities($responseArray, $key_provider); $lastEntity = end($entities); $lastId = $lastEntity->{$key_provider}(); do { $tmp = $this->getResultsInRange($this->createPager(0, $lastId), $query_params); // Ignore entity type key from response, ex.: developer, // apiproduct, etc. $tmp = reset($tmp); // Remove the first item from the list because it is the same // as the last item of $entities at this moment. // Apigee Edge response always starts with the requested entity // (startKey). array_shift($tmp); $tmpEntities = $this->responseArrayToArrayOfEntities($tmp, $key_provider); if (count($tmpEntities) > 0) { // The returned entity array is keyed by entity id which // is unique so we can do this. $entities += $tmpEntities; $lastEntity = end($tmpEntities); $lastId = $lastEntity->{$key_provider}(); } else { $lastId = false; } } while ($lastId); return $entities; } }
[ "private", "function", "listEntitiesWithCps", "(", "PagerInterface", "$", "pager", "=", "null", ",", "array", "$", "query_params", "=", "[", "]", ",", "string", "$", "key_provider", "=", "'id'", ")", ":", "array", "{", "$", "query_params", "=", "[", "'expa...
Real paginated entity listing on organization with CPS support. @param \Apigee\Edge\Structure\PagerInterface|null $pager Pager. @param array $query_params Additional query parameters. @param string $key_provider Getter method on the entity that should provide a unique array key. @return \Apigee\Edge\Entity\EntityInterface[] Array of entity objects. @psalm-suppress PossiblyNullArrayOffset $tmp->id() is always not null here.
[ "Real", "paginated", "entity", "listing", "on", "organization", "with", "CPS", "support", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/PaginationHelperTrait.php#L172-L222
apigee/apigee-client-php
src/Controller/PaginationHelperTrait.php
PaginationHelperTrait.listEntitiesWithoutCps
private function listEntitiesWithoutCps(PagerInterface $pager = null, array $query_params = [], string $key_provider = 'id'): array { $query_params = [ 'expand' => 'true', ] + $query_params; $uri = $this->getBaseEndpointUri()->withQuery(http_build_query($query_params)); $response = $this->getClient()->get($uri); $responseArray = $this->responseToArray($response); // Ignore entity type key from response, ex.: apiProduct. $responseArray = reset($responseArray); $entities = $this->responseArrayToArrayOfEntities($responseArray, $key_provider); return $pager ? $this->simulateCpsPagination($pager, $entities, array_keys($entities)) : $entities; }
php
private function listEntitiesWithoutCps(PagerInterface $pager = null, array $query_params = [], string $key_provider = 'id'): array { $query_params = [ 'expand' => 'true', ] + $query_params; $uri = $this->getBaseEndpointUri()->withQuery(http_build_query($query_params)); $response = $this->getClient()->get($uri); $responseArray = $this->responseToArray($response); // Ignore entity type key from response, ex.: apiProduct. $responseArray = reset($responseArray); $entities = $this->responseArrayToArrayOfEntities($responseArray, $key_provider); return $pager ? $this->simulateCpsPagination($pager, $entities, array_keys($entities)) : $entities; }
[ "private", "function", "listEntitiesWithoutCps", "(", "PagerInterface", "$", "pager", "=", "null", ",", "array", "$", "query_params", "=", "[", "]", ",", "string", "$", "key_provider", "=", "'id'", ")", ":", "array", "{", "$", "query_params", "=", "[", "'e...
Simulates paginated entity listing on organization without CPS support. For example, on on-prem installations. @param \Apigee\Edge\Structure\PagerInterface|null $pager Pager. @param array $query_params Additional query parameters. @param string $key_provider Getter method on the entity that should provide a unique array key. @return \Apigee\Edge\Entity\EntityInterface[] Array of entity objects.
[ "Simulates", "paginated", "entity", "listing", "on", "organization", "without", "CPS", "support", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/PaginationHelperTrait.php#L239-L254
apigee/apigee-client-php
src/Controller/PaginationHelperTrait.php
PaginationHelperTrait.getResultsInRange
private function getResultsInRange(PagerInterface $pager, array $query_params): array { $query_params['startKey'] = $pager->getStartKey(); // Do not add 0 unnecessarily to the query parameters. if ($pager->getLimit() > 0) { $query_params['count'] = $pager->getLimit(); } $uri = $this->getBaseEndpointUri()->withQuery(http_build_query($query_params)); $response = $this->getClient()->get($uri); return $this->responseToArray($response); }
php
private function getResultsInRange(PagerInterface $pager, array $query_params): array { $query_params['startKey'] = $pager->getStartKey(); // Do not add 0 unnecessarily to the query parameters. if ($pager->getLimit() > 0) { $query_params['count'] = $pager->getLimit(); } $uri = $this->getBaseEndpointUri()->withQuery(http_build_query($query_params)); $response = $this->getClient()->get($uri); return $this->responseToArray($response); }
[ "private", "function", "getResultsInRange", "(", "PagerInterface", "$", "pager", ",", "array", "$", "query_params", ")", ":", "array", "{", "$", "query_params", "[", "'startKey'", "]", "=", "$", "pager", "->", "getStartKey", "(", ")", ";", "// Do not add 0 unn...
Gets entities and entity ids in a provided range from Apigee Edge. This method for organizations with CPS enabled. @param \Apigee\Edge\Structure\PagerInterface $pager CPS limit object with configured startKey and limit. @param array $query_params Query parameters for the API call. @return array API response parsed as an array.
[ "Gets", "entities", "and", "entity", "ids", "in", "a", "provided", "range", "from", "Apigee", "Edge", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/PaginationHelperTrait.php#L269-L280
apigee/apigee-client-php
src/Controller/PaginationHelperTrait.php
PaginationHelperTrait.listEntityIdsWithCps
private function listEntityIdsWithCps(PagerInterface $pager = null, array $query_params = []): array { $query_params = [ 'expand' => 'false', ] + $query_params; if ($pager) { return $this->getResultsInRange($pager, $query_params); } else { $ids = $this->getResultsInRange($this->createPager(), $query_params); if (empty($ids)) { return []; } $lastId = end($ids); do { $tmp = $this->getResultsInRange($this->createPager(0, $lastId), $query_params); // Remove the first item from the list because it is the same // as the current last item of $ids. // Apigee Edge response always starts with the requested entity // id (startKey). array_shift($tmp); if (count($tmp) > 0) { $ids = array_merge($ids, $tmp); $lastId = end($tmp); } else { $lastId = false; } } while ($lastId); return $ids; } }
php
private function listEntityIdsWithCps(PagerInterface $pager = null, array $query_params = []): array { $query_params = [ 'expand' => 'false', ] + $query_params; if ($pager) { return $this->getResultsInRange($pager, $query_params); } else { $ids = $this->getResultsInRange($this->createPager(), $query_params); if (empty($ids)) { return []; } $lastId = end($ids); do { $tmp = $this->getResultsInRange($this->createPager(0, $lastId), $query_params); // Remove the first item from the list because it is the same // as the current last item of $ids. // Apigee Edge response always starts with the requested entity // id (startKey). array_shift($tmp); if (count($tmp) > 0) { $ids = array_merge($ids, $tmp); $lastId = end($tmp); } else { $lastId = false; } } while ($lastId); return $ids; } }
[ "private", "function", "listEntityIdsWithCps", "(", "PagerInterface", "$", "pager", "=", "null", ",", "array", "$", "query_params", "=", "[", "]", ")", ":", "array", "{", "$", "query_params", "=", "[", "'expand'", "=>", "'false'", ",", "]", "+", "$", "qu...
Real paginated entity id listing on organization with CPS support. @param \Apigee\Edge\Structure\PagerInterface|null $pager Pager. @param array $query_params Additional query parameters. @return string[] Array of entity ids.
[ "Real", "paginated", "entity", "id", "listing", "on", "organization", "with", "CPS", "support", "." ]
train
https://github.com/apigee/apigee-client-php/blob/7b4b4c29b65c06abe5ebef19634644271203a4e8/src/Controller/PaginationHelperTrait.php#L312-L343