repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
yuncms/framework
src/admin/ItemController.php
ItemController.findModel
protected function findModel($id) { $auth = Yii::$app->getAuthManager(); $item = $this->type === Item::TYPE_ROLE ? $auth->getRole($id) : $auth->getPermission($id); if ($item) { return new AdminAuthItem($item); } else { throw new NotFoundHttpException(Yii::t('yuncms', 'The requested page does not exist.')); } }
php
protected function findModel($id) { $auth = Yii::$app->getAuthManager(); $item = $this->type === Item::TYPE_ROLE ? $auth->getRole($id) : $auth->getPermission($id); if ($item) { return new AdminAuthItem($item); } else { throw new NotFoundHttpException(Yii::t('yuncms', 'The requested page does not exist.')); } }
[ "protected", "function", "findModel", "(", "$", "id", ")", "{", "$", "auth", "=", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", ";", "$", "item", "=", "$", "this", "->", "type", "===", "Item", "::", "TYPE_ROLE", "?", "$", "auth", "->", "getRole", "(", "$", "id", ")", ":", "$", "auth", "->", "getPermission", "(", "$", "id", ")", ";", "if", "(", "$", "item", ")", "{", "return", "new", "AdminAuthItem", "(", "$", "item", ")", ";", "}", "else", "{", "throw", "new", "NotFoundHttpException", "(", "Yii", "::", "t", "(", "'yuncms'", ",", "'The requested page does not exist.'", ")", ")", ";", "}", "}" ]
Finds the AuthItem model based on its primary key value. If the model is not found, a 404 HTTP exception will be thrown. @param string $id @return AdminAuthItem the loaded model @throws NotFoundHttpException if the model cannot be found
[ "Finds", "the", "AuthItem", "model", "based", "on", "its", "primary", "key", "value", ".", "If", "the", "model", "is", "not", "found", "a", "404", "HTTP", "exception", "will", "be", "thrown", "." ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/admin/ItemController.php#L185-L194
phpmob/changmin
src/PhpMob/CoreBundle/DependencyInjection/PhpMobCoreExtension.php
PhpMobCoreExtension.load
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $this->registerResources('phpmob', $config['driver'], [], $container); $loader->load('services.xml'); $container->setParameter('phpmob.security_firewall_context_name', $config['security']['firewall_context_name']); $container->setParameter('phpmob.security_reserved_words', $config['security']['username']['reserved_words']); $container->setParameter('phpmob.security_password_requirements', $config['security']['password']['requirements']); $container->setParameter('phpmob.security_password_strengths', $config['security']['password']['strengths']); if ($config['security']['enabled']) { $loader->load('services/security.xml'); } if ($config['gravatar']['enabled']) { $loader->load('services/gravatar.xml'); $definition = $container->getDefinition('phpmob.gravatar_listener'); $definition->replaceArgument(2, $config['gravatar']['size']); $definition->replaceArgument(3, $config['gravatar']['imageset']); $definition->replaceArgument(4, $config['gravatar']['rating']); } }
php
public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $this->registerResources('phpmob', $config['driver'], [], $container); $loader->load('services.xml'); $container->setParameter('phpmob.security_firewall_context_name', $config['security']['firewall_context_name']); $container->setParameter('phpmob.security_reserved_words', $config['security']['username']['reserved_words']); $container->setParameter('phpmob.security_password_requirements', $config['security']['password']['requirements']); $container->setParameter('phpmob.security_password_strengths', $config['security']['password']['strengths']); if ($config['security']['enabled']) { $loader->load('services/security.xml'); } if ($config['gravatar']['enabled']) { $loader->load('services/gravatar.xml'); $definition = $container->getDefinition('phpmob.gravatar_listener'); $definition->replaceArgument(2, $config['gravatar']['size']); $definition->replaceArgument(3, $config['gravatar']['imageset']); $definition->replaceArgument(4, $config['gravatar']['rating']); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "config", "=", "$", "this", "->", "processConfiguration", "(", "new", "Configuration", "(", ")", ",", "$", "configs", ")", ";", "$", "loader", "=", "new", "Loader", "\\", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/../Resources/config'", ")", ")", ";", "$", "this", "->", "registerResources", "(", "'phpmob'", ",", "$", "config", "[", "'driver'", "]", ",", "[", "]", ",", "$", "container", ")", ";", "$", "loader", "->", "load", "(", "'services.xml'", ")", ";", "$", "container", "->", "setParameter", "(", "'phpmob.security_firewall_context_name'", ",", "$", "config", "[", "'security'", "]", "[", "'firewall_context_name'", "]", ")", ";", "$", "container", "->", "setParameter", "(", "'phpmob.security_reserved_words'", ",", "$", "config", "[", "'security'", "]", "[", "'username'", "]", "[", "'reserved_words'", "]", ")", ";", "$", "container", "->", "setParameter", "(", "'phpmob.security_password_requirements'", ",", "$", "config", "[", "'security'", "]", "[", "'password'", "]", "[", "'requirements'", "]", ")", ";", "$", "container", "->", "setParameter", "(", "'phpmob.security_password_strengths'", ",", "$", "config", "[", "'security'", "]", "[", "'password'", "]", "[", "'strengths'", "]", ")", ";", "if", "(", "$", "config", "[", "'security'", "]", "[", "'enabled'", "]", ")", "{", "$", "loader", "->", "load", "(", "'services/security.xml'", ")", ";", "}", "if", "(", "$", "config", "[", "'gravatar'", "]", "[", "'enabled'", "]", ")", "{", "$", "loader", "->", "load", "(", "'services/gravatar.xml'", ")", ";", "$", "definition", "=", "$", "container", "->", "getDefinition", "(", "'phpmob.gravatar_listener'", ")", ";", "$", "definition", "->", "replaceArgument", "(", "2", ",", "$", "config", "[", "'gravatar'", "]", "[", "'size'", "]", ")", ";", "$", "definition", "->", "replaceArgument", "(", "3", ",", "$", "config", "[", "'gravatar'", "]", "[", "'imageset'", "]", ")", ";", "$", "definition", "->", "replaceArgument", "(", "4", ",", "$", "config", "[", "'gravatar'", "]", "[", "'rating'", "]", ")", ";", "}", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/CoreBundle/DependencyInjection/PhpMobCoreExtension.php#L23-L49
EvanDotPro/EdpGithub
src/EdpGithub/Api/AbstractApi.php
AbstractApi.get
protected function get($path, array $parameters = array(), $requestHeaders = array()) { $response = $this->getClient()->getHttpClient()->get($path, $parameters, $requestHeaders); return $response->getBody(); }
php
protected function get($path, array $parameters = array(), $requestHeaders = array()) { $response = $this->getClient()->getHttpClient()->get($path, $parameters, $requestHeaders); return $response->getBody(); }
[ "protected", "function", "get", "(", "$", "path", ",", "array", "$", "parameters", "=", "array", "(", ")", ",", "$", "requestHeaders", "=", "array", "(", ")", ")", "{", "$", "response", "=", "$", "this", "->", "getClient", "(", ")", "->", "getHttpClient", "(", ")", "->", "get", "(", "$", "path", ",", "$", "parameters", ",", "$", "requestHeaders", ")", ";", "return", "$", "response", "->", "getBody", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/EvanDotPro/EdpGithub/blob/51f3e33e02edbef011103e3c2c1629d46af011a3/src/EdpGithub/Api/AbstractApi.php#L26-L31
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.getUser
public function getUser() { $this->user = $this->sessionStorage->read('user'); if (!empty($this->user)) { return $this->user; } $this->exchangeToken(); return $this->user; }
php
public function getUser() { $this->user = $this->sessionStorage->read('user'); if (!empty($this->user)) { return $this->user; } $this->exchangeToken(); return $this->user; }
[ "public", "function", "getUser", "(", ")", "{", "$", "this", "->", "user", "=", "$", "this", "->", "sessionStorage", "->", "read", "(", "'user'", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "user", ")", ")", "{", "return", "$", "this", "->", "user", ";", "}", "$", "this", "->", "exchangeToken", "(", ")", ";", "return", "$", "this", "->", "user", ";", "}" ]
Get User object @return mixed
[ "Get", "User", "object" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L75-L84
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.getAccessToken
public function getAccessToken() { if (!empty($this->accessToken)) { return $this->accessToken; } $accessToken = $this->sessionStorage->read('access_token'); if (!empty($accessToken)) { $this->accessToken = $accssToken; return $this->accessToken; } $this->exchangeToken(); return $this->accessToken; }
php
public function getAccessToken() { if (!empty($this->accessToken)) { return $this->accessToken; } $accessToken = $this->sessionStorage->read('access_token'); if (!empty($accessToken)) { $this->accessToken = $accssToken; return $this->accessToken; } $this->exchangeToken(); return $this->accessToken; }
[ "public", "function", "getAccessToken", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "accessToken", ")", ")", "{", "return", "$", "this", "->", "accessToken", ";", "}", "$", "accessToken", "=", "$", "this", "->", "sessionStorage", "->", "read", "(", "'access_token'", ")", ";", "if", "(", "!", "empty", "(", "$", "accessToken", ")", ")", "{", "$", "this", "->", "accessToken", "=", "$", "accssToken", ";", "return", "$", "this", "->", "accessToken", ";", "}", "$", "this", "->", "exchangeToken", "(", ")", ";", "return", "$", "this", "->", "accessToken", ";", "}" ]
Get Access token. @return mixed
[ "Get", "Access", "token", "." ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L91-L104
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.getRefreshToken
public function getRefreshToken() { if (empty($this->refreshToken)) { $this->refreshToken = $this->sessionStorage->read('refresh_token'); return $this->refreshToken; } return $this->refreshToken; }
php
public function getRefreshToken() { if (empty($this->refreshToken)) { $this->refreshToken = $this->sessionStorage->read('refresh_token'); return $this->refreshToken; } return $this->refreshToken; }
[ "public", "function", "getRefreshToken", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "refreshToken", ")", ")", "{", "$", "this", "->", "refreshToken", "=", "$", "this", "->", "sessionStorage", "->", "read", "(", "'refresh_token'", ")", ";", "return", "$", "this", "->", "refreshToken", ";", "}", "return", "$", "this", "->", "refreshToken", ";", "}" ]
Get Refresh token. @return mixed
[ "Get", "Refresh", "token", "." ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L111-L117
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.requestClientCredentials
public function requestClientCredentials($options = array()) { $options = array_merge(array( 'scope' => '', ), $options); $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array( 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'grant_type' => 'client_credentials', 'scope' => $options['scope'], )); $result = $res->getBody(); $token = null; if ($result && $result = json_decode($result, true)) { if (!empty($result['error'])) { throw new Exception($result['error_description']); } if (!empty($result['access_token'])) { $this->accessToken = $token = $result['access_token']; } } if (empty($token)) { throw new InvalidTokenException('token not available.'); } return $token; }
php
public function requestClientCredentials($options = array()) { $options = array_merge(array( 'scope' => '', ), $options); $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array( 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'grant_type' => 'client_credentials', 'scope' => $options['scope'], )); $result = $res->getBody(); $token = null; if ($result && $result = json_decode($result, true)) { if (!empty($result['error'])) { throw new Exception($result['error_description']); } if (!empty($result['access_token'])) { $this->accessToken = $token = $result['access_token']; } } if (empty($token)) { throw new InvalidTokenException('token not available.'); } return $token; }
[ "public", "function", "requestClientCredentials", "(", "$", "options", "=", "array", "(", ")", ")", "{", "$", "options", "=", "array_merge", "(", "array", "(", "'scope'", "=>", "''", ",", ")", ",", "$", "options", ")", ";", "$", "res", "=", "$", "this", "->", "sendRequest", "(", "'POST'", ",", "$", "this", "->", "getUrl", "(", "'oauth'", ",", "'token'", ")", ",", "array", "(", "'client_id'", "=>", "$", "this", "->", "getClientId", "(", ")", ",", "'client_secret'", "=>", "$", "this", "->", "getClientSecret", "(", ")", ",", "'grant_type'", "=>", "'client_credentials'", ",", "'scope'", "=>", "$", "options", "[", "'scope'", "]", ",", ")", ")", ";", "$", "result", "=", "$", "res", "->", "getBody", "(", ")", ";", "$", "token", "=", "null", ";", "if", "(", "$", "result", "&&", "$", "result", "=", "json_decode", "(", "$", "result", ",", "true", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "result", "[", "'error'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "$", "result", "[", "'error_description'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "result", "[", "'access_token'", "]", ")", ")", "{", "$", "this", "->", "accessToken", "=", "$", "token", "=", "$", "result", "[", "'access_token'", "]", ";", "}", "}", "if", "(", "empty", "(", "$", "token", ")", ")", "{", "throw", "new", "InvalidTokenException", "(", "'token not available.'", ")", ";", "}", "return", "$", "token", ";", "}" ]
Request Client Credentials token
[ "Request", "Client", "Credentials", "token" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L122-L151
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.getLoginUrl
public function getLoginUrl($options = array()) { $options = array_merge(array( 'scope' => 'openid profile', ), $options); if (isset($options['scope']) && is_array($options['scope'])) { $options['scope'] = join(' ', $options['scope']); } // Generate nonce if (function_exists('openssl_random_pseudo_bytes')) { $nonce = sha1(openssl_random_pseudo_bytes(24)); } else { $nonce = sha1(uniqid(mt_rand(), true)); } $this->sessionStorage->write('nonce', $nonce); return $this->getUrl('oauth', 'authorize', array( 'client_id' => $this->getClientId(), 'response_type' => 'code', 'scope' => $options['scope'], 'redirect_uri' => isset($options['redirect_uri']) ? $options['redirect_uri'] : $this->redirectUri, 'nonce' => $nonce, )); }
php
public function getLoginUrl($options = array()) { $options = array_merge(array( 'scope' => 'openid profile', ), $options); if (isset($options['scope']) && is_array($options['scope'])) { $options['scope'] = join(' ', $options['scope']); } // Generate nonce if (function_exists('openssl_random_pseudo_bytes')) { $nonce = sha1(openssl_random_pseudo_bytes(24)); } else { $nonce = sha1(uniqid(mt_rand(), true)); } $this->sessionStorage->write('nonce', $nonce); return $this->getUrl('oauth', 'authorize', array( 'client_id' => $this->getClientId(), 'response_type' => 'code', 'scope' => $options['scope'], 'redirect_uri' => isset($options['redirect_uri']) ? $options['redirect_uri'] : $this->redirectUri, 'nonce' => $nonce, )); }
[ "public", "function", "getLoginUrl", "(", "$", "options", "=", "array", "(", ")", ")", "{", "$", "options", "=", "array_merge", "(", "array", "(", "'scope'", "=>", "'openid profile'", ",", ")", ",", "$", "options", ")", ";", "if", "(", "isset", "(", "$", "options", "[", "'scope'", "]", ")", "&&", "is_array", "(", "$", "options", "[", "'scope'", "]", ")", ")", "{", "$", "options", "[", "'scope'", "]", "=", "join", "(", "' '", ",", "$", "options", "[", "'scope'", "]", ")", ";", "}", "// Generate nonce", "if", "(", "function_exists", "(", "'openssl_random_pseudo_bytes'", ")", ")", "{", "$", "nonce", "=", "sha1", "(", "openssl_random_pseudo_bytes", "(", "24", ")", ")", ";", "}", "else", "{", "$", "nonce", "=", "sha1", "(", "uniqid", "(", "mt_rand", "(", ")", ",", "true", ")", ")", ";", "}", "$", "this", "->", "sessionStorage", "->", "write", "(", "'nonce'", ",", "$", "nonce", ")", ";", "return", "$", "this", "->", "getUrl", "(", "'oauth'", ",", "'authorize'", ",", "array", "(", "'client_id'", "=>", "$", "this", "->", "getClientId", "(", ")", ",", "'response_type'", "=>", "'code'", ",", "'scope'", "=>", "$", "options", "[", "'scope'", "]", ",", "'redirect_uri'", "=>", "isset", "(", "$", "options", "[", "'redirect_uri'", "]", ")", "?", "$", "options", "[", "'redirect_uri'", "]", ":", "$", "this", "->", "redirectUri", ",", "'nonce'", "=>", "$", "nonce", ",", ")", ")", ";", "}" ]
Get login url for redirect. @param array $options @return string
[ "Get", "login", "url", "for", "redirect", "." ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L159-L183
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.logout
public function logout() { $this->sessionStorage->remove('access_token'); $this->sessionStorage->remove('refresh_token'); $this->sessionStorage->remove('user'); }
php
public function logout() { $this->sessionStorage->remove('access_token'); $this->sessionStorage->remove('refresh_token'); $this->sessionStorage->remove('user'); }
[ "public", "function", "logout", "(", ")", "{", "$", "this", "->", "sessionStorage", "->", "remove", "(", "'access_token'", ")", ";", "$", "this", "->", "sessionStorage", "->", "remove", "(", "'refresh_token'", ")", ";", "$", "this", "->", "sessionStorage", "->", "remove", "(", "'user'", ")", ";", "}" ]
Do logout
[ "Do", "logout" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L188-L192
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.exchangeToken
protected function exchangeToken() { $result = $this->requestAccessToken(); if ($result && !empty($result['access_token'])) { $this->accessToken = $result['access_token']; $this->sessionStorage->write('access_token', $result['access_token']); if (!empty($result['refresh_token'])) { $this->refreshToken = $result['refresh_token']; $this->sessionStorage->write('refresh_token', $result['refresh_token']); } if (!empty($result['id_token'])) { $this->validateIdToken($result['id_token']); $this->user = $this->requestUserInfo(); if ($this->user) { $this->sessionStorage->write('user', $this->user); } } } }
php
protected function exchangeToken() { $result = $this->requestAccessToken(); if ($result && !empty($result['access_token'])) { $this->accessToken = $result['access_token']; $this->sessionStorage->write('access_token', $result['access_token']); if (!empty($result['refresh_token'])) { $this->refreshToken = $result['refresh_token']; $this->sessionStorage->write('refresh_token', $result['refresh_token']); } if (!empty($result['id_token'])) { $this->validateIdToken($result['id_token']); $this->user = $this->requestUserInfo(); if ($this->user) { $this->sessionStorage->write('user', $this->user); } } } }
[ "protected", "function", "exchangeToken", "(", ")", "{", "$", "result", "=", "$", "this", "->", "requestAccessToken", "(", ")", ";", "if", "(", "$", "result", "&&", "!", "empty", "(", "$", "result", "[", "'access_token'", "]", ")", ")", "{", "$", "this", "->", "accessToken", "=", "$", "result", "[", "'access_token'", "]", ";", "$", "this", "->", "sessionStorage", "->", "write", "(", "'access_token'", ",", "$", "result", "[", "'access_token'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "result", "[", "'refresh_token'", "]", ")", ")", "{", "$", "this", "->", "refreshToken", "=", "$", "result", "[", "'refresh_token'", "]", ";", "$", "this", "->", "sessionStorage", "->", "write", "(", "'refresh_token'", ",", "$", "result", "[", "'refresh_token'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "result", "[", "'id_token'", "]", ")", ")", "{", "$", "this", "->", "validateIdToken", "(", "$", "result", "[", "'id_token'", "]", ")", ";", "$", "this", "->", "user", "=", "$", "this", "->", "requestUserInfo", "(", ")", ";", "if", "(", "$", "this", "->", "user", ")", "{", "$", "this", "->", "sessionStorage", "->", "write", "(", "'user'", ",", "$", "this", "->", "user", ")", ";", "}", "}", "}", "}" ]
Exchange code to access_token
[ "Exchange", "code", "to", "access_token" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L222-L240
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.refreshToken
public function refreshToken() { $refreshToken = $this->getRefreshToken(); if (empty($refreshToken)) { throw new InvalidTokenException('refresh token not available.'); } $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array( 'refresh_token' => $refreshToken, 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'grant_type' => 'refresh_token', )); $result = $res->getBody(); if ($result && $result = json_decode($result, true)) { if (!empty($result['error'])) { throw new Exception($result['error_description']); } else if (!empty($result['access_token'])) { $this->accessToken = $result['access_token']; $this->sessionStorage->write('access_token', $result['access_token']); return true; } } throw new Exception('failed to refreshing token.'); }
php
public function refreshToken() { $refreshToken = $this->getRefreshToken(); if (empty($refreshToken)) { throw new InvalidTokenException('refresh token not available.'); } $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array( 'refresh_token' => $refreshToken, 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'grant_type' => 'refresh_token', )); $result = $res->getBody(); if ($result && $result = json_decode($result, true)) { if (!empty($result['error'])) { throw new Exception($result['error_description']); } else if (!empty($result['access_token'])) { $this->accessToken = $result['access_token']; $this->sessionStorage->write('access_token', $result['access_token']); return true; } } throw new Exception('failed to refreshing token.'); }
[ "public", "function", "refreshToken", "(", ")", "{", "$", "refreshToken", "=", "$", "this", "->", "getRefreshToken", "(", ")", ";", "if", "(", "empty", "(", "$", "refreshToken", ")", ")", "{", "throw", "new", "InvalidTokenException", "(", "'refresh token not available.'", ")", ";", "}", "$", "res", "=", "$", "this", "->", "sendRequest", "(", "'POST'", ",", "$", "this", "->", "getUrl", "(", "'oauth'", ",", "'token'", ")", ",", "array", "(", "'refresh_token'", "=>", "$", "refreshToken", ",", "'client_id'", "=>", "$", "this", "->", "getClientId", "(", ")", ",", "'client_secret'", "=>", "$", "this", "->", "getClientSecret", "(", ")", ",", "'grant_type'", "=>", "'refresh_token'", ",", ")", ")", ";", "$", "result", "=", "$", "res", "->", "getBody", "(", ")", ";", "if", "(", "$", "result", "&&", "$", "result", "=", "json_decode", "(", "$", "result", ",", "true", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "result", "[", "'error'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "$", "result", "[", "'error_description'", "]", ")", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "result", "[", "'access_token'", "]", ")", ")", "{", "$", "this", "->", "accessToken", "=", "$", "result", "[", "'access_token'", "]", ";", "$", "this", "->", "sessionStorage", "->", "write", "(", "'access_token'", ",", "$", "result", "[", "'access_token'", "]", ")", ";", "return", "true", ";", "}", "}", "throw", "new", "Exception", "(", "'failed to refreshing token.'", ")", ";", "}" ]
Refresh token
[ "Refresh", "token" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L245-L267
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.requestUserInfo
protected function requestUserInfo() { $res = $this->sendRequest('GET', $this->getUrl('oauth', 'userinfo'), array(), array( 'Authorization' => 'Bearer ' . $this->sessionStorage->read('access_token'), )); $result = $res->getBody(); return json_decode($result, true); }
php
protected function requestUserInfo() { $res = $this->sendRequest('GET', $this->getUrl('oauth', 'userinfo'), array(), array( 'Authorization' => 'Bearer ' . $this->sessionStorage->read('access_token'), )); $result = $res->getBody(); return json_decode($result, true); }
[ "protected", "function", "requestUserInfo", "(", ")", "{", "$", "res", "=", "$", "this", "->", "sendRequest", "(", "'GET'", ",", "$", "this", "->", "getUrl", "(", "'oauth'", ",", "'userinfo'", ")", ",", "array", "(", ")", ",", "array", "(", "'Authorization'", "=>", "'Bearer '", ".", "$", "this", "->", "sessionStorage", "->", "read", "(", "'access_token'", ")", ",", ")", ")", ";", "$", "result", "=", "$", "res", "->", "getBody", "(", ")", ";", "return", "json_decode", "(", "$", "result", ",", "true", ")", ";", "}" ]
Request User Info @return mixed
[ "Request", "User", "Info" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L274-L281
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.requestAccessToken
protected function requestAccessToken() { $code = $this->getRequestVar('code'); if (!empty($code)) { $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array( 'code' => $code, 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'grant_type' => 'authorization_code', 'redirect_uri' => $this->redirectUri, )); $result = $res->getBody(); if ($result && $result = json_decode($result, true)) { if (!empty($result['error'])) { throw new Exception($result['error_description']); } return $result; } } return null; }
php
protected function requestAccessToken() { $code = $this->getRequestVar('code'); if (!empty($code)) { $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array( 'code' => $code, 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'grant_type' => 'authorization_code', 'redirect_uri' => $this->redirectUri, )); $result = $res->getBody(); if ($result && $result = json_decode($result, true)) { if (!empty($result['error'])) { throw new Exception($result['error_description']); } return $result; } } return null; }
[ "protected", "function", "requestAccessToken", "(", ")", "{", "$", "code", "=", "$", "this", "->", "getRequestVar", "(", "'code'", ")", ";", "if", "(", "!", "empty", "(", "$", "code", ")", ")", "{", "$", "res", "=", "$", "this", "->", "sendRequest", "(", "'POST'", ",", "$", "this", "->", "getUrl", "(", "'oauth'", ",", "'token'", ")", ",", "array", "(", "'code'", "=>", "$", "code", ",", "'client_id'", "=>", "$", "this", "->", "getClientId", "(", ")", ",", "'client_secret'", "=>", "$", "this", "->", "getClientSecret", "(", ")", ",", "'grant_type'", "=>", "'authorization_code'", ",", "'redirect_uri'", "=>", "$", "this", "->", "redirectUri", ",", ")", ")", ";", "$", "result", "=", "$", "res", "->", "getBody", "(", ")", ";", "if", "(", "$", "result", "&&", "$", "result", "=", "json_decode", "(", "$", "result", ",", "true", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "result", "[", "'error'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "$", "result", "[", "'error_description'", "]", ")", ";", "}", "return", "$", "result", ";", "}", "}", "return", "null", ";", "}" ]
Request Access Token @return mixed|null @throws Exception
[ "Request", "Access", "Token" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L289-L309
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.getUrl
public function getUrl($type, $path, $params = array()) { $url = self::$URL_TABLE[$type] . $path; if (!empty($params)) { $url .= '?' . http_build_query($params); } return $url; }
php
public function getUrl($type, $path, $params = array()) { $url = self::$URL_TABLE[$type] . $path; if (!empty($params)) { $url .= '?' . http_build_query($params); } return $url; }
[ "public", "function", "getUrl", "(", "$", "type", ",", "$", "path", ",", "$", "params", "=", "array", "(", ")", ")", "{", "$", "url", "=", "self", "::", "$", "URL_TABLE", "[", "$", "type", "]", ".", "$", "path", ";", "if", "(", "!", "empty", "(", "$", "params", ")", ")", "{", "$", "url", ".=", "'?'", ".", "http_build_query", "(", "$", "params", ")", ";", "}", "return", "$", "url", ";", "}" ]
Build API Url @param $type @param $path @param array $params @return string
[ "Build", "API", "Url" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L319-L325
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.sendRequest
protected function sendRequest($method, $url, $data = array(), $headers = array()) { $contextOptions = array( 'http' => array( 'method' => $method, 'user_agent' => 'MinecraftJP-PHP-SDK/' . self::VERSION, 'ignore_errors' => true, ), ); if ($method == 'POST' && is_array($data)) { $formEncoded = http_build_query($data); $headers['Content-Type'] = 'application/x-www-form-urlencoded'; $headers['Content-Length'] = strlen($formEncoded); $contextOptions['http']['content'] = $formEncoded; } $contextOptions['http']['header'] = ''; foreach ($headers as $k => $v) { $contextOptions['http']['header'] .= $k . ': ' . $v . "\r\n"; } $context = stream_context_create($contextOptions); $body = file_get_contents($url, false, $context); return new HttpResponse($http_response_header, $body); }
php
protected function sendRequest($method, $url, $data = array(), $headers = array()) { $contextOptions = array( 'http' => array( 'method' => $method, 'user_agent' => 'MinecraftJP-PHP-SDK/' . self::VERSION, 'ignore_errors' => true, ), ); if ($method == 'POST' && is_array($data)) { $formEncoded = http_build_query($data); $headers['Content-Type'] = 'application/x-www-form-urlencoded'; $headers['Content-Length'] = strlen($formEncoded); $contextOptions['http']['content'] = $formEncoded; } $contextOptions['http']['header'] = ''; foreach ($headers as $k => $v) { $contextOptions['http']['header'] .= $k . ': ' . $v . "\r\n"; } $context = stream_context_create($contextOptions); $body = file_get_contents($url, false, $context); return new HttpResponse($http_response_header, $body); }
[ "protected", "function", "sendRequest", "(", "$", "method", ",", "$", "url", ",", "$", "data", "=", "array", "(", ")", ",", "$", "headers", "=", "array", "(", ")", ")", "{", "$", "contextOptions", "=", "array", "(", "'http'", "=>", "array", "(", "'method'", "=>", "$", "method", ",", "'user_agent'", "=>", "'MinecraftJP-PHP-SDK/'", ".", "self", "::", "VERSION", ",", "'ignore_errors'", "=>", "true", ",", ")", ",", ")", ";", "if", "(", "$", "method", "==", "'POST'", "&&", "is_array", "(", "$", "data", ")", ")", "{", "$", "formEncoded", "=", "http_build_query", "(", "$", "data", ")", ";", "$", "headers", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded'", ";", "$", "headers", "[", "'Content-Length'", "]", "=", "strlen", "(", "$", "formEncoded", ")", ";", "$", "contextOptions", "[", "'http'", "]", "[", "'content'", "]", "=", "$", "formEncoded", ";", "}", "$", "contextOptions", "[", "'http'", "]", "[", "'header'", "]", "=", "''", ";", "foreach", "(", "$", "headers", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "contextOptions", "[", "'http'", "]", "[", "'header'", "]", ".=", "$", "k", ".", "': '", ".", "$", "v", ".", "\"\\r\\n\"", ";", "}", "$", "context", "=", "stream_context_create", "(", "$", "contextOptions", ")", ";", "$", "body", "=", "file_get_contents", "(", "$", "url", ",", "false", ",", "$", "context", ")", ";", "return", "new", "HttpResponse", "(", "$", "http_response_header", ",", "$", "body", ")", ";", "}" ]
Send HTTP Request @param $method @param $url @param array $data @param array $headers @return string
[ "Send", "HTTP", "Request" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L336-L360
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.getCurrentUrl
protected function getCurrentUrl() { $isHttps = $this->getServerVar('HTTPS'); $forwardedProto = $this->getServerVar('HTTP_X_FORWARDED_PROTO'); if ($isHttps == 'on' || $forwardedProto === 'https') { $schema = 'https://'; } else { $schema = 'http://'; } $host = $this->getServerVar('HTTP_HOST'); if (preg_match('#:(\d+)$#', $host, $match)) { $port = ':' . $match[1]; } else { $port = ''; } $urls = parse_url($this->getServerVar('REQUEST_URI')); $path = $urls['path']; $query = ''; return $schema . $host . $port . $path . $query; }
php
protected function getCurrentUrl() { $isHttps = $this->getServerVar('HTTPS'); $forwardedProto = $this->getServerVar('HTTP_X_FORWARDED_PROTO'); if ($isHttps == 'on' || $forwardedProto === 'https') { $schema = 'https://'; } else { $schema = 'http://'; } $host = $this->getServerVar('HTTP_HOST'); if (preg_match('#:(\d+)$#', $host, $match)) { $port = ':' . $match[1]; } else { $port = ''; } $urls = parse_url($this->getServerVar('REQUEST_URI')); $path = $urls['path']; $query = ''; return $schema . $host . $port . $path . $query; }
[ "protected", "function", "getCurrentUrl", "(", ")", "{", "$", "isHttps", "=", "$", "this", "->", "getServerVar", "(", "'HTTPS'", ")", ";", "$", "forwardedProto", "=", "$", "this", "->", "getServerVar", "(", "'HTTP_X_FORWARDED_PROTO'", ")", ";", "if", "(", "$", "isHttps", "==", "'on'", "||", "$", "forwardedProto", "===", "'https'", ")", "{", "$", "schema", "=", "'https://'", ";", "}", "else", "{", "$", "schema", "=", "'http://'", ";", "}", "$", "host", "=", "$", "this", "->", "getServerVar", "(", "'HTTP_HOST'", ")", ";", "if", "(", "preg_match", "(", "'#:(\\d+)$#'", ",", "$", "host", ",", "$", "match", ")", ")", "{", "$", "port", "=", "':'", ".", "$", "match", "[", "1", "]", ";", "}", "else", "{", "$", "port", "=", "''", ";", "}", "$", "urls", "=", "parse_url", "(", "$", "this", "->", "getServerVar", "(", "'REQUEST_URI'", ")", ")", ";", "$", "path", "=", "$", "urls", "[", "'path'", "]", ";", "$", "query", "=", "''", ";", "return", "$", "schema", ".", "$", "host", ".", "$", "port", ".", "$", "path", ".", "$", "query", ";", "}" ]
Get Current Url @return string
[ "Get", "Current", "Url" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L367-L389
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.getPublicKey
protected function getPublicKey($kid) { $publicKeyFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'MinecraftJP.crt'; if (file_exists($publicKeyFile)) { return openssl_pkey_get_public('file://' . $publicKeyFile); } if (empty($kid)) { throw new Exception('No such public key.'); } $result = $this->sendRequest('GET', $this->getUrl('oauth', 'jwks')); if ($result && $result = json_decode($result, true)) { $len = count($result['keys']); for ($i = 0; $i < $len; $i++) { $key = $result['keys'][$i]; if (!isset($key['kid']) || $key['kid'] != $kid) continue; // もうちょっとスマートにやりたい所 // 2048bit MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A // 4096bit MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A $data = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A' . 'MIIBCgKCAQEA' . $key['n'] . 'ID' . $key['e']; $data = "-----BEGIN PUBLIC KEY----- \n" . wordwrap($data, 64, "\n", true) . "\n-----END PUBLIC KEY----- \n"; $publicKey = openssl_pkey_get_public($data); if (!$publicKey) throw new Exception('Unable to fetch public key.'); return $publicKey; } } throw new Exception('No such public key.'); }
php
protected function getPublicKey($kid) { $publicKeyFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'MinecraftJP.crt'; if (file_exists($publicKeyFile)) { return openssl_pkey_get_public('file://' . $publicKeyFile); } if (empty($kid)) { throw new Exception('No such public key.'); } $result = $this->sendRequest('GET', $this->getUrl('oauth', 'jwks')); if ($result && $result = json_decode($result, true)) { $len = count($result['keys']); for ($i = 0; $i < $len; $i++) { $key = $result['keys'][$i]; if (!isset($key['kid']) || $key['kid'] != $kid) continue; // もうちょっとスマートにやりたい所 // 2048bit MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A // 4096bit MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A $data = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A' . 'MIIBCgKCAQEA' . $key['n'] . 'ID' . $key['e']; $data = "-----BEGIN PUBLIC KEY----- \n" . wordwrap($data, 64, "\n", true) . "\n-----END PUBLIC KEY----- \n"; $publicKey = openssl_pkey_get_public($data); if (!$publicKey) throw new Exception('Unable to fetch public key.'); return $publicKey; } } throw new Exception('No such public key.'); }
[ "protected", "function", "getPublicKey", "(", "$", "kid", ")", "{", "$", "publicKeyFile", "=", "dirname", "(", "__FILE__", ")", ".", "DIRECTORY_SEPARATOR", ".", "'MinecraftJP.crt'", ";", "if", "(", "file_exists", "(", "$", "publicKeyFile", ")", ")", "{", "return", "openssl_pkey_get_public", "(", "'file://'", ".", "$", "publicKeyFile", ")", ";", "}", "if", "(", "empty", "(", "$", "kid", ")", ")", "{", "throw", "new", "Exception", "(", "'No such public key.'", ")", ";", "}", "$", "result", "=", "$", "this", "->", "sendRequest", "(", "'GET'", ",", "$", "this", "->", "getUrl", "(", "'oauth'", ",", "'jwks'", ")", ")", ";", "if", "(", "$", "result", "&&", "$", "result", "=", "json_decode", "(", "$", "result", ",", "true", ")", ")", "{", "$", "len", "=", "count", "(", "$", "result", "[", "'keys'", "]", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "len", ";", "$", "i", "++", ")", "{", "$", "key", "=", "$", "result", "[", "'keys'", "]", "[", "$", "i", "]", ";", "if", "(", "!", "isset", "(", "$", "key", "[", "'kid'", "]", ")", "||", "$", "key", "[", "'kid'", "]", "!=", "$", "kid", ")", "continue", ";", "// もうちょっとスマートにやりたい所", "// 2048bit MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A", "// 4096bit MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A", "$", "data", "=", "'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A'", ".", "'MIIBCgKCAQEA'", ".", "$", "key", "[", "'n'", "]", ".", "'ID'", ".", "$", "key", "[", "'e'", "]", ";", "$", "data", "=", "\"-----BEGIN PUBLIC KEY----- \\n\"", ".", "wordwrap", "(", "$", "data", ",", "64", ",", "\"\\n\"", ",", "true", ")", ".", "\"\\n-----END PUBLIC KEY----- \\n\"", ";", "$", "publicKey", "=", "openssl_pkey_get_public", "(", "$", "data", ")", ";", "if", "(", "!", "$", "publicKey", ")", "throw", "new", "Exception", "(", "'Unable to fetch public key.'", ")", ";", "return", "$", "publicKey", ";", "}", "}", "throw", "new", "Exception", "(", "'No such public key.'", ")", ";", "}" ]
Get Public Key @param $kid @return resource|void @throws Exception
[ "Get", "Public", "Key" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L398-L427
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
MinecraftJP.validateIdToken
protected function validateIdToken($idToken) { $segments = explode('.', $idToken); if (count($segments) != 3) { throw new InvalidIdTokenException('Invalid Token'); } $header = json_decode($this->decodeBase64Url($segments[0]), true); if (empty($header)) { throw new InvalidIdTokenException('Invalid Token'); } $payload = json_decode($this->decodeBase64Url($segments[1]), true); if (empty($payload)) { throw new InvalidIdTokenException('Invalid Token'); } $signature = $this->decodeBase64Url($segments[2]); $signingInput = implode('.', array($segments[0], $segments[1])); $kid = isset($header['kid']) ? $header['kid'] : null; switch ($header['alg']) { case 'RS256': case 'RS384': case 'RS512': // 署名検証用に公開鍵を取得する $publicKey = $this->getPublicKey($kid); $algo = 'sha' . substr($header['alg'], 2); if (openssl_verify($signingInput, $signature, $publicKey, $algo) != 1) { openssl_free_key($publicKey); throw new InvalidIdTokenException('Signature Mismatch'); } openssl_free_key($publicKey); break; default: throw new InvalidIdTokenException('Unsupported Algorithm: ' . $header['alg']); } // Check Issuer if ($payload['iss'] != 'minecraft.jp') { throw new InvalidIdTokenException('Invalid Issuer.'); } // Check Client Id if ($payload['aud'] != $this->getClientId()) { throw new InvalidIdTokenException('Client ID Mismatch.'); } // Check expired $now = time(); if ($payload['exp'] < $now || $payload['iat'] < $now - 600) { throw new InvalidIdTokenException('ID Token expired.'); } // Check nonce if ($payload['nonce'] != $this->sessionStorage->read('nonce')) { throw new InvalidIdTokenException('Nonce Mismatch.'); } $this->sessionStorage->remove('nonce'); return $payload; }
php
protected function validateIdToken($idToken) { $segments = explode('.', $idToken); if (count($segments) != 3) { throw new InvalidIdTokenException('Invalid Token'); } $header = json_decode($this->decodeBase64Url($segments[0]), true); if (empty($header)) { throw new InvalidIdTokenException('Invalid Token'); } $payload = json_decode($this->decodeBase64Url($segments[1]), true); if (empty($payload)) { throw new InvalidIdTokenException('Invalid Token'); } $signature = $this->decodeBase64Url($segments[2]); $signingInput = implode('.', array($segments[0], $segments[1])); $kid = isset($header['kid']) ? $header['kid'] : null; switch ($header['alg']) { case 'RS256': case 'RS384': case 'RS512': // 署名検証用に公開鍵を取得する $publicKey = $this->getPublicKey($kid); $algo = 'sha' . substr($header['alg'], 2); if (openssl_verify($signingInput, $signature, $publicKey, $algo) != 1) { openssl_free_key($publicKey); throw new InvalidIdTokenException('Signature Mismatch'); } openssl_free_key($publicKey); break; default: throw new InvalidIdTokenException('Unsupported Algorithm: ' . $header['alg']); } // Check Issuer if ($payload['iss'] != 'minecraft.jp') { throw new InvalidIdTokenException('Invalid Issuer.'); } // Check Client Id if ($payload['aud'] != $this->getClientId()) { throw new InvalidIdTokenException('Client ID Mismatch.'); } // Check expired $now = time(); if ($payload['exp'] < $now || $payload['iat'] < $now - 600) { throw new InvalidIdTokenException('ID Token expired.'); } // Check nonce if ($payload['nonce'] != $this->sessionStorage->read('nonce')) { throw new InvalidIdTokenException('Nonce Mismatch.'); } $this->sessionStorage->remove('nonce'); return $payload; }
[ "protected", "function", "validateIdToken", "(", "$", "idToken", ")", "{", "$", "segments", "=", "explode", "(", "'.'", ",", "$", "idToken", ")", ";", "if", "(", "count", "(", "$", "segments", ")", "!=", "3", ")", "{", "throw", "new", "InvalidIdTokenException", "(", "'Invalid Token'", ")", ";", "}", "$", "header", "=", "json_decode", "(", "$", "this", "->", "decodeBase64Url", "(", "$", "segments", "[", "0", "]", ")", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "header", ")", ")", "{", "throw", "new", "InvalidIdTokenException", "(", "'Invalid Token'", ")", ";", "}", "$", "payload", "=", "json_decode", "(", "$", "this", "->", "decodeBase64Url", "(", "$", "segments", "[", "1", "]", ")", ",", "true", ")", ";", "if", "(", "empty", "(", "$", "payload", ")", ")", "{", "throw", "new", "InvalidIdTokenException", "(", "'Invalid Token'", ")", ";", "}", "$", "signature", "=", "$", "this", "->", "decodeBase64Url", "(", "$", "segments", "[", "2", "]", ")", ";", "$", "signingInput", "=", "implode", "(", "'.'", ",", "array", "(", "$", "segments", "[", "0", "]", ",", "$", "segments", "[", "1", "]", ")", ")", ";", "$", "kid", "=", "isset", "(", "$", "header", "[", "'kid'", "]", ")", "?", "$", "header", "[", "'kid'", "]", ":", "null", ";", "switch", "(", "$", "header", "[", "'alg'", "]", ")", "{", "case", "'RS256'", ":", "case", "'RS384'", ":", "case", "'RS512'", ":", "// 署名検証用に公開鍵を取得する", "$", "publicKey", "=", "$", "this", "->", "getPublicKey", "(", "$", "kid", ")", ";", "$", "algo", "=", "'sha'", ".", "substr", "(", "$", "header", "[", "'alg'", "]", ",", "2", ")", ";", "if", "(", "openssl_verify", "(", "$", "signingInput", ",", "$", "signature", ",", "$", "publicKey", ",", "$", "algo", ")", "!=", "1", ")", "{", "openssl_free_key", "(", "$", "publicKey", ")", ";", "throw", "new", "InvalidIdTokenException", "(", "'Signature Mismatch'", ")", ";", "}", "openssl_free_key", "(", "$", "publicKey", ")", ";", "break", ";", "default", ":", "throw", "new", "InvalidIdTokenException", "(", "'Unsupported Algorithm: '", ".", "$", "header", "[", "'alg'", "]", ")", ";", "}", "// Check Issuer", "if", "(", "$", "payload", "[", "'iss'", "]", "!=", "'minecraft.jp'", ")", "{", "throw", "new", "InvalidIdTokenException", "(", "'Invalid Issuer.'", ")", ";", "}", "// Check Client Id", "if", "(", "$", "payload", "[", "'aud'", "]", "!=", "$", "this", "->", "getClientId", "(", ")", ")", "{", "throw", "new", "InvalidIdTokenException", "(", "'Client ID Mismatch.'", ")", ";", "}", "// Check expired", "$", "now", "=", "time", "(", ")", ";", "if", "(", "$", "payload", "[", "'exp'", "]", "<", "$", "now", "||", "$", "payload", "[", "'iat'", "]", "<", "$", "now", "-", "600", ")", "{", "throw", "new", "InvalidIdTokenException", "(", "'ID Token expired.'", ")", ";", "}", "// Check nonce", "if", "(", "$", "payload", "[", "'nonce'", "]", "!=", "$", "this", "->", "sessionStorage", "->", "read", "(", "'nonce'", ")", ")", "{", "throw", "new", "InvalidIdTokenException", "(", "'Nonce Mismatch.'", ")", ";", "}", "$", "this", "->", "sessionStorage", "->", "remove", "(", "'nonce'", ")", ";", "return", "$", "payload", ";", "}" ]
Validate ID Token @param $idToken @return mixed @throws Exception
[ "Validate", "ID", "Token" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L436-L495
MinecraftJP/minecraftjp-php-sdk
src/MinecraftJP.php
PHPSessionStorage.read
public function read($key) { return isset($_SESSION[$this->prefix . $key]) ? $_SESSION[$this->prefix . $key] : null; }
php
public function read($key) { return isset($_SESSION[$this->prefix . $key]) ? $_SESSION[$this->prefix . $key] : null; }
[ "public", "function", "read", "(", "$", "key", ")", "{", "return", "isset", "(", "$", "_SESSION", "[", "$", "this", "->", "prefix", ".", "$", "key", "]", ")", "?", "$", "_SESSION", "[", "$", "this", "->", "prefix", ".", "$", "key", "]", ":", "null", ";", "}" ]
Read from session @param $key string @return mixed
[ "Read", "from", "session" ]
train
https://github.com/MinecraftJP/minecraftjp-php-sdk/blob/ecc592c9b6d33eb0c896210f7c9948672db54728/src/MinecraftJP.php#L681-L683
PeekAndPoke/psi
src/Operation/FullSet/UniqueByOperation.php
UniqueByOperation.apply
public function apply(\Iterator $set) { $map = $this->mapper; $result = []; $known = []; foreach ($set as $item) { $mapped = $map($item); if (! in_array($mapped, $known, $this->strict)) { $known[] = $mapped; $result[] = $item; } } return new \ArrayIterator($result); }
php
public function apply(\Iterator $set) { $map = $this->mapper; $result = []; $known = []; foreach ($set as $item) { $mapped = $map($item); if (! in_array($mapped, $known, $this->strict)) { $known[] = $mapped; $result[] = $item; } } return new \ArrayIterator($result); }
[ "public", "function", "apply", "(", "\\", "Iterator", "$", "set", ")", "{", "$", "map", "=", "$", "this", "->", "mapper", ";", "$", "result", "=", "[", "]", ";", "$", "known", "=", "[", "]", ";", "foreach", "(", "$", "set", "as", "$", "item", ")", "{", "$", "mapped", "=", "$", "map", "(", "$", "item", ")", ";", "if", "(", "!", "in_array", "(", "$", "mapped", ",", "$", "known", ",", "$", "this", "->", "strict", ")", ")", "{", "$", "known", "[", "]", "=", "$", "mapped", ";", "$", "result", "[", "]", "=", "$", "item", ";", "}", "}", "return", "new", "\\", "ArrayIterator", "(", "$", "result", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/PeekAndPoke/psi/blob/cfd45d995d3a2c2ea6ba5b1ce7b5fcc71179456f/src/Operation/FullSet/UniqueByOperation.php#L37-L54
Craftsware/scissor
src/Module/Controller.php
Controller.add
public function add($arg1, $arg2 = null) { if(isset($arg2)) { $this->set("var[$arg1]", $arg2); return $arg2; } else { if(is_array($arg1)) { foreach($arg1 as $name => $value) { $this->set("var[$name]", $value); } return $arg1; } } }
php
public function add($arg1, $arg2 = null) { if(isset($arg2)) { $this->set("var[$arg1]", $arg2); return $arg2; } else { if(is_array($arg1)) { foreach($arg1 as $name => $value) { $this->set("var[$name]", $value); } return $arg1; } } }
[ "public", "function", "add", "(", "$", "arg1", ",", "$", "arg2", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "arg2", ")", ")", "{", "$", "this", "->", "set", "(", "\"var[$arg1]\"", ",", "$", "arg2", ")", ";", "return", "$", "arg2", ";", "}", "else", "{", "if", "(", "is_array", "(", "$", "arg1", ")", ")", "{", "foreach", "(", "$", "arg1", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "this", "->", "set", "(", "\"var[$name]\"", ",", "$", "value", ")", ";", "}", "return", "$", "arg1", ";", "}", "}", "}" ]
Get Variable @param $arg1 mixed @return mixed
[ "Get", "Variable" ]
train
https://github.com/Craftsware/scissor/blob/644e4a8ea9859fc30fee36705e54784acd8d43e2/src/Module/Controller.php#L30-L50
parsnick/steak
src/Build/Builder.php
Builder.build
public function build($sourceDir, $outputDir) { $sourceList = $this->findSources($sourceDir, $outputDir); return array_walk($sourceList, [$this, 'publish']); }
php
public function build($sourceDir, $outputDir) { $sourceList = $this->findSources($sourceDir, $outputDir); return array_walk($sourceList, [$this, 'publish']); }
[ "public", "function", "build", "(", "$", "sourceDir", ",", "$", "outputDir", ")", "{", "$", "sourceList", "=", "$", "this", "->", "findSources", "(", "$", "sourceDir", ",", "$", "outputDir", ")", ";", "return", "array_walk", "(", "$", "sourceList", ",", "[", "$", "this", ",", "'publish'", "]", ")", ";", "}" ]
Build the site. @param string $sourceDir @param string $outputDir @return bool
[ "Build", "the", "site", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Build/Builder.php#L43-L48
parsnick/steak
src/Build/Builder.php
Builder.findSources
protected function findSources($searchIn, $outputTo) { $files = iterator_to_array(new FilesystemIterator($searchIn)); return array_map(function (SplFileInfo $file) use ($outputTo) { return $this->makeSource($file, $outputTo); }, $files); }
php
protected function findSources($searchIn, $outputTo) { $files = iterator_to_array(new FilesystemIterator($searchIn)); return array_map(function (SplFileInfo $file) use ($outputTo) { return $this->makeSource($file, $outputTo); }, $files); }
[ "protected", "function", "findSources", "(", "$", "searchIn", ",", "$", "outputTo", ")", "{", "$", "files", "=", "iterator_to_array", "(", "new", "FilesystemIterator", "(", "$", "searchIn", ")", ")", ";", "return", "array_map", "(", "function", "(", "SplFileInfo", "$", "file", ")", "use", "(", "$", "outputTo", ")", "{", "return", "$", "this", "->", "makeSource", "(", "$", "file", ",", "$", "outputTo", ")", ";", "}", ",", "$", "files", ")", ";", "}" ]
Create array of Sources from the given input directory. @param string $searchIn @param string $outputTo @return array
[ "Create", "array", "of", "Sources", "from", "the", "given", "input", "directory", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Build/Builder.php#L57-L66
parsnick/steak
src/Build/Builder.php
Builder.makeSource
public function makeSource(SplFileInfo $file, $outputDir) { return new Source($file->getPathname(), $outputDir . DIRECTORY_SEPARATOR . $file->getFilename()); }
php
public function makeSource(SplFileInfo $file, $outputDir) { return new Source($file->getPathname(), $outputDir . DIRECTORY_SEPARATOR . $file->getFilename()); }
[ "public", "function", "makeSource", "(", "SplFileInfo", "$", "file", ",", "$", "outputDir", ")", "{", "return", "new", "Source", "(", "$", "file", "->", "getPathname", "(", ")", ",", "$", "outputDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "file", "->", "getFilename", "(", ")", ")", ";", "}" ]
Create a Source from the given file and output dir. @param SplFileInfo $file @param string $outputDir @return Source
[ "Create", "a", "Source", "from", "the", "given", "file", "and", "output", "dir", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Build/Builder.php#L75-L78
parsnick/steak
src/Build/Builder.php
Builder.publish
public function publish(Source $source) { return (new Pipeline($this->app)) ->send($source) ->through($this->publishers) ->then(function (Source $source) { if ($source->isDir()) { $this->build($source->getPathname(), $source->getOutputPathname()); } }); }
php
public function publish(Source $source) { return (new Pipeline($this->app)) ->send($source) ->through($this->publishers) ->then(function (Source $source) { if ($source->isDir()) { $this->build($source->getPathname(), $source->getOutputPathname()); } }); }
[ "public", "function", "publish", "(", "Source", "$", "source", ")", "{", "return", "(", "new", "Pipeline", "(", "$", "this", "->", "app", ")", ")", "->", "send", "(", "$", "source", ")", "->", "through", "(", "$", "this", "->", "publishers", ")", "->", "then", "(", "function", "(", "Source", "$", "source", ")", "{", "if", "(", "$", "source", "->", "isDir", "(", ")", ")", "{", "$", "this", "->", "build", "(", "$", "source", "->", "getPathname", "(", ")", ",", "$", "source", "->", "getOutputPathname", "(", ")", ")", ";", "}", "}", ")", ";", "}" ]
Publish a file / directory. @param Source $source @return bool|mixed
[ "Publish", "a", "file", "/", "directory", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Build/Builder.php#L86-L96
parsnick/steak
src/Build/Builder.php
Builder.clean
public function clean($dir, $preserveGit = false) { $filesystem = new Filesystem(); if ( ! $filesystem->exists($dir)) { return $filesystem->makeDirectory($dir, 0755, true); } foreach (new FilesystemIterator($dir) as $file) { if ($preserveGit && $file->getFilename() == '.git') { continue; } if ($file->isDir() && ! $file->isLink()) { $filesystem->deleteDirectory($file); } else { $filesystem->delete($file); } } return true; }
php
public function clean($dir, $preserveGit = false) { $filesystem = new Filesystem(); if ( ! $filesystem->exists($dir)) { return $filesystem->makeDirectory($dir, 0755, true); } foreach (new FilesystemIterator($dir) as $file) { if ($preserveGit && $file->getFilename() == '.git') { continue; } if ($file->isDir() && ! $file->isLink()) { $filesystem->deleteDirectory($file); } else { $filesystem->delete($file); } } return true; }
[ "public", "function", "clean", "(", "$", "dir", ",", "$", "preserveGit", "=", "false", ")", "{", "$", "filesystem", "=", "new", "Filesystem", "(", ")", ";", "if", "(", "!", "$", "filesystem", "->", "exists", "(", "$", "dir", ")", ")", "{", "return", "$", "filesystem", "->", "makeDirectory", "(", "$", "dir", ",", "0755", ",", "true", ")", ";", "}", "foreach", "(", "new", "FilesystemIterator", "(", "$", "dir", ")", "as", "$", "file", ")", "{", "if", "(", "$", "preserveGit", "&&", "$", "file", "->", "getFilename", "(", ")", "==", "'.git'", ")", "{", "continue", ";", "}", "if", "(", "$", "file", "->", "isDir", "(", ")", "&&", "!", "$", "file", "->", "isLink", "(", ")", ")", "{", "$", "filesystem", "->", "deleteDirectory", "(", "$", "file", ")", ";", "}", "else", "{", "$", "filesystem", "->", "delete", "(", "$", "file", ")", ";", "}", "}", "return", "true", ";", "}" ]
Remove the contents of a directory, but not the directory itself. @param string $dir @param bool $preserveGit @return bool
[ "Remove", "the", "contents", "of", "a", "directory", "but", "not", "the", "directory", "itself", "." ]
train
https://github.com/parsnick/steak/blob/461869189a640938438187330f6c50aca97c5ccc/src/Build/Builder.php#L105-L125
dunkelfrosch/phpcoverfish
src/PHPCoverFish/Validator/ValidatorClassNameMethodName.php
ValidatorClassNameMethodName.getMapping
public function getMapping(CoverFishPHPUnitFile $phpUnitFile) { $method = $this->getResult()['method']; $class = $this->getResult()['class']; $classFQN = $this->coverFishHelper->getClassFromUse($class, $phpUnitFile->getUsedClasses()); $mappingOptions = array( 'coverToken' => $this->coversToken, 'coverMethod' => $method, 'coverAccessor' => null, 'coverClass' => $class, 'coverClassFQN' => $classFQN, 'validatorMatch' => $this->getValidationTag(), 'validatorClass' => get_class($this) ); return $this->setMapping($mappingOptions); }
php
public function getMapping(CoverFishPHPUnitFile $phpUnitFile) { $method = $this->getResult()['method']; $class = $this->getResult()['class']; $classFQN = $this->coverFishHelper->getClassFromUse($class, $phpUnitFile->getUsedClasses()); $mappingOptions = array( 'coverToken' => $this->coversToken, 'coverMethod' => $method, 'coverAccessor' => null, 'coverClass' => $class, 'coverClassFQN' => $classFQN, 'validatorMatch' => $this->getValidationTag(), 'validatorClass' => get_class($this) ); return $this->setMapping($mappingOptions); }
[ "public", "function", "getMapping", "(", "CoverFishPHPUnitFile", "$", "phpUnitFile", ")", "{", "$", "method", "=", "$", "this", "->", "getResult", "(", ")", "[", "'method'", "]", ";", "$", "class", "=", "$", "this", "->", "getResult", "(", ")", "[", "'class'", "]", ";", "$", "classFQN", "=", "$", "this", "->", "coverFishHelper", "->", "getClassFromUse", "(", "$", "class", ",", "$", "phpUnitFile", "->", "getUsedClasses", "(", ")", ")", ";", "$", "mappingOptions", "=", "array", "(", "'coverToken'", "=>", "$", "this", "->", "coversToken", ",", "'coverMethod'", "=>", "$", "method", ",", "'coverAccessor'", "=>", "null", ",", "'coverClass'", "=>", "$", "class", ",", "'coverClassFQN'", "=>", "$", "classFQN", ",", "'validatorMatch'", "=>", "$", "this", "->", "getValidationTag", "(", ")", ",", "'validatorClass'", "=>", "get_class", "(", "$", "this", ")", ")", ";", "return", "$", "this", "->", "setMapping", "(", "$", "mappingOptions", ")", ";", "}" ]
@param CoverFishPHPUnitFile $phpUnitFile @return CoverFishMapping
[ "@param", "CoverFishPHPUnitFile", "$phpUnitFile" ]
train
https://github.com/dunkelfrosch/phpcoverfish/blob/779bd399ec8f4cadb3b7854200695c5eb3f5a8ad/src/PHPCoverFish/Validator/ValidatorClassNameMethodName.php#L56-L73
simple-php-mvc/simple-php-mvc
src/MVC/DataBase/PDO.php
PDO.__getInstance
public static function __getInstance($dsn, $user = null, $passwd = null, array $driverOptions = array()) { if (!self::$instance) { self::$instance = new self($dsn, $user, $passwd, $driverOptions); } return self::$instance; }
php
public static function __getInstance($dsn, $user = null, $passwd = null, array $driverOptions = array()) { if (!self::$instance) { self::$instance = new self($dsn, $user, $passwd, $driverOptions); } return self::$instance; }
[ "public", "static", "function", "__getInstance", "(", "$", "dsn", ",", "$", "user", "=", "null", ",", "$", "passwd", "=", "null", ",", "array", "$", "driverOptions", "=", "array", "(", ")", ")", "{", "if", "(", "!", "self", "::", "$", "instance", ")", "{", "self", "::", "$", "instance", "=", "new", "self", "(", "$", "dsn", ",", "$", "user", ",", "$", "passwd", ",", "$", "driverOptions", ")", ";", "}", "return", "self", "::", "$", "instance", ";", "}" ]
Get the instance of the class @access public @param string $dsn URI of the driver @param string $user Connection user @param string $passwd Connection password @param array $driverOptions Driver options @return PDO
[ "Get", "the", "instance", "of", "the", "class" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/DataBase/PDO.php#L85-L91
simple-php-mvc/simple-php-mvc
src/MVC/DataBase/PDO.php
PDO.prepare
public function prepare($sql, array $driverOptions = array()) { $this->numStatements++; $pdos = $this->_pdo->prepare($sql, $driverOptions); return new PDOStatement($this, $pdos); }
php
public function prepare($sql, array $driverOptions = array()) { $this->numStatements++; $pdos = $this->_pdo->prepare($sql, $driverOptions); return new PDOStatement($this, $pdos); }
[ "public", "function", "prepare", "(", "$", "sql", ",", "array", "$", "driverOptions", "=", "array", "(", ")", ")", "{", "$", "this", "->", "numStatements", "++", ";", "$", "pdos", "=", "$", "this", "->", "_pdo", "->", "prepare", "(", "$", "sql", ",", "$", "driverOptions", ")", ";", "return", "new", "PDOStatement", "(", "$", "this", ",", "$", "pdos", ")", ";", "}" ]
Prepare the statement SQL @access public @param string $sql Statement SQL @param srray $driverOptions Driver options @return PDOStatement
[ "Prepare", "the", "statement", "SQL" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/DataBase/PDO.php#L100-L107
simple-php-mvc/simple-php-mvc
src/MVC/DataBase/PDO.php
PDO.query
public function query($sql) { $this->numExecutes++; $this->numStatements++; $pdos = $this->_pdo->query($sql); return new PDOStatement($this, $pdos); }
php
public function query($sql) { $this->numExecutes++; $this->numStatements++; $pdos = $this->_pdo->query($sql); return new PDOStatement($this, $pdos); }
[ "public", "function", "query", "(", "$", "sql", ")", "{", "$", "this", "->", "numExecutes", "++", ";", "$", "this", "->", "numStatements", "++", ";", "$", "pdos", "=", "$", "this", "->", "_pdo", "->", "query", "(", "$", "sql", ")", ";", "return", "new", "PDOStatement", "(", "$", "this", ",", "$", "pdos", ")", ";", "}" ]
Executes the statement query @access public @param string $sql Statement SQL @return PDOStatement
[ "Executes", "the", "statement", "query" ]
train
https://github.com/simple-php-mvc/simple-php-mvc/blob/e319eb09d29afad6993acb4a7e35f32a87dd0841/src/MVC/DataBase/PDO.php#L115-L123
nyeholt/silverstripe-external-content
code/transform/ExternalContentImporter.php
ExternalContentImporter.import
public function import($contentItem, $target, $includeParent = false, $includeChildren = true, $duplicateStrategy='Overwrite', $params = array()) { $this->runOnImportStart(); $this->params = $params; // if the queuedjobs module exists, use that $queuedVersion = 'Queued' . get_class($this); if ($this->config()->use_queue && ClassInfo::exists('QueuedJob') && ClassInfo::exists($queuedVersion)) { $importer = new $queuedVersion( $contentItem, $target, $includeParent, $includeChildren, $duplicateStrategy, $params); $service = singleton('QueuedJobService'); $service->queueJob($importer); return $importer; } $children = null; if ($includeParent) { // Get the children of a particular node $children = new ArrayList(); $children->push($contentItem); } else { $children = $contentItem->stageChildren(); } $this->importChildren($children, $target, $includeChildren, $duplicateStrategy); $this->runOnImportEnd(); return true; }
php
public function import($contentItem, $target, $includeParent = false, $includeChildren = true, $duplicateStrategy='Overwrite', $params = array()) { $this->runOnImportStart(); $this->params = $params; // if the queuedjobs module exists, use that $queuedVersion = 'Queued' . get_class($this); if ($this->config()->use_queue && ClassInfo::exists('QueuedJob') && ClassInfo::exists($queuedVersion)) { $importer = new $queuedVersion( $contentItem, $target, $includeParent, $includeChildren, $duplicateStrategy, $params); $service = singleton('QueuedJobService'); $service->queueJob($importer); return $importer; } $children = null; if ($includeParent) { // Get the children of a particular node $children = new ArrayList(); $children->push($contentItem); } else { $children = $contentItem->stageChildren(); } $this->importChildren($children, $target, $includeChildren, $duplicateStrategy); $this->runOnImportEnd(); return true; }
[ "public", "function", "import", "(", "$", "contentItem", ",", "$", "target", ",", "$", "includeParent", "=", "false", ",", "$", "includeChildren", "=", "true", ",", "$", "duplicateStrategy", "=", "'Overwrite'", ",", "$", "params", "=", "array", "(", ")", ")", "{", "$", "this", "->", "runOnImportStart", "(", ")", ";", "$", "this", "->", "params", "=", "$", "params", ";", "// if the queuedjobs module exists, use that", "$", "queuedVersion", "=", "'Queued'", ".", "get_class", "(", "$", "this", ")", ";", "if", "(", "$", "this", "->", "config", "(", ")", "->", "use_queue", "&&", "ClassInfo", "::", "exists", "(", "'QueuedJob'", ")", "&&", "ClassInfo", "::", "exists", "(", "$", "queuedVersion", ")", ")", "{", "$", "importer", "=", "new", "$", "queuedVersion", "(", "$", "contentItem", ",", "$", "target", ",", "$", "includeParent", ",", "$", "includeChildren", ",", "$", "duplicateStrategy", ",", "$", "params", ")", ";", "$", "service", "=", "singleton", "(", "'QueuedJobService'", ")", ";", "$", "service", "->", "queueJob", "(", "$", "importer", ")", ";", "return", "$", "importer", ";", "}", "$", "children", "=", "null", ";", "if", "(", "$", "includeParent", ")", "{", "// Get the children of a particular node", "$", "children", "=", "new", "ArrayList", "(", ")", ";", "$", "children", "->", "push", "(", "$", "contentItem", ")", ";", "}", "else", "{", "$", "children", "=", "$", "contentItem", "->", "stageChildren", "(", ")", ";", "}", "$", "this", "->", "importChildren", "(", "$", "children", ",", "$", "target", ",", "$", "includeChildren", ",", "$", "duplicateStrategy", ")", ";", "$", "this", "->", "runOnImportEnd", "(", ")", ";", "return", "true", ";", "}" ]
Import from a content source to a particular target @param ExternalContentItem $contentItem @param SiteTree $target @param boolean $includeParent Whether to include the selected item in the import or not @param String $duplicateStrategy How to handle duplication @param array $params All parameters passed with the import request.
[ "Import", "from", "a", "content", "source", "to", "a", "particular", "target" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/code/transform/ExternalContentImporter.php#L34-L66
nyeholt/silverstripe-external-content
code/transform/ExternalContentImporter.php
ExternalContentImporter.importChildren
protected function importChildren($children, $parent, $includeChildren, $duplicateStrategy) { if (!$children) { return; } // get the importer to use, import, then see if there's any foreach ($children as $child) { $pageType = $this->getExternalType($child); if (isset($this->contentTransforms[$pageType])) { $transformer = $this->contentTransforms[$pageType]; $result = $transformer->transform($child, $parent, $duplicateStrategy); $this->extend('onAfterImport', $result); // if there's more, then transform them if ($includeChildren && $result && $result->children && count($result->children)) { // import the children $this->importChildren($result->children, $result->page, $includeChildren, $duplicateStrategy); } } } }
php
protected function importChildren($children, $parent, $includeChildren, $duplicateStrategy) { if (!$children) { return; } // get the importer to use, import, then see if there's any foreach ($children as $child) { $pageType = $this->getExternalType($child); if (isset($this->contentTransforms[$pageType])) { $transformer = $this->contentTransforms[$pageType]; $result = $transformer->transform($child, $parent, $duplicateStrategy); $this->extend('onAfterImport', $result); // if there's more, then transform them if ($includeChildren && $result && $result->children && count($result->children)) { // import the children $this->importChildren($result->children, $result->page, $includeChildren, $duplicateStrategy); } } } }
[ "protected", "function", "importChildren", "(", "$", "children", ",", "$", "parent", ",", "$", "includeChildren", ",", "$", "duplicateStrategy", ")", "{", "if", "(", "!", "$", "children", ")", "{", "return", ";", "}", "// get the importer to use, import, then see if there's any", "foreach", "(", "$", "children", "as", "$", "child", ")", "{", "$", "pageType", "=", "$", "this", "->", "getExternalType", "(", "$", "child", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "contentTransforms", "[", "$", "pageType", "]", ")", ")", "{", "$", "transformer", "=", "$", "this", "->", "contentTransforms", "[", "$", "pageType", "]", ";", "$", "result", "=", "$", "transformer", "->", "transform", "(", "$", "child", ",", "$", "parent", ",", "$", "duplicateStrategy", ")", ";", "$", "this", "->", "extend", "(", "'onAfterImport'", ",", "$", "result", ")", ";", "// if there's more, then transform them", "if", "(", "$", "includeChildren", "&&", "$", "result", "&&", "$", "result", "->", "children", "&&", "count", "(", "$", "result", "->", "children", ")", ")", "{", "// import the children", "$", "this", "->", "importChildren", "(", "$", "result", "->", "children", ",", "$", "result", "->", "page", ",", "$", "includeChildren", ",", "$", "duplicateStrategy", ")", ";", "}", "}", "}", "}" ]
Execute the importing of several children @param DataObjectSet $children @param SiteTree $parent
[ "Execute", "the", "importing", "of", "several", "children" ]
train
https://github.com/nyeholt/silverstripe-external-content/blob/1c6da8c56ef717225ff904e1522aff94ed051601/code/transform/ExternalContentImporter.php#L74-L95
spiral-modules/scaffolder
source/Scaffolder/Declarations/Database/RecordDeclaration.php
RecordDeclaration.normalizeDeclaration
public function normalizeDeclaration() { if (empty($this->getTable())) { $this->getConstants()->remove('TABLE'); } if (empty($this->getDatabase())) { $this->getConstants()->remove('DATABASE'); } return $this; }
php
public function normalizeDeclaration() { if (empty($this->getTable())) { $this->getConstants()->remove('TABLE'); } if (empty($this->getDatabase())) { $this->getConstants()->remove('DATABASE'); } return $this; }
[ "public", "function", "normalizeDeclaration", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "getTable", "(", ")", ")", ")", "{", "$", "this", "->", "getConstants", "(", ")", "->", "remove", "(", "'TABLE'", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "getDatabase", "(", ")", ")", ")", "{", "$", "this", "->", "getConstants", "(", ")", "->", "remove", "(", "'DATABASE'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Drop non required properties and methods @return $this
[ "Drop", "non", "required", "properties", "and", "methods" ]
train
https://github.com/spiral-modules/scaffolder/blob/9be9dd0da6e4b02232db24e797fe5c288afbbddf/source/Scaffolder/Declarations/Database/RecordDeclaration.php#L62-L73
zodream/thirdparty
src/ALi/TaoBaoKe.php
TaoBaoKe.links
public function links($adzone_id, $start_time, $end_time) { $res = $this->getSearch() ->parameters(compact('adzone_id', 'start_time', 'end_time'))->text(); return $res['results']['results']; }
php
public function links($adzone_id, $start_time, $end_time) { $res = $this->getSearch() ->parameters(compact('adzone_id', 'start_time', 'end_time'))->text(); return $res['results']['results']; }
[ "public", "function", "links", "(", "$", "adzone_id", ",", "$", "start_time", ",", "$", "end_time", ")", "{", "$", "res", "=", "$", "this", "->", "getSearch", "(", ")", "->", "parameters", "(", "compact", "(", "'adzone_id'", ",", "'start_time'", ",", "'end_time'", ")", ")", "->", "text", "(", ")", ";", "return", "$", "res", "[", "'results'", "]", "[", "'results'", "]", ";", "}" ]
获取淘抢购的数据,淘客商品转淘客链接 @param $adzone_id @param $start_time @param $end_time @return mixed @throws Exception
[ "获取淘抢购的数据,淘客商品转淘客链接" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/TaoBaoKe.php#L186-L190
zodream/thirdparty
src/ALi/TaoBaoKe.php
TaoBaoKe.convert
public function convert($id, $adzone_id) { $res = $this->getConvert()->parameters([ 'num_iids' => $id, 'adzone_id' => $adzone_id, ])->text(); return $res['results']['n_tbk_item']; }
php
public function convert($id, $adzone_id) { $res = $this->getConvert()->parameters([ 'num_iids' => $id, 'adzone_id' => $adzone_id, ])->text(); return $res['results']['n_tbk_item']; }
[ "public", "function", "convert", "(", "$", "id", ",", "$", "adzone_id", ")", "{", "$", "res", "=", "$", "this", "->", "getConvert", "(", ")", "->", "parameters", "(", "[", "'num_iids'", "=>", "$", "id", ",", "'adzone_id'", "=>", "$", "adzone_id", ",", "]", ")", "->", "text", "(", ")", ";", "return", "$", "res", "[", "'results'", "]", "[", "'n_tbk_item'", "]", ";", "}" ]
获取淘宝客商品链接转换(需要拥有此权限) @param $id @param $adzone_id @return mixed @throws Exception
[ "获取淘宝客商品链接转换", "(", "需要拥有此权限", ")" ]
train
https://github.com/zodream/thirdparty/blob/b9d39087913850f1c5c7c9165105fec22a128f8f/src/ALi/TaoBaoKe.php#L204-L210
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.getBase64Tag
public function getBase64Tag() { if($this->owner->exists()) { $url = $this->owner->getBase64Source(); $title = ($this->owner->Title) ? $this->owner->Title : $this->owner->Filename; if($this->owner->Title) { $title = Convert::raw2att($this->owner->Title); } else { if(preg_match("/([^\/]*)\.[a-zA-Z0-9]{1,6}$/", $title, $matches)) $title = Convert::raw2att($matches[1]); } return "<img src=\"$url\" alt=\"$title\" />"; } }
php
public function getBase64Tag() { if($this->owner->exists()) { $url = $this->owner->getBase64Source(); $title = ($this->owner->Title) ? $this->owner->Title : $this->owner->Filename; if($this->owner->Title) { $title = Convert::raw2att($this->owner->Title); } else { if(preg_match("/([^\/]*)\.[a-zA-Z0-9]{1,6}$/", $title, $matches)) $title = Convert::raw2att($matches[1]); } return "<img src=\"$url\" alt=\"$title\" />"; } }
[ "public", "function", "getBase64Tag", "(", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "$", "url", "=", "$", "this", "->", "owner", "->", "getBase64Source", "(", ")", ";", "$", "title", "=", "(", "$", "this", "->", "owner", "->", "Title", ")", "?", "$", "this", "->", "owner", "->", "Title", ":", "$", "this", "->", "owner", "->", "Filename", ";", "if", "(", "$", "this", "->", "owner", "->", "Title", ")", "{", "$", "title", "=", "Convert", "::", "raw2att", "(", "$", "this", "->", "owner", "->", "Title", ")", ";", "}", "else", "{", "if", "(", "preg_match", "(", "\"/([^\\/]*)\\.[a-zA-Z0-9]{1,6}$/\"", ",", "$", "title", ",", "$", "matches", ")", ")", "$", "title", "=", "Convert", "::", "raw2att", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "return", "\"<img src=\\\"$url\\\" alt=\\\"$title\\\" />\"", ";", "}", "}" ]
Return an XHTML img tag for this Image. @return string
[ "Return", "an", "XHTML", "img", "tag", "for", "this", "Image", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L29-L40
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.getBase64Source
public function getBase64Source(){ $Fullpath = $this->owner->getFullPath(); $cache = SS_Cache::factory('Base64Image'); $cachekey = md5($Fullpath); if(!($Base64Image = $cache->load($cachekey))){ $Base64Image = base64_encode(file_get_contents($Fullpath)); $cache->save($Base64Image); } $type = strtolower($this->owner->getExtension()); return "data:image/".$type.";base64,".$Base64Image; }
php
public function getBase64Source(){ $Fullpath = $this->owner->getFullPath(); $cache = SS_Cache::factory('Base64Image'); $cachekey = md5($Fullpath); if(!($Base64Image = $cache->load($cachekey))){ $Base64Image = base64_encode(file_get_contents($Fullpath)); $cache->save($Base64Image); } $type = strtolower($this->owner->getExtension()); return "data:image/".$type.";base64,".$Base64Image; }
[ "public", "function", "getBase64Source", "(", ")", "{", "$", "Fullpath", "=", "$", "this", "->", "owner", "->", "getFullPath", "(", ")", ";", "$", "cache", "=", "SS_Cache", "::", "factory", "(", "'Base64Image'", ")", ";", "$", "cachekey", "=", "md5", "(", "$", "Fullpath", ")", ";", "if", "(", "!", "(", "$", "Base64Image", "=", "$", "cache", "->", "load", "(", "$", "cachekey", ")", ")", ")", "{", "$", "Base64Image", "=", "base64_encode", "(", "file_get_contents", "(", "$", "Fullpath", ")", ")", ";", "$", "cache", "->", "save", "(", "$", "Base64Image", ")", ";", "}", "$", "type", "=", "strtolower", "(", "$", "this", "->", "owner", "->", "getExtension", "(", ")", ")", ";", "return", "\"data:image/\"", ".", "$", "type", ".", "\";base64,\"", ".", "$", "Base64Image", ";", "}" ]
retrun the Base64 Notation of the Image
[ "retrun", "the", "Base64", "Notation", "of", "the", "Image" ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L45-L58
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.DetectFace
public function DetectFace(){ $detector = new svay\FaceDetector(); $detector->faceDetect($this->owner->getFullPath()); return $detector->getFace(); }
php
public function DetectFace(){ $detector = new svay\FaceDetector(); $detector->faceDetect($this->owner->getFullPath()); return $detector->getFace(); }
[ "public", "function", "DetectFace", "(", ")", "{", "$", "detector", "=", "new", "svay", "\\", "FaceDetector", "(", ")", ";", "$", "detector", "->", "faceDetect", "(", "$", "this", "->", "owner", "->", "getFullPath", "(", ")", ")", ";", "return", "$", "detector", "->", "getFace", "(", ")", ";", "}" ]
Detect a Face inside the image returns null or an Array with x, y coordinates and w = width/height (square) @return Array
[ "Detect", "a", "Face", "inside", "the", "image" ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L66-L70
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.DetectedFace
public function DetectedFace(){ if($this->owner->exists()) { $cacheFile = $this->owner->cacheDetectedFaceFilename(); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { $this->owner->generateDetectedFaceImage(); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
php
public function DetectedFace(){ if($this->owner->exists()) { $cacheFile = $this->owner->cacheDetectedFaceFilename(); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { $this->owner->generateDetectedFaceImage(); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
[ "public", "function", "DetectedFace", "(", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheDetectedFaceFilename", "(", ")", ";", "if", "(", "!", "file_exists", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", "||", "isset", "(", "$", "_GET", "[", "'flush'", "]", ")", ")", "{", "$", "this", "->", "owner", "->", "generateDetectedFaceImage", "(", ")", ";", "}", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "$", "cached", "=", "new", "SecureImage_Cached", "(", "$", "cacheFile", ")", ";", "else", "$", "cached", "=", "new", "Image_Cached", "(", "$", "cacheFile", ")", ";", "// Pass through the title so the templates can use it", "$", "cached", "->", "Title", "=", "$", "this", "->", "owner", "->", "Title", ";", "$", "cached", "->", "ID", "=", "$", "this", "->", "owner", "->", "ID", ";", "$", "cached", "->", "ParentID", "=", "$", "this", "->", "owner", "->", "ParentID", ";", "return", "$", "cached", ";", "}", "}" ]
returns the image with the face marked in a red square @return Image_Cached|SecureImage_Cached
[ "returns", "the", "image", "with", "the", "face", "marked", "in", "a", "red", "square" ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L77-L94
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.cacheDetectedFaceFilename
public function cacheDetectedFaceFilename() { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = 'DetectedFace'; if($this->owner instanceof SecureImage){ $file = pathinfo($this->owner->Name); return $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; }else{ return $folder . "_resampled/".$format."-".$this->owner->Name; } }
php
public function cacheDetectedFaceFilename() { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = 'DetectedFace'; if($this->owner instanceof SecureImage){ $file = pathinfo($this->owner->Name); return $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; }else{ return $folder . "_resampled/".$format."-".$this->owner->Name; } }
[ "public", "function", "cacheDetectedFaceFilename", "(", ")", "{", "$", "folder", "=", "$", "this", "->", "owner", "->", "ParentID", "?", "$", "this", "->", "owner", "->", "Parent", "(", ")", "->", "Filename", ":", "ASSETS_DIR", ".", "\"/\"", ";", "$", "format", "=", "'DetectedFace'", ";", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "{", "$", "file", "=", "pathinfo", "(", "$", "this", "->", "owner", "->", "Name", ")", ";", "return", "$", "folder", ".", "\"_resampled/\"", ".", "md5", "(", "$", "format", ".", "\"-\"", ".", "$", "file", "[", "'filename'", "]", ")", ".", "\".\"", ".", "$", "file", "[", "'extension'", "]", ";", "}", "else", "{", "return", "$", "folder", ".", "\"_resampled/\"", ".", "$", "format", ".", "\"-\"", ".", "$", "this", "->", "owner", "->", "Name", ";", "}", "}" ]
Return the filename for the cached image. @return string
[ "Return", "the", "filename", "for", "the", "cached", "image", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L100-L111
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.generateDetectedFaceImage
public function generateDetectedFaceImage() { $cacheFile = $this->owner->cacheDetectedFaceFilename(); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); if($backend->hasImageResource()){ $backend = $backend->detectedFaceImage($this->DetectFace()); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } } }
php
public function generateDetectedFaceImage() { $cacheFile = $this->owner->cacheDetectedFaceFilename(); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); if($backend->hasImageResource()){ $backend = $backend->detectedFaceImage($this->DetectFace()); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } } }
[ "public", "function", "generateDetectedFaceImage", "(", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheDetectedFaceFilename", "(", ")", ";", "$", "backend", "=", "Injector", "::", "inst", "(", ")", "->", "createWithArgs", "(", "Image", "::", "get_backend", "(", ")", ",", "array", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "this", "->", "owner", "->", "Filename", ")", ")", ";", "if", "(", "$", "backend", "->", "hasImageResource", "(", ")", ")", "{", "$", "backend", "=", "$", "backend", "->", "detectedFaceImage", "(", "$", "this", "->", "DetectFace", "(", ")", ")", ";", "if", "(", "$", "backend", ")", "{", "$", "backend", "->", "writeTo", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", ";", "}", "}", "}" ]
Generate an image on the specified format. It will save the image at the location specified by cacheFilename(). The image will be generated using the specific 'generate' method for the specified format.
[ "Generate", "an", "image", "on", "the", "specified", "format", ".", "It", "will", "save", "the", "image", "at", "the", "location", "specified", "by", "cacheFilename", "()", ".", "The", "image", "will", "be", "generated", "using", "the", "specific", "generate", "method", "for", "the", "specified", "format", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L118-L132
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.TagWithClass
public function TagWithClass($cssclass) { if($this->owner->exists()) { $url = $this->owner->getURL(); $title = ($this->owner->Title) ? $this->owner->Title : $this->owner->Filename; if($this->owner->Title) { $title = Convert::raw2att($this->owner->Title); } else { if(preg_match("/([^\/]*)\.[a-zA-Z0-9]{1,6}$/", $title, $matches)) { $title = Convert::raw2att($matches[1]); } } return "<img src=\"$url\" alt=\"$title\" class=\"$cssclass\" />"; } }
php
public function TagWithClass($cssclass) { if($this->owner->exists()) { $url = $this->owner->getURL(); $title = ($this->owner->Title) ? $this->owner->Title : $this->owner->Filename; if($this->owner->Title) { $title = Convert::raw2att($this->owner->Title); } else { if(preg_match("/([^\/]*)\.[a-zA-Z0-9]{1,6}$/", $title, $matches)) { $title = Convert::raw2att($matches[1]); } } return "<img src=\"$url\" alt=\"$title\" class=\"$cssclass\" />"; } }
[ "public", "function", "TagWithClass", "(", "$", "cssclass", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "$", "url", "=", "$", "this", "->", "owner", "->", "getURL", "(", ")", ";", "$", "title", "=", "(", "$", "this", "->", "owner", "->", "Title", ")", "?", "$", "this", "->", "owner", "->", "Title", ":", "$", "this", "->", "owner", "->", "Filename", ";", "if", "(", "$", "this", "->", "owner", "->", "Title", ")", "{", "$", "title", "=", "Convert", "::", "raw2att", "(", "$", "this", "->", "owner", "->", "Title", ")", ";", "}", "else", "{", "if", "(", "preg_match", "(", "\"/([^\\/]*)\\.[a-zA-Z0-9]{1,6}$/\"", ",", "$", "title", ",", "$", "matches", ")", ")", "{", "$", "title", "=", "Convert", "::", "raw2att", "(", "$", "matches", "[", "1", "]", ")", ";", "}", "}", "return", "\"<img src=\\\"$url\\\" alt=\\\"$title\\\" class=\\\"$cssclass\\\" />\"", ";", "}", "}" ]
Return an XHTML img tag for this Image, or NULL if the image file doesn't exist on the filesystem. @return string
[ "Return", "an", "XHTML", "img", "tag", "for", "this", "Image", "or", "NULL", "if", "the", "image", "file", "doesn", "t", "exist", "on", "the", "filesystem", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L140-L153
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.getMergedImage
public function getMergedImage($format, $padding, $mergeimage) { if($this->owner->exists() && Director::fileExists($mergeimage)) { $cacheFile = $this->owner->cacheMergedFilename($format, $padding, $mergeimage); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { // merge the current image over the given Merging Image if($format == 'over') $this->owner->generateMergedImage($padding, $mergeimage, $this->owner->getFullPath(), $cacheFile); // merge the current image over the given Merging Image else $this->owner->generateMergedImage($padding, $this->owner->getFullPath(), $mergeimage, $cacheFile); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
php
public function getMergedImage($format, $padding, $mergeimage) { if($this->owner->exists() && Director::fileExists($mergeimage)) { $cacheFile = $this->owner->cacheMergedFilename($format, $padding, $mergeimage); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { // merge the current image over the given Merging Image if($format == 'over') $this->owner->generateMergedImage($padding, $mergeimage, $this->owner->getFullPath(), $cacheFile); // merge the current image over the given Merging Image else $this->owner->generateMergedImage($padding, $this->owner->getFullPath(), $mergeimage, $cacheFile); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
[ "public", "function", "getMergedImage", "(", "$", "format", ",", "$", "padding", ",", "$", "mergeimage", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", "&&", "Director", "::", "fileExists", "(", "$", "mergeimage", ")", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheMergedFilename", "(", "$", "format", ",", "$", "padding", ",", "$", "mergeimage", ")", ";", "if", "(", "!", "file_exists", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", "||", "isset", "(", "$", "_GET", "[", "'flush'", "]", ")", ")", "{", "// merge the current image over the given Merging Image", "if", "(", "$", "format", "==", "'over'", ")", "$", "this", "->", "owner", "->", "generateMergedImage", "(", "$", "padding", ",", "$", "mergeimage", ",", "$", "this", "->", "owner", "->", "getFullPath", "(", ")", ",", "$", "cacheFile", ")", ";", "// merge the current image over the given Merging Image", "else", "$", "this", "->", "owner", "->", "generateMergedImage", "(", "$", "padding", ",", "$", "this", "->", "owner", "->", "getFullPath", "(", ")", ",", "$", "mergeimage", ",", "$", "cacheFile", ")", ";", "}", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "$", "cached", "=", "new", "SecureImage_Cached", "(", "$", "cacheFile", ")", ";", "else", "$", "cached", "=", "new", "Image_Cached", "(", "$", "cacheFile", ")", ";", "// Pass through the title so the templates can use it", "$", "cached", "->", "Title", "=", "$", "this", "->", "owner", "->", "Title", ";", "$", "cached", "->", "ID", "=", "$", "this", "->", "owner", "->", "ID", ";", "$", "cached", "->", "ParentID", "=", "$", "this", "->", "owner", "->", "ParentID", ";", "return", "$", "cached", ";", "}", "}" ]
Return an image object representing the merged image. @param type $format @param type $padding @param type $mergeimage @return Image_Cached
[ "Return", "an", "image", "object", "representing", "the", "merged", "image", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L180-L200
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.cacheMergedFilename
public function cacheMergedFilename($format, $padding, $mergedimage) { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = 'merged-'.$format.$padding.md5($mergedimage); // Ermitteln, ob eine der Dateien ein png ist $image_pathinfo = pathinfo($this->owner->Filename); $merge_pathinfo = pathinfo($mergedimage); if($this->owner instanceof SecureImage){ $file = pathinfo($this->owner->Name); if(strtolower($image_pathinfo['extension']) == 'png' || strtolower($merge_pathinfo['extension']) == 'png'){ $mergedName = $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; $mergedName = pathinfo($mergedName); return $mergedName['dirname'].'/'.$mergedName['filename'].'_'.$image_pathinfo['extension'].'.png'; }else{ return $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; } }else{ if(strtolower($image_pathinfo['extension']) == 'png' || strtolower($merge_pathinfo['extension']) == 'png'){ $mergedName = $folder . "_resampled/$format-" . $this->owner->Name; $mergedName = pathinfo($mergedName); return $mergedName['dirname'].'/'.$mergedName['filename'].'_'.$image_pathinfo['extension'].'.png'; }else{ return $folder . "_resampled/$format-" . $this->owner->Name; } } }
php
public function cacheMergedFilename($format, $padding, $mergedimage) { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = 'merged-'.$format.$padding.md5($mergedimage); // Ermitteln, ob eine der Dateien ein png ist $image_pathinfo = pathinfo($this->owner->Filename); $merge_pathinfo = pathinfo($mergedimage); if($this->owner instanceof SecureImage){ $file = pathinfo($this->owner->Name); if(strtolower($image_pathinfo['extension']) == 'png' || strtolower($merge_pathinfo['extension']) == 'png'){ $mergedName = $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; $mergedName = pathinfo($mergedName); return $mergedName['dirname'].'/'.$mergedName['filename'].'_'.$image_pathinfo['extension'].'.png'; }else{ return $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; } }else{ if(strtolower($image_pathinfo['extension']) == 'png' || strtolower($merge_pathinfo['extension']) == 'png'){ $mergedName = $folder . "_resampled/$format-" . $this->owner->Name; $mergedName = pathinfo($mergedName); return $mergedName['dirname'].'/'.$mergedName['filename'].'_'.$image_pathinfo['extension'].'.png'; }else{ return $folder . "_resampled/$format-" . $this->owner->Name; } } }
[ "public", "function", "cacheMergedFilename", "(", "$", "format", ",", "$", "padding", ",", "$", "mergedimage", ")", "{", "$", "folder", "=", "$", "this", "->", "owner", "->", "ParentID", "?", "$", "this", "->", "owner", "->", "Parent", "(", ")", "->", "Filename", ":", "ASSETS_DIR", ".", "\"/\"", ";", "$", "format", "=", "'merged-'", ".", "$", "format", ".", "$", "padding", ".", "md5", "(", "$", "mergedimage", ")", ";", "// Ermitteln, ob eine der Dateien ein png ist", "$", "image_pathinfo", "=", "pathinfo", "(", "$", "this", "->", "owner", "->", "Filename", ")", ";", "$", "merge_pathinfo", "=", "pathinfo", "(", "$", "mergedimage", ")", ";", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "{", "$", "file", "=", "pathinfo", "(", "$", "this", "->", "owner", "->", "Name", ")", ";", "if", "(", "strtolower", "(", "$", "image_pathinfo", "[", "'extension'", "]", ")", "==", "'png'", "||", "strtolower", "(", "$", "merge_pathinfo", "[", "'extension'", "]", ")", "==", "'png'", ")", "{", "$", "mergedName", "=", "$", "folder", ".", "\"_resampled/\"", ".", "md5", "(", "$", "format", ".", "\"-\"", ".", "$", "file", "[", "'filename'", "]", ")", ".", "\".\"", ".", "$", "file", "[", "'extension'", "]", ";", "$", "mergedName", "=", "pathinfo", "(", "$", "mergedName", ")", ";", "return", "$", "mergedName", "[", "'dirname'", "]", ".", "'/'", ".", "$", "mergedName", "[", "'filename'", "]", ".", "'_'", ".", "$", "image_pathinfo", "[", "'extension'", "]", ".", "'.png'", ";", "}", "else", "{", "return", "$", "folder", ".", "\"_resampled/\"", ".", "md5", "(", "$", "format", ".", "\"-\"", ".", "$", "file", "[", "'filename'", "]", ")", ".", "\".\"", ".", "$", "file", "[", "'extension'", "]", ";", "}", "}", "else", "{", "if", "(", "strtolower", "(", "$", "image_pathinfo", "[", "'extension'", "]", ")", "==", "'png'", "||", "strtolower", "(", "$", "merge_pathinfo", "[", "'extension'", "]", ")", "==", "'png'", ")", "{", "$", "mergedName", "=", "$", "folder", ".", "\"_resampled/$format-\"", ".", "$", "this", "->", "owner", "->", "Name", ";", "$", "mergedName", "=", "pathinfo", "(", "$", "mergedName", ")", ";", "return", "$", "mergedName", "[", "'dirname'", "]", ".", "'/'", ".", "$", "mergedName", "[", "'filename'", "]", ".", "'_'", ".", "$", "image_pathinfo", "[", "'extension'", "]", ".", "'.png'", ";", "}", "else", "{", "return", "$", "folder", ".", "\"_resampled/$format-\"", ".", "$", "this", "->", "owner", "->", "Name", ";", "}", "}", "}" ]
Return the filename for the cached image, given it's format name and arguments. @param string $format The format name. @param string $padding @param string $mergedimage (<- path, md5() this) @return string
[ "Return", "the", "filename", "for", "the", "cached", "image", "given", "it", "s", "format", "name", "and", "arguments", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L209-L236
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.generateMergedImage
public function generateMergedImage($padding, $bgImagePath, $overlayImagePath, $cacheFile){ $bgImage = Injector::inst()->createWithArgs(Image::get_backend(), array( $bgImagePath )); $ovImage = Injector::inst()->createWithArgs(Image::get_backend(), array( $overlayImagePath )); $frontImage = $this->owner->generateFit($ovImage, ($bgImage->getWidth() - (2*$padding)), ($bgImage->getHeight() - (2*$padding))); $backend = $bgImage->merge($frontImage); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } }
php
public function generateMergedImage($padding, $bgImagePath, $overlayImagePath, $cacheFile){ $bgImage = Injector::inst()->createWithArgs(Image::get_backend(), array( $bgImagePath )); $ovImage = Injector::inst()->createWithArgs(Image::get_backend(), array( $overlayImagePath )); $frontImage = $this->owner->generateFit($ovImage, ($bgImage->getWidth() - (2*$padding)), ($bgImage->getHeight() - (2*$padding))); $backend = $bgImage->merge($frontImage); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } }
[ "public", "function", "generateMergedImage", "(", "$", "padding", ",", "$", "bgImagePath", ",", "$", "overlayImagePath", ",", "$", "cacheFile", ")", "{", "$", "bgImage", "=", "Injector", "::", "inst", "(", ")", "->", "createWithArgs", "(", "Image", "::", "get_backend", "(", ")", ",", "array", "(", "$", "bgImagePath", ")", ")", ";", "$", "ovImage", "=", "Injector", "::", "inst", "(", ")", "->", "createWithArgs", "(", "Image", "::", "get_backend", "(", ")", ",", "array", "(", "$", "overlayImagePath", ")", ")", ";", "$", "frontImage", "=", "$", "this", "->", "owner", "->", "generateFit", "(", "$", "ovImage", ",", "(", "$", "bgImage", "->", "getWidth", "(", ")", "-", "(", "2", "*", "$", "padding", ")", ")", ",", "(", "$", "bgImage", "->", "getHeight", "(", ")", "-", "(", "2", "*", "$", "padding", ")", ")", ")", ";", "$", "backend", "=", "$", "bgImage", "->", "merge", "(", "$", "frontImage", ")", ";", "if", "(", "$", "backend", ")", "{", "$", "backend", "->", "writeTo", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", ";", "}", "}" ]
genereate the merged image
[ "genereate", "the", "merged", "image" ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L241-L256
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.TransparentPad
public function TransparentPad($width, $height){ return (($this->owner->getWidth() == $width) && ($this->owner->getHeight() == $height)) ? $this->owner : $this->owner->getTransparentFormattedImage('TransparentPad', $width, $height); }
php
public function TransparentPad($width, $height){ return (($this->owner->getWidth() == $width) && ($this->owner->getHeight() == $height)) ? $this->owner : $this->owner->getTransparentFormattedImage('TransparentPad', $width, $height); }
[ "public", "function", "TransparentPad", "(", "$", "width", ",", "$", "height", ")", "{", "return", "(", "(", "$", "this", "->", "owner", "->", "getWidth", "(", ")", "==", "$", "width", ")", "&&", "(", "$", "this", "->", "owner", "->", "getHeight", "(", ")", "==", "$", "height", ")", ")", "?", "$", "this", "->", "owner", ":", "$", "this", "->", "owner", "->", "getTransparentFormattedImage", "(", "'TransparentPad'", ",", "$", "width", ",", "$", "height", ")", ";", "}" ]
Resize this Image by both width and height with transparent Background, using padded resize. Use in templates with $transparentPad. @param type $width @param type $height
[ "Resize", "this", "Image", "by", "both", "width", "and", "height", "with", "transparent", "Background", "using", "padded", "resize", ".", "Use", "in", "templates", "with", "$transparentPad", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L263-L267
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.getTransparentFormattedImage
public function getTransparentFormattedImage($format, $arg1 = null, $arg2 = null) { if($this->owner->exists()) { $cacheFile = $this->owner->cacheTransparentFilename($format, $arg1, $arg2); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { $this->owner->generateTransparentFormattedImage($format, $arg1, $arg2); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
php
public function getTransparentFormattedImage($format, $arg1 = null, $arg2 = null) { if($this->owner->exists()) { $cacheFile = $this->owner->cacheTransparentFilename($format, $arg1, $arg2); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { $this->owner->generateTransparentFormattedImage($format, $arg1, $arg2); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
[ "public", "function", "getTransparentFormattedImage", "(", "$", "format", ",", "$", "arg1", "=", "null", ",", "$", "arg2", "=", "null", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheTransparentFilename", "(", "$", "format", ",", "$", "arg1", ",", "$", "arg2", ")", ";", "if", "(", "!", "file_exists", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", "||", "isset", "(", "$", "_GET", "[", "'flush'", "]", ")", ")", "{", "$", "this", "->", "owner", "->", "generateTransparentFormattedImage", "(", "$", "format", ",", "$", "arg1", ",", "$", "arg2", ")", ";", "}", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "$", "cached", "=", "new", "SecureImage_Cached", "(", "$", "cacheFile", ")", ";", "else", "$", "cached", "=", "new", "Image_Cached", "(", "$", "cacheFile", ")", ";", "// Pass through the title so the templates can use it", "$", "cached", "->", "Title", "=", "$", "this", "->", "owner", "->", "Title", ";", "$", "cached", "->", "ID", "=", "$", "this", "->", "owner", "->", "ID", ";", "$", "cached", "->", "ParentID", "=", "$", "this", "->", "owner", "->", "ParentID", ";", "return", "$", "cached", ";", "}", "}" ]
Return an image object representing the image in the given format. This image will be generated using generateFormattedImage(). The generated image is cached, to flush the cache append ?flush=1 to your URL. @param string $format The name of the format. @param string $arg1 An argument to pass to the generate function. @param string $arg2 A second argument to pass to the generate function. @return Image_Cached
[ "Return", "an", "image", "object", "representing", "the", "image", "in", "the", "given", "format", ".", "This", "image", "will", "be", "generated", "using", "generateFormattedImage", "()", ".", "The", "generated", "image", "is", "cached", "to", "flush", "the", "cache", "append", "?flush", "=", "1", "to", "your", "URL", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L278-L295
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.cacheTransparentFilename
public function cacheTransparentFilename($format, $arg1 = null, $arg2 = null) { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = $format.$arg1.$arg2; if($this->owner instanceof SecureImage){ $file = pathinfo($this->owner->Name); return $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; }else{ return $folder . "_resampled/".$format."-".$this->owner->Name; } }
php
public function cacheTransparentFilename($format, $arg1 = null, $arg2 = null) { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = $format.$arg1.$arg2; if($this->owner instanceof SecureImage){ $file = pathinfo($this->owner->Name); return $folder . "_resampled/".md5($format."-".$file['filename']).".".$file['extension']; }else{ return $folder . "_resampled/".$format."-".$this->owner->Name; } }
[ "public", "function", "cacheTransparentFilename", "(", "$", "format", ",", "$", "arg1", "=", "null", ",", "$", "arg2", "=", "null", ")", "{", "$", "folder", "=", "$", "this", "->", "owner", "->", "ParentID", "?", "$", "this", "->", "owner", "->", "Parent", "(", ")", "->", "Filename", ":", "ASSETS_DIR", ".", "\"/\"", ";", "$", "format", "=", "$", "format", ".", "$", "arg1", ".", "$", "arg2", ";", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "{", "$", "file", "=", "pathinfo", "(", "$", "this", "->", "owner", "->", "Name", ")", ";", "return", "$", "folder", ".", "\"_resampled/\"", ".", "md5", "(", "$", "format", ".", "\"-\"", ".", "$", "file", "[", "'filename'", "]", ")", ".", "\".\"", ".", "$", "file", "[", "'extension'", "]", ";", "}", "else", "{", "return", "$", "folder", ".", "\"_resampled/\"", ".", "$", "format", ".", "\"-\"", ".", "$", "this", "->", "owner", "->", "Name", ";", "}", "}" ]
Return the filename for the cached image, given it's format name and arguments. @param string $format The format name. @param string $arg1 The first argument passed to the generate function. @param string $arg2 The second argument passed to the generate function. @return string
[ "Return", "the", "filename", "for", "the", "cached", "image", "given", "it", "s", "format", "name", "and", "arguments", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L304-L315
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.generateTransparentFormattedImage
public function generateTransparentFormattedImage($format, $arg1 = null, $arg2 = null) { $cacheFile = $this->owner->cacheTransparentFilename($format, $arg1, $arg2); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); if($backend->hasImageResource()){ $generateFunc = "generate$format"; if($this->owner->hasMethod($generateFunc)){ $backend = $this->owner->$generateFunc($backend, $arg1, $arg2); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } } else { USER_ERROR("Image::generateTransparentFormattedImage - Image $format function not found.",E_USER_WARNING); } } }
php
public function generateTransparentFormattedImage($format, $arg1 = null, $arg2 = null) { $cacheFile = $this->owner->cacheTransparentFilename($format, $arg1, $arg2); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); if($backend->hasImageResource()){ $generateFunc = "generate$format"; if($this->owner->hasMethod($generateFunc)){ $backend = $this->owner->$generateFunc($backend, $arg1, $arg2); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } } else { USER_ERROR("Image::generateTransparentFormattedImage - Image $format function not found.",E_USER_WARNING); } } }
[ "public", "function", "generateTransparentFormattedImage", "(", "$", "format", ",", "$", "arg1", "=", "null", ",", "$", "arg2", "=", "null", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheTransparentFilename", "(", "$", "format", ",", "$", "arg1", ",", "$", "arg2", ")", ";", "$", "backend", "=", "Injector", "::", "inst", "(", ")", "->", "createWithArgs", "(", "Image", "::", "get_backend", "(", ")", ",", "array", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "this", "->", "owner", "->", "Filename", ")", ")", ";", "if", "(", "$", "backend", "->", "hasImageResource", "(", ")", ")", "{", "$", "generateFunc", "=", "\"generate$format\"", ";", "if", "(", "$", "this", "->", "owner", "->", "hasMethod", "(", "$", "generateFunc", ")", ")", "{", "$", "backend", "=", "$", "this", "->", "owner", "->", "$", "generateFunc", "(", "$", "backend", ",", "$", "arg1", ",", "$", "arg2", ")", ";", "if", "(", "$", "backend", ")", "{", "$", "backend", "->", "writeTo", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", ";", "}", "}", "else", "{", "USER_ERROR", "(", "\"Image::generateTransparentFormattedImage - Image $format function not found.\"", ",", "E_USER_WARNING", ")", ";", "}", "}", "}" ]
Generate an image on the specified format. It will save the image at the location specified by cacheFilename(). The image will be generated using the specific 'generate' method for the specified format. @param string $format Name of the format to generate. @param string $arg1 Argument to pass to the generate method. @param string $arg2 A second argument to pass to the generate method.
[ "Generate", "an", "image", "on", "the", "specified", "format", ".", "It", "will", "save", "the", "image", "at", "the", "location", "specified", "by", "cacheFilename", "()", ".", "The", "image", "will", "be", "generated", "using", "the", "specific", "generate", "method", "for", "the", "specified", "format", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L325-L344
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.generateTransparentPad
public function generateTransparentPad(Image_Backend $backend, $width, $height) { if(!$backend){ user_error("Image::generateTransparentFormattedImage - generateTransparentPad is being called by legacy code" . " or Image::\$backend is not set.",E_USER_WARNING); }else{ return $backend->transparentPaddedResize($width, $height); } }
php
public function generateTransparentPad(Image_Backend $backend, $width, $height) { if(!$backend){ user_error("Image::generateTransparentFormattedImage - generateTransparentPad is being called by legacy code" . " or Image::\$backend is not set.",E_USER_WARNING); }else{ return $backend->transparentPaddedResize($width, $height); } }
[ "public", "function", "generateTransparentPad", "(", "Image_Backend", "$", "backend", ",", "$", "width", ",", "$", "height", ")", "{", "if", "(", "!", "$", "backend", ")", "{", "user_error", "(", "\"Image::generateTransparentFormattedImage - generateTransparentPad is being called by legacy code\"", ".", "\" or Image::\\$backend is not set.\"", ",", "E_USER_WARNING", ")", ";", "}", "else", "{", "return", "$", "backend", "->", "transparentPaddedResize", "(", "$", "width", ",", "$", "height", ")", ";", "}", "}" ]
Resize this Image by both width and height, using padded resize. Use in templates with $SetSize. @return GD
[ "Resize", "this", "Image", "by", "both", "width", "and", "height", "using", "padded", "resize", ".", "Use", "in", "templates", "with", "$SetSize", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L350-L357
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.getBluredImage
public function getBluredImage($intensity){ if($this->owner->exists()) { $cacheFile = $this->owner->cacheBluredFilename($intensity); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { // blur the current image $this->owner->generateBluredImage($intensity); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
php
public function getBluredImage($intensity){ if($this->owner->exists()) { $cacheFile = $this->owner->cacheBluredFilename($intensity); if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { // blur the current image $this->owner->generateBluredImage($intensity); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
[ "public", "function", "getBluredImage", "(", "$", "intensity", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheBluredFilename", "(", "$", "intensity", ")", ";", "if", "(", "!", "file_exists", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", "||", "isset", "(", "$", "_GET", "[", "'flush'", "]", ")", ")", "{", "// blur the current image", "$", "this", "->", "owner", "->", "generateBluredImage", "(", "$", "intensity", ")", ";", "}", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "$", "cached", "=", "new", "SecureImage_Cached", "(", "$", "cacheFile", ")", ";", "else", "$", "cached", "=", "new", "Image_Cached", "(", "$", "cacheFile", ")", ";", "// Pass through the title so the templates can use it", "$", "cached", "->", "Title", "=", "$", "this", "->", "owner", "->", "Title", ";", "$", "cached", "->", "ID", "=", "$", "this", "->", "owner", "->", "ID", ";", "$", "cached", "->", "ParentID", "=", "$", "this", "->", "owner", "->", "ParentID", ";", "return", "$", "cached", ";", "}", "}" ]
Return an image object representing the blured image. @return Image_Cached
[ "Return", "an", "image", "object", "representing", "the", "blured", "image", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L370-L388
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.generateBluredImage
public function generateBluredImage($intensity){ $cacheFile = $this->owner->cacheBluredFilename($intensity); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); $backend = $backend->blur($intensity); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } }
php
public function generateBluredImage($intensity){ $cacheFile = $this->owner->cacheBluredFilename($intensity); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); $backend = $backend->blur($intensity); if($backend){ $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } }
[ "public", "function", "generateBluredImage", "(", "$", "intensity", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheBluredFilename", "(", "$", "intensity", ")", ";", "$", "backend", "=", "Injector", "::", "inst", "(", ")", "->", "createWithArgs", "(", "Image", "::", "get_backend", "(", ")", ",", "array", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "this", "->", "owner", "->", "Filename", ")", ")", ";", "$", "backend", "=", "$", "backend", "->", "blur", "(", "$", "intensity", ")", ";", "if", "(", "$", "backend", ")", "{", "$", "backend", "->", "writeTo", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", ";", "}", "}" ]
Generate an image on the specified format. It will save the image at the location specified by cacheFilename(). The image will be generated using the specific 'generate' method for the specified format.
[ "Generate", "an", "image", "on", "the", "specified", "format", ".", "It", "will", "save", "the", "image", "at", "the", "location", "specified", "by", "cacheFilename", "()", ".", "The", "image", "will", "be", "generated", "using", "the", "specific", "generate", "method", "for", "the", "specified", "format", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L412-L423
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.ToJPEG
public function ToJPEG($quality = null, $backgroundColor = null) { if (!$quality) $quality = Config::inst()->get('ExtendedImage', 'get_jpeg_default_quality'); if (!$backgroundColor) $backgroundColor = Config::inst()->get('ExtendedImage', 'get_jpeg_default_background_color'); return $this->owner->getJPEGImage($quality, $backgroundColor); }
php
public function ToJPEG($quality = null, $backgroundColor = null) { if (!$quality) $quality = Config::inst()->get('ExtendedImage', 'get_jpeg_default_quality'); if (!$backgroundColor) $backgroundColor = Config::inst()->get('ExtendedImage', 'get_jpeg_default_background_color'); return $this->owner->getJPEGImage($quality, $backgroundColor); }
[ "public", "function", "ToJPEG", "(", "$", "quality", "=", "null", ",", "$", "backgroundColor", "=", "null", ")", "{", "if", "(", "!", "$", "quality", ")", "$", "quality", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "'ExtendedImage'", ",", "'get_jpeg_default_quality'", ")", ";", "if", "(", "!", "$", "backgroundColor", ")", "$", "backgroundColor", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "'ExtendedImage'", ",", "'get_jpeg_default_background_color'", ")", ";", "return", "$", "this", "->", "owner", "->", "getJPEGImage", "(", "$", "quality", ",", "$", "backgroundColor", ")", ";", "}" ]
Generate a jpeg image from the source set quality and backgroundColor for Transparency @param $quality @param $backgroundColor
[ "Generate", "a", "jpeg", "image", "from", "the", "source" ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L433-L440
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.getJPEGImage
public function getJPEGImage($quality, $backgroundColor){ if($this->owner->exists()) { $pathinfo = pathinfo($this->owner->Name); $cacheFile = $this->owner->cacheToJPEGFilename($quality, $backgroundColor, $pathinfo); list($width, $height, $type, $attr) = getimagesize($this->owner->getFullPath()); if($type == IMAGETYPE_JPEG && $quality == 100) return $this->owner; if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { // convert the current file to jpeg $this->owner->generateToJPEGImage($quality, $backgroundColor, $pathinfo, $type); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
php
public function getJPEGImage($quality, $backgroundColor){ if($this->owner->exists()) { $pathinfo = pathinfo($this->owner->Name); $cacheFile = $this->owner->cacheToJPEGFilename($quality, $backgroundColor, $pathinfo); list($width, $height, $type, $attr) = getimagesize($this->owner->getFullPath()); if($type == IMAGETYPE_JPEG && $quality == 100) return $this->owner; if(!file_exists(Director::baseFolder()."/".$cacheFile) || isset($_GET['flush'])) { // convert the current file to jpeg $this->owner->generateToJPEGImage($quality, $backgroundColor, $pathinfo, $type); } if($this->owner instanceof SecureImage) $cached = new SecureImage_Cached($cacheFile); else $cached = new Image_Cached($cacheFile); // Pass through the title so the templates can use it $cached->Title = $this->owner->Title; $cached->ID = $this->owner->ID; $cached->ParentID = $this->owner->ParentID; return $cached; } }
[ "public", "function", "getJPEGImage", "(", "$", "quality", ",", "$", "backgroundColor", ")", "{", "if", "(", "$", "this", "->", "owner", "->", "exists", "(", ")", ")", "{", "$", "pathinfo", "=", "pathinfo", "(", "$", "this", "->", "owner", "->", "Name", ")", ";", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheToJPEGFilename", "(", "$", "quality", ",", "$", "backgroundColor", ",", "$", "pathinfo", ")", ";", "list", "(", "$", "width", ",", "$", "height", ",", "$", "type", ",", "$", "attr", ")", "=", "getimagesize", "(", "$", "this", "->", "owner", "->", "getFullPath", "(", ")", ")", ";", "if", "(", "$", "type", "==", "IMAGETYPE_JPEG", "&&", "$", "quality", "==", "100", ")", "return", "$", "this", "->", "owner", ";", "if", "(", "!", "file_exists", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", "||", "isset", "(", "$", "_GET", "[", "'flush'", "]", ")", ")", "{", "// convert the current file to jpeg", "$", "this", "->", "owner", "->", "generateToJPEGImage", "(", "$", "quality", ",", "$", "backgroundColor", ",", "$", "pathinfo", ",", "$", "type", ")", ";", "}", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "$", "cached", "=", "new", "SecureImage_Cached", "(", "$", "cacheFile", ")", ";", "else", "$", "cached", "=", "new", "Image_Cached", "(", "$", "cacheFile", ")", ";", "// Pass through the title so the templates can use it", "$", "cached", "->", "Title", "=", "$", "this", "->", "owner", "->", "Title", ";", "$", "cached", "->", "ID", "=", "$", "this", "->", "owner", "->", "ID", ";", "$", "cached", "->", "ParentID", "=", "$", "this", "->", "owner", "->", "ParentID", ";", "return", "$", "cached", ";", "}", "}" ]
Return an image object representing the blured image. @return Image_Cached
[ "Return", "an", "image", "object", "representing", "the", "blured", "image", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L446-L473
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.cacheToJPEGFilename
public function cacheToJPEGFilename($quality, $backgroundColor, $pathinfo) { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = $pathinfo['extension'].'tojpeg-'.$quality.'-'.$backgroundColor; if($this->owner instanceof SecureImage){ return $folder . "_resampled/".md5($format."-".$pathinfo['filename']).".jpg"; }else{ return $folder . "_resampled/".$format."-".$pathinfo['filename'].".jpg"; } }
php
public function cacheToJPEGFilename($quality, $backgroundColor, $pathinfo) { $folder = $this->owner->ParentID ? $this->owner->Parent()->Filename : ASSETS_DIR . "/"; $format = $pathinfo['extension'].'tojpeg-'.$quality.'-'.$backgroundColor; if($this->owner instanceof SecureImage){ return $folder . "_resampled/".md5($format."-".$pathinfo['filename']).".jpg"; }else{ return $folder . "_resampled/".$format."-".$pathinfo['filename'].".jpg"; } }
[ "public", "function", "cacheToJPEGFilename", "(", "$", "quality", ",", "$", "backgroundColor", ",", "$", "pathinfo", ")", "{", "$", "folder", "=", "$", "this", "->", "owner", "->", "ParentID", "?", "$", "this", "->", "owner", "->", "Parent", "(", ")", "->", "Filename", ":", "ASSETS_DIR", ".", "\"/\"", ";", "$", "format", "=", "$", "pathinfo", "[", "'extension'", "]", ".", "'tojpeg-'", ".", "$", "quality", ".", "'-'", ".", "$", "backgroundColor", ";", "if", "(", "$", "this", "->", "owner", "instanceof", "SecureImage", ")", "{", "return", "$", "folder", ".", "\"_resampled/\"", ".", "md5", "(", "$", "format", ".", "\"-\"", ".", "$", "pathinfo", "[", "'filename'", "]", ")", ".", "\".jpg\"", ";", "}", "else", "{", "return", "$", "folder", ".", "\"_resampled/\"", ".", "$", "format", ".", "\"-\"", ".", "$", "pathinfo", "[", "'filename'", "]", ".", "\".jpg\"", ";", "}", "}" ]
Return the filename for the cached image. @return string
[ "Return", "the", "filename", "for", "the", "cached", "image", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L479-L489
andrelohmann/silverstripe-extended-image
code/extensions/ExtendedImage.php
ExtendedImage.generateToJPEGImage
public function generateToJPEGImage($quality, $backgroundColor, $pathinfo, $type){ $cacheFile = $this->owner->cacheToJPEGFilename($quality, $backgroundColor, $pathinfo); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); $backend = $backend->toJpeg($backgroundColor, $type); if($backend){ $backend->setQuality($quality); $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } }
php
public function generateToJPEGImage($quality, $backgroundColor, $pathinfo, $type){ $cacheFile = $this->owner->cacheToJPEGFilename($quality, $backgroundColor, $pathinfo); $backend = Injector::inst()->createWithArgs(Image::get_backend(), array( Director::baseFolder()."/" . $this->owner->Filename )); $backend = $backend->toJpeg($backgroundColor, $type); if($backend){ $backend->setQuality($quality); $backend->writeTo(Director::baseFolder()."/" . $cacheFile); } }
[ "public", "function", "generateToJPEGImage", "(", "$", "quality", ",", "$", "backgroundColor", ",", "$", "pathinfo", ",", "$", "type", ")", "{", "$", "cacheFile", "=", "$", "this", "->", "owner", "->", "cacheToJPEGFilename", "(", "$", "quality", ",", "$", "backgroundColor", ",", "$", "pathinfo", ")", ";", "$", "backend", "=", "Injector", "::", "inst", "(", ")", "->", "createWithArgs", "(", "Image", "::", "get_backend", "(", ")", ",", "array", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "this", "->", "owner", "->", "Filename", ")", ")", ";", "$", "backend", "=", "$", "backend", "->", "toJpeg", "(", "$", "backgroundColor", ",", "$", "type", ")", ";", "if", "(", "$", "backend", ")", "{", "$", "backend", "->", "setQuality", "(", "$", "quality", ")", ";", "$", "backend", "->", "writeTo", "(", "Director", "::", "baseFolder", "(", ")", ".", "\"/\"", ".", "$", "cacheFile", ")", ";", "}", "}" ]
Generate an image on the specified format. It will save the image at the location specified by cacheFilename(). The image will be generated using the specific 'generate' method for the specified format.
[ "Generate", "an", "image", "on", "the", "specified", "format", ".", "It", "will", "save", "the", "image", "at", "the", "location", "specified", "by", "cacheFilename", "()", ".", "The", "image", "will", "be", "generated", "using", "the", "specific", "generate", "method", "for", "the", "specified", "format", "." ]
train
https://github.com/andrelohmann/silverstripe-extended-image/blob/178e9142ae8ff63f9bf36464093379f6e836b90b/code/extensions/ExtendedImage.php#L496-L508
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.parseParameters
public function parseParameters(array $parameters = [], $possibleAlias = []) { if (count($parameters) == 0) { $parameters = $this->getPossibleParams(); } $arguments = []; foreach ($parameters as $parameter => $description) { if (strpos($parameter, "=") !== false) { $parameterParts = explode("=", $parameter); if (count($parameterParts) != 2) { throw new CommandsException("Invalid definition for the parameter '$parameter'"); } if (strlen($parameterParts[0]) == "") { throw new CommandsException("Invalid definition for the parameter '$parameter'"); } if (!in_array($parameterParts[1], ['s', 'i', 'l'])) { throw new CommandsException("Incorrect data type on parameter '$parameter'"); } $this->_preparedArguments[$parameterParts[0]] = true; $arguments[$parameterParts[0]] = [ 'have-option' => true, 'option-required' => true, 'data-type' => $parameterParts[1] ]; } else { if (!preg_match('/([a-zA-Z0-9]+)/', $parameter)) { throw new CommandsException("Invalid parameter '$parameter'"); } $this->_preparedArguments[$parameter] = true; $arguments[$parameter] = [ 'have-option' => false, 'option-required' => false ]; } } $param = ''; $paramName = ''; $receivedParams = []; $numberArguments = count($_SERVER['argv']); for ($i = 1; $i < $numberArguments; $i++) { $argv = $_SERVER['argv'][$i]; if (preg_match('#^([\-]{1,2})([a-zA-Z0-9][a-zA-Z0-9\-]*)(=(.*)){0,1}$#', $argv, $matches)) { if (strlen($matches[1]) == 1) { $param = substr($matches[2], 1); $paramName = substr($matches[2], 0, 1); } else { if (strlen($matches[2]) < 2) { throw new CommandsException("Invalid script parameter '$argv'"); } $paramName = $matches[2]; } if (!isset($this->_preparedArguments[$paramName])) { if (!isset($possibleAlias[$paramName])) { throw new CommandsException("Unknown parameter '$paramName'"); } $paramName = $possibleAlias[$paramName]; } if (isset($arguments[$paramName])) { if ($param != '') { $receivedParams[$paramName] = $param; $param = ''; $paramName = ''; } if ($arguments[$paramName]['have-option'] == false) { $receivedParams[$paramName] = true; } elseif (isset($matches[4])) { $receivedParams[$paramName] = $matches[4]; } } } else { $param = $argv; if ($paramName != '') { if (isset($arguments[$paramName])) { if ($param == '') { if ($arguments[$paramName]['have-option'] == true) { throw new CommandsException("The parameter '$paramName' requires an option"); } } } $receivedParams[$paramName] = $param; $param = ''; $paramName = ''; } else { $receivedParams[$i - 1] = $param; $param = ''; } } } $this->_parameters = $receivedParams; return $receivedParams; }
php
public function parseParameters(array $parameters = [], $possibleAlias = []) { if (count($parameters) == 0) { $parameters = $this->getPossibleParams(); } $arguments = []; foreach ($parameters as $parameter => $description) { if (strpos($parameter, "=") !== false) { $parameterParts = explode("=", $parameter); if (count($parameterParts) != 2) { throw new CommandsException("Invalid definition for the parameter '$parameter'"); } if (strlen($parameterParts[0]) == "") { throw new CommandsException("Invalid definition for the parameter '$parameter'"); } if (!in_array($parameterParts[1], ['s', 'i', 'l'])) { throw new CommandsException("Incorrect data type on parameter '$parameter'"); } $this->_preparedArguments[$parameterParts[0]] = true; $arguments[$parameterParts[0]] = [ 'have-option' => true, 'option-required' => true, 'data-type' => $parameterParts[1] ]; } else { if (!preg_match('/([a-zA-Z0-9]+)/', $parameter)) { throw new CommandsException("Invalid parameter '$parameter'"); } $this->_preparedArguments[$parameter] = true; $arguments[$parameter] = [ 'have-option' => false, 'option-required' => false ]; } } $param = ''; $paramName = ''; $receivedParams = []; $numberArguments = count($_SERVER['argv']); for ($i = 1; $i < $numberArguments; $i++) { $argv = $_SERVER['argv'][$i]; if (preg_match('#^([\-]{1,2})([a-zA-Z0-9][a-zA-Z0-9\-]*)(=(.*)){0,1}$#', $argv, $matches)) { if (strlen($matches[1]) == 1) { $param = substr($matches[2], 1); $paramName = substr($matches[2], 0, 1); } else { if (strlen($matches[2]) < 2) { throw new CommandsException("Invalid script parameter '$argv'"); } $paramName = $matches[2]; } if (!isset($this->_preparedArguments[$paramName])) { if (!isset($possibleAlias[$paramName])) { throw new CommandsException("Unknown parameter '$paramName'"); } $paramName = $possibleAlias[$paramName]; } if (isset($arguments[$paramName])) { if ($param != '') { $receivedParams[$paramName] = $param; $param = ''; $paramName = ''; } if ($arguments[$paramName]['have-option'] == false) { $receivedParams[$paramName] = true; } elseif (isset($matches[4])) { $receivedParams[$paramName] = $matches[4]; } } } else { $param = $argv; if ($paramName != '') { if (isset($arguments[$paramName])) { if ($param == '') { if ($arguments[$paramName]['have-option'] == true) { throw new CommandsException("The parameter '$paramName' requires an option"); } } } $receivedParams[$paramName] = $param; $param = ''; $paramName = ''; } else { $receivedParams[$i - 1] = $param; $param = ''; } } } $this->_parameters = $receivedParams; return $receivedParams; }
[ "public", "function", "parseParameters", "(", "array", "$", "parameters", "=", "[", "]", ",", "$", "possibleAlias", "=", "[", "]", ")", "{", "if", "(", "count", "(", "$", "parameters", ")", "==", "0", ")", "{", "$", "parameters", "=", "$", "this", "->", "getPossibleParams", "(", ")", ";", "}", "$", "arguments", "=", "[", "]", ";", "foreach", "(", "$", "parameters", "as", "$", "parameter", "=>", "$", "description", ")", "{", "if", "(", "strpos", "(", "$", "parameter", ",", "\"=\"", ")", "!==", "false", ")", "{", "$", "parameterParts", "=", "explode", "(", "\"=\"", ",", "$", "parameter", ")", ";", "if", "(", "count", "(", "$", "parameterParts", ")", "!=", "2", ")", "{", "throw", "new", "CommandsException", "(", "\"Invalid definition for the parameter '$parameter'\"", ")", ";", "}", "if", "(", "strlen", "(", "$", "parameterParts", "[", "0", "]", ")", "==", "\"\"", ")", "{", "throw", "new", "CommandsException", "(", "\"Invalid definition for the parameter '$parameter'\"", ")", ";", "}", "if", "(", "!", "in_array", "(", "$", "parameterParts", "[", "1", "]", ",", "[", "'s'", ",", "'i'", ",", "'l'", "]", ")", ")", "{", "throw", "new", "CommandsException", "(", "\"Incorrect data type on parameter '$parameter'\"", ")", ";", "}", "$", "this", "->", "_preparedArguments", "[", "$", "parameterParts", "[", "0", "]", "]", "=", "true", ";", "$", "arguments", "[", "$", "parameterParts", "[", "0", "]", "]", "=", "[", "'have-option'", "=>", "true", ",", "'option-required'", "=>", "true", ",", "'data-type'", "=>", "$", "parameterParts", "[", "1", "]", "]", ";", "}", "else", "{", "if", "(", "!", "preg_match", "(", "'/([a-zA-Z0-9]+)/'", ",", "$", "parameter", ")", ")", "{", "throw", "new", "CommandsException", "(", "\"Invalid parameter '$parameter'\"", ")", ";", "}", "$", "this", "->", "_preparedArguments", "[", "$", "parameter", "]", "=", "true", ";", "$", "arguments", "[", "$", "parameter", "]", "=", "[", "'have-option'", "=>", "false", ",", "'option-required'", "=>", "false", "]", ";", "}", "}", "$", "param", "=", "''", ";", "$", "paramName", "=", "''", ";", "$", "receivedParams", "=", "[", "]", ";", "$", "numberArguments", "=", "count", "(", "$", "_SERVER", "[", "'argv'", "]", ")", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "$", "numberArguments", ";", "$", "i", "++", ")", "{", "$", "argv", "=", "$", "_SERVER", "[", "'argv'", "]", "[", "$", "i", "]", ";", "if", "(", "preg_match", "(", "'#^([\\-]{1,2})([a-zA-Z0-9][a-zA-Z0-9\\-]*)(=(.*)){0,1}$#'", ",", "$", "argv", ",", "$", "matches", ")", ")", "{", "if", "(", "strlen", "(", "$", "matches", "[", "1", "]", ")", "==", "1", ")", "{", "$", "param", "=", "substr", "(", "$", "matches", "[", "2", "]", ",", "1", ")", ";", "$", "paramName", "=", "substr", "(", "$", "matches", "[", "2", "]", ",", "0", ",", "1", ")", ";", "}", "else", "{", "if", "(", "strlen", "(", "$", "matches", "[", "2", "]", ")", "<", "2", ")", "{", "throw", "new", "CommandsException", "(", "\"Invalid script parameter '$argv'\"", ")", ";", "}", "$", "paramName", "=", "$", "matches", "[", "2", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "_preparedArguments", "[", "$", "paramName", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "possibleAlias", "[", "$", "paramName", "]", ")", ")", "{", "throw", "new", "CommandsException", "(", "\"Unknown parameter '$paramName'\"", ")", ";", "}", "$", "paramName", "=", "$", "possibleAlias", "[", "$", "paramName", "]", ";", "}", "if", "(", "isset", "(", "$", "arguments", "[", "$", "paramName", "]", ")", ")", "{", "if", "(", "$", "param", "!=", "''", ")", "{", "$", "receivedParams", "[", "$", "paramName", "]", "=", "$", "param", ";", "$", "param", "=", "''", ";", "$", "paramName", "=", "''", ";", "}", "if", "(", "$", "arguments", "[", "$", "paramName", "]", "[", "'have-option'", "]", "==", "false", ")", "{", "$", "receivedParams", "[", "$", "paramName", "]", "=", "true", ";", "}", "elseif", "(", "isset", "(", "$", "matches", "[", "4", "]", ")", ")", "{", "$", "receivedParams", "[", "$", "paramName", "]", "=", "$", "matches", "[", "4", "]", ";", "}", "}", "}", "else", "{", "$", "param", "=", "$", "argv", ";", "if", "(", "$", "paramName", "!=", "''", ")", "{", "if", "(", "isset", "(", "$", "arguments", "[", "$", "paramName", "]", ")", ")", "{", "if", "(", "$", "param", "==", "''", ")", "{", "if", "(", "$", "arguments", "[", "$", "paramName", "]", "[", "'have-option'", "]", "==", "true", ")", "{", "throw", "new", "CommandsException", "(", "\"The parameter '$paramName' requires an option\"", ")", ";", "}", "}", "}", "$", "receivedParams", "[", "$", "paramName", "]", "=", "$", "param", ";", "$", "param", "=", "''", ";", "$", "paramName", "=", "''", ";", "}", "else", "{", "$", "receivedParams", "[", "$", "i", "-", "1", "]", "=", "$", "param", ";", "$", "param", "=", "''", ";", "}", "}", "}", "$", "this", "->", "_parameters", "=", "$", "receivedParams", ";", "return", "$", "receivedParams", ";", "}" ]
Parse the parameters passed to the script. @param array $parameters Command parameters @param array $possibleAlias Command aliases @return array @throws CommandsException @todo Refactor
[ "Parse", "the", "parameters", "passed", "to", "the", "script", "." ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L156-L254
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.checkRequired
public function checkRequired($required) { foreach ($required as $fieldRequired) { if (!isset($this->_parameters[$fieldRequired])) { throw new CommandsException("The parameter '$fieldRequired' is required for this script"); } } }
php
public function checkRequired($required) { foreach ($required as $fieldRequired) { if (!isset($this->_parameters[$fieldRequired])) { throw new CommandsException("The parameter '$fieldRequired' is required for this script"); } } }
[ "public", "function", "checkRequired", "(", "$", "required", ")", "{", "foreach", "(", "$", "required", "as", "$", "fieldRequired", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_parameters", "[", "$", "fieldRequired", "]", ")", ")", "{", "throw", "new", "CommandsException", "(", "\"The parameter '$fieldRequired' is required for this script\"", ")", ";", "}", "}", "}" ]
Check that a set of parameters has been received. @param $required @throws CommandsException
[ "Check", "that", "a", "set", "of", "parameters", "has", "been", "received", "." ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L263-L270
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.showHelp
public function showHelp($possibleParameters) { echo get_class($this).' - Usage:'.PHP_EOL.PHP_EOL; foreach ($possibleParameters as $parameter => $description) { echo html_entity_decode($description, ENT_COMPAT, $this->_encoding).PHP_EOL; } }
php
public function showHelp($possibleParameters) { echo get_class($this).' - Usage:'.PHP_EOL.PHP_EOL; foreach ($possibleParameters as $parameter => $description) { echo html_entity_decode($description, ENT_COMPAT, $this->_encoding).PHP_EOL; } }
[ "public", "function", "showHelp", "(", "$", "possibleParameters", ")", "{", "echo", "get_class", "(", "$", "this", ")", ".", "' - Usage:'", ".", "PHP_EOL", ".", "PHP_EOL", ";", "foreach", "(", "$", "possibleParameters", "as", "$", "parameter", "=>", "$", "description", ")", "{", "echo", "html_entity_decode", "(", "$", "description", ",", "ENT_COMPAT", ",", "$", "this", "->", "_encoding", ")", ".", "PHP_EOL", ";", "}", "}" ]
Displays help for the script. @param array $possibleParameters
[ "Displays", "help", "for", "the", "script", "." ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L290-L296
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.getOptions
public function getOptions($filters = null) { if (!$filters) { return $this->_parameters; } $result = []; foreach ($this->_parameters as $param) { $result[] = $this->filter($param, $filters); } return $result; }
php
public function getOptions($filters = null) { if (!$filters) { return $this->_parameters; } $result = []; foreach ($this->_parameters as $param) { $result[] = $this->filter($param, $filters); } return $result; }
[ "public", "function", "getOptions", "(", "$", "filters", "=", "null", ")", "{", "if", "(", "!", "$", "filters", ")", "{", "return", "$", "this", "->", "_parameters", ";", "}", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "_parameters", "as", "$", "param", ")", "{", "$", "result", "[", "]", "=", "$", "this", "->", "filter", "(", "$", "param", ",", "$", "filters", ")", ";", "}", "return", "$", "result", ";", "}" ]
Returns all received options. @param mixed $filters Filter name or array of filters [Optional] @return array
[ "Returns", "all", "received", "options", "." ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L305-L318
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.getOption
public function getOption($option, $filters = null, $defaultValue = null) { if (is_array($option)) { foreach ($option as $optionItem) { if (isset($this->_parameters[$optionItem])) { if ($filters !== null) { return $this->filter($this->_parameters[$optionItem], $filters); } return $this->_parameters[$optionItem]; } } return $defaultValue; } if (isset($this->_parameters[$option])) { if ($filters !== null) { return $this->filter($this->_parameters[$option], $filters); } return $this->_parameters[$option]; } return $defaultValue; }
php
public function getOption($option, $filters = null, $defaultValue = null) { if (is_array($option)) { foreach ($option as $optionItem) { if (isset($this->_parameters[$optionItem])) { if ($filters !== null) { return $this->filter($this->_parameters[$optionItem], $filters); } return $this->_parameters[$optionItem]; } } return $defaultValue; } if (isset($this->_parameters[$option])) { if ($filters !== null) { return $this->filter($this->_parameters[$option], $filters); } return $this->_parameters[$option]; } return $defaultValue; }
[ "public", "function", "getOption", "(", "$", "option", ",", "$", "filters", "=", "null", ",", "$", "defaultValue", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "option", ")", ")", "{", "foreach", "(", "$", "option", "as", "$", "optionItem", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_parameters", "[", "$", "optionItem", "]", ")", ")", "{", "if", "(", "$", "filters", "!==", "null", ")", "{", "return", "$", "this", "->", "filter", "(", "$", "this", "->", "_parameters", "[", "$", "optionItem", "]", ",", "$", "filters", ")", ";", "}", "return", "$", "this", "->", "_parameters", "[", "$", "optionItem", "]", ";", "}", "}", "return", "$", "defaultValue", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "_parameters", "[", "$", "option", "]", ")", ")", "{", "if", "(", "$", "filters", "!==", "null", ")", "{", "return", "$", "this", "->", "filter", "(", "$", "this", "->", "_parameters", "[", "$", "option", "]", ",", "$", "filters", ")", ";", "}", "return", "$", "this", "->", "_parameters", "[", "$", "option", "]", ";", "}", "return", "$", "defaultValue", ";", "}" ]
Returns the value of an option received. @param mixed $option Option name or array of options @param mixed $filters Filter name or array of filters [Optional] @param mixed $defaultValue Default value [Optional] @return mixed
[ "Returns", "the", "value", "of", "an", "option", "received", "." ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L329-L354
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.isReceivedOption
public function isReceivedOption($option) { if (!is_array($option)) { $option = [$option]; } foreach ($option as $op) { if (isset($this->_parameters[$op])) { return true; } } return false; }
php
public function isReceivedOption($option) { if (!is_array($option)) { $option = [$option]; } foreach ($option as $op) { if (isset($this->_parameters[$op])) { return true; } } return false; }
[ "public", "function", "isReceivedOption", "(", "$", "option", ")", "{", "if", "(", "!", "is_array", "(", "$", "option", ")", ")", "{", "$", "option", "=", "[", "$", "option", "]", ";", "}", "foreach", "(", "$", "option", "as", "$", "op", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_parameters", "[", "$", "op", "]", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Indicates whether the script was a particular option. @param string $option @return boolean
[ "Indicates", "whether", "the", "script", "was", "a", "particular", "option", "." ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L362-L375
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.getLastUnNamedParam
public function getLastUnNamedParam() { foreach (array_reverse($this->_parameters) as $key => $value) { if (is_numeric($key)) { return $value; } } return false; }
php
public function getLastUnNamedParam() { foreach (array_reverse($this->_parameters) as $key => $value) { if (is_numeric($key)) { return $value; } } return false; }
[ "public", "function", "getLastUnNamedParam", "(", ")", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "_parameters", ")", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "{", "return", "$", "value", ";", "}", "}", "return", "false", ";", "}" ]
Gets the last parameter is not associated with any parameter name. @return string
[ "Gets", "the", "last", "parameter", "is", "not", "associated", "with", "any", "parameter", "name", "." ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L397-L406
SachaMorard/phalcon-console
Library/Phalcon/Commands/Command.php
Command.printParameters
public function printParameters($parameters) { $length = 0; foreach ($parameters as $parameter => $description) { if ($length == 0) { $length = strlen($parameter); } if (strlen($parameter) > $length) { $length = strlen($parameter); } } print Color::head('Options:') . PHP_EOL; foreach ($parameters as $parameter => $description) { print Color::colorize(' --' . $parameter . str_repeat(' ', $length - strlen($parameter)), Color::FG_GREEN); print Color::colorize(" " . $description) . PHP_EOL; } }
php
public function printParameters($parameters) { $length = 0; foreach ($parameters as $parameter => $description) { if ($length == 0) { $length = strlen($parameter); } if (strlen($parameter) > $length) { $length = strlen($parameter); } } print Color::head('Options:') . PHP_EOL; foreach ($parameters as $parameter => $description) { print Color::colorize(' --' . $parameter . str_repeat(' ', $length - strlen($parameter)), Color::FG_GREEN); print Color::colorize(" " . $description) . PHP_EOL; } }
[ "public", "function", "printParameters", "(", "$", "parameters", ")", "{", "$", "length", "=", "0", ";", "foreach", "(", "$", "parameters", "as", "$", "parameter", "=>", "$", "description", ")", "{", "if", "(", "$", "length", "==", "0", ")", "{", "$", "length", "=", "strlen", "(", "$", "parameter", ")", ";", "}", "if", "(", "strlen", "(", "$", "parameter", ")", ">", "$", "length", ")", "{", "$", "length", "=", "strlen", "(", "$", "parameter", ")", ";", "}", "}", "print", "Color", "::", "head", "(", "'Options:'", ")", ".", "PHP_EOL", ";", "foreach", "(", "$", "parameters", "as", "$", "parameter", "=>", "$", "description", ")", "{", "print", "Color", "::", "colorize", "(", "' --'", ".", "$", "parameter", ".", "str_repeat", "(", "' '", ",", "$", "length", "-", "strlen", "(", "$", "parameter", ")", ")", ",", "Color", "::", "FG_GREEN", ")", ";", "print", "Color", "::", "colorize", "(", "\" \"", ".", "$", "description", ")", ".", "PHP_EOL", ";", "}", "}" ]
Prints the available options in the script @param array $parameters
[ "Prints", "the", "available", "options", "in", "the", "script" ]
train
https://github.com/SachaMorard/phalcon-console/blob/a7922e4c488ea19bc0ecce793e6f01cf9cf3c0c3/Library/Phalcon/Commands/Command.php#L425-L442
seeruo/framework
src/Command/CreateCommand.php
CreateCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { try { $output->writeln([ 'File Creator', '=====================', ]); $filename = $input->getArgument('filename'); $this->create($filename); $output->writeln('Create <bg=yellow;>'.$filename.'.md</> <options=bold>Success!!!</>'); $output->writeln(''); } catch (Exception $e) { $output->writeln('<bg=red;>'.$e->getMessage().'</> <options=bold></>'); $output->writeln(''); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { try { $output->writeln([ 'File Creator', '=====================', ]); $filename = $input->getArgument('filename'); $this->create($filename); $output->writeln('Create <bg=yellow;>'.$filename.'.md</> <options=bold>Success!!!</>'); $output->writeln(''); } catch (Exception $e) { $output->writeln('<bg=red;>'.$e->getMessage().'</> <options=bold></>'); $output->writeln(''); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "try", "{", "$", "output", "->", "writeln", "(", "[", "'File Creator'", ",", "'====================='", ",", "]", ")", ";", "$", "filename", "=", "$", "input", "->", "getArgument", "(", "'filename'", ")", ";", "$", "this", "->", "create", "(", "$", "filename", ")", ";", "$", "output", "->", "writeln", "(", "'Create <bg=yellow;>'", ".", "$", "filename", ".", "'.md</> <options=bold>Success!!!</>'", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "output", "->", "writeln", "(", "'<bg=red;>'", ".", "$", "e", "->", "getMessage", "(", ")", ".", "'</> <options=bold></>'", ")", ";", "$", "output", "->", "writeln", "(", "''", ")", ";", "}", "}" ]
[执行命令] @DateTime 2018-12-13 @param InputInterface $input 输入对象 @param OutputInterface $output 输出对象
[ "[", "执行命令", "]" ]
train
https://github.com/seeruo/framework/blob/689c6e95bc95fe2ae037e056d8228820dd08d7e9/src/Command/CreateCommand.php#L38-L55
seeruo/framework
src/Command/CreateCommand.php
CreateCommand.create
protected function create(string $filename){ $fileSystem = new Filesystem(); $source = $this->config['source'] ?: 'Source'; $file_path = ROOT . '/' . $source; // 创建文件路径 $fileSystem->exists($file_path) || $fileSystem->mkdir($file_path); $html = ''; $html .= "---" . PHP_EOL; $html .= "title: " . $filename . PHP_EOL; $html .= "type: " . 'type' . PHP_EOL; $html .= "date: " . date('Y-m-d H:i:s') . PHP_EOL; $html .= "tags: " . $filename . PHP_EOL; $html .= "---" . PHP_EOL . PHP_EOL; $html .= "Create at ".date('Y-m-d H:i:s').PHP_EOL; $html .= 'You should edit this page as markdown'.PHP_EOL; $file_name = $file_path . '/' . $filename . '.md'; if ($fileSystem->exists([$file_name])) { throw new Exception('Create '.$filename.'.php failed, this file exited!!!'); } $status = file_put_contents($file_name, $html, LOCK_EX); if ($status === false) { throw new Exception('Create '.$filename.' failed!'); } }
php
protected function create(string $filename){ $fileSystem = new Filesystem(); $source = $this->config['source'] ?: 'Source'; $file_path = ROOT . '/' . $source; // 创建文件路径 $fileSystem->exists($file_path) || $fileSystem->mkdir($file_path); $html = ''; $html .= "---" . PHP_EOL; $html .= "title: " . $filename . PHP_EOL; $html .= "type: " . 'type' . PHP_EOL; $html .= "date: " . date('Y-m-d H:i:s') . PHP_EOL; $html .= "tags: " . $filename . PHP_EOL; $html .= "---" . PHP_EOL . PHP_EOL; $html .= "Create at ".date('Y-m-d H:i:s').PHP_EOL; $html .= 'You should edit this page as markdown'.PHP_EOL; $file_name = $file_path . '/' . $filename . '.md'; if ($fileSystem->exists([$file_name])) { throw new Exception('Create '.$filename.'.php failed, this file exited!!!'); } $status = file_put_contents($file_name, $html, LOCK_EX); if ($status === false) { throw new Exception('Create '.$filename.' failed!'); } }
[ "protected", "function", "create", "(", "string", "$", "filename", ")", "{", "$", "fileSystem", "=", "new", "Filesystem", "(", ")", ";", "$", "source", "=", "$", "this", "->", "config", "[", "'source'", "]", "?", ":", "'Source'", ";", "$", "file_path", "=", "ROOT", ".", "'/'", ".", "$", "source", ";", "// 创建文件路径", "$", "fileSystem", "->", "exists", "(", "$", "file_path", ")", "||", "$", "fileSystem", "->", "mkdir", "(", "$", "file_path", ")", ";", "$", "html", "=", "''", ";", "$", "html", ".=", "\"---\"", ".", "PHP_EOL", ";", "$", "html", ".=", "\"title: \"", ".", "$", "filename", ".", "PHP_EOL", ";", "$", "html", ".=", "\"type: \"", ".", "'type'", ".", "PHP_EOL", ";", "$", "html", ".=", "\"date: \"", ".", "date", "(", "'Y-m-d H:i:s'", ")", ".", "PHP_EOL", ";", "$", "html", ".=", "\"tags: \"", ".", "$", "filename", ".", "PHP_EOL", ";", "$", "html", ".=", "\"---\"", ".", "PHP_EOL", ".", "PHP_EOL", ";", "$", "html", ".=", "\"Create at \"", ".", "date", "(", "'Y-m-d H:i:s'", ")", ".", "PHP_EOL", ";", "$", "html", ".=", "'You should edit this page as markdown'", ".", "PHP_EOL", ";", "$", "file_name", "=", "$", "file_path", ".", "'/'", ".", "$", "filename", ".", "'.md'", ";", "if", "(", "$", "fileSystem", "->", "exists", "(", "[", "$", "file_name", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'Create '", ".", "$", "filename", ".", "'.php failed, this file exited!!!'", ")", ";", "}", "$", "status", "=", "file_put_contents", "(", "$", "file_name", ",", "$", "html", ",", "LOCK_EX", ")", ";", "if", "(", "$", "status", "===", "false", ")", "{", "throw", "new", "Exception", "(", "'Create '", ".", "$", "filename", ".", "' failed!'", ")", ";", "}", "}" ]
[create md file] @DateTime 2018-12-13 @param string $filename 文件名称
[ "[", "create", "md", "file", "]" ]
train
https://github.com/seeruo/framework/blob/689c6e95bc95fe2ae037e056d8228820dd08d7e9/src/Command/CreateCommand.php#L61-L87
webforge-labs/psc-cms
lib/Psc/Doctrine/UniqueConstraintValidator.php
UniqueConstraintValidator.process
public function process(Array $data) { foreach ($this->uniqueConstraints as $constraint) { $constraintValue = array(); foreach ($constraint->getKeys() as $key) { // da wir diese reihenfolge nehmen, ist diese immer gleich $type = $constraint->getKeyType($key); if (!array_key_exists($key, $data)) { throw new WrongDataException(sprintf("In Data ist der Schlüssel '%s' nicht vorhanden. Erwartet: '%s'", $key, $type->getName())); } $value = $data[$key]; if (!$this->typeMatcher->isTypeof($value, $type)) { $e = new TypeExpectedException( sprintf("Data %s für Key: '%s' sollte vom Type '%s' sein", \Psc\Code\Code::varInfo($value), $key, $type->getName()) ); $e->expectedType = $type; throw $e; } $constraintValue[$key] = $value; } // schlüssel darf es nicht geben, wert nicht gesetzt kann es nicht geben if (($indexEntry = $this->index->get($constraintValue, FALSE, DataInput::THROW_EXCEPTION)) === FALSE) { // ok: nicht im index => zum index hinzufügen $this->index->set($constraintValue, array_key_exists('identifier', $data) ? $data['identifier'] : TRUE); } else { throw UniqueConstraintException::factory($constraint->getName(), $this->getStringValue($constraintValue), $constraintValue, !is_bool($indexEntry) ? $indexEntry : NULL // kann der identifier sein ); } } }
php
public function process(Array $data) { foreach ($this->uniqueConstraints as $constraint) { $constraintValue = array(); foreach ($constraint->getKeys() as $key) { // da wir diese reihenfolge nehmen, ist diese immer gleich $type = $constraint->getKeyType($key); if (!array_key_exists($key, $data)) { throw new WrongDataException(sprintf("In Data ist der Schlüssel '%s' nicht vorhanden. Erwartet: '%s'", $key, $type->getName())); } $value = $data[$key]; if (!$this->typeMatcher->isTypeof($value, $type)) { $e = new TypeExpectedException( sprintf("Data %s für Key: '%s' sollte vom Type '%s' sein", \Psc\Code\Code::varInfo($value), $key, $type->getName()) ); $e->expectedType = $type; throw $e; } $constraintValue[$key] = $value; } // schlüssel darf es nicht geben, wert nicht gesetzt kann es nicht geben if (($indexEntry = $this->index->get($constraintValue, FALSE, DataInput::THROW_EXCEPTION)) === FALSE) { // ok: nicht im index => zum index hinzufügen $this->index->set($constraintValue, array_key_exists('identifier', $data) ? $data['identifier'] : TRUE); } else { throw UniqueConstraintException::factory($constraint->getName(), $this->getStringValue($constraintValue), $constraintValue, !is_bool($indexEntry) ? $indexEntry : NULL // kann der identifier sein ); } } }
[ "public", "function", "process", "(", "Array", "$", "data", ")", "{", "foreach", "(", "$", "this", "->", "uniqueConstraints", "as", "$", "constraint", ")", "{", "$", "constraintValue", "=", "array", "(", ")", ";", "foreach", "(", "$", "constraint", "->", "getKeys", "(", ")", "as", "$", "key", ")", "{", "// da wir diese reihenfolge nehmen, ist diese immer gleich", "$", "type", "=", "$", "constraint", "->", "getKeyType", "(", "$", "key", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "data", ")", ")", "{", "throw", "new", "WrongDataException", "(", "sprintf", "(", "\"In Data ist der Schlüssel '%s' nicht vorhanden. Erwartet: '%s'\",", " ", "k", "ey,", " ", "t", "ype-", ">g", "etName(", ")", ")", ")", ";", "", "}", "$", "value", "=", "$", "data", "[", "$", "key", "]", ";", "if", "(", "!", "$", "this", "->", "typeMatcher", "->", "isTypeof", "(", "$", "value", ",", "$", "type", ")", ")", "{", "$", "e", "=", "new", "TypeExpectedException", "(", "sprintf", "(", "\"Data %s für Key: '%s' sollte vom Type '%s' sein\",", " ", "P", "sc\\", "C", "ode\\", "C", "ode:", ":v", "arInfo(", "$", "v", "alue)", ",", " ", "k", "ey,", " ", "t", "ype-", ">g", "etName(", ")", ")", "", ")", ";", "$", "e", "->", "expectedType", "=", "$", "type", ";", "throw", "$", "e", ";", "}", "$", "constraintValue", "[", "$", "key", "]", "=", "$", "value", ";", "}", "// schlüssel darf es nicht geben, wert nicht gesetzt kann es nicht geben", "if", "(", "(", "$", "indexEntry", "=", "$", "this", "->", "index", "->", "get", "(", "$", "constraintValue", ",", "FALSE", ",", "DataInput", "::", "THROW_EXCEPTION", ")", ")", "===", "FALSE", ")", "{", "// ok: nicht im index => zum index hinzufügen", "$", "this", "->", "index", "->", "set", "(", "$", "constraintValue", ",", "array_key_exists", "(", "'identifier'", ",", "$", "data", ")", "?", "$", "data", "[", "'identifier'", "]", ":", "TRUE", ")", ";", "}", "else", "{", "throw", "UniqueConstraintException", "::", "factory", "(", "$", "constraint", "->", "getName", "(", ")", ",", "$", "this", "->", "getStringValue", "(", "$", "constraintValue", ")", ",", "$", "constraintValue", ",", "!", "is_bool", "(", "$", "indexEntry", ")", "?", "$", "indexEntry", ":", "NULL", "// kann der identifier sein", ")", ";", "}", "}", "}" ]
Überprüft die Daten anhand der Constraints und fügt die Daten zum Index hinzu Schmeisst eine Exception wenn die daten bereits im Index sind diese Exception wird mit duplicateIdentifier gesetzt, wenn in $data der key 'identifier' für den vorigen Index-Eintrag gesetzt war
[ "Überprüft", "die", "Daten", "anhand", "der", "Constraints", "und", "fügt", "die", "Daten", "zum", "Index", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Doctrine/UniqueConstraintValidator.php#L36-L73
webforge-labs/psc-cms
lib/Psc/Doctrine/UniqueConstraintValidator.php
UniqueConstraintValidator.updateIndex
public function updateIndex(UniqueConstraint $constraint, Array $dataRows) { if (!array_key_exists($constraint->getName(), $this->uniqueConstraints)) { throw new InvalidArgumentException(sprintf("Constraint '%s' wurde noch nicht mit addConstraint() hinzugefügt'",$constraint->getName())); } foreach ($dataRows as $data) { // hierbei können natürlich auch UniqueConstraintExceptions auftreten, diese wollen wir aber nicht abfangen, weil wir davon ausgehen, dass meistens diese Funktion dafür genutzt wird, den Index aus der Datenbank zu füllen (die ja konsistent in sich, ist) $this->process($data); } return $this; }
php
public function updateIndex(UniqueConstraint $constraint, Array $dataRows) { if (!array_key_exists($constraint->getName(), $this->uniqueConstraints)) { throw new InvalidArgumentException(sprintf("Constraint '%s' wurde noch nicht mit addConstraint() hinzugefügt'",$constraint->getName())); } foreach ($dataRows as $data) { // hierbei können natürlich auch UniqueConstraintExceptions auftreten, diese wollen wir aber nicht abfangen, weil wir davon ausgehen, dass meistens diese Funktion dafür genutzt wird, den Index aus der Datenbank zu füllen (die ja konsistent in sich, ist) $this->process($data); } return $this; }
[ "public", "function", "updateIndex", "(", "UniqueConstraint", "$", "constraint", ",", "Array", "$", "dataRows", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "constraint", "->", "getName", "(", ")", ",", "$", "this", "->", "uniqueConstraints", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "\"Constraint '%s' wurde noch nicht mit addConstraint() hinzugefügt'\",", "$", "c", "onstraint-", ">g", "etName(", ")", ")", ")", ";", "", "}", "foreach", "(", "$", "dataRows", "as", "$", "data", ")", "{", "// hierbei können natürlich auch UniqueConstraintExceptions auftreten, diese wollen wir aber nicht abfangen, weil wir davon ausgehen, dass meistens diese Funktion dafür genutzt wird, den Index aus der Datenbank zu füllen (die ja konsistent in sich, ist)", "$", "this", "->", "process", "(", "$", "data", ")", ";", "}", "return", "$", "this", ";", "}" ]
Fügt mehrere Einträge zum Unique-Index hinzu ist z. B. dafür nötig, um den Index mit der Datenbank zu synchronisieren. @param Array $dataRows jeder Eintrag ist ein Parameter für $this->process() @chainable
[ "Fügt", "mehrere", "Einträge", "zum", "Unique", "-", "Index", "hinzu" ]
train
https://github.com/webforge-labs/psc-cms/blob/467bfa2547e6b4fa487d2d7f35fa6cc618dbc763/lib/Psc/Doctrine/UniqueConstraintValidator.php#L83-L94
thienhungho/yii2-order-management
src/modules/OrderManage/controllers/OrderController.php
OrderController.findModel
protected function findModel($id) { if (($model = Order::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
php
protected function findModel($id) { if (($model = Order::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
[ "protected", "function", "findModel", "(", "$", "id", ")", "{", "if", "(", "(", "$", "model", "=", "Order", "::", "findOne", "(", "$", "id", ")", ")", "!==", "null", ")", "{", "return", "$", "model", ";", "}", "else", "{", "throw", "new", "NotFoundHttpException", "(", "t", "(", "'app'", ",", "'The requested page does not exist.'", ")", ")", ";", "}", "}" ]
Finds the Order model based on its primary key value. If the model is not found, a 404 HTTP exception will be thrown. @param integer $id @return Order the loaded model @throws NotFoundHttpException if the model cannot be found
[ "Finds", "the", "Order", "model", "based", "on", "its", "primary", "key", "value", ".", "If", "the", "model", "is", "not", "found", "a", "404", "HTTP", "exception", "will", "be", "thrown", "." ]
train
https://github.com/thienhungho/yii2-order-management/blob/f263f0b2168d6f5e99cee2e20a5878d09d4e81c0/src/modules/OrderManage/controllers/OrderController.php#L306-L313
thienhungho/yii2-order-management
src/modules/OrderManage/controllers/OrderController.php
OrderController.findUser
protected function findUser($id) { if (($model = User::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
php
protected function findUser($id) { if (($model = User::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(t('app', 'The requested page does not exist.')); } }
[ "protected", "function", "findUser", "(", "$", "id", ")", "{", "if", "(", "(", "$", "model", "=", "User", "::", "findOne", "(", "$", "id", ")", ")", "!==", "null", ")", "{", "return", "$", "model", ";", "}", "else", "{", "throw", "new", "NotFoundHttpException", "(", "t", "(", "'app'", ",", "'The requested page does not exist.'", ")", ")", ";", "}", "}" ]
@param $id @return null|Order @throws NotFoundHttpException
[ "@param", "$id" ]
train
https://github.com/thienhungho/yii2-order-management/blob/f263f0b2168d6f5e99cee2e20a5878d09d4e81c0/src/modules/OrderManage/controllers/OrderController.php#L321-L328
anime-db/world-art-filler-bundle
src/Service/Browser.php
Browser.setRequest
public function setRequest(Request $request = null) { $this->request = $request; // try to set User-Agent from original request if ($request && $this->browser) { $this->browser->setDefaultHeaders([ 'User-Agent' => $request->server->get('HTTP_USER_AGENT', self::DEFAULT_USER_AGENT), ]); } }
php
public function setRequest(Request $request = null) { $this->request = $request; // try to set User-Agent from original request if ($request && $this->browser) { $this->browser->setDefaultHeaders([ 'User-Agent' => $request->server->get('HTTP_USER_AGENT', self::DEFAULT_USER_AGENT), ]); } }
[ "public", "function", "setRequest", "(", "Request", "$", "request", "=", "null", ")", "{", "$", "this", "->", "request", "=", "$", "request", ";", "// try to set User-Agent from original request", "if", "(", "$", "request", "&&", "$", "this", "->", "browser", ")", "{", "$", "this", "->", "browser", "->", "setDefaultHeaders", "(", "[", "'User-Agent'", "=>", "$", "request", "->", "server", "->", "get", "(", "'HTTP_USER_AGENT'", ",", "self", "::", "DEFAULT_USER_AGENT", ")", ",", "]", ")", ";", "}", "}" ]
Set request. @param \Symfony\Component\HttpFoundation\Request $request
[ "Set", "request", "." ]
train
https://github.com/anime-db/world-art-filler-bundle/blob/f2ef4dbd12fe39c18183d1628b5049b8d381e42c/src/Service/Browser.php#L88-L97
anime-db/world-art-filler-bundle
src/Service/Browser.php
Browser.getDom
public function getDom($path) { $dom = new \DOMDocument('1.0', 'utf8'); if (($content = $this->getContent($path)) && $dom->loadHTML($content)) { return $dom; } else { return; } }
php
public function getDom($path) { $dom = new \DOMDocument('1.0', 'utf8'); if (($content = $this->getContent($path)) && $dom->loadHTML($content)) { return $dom; } else { return; } }
[ "public", "function", "getDom", "(", "$", "path", ")", "{", "$", "dom", "=", "new", "\\", "DOMDocument", "(", "'1.0'", ",", "'utf8'", ")", ";", "if", "(", "(", "$", "content", "=", "$", "this", "->", "getContent", "(", "$", "path", ")", ")", "&&", "$", "dom", "->", "loadHTML", "(", "$", "content", ")", ")", "{", "return", "$", "dom", ";", "}", "else", "{", "return", ";", "}", "}" ]
Get DOMDocument from path. Receive content from the URL, cleaning using Tidy and creating DOM document @param string $path @return \DOMDocument|null
[ "Get", "DOMDocument", "from", "path", "." ]
train
https://github.com/anime-db/world-art-filler-bundle/blob/f2ef4dbd12fe39c18183d1628b5049b8d381e42c/src/Service/Browser.php#L108-L116
anime-db/world-art-filler-bundle
src/Service/Browser.php
Browser.getContent
public function getContent($path) { /* @var $response \Guzzle\Http\Message\Response */ $response = $this->getBrowser()->get($path)->send(); if ($response->isError()) { throw new \RuntimeException('Failed to query the server '.$this->host); } if ($response->getStatusCode() !== 200 || !($html = $response->getBody(true))) { return; } $html = iconv('windows-1251', 'utf-8', $html); // clean content $config = [ 'output-xhtml' => true, 'indent' => true, 'indent-spaces' => 0, 'fix-backslash' => true, 'hide-comments' => true, 'drop-empty-paras' => true, 'wrap' => false, ]; $tidy = new \tidy(); $tidy->parseString($html, $config, 'utf8'); $tidy->cleanRepair(); $html = $tidy->root()->value; // ignore blocks $html = preg_replace('/<noembed>.*?<\/noembed>/is', '', $html); $html = preg_replace('/<noindex>.*?<\/noindex>/is', '', $html); // remove noembed return $html; }
php
public function getContent($path) { /* @var $response \Guzzle\Http\Message\Response */ $response = $this->getBrowser()->get($path)->send(); if ($response->isError()) { throw new \RuntimeException('Failed to query the server '.$this->host); } if ($response->getStatusCode() !== 200 || !($html = $response->getBody(true))) { return; } $html = iconv('windows-1251', 'utf-8', $html); // clean content $config = [ 'output-xhtml' => true, 'indent' => true, 'indent-spaces' => 0, 'fix-backslash' => true, 'hide-comments' => true, 'drop-empty-paras' => true, 'wrap' => false, ]; $tidy = new \tidy(); $tidy->parseString($html, $config, 'utf8'); $tidy->cleanRepair(); $html = $tidy->root()->value; // ignore blocks $html = preg_replace('/<noembed>.*?<\/noembed>/is', '', $html); $html = preg_replace('/<noindex>.*?<\/noindex>/is', '', $html); // remove noembed return $html; }
[ "public", "function", "getContent", "(", "$", "path", ")", "{", "/* @var $response \\Guzzle\\Http\\Message\\Response */", "$", "response", "=", "$", "this", "->", "getBrowser", "(", ")", "->", "get", "(", "$", "path", ")", "->", "send", "(", ")", ";", "if", "(", "$", "response", "->", "isError", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Failed to query the server '", ".", "$", "this", "->", "host", ")", ";", "}", "if", "(", "$", "response", "->", "getStatusCode", "(", ")", "!==", "200", "||", "!", "(", "$", "html", "=", "$", "response", "->", "getBody", "(", "true", ")", ")", ")", "{", "return", ";", "}", "$", "html", "=", "iconv", "(", "'windows-1251'", ",", "'utf-8'", ",", "$", "html", ")", ";", "// clean content", "$", "config", "=", "[", "'output-xhtml'", "=>", "true", ",", "'indent'", "=>", "true", ",", "'indent-spaces'", "=>", "0", ",", "'fix-backslash'", "=>", "true", ",", "'hide-comments'", "=>", "true", ",", "'drop-empty-paras'", "=>", "true", ",", "'wrap'", "=>", "false", ",", "]", ";", "$", "tidy", "=", "new", "\\", "tidy", "(", ")", ";", "$", "tidy", "->", "parseString", "(", "$", "html", ",", "$", "config", ",", "'utf8'", ")", ";", "$", "tidy", "->", "cleanRepair", "(", ")", ";", "$", "html", "=", "$", "tidy", "->", "root", "(", ")", "->", "value", ";", "// ignore blocks", "$", "html", "=", "preg_replace", "(", "'/<noembed>.*?<\\/noembed>/is'", ",", "''", ",", "$", "html", ")", ";", "$", "html", "=", "preg_replace", "(", "'/<noindex>.*?<\\/noindex>/is'", ",", "''", ",", "$", "html", ")", ";", "// remove noembed", "return", "$", "html", ";", "}" ]
Get content from path. Receive content from the URL and cleaning using Tidy @param string $path @return string
[ "Get", "content", "from", "path", "." ]
train
https://github.com/anime-db/world-art-filler-bundle/blob/f2ef4dbd12fe39c18183d1628b5049b8d381e42c/src/Service/Browser.php#L127-L158
anime-db/world-art-filler-bundle
src/Service/Browser.php
Browser.getBrowser
protected function getBrowser() { if (!($this->browser instanceof Client)) { $this->browser = new Client($this->host); // try to set User-Agent from original request $user_agent = self::DEFAULT_USER_AGENT; if ($this->request) { $user_agent = $this->request->server->get('HTTP_USER_AGENT', self::DEFAULT_USER_AGENT); } $this->browser->setDefaultHeaders(['User-Agent' => $user_agent]); // configure browser client $this->browser->setDefaultOption('timeout', $this->timeout); if ($this->proxy_list) { $this->browser->setDefaultOption('proxy', $this->proxy_list[array_rand($this->proxy_list)]); } } return $this->browser; }
php
protected function getBrowser() { if (!($this->browser instanceof Client)) { $this->browser = new Client($this->host); // try to set User-Agent from original request $user_agent = self::DEFAULT_USER_AGENT; if ($this->request) { $user_agent = $this->request->server->get('HTTP_USER_AGENT', self::DEFAULT_USER_AGENT); } $this->browser->setDefaultHeaders(['User-Agent' => $user_agent]); // configure browser client $this->browser->setDefaultOption('timeout', $this->timeout); if ($this->proxy_list) { $this->browser->setDefaultOption('proxy', $this->proxy_list[array_rand($this->proxy_list)]); } } return $this->browser; }
[ "protected", "function", "getBrowser", "(", ")", "{", "if", "(", "!", "(", "$", "this", "->", "browser", "instanceof", "Client", ")", ")", "{", "$", "this", "->", "browser", "=", "new", "Client", "(", "$", "this", "->", "host", ")", ";", "// try to set User-Agent from original request", "$", "user_agent", "=", "self", "::", "DEFAULT_USER_AGENT", ";", "if", "(", "$", "this", "->", "request", ")", "{", "$", "user_agent", "=", "$", "this", "->", "request", "->", "server", "->", "get", "(", "'HTTP_USER_AGENT'", ",", "self", "::", "DEFAULT_USER_AGENT", ")", ";", "}", "$", "this", "->", "browser", "->", "setDefaultHeaders", "(", "[", "'User-Agent'", "=>", "$", "user_agent", "]", ")", ";", "// configure browser client", "$", "this", "->", "browser", "->", "setDefaultOption", "(", "'timeout'", ",", "$", "this", "->", "timeout", ")", ";", "if", "(", "$", "this", "->", "proxy_list", ")", "{", "$", "this", "->", "browser", "->", "setDefaultOption", "(", "'proxy'", ",", "$", "this", "->", "proxy_list", "[", "array_rand", "(", "$", "this", "->", "proxy_list", ")", "]", ")", ";", "}", "}", "return", "$", "this", "->", "browser", ";", "}" ]
Get HTTP browser. @param \Guzzle\Http\Client
[ "Get", "HTTP", "browser", "." ]
train
https://github.com/anime-db/world-art-filler-bundle/blob/f2ef4dbd12fe39c18183d1628b5049b8d381e42c/src/Service/Browser.php#L165-L185
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.setMaxClients
public function setMaxClients($v) { if ($v !== null && is_numeric($v)) { $v = (int) $v; } if ($this->max_clients !== $v) { $this->max_clients = $v; $this->modifiedColumns[] = LicensePeer::MAX_CLIENTS; } return $this; }
php
public function setMaxClients($v) { if ($v !== null && is_numeric($v)) { $v = (int) $v; } if ($this->max_clients !== $v) { $this->max_clients = $v; $this->modifiedColumns[] = LicensePeer::MAX_CLIENTS; } return $this; }
[ "public", "function", "setMaxClients", "(", "$", "v", ")", "{", "if", "(", "$", "v", "!==", "null", "&&", "is_numeric", "(", "$", "v", ")", ")", "{", "$", "v", "=", "(", "int", ")", "$", "v", ";", "}", "if", "(", "$", "this", "->", "max_clients", "!==", "$", "v", ")", "{", "$", "this", "->", "max_clients", "=", "$", "v", ";", "$", "this", "->", "modifiedColumns", "[", "]", "=", "LicensePeer", "::", "MAX_CLIENTS", ";", "}", "return", "$", "this", ";", "}" ]
Set the value of [max_clients] column. @param int $v new value @return License The current object (for fluent API support)
[ "Set", "the", "value", "of", "[", "max_clients", "]", "column", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L171-L184
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.setValidUntil
public function setValidUntil($v) { if ($v !== null) { $v = (string) $v; } if ($this->valid_until !== $v) { $this->valid_until = $v; $this->modifiedColumns[] = LicensePeer::VALID_UNTIL; } return $this; }
php
public function setValidUntil($v) { if ($v !== null) { $v = (string) $v; } if ($this->valid_until !== $v) { $this->valid_until = $v; $this->modifiedColumns[] = LicensePeer::VALID_UNTIL; } return $this; }
[ "public", "function", "setValidUntil", "(", "$", "v", ")", "{", "if", "(", "$", "v", "!==", "null", ")", "{", "$", "v", "=", "(", "string", ")", "$", "v", ";", "}", "if", "(", "$", "this", "->", "valid_until", "!==", "$", "v", ")", "{", "$", "this", "->", "valid_until", "=", "$", "v", ";", "$", "this", "->", "modifiedColumns", "[", "]", "=", "LicensePeer", "::", "VALID_UNTIL", ";", "}", "return", "$", "this", ";", "}" ]
Set the value of [valid_until] column. @param string $v new value @return License The current object (for fluent API support)
[ "Set", "the", "value", "of", "[", "valid_until", "]", "column", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L213-L226
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.setSerial
public function setSerial($v) { if ($v !== null) { $v = (string) $v; } if ($this->serial !== $v) { $this->serial = $v; $this->modifiedColumns[] = LicensePeer::SERIAL; } return $this; }
php
public function setSerial($v) { if ($v !== null) { $v = (string) $v; } if ($this->serial !== $v) { $this->serial = $v; $this->modifiedColumns[] = LicensePeer::SERIAL; } return $this; }
[ "public", "function", "setSerial", "(", "$", "v", ")", "{", "if", "(", "$", "v", "!==", "null", ")", "{", "$", "v", "=", "(", "string", ")", "$", "v", ";", "}", "if", "(", "$", "this", "->", "serial", "!==", "$", "v", ")", "{", "$", "this", "->", "serial", "=", "$", "v", ";", "$", "this", "->", "modifiedColumns", "[", "]", "=", "LicensePeer", "::", "SERIAL", ";", "}", "return", "$", "this", ";", "}" ]
Set the value of [serial] column. @param string $v new value @return License The current object (for fluent API support)
[ "Set", "the", "value", "of", "[", "serial", "]", "column", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L234-L247
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.hydrate
public function hydrate($row, $startcol = 0, $rehydrate = false) { try { $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->max_clients = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; $this->domain = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; $this->valid_until = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; $this->serial = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; $this->resetModified(); $this->setNew(false); if ($rehydrate) { $this->ensureConsistency(); } $this->postHydrate($row, $startcol, $rehydrate); return $startcol + 5; // 5 = LicensePeer::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating License object", $e); } }
php
public function hydrate($row, $startcol = 0, $rehydrate = false) { try { $this->id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null; $this->max_clients = ($row[$startcol + 1] !== null) ? (int) $row[$startcol + 1] : null; $this->domain = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null; $this->valid_until = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null; $this->serial = ($row[$startcol + 4] !== null) ? (string) $row[$startcol + 4] : null; $this->resetModified(); $this->setNew(false); if ($rehydrate) { $this->ensureConsistency(); } $this->postHydrate($row, $startcol, $rehydrate); return $startcol + 5; // 5 = LicensePeer::NUM_HYDRATE_COLUMNS. } catch (Exception $e) { throw new PropelException("Error populating License object", $e); } }
[ "public", "function", "hydrate", "(", "$", "row", ",", "$", "startcol", "=", "0", ",", "$", "rehydrate", "=", "false", ")", "{", "try", "{", "$", "this", "->", "id", "=", "(", "$", "row", "[", "$", "startcol", "+", "0", "]", "!==", "null", ")", "?", "(", "int", ")", "$", "row", "[", "$", "startcol", "+", "0", "]", ":", "null", ";", "$", "this", "->", "max_clients", "=", "(", "$", "row", "[", "$", "startcol", "+", "1", "]", "!==", "null", ")", "?", "(", "int", ")", "$", "row", "[", "$", "startcol", "+", "1", "]", ":", "null", ";", "$", "this", "->", "domain", "=", "(", "$", "row", "[", "$", "startcol", "+", "2", "]", "!==", "null", ")", "?", "(", "string", ")", "$", "row", "[", "$", "startcol", "+", "2", "]", ":", "null", ";", "$", "this", "->", "valid_until", "=", "(", "$", "row", "[", "$", "startcol", "+", "3", "]", "!==", "null", ")", "?", "(", "string", ")", "$", "row", "[", "$", "startcol", "+", "3", "]", ":", "null", ";", "$", "this", "->", "serial", "=", "(", "$", "row", "[", "$", "startcol", "+", "4", "]", "!==", "null", ")", "?", "(", "string", ")", "$", "row", "[", "$", "startcol", "+", "4", "]", ":", "null", ";", "$", "this", "->", "resetModified", "(", ")", ";", "$", "this", "->", "setNew", "(", "false", ")", ";", "if", "(", "$", "rehydrate", ")", "{", "$", "this", "->", "ensureConsistency", "(", ")", ";", "}", "$", "this", "->", "postHydrate", "(", "$", "row", ",", "$", "startcol", ",", "$", "rehydrate", ")", ";", "return", "$", "startcol", "+", "5", ";", "// 5 = LicensePeer::NUM_HYDRATE_COLUMNS.", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "PropelException", "(", "\"Error populating License object\"", ",", "$", "e", ")", ";", "}", "}" ]
Hydrates (populates) the object variables with values from the database resultset. An offset (0-based "start column") is specified so that objects can be hydrated with a subset of the columns in the resultset rows. This is needed, for example, for results of JOIN queries where the resultset row includes columns from two or more tables. @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM) @param int $startcol 0-based offset column which indicates which resultset column to start with. @param boolean $rehydrate Whether this object is being re-hydrated from the database. @return int next starting column @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
[ "Hydrates", "(", "populates", ")", "the", "object", "variables", "with", "values", "from", "the", "database", "resultset", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L277-L300
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.doInsert
protected function doInsert(PropelPDO $con) { $modifiedColumns = array(); $index = 0; $this->modifiedColumns[] = LicensePeer::ID; if (null !== $this->id) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . LicensePeer::ID . ')'); } // check the columns in natural order for more readable SQL queries if ($this->isColumnModified(LicensePeer::ID)) { $modifiedColumns[':p' . $index++] = '`id`'; } if ($this->isColumnModified(LicensePeer::MAX_CLIENTS)) { $modifiedColumns[':p' . $index++] = '`max_clients`'; } if ($this->isColumnModified(LicensePeer::DOMAIN)) { $modifiedColumns[':p' . $index++] = '`domain`'; } if ($this->isColumnModified(LicensePeer::VALID_UNTIL)) { $modifiedColumns[':p' . $index++] = '`valid_until`'; } if ($this->isColumnModified(LicensePeer::SERIAL)) { $modifiedColumns[':p' . $index++] = '`serial`'; } $sql = sprintf( 'INSERT INTO `license` (%s) VALUES (%s)', implode(', ', $modifiedColumns), implode(', ', array_keys($modifiedColumns)) ); try { $stmt = $con->prepare($sql); foreach ($modifiedColumns as $identifier => $columnName) { switch ($columnName) { case '`id`': $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); break; case '`max_clients`': $stmt->bindValue($identifier, $this->max_clients, PDO::PARAM_INT); break; case '`domain`': $stmt->bindValue($identifier, $this->domain, PDO::PARAM_STR); break; case '`valid_until`': $stmt->bindValue($identifier, $this->valid_until, PDO::PARAM_STR); break; case '`serial`': $stmt->bindValue($identifier, $this->serial, PDO::PARAM_STR); break; } } $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), $e); } try { $pk = $con->lastInsertId(); } catch (Exception $e) { throw new PropelException('Unable to get autoincrement id.', $e); } $this->setId($pk); $this->setNew(false); }
php
protected function doInsert(PropelPDO $con) { $modifiedColumns = array(); $index = 0; $this->modifiedColumns[] = LicensePeer::ID; if (null !== $this->id) { throw new PropelException('Cannot insert a value for auto-increment primary key (' . LicensePeer::ID . ')'); } // check the columns in natural order for more readable SQL queries if ($this->isColumnModified(LicensePeer::ID)) { $modifiedColumns[':p' . $index++] = '`id`'; } if ($this->isColumnModified(LicensePeer::MAX_CLIENTS)) { $modifiedColumns[':p' . $index++] = '`max_clients`'; } if ($this->isColumnModified(LicensePeer::DOMAIN)) { $modifiedColumns[':p' . $index++] = '`domain`'; } if ($this->isColumnModified(LicensePeer::VALID_UNTIL)) { $modifiedColumns[':p' . $index++] = '`valid_until`'; } if ($this->isColumnModified(LicensePeer::SERIAL)) { $modifiedColumns[':p' . $index++] = '`serial`'; } $sql = sprintf( 'INSERT INTO `license` (%s) VALUES (%s)', implode(', ', $modifiedColumns), implode(', ', array_keys($modifiedColumns)) ); try { $stmt = $con->prepare($sql); foreach ($modifiedColumns as $identifier => $columnName) { switch ($columnName) { case '`id`': $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); break; case '`max_clients`': $stmt->bindValue($identifier, $this->max_clients, PDO::PARAM_INT); break; case '`domain`': $stmt->bindValue($identifier, $this->domain, PDO::PARAM_STR); break; case '`valid_until`': $stmt->bindValue($identifier, $this->valid_until, PDO::PARAM_STR); break; case '`serial`': $stmt->bindValue($identifier, $this->serial, PDO::PARAM_STR); break; } } $stmt->execute(); } catch (Exception $e) { Propel::log($e->getMessage(), Propel::LOG_ERR); throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), $e); } try { $pk = $con->lastInsertId(); } catch (Exception $e) { throw new PropelException('Unable to get autoincrement id.', $e); } $this->setId($pk); $this->setNew(false); }
[ "protected", "function", "doInsert", "(", "PropelPDO", "$", "con", ")", "{", "$", "modifiedColumns", "=", "array", "(", ")", ";", "$", "index", "=", "0", ";", "$", "this", "->", "modifiedColumns", "[", "]", "=", "LicensePeer", "::", "ID", ";", "if", "(", "null", "!==", "$", "this", "->", "id", ")", "{", "throw", "new", "PropelException", "(", "'Cannot insert a value for auto-increment primary key ('", ".", "LicensePeer", "::", "ID", ".", "')'", ")", ";", "}", "// check the columns in natural order for more readable SQL queries", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "ID", ")", ")", "{", "$", "modifiedColumns", "[", "':p'", ".", "$", "index", "++", "]", "=", "'`id`'", ";", "}", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "MAX_CLIENTS", ")", ")", "{", "$", "modifiedColumns", "[", "':p'", ".", "$", "index", "++", "]", "=", "'`max_clients`'", ";", "}", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "DOMAIN", ")", ")", "{", "$", "modifiedColumns", "[", "':p'", ".", "$", "index", "++", "]", "=", "'`domain`'", ";", "}", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "VALID_UNTIL", ")", ")", "{", "$", "modifiedColumns", "[", "':p'", ".", "$", "index", "++", "]", "=", "'`valid_until`'", ";", "}", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "SERIAL", ")", ")", "{", "$", "modifiedColumns", "[", "':p'", ".", "$", "index", "++", "]", "=", "'`serial`'", ";", "}", "$", "sql", "=", "sprintf", "(", "'INSERT INTO `license` (%s) VALUES (%s)'", ",", "implode", "(", "', '", ",", "$", "modifiedColumns", ")", ",", "implode", "(", "', '", ",", "array_keys", "(", "$", "modifiedColumns", ")", ")", ")", ";", "try", "{", "$", "stmt", "=", "$", "con", "->", "prepare", "(", "$", "sql", ")", ";", "foreach", "(", "$", "modifiedColumns", "as", "$", "identifier", "=>", "$", "columnName", ")", "{", "switch", "(", "$", "columnName", ")", "{", "case", "'`id`'", ":", "$", "stmt", "->", "bindValue", "(", "$", "identifier", ",", "$", "this", "->", "id", ",", "PDO", "::", "PARAM_INT", ")", ";", "break", ";", "case", "'`max_clients`'", ":", "$", "stmt", "->", "bindValue", "(", "$", "identifier", ",", "$", "this", "->", "max_clients", ",", "PDO", "::", "PARAM_INT", ")", ";", "break", ";", "case", "'`domain`'", ":", "$", "stmt", "->", "bindValue", "(", "$", "identifier", ",", "$", "this", "->", "domain", ",", "PDO", "::", "PARAM_STR", ")", ";", "break", ";", "case", "'`valid_until`'", ":", "$", "stmt", "->", "bindValue", "(", "$", "identifier", ",", "$", "this", "->", "valid_until", ",", "PDO", "::", "PARAM_STR", ")", ";", "break", ";", "case", "'`serial`'", ":", "$", "stmt", "->", "bindValue", "(", "$", "identifier", ",", "$", "this", "->", "serial", ",", "PDO", "::", "PARAM_STR", ")", ";", "break", ";", "}", "}", "$", "stmt", "->", "execute", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "Propel", "::", "log", "(", "$", "e", "->", "getMessage", "(", ")", ",", "Propel", "::", "LOG_ERR", ")", ";", "throw", "new", "PropelException", "(", "sprintf", "(", "'Unable to execute INSERT statement [%s]'", ",", "$", "sql", ")", ",", "$", "e", ")", ";", "}", "try", "{", "$", "pk", "=", "$", "con", "->", "lastInsertId", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "new", "PropelException", "(", "'Unable to get autoincrement id.'", ",", "$", "e", ")", ";", "}", "$", "this", "->", "setId", "(", "$", "pk", ")", ";", "$", "this", "->", "setNew", "(", "false", ")", ";", "}" ]
Insert the row in the database. @param PropelPDO $con @throws PropelException @see doSave()
[ "Insert", "the", "row", "in", "the", "database", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L496-L564
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.doUpdate
protected function doUpdate(PropelPDO $con) { $selectCriteria = $this->buildPkeyCriteria(); $valuesCriteria = $this->buildCriteria(); BasePeer::doUpdate($selectCriteria, $valuesCriteria, $con); }
php
protected function doUpdate(PropelPDO $con) { $selectCriteria = $this->buildPkeyCriteria(); $valuesCriteria = $this->buildCriteria(); BasePeer::doUpdate($selectCriteria, $valuesCriteria, $con); }
[ "protected", "function", "doUpdate", "(", "PropelPDO", "$", "con", ")", "{", "$", "selectCriteria", "=", "$", "this", "->", "buildPkeyCriteria", "(", ")", ";", "$", "valuesCriteria", "=", "$", "this", "->", "buildCriteria", "(", ")", ";", "BasePeer", "::", "doUpdate", "(", "$", "selectCriteria", ",", "$", "valuesCriteria", ",", "$", "con", ")", ";", "}" ]
Update the row in the database. @param PropelPDO $con @see doSave()
[ "Update", "the", "row", "in", "the", "database", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L573-L578
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.validate
public function validate($columns = null) { $res = $this->doValidate($columns); if ($res === true) { $this->validationFailures = array(); return true; } $this->validationFailures = $res; return false; }
php
public function validate($columns = null) { $res = $this->doValidate($columns); if ($res === true) { $this->validationFailures = array(); return true; } $this->validationFailures = $res; return false; }
[ "public", "function", "validate", "(", "$", "columns", "=", "null", ")", "{", "$", "res", "=", "$", "this", "->", "doValidate", "(", "$", "columns", ")", ";", "if", "(", "$", "res", "===", "true", ")", "{", "$", "this", "->", "validationFailures", "=", "array", "(", ")", ";", "return", "true", ";", "}", "$", "this", "->", "validationFailures", "=", "$", "res", ";", "return", "false", ";", "}" ]
Validates the objects modified field values and all objects related to this table. If $columns is either a column name or an array of column names only those columns are validated. @param mixed $columns Column name or an array of column names. @return boolean Whether all columns pass validation. @see doValidate() @see getValidationFailures()
[ "Validates", "the", "objects", "modified", "field", "values", "and", "all", "objects", "related", "to", "this", "table", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L609-L621
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.getByPosition
public function getByPosition($pos) { switch ($pos) { case 0: return $this->getId(); break; case 1: return $this->getMaxClients(); break; case 2: return $this->getDomain(); break; case 3: return $this->getValidUntil(); break; case 4: return $this->getSerial(); break; default: return null; break; } // switch() }
php
public function getByPosition($pos) { switch ($pos) { case 0: return $this->getId(); break; case 1: return $this->getMaxClients(); break; case 2: return $this->getDomain(); break; case 3: return $this->getValidUntil(); break; case 4: return $this->getSerial(); break; default: return null; break; } // switch() }
[ "public", "function", "getByPosition", "(", "$", "pos", ")", "{", "switch", "(", "$", "pos", ")", "{", "case", "0", ":", "return", "$", "this", "->", "getId", "(", ")", ";", "break", ";", "case", "1", ":", "return", "$", "this", "->", "getMaxClients", "(", ")", ";", "break", ";", "case", "2", ":", "return", "$", "this", "->", "getDomain", "(", ")", ";", "break", ";", "case", "3", ":", "return", "$", "this", "->", "getValidUntil", "(", ")", ";", "break", ";", "case", "4", ":", "return", "$", "this", "->", "getSerial", "(", ")", ";", "break", ";", "default", ":", "return", "null", ";", "break", ";", "}", "// switch()", "}" ]
Retrieves a field from the object by Position as specified in the xml schema. Zero-based. @param int $pos position in xml schema @return mixed Value of field at $pos
[ "Retrieves", "a", "field", "from", "the", "object", "by", "Position", "as", "specified", "in", "the", "xml", "schema", ".", "Zero", "-", "based", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L679-L701
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.toArray
public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array()) { if (isset($alreadyDumpedObjects['License'][$this->getPrimaryKey()])) { return '*RECURSION*'; } $alreadyDumpedObjects['License'][$this->getPrimaryKey()] = true; $keys = LicensePeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getId(), $keys[1] => $this->getMaxClients(), $keys[2] => $this->getDomain(), $keys[3] => $this->getValidUntil(), $keys[4] => $this->getSerial(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { $result[$key] = $virtualColumn; } return $result; }
php
public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array()) { if (isset($alreadyDumpedObjects['License'][$this->getPrimaryKey()])) { return '*RECURSION*'; } $alreadyDumpedObjects['License'][$this->getPrimaryKey()] = true; $keys = LicensePeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getId(), $keys[1] => $this->getMaxClients(), $keys[2] => $this->getDomain(), $keys[3] => $this->getValidUntil(), $keys[4] => $this->getSerial(), ); $virtualColumns = $this->virtualColumns; foreach ($virtualColumns as $key => $virtualColumn) { $result[$key] = $virtualColumn; } return $result; }
[ "public", "function", "toArray", "(", "$", "keyType", "=", "BasePeer", "::", "TYPE_PHPNAME", ",", "$", "includeLazyLoadColumns", "=", "true", ",", "$", "alreadyDumpedObjects", "=", "array", "(", ")", ")", "{", "if", "(", "isset", "(", "$", "alreadyDumpedObjects", "[", "'License'", "]", "[", "$", "this", "->", "getPrimaryKey", "(", ")", "]", ")", ")", "{", "return", "'*RECURSION*'", ";", "}", "$", "alreadyDumpedObjects", "[", "'License'", "]", "[", "$", "this", "->", "getPrimaryKey", "(", ")", "]", "=", "true", ";", "$", "keys", "=", "LicensePeer", "::", "getFieldNames", "(", "$", "keyType", ")", ";", "$", "result", "=", "array", "(", "$", "keys", "[", "0", "]", "=>", "$", "this", "->", "getId", "(", ")", ",", "$", "keys", "[", "1", "]", "=>", "$", "this", "->", "getMaxClients", "(", ")", ",", "$", "keys", "[", "2", "]", "=>", "$", "this", "->", "getDomain", "(", ")", ",", "$", "keys", "[", "3", "]", "=>", "$", "this", "->", "getValidUntil", "(", ")", ",", "$", "keys", "[", "4", "]", "=>", "$", "this", "->", "getSerial", "(", ")", ",", ")", ";", "$", "virtualColumns", "=", "$", "this", "->", "virtualColumns", ";", "foreach", "(", "$", "virtualColumns", "as", "$", "key", "=>", "$", "virtualColumn", ")", "{", "$", "result", "[", "$", "key", "]", "=", "$", "virtualColumn", ";", "}", "return", "$", "result", ";", "}" ]
Exports the object as an array. You can specify the key type of the array by passing one of the class type constants. @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. Defaults to BasePeer::TYPE_PHPNAME. @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to true. @param array $alreadyDumpedObjects List of objects to skip to avoid recursion @return array an associative array containing the field names (as keys) and field values
[ "Exports", "the", "object", "as", "an", "array", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L717-L738
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.setByPosition
public function setByPosition($pos, $value) { switch ($pos) { case 0: $this->setId($value); break; case 1: $this->setMaxClients($value); break; case 2: $this->setDomain($value); break; case 3: $this->setValidUntil($value); break; case 4: $this->setSerial($value); break; } // switch() }
php
public function setByPosition($pos, $value) { switch ($pos) { case 0: $this->setId($value); break; case 1: $this->setMaxClients($value); break; case 2: $this->setDomain($value); break; case 3: $this->setValidUntil($value); break; case 4: $this->setSerial($value); break; } // switch() }
[ "public", "function", "setByPosition", "(", "$", "pos", ",", "$", "value", ")", "{", "switch", "(", "$", "pos", ")", "{", "case", "0", ":", "$", "this", "->", "setId", "(", "$", "value", ")", ";", "break", ";", "case", "1", ":", "$", "this", "->", "setMaxClients", "(", "$", "value", ")", ";", "break", ";", "case", "2", ":", "$", "this", "->", "setDomain", "(", "$", "value", ")", ";", "break", ";", "case", "3", ":", "$", "this", "->", "setValidUntil", "(", "$", "value", ")", ";", "break", ";", "case", "4", ":", "$", "this", "->", "setSerial", "(", "$", "value", ")", ";", "break", ";", "}", "// switch()", "}" ]
Sets a field from the object by Position as specified in the xml schema. Zero-based. @param int $pos position in xml schema @param mixed $value field value @return void
[ "Sets", "a", "field", "from", "the", "object", "by", "Position", "as", "specified", "in", "the", "xml", "schema", ".", "Zero", "-", "based", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L766-L785
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.fromArray
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { $keys = LicensePeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setMaxClients($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setDomain($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setValidUntil($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setSerial($arr[$keys[4]]); }
php
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { $keys = LicensePeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setMaxClients($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setDomain($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setValidUntil($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setSerial($arr[$keys[4]]); }
[ "public", "function", "fromArray", "(", "$", "arr", ",", "$", "keyType", "=", "BasePeer", "::", "TYPE_PHPNAME", ")", "{", "$", "keys", "=", "LicensePeer", "::", "getFieldNames", "(", "$", "keyType", ")", ";", "if", "(", "array_key_exists", "(", "$", "keys", "[", "0", "]", ",", "$", "arr", ")", ")", "$", "this", "->", "setId", "(", "$", "arr", "[", "$", "keys", "[", "0", "]", "]", ")", ";", "if", "(", "array_key_exists", "(", "$", "keys", "[", "1", "]", ",", "$", "arr", ")", ")", "$", "this", "->", "setMaxClients", "(", "$", "arr", "[", "$", "keys", "[", "1", "]", "]", ")", ";", "if", "(", "array_key_exists", "(", "$", "keys", "[", "2", "]", ",", "$", "arr", ")", ")", "$", "this", "->", "setDomain", "(", "$", "arr", "[", "$", "keys", "[", "2", "]", "]", ")", ";", "if", "(", "array_key_exists", "(", "$", "keys", "[", "3", "]", ",", "$", "arr", ")", ")", "$", "this", "->", "setValidUntil", "(", "$", "arr", "[", "$", "keys", "[", "3", "]", "]", ")", ";", "if", "(", "array_key_exists", "(", "$", "keys", "[", "4", "]", ",", "$", "arr", ")", ")", "$", "this", "->", "setSerial", "(", "$", "arr", "[", "$", "keys", "[", "4", "]", "]", ")", ";", "}" ]
Populates the object using an array. This is particularly useful when populating an object from one of the request arrays (e.g. $_POST). This method goes through the column names, checking to see whether a matching key exists in populated array. If so the setByName() method is called for that column. You can specify the key type of the array by additionally passing one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. The default key type is the column's BasePeer::TYPE_PHPNAME @param array $arr An array to populate the object from. @param string $keyType The type of keys the array uses. @return void
[ "Populates", "the", "object", "using", "an", "array", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L804-L813
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.buildCriteria
public function buildCriteria() { $criteria = new Criteria(LicensePeer::DATABASE_NAME); if ($this->isColumnModified(LicensePeer::ID)) $criteria->add(LicensePeer::ID, $this->id); if ($this->isColumnModified(LicensePeer::MAX_CLIENTS)) $criteria->add(LicensePeer::MAX_CLIENTS, $this->max_clients); if ($this->isColumnModified(LicensePeer::DOMAIN)) $criteria->add(LicensePeer::DOMAIN, $this->domain); if ($this->isColumnModified(LicensePeer::VALID_UNTIL)) $criteria->add(LicensePeer::VALID_UNTIL, $this->valid_until); if ($this->isColumnModified(LicensePeer::SERIAL)) $criteria->add(LicensePeer::SERIAL, $this->serial); return $criteria; }
php
public function buildCriteria() { $criteria = new Criteria(LicensePeer::DATABASE_NAME); if ($this->isColumnModified(LicensePeer::ID)) $criteria->add(LicensePeer::ID, $this->id); if ($this->isColumnModified(LicensePeer::MAX_CLIENTS)) $criteria->add(LicensePeer::MAX_CLIENTS, $this->max_clients); if ($this->isColumnModified(LicensePeer::DOMAIN)) $criteria->add(LicensePeer::DOMAIN, $this->domain); if ($this->isColumnModified(LicensePeer::VALID_UNTIL)) $criteria->add(LicensePeer::VALID_UNTIL, $this->valid_until); if ($this->isColumnModified(LicensePeer::SERIAL)) $criteria->add(LicensePeer::SERIAL, $this->serial); return $criteria; }
[ "public", "function", "buildCriteria", "(", ")", "{", "$", "criteria", "=", "new", "Criteria", "(", "LicensePeer", "::", "DATABASE_NAME", ")", ";", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "ID", ")", ")", "$", "criteria", "->", "add", "(", "LicensePeer", "::", "ID", ",", "$", "this", "->", "id", ")", ";", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "MAX_CLIENTS", ")", ")", "$", "criteria", "->", "add", "(", "LicensePeer", "::", "MAX_CLIENTS", ",", "$", "this", "->", "max_clients", ")", ";", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "DOMAIN", ")", ")", "$", "criteria", "->", "add", "(", "LicensePeer", "::", "DOMAIN", ",", "$", "this", "->", "domain", ")", ";", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "VALID_UNTIL", ")", ")", "$", "criteria", "->", "add", "(", "LicensePeer", "::", "VALID_UNTIL", ",", "$", "this", "->", "valid_until", ")", ";", "if", "(", "$", "this", "->", "isColumnModified", "(", "LicensePeer", "::", "SERIAL", ")", ")", "$", "criteria", "->", "add", "(", "LicensePeer", "::", "SERIAL", ",", "$", "this", "->", "serial", ")", ";", "return", "$", "criteria", ";", "}" ]
Build a Criteria object containing the values of all modified columns in this object. @return Criteria The Criteria object containing all modified values.
[ "Build", "a", "Criteria", "object", "containing", "the", "values", "of", "all", "modified", "columns", "in", "this", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L820-L831
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.copyInto
public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { $copyObj->setMaxClients($this->getMaxClients()); $copyObj->setDomain($this->getDomain()); $copyObj->setValidUntil($this->getValidUntil()); $copyObj->setSerial($this->getSerial()); if ($makeNew) { $copyObj->setNew(true); $copyObj->setId(NULL); // this is a auto-increment column, so set to default value } }
php
public function copyInto($copyObj, $deepCopy = false, $makeNew = true) { $copyObj->setMaxClients($this->getMaxClients()); $copyObj->setDomain($this->getDomain()); $copyObj->setValidUntil($this->getValidUntil()); $copyObj->setSerial($this->getSerial()); if ($makeNew) { $copyObj->setNew(true); $copyObj->setId(NULL); // this is a auto-increment column, so set to default value } }
[ "public", "function", "copyInto", "(", "$", "copyObj", ",", "$", "deepCopy", "=", "false", ",", "$", "makeNew", "=", "true", ")", "{", "$", "copyObj", "->", "setMaxClients", "(", "$", "this", "->", "getMaxClients", "(", ")", ")", ";", "$", "copyObj", "->", "setDomain", "(", "$", "this", "->", "getDomain", "(", ")", ")", ";", "$", "copyObj", "->", "setValidUntil", "(", "$", "this", "->", "getValidUntil", "(", ")", ")", ";", "$", "copyObj", "->", "setSerial", "(", "$", "this", "->", "getSerial", "(", ")", ")", ";", "if", "(", "$", "makeNew", ")", "{", "$", "copyObj", "->", "setNew", "(", "true", ")", ";", "$", "copyObj", "->", "setId", "(", "NULL", ")", ";", "// this is a auto-increment column, so set to default value", "}", "}" ]
Sets contents of passed object to values from current object. If desired, this method can also make copies of all associated (fkey referrers) objects. @param object $copyObj An object of License (or compatible) type. @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. @throws PropelException
[ "Sets", "contents", "of", "passed", "object", "to", "values", "from", "current", "object", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L890-L900
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.clear
public function clear() { $this->id = null; $this->max_clients = null; $this->domain = null; $this->valid_until = null; $this->serial = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->alreadyInClearAllReferencesDeep = false; $this->clearAllReferences(); $this->resetModified(); $this->setNew(true); $this->setDeleted(false); }
php
public function clear() { $this->id = null; $this->max_clients = null; $this->domain = null; $this->valid_until = null; $this->serial = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->alreadyInClearAllReferencesDeep = false; $this->clearAllReferences(); $this->resetModified(); $this->setNew(true); $this->setDeleted(false); }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "id", "=", "null", ";", "$", "this", "->", "max_clients", "=", "null", ";", "$", "this", "->", "domain", "=", "null", ";", "$", "this", "->", "valid_until", "=", "null", ";", "$", "this", "->", "serial", "=", "null", ";", "$", "this", "->", "alreadyInSave", "=", "false", ";", "$", "this", "->", "alreadyInValidation", "=", "false", ";", "$", "this", "->", "alreadyInClearAllReferencesDeep", "=", "false", ";", "$", "this", "->", "clearAllReferences", "(", ")", ";", "$", "this", "->", "resetModified", "(", ")", ";", "$", "this", "->", "setNew", "(", "true", ")", ";", "$", "this", "->", "setDeleted", "(", "false", ")", ";", "}" ]
Clears the current object and sets all attributes to their default values
[ "Clears", "the", "current", "object", "and", "sets", "all", "attributes", "to", "their", "default", "values" ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L945-L959
slashworks/control-bundle
src/Slashworks/AppBundle/Model/om/BaseLicense.php
BaseLicense.clearAllReferences
public function clearAllReferences($deep = false) { if ($deep && !$this->alreadyInClearAllReferencesDeep) { $this->alreadyInClearAllReferencesDeep = true; $this->alreadyInClearAllReferencesDeep = false; } // if ($deep) }
php
public function clearAllReferences($deep = false) { if ($deep && !$this->alreadyInClearAllReferencesDeep) { $this->alreadyInClearAllReferencesDeep = true; $this->alreadyInClearAllReferencesDeep = false; } // if ($deep) }
[ "public", "function", "clearAllReferences", "(", "$", "deep", "=", "false", ")", "{", "if", "(", "$", "deep", "&&", "!", "$", "this", "->", "alreadyInClearAllReferencesDeep", ")", "{", "$", "this", "->", "alreadyInClearAllReferencesDeep", "=", "true", ";", "$", "this", "->", "alreadyInClearAllReferencesDeep", "=", "false", ";", "}", "// if ($deep)", "}" ]
Resets all references to other model objects or collections of model objects. This method is a user-space workaround for PHP's inability to garbage collect objects with circular references (even in PHP 5.3). This is currently necessary when using Propel in certain daemon or large-volume/high-memory operations. @param boolean $deep Whether to also clear the references on all referrer objects.
[ "Resets", "all", "references", "to", "other", "model", "objects", "or", "collections", "of", "model", "objects", "." ]
train
https://github.com/slashworks/control-bundle/blob/2ba86d96f1f41f9424e2229c4e2b13017e973f89/src/Slashworks/AppBundle/Model/om/BaseLicense.php#L970-L978
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit.mock
public static function mock($mockedClass) { $reflection = self::getMockReflection($mockedClass); return static::mockClass( $reflection, self::$namespace, self::$classBasePrefix ); }
php
public static function mock($mockedClass) { $reflection = self::getMockReflection($mockedClass); return static::mockClass( $reflection, self::$namespace, self::$classBasePrefix ); }
[ "public", "static", "function", "mock", "(", "$", "mockedClass", ")", "{", "$", "reflection", "=", "self", "::", "getMockReflection", "(", "$", "mockedClass", ")", ";", "return", "static", "::", "mockClass", "(", "$", "reflection", ",", "self", "::", "$", "namespace", ",", "self", "::", "$", "classBasePrefix", ")", ";", "}" ]
Mocking interfaces & classes @desc Ignoring final and private methods Examples: // Creating a new mock for SimpleClassForMocking $mock = ShortifyPunit::mock('SimpleClassForMocking'); // Returns NULL, was not stubbed yet $mock->first_method(); @param $mockedClass @return mixed
[ "Mocking", "interfaces", "&", "classes" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L95-L104
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit.partialMock
public static function partialMock($mockedClass) { $reflection = self::getMockReflection($mockedClass); return static::mockClass( $reflection, self::$namespace, self::$classBasePrefix, MockTypes::PARTIAL ); }
php
public static function partialMock($mockedClass) { $reflection = self::getMockReflection($mockedClass); return static::mockClass( $reflection, self::$namespace, self::$classBasePrefix, MockTypes::PARTIAL ); }
[ "public", "static", "function", "partialMock", "(", "$", "mockedClass", ")", "{", "$", "reflection", "=", "self", "::", "getMockReflection", "(", "$", "mockedClass", ")", ";", "return", "static", "::", "mockClass", "(", "$", "reflection", ",", "self", "::", "$", "namespace", ",", "self", "::", "$", "classBasePrefix", ",", "MockTypes", "::", "PARTIAL", ")", ";", "}" ]
Partial Mocking interfaces & classes @desc Partial mock is not stubbing any function by default (to NULL) like in regular mock() Examples: // class to partial mock class Foo { function bar() { return 'bar'; } } $mock = ShortifyPunit::mock('Foo'); $partialMock = ShortifyPunit::partialMock('Foo'); $mock->bar(); // returns NULL echo $partialMock->bar(); // prints 'bar' ShortifyPunit::when($partialMock)->bar()->returns('foo'); // stubbing partial mock echo $partialMock->bar(); // prints 'foo' @param $mockedClass @return mixed
[ "Partial", "Mocking", "interfaces", "&", "classes" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L129-L139
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit._isMethodStubbed
protected static function _isMethodStubbed($className, $instanceId, $methodName) { // check if instance of this method even exist if ( ! isset(self::$returnValues[$className][$instanceId][$methodName])) { return false; } return true; }
php
protected static function _isMethodStubbed($className, $instanceId, $methodName) { // check if instance of this method even exist if ( ! isset(self::$returnValues[$className][$instanceId][$methodName])) { return false; } return true; }
[ "protected", "static", "function", "_isMethodStubbed", "(", "$", "className", ",", "$", "instanceId", ",", "$", "methodName", ")", "{", "// check if instance of this method even exist", "if", "(", "!", "isset", "(", "self", "::", "$", "returnValues", "[", "$", "className", "]", "[", "$", "instanceId", "]", "[", "$", "methodName", "]", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checking if a method with specific arguments has been stubbed @param $className @param $instanceId @param $methodName @return bool
[ "Checking", "if", "a", "method", "with", "specific", "arguments", "has", "been", "stubbed" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L229-L237
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit._createChainResponse
protected static function _createChainResponse( $mockClassInstanceId, $mockClassType, $chainedMethodsBefore, $currentMethod, $args ) { $currentMethodName = key($currentMethod); $rReturnValues = &self::getMockHierarchyResponse( $chainedMethodsBefore, $mockClassType, $mockClassInstanceId ); // Check current method exist in return values chain $serializedArgs = serialize($args); if ( ! isset($rReturnValues[$currentMethodName][$serializedArgs]['response'])) { $serializedArgs = static::checkMatchingArguments( $rReturnValues[$currentMethodName], $args ); if (is_null($serializedArgs)) { return null; } } return self::generateResponse( $rReturnValues[$currentMethodName][$serializedArgs]['response'], $args ); }
php
protected static function _createChainResponse( $mockClassInstanceId, $mockClassType, $chainedMethodsBefore, $currentMethod, $args ) { $currentMethodName = key($currentMethod); $rReturnValues = &self::getMockHierarchyResponse( $chainedMethodsBefore, $mockClassType, $mockClassInstanceId ); // Check current method exist in return values chain $serializedArgs = serialize($args); if ( ! isset($rReturnValues[$currentMethodName][$serializedArgs]['response'])) { $serializedArgs = static::checkMatchingArguments( $rReturnValues[$currentMethodName], $args ); if (is_null($serializedArgs)) { return null; } } return self::generateResponse( $rReturnValues[$currentMethodName][$serializedArgs]['response'], $args ); }
[ "protected", "static", "function", "_createChainResponse", "(", "$", "mockClassInstanceId", ",", "$", "mockClassType", ",", "$", "chainedMethodsBefore", ",", "$", "currentMethod", ",", "$", "args", ")", "{", "$", "currentMethodName", "=", "key", "(", "$", "currentMethod", ")", ";", "$", "rReturnValues", "=", "&", "self", "::", "getMockHierarchyResponse", "(", "$", "chainedMethodsBefore", ",", "$", "mockClassType", ",", "$", "mockClassInstanceId", ")", ";", "// Check current method exist in return values chain", "$", "serializedArgs", "=", "serialize", "(", "$", "args", ")", ";", "if", "(", "!", "isset", "(", "$", "rReturnValues", "[", "$", "currentMethodName", "]", "[", "$", "serializedArgs", "]", "[", "'response'", "]", ")", ")", "{", "$", "serializedArgs", "=", "static", "::", "checkMatchingArguments", "(", "$", "rReturnValues", "[", "$", "currentMethodName", "]", ",", "$", "args", ")", ";", "if", "(", "is_null", "(", "$", "serializedArgs", ")", ")", "{", "return", "null", ";", "}", "}", "return", "self", "::", "generateResponse", "(", "$", "rReturnValues", "[", "$", "currentMethodName", "]", "[", "$", "serializedArgs", "]", "[", "'response'", "]", ",", "$", "args", ")", ";", "}" ]
Setting up a chained mock response, function is called from mocked classes @param $mockClassInstanceId @param $mockClassType @param $chainedMethodsBefore @param $currentMethod @param $args @return null
[ "Setting", "up", "a", "chained", "mock", "response", "function", "is", "called", "from", "mocked", "classes" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L249-L283
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit._setWhenMockResponse
protected static function _setWhenMockResponse( $className, $instanceId, $methodName, $args, $action, $returns ) { $args = serialize($args); $returnValues = array(); $returnValues[$className][$instanceId][$methodName][$args]['response'] = ['action' => $action, 'value' => $returns]; self::_addChainedResponse($returnValues); }
php
protected static function _setWhenMockResponse( $className, $instanceId, $methodName, $args, $action, $returns ) { $args = serialize($args); $returnValues = array(); $returnValues[$className][$instanceId][$methodName][$args]['response'] = ['action' => $action, 'value' => $returns]; self::_addChainedResponse($returnValues); }
[ "protected", "static", "function", "_setWhenMockResponse", "(", "$", "className", ",", "$", "instanceId", ",", "$", "methodName", ",", "$", "args", ",", "$", "action", ",", "$", "returns", ")", "{", "$", "args", "=", "serialize", "(", "$", "args", ")", ";", "$", "returnValues", "=", "array", "(", ")", ";", "$", "returnValues", "[", "$", "className", "]", "[", "$", "instanceId", "]", "[", "$", "methodName", "]", "[", "$", "args", "]", "[", "'response'", "]", "=", "[", "'action'", "=>", "$", "action", ",", "'value'", "=>", "$", "returns", "]", ";", "self", "::", "_addChainedResponse", "(", "$", "returnValues", ")", ";", "}" ]
Setting up a mock response, function is called from mocked classes @param $className @param $instanceId @param $methodName @param $args @param $action @param $returns
[ "Setting", "up", "a", "mock", "response", "function", "is", "called", "from", "mocked", "classes" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L297-L311
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit._createResponse
protected static function _createResponse($className, $instanceId, $methodName, $arguments) { $args = serialize($arguments); // check if instance of this method even exist if ( ! isset(self::$returnValues[$className][$instanceId][$methodName])) { return null; } // Check if doesn't exist as-is in return values array if ( ! isset(self::$returnValues[$className][$instanceId][$methodName][$args]['response'])) { // try to finding matching Hamcrest-API Function (anything(), equalTo()) $returnValues = self::$returnValues[$className][$instanceId][$methodName]; $args = static::checkMatchingArguments($returnValues, $arguments); } return is_null($args) ? null : self::generateResponse(self::$returnValues[$className][$instanceId][$methodName][$args]['response'], $arguments); }
php
protected static function _createResponse($className, $instanceId, $methodName, $arguments) { $args = serialize($arguments); // check if instance of this method even exist if ( ! isset(self::$returnValues[$className][$instanceId][$methodName])) { return null; } // Check if doesn't exist as-is in return values array if ( ! isset(self::$returnValues[$className][$instanceId][$methodName][$args]['response'])) { // try to finding matching Hamcrest-API Function (anything(), equalTo()) $returnValues = self::$returnValues[$className][$instanceId][$methodName]; $args = static::checkMatchingArguments($returnValues, $arguments); } return is_null($args) ? null : self::generateResponse(self::$returnValues[$className][$instanceId][$methodName][$args]['response'], $arguments); }
[ "protected", "static", "function", "_createResponse", "(", "$", "className", ",", "$", "instanceId", ",", "$", "methodName", ",", "$", "arguments", ")", "{", "$", "args", "=", "serialize", "(", "$", "arguments", ")", ";", "// check if instance of this method even exist", "if", "(", "!", "isset", "(", "self", "::", "$", "returnValues", "[", "$", "className", "]", "[", "$", "instanceId", "]", "[", "$", "methodName", "]", ")", ")", "{", "return", "null", ";", "}", "// Check if doesn't exist as-is in return values array", "if", "(", "!", "isset", "(", "self", "::", "$", "returnValues", "[", "$", "className", "]", "[", "$", "instanceId", "]", "[", "$", "methodName", "]", "[", "$", "args", "]", "[", "'response'", "]", ")", ")", "{", "// try to finding matching Hamcrest-API Function (anything(), equalTo())", "$", "returnValues", "=", "self", "::", "$", "returnValues", "[", "$", "className", "]", "[", "$", "instanceId", "]", "[", "$", "methodName", "]", ";", "$", "args", "=", "static", "::", "checkMatchingArguments", "(", "$", "returnValues", ",", "$", "arguments", ")", ";", "}", "return", "is_null", "(", "$", "args", ")", "?", "null", ":", "self", "::", "generateResponse", "(", "self", "::", "$", "returnValues", "[", "$", "className", "]", "[", "$", "instanceId", "]", "[", "$", "methodName", "]", "[", "$", "args", "]", "[", "'response'", "]", ",", "$", "arguments", ")", ";", "}" ]
Create response is a private method which is called from the Mocked classes returns a value which was set before in the When() function otherwise returning NULL @param $className @param $instanceId @param $methodName @param $arguments @internal param $args @return Mixed | null
[ "Create", "response", "is", "a", "private", "method", "which", "is", "called", "from", "the", "Mocked", "classes", "returns", "a", "value", "which", "was", "set", "before", "in", "the", "When", "()", "function", "otherwise", "returning", "NULL" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L333-L351
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit._addChainedResponse
protected static function _addChainedResponse($response) { $firstChainedMethodName = key($response); if (isset(self::$returnValues[$firstChainedMethodName])) { self::$returnValues[$firstChainedMethodName] = array_replace_recursive( self::$returnValues[$firstChainedMethodName], $response[$firstChainedMethodName] ); } else { self::$returnValues[$firstChainedMethodName] = $response[$firstChainedMethodName]; } }
php
protected static function _addChainedResponse($response) { $firstChainedMethodName = key($response); if (isset(self::$returnValues[$firstChainedMethodName])) { self::$returnValues[$firstChainedMethodName] = array_replace_recursive( self::$returnValues[$firstChainedMethodName], $response[$firstChainedMethodName] ); } else { self::$returnValues[$firstChainedMethodName] = $response[$firstChainedMethodName]; } }
[ "protected", "static", "function", "_addChainedResponse", "(", "$", "response", ")", "{", "$", "firstChainedMethodName", "=", "key", "(", "$", "response", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "returnValues", "[", "$", "firstChainedMethodName", "]", ")", ")", "{", "self", "::", "$", "returnValues", "[", "$", "firstChainedMethodName", "]", "=", "array_replace_recursive", "(", "self", "::", "$", "returnValues", "[", "$", "firstChainedMethodName", "]", ",", "$", "response", "[", "$", "firstChainedMethodName", "]", ")", ";", "}", "else", "{", "self", "::", "$", "returnValues", "[", "$", "firstChainedMethodName", "]", "=", "$", "response", "[", "$", "firstChainedMethodName", "]", ";", "}", "}" ]
Adding chained response to ReturnValues array @param $response
[ "Adding", "chained", "response", "to", "ReturnValues", "array" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L358-L370
danrevah/shortify-punit
src/ShortifyPunit.php
ShortifyPunit.&
private static function &getMockHierarchyResponse( $chainedMethodsBefore, $mockClassType, $mockClassInstanceId ) { $rReturnValues = &self::$returnValues[$mockClassType][$mockClassInstanceId]; // Check return values chain foreach ($chainedMethodsBefore as $chainedMethod) { $chainedMethodName = key($chainedMethod); $chainedMethodArgs = $chainedMethod[$chainedMethodName]; $serializedChainMethodArgs = serialize($chainedMethodArgs); $rReturnValues = & $rReturnValues[$chainedMethodName][$serializedChainMethodArgs]; } return $rReturnValues; }
php
private static function &getMockHierarchyResponse( $chainedMethodsBefore, $mockClassType, $mockClassInstanceId ) { $rReturnValues = &self::$returnValues[$mockClassType][$mockClassInstanceId]; // Check return values chain foreach ($chainedMethodsBefore as $chainedMethod) { $chainedMethodName = key($chainedMethod); $chainedMethodArgs = $chainedMethod[$chainedMethodName]; $serializedChainMethodArgs = serialize($chainedMethodArgs); $rReturnValues = & $rReturnValues[$chainedMethodName][$serializedChainMethodArgs]; } return $rReturnValues; }
[ "private", "static", "function", "&", "getMockHierarchyResponse", "(", "$", "chainedMethodsBefore", ",", "$", "mockClassType", ",", "$", "mockClassInstanceId", ")", "{", "$", "rReturnValues", "=", "&", "self", "::", "$", "returnValues", "[", "$", "mockClassType", "]", "[", "$", "mockClassInstanceId", "]", ";", "// Check return values chain", "foreach", "(", "$", "chainedMethodsBefore", "as", "$", "chainedMethod", ")", "{", "$", "chainedMethodName", "=", "key", "(", "$", "chainedMethod", ")", ";", "$", "chainedMethodArgs", "=", "$", "chainedMethod", "[", "$", "chainedMethodName", "]", ";", "$", "serializedChainMethodArgs", "=", "serialize", "(", "$", "chainedMethodArgs", ")", ";", "$", "rReturnValues", "=", "&", "$", "rReturnValues", "[", "$", "chainedMethodName", "]", "[", "$", "serializedChainMethodArgs", "]", ";", "}", "return", "$", "rReturnValues", ";", "}" ]
Returns the mock hierarchy response values @param $chainedMethodsBefore @param $mockClassType @param $mockClassInstanceId @return mixed
[ "Returns", "the", "mock", "hierarchy", "response", "values" ]
train
https://github.com/danrevah/shortify-punit/blob/cedd08f31de8e7409a07d2630701ef4e924cc5f0/src/ShortifyPunit.php#L398-L414
forxer/tao
src/Tao/Templating/Helpers/Router.php
Router.generate
public function generate($name, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH) { return $this->generator->generate($name, $parameters, $referenceType); }
php
public function generate($name, array $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH) { return $this->generator->generate($name, $parameters, $referenceType); }
[ "public", "function", "generate", "(", "$", "name", ",", "array", "$", "parameters", "=", "[", "]", ",", "$", "referenceType", "=", "UrlGeneratorInterface", "::", "ABSOLUTE_PATH", ")", "{", "return", "$", "this", "->", "generator", "->", "generate", "(", "$", "name", ",", "$", "parameters", ",", "$", "referenceType", ")", ";", "}" ]
Generates a URL from the given parameters. @param string $name The name of the route @param mixed $parameters An array of parameters @param bool|string $referenceType The type of reference (one of the constants in UrlGeneratorInterface) @return string The generated URL @see UrlGeneratorInterface
[ "Generates", "a", "URL", "from", "the", "given", "parameters", "." ]
train
https://github.com/forxer/tao/blob/b5e9109c244a29a72403ae6a58633ab96a67c660/src/Tao/Templating/Helpers/Router.php#L32-L35
yuncms/framework
src/jobs/SocialAvatarDownloadJob.php
SocialAvatarDownloadJob.execute
public function execute($queue) { if (($user = $this->getUser()) != null) { $originalImage = Yii::getAlias('@runtime/') . $user->id . '_avatar.jpg'; //下载图片 if (($image = @file_get_contents($this->faceUrl)) != false) { //保存原图 file_put_contents($originalImage, $image); AvatarHelper::save($user, $originalImage); }; } }
php
public function execute($queue) { if (($user = $this->getUser()) != null) { $originalImage = Yii::getAlias('@runtime/') . $user->id . '_avatar.jpg'; //下载图片 if (($image = @file_get_contents($this->faceUrl)) != false) { //保存原图 file_put_contents($originalImage, $image); AvatarHelper::save($user, $originalImage); }; } }
[ "public", "function", "execute", "(", "$", "queue", ")", "{", "if", "(", "(", "$", "user", "=", "$", "this", "->", "getUser", "(", ")", ")", "!=", "null", ")", "{", "$", "originalImage", "=", "Yii", "::", "getAlias", "(", "'@runtime/'", ")", ".", "$", "user", "->", "id", ".", "'_avatar.jpg'", ";", "//下载图片", "if", "(", "(", "$", "image", "=", "@", "file_get_contents", "(", "$", "this", "->", "faceUrl", ")", ")", "!=", "false", ")", "{", "//保存原图", "file_put_contents", "(", "$", "originalImage", ",", "$", "image", ")", ";", "AvatarHelper", "::", "save", "(", "$", "user", ",", "$", "originalImage", ")", ";", "}", ";", "}", "}" ]
下载头像并保存 @param \yii\queue\Queue $queue @throws \yii\base\ErrorException @throws \yii\base\Exception
[ "下载头像并保存" ]
train
https://github.com/yuncms/framework/blob/af42e28ea4ae15ab8eead3f6d119f93863b94154/src/jobs/SocialAvatarDownloadJob.php#L44-L55
phpmob/changmin
src/PhpMob/ChangMinBundle/Fixture/TaxonFixture.php
TaxonFixture.configureResourceNode
protected function configureResourceNode(ArrayNodeDefinition $resourceNode) { $resourceNode ->children() ->scalarNode('code')->cannotBeEmpty()->end() ->variableNode('name')->cannotBeEmpty()->end() ->variableNode('slug')->cannotBeEmpty()->end() ->variableNode('description')->cannotBeEmpty()->end() ->variableNode('children')->end() ; }
php
protected function configureResourceNode(ArrayNodeDefinition $resourceNode) { $resourceNode ->children() ->scalarNode('code')->cannotBeEmpty()->end() ->variableNode('name')->cannotBeEmpty()->end() ->variableNode('slug')->cannotBeEmpty()->end() ->variableNode('description')->cannotBeEmpty()->end() ->variableNode('children')->end() ; }
[ "protected", "function", "configureResourceNode", "(", "ArrayNodeDefinition", "$", "resourceNode", ")", "{", "$", "resourceNode", "->", "children", "(", ")", "->", "scalarNode", "(", "'code'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "variableNode", "(", "'name'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "variableNode", "(", "'slug'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "variableNode", "(", "'description'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "variableNode", "(", "'children'", ")", "->", "end", "(", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/phpmob/changmin/blob/bfebb1561229094d1c138574abab75f2f1d17d66/src/PhpMob/ChangMinBundle/Fixture/TaxonFixture.php#L34-L44