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
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
skmetaly/laravel-twitch-restful-api | src/API/Users.php | Users.videosFollowed | public function videosFollowed($token = null)
{
$token = $this->getToken($token);
$videos = $this->client->get('https://api.twitch.tv/kraken/videos/followed?oauth_token=' . $token);
return $videos->json();
} | php | public function videosFollowed($token = null)
{
$token = $this->getToken($token);
$videos = $this->client->get('https://api.twitch.tv/kraken/videos/followed?oauth_token=' . $token);
return $videos->json();
} | [
"public",
"function",
"videosFollowed",
"(",
"$",
"token",
"=",
"null",
")",
"{",
"$",
"token",
"=",
"$",
"this",
"->",
"getToken",
"(",
"$",
"token",
")",
";",
"$",
"videos",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"'https://api.twitch.tv/kraken/videos/followed?oauth_token='",
".",
"$",
"token",
")",
";",
"return",
"$",
"videos",
"->",
"json",
"(",
")",
";",
"}"
] | Returns a list of video objects from channels that the authenticated user is following.
Authenticated, required scope: user_read
@param null $token
@return json
@throws \Skmetaly\TwitchApi\Exceptions\RequestRequiresAuthenticationException | [
"Returns",
"a",
"list",
"of",
"video",
"objects",
"from",
"channels",
"that",
"the",
"authenticated",
"user",
"is",
"following",
"."
] | train | https://github.com/skmetaly/laravel-twitch-restful-api/blob/70c83e441deb411ade2e343ad5cb0339c90dc6c2/src/API/Users.php#L77-L84 |
hametuha/wpametu | src/WPametu/UI/Field/Select.php | Select.get_option | protected function get_option($key, $label, $counter, $data, array $fields = []){
return sprintf('<option value="%s"%s>%s</option>',
esc_attr($key),
selected( (!$data && $key == $this->default) || $key == $data, true, false ),
esc_html($label));
} | php | protected function get_option($key, $label, $counter, $data, array $fields = []){
return sprintf('<option value="%s"%s>%s</option>',
esc_attr($key),
selected( (!$data && $key == $this->default) || $key == $data, true, false ),
esc_html($label));
} | [
"protected",
"function",
"get_option",
"(",
"$",
"key",
",",
"$",
"label",
",",
"$",
"counter",
",",
"$",
"data",
",",
"array",
"$",
"fields",
"=",
"[",
"]",
")",
"{",
"return",
"sprintf",
"(",
"'<option value=\"%s\"%s>%s</option>'",
",",
"esc_attr",
"(",
"$",
"key",
")",
",",
"selected",
"(",
"(",
"!",
"$",
"data",
"&&",
"$",
"key",
"==",
"$",
"this",
"->",
"default",
")",
"||",
"$",
"key",
"==",
"$",
"data",
",",
"true",
",",
"false",
")",
",",
"esc_html",
"(",
"$",
"label",
")",
")",
";",
"}"
] | Get fields input
@param string $key
@param string $label
@param int $counter
@param string $data
@param array $fields
@return string | [
"Get",
"fields",
"input"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Select.php#L32-L37 |
42mate/towel | src/Towel/Model/Pic.php | Pic.findObjectPics | public function findObjectPics($object_type, $object_id)
{
$query = $this->db()->createQueryBuilder();
return $query->select('*')
->from($this->table, 'p')
->where('p.object_type = ?')
->andWhere(('p.object_id = ?'))
->setParameter(0, $object_type)
->setParameter(1, $object_id)
->execute();
} | php | public function findObjectPics($object_type, $object_id)
{
$query = $this->db()->createQueryBuilder();
return $query->select('*')
->from($this->table, 'p')
->where('p.object_type = ?')
->andWhere(('p.object_id = ?'))
->setParameter(0, $object_type)
->setParameter(1, $object_id)
->execute();
} | [
"public",
"function",
"findObjectPics",
"(",
"$",
"object_type",
",",
"$",
"object_id",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"db",
"(",
")",
"->",
"createQueryBuilder",
"(",
")",
";",
"return",
"$",
"query",
"->",
"select",
"(",
"'*'",
")",
"->",
"from",
"(",
"$",
"this",
"->",
"table",
",",
"'p'",
")",
"->",
"where",
"(",
"'p.object_type = ?'",
")",
"->",
"andWhere",
"(",
"(",
"'p.object_id = ?'",
")",
")",
"->",
"setParameter",
"(",
"0",
",",
"$",
"object_type",
")",
"->",
"setParameter",
"(",
"1",
",",
"$",
"object_id",
")",
"->",
"execute",
"(",
")",
";",
"}"
] | Finds a Picture/s for the given object type / object id.
@param $object_type
@param $object_id
@return mixed | [
"Finds",
"a",
"Picture",
"/",
"s",
"for",
"the",
"given",
"object",
"type",
"/",
"object",
"id",
"."
] | train | https://github.com/42mate/towel/blob/5316c3075fc844e8a5cbae113712b26556227dff/src/Towel/Model/Pic.php#L17-L27 |
php-lug/lug | src/Bundle/RegistryBundle/DependencyInjection/Compiler/ConvertRegistryPass.php | ConvertRegistryPass.process | public function process(ContainerBuilder $container)
{
foreach (array_keys($container->findTaggedServiceIds($tag = 'lug.registry')) as $registry) {
$definition = $container->getDefinition($registry);
if (is_subclass_of($definition->getClass(), LazyRegistryInterface::class)) {
continue;
}
$container->setDefinition($internal = $registry.'.internal', $definition->clearTag($tag));
$container->setDefinition($registry, $this->createLazyDefinition($internal, $definition));
$this->clearMethodCalls($definition);
}
} | php | public function process(ContainerBuilder $container)
{
foreach (array_keys($container->findTaggedServiceIds($tag = 'lug.registry')) as $registry) {
$definition = $container->getDefinition($registry);
if (is_subclass_of($definition->getClass(), LazyRegistryInterface::class)) {
continue;
}
$container->setDefinition($internal = $registry.'.internal', $definition->clearTag($tag));
$container->setDefinition($registry, $this->createLazyDefinition($internal, $definition));
$this->clearMethodCalls($definition);
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"foreach",
"(",
"array_keys",
"(",
"$",
"container",
"->",
"findTaggedServiceIds",
"(",
"$",
"tag",
"=",
"'lug.registry'",
")",
")",
"as",
"$",
"registry",
")",
"{",
"$",
"definition",
"=",
"$",
"container",
"->",
"getDefinition",
"(",
"$",
"registry",
")",
";",
"if",
"(",
"is_subclass_of",
"(",
"$",
"definition",
"->",
"getClass",
"(",
")",
",",
"LazyRegistryInterface",
"::",
"class",
")",
")",
"{",
"continue",
";",
"}",
"$",
"container",
"->",
"setDefinition",
"(",
"$",
"internal",
"=",
"$",
"registry",
".",
"'.internal'",
",",
"$",
"definition",
"->",
"clearTag",
"(",
"$",
"tag",
")",
")",
";",
"$",
"container",
"->",
"setDefinition",
"(",
"$",
"registry",
",",
"$",
"this",
"->",
"createLazyDefinition",
"(",
"$",
"internal",
",",
"$",
"definition",
")",
")",
";",
"$",
"this",
"->",
"clearMethodCalls",
"(",
"$",
"definition",
")",
";",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/RegistryBundle/DependencyInjection/Compiler/ConvertRegistryPass.php#L29-L43 |
php-lug/lug | src/Bundle/RegistryBundle/DependencyInjection/Compiler/ConvertRegistryPass.php | ConvertRegistryPass.createLazyDefinition | private function createLazyDefinition($registry, Definition $definition)
{
$lazy = new Definition(LazyRegistry::class, [
new Reference('service_container'),
new Reference($registry),
]);
foreach ($definition->getMethodCalls() as $methodCall) {
if ($methodCall[0] === 'offsetSet') {
$methodCall[1][1] = (string) $methodCall[1][1];
$lazy->addMethodCall('setLazy', $methodCall[1]);
}
}
return $lazy;
} | php | private function createLazyDefinition($registry, Definition $definition)
{
$lazy = new Definition(LazyRegistry::class, [
new Reference('service_container'),
new Reference($registry),
]);
foreach ($definition->getMethodCalls() as $methodCall) {
if ($methodCall[0] === 'offsetSet') {
$methodCall[1][1] = (string) $methodCall[1][1];
$lazy->addMethodCall('setLazy', $methodCall[1]);
}
}
return $lazy;
} | [
"private",
"function",
"createLazyDefinition",
"(",
"$",
"registry",
",",
"Definition",
"$",
"definition",
")",
"{",
"$",
"lazy",
"=",
"new",
"Definition",
"(",
"LazyRegistry",
"::",
"class",
",",
"[",
"new",
"Reference",
"(",
"'service_container'",
")",
",",
"new",
"Reference",
"(",
"$",
"registry",
")",
",",
"]",
")",
";",
"foreach",
"(",
"$",
"definition",
"->",
"getMethodCalls",
"(",
")",
"as",
"$",
"methodCall",
")",
"{",
"if",
"(",
"$",
"methodCall",
"[",
"0",
"]",
"===",
"'offsetSet'",
")",
"{",
"$",
"methodCall",
"[",
"1",
"]",
"[",
"1",
"]",
"=",
"(",
"string",
")",
"$",
"methodCall",
"[",
"1",
"]",
"[",
"1",
"]",
";",
"$",
"lazy",
"->",
"addMethodCall",
"(",
"'setLazy'",
",",
"$",
"methodCall",
"[",
"1",
"]",
")",
";",
"}",
"}",
"return",
"$",
"lazy",
";",
"}"
] | @param string $registry
@param Definition $definition
@return Definition | [
"@param",
"string",
"$registry",
"@param",
"Definition",
"$definition"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/RegistryBundle/DependencyInjection/Compiler/ConvertRegistryPass.php#L51-L66 |
skmetaly/laravel-twitch-restful-api | src/API/Videos.php | Videos.videosTop | public function videosTop($options = [])
{
$availableOptions = ['limit', 'offset', 'game', 'period'];
$query = [];
// Filter the available options
foreach ($availableOptions as $option) {
if (isset($options[ $option ])) {
$query[ $option ] = $options[ $option ];
}
}
$parameters = $this->getDefaultHeaders();
$parameters[ 'query' ] = $query;
$response = $this->client->get('/kraken/videos/top', $parameters);
return $response->json();
} | php | public function videosTop($options = [])
{
$availableOptions = ['limit', 'offset', 'game', 'period'];
$query = [];
// Filter the available options
foreach ($availableOptions as $option) {
if (isset($options[ $option ])) {
$query[ $option ] = $options[ $option ];
}
}
$parameters = $this->getDefaultHeaders();
$parameters[ 'query' ] = $query;
$response = $this->client->get('/kraken/videos/top', $parameters);
return $response->json();
} | [
"public",
"function",
"videosTop",
"(",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"availableOptions",
"=",
"[",
"'limit'",
",",
"'offset'",
",",
"'game'",
",",
"'period'",
"]",
";",
"$",
"query",
"=",
"[",
"]",
";",
"// Filter the available options",
"foreach",
"(",
"$",
"availableOptions",
"as",
"$",
"option",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"$",
"option",
"]",
")",
")",
"{",
"$",
"query",
"[",
"$",
"option",
"]",
"=",
"$",
"options",
"[",
"$",
"option",
"]",
";",
"}",
"}",
"$",
"parameters",
"=",
"$",
"this",
"->",
"getDefaultHeaders",
"(",
")",
";",
"$",
"parameters",
"[",
"'query'",
"]",
"=",
"$",
"query",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"'/kraken/videos/top'",
",",
"$",
"parameters",
")",
";",
"return",
"$",
"response",
"->",
"json",
"(",
")",
";",
"}"
] | Returns a list of videos created in a given time period sorted by number of views, most popular first.
@param array $options
@return mixed | [
"Returns",
"a",
"list",
"of",
"videos",
"created",
"in",
"a",
"given",
"time",
"period",
"sorted",
"by",
"number",
"of",
"views",
"most",
"popular",
"first",
"."
] | train | https://github.com/skmetaly/laravel-twitch-restful-api/blob/70c83e441deb411ade2e343ad5cb0339c90dc6c2/src/API/Videos.php#L38-L59 |
skmetaly/laravel-twitch-restful-api | src/API/Videos.php | Videos.channelsVideo | public function channelsVideo($channel, $options = null)
{
$availableOptions = ['limit', 'offset', 'broadcasts', 'hls'];
$query = [];
// Filter the available options
foreach ($availableOptions as $option) {
if (isset($options[ $option ])) {
$query[ $option ] = $options[ $option ];
}
}
$parameters = $this->getDefaultHeaders();
$parameters[ 'query' ] = $query;
$response = $this->client->get('/kraken/channels/' . $channel . '/videos', $parameters);
return $response->json();
} | php | public function channelsVideo($channel, $options = null)
{
$availableOptions = ['limit', 'offset', 'broadcasts', 'hls'];
$query = [];
// Filter the available options
foreach ($availableOptions as $option) {
if (isset($options[ $option ])) {
$query[ $option ] = $options[ $option ];
}
}
$parameters = $this->getDefaultHeaders();
$parameters[ 'query' ] = $query;
$response = $this->client->get('/kraken/channels/' . $channel . '/videos', $parameters);
return $response->json();
} | [
"public",
"function",
"channelsVideo",
"(",
"$",
"channel",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"availableOptions",
"=",
"[",
"'limit'",
",",
"'offset'",
",",
"'broadcasts'",
",",
"'hls'",
"]",
";",
"$",
"query",
"=",
"[",
"]",
";",
"// Filter the available options",
"foreach",
"(",
"$",
"availableOptions",
"as",
"$",
"option",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"$",
"option",
"]",
")",
")",
"{",
"$",
"query",
"[",
"$",
"option",
"]",
"=",
"$",
"options",
"[",
"$",
"option",
"]",
";",
"}",
"}",
"$",
"parameters",
"=",
"$",
"this",
"->",
"getDefaultHeaders",
"(",
")",
";",
"$",
"parameters",
"[",
"'query'",
"]",
"=",
"$",
"query",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"get",
"(",
"'/kraken/channels/'",
".",
"$",
"channel",
".",
"'/videos'",
",",
"$",
"parameters",
")",
";",
"return",
"$",
"response",
"->",
"json",
"(",
")",
";",
"}"
] | @param $channel
@param $options
@return json | [
"@param",
"$channel"
] | train | https://github.com/skmetaly/laravel-twitch-restful-api/blob/70c83e441deb411ade2e343ad5cb0339c90dc6c2/src/API/Videos.php#L68-L89 |
weew/http | src/Weew/Http/ContentTypeDataMatcher.php | ContentTypeDataMatcher.createDataForContentType | public function createDataForContentType(IContentHolder $holder, $contentType) {
$parts = $this->parseContentType($contentType);
foreach ($parts as $part) {
$class = array_get($this->getMappings(), $part);
if ($class !== null) {
break;
}
}
if ($class === null) {
$class = $this->getDefaultDataClass();
}
return new $class($holder);
} | php | public function createDataForContentType(IContentHolder $holder, $contentType) {
$parts = $this->parseContentType($contentType);
foreach ($parts as $part) {
$class = array_get($this->getMappings(), $part);
if ($class !== null) {
break;
}
}
if ($class === null) {
$class = $this->getDefaultDataClass();
}
return new $class($holder);
} | [
"public",
"function",
"createDataForContentType",
"(",
"IContentHolder",
"$",
"holder",
",",
"$",
"contentType",
")",
"{",
"$",
"parts",
"=",
"$",
"this",
"->",
"parseContentType",
"(",
"$",
"contentType",
")",
";",
"foreach",
"(",
"$",
"parts",
"as",
"$",
"part",
")",
"{",
"$",
"class",
"=",
"array_get",
"(",
"$",
"this",
"->",
"getMappings",
"(",
")",
",",
"$",
"part",
")",
";",
"if",
"(",
"$",
"class",
"!==",
"null",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"$",
"class",
"===",
"null",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"getDefaultDataClass",
"(",
")",
";",
"}",
"return",
"new",
"$",
"class",
"(",
"$",
"holder",
")",
";",
"}"
] | @param IContentHolder $holder
@param string $contentType
@return IHttpData | [
"@param",
"IContentHolder",
"$holder",
"@param",
"string",
"$contentType"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/ContentTypeDataMatcher.php#L28-L44 |
weew/http | src/Weew/Http/ContentTypeDataMatcher.php | ContentTypeDataMatcher.setMappings | public function setMappings(array $mappings) {
$this->mappings = [];
foreach ($mappings as $contentType => $dataClass) {
$this->addMapping($contentType, $dataClass);
}
} | php | public function setMappings(array $mappings) {
$this->mappings = [];
foreach ($mappings as $contentType => $dataClass) {
$this->addMapping($contentType, $dataClass);
}
} | [
"public",
"function",
"setMappings",
"(",
"array",
"$",
"mappings",
")",
"{",
"$",
"this",
"->",
"mappings",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"mappings",
"as",
"$",
"contentType",
"=>",
"$",
"dataClass",
")",
"{",
"$",
"this",
"->",
"addMapping",
"(",
"$",
"contentType",
",",
"$",
"dataClass",
")",
";",
"}",
"}"
] | @param array $mappings
@throws InvalidDataClassException | [
"@param",
"array",
"$mappings"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/ContentTypeDataMatcher.php#L58-L64 |
weew/http | src/Weew/Http/ContentTypeDataMatcher.php | ContentTypeDataMatcher.addMapping | public function addMapping($contentType, $dataClass) {
if ( ! class_exists($dataClass)
|| ! array_contains(class_implements($dataClass), IHttpData::class)) {
throw new InvalidDataClassException(
s('Class "%s" must implement the "%s" interface.',
$dataClass, IHttpData::class)
);
}
$this->mappings[$contentType] = $dataClass;
} | php | public function addMapping($contentType, $dataClass) {
if ( ! class_exists($dataClass)
|| ! array_contains(class_implements($dataClass), IHttpData::class)) {
throw new InvalidDataClassException(
s('Class "%s" must implement the "%s" interface.',
$dataClass, IHttpData::class)
);
}
$this->mappings[$contentType] = $dataClass;
} | [
"public",
"function",
"addMapping",
"(",
"$",
"contentType",
",",
"$",
"dataClass",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"dataClass",
")",
"||",
"!",
"array_contains",
"(",
"class_implements",
"(",
"$",
"dataClass",
")",
",",
"IHttpData",
"::",
"class",
")",
")",
"{",
"throw",
"new",
"InvalidDataClassException",
"(",
"s",
"(",
"'Class \"%s\" must implement the \"%s\" interface.'",
",",
"$",
"dataClass",
",",
"IHttpData",
"::",
"class",
")",
")",
";",
"}",
"$",
"this",
"->",
"mappings",
"[",
"$",
"contentType",
"]",
"=",
"$",
"dataClass",
";",
"}"
] | @param string $contentType
@param string $dataClass
@throws InvalidDataClassException | [
"@param",
"string",
"$contentType",
"@param",
"string",
"$dataClass"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/ContentTypeDataMatcher.php#L72-L82 |
weew/http | src/Weew/Http/ContentTypeDataMatcher.php | ContentTypeDataMatcher.parseContentType | protected function parseContentType($contentType) {
$parts = explode(';', $contentType);
foreach ($parts as $key => $value) {
$parts[$key] = trim($value);
}
return $parts;
} | php | protected function parseContentType($contentType) {
$parts = explode(';', $contentType);
foreach ($parts as $key => $value) {
$parts[$key] = trim($value);
}
return $parts;
} | [
"protected",
"function",
"parseContentType",
"(",
"$",
"contentType",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"';'",
",",
"$",
"contentType",
")",
";",
"foreach",
"(",
"$",
"parts",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"parts",
"[",
"$",
"key",
"]",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"}",
"return",
"$",
"parts",
";",
"}"
] | @param string $contentType
@return array | [
"@param",
"string",
"$contentType"
] | train | https://github.com/weew/http/blob/fd34d3d5643ca01c8e0946e888224a8e8dcc3c0d/src/Weew/Http/ContentTypeDataMatcher.php#L89-L97 |
surebert/surebert-framework | src/sb/Application/Debugger.php | Debugger.errorHandler | public static function errorHandler($code, $message, $file, $line)
{
if (error_reporting() === 0) {
// This error code is not included in error_reporting
return false;
}
throw new \sb\Exception($code, $message, $file, $line);
} | php | public static function errorHandler($code, $message, $file, $line)
{
if (error_reporting() === 0) {
// This error code is not included in error_reporting
return false;
}
throw new \sb\Exception($code, $message, $file, $line);
} | [
"public",
"static",
"function",
"errorHandler",
"(",
"$",
"code",
",",
"$",
"message",
",",
"$",
"file",
",",
"$",
"line",
")",
"{",
"if",
"(",
"error_reporting",
"(",
")",
"===",
"0",
")",
"{",
"// This error code is not included in error_reporting",
"return",
"false",
";",
"}",
"throw",
"new",
"\\",
"sb",
"\\",
"Exception",
"(",
"$",
"code",
",",
"$",
"message",
",",
"$",
"file",
",",
"$",
"line",
")",
";",
"}"
] | Converts errors into exceptions
@param integer $code The error code
@param string $message The error message
@param string $file The file the error occurred in
@param integer $line The line the error occurred on | [
"Converts",
"errors",
"into",
"exceptions"
] | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Application/Debugger.php#L29-L37 |
surebert/surebert-framework | src/sb/Application/Debugger.php | Debugger.exceptionHandler | public static function exceptionHandler($e)
{
$message = 'Code: ' . $e->getCode() . "\n" .
'Path: ' . \sb\Gateway::$request->path . "\n" .
'Message: ' . $e->getMessage() . "\n" .
'Location: ' . $e->getFile() . "\n" .
'Line: ' . $e->getLine() . "\n";
if(isset(\sb\Gateway::$request)){
$message .= 'Request: '.\sb\Gateway::$request->request."\n";
if(isset(\sb\Gateway::$request->method)){
$message .= 'Method: '.\sb\Gateway::$request->method."\n";
}
if(count(\sb\Gateway::$request->get)){
$message .= 'Get: '.http_build_query(\sb\Gateway::$request->get) ."\n";
}
}
if (self::$show_trace) {
$message .= "Trace: \n\t" . str_replace("\n", "\n\t", \print_r($e->getTrace(), 1));
}
if (\method_exists("\App", "exception_handler")) {
if (\App::exceptionHandler($e, $message) === false) {
return false;
}
}
if (\ini_get("display_errors") == true) {
if (\sb\Gateway::$command_line) {
\file_put_contents('php://stderr', "\n" . $message . "\n");
} else {
echo '<pre style="background-color:red;padding:10px;color:#FFF;">' . $message . '</pre>';
}
}
if (!isset(\App::$logger)) {
\App::$logger = new \sb\Logger\FileSystem();
}
\App::$logger->exceptions($message);
} | php | public static function exceptionHandler($e)
{
$message = 'Code: ' . $e->getCode() . "\n" .
'Path: ' . \sb\Gateway::$request->path . "\n" .
'Message: ' . $e->getMessage() . "\n" .
'Location: ' . $e->getFile() . "\n" .
'Line: ' . $e->getLine() . "\n";
if(isset(\sb\Gateway::$request)){
$message .= 'Request: '.\sb\Gateway::$request->request."\n";
if(isset(\sb\Gateway::$request->method)){
$message .= 'Method: '.\sb\Gateway::$request->method."\n";
}
if(count(\sb\Gateway::$request->get)){
$message .= 'Get: '.http_build_query(\sb\Gateway::$request->get) ."\n";
}
}
if (self::$show_trace) {
$message .= "Trace: \n\t" . str_replace("\n", "\n\t", \print_r($e->getTrace(), 1));
}
if (\method_exists("\App", "exception_handler")) {
if (\App::exceptionHandler($e, $message) === false) {
return false;
}
}
if (\ini_get("display_errors") == true) {
if (\sb\Gateway::$command_line) {
\file_put_contents('php://stderr', "\n" . $message . "\n");
} else {
echo '<pre style="background-color:red;padding:10px;color:#FFF;">' . $message . '</pre>';
}
}
if (!isset(\App::$logger)) {
\App::$logger = new \sb\Logger\FileSystem();
}
\App::$logger->exceptions($message);
} | [
"public",
"static",
"function",
"exceptionHandler",
"(",
"$",
"e",
")",
"{",
"$",
"message",
"=",
"'Code: '",
".",
"$",
"e",
"->",
"getCode",
"(",
")",
".",
"\"\\n\"",
".",
"'Path: '",
".",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"request",
"->",
"path",
".",
"\"\\n\"",
".",
"'Message: '",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
".",
"\"\\n\"",
".",
"'Location: '",
".",
"$",
"e",
"->",
"getFile",
"(",
")",
".",
"\"\\n\"",
".",
"'Line: '",
".",
"$",
"e",
"->",
"getLine",
"(",
")",
".",
"\"\\n\"",
";",
"if",
"(",
"isset",
"(",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"request",
")",
")",
"{",
"$",
"message",
".=",
"'Request: '",
".",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"request",
"->",
"request",
".",
"\"\\n\"",
";",
"if",
"(",
"isset",
"(",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"request",
"->",
"method",
")",
")",
"{",
"$",
"message",
".=",
"'Method: '",
".",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"request",
"->",
"method",
".",
"\"\\n\"",
";",
"}",
"if",
"(",
"count",
"(",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"request",
"->",
"get",
")",
")",
"{",
"$",
"message",
".=",
"'Get: '",
".",
"http_build_query",
"(",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"request",
"->",
"get",
")",
".",
"\"\\n\"",
";",
"}",
"}",
"if",
"(",
"self",
"::",
"$",
"show_trace",
")",
"{",
"$",
"message",
".=",
"\"Trace: \\n\\t\"",
".",
"str_replace",
"(",
"\"\\n\"",
",",
"\"\\n\\t\"",
",",
"\\",
"print_r",
"(",
"$",
"e",
"->",
"getTrace",
"(",
")",
",",
"1",
")",
")",
";",
"}",
"if",
"(",
"\\",
"method_exists",
"(",
"\"\\App\"",
",",
"\"exception_handler\"",
")",
")",
"{",
"if",
"(",
"\\",
"App",
"::",
"exceptionHandler",
"(",
"$",
"e",
",",
"$",
"message",
")",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"\\",
"ini_get",
"(",
"\"display_errors\"",
")",
"==",
"true",
")",
"{",
"if",
"(",
"\\",
"sb",
"\\",
"Gateway",
"::",
"$",
"command_line",
")",
"{",
"\\",
"file_put_contents",
"(",
"'php://stderr'",
",",
"\"\\n\"",
".",
"$",
"message",
".",
"\"\\n\"",
")",
";",
"}",
"else",
"{",
"echo",
"'<pre style=\"background-color:red;padding:10px;color:#FFF;\">'",
".",
"$",
"message",
".",
"'</pre>'",
";",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"\\",
"App",
"::",
"$",
"logger",
")",
")",
"{",
"\\",
"App",
"::",
"$",
"logger",
"=",
"new",
"\\",
"sb",
"\\",
"Logger",
"\\",
"FileSystem",
"(",
")",
";",
"}",
"\\",
"App",
"::",
"$",
"logger",
"->",
"exceptions",
"(",
"$",
"message",
")",
";",
"}"
] | Handles acceptions and turns them into strings
@param Throwable|Exception $e A PHP exception or another class that implements the Throwable interface in PHP 7 | [
"Handles",
"acceptions",
"and",
"turns",
"them",
"into",
"strings"
] | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Application/Debugger.php#L43-L86 |
surebert/surebert-framework | src/sb/Application/Debugger.php | Debugger.shutdown | public static function shutdown()
{
if (\is_null($e = \error_get_last()) === false) {
self::exceptionHandler(new \sb\Exception($e['type'], $e['message'], $e['file'], $e['line']));
}
} | php | public static function shutdown()
{
if (\is_null($e = \error_get_last()) === false) {
self::exceptionHandler(new \sb\Exception($e['type'], $e['message'], $e['file'], $e['line']));
}
} | [
"public",
"static",
"function",
"shutdown",
"(",
")",
"{",
"if",
"(",
"\\",
"is_null",
"(",
"$",
"e",
"=",
"\\",
"error_get_last",
"(",
")",
")",
"===",
"false",
")",
"{",
"self",
"::",
"exceptionHandler",
"(",
"new",
"\\",
"sb",
"\\",
"Exception",
"(",
"$",
"e",
"[",
"'type'",
"]",
",",
"$",
"e",
"[",
"'message'",
"]",
",",
"$",
"e",
"[",
"'file'",
"]",
",",
"$",
"e",
"[",
"'line'",
"]",
")",
")",
";",
"}",
"}"
] | Shutdown function catches additional parse errors | [
"Shutdown",
"function",
"catches",
"additional",
"parse",
"errors"
] | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Application/Debugger.php#L91-L96 |
surebert/surebert-framework | src/sb/Application/Debugger.php | Debugger.init | public static function init($error_reporting_level = E_ALL, $display_errors = true, $show_trace = true)
{
\error_reporting($error_reporting_level);
\ini_set("display_errors", $display_errors ? true : false);
self::$show_trace = $show_trace ? true : false;
\set_error_handler('\sb\Application\Debugger::errorHandler');
\set_exception_handler('\sb\Application\Debugger::exceptionHandler');
\register_shutdown_function('\sb\Application\Debugger::shutdown');
} | php | public static function init($error_reporting_level = E_ALL, $display_errors = true, $show_trace = true)
{
\error_reporting($error_reporting_level);
\ini_set("display_errors", $display_errors ? true : false);
self::$show_trace = $show_trace ? true : false;
\set_error_handler('\sb\Application\Debugger::errorHandler');
\set_exception_handler('\sb\Application\Debugger::exceptionHandler');
\register_shutdown_function('\sb\Application\Debugger::shutdown');
} | [
"public",
"static",
"function",
"init",
"(",
"$",
"error_reporting_level",
"=",
"E_ALL",
",",
"$",
"display_errors",
"=",
"true",
",",
"$",
"show_trace",
"=",
"true",
")",
"{",
"\\",
"error_reporting",
"(",
"$",
"error_reporting_level",
")",
";",
"\\",
"ini_set",
"(",
"\"display_errors\"",
",",
"$",
"display_errors",
"?",
"true",
":",
"false",
")",
";",
"self",
"::",
"$",
"show_trace",
"=",
"$",
"show_trace",
"?",
"true",
":",
"false",
";",
"\\",
"set_error_handler",
"(",
"'\\sb\\Application\\Debugger::errorHandler'",
")",
";",
"\\",
"set_exception_handler",
"(",
"'\\sb\\Application\\Debugger::exceptionHandler'",
")",
";",
"\\",
"register_shutdown_function",
"(",
"'\\sb\\Application\\Debugger::shutdown'",
")",
";",
"}"
] | Sets up debugger
@param string $error_reporting_level The error level like
@param boolean $display_errors Should errors be dumped to output
@param type $show_trace Should trace message be shown | [
"Sets",
"up",
"debugger"
] | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Application/Debugger.php#L103-L112 |
odiaseo/pagebuilder | src/PageBuilder/WidgetFactory.php | WidgetFactory.canCreate | public function canCreate(ContainerInterface $serviceLocator, $requestedName)
{
if (substr($requestedName, -6) == self::WIDGET_SUFFIX) {
/** @var $util \PageBuilder\Util\Widget */
$util = $serviceLocator->get('util\widget');
$widgetId = str_replace(self::WIDGET_SUFFIX, '', $requestedName);
return $util->widgetExist($widgetId);
}
return false;
} | php | public function canCreate(ContainerInterface $serviceLocator, $requestedName)
{
if (substr($requestedName, -6) == self::WIDGET_SUFFIX) {
/** @var $util \PageBuilder\Util\Widget */
$util = $serviceLocator->get('util\widget');
$widgetId = str_replace(self::WIDGET_SUFFIX, '', $requestedName);
return $util->widgetExist($widgetId);
}
return false;
} | [
"public",
"function",
"canCreate",
"(",
"ContainerInterface",
"$",
"serviceLocator",
",",
"$",
"requestedName",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"requestedName",
",",
"-",
"6",
")",
"==",
"self",
"::",
"WIDGET_SUFFIX",
")",
"{",
"/** @var $util \\PageBuilder\\Util\\Widget */",
"$",
"util",
"=",
"$",
"serviceLocator",
"->",
"get",
"(",
"'util\\widget'",
")",
";",
"$",
"widgetId",
"=",
"str_replace",
"(",
"self",
"::",
"WIDGET_SUFFIX",
",",
"''",
",",
"$",
"requestedName",
")",
";",
"return",
"$",
"util",
"->",
"widgetExist",
"(",
"$",
"widgetId",
")",
";",
"}",
"return",
"false",
";",
"}"
] | @param ContainerInterface $serviceLocator
@param string $requestedName
@return bool | [
"@param",
"ContainerInterface",
"$serviceLocator",
"@param",
"string",
"$requestedName"
] | train | https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/WidgetFactory.php#L27-L38 |
php-lug/lug | src/Component/Grid/Column/Type/Formatter/DateTimeFormatter.php | DateTimeFormatter.format | public function format($value, array $options = [])
{
if (!$value instanceof \DateTimeInterface) {
throw new InvalidTypeException(sprintf(
'The number formatter expects a numeric value, got "%s".',
is_object($value) ? get_class($value) : gettype($value)
));
}
$formatter = new \IntlDateFormatter(
$this->localeContext->getLocale(),
isset($options['date_format']) ? $options['date_format'] : \IntlDateFormatter::MEDIUM,
isset($options['time_format']) ? $options['time_format'] : \IntlDateFormatter::MEDIUM,
isset($options['timezone']) ? $options['timezone'] : $value->getTimezone(),
isset($options['calendar']) ? $options['calendar'] : null,
isset($options['pattern']) ? $options['pattern'] : null
);
$formatter->setLenient(isset($options['lenient']) ? $options['lenient'] : false);
return $formatter->format($value);
} | php | public function format($value, array $options = [])
{
if (!$value instanceof \DateTimeInterface) {
throw new InvalidTypeException(sprintf(
'The number formatter expects a numeric value, got "%s".',
is_object($value) ? get_class($value) : gettype($value)
));
}
$formatter = new \IntlDateFormatter(
$this->localeContext->getLocale(),
isset($options['date_format']) ? $options['date_format'] : \IntlDateFormatter::MEDIUM,
isset($options['time_format']) ? $options['time_format'] : \IntlDateFormatter::MEDIUM,
isset($options['timezone']) ? $options['timezone'] : $value->getTimezone(),
isset($options['calendar']) ? $options['calendar'] : null,
isset($options['pattern']) ? $options['pattern'] : null
);
$formatter->setLenient(isset($options['lenient']) ? $options['lenient'] : false);
return $formatter->format($value);
} | [
"public",
"function",
"format",
"(",
"$",
"value",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"\\",
"DateTimeInterface",
")",
"{",
"throw",
"new",
"InvalidTypeException",
"(",
"sprintf",
"(",
"'The number formatter expects a numeric value, got \"%s\".'",
",",
"is_object",
"(",
"$",
"value",
")",
"?",
"get_class",
"(",
"$",
"value",
")",
":",
"gettype",
"(",
"$",
"value",
")",
")",
")",
";",
"}",
"$",
"formatter",
"=",
"new",
"\\",
"IntlDateFormatter",
"(",
"$",
"this",
"->",
"localeContext",
"->",
"getLocale",
"(",
")",
",",
"isset",
"(",
"$",
"options",
"[",
"'date_format'",
"]",
")",
"?",
"$",
"options",
"[",
"'date_format'",
"]",
":",
"\\",
"IntlDateFormatter",
"::",
"MEDIUM",
",",
"isset",
"(",
"$",
"options",
"[",
"'time_format'",
"]",
")",
"?",
"$",
"options",
"[",
"'time_format'",
"]",
":",
"\\",
"IntlDateFormatter",
"::",
"MEDIUM",
",",
"isset",
"(",
"$",
"options",
"[",
"'timezone'",
"]",
")",
"?",
"$",
"options",
"[",
"'timezone'",
"]",
":",
"$",
"value",
"->",
"getTimezone",
"(",
")",
",",
"isset",
"(",
"$",
"options",
"[",
"'calendar'",
"]",
")",
"?",
"$",
"options",
"[",
"'calendar'",
"]",
":",
"null",
",",
"isset",
"(",
"$",
"options",
"[",
"'pattern'",
"]",
")",
"?",
"$",
"options",
"[",
"'pattern'",
"]",
":",
"null",
")",
";",
"$",
"formatter",
"->",
"setLenient",
"(",
"isset",
"(",
"$",
"options",
"[",
"'lenient'",
"]",
")",
"?",
"$",
"options",
"[",
"'lenient'",
"]",
":",
"false",
")",
";",
"return",
"$",
"formatter",
"->",
"format",
"(",
"$",
"value",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/Column/Type/Formatter/DateTimeFormatter.php#L38-L59 |
PayBreak/foundation | src/Data/Value.php | Value.availableTypes | public static function availableTypes()
{
return [
self::VALUE_INT,
self::VALUE_STRING,
self::VALUE_BOOL,
self::VALUE_FLOAT,
self::VALUE_DEFAULT,
self::VALUE_NON_EXISTS,
self::VALUE_EMPTY,
self::VALUE_ARRAY,
];
} | php | public static function availableTypes()
{
return [
self::VALUE_INT,
self::VALUE_STRING,
self::VALUE_BOOL,
self::VALUE_FLOAT,
self::VALUE_DEFAULT,
self::VALUE_NON_EXISTS,
self::VALUE_EMPTY,
self::VALUE_ARRAY,
];
} | [
"public",
"static",
"function",
"availableTypes",
"(",
")",
"{",
"return",
"[",
"self",
"::",
"VALUE_INT",
",",
"self",
"::",
"VALUE_STRING",
",",
"self",
"::",
"VALUE_BOOL",
",",
"self",
"::",
"VALUE_FLOAT",
",",
"self",
"::",
"VALUE_DEFAULT",
",",
"self",
"::",
"VALUE_NON_EXISTS",
",",
"self",
"::",
"VALUE_EMPTY",
",",
"self",
"::",
"VALUE_ARRAY",
",",
"]",
";",
"}"
] | Get Available Value Types
@author WN
@return array | [
"Get",
"Available",
"Value",
"Types"
] | train | https://github.com/PayBreak/foundation/blob/3dc5a5791e0c95abefa2a415a7f9fdb5abb62ca4/src/Data/Value.php#L56-L68 |
PayBreak/foundation | src/Data/Value.php | Value.availableDefaultValues | public static function availableDefaultValues()
{
return [
self::DEFAULT_NULL,
self::DEFAULT_OUT_OF_BOUNDS,
self::DEFAULT_NOT_DERIVABLE,
self::DEFAULT_NOT_GIVEN,
self::DEFAULT_NOT_ASKED,
self::DEFAULT_NOT_PERMITTED,
];
} | php | public static function availableDefaultValues()
{
return [
self::DEFAULT_NULL,
self::DEFAULT_OUT_OF_BOUNDS,
self::DEFAULT_NOT_DERIVABLE,
self::DEFAULT_NOT_GIVEN,
self::DEFAULT_NOT_ASKED,
self::DEFAULT_NOT_PERMITTED,
];
} | [
"public",
"static",
"function",
"availableDefaultValues",
"(",
")",
"{",
"return",
"[",
"self",
"::",
"DEFAULT_NULL",
",",
"self",
"::",
"DEFAULT_OUT_OF_BOUNDS",
",",
"self",
"::",
"DEFAULT_NOT_DERIVABLE",
",",
"self",
"::",
"DEFAULT_NOT_GIVEN",
",",
"self",
"::",
"DEFAULT_NOT_ASKED",
",",
"self",
"::",
"DEFAULT_NOT_PERMITTED",
",",
"]",
";",
"}"
] | Get Available Default Values
@author WN
@return array | [
"Get",
"Available",
"Default",
"Values"
] | train | https://github.com/PayBreak/foundation/blob/3dc5a5791e0c95abefa2a415a7f9fdb5abb62ca4/src/Data/Value.php#L76-L86 |
mainio/c5pkg_symfony_forms | src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/UserToIntegerTransformer.php | UserToIntegerTransformer.transform | public function transform($value)
{
if ($value === null || $value == '') {
return null;
}
if (!($value instanceof User)) {
throw new TransformationFailedException('Expected an instance of a concrete5 user object.');
}
return intval($value->getUserID());
} | php | public function transform($value)
{
if ($value === null || $value == '') {
return null;
}
if (!($value instanceof User)) {
throw new TransformationFailedException('Expected an instance of a concrete5 user object.');
}
return intval($value->getUserID());
} | [
"public",
"function",
"transform",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
"||",
"$",
"value",
"==",
"''",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"value",
"instanceof",
"User",
")",
")",
"{",
"throw",
"new",
"TransformationFailedException",
"(",
"'Expected an instance of a concrete5 user object.'",
")",
";",
"}",
"return",
"intval",
"(",
"$",
"value",
"->",
"getUserID",
"(",
")",
")",
";",
"}"
] | Converts a concrete5 user object to an integer.
@param \Concrete\Core\User\User $value The user object value
@return int The integer value
@throws TransformationFailedException If the given value is not an
instance of Concrete\Core\User\User. | [
"Converts",
"a",
"concrete5",
"user",
"object",
"to",
"an",
"integer",
"."
] | train | https://github.com/mainio/c5pkg_symfony_forms/blob/41a93c293d986574ec5cade8a7c8700e083dbaaa/src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/UserToIntegerTransformer.php#L33-L42 |
mainio/c5pkg_symfony_forms | src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/UserToIntegerTransformer.php | UserToIntegerTransformer.reverseTransform | public function reverseTransform($uID)
{
if (!is_numeric($uID) || $uID == 0) {
return null;
}
$rep = $this->entityManager->getRepository('Concrete\Core\User\User');
$u = $rep->find($uID);
if (!is_object($u) || $u->isError()) {
throw new TransformationFailedException('Invalid user ID.');
}
return $u;
} | php | public function reverseTransform($uID)
{
if (!is_numeric($uID) || $uID == 0) {
return null;
}
$rep = $this->entityManager->getRepository('Concrete\Core\User\User');
$u = $rep->find($uID);
if (!is_object($u) || $u->isError()) {
throw new TransformationFailedException('Invalid user ID.');
}
return $u;
} | [
"public",
"function",
"reverseTransform",
"(",
"$",
"uID",
")",
"{",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"uID",
")",
"||",
"$",
"uID",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"$",
"rep",
"=",
"$",
"this",
"->",
"entityManager",
"->",
"getRepository",
"(",
"'Concrete\\Core\\User\\User'",
")",
";",
"$",
"u",
"=",
"$",
"rep",
"->",
"find",
"(",
"$",
"uID",
")",
";",
"if",
"(",
"!",
"is_object",
"(",
"$",
"u",
")",
"||",
"$",
"u",
"->",
"isError",
"(",
")",
")",
"{",
"throw",
"new",
"TransformationFailedException",
"(",
"'Invalid user ID.'",
")",
";",
"}",
"return",
"$",
"u",
";",
"}"
] | Converts an integer to a concrete5 page object.
@param int $uID
@return mixed The value
@throws TransformationFailedException If the given value is not a proper
concrete5 page ID. | [
"Converts",
"an",
"integer",
"to",
"a",
"concrete5",
"page",
"object",
"."
] | train | https://github.com/mainio/c5pkg_symfony_forms/blob/41a93c293d986574ec5cade8a7c8700e083dbaaa/src/Mainio/C5/Symfony/Form/Extension/Concrete5/DataTransformer/UserToIntegerTransformer.php#L52-L66 |
superjimpupcake/Pupcake | src/Pupcake/Plugin.php | Plugin.help | public function help($event_name, $callback)
{
if (!isset($this->event_helpers[$event_name]))
{
$this->event_helpers[$event_name] = $callback;
}
} | php | public function help($event_name, $callback)
{
if (!isset($this->event_helpers[$event_name]))
{
$this->event_helpers[$event_name] = $callback;
}
} | [
"public",
"function",
"help",
"(",
"$",
"event_name",
",",
"$",
"callback",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"event_helpers",
"[",
"$",
"event_name",
"]",
")",
")",
"{",
"$",
"this",
"->",
"event_helpers",
"[",
"$",
"event_name",
"]",
"=",
"$",
"callback",
";",
"}",
"}"
] | add a helper callback to an event | [
"add",
"a",
"helper",
"callback",
"to",
"an",
"event"
] | train | https://github.com/superjimpupcake/Pupcake/blob/2f962818646e4e1d65f5d008eeb953cb41ebb3e0/src/Pupcake/Plugin.php#L46-L52 |
superjimpupcake/Pupcake | src/Pupcake/Plugin.php | Plugin.trigger | public function trigger($event_name, $default_handler_callback = "", $event_properties = array())
{
//pass all the params along
return $this->app->trigger($event_name, $default_handler_callback, $event_properties);
} | php | public function trigger($event_name, $default_handler_callback = "", $event_properties = array())
{
//pass all the params along
return $this->app->trigger($event_name, $default_handler_callback, $event_properties);
} | [
"public",
"function",
"trigger",
"(",
"$",
"event_name",
",",
"$",
"default_handler_callback",
"=",
"\"\"",
",",
"$",
"event_properties",
"=",
"array",
"(",
")",
")",
"{",
"//pass all the params along",
"return",
"$",
"this",
"->",
"app",
"->",
"trigger",
"(",
"$",
"event_name",
",",
"$",
"default_handler_callback",
",",
"$",
"event_properties",
")",
";",
"}"
] | trigger an event | [
"trigger",
"an",
"event"
] | train | https://github.com/superjimpupcake/Pupcake/blob/2f962818646e4e1d65f5d008eeb953cb41ebb3e0/src/Pupcake/Plugin.php#L66-L70 |
old-town/workflow-designer-server | src/Listener/SendApiProblemResponseListener.php | SendApiProblemResponseListener.sendContent | public function sendContent(SendResponseEvent $e)
{
$response = $e->getResponse();
if (!$response instanceof ApiProblemResponse) {
return $this;
}
$response->getApiProblem()->setDetailIncludesStackTrace($this->displayExceptions());
/** @var Request $request */
$request = $this->getMvcEvent()->getRequest();
/** @var Accept $accept */
$accept = $request->getHeader('Accept');
if ($accept instanceof Accept && $accept->hasMediaType('text/xml')) {
$arrayResponse = $response->getApiProblem()->toArray();
$xmlWriter = new XmlWriter();
if (array_key_exists('trace', $arrayResponse)) {
array_walk($arrayResponse['trace'], function (&$item) {
unset($item['args']);
});
}
if (array_key_exists('exception_stack', $arrayResponse)) {
array_walk($arrayResponse['exception_stack'], function (&$item) {
array_walk($item['trace'], function (&$trace) {
unset($trace['args']);
});
});
}
$output = $xmlWriter->processConfig($arrayResponse);
echo $output;
$e->setContentSent();
return $this;
}
return parent::sendHeaders($e);
} | php | public function sendContent(SendResponseEvent $e)
{
$response = $e->getResponse();
if (!$response instanceof ApiProblemResponse) {
return $this;
}
$response->getApiProblem()->setDetailIncludesStackTrace($this->displayExceptions());
/** @var Request $request */
$request = $this->getMvcEvent()->getRequest();
/** @var Accept $accept */
$accept = $request->getHeader('Accept');
if ($accept instanceof Accept && $accept->hasMediaType('text/xml')) {
$arrayResponse = $response->getApiProblem()->toArray();
$xmlWriter = new XmlWriter();
if (array_key_exists('trace', $arrayResponse)) {
array_walk($arrayResponse['trace'], function (&$item) {
unset($item['args']);
});
}
if (array_key_exists('exception_stack', $arrayResponse)) {
array_walk($arrayResponse['exception_stack'], function (&$item) {
array_walk($item['trace'], function (&$trace) {
unset($trace['args']);
});
});
}
$output = $xmlWriter->processConfig($arrayResponse);
echo $output;
$e->setContentSent();
return $this;
}
return parent::sendHeaders($e);
} | [
"public",
"function",
"sendContent",
"(",
"SendResponseEvent",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"e",
"->",
"getResponse",
"(",
")",
";",
"if",
"(",
"!",
"$",
"response",
"instanceof",
"ApiProblemResponse",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"response",
"->",
"getApiProblem",
"(",
")",
"->",
"setDetailIncludesStackTrace",
"(",
"$",
"this",
"->",
"displayExceptions",
"(",
")",
")",
";",
"/** @var Request $request */",
"$",
"request",
"=",
"$",
"this",
"->",
"getMvcEvent",
"(",
")",
"->",
"getRequest",
"(",
")",
";",
"/** @var Accept $accept */",
"$",
"accept",
"=",
"$",
"request",
"->",
"getHeader",
"(",
"'Accept'",
")",
";",
"if",
"(",
"$",
"accept",
"instanceof",
"Accept",
"&&",
"$",
"accept",
"->",
"hasMediaType",
"(",
"'text/xml'",
")",
")",
"{",
"$",
"arrayResponse",
"=",
"$",
"response",
"->",
"getApiProblem",
"(",
")",
"->",
"toArray",
"(",
")",
";",
"$",
"xmlWriter",
"=",
"new",
"XmlWriter",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"'trace'",
",",
"$",
"arrayResponse",
")",
")",
"{",
"array_walk",
"(",
"$",
"arrayResponse",
"[",
"'trace'",
"]",
",",
"function",
"(",
"&",
"$",
"item",
")",
"{",
"unset",
"(",
"$",
"item",
"[",
"'args'",
"]",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'exception_stack'",
",",
"$",
"arrayResponse",
")",
")",
"{",
"array_walk",
"(",
"$",
"arrayResponse",
"[",
"'exception_stack'",
"]",
",",
"function",
"(",
"&",
"$",
"item",
")",
"{",
"array_walk",
"(",
"$",
"item",
"[",
"'trace'",
"]",
",",
"function",
"(",
"&",
"$",
"trace",
")",
"{",
"unset",
"(",
"$",
"trace",
"[",
"'args'",
"]",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"$",
"output",
"=",
"$",
"xmlWriter",
"->",
"processConfig",
"(",
"$",
"arrayResponse",
")",
";",
"echo",
"$",
"output",
";",
"$",
"e",
"->",
"setContentSent",
"(",
")",
";",
"return",
"$",
"this",
";",
"}",
"return",
"parent",
"::",
"sendHeaders",
"(",
"$",
"e",
")",
";",
"}"
] | Send the response content
Sets the composed ApiProblem's flag for including the stack trace in the
detail based on the display exceptions flag, and then sends content.
@param SendResponseEvent $e
@return self
@throws \Zend\Config\Exception\RuntimeException | [
"Send",
"the",
"response",
"content"
] | train | https://github.com/old-town/workflow-designer-server/blob/6389c5a515861cc8e0b769f1ca7be12c6b78c611/src/Listener/SendApiProblemResponseListener.php#L63-L102 |
old-town/workflow-designer-server | src/Listener/SendApiProblemResponseListener.php | SendApiProblemResponseListener.sendHeaders | public function sendHeaders(SendResponseEvent $e)
{
$response = $e->getResponse();
if (!$response instanceof ApiProblemResponse) {
return $this;
}
/** @var Request $request */
$request = $this->getMvcEvent()->getRequest();
/** @var Accept $accept */
$accept = $request->getHeader('Accept');
if ($accept instanceof Accept && $accept->hasMediaType('text/xml')) {
$headers = $response->getHeaders();
if ($headers->has('content-type')) {
$contentTypeHeader = $headers->get('content-type');
$headers->removeHeader($contentTypeHeader);
}
$headers->addHeaderLine('content-type', 'text/xml');
if ($this->applicationResponse instanceof HttpResponse) {
$this->mergeHeaders($this->applicationResponse, $response);
}
}
return parent::sendHeaders($e);
} | php | public function sendHeaders(SendResponseEvent $e)
{
$response = $e->getResponse();
if (!$response instanceof ApiProblemResponse) {
return $this;
}
/** @var Request $request */
$request = $this->getMvcEvent()->getRequest();
/** @var Accept $accept */
$accept = $request->getHeader('Accept');
if ($accept instanceof Accept && $accept->hasMediaType('text/xml')) {
$headers = $response->getHeaders();
if ($headers->has('content-type')) {
$contentTypeHeader = $headers->get('content-type');
$headers->removeHeader($contentTypeHeader);
}
$headers->addHeaderLine('content-type', 'text/xml');
if ($this->applicationResponse instanceof HttpResponse) {
$this->mergeHeaders($this->applicationResponse, $response);
}
}
return parent::sendHeaders($e);
} | [
"public",
"function",
"sendHeaders",
"(",
"SendResponseEvent",
"$",
"e",
")",
"{",
"$",
"response",
"=",
"$",
"e",
"->",
"getResponse",
"(",
")",
";",
"if",
"(",
"!",
"$",
"response",
"instanceof",
"ApiProblemResponse",
")",
"{",
"return",
"$",
"this",
";",
"}",
"/** @var Request $request */",
"$",
"request",
"=",
"$",
"this",
"->",
"getMvcEvent",
"(",
")",
"->",
"getRequest",
"(",
")",
";",
"/** @var Accept $accept */",
"$",
"accept",
"=",
"$",
"request",
"->",
"getHeader",
"(",
"'Accept'",
")",
";",
"if",
"(",
"$",
"accept",
"instanceof",
"Accept",
"&&",
"$",
"accept",
"->",
"hasMediaType",
"(",
"'text/xml'",
")",
")",
"{",
"$",
"headers",
"=",
"$",
"response",
"->",
"getHeaders",
"(",
")",
";",
"if",
"(",
"$",
"headers",
"->",
"has",
"(",
"'content-type'",
")",
")",
"{",
"$",
"contentTypeHeader",
"=",
"$",
"headers",
"->",
"get",
"(",
"'content-type'",
")",
";",
"$",
"headers",
"->",
"removeHeader",
"(",
"$",
"contentTypeHeader",
")",
";",
"}",
"$",
"headers",
"->",
"addHeaderLine",
"(",
"'content-type'",
",",
"'text/xml'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"applicationResponse",
"instanceof",
"HttpResponse",
")",
"{",
"$",
"this",
"->",
"mergeHeaders",
"(",
"$",
"this",
"->",
"applicationResponse",
",",
"$",
"response",
")",
";",
"}",
"}",
"return",
"parent",
"::",
"sendHeaders",
"(",
"$",
"e",
")",
";",
"}"
] | Send HTTP response headers
If an application response is composed, and is an HTTP response, merges
its headers with the ApiProblemResponse headers prior to sending them.
@param SendResponseEvent $e
@return self
@throws \Zend\Http\Exception\InvalidArgumentException | [
"Send",
"HTTP",
"response",
"headers"
] | train | https://github.com/old-town/workflow-designer-server/blob/6389c5a515861cc8e0b769f1ca7be12c6b78c611/src/Listener/SendApiProblemResponseListener.php#L115-L143 |
antaresproject/notifications | src/Console/NotificationsRemover.php | NotificationsRemover.handle | public function handle()
{
$days = (int) app('antares.memory')->make('primary')->get('notifications_remove_after_days', '');
if (!$days) {
$this->comment('Configuration for remove notifications logs is not configured. Ignoring.');
return;
}
$logs = $this->builder->where('created_at', 'like', DB::raw("DATE(DATE_ADD(NOW(), INTERVAL +{$days} DAY))"));
$count = $logs->count();
if (!$count) {
$this->comment('There are no notification logs available. Ignoring.');
return;
}
$logs->delete();
$this->line(sprintf('%d notification logs has been deleted.', $count));
} | php | public function handle()
{
$days = (int) app('antares.memory')->make('primary')->get('notifications_remove_after_days', '');
if (!$days) {
$this->comment('Configuration for remove notifications logs is not configured. Ignoring.');
return;
}
$logs = $this->builder->where('created_at', 'like', DB::raw("DATE(DATE_ADD(NOW(), INTERVAL +{$days} DAY))"));
$count = $logs->count();
if (!$count) {
$this->comment('There are no notification logs available. Ignoring.');
return;
}
$logs->delete();
$this->line(sprintf('%d notification logs has been deleted.', $count));
} | [
"public",
"function",
"handle",
"(",
")",
"{",
"$",
"days",
"=",
"(",
"int",
")",
"app",
"(",
"'antares.memory'",
")",
"->",
"make",
"(",
"'primary'",
")",
"->",
"get",
"(",
"'notifications_remove_after_days'",
",",
"''",
")",
";",
"if",
"(",
"!",
"$",
"days",
")",
"{",
"$",
"this",
"->",
"comment",
"(",
"'Configuration for remove notifications logs is not configured. Ignoring.'",
")",
";",
"return",
";",
"}",
"$",
"logs",
"=",
"$",
"this",
"->",
"builder",
"->",
"where",
"(",
"'created_at'",
",",
"'like'",
",",
"DB",
"::",
"raw",
"(",
"\"DATE(DATE_ADD(NOW(), INTERVAL +{$days} DAY))\"",
")",
")",
";",
"$",
"count",
"=",
"$",
"logs",
"->",
"count",
"(",
")",
";",
"if",
"(",
"!",
"$",
"count",
")",
"{",
"$",
"this",
"->",
"comment",
"(",
"'There are no notification logs available. Ignoring.'",
")",
";",
"return",
";",
"}",
"$",
"logs",
"->",
"delete",
"(",
")",
";",
"$",
"this",
"->",
"line",
"(",
"sprintf",
"(",
"'%d notification logs has been deleted.'",
",",
"$",
"count",
")",
")",
";",
"}"
] | Execute the console command.
@return void | [
"Execute",
"the",
"console",
"command",
"."
] | train | https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Console/NotificationsRemover.php#L101-L116 |
hametuha/wpametu | src/WPametu.php | WPametu.entry | public static function entry( $namespace = '', $base = '' ) {
if ( ! self::$initialized ) {
self::init();
}
// Namespace is specified.
AutoLoader::get_instance()->register_namespace( $namespace, $base );
} | php | public static function entry( $namespace = '', $base = '' ) {
if ( ! self::$initialized ) {
self::init();
}
// Namespace is specified.
AutoLoader::get_instance()->register_namespace( $namespace, $base );
} | [
"public",
"static",
"function",
"entry",
"(",
"$",
"namespace",
"=",
"''",
",",
"$",
"base",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"initialized",
")",
"{",
"self",
"::",
"init",
"(",
")",
";",
"}",
"// Namespace is specified.",
"AutoLoader",
"::",
"get_instance",
"(",
")",
"->",
"register_namespace",
"(",
"$",
"namespace",
",",
"$",
"base",
")",
";",
"}"
] | Initialize WPametu
@param string $namespace Namespace base to scan
@param string $base Namespace root directory path | [
"Initialize",
"WPametu"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu.php#L43-L49 |
hametuha/wpametu | src/WPametu.php | WPametu.init | private static function init() {
// Avoid double initialization
if ( self::$initialized ) {
trigger_error( 'Do not call WPametu::init twice!', E_USER_WARNING );
return;
}
// Todo: i18n for plugin
load_theme_textdomain( self::DOMAIN, dirname( __DIR__ ) . '/i18n' );
// Check version
if ( version_compare( phpversion(), self::PHP_VERSION, '<' ) ) {
trigger_error( sprintf( __( 'PHP version should be %s and over. Your version is %s.', self::DOMAIN ), self::PHP_VERSION, phpversion() ), E_USER_WARNING );
return;
}
// Fire AutoLoader
AutoLoader::get_instance();
self::$initialized = true;
} | php | private static function init() {
// Avoid double initialization
if ( self::$initialized ) {
trigger_error( 'Do not call WPametu::init twice!', E_USER_WARNING );
return;
}
// Todo: i18n for plugin
load_theme_textdomain( self::DOMAIN, dirname( __DIR__ ) . '/i18n' );
// Check version
if ( version_compare( phpversion(), self::PHP_VERSION, '<' ) ) {
trigger_error( sprintf( __( 'PHP version should be %s and over. Your version is %s.', self::DOMAIN ), self::PHP_VERSION, phpversion() ), E_USER_WARNING );
return;
}
// Fire AutoLoader
AutoLoader::get_instance();
self::$initialized = true;
} | [
"private",
"static",
"function",
"init",
"(",
")",
"{",
"// Avoid double initialization",
"if",
"(",
"self",
"::",
"$",
"initialized",
")",
"{",
"trigger_error",
"(",
"'Do not call WPametu::init twice!'",
",",
"E_USER_WARNING",
")",
";",
"return",
";",
"}",
"// Todo: i18n for plugin",
"load_theme_textdomain",
"(",
"self",
"::",
"DOMAIN",
",",
"dirname",
"(",
"__DIR__",
")",
".",
"'/i18n'",
")",
";",
"// Check version",
"if",
"(",
"version_compare",
"(",
"phpversion",
"(",
")",
",",
"self",
"::",
"PHP_VERSION",
",",
"'<'",
")",
")",
"{",
"trigger_error",
"(",
"sprintf",
"(",
"__",
"(",
"'PHP version should be %s and over. Your version is %s.'",
",",
"self",
"::",
"DOMAIN",
")",
",",
"self",
"::",
"PHP_VERSION",
",",
"phpversion",
"(",
")",
")",
",",
"E_USER_WARNING",
")",
";",
"return",
";",
"}",
"// Fire AutoLoader",
"AutoLoader",
"::",
"get_instance",
"(",
")",
";",
"self",
"::",
"$",
"initialized",
"=",
"true",
";",
"}"
] | Initialize WPametu | [
"Initialize",
"WPametu"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu.php#L54-L72 |
ellipsephp/session-validation | src/ValidateSessionMiddleware.php | ValidateSessionMiddleware.process | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Get a valid signature.
$signature = ($this->signature)($request);
if (! is_array($signature)) {
throw new OwnershipSignatureTypeException($signature);
}
// Invalidate the session when signature and session does not match.
$metadata = $_SESSION[self::METADATA_KEY] ?? [];
if (! $this->compare($signature, $metadata)) {
$_SESSION = [];
session_regenerate_id();
}
// Process the request and save the current signature.
$response = $handler->handle($request);
$_SESSION[self::METADATA_KEY] = $signature;
return $response;
} | php | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Get a valid signature.
$signature = ($this->signature)($request);
if (! is_array($signature)) {
throw new OwnershipSignatureTypeException($signature);
}
// Invalidate the session when signature and session does not match.
$metadata = $_SESSION[self::METADATA_KEY] ?? [];
if (! $this->compare($signature, $metadata)) {
$_SESSION = [];
session_regenerate_id();
}
// Process the request and save the current signature.
$response = $handler->handle($request);
$_SESSION[self::METADATA_KEY] = $signature;
return $response;
} | [
"public",
"function",
"process",
"(",
"ServerRequestInterface",
"$",
"request",
",",
"RequestHandlerInterface",
"$",
"handler",
")",
":",
"ResponseInterface",
"{",
"// Get a valid signature.",
"$",
"signature",
"=",
"(",
"$",
"this",
"->",
"signature",
")",
"(",
"$",
"request",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"signature",
")",
")",
"{",
"throw",
"new",
"OwnershipSignatureTypeException",
"(",
"$",
"signature",
")",
";",
"}",
"// Invalidate the session when signature and session does not match.",
"$",
"metadata",
"=",
"$",
"_SESSION",
"[",
"self",
"::",
"METADATA_KEY",
"]",
"??",
"[",
"]",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"compare",
"(",
"$",
"signature",
",",
"$",
"metadata",
")",
")",
"{",
"$",
"_SESSION",
"=",
"[",
"]",
";",
"session_regenerate_id",
"(",
")",
";",
"}",
"// Process the request and save the current signature.",
"$",
"response",
"=",
"$",
"handler",
"->",
"handle",
"(",
"$",
"request",
")",
";",
"$",
"_SESSION",
"[",
"self",
"::",
"METADATA_KEY",
"]",
"=",
"$",
"signature",
";",
"return",
"$",
"response",
";",
"}"
] | Build a signature and compare it to the ownership metadata stored in
session. Invalidate the session when any key does not match. Process the
request and save the current signature in session.
@param \Psr\Http\Message\ServerRequestInterface $request
@param \Psr\Http\Server\RequestHandlerInterface $handler
@return \Psr\Http\Message\ResponseInterface | [
"Build",
"a",
"signature",
"and",
"compare",
"it",
"to",
"the",
"ownership",
"metadata",
"stored",
"in",
"session",
".",
"Invalidate",
"the",
"session",
"when",
"any",
"key",
"does",
"not",
"match",
".",
"Process",
"the",
"request",
"and",
"save",
"the",
"current",
"signature",
"in",
"session",
"."
] | train | https://github.com/ellipsephp/session-validation/blob/c5d8bd0aed23abe0933f649b9e20ff48ab9efbc9/src/ValidateSessionMiddleware.php#L47-L74 |
ellipsephp/session-validation | src/ValidateSessionMiddleware.php | ValidateSessionMiddleware.compare | private function compare(array $signature, array $metadata): bool
{
foreach ($signature as $key => $v1) {
$v2 = $metadata[$key] ?? null;
if (! is_null($v2) && $v1 !== $v2) return false;
}
return true;
} | php | private function compare(array $signature, array $metadata): bool
{
foreach ($signature as $key => $v1) {
$v2 = $metadata[$key] ?? null;
if (! is_null($v2) && $v1 !== $v2) return false;
}
return true;
} | [
"private",
"function",
"compare",
"(",
"array",
"$",
"signature",
",",
"array",
"$",
"metadata",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"signature",
"as",
"$",
"key",
"=>",
"$",
"v1",
")",
"{",
"$",
"v2",
"=",
"$",
"metadata",
"[",
"$",
"key",
"]",
"??",
"null",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"v2",
")",
"&&",
"$",
"v1",
"!==",
"$",
"v2",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Return whether all keys of the given signature match the given metadata.
@param array $signature
@param array $metadata
@return bool | [
"Return",
"whether",
"all",
"keys",
"of",
"the",
"given",
"signature",
"match",
"the",
"given",
"metadata",
"."
] | train | https://github.com/ellipsephp/session-validation/blob/c5d8bd0aed23abe0933f649b9e20ff48ab9efbc9/src/ValidateSessionMiddleware.php#L83-L94 |
purocean/php-wechat-sdk | src/Mpwx.php | Mpwx.getAuth | public function getAuth($code)
{
$result = $this->_curl(
'https://api.weixin.qq.com/sns/oauth2/access_token',
[
'appid' => $this->getConfig('appid'),
'secret' => $this->getConfig('secret'),
'code' => $code,
'grant_type' => 'authorization_code',
]
);
if ($result) {
return [
'access_token' => $result['access_token'],
'openid' => $result['openid'],
];
}
return false;
} | php | public function getAuth($code)
{
$result = $this->_curl(
'https://api.weixin.qq.com/sns/oauth2/access_token',
[
'appid' => $this->getConfig('appid'),
'secret' => $this->getConfig('secret'),
'code' => $code,
'grant_type' => 'authorization_code',
]
);
if ($result) {
return [
'access_token' => $result['access_token'],
'openid' => $result['openid'],
];
}
return false;
} | [
"public",
"function",
"getAuth",
"(",
"$",
"code",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"_curl",
"(",
"'https://api.weixin.qq.com/sns/oauth2/access_token'",
",",
"[",
"'appid'",
"=>",
"$",
"this",
"->",
"getConfig",
"(",
"'appid'",
")",
",",
"'secret'",
"=>",
"$",
"this",
"->",
"getConfig",
"(",
"'secret'",
")",
",",
"'code'",
"=>",
"$",
"code",
",",
"'grant_type'",
"=>",
"'authorization_code'",
",",
"]",
")",
";",
"if",
"(",
"$",
"result",
")",
"{",
"return",
"[",
"'access_token'",
"=>",
"$",
"result",
"[",
"'access_token'",
"]",
",",
"'openid'",
"=>",
"$",
"result",
"[",
"'openid'",
"]",
",",
"]",
";",
"}",
"return",
"false",
";",
"}"
] | 获取网页授权 Access Token 和 Openid
这里暂时不做缓存
@param string $code 网页授权 code
@return array|false | [
"获取网页授权",
"Access",
"Token",
"和",
"Openid",
"这里暂时不做缓存"
] | train | https://github.com/purocean/php-wechat-sdk/blob/a369c4f8b8a24e54ecc505d0432b4479c0a9e827/src/Mpwx.php#L76-L96 |
purocean/php-wechat-sdk | src/Mpwx.php | Mpwx.getUserInfo | public function getUserInfo($accessToken, $openid)
{
$apiUrl = 'https://api.weixin.qq.com/sns/userinfo';
if ($result = $this->_curl($apiUrl, [
'access_token' => $accessToken,
'openid' => $openid,
'lang' => 'zh_CN',
])) {
unset($result['errcode'], $result['errmsg']);
return $result;
} else {
return null;
}
} | php | public function getUserInfo($accessToken, $openid)
{
$apiUrl = 'https://api.weixin.qq.com/sns/userinfo';
if ($result = $this->_curl($apiUrl, [
'access_token' => $accessToken,
'openid' => $openid,
'lang' => 'zh_CN',
])) {
unset($result['errcode'], $result['errmsg']);
return $result;
} else {
return null;
}
} | [
"public",
"function",
"getUserInfo",
"(",
"$",
"accessToken",
",",
"$",
"openid",
")",
"{",
"$",
"apiUrl",
"=",
"'https://api.weixin.qq.com/sns/userinfo'",
";",
"if",
"(",
"$",
"result",
"=",
"$",
"this",
"->",
"_curl",
"(",
"$",
"apiUrl",
",",
"[",
"'access_token'",
"=>",
"$",
"accessToken",
",",
"'openid'",
"=>",
"$",
"openid",
",",
"'lang'",
"=>",
"'zh_CN'",
",",
"]",
")",
")",
"{",
"unset",
"(",
"$",
"result",
"[",
"'errcode'",
"]",
",",
"$",
"result",
"[",
"'errmsg'",
"]",
")",
";",
"return",
"$",
"result",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | 获取某个用户的信息.
@param string $accessToken 网页授权的 Access Token,可由 getAuth 方法获取
@param string $openid 用户的 openid,可由 getAuth 方法获取
@return array | [
"获取某个用户的信息",
"."
] | train | https://github.com/purocean/php-wechat-sdk/blob/a369c4f8b8a24e54ecc505d0432b4479c0a9e827/src/Mpwx.php#L182-L196 |
purocean/php-wechat-sdk | src/Mpwx.php | Mpwx.getJsApiPackage | public function getJsApiPackage($url = null)
{
$jsapiTicket = $this->getJsApiTicket();
if (is_null($url)) {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
$url = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
$timestamp = time();
$nonceStr = base64_encode(openssl_random_pseudo_bytes(24));
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}";
$signature = sha1($string);
$signPackage = [
'appid' => $this->getConfig('appid'),
'nonceStr' => $nonceStr,
'timestamp' => $timestamp,
'url' => $url,
'signature' => $signature,
'rawString' => $string,
];
return $signPackage;
} | php | public function getJsApiPackage($url = null)
{
$jsapiTicket = $this->getJsApiTicket();
if (is_null($url)) {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
$url = $protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
}
$timestamp = time();
$nonceStr = base64_encode(openssl_random_pseudo_bytes(24));
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}";
$signature = sha1($string);
$signPackage = [
'appid' => $this->getConfig('appid'),
'nonceStr' => $nonceStr,
'timestamp' => $timestamp,
'url' => $url,
'signature' => $signature,
'rawString' => $string,
];
return $signPackage;
} | [
"public",
"function",
"getJsApiPackage",
"(",
"$",
"url",
"=",
"null",
")",
"{",
"$",
"jsapiTicket",
"=",
"$",
"this",
"->",
"getJsApiTicket",
"(",
")",
";",
"if",
"(",
"is_null",
"(",
"$",
"url",
")",
")",
"{",
"$",
"protocol",
"=",
"(",
"!",
"empty",
"(",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
")",
"&&",
"$",
"_SERVER",
"[",
"'HTTPS'",
"]",
"!==",
"'off'",
"||",
"$",
"_SERVER",
"[",
"'SERVER_PORT'",
"]",
"==",
"443",
")",
"?",
"'https://'",
":",
"'http://'",
";",
"$",
"url",
"=",
"$",
"protocol",
".",
"$",
"_SERVER",
"[",
"'HTTP_HOST'",
"]",
".",
"$",
"_SERVER",
"[",
"'REQUEST_URI'",
"]",
";",
"}",
"$",
"timestamp",
"=",
"time",
"(",
")",
";",
"$",
"nonceStr",
"=",
"base64_encode",
"(",
"openssl_random_pseudo_bytes",
"(",
"24",
")",
")",
";",
"// 这里参数的顺序要按照 key 值 ASCII 码升序排序",
"$",
"string",
"=",
"\"jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}\"",
";",
"$",
"signature",
"=",
"sha1",
"(",
"$",
"string",
")",
";",
"$",
"signPackage",
"=",
"[",
"'appid'",
"=>",
"$",
"this",
"->",
"getConfig",
"(",
"'appid'",
")",
",",
"'nonceStr'",
"=>",
"$",
"nonceStr",
",",
"'timestamp'",
"=>",
"$",
"timestamp",
",",
"'url'",
"=>",
"$",
"url",
",",
"'signature'",
"=>",
"$",
"signature",
",",
"'rawString'",
"=>",
"$",
"string",
",",
"]",
";",
"return",
"$",
"signPackage",
";",
"}"
] | 获取微信 JS API 签名包
@param string $url 要签名的网址,不提供则为当前地址
@return array 签名包 | [
"获取微信",
"JS",
"API",
"签名包"
] | train | https://github.com/purocean/php-wechat-sdk/blob/a369c4f8b8a24e54ecc505d0432b4479c0a9e827/src/Mpwx.php#L205-L232 |
purocean/php-wechat-sdk | src/Mpwx.php | Mpwx.sendTplMsg | public function sendTplMsg($tplId, $data, $url, $openid, $topcolor = '#FF0000', $accessToken = null)
{
if (is_null($accessToken)) {
$accessToken = $this->getAccessToken();
}
$postData = [
'touser' => $openid,
'template_id' => $tplId,
'url' => $url,
'topcolor' => $topcolor,
'data' => $data,
];
$apiUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$accessToken;
$result = $this->_curl($apiUrl, json_encode($postData), 'post');
if (isset($result['errcode']) && $result['errcode'] == '0') {
return true;
} else {
return $result;
}
} | php | public function sendTplMsg($tplId, $data, $url, $openid, $topcolor = '#FF0000', $accessToken = null)
{
if (is_null($accessToken)) {
$accessToken = $this->getAccessToken();
}
$postData = [
'touser' => $openid,
'template_id' => $tplId,
'url' => $url,
'topcolor' => $topcolor,
'data' => $data,
];
$apiUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$accessToken;
$result = $this->_curl($apiUrl, json_encode($postData), 'post');
if (isset($result['errcode']) && $result['errcode'] == '0') {
return true;
} else {
return $result;
}
} | [
"public",
"function",
"sendTplMsg",
"(",
"$",
"tplId",
",",
"$",
"data",
",",
"$",
"url",
",",
"$",
"openid",
",",
"$",
"topcolor",
"=",
"'#FF0000'",
",",
"$",
"accessToken",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"accessToken",
")",
")",
"{",
"$",
"accessToken",
"=",
"$",
"this",
"->",
"getAccessToken",
"(",
")",
";",
"}",
"$",
"postData",
"=",
"[",
"'touser'",
"=>",
"$",
"openid",
",",
"'template_id'",
"=>",
"$",
"tplId",
",",
"'url'",
"=>",
"$",
"url",
",",
"'topcolor'",
"=>",
"$",
"topcolor",
",",
"'data'",
"=>",
"$",
"data",
",",
"]",
";",
"$",
"apiUrl",
"=",
"'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='",
".",
"$",
"accessToken",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"_curl",
"(",
"$",
"apiUrl",
",",
"json_encode",
"(",
"$",
"postData",
")",
",",
"'post'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"result",
"[",
"'errcode'",
"]",
")",
"&&",
"$",
"result",
"[",
"'errcode'",
"]",
"==",
"'0'",
")",
"{",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"$",
"result",
";",
"}",
"}"
] | 向用户发送模板消息.
@param string $tplId 模板 ID
@param array $data 模板数据
@param string $url 链接地址
@param string $openid 用户的openid
@param string $topcolor topcolor
@param string $accessToken access_token
@return true|array | [
"向用户发送模板消息",
"."
] | train | https://github.com/purocean/php-wechat-sdk/blob/a369c4f8b8a24e54ecc505d0432b4479c0a9e827/src/Mpwx.php#L246-L268 |
purocean/php-wechat-sdk | src/Mpwx.php | Mpwx._curl | private function _curl($url, $data = '', $method = 'get')
{
$parStr = '';
if (is_array($data)) {
$parStr = http_build_query($data);
} else {
$parStr = $data;
}
if (strtolower($method) == 'get') {
$json = file_get_contents(rtrim($url, '?').'?'.$parStr);
} else {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parStr);
$json = curl_exec($ch);
curl_close($ch);
}
$result = json_decode($json, true);
if (isset($result['errcode']) and $result['errcode'] != 0) {
$this->_log("Error-{$method}-{$url}", $json, $data);
return false;
}
return $result;
} | php | private function _curl($url, $data = '', $method = 'get')
{
$parStr = '';
if (is_array($data)) {
$parStr = http_build_query($data);
} else {
$parStr = $data;
}
if (strtolower($method) == 'get') {
$json = file_get_contents(rtrim($url, '?').'?'.$parStr);
} else {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parStr);
$json = curl_exec($ch);
curl_close($ch);
}
$result = json_decode($json, true);
if (isset($result['errcode']) and $result['errcode'] != 0) {
$this->_log("Error-{$method}-{$url}", $json, $data);
return false;
}
return $result;
} | [
"private",
"function",
"_curl",
"(",
"$",
"url",
",",
"$",
"data",
"=",
"''",
",",
"$",
"method",
"=",
"'get'",
")",
"{",
"$",
"parStr",
"=",
"''",
";",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"$",
"parStr",
"=",
"http_build_query",
"(",
"$",
"data",
")",
";",
"}",
"else",
"{",
"$",
"parStr",
"=",
"$",
"data",
";",
"}",
"if",
"(",
"strtolower",
"(",
"$",
"method",
")",
"==",
"'get'",
")",
"{",
"$",
"json",
"=",
"file_get_contents",
"(",
"rtrim",
"(",
"$",
"url",
",",
"'?'",
")",
".",
"'?'",
".",
"$",
"parStr",
")",
";",
"}",
"else",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_URL",
",",
"$",
"url",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_TIMEOUT",
",",
"30",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSL_VERIFYPEER",
",",
"false",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_SSL_VERIFYHOST",
",",
"false",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_RETURNTRANSFER",
",",
"1",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POST",
",",
"1",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POSTFIELDS",
",",
"$",
"parStr",
")",
";",
"$",
"json",
"=",
"curl_exec",
"(",
"$",
"ch",
")",
";",
"curl_close",
"(",
"$",
"ch",
")",
";",
"}",
"$",
"result",
"=",
"json_decode",
"(",
"$",
"json",
",",
"true",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"result",
"[",
"'errcode'",
"]",
")",
"and",
"$",
"result",
"[",
"'errcode'",
"]",
"!=",
"0",
")",
"{",
"$",
"this",
"->",
"_log",
"(",
"\"Error-{$method}-{$url}\"",
",",
"$",
"json",
",",
"$",
"data",
")",
";",
"return",
"false",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | 简化的 HTTP 通信函数.
@param string $url 目标 URL
@param array|string $data 发送的数据
@param string $method 发送方式
@return array|boolen 获得的内容 | [
"简化的",
"HTTP",
"通信函数",
"."
] | train | https://github.com/purocean/php-wechat-sdk/blob/a369c4f8b8a24e54ecc505d0432b4479c0a9e827/src/Mpwx.php#L298-L330 |
expectation-php/expect | src/matcher/ToEqual.php | ToEqual.reportFailed | public function reportFailed(FailedMessage $message)
{
$message->appendText("Expected ")
->appendValue($this->actual)
->appendText(' to be ')
->appendValue($this->expected)
->appendText("\n\n")
->appendText(' expected: ')
->appendValue($this->expected)
->appendText("\n")
->appendText(' got: ')
->appendValue($this->actual);
} | php | public function reportFailed(FailedMessage $message)
{
$message->appendText("Expected ")
->appendValue($this->actual)
->appendText(' to be ')
->appendValue($this->expected)
->appendText("\n\n")
->appendText(' expected: ')
->appendValue($this->expected)
->appendText("\n")
->appendText(' got: ')
->appendValue($this->actual);
} | [
"public",
"function",
"reportFailed",
"(",
"FailedMessage",
"$",
"message",
")",
"{",
"$",
"message",
"->",
"appendText",
"(",
"\"Expected \"",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"actual",
")",
"->",
"appendText",
"(",
"' to be '",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"expected",
")",
"->",
"appendText",
"(",
"\"\\n\\n\"",
")",
"->",
"appendText",
"(",
"' expected: '",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"expected",
")",
"->",
"appendText",
"(",
"\"\\n\"",
")",
"->",
"appendText",
"(",
"' got: '",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"actual",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/expectation-php/expect/blob/1a32c5af37f3dc8dabe4e8eedeeb21aea16ce139/src/matcher/ToEqual.php#L62-L74 |
expectation-php/expect | src/matcher/ToEqual.php | ToEqual.reportNegativeFailed | public function reportNegativeFailed(FailedMessage $message)
{
$message->appendText("Expected ")
->appendValue($this->actual)
->appendText(' not to be ')
->appendValue($this->expected)
->appendText("\n\n")
->appendText(' expected not: ')
->appendValue($this->expected)
->appendText("\n")
->appendText(' got: ')
->appendValue($this->actual);
} | php | public function reportNegativeFailed(FailedMessage $message)
{
$message->appendText("Expected ")
->appendValue($this->actual)
->appendText(' not to be ')
->appendValue($this->expected)
->appendText("\n\n")
->appendText(' expected not: ')
->appendValue($this->expected)
->appendText("\n")
->appendText(' got: ')
->appendValue($this->actual);
} | [
"public",
"function",
"reportNegativeFailed",
"(",
"FailedMessage",
"$",
"message",
")",
"{",
"$",
"message",
"->",
"appendText",
"(",
"\"Expected \"",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"actual",
")",
"->",
"appendText",
"(",
"' not to be '",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"expected",
")",
"->",
"appendText",
"(",
"\"\\n\\n\"",
")",
"->",
"appendText",
"(",
"' expected not: '",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"expected",
")",
"->",
"appendText",
"(",
"\"\\n\"",
")",
"->",
"appendText",
"(",
"' got: '",
")",
"->",
"appendValue",
"(",
"$",
"this",
"->",
"actual",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/expectation-php/expect/blob/1a32c5af37f3dc8dabe4e8eedeeb21aea16ce139/src/matcher/ToEqual.php#L79-L91 |
heidelpay/PhpDoc | src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Classes/HasPackageWithSubpackageValidator.php | HasPackageWithSubpackageValidator.validate | public function validate($value, Constraint $constraint)
{
if (! $value instanceof FileDescriptor
&& ! $value instanceof ClassDescriptor
&& ! $value instanceof InterfaceDescriptor
&& ! $value instanceof TraitDescriptor
) {
throw new ConstraintDefinitionException(
'The HasPackageWithSubpackageValidator validator may only be used on files, classes, '
. 'interfaces and traits'
);
}
if ($value->getTags()->get('subpackage', new Collection())->count() > 0
&& $value->getTags()->get('package', new Collection())->count() < 1) {
$this->context->addViolationAt('package', $constraint->message, array(), null, null, $constraint->code);
}
} | php | public function validate($value, Constraint $constraint)
{
if (! $value instanceof FileDescriptor
&& ! $value instanceof ClassDescriptor
&& ! $value instanceof InterfaceDescriptor
&& ! $value instanceof TraitDescriptor
) {
throw new ConstraintDefinitionException(
'The HasPackageWithSubpackageValidator validator may only be used on files, classes, '
. 'interfaces and traits'
);
}
if ($value->getTags()->get('subpackage', new Collection())->count() > 0
&& $value->getTags()->get('package', new Collection())->count() < 1) {
$this->context->addViolationAt('package', $constraint->message, array(), null, null, $constraint->code);
}
} | [
"public",
"function",
"validate",
"(",
"$",
"value",
",",
"Constraint",
"$",
"constraint",
")",
"{",
"if",
"(",
"!",
"$",
"value",
"instanceof",
"FileDescriptor",
"&&",
"!",
"$",
"value",
"instanceof",
"ClassDescriptor",
"&&",
"!",
"$",
"value",
"instanceof",
"InterfaceDescriptor",
"&&",
"!",
"$",
"value",
"instanceof",
"TraitDescriptor",
")",
"{",
"throw",
"new",
"ConstraintDefinitionException",
"(",
"'The HasPackageWithSubpackageValidator validator may only be used on files, classes, '",
".",
"'interfaces and traits'",
")",
";",
"}",
"if",
"(",
"$",
"value",
"->",
"getTags",
"(",
")",
"->",
"get",
"(",
"'subpackage'",
",",
"new",
"Collection",
"(",
")",
")",
"->",
"count",
"(",
")",
">",
"0",
"&&",
"$",
"value",
"->",
"getTags",
"(",
")",
"->",
"get",
"(",
"'package'",
",",
"new",
"Collection",
"(",
")",
")",
"->",
"count",
"(",
")",
"<",
"1",
")",
"{",
"$",
"this",
"->",
"context",
"->",
"addViolationAt",
"(",
"'package'",
",",
"$",
"constraint",
"->",
"message",
",",
"array",
"(",
")",
",",
"null",
",",
"null",
",",
"$",
"constraint",
"->",
"code",
")",
";",
"}",
"}"
] | Checks if the passed value is valid.
@param FileDescriptor|ClassDescriptor|InterfaceDescriptor|TraitDescriptor $value The value that should
be validated.
@param Constraint $constraint The constraint for
the validation.
@throws ConstraintDefinitionException if this is not a constraint on a PropertyDescriptor object. | [
"Checks",
"if",
"the",
"passed",
"value",
"is",
"valid",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Plugin/Core/Descriptor/Validator/Constraints/Classes/HasPackageWithSubpackageValidator.php#L37-L54 |
heidelpay/PhpDoc | src/phpDocumentor/Application.php | Application.configureLogger | public function configureLogger($logger, $level, $logPath = null)
{
/** @var Logger $monolog */
$monolog = $logger;
switch ($level) {
case 'emergency':
case 'emerg':
$level = Logger::EMERGENCY;
break;
case 'alert':
$level = Logger::ALERT;
break;
case 'critical':
case 'crit':
$level = Logger::CRITICAL;
break;
case 'error':
case 'err':
$level = Logger::ERROR;
break;
case 'warning':
case 'warn':
$level = Logger::WARNING;
break;
case 'notice':
$level = Logger::NOTICE;
break;
case 'info':
$level = Logger::INFO;
break;
case 'debug':
$level = Logger::DEBUG;
break;
}
$this['monolog.level'] = $level;
if ($logPath) {
$logPath = str_replace(
array('{APP_ROOT}', '{DATE}'),
array(realpath(__DIR__.'/../..'), $this['kernel.timer.start']),
$logPath
);
$this['monolog.logfile'] = $logPath;
}
// remove all handlers from the stack
try {
while ($monolog->popHandler()) {
}
} catch (\LogicException $e) {
// popHandler throws an exception when you try to pop the empty stack; to us this is not an
// error but an indication that the handler stack is empty.
}
if ($level === 'quiet') {
$monolog->pushHandler(new NullHandler());
return;
}
// set our new handlers
if ($logPath) {
$monolog->pushHandler(new StreamHandler($logPath, $level));
} else {
$monolog->pushHandler(new StreamHandler('php://stdout', $level));
}
} | php | public function configureLogger($logger, $level, $logPath = null)
{
/** @var Logger $monolog */
$monolog = $logger;
switch ($level) {
case 'emergency':
case 'emerg':
$level = Logger::EMERGENCY;
break;
case 'alert':
$level = Logger::ALERT;
break;
case 'critical':
case 'crit':
$level = Logger::CRITICAL;
break;
case 'error':
case 'err':
$level = Logger::ERROR;
break;
case 'warning':
case 'warn':
$level = Logger::WARNING;
break;
case 'notice':
$level = Logger::NOTICE;
break;
case 'info':
$level = Logger::INFO;
break;
case 'debug':
$level = Logger::DEBUG;
break;
}
$this['monolog.level'] = $level;
if ($logPath) {
$logPath = str_replace(
array('{APP_ROOT}', '{DATE}'),
array(realpath(__DIR__.'/../..'), $this['kernel.timer.start']),
$logPath
);
$this['monolog.logfile'] = $logPath;
}
// remove all handlers from the stack
try {
while ($monolog->popHandler()) {
}
} catch (\LogicException $e) {
// popHandler throws an exception when you try to pop the empty stack; to us this is not an
// error but an indication that the handler stack is empty.
}
if ($level === 'quiet') {
$monolog->pushHandler(new NullHandler());
return;
}
// set our new handlers
if ($logPath) {
$monolog->pushHandler(new StreamHandler($logPath, $level));
} else {
$monolog->pushHandler(new StreamHandler('php://stdout', $level));
}
} | [
"public",
"function",
"configureLogger",
"(",
"$",
"logger",
",",
"$",
"level",
",",
"$",
"logPath",
"=",
"null",
")",
"{",
"/** @var Logger $monolog */",
"$",
"monolog",
"=",
"$",
"logger",
";",
"switch",
"(",
"$",
"level",
")",
"{",
"case",
"'emergency'",
":",
"case",
"'emerg'",
":",
"$",
"level",
"=",
"Logger",
"::",
"EMERGENCY",
";",
"break",
";",
"case",
"'alert'",
":",
"$",
"level",
"=",
"Logger",
"::",
"ALERT",
";",
"break",
";",
"case",
"'critical'",
":",
"case",
"'crit'",
":",
"$",
"level",
"=",
"Logger",
"::",
"CRITICAL",
";",
"break",
";",
"case",
"'error'",
":",
"case",
"'err'",
":",
"$",
"level",
"=",
"Logger",
"::",
"ERROR",
";",
"break",
";",
"case",
"'warning'",
":",
"case",
"'warn'",
":",
"$",
"level",
"=",
"Logger",
"::",
"WARNING",
";",
"break",
";",
"case",
"'notice'",
":",
"$",
"level",
"=",
"Logger",
"::",
"NOTICE",
";",
"break",
";",
"case",
"'info'",
":",
"$",
"level",
"=",
"Logger",
"::",
"INFO",
";",
"break",
";",
"case",
"'debug'",
":",
"$",
"level",
"=",
"Logger",
"::",
"DEBUG",
";",
"break",
";",
"}",
"$",
"this",
"[",
"'monolog.level'",
"]",
"=",
"$",
"level",
";",
"if",
"(",
"$",
"logPath",
")",
"{",
"$",
"logPath",
"=",
"str_replace",
"(",
"array",
"(",
"'{APP_ROOT}'",
",",
"'{DATE}'",
")",
",",
"array",
"(",
"realpath",
"(",
"__DIR__",
".",
"'/../..'",
")",
",",
"$",
"this",
"[",
"'kernel.timer.start'",
"]",
")",
",",
"$",
"logPath",
")",
";",
"$",
"this",
"[",
"'monolog.logfile'",
"]",
"=",
"$",
"logPath",
";",
"}",
"// remove all handlers from the stack",
"try",
"{",
"while",
"(",
"$",
"monolog",
"->",
"popHandler",
"(",
")",
")",
"{",
"}",
"}",
"catch",
"(",
"\\",
"LogicException",
"$",
"e",
")",
"{",
"// popHandler throws an exception when you try to pop the empty stack; to us this is not an",
"// error but an indication that the handler stack is empty.",
"}",
"if",
"(",
"$",
"level",
"===",
"'quiet'",
")",
"{",
"$",
"monolog",
"->",
"pushHandler",
"(",
"new",
"NullHandler",
"(",
")",
")",
";",
"return",
";",
"}",
"// set our new handlers",
"if",
"(",
"$",
"logPath",
")",
"{",
"$",
"monolog",
"->",
"pushHandler",
"(",
"new",
"StreamHandler",
"(",
"$",
"logPath",
",",
"$",
"level",
")",
")",
";",
"}",
"else",
"{",
"$",
"monolog",
"->",
"pushHandler",
"(",
"new",
"StreamHandler",
"(",
"'php://stdout'",
",",
"$",
"level",
")",
")",
";",
"}",
"}"
] | Removes all logging handlers and replaces them with handlers that can write to the given logPath and level.
@param Logger $logger The logger instance that needs to be configured.
@param integer $level The minimum level that will be written to the normal logfile; matches one of the
constants in {@see \Monolog\Logger}.
@param string $logPath The full path where the normal log file needs to be written.
@return void | [
"Removes",
"all",
"logging",
"handlers",
"and",
"replaces",
"them",
"with",
"handlers",
"that",
"can",
"write",
"to",
"the",
"given",
"logPath",
"and",
"level",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Application.php#L94-L161 |
heidelpay/PhpDoc | src/phpDocumentor/Application.php | Application.run | public function run($interactive = false)
{
/** @var ConsoleApplication $app */
$app = $this['console'];
$app->setAutoExit(false);
if ($interactive) {
$app = new Shell($app);
}
$output = new Console\Output\Output();
$output->setLogger($this['monolog']);
$app->run(new ArgvInput(), $output);
} | php | public function run($interactive = false)
{
/** @var ConsoleApplication $app */
$app = $this['console'];
$app->setAutoExit(false);
if ($interactive) {
$app = new Shell($app);
}
$output = new Console\Output\Output();
$output->setLogger($this['monolog']);
$app->run(new ArgvInput(), $output);
} | [
"public",
"function",
"run",
"(",
"$",
"interactive",
"=",
"false",
")",
"{",
"/** @var ConsoleApplication $app */",
"$",
"app",
"=",
"$",
"this",
"[",
"'console'",
"]",
";",
"$",
"app",
"->",
"setAutoExit",
"(",
"false",
")",
";",
"if",
"(",
"$",
"interactive",
")",
"{",
"$",
"app",
"=",
"new",
"Shell",
"(",
"$",
"app",
")",
";",
"}",
"$",
"output",
"=",
"new",
"Console",
"\\",
"Output",
"\\",
"Output",
"(",
")",
";",
"$",
"output",
"->",
"setLogger",
"(",
"$",
"this",
"[",
"'monolog'",
"]",
")",
";",
"$",
"app",
"->",
"run",
"(",
"new",
"ArgvInput",
"(",
")",
",",
"$",
"output",
")",
";",
"}"
] | Run the application and if no command is provided, use project:run.
@param bool $interactive Whether to run in interactive mode.
@return void | [
"Run",
"the",
"application",
"and",
"if",
"no",
"command",
"is",
"provided",
"use",
"project",
":",
"run",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Application.php#L170-L184 |
heidelpay/PhpDoc | src/phpDocumentor/Application.php | Application.addLogging | protected function addLogging()
{
$this->register(
new MonologServiceProvider(),
array(
'monolog.name' => 'phpDocumentor',
'monolog.logfile' => sys_get_temp_dir() . '/phpdoc.log',
'monolog.debugfile' => sys_get_temp_dir() . '/phpdoc.debug.log',
'monolog.level' => Logger::INFO,
)
);
$app = $this;
/** @var Configuration $configuration */
$configuration = $this['config'];
$this['monolog.configure'] = $this->protect(
function ($log) use ($app, $configuration) {
$paths = $configuration->getLogging()->getPaths();
$logLevel = $configuration->getLogging()->getLevel();
$app->configureLogger($log, $logLevel, $paths['default'], $paths['errors']);
}
);
$this->extend(
'console',
function (ConsoleApplication $console) use ($configuration) {
$console->getHelperSet()->set(new LoggerHelper());
$console->getHelperSet()->set(new ConfigurationHelper($configuration));
return $console;
}
);
ErrorHandler::register($this['monolog']);
} | php | protected function addLogging()
{
$this->register(
new MonologServiceProvider(),
array(
'monolog.name' => 'phpDocumentor',
'monolog.logfile' => sys_get_temp_dir() . '/phpdoc.log',
'monolog.debugfile' => sys_get_temp_dir() . '/phpdoc.debug.log',
'monolog.level' => Logger::INFO,
)
);
$app = $this;
/** @var Configuration $configuration */
$configuration = $this['config'];
$this['monolog.configure'] = $this->protect(
function ($log) use ($app, $configuration) {
$paths = $configuration->getLogging()->getPaths();
$logLevel = $configuration->getLogging()->getLevel();
$app->configureLogger($log, $logLevel, $paths['default'], $paths['errors']);
}
);
$this->extend(
'console',
function (ConsoleApplication $console) use ($configuration) {
$console->getHelperSet()->set(new LoggerHelper());
$console->getHelperSet()->set(new ConfigurationHelper($configuration));
return $console;
}
);
ErrorHandler::register($this['monolog']);
} | [
"protected",
"function",
"addLogging",
"(",
")",
"{",
"$",
"this",
"->",
"register",
"(",
"new",
"MonologServiceProvider",
"(",
")",
",",
"array",
"(",
"'monolog.name'",
"=>",
"'phpDocumentor'",
",",
"'monolog.logfile'",
"=>",
"sys_get_temp_dir",
"(",
")",
".",
"'/phpdoc.log'",
",",
"'monolog.debugfile'",
"=>",
"sys_get_temp_dir",
"(",
")",
".",
"'/phpdoc.debug.log'",
",",
"'monolog.level'",
"=>",
"Logger",
"::",
"INFO",
",",
")",
")",
";",
"$",
"app",
"=",
"$",
"this",
";",
"/** @var Configuration $configuration */",
"$",
"configuration",
"=",
"$",
"this",
"[",
"'config'",
"]",
";",
"$",
"this",
"[",
"'monolog.configure'",
"]",
"=",
"$",
"this",
"->",
"protect",
"(",
"function",
"(",
"$",
"log",
")",
"use",
"(",
"$",
"app",
",",
"$",
"configuration",
")",
"{",
"$",
"paths",
"=",
"$",
"configuration",
"->",
"getLogging",
"(",
")",
"->",
"getPaths",
"(",
")",
";",
"$",
"logLevel",
"=",
"$",
"configuration",
"->",
"getLogging",
"(",
")",
"->",
"getLevel",
"(",
")",
";",
"$",
"app",
"->",
"configureLogger",
"(",
"$",
"log",
",",
"$",
"logLevel",
",",
"$",
"paths",
"[",
"'default'",
"]",
",",
"$",
"paths",
"[",
"'errors'",
"]",
")",
";",
"}",
")",
";",
"$",
"this",
"->",
"extend",
"(",
"'console'",
",",
"function",
"(",
"ConsoleApplication",
"$",
"console",
")",
"use",
"(",
"$",
"configuration",
")",
"{",
"$",
"console",
"->",
"getHelperSet",
"(",
")",
"->",
"set",
"(",
"new",
"LoggerHelper",
"(",
")",
")",
";",
"$",
"console",
"->",
"getHelperSet",
"(",
")",
"->",
"set",
"(",
"new",
"ConfigurationHelper",
"(",
"$",
"configuration",
")",
")",
";",
"return",
"$",
"console",
";",
"}",
")",
";",
"ErrorHandler",
"::",
"register",
"(",
"$",
"this",
"[",
"'monolog'",
"]",
")",
";",
"}"
] | Adds a logging provider to the container of phpDocumentor.
@return void | [
"Adds",
"a",
"logging",
"provider",
"to",
"the",
"container",
"of",
"phpDocumentor",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Application.php#L240-L275 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/oracle/helper.php | ezcDbSchemaOracleHelper.generateSuffixedIdentName | public static function generateSuffixedIdentName( array $identNames, $suffix )
{
$ident = implode( "_", $identNames ) . "_" . $suffix;
$i = 0;
$last = -1;
while ( strlen( $ident ) > self::IDENTIFIER_MAX_LENGTH )
{
if ( strlen( $identNames[$i] ) > 1 || $last == $i )
{
$identNames[$i] = substr( $identNames[$i], 0, strlen( $identNames[$i] ) - 1 );
$last = $i;
}
$i = ( $i + 1 ) % count( $identNames );
$ident = implode( "_", $identNames ) . "_" . $suffix;
}
return $ident;
} | php | public static function generateSuffixedIdentName( array $identNames, $suffix )
{
$ident = implode( "_", $identNames ) . "_" . $suffix;
$i = 0;
$last = -1;
while ( strlen( $ident ) > self::IDENTIFIER_MAX_LENGTH )
{
if ( strlen( $identNames[$i] ) > 1 || $last == $i )
{
$identNames[$i] = substr( $identNames[$i], 0, strlen( $identNames[$i] ) - 1 );
$last = $i;
}
$i = ( $i + 1 ) % count( $identNames );
$ident = implode( "_", $identNames ) . "_" . $suffix;
}
return $ident;
} | [
"public",
"static",
"function",
"generateSuffixedIdentName",
"(",
"array",
"$",
"identNames",
",",
"$",
"suffix",
")",
"{",
"$",
"ident",
"=",
"implode",
"(",
"\"_\"",
",",
"$",
"identNames",
")",
".",
"\"_\"",
".",
"$",
"suffix",
";",
"$",
"i",
"=",
"0",
";",
"$",
"last",
"=",
"-",
"1",
";",
"while",
"(",
"strlen",
"(",
"$",
"ident",
")",
">",
"self",
"::",
"IDENTIFIER_MAX_LENGTH",
")",
"{",
"if",
"(",
"strlen",
"(",
"$",
"identNames",
"[",
"$",
"i",
"]",
")",
">",
"1",
"||",
"$",
"last",
"==",
"$",
"i",
")",
"{",
"$",
"identNames",
"[",
"$",
"i",
"]",
"=",
"substr",
"(",
"$",
"identNames",
"[",
"$",
"i",
"]",
",",
"0",
",",
"strlen",
"(",
"$",
"identNames",
"[",
"$",
"i",
"]",
")",
"-",
"1",
")",
";",
"$",
"last",
"=",
"$",
"i",
";",
"}",
"$",
"i",
"=",
"(",
"$",
"i",
"+",
"1",
")",
"%",
"count",
"(",
"$",
"identNames",
")",
";",
"$",
"ident",
"=",
"implode",
"(",
"\"_\"",
",",
"$",
"identNames",
")",
".",
"\"_\"",
".",
"$",
"suffix",
";",
"}",
"return",
"$",
"ident",
";",
"}"
] | Generate single identifier name for constraints for example obeying oracle 30 chars ident restriction.
@param array $identNames
@param string $suffix
@return string | [
"Generate",
"single",
"identifier",
"name",
"for",
"constraints",
"for",
"example",
"obeying",
"oracle",
"30",
"chars",
"ident",
"restriction",
"."
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/oracle/helper.php#L46-L63 |
DesignPond/newsletter | src/Http/Controllers/Backend/EmailController.php | EmailController.update | public function update($id,Request $request)
{
$email = $this->emails->update( $request->all() );
alert()->success('Email mis à jour');
return redirect('build/liste/'.$email->list_id);
} | php | public function update($id,Request $request)
{
$email = $this->emails->update( $request->all() );
alert()->success('Email mis à jour');
return redirect('build/liste/'.$email->list_id);
} | [
"public",
"function",
"update",
"(",
"$",
"id",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"email",
"=",
"$",
"this",
"->",
"emails",
"->",
"update",
"(",
"$",
"request",
"->",
"all",
"(",
")",
")",
";",
"alert",
"(",
")",
"->",
"success",
"(",
"'Email mis à jour')",
";",
"",
"return",
"redirect",
"(",
"'build/liste/'",
".",
"$",
"email",
"->",
"list_id",
")",
";",
"}"
] | Update the specified resource in storage.
PUT /compte/{id}
@param int $id
@return Response | [
"Update",
"the",
"specified",
"resource",
"in",
"storage",
".",
"PUT",
"/",
"compte",
"/",
"{",
"id",
"}"
] | train | https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Http/Controllers/Backend/EmailController.php#L43-L50 |
DesignPond/newsletter | src/Http/Controllers/Backend/EmailController.php | EmailController.destroy | public function destroy($id)
{
$this->emails->delete($id);
alert()->success('Email supprimée de la liste');
return redirect()->back();
} | php | public function destroy($id)
{
$this->emails->delete($id);
alert()->success('Email supprimée de la liste');
return redirect()->back();
} | [
"public",
"function",
"destroy",
"(",
"$",
"id",
")",
"{",
"$",
"this",
"->",
"emails",
"->",
"delete",
"(",
"$",
"id",
")",
";",
"alert",
"(",
")",
"->",
"success",
"(",
"'Email supprimée de la liste')",
";",
"",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"}"
] | Remove the specified resource from storage.
DELETE /list
@return Response | [
"Remove",
"the",
"specified",
"resource",
"from",
"storage",
".",
"DELETE",
"/",
"list"
] | train | https://github.com/DesignPond/newsletter/blob/0bf0e7a8a42fa4b90a5e937771bb80058e0a91c3/src/Http/Controllers/Backend/EmailController.php#L58-L65 |
endroid/import-bundle | src/EndroidImportBundle.php | EndroidImportBundle.build | public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ImporterCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1);
} | php | public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ImporterCompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1);
} | [
"public",
"function",
"build",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"parent",
"::",
"build",
"(",
"$",
"container",
")",
";",
"$",
"container",
"->",
"addCompilerPass",
"(",
"new",
"ImporterCompilerPass",
"(",
")",
",",
"PassConfig",
"::",
"TYPE_BEFORE_OPTIMIZATION",
",",
"1",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/endroid/import-bundle/blob/637f29720822432192efad6993f505adc9dd4af4/src/EndroidImportBundle.php#L24-L29 |
mothership-ec/composer | src/Composer/Autoload/ClassMapGenerator.php | ClassMapGenerator.findClasses | private static function findClasses($path)
{
$extraTypes = PHP_VERSION_ID < 50400 ? '' : '|trait';
if (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>=')) {
$extraTypes .= '|enum';
}
try {
$contents = @php_strip_whitespace($path);
if (!$contents) {
if (!file_exists($path)) {
throw new \Exception('File does not exist');
}
if (!is_readable($path)) {
throw new \Exception('File is not readable');
}
}
} catch (\Exception $e) {
throw new \RuntimeException('Could not scan for classes inside '.$path.": \n".$e->getMessage(), 0, $e);
}
// return early if there is no chance of matching anything in this file
if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) {
return array();
}
// strip heredocs/nowdocs
$contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents);
// strip strings
$contents = preg_replace('{"[^"\\\\]*(\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(\\\\.[^\'\\\\]*)*\'}s', 'null', $contents);
// strip leading non-php code if needed
if (substr($contents, 0, 2) !== '<?') {
$contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
if ($replacements === 0) {
return array();
}
}
// strip non-php blocks in the file
$contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
// strip trailing non-php code if needed
$pos = strrpos($contents, '?>');
if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
$contents = substr($contents, 0, $pos);
}
preg_match_all('{
(?:
\b(?<![\$:>])(?P<type>class|interface'.$extraTypes.') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
)
}ix', $contents, $matches);
$classes = array();
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) {
$namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
} elseif ($matches['type'][$i] === 'enum') {
// In Hack, something like:
// enum Foo: int { HERP = '123'; }
// The regex above captures the colon, which isn't part of
// the class name.
$name = rtrim($name, ':');
}
$classes[] = ltrim($namespace . $name, '\\');
}
}
return $classes;
} | php | private static function findClasses($path)
{
$extraTypes = PHP_VERSION_ID < 50400 ? '' : '|trait';
if (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>=')) {
$extraTypes .= '|enum';
}
try {
$contents = @php_strip_whitespace($path);
if (!$contents) {
if (!file_exists($path)) {
throw new \Exception('File does not exist');
}
if (!is_readable($path)) {
throw new \Exception('File is not readable');
}
}
} catch (\Exception $e) {
throw new \RuntimeException('Could not scan for classes inside '.$path.": \n".$e->getMessage(), 0, $e);
}
// return early if there is no chance of matching anything in this file
if (!preg_match('{\b(?:class|interface'.$extraTypes.')\s}i', $contents)) {
return array();
}
// strip heredocs/nowdocs
$contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents);
// strip strings
$contents = preg_replace('{"[^"\\\\]*(\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(\\\\.[^\'\\\\]*)*\'}s', 'null', $contents);
// strip leading non-php code if needed
if (substr($contents, 0, 2) !== '<?') {
$contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
if ($replacements === 0) {
return array();
}
}
// strip non-php blocks in the file
$contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
// strip trailing non-php code if needed
$pos = strrpos($contents, '?>');
if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
$contents = substr($contents, 0, $pos);
}
preg_match_all('{
(?:
\b(?<![\$:>])(?P<type>class|interface'.$extraTypes.') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
)
}ix', $contents, $matches);
$classes = array();
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) {
$namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
} elseif ($matches['type'][$i] === 'enum') {
// In Hack, something like:
// enum Foo: int { HERP = '123'; }
// The regex above captures the colon, which isn't part of
// the class name.
$name = rtrim($name, ':');
}
$classes[] = ltrim($namespace . $name, '\\');
}
}
return $classes;
} | [
"private",
"static",
"function",
"findClasses",
"(",
"$",
"path",
")",
"{",
"$",
"extraTypes",
"=",
"PHP_VERSION_ID",
"<",
"50400",
"?",
"''",
":",
"'|trait'",
";",
"if",
"(",
"defined",
"(",
"'HHVM_VERSION'",
")",
"&&",
"version_compare",
"(",
"HHVM_VERSION",
",",
"'3.3'",
",",
"'>='",
")",
")",
"{",
"$",
"extraTypes",
".=",
"'|enum'",
";",
"}",
"try",
"{",
"$",
"contents",
"=",
"@",
"php_strip_whitespace",
"(",
"$",
"path",
")",
";",
"if",
"(",
"!",
"$",
"contents",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'File does not exist'",
")",
";",
"}",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'File is not readable'",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Could not scan for classes inside '",
".",
"$",
"path",
".",
"\": \\n\"",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"0",
",",
"$",
"e",
")",
";",
"}",
"// return early if there is no chance of matching anything in this file",
"if",
"(",
"!",
"preg_match",
"(",
"'{\\b(?:class|interface'",
".",
"$",
"extraTypes",
".",
"')\\s}i'",
",",
"$",
"contents",
")",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"// strip heredocs/nowdocs",
"$",
"contents",
"=",
"preg_replace",
"(",
"'{<<<\\s*(\\'?)(\\w+)\\\\1(?:\\r\\n|\\n|\\r)(?:.*?)(?:\\r\\n|\\n|\\r)\\\\2(?=\\r\\n|\\n|\\r|;)}s'",
",",
"'null'",
",",
"$",
"contents",
")",
";",
"// strip strings",
"$",
"contents",
"=",
"preg_replace",
"(",
"'{\"[^\"\\\\\\\\]*(\\\\\\\\.[^\"\\\\\\\\]*)*\"|\\'[^\\'\\\\\\\\]*(\\\\\\\\.[^\\'\\\\\\\\]*)*\\'}s'",
",",
"'null'",
",",
"$",
"contents",
")",
";",
"// strip leading non-php code if needed",
"if",
"(",
"substr",
"(",
"$",
"contents",
",",
"0",
",",
"2",
")",
"!==",
"'<?'",
")",
"{",
"$",
"contents",
"=",
"preg_replace",
"(",
"'{^.+?<\\?}s'",
",",
"'<?'",
",",
"$",
"contents",
",",
"1",
",",
"$",
"replacements",
")",
";",
"if",
"(",
"$",
"replacements",
"===",
"0",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"}",
"// strip non-php blocks in the file",
"$",
"contents",
"=",
"preg_replace",
"(",
"'{\\?>.+<\\?}s'",
",",
"'?><?'",
",",
"$",
"contents",
")",
";",
"// strip trailing non-php code if needed",
"$",
"pos",
"=",
"strrpos",
"(",
"$",
"contents",
",",
"'?>'",
")",
";",
"if",
"(",
"false",
"!==",
"$",
"pos",
"&&",
"false",
"===",
"strpos",
"(",
"substr",
"(",
"$",
"contents",
",",
"$",
"pos",
")",
",",
"'<?'",
")",
")",
"{",
"$",
"contents",
"=",
"substr",
"(",
"$",
"contents",
",",
"0",
",",
"$",
"pos",
")",
";",
"}",
"preg_match_all",
"(",
"'{\n (?:\n \\b(?<![\\$:>])(?P<type>class|interface'",
".",
"$",
"extraTypes",
".",
"') \\s+ (?P<name>[a-zA-Z_\\x7f-\\xff:][a-zA-Z0-9_\\x7f-\\xff:\\-]*)\n | \\b(?<![\\$:>])(?P<ns>namespace) (?P<nsname>\\s+[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*(?:\\s*\\\\\\\\\\s*[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)*)? \\s*[\\{;]\n )\n }ix'",
",",
"$",
"contents",
",",
"$",
"matches",
")",
";",
"$",
"classes",
"=",
"array",
"(",
")",
";",
"$",
"namespace",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"len",
"=",
"count",
"(",
"$",
"matches",
"[",
"'type'",
"]",
")",
";",
"$",
"i",
"<",
"$",
"len",
";",
"$",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"matches",
"[",
"'ns'",
"]",
"[",
"$",
"i",
"]",
")",
")",
"{",
"$",
"namespace",
"=",
"str_replace",
"(",
"array",
"(",
"' '",
",",
"\"\\t\"",
",",
"\"\\r\"",
",",
"\"\\n\"",
")",
",",
"''",
",",
"$",
"matches",
"[",
"'nsname'",
"]",
"[",
"$",
"i",
"]",
")",
".",
"'\\\\'",
";",
"}",
"else",
"{",
"$",
"name",
"=",
"$",
"matches",
"[",
"'name'",
"]",
"[",
"$",
"i",
"]",
";",
"if",
"(",
"$",
"name",
"[",
"0",
"]",
"===",
"':'",
")",
"{",
"// This is an XHP class, https://github.com/facebook/xhp",
"$",
"name",
"=",
"'xhp'",
".",
"substr",
"(",
"str_replace",
"(",
"array",
"(",
"'-'",
",",
"':'",
")",
",",
"array",
"(",
"'_'",
",",
"'__'",
")",
",",
"$",
"name",
")",
",",
"1",
")",
";",
"}",
"elseif",
"(",
"$",
"matches",
"[",
"'type'",
"]",
"[",
"$",
"i",
"]",
"===",
"'enum'",
")",
"{",
"// In Hack, something like:",
"// enum Foo: int { HERP = '123'; }",
"// The regex above captures the colon, which isn't part of",
"// the class name.",
"$",
"name",
"=",
"rtrim",
"(",
"$",
"name",
",",
"':'",
")",
";",
"}",
"$",
"classes",
"[",
"]",
"=",
"ltrim",
"(",
"$",
"namespace",
".",
"$",
"name",
",",
"'\\\\'",
")",
";",
"}",
"}",
"return",
"$",
"classes",
";",
"}"
] | Extract the classes in the given file
@param string $path The file to check
@throws \RuntimeException
@return array The found classes | [
"Extract",
"the",
"classes",
"in",
"the",
"given",
"file"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Autoload/ClassMapGenerator.php#L113-L188 |
Eresus/EresusCMS | src/core/DB/Exception/QueryFailed.php | Eresus_DB_Exception_QueryFailed.create | public static function create($query, PDOException $previous = null)
{
if ($query instanceof ezcQuery)
{
$insider = new DBQueryInsider;
$query->doBind($insider);
$query = $insider->subst($query);
}
return new self(sprintf('Database query "%s" failed: %s', $query, $previous->getMessage()),
0, $previous);
} | php | public static function create($query, PDOException $previous = null)
{
if ($query instanceof ezcQuery)
{
$insider = new DBQueryInsider;
$query->doBind($insider);
$query = $insider->subst($query);
}
return new self(sprintf('Database query "%s" failed: %s', $query, $previous->getMessage()),
0, $previous);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"query",
",",
"PDOException",
"$",
"previous",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"query",
"instanceof",
"ezcQuery",
")",
"{",
"$",
"insider",
"=",
"new",
"DBQueryInsider",
";",
"$",
"query",
"->",
"doBind",
"(",
"$",
"insider",
")",
";",
"$",
"query",
"=",
"$",
"insider",
"->",
"subst",
"(",
"$",
"query",
")",
";",
"}",
"return",
"new",
"self",
"(",
"sprintf",
"(",
"'Database query \"%s\" failed: %s'",
",",
"$",
"query",
",",
"$",
"previous",
"->",
"getMessage",
"(",
")",
")",
",",
"0",
",",
"$",
"previous",
")",
";",
"}"
] | Фабрика исключений
@param ezcQuery|string $query неудавшийся запрос
@param PDOException $previous предыдущее исключение
@return Eresus_DB_Exception_QueryFailed | [
"Фабрика",
"исключений"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/DB/Exception/QueryFailed.php#L47-L57 |
philiplb/Valdi | src/Valdi/Validator/AbstractArray.php | AbstractArray.isValid | public function isValid($value, array $parameters) {
if (count($parameters) !== 2) {
throw new ValidationException('Expecting two parameters.');
}
if (!($parameters[0] instanceof Validator)) {
throw new ValidationException('Expecting the first parameter to be an instance of a Validator.');
}
return in_array($value, ['', null], true) ||
$this->isValidArray($value, $parameters[0], $parameters[1]);
} | php | public function isValid($value, array $parameters) {
if (count($parameters) !== 2) {
throw new ValidationException('Expecting two parameters.');
}
if (!($parameters[0] instanceof Validator)) {
throw new ValidationException('Expecting the first parameter to be an instance of a Validator.');
}
return in_array($value, ['', null], true) ||
$this->isValidArray($value, $parameters[0], $parameters[1]);
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
",",
"array",
"$",
"parameters",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"parameters",
")",
"!==",
"2",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"'Expecting two parameters.'",
")",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"parameters",
"[",
"0",
"]",
"instanceof",
"Validator",
")",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"'Expecting the first parameter to be an instance of a Validator.'",
")",
";",
"}",
"return",
"in_array",
"(",
"$",
"value",
",",
"[",
"''",
",",
"null",
"]",
",",
"true",
")",
"||",
"$",
"this",
"->",
"isValidArray",
"(",
"$",
"value",
",",
"$",
"parameters",
"[",
"0",
"]",
",",
"$",
"parameters",
"[",
"1",
"]",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/philiplb/Valdi/blob/9927ec34a2cb00cec705e952d3c2374e2dc3c972/src/Valdi/Validator/AbstractArray.php#L47-L56 |
mothership-ec/composer | src/Composer/DependencyResolver/RuleSetGenerator.php | RuleSetGenerator.createInstallOneOfRule | protected function createInstallOneOfRule(array $packages, $reason, $job)
{
$literals = array();
foreach ($packages as $package) {
$literals[] = $package->id;
}
return new Rule($literals, $reason, $job['packageName'], $job);
} | php | protected function createInstallOneOfRule(array $packages, $reason, $job)
{
$literals = array();
foreach ($packages as $package) {
$literals[] = $package->id;
}
return new Rule($literals, $reason, $job['packageName'], $job);
} | [
"protected",
"function",
"createInstallOneOfRule",
"(",
"array",
"$",
"packages",
",",
"$",
"reason",
",",
"$",
"job",
")",
"{",
"$",
"literals",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"packages",
"as",
"$",
"package",
")",
"{",
"$",
"literals",
"[",
"]",
"=",
"$",
"package",
"->",
"id",
";",
"}",
"return",
"new",
"Rule",
"(",
"$",
"literals",
",",
"$",
"reason",
",",
"$",
"job",
"[",
"'packageName'",
"]",
",",
"$",
"job",
")",
";",
"}"
] | Creates a rule to install at least one of a set of packages
The rule is (A|B|C) with A, B and C different packages. If the given
set of packages is empty an impossible rule is generated.
@param array $packages The set of packages to choose from
@param int $reason A RULE_* constant describing the reason for
generating this rule
@param array $job The job this rule was created from
@return Rule The generated rule | [
"Creates",
"a",
"rule",
"to",
"install",
"at",
"least",
"one",
"of",
"a",
"set",
"of",
"packages"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/DependencyResolver/RuleSetGenerator.php#L79-L87 |
mothership-ec/composer | src/Composer/DependencyResolver/RuleSetGenerator.php | RuleSetGenerator.createRemoveRule | protected function createRemoveRule(PackageInterface $package, $reason, $job)
{
return new Rule(array(-$package->id), $reason, $job['packageName'], $job);
} | php | protected function createRemoveRule(PackageInterface $package, $reason, $job)
{
return new Rule(array(-$package->id), $reason, $job['packageName'], $job);
} | [
"protected",
"function",
"createRemoveRule",
"(",
"PackageInterface",
"$",
"package",
",",
"$",
"reason",
",",
"$",
"job",
")",
"{",
"return",
"new",
"Rule",
"(",
"array",
"(",
"-",
"$",
"package",
"->",
"id",
")",
",",
"$",
"reason",
",",
"$",
"job",
"[",
"'packageName'",
"]",
",",
"$",
"job",
")",
";",
"}"
] | Creates a rule to remove a package
The rule for a package A is (-A).
@param PackageInterface $package The package to be removed
@param int $reason A RULE_* constant describing the
reason for generating this rule
@param array $job The job this rule was created from
@return Rule The generated rule | [
"Creates",
"a",
"rule",
"to",
"remove",
"a",
"package"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/DependencyResolver/RuleSetGenerator.php#L100-L103 |
mothership-ec/composer | src/Composer/DependencyResolver/RuleSetGenerator.php | RuleSetGenerator.createConflictRule | protected function createConflictRule(PackageInterface $issuer, PackageInterface $provider, $reason, $reasonData = null)
{
// ignore self conflict
if ($issuer === $provider) {
return null;
}
return new Rule(array(-$issuer->id, -$provider->id), $reason, $reasonData);
} | php | protected function createConflictRule(PackageInterface $issuer, PackageInterface $provider, $reason, $reasonData = null)
{
// ignore self conflict
if ($issuer === $provider) {
return null;
}
return new Rule(array(-$issuer->id, -$provider->id), $reason, $reasonData);
} | [
"protected",
"function",
"createConflictRule",
"(",
"PackageInterface",
"$",
"issuer",
",",
"PackageInterface",
"$",
"provider",
",",
"$",
"reason",
",",
"$",
"reasonData",
"=",
"null",
")",
"{",
"// ignore self conflict",
"if",
"(",
"$",
"issuer",
"===",
"$",
"provider",
")",
"{",
"return",
"null",
";",
"}",
"return",
"new",
"Rule",
"(",
"array",
"(",
"-",
"$",
"issuer",
"->",
"id",
",",
"-",
"$",
"provider",
"->",
"id",
")",
",",
"$",
"reason",
",",
"$",
"reasonData",
")",
";",
"}"
] | Creates a rule for two conflicting packages
The rule for conflicting packages A and B is (-A|-B). A is called the issuer
and B the provider.
@param PackageInterface $issuer The package declaring the conflict
@param PackageInterface $provider The package causing the conflict
@param int $reason A RULE_* constant describing the
reason for generating this rule
@param mixed $reasonData Any data, e.g. the package name, that
goes with the reason
@return Rule The generated rule | [
"Creates",
"a",
"rule",
"for",
"two",
"conflicting",
"packages"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/DependencyResolver/RuleSetGenerator.php#L119-L127 |
mothership-ec/composer | src/Composer/DependencyResolver/RuleSetGenerator.php | RuleSetGenerator.addRule | private function addRule($type, Rule $newRule = null)
{
if (!$newRule || $this->rules->containsEqual($newRule)) {
return;
}
$this->rules->add($newRule, $type);
} | php | private function addRule($type, Rule $newRule = null)
{
if (!$newRule || $this->rules->containsEqual($newRule)) {
return;
}
$this->rules->add($newRule, $type);
} | [
"private",
"function",
"addRule",
"(",
"$",
"type",
",",
"Rule",
"$",
"newRule",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"newRule",
"||",
"$",
"this",
"->",
"rules",
"->",
"containsEqual",
"(",
"$",
"newRule",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"rules",
"->",
"add",
"(",
"$",
"newRule",
",",
"$",
"type",
")",
";",
"}"
] | Adds a rule unless it duplicates an existing one of any type
To be able to directly pass in the result of one of the rule creation
methods null is allowed which will not insert a rule.
@param int $type A TYPE_* constant defining the rule type
@param Rule $newRule The rule about to be added | [
"Adds",
"a",
"rule",
"unless",
"it",
"duplicates",
"an",
"existing",
"one",
"of",
"any",
"type"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/DependencyResolver/RuleSetGenerator.php#L138-L145 |
zhouyl/mellivora | Mellivora/Cache/CacheServiceProvider.php | CacheServiceProvider.register | public function register()
{
$this->container['cache.manager'] = function ($container) {
$config = $container['config']->get('cache');
$manager = new Manager($config->drivers->toArray());
// 设置默认缓存驱动
$manager->setDefault($config->default);
// 设置日志处理器
$logger = value($config->logger);
if ($logger instanceof LoggerInterface) {
$manager->setLogger($logger);
}
return $manager;
};
$this->container['cache'] = function ($container) {
return $container['cache.manager']->getDefaultCache();
};
$this->container['cache.simple'] = function ($container) {
return $container['cache.manager']->getDefaultSimpleCache();
};
} | php | public function register()
{
$this->container['cache.manager'] = function ($container) {
$config = $container['config']->get('cache');
$manager = new Manager($config->drivers->toArray());
// 设置默认缓存驱动
$manager->setDefault($config->default);
// 设置日志处理器
$logger = value($config->logger);
if ($logger instanceof LoggerInterface) {
$manager->setLogger($logger);
}
return $manager;
};
$this->container['cache'] = function ($container) {
return $container['cache.manager']->getDefaultCache();
};
$this->container['cache.simple'] = function ($container) {
return $container['cache.manager']->getDefaultSimpleCache();
};
} | [
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"container",
"[",
"'cache.manager'",
"]",
"=",
"function",
"(",
"$",
"container",
")",
"{",
"$",
"config",
"=",
"$",
"container",
"[",
"'config'",
"]",
"->",
"get",
"(",
"'cache'",
")",
";",
"$",
"manager",
"=",
"new",
"Manager",
"(",
"$",
"config",
"->",
"drivers",
"->",
"toArray",
"(",
")",
")",
";",
"// 设置默认缓存驱动",
"$",
"manager",
"->",
"setDefault",
"(",
"$",
"config",
"->",
"default",
")",
";",
"// 设置日志处理器",
"$",
"logger",
"=",
"value",
"(",
"$",
"config",
"->",
"logger",
")",
";",
"if",
"(",
"$",
"logger",
"instanceof",
"LoggerInterface",
")",
"{",
"$",
"manager",
"->",
"setLogger",
"(",
"$",
"logger",
")",
";",
"}",
"return",
"$",
"manager",
";",
"}",
";",
"$",
"this",
"->",
"container",
"[",
"'cache'",
"]",
"=",
"function",
"(",
"$",
"container",
")",
"{",
"return",
"$",
"container",
"[",
"'cache.manager'",
"]",
"->",
"getDefaultCache",
"(",
")",
";",
"}",
";",
"$",
"this",
"->",
"container",
"[",
"'cache.simple'",
"]",
"=",
"function",
"(",
"$",
"container",
")",
"{",
"return",
"$",
"container",
"[",
"'cache.manager'",
"]",
"->",
"getDefaultSimpleCache",
"(",
")",
";",
"}",
";",
"}"
] | Register the service provider.
@return void | [
"Register",
"the",
"service",
"provider",
"."
] | train | https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Cache/CacheServiceProvider.php#L15-L41 |
InactiveProjects/limoncello-illuminate | app/Database/Models/Model.php | Model.setAttribute | public function setAttribute($key, $value)
{
// we want to be able to set dates in ISO8601. Laravel has an issue with
// build-in format so we convert input manually.
// For more see https://github.com/laravel/framework/issues/12203
if (is_string($value) && (in_array($key, $this->getDates()) || $this->isDateCastable($key))) {
$value = Carbon::createFromFormat(self::DATE_TIME_FORMAT, $value);
}
return parent::setAttribute($key, $value);
} | php | public function setAttribute($key, $value)
{
// we want to be able to set dates in ISO8601. Laravel has an issue with
// build-in format so we convert input manually.
// For more see https://github.com/laravel/framework/issues/12203
if (is_string($value) && (in_array($key, $this->getDates()) || $this->isDateCastable($key))) {
$value = Carbon::createFromFormat(self::DATE_TIME_FORMAT, $value);
}
return parent::setAttribute($key, $value);
} | [
"public",
"function",
"setAttribute",
"(",
"$",
"key",
",",
"$",
"value",
")",
"{",
"// we want to be able to set dates in ISO8601. Laravel has an issue with",
"// build-in format so we convert input manually.",
"// For more see https://github.com/laravel/framework/issues/12203",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
"&&",
"(",
"in_array",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"getDates",
"(",
")",
")",
"||",
"$",
"this",
"->",
"isDateCastable",
"(",
"$",
"key",
")",
")",
")",
"{",
"$",
"value",
"=",
"Carbon",
"::",
"createFromFormat",
"(",
"self",
"::",
"DATE_TIME_FORMAT",
",",
"$",
"value",
")",
";",
"}",
"return",
"parent",
"::",
"setAttribute",
"(",
"$",
"key",
",",
"$",
"value",
")",
";",
"}"
] | @inheritdoc
@SuppressWarnings(PHPMD.StaticAccess) | [
"@inheritdoc"
] | train | https://github.com/InactiveProjects/limoncello-illuminate/blob/cae6fc26190efcf090495a5c3582c10fa2430897/app/Database/Models/Model.php#L56-L67 |
eXistenZNL/PermCheck | src/Config/Loader/Xml.php | Xml.parse | public function parse()
{
if (!is_string($this->data)) {
throw new \RuntimeException('The given data is no valid string');
}
libxml_use_internal_errors(true);
$xml = simplexml_load_string($this->data);
if ($xml === false) {
throw new \RuntimeException('Error during the loading of the XML file');
}
if (!isset($xml->executables, $xml->excludes)) {
throw new \RuntimeException('Missing configuration elements');
}
foreach ($xml->excludes->children()->file as $file) {
$this->config->addExcludedFile((string) $file);
}
foreach ($xml->excludes->children()->dir as $dir) {
$this->config->addExcludedDir((string) $dir);
}
foreach ($xml->executables->children() as $file) {
$this->config->addExecutableFile((string) $file);
}
return $this->config;
} | php | public function parse()
{
if (!is_string($this->data)) {
throw new \RuntimeException('The given data is no valid string');
}
libxml_use_internal_errors(true);
$xml = simplexml_load_string($this->data);
if ($xml === false) {
throw new \RuntimeException('Error during the loading of the XML file');
}
if (!isset($xml->executables, $xml->excludes)) {
throw new \RuntimeException('Missing configuration elements');
}
foreach ($xml->excludes->children()->file as $file) {
$this->config->addExcludedFile((string) $file);
}
foreach ($xml->excludes->children()->dir as $dir) {
$this->config->addExcludedDir((string) $dir);
}
foreach ($xml->executables->children() as $file) {
$this->config->addExecutableFile((string) $file);
}
return $this->config;
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"this",
"->",
"data",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'The given data is no valid string'",
")",
";",
"}",
"libxml_use_internal_errors",
"(",
"true",
")",
";",
"$",
"xml",
"=",
"simplexml_load_string",
"(",
"$",
"this",
"->",
"data",
")",
";",
"if",
"(",
"$",
"xml",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Error during the loading of the XML file'",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"xml",
"->",
"executables",
",",
"$",
"xml",
"->",
"excludes",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Missing configuration elements'",
")",
";",
"}",
"foreach",
"(",
"$",
"xml",
"->",
"excludes",
"->",
"children",
"(",
")",
"->",
"file",
"as",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"config",
"->",
"addExcludedFile",
"(",
"(",
"string",
")",
"$",
"file",
")",
";",
"}",
"foreach",
"(",
"$",
"xml",
"->",
"excludes",
"->",
"children",
"(",
")",
"->",
"dir",
"as",
"$",
"dir",
")",
"{",
"$",
"this",
"->",
"config",
"->",
"addExcludedDir",
"(",
"(",
"string",
")",
"$",
"dir",
")",
";",
"}",
"foreach",
"(",
"$",
"xml",
"->",
"executables",
"->",
"children",
"(",
")",
"as",
"$",
"file",
")",
"{",
"$",
"this",
"->",
"config",
"->",
"addExecutableFile",
"(",
"(",
"string",
")",
"$",
"file",
")",
";",
"}",
"return",
"$",
"this",
"->",
"config",
";",
"}"
] | Load the configuration and return it in an easy to use config bag.
@throws \RuntimeException When an error occurs.
@return ConfigInterface | [
"Load",
"the",
"configuration",
"and",
"return",
"it",
"in",
"an",
"easy",
"to",
"use",
"config",
"bag",
"."
] | train | https://github.com/eXistenZNL/PermCheck/blob/f22f2936350f6b440222fb6ea37dfc382fc4550e/src/Config/Loader/Xml.php#L20-L47 |
hametuha/wpametu | src/WPametu/UI/Field/Multiple.php | Multiple.build_input | protected function build_input($data, array $fields = []){
$input = $this->get_open_tag($data, $fields);
$counter = 1;
foreach( $this->get_options() as $key => $label ){
$input .= $this->get_option($key, $label, $counter, $data, $fields);
$counter++;
}
$input .= $this->close_tag;
return $input;
} | php | protected function build_input($data, array $fields = []){
$input = $this->get_open_tag($data, $fields);
$counter = 1;
foreach( $this->get_options() as $key => $label ){
$input .= $this->get_option($key, $label, $counter, $data, $fields);
$counter++;
}
$input .= $this->close_tag;
return $input;
} | [
"protected",
"function",
"build_input",
"(",
"$",
"data",
",",
"array",
"$",
"fields",
"=",
"[",
"]",
")",
"{",
"$",
"input",
"=",
"$",
"this",
"->",
"get_open_tag",
"(",
"$",
"data",
",",
"$",
"fields",
")",
";",
"$",
"counter",
"=",
"1",
";",
"foreach",
"(",
"$",
"this",
"->",
"get_options",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"label",
")",
"{",
"$",
"input",
".=",
"$",
"this",
"->",
"get_option",
"(",
"$",
"key",
",",
"$",
"label",
",",
"$",
"counter",
",",
"$",
"data",
",",
"$",
"fields",
")",
";",
"$",
"counter",
"++",
";",
"}",
"$",
"input",
".=",
"$",
"this",
"->",
"close_tag",
";",
"return",
"$",
"input",
";",
"}"
] | Show input labels
@param mixed $data
@param array $fields
@return string | [
"Show",
"input",
"labels"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/Multiple.php#L61-L70 |
php-lug/lug | src/Component/Grid/Filter/Type/ResourceType.php | ResourceType.getTypes | public static function getTypes($collection = false)
{
return array_merge($collection ? self::getCompoundTypes() : self::getSimpleTypes(), self::getEmptyTypes());
} | php | public static function getTypes($collection = false)
{
return array_merge($collection ? self::getCompoundTypes() : self::getSimpleTypes(), self::getEmptyTypes());
} | [
"public",
"static",
"function",
"getTypes",
"(",
"$",
"collection",
"=",
"false",
")",
"{",
"return",
"array_merge",
"(",
"$",
"collection",
"?",
"self",
"::",
"getCompoundTypes",
"(",
")",
":",
"self",
"::",
"getSimpleTypes",
"(",
")",
",",
"self",
"::",
"getEmptyTypes",
"(",
")",
")",
";",
"}"
] | @param bool $collection
@return string[] | [
"@param",
"bool",
"$collection"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/Filter/Type/ResourceType.php#L49-L52 |
php-lug/lug | src/Component/Grid/Filter/Type/ResourceType.php | ResourceType.process | protected function process($field, $data, array $options)
{
$builder = $options['builder'];
$alias = $builder->getAliases()[0];
$prefix = 'lug_'.str_replace('.', '', uniqid(null, true));
$path = isset($options['path']) ? $options['path'] : $field;
if (isset($options['collection']) && $options['collection']) {
$path .= '.'.$options['resource']->getIdPropertyPath();
}
$paths = explode('.', $path);
$field = array_pop($paths);
foreach ($paths as $index => $path) {
$builder->innerJoin($alias.'.'.$path, $alias = $prefix.$index);
}
switch ($data['type']) {
case self::TYPE_EMPTY:
return $builder->getExpressionBuilder()->isNull($builder->getProperty($field, $alias));
case self::TYPE_NOT_EMPTY:
return $builder->getExpressionBuilder()->isNotNull($builder->getProperty($field, $alias));
case self::TYPE_IN:
return $builder->getExpressionBuilder()->in(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
case self::TYPE_NOT_IN:
return $builder->getExpressionBuilder()->notIn(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
case self::TYPE_NOT_EQUALS:
return $builder->getExpressionBuilder()->neq(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
}
return $builder->getExpressionBuilder()->eq(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
} | php | protected function process($field, $data, array $options)
{
$builder = $options['builder'];
$alias = $builder->getAliases()[0];
$prefix = 'lug_'.str_replace('.', '', uniqid(null, true));
$path = isset($options['path']) ? $options['path'] : $field;
if (isset($options['collection']) && $options['collection']) {
$path .= '.'.$options['resource']->getIdPropertyPath();
}
$paths = explode('.', $path);
$field = array_pop($paths);
foreach ($paths as $index => $path) {
$builder->innerJoin($alias.'.'.$path, $alias = $prefix.$index);
}
switch ($data['type']) {
case self::TYPE_EMPTY:
return $builder->getExpressionBuilder()->isNull($builder->getProperty($field, $alias));
case self::TYPE_NOT_EMPTY:
return $builder->getExpressionBuilder()->isNotNull($builder->getProperty($field, $alias));
case self::TYPE_IN:
return $builder->getExpressionBuilder()->in(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
case self::TYPE_NOT_IN:
return $builder->getExpressionBuilder()->notIn(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
case self::TYPE_NOT_EQUALS:
return $builder->getExpressionBuilder()->neq(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
}
return $builder->getExpressionBuilder()->eq(
$builder->getProperty($field, $alias),
$builder->createPlaceholder($field, $data['value'])
);
} | [
"protected",
"function",
"process",
"(",
"$",
"field",
",",
"$",
"data",
",",
"array",
"$",
"options",
")",
"{",
"$",
"builder",
"=",
"$",
"options",
"[",
"'builder'",
"]",
";",
"$",
"alias",
"=",
"$",
"builder",
"->",
"getAliases",
"(",
")",
"[",
"0",
"]",
";",
"$",
"prefix",
"=",
"'lug_'",
".",
"str_replace",
"(",
"'.'",
",",
"''",
",",
"uniqid",
"(",
"null",
",",
"true",
")",
")",
";",
"$",
"path",
"=",
"isset",
"(",
"$",
"options",
"[",
"'path'",
"]",
")",
"?",
"$",
"options",
"[",
"'path'",
"]",
":",
"$",
"field",
";",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'collection'",
"]",
")",
"&&",
"$",
"options",
"[",
"'collection'",
"]",
")",
"{",
"$",
"path",
".=",
"'.'",
".",
"$",
"options",
"[",
"'resource'",
"]",
"->",
"getIdPropertyPath",
"(",
")",
";",
"}",
"$",
"paths",
"=",
"explode",
"(",
"'.'",
",",
"$",
"path",
")",
";",
"$",
"field",
"=",
"array_pop",
"(",
"$",
"paths",
")",
";",
"foreach",
"(",
"$",
"paths",
"as",
"$",
"index",
"=>",
"$",
"path",
")",
"{",
"$",
"builder",
"->",
"innerJoin",
"(",
"$",
"alias",
".",
"'.'",
".",
"$",
"path",
",",
"$",
"alias",
"=",
"$",
"prefix",
".",
"$",
"index",
")",
";",
"}",
"switch",
"(",
"$",
"data",
"[",
"'type'",
"]",
")",
"{",
"case",
"self",
"::",
"TYPE_EMPTY",
":",
"return",
"$",
"builder",
"->",
"getExpressionBuilder",
"(",
")",
"->",
"isNull",
"(",
"$",
"builder",
"->",
"getProperty",
"(",
"$",
"field",
",",
"$",
"alias",
")",
")",
";",
"case",
"self",
"::",
"TYPE_NOT_EMPTY",
":",
"return",
"$",
"builder",
"->",
"getExpressionBuilder",
"(",
")",
"->",
"isNotNull",
"(",
"$",
"builder",
"->",
"getProperty",
"(",
"$",
"field",
",",
"$",
"alias",
")",
")",
";",
"case",
"self",
"::",
"TYPE_IN",
":",
"return",
"$",
"builder",
"->",
"getExpressionBuilder",
"(",
")",
"->",
"in",
"(",
"$",
"builder",
"->",
"getProperty",
"(",
"$",
"field",
",",
"$",
"alias",
")",
",",
"$",
"builder",
"->",
"createPlaceholder",
"(",
"$",
"field",
",",
"$",
"data",
"[",
"'value'",
"]",
")",
")",
";",
"case",
"self",
"::",
"TYPE_NOT_IN",
":",
"return",
"$",
"builder",
"->",
"getExpressionBuilder",
"(",
")",
"->",
"notIn",
"(",
"$",
"builder",
"->",
"getProperty",
"(",
"$",
"field",
",",
"$",
"alias",
")",
",",
"$",
"builder",
"->",
"createPlaceholder",
"(",
"$",
"field",
",",
"$",
"data",
"[",
"'value'",
"]",
")",
")",
";",
"case",
"self",
"::",
"TYPE_NOT_EQUALS",
":",
"return",
"$",
"builder",
"->",
"getExpressionBuilder",
"(",
")",
"->",
"neq",
"(",
"$",
"builder",
"->",
"getProperty",
"(",
"$",
"field",
",",
"$",
"alias",
")",
",",
"$",
"builder",
"->",
"createPlaceholder",
"(",
"$",
"field",
",",
"$",
"data",
"[",
"'value'",
"]",
")",
")",
";",
"}",
"return",
"$",
"builder",
"->",
"getExpressionBuilder",
"(",
")",
"->",
"eq",
"(",
"$",
"builder",
"->",
"getProperty",
"(",
"$",
"field",
",",
"$",
"alias",
")",
",",
"$",
"builder",
"->",
"createPlaceholder",
"(",
"$",
"field",
",",
"$",
"data",
"[",
"'value'",
"]",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/Filter/Type/ResourceType.php#L119-L167 |
php-lug/lug | src/Component/Grid/Filter/Type/ResourceType.php | ResourceType.validate | protected function validate($data, array $options)
{
return parent::validate($data, $options)
&& is_array($data)
&& isset($data['type'])
&& (
(
in_array($data['type'], self::getCompoundTypes(), true)
&& isset($data['value'])
&& is_array($data['value'])
)
|| (
in_array($data['type'], self::getSimpleTypes(), true)
&& isset($data['value'])
&& is_a($data['value'], $options['resource']->getModel())
)
|| in_array($data['type'], self::getEmptyTypes(), true)
);
} | php | protected function validate($data, array $options)
{
return parent::validate($data, $options)
&& is_array($data)
&& isset($data['type'])
&& (
(
in_array($data['type'], self::getCompoundTypes(), true)
&& isset($data['value'])
&& is_array($data['value'])
)
|| (
in_array($data['type'], self::getSimpleTypes(), true)
&& isset($data['value'])
&& is_a($data['value'], $options['resource']->getModel())
)
|| in_array($data['type'], self::getEmptyTypes(), true)
);
} | [
"protected",
"function",
"validate",
"(",
"$",
"data",
",",
"array",
"$",
"options",
")",
"{",
"return",
"parent",
"::",
"validate",
"(",
"$",
"data",
",",
"$",
"options",
")",
"&&",
"is_array",
"(",
"$",
"data",
")",
"&&",
"isset",
"(",
"$",
"data",
"[",
"'type'",
"]",
")",
"&&",
"(",
"(",
"in_array",
"(",
"$",
"data",
"[",
"'type'",
"]",
",",
"self",
"::",
"getCompoundTypes",
"(",
")",
",",
"true",
")",
"&&",
"isset",
"(",
"$",
"data",
"[",
"'value'",
"]",
")",
"&&",
"is_array",
"(",
"$",
"data",
"[",
"'value'",
"]",
")",
")",
"||",
"(",
"in_array",
"(",
"$",
"data",
"[",
"'type'",
"]",
",",
"self",
"::",
"getSimpleTypes",
"(",
")",
",",
"true",
")",
"&&",
"isset",
"(",
"$",
"data",
"[",
"'value'",
"]",
")",
"&&",
"is_a",
"(",
"$",
"data",
"[",
"'value'",
"]",
",",
"$",
"options",
"[",
"'resource'",
"]",
"->",
"getModel",
"(",
")",
")",
")",
"||",
"in_array",
"(",
"$",
"data",
"[",
"'type'",
"]",
",",
"self",
"::",
"getEmptyTypes",
"(",
")",
",",
"true",
")",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Component/Grid/Filter/Type/ResourceType.php#L172-L190 |
zhouyl/mellivora | Mellivora/Database/Grammar.php | Grammar.wrap | public function wrap($value, $prefixAlias = false)
{
if ($this->isExpression($value)) {
return $this->getValue($value);
}
// If the value being wrapped has a column alias we will need to separate out
// the pieces so we can wrap each of the segments of the expression on it
// own, and then joins them both back together with the "as" connector.
if (strpos(strtolower($value), ' as ') !== false) {
return $this->wrapAliasedValue($value, $prefixAlias);
}
return $this->wrapSegments(explode('.', $value));
} | php | public function wrap($value, $prefixAlias = false)
{
if ($this->isExpression($value)) {
return $this->getValue($value);
}
// If the value being wrapped has a column alias we will need to separate out
// the pieces so we can wrap each of the segments of the expression on it
// own, and then joins them both back together with the "as" connector.
if (strpos(strtolower($value), ' as ') !== false) {
return $this->wrapAliasedValue($value, $prefixAlias);
}
return $this->wrapSegments(explode('.', $value));
} | [
"public",
"function",
"wrap",
"(",
"$",
"value",
",",
"$",
"prefixAlias",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isExpression",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getValue",
"(",
"$",
"value",
")",
";",
"}",
"// If the value being wrapped has a column alias we will need to separate out",
"// the pieces so we can wrap each of the segments of the expression on it",
"// own, and then joins them both back together with the \"as\" connector.",
"if",
"(",
"strpos",
"(",
"strtolower",
"(",
"$",
"value",
")",
",",
"' as '",
")",
"!==",
"false",
")",
"{",
"return",
"$",
"this",
"->",
"wrapAliasedValue",
"(",
"$",
"value",
",",
"$",
"prefixAlias",
")",
";",
"}",
"return",
"$",
"this",
"->",
"wrapSegments",
"(",
"explode",
"(",
"'.'",
",",
"$",
"value",
")",
")",
";",
"}"
] | Wrap a value in keyword identifiers.
@param \Mellivora\Database\Query\Expression|string $value
@param bool $prefixAlias
@return string | [
"Wrap",
"a",
"value",
"in",
"keyword",
"identifiers",
"."
] | train | https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Grammar.php#L52-L66 |
zhouyl/mellivora | Mellivora/Database/Eloquent/Concerns/HasGlobalScopes.php | HasGlobalScopes.addGlobalScope | public static function addGlobalScope($scope, Closure $implementation = null)
{
if (is_string($scope) && !is_null($implementation)) {
return static::$globalScopes[static::class][$scope] = $implementation;
}
if ($scope instanceof Closure) {
return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope;
}
if ($scope instanceof Scope) {
return static::$globalScopes[static::class][get_class($scope)] = $scope;
}
throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.');
} | php | public static function addGlobalScope($scope, Closure $implementation = null)
{
if (is_string($scope) && !is_null($implementation)) {
return static::$globalScopes[static::class][$scope] = $implementation;
}
if ($scope instanceof Closure) {
return static::$globalScopes[static::class][spl_object_hash($scope)] = $scope;
}
if ($scope instanceof Scope) {
return static::$globalScopes[static::class][get_class($scope)] = $scope;
}
throw new InvalidArgumentException('Global scope must be an instance of Closure or Scope.');
} | [
"public",
"static",
"function",
"addGlobalScope",
"(",
"$",
"scope",
",",
"Closure",
"$",
"implementation",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"scope",
")",
"&&",
"!",
"is_null",
"(",
"$",
"implementation",
")",
")",
"{",
"return",
"static",
"::",
"$",
"globalScopes",
"[",
"static",
"::",
"class",
"]",
"[",
"$",
"scope",
"]",
"=",
"$",
"implementation",
";",
"}",
"if",
"(",
"$",
"scope",
"instanceof",
"Closure",
")",
"{",
"return",
"static",
"::",
"$",
"globalScopes",
"[",
"static",
"::",
"class",
"]",
"[",
"spl_object_hash",
"(",
"$",
"scope",
")",
"]",
"=",
"$",
"scope",
";",
"}",
"if",
"(",
"$",
"scope",
"instanceof",
"Scope",
")",
"{",
"return",
"static",
"::",
"$",
"globalScopes",
"[",
"static",
"::",
"class",
"]",
"[",
"get_class",
"(",
"$",
"scope",
")",
"]",
"=",
"$",
"scope",
";",
"}",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Global scope must be an instance of Closure or Scope.'",
")",
";",
"}"
] | Register a new global scope on the model.
@param \Closure|\Mellivora\Database\Eloquent\Scope|string $scope
@param null|\Closure $implementation
@throws \InvalidArgumentException
@return mixed | [
"Register",
"a",
"new",
"global",
"scope",
"on",
"the",
"model",
"."
] | train | https://github.com/zhouyl/mellivora/blob/79f844c5c9c25ffbe18d142062e9bc3df00b36a1/Mellivora/Database/Eloquent/Concerns/HasGlobalScopes.php#L22-L35 |
dcsg/EventbriteApiConnector | lib/EventbriteApiConnector/Eventbrite.php | Eventbrite.get | public function get($method, array $params, array $options = array())
{
$this->parseOptions($options);
$params = array_merge($params, $this->apiKeys);
$response = $this->httpAdapter->getContent(
sprintf(self::API_ENDPOINT, $this->scheme, $this->outputFormat, $method .'?'. http_build_query($params)),
$this->headers
);
return $this->responseHandler($response);
} | php | public function get($method, array $params, array $options = array())
{
$this->parseOptions($options);
$params = array_merge($params, $this->apiKeys);
$response = $this->httpAdapter->getContent(
sprintf(self::API_ENDPOINT, $this->scheme, $this->outputFormat, $method .'?'. http_build_query($params)),
$this->headers
);
return $this->responseHandler($response);
} | [
"public",
"function",
"get",
"(",
"$",
"method",
",",
"array",
"$",
"params",
",",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"parseOptions",
"(",
"$",
"options",
")",
";",
"$",
"params",
"=",
"array_merge",
"(",
"$",
"params",
",",
"$",
"this",
"->",
"apiKeys",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"httpAdapter",
"->",
"getContent",
"(",
"sprintf",
"(",
"self",
"::",
"API_ENDPOINT",
",",
"$",
"this",
"->",
"scheme",
",",
"$",
"this",
"->",
"outputFormat",
",",
"$",
"method",
".",
"'?'",
".",
"http_build_query",
"(",
"$",
"params",
")",
")",
",",
"$",
"this",
"->",
"headers",
")",
";",
"return",
"$",
"this",
"->",
"responseHandler",
"(",
"$",
"response",
")",
";",
"}"
] | Calls the Eventbrite API via GET
@param string $method Eventbrite API method
@param array $params API method params
@param array $options Options for calling the API like scheme, headers and output format
@return string The content | [
"Calls",
"the",
"Eventbrite",
"API",
"via",
"GET"
] | train | https://github.com/dcsg/EventbriteApiConnector/blob/3926f6dee8d824601cad7155bc2b5f9748218236/lib/EventbriteApiConnector/Eventbrite.php#L79-L91 |
dcsg/EventbriteApiConnector | lib/EventbriteApiConnector/Eventbrite.php | Eventbrite.parseOptions | private function parseOptions(array $options)
{
if (isset($options['headers']) && is_array($options['headers'])) {
$this->headers = $options['headers'];
}
if (isset($options['scheme']) && strtolower($options['scheme']) === 'http') {
$this->scheme = 'http';
}
if (isset($options['output_format']) && strtolower($options['output_format']) === 'xml') {
$this->outputFormat = 'xml';
}
} | php | private function parseOptions(array $options)
{
if (isset($options['headers']) && is_array($options['headers'])) {
$this->headers = $options['headers'];
}
if (isset($options['scheme']) && strtolower($options['scheme']) === 'http') {
$this->scheme = 'http';
}
if (isset($options['output_format']) && strtolower($options['output_format']) === 'xml') {
$this->outputFormat = 'xml';
}
} | [
"private",
"function",
"parseOptions",
"(",
"array",
"$",
"options",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'headers'",
"]",
")",
"&&",
"is_array",
"(",
"$",
"options",
"[",
"'headers'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"headers",
"=",
"$",
"options",
"[",
"'headers'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'scheme'",
"]",
")",
"&&",
"strtolower",
"(",
"$",
"options",
"[",
"'scheme'",
"]",
")",
"===",
"'http'",
")",
"{",
"$",
"this",
"->",
"scheme",
"=",
"'http'",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"options",
"[",
"'output_format'",
"]",
")",
"&&",
"strtolower",
"(",
"$",
"options",
"[",
"'output_format'",
"]",
")",
"===",
"'xml'",
")",
"{",
"$",
"this",
"->",
"outputFormat",
"=",
"'xml'",
";",
"}",
"}"
] | Parser for options like scheme, headers and output format.
@param array $options
@return null | [
"Parser",
"for",
"options",
"like",
"scheme",
"headers",
"and",
"output",
"format",
"."
] | train | https://github.com/dcsg/EventbriteApiConnector/blob/3926f6dee8d824601cad7155bc2b5f9748218236/lib/EventbriteApiConnector/Eventbrite.php#L126-L139 |
dcsg/EventbriteApiConnector | lib/EventbriteApiConnector/Eventbrite.php | Eventbrite.responseHandler | private function responseHandler($responseBody)
{
if ('json' === $this->outputFormat) {
return $this->validateJsonResponse($responseBody);
}
return $this->validateXmlResponse($responseBody);
} | php | private function responseHandler($responseBody)
{
if ('json' === $this->outputFormat) {
return $this->validateJsonResponse($responseBody);
}
return $this->validateXmlResponse($responseBody);
} | [
"private",
"function",
"responseHandler",
"(",
"$",
"responseBody",
")",
"{",
"if",
"(",
"'json'",
"===",
"$",
"this",
"->",
"outputFormat",
")",
"{",
"return",
"$",
"this",
"->",
"validateJsonResponse",
"(",
"$",
"responseBody",
")",
";",
"}",
"return",
"$",
"this",
"->",
"validateXmlResponse",
"(",
"$",
"responseBody",
")",
";",
"}"
] | Handler for validate the response body.
@param string $responseBody Content body of the response
@return string | [
"Handler",
"for",
"validate",
"the",
"response",
"body",
"."
] | train | https://github.com/dcsg/EventbriteApiConnector/blob/3926f6dee8d824601cad7155bc2b5f9748218236/lib/EventbriteApiConnector/Eventbrite.php#L148-L155 |
dcsg/EventbriteApiConnector | lib/EventbriteApiConnector/Eventbrite.php | Eventbrite.validateJsonResponse | private function validateJsonResponse($responseBody)
{
$data = json_decode($responseBody);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception('Error decoding JSON.');
}
if (isset($data->error)) {
throw new \Exception($data->error->error_message);
}
if (empty($data)) {
throw new \Exception('No results found.');
}
return $responseBody;
} | php | private function validateJsonResponse($responseBody)
{
$data = json_decode($responseBody);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception('Error decoding JSON.');
}
if (isset($data->error)) {
throw new \Exception($data->error->error_message);
}
if (empty($data)) {
throw new \Exception('No results found.');
}
return $responseBody;
} | [
"private",
"function",
"validateJsonResponse",
"(",
"$",
"responseBody",
")",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"responseBody",
")",
";",
"if",
"(",
"json_last_error",
"(",
")",
"!==",
"JSON_ERROR_NONE",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Error decoding JSON.'",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"data",
"->",
"error",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"$",
"data",
"->",
"error",
"->",
"error_message",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'No results found.'",
")",
";",
"}",
"return",
"$",
"responseBody",
";",
"}"
] | Parses the response content for the JSON output format
@param string $responseBody
@return string
@throws \Exception | [
"Parses",
"the",
"response",
"content",
"for",
"the",
"JSON",
"output",
"format"
] | train | https://github.com/dcsg/EventbriteApiConnector/blob/3926f6dee8d824601cad7155bc2b5f9748218236/lib/EventbriteApiConnector/Eventbrite.php#L165-L182 |
dcsg/EventbriteApiConnector | lib/EventbriteApiConnector/Eventbrite.php | Eventbrite.validateXmlResponse | private function validateXmlResponse($responseBody)
{
$data = simplexml_load_string($responseBody);
if (isset($data->error_type)) {
throw new \Exception($data->error_message);
}
return $responseBody;
} | php | private function validateXmlResponse($responseBody)
{
$data = simplexml_load_string($responseBody);
if (isset($data->error_type)) {
throw new \Exception($data->error_message);
}
return $responseBody;
} | [
"private",
"function",
"validateXmlResponse",
"(",
"$",
"responseBody",
")",
"{",
"$",
"data",
"=",
"simplexml_load_string",
"(",
"$",
"responseBody",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"data",
"->",
"error_type",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"$",
"data",
"->",
"error_message",
")",
";",
"}",
"return",
"$",
"responseBody",
";",
"}"
] | Parses the response content for the XML output format
@param string $responseBody
@return string
@throws \Exception | [
"Parses",
"the",
"response",
"content",
"for",
"the",
"XML",
"output",
"format"
] | train | https://github.com/dcsg/EventbriteApiConnector/blob/3926f6dee8d824601cad7155bc2b5f9748218236/lib/EventbriteApiConnector/Eventbrite.php#L192-L201 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.getTypes | public function getTypes($number)
{
$binstring = decbin((int) $number);
$types = array();
$mlen = strlen($binstring) - 3;
$low = substr($binstring, $mlen, strlen($binstring));
$high = substr($binstring, 0, $mlen) . '0000';
$types['wired'] = bindec($low);
$types['field'] = bindec($binstring) >> 3;
return $types;
} | php | public function getTypes($number)
{
$binstring = decbin((int) $number);
$types = array();
$mlen = strlen($binstring) - 3;
$low = substr($binstring, $mlen, strlen($binstring));
$high = substr($binstring, 0, $mlen) . '0000';
$types['wired'] = bindec($low);
$types['field'] = bindec($binstring) >> 3;
return $types;
} | [
"public",
"function",
"getTypes",
"(",
"$",
"number",
")",
"{",
"$",
"binstring",
"=",
"decbin",
"(",
"(",
"int",
")",
"$",
"number",
")",
";",
"$",
"types",
"=",
"array",
"(",
")",
";",
"$",
"mlen",
"=",
"strlen",
"(",
"$",
"binstring",
")",
"-",
"3",
";",
"$",
"low",
"=",
"substr",
"(",
"$",
"binstring",
",",
"$",
"mlen",
",",
"strlen",
"(",
"$",
"binstring",
")",
")",
";",
"$",
"high",
"=",
"substr",
"(",
"$",
"binstring",
",",
"0",
",",
"$",
"mlen",
")",
".",
"'0000'",
";",
"$",
"types",
"[",
"'wired'",
"]",
"=",
"bindec",
"(",
"$",
"low",
")",
";",
"$",
"types",
"[",
"'field'",
"]",
"=",
"bindec",
"(",
"$",
"binstring",
")",
">>",
"3",
";",
"return",
"$",
"types",
";",
"}"
] | Get the wired_type and field_type
@param $number
@return array wired_type, field_type | [
"Get",
"the",
"wired_type",
"and",
"field_type"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L77-L87 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.serializeToString | public function serializeToString($rec = -1)
{
$string = '';
// wired and type
if ($rec > -1) {
$string .= $this->base128->setValue($rec << 3 | $this->wired_type);
}
$stringinner = '';
foreach ($this->fields as $index => $field) {
if (is_array($this->values[$index]) && count($this->values[$index]) > 0) {
// make serialization for every array
foreach ($this->values[$index] as $array) {
$newstring = '';
if (method_exists($array, 'serializeToString')) {
$newstring .= $array->serializeToString($index);
}
$stringinner .= $newstring;
}
} elseif ($this->values[$index] !== null) {
// wired and type
$newstring = '';
if (method_exists($this->values[$index], 'serializeToString')) {
$newstring .= $this->values[$index]->serializeToString($index);
}
$stringinner .= $newstring;
}
}
$this->serializeChunk($stringinner);
if ($this->wired_type === PBMessage::WIRED_LENGTH_DELIMITED && $rec > -1) {
$stringinner = $this->base128->setValue(strlen($stringinner) / PBMessage::MODUS) . $stringinner;
}
return $string . $stringinner;
} | php | public function serializeToString($rec = -1)
{
$string = '';
// wired and type
if ($rec > -1) {
$string .= $this->base128->setValue($rec << 3 | $this->wired_type);
}
$stringinner = '';
foreach ($this->fields as $index => $field) {
if (is_array($this->values[$index]) && count($this->values[$index]) > 0) {
// make serialization for every array
foreach ($this->values[$index] as $array) {
$newstring = '';
if (method_exists($array, 'serializeToString')) {
$newstring .= $array->serializeToString($index);
}
$stringinner .= $newstring;
}
} elseif ($this->values[$index] !== null) {
// wired and type
$newstring = '';
if (method_exists($this->values[$index], 'serializeToString')) {
$newstring .= $this->values[$index]->serializeToString($index);
}
$stringinner .= $newstring;
}
}
$this->serializeChunk($stringinner);
if ($this->wired_type === PBMessage::WIRED_LENGTH_DELIMITED && $rec > -1) {
$stringinner = $this->base128->setValue(strlen($stringinner) / PBMessage::MODUS) . $stringinner;
}
return $string . $stringinner;
} | [
"public",
"function",
"serializeToString",
"(",
"$",
"rec",
"=",
"-",
"1",
")",
"{",
"$",
"string",
"=",
"''",
";",
"// wired and type\r",
"if",
"(",
"$",
"rec",
">",
"-",
"1",
")",
"{",
"$",
"string",
".=",
"$",
"this",
"->",
"base128",
"->",
"setValue",
"(",
"$",
"rec",
"<<",
"3",
"|",
"$",
"this",
"->",
"wired_type",
")",
";",
"}",
"$",
"stringinner",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"fields",
"as",
"$",
"index",
"=>",
"$",
"field",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
")",
"&&",
"count",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
")",
">",
"0",
")",
"{",
"// make serialization for every array\r",
"foreach",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"as",
"$",
"array",
")",
"{",
"$",
"newstring",
"=",
"''",
";",
"if",
"(",
"method_exists",
"(",
"$",
"array",
",",
"'serializeToString'",
")",
")",
"{",
"$",
"newstring",
".=",
"$",
"array",
"->",
"serializeToString",
"(",
"$",
"index",
")",
";",
"}",
"$",
"stringinner",
".=",
"$",
"newstring",
";",
"}",
"}",
"elseif",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"!==",
"null",
")",
"{",
"// wired and type\r",
"$",
"newstring",
"=",
"''",
";",
"if",
"(",
"method_exists",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
",",
"'serializeToString'",
")",
")",
"{",
"$",
"newstring",
".=",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"->",
"serializeToString",
"(",
"$",
"index",
")",
";",
"}",
"$",
"stringinner",
".=",
"$",
"newstring",
";",
"}",
"}",
"$",
"this",
"->",
"serializeChunk",
"(",
"$",
"stringinner",
")",
";",
"if",
"(",
"$",
"this",
"->",
"wired_type",
"===",
"PBMessage",
"::",
"WIRED_LENGTH_DELIMITED",
"&&",
"$",
"rec",
">",
"-",
"1",
")",
"{",
"$",
"stringinner",
"=",
"$",
"this",
"->",
"base128",
"->",
"setValue",
"(",
"strlen",
"(",
"$",
"stringinner",
")",
"/",
"PBMessage",
"::",
"MODUS",
")",
".",
"$",
"stringinner",
";",
"}",
"return",
"$",
"string",
".",
"$",
"stringinner",
";",
"}"
] | Encodes a Message
@param mixed $rec
@return string the encoded message | [
"Encodes",
"a",
"Message"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L95-L135 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.parseFromArray | public function parseFromArray()
{
$this->chunk = '';
// read the length byte
$length = $this->reader->next();
// just take the splice from this array
$this->childParseFromArray($length);
} | php | public function parseFromArray()
{
$this->chunk = '';
// read the length byte
$length = $this->reader->next();
// just take the splice from this array
$this->childParseFromArray($length);
} | [
"public",
"function",
"parseFromArray",
"(",
")",
"{",
"$",
"this",
"->",
"chunk",
"=",
"''",
";",
"// read the length byte\r",
"$",
"length",
"=",
"$",
"this",
"->",
"reader",
"->",
"next",
"(",
")",
";",
"// just take the splice from this array\r",
"$",
"this",
"->",
"childParseFromArray",
"(",
"$",
"length",
")",
";",
"}"
] | Internal function
@throws \InvalidArgumentException | [
"Internal",
"function"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L162-L169 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.childParseFromArray | private function childParseFromArray($length = 99999999)
{
$_begin = $this->reader->getPointer();
while ($this->reader->getPointer() - $_begin < $length) {
$next = $this->reader->next();
if ($next === false) {
break;
}
// now get the message type
$messtypes = $this->getTypes($next);
// now make method test
if (!array_key_exists($messtypes['field'], $this->fields)) {
// field is unknown so just ignore it
// throw new \Exception('Field ' . $messtypes['field'] . ' not present ');
if ((int) $messtypes['wired'] === PBMessage::WIRED_LENGTH_DELIMITED) {
$consume = new PBString($this->reader);
} elseif ((int) $messtypes['wired'] === PBMessage::WIRED_VARINT) {
$consume = new PBInt($this->reader);
} else {
throw new \InvalidArgumentException('I dont understand this wired code:' . $messtypes['wired']);
}
// perhaps send a warning out
// @TODO SEND CHUNK WARNING
$_oldpointer = $this->reader->getPointer();
$consume->parseFromArray();
// now add array from _oldpointer to pointer to the chunk array
$this->chunk .= $this->reader->getMessageFrom($_oldpointer);
continue;
}
// now array or not
if (is_array($this->values[$messtypes['field']])) {
$this->values[$messtypes['field']][] = new $this->fields[$messtypes['field']]($this->reader);
$index = count($this->values[$messtypes['field']]) - 1;
if ($messtypes['wired'] !== $this->values[$messtypes['field']][$index]->wired_type) {
throw new \InvalidArgumentException('Expected type:' . $messtypes['wired']
. ' but had ' . $this->fields[$messtypes['field']]->wired_type);
}
if (method_exists($this->values[$messtypes['field']][$index], 'parseFromArray')) {
$this->values[$messtypes['field']][$index]->parseFromArray();
}
} else {
$this->values[$messtypes['field']] = new $this->fields[$messtypes['field']]($this->reader);
if ($messtypes['wired'] !== $this->values[$messtypes['field']]->wired_type) {
throw new \InvalidArgumentException('Expected type:' . $messtypes['wired']
. ' but had ' . $this->fields[$messtypes['field']]->wired_type);
}
if (method_exists($this->values[$messtypes['field']], 'parseFromArray')) {
$this->values[$messtypes['field']]->parseFromArray();
}
}
}
} | php | private function childParseFromArray($length = 99999999)
{
$_begin = $this->reader->getPointer();
while ($this->reader->getPointer() - $_begin < $length) {
$next = $this->reader->next();
if ($next === false) {
break;
}
// now get the message type
$messtypes = $this->getTypes($next);
// now make method test
if (!array_key_exists($messtypes['field'], $this->fields)) {
// field is unknown so just ignore it
// throw new \Exception('Field ' . $messtypes['field'] . ' not present ');
if ((int) $messtypes['wired'] === PBMessage::WIRED_LENGTH_DELIMITED) {
$consume = new PBString($this->reader);
} elseif ((int) $messtypes['wired'] === PBMessage::WIRED_VARINT) {
$consume = new PBInt($this->reader);
} else {
throw new \InvalidArgumentException('I dont understand this wired code:' . $messtypes['wired']);
}
// perhaps send a warning out
// @TODO SEND CHUNK WARNING
$_oldpointer = $this->reader->getPointer();
$consume->parseFromArray();
// now add array from _oldpointer to pointer to the chunk array
$this->chunk .= $this->reader->getMessageFrom($_oldpointer);
continue;
}
// now array or not
if (is_array($this->values[$messtypes['field']])) {
$this->values[$messtypes['field']][] = new $this->fields[$messtypes['field']]($this->reader);
$index = count($this->values[$messtypes['field']]) - 1;
if ($messtypes['wired'] !== $this->values[$messtypes['field']][$index]->wired_type) {
throw new \InvalidArgumentException('Expected type:' . $messtypes['wired']
. ' but had ' . $this->fields[$messtypes['field']]->wired_type);
}
if (method_exists($this->values[$messtypes['field']][$index], 'parseFromArray')) {
$this->values[$messtypes['field']][$index]->parseFromArray();
}
} else {
$this->values[$messtypes['field']] = new $this->fields[$messtypes['field']]($this->reader);
if ($messtypes['wired'] !== $this->values[$messtypes['field']]->wired_type) {
throw new \InvalidArgumentException('Expected type:' . $messtypes['wired']
. ' but had ' . $this->fields[$messtypes['field']]->wired_type);
}
if (method_exists($this->values[$messtypes['field']], 'parseFromArray')) {
$this->values[$messtypes['field']]->parseFromArray();
}
}
}
} | [
"private",
"function",
"childParseFromArray",
"(",
"$",
"length",
"=",
"99999999",
")",
"{",
"$",
"_begin",
"=",
"$",
"this",
"->",
"reader",
"->",
"getPointer",
"(",
")",
";",
"while",
"(",
"$",
"this",
"->",
"reader",
"->",
"getPointer",
"(",
")",
"-",
"$",
"_begin",
"<",
"$",
"length",
")",
"{",
"$",
"next",
"=",
"$",
"this",
"->",
"reader",
"->",
"next",
"(",
")",
";",
"if",
"(",
"$",
"next",
"===",
"false",
")",
"{",
"break",
";",
"}",
"// now get the message type\r",
"$",
"messtypes",
"=",
"$",
"this",
"->",
"getTypes",
"(",
"$",
"next",
")",
";",
"// now make method test\r",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"messtypes",
"[",
"'field'",
"]",
",",
"$",
"this",
"->",
"fields",
")",
")",
"{",
"// field is unknown so just ignore it\r",
"// throw new \\Exception('Field ' . $messtypes['field'] . ' not present ');\r",
"if",
"(",
"(",
"int",
")",
"$",
"messtypes",
"[",
"'wired'",
"]",
"===",
"PBMessage",
"::",
"WIRED_LENGTH_DELIMITED",
")",
"{",
"$",
"consume",
"=",
"new",
"PBString",
"(",
"$",
"this",
"->",
"reader",
")",
";",
"}",
"elseif",
"(",
"(",
"int",
")",
"$",
"messtypes",
"[",
"'wired'",
"]",
"===",
"PBMessage",
"::",
"WIRED_VARINT",
")",
"{",
"$",
"consume",
"=",
"new",
"PBInt",
"(",
"$",
"this",
"->",
"reader",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'I dont understand this wired code:'",
".",
"$",
"messtypes",
"[",
"'wired'",
"]",
")",
";",
"}",
"// perhaps send a warning out\r",
"// @TODO SEND CHUNK WARNING\r",
"$",
"_oldpointer",
"=",
"$",
"this",
"->",
"reader",
"->",
"getPointer",
"(",
")",
";",
"$",
"consume",
"->",
"parseFromArray",
"(",
")",
";",
"// now add array from _oldpointer to pointer to the chunk array\r",
"$",
"this",
"->",
"chunk",
".=",
"$",
"this",
"->",
"reader",
"->",
"getMessageFrom",
"(",
"$",
"_oldpointer",
")",
";",
"continue",
";",
"}",
"// now array or not\r",
"if",
"(",
"is_array",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
")",
")",
"{",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"[",
"]",
"=",
"new",
"$",
"this",
"->",
"fields",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"(",
"$",
"this",
"->",
"reader",
")",
";",
"$",
"index",
"=",
"count",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
")",
"-",
"1",
";",
"if",
"(",
"$",
"messtypes",
"[",
"'wired'",
"]",
"!==",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"[",
"$",
"index",
"]",
"->",
"wired_type",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Expected type:'",
".",
"$",
"messtypes",
"[",
"'wired'",
"]",
".",
"' but had '",
".",
"$",
"this",
"->",
"fields",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"->",
"wired_type",
")",
";",
"}",
"if",
"(",
"method_exists",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"[",
"$",
"index",
"]",
",",
"'parseFromArray'",
")",
")",
"{",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"[",
"$",
"index",
"]",
"->",
"parseFromArray",
"(",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"=",
"new",
"$",
"this",
"->",
"fields",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"(",
"$",
"this",
"->",
"reader",
")",
";",
"if",
"(",
"$",
"messtypes",
"[",
"'wired'",
"]",
"!==",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"->",
"wired_type",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Expected type:'",
".",
"$",
"messtypes",
"[",
"'wired'",
"]",
".",
"' but had '",
".",
"$",
"this",
"->",
"fields",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"->",
"wired_type",
")",
";",
"}",
"if",
"(",
"method_exists",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
",",
"'parseFromArray'",
")",
")",
"{",
"$",
"this",
"->",
"values",
"[",
"$",
"messtypes",
"[",
"'field'",
"]",
"]",
"->",
"parseFromArray",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Internal function
@throws \InvalidArgumentException | [
"Internal",
"function"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L175-L230 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.addArrValue | protected function addArrValue($index)
{
$class_name = $this->fields[$index];
$real_class_name = __NAMESPACE__ . "\\" . $class_name;
return $this->values[$index][] = new $real_class_name();
} | php | protected function addArrValue($index)
{
$class_name = $this->fields[$index];
$real_class_name = __NAMESPACE__ . "\\" . $class_name;
return $this->values[$index][] = new $real_class_name();
} | [
"protected",
"function",
"addArrValue",
"(",
"$",
"index",
")",
"{",
"$",
"class_name",
"=",
"$",
"this",
"->",
"fields",
"[",
"$",
"index",
"]",
";",
"$",
"real_class_name",
"=",
"__NAMESPACE__",
".",
"\"\\\\\"",
".",
"$",
"class_name",
";",
"return",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"[",
"]",
"=",
"new",
"$",
"real_class_name",
"(",
")",
";",
"}"
] | Add an array value
@param int - index of the field | [
"Add",
"an",
"array",
"value"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L236-L241 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.setValue | protected function setValue($index, $value)
{
if (gettype($value) === 'object') {
$this->values[$index] = $value;
} else {
$class_name = $this->fields[$index];
$real_class_name = __NAMESPACE__ . "\\" . $class_name;
$this->values[$index] = new $real_class_name();
$this->values[$index]->value = $value;
}
return $this;
} | php | protected function setValue($index, $value)
{
if (gettype($value) === 'object') {
$this->values[$index] = $value;
} else {
$class_name = $this->fields[$index];
$real_class_name = __NAMESPACE__ . "\\" . $class_name;
$this->values[$index] = new $real_class_name();
$this->values[$index]->value = $value;
}
return $this;
} | [
"protected",
"function",
"setValue",
"(",
"$",
"index",
",",
"$",
"value",
")",
"{",
"if",
"(",
"gettype",
"(",
"$",
"value",
")",
"===",
"'object'",
")",
"{",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"$",
"class_name",
"=",
"$",
"this",
"->",
"fields",
"[",
"$",
"index",
"]",
";",
"$",
"real_class_name",
"=",
"__NAMESPACE__",
".",
"\"\\\\\"",
".",
"$",
"class_name",
";",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"=",
"new",
"$",
"real_class_name",
"(",
")",
";",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"->",
"value",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Set an value
@param int - index of the field
@param Mixed $value
@return mixed | [
"Set",
"an",
"value"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L269-L280 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.getValue | protected function getValue($index)
{
if ($this->values[$index] === null) {
return null;
}
return $this->values[$index]->value;
} | php | protected function getValue($index)
{
if ($this->values[$index] === null) {
return null;
}
return $this->values[$index]->value;
} | [
"protected",
"function",
"getValue",
"(",
"$",
"index",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"values",
"[",
"$",
"index",
"]",
"->",
"value",
";",
"}"
] | Get a value
@param string $index id of the field
@return mixed | [
"Get",
"a",
"value"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L288-L294 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.saveString | protected function saveString($ch, $string)
{
$this->dString .= $string;
$content_length = strlen($this->dString);
return strlen($string);
} | php | protected function saveString($ch, $string)
{
$this->dString .= $string;
$content_length = strlen($this->dString);
return strlen($string);
} | [
"protected",
"function",
"saveString",
"(",
"$",
"ch",
",",
"$",
"string",
")",
"{",
"$",
"this",
"->",
"dString",
".=",
"$",
"string",
";",
"$",
"content_length",
"=",
"strlen",
"(",
"$",
"this",
"->",
"dString",
")",
";",
"return",
"strlen",
"(",
"$",
"string",
")",
";",
"}"
] | Helper method for send string | [
"Helper",
"method",
"for",
"send",
"string"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L319-L324 |
getuisdk/getui-php-sdk | src/PBMessage.php | PBMessage.send | public function send($url, &$class = null)
{
$ch = curl_init();
$this->dString = '';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'saveString'));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'message=' . urlencode($this->serializeToString()));
$result = curl_exec($ch);
if ($class !== null && method_exists($class, 'parseFromString')) {
$class->parseFromString($this->dString);
}
return $this->dString;
} | php | public function send($url, &$class = null)
{
$ch = curl_init();
$this->dString = '';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'saveString'));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'message=' . urlencode($this->serializeToString()));
$result = curl_exec($ch);
if ($class !== null && method_exists($class, 'parseFromString')) {
$class->parseFromString($this->dString);
}
return $this->dString;
} | [
"public",
"function",
"send",
"(",
"$",
"url",
",",
"&",
"$",
"class",
"=",
"null",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"$",
"this",
"->",
"dString",
"=",
"''",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_URL",
",",
"$",
"url",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POST",
",",
"true",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_WRITEFUNCTION",
",",
"array",
"(",
"$",
"this",
",",
"'saveString'",
")",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POSTFIELDS",
",",
"'message='",
".",
"urlencode",
"(",
"$",
"this",
"->",
"serializeToString",
"(",
")",
")",
")",
";",
"$",
"result",
"=",
"curl_exec",
"(",
"$",
"ch",
")",
";",
"if",
"(",
"$",
"class",
"!==",
"null",
"&&",
"method_exists",
"(",
"$",
"class",
",",
"'parseFromString'",
")",
")",
"{",
"$",
"class",
"->",
"parseFromString",
"(",
"$",
"this",
"->",
"dString",
")",
";",
"}",
"return",
"$",
"this",
"->",
"dString",
";",
"}"
] | sends the message via post request ['message'] to the url
@param string $url the url
@param the PBMessage class where the request should be encoded
@return String - the return string from the request to the url | [
"sends",
"the",
"message",
"via",
"post",
"request",
"[",
"message",
"]",
"to",
"the",
"url",
"@param",
"string",
"$url",
"the",
"url",
"@param",
"the",
"PBMessage",
"class",
"where",
"the",
"request",
"should",
"be",
"encoded"
] | train | https://github.com/getuisdk/getui-php-sdk/blob/e91773b099bcbfd7492a44086b373d1c9fee37e2/src/PBMessage.php#L333-L348 |
pinepain/amqpy | src/AMQPy/AbstractConsumer.php | AbstractConsumer.failure | public function failure(Exception $e, Delivery $delivery, AbstractListener $listener)
{
$listener->resend($delivery);
} | php | public function failure(Exception $e, Delivery $delivery, AbstractListener $listener)
{
$listener->resend($delivery);
} | [
"public",
"function",
"failure",
"(",
"Exception",
"$",
"e",
",",
"Delivery",
"$",
"delivery",
",",
"AbstractListener",
"$",
"listener",
")",
"{",
"$",
"listener",
"->",
"resend",
"(",
"$",
"delivery",
")",
";",
"}"
] | Handle any exception during queued message data processing. | [
"Handle",
"any",
"exception",
"during",
"queued",
"message",
"data",
"processing",
"."
] | train | https://github.com/pinepain/amqpy/blob/fc61dacc37a97a100caf67232a72be32dd7cc896/src/AMQPy/AbstractConsumer.php#L37-L40 |
pinepain/amqpy | src/AMQPy/AbstractConsumer.php | AbstractConsumer.always | public function always($result, $payload, Delivery $delivery, AbstractListener $listener, Exception $exception = null)
{
if ($exception) {
throw $exception;
}
} | php | public function always($result, $payload, Delivery $delivery, AbstractListener $listener, Exception $exception = null)
{
if ($exception) {
throw $exception;
}
} | [
"public",
"function",
"always",
"(",
"$",
"result",
",",
"$",
"payload",
",",
"Delivery",
"$",
"delivery",
",",
"AbstractListener",
"$",
"listener",
",",
"Exception",
"$",
"exception",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"exception",
")",
"{",
"throw",
"$",
"exception",
";",
"}",
"}"
] | Post-consume hook. Invoked after failure() or after() method.
@param $result
@param $payload
@param Delivery $delivery
@param AbstractListener $listener
@param Exception $exception
@throws Exception | [
"Post",
"-",
"consume",
"hook",
".",
"Invoked",
"after",
"failure",
"()",
"or",
"after",
"()",
"method",
"."
] | train | https://github.com/pinepain/amqpy/blob/fc61dacc37a97a100caf67232a72be32dd7cc896/src/AMQPy/AbstractConsumer.php#L60-L65 |
zicht/z | src/Zicht/Tool/Script/Node/Script/With.php | With.beforeScript | public function beforeScript(Buffer $buffer)
{
$buffer->write(sprintf('$z->push(\'%s\', ', $this->name));
$this->nodes[0]->compile($buffer);
$buffer->write(');');
} | php | public function beforeScript(Buffer $buffer)
{
$buffer->write(sprintf('$z->push(\'%s\', ', $this->name));
$this->nodes[0]->compile($buffer);
$buffer->write(');');
} | [
"public",
"function",
"beforeScript",
"(",
"Buffer",
"$",
"buffer",
")",
"{",
"$",
"buffer",
"->",
"write",
"(",
"sprintf",
"(",
"'$z->push(\\'%s\\', '",
",",
"$",
"this",
"->",
"name",
")",
")",
";",
"$",
"this",
"->",
"nodes",
"[",
"0",
"]",
"->",
"compile",
"(",
"$",
"buffer",
")",
";",
"$",
"buffer",
"->",
"write",
"(",
"');'",
")",
";",
"}"
] | Allows the annotation to modify the buffer before the script is compiled.
@param Buffer $buffer
@return void | [
"Allows",
"the",
"annotation",
"to",
"modify",
"the",
"buffer",
"before",
"the",
"script",
"is",
"compiled",
"."
] | train | https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Script/Node/Script/With.php#L39-L44 |
SporkCode/Spork | src/View/Helper/HeadScript.php | HeadScript.toString | public function toString($indent = null)
{
$helperManager = $this->getView()->getHelperPluginManager();
if ($helperManager->has('dojo')) {
$dojo = $helperManager->get('dojo');
$dojo->initialize();
}
return parent::toString($indent);
} | php | public function toString($indent = null)
{
$helperManager = $this->getView()->getHelperPluginManager();
if ($helperManager->has('dojo')) {
$dojo = $helperManager->get('dojo');
$dojo->initialize();
}
return parent::toString($indent);
} | [
"public",
"function",
"toString",
"(",
"$",
"indent",
"=",
"null",
")",
"{",
"$",
"helperManager",
"=",
"$",
"this",
"->",
"getView",
"(",
")",
"->",
"getHelperPluginManager",
"(",
")",
";",
"if",
"(",
"$",
"helperManager",
"->",
"has",
"(",
"'dojo'",
")",
")",
"{",
"$",
"dojo",
"=",
"$",
"helperManager",
"->",
"get",
"(",
"'dojo'",
")",
";",
"$",
"dojo",
"->",
"initialize",
"(",
")",
";",
"}",
"return",
"parent",
"::",
"toString",
"(",
"$",
"indent",
")",
";",
"}"
] | Find an initialize Dojo helper before rendering head scripts
@see \Zend\View\Helper\HeadScript::toString()
@param string $indent
@return string | [
"Find",
"an",
"initialize",
"Dojo",
"helper",
"before",
"rendering",
"head",
"scripts"
] | train | https://github.com/SporkCode/Spork/blob/7f569efdc0ceb4a9c1c7a8b648b6a7ed50d2088a/src/View/Helper/HeadScript.php#L22-L30 |
oroinc/OroLayoutComponent | Config/Loader/LayoutUpdateCumulativeResourceLoader.php | LayoutUpdateCumulativeResourceLoader.isResourceFresh | public function isResourceFresh($bundleClass, $bundleDir, $bundleAppDir, CumulativeResource $resource, $timestamp)
{
$registeredFiles = $resource->getFound($bundleClass);
$registeredFiles = array_flip($registeredFiles);
// Check and remove data from $bundleAppDir resources directory
if (is_dir($bundleAppDir)) {
$dir = $this->getResourcesDirectoryAbsolutePath($bundleAppDir);
$realPath = realpath($dir);
if (is_dir($realPath)) {
$currentContents = $this->getDirectoryContentsArray($realPath);
foreach ($currentContents as $filename) {
if (!$this->isFoundAndFresh($resource, $bundleClass, $filename, $timestamp)) {
return false;
}
unset($registeredFiles[$filename]);
}
}
}
// Check and remove data from $bundleDir resources directory
$dir = $this->getDirectoryAbsolutePath($bundleDir);
$realPath = realpath($dir);
if (is_dir($realPath)) {
$currentContents = $this->getDirectoryContentsArray($realPath);
foreach ($currentContents as $filename) {
if (!$this->isFoundAndFresh($resource, $bundleClass, $filename, $timestamp)) {
return false;
}
unset($registeredFiles[$filename]);
}
}
// case when entire dir was removed or some file was removed
if (!empty($registeredFiles)) {
return false;
}
return true;
} | php | public function isResourceFresh($bundleClass, $bundleDir, $bundleAppDir, CumulativeResource $resource, $timestamp)
{
$registeredFiles = $resource->getFound($bundleClass);
$registeredFiles = array_flip($registeredFiles);
// Check and remove data from $bundleAppDir resources directory
if (is_dir($bundleAppDir)) {
$dir = $this->getResourcesDirectoryAbsolutePath($bundleAppDir);
$realPath = realpath($dir);
if (is_dir($realPath)) {
$currentContents = $this->getDirectoryContentsArray($realPath);
foreach ($currentContents as $filename) {
if (!$this->isFoundAndFresh($resource, $bundleClass, $filename, $timestamp)) {
return false;
}
unset($registeredFiles[$filename]);
}
}
}
// Check and remove data from $bundleDir resources directory
$dir = $this->getDirectoryAbsolutePath($bundleDir);
$realPath = realpath($dir);
if (is_dir($realPath)) {
$currentContents = $this->getDirectoryContentsArray($realPath);
foreach ($currentContents as $filename) {
if (!$this->isFoundAndFresh($resource, $bundleClass, $filename, $timestamp)) {
return false;
}
unset($registeredFiles[$filename]);
}
}
// case when entire dir was removed or some file was removed
if (!empty($registeredFiles)) {
return false;
}
return true;
} | [
"public",
"function",
"isResourceFresh",
"(",
"$",
"bundleClass",
",",
"$",
"bundleDir",
",",
"$",
"bundleAppDir",
",",
"CumulativeResource",
"$",
"resource",
",",
"$",
"timestamp",
")",
"{",
"$",
"registeredFiles",
"=",
"$",
"resource",
"->",
"getFound",
"(",
"$",
"bundleClass",
")",
";",
"$",
"registeredFiles",
"=",
"array_flip",
"(",
"$",
"registeredFiles",
")",
";",
"// Check and remove data from $bundleAppDir resources directory",
"if",
"(",
"is_dir",
"(",
"$",
"bundleAppDir",
")",
")",
"{",
"$",
"dir",
"=",
"$",
"this",
"->",
"getResourcesDirectoryAbsolutePath",
"(",
"$",
"bundleAppDir",
")",
";",
"$",
"realPath",
"=",
"realpath",
"(",
"$",
"dir",
")",
";",
"if",
"(",
"is_dir",
"(",
"$",
"realPath",
")",
")",
"{",
"$",
"currentContents",
"=",
"$",
"this",
"->",
"getDirectoryContentsArray",
"(",
"$",
"realPath",
")",
";",
"foreach",
"(",
"$",
"currentContents",
"as",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isFoundAndFresh",
"(",
"$",
"resource",
",",
"$",
"bundleClass",
",",
"$",
"filename",
",",
"$",
"timestamp",
")",
")",
"{",
"return",
"false",
";",
"}",
"unset",
"(",
"$",
"registeredFiles",
"[",
"$",
"filename",
"]",
")",
";",
"}",
"}",
"}",
"// Check and remove data from $bundleDir resources directory",
"$",
"dir",
"=",
"$",
"this",
"->",
"getDirectoryAbsolutePath",
"(",
"$",
"bundleDir",
")",
";",
"$",
"realPath",
"=",
"realpath",
"(",
"$",
"dir",
")",
";",
"if",
"(",
"is_dir",
"(",
"$",
"realPath",
")",
")",
"{",
"$",
"currentContents",
"=",
"$",
"this",
"->",
"getDirectoryContentsArray",
"(",
"$",
"realPath",
")",
";",
"foreach",
"(",
"$",
"currentContents",
"as",
"$",
"filename",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isFoundAndFresh",
"(",
"$",
"resource",
",",
"$",
"bundleClass",
",",
"$",
"filename",
",",
"$",
"timestamp",
")",
")",
"{",
"return",
"false",
";",
"}",
"unset",
"(",
"$",
"registeredFiles",
"[",
"$",
"filename",
"]",
")",
";",
"}",
"}",
"// case when entire dir was removed or some file was removed",
"if",
"(",
"!",
"empty",
"(",
"$",
"registeredFiles",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Config/Loader/LayoutUpdateCumulativeResourceLoader.php#L13-L56 |
oroinc/OroLayoutComponent | Config/Loader/LayoutUpdateCumulativeResourceLoader.php | LayoutUpdateCumulativeResourceLoader.isFoundAndFresh | private function isFoundAndFresh(CumulativeResource $resource, $bundleClass, $filename, $timestamp)
{
return $resource->isFound($bundleClass, $filename) && is_file($filename) && filemtime($filename) < $timestamp;
} | php | private function isFoundAndFresh(CumulativeResource $resource, $bundleClass, $filename, $timestamp)
{
return $resource->isFound($bundleClass, $filename) && is_file($filename) && filemtime($filename) < $timestamp;
} | [
"private",
"function",
"isFoundAndFresh",
"(",
"CumulativeResource",
"$",
"resource",
",",
"$",
"bundleClass",
",",
"$",
"filename",
",",
"$",
"timestamp",
")",
"{",
"return",
"$",
"resource",
"->",
"isFound",
"(",
"$",
"bundleClass",
",",
"$",
"filename",
")",
"&&",
"is_file",
"(",
"$",
"filename",
")",
"&&",
"filemtime",
"(",
"$",
"filename",
")",
"<",
"$",
"timestamp",
";",
"}"
] | @param CumulativeResource $resource
@param string $bundleClass
@param string $filename
@param int $timestamp
@return boolean | [
"@param",
"CumulativeResource",
"$resource",
"@param",
"string",
"$bundleClass",
"@param",
"string",
"$filename",
"@param",
"int",
"$timestamp"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Config/Loader/LayoutUpdateCumulativeResourceLoader.php#L66-L69 |
inhere/php-librarys | src/Helpers/ObjectHelper.php | ObjectHelper.init | public static function init($object, array $options)
{
foreach ($options as $property => $value) {
if (is_numeric($property)) {
continue;
}
$setter = 'set' . ucfirst($property);
// has setter
if (method_exists($object, $setter)) {
$object->$setter($value);
} else {
$object->$property = $value;
}
}
return $object;
} | php | public static function init($object, array $options)
{
foreach ($options as $property => $value) {
if (is_numeric($property)) {
continue;
}
$setter = 'set' . ucfirst($property);
// has setter
if (method_exists($object, $setter)) {
$object->$setter($value);
} else {
$object->$property = $value;
}
}
return $object;
} | [
"public",
"static",
"function",
"init",
"(",
"$",
"object",
",",
"array",
"$",
"options",
")",
"{",
"foreach",
"(",
"$",
"options",
"as",
"$",
"property",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"property",
")",
")",
"{",
"continue",
";",
"}",
"$",
"setter",
"=",
"'set'",
".",
"ucfirst",
"(",
"$",
"property",
")",
";",
"// has setter",
"if",
"(",
"method_exists",
"(",
"$",
"object",
",",
"$",
"setter",
")",
")",
"{",
"$",
"object",
"->",
"$",
"setter",
"(",
"$",
"value",
")",
";",
"}",
"else",
"{",
"$",
"object",
"->",
"$",
"property",
"=",
"$",
"value",
";",
"}",
"}",
"return",
"$",
"object",
";",
"}"
] | 给对象设置属性值
- 会先尝试用 setter 方法设置属性
- 再尝试直接设置属性
@param mixed $object An object instance
@param array $options
@return mixed | [
"给对象设置属性值",
"-",
"会先尝试用",
"setter",
"方法设置属性",
"-",
"再尝试直接设置属性"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/ObjectHelper.php#L38-L56 |
inhere/php-librarys | src/Helpers/ObjectHelper.php | ObjectHelper.configure | public static function configure($object, array $options)
{
foreach ($options as $property => $value) {
$object->$property = $value;
}
} | php | public static function configure($object, array $options)
{
foreach ($options as $property => $value) {
$object->$property = $value;
}
} | [
"public",
"static",
"function",
"configure",
"(",
"$",
"object",
",",
"array",
"$",
"options",
")",
"{",
"foreach",
"(",
"$",
"options",
"as",
"$",
"property",
"=>",
"$",
"value",
")",
"{",
"$",
"object",
"->",
"$",
"property",
"=",
"$",
"value",
";",
"}",
"}"
] | 给对象设置属性值
@param $object
@param array $options | [
"给对象设置属性值"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/ObjectHelper.php#L63-L68 |
inhere/php-librarys | src/Helpers/ObjectHelper.php | ObjectHelper.create | public static function create($class)
{
try {
$reflection = new \ReflectionClass($class);
} catch (\ReflectionException $e) {
return false;
}
$constructor = $reflection->getConstructor();
// If there are no parameters, just return a new object.
if (null === $constructor) {
return new $class;
}
$newInstanceArgs = self::getMethodArgs($constructor);
// Create a callable for the dataStorage
return $reflection->newInstanceArgs($newInstanceArgs);
} | php | public static function create($class)
{
try {
$reflection = new \ReflectionClass($class);
} catch (\ReflectionException $e) {
return false;
}
$constructor = $reflection->getConstructor();
// If there are no parameters, just return a new object.
if (null === $constructor) {
return new $class;
}
$newInstanceArgs = self::getMethodArgs($constructor);
// Create a callable for the dataStorage
return $reflection->newInstanceArgs($newInstanceArgs);
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"class",
")",
"{",
"try",
"{",
"$",
"reflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"class",
")",
";",
"}",
"catch",
"(",
"\\",
"ReflectionException",
"$",
"e",
")",
"{",
"return",
"false",
";",
"}",
"$",
"constructor",
"=",
"$",
"reflection",
"->",
"getConstructor",
"(",
")",
";",
"// If there are no parameters, just return a new object.",
"if",
"(",
"null",
"===",
"$",
"constructor",
")",
"{",
"return",
"new",
"$",
"class",
";",
"}",
"$",
"newInstanceArgs",
"=",
"self",
"::",
"getMethodArgs",
"(",
"$",
"constructor",
")",
";",
"// Create a callable for the dataStorage",
"return",
"$",
"reflection",
"->",
"newInstanceArgs",
"(",
"$",
"newInstanceArgs",
")",
";",
"}"
] | 从类名创建服务实例对象,会尽可能自动补完构造函数依赖
@from windWalker https://github.com/ventoviro/windwalker
@param string $class a className
@throws DependencyResolutionException
@return mixed | [
"从类名创建服务实例对象,会尽可能自动补完构造函数依赖"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/ObjectHelper.php#L188-L207 |
heidelpay/PhpDoc | src/phpDocumentor/Translator/Translator.php | Translator.addTranslations | public function addTranslations($filename, $locale = self::DEFAULT_LOCALE, $textDomain = self::DEFAULT_DOMAIN)
{
parent::addTranslationFile(self::TRANSLATION_FILE_TYPE, $filename, $textDomain, $locale);
$this->messages = array();
return $this;
} | php | public function addTranslations($filename, $locale = self::DEFAULT_LOCALE, $textDomain = self::DEFAULT_DOMAIN)
{
parent::addTranslationFile(self::TRANSLATION_FILE_TYPE, $filename, $textDomain, $locale);
$this->messages = array();
return $this;
} | [
"public",
"function",
"addTranslations",
"(",
"$",
"filename",
",",
"$",
"locale",
"=",
"self",
"::",
"DEFAULT_LOCALE",
",",
"$",
"textDomain",
"=",
"self",
"::",
"DEFAULT_DOMAIN",
")",
"{",
"parent",
"::",
"addTranslationFile",
"(",
"self",
"::",
"TRANSLATION_FILE_TYPE",
",",
"$",
"filename",
",",
"$",
"textDomain",
",",
"$",
"locale",
")",
";",
"$",
"this",
"->",
"messages",
"=",
"array",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Adds a translation file for a specific locale, or the default locale when none is provided.
@param string $filename Name of the file to add.
@param string|null $locale The locale to assign to, matches
{@link http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes ISO-639-1} and defaults to en (English).
@param string $textDomain Translations may be divided into separate files / domains; this represents in
which domain the translation should be.
@api
@return $this | [
"Adds",
"a",
"translation",
"file",
"for",
"a",
"specific",
"locale",
"or",
"the",
"default",
"locale",
"when",
"none",
"is",
"provided",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Translator/Translator.php#L103-L110 |
heidelpay/PhpDoc | src/phpDocumentor/Translator/Translator.php | Translator.addTranslationFolder | public function addTranslationFolder($folder, array $domains = array())
{
if (empty($domains)) {
$domains = array(self::DEFAULT_DOMAIN);
}
foreach ($domains as $domain) {
$this->addTranslationsUsingPattern($folder, $domain);
}
return $this;
} | php | public function addTranslationFolder($folder, array $domains = array())
{
if (empty($domains)) {
$domains = array(self::DEFAULT_DOMAIN);
}
foreach ($domains as $domain) {
$this->addTranslationsUsingPattern($folder, $domain);
}
return $this;
} | [
"public",
"function",
"addTranslationFolder",
"(",
"$",
"folder",
",",
"array",
"$",
"domains",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"domains",
")",
")",
"{",
"$",
"domains",
"=",
"array",
"(",
"self",
"::",
"DEFAULT_DOMAIN",
")",
";",
"}",
"foreach",
"(",
"$",
"domains",
"as",
"$",
"domain",
")",
"{",
"$",
"this",
"->",
"addTranslationsUsingPattern",
"(",
"$",
"folder",
",",
"$",
"domain",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Adds a folder with files containing translation sources.
This method scans the provided folder for any file matching the following format:
`[domain].[locale].php`
If the domain matches the {@see self::DEFAULT_DOMAIN default domain} then that part is omitted and the filename
should match:
`[locale].php`
@link http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes for a list of ISO-639-1 locale codes as used by
this method.
@param string $folder Name of the folder, it is recommended to use an absolute path.
@param string[] $domains One or more domains to load, when none is provided only the default is added.
@api
@return $this | [
"Adds",
"a",
"folder",
"with",
"files",
"containing",
"translation",
"sources",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Translator/Translator.php#L134-L145 |
heidelpay/PhpDoc | src/phpDocumentor/Translator/Translator.php | Translator.addTranslationsUsingPattern | public function addTranslationsUsingPattern(
$baseDir,
$textDomain = self::DEFAULT_DOMAIN,
$pattern = self::DEFAULT_PATTERN
) {
if ($textDomain !== self::DEFAULT_DOMAIN && $pattern === self::DEFAULT_PATTERN) {
$pattern = $textDomain . '.' . $pattern;
}
parent::addTranslationFilePattern(self::TRANSLATION_FILE_TYPE, $baseDir, $pattern, $textDomain);
$this->messages = array();
return $this;
} | php | public function addTranslationsUsingPattern(
$baseDir,
$textDomain = self::DEFAULT_DOMAIN,
$pattern = self::DEFAULT_PATTERN
) {
if ($textDomain !== self::DEFAULT_DOMAIN && $pattern === self::DEFAULT_PATTERN) {
$pattern = $textDomain . '.' . $pattern;
}
parent::addTranslationFilePattern(self::TRANSLATION_FILE_TYPE, $baseDir, $pattern, $textDomain);
$this->messages = array();
return $this;
} | [
"public",
"function",
"addTranslationsUsingPattern",
"(",
"$",
"baseDir",
",",
"$",
"textDomain",
"=",
"self",
"::",
"DEFAULT_DOMAIN",
",",
"$",
"pattern",
"=",
"self",
"::",
"DEFAULT_PATTERN",
")",
"{",
"if",
"(",
"$",
"textDomain",
"!==",
"self",
"::",
"DEFAULT_DOMAIN",
"&&",
"$",
"pattern",
"===",
"self",
"::",
"DEFAULT_PATTERN",
")",
"{",
"$",
"pattern",
"=",
"$",
"textDomain",
".",
"'.'",
".",
"$",
"pattern",
";",
"}",
"parent",
"::",
"addTranslationFilePattern",
"(",
"self",
"::",
"TRANSLATION_FILE_TYPE",
",",
"$",
"baseDir",
",",
"$",
"pattern",
",",
"$",
"textDomain",
")",
";",
"$",
"this",
"->",
"messages",
"=",
"array",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Adds a series of translation files given a pattern.
This method will search the base directory for a series of files matching the given pattern (where %s is replaces
by the two-letter locale shorthand) and adds any translations to the translation table.
@param string $baseDir Directory to search in (not-recursive)
@param string $textDomain The domain to assign the translation messages to.
@param string $pattern The pattern used to load files for all languages, one variable `%s` is supported and
is replaced with the {@link http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes ISO-639-1 code} for each
locale that is requested by the translate method.
@internal this method is not to be used by consumers; it is an extension of the Zend Translator component
and is overridden to clear the messages caching array so it may be rebuild.
@see self::addTranslationFolder() to provide a series of translation files.
@return $this|ZendTranslator | [
"Adds",
"a",
"series",
"of",
"translation",
"files",
"given",
"a",
"pattern",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Translator/Translator.php#L166-L180 |
heidelpay/PhpDoc | src/phpDocumentor/Translator/Translator.php | Translator.translate | public function translate($message, $textDomain = self::DEFAULT_DOMAIN, $locale = null)
{
return parent::translate($message, $textDomain, $locale);
} | php | public function translate($message, $textDomain = self::DEFAULT_DOMAIN, $locale = null)
{
return parent::translate($message, $textDomain, $locale);
} | [
"public",
"function",
"translate",
"(",
"$",
"message",
",",
"$",
"textDomain",
"=",
"self",
"::",
"DEFAULT_DOMAIN",
",",
"$",
"locale",
"=",
"null",
")",
"{",
"return",
"parent",
"::",
"translate",
"(",
"$",
"message",
",",
"$",
"textDomain",
",",
"$",
"locale",
")",
";",
"}"
] | Attempts to translate the given message or code into the provided locale.
@param string $message The message or code to translate.
@param string $textDomain A message may be located in a domain, here you can provide in which.
@param null $locale The locale to translate to or the default if not set.
@return string | [
"Attempts",
"to",
"translate",
"the",
"given",
"message",
"or",
"code",
"into",
"the",
"provided",
"locale",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Translator/Translator.php#L191-L194 |
phpnfe/tools | src/Soap/NatSoap.php | NatSoap.send | public function send(
$siglaUF = '',
$namespace = '',
$cabecalho = '',
$dados = '',
$metodo = '',
$tpAmb = '2'
) {
try {
if (! class_exists('SoapClient')) {
$msg = 'A classe SOAP não está disponível no PHP, veja a configuração.';
throw new Exception($msg);
}
$soapFault = '';
//ativa retorno de erros soap
use_soap_error_handler(true);
//versão do SOAP
$soapver = SOAP_1_2;
if ($tpAmb == 1) {
$ambiente = 'producao';
} else {
$ambiente = 'homologacao';
}
$usef = "_$metodo.asmx";
$urlsefaz = "$this->pathWsdl/$ambiente/$siglaUF$usef";
if ($this->enableSVAN) {
//se for SVAN montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVAN$usef";
}
if ($this->enableSCAN) {
//se for SCAN montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SCAN$usef";
}
if ($this->enableSVRS) {
//se for SVRS montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVRS$usef";
}
if ($this->enableSVCAN) {
//se for SVCAN montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVCAN$usef";
}
if ($this->enableSVCRS) {
//se for SVCRS montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVCRS$usef";
}
if ($this->soapTimeout == 0) {
$tout = 999999;
} else {
$tout = $this->soapTimeout;
}
//completa a url do serviço para baixar o arquivo WSDL
$sefazURL = $urlsefaz . '?WSDL';
$this->soapDebug = $urlsefaz;
$options = [
'encoding' => 'UTF-8',
'verifypeer' => false,
'verifyhost' => true,
'soap_version' => $soapver,
'style' => SOAP_DOCUMENT,
'use' => SOAP_LITERAL,
'local_cert' => $this->certKEY,
'trace' => true,
'compression' => 0,
'exceptions' => true,
'connection_timeout' => $tout,
'cache_wsdl' => WSDL_CACHE_NONE,
];
//instancia a classe soap
$oSoapClient = new CorrectedSoapClient($sefazURL, $options);
//monta o cabeçalho da mensagem
$varCabec = new \SoapVar($cabecalho, XSD_ANYXML);
$header = new \SoapHeader($namespace, 'nfeCabecMsg', $varCabec);
//instancia o cabeçalho
$oSoapClient->__setSoapHeaders($header);
//monta o corpo da mensagem soap
$varBody = new \SoapVar($dados, XSD_ANYXML);
//faz a chamada ao metodo do webservices
$resp = $oSoapClient->__soapCall($metodo, [$varBody]);
if (is_soap_fault($resp)) {
$soapFault = "SOAP Fault: (faultcode: {$resp->faultcode}, faultstring: {$resp->faultstring})";
}
$resposta = $oSoapClient->__getLastResponse();
$this->soapDebug .= "\n" . $soapFault;
$this->soapDebug .= "\n" . $oSoapClient->__getLastRequestHeaders();
$this->soapDebug .= "\n" . $oSoapClient->__getLastRequest();
$this->soapDebug .= "\n" . $oSoapClient->__getLastResponseHeaders();
$this->soapDebug .= "\n" . $oSoapClient->__getLastResponse();
} catch (Exception $e) {
$this->aError[] = $e->getMessage();
return false;
}
return $resposta;
} | php | public function send(
$siglaUF = '',
$namespace = '',
$cabecalho = '',
$dados = '',
$metodo = '',
$tpAmb = '2'
) {
try {
if (! class_exists('SoapClient')) {
$msg = 'A classe SOAP não está disponível no PHP, veja a configuração.';
throw new Exception($msg);
}
$soapFault = '';
//ativa retorno de erros soap
use_soap_error_handler(true);
//versão do SOAP
$soapver = SOAP_1_2;
if ($tpAmb == 1) {
$ambiente = 'producao';
} else {
$ambiente = 'homologacao';
}
$usef = "_$metodo.asmx";
$urlsefaz = "$this->pathWsdl/$ambiente/$siglaUF$usef";
if ($this->enableSVAN) {
//se for SVAN montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVAN$usef";
}
if ($this->enableSCAN) {
//se for SCAN montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SCAN$usef";
}
if ($this->enableSVRS) {
//se for SVRS montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVRS$usef";
}
if ($this->enableSVCAN) {
//se for SVCAN montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVCAN$usef";
}
if ($this->enableSVCRS) {
//se for SVCRS montar o URL baseado no metodo e ambiente
$urlsefaz = "$this->pathWsdl/$ambiente/SVCRS$usef";
}
if ($this->soapTimeout == 0) {
$tout = 999999;
} else {
$tout = $this->soapTimeout;
}
//completa a url do serviço para baixar o arquivo WSDL
$sefazURL = $urlsefaz . '?WSDL';
$this->soapDebug = $urlsefaz;
$options = [
'encoding' => 'UTF-8',
'verifypeer' => false,
'verifyhost' => true,
'soap_version' => $soapver,
'style' => SOAP_DOCUMENT,
'use' => SOAP_LITERAL,
'local_cert' => $this->certKEY,
'trace' => true,
'compression' => 0,
'exceptions' => true,
'connection_timeout' => $tout,
'cache_wsdl' => WSDL_CACHE_NONE,
];
//instancia a classe soap
$oSoapClient = new CorrectedSoapClient($sefazURL, $options);
//monta o cabeçalho da mensagem
$varCabec = new \SoapVar($cabecalho, XSD_ANYXML);
$header = new \SoapHeader($namespace, 'nfeCabecMsg', $varCabec);
//instancia o cabeçalho
$oSoapClient->__setSoapHeaders($header);
//monta o corpo da mensagem soap
$varBody = new \SoapVar($dados, XSD_ANYXML);
//faz a chamada ao metodo do webservices
$resp = $oSoapClient->__soapCall($metodo, [$varBody]);
if (is_soap_fault($resp)) {
$soapFault = "SOAP Fault: (faultcode: {$resp->faultcode}, faultstring: {$resp->faultstring})";
}
$resposta = $oSoapClient->__getLastResponse();
$this->soapDebug .= "\n" . $soapFault;
$this->soapDebug .= "\n" . $oSoapClient->__getLastRequestHeaders();
$this->soapDebug .= "\n" . $oSoapClient->__getLastRequest();
$this->soapDebug .= "\n" . $oSoapClient->__getLastResponseHeaders();
$this->soapDebug .= "\n" . $oSoapClient->__getLastResponse();
} catch (Exception $e) {
$this->aError[] = $e->getMessage();
return false;
}
return $resposta;
} | [
"public",
"function",
"send",
"(",
"$",
"siglaUF",
"=",
"''",
",",
"$",
"namespace",
"=",
"''",
",",
"$",
"cabecalho",
"=",
"''",
",",
"$",
"dados",
"=",
"''",
",",
"$",
"metodo",
"=",
"''",
",",
"$",
"tpAmb",
"=",
"'2'",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"'SoapClient'",
")",
")",
"{",
"$",
"msg",
"=",
"'A classe SOAP não está disponível no PHP, veja a configuração.';",
"",
"throw",
"new",
"Exception",
"(",
"$",
"msg",
")",
";",
"}",
"$",
"soapFault",
"=",
"''",
";",
"//ativa retorno de erros soap",
"use_soap_error_handler",
"(",
"true",
")",
";",
"//versão do SOAP",
"$",
"soapver",
"=",
"SOAP_1_2",
";",
"if",
"(",
"$",
"tpAmb",
"==",
"1",
")",
"{",
"$",
"ambiente",
"=",
"'producao'",
";",
"}",
"else",
"{",
"$",
"ambiente",
"=",
"'homologacao'",
";",
"}",
"$",
"usef",
"=",
"\"_$metodo.asmx\"",
";",
"$",
"urlsefaz",
"=",
"\"$this->pathWsdl/$ambiente/$siglaUF$usef\"",
";",
"if",
"(",
"$",
"this",
"->",
"enableSVAN",
")",
"{",
"//se for SVAN montar o URL baseado no metodo e ambiente",
"$",
"urlsefaz",
"=",
"\"$this->pathWsdl/$ambiente/SVAN$usef\"",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"enableSCAN",
")",
"{",
"//se for SCAN montar o URL baseado no metodo e ambiente",
"$",
"urlsefaz",
"=",
"\"$this->pathWsdl/$ambiente/SCAN$usef\"",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"enableSVRS",
")",
"{",
"//se for SVRS montar o URL baseado no metodo e ambiente",
"$",
"urlsefaz",
"=",
"\"$this->pathWsdl/$ambiente/SVRS$usef\"",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"enableSVCAN",
")",
"{",
"//se for SVCAN montar o URL baseado no metodo e ambiente",
"$",
"urlsefaz",
"=",
"\"$this->pathWsdl/$ambiente/SVCAN$usef\"",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"enableSVCRS",
")",
"{",
"//se for SVCRS montar o URL baseado no metodo e ambiente",
"$",
"urlsefaz",
"=",
"\"$this->pathWsdl/$ambiente/SVCRS$usef\"",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"soapTimeout",
"==",
"0",
")",
"{",
"$",
"tout",
"=",
"999999",
";",
"}",
"else",
"{",
"$",
"tout",
"=",
"$",
"this",
"->",
"soapTimeout",
";",
"}",
"//completa a url do serviço para baixar o arquivo WSDL",
"$",
"sefazURL",
"=",
"$",
"urlsefaz",
".",
"'?WSDL'",
";",
"$",
"this",
"->",
"soapDebug",
"=",
"$",
"urlsefaz",
";",
"$",
"options",
"=",
"[",
"'encoding'",
"=>",
"'UTF-8'",
",",
"'verifypeer'",
"=>",
"false",
",",
"'verifyhost'",
"=>",
"true",
",",
"'soap_version'",
"=>",
"$",
"soapver",
",",
"'style'",
"=>",
"SOAP_DOCUMENT",
",",
"'use'",
"=>",
"SOAP_LITERAL",
",",
"'local_cert'",
"=>",
"$",
"this",
"->",
"certKEY",
",",
"'trace'",
"=>",
"true",
",",
"'compression'",
"=>",
"0",
",",
"'exceptions'",
"=>",
"true",
",",
"'connection_timeout'",
"=>",
"$",
"tout",
",",
"'cache_wsdl'",
"=>",
"WSDL_CACHE_NONE",
",",
"]",
";",
"//instancia a classe soap",
"$",
"oSoapClient",
"=",
"new",
"CorrectedSoapClient",
"(",
"$",
"sefazURL",
",",
"$",
"options",
")",
";",
"//monta o cabeçalho da mensagem",
"$",
"varCabec",
"=",
"new",
"\\",
"SoapVar",
"(",
"$",
"cabecalho",
",",
"XSD_ANYXML",
")",
";",
"$",
"header",
"=",
"new",
"\\",
"SoapHeader",
"(",
"$",
"namespace",
",",
"'nfeCabecMsg'",
",",
"$",
"varCabec",
")",
";",
"//instancia o cabeçalho",
"$",
"oSoapClient",
"->",
"__setSoapHeaders",
"(",
"$",
"header",
")",
";",
"//monta o corpo da mensagem soap",
"$",
"varBody",
"=",
"new",
"\\",
"SoapVar",
"(",
"$",
"dados",
",",
"XSD_ANYXML",
")",
";",
"//faz a chamada ao metodo do webservices",
"$",
"resp",
"=",
"$",
"oSoapClient",
"->",
"__soapCall",
"(",
"$",
"metodo",
",",
"[",
"$",
"varBody",
"]",
")",
";",
"if",
"(",
"is_soap_fault",
"(",
"$",
"resp",
")",
")",
"{",
"$",
"soapFault",
"=",
"\"SOAP Fault: (faultcode: {$resp->faultcode}, faultstring: {$resp->faultstring})\"",
";",
"}",
"$",
"resposta",
"=",
"$",
"oSoapClient",
"->",
"__getLastResponse",
"(",
")",
";",
"$",
"this",
"->",
"soapDebug",
".=",
"\"\\n\"",
".",
"$",
"soapFault",
";",
"$",
"this",
"->",
"soapDebug",
".=",
"\"\\n\"",
".",
"$",
"oSoapClient",
"->",
"__getLastRequestHeaders",
"(",
")",
";",
"$",
"this",
"->",
"soapDebug",
".=",
"\"\\n\"",
".",
"$",
"oSoapClient",
"->",
"__getLastRequest",
"(",
")",
";",
"$",
"this",
"->",
"soapDebug",
".=",
"\"\\n\"",
".",
"$",
"oSoapClient",
"->",
"__getLastResponseHeaders",
"(",
")",
";",
"$",
"this",
"->",
"soapDebug",
".=",
"\"\\n\"",
".",
"$",
"oSoapClient",
"->",
"__getLastResponse",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"aError",
"[",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"return",
"false",
";",
"}",
"return",
"$",
"resposta",
";",
"}"
] | Estabelece comunicaçao com servidor SOAP 1.1 ou 1.2 da SEFAZ,
usando as chaves publica e privada parametrizadas na contrução da classe.
Conforme Manual de Integração Versão 4.0.1.
@param string $urlsefaz
@param string $namespace
@param string $cabecalho
@param string $dados
@param string $metodo
@param int $ambiente tipo de ambiente 1 - produção e 2 - homologação
@param string $UF unidade da federação, necessário para diferenciar AM, MT e PR
@return mixed false se houve falha ou o retorno em xml do SEFAZ | [
"Estabelece",
"comunicaçao",
"com",
"servidor",
"SOAP",
"1",
".",
"1",
"ou",
"1",
".",
"2",
"da",
"SEFAZ",
"usando",
"as",
"chaves",
"publica",
"e",
"privada",
"parametrizadas",
"na",
"contrução",
"da",
"classe",
".",
"Conforme",
"Manual",
"de",
"Integração",
"Versão",
"4",
".",
"0",
".",
"1",
"."
] | train | https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Soap/NatSoap.php#L91-L185 |
j-d/draggy | src/Draggy/Autocode/File.php | File.saveFile | public function saveFile ($path, $name, $contents)
{
$targetFile = $path . $name;
$folder = pathinfo($targetFile, PATHINFO_DIRNAME);
if(!is_dir($folder)) {
echo $folder . '<br>';
mkdir($folder, 0777, true);
}
if (!file_exists($targetFile)) {
file_put_contents($targetFile, $contents);
$this->log->append(sprintf('Saved \'%s\' to \'%s\'', $name, $path));
} elseif ($this->getOverwrite()) {
$existingFile = file_get_contents($targetFile);
$newFile = $this->keepUserAdditions($contents, $existingFile, $path, $name);
file_put_contents($targetFile, $newFile);
$this->log->appendExtended(sprintf('\'%s\' file existed and modified in \'%s\'', $name, $path));
} else {
$this->log->prepend(sprintf('*** You may need to manually change the \'%s\' file in the \'%s\' folder as the template might have changed since you started using it.', $name, $path));
}
} | php | public function saveFile ($path, $name, $contents)
{
$targetFile = $path . $name;
$folder = pathinfo($targetFile, PATHINFO_DIRNAME);
if(!is_dir($folder)) {
echo $folder . '<br>';
mkdir($folder, 0777, true);
}
if (!file_exists($targetFile)) {
file_put_contents($targetFile, $contents);
$this->log->append(sprintf('Saved \'%s\' to \'%s\'', $name, $path));
} elseif ($this->getOverwrite()) {
$existingFile = file_get_contents($targetFile);
$newFile = $this->keepUserAdditions($contents, $existingFile, $path, $name);
file_put_contents($targetFile, $newFile);
$this->log->appendExtended(sprintf('\'%s\' file existed and modified in \'%s\'', $name, $path));
} else {
$this->log->prepend(sprintf('*** You may need to manually change the \'%s\' file in the \'%s\' folder as the template might have changed since you started using it.', $name, $path));
}
} | [
"public",
"function",
"saveFile",
"(",
"$",
"path",
",",
"$",
"name",
",",
"$",
"contents",
")",
"{",
"$",
"targetFile",
"=",
"$",
"path",
".",
"$",
"name",
";",
"$",
"folder",
"=",
"pathinfo",
"(",
"$",
"targetFile",
",",
"PATHINFO_DIRNAME",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"folder",
")",
")",
"{",
"echo",
"$",
"folder",
".",
"'<br>'",
";",
"mkdir",
"(",
"$",
"folder",
",",
"0777",
",",
"true",
")",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"targetFile",
")",
")",
"{",
"file_put_contents",
"(",
"$",
"targetFile",
",",
"$",
"contents",
")",
";",
"$",
"this",
"->",
"log",
"->",
"append",
"(",
"sprintf",
"(",
"'Saved \\'%s\\' to \\'%s\\''",
",",
"$",
"name",
",",
"$",
"path",
")",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"getOverwrite",
"(",
")",
")",
"{",
"$",
"existingFile",
"=",
"file_get_contents",
"(",
"$",
"targetFile",
")",
";",
"$",
"newFile",
"=",
"$",
"this",
"->",
"keepUserAdditions",
"(",
"$",
"contents",
",",
"$",
"existingFile",
",",
"$",
"path",
",",
"$",
"name",
")",
";",
"file_put_contents",
"(",
"$",
"targetFile",
",",
"$",
"newFile",
")",
";",
"$",
"this",
"->",
"log",
"->",
"appendExtended",
"(",
"sprintf",
"(",
"'\\'%s\\' file existed and modified in \\'%s\\''",
",",
"$",
"name",
",",
"$",
"path",
")",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"log",
"->",
"prepend",
"(",
"sprintf",
"(",
"'*** You may need to manually change the \\'%s\\' file in the \\'%s\\' folder as the template might have changed since you started using it.'",
",",
"$",
"name",
",",
"$",
"path",
")",
")",
";",
"}",
"}"
] | TODO: REMOVE PATH AND NAME | [
"TODO",
":",
"REMOVE",
"PATH",
"AND",
"NAME"
] | train | https://github.com/j-d/draggy/blob/97ffc66e1aacb5f685d7aac5251c4abb8888d4bb/src/Draggy/Autocode/File.php#L81-L105 |
oroinc/OroLayoutComponent | Extension/Theme/Visitor/ImportVisitor.php | ImportVisitor.walkUpdates | public function walkUpdates(array &$updates, ContextInterface $context)
{
$this->updates = &$updates;
foreach ($updates as $group) {
foreach ($group as $update) {
if ($update instanceof ImportsAwareLayoutUpdateInterface) {
$this->loadImportUpdate($update, $context);
}
}
}
} | php | public function walkUpdates(array &$updates, ContextInterface $context)
{
$this->updates = &$updates;
foreach ($updates as $group) {
foreach ($group as $update) {
if ($update instanceof ImportsAwareLayoutUpdateInterface) {
$this->loadImportUpdate($update, $context);
}
}
}
} | [
"public",
"function",
"walkUpdates",
"(",
"array",
"&",
"$",
"updates",
",",
"ContextInterface",
"$",
"context",
")",
"{",
"$",
"this",
"->",
"updates",
"=",
"&",
"$",
"updates",
";",
"foreach",
"(",
"$",
"updates",
"as",
"$",
"group",
")",
"{",
"foreach",
"(",
"$",
"group",
"as",
"$",
"update",
")",
"{",
"if",
"(",
"$",
"update",
"instanceof",
"ImportsAwareLayoutUpdateInterface",
")",
"{",
"$",
"this",
"->",
"loadImportUpdate",
"(",
"$",
"update",
",",
"$",
"context",
")",
";",
"}",
"}",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/Visitor/ImportVisitor.php#L58-L69 |
oroinc/OroLayoutComponent | Extension/Theme/Visitor/ImportVisitor.php | ImportVisitor.loadImportUpdate | private function loadImportUpdate($parentUpdate, ContextInterface $context)
{
if ($parentUpdate instanceof IsApplicableLayoutUpdateInterface && !$parentUpdate->isApplicable($context)) {
return;
}
$imports = $parentUpdate->getImports();
if (!is_array($imports)) {
throw new LogicException(
sprintf('Imports statement should be an array, %s given', gettype($imports))
);
}
$importsReversed = array_reverse($imports);
foreach ($importsReversed as $importData) {
$import = $this->createImport($importData);
if ($parentUpdate instanceof LayoutUpdateImportInterface) {
$import->setParent($parentUpdate->getImport());
}
$files = $this->getImportResources($context->get(ThemeExtension::THEME_KEY), $import->getId());
foreach ($files as $file) {
$update = $this->loader->load($file);
if ($update instanceof LayoutUpdateImportInterface) {
$update->setImport($import);
$update->setParentUpdate($parentUpdate);
}
$this->insertUpdate($parentUpdate, $update);
$this->dependencyInitializer->initialize($update);
if ($update instanceof ImportsAwareLayoutUpdateInterface) {
$this->loadImportUpdate($update, $context);
}
}
}
} | php | private function loadImportUpdate($parentUpdate, ContextInterface $context)
{
if ($parentUpdate instanceof IsApplicableLayoutUpdateInterface && !$parentUpdate->isApplicable($context)) {
return;
}
$imports = $parentUpdate->getImports();
if (!is_array($imports)) {
throw new LogicException(
sprintf('Imports statement should be an array, %s given', gettype($imports))
);
}
$importsReversed = array_reverse($imports);
foreach ($importsReversed as $importData) {
$import = $this->createImport($importData);
if ($parentUpdate instanceof LayoutUpdateImportInterface) {
$import->setParent($parentUpdate->getImport());
}
$files = $this->getImportResources($context->get(ThemeExtension::THEME_KEY), $import->getId());
foreach ($files as $file) {
$update = $this->loader->load($file);
if ($update instanceof LayoutUpdateImportInterface) {
$update->setImport($import);
$update->setParentUpdate($parentUpdate);
}
$this->insertUpdate($parentUpdate, $update);
$this->dependencyInitializer->initialize($update);
if ($update instanceof ImportsAwareLayoutUpdateInterface) {
$this->loadImportUpdate($update, $context);
}
}
}
} | [
"private",
"function",
"loadImportUpdate",
"(",
"$",
"parentUpdate",
",",
"ContextInterface",
"$",
"context",
")",
"{",
"if",
"(",
"$",
"parentUpdate",
"instanceof",
"IsApplicableLayoutUpdateInterface",
"&&",
"!",
"$",
"parentUpdate",
"->",
"isApplicable",
"(",
"$",
"context",
")",
")",
"{",
"return",
";",
"}",
"$",
"imports",
"=",
"$",
"parentUpdate",
"->",
"getImports",
"(",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"imports",
")",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"sprintf",
"(",
"'Imports statement should be an array, %s given'",
",",
"gettype",
"(",
"$",
"imports",
")",
")",
")",
";",
"}",
"$",
"importsReversed",
"=",
"array_reverse",
"(",
"$",
"imports",
")",
";",
"foreach",
"(",
"$",
"importsReversed",
"as",
"$",
"importData",
")",
"{",
"$",
"import",
"=",
"$",
"this",
"->",
"createImport",
"(",
"$",
"importData",
")",
";",
"if",
"(",
"$",
"parentUpdate",
"instanceof",
"LayoutUpdateImportInterface",
")",
"{",
"$",
"import",
"->",
"setParent",
"(",
"$",
"parentUpdate",
"->",
"getImport",
"(",
")",
")",
";",
"}",
"$",
"files",
"=",
"$",
"this",
"->",
"getImportResources",
"(",
"$",
"context",
"->",
"get",
"(",
"ThemeExtension",
"::",
"THEME_KEY",
")",
",",
"$",
"import",
"->",
"getId",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"file",
")",
"{",
"$",
"update",
"=",
"$",
"this",
"->",
"loader",
"->",
"load",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"update",
"instanceof",
"LayoutUpdateImportInterface",
")",
"{",
"$",
"update",
"->",
"setImport",
"(",
"$",
"import",
")",
";",
"$",
"update",
"->",
"setParentUpdate",
"(",
"$",
"parentUpdate",
")",
";",
"}",
"$",
"this",
"->",
"insertUpdate",
"(",
"$",
"parentUpdate",
",",
"$",
"update",
")",
";",
"$",
"this",
"->",
"dependencyInitializer",
"->",
"initialize",
"(",
"$",
"update",
")",
";",
"if",
"(",
"$",
"update",
"instanceof",
"ImportsAwareLayoutUpdateInterface",
")",
"{",
"$",
"this",
"->",
"loadImportUpdate",
"(",
"$",
"update",
",",
"$",
"context",
")",
";",
"}",
"}",
"}",
"}"
] | @param ImportsAwareLayoutUpdateInterface $parentUpdate
@param ContextInterface $context
@throws LogicException | [
"@param",
"ImportsAwareLayoutUpdateInterface",
"$parentUpdate",
"@param",
"ContextInterface",
"$context"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/Visitor/ImportVisitor.php#L77-L114 |
oroinc/OroLayoutComponent | Extension/Theme/Visitor/ImportVisitor.php | ImportVisitor.insertUpdate | private function insertUpdate($parentUpdate, $update)
{
$el = $update instanceof ElementDependentLayoutUpdateInterface
? $update->getElement()
: 'root';
$parentUpdateIndex = array_search($parentUpdate, $this->updates[$el]);
$this->updates[$el] = array_merge(
array_slice($this->updates[$el], 0, $parentUpdateIndex, true),
[$update],
array_slice($this->updates[$el], $parentUpdateIndex, null, true)
);
} | php | private function insertUpdate($parentUpdate, $update)
{
$el = $update instanceof ElementDependentLayoutUpdateInterface
? $update->getElement()
: 'root';
$parentUpdateIndex = array_search($parentUpdate, $this->updates[$el]);
$this->updates[$el] = array_merge(
array_slice($this->updates[$el], 0, $parentUpdateIndex, true),
[$update],
array_slice($this->updates[$el], $parentUpdateIndex, null, true)
);
} | [
"private",
"function",
"insertUpdate",
"(",
"$",
"parentUpdate",
",",
"$",
"update",
")",
"{",
"$",
"el",
"=",
"$",
"update",
"instanceof",
"ElementDependentLayoutUpdateInterface",
"?",
"$",
"update",
"->",
"getElement",
"(",
")",
":",
"'root'",
";",
"$",
"parentUpdateIndex",
"=",
"array_search",
"(",
"$",
"parentUpdate",
",",
"$",
"this",
"->",
"updates",
"[",
"$",
"el",
"]",
")",
";",
"$",
"this",
"->",
"updates",
"[",
"$",
"el",
"]",
"=",
"array_merge",
"(",
"array_slice",
"(",
"$",
"this",
"->",
"updates",
"[",
"$",
"el",
"]",
",",
"0",
",",
"$",
"parentUpdateIndex",
",",
"true",
")",
",",
"[",
"$",
"update",
"]",
",",
"array_slice",
"(",
"$",
"this",
"->",
"updates",
"[",
"$",
"el",
"]",
",",
"$",
"parentUpdateIndex",
",",
"null",
",",
"true",
")",
")",
";",
"}"
] | Insert import update right after its parent update
@param ImportsAwareLayoutUpdateInterface $parentUpdate
@param LayoutUpdateImportInterface $update | [
"Insert",
"import",
"update",
"right",
"after",
"its",
"parent",
"update"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/Visitor/ImportVisitor.php#L122-L135 |
oroinc/OroLayoutComponent | Extension/Theme/Visitor/ImportVisitor.php | ImportVisitor.createImport | private function createImport($importProperties)
{
if (!is_array($importProperties)) {
$importProperties = [ImportsAwareLayoutUpdateInterface::ID_KEY => $importProperties];
}
return LayoutUpdateImport::createFromArray($importProperties);
} | php | private function createImport($importProperties)
{
if (!is_array($importProperties)) {
$importProperties = [ImportsAwareLayoutUpdateInterface::ID_KEY => $importProperties];
}
return LayoutUpdateImport::createFromArray($importProperties);
} | [
"private",
"function",
"createImport",
"(",
"$",
"importProperties",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"importProperties",
")",
")",
"{",
"$",
"importProperties",
"=",
"[",
"ImportsAwareLayoutUpdateInterface",
"::",
"ID_KEY",
"=>",
"$",
"importProperties",
"]",
";",
"}",
"return",
"LayoutUpdateImport",
"::",
"createFromArray",
"(",
"$",
"importProperties",
")",
";",
"}"
] | @param string|array $importProperties
@return LayoutUpdateImport | [
"@param",
"string|array",
"$importProperties"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/Visitor/ImportVisitor.php#L142-L149 |
oroinc/OroLayoutComponent | Extension/Theme/Visitor/ImportVisitor.php | ImportVisitor.getImportResources | private function getImportResources($themeName, $importId)
{
$theme = $this->themeManager->getTheme($themeName);
$path = implode(
DIRECTORY_SEPARATOR,
[$theme->getName(), self::IMPORT_FOLDER, $importId]
);
$files = $this->resourceProvider->findApplicableResources([$path]);
if ($theme->getParentTheme()) {
$files = array_merge($this->getImportResources($theme->getParentTheme(), $importId), $files);
}
return $files;
} | php | private function getImportResources($themeName, $importId)
{
$theme = $this->themeManager->getTheme($themeName);
$path = implode(
DIRECTORY_SEPARATOR,
[$theme->getName(), self::IMPORT_FOLDER, $importId]
);
$files = $this->resourceProvider->findApplicableResources([$path]);
if ($theme->getParentTheme()) {
$files = array_merge($this->getImportResources($theme->getParentTheme(), $importId), $files);
}
return $files;
} | [
"private",
"function",
"getImportResources",
"(",
"$",
"themeName",
",",
"$",
"importId",
")",
"{",
"$",
"theme",
"=",
"$",
"this",
"->",
"themeManager",
"->",
"getTheme",
"(",
"$",
"themeName",
")",
";",
"$",
"path",
"=",
"implode",
"(",
"DIRECTORY_SEPARATOR",
",",
"[",
"$",
"theme",
"->",
"getName",
"(",
")",
",",
"self",
"::",
"IMPORT_FOLDER",
",",
"$",
"importId",
"]",
")",
";",
"$",
"files",
"=",
"$",
"this",
"->",
"resourceProvider",
"->",
"findApplicableResources",
"(",
"[",
"$",
"path",
"]",
")",
";",
"if",
"(",
"$",
"theme",
"->",
"getParentTheme",
"(",
")",
")",
"{",
"$",
"files",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"getImportResources",
"(",
"$",
"theme",
"->",
"getParentTheme",
"(",
")",
",",
"$",
"importId",
")",
",",
"$",
"files",
")",
";",
"}",
"return",
"$",
"files",
";",
"}"
] | @param string $themeName
@param string $importId
@return array | [
"@param",
"string",
"$themeName",
"@param",
"string",
"$importId"
] | train | https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Extension/Theme/Visitor/ImportVisitor.php#L157-L172 |
luniki/trails | lib/trails.php | Trails_Dispatcher.dispatch | function dispatch($uri) {
# E_USER_ERROR|E_USER_WARNING|E_USER_NOTICE|E_RECOVERABLE_ERROR = 5888
$old_handler = set_error_handler(array($this, 'error_handler'), 5888);
ob_start();
$level = ob_get_level();
$this->map_uri_to_response($this->clean_request_uri((string) $uri))->output();
while (ob_get_level() >= $level) {
ob_end_flush();
}
if (isset($old_handler)) {
set_error_handler($old_handler);
}
} | php | function dispatch($uri) {
# E_USER_ERROR|E_USER_WARNING|E_USER_NOTICE|E_RECOVERABLE_ERROR = 5888
$old_handler = set_error_handler(array($this, 'error_handler'), 5888);
ob_start();
$level = ob_get_level();
$this->map_uri_to_response($this->clean_request_uri((string) $uri))->output();
while (ob_get_level() >= $level) {
ob_end_flush();
}
if (isset($old_handler)) {
set_error_handler($old_handler);
}
} | [
"function",
"dispatch",
"(",
"$",
"uri",
")",
"{",
"# E_USER_ERROR|E_USER_WARNING|E_USER_NOTICE|E_RECOVERABLE_ERROR = 5888",
"$",
"old_handler",
"=",
"set_error_handler",
"(",
"array",
"(",
"$",
"this",
",",
"'error_handler'",
")",
",",
"5888",
")",
";",
"ob_start",
"(",
")",
";",
"$",
"level",
"=",
"ob_get_level",
"(",
")",
";",
"$",
"this",
"->",
"map_uri_to_response",
"(",
"$",
"this",
"->",
"clean_request_uri",
"(",
"(",
"string",
")",
"$",
"uri",
")",
")",
"->",
"output",
"(",
")",
";",
"while",
"(",
"ob_get_level",
"(",
")",
">=",
"$",
"level",
")",
"{",
"ob_end_flush",
"(",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"old_handler",
")",
")",
"{",
"set_error_handler",
"(",
"$",
"old_handler",
")",
";",
"}",
"}"
] | Maps a string to a response which is then rendered.
@param string The requested URI.
@return void | [
"Maps",
"a",
"string",
"to",
"a",
"response",
"which",
"is",
"then",
"rendered",
"."
] | train | https://github.com/luniki/trails/blob/ade6e3aa6bb543fb66e3295acc74f32121085c16/lib/trails.php#L113-L130 |
luniki/trails | lib/trails.php | Trails_Controller.perform | function perform($unconsumed) {
list($action, $args, $format) = $this->extract_action_and_args($unconsumed);
# set format
$this->format = isset($format) ? $format : 'html';
# call before filter
$before_filter_result = $this->before_filter($action, $args);
# send action to controller
# TODO (mlunzena) shouldn't the after filter be triggered too?
if (!(FALSE === $before_filter_result || $this->performed)) {
$mapped_action = $this->map_action($action);
# is action callable?
if (method_exists($this, $mapped_action)) {
call_user_func_array(array(&$this, $mapped_action), $args);
}
else {
$this->does_not_understand($action, $args);
}
if (!$this->performed) {
$this->render_action($action);
}
# call after filter
$this->after_filter($action, $args);
}
return $this->response;
} | php | function perform($unconsumed) {
list($action, $args, $format) = $this->extract_action_and_args($unconsumed);
# set format
$this->format = isset($format) ? $format : 'html';
# call before filter
$before_filter_result = $this->before_filter($action, $args);
# send action to controller
# TODO (mlunzena) shouldn't the after filter be triggered too?
if (!(FALSE === $before_filter_result || $this->performed)) {
$mapped_action = $this->map_action($action);
# is action callable?
if (method_exists($this, $mapped_action)) {
call_user_func_array(array(&$this, $mapped_action), $args);
}
else {
$this->does_not_understand($action, $args);
}
if (!$this->performed) {
$this->render_action($action);
}
# call after filter
$this->after_filter($action, $args);
}
return $this->response;
} | [
"function",
"perform",
"(",
"$",
"unconsumed",
")",
"{",
"list",
"(",
"$",
"action",
",",
"$",
"args",
",",
"$",
"format",
")",
"=",
"$",
"this",
"->",
"extract_action_and_args",
"(",
"$",
"unconsumed",
")",
";",
"# set format",
"$",
"this",
"->",
"format",
"=",
"isset",
"(",
"$",
"format",
")",
"?",
"$",
"format",
":",
"'html'",
";",
"# call before filter",
"$",
"before_filter_result",
"=",
"$",
"this",
"->",
"before_filter",
"(",
"$",
"action",
",",
"$",
"args",
")",
";",
"# send action to controller",
"# TODO (mlunzena) shouldn't the after filter be triggered too?",
"if",
"(",
"!",
"(",
"FALSE",
"===",
"$",
"before_filter_result",
"||",
"$",
"this",
"->",
"performed",
")",
")",
"{",
"$",
"mapped_action",
"=",
"$",
"this",
"->",
"map_action",
"(",
"$",
"action",
")",
";",
"# is action callable?",
"if",
"(",
"method_exists",
"(",
"$",
"this",
",",
"$",
"mapped_action",
")",
")",
"{",
"call_user_func_array",
"(",
"array",
"(",
"&",
"$",
"this",
",",
"$",
"mapped_action",
")",
",",
"$",
"args",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"does_not_understand",
"(",
"$",
"action",
",",
"$",
"args",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"performed",
")",
"{",
"$",
"this",
"->",
"render_action",
"(",
"$",
"action",
")",
";",
"}",
"# call after filter",
"$",
"this",
"->",
"after_filter",
"(",
"$",
"action",
",",
"$",
"args",
")",
";",
"}",
"return",
"$",
"this",
"->",
"response",
";",
"}"
] | This method extracts an action string and further arguments from it's
parameter. The action string is mapped to a method being called afterwards
using the said arguments. That method is called and a response object is
generated, populated and sent back to the dispatcher.
@param type <description>
@return type <description> | [
"This",
"method",
"extracts",
"an",
"action",
"string",
"and",
"further",
"arguments",
"from",
"it",
"s",
"parameter",
".",
"The",
"action",
"string",
"is",
"mapped",
"to",
"a",
"method",
"being",
"called",
"afterwards",
"using",
"the",
"said",
"arguments",
".",
"That",
"method",
"is",
"called",
"and",
"a",
"response",
"object",
"is",
"generated",
"populated",
"and",
"sent",
"back",
"to",
"the",
"dispatcher",
"."
] | train | https://github.com/luniki/trails/blob/ade6e3aa6bb543fb66e3295acc74f32121085c16/lib/trails.php#L536-L569 |
luniki/trails | lib/trails.php | Trails_Controller.extract_action_and_args | function extract_action_and_args($string) {
if ('' === $string) {
return array('index', array(), NULL);
}
// find optional file extension
$format = NULL;
if (preg_match('/^(.*[^\/.])\.(\w+)$/', $string, $matches)) {
list($_, $string, $format) = $matches;
}
// TODO this should possibly remove empty tokens
$args = explode('/', $string);
$action = array_shift($args);
return array($action, $args, $format);
} | php | function extract_action_and_args($string) {
if ('' === $string) {
return array('index', array(), NULL);
}
// find optional file extension
$format = NULL;
if (preg_match('/^(.*[^\/.])\.(\w+)$/', $string, $matches)) {
list($_, $string, $format) = $matches;
}
// TODO this should possibly remove empty tokens
$args = explode('/', $string);
$action = array_shift($args);
return array($action, $args, $format);
} | [
"function",
"extract_action_and_args",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"''",
"===",
"$",
"string",
")",
"{",
"return",
"array",
"(",
"'index'",
",",
"array",
"(",
")",
",",
"NULL",
")",
";",
"}",
"// find optional file extension",
"$",
"format",
"=",
"NULL",
";",
"if",
"(",
"preg_match",
"(",
"'/^(.*[^\\/.])\\.(\\w+)$/'",
",",
"$",
"string",
",",
"$",
"matches",
")",
")",
"{",
"list",
"(",
"$",
"_",
",",
"$",
"string",
",",
"$",
"format",
")",
"=",
"$",
"matches",
";",
"}",
"// TODO this should possibly remove empty tokens",
"$",
"args",
"=",
"explode",
"(",
"'/'",
",",
"$",
"string",
")",
";",
"$",
"action",
"=",
"array_shift",
"(",
"$",
"args",
")",
";",
"return",
"array",
"(",
"$",
"action",
",",
"$",
"args",
",",
"$",
"format",
")",
";",
"}"
] | Extracts action and args from a string.
@param string the processed string
@return array an array with two elements - a string containing the
action and an array of strings representing the args | [
"Extracts",
"action",
"and",
"args",
"from",
"a",
"string",
"."
] | train | https://github.com/luniki/trails/blob/ade6e3aa6bb543fb66e3295acc74f32121085c16/lib/trails.php#L580-L596 |
luniki/trails | lib/trails.php | Trails_Controller.redirect | function redirect($to) {
if ($this->performed) {
throw new Trails_DoubleRenderError();
}
$this->performed = TRUE;
# get uri; keep absolute URIs
$url = preg_match('#^(/|\w+://)#', $to)
? $to
: $this->url_for($to);
$this->response->add_header('Location', $url)->set_status(302);
} | php | function redirect($to) {
if ($this->performed) {
throw new Trails_DoubleRenderError();
}
$this->performed = TRUE;
# get uri; keep absolute URIs
$url = preg_match('#^(/|\w+://)#', $to)
? $to
: $this->url_for($to);
$this->response->add_header('Location', $url)->set_status(302);
} | [
"function",
"redirect",
"(",
"$",
"to",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"performed",
")",
"{",
"throw",
"new",
"Trails_DoubleRenderError",
"(",
")",
";",
"}",
"$",
"this",
"->",
"performed",
"=",
"TRUE",
";",
"# get uri; keep absolute URIs",
"$",
"url",
"=",
"preg_match",
"(",
"'#^(/|\\w+://)#'",
",",
"$",
"to",
")",
"?",
"$",
"to",
":",
"$",
"this",
"->",
"url_for",
"(",
"$",
"to",
")",
";",
"$",
"this",
"->",
"response",
"->",
"add_header",
"(",
"'Location'",
",",
"$",
"url",
")",
"->",
"set_status",
"(",
"302",
")",
";",
"}"
] | <MethodDescription>
@param string <description>
@return void | [
"<MethodDescription",
">"
] | train | https://github.com/luniki/trails/blob/ade6e3aa6bb543fb66e3295acc74f32121085c16/lib/trails.php#L659-L673 |
luniki/trails | lib/trails.php | Trails_Controller.url_for | function url_for($to/*, ...*/) {
# urlencode all but the first argument
$args = func_get_args();
$args = array_map('urlencode', $args);
$args[0] = $to;
return $this->dispatcher->trails_uri . '/' . join('/', $args);
} | php | function url_for($to/*, ...*/) {
# urlencode all but the first argument
$args = func_get_args();
$args = array_map('urlencode', $args);
$args[0] = $to;
return $this->dispatcher->trails_uri . '/' . join('/', $args);
} | [
"function",
"url_for",
"(",
"$",
"to",
"/*, ...*/",
")",
"{",
"# urlencode all but the first argument",
"$",
"args",
"=",
"func_get_args",
"(",
")",
";",
"$",
"args",
"=",
"array_map",
"(",
"'urlencode'",
",",
"$",
"args",
")",
";",
"$",
"args",
"[",
"0",
"]",
"=",
"$",
"to",
";",
"return",
"$",
"this",
"->",
"dispatcher",
"->",
"trails_uri",
".",
"'/'",
".",
"join",
"(",
"'/'",
",",
"$",
"args",
")",
";",
"}"
] | Returns a URL to a specified route to your Trails application.
Example:
Your Trails application is located at 'http://example.com/dispatch.php'.
So your dispatcher's trails_uri is set to 'http://example.com/dispatch.php'
If you want the URL to your 'wiki' controller with action 'show' and
parameter 'page' you should send:
$url = $controller->url_for('wiki/show', 'page');
$url should then contain 'http://example.com/dispatch.php/wiki/show/page'.
The first parameter is a string containing the controller and optionally an
action:
- "{controller}/{action}"
- "path/to/controller/action"
- "controller"
This "controller/action" string is not url encoded. You may provide
additional parameter which will be urlencoded and concatenated with
slashes:
$controller->url_for('wiki/show', 'page');
-> 'wiki/show/page'
$controller->url_for('wiki/show', 'page', 'one and a half');
-> 'wiki/show/page/one+and+a+half'
@param string a string containing a controller and optionally an action
@param strings optional arguments
@return string a URL to this route | [
"Returns",
"a",
"URL",
"to",
"a",
"specified",
"route",
"to",
"your",
"Trails",
"application",
"."
] | train | https://github.com/luniki/trails/blob/ade6e3aa6bb543fb66e3295acc74f32121085c16/lib/trails.php#L825-L833 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.