repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
infusephp/auth
src/Libs/Storage/SymfonySessionStorage.php
SymfonySessionStorage.getUserRememberMe
private function getUserRememberMe(Request $req, Response $res) { // retrieve and verify the remember me cookie $cookie = $this->getRememberMeCookie($req); if (!$cookie) { return false; } $user = $cookie->verify($req, $this->auth); if (!$user) { $this->destroyRememberMeCookie($req, $res); return false; } $signedInUser = $this->auth->signInUser($user, 'remember_me'); // generate a new remember me cookie for the next time, using // the same series $new = new RememberMeCookie($user->email(), $req->agent(), $cookie->getSeries()); $this->sendRememberMeCookie($user, $new, $res); // mark this session as remembered (could be useful to know) $this->getSession()->set(self::SESSION_REMEMBERED_KEY, true); $req->setSession(self::SESSION_REMEMBERED_KEY, true); return $signedInUser; }
php
private function getUserRememberMe(Request $req, Response $res) { // retrieve and verify the remember me cookie $cookie = $this->getRememberMeCookie($req); if (!$cookie) { return false; } $user = $cookie->verify($req, $this->auth); if (!$user) { $this->destroyRememberMeCookie($req, $res); return false; } $signedInUser = $this->auth->signInUser($user, 'remember_me'); // generate a new remember me cookie for the next time, using // the same series $new = new RememberMeCookie($user->email(), $req->agent(), $cookie->getSeries()); $this->sendRememberMeCookie($user, $new, $res); // mark this session as remembered (could be useful to know) $this->getSession()->set(self::SESSION_REMEMBERED_KEY, true); $req->setSession(self::SESSION_REMEMBERED_KEY, true); return $signedInUser; }
[ "private", "function", "getUserRememberMe", "(", "Request", "$", "req", ",", "Response", "$", "res", ")", "{", "// retrieve and verify the remember me cookie", "$", "cookie", "=", "$", "this", "->", "getRememberMeCookie", "(", "$", "req", ")", ";", "if", "(", "!", "$", "cookie", ")", "{", "return", "false", ";", "}", "$", "user", "=", "$", "cookie", "->", "verify", "(", "$", "req", ",", "$", "this", "->", "auth", ")", ";", "if", "(", "!", "$", "user", ")", "{", "$", "this", "->", "destroyRememberMeCookie", "(", "$", "req", ",", "$", "res", ")", ";", "return", "false", ";", "}", "$", "signedInUser", "=", "$", "this", "->", "auth", "->", "signInUser", "(", "$", "user", ",", "'remember_me'", ")", ";", "// generate a new remember me cookie for the next time, using", "// the same series", "$", "new", "=", "new", "RememberMeCookie", "(", "$", "user", "->", "email", "(", ")", ",", "$", "req", "->", "agent", "(", ")", ",", "$", "cookie", "->", "getSeries", "(", ")", ")", ";", "$", "this", "->", "sendRememberMeCookie", "(", "$", "user", ",", "$", "new", ",", "$", "res", ")", ";", "// mark this session as remembered (could be useful to know)", "$", "this", "->", "getSession", "(", ")", "->", "set", "(", "self", "::", "SESSION_REMEMBERED_KEY", ",", "true", ")", ";", "$", "req", "->", "setSession", "(", "self", "::", "SESSION_REMEMBERED_KEY", ",", "true", ")", ";", "return", "$", "signedInUser", ";", "}" ]
Tries to get an authenticated user via remember me. @param Request $req @param Response $res @return UserInterface|false
[ "Tries", "to", "get", "an", "authenticated", "user", "via", "remember", "me", "." ]
720280b4b2635572f331afe8d082e3e88cf54eb7
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L313-L342
train
infusephp/auth
src/Libs/Storage/SymfonySessionStorage.php
SymfonySessionStorage.getRememberMeCookie
private function getRememberMeCookie(Request $req) { $encoded = $req->cookies($this->rememberMeCookieName()); if (!$encoded) { return false; } return RememberMeCookie::decode($encoded); }
php
private function getRememberMeCookie(Request $req) { $encoded = $req->cookies($this->rememberMeCookieName()); if (!$encoded) { return false; } return RememberMeCookie::decode($encoded); }
[ "private", "function", "getRememberMeCookie", "(", "Request", "$", "req", ")", "{", "$", "encoded", "=", "$", "req", "->", "cookies", "(", "$", "this", "->", "rememberMeCookieName", "(", ")", ")", ";", "if", "(", "!", "$", "encoded", ")", "{", "return", "false", ";", "}", "return", "RememberMeCookie", "::", "decode", "(", "$", "encoded", ")", ";", "}" ]
Gets the decoded remember me cookie from the request. @param Request $req @return RememberMeCookie|false
[ "Gets", "the", "decoded", "remember", "me", "cookie", "from", "the", "request", "." ]
720280b4b2635572f331afe8d082e3e88cf54eb7
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L351-L359
train
infusephp/auth
src/Libs/Storage/SymfonySessionStorage.php
SymfonySessionStorage.sendRememberMeCookie
private function sendRememberMeCookie(UserInterface $user, RememberMeCookie $cookie, Response $res) { // send the cookie with the same properties as the session cookie $sessionCookie = session_get_cookie_params(); $res->setCookie($this->rememberMeCookieName(), $cookie->encode(), $cookie->getExpires(time()), $sessionCookie['path'], $sessionCookie['domain'], $sessionCookie['secure'], true); // save the cookie in the DB $cookie->persist($user); }
php
private function sendRememberMeCookie(UserInterface $user, RememberMeCookie $cookie, Response $res) { // send the cookie with the same properties as the session cookie $sessionCookie = session_get_cookie_params(); $res->setCookie($this->rememberMeCookieName(), $cookie->encode(), $cookie->getExpires(time()), $sessionCookie['path'], $sessionCookie['domain'], $sessionCookie['secure'], true); // save the cookie in the DB $cookie->persist($user); }
[ "private", "function", "sendRememberMeCookie", "(", "UserInterface", "$", "user", ",", "RememberMeCookie", "$", "cookie", ",", "Response", "$", "res", ")", "{", "// send the cookie with the same properties as the session cookie", "$", "sessionCookie", "=", "session_get_cookie_params", "(", ")", ";", "$", "res", "->", "setCookie", "(", "$", "this", "->", "rememberMeCookieName", "(", ")", ",", "$", "cookie", "->", "encode", "(", ")", ",", "$", "cookie", "->", "getExpires", "(", "time", "(", ")", ")", ",", "$", "sessionCookie", "[", "'path'", "]", ",", "$", "sessionCookie", "[", "'domain'", "]", ",", "$", "sessionCookie", "[", "'secure'", "]", ",", "true", ")", ";", "// save the cookie in the DB", "$", "cookie", "->", "persist", "(", "$", "user", ")", ";", "}" ]
Stores a remember me session cookie on the response. @param UserInterface $user @param RememberMeCookie $cookie @param Response $res
[ "Stores", "a", "remember", "me", "session", "cookie", "on", "the", "response", "." ]
720280b4b2635572f331afe8d082e3e88cf54eb7
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L368-L382
train
infusephp/auth
src/Libs/Storage/SymfonySessionStorage.php
SymfonySessionStorage.destroyRememberMeCookie
private function destroyRememberMeCookie(Request $req, Response $res) { $cookie = $this->getRememberMeCookie($req); if ($cookie) { $cookie->destroy(); } $sessionCookie = session_get_cookie_params(); $res->setCookie($this->rememberMeCookieName(), '', time() - 86400, $sessionCookie['path'], $sessionCookie['domain'], $sessionCookie['secure'], true); return $this; }
php
private function destroyRememberMeCookie(Request $req, Response $res) { $cookie = $this->getRememberMeCookie($req); if ($cookie) { $cookie->destroy(); } $sessionCookie = session_get_cookie_params(); $res->setCookie($this->rememberMeCookieName(), '', time() - 86400, $sessionCookie['path'], $sessionCookie['domain'], $sessionCookie['secure'], true); return $this; }
[ "private", "function", "destroyRememberMeCookie", "(", "Request", "$", "req", ",", "Response", "$", "res", ")", "{", "$", "cookie", "=", "$", "this", "->", "getRememberMeCookie", "(", "$", "req", ")", ";", "if", "(", "$", "cookie", ")", "{", "$", "cookie", "->", "destroy", "(", ")", ";", "}", "$", "sessionCookie", "=", "session_get_cookie_params", "(", ")", ";", "$", "res", "->", "setCookie", "(", "$", "this", "->", "rememberMeCookieName", "(", ")", ",", "''", ",", "time", "(", ")", "-", "86400", ",", "$", "sessionCookie", "[", "'path'", "]", ",", "$", "sessionCookie", "[", "'domain'", "]", ",", "$", "sessionCookie", "[", "'secure'", "]", ",", "true", ")", ";", "return", "$", "this", ";", "}" ]
Destroys the remember me cookie. @param Request $req @param Response $res @return self
[ "Destroys", "the", "remember", "me", "cookie", "." ]
720280b4b2635572f331afe8d082e3e88cf54eb7
https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/Storage/SymfonySessionStorage.php#L392-L409
train
luoxiaojun1992/lb_framework
components/traits/lb/Cookie.php
Cookie.setCookie
public function setCookie($cookie_key, $cookie_value, $expire = null, $path = null, $domain = null, $secure = null, $httpOnly = null) { if ($this->isSingle()) { ResponseKit::setCookie($cookie_key, $cookie_value, $expire, $path, $domain, $secure, $httpOnly); } }
php
public function setCookie($cookie_key, $cookie_value, $expire = null, $path = null, $domain = null, $secure = null, $httpOnly = null) { if ($this->isSingle()) { ResponseKit::setCookie($cookie_key, $cookie_value, $expire, $path, $domain, $secure, $httpOnly); } }
[ "public", "function", "setCookie", "(", "$", "cookie_key", ",", "$", "cookie_value", ",", "$", "expire", "=", "null", ",", "$", "path", "=", "null", ",", "$", "domain", "=", "null", ",", "$", "secure", "=", "null", ",", "$", "httpOnly", "=", "null", ")", "{", "if", "(", "$", "this", "->", "isSingle", "(", ")", ")", "{", "ResponseKit", "::", "setCookie", "(", "$", "cookie_key", ",", "$", "cookie_value", ",", "$", "expire", ",", "$", "path", ",", "$", "domain", ",", "$", "secure", ",", "$", "httpOnly", ")", ";", "}", "}" ]
Set Cookie Value @param $cookie_key @param $cookie_value @param null $expire @param null $path @param null $domain @param null $secure @param null $httpOnly
[ "Set", "Cookie", "Value" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Cookie.php#L35-L40
train
luoxiaojun1992/lb_framework
components/traits/lb/Cookie.php
Cookie.delCookies
public function delCookies($cookie_keys) { if ($this->isSingle()) { foreach ($cookie_keys as $cookie_key) { $this->delCookie($cookie_key); } } }
php
public function delCookies($cookie_keys) { if ($this->isSingle()) { foreach ($cookie_keys as $cookie_key) { $this->delCookie($cookie_key); } } }
[ "public", "function", "delCookies", "(", "$", "cookie_keys", ")", "{", "if", "(", "$", "this", "->", "isSingle", "(", ")", ")", "{", "foreach", "(", "$", "cookie_keys", "as", "$", "cookie_key", ")", "{", "$", "this", "->", "delCookie", "(", "$", "cookie_key", ")", ";", "}", "}", "}" ]
Delete Multi Cookies @param $cookie_keys
[ "Delete", "Multi", "Cookies" ]
12a865729e7738d7d1e07371ad7203243c4571fa
https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Cookie.php#L61-L68
train
tidal/phpspec-console
spec/Command/InlineConfiguratorSpec.php
InlineConfiguratorSpec.createCommandProphecy
private function createCommandProphecy() { $prophet = new Prophet; $prophecy = $prophet->prophesize()->willImplement(InlineConfigCommandInterface::class); $prophecy ->setName('foo') ->shouldBeCalled(); $prophecy ->getConfig() ->willReturn(['name'=>'foo']); return $prophecy; }
php
private function createCommandProphecy() { $prophet = new Prophet; $prophecy = $prophet->prophesize()->willImplement(InlineConfigCommandInterface::class); $prophecy ->setName('foo') ->shouldBeCalled(); $prophecy ->getConfig() ->willReturn(['name'=>'foo']); return $prophecy; }
[ "private", "function", "createCommandProphecy", "(", ")", "{", "$", "prophet", "=", "new", "Prophet", ";", "$", "prophecy", "=", "$", "prophet", "->", "prophesize", "(", ")", "->", "willImplement", "(", "InlineConfigCommandInterface", "::", "class", ")", ";", "$", "prophecy", "->", "setName", "(", "'foo'", ")", "->", "shouldBeCalled", "(", ")", ";", "$", "prophecy", "->", "getConfig", "(", ")", "->", "willReturn", "(", "[", "'name'", "=>", "'foo'", "]", ")", ";", "return", "$", "prophecy", ";", "}" ]
override prophecy creation @return ObjectProphecy
[ "override", "prophecy", "creation" ]
5946f1dfdc30c4af5605a889a407b6113ee16d59
https://github.com/tidal/phpspec-console/blob/5946f1dfdc30c4af5605a889a407b6113ee16d59/spec/Command/InlineConfiguratorSpec.php#L35-L47
train
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
Configuration.validateComponentKeys
private function validateComponentKeys(array $v) { $diff = array_diff_key($v, array_flip($this->enabledComponentTypes)); if (!empty($diff)) { throw new InvalidConfigurationException(sprintf( 'Only "%s" component types are supported for configuration, "%s" more given.', implode('", "', $this->enabledComponentTypes), implode('", "', array_keys($diff)) )); } return $v; }
php
private function validateComponentKeys(array $v) { $diff = array_diff_key($v, array_flip($this->enabledComponentTypes)); if (!empty($diff)) { throw new InvalidConfigurationException(sprintf( 'Only "%s" component types are supported for configuration, "%s" more given.', implode('", "', $this->enabledComponentTypes), implode('", "', array_keys($diff)) )); } return $v; }
[ "private", "function", "validateComponentKeys", "(", "array", "$", "v", ")", "{", "$", "diff", "=", "array_diff_key", "(", "$", "v", ",", "array_flip", "(", "$", "this", "->", "enabledComponentTypes", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "diff", ")", ")", "{", "throw", "new", "InvalidConfigurationException", "(", "sprintf", "(", "'Only \"%s\" component types are supported for configuration, \"%s\" more given.'", ",", "implode", "(", "'\", \"'", ",", "$", "this", "->", "enabledComponentTypes", ")", ",", "implode", "(", "'\", \"'", ",", "array_keys", "(", "$", "diff", ")", ")", ")", ")", ";", "}", "return", "$", "v", ";", "}" ]
Validate given array keys are all registered components. @param array $v @return array
[ "Validate", "given", "array", "keys", "are", "all", "registered", "components", "." ]
d8122a4150a83d5607289724425cf35c56a5e880
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L44-L56
train
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
Configuration.hydrateTemplatesNode
private function hydrateTemplatesNode(NodeBuilder $node) { $node ->booleanNode('default') ->defaultFalse() ->end() ->scalarNode('path') ->cannotBeEmpty() ->end() ->arrayNode('contents') ->prototype('scalar') ->cannotBeEmpty() ->end() ->end() ; return $node; }
php
private function hydrateTemplatesNode(NodeBuilder $node) { $node ->booleanNode('default') ->defaultFalse() ->end() ->scalarNode('path') ->cannotBeEmpty() ->end() ->arrayNode('contents') ->prototype('scalar') ->cannotBeEmpty() ->end() ->end() ; return $node; }
[ "private", "function", "hydrateTemplatesNode", "(", "NodeBuilder", "$", "node", ")", "{", "$", "node", "->", "booleanNode", "(", "'default'", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'path'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'contents'", ")", "->", "prototype", "(", "'scalar'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Hydrate given node with templates configuration nodes. @param NodeBuilder $node @return NodeBuilder
[ "Hydrate", "given", "node", "with", "templates", "configuration", "nodes", "." ]
d8122a4150a83d5607289724425cf35c56a5e880
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L188-L205
train
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
Configuration.hydrateZonesNode
private function hydrateZonesNode(NodeBuilder $node) { $node ->booleanNode('main') ->defaultFalse() ->end() ->booleanNode('virtual') ->defaultFalse() ->end() ->arrayNode('aggregation') ->addDefaultsIfNotSet() ->beforeNormalization() ->always(function ($v) { if (is_string($v)) { // shortcut case $v = array('type' => $v); } if (is_array($v) && !empty($v['path'])) { // path shortcut case $v['type'] = 'template'; } return $v; }) ->end() ->children() ->scalarNode('type') ->defaultValue('inline') ->cannotBeEmpty() ->end() ->scalarNode('path')->end() ->end() ->end() ; return $node; }
php
private function hydrateZonesNode(NodeBuilder $node) { $node ->booleanNode('main') ->defaultFalse() ->end() ->booleanNode('virtual') ->defaultFalse() ->end() ->arrayNode('aggregation') ->addDefaultsIfNotSet() ->beforeNormalization() ->always(function ($v) { if (is_string($v)) { // shortcut case $v = array('type' => $v); } if (is_array($v) && !empty($v['path'])) { // path shortcut case $v['type'] = 'template'; } return $v; }) ->end() ->children() ->scalarNode('type') ->defaultValue('inline') ->cannotBeEmpty() ->end() ->scalarNode('path')->end() ->end() ->end() ; return $node; }
[ "private", "function", "hydrateZonesNode", "(", "NodeBuilder", "$", "node", ")", "{", "$", "node", "->", "booleanNode", "(", "'main'", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "booleanNode", "(", "'virtual'", ")", "->", "defaultFalse", "(", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'aggregation'", ")", "->", "addDefaultsIfNotSet", "(", ")", "->", "beforeNormalization", "(", ")", "->", "always", "(", "function", "(", "$", "v", ")", "{", "if", "(", "is_string", "(", "$", "v", ")", ")", "{", "// shortcut case", "$", "v", "=", "array", "(", "'type'", "=>", "$", "v", ")", ";", "}", "if", "(", "is_array", "(", "$", "v", ")", "&&", "!", "empty", "(", "$", "v", "[", "'path'", "]", ")", ")", "{", "// path shortcut case", "$", "v", "[", "'type'", "]", "=", "'template'", ";", "}", "return", "$", "v", ";", "}", ")", "->", "end", "(", ")", "->", "children", "(", ")", "->", "scalarNode", "(", "'type'", ")", "->", "defaultValue", "(", "'inline'", ")", "->", "cannotBeEmpty", "(", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'path'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Hydrate given node with zones configuration nodes. @param NodeBuilder $node @return NodeBuilder
[ "Hydrate", "given", "node", "with", "zones", "configuration", "nodes", "." ]
d8122a4150a83d5607289724425cf35c56a5e880
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L214-L248
train
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php
Configuration.hydrateComponentsNode
private function hydrateComponentsNode(NodeBuilder $node) { $node ->scalarNode('path')->end() ->scalarNode('controller')->end() ->arrayNode('config') ->useAttributeAsKey('name') ->prototype('array') ->useAttributeAsKey('name') ->beforeNormalization() ->always(function ($v) { if (is_bool($v)) { return array('enabled' => $v); } return $v; }) ->end() ->prototype('scalar')->end() ->end() ->end() ; return $node; }
php
private function hydrateComponentsNode(NodeBuilder $node) { $node ->scalarNode('path')->end() ->scalarNode('controller')->end() ->arrayNode('config') ->useAttributeAsKey('name') ->prototype('array') ->useAttributeAsKey('name') ->beforeNormalization() ->always(function ($v) { if (is_bool($v)) { return array('enabled' => $v); } return $v; }) ->end() ->prototype('scalar')->end() ->end() ->end() ; return $node; }
[ "private", "function", "hydrateComponentsNode", "(", "NodeBuilder", "$", "node", ")", "{", "$", "node", "->", "scalarNode", "(", "'path'", ")", "->", "end", "(", ")", "->", "scalarNode", "(", "'controller'", ")", "->", "end", "(", ")", "->", "arrayNode", "(", "'config'", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "prototype", "(", "'array'", ")", "->", "useAttributeAsKey", "(", "'name'", ")", "->", "beforeNormalization", "(", ")", "->", "always", "(", "function", "(", "$", "v", ")", "{", "if", "(", "is_bool", "(", "$", "v", ")", ")", "{", "return", "array", "(", "'enabled'", "=>", "$", "v", ")", ";", "}", "return", "$", "v", ";", "}", ")", "->", "end", "(", ")", "->", "prototype", "(", "'scalar'", ")", "->", "end", "(", ")", "->", "end", "(", ")", "->", "end", "(", ")", ";", "return", "$", "node", ";", "}" ]
Hydrate given node with components configuration nodes. @param NodeBuilder $node @return NodeBuilder
[ "Hydrate", "given", "node", "with", "components", "configuration", "nodes", "." ]
d8122a4150a83d5607289724425cf35c56a5e880
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Distribution/Theme/Bundle/Configuration.php#L257-L281
train
temp/media-converter
src/Binary/MP4Box.php
MP4Box.process
public function process($inputFile, $outputFile = null) { if (!file_exists($inputFile) || !is_readable($inputFile)) { throw new InvalidFileArgumentException(sprintf('File %s does not exist or is not readable', $inputFile)); } $arguments = array( '-quiet', '-inter', '0.5', '-tmp', dirname($inputFile), $inputFile, ); if ($outputFile) { $arguments[] = '-out'; $arguments[] = $outputFile; } try { $this->command($arguments); } catch (ExecutionFailureException $e) { throw new RuntimeException(sprintf( 'MP4Box failed to process %s', $inputFile ), $e->getCode(), $e); } return $this; }
php
public function process($inputFile, $outputFile = null) { if (!file_exists($inputFile) || !is_readable($inputFile)) { throw new InvalidFileArgumentException(sprintf('File %s does not exist or is not readable', $inputFile)); } $arguments = array( '-quiet', '-inter', '0.5', '-tmp', dirname($inputFile), $inputFile, ); if ($outputFile) { $arguments[] = '-out'; $arguments[] = $outputFile; } try { $this->command($arguments); } catch (ExecutionFailureException $e) { throw new RuntimeException(sprintf( 'MP4Box failed to process %s', $inputFile ), $e->getCode(), $e); } return $this; }
[ "public", "function", "process", "(", "$", "inputFile", ",", "$", "outputFile", "=", "null", ")", "{", "if", "(", "!", "file_exists", "(", "$", "inputFile", ")", "||", "!", "is_readable", "(", "$", "inputFile", ")", ")", "{", "throw", "new", "InvalidFileArgumentException", "(", "sprintf", "(", "'File %s does not exist or is not readable'", ",", "$", "inputFile", ")", ")", ";", "}", "$", "arguments", "=", "array", "(", "'-quiet'", ",", "'-inter'", ",", "'0.5'", ",", "'-tmp'", ",", "dirname", "(", "$", "inputFile", ")", ",", "$", "inputFile", ",", ")", ";", "if", "(", "$", "outputFile", ")", "{", "$", "arguments", "[", "]", "=", "'-out'", ";", "$", "arguments", "[", "]", "=", "$", "outputFile", ";", "}", "try", "{", "$", "this", "->", "command", "(", "$", "arguments", ")", ";", "}", "catch", "(", "ExecutionFailureException", "$", "e", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'MP4Box failed to process %s'", ",", "$", "inputFile", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "return", "$", "this", ";", "}" ]
Processes a file @param string $inputFile The file to process. @param null|string $outputFile The output file to write. If not provided, processes the file in place. @return MP4Box @throws InvalidFileArgumentException In case the input file is not readable @throws RuntimeException In case the process failed
[ "Processes", "a", "file" ]
a6e8768c583aa461be568f13e592ae49294e5e33
https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Binary/MP4Box.php#L43-L72
train
temp/media-converter
src/Binary/MP4Box.php
MP4Box.create
public static function create($conf = array(), LoggerInterface $logger = null) { if (!$conf instanceof ConfigurationInterface) { $conf = new Configuration($conf); } $binaries = $conf->get('mp4box.binaries', array('MP4Box')); return static::load($binaries, $logger, $conf); }
php
public static function create($conf = array(), LoggerInterface $logger = null) { if (!$conf instanceof ConfigurationInterface) { $conf = new Configuration($conf); } $binaries = $conf->get('mp4box.binaries', array('MP4Box')); return static::load($binaries, $logger, $conf); }
[ "public", "static", "function", "create", "(", "$", "conf", "=", "array", "(", ")", ",", "LoggerInterface", "$", "logger", "=", "null", ")", "{", "if", "(", "!", "$", "conf", "instanceof", "ConfigurationInterface", ")", "{", "$", "conf", "=", "new", "Configuration", "(", "$", "conf", ")", ";", "}", "$", "binaries", "=", "$", "conf", "->", "get", "(", "'mp4box.binaries'", ",", "array", "(", "'MP4Box'", ")", ")", ";", "return", "static", "::", "load", "(", "$", "binaries", ",", "$", "logger", ",", "$", "conf", ")", ";", "}" ]
Creates an MP4Box binary adapter. @param null|LoggerInterface $logger @param array|ConfigurationInterface $conf @return MP4Box
[ "Creates", "an", "MP4Box", "binary", "adapter", "." ]
a6e8768c583aa461be568f13e592ae49294e5e33
https://github.com/temp/media-converter/blob/a6e8768c583aa461be568f13e592ae49294e5e33/src/Binary/MP4Box.php#L82-L91
train
YiMAproject/yimaWidgetator
src/yimaWidgetator/Service/WidgetManager.php
WidgetManager.injectWidgetDependencies
public function injectWidgetDependencies(WidgetInterface $widget, ServiceLocatorInterface $serviceLocator) { /** @var $serviceLocator \yimaWidgetator\Service\WidgetManager */ $sm = $serviceLocator->getServiceLocator(); if (!$sm) throw new \Exception('Service Manager can`t found.'); /** * MVC Widget */ if ($widget instanceof ViewRendererPlugInterface) { if (! $sm->has('ViewRenderer')) throw new \Exception('ViewRenderer service not found on Service Manager.'); $widget->setView($sm->get('ViewRenderer')); } if ($widget instanceof iInitableWidgetFeature) { // widget initialize himself after all $widget->init(); } /*if ($widget instanceof AbstractWidget) { // register widget in service locator with own unique id $sl = $this->getServiceLocator(); $sl->setService($widget->getID(), $widget); }*/ }
php
public function injectWidgetDependencies(WidgetInterface $widget, ServiceLocatorInterface $serviceLocator) { /** @var $serviceLocator \yimaWidgetator\Service\WidgetManager */ $sm = $serviceLocator->getServiceLocator(); if (!$sm) throw new \Exception('Service Manager can`t found.'); /** * MVC Widget */ if ($widget instanceof ViewRendererPlugInterface) { if (! $sm->has('ViewRenderer')) throw new \Exception('ViewRenderer service not found on Service Manager.'); $widget->setView($sm->get('ViewRenderer')); } if ($widget instanceof iInitableWidgetFeature) { // widget initialize himself after all $widget->init(); } /*if ($widget instanceof AbstractWidget) { // register widget in service locator with own unique id $sl = $this->getServiceLocator(); $sl->setService($widget->getID(), $widget); }*/ }
[ "public", "function", "injectWidgetDependencies", "(", "WidgetInterface", "$", "widget", ",", "ServiceLocatorInterface", "$", "serviceLocator", ")", "{", "/** @var $serviceLocator \\yimaWidgetator\\Service\\WidgetManager */", "$", "sm", "=", "$", "serviceLocator", "->", "getServiceLocator", "(", ")", ";", "if", "(", "!", "$", "sm", ")", "throw", "new", "\\", "Exception", "(", "'Service Manager can`t found.'", ")", ";", "/**\n * MVC Widget\n */", "if", "(", "$", "widget", "instanceof", "ViewRendererPlugInterface", ")", "{", "if", "(", "!", "$", "sm", "->", "has", "(", "'ViewRenderer'", ")", ")", "throw", "new", "\\", "Exception", "(", "'ViewRenderer service not found on Service Manager.'", ")", ";", "$", "widget", "->", "setView", "(", "$", "sm", "->", "get", "(", "'ViewRenderer'", ")", ")", ";", "}", "if", "(", "$", "widget", "instanceof", "iInitableWidgetFeature", ")", "{", "// widget initialize himself after all", "$", "widget", "->", "init", "(", ")", ";", "}", "/*if ($widget instanceof AbstractWidget) {\n // register widget in service locator with own unique id\n $sl = $this->getServiceLocator();\n $sl->setService($widget->getID(), $widget);\n }*/", "}" ]
Inject required dependencies into the widget. @param WidgetInterface $widget @param ServiceLocatorInterface $serviceLocator @throws \Exception @return void
[ "Inject", "required", "dependencies", "into", "the", "widget", "." ]
332bc9318e6ceaec918147b30317da2f5b3d2636
https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Service/WidgetManager.php#L98-L125
train
bluetree-service/data
src/Data/Xml.php
Xml.loadXmlFile
public function loadXmlFile($path, $parse = false) { $this->preserveWhiteSpace = false; $bool = file_exists($path); if (!$bool) { $this->error = 'file_not_exists'; return false; } $bool = @$this->load($path); if (!$bool) { $this->error = 'loading_file_error'; return false; } if ($parse && !@$this->validate()) { $this->error = 'parse_file_error'; return false; } return true; }
php
public function loadXmlFile($path, $parse = false) { $this->preserveWhiteSpace = false; $bool = file_exists($path); if (!$bool) { $this->error = 'file_not_exists'; return false; } $bool = @$this->load($path); if (!$bool) { $this->error = 'loading_file_error'; return false; } if ($parse && !@$this->validate()) { $this->error = 'parse_file_error'; return false; } return true; }
[ "public", "function", "loadXmlFile", "(", "$", "path", ",", "$", "parse", "=", "false", ")", "{", "$", "this", "->", "preserveWhiteSpace", "=", "false", ";", "$", "bool", "=", "file_exists", "(", "$", "path", ")", ";", "if", "(", "!", "$", "bool", ")", "{", "$", "this", "->", "error", "=", "'file_not_exists'", ";", "return", "false", ";", "}", "$", "bool", "=", "@", "$", "this", "->", "load", "(", "$", "path", ")", ";", "if", "(", "!", "$", "bool", ")", "{", "$", "this", "->", "error", "=", "'loading_file_error'", ";", "return", "false", ";", "}", "if", "(", "$", "parse", "&&", "!", "@", "$", "this", "->", "validate", "(", ")", ")", "{", "$", "this", "->", "error", "=", "'parse_file_error'", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
load xml file, optionally check file DTD @param string $path xml file path @param boolean $parse if true will check file DTD @return boolean @example loadXmlFile('cfg/config.xml', true)
[ "load", "xml", "file", "optionally", "check", "file", "DTD" ]
a8df78ee4f7b97b862f989d3effc75f022fd75cb
https://github.com/bluetree-service/data/blob/a8df78ee4f7b97b862f989d3effc75f022fd75cb/src/Data/Xml.php#L78-L100
train
bluetree-service/data
src/Data/Xml.php
Xml.saveXmlFile
public function saveXmlFile($path = '') { $this->formatOutput = true; if ($path) { $bool = @$this->save($path); if (!$bool) { $this->error = 'save_file_error'; return false; } return true; } return $this->saveXML(); }
php
public function saveXmlFile($path = '') { $this->formatOutput = true; if ($path) { $bool = @$this->save($path); if (!$bool) { $this->error = 'save_file_error'; return false; } return true; } return $this->saveXML(); }
[ "public", "function", "saveXmlFile", "(", "$", "path", "=", "''", ")", "{", "$", "this", "->", "formatOutput", "=", "true", ";", "if", "(", "$", "path", ")", "{", "$", "bool", "=", "@", "$", "this", "->", "save", "(", "$", "path", ")", ";", "if", "(", "!", "$", "bool", ")", "{", "$", "this", "->", "error", "=", "'save_file_error'", ";", "return", "false", ";", "}", "return", "true", ";", "}", "return", "$", "this", "->", "saveXML", "(", ")", ";", "}" ]
save xml file, optionally will return as string @param string $path xml file path @return string|boolean @example saveXmlFile('path/filename.xml'); save to file @example saveXmlFile() will return as simple text
[ "save", "xml", "file", "optionally", "will", "return", "as", "string" ]
a8df78ee4f7b97b862f989d3effc75f022fd75cb
https://github.com/bluetree-service/data/blob/a8df78ee4f7b97b862f989d3effc75f022fd75cb/src/Data/Xml.php#L111-L126
train
bluetree-service/data
src/Data/Xml.php
Xml.searchByAttributeRecurrent
protected function searchByAttributeRecurrent( DOMNodeList $node, $value, array $list = [] ) { /** @var DomElement $child */ foreach ($node as $child) { if ($child->nodeType === 1) { if ($child->hasChildNodes()) { $list = $this->searchByAttributeRecurrent( $child->childNodes, $value, $list ); } $attribute = $child->getAttribute($value); if ($attribute) { $list[$attribute] = $child; } } } return $list; }
php
protected function searchByAttributeRecurrent( DOMNodeList $node, $value, array $list = [] ) { /** @var DomElement $child */ foreach ($node as $child) { if ($child->nodeType === 1) { if ($child->hasChildNodes()) { $list = $this->searchByAttributeRecurrent( $child->childNodes, $value, $list ); } $attribute = $child->getAttribute($value); if ($attribute) { $list[$attribute] = $child; } } } return $list; }
[ "protected", "function", "searchByAttributeRecurrent", "(", "DOMNodeList", "$", "node", ",", "$", "value", ",", "array", "$", "list", "=", "[", "]", ")", "{", "/** @var DomElement $child */", "foreach", "(", "$", "node", "as", "$", "child", ")", "{", "if", "(", "$", "child", "->", "nodeType", "===", "1", ")", "{", "if", "(", "$", "child", "->", "hasChildNodes", "(", ")", ")", "{", "$", "list", "=", "$", "this", "->", "searchByAttributeRecurrent", "(", "$", "child", "->", "childNodes", ",", "$", "value", ",", "$", "list", ")", ";", "}", "$", "attribute", "=", "$", "child", "->", "getAttribute", "(", "$", "value", ")", ";", "if", "(", "$", "attribute", ")", "{", "$", "list", "[", "$", "attribute", "]", "=", "$", "child", ";", "}", "}", "}", "return", "$", "list", ";", "}" ]
search for all nodes with given attribute return list of nodes with attribute value as key @param DOMNodeList $node @param string $value attribute value to search @param array|boolean $list list of find nodes for recurrence @return array
[ "search", "for", "all", "nodes", "with", "given", "attribute", "return", "list", "of", "nodes", "with", "attribute", "value", "as", "key" ]
a8df78ee4f7b97b862f989d3effc75f022fd75cb
https://github.com/bluetree-service/data/blob/a8df78ee4f7b97b862f989d3effc75f022fd75cb/src/Data/Xml.php#L137-L161
train
iron-bound-designs/wp-notifications
src/Notification.php
Notification.generate_rendered_tags
final protected function generate_rendered_tags() { $data_sources = $this->data_sources; $data_sources[] = $this->recipient; $tags = $this->manager->render_tags( $data_sources ); $rendered = array(); foreach ( $tags as $tag => $value ) { $rendered[ '{' . $tag . '}' ] = $value; } $this->regenerate = false; return $rendered; }
php
final protected function generate_rendered_tags() { $data_sources = $this->data_sources; $data_sources[] = $this->recipient; $tags = $this->manager->render_tags( $data_sources ); $rendered = array(); foreach ( $tags as $tag => $value ) { $rendered[ '{' . $tag . '}' ] = $value; } $this->regenerate = false; return $rendered; }
[ "final", "protected", "function", "generate_rendered_tags", "(", ")", "{", "$", "data_sources", "=", "$", "this", "->", "data_sources", ";", "$", "data_sources", "[", "]", "=", "$", "this", "->", "recipient", ";", "$", "tags", "=", "$", "this", "->", "manager", "->", "render_tags", "(", "$", "data_sources", ")", ";", "$", "rendered", "=", "array", "(", ")", ";", "foreach", "(", "$", "tags", "as", "$", "tag", "=>", "$", "value", ")", "{", "$", "rendered", "[", "'{'", ".", "$", "tag", ".", "'}'", "]", "=", "$", "value", ";", "}", "$", "this", "->", "regenerate", "=", "false", ";", "return", "$", "rendered", ";", "}" ]
Generate the rendered forms of the tags. @since 1.0 @return array
[ "Generate", "the", "rendered", "forms", "of", "the", "tags", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L88-L103
train
iron-bound-designs/wp-notifications
src/Notification.php
Notification.add_data_source
public function add_data_source( \Serializable $source, $name = '' ) { if ( $name ) { $this->data_sources[ $name ] = $source; } else { $this->data_sources[] = $source; } $this->regenerate(); return $this; }
php
public function add_data_source( \Serializable $source, $name = '' ) { if ( $name ) { $this->data_sources[ $name ] = $source; } else { $this->data_sources[] = $source; } $this->regenerate(); return $this; }
[ "public", "function", "add_data_source", "(", "\\", "Serializable", "$", "source", ",", "$", "name", "=", "''", ")", "{", "if", "(", "$", "name", ")", "{", "$", "this", "->", "data_sources", "[", "$", "name", "]", "=", "$", "source", ";", "}", "else", "{", "$", "this", "->", "data_sources", "[", "]", "=", "$", "source", ";", "}", "$", "this", "->", "regenerate", "(", ")", ";", "return", "$", "this", ";", "}" ]
Add a data source. @since 1.0 @param \Serializable $source @param string $name If passed, listeners specifying that function argument name will receive this data source. @return self
[ "Add", "a", "data", "source", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L125-L136
train
iron-bound-designs/wp-notifications
src/Notification.php
Notification.get_data_to_serialize
protected function get_data_to_serialize() { return array( 'recipient' => $this->recipient->ID, 'message' => $this->message, 'subject' => $this->subject, 'strategy' => $this->strategy, 'manager' => $this->manager->get_type(), 'data_sources' => $this->data_sources ); }
php
protected function get_data_to_serialize() { return array( 'recipient' => $this->recipient->ID, 'message' => $this->message, 'subject' => $this->subject, 'strategy' => $this->strategy, 'manager' => $this->manager->get_type(), 'data_sources' => $this->data_sources ); }
[ "protected", "function", "get_data_to_serialize", "(", ")", "{", "return", "array", "(", "'recipient'", "=>", "$", "this", "->", "recipient", "->", "ID", ",", "'message'", "=>", "$", "this", "->", "message", ",", "'subject'", "=>", "$", "this", "->", "subject", ",", "'strategy'", "=>", "$", "this", "->", "strategy", ",", "'manager'", "=>", "$", "this", "->", "manager", "->", "get_type", "(", ")", ",", "'data_sources'", "=>", "$", "this", "->", "data_sources", ")", ";", "}" ]
Get the data to serialize. Child classes should override this method, and add their own data. This can be exploited to override the base class's data - don't. @since 1.0 @return array
[ "Get", "the", "data", "to", "serialize", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L263-L272
train
iron-bound-designs/wp-notifications
src/Notification.php
Notification.do_unserialize
protected function do_unserialize( array $data ) { $this->recipient = get_user_by( 'id', $data['recipient'] ); $this->message = $data['message']; $this->subject = $data['subject']; $this->manager = Factory::make( $data['manager'] ); $this->strategy = $data['strategy']; $this->data_sources = $data['data_sources']; $this->tags = $this->generate_rendered_tags(); }
php
protected function do_unserialize( array $data ) { $this->recipient = get_user_by( 'id', $data['recipient'] ); $this->message = $data['message']; $this->subject = $data['subject']; $this->manager = Factory::make( $data['manager'] ); $this->strategy = $data['strategy']; $this->data_sources = $data['data_sources']; $this->tags = $this->generate_rendered_tags(); }
[ "protected", "function", "do_unserialize", "(", "array", "$", "data", ")", "{", "$", "this", "->", "recipient", "=", "get_user_by", "(", "'id'", ",", "$", "data", "[", "'recipient'", "]", ")", ";", "$", "this", "->", "message", "=", "$", "data", "[", "'message'", "]", ";", "$", "this", "->", "subject", "=", "$", "data", "[", "'subject'", "]", ";", "$", "this", "->", "manager", "=", "Factory", "::", "make", "(", "$", "data", "[", "'manager'", "]", ")", ";", "$", "this", "->", "strategy", "=", "$", "data", "[", "'strategy'", "]", ";", "$", "this", "->", "data_sources", "=", "$", "data", "[", "'data_sources'", "]", ";", "$", "this", "->", "tags", "=", "$", "this", "->", "generate_rendered_tags", "(", ")", ";", "}" ]
Do the actual unserialization. Assign the data to class properties. @since 1.0 @param array $data
[ "Do", "the", "actual", "unserialization", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Notification.php#L301-L310
train
umbrella-code/umbrella
src/Umbrella/Validation/Validator.php
Validator.hasFailed
public function hasFailed() { if($this->failed == false || $this->passed == true) { $this->failed = true; $this->passed = false; } }
php
public function hasFailed() { if($this->failed == false || $this->passed == true) { $this->failed = true; $this->passed = false; } }
[ "public", "function", "hasFailed", "(", ")", "{", "if", "(", "$", "this", "->", "failed", "==", "false", "||", "$", "this", "->", "passed", "==", "true", ")", "{", "$", "this", "->", "failed", "=", "true", ";", "$", "this", "->", "passed", "=", "false", ";", "}", "}" ]
Set booleans if validator failed @return void
[ "Set", "booleans", "if", "validator", "failed" ]
e23d8d367047113933ec22346eb9f002a555bd52
https://github.com/umbrella-code/umbrella/blob/e23d8d367047113933ec22346eb9f002a555bd52/src/Umbrella/Validation/Validator.php#L73-L80
train
umbrella-code/umbrella
src/Umbrella/Validation/Validator.php
Validator.hasPassed
public function hasPassed() { if($this->passed == false || $this->failed == true) { $this->passed = true; $this->failed = false; } }
php
public function hasPassed() { if($this->passed == false || $this->failed == true) { $this->passed = true; $this->failed = false; } }
[ "public", "function", "hasPassed", "(", ")", "{", "if", "(", "$", "this", "->", "passed", "==", "false", "||", "$", "this", "->", "failed", "==", "true", ")", "{", "$", "this", "->", "passed", "=", "true", ";", "$", "this", "->", "failed", "=", "false", ";", "}", "}" ]
Set booleans if validator passed @return void
[ "Set", "booleans", "if", "validator", "passed" ]
e23d8d367047113933ec22346eb9f002a555bd52
https://github.com/umbrella-code/umbrella/blob/e23d8d367047113933ec22346eb9f002a555bd52/src/Umbrella/Validation/Validator.php#L87-L94
train
SpoonX/SxBootstrap
src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php
Form.renderFormActions
protected function renderFormActions() { $rowPlugin = $this->getRowPlugin(); if (!empty($this->formActionElements)) { $this->getElement()->addChild($rowPlugin($this->formActionElements, true)->getElement()); } return $this; }
php
protected function renderFormActions() { $rowPlugin = $this->getRowPlugin(); if (!empty($this->formActionElements)) { $this->getElement()->addChild($rowPlugin($this->formActionElements, true)->getElement()); } return $this; }
[ "protected", "function", "renderFormActions", "(", ")", "{", "$", "rowPlugin", "=", "$", "this", "->", "getRowPlugin", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "formActionElements", ")", ")", "{", "$", "this", "->", "getElement", "(", ")", "->", "addChild", "(", "$", "rowPlugin", "(", "$", "this", "->", "formActionElements", ",", "true", ")", "->", "getElement", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Render the form action elements, when needed. @return $this
[ "Render", "the", "form", "action", "elements", "when", "needed", "." ]
768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6
https://github.com/SpoonX/SxBootstrap/blob/768b02e3b65f7dfe560e821cb0ff41ad3f86b3b6/src/SxBootstrap/View/Helper/Bootstrap/Form/Form.php#L146-L155
train
bantuXorg/php-ini-get-wrapper
src/IniGetWrapper.php
IniGetWrapper.getString
public function getString($varname) { $value = $this->get($varname); return $value === null ? null : trim($value); }
php
public function getString($varname) { $value = $this->get($varname); return $value === null ? null : trim($value); }
[ "public", "function", "getString", "(", "$", "varname", ")", "{", "$", "value", "=", "$", "this", "->", "get", "(", "$", "varname", ")", ";", "return", "$", "value", "===", "null", "?", "null", ":", "trim", "(", "$", "value", ")", ";", "}" ]
Gets the configuration option value as a trimmed string. @param string $varname The configuration option name. @return null|string Null if configuration option does not exist. The configuration option value (string) otherwise.
[ "Gets", "the", "configuration", "option", "value", "as", "a", "trimmed", "string", "." ]
789ef63472cb2a8d6f49324485bc3b057ff56d50
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L40-L44
train
bantuXorg/php-ini-get-wrapper
src/IniGetWrapper.php
IniGetWrapper.getBool
public function getBool($varname) { $value = $this->getString($varname); return $value === null ? null : $value && strtolower($value) !== 'off'; }
php
public function getBool($varname) { $value = $this->getString($varname); return $value === null ? null : $value && strtolower($value) !== 'off'; }
[ "public", "function", "getBool", "(", "$", "varname", ")", "{", "$", "value", "=", "$", "this", "->", "getString", "(", "$", "varname", ")", ";", "return", "$", "value", "===", "null", "?", "null", ":", "$", "value", "&&", "strtolower", "(", "$", "value", ")", "!==", "'off'", ";", "}" ]
Gets configuration option value as a boolean. Interprets the string value 'off' as false. @param string $varname The configuration option name. @return null|bool Null if configuration option does not exist. False if configuration option is disabled. True otherwise.
[ "Gets", "configuration", "option", "value", "as", "a", "boolean", ".", "Interprets", "the", "string", "value", "off", "as", "false", "." ]
789ef63472cb2a8d6f49324485bc3b057ff56d50
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L55-L59
train
bantuXorg/php-ini-get-wrapper
src/IniGetWrapper.php
IniGetWrapper.getNumeric
public function getNumeric($varname) { $value = $this->getString($varname); return is_numeric($value) ? $value + 0 : null; }
php
public function getNumeric($varname) { $value = $this->getString($varname); return is_numeric($value) ? $value + 0 : null; }
[ "public", "function", "getNumeric", "(", "$", "varname", ")", "{", "$", "value", "=", "$", "this", "->", "getString", "(", "$", "varname", ")", ";", "return", "is_numeric", "(", "$", "value", ")", "?", "$", "value", "+", "0", ":", "null", ";", "}" ]
Gets configuration option value as an integer. @param string $varname The configuration option name. @return null|int|float Null if configuration option does not exist or is not numeric. The configuration option value (integer or float) otherwise.
[ "Gets", "configuration", "option", "value", "as", "an", "integer", "." ]
789ef63472cb2a8d6f49324485bc3b057ff56d50
https://github.com/bantuXorg/php-ini-get-wrapper/blob/789ef63472cb2a8d6f49324485bc3b057ff56d50/src/IniGetWrapper.php#L68-L72
train
RowlandOti/ooglee-blogmodule
src/OoGlee/Application/Entities/Post/PostResolver.php
PostResolver.resolve
public function resolve() { $url = $this->request->url(); $tmp = explode('/', $url); $last_seg = end($tmp); return $this->repository->findBySlug($last_seg); }
php
public function resolve() { $url = $this->request->url(); $tmp = explode('/', $url); $last_seg = end($tmp); return $this->repository->findBySlug($last_seg); }
[ "public", "function", "resolve", "(", ")", "{", "$", "url", "=", "$", "this", "->", "request", "->", "url", "(", ")", ";", "$", "tmp", "=", "explode", "(", "'/'", ",", "$", "url", ")", ";", "$", "last_seg", "=", "end", "(", "$", "tmp", ")", ";", "return", "$", "this", "->", "repository", "->", "findBySlug", "(", "$", "last_seg", ")", ";", "}" ]
Resolve the post. @return PostInterface|null
[ "Resolve", "the", "post", "." ]
d9c0fe4745bb09f8b94047b0cda4fd7438cde16a
https://github.com/RowlandOti/ooglee-blogmodule/blob/d9c0fe4745bb09f8b94047b0cda4fd7438cde16a/src/OoGlee/Application/Entities/Post/PostResolver.php#L51-L58
train
slickframework/form
src/Element/FieldSet.php
FieldSet.isValid
public function isValid() { $valid = true; $this->validate(); foreach ($this->getIterator() as $element) { if ($element instanceof ValidationAwareInterface) { $valid = $element->isValid() ? $valid : false; } } return $valid; }
php
public function isValid() { $valid = true; $this->validate(); foreach ($this->getIterator() as $element) { if ($element instanceof ValidationAwareInterface) { $valid = $element->isValid() ? $valid : false; } } return $valid; }
[ "public", "function", "isValid", "(", ")", "{", "$", "valid", "=", "true", ";", "$", "this", "->", "validate", "(", ")", ";", "foreach", "(", "$", "this", "->", "getIterator", "(", ")", "as", "$", "element", ")", "{", "if", "(", "$", "element", "instanceof", "ValidationAwareInterface", ")", "{", "$", "valid", "=", "$", "element", "->", "isValid", "(", ")", "?", "$", "valid", ":", "false", ";", "}", "}", "return", "$", "valid", ";", "}" ]
Checks if all elements are valid @return mixed
[ "Checks", "if", "all", "elements", "are", "valid" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L62-L74
train
slickframework/form
src/Element/FieldSet.php
FieldSet.get
public function get($name) { $selected = null; /** @var ElementInterface|ContainerInterface $element */ foreach ($this as $element) { if ($element->getName() == $name) { $selected = $element; break; } if ($element instanceof ContainerInterface) { $selected = $element->get($name); if (null !== $selected) { break; } } } return $selected; }
php
public function get($name) { $selected = null; /** @var ElementInterface|ContainerInterface $element */ foreach ($this as $element) { if ($element->getName() == $name) { $selected = $element; break; } if ($element instanceof ContainerInterface) { $selected = $element->get($name); if (null !== $selected) { break; } } } return $selected; }
[ "public", "function", "get", "(", "$", "name", ")", "{", "$", "selected", "=", "null", ";", "/** @var ElementInterface|ContainerInterface $element */", "foreach", "(", "$", "this", "as", "$", "element", ")", "{", "if", "(", "$", "element", "->", "getName", "(", ")", "==", "$", "name", ")", "{", "$", "selected", "=", "$", "element", ";", "break", ";", "}", "if", "(", "$", "element", "instanceof", "ContainerInterface", ")", "{", "$", "selected", "=", "$", "element", "->", "get", "(", "$", "name", ")", ";", "if", "(", "null", "!==", "$", "selected", ")", "{", "break", ";", "}", "}", "}", "return", "$", "selected", ";", "}" ]
Gets element by name @param string $name @return null|ElementInterface|InputInterface
[ "Gets", "element", "by", "name" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L100-L119
train
slickframework/form
src/Element/FieldSet.php
FieldSet.setValues
public function setValues(array $values) { foreach ($values as $name => $value) { if ($element = $this->get($name)) { $element->setValue($value); } } return $this; }
php
public function setValues(array $values) { foreach ($values as $name => $value) { if ($element = $this->get($name)) { $element->setValue($value); } } return $this; }
[ "public", "function", "setValues", "(", "array", "$", "values", ")", "{", "foreach", "(", "$", "values", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "$", "element", "=", "$", "this", "->", "get", "(", "$", "name", ")", ")", "{", "$", "element", "->", "setValue", "(", "$", "value", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Sets the values form matched elements The passed array is a key/value array where keys are used to match against element names. It will only assign the value to the marched element only. @param array $values @return self|$this|ContainerInterface
[ "Sets", "the", "values", "form", "matched", "elements" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L132-L140
train
slickframework/form
src/Element/FieldSet.php
FieldSet.validate
public function validate() { foreach ($this as $element) { if ( $element instanceof ValidationAwareInterface || $element instanceof ContainerInterface ) { $element->validate(); } } return $this; }
php
public function validate() { foreach ($this as $element) { if ( $element instanceof ValidationAwareInterface || $element instanceof ContainerInterface ) { $element->validate(); } } return $this; }
[ "public", "function", "validate", "(", ")", "{", "foreach", "(", "$", "this", "as", "$", "element", ")", "{", "if", "(", "$", "element", "instanceof", "ValidationAwareInterface", "||", "$", "element", "instanceof", "ContainerInterface", ")", "{", "$", "element", "->", "validate", "(", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Runs validation chain in all its elements @return self|$this|ElementInterface
[ "Runs", "validation", "chain", "in", "all", "its", "elements" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Element/FieldSet.php#L219-L231
train
jelix/file-utilities
lib/Path.php
Path.isAbsolute
public static function isAbsolute($path) { list($prefix, $path, $absolute) = self::_startNormalize($path); return $absolute; }
php
public static function isAbsolute($path) { list($prefix, $path, $absolute) = self::_startNormalize($path); return $absolute; }
[ "public", "static", "function", "isAbsolute", "(", "$", "path", ")", "{", "list", "(", "$", "prefix", ",", "$", "path", ",", "$", "absolute", ")", "=", "self", "::", "_startNormalize", "(", "$", "path", ")", ";", "return", "$", "absolute", ";", "}" ]
says if the given path is an absolute one or not. @param string $path @return bool true if the path is absolute
[ "says", "if", "the", "given", "path", "is", "an", "absolute", "one", "or", "not", "." ]
05fd364860ed147e6367de9db3dc544f58c5a05c
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Path.php#L50-L55
train
jelix/file-utilities
lib/Path.php
Path._normalizePath
protected static function _normalizePath($originalPath, $alwaysArray, $basePath = '') { list($prefix, $path, $absolute) = self::_startNormalize($originalPath); if (!$absolute && $basePath) { list($prefix, $path, $absolute) = self::_startNormalize($basePath.'/'.$originalPath); } if ($absolute && $path != '') { // remove leading '/' for path if ($path == '/') { $path = ''; } else { $path = substr($path, 1); } } if (strpos($path, './') === false && substr($path, -1) != '.') { // if there is no relative path component like ../ or ./, we can // return directly the path informations if ($alwaysArray) { if ($path == '') { return array($prefix, array(), $absolute); } return array($prefix, explode('/', rtrim($path, '/')), $absolute); } else { if ($path == '') { return array($prefix, $path, $absolute); } return array($prefix, rtrim($path, '/'), $absolute); } } $path = explode('/', $path); $path2 = array(); $up = false; foreach ($path as $chunk) { if ($chunk === '..') { if (count($path2)) { if (end($path2) != '..') { array_pop($path2); } else { $path2[] = '..'; } } elseif (!$absolute) { // for non absolute path, we keep leading '..' $path2[] = '..'; } } elseif ($chunk !== '' && $chunk != '.') { $path2[] = $chunk; } } return array($prefix, $path2, $absolute); }
php
protected static function _normalizePath($originalPath, $alwaysArray, $basePath = '') { list($prefix, $path, $absolute) = self::_startNormalize($originalPath); if (!$absolute && $basePath) { list($prefix, $path, $absolute) = self::_startNormalize($basePath.'/'.$originalPath); } if ($absolute && $path != '') { // remove leading '/' for path if ($path == '/') { $path = ''; } else { $path = substr($path, 1); } } if (strpos($path, './') === false && substr($path, -1) != '.') { // if there is no relative path component like ../ or ./, we can // return directly the path informations if ($alwaysArray) { if ($path == '') { return array($prefix, array(), $absolute); } return array($prefix, explode('/', rtrim($path, '/')), $absolute); } else { if ($path == '') { return array($prefix, $path, $absolute); } return array($prefix, rtrim($path, '/'), $absolute); } } $path = explode('/', $path); $path2 = array(); $up = false; foreach ($path as $chunk) { if ($chunk === '..') { if (count($path2)) { if (end($path2) != '..') { array_pop($path2); } else { $path2[] = '..'; } } elseif (!$absolute) { // for non absolute path, we keep leading '..' $path2[] = '..'; } } elseif ($chunk !== '' && $chunk != '.') { $path2[] = $chunk; } } return array($prefix, $path2, $absolute); }
[ "protected", "static", "function", "_normalizePath", "(", "$", "originalPath", ",", "$", "alwaysArray", ",", "$", "basePath", "=", "''", ")", "{", "list", "(", "$", "prefix", ",", "$", "path", ",", "$", "absolute", ")", "=", "self", "::", "_startNormalize", "(", "$", "originalPath", ")", ";", "if", "(", "!", "$", "absolute", "&&", "$", "basePath", ")", "{", "list", "(", "$", "prefix", ",", "$", "path", ",", "$", "absolute", ")", "=", "self", "::", "_startNormalize", "(", "$", "basePath", ".", "'/'", ".", "$", "originalPath", ")", ";", "}", "if", "(", "$", "absolute", "&&", "$", "path", "!=", "''", ")", "{", "// remove leading '/' for path", "if", "(", "$", "path", "==", "'/'", ")", "{", "$", "path", "=", "''", ";", "}", "else", "{", "$", "path", "=", "substr", "(", "$", "path", ",", "1", ")", ";", "}", "}", "if", "(", "strpos", "(", "$", "path", ",", "'./'", ")", "===", "false", "&&", "substr", "(", "$", "path", ",", "-", "1", ")", "!=", "'.'", ")", "{", "// if there is no relative path component like ../ or ./, we can", "// return directly the path informations", "if", "(", "$", "alwaysArray", ")", "{", "if", "(", "$", "path", "==", "''", ")", "{", "return", "array", "(", "$", "prefix", ",", "array", "(", ")", ",", "$", "absolute", ")", ";", "}", "return", "array", "(", "$", "prefix", ",", "explode", "(", "'/'", ",", "rtrim", "(", "$", "path", ",", "'/'", ")", ")", ",", "$", "absolute", ")", ";", "}", "else", "{", "if", "(", "$", "path", "==", "''", ")", "{", "return", "array", "(", "$", "prefix", ",", "$", "path", ",", "$", "absolute", ")", ";", "}", "return", "array", "(", "$", "prefix", ",", "rtrim", "(", "$", "path", ",", "'/'", ")", ",", "$", "absolute", ")", ";", "}", "}", "$", "path", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "$", "path2", "=", "array", "(", ")", ";", "$", "up", "=", "false", ";", "foreach", "(", "$", "path", "as", "$", "chunk", ")", "{", "if", "(", "$", "chunk", "===", "'..'", ")", "{", "if", "(", "count", "(", "$", "path2", ")", ")", "{", "if", "(", "end", "(", "$", "path2", ")", "!=", "'..'", ")", "{", "array_pop", "(", "$", "path2", ")", ";", "}", "else", "{", "$", "path2", "[", "]", "=", "'..'", ";", "}", "}", "elseif", "(", "!", "$", "absolute", ")", "{", "// for non absolute path, we keep leading '..'", "$", "path2", "[", "]", "=", "'..'", ";", "}", "}", "elseif", "(", "$", "chunk", "!==", "''", "&&", "$", "chunk", "!=", "'.'", ")", "{", "$", "path2", "[", "]", "=", "$", "chunk", ";", "}", "}", "return", "array", "(", "$", "prefix", ",", "$", "path2", ",", "$", "absolute", ")", ";", "}" ]
it returns components of a path after normalization, in an array. - first element: for windows path, the drive part "C:", "C:" etc... always in uppercase - second element: the normalized path. as string or array depending of $alwaysArray when as string: no trailing slash. - third element: indicate if the given path is an absolute path (true) or not (false) @param bool $alwaysArray if true, second element is an array @return array
[ "it", "returns", "components", "of", "a", "path", "after", "normalization", "in", "an", "array", "." ]
05fd364860ed147e6367de9db3dc544f58c5a05c
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Path.php#L112-L165
train
phPoirot/Client-OAuth2
src/Client.php
Client.attainAuthorizationUrl
function attainAuthorizationUrl(iGrantAuthorizeRequest $grant) { # Build Authorize Url $grantParams = $grant->assertAuthorizeParams(); $response = $this->call( new GetAuthorizeUrl($grantParams) ); if ( $ex = $response->hasException() ) throw $ex; return $response->expected(); }
php
function attainAuthorizationUrl(iGrantAuthorizeRequest $grant) { # Build Authorize Url $grantParams = $grant->assertAuthorizeParams(); $response = $this->call( new GetAuthorizeUrl($grantParams) ); if ( $ex = $response->hasException() ) throw $ex; return $response->expected(); }
[ "function", "attainAuthorizationUrl", "(", "iGrantAuthorizeRequest", "$", "grant", ")", "{", "# Build Authorize Url", "$", "grantParams", "=", "$", "grant", "->", "assertAuthorizeParams", "(", ")", ";", "$", "response", "=", "$", "this", "->", "call", "(", "new", "GetAuthorizeUrl", "(", "$", "grantParams", ")", ")", ";", "if", "(", "$", "ex", "=", "$", "response", "->", "hasException", "(", ")", ")", "throw", "$", "ex", ";", "return", "$", "response", "->", "expected", "(", ")", ";", "}" ]
Builds the authorization URL - look in grants available with response_type code - make url from grant parameters @param iGrantAuthorizeRequest $grant Using specific grant @return string Authorization URL @throws \Exception
[ "Builds", "the", "authorization", "URL" ]
8745fd54afbbb185669b9e38b1241ecc8ffc7268
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L65-L76
train
phPoirot/Client-OAuth2
src/Client.php
Client.attainAccessToken
function attainAccessToken(iGrantTokenRequest $grant) { // client_id, secret_key can send as Authorization Header Or Post Request Body $grantParams = $grant->assertTokenParams(); $response = $this->call( new Token($grantParams) ); if ( $ex = $response->hasException() ) throw $ex; /** @var DataEntity $r */ $r = $response->expected(); if (! $r->get('access_token') ) // It not fulfilled with access_token; in case of two step validation like single-signin // return response otherwise access token return $r; return new AccessTokenObject($r); }
php
function attainAccessToken(iGrantTokenRequest $grant) { // client_id, secret_key can send as Authorization Header Or Post Request Body $grantParams = $grant->assertTokenParams(); $response = $this->call( new Token($grantParams) ); if ( $ex = $response->hasException() ) throw $ex; /** @var DataEntity $r */ $r = $response->expected(); if (! $r->get('access_token') ) // It not fulfilled with access_token; in case of two step validation like single-signin // return response otherwise access token return $r; return new AccessTokenObject($r); }
[ "function", "attainAccessToken", "(", "iGrantTokenRequest", "$", "grant", ")", "{", "// client_id, secret_key can send as Authorization Header Or Post Request Body", "$", "grantParams", "=", "$", "grant", "->", "assertTokenParams", "(", ")", ";", "$", "response", "=", "$", "this", "->", "call", "(", "new", "Token", "(", "$", "grantParams", ")", ")", ";", "if", "(", "$", "ex", "=", "$", "response", "->", "hasException", "(", ")", ")", "throw", "$", "ex", ";", "/** @var DataEntity $r */", "$", "r", "=", "$", "response", "->", "expected", "(", ")", ";", "if", "(", "!", "$", "r", "->", "get", "(", "'access_token'", ")", ")", "// It not fulfilled with access_token; in case of two step validation like single-signin", "// return response otherwise access token", "return", "$", "r", ";", "return", "new", "AccessTokenObject", "(", "$", "r", ")", ";", "}" ]
Requests an access token using a specified grant. @param iGrantTokenRequest $grant @return iAccessTokenObject|DataEntity @throws \Exception
[ "Requests", "an", "access", "token", "using", "a", "specified", "grant", "." ]
8745fd54afbbb185669b9e38b1241ecc8ffc7268
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L86-L104
train
phPoirot/Client-OAuth2
src/Client.php
Client.withGrant
function withGrant($grantTypeName, array $overrideOptions = []) { $options = [ 'scopes' => $this->defaultScopes, 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, ]; if (! empty($overrideOptions) ) $options = array_merge($options, $overrideOptions); if ($grantTypeName instanceof ipGrantRequest) { $grant = clone $grantTypeName; $grant->with($grant::parseWith($options)); } else { $grant = $this->plugins()->fresh($grantTypeName, $options); } return $grant; }
php
function withGrant($grantTypeName, array $overrideOptions = []) { $options = [ 'scopes' => $this->defaultScopes, 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, ]; if (! empty($overrideOptions) ) $options = array_merge($options, $overrideOptions); if ($grantTypeName instanceof ipGrantRequest) { $grant = clone $grantTypeName; $grant->with($grant::parseWith($options)); } else { $grant = $this->plugins()->fresh($grantTypeName, $options); } return $grant; }
[ "function", "withGrant", "(", "$", "grantTypeName", ",", "array", "$", "overrideOptions", "=", "[", "]", ")", "{", "$", "options", "=", "[", "'scopes'", "=>", "$", "this", "->", "defaultScopes", ",", "'client_id'", "=>", "$", "this", "->", "clientId", ",", "'client_secret'", "=>", "$", "this", "->", "clientSecret", ",", "]", ";", "if", "(", "!", "empty", "(", "$", "overrideOptions", ")", ")", "$", "options", "=", "array_merge", "(", "$", "options", ",", "$", "overrideOptions", ")", ";", "if", "(", "$", "grantTypeName", "instanceof", "ipGrantRequest", ")", "{", "$", "grant", "=", "clone", "$", "grantTypeName", ";", "$", "grant", "->", "with", "(", "$", "grant", "::", "parseWith", "(", "$", "options", ")", ")", ";", "}", "else", "{", "$", "grant", "=", "$", "this", "->", "plugins", "(", ")", "->", "fresh", "(", "$", "grantTypeName", ",", "$", "options", ")", ";", "}", "return", "$", "grant", ";", "}" ]
Retrieve Specific Grant Type - inject default client configuration within grant object example code: $auth->withGrant( GrantPlugins::AUTHORIZATION_CODE , ['state' => 'custom_state'] ) @param string|ipGrantRequest $grantTypeName @param array $overrideOptions @return aGrantRequest
[ "Retrieve", "Specific", "Grant", "Type" ]
8745fd54afbbb185669b9e38b1241ecc8ffc7268
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L122-L142
train
phPoirot/Client-OAuth2
src/Client.php
Client.platform
protected function platform() { if (! $this->platform ) $this->platform = new PlatformRest; # Default Options Overriding $this->platform->setServerUrl( $this->serverUrl ); return $this->platform; }
php
protected function platform() { if (! $this->platform ) $this->platform = new PlatformRest; # Default Options Overriding $this->platform->setServerUrl( $this->serverUrl ); return $this->platform; }
[ "protected", "function", "platform", "(", ")", "{", "if", "(", "!", "$", "this", "->", "platform", ")", "$", "this", "->", "platform", "=", "new", "PlatformRest", ";", "# Default Options Overriding", "$", "this", "->", "platform", "->", "setServerUrl", "(", "$", "this", "->", "serverUrl", ")", ";", "return", "$", "this", "->", "platform", ";", "}" ]
Get Client Platform - used by request to build params for server execution call and response @return iPlatform
[ "Get", "Client", "Platform" ]
8745fd54afbbb185669b9e38b1241ecc8ffc7268
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/src/Client.php#L166-L176
train
3ev/wordpress-core
src/Tev/View/Renderer.php
Renderer.render
public function render($filename, $vars = array()) { $localTemplate = $this->templateDir . '/' . $filename; $themeTemplate = locate_template($filename); if (!file_exists($localTemplate) && !file_exists($themeTemplate)) { throw new NotFoundException("View at $localTemplate or $themeTemplate not found"); } $this->viewData = $vars; $template = file_exists($localTemplate) ? $localTemplate : $themeTemplate; ob_start(); include($template); $view = ob_get_contents(); ob_end_clean(); return $view; }
php
public function render($filename, $vars = array()) { $localTemplate = $this->templateDir . '/' . $filename; $themeTemplate = locate_template($filename); if (!file_exists($localTemplate) && !file_exists($themeTemplate)) { throw new NotFoundException("View at $localTemplate or $themeTemplate not found"); } $this->viewData = $vars; $template = file_exists($localTemplate) ? $localTemplate : $themeTemplate; ob_start(); include($template); $view = ob_get_contents(); ob_end_clean(); return $view; }
[ "public", "function", "render", "(", "$", "filename", ",", "$", "vars", "=", "array", "(", ")", ")", "{", "$", "localTemplate", "=", "$", "this", "->", "templateDir", ".", "'/'", ".", "$", "filename", ";", "$", "themeTemplate", "=", "locate_template", "(", "$", "filename", ")", ";", "if", "(", "!", "file_exists", "(", "$", "localTemplate", ")", "&&", "!", "file_exists", "(", "$", "themeTemplate", ")", ")", "{", "throw", "new", "NotFoundException", "(", "\"View at $localTemplate or $themeTemplate not found\"", ")", ";", "}", "$", "this", "->", "viewData", "=", "$", "vars", ";", "$", "template", "=", "file_exists", "(", "$", "localTemplate", ")", "?", "$", "localTemplate", ":", "$", "themeTemplate", ";", "ob_start", "(", ")", ";", "include", "(", "$", "template", ")", ";", "$", "view", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "return", "$", "view", ";", "}" ]
Renders a template file. Assigns all $var keys to $this->$key for us in template. @param string $filename Full-filename @param array $vars View variables @return string Rendered view @throws \Tev\View\Exception\NotFoundException If view file not found
[ "Renders", "a", "template", "file", "." ]
da674fbec5bf3d5bd2a2141680a4c141113eb6b0
https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/View/Renderer.php#L51-L70
train
ekyna/AdminBundle
Helper/ResourceHelper.php
ResourceHelper.isGranted
public function isGranted($resource, $action = 'view') { return $this->aclOperator->isAccessGranted($resource, $this->getPermission($action)); }
php
public function isGranted($resource, $action = 'view') { return $this->aclOperator->isAccessGranted($resource, $this->getPermission($action)); }
[ "public", "function", "isGranted", "(", "$", "resource", ",", "$", "action", "=", "'view'", ")", "{", "return", "$", "this", "->", "aclOperator", "->", "isAccessGranted", "(", "$", "resource", ",", "$", "this", "->", "getPermission", "(", "$", "action", ")", ")", ";", "}" ]
Returns whether the user has access granted or not on the given resource for the given action. @param mixed $resource @param string $action @return boolean
[ "Returns", "whether", "the", "user", "has", "access", "granted", "or", "not", "on", "the", "given", "resource", "for", "the", "given", "action", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L87-L90
train
ekyna/AdminBundle
Helper/ResourceHelper.php
ResourceHelper.generateResourcePath
public function generateResourcePath($resource, $action = 'show') { $configuration = $this->registry->findConfiguration($resource); $routeName = $configuration->getRoute($action); $route = $this->findRoute($routeName); $requirements = $route->getRequirements(); $accessor = PropertyAccess::createPropertyAccessor(); $entities = []; if (is_object($resource)) { $entities[$configuration->getResourceName()] = $resource; $current = $resource; while (null !== $configuration->getParentId()) { $configuration = $this->registry->findConfiguration($configuration->getParentId()); $current = $accessor->getValue($current, $configuration->getResourceName()); $entities[$configuration->getResourceName()] = $current; } } $parameters = []; foreach ($entities as $name => $resource) { if (array_key_exists($name . 'Id', $requirements)) { $parameters[$name . 'Id'] = $accessor->getValue($resource, 'id'); } } return $this->router->generate($routeName, $parameters); }
php
public function generateResourcePath($resource, $action = 'show') { $configuration = $this->registry->findConfiguration($resource); $routeName = $configuration->getRoute($action); $route = $this->findRoute($routeName); $requirements = $route->getRequirements(); $accessor = PropertyAccess::createPropertyAccessor(); $entities = []; if (is_object($resource)) { $entities[$configuration->getResourceName()] = $resource; $current = $resource; while (null !== $configuration->getParentId()) { $configuration = $this->registry->findConfiguration($configuration->getParentId()); $current = $accessor->getValue($current, $configuration->getResourceName()); $entities[$configuration->getResourceName()] = $current; } } $parameters = []; foreach ($entities as $name => $resource) { if (array_key_exists($name . 'Id', $requirements)) { $parameters[$name . 'Id'] = $accessor->getValue($resource, 'id'); } } return $this->router->generate($routeName, $parameters); }
[ "public", "function", "generateResourcePath", "(", "$", "resource", ",", "$", "action", "=", "'show'", ")", "{", "$", "configuration", "=", "$", "this", "->", "registry", "->", "findConfiguration", "(", "$", "resource", ")", ";", "$", "routeName", "=", "$", "configuration", "->", "getRoute", "(", "$", "action", ")", ";", "$", "route", "=", "$", "this", "->", "findRoute", "(", "$", "routeName", ")", ";", "$", "requirements", "=", "$", "route", "->", "getRequirements", "(", ")", ";", "$", "accessor", "=", "PropertyAccess", "::", "createPropertyAccessor", "(", ")", ";", "$", "entities", "=", "[", "]", ";", "if", "(", "is_object", "(", "$", "resource", ")", ")", "{", "$", "entities", "[", "$", "configuration", "->", "getResourceName", "(", ")", "]", "=", "$", "resource", ";", "$", "current", "=", "$", "resource", ";", "while", "(", "null", "!==", "$", "configuration", "->", "getParentId", "(", ")", ")", "{", "$", "configuration", "=", "$", "this", "->", "registry", "->", "findConfiguration", "(", "$", "configuration", "->", "getParentId", "(", ")", ")", ";", "$", "current", "=", "$", "accessor", "->", "getValue", "(", "$", "current", ",", "$", "configuration", "->", "getResourceName", "(", ")", ")", ";", "$", "entities", "[", "$", "configuration", "->", "getResourceName", "(", ")", "]", "=", "$", "current", ";", "}", "}", "$", "parameters", "=", "[", "]", ";", "foreach", "(", "$", "entities", "as", "$", "name", "=>", "$", "resource", ")", "{", "if", "(", "array_key_exists", "(", "$", "name", ".", "'Id'", ",", "$", "requirements", ")", ")", "{", "$", "parameters", "[", "$", "name", ".", "'Id'", "]", "=", "$", "accessor", "->", "getValue", "(", "$", "resource", ",", "'id'", ")", ";", "}", "}", "return", "$", "this", "->", "router", "->", "generate", "(", "$", "routeName", ",", "$", "parameters", ")", ";", "}" ]
Generates an admin path for the given resource and action. @param object $resource @param string $action @throws \RuntimeException @return string
[ "Generates", "an", "admin", "path", "for", "the", "given", "resource", "and", "action", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L102-L131
train
ekyna/AdminBundle
Helper/ResourceHelper.php
ResourceHelper.getPermission
public function getPermission($action) { $action = strtoupper($action); if ($action == 'LIST') { return 'VIEW'; } elseif ($action == 'SHOW') { return 'VIEW'; } elseif ($action == 'NEW') { return 'CREATE'; } elseif ($action == 'EDIT') { return 'EDIT'; } elseif ($action == 'REMOVE') { return 'DELETE'; } return $action; }
php
public function getPermission($action) { $action = strtoupper($action); if ($action == 'LIST') { return 'VIEW'; } elseif ($action == 'SHOW') { return 'VIEW'; } elseif ($action == 'NEW') { return 'CREATE'; } elseif ($action == 'EDIT') { return 'EDIT'; } elseif ($action == 'REMOVE') { return 'DELETE'; } return $action; }
[ "public", "function", "getPermission", "(", "$", "action", ")", "{", "$", "action", "=", "strtoupper", "(", "$", "action", ")", ";", "if", "(", "$", "action", "==", "'LIST'", ")", "{", "return", "'VIEW'", ";", "}", "elseif", "(", "$", "action", "==", "'SHOW'", ")", "{", "return", "'VIEW'", ";", "}", "elseif", "(", "$", "action", "==", "'NEW'", ")", "{", "return", "'CREATE'", ";", "}", "elseif", "(", "$", "action", "==", "'EDIT'", ")", "{", "return", "'EDIT'", ";", "}", "elseif", "(", "$", "action", "==", "'REMOVE'", ")", "{", "return", "'DELETE'", ";", "}", "return", "$", "action", ";", "}" ]
Returns the permission for the given action. @param string $action @return string
[ "Returns", "the", "permission", "for", "the", "given", "action", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L140-L155
train
ekyna/AdminBundle
Helper/ResourceHelper.php
ResourceHelper.findRoute
public function findRoute($routeName) { // TODO create a route finder ? (same in CmsBundle BreadcrumbBuilder) $i18nRouterClass = 'JMS\I18nRoutingBundle\Router\I18nRouterInterface'; if (interface_exists($i18nRouterClass) && $this->router instanceof $i18nRouterClass) { $route = $this->router->getOriginalRouteCollection()->get($routeName); } else { $route = $this->router->getRouteCollection()->get($routeName); } if (null === $route) { throw new \RuntimeException(sprintf('Route "%s" not found.', $routeName)); } return $route; }
php
public function findRoute($routeName) { // TODO create a route finder ? (same in CmsBundle BreadcrumbBuilder) $i18nRouterClass = 'JMS\I18nRoutingBundle\Router\I18nRouterInterface'; if (interface_exists($i18nRouterClass) && $this->router instanceof $i18nRouterClass) { $route = $this->router->getOriginalRouteCollection()->get($routeName); } else { $route = $this->router->getRouteCollection()->get($routeName); } if (null === $route) { throw new \RuntimeException(sprintf('Route "%s" not found.', $routeName)); } return $route; }
[ "public", "function", "findRoute", "(", "$", "routeName", ")", "{", "// TODO create a route finder ? (same in CmsBundle BreadcrumbBuilder)", "$", "i18nRouterClass", "=", "'JMS\\I18nRoutingBundle\\Router\\I18nRouterInterface'", ";", "if", "(", "interface_exists", "(", "$", "i18nRouterClass", ")", "&&", "$", "this", "->", "router", "instanceof", "$", "i18nRouterClass", ")", "{", "$", "route", "=", "$", "this", "->", "router", "->", "getOriginalRouteCollection", "(", ")", "->", "get", "(", "$", "routeName", ")", ";", "}", "else", "{", "$", "route", "=", "$", "this", "->", "router", "->", "getRouteCollection", "(", ")", "->", "get", "(", "$", "routeName", ")", ";", "}", "if", "(", "null", "===", "$", "route", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Route \"%s\" not found.'", ",", "$", "routeName", ")", ")", ";", "}", "return", "$", "route", ";", "}" ]
Finds the route definition. @param string $routeName @return null|\Symfony\Component\Routing\Route
[ "Finds", "the", "route", "definition", "." ]
3f58e253ae9cf651add7f3d587caec80eaea459a
https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Helper/ResourceHelper.php#L163-L176
train
smalldb/libSmalldb
class/FlupdoCrudMachine.php
FlupdoCrudMachine.setupDefaultMachine
protected function setupDefaultMachine(array $config) { // Name of inputs and outputs with properties $io_name = isset($config['io_name']) ? (string) $config['io_name'] : 'item'; // Create default transitions? $no_default_transitions = !empty($config['crud_machine_no_default_transitions']); /// @deprecated // Exists state only $this->states = array_replace_recursive($no_default_transitions ? array() : array( 'exists' => array( 'label' => _('Exists'), 'description' => '', ), ), $this->states ? : []); // Simple 'exists' state if not state select is not defined if ($this->state_select === null) { $this->state_select = '"exists"'; } // Actions $this->actions = array_replace_recursive(array( 'create' => array( 'label' => _('Create'), 'description' => _('Create a new item'), 'transitions' => $no_default_transitions ? array() : array( '' => array( 'targets' => array('exists'), ), ), 'returns' => self::RETURNS_NEW_ID, 'block' => array( 'inputs' => array( $io_name => array() ), 'outputs' => array( 'ref' => 'return_value' ), 'accepted_exceptions' => array( 'PDOException' => true, ), ), ), 'edit' => array( 'label' => _('Edit'), 'description' => _('Modify item'), 'transitions' => $no_default_transitions ? array() : array( 'exists' => array( 'targets' => array('exists'), ), ), 'block' => array( 'inputs' => array( 'ref' => array(), $io_name => array() ), 'outputs' => array( 'ref' => 'ref' ), 'accepted_exceptions' => array( 'PDOException' => true, ), ), ), 'delete' => array( 'label' => _('Delete'), 'description' => _('Delete item'), 'weight' => 80, 'transitions' => $no_default_transitions ? array() : array( 'exists' => array( 'targets' => array(''), ), ), 'block' => array( 'inputs' => array( 'ref' => array(), ), 'outputs' => array( ), 'accepted_exceptions' => array( 'PDOException' => true, ), ), ), ), $this->actions ? : []); }
php
protected function setupDefaultMachine(array $config) { // Name of inputs and outputs with properties $io_name = isset($config['io_name']) ? (string) $config['io_name'] : 'item'; // Create default transitions? $no_default_transitions = !empty($config['crud_machine_no_default_transitions']); /// @deprecated // Exists state only $this->states = array_replace_recursive($no_default_transitions ? array() : array( 'exists' => array( 'label' => _('Exists'), 'description' => '', ), ), $this->states ? : []); // Simple 'exists' state if not state select is not defined if ($this->state_select === null) { $this->state_select = '"exists"'; } // Actions $this->actions = array_replace_recursive(array( 'create' => array( 'label' => _('Create'), 'description' => _('Create a new item'), 'transitions' => $no_default_transitions ? array() : array( '' => array( 'targets' => array('exists'), ), ), 'returns' => self::RETURNS_NEW_ID, 'block' => array( 'inputs' => array( $io_name => array() ), 'outputs' => array( 'ref' => 'return_value' ), 'accepted_exceptions' => array( 'PDOException' => true, ), ), ), 'edit' => array( 'label' => _('Edit'), 'description' => _('Modify item'), 'transitions' => $no_default_transitions ? array() : array( 'exists' => array( 'targets' => array('exists'), ), ), 'block' => array( 'inputs' => array( 'ref' => array(), $io_name => array() ), 'outputs' => array( 'ref' => 'ref' ), 'accepted_exceptions' => array( 'PDOException' => true, ), ), ), 'delete' => array( 'label' => _('Delete'), 'description' => _('Delete item'), 'weight' => 80, 'transitions' => $no_default_transitions ? array() : array( 'exists' => array( 'targets' => array(''), ), ), 'block' => array( 'inputs' => array( 'ref' => array(), ), 'outputs' => array( ), 'accepted_exceptions' => array( 'PDOException' => true, ), ), ), ), $this->actions ? : []); }
[ "protected", "function", "setupDefaultMachine", "(", "array", "$", "config", ")", "{", "// Name of inputs and outputs with properties", "$", "io_name", "=", "isset", "(", "$", "config", "[", "'io_name'", "]", ")", "?", "(", "string", ")", "$", "config", "[", "'io_name'", "]", ":", "'item'", ";", "// Create default transitions?", "$", "no_default_transitions", "=", "!", "empty", "(", "$", "config", "[", "'crud_machine_no_default_transitions'", "]", ")", ";", "/// @deprecated", "// Exists state only", "$", "this", "->", "states", "=", "array_replace_recursive", "(", "$", "no_default_transitions", "?", "array", "(", ")", ":", "array", "(", "'exists'", "=>", "array", "(", "'label'", "=>", "_", "(", "'Exists'", ")", ",", "'description'", "=>", "''", ",", ")", ",", ")", ",", "$", "this", "->", "states", "?", ":", "[", "]", ")", ";", "// Simple 'exists' state if not state select is not defined", "if", "(", "$", "this", "->", "state_select", "===", "null", ")", "{", "$", "this", "->", "state_select", "=", "'\"exists\"'", ";", "}", "// Actions", "$", "this", "->", "actions", "=", "array_replace_recursive", "(", "array", "(", "'create'", "=>", "array", "(", "'label'", "=>", "_", "(", "'Create'", ")", ",", "'description'", "=>", "_", "(", "'Create a new item'", ")", ",", "'transitions'", "=>", "$", "no_default_transitions", "?", "array", "(", ")", ":", "array", "(", "''", "=>", "array", "(", "'targets'", "=>", "array", "(", "'exists'", ")", ",", ")", ",", ")", ",", "'returns'", "=>", "self", "::", "RETURNS_NEW_ID", ",", "'block'", "=>", "array", "(", "'inputs'", "=>", "array", "(", "$", "io_name", "=>", "array", "(", ")", ")", ",", "'outputs'", "=>", "array", "(", "'ref'", "=>", "'return_value'", ")", ",", "'accepted_exceptions'", "=>", "array", "(", "'PDOException'", "=>", "true", ",", ")", ",", ")", ",", ")", ",", "'edit'", "=>", "array", "(", "'label'", "=>", "_", "(", "'Edit'", ")", ",", "'description'", "=>", "_", "(", "'Modify item'", ")", ",", "'transitions'", "=>", "$", "no_default_transitions", "?", "array", "(", ")", ":", "array", "(", "'exists'", "=>", "array", "(", "'targets'", "=>", "array", "(", "'exists'", ")", ",", ")", ",", ")", ",", "'block'", "=>", "array", "(", "'inputs'", "=>", "array", "(", "'ref'", "=>", "array", "(", ")", ",", "$", "io_name", "=>", "array", "(", ")", ")", ",", "'outputs'", "=>", "array", "(", "'ref'", "=>", "'ref'", ")", ",", "'accepted_exceptions'", "=>", "array", "(", "'PDOException'", "=>", "true", ",", ")", ",", ")", ",", ")", ",", "'delete'", "=>", "array", "(", "'label'", "=>", "_", "(", "'Delete'", ")", ",", "'description'", "=>", "_", "(", "'Delete item'", ")", ",", "'weight'", "=>", "80", ",", "'transitions'", "=>", "$", "no_default_transitions", "?", "array", "(", ")", ":", "array", "(", "'exists'", "=>", "array", "(", "'targets'", "=>", "array", "(", "''", ")", ",", ")", ",", ")", ",", "'block'", "=>", "array", "(", "'inputs'", "=>", "array", "(", "'ref'", "=>", "array", "(", ")", ",", ")", ",", "'outputs'", "=>", "array", "(", ")", ",", "'accepted_exceptions'", "=>", "array", "(", "'PDOException'", "=>", "true", ",", ")", ",", ")", ",", ")", ",", ")", ",", "$", "this", "->", "actions", "?", ":", "[", "]", ")", ";", "}" ]
Setup basic CRUD machine.
[ "Setup", "basic", "CRUD", "machine", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L95-L181
train
smalldb/libSmalldb
class/FlupdoCrudMachine.php
FlupdoCrudMachine.recalculateTree
protected function recalculateTree() { if (!$this->nested_sets_enabled) { throw new \RuntimeException('Nested sets are disabled for this entity.'); } $q_table = $this->flupdo->quoteIdent($this->table); $cols = $this->nested_sets_table_columns; $c_order_by = $this->nested_sets_order_by; $c_id = $this->flupdo->quoteIdent($cols['id']); $c_parent_id = $this->flupdo->quoteIdent($cols['parent_id']); $c_left = $this->flupdo->quoteIdent($cols['left']); $c_right = $this->flupdo->quoteIdent($cols['right']); $c_depth = $this->flupdo->quoteIdent($cols['depth']); $set = $this->flupdo->select($c_id) ->from($q_table) ->where("$c_parent_id IS NULL") ->orderBy($c_order_by) ->query(); $this->recalculateSubTree($set, 1, 0, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth); }
php
protected function recalculateTree() { if (!$this->nested_sets_enabled) { throw new \RuntimeException('Nested sets are disabled for this entity.'); } $q_table = $this->flupdo->quoteIdent($this->table); $cols = $this->nested_sets_table_columns; $c_order_by = $this->nested_sets_order_by; $c_id = $this->flupdo->quoteIdent($cols['id']); $c_parent_id = $this->flupdo->quoteIdent($cols['parent_id']); $c_left = $this->flupdo->quoteIdent($cols['left']); $c_right = $this->flupdo->quoteIdent($cols['right']); $c_depth = $this->flupdo->quoteIdent($cols['depth']); $set = $this->flupdo->select($c_id) ->from($q_table) ->where("$c_parent_id IS NULL") ->orderBy($c_order_by) ->query(); $this->recalculateSubTree($set, 1, 0, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth); }
[ "protected", "function", "recalculateTree", "(", ")", "{", "if", "(", "!", "$", "this", "->", "nested_sets_enabled", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Nested sets are disabled for this entity.'", ")", ";", "}", "$", "q_table", "=", "$", "this", "->", "flupdo", "->", "quoteIdent", "(", "$", "this", "->", "table", ")", ";", "$", "cols", "=", "$", "this", "->", "nested_sets_table_columns", ";", "$", "c_order_by", "=", "$", "this", "->", "nested_sets_order_by", ";", "$", "c_id", "=", "$", "this", "->", "flupdo", "->", "quoteIdent", "(", "$", "cols", "[", "'id'", "]", ")", ";", "$", "c_parent_id", "=", "$", "this", "->", "flupdo", "->", "quoteIdent", "(", "$", "cols", "[", "'parent_id'", "]", ")", ";", "$", "c_left", "=", "$", "this", "->", "flupdo", "->", "quoteIdent", "(", "$", "cols", "[", "'left'", "]", ")", ";", "$", "c_right", "=", "$", "this", "->", "flupdo", "->", "quoteIdent", "(", "$", "cols", "[", "'right'", "]", ")", ";", "$", "c_depth", "=", "$", "this", "->", "flupdo", "->", "quoteIdent", "(", "$", "cols", "[", "'depth'", "]", ")", ";", "$", "set", "=", "$", "this", "->", "flupdo", "->", "select", "(", "$", "c_id", ")", "->", "from", "(", "$", "q_table", ")", "->", "where", "(", "\"$c_parent_id IS NULL\"", ")", "->", "orderBy", "(", "$", "c_order_by", ")", "->", "query", "(", ")", ";", "$", "this", "->", "recalculateSubTree", "(", "$", "set", ",", "1", ",", "0", ",", "$", "q_table", ",", "$", "c_order_by", ",", "$", "c_id", ",", "$", "c_parent_id", ",", "$", "c_left", ",", "$", "c_right", ",", "$", "c_depth", ")", ";", "}" ]
Recalculate nested-sets tree indices To use this feature a parent, left, right and depth columns must be specified. Composed primary keys are not supported yet. Three extra columns are required: tree_left, tree_right, tree_depth (ints, all nullable). This function will update them according to id and parent_id columns.
[ "Recalculate", "nested", "-", "sets", "tree", "indices" ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L350-L372
train
smalldb/libSmalldb
class/FlupdoCrudMachine.php
FlupdoCrudMachine.recalculateSubTree
private function recalculateSubTree($set, $left, $depth, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth) { foreach($set as $row) { $id = $row['id']; $this->flupdo->update($q_table) ->set("$c_left = ?", $left) ->set("$c_depth = ?", $depth) ->where("$c_id = ?", $id) ->exec(); $sub_set = $this->flupdo->select($c_id) ->from($q_table) ->where("$c_parent_id = ?", $id) ->orderBy($c_order_by) ->query(); $left = $this->recalculateSubTree($sub_set, $left + 1, $depth + 1, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth); $this->flupdo->update($q_table) ->set("$c_right = ?", $left) ->where("$c_id = ?", $id) ->exec(); $left++; } return $left; }
php
private function recalculateSubTree($set, $left, $depth, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth) { foreach($set as $row) { $id = $row['id']; $this->flupdo->update($q_table) ->set("$c_left = ?", $left) ->set("$c_depth = ?", $depth) ->where("$c_id = ?", $id) ->exec(); $sub_set = $this->flupdo->select($c_id) ->from($q_table) ->where("$c_parent_id = ?", $id) ->orderBy($c_order_by) ->query(); $left = $this->recalculateSubTree($sub_set, $left + 1, $depth + 1, $q_table, $c_order_by, $c_id, $c_parent_id, $c_left, $c_right, $c_depth); $this->flupdo->update($q_table) ->set("$c_right = ?", $left) ->where("$c_id = ?", $id) ->exec(); $left++; } return $left; }
[ "private", "function", "recalculateSubTree", "(", "$", "set", ",", "$", "left", ",", "$", "depth", ",", "$", "q_table", ",", "$", "c_order_by", ",", "$", "c_id", ",", "$", "c_parent_id", ",", "$", "c_left", ",", "$", "c_right", ",", "$", "c_depth", ")", "{", "foreach", "(", "$", "set", "as", "$", "row", ")", "{", "$", "id", "=", "$", "row", "[", "'id'", "]", ";", "$", "this", "->", "flupdo", "->", "update", "(", "$", "q_table", ")", "->", "set", "(", "\"$c_left = ?\"", ",", "$", "left", ")", "->", "set", "(", "\"$c_depth = ?\"", ",", "$", "depth", ")", "->", "where", "(", "\"$c_id = ?\"", ",", "$", "id", ")", "->", "exec", "(", ")", ";", "$", "sub_set", "=", "$", "this", "->", "flupdo", "->", "select", "(", "$", "c_id", ")", "->", "from", "(", "$", "q_table", ")", "->", "where", "(", "\"$c_parent_id = ?\"", ",", "$", "id", ")", "->", "orderBy", "(", "$", "c_order_by", ")", "->", "query", "(", ")", ";", "$", "left", "=", "$", "this", "->", "recalculateSubTree", "(", "$", "sub_set", ",", "$", "left", "+", "1", ",", "$", "depth", "+", "1", ",", "$", "q_table", ",", "$", "c_order_by", ",", "$", "c_id", ",", "$", "c_parent_id", ",", "$", "c_left", ",", "$", "c_right", ",", "$", "c_depth", ")", ";", "$", "this", "->", "flupdo", "->", "update", "(", "$", "q_table", ")", "->", "set", "(", "\"$c_right = ?\"", ",", "$", "left", ")", "->", "where", "(", "\"$c_id = ?\"", ",", "$", "id", ")", "->", "exec", "(", ")", ";", "$", "left", "++", ";", "}", "return", "$", "left", ";", "}" ]
Recalculate given subtree. @see recalculateTree()
[ "Recalculate", "given", "subtree", "." ]
b94d22af5014e8060d0530fc7043768cdc57b01a
https://github.com/smalldb/libSmalldb/blob/b94d22af5014e8060d0530fc7043768cdc57b01a/class/FlupdoCrudMachine.php#L380-L408
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._setOptions
protected function _setOptions(array $options) { if (isset($options['escape'])) { if (!is_callable($options['escape'])) { throw new InvalidArgumentException('Mustache constructor "escape" option must be callable'); } $this->_escape = $options['escape']; } if (isset($options['charset'])) { $this->_charset = $options['charset']; } if (isset($options['delimiters'])) { $delims = $options['delimiters']; if (!is_array($delims)) { $delims = array_map('trim', explode(' ', $delims, 2)); } $this->_otag = $delims[0]; $this->_ctag = $delims[1]; } if (isset($options['pragmas'])) { foreach ($options['pragmas'] as $pragma_name => $pragma_value) { if (!in_array($pragma_name, $this->_pragmasImplemented, true)) { throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); } } $this->_pragmas = $options['pragmas']; } if (isset($options['throws_exceptions'])) { foreach ($options['throws_exceptions'] as $exception => $value) { $this->_throwsExceptions[$exception] = $value; } } }
php
protected function _setOptions(array $options) { if (isset($options['escape'])) { if (!is_callable($options['escape'])) { throw new InvalidArgumentException('Mustache constructor "escape" option must be callable'); } $this->_escape = $options['escape']; } if (isset($options['charset'])) { $this->_charset = $options['charset']; } if (isset($options['delimiters'])) { $delims = $options['delimiters']; if (!is_array($delims)) { $delims = array_map('trim', explode(' ', $delims, 2)); } $this->_otag = $delims[0]; $this->_ctag = $delims[1]; } if (isset($options['pragmas'])) { foreach ($options['pragmas'] as $pragma_name => $pragma_value) { if (!in_array($pragma_name, $this->_pragmasImplemented, true)) { throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); } } $this->_pragmas = $options['pragmas']; } if (isset($options['throws_exceptions'])) { foreach ($options['throws_exceptions'] as $exception => $value) { $this->_throwsExceptions[$exception] = $value; } } }
[ "protected", "function", "_setOptions", "(", "array", "$", "options", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'escape'", "]", ")", ")", "{", "if", "(", "!", "is_callable", "(", "$", "options", "[", "'escape'", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Mustache constructor \"escape\" option must be callable'", ")", ";", "}", "$", "this", "->", "_escape", "=", "$", "options", "[", "'escape'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'charset'", "]", ")", ")", "{", "$", "this", "->", "_charset", "=", "$", "options", "[", "'charset'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'delimiters'", "]", ")", ")", "{", "$", "delims", "=", "$", "options", "[", "'delimiters'", "]", ";", "if", "(", "!", "is_array", "(", "$", "delims", ")", ")", "{", "$", "delims", "=", "array_map", "(", "'trim'", ",", "explode", "(", "' '", ",", "$", "delims", ",", "2", ")", ")", ";", "}", "$", "this", "->", "_otag", "=", "$", "delims", "[", "0", "]", ";", "$", "this", "->", "_ctag", "=", "$", "delims", "[", "1", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'pragmas'", "]", ")", ")", "{", "foreach", "(", "$", "options", "[", "'pragmas'", "]", "as", "$", "pragma_name", "=>", "$", "pragma_value", ")", "{", "if", "(", "!", "in_array", "(", "$", "pragma_name", ",", "$", "this", "->", "_pragmasImplemented", ",", "true", ")", ")", "{", "throw", "new", "MustacheException", "(", "'Unknown pragma: '", ".", "$", "pragma_name", ",", "MustacheException", "::", "UNKNOWN_PRAGMA", ")", ";", "}", "}", "$", "this", "->", "_pragmas", "=", "$", "options", "[", "'pragmas'", "]", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'throws_exceptions'", "]", ")", ")", "{", "foreach", "(", "$", "options", "[", "'throws_exceptions'", "]", "as", "$", "exception", "=>", "$", "value", ")", "{", "$", "this", "->", "_throwsExceptions", "[", "$", "exception", "]", "=", "$", "value", ";", "}", "}", "}" ]
Helper function for setting options from constructor args. @access protected @param array $options @return void
[ "Helper", "function", "for", "setting", "options", "from", "constructor", "args", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L140-L175
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine.render
public function render($template = null, $view = null, $partials = null) { if ($template === null) $template = $this->_template; if ($partials !== null) $this->_partials = $partials; $otag_orig = $this->_otag; $ctag_orig = $this->_ctag; // Including server properties in the view //$view = array_merge($this->server->getAll(), $view); $view['baseUrl'] = $this->server->siteUrl(''); if ($view) { $this->_context = array($view); } else if (empty($this->_context)) { $this->_context = array($this); } $template = $this->_renderPragmas($template); $template = $this->_renderTemplate($template); $this->_otag = $otag_orig; $this->_ctag = $ctag_orig; return $template; }
php
public function render($template = null, $view = null, $partials = null) { if ($template === null) $template = $this->_template; if ($partials !== null) $this->_partials = $partials; $otag_orig = $this->_otag; $ctag_orig = $this->_ctag; // Including server properties in the view //$view = array_merge($this->server->getAll(), $view); $view['baseUrl'] = $this->server->siteUrl(''); if ($view) { $this->_context = array($view); } else if (empty($this->_context)) { $this->_context = array($this); } $template = $this->_renderPragmas($template); $template = $this->_renderTemplate($template); $this->_otag = $otag_orig; $this->_ctag = $ctag_orig; return $template; }
[ "public", "function", "render", "(", "$", "template", "=", "null", ",", "$", "view", "=", "null", ",", "$", "partials", "=", "null", ")", "{", "if", "(", "$", "template", "===", "null", ")", "$", "template", "=", "$", "this", "->", "_template", ";", "if", "(", "$", "partials", "!==", "null", ")", "$", "this", "->", "_partials", "=", "$", "partials", ";", "$", "otag_orig", "=", "$", "this", "->", "_otag", ";", "$", "ctag_orig", "=", "$", "this", "->", "_ctag", ";", "// Including server properties in the view", "//$view = array_merge($this->server->getAll(), $view);", "$", "view", "[", "'baseUrl'", "]", "=", "$", "this", "->", "server", "->", "siteUrl", "(", "''", ")", ";", "if", "(", "$", "view", ")", "{", "$", "this", "->", "_context", "=", "array", "(", "$", "view", ")", ";", "}", "else", "if", "(", "empty", "(", "$", "this", "->", "_context", ")", ")", "{", "$", "this", "->", "_context", "=", "array", "(", "$", "this", ")", ";", "}", "$", "template", "=", "$", "this", "->", "_renderPragmas", "(", "$", "template", ")", ";", "$", "template", "=", "$", "this", "->", "_renderTemplate", "(", "$", "template", ")", ";", "$", "this", "->", "_otag", "=", "$", "otag_orig", ";", "$", "this", "->", "_ctag", "=", "$", "ctag_orig", ";", "return", "$", "template", ";", "}" ]
Render the given template and view object. Defaults to the template and view passed to the class constructor unless a new one is provided. Optionally, pass an associative array of partials as well. @access public @param string $template (default: null) @param mixed $view (default: null) @param array $partials (default: null) @return string Rendered Mustache template.
[ "Render", "the", "given", "template", "and", "view", "object", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L211-L235
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._renderTemplate
protected function _renderTemplate($template) { if ($section = $this->_findSection($template)) { list($before, $type, $tag_name, $content, $after) = $section; $rendered_before = $this->_renderTags($before); $rendered_content = ''; $val = $this->_getVariable($tag_name); switch($type) { // inverted section case '^': if (empty($val)) { $rendered_content = $this->_renderTemplate($content); } break; // regular section case '#': // higher order sections if ($this->_varIsCallable($val)) { $rendered_content = $this->_renderTemplate(call_user_func($val, $content)); } else if ($this->_varIsIterable($val)) { foreach ($val as $local_context) { $this->_pushContext($local_context); $rendered_content .= $this->_renderTemplate($content); $this->_popContext(); } } else if ($val) { if (is_array($val) || is_object($val)) { $this->_pushContext($val); $rendered_content = $this->_renderTemplate($content); $this->_popContext(); } else { $rendered_content = $this->_renderTemplate($content); } } break; } return $rendered_before . $rendered_content . $this->_renderTemplate($after); } return $this->_renderTags($template); }
php
protected function _renderTemplate($template) { if ($section = $this->_findSection($template)) { list($before, $type, $tag_name, $content, $after) = $section; $rendered_before = $this->_renderTags($before); $rendered_content = ''; $val = $this->_getVariable($tag_name); switch($type) { // inverted section case '^': if (empty($val)) { $rendered_content = $this->_renderTemplate($content); } break; // regular section case '#': // higher order sections if ($this->_varIsCallable($val)) { $rendered_content = $this->_renderTemplate(call_user_func($val, $content)); } else if ($this->_varIsIterable($val)) { foreach ($val as $local_context) { $this->_pushContext($local_context); $rendered_content .= $this->_renderTemplate($content); $this->_popContext(); } } else if ($val) { if (is_array($val) || is_object($val)) { $this->_pushContext($val); $rendered_content = $this->_renderTemplate($content); $this->_popContext(); } else { $rendered_content = $this->_renderTemplate($content); } } break; } return $rendered_before . $rendered_content . $this->_renderTemplate($after); } return $this->_renderTags($template); }
[ "protected", "function", "_renderTemplate", "(", "$", "template", ")", "{", "if", "(", "$", "section", "=", "$", "this", "->", "_findSection", "(", "$", "template", ")", ")", "{", "list", "(", "$", "before", ",", "$", "type", ",", "$", "tag_name", ",", "$", "content", ",", "$", "after", ")", "=", "$", "section", ";", "$", "rendered_before", "=", "$", "this", "->", "_renderTags", "(", "$", "before", ")", ";", "$", "rendered_content", "=", "''", ";", "$", "val", "=", "$", "this", "->", "_getVariable", "(", "$", "tag_name", ")", ";", "switch", "(", "$", "type", ")", "{", "// inverted section", "case", "'^'", ":", "if", "(", "empty", "(", "$", "val", ")", ")", "{", "$", "rendered_content", "=", "$", "this", "->", "_renderTemplate", "(", "$", "content", ")", ";", "}", "break", ";", "// regular section", "case", "'#'", ":", "// higher order sections", "if", "(", "$", "this", "->", "_varIsCallable", "(", "$", "val", ")", ")", "{", "$", "rendered_content", "=", "$", "this", "->", "_renderTemplate", "(", "call_user_func", "(", "$", "val", ",", "$", "content", ")", ")", ";", "}", "else", "if", "(", "$", "this", "->", "_varIsIterable", "(", "$", "val", ")", ")", "{", "foreach", "(", "$", "val", "as", "$", "local_context", ")", "{", "$", "this", "->", "_pushContext", "(", "$", "local_context", ")", ";", "$", "rendered_content", ".=", "$", "this", "->", "_renderTemplate", "(", "$", "content", ")", ";", "$", "this", "->", "_popContext", "(", ")", ";", "}", "}", "else", "if", "(", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", "||", "is_object", "(", "$", "val", ")", ")", "{", "$", "this", "->", "_pushContext", "(", "$", "val", ")", ";", "$", "rendered_content", "=", "$", "this", "->", "_renderTemplate", "(", "$", "content", ")", ";", "$", "this", "->", "_popContext", "(", ")", ";", "}", "else", "{", "$", "rendered_content", "=", "$", "this", "->", "_renderTemplate", "(", "$", "content", ")", ";", "}", "}", "break", ";", "}", "return", "$", "rendered_before", ".", "$", "rendered_content", ".", "$", "this", "->", "_renderTemplate", "(", "$", "after", ")", ";", "}", "return", "$", "this", "->", "_renderTags", "(", "$", "template", ")", ";", "}" ]
Internal render function, used for recursive calls. @access protected @param string $template @return string Rendered Mustache template.
[ "Internal", "render", "function", "used", "for", "recursive", "calls", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L261-L304
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._renderPragmas
protected function _renderPragmas($template) { $this->_localPragmas = $this->_pragmas; // no pragmas if (strpos($template, $this->_otag . '%') === false) { return $template; } $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag); return preg_replace_callback($regEx, array($this, '_renderPragma'), $template); }
php
protected function _renderPragmas($template) { $this->_localPragmas = $this->_pragmas; // no pragmas if (strpos($template, $this->_otag . '%') === false) { return $template; } $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag); return preg_replace_callback($regEx, array($this, '_renderPragma'), $template); }
[ "protected", "function", "_renderPragmas", "(", "$", "template", ")", "{", "$", "this", "->", "_localPragmas", "=", "$", "this", "->", "_pragmas", ";", "// no pragmas", "if", "(", "strpos", "(", "$", "template", ",", "$", "this", "->", "_otag", ".", "'%'", ")", "===", "false", ")", "{", "return", "$", "template", ";", "}", "$", "regEx", "=", "$", "this", "->", "_preparePragmaRegEx", "(", "$", "this", "->", "_otag", ",", "$", "this", "->", "_ctag", ")", ";", "return", "preg_replace_callback", "(", "$", "regEx", ",", "array", "(", "$", "this", ",", "'_renderPragma'", ")", ",", "$", "template", ")", ";", "}" ]
Initialize pragmas and remove all pragma tags. @access protected @param string $template @return string
[ "Initialize", "pragmas", "and", "remove", "all", "pragma", "tags", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L417-L427
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._hasPragma
protected function _hasPragma($pragma_name) { if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) { return true; } else { return false; } }
php
protected function _hasPragma($pragma_name) { if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) { return true; } else { return false; } }
[ "protected", "function", "_hasPragma", "(", "$", "pragma_name", ")", "{", "if", "(", "array_key_exists", "(", "$", "pragma_name", ",", "$", "this", "->", "_localPragmas", ")", "&&", "$", "this", "->", "_localPragmas", "[", "$", "pragma_name", "]", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Check whether this Mustache has a specific pragma. @access protected @param string $pragma_name @return bool
[ "Check", "whether", "this", "Mustache", "has", "a", "specific", "pragma", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L474-L480
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._getPragmaOptions
protected function _getPragmaOptions($pragma_name) { if (!$this->_hasPragma($pragma_name)) { if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) { throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); } } return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array(); }
php
protected function _getPragmaOptions($pragma_name) { if (!$this->_hasPragma($pragma_name)) { if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) { throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); } } return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array(); }
[ "protected", "function", "_getPragmaOptions", "(", "$", "pragma_name", ")", "{", "if", "(", "!", "$", "this", "->", "_hasPragma", "(", "$", "pragma_name", ")", ")", "{", "if", "(", "$", "this", "->", "_throwsException", "(", "MustacheException", "::", "UNKNOWN_PRAGMA", ")", ")", "{", "throw", "new", "MustacheException", "(", "'Unknown pragma: '", ".", "$", "pragma_name", ",", "MustacheException", "::", "UNKNOWN_PRAGMA", ")", ";", "}", "}", "return", "(", "is_array", "(", "$", "this", "->", "_localPragmas", "[", "$", "pragma_name", "]", ")", ")", "?", "$", "this", "->", "_localPragmas", "[", "$", "pragma_name", "]", ":", "array", "(", ")", ";", "}" ]
Return pragma options, if any. @access protected @param string $pragma_name @return mixed @throws MustacheException Unknown pragma
[ "Return", "pragma", "options", "if", "any", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L490-L498
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._renderTags
protected function _renderTags($template) { if (strpos($template, $this->_otag) === false) { return $template; } $first = true; $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true); $html = ''; $matches = array(); while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) { $tag = $matches[0][0]; $offset = $matches[0][1]; $modifier = $matches['type'][0]; $tag_name = trim($matches['tag_name'][0]); if (isset($matches['leading']) && $matches['leading'][1] > -1) { $leading = $matches['leading'][0]; } else { $leading = null; } if (isset($matches['trailing']) && $matches['trailing'][1] > -1) { $trailing = $matches['trailing'][0]; } else { $trailing = null; } $html .= substr($template, 0, $offset); $next_offset = $offset + strlen($tag); if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) { $next_offset++; } $template = substr($template, $next_offset); $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing); if ($first == true) { $first = false; $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); } } return $html . $template; }
php
protected function _renderTags($template) { if (strpos($template, $this->_otag) === false) { return $template; } $first = true; $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true); $html = ''; $matches = array(); while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) { $tag = $matches[0][0]; $offset = $matches[0][1]; $modifier = $matches['type'][0]; $tag_name = trim($matches['tag_name'][0]); if (isset($matches['leading']) && $matches['leading'][1] > -1) { $leading = $matches['leading'][0]; } else { $leading = null; } if (isset($matches['trailing']) && $matches['trailing'][1] > -1) { $trailing = $matches['trailing'][0]; } else { $trailing = null; } $html .= substr($template, 0, $offset); $next_offset = $offset + strlen($tag); if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) { $next_offset++; } $template = substr($template, $next_offset); $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing); if ($first == true) { $first = false; $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); } } return $html . $template; }
[ "protected", "function", "_renderTags", "(", "$", "template", ")", "{", "if", "(", "strpos", "(", "$", "template", ",", "$", "this", "->", "_otag", ")", "===", "false", ")", "{", "return", "$", "template", ";", "}", "$", "first", "=", "true", ";", "$", "this", "->", "_tagRegEx", "=", "$", "this", "->", "_prepareTagRegEx", "(", "$", "this", "->", "_otag", ",", "$", "this", "->", "_ctag", ",", "true", ")", ";", "$", "html", "=", "''", ";", "$", "matches", "=", "array", "(", ")", ";", "while", "(", "preg_match", "(", "$", "this", "->", "_tagRegEx", ",", "$", "template", ",", "$", "matches", ",", "PREG_OFFSET_CAPTURE", ")", ")", "{", "$", "tag", "=", "$", "matches", "[", "0", "]", "[", "0", "]", ";", "$", "offset", "=", "$", "matches", "[", "0", "]", "[", "1", "]", ";", "$", "modifier", "=", "$", "matches", "[", "'type'", "]", "[", "0", "]", ";", "$", "tag_name", "=", "trim", "(", "$", "matches", "[", "'tag_name'", "]", "[", "0", "]", ")", ";", "if", "(", "isset", "(", "$", "matches", "[", "'leading'", "]", ")", "&&", "$", "matches", "[", "'leading'", "]", "[", "1", "]", ">", "-", "1", ")", "{", "$", "leading", "=", "$", "matches", "[", "'leading'", "]", "[", "0", "]", ";", "}", "else", "{", "$", "leading", "=", "null", ";", "}", "if", "(", "isset", "(", "$", "matches", "[", "'trailing'", "]", ")", "&&", "$", "matches", "[", "'trailing'", "]", "[", "1", "]", ">", "-", "1", ")", "{", "$", "trailing", "=", "$", "matches", "[", "'trailing'", "]", "[", "0", "]", ";", "}", "else", "{", "$", "trailing", "=", "null", ";", "}", "$", "html", ".=", "substr", "(", "$", "template", ",", "0", ",", "$", "offset", ")", ";", "$", "next_offset", "=", "$", "offset", "+", "strlen", "(", "$", "tag", ")", ";", "if", "(", "(", "substr", "(", "$", "html", ",", "-", "1", ")", "==", "\"\\n\"", ")", "&&", "(", "substr", "(", "$", "template", ",", "$", "next_offset", ",", "1", ")", "==", "\"\\n\"", ")", ")", "{", "$", "next_offset", "++", ";", "}", "$", "template", "=", "substr", "(", "$", "template", ",", "$", "next_offset", ")", ";", "$", "html", ".=", "$", "this", "->", "_renderTag", "(", "$", "modifier", ",", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "if", "(", "$", "first", "==", "true", ")", "{", "$", "first", "=", "false", ";", "$", "this", "->", "_tagRegEx", "=", "$", "this", "->", "_prepareTagRegEx", "(", "$", "this", "->", "_otag", ",", "$", "this", "->", "_ctag", ")", ";", "}", "}", "return", "$", "html", ".", "$", "template", ";", "}" ]
Loop through and render individual Mustache tags. @access protected @param string $template @return void
[ "Loop", "through", "and", "render", "individual", "Mustache", "tags", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L538-L583
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._renderTag
protected function _renderTag($modifier, $tag_name, $leading, $trailing) { switch ($modifier) { case '=': return $this->_changeDelimiter($tag_name, $leading, $trailing); break; case '!': return $this->_renderComment($tag_name, $leading, $trailing); break; case '>': case '<': return $this->_renderPartial($tag_name, $leading, $trailing); break; case '{': // strip the trailing } ... if ($tag_name[(strlen($tag_name) - 1)] == '}') { $tag_name = substr($tag_name, 0, -1); } case '&': if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { return $this->_renderEscaped($tag_name, $leading, $trailing); } else { return $this->_renderUnescaped($tag_name, $leading, $trailing); } break; case '#': case '^': case "*": return $leading . $this->server->siteUrl($tag_name) . $trailing; break; case '/': // remove any leftover section tags return $leading . $trailing; break; default: if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing); } else { return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing); } break; } }
php
protected function _renderTag($modifier, $tag_name, $leading, $trailing) { switch ($modifier) { case '=': return $this->_changeDelimiter($tag_name, $leading, $trailing); break; case '!': return $this->_renderComment($tag_name, $leading, $trailing); break; case '>': case '<': return $this->_renderPartial($tag_name, $leading, $trailing); break; case '{': // strip the trailing } ... if ($tag_name[(strlen($tag_name) - 1)] == '}') { $tag_name = substr($tag_name, 0, -1); } case '&': if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { return $this->_renderEscaped($tag_name, $leading, $trailing); } else { return $this->_renderUnescaped($tag_name, $leading, $trailing); } break; case '#': case '^': case "*": return $leading . $this->server->siteUrl($tag_name) . $trailing; break; case '/': // remove any leftover section tags return $leading . $trailing; break; default: if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing); } else { return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing); } break; } }
[ "protected", "function", "_renderTag", "(", "$", "modifier", ",", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", "{", "switch", "(", "$", "modifier", ")", "{", "case", "'='", ":", "return", "$", "this", "->", "_changeDelimiter", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "break", ";", "case", "'!'", ":", "return", "$", "this", "->", "_renderComment", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "break", ";", "case", "'>'", ":", "case", "'<'", ":", "return", "$", "this", "->", "_renderPartial", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "break", ";", "case", "'{'", ":", "// strip the trailing } ...", "if", "(", "$", "tag_name", "[", "(", "strlen", "(", "$", "tag_name", ")", "-", "1", ")", "]", "==", "'}'", ")", "{", "$", "tag_name", "=", "substr", "(", "$", "tag_name", ",", "0", ",", "-", "1", ")", ";", "}", "case", "'&'", ":", "if", "(", "$", "this", "->", "_hasPragma", "(", "self", "::", "PRAGMA_UNESCAPED", ")", ")", "{", "return", "$", "this", "->", "_renderEscaped", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "}", "else", "{", "return", "$", "this", "->", "_renderUnescaped", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "}", "break", ";", "case", "'#'", ":", "case", "'^'", ":", "case", "\"*\"", ":", "return", "$", "leading", ".", "$", "this", "->", "server", "->", "siteUrl", "(", "$", "tag_name", ")", ".", "$", "trailing", ";", "break", ";", "case", "'/'", ":", "// remove any leftover section tags", "return", "$", "leading", ".", "$", "trailing", ";", "break", ";", "default", ":", "if", "(", "$", "this", "->", "_hasPragma", "(", "self", "::", "PRAGMA_UNESCAPED", ")", ")", "{", "return", "$", "this", "->", "_renderUnescaped", "(", "$", "modifier", ".", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "}", "else", "{", "return", "$", "this", "->", "_renderEscaped", "(", "$", "modifier", ".", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", ";", "}", "break", ";", "}", "}" ]
Render the named tag, given the specified modifier. Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial) `{` or `&` (don't escape output), or none (render escaped output). @access protected @param string $modifier @param string $tag_name @param string $leading Whitespace @param string $trailing Whitespace @throws MustacheException Unmatched section tag encountered. @return string
[ "Render", "the", "named", "tag", "given", "the", "specified", "modifier", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L599-L640
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._stringHasR
protected function _stringHasR($str) { foreach (func_get_args() as $arg) { if (strpos($arg, "\r") !== false) { return true; } } return false; }
php
protected function _stringHasR($str) { foreach (func_get_args() as $arg) { if (strpos($arg, "\r") !== false) { return true; } } return false; }
[ "protected", "function", "_stringHasR", "(", "$", "str", ")", "{", "foreach", "(", "func_get_args", "(", ")", "as", "$", "arg", ")", "{", "if", "(", "strpos", "(", "$", "arg", ",", "\"\\r\"", ")", "!==", "false", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if any of its args contains the "\r" character. @access protected @param string $str @return boolean
[ "Returns", "true", "if", "any", "of", "its", "args", "contains", "the", "\\", "r", "character", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L649-L656
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._renderEscaped
protected function _renderEscaped($tag_name, $leading, $trailing) { $value = $this->_renderUnescaped($tag_name, '', ''); if (isset($this->_escape)) { $rendered = call_user_func($this->_escape, $value); } else { $rendered = htmlentities($value, ENT_COMPAT, $this->_charset); } return $leading . $rendered . $trailing; }
php
protected function _renderEscaped($tag_name, $leading, $trailing) { $value = $this->_renderUnescaped($tag_name, '', ''); if (isset($this->_escape)) { $rendered = call_user_func($this->_escape, $value); } else { $rendered = htmlentities($value, ENT_COMPAT, $this->_charset); } return $leading . $rendered . $trailing; }
[ "protected", "function", "_renderEscaped", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", "{", "$", "value", "=", "$", "this", "->", "_renderUnescaped", "(", "$", "tag_name", ",", "''", ",", "''", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "_escape", ")", ")", "{", "$", "rendered", "=", "call_user_func", "(", "$", "this", "->", "_escape", ",", "$", "value", ")", ";", "}", "else", "{", "$", "rendered", "=", "htmlentities", "(", "$", "value", ",", "ENT_COMPAT", ",", "$", "this", "->", "_charset", ")", ";", "}", "return", "$", "leading", ".", "$", "rendered", ".", "$", "trailing", ";", "}" ]
Escape and return the requested tag. @access protected @param string $tag_name @param string $leading Whitespace @param string $trailing Whitespace @return string
[ "Escape", "and", "return", "the", "requested", "tag", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L667-L676
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._renderUnescaped
protected function _renderUnescaped($tag_name, $leading, $trailing) { $val = $this->_getVariable($tag_name); if ($this->_varIsCallable($val)) { $val = $this->_renderTemplate(call_user_func($val)); } return $leading . $val . $trailing; }
php
protected function _renderUnescaped($tag_name, $leading, $trailing) { $val = $this->_getVariable($tag_name); if ($this->_varIsCallable($val)) { $val = $this->_renderTemplate(call_user_func($val)); } return $leading . $val . $trailing; }
[ "protected", "function", "_renderUnescaped", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", "{", "$", "val", "=", "$", "this", "->", "_getVariable", "(", "$", "tag_name", ")", ";", "if", "(", "$", "this", "->", "_varIsCallable", "(", "$", "val", ")", ")", "{", "$", "val", "=", "$", "this", "->", "_renderTemplate", "(", "call_user_func", "(", "$", "val", ")", ")", ";", "}", "return", "$", "leading", ".", "$", "val", ".", "$", "trailing", ";", "}" ]
Return the requested tag unescaped. @access protected @param string $tag_name @param string $leading Whitespace @param string $trailing Whitespace @return string
[ "Return", "the", "requested", "tag", "unescaped", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L706-L714
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._renderPartial
protected function _renderPartial($tag_name, $leading, $trailing) { $partial = $this->_getPartial($tag_name); if ($leading !== null && $trailing !== null) { $whitespace = trim($leading, "\r\n"); $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial); } $view = clone($this); if ($leading !== null && $trailing !== null) { return $leading . $view->render($partial); } else { return $leading . $view->render($partial) . $trailing; } }
php
protected function _renderPartial($tag_name, $leading, $trailing) { $partial = $this->_getPartial($tag_name); if ($leading !== null && $trailing !== null) { $whitespace = trim($leading, "\r\n"); $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial); } $view = clone($this); if ($leading !== null && $trailing !== null) { return $leading . $view->render($partial); } else { return $leading . $view->render($partial) . $trailing; } }
[ "protected", "function", "_renderPartial", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", "{", "$", "partial", "=", "$", "this", "->", "_getPartial", "(", "$", "tag_name", ")", ";", "if", "(", "$", "leading", "!==", "null", "&&", "$", "trailing", "!==", "null", ")", "{", "$", "whitespace", "=", "trim", "(", "$", "leading", ",", "\"\\r\\n\"", ")", ";", "$", "partial", "=", "preg_replace", "(", "'/(\\\\r?\\\\n)(?!$)/s'", ",", "\"\\\\1\"", ".", "$", "whitespace", ",", "$", "partial", ")", ";", "}", "$", "view", "=", "clone", "(", "$", "this", ")", ";", "if", "(", "$", "leading", "!==", "null", "&&", "$", "trailing", "!==", "null", ")", "{", "return", "$", "leading", ".", "$", "view", "->", "render", "(", "$", "partial", ")", ";", "}", "else", "{", "return", "$", "leading", ".", "$", "view", "->", "render", "(", "$", "partial", ")", ".", "$", "trailing", ";", "}", "}" ]
Render the requested partial. @access protected @param string $tag_name @param string $leading Whitespace @param string $trailing Whitespace @return string
[ "Render", "the", "requested", "partial", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L725-L739
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._changeDelimiter
protected function _changeDelimiter($tag_name, $leading, $trailing) { list($otag, $ctag) = explode(' ', $tag_name); $this->_otag = $otag; $this->_ctag = $ctag; $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); if ($leading !== null && $trailing !== null) { if (strpos($leading, "\n") === false) { return ''; } return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n"; } return $leading . $trailing; }
php
protected function _changeDelimiter($tag_name, $leading, $trailing) { list($otag, $ctag) = explode(' ', $tag_name); $this->_otag = $otag; $this->_ctag = $ctag; $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); if ($leading !== null && $trailing !== null) { if (strpos($leading, "\n") === false) { return ''; } return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n"; } return $leading . $trailing; }
[ "protected", "function", "_changeDelimiter", "(", "$", "tag_name", ",", "$", "leading", ",", "$", "trailing", ")", "{", "list", "(", "$", "otag", ",", "$", "ctag", ")", "=", "explode", "(", "' '", ",", "$", "tag_name", ")", ";", "$", "this", "->", "_otag", "=", "$", "otag", ";", "$", "this", "->", "_ctag", "=", "$", "ctag", ";", "$", "this", "->", "_tagRegEx", "=", "$", "this", "->", "_prepareTagRegEx", "(", "$", "this", "->", "_otag", ",", "$", "this", "->", "_ctag", ")", ";", "if", "(", "$", "leading", "!==", "null", "&&", "$", "trailing", "!==", "null", ")", "{", "if", "(", "strpos", "(", "$", "leading", ",", "\"\\n\"", ")", "===", "false", ")", "{", "return", "''", ";", "}", "return", "$", "this", "->", "_stringHasR", "(", "$", "leading", ",", "$", "trailing", ")", "?", "\"\\r\\n\"", ":", "\"\\n\"", ";", "}", "return", "$", "leading", ".", "$", "trailing", ";", "}" ]
Change the Mustache tag delimiter. This method also replaces this object's current tag RegEx with one using the new delimiters. @access protected @param string $tag_name @param string $leading Whitespace @param string $trailing Whitespace @return string
[ "Change", "the", "Mustache", "tag", "delimiter", ".", "This", "method", "also", "replaces", "this", "object", "s", "current", "tag", "RegEx", "with", "one", "using", "the", "new", "delimiters", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L751-L765
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._pushContext
protected function _pushContext(&$local_context) { $new = array(); $new[] =& $local_context; foreach (array_keys($this->_context) as $key) { $new[] =& $this->_context[$key]; } $this->_context = $new; }
php
protected function _pushContext(&$local_context) { $new = array(); $new[] =& $local_context; foreach (array_keys($this->_context) as $key) { $new[] =& $this->_context[$key]; } $this->_context = $new; }
[ "protected", "function", "_pushContext", "(", "&", "$", "local_context", ")", "{", "$", "new", "=", "array", "(", ")", ";", "$", "new", "[", "]", "=", "&", "$", "local_context", ";", "foreach", "(", "array_keys", "(", "$", "this", "->", "_context", ")", "as", "$", "key", ")", "{", "$", "new", "[", "]", "=", "&", "$", "this", "->", "_context", "[", "$", "key", "]", ";", "}", "$", "this", "->", "_context", "=", "$", "new", ";", "}" ]
Push a local context onto the stack. @access protected @param array &$local_context @return void
[ "Push", "a", "local", "context", "onto", "the", "stack", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L774-L781
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._popContext
protected function _popContext() { $new = array(); $keys = array_keys($this->_context); array_shift($keys); foreach ($keys as $key) { $new[] =& $this->_context[$key]; } $this->_context = $new; }
php
protected function _popContext() { $new = array(); $keys = array_keys($this->_context); array_shift($keys); foreach ($keys as $key) { $new[] =& $this->_context[$key]; } $this->_context = $new; }
[ "protected", "function", "_popContext", "(", ")", "{", "$", "new", "=", "array", "(", ")", ";", "$", "keys", "=", "array_keys", "(", "$", "this", "->", "_context", ")", ";", "array_shift", "(", "$", "keys", ")", ";", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "$", "new", "[", "]", "=", "&", "$", "this", "->", "_context", "[", "$", "key", "]", ";", "}", "$", "this", "->", "_context", "=", "$", "new", ";", "}" ]
Remove the latest context from the stack. @access protected @return void
[ "Remove", "the", "latest", "context", "from", "the", "stack", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L789-L798
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._getVariable
protected function _getVariable($tag_name) { if ($tag_name === '.') { return $this->_context[0]; } else if (strpos($tag_name, '.') !== false) { $chunks = explode('.', $tag_name); $first = array_shift($chunks); $ret = $this->_findVariableInContext($first, $this->_context); foreach ($chunks as $next) { // Slice off a chunk of context for dot notation traversal. $c = array($ret); $ret = $this->_findVariableInContext($next, $c); } return $ret; } else { return $this->_findVariableInContext($tag_name, $this->_context); } }
php
protected function _getVariable($tag_name) { if ($tag_name === '.') { return $this->_context[0]; } else if (strpos($tag_name, '.') !== false) { $chunks = explode('.', $tag_name); $first = array_shift($chunks); $ret = $this->_findVariableInContext($first, $this->_context); foreach ($chunks as $next) { // Slice off a chunk of context for dot notation traversal. $c = array($ret); $ret = $this->_findVariableInContext($next, $c); } return $ret; } else { return $this->_findVariableInContext($tag_name, $this->_context); } }
[ "protected", "function", "_getVariable", "(", "$", "tag_name", ")", "{", "if", "(", "$", "tag_name", "===", "'.'", ")", "{", "return", "$", "this", "->", "_context", "[", "0", "]", ";", "}", "else", "if", "(", "strpos", "(", "$", "tag_name", ",", "'.'", ")", "!==", "false", ")", "{", "$", "chunks", "=", "explode", "(", "'.'", ",", "$", "tag_name", ")", ";", "$", "first", "=", "array_shift", "(", "$", "chunks", ")", ";", "$", "ret", "=", "$", "this", "->", "_findVariableInContext", "(", "$", "first", ",", "$", "this", "->", "_context", ")", ";", "foreach", "(", "$", "chunks", "as", "$", "next", ")", "{", "// Slice off a chunk of context for dot notation traversal.", "$", "c", "=", "array", "(", "$", "ret", ")", ";", "$", "ret", "=", "$", "this", "->", "_findVariableInContext", "(", "$", "next", ",", "$", "c", ")", ";", "}", "return", "$", "ret", ";", "}", "else", "{", "return", "$", "this", "->", "_findVariableInContext", "(", "$", "tag_name", ",", "$", "this", "->", "_context", ")", ";", "}", "}" ]
Get a variable from the context array. If the view is an array, returns the value with array key $tag_name. If the view is an object, this will check for a public member variable named $tag_name. If none is available, this method will execute and return any class method named $tag_name. Failing all of the above, this method will return an empty string. @access protected @param string $tag_name @throws MustacheException Unknown variable name. @return string
[ "Get", "a", "variable", "from", "the", "context", "array", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L814-L831
train
Etenil/assegai
src/assegai/modules/mustache/MustacheEngine.php
MustacheEngine._getPartial
protected function _getPartial($tag_name) { if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) { return $this->_partials[$tag_name]; } else { $partial_file = $this->server->getRelAppPath('views/' . $tag_name . '.tpl'); if(file_exists($partial_file)) { return file_get_contents($partial_file); } } if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) { throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL); } else { return ''; } }
php
protected function _getPartial($tag_name) { if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) { return $this->_partials[$tag_name]; } else { $partial_file = $this->server->getRelAppPath('views/' . $tag_name . '.tpl'); if(file_exists($partial_file)) { return file_get_contents($partial_file); } } if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) { throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL); } else { return ''; } }
[ "protected", "function", "_getPartial", "(", "$", "tag_name", ")", "{", "if", "(", "(", "is_array", "(", "$", "this", "->", "_partials", ")", "||", "$", "this", "->", "_partials", "instanceof", "ArrayAccess", ")", "&&", "isset", "(", "$", "this", "->", "_partials", "[", "$", "tag_name", "]", ")", ")", "{", "return", "$", "this", "->", "_partials", "[", "$", "tag_name", "]", ";", "}", "else", "{", "$", "partial_file", "=", "$", "this", "->", "server", "->", "getRelAppPath", "(", "'views/'", ".", "$", "tag_name", ".", "'.tpl'", ")", ";", "if", "(", "file_exists", "(", "$", "partial_file", ")", ")", "{", "return", "file_get_contents", "(", "$", "partial_file", ")", ";", "}", "}", "if", "(", "$", "this", "->", "_throwsException", "(", "MustacheException", "::", "UNKNOWN_PARTIAL", ")", ")", "{", "throw", "new", "MustacheException", "(", "'Unknown partial: '", ".", "$", "tag_name", ",", "MustacheException", "::", "UNKNOWN_PARTIAL", ")", ";", "}", "else", "{", "return", "''", ";", "}", "}" ]
Retrieve the partial corresponding to the requested tag name. Silently fails (i.e. returns '') when the requested partial is not found. @access protected @param string $tag_name @throws MustacheException Unknown partial name. @return string
[ "Retrieve", "the", "partial", "corresponding", "to", "the", "requested", "tag", "name", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/mustache/MustacheEngine.php#L873-L888
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.setName
public function setName($name) { $attrName = $this->isMultiple() ? "{$name}[]" : $name; $this->setAttribute('name', $attrName); $this->name = $name; if ($label = $this->getLabel()) { $this->getLabel()->setAttribute('for', $this->generateId()); } return $this; }
php
public function setName($name) { $attrName = $this->isMultiple() ? "{$name}[]" : $name; $this->setAttribute('name', $attrName); $this->name = $name; if ($label = $this->getLabel()) { $this->getLabel()->setAttribute('for', $this->generateId()); } return $this; }
[ "public", "function", "setName", "(", "$", "name", ")", "{", "$", "attrName", "=", "$", "this", "->", "isMultiple", "(", ")", "?", "\"{$name}[]\"", ":", "$", "name", ";", "$", "this", "->", "setAttribute", "(", "'name'", ",", "$", "attrName", ")", ";", "$", "this", "->", "name", "=", "$", "name", ";", "if", "(", "$", "label", "=", "$", "this", "->", "getLabel", "(", ")", ")", "{", "$", "this", "->", "getLabel", "(", ")", "->", "setAttribute", "(", "'for'", ",", "$", "this", "->", "generateId", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets input name @param string $name @return self|$this|InputInterface|AbstractInput
[ "Sets", "input", "name" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L86-L97
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.setLabel
public function setLabel($label) { $this->label = $this->checkLabel($label); $class = $this->label->getAttribute('class'); $this->label->setAttribute('for', $this->generateId()) ->setAttribute('class', trim("control-label {$class}")); return $this; }
php
public function setLabel($label) { $this->label = $this->checkLabel($label); $class = $this->label->getAttribute('class'); $this->label->setAttribute('for', $this->generateId()) ->setAttribute('class', trim("control-label {$class}")); return $this; }
[ "public", "function", "setLabel", "(", "$", "label", ")", "{", "$", "this", "->", "label", "=", "$", "this", "->", "checkLabel", "(", "$", "label", ")", ";", "$", "class", "=", "$", "this", "->", "label", "->", "getAttribute", "(", "'class'", ")", ";", "$", "this", "->", "label", "->", "setAttribute", "(", "'for'", ",", "$", "this", "->", "generateId", "(", ")", ")", "->", "setAttribute", "(", "'class'", ",", "trim", "(", "\"control-label {$class}\"", ")", ")", ";", "return", "$", "this", ";", "}" ]
Sets the input label Label parameter can be a string or a element interface. If a string is provided then an ElementInterface MUST be created. This element MUST result in a <label> HTML tag when rendering and as you may define your own implementation it is advisable that you use the Slick\Form\Element\Label object. @param string|ElementInterface $label @return self|$this|InputInterface @throws InvalidArgumentException If the provided label is not a string or is not an object of a class implementing the ElementInterface.
[ "Sets", "the", "input", "label" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L115-L122
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.generateId
protected function generateId() { $inputId = static::$idPrefix . $this->getName(); if ($this->isMultiple()) { $inputId = "{$inputId}-{$this->instances}"; } $this->setAttribute('id', $inputId); return $inputId; }
php
protected function generateId() { $inputId = static::$idPrefix . $this->getName(); if ($this->isMultiple()) { $inputId = "{$inputId}-{$this->instances}"; } $this->setAttribute('id', $inputId); return $inputId; }
[ "protected", "function", "generateId", "(", ")", "{", "$", "inputId", "=", "static", "::", "$", "idPrefix", ".", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "$", "this", "->", "isMultiple", "(", ")", ")", "{", "$", "inputId", "=", "\"{$inputId}-{$this->instances}\"", ";", "}", "$", "this", "->", "setAttribute", "(", "'id'", ",", "$", "inputId", ")", ";", "return", "$", "inputId", ";", "}" ]
Generate input id based on provided name @return string
[ "Generate", "input", "id", "based", "on", "provided", "name" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L161-L169
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.checkLabel
protected function checkLabel($label) { if ($label instanceof ElementInterface) { return $label; } return $this->createLabel($this->translate($label)); }
php
protected function checkLabel($label) { if ($label instanceof ElementInterface) { return $label; } return $this->createLabel($this->translate($label)); }
[ "protected", "function", "checkLabel", "(", "$", "label", ")", "{", "if", "(", "$", "label", "instanceof", "ElementInterface", ")", "{", "return", "$", "label", ";", "}", "return", "$", "this", "->", "createLabel", "(", "$", "this", "->", "translate", "(", "$", "label", ")", ")", ";", "}" ]
Check provided label @param string|ElementInterface $label @return ElementInterface|Label
[ "Check", "provided", "label" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L178-L185
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.createLabel
protected function createLabel($label) { if (!is_string($label)) { throw new InvalidArgumentException( "Provided label is not a string or an ElementInterface ". "interface object." ); } $element = class_exists($label) ? $this->createLabelFromClass($label) : new Label('', $label); return $element; }
php
protected function createLabel($label) { if (!is_string($label)) { throw new InvalidArgumentException( "Provided label is not a string or an ElementInterface ". "interface object." ); } $element = class_exists($label) ? $this->createLabelFromClass($label) : new Label('', $label); return $element; }
[ "protected", "function", "createLabel", "(", "$", "label", ")", "{", "if", "(", "!", "is_string", "(", "$", "label", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Provided label is not a string or an ElementInterface \"", ".", "\"interface object.\"", ")", ";", "}", "$", "element", "=", "class_exists", "(", "$", "label", ")", "?", "$", "this", "->", "createLabelFromClass", "(", "$", "label", ")", ":", "new", "Label", "(", "''", ",", "$", "label", ")", ";", "return", "$", "element", ";", "}" ]
Creates label from string @param string $label @return ElementInterface|Label
[ "Creates", "label", "from", "string" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L194-L208
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.setRequired
public function setRequired($required) { $this->required = (boolean) $required; if ($this->isRequired()) { $this->setAttribute('required'); return $this; } if ($this->getAttributes()->containsKey('required')) { $this->getAttributes()->remove('required'); } return $this; }
php
public function setRequired($required) { $this->required = (boolean) $required; if ($this->isRequired()) { $this->setAttribute('required'); return $this; } if ($this->getAttributes()->containsKey('required')) { $this->getAttributes()->remove('required'); } return $this; }
[ "public", "function", "setRequired", "(", "$", "required", ")", "{", "$", "this", "->", "required", "=", "(", "boolean", ")", "$", "required", ";", "if", "(", "$", "this", "->", "isRequired", "(", ")", ")", "{", "$", "this", "->", "setAttribute", "(", "'required'", ")", ";", "return", "$", "this", ";", "}", "if", "(", "$", "this", "->", "getAttributes", "(", ")", "->", "containsKey", "(", "'required'", ")", ")", "{", "$", "this", "->", "getAttributes", "(", ")", "->", "remove", "(", "'required'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Sets the required flag for this input @param boolean $required @return $this|self|InputInterface
[ "Sets", "the", "required", "flag", "for", "this", "input" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L247-L259
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.getInstanceValue
public function getInstanceValue() { $value = $this->getValue(); if ( is_array($value) && array_key_exists($this->instances, $this->value) ) { $value = $value[$this->instances]; } return $value; }
php
public function getInstanceValue() { $value = $this->getValue(); if ( is_array($value) && array_key_exists($this->instances, $this->value) ) { $value = $value[$this->instances]; } return $value; }
[ "public", "function", "getInstanceValue", "(", ")", "{", "$", "value", "=", "$", "this", "->", "getValue", "(", ")", ";", "if", "(", "is_array", "(", "$", "value", ")", "&&", "array_key_exists", "(", "$", "this", "->", "instances", ",", "$", "this", "->", "value", ")", ")", "{", "$", "value", "=", "$", "value", "[", "$", "this", "->", "instances", "]", ";", "}", "return", "$", "value", ";", "}" ]
If input is multiple get the instance value of it @return mixed
[ "If", "input", "is", "multiple", "get", "the", "instance", "value", "of", "it" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L286-L296
train
slickframework/form
src/Input/AbstractInput.php
AbstractInput.updateInstance
protected function updateInstance() { $this->instances++; $id = $this->generateId(); $this->setAttribute($id, $id); if ($label = $this->getLabel()) { $label->setAttribute('for', $id); } return $this; }
php
protected function updateInstance() { $this->instances++; $id = $this->generateId(); $this->setAttribute($id, $id); if ($label = $this->getLabel()) { $label->setAttribute('for', $id); } return $this; }
[ "protected", "function", "updateInstance", "(", ")", "{", "$", "this", "->", "instances", "++", ";", "$", "id", "=", "$", "this", "->", "generateId", "(", ")", ";", "$", "this", "->", "setAttribute", "(", "$", "id", ",", "$", "id", ")", ";", "if", "(", "$", "label", "=", "$", "this", "->", "getLabel", "(", ")", ")", "{", "$", "label", "->", "setAttribute", "(", "'for'", ",", "$", "id", ")", ";", "}", "return", "$", "this", ";", "}" ]
Updates input id and link it to its label @return self|AbstractInput
[ "Updates", "input", "id", "and", "link", "it", "to", "its", "label" ]
e7d536b3bad49194e246ff93587da2589e31a003
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Input/AbstractInput.php#L320-L330
train
romaricdrigon/OrchestraBundle
Core/Pool/RepositoryPool.php
RepositoryPool.addRepositoryDefinition
public function addRepositoryDefinition(RepositoryDefinitionInterface $repositoryDefinition) { $slug = $repositoryDefinition->getSlug(); if (isset($this->repositoriesBySlug[$slug])) { throw new DomainErrorException('Two repositories has the same "'.$slug.'" slug!'); } $this->repositoriesBySlug[$slug] = $repositoryDefinition; }
php
public function addRepositoryDefinition(RepositoryDefinitionInterface $repositoryDefinition) { $slug = $repositoryDefinition->getSlug(); if (isset($this->repositoriesBySlug[$slug])) { throw new DomainErrorException('Two repositories has the same "'.$slug.'" slug!'); } $this->repositoriesBySlug[$slug] = $repositoryDefinition; }
[ "public", "function", "addRepositoryDefinition", "(", "RepositoryDefinitionInterface", "$", "repositoryDefinition", ")", "{", "$", "slug", "=", "$", "repositoryDefinition", "->", "getSlug", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "repositoriesBySlug", "[", "$", "slug", "]", ")", ")", "{", "throw", "new", "DomainErrorException", "(", "'Two repositories has the same \"'", ".", "$", "slug", ".", "'\" slug!'", ")", ";", "}", "$", "this", "->", "repositoriesBySlug", "[", "$", "slug", "]", "=", "$", "repositoryDefinition", ";", "}" ]
Add a repository definition to the pool @param RepositoryDefinitionInterface $repositoryDefinition @throws DomainErrorException
[ "Add", "a", "repository", "definition", "to", "the", "pool" ]
4abb9736fcb6b23ed08ebd14ab169867339a4785
https://github.com/romaricdrigon/OrchestraBundle/blob/4abb9736fcb6b23ed08ebd14ab169867339a4785/Core/Pool/RepositoryPool.php#L34-L43
train
lrezek/Arachnid
src/LRezek/Arachnid/Proxy/Factory.php
Factory.fromRelation
function fromRelation($relationship, $repository, \Closure $loadCallback) { //Get the class name from the node, and the meta from that class name $class = $relationship->getType(); //Create the proxy factory return $this->fromEntity($relationship, $class, $repository, $loadCallback); }
php
function fromRelation($relationship, $repository, \Closure $loadCallback) { //Get the class name from the node, and the meta from that class name $class = $relationship->getType(); //Create the proxy factory return $this->fromEntity($relationship, $class, $repository, $loadCallback); }
[ "function", "fromRelation", "(", "$", "relationship", ",", "$", "repository", ",", "\\", "Closure", "$", "loadCallback", ")", "{", "//Get the class name from the node, and the meta from that class name", "$", "class", "=", "$", "relationship", "->", "getType", "(", ")", ";", "//Create the proxy factory", "return", "$", "this", "->", "fromEntity", "(", "$", "relationship", ",", "$", "class", ",", "$", "repository", ",", "$", "loadCallback", ")", ";", "}" ]
Creates a proxy object for an Everyman relationship. This creates a proxy object for a Everyman relationship, given the meta repository. @param \Everyman\Neo4j\Relationship $relationship The node to create a proxy of. @param \LRezek\Arachnid\Meta\Repository $repository The meta repository. @param callable $loadCallback Callback for start/end node lazy loading. @return mixed The proxy object.
[ "Creates", "a", "proxy", "object", "for", "an", "Everyman", "relationship", "." ]
fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a
https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L72-L79
train
lrezek/Arachnid
src/LRezek/Arachnid/Proxy/Factory.php
Factory.fromEntity
function fromEntity($entity, $class, $repository, $callback = null) { $meta = $repository->fromClass($class); //Create the proxy object and set the meta, node, and load callback $proxy = $this->createProxy($meta); $proxy->__setMeta($meta); $proxy->__setEntity($entity); $proxy->__setLoadCallback($callback); $proxy->__setEntity($entity); //Set the primary key property in the object to the node id. $pk = $meta->getPrimaryKey(); $pk->setValue($proxy, $entity->getId()); $proxy->__addHydrated($pk->getName()); //Set the properties foreach ($meta->getProperties() as $property) { $name = $property->getName(); //If the value isn't null in the DB, set the property to the correct value if($value = $entity->getProperty($name)) { $property->setValue($proxy, $value); $proxy->__addHydrated($name); } } return $proxy; }
php
function fromEntity($entity, $class, $repository, $callback = null) { $meta = $repository->fromClass($class); //Create the proxy object and set the meta, node, and load callback $proxy = $this->createProxy($meta); $proxy->__setMeta($meta); $proxy->__setEntity($entity); $proxy->__setLoadCallback($callback); $proxy->__setEntity($entity); //Set the primary key property in the object to the node id. $pk = $meta->getPrimaryKey(); $pk->setValue($proxy, $entity->getId()); $proxy->__addHydrated($pk->getName()); //Set the properties foreach ($meta->getProperties() as $property) { $name = $property->getName(); //If the value isn't null in the DB, set the property to the correct value if($value = $entity->getProperty($name)) { $property->setValue($proxy, $value); $proxy->__addHydrated($name); } } return $proxy; }
[ "function", "fromEntity", "(", "$", "entity", ",", "$", "class", ",", "$", "repository", ",", "$", "callback", "=", "null", ")", "{", "$", "meta", "=", "$", "repository", "->", "fromClass", "(", "$", "class", ")", ";", "//Create the proxy object and set the meta, node, and load callback", "$", "proxy", "=", "$", "this", "->", "createProxy", "(", "$", "meta", ")", ";", "$", "proxy", "->", "__setMeta", "(", "$", "meta", ")", ";", "$", "proxy", "->", "__setEntity", "(", "$", "entity", ")", ";", "$", "proxy", "->", "__setLoadCallback", "(", "$", "callback", ")", ";", "$", "proxy", "->", "__setEntity", "(", "$", "entity", ")", ";", "//Set the primary key property in the object to the node id.", "$", "pk", "=", "$", "meta", "->", "getPrimaryKey", "(", ")", ";", "$", "pk", "->", "setValue", "(", "$", "proxy", ",", "$", "entity", "->", "getId", "(", ")", ")", ";", "$", "proxy", "->", "__addHydrated", "(", "$", "pk", "->", "getName", "(", ")", ")", ";", "//Set the properties", "foreach", "(", "$", "meta", "->", "getProperties", "(", ")", "as", "$", "property", ")", "{", "$", "name", "=", "$", "property", "->", "getName", "(", ")", ";", "//If the value isn't null in the DB, set the property to the correct value", "if", "(", "$", "value", "=", "$", "entity", "->", "getProperty", "(", "$", "name", ")", ")", "{", "$", "property", "->", "setValue", "(", "$", "proxy", ",", "$", "value", ")", ";", "$", "proxy", "->", "__addHydrated", "(", "$", "name", ")", ";", "}", "}", "return", "$", "proxy", ";", "}" ]
Creates a proxy object for a Everyman node or relationship. This creates a proxy object for a Everyman relationship, given the meta repository and class name @param \Everyman\Neo4j\Node|\Everyman\Neo4j\Relationship $entity The entity to create a proxy of. @param string $class The class name. @param \LRezek\Arachnid\Meta\Repository $repository The meta repository. @param null $callback The load callback to use for start/end nodes. @return mixed The proxy object.
[ "Creates", "a", "proxy", "object", "for", "a", "Everyman", "node", "or", "relationship", "." ]
fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a
https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L92-L123
train
lrezek/Arachnid
src/LRezek/Arachnid/Proxy/Factory.php
Factory.createProxy
private function createProxy(GraphElement $meta) { //Get the proxy class name, as well as the regular class name $proxyClass = $meta->getProxyClass(); $className = $meta->getName(); //If the class already exists, just make an instance of it with the correct properties and return it. if(class_exists($proxyClass, false)) { return $this->newInstance($proxyClass); } //Create a target file for the class $targetFile = "{$this->proxyDir}/$proxyClass.php"; //If the file doesn't exist if($this->debug || !file_exists($targetFile)) { //Initialize functions $functions = ''; $reflectionClass = new \ReflectionClass($className); //Loop through entities public methods foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { //If the method isn't a constructor, destructor, or final, add it to the methods via method proxy. if(!$method->isConstructor() && !$method->isDestructor() && !$method->isFinal()) { $functions .= $this->methodProxy($method, $meta); } } //Get the properties and primary key. $properties = $meta->getProperties(); $properties[] = $meta->getPrimaryKey(); //Filter out private properties $properties = array_filter($properties, function ($property) { return !$property->isPrivate(); }); //Create an array map by property name $properties = array_map(function ($property) { return $property->getName(); }, $properties); //Create php code for properties. $properties = var_export($properties, true); //Create the actual class. $content = <<<CONTENT <?php class $proxyClass extends $className implements LRezek\\Arachnid\\Proxy\\Entity { private \$neo4j_hydrated = array(); private \$neo4j_meta; private \$neo4j_entity; private \$neo4j_loadCallback; function getEntity() { \$entity = new $className; foreach (\$this->neo4j_meta->getProperties() as \$prop) { \$prop->setValue(\$entity, \$prop->getValue(\$this)); } \$prop = \$this->neo4j_meta->getPrimaryKey(); \$prop->setValue(\$entity, \$prop->getValue(\$this)); return \$entity; } $functions function __addHydrated(\$name) { \$this->neo4j_hydrated[] = \$name; } function __setMeta(\$meta) { \$this->neo4j_meta = \$meta; } function __setEntity(\$entity) { \$this->neo4j_entity = \$entity; } function __getEntity() { return \$this->neo4j_entity; } function __setLoadCallback(\$loadCallback) { \$this->neo4j_loadCallback = \$loadCallback; } private function __load(\$name, \$propertyName) { //Already hydrated if(in_array(\$propertyName, \$this->neo4j_hydrated)) { return; } if(! \$this->neo4j_meta) { throw new \\LRezek\\Arachnid\\Exception('Proxy not fully initialized.'); } \$property = \$this->neo4j_meta->findProperty(\$name); if(strpos(\$name, 'set') === 0) { \$this->__addHydrated(\$propertyName); return; } //Make property node if(\$property->isStart() || \$property->isEnd()) { \$loader = \$this->neo4j_loadCallback; //Get the node if(\$property->isStart()) { \$node = \$this->neo4j_entity->getStartNode(); } else { \$node = \$this->neo4j_entity->getEndNode(); } \$node = \$loader(\$node); //Set the property \$property->setValue(\$this, \$node); } //Hydrate the property \$this->__addHydrated(\$propertyName); } function __sleep() { return $properties; } } CONTENT; //Make sure the proxy directory is an actual directory if(!is_dir($this->proxyDir)) { if(false === @mkdir($this->proxyDir, 0775, true)) { throw new Exception('Proxy Dir is not writable.'); } } //Make sure the directory is writable else if(!is_writable($this->proxyDir)) { throw new Exception('Proxy Dir is not writable.'); } //Write the file file_put_contents($targetFile, $content); } //Add file to class loader require $targetFile; //Return an instance of the proxy class return $this->newInstance($proxyClass); }
php
private function createProxy(GraphElement $meta) { //Get the proxy class name, as well as the regular class name $proxyClass = $meta->getProxyClass(); $className = $meta->getName(); //If the class already exists, just make an instance of it with the correct properties and return it. if(class_exists($proxyClass, false)) { return $this->newInstance($proxyClass); } //Create a target file for the class $targetFile = "{$this->proxyDir}/$proxyClass.php"; //If the file doesn't exist if($this->debug || !file_exists($targetFile)) { //Initialize functions $functions = ''; $reflectionClass = new \ReflectionClass($className); //Loop through entities public methods foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { //If the method isn't a constructor, destructor, or final, add it to the methods via method proxy. if(!$method->isConstructor() && !$method->isDestructor() && !$method->isFinal()) { $functions .= $this->methodProxy($method, $meta); } } //Get the properties and primary key. $properties = $meta->getProperties(); $properties[] = $meta->getPrimaryKey(); //Filter out private properties $properties = array_filter($properties, function ($property) { return !$property->isPrivate(); }); //Create an array map by property name $properties = array_map(function ($property) { return $property->getName(); }, $properties); //Create php code for properties. $properties = var_export($properties, true); //Create the actual class. $content = <<<CONTENT <?php class $proxyClass extends $className implements LRezek\\Arachnid\\Proxy\\Entity { private \$neo4j_hydrated = array(); private \$neo4j_meta; private \$neo4j_entity; private \$neo4j_loadCallback; function getEntity() { \$entity = new $className; foreach (\$this->neo4j_meta->getProperties() as \$prop) { \$prop->setValue(\$entity, \$prop->getValue(\$this)); } \$prop = \$this->neo4j_meta->getPrimaryKey(); \$prop->setValue(\$entity, \$prop->getValue(\$this)); return \$entity; } $functions function __addHydrated(\$name) { \$this->neo4j_hydrated[] = \$name; } function __setMeta(\$meta) { \$this->neo4j_meta = \$meta; } function __setEntity(\$entity) { \$this->neo4j_entity = \$entity; } function __getEntity() { return \$this->neo4j_entity; } function __setLoadCallback(\$loadCallback) { \$this->neo4j_loadCallback = \$loadCallback; } private function __load(\$name, \$propertyName) { //Already hydrated if(in_array(\$propertyName, \$this->neo4j_hydrated)) { return; } if(! \$this->neo4j_meta) { throw new \\LRezek\\Arachnid\\Exception('Proxy not fully initialized.'); } \$property = \$this->neo4j_meta->findProperty(\$name); if(strpos(\$name, 'set') === 0) { \$this->__addHydrated(\$propertyName); return; } //Make property node if(\$property->isStart() || \$property->isEnd()) { \$loader = \$this->neo4j_loadCallback; //Get the node if(\$property->isStart()) { \$node = \$this->neo4j_entity->getStartNode(); } else { \$node = \$this->neo4j_entity->getEndNode(); } \$node = \$loader(\$node); //Set the property \$property->setValue(\$this, \$node); } //Hydrate the property \$this->__addHydrated(\$propertyName); } function __sleep() { return $properties; } } CONTENT; //Make sure the proxy directory is an actual directory if(!is_dir($this->proxyDir)) { if(false === @mkdir($this->proxyDir, 0775, true)) { throw new Exception('Proxy Dir is not writable.'); } } //Make sure the directory is writable else if(!is_writable($this->proxyDir)) { throw new Exception('Proxy Dir is not writable.'); } //Write the file file_put_contents($targetFile, $content); } //Add file to class loader require $targetFile; //Return an instance of the proxy class return $this->newInstance($proxyClass); }
[ "private", "function", "createProxy", "(", "GraphElement", "$", "meta", ")", "{", "//Get the proxy class name, as well as the regular class name", "$", "proxyClass", "=", "$", "meta", "->", "getProxyClass", "(", ")", ";", "$", "className", "=", "$", "meta", "->", "getName", "(", ")", ";", "//If the class already exists, just make an instance of it with the correct properties and return it.", "if", "(", "class_exists", "(", "$", "proxyClass", ",", "false", ")", ")", "{", "return", "$", "this", "->", "newInstance", "(", "$", "proxyClass", ")", ";", "}", "//Create a target file for the class", "$", "targetFile", "=", "\"{$this->proxyDir}/$proxyClass.php\"", ";", "//If the file doesn't exist", "if", "(", "$", "this", "->", "debug", "||", "!", "file_exists", "(", "$", "targetFile", ")", ")", "{", "//Initialize functions", "$", "functions", "=", "''", ";", "$", "reflectionClass", "=", "new", "\\", "ReflectionClass", "(", "$", "className", ")", ";", "//Loop through entities public methods", "foreach", "(", "$", "reflectionClass", "->", "getMethods", "(", "\\", "ReflectionMethod", "::", "IS_PUBLIC", ")", "as", "$", "method", ")", "{", "//If the method isn't a constructor, destructor, or final, add it to the methods via method proxy.", "if", "(", "!", "$", "method", "->", "isConstructor", "(", ")", "&&", "!", "$", "method", "->", "isDestructor", "(", ")", "&&", "!", "$", "method", "->", "isFinal", "(", ")", ")", "{", "$", "functions", ".=", "$", "this", "->", "methodProxy", "(", "$", "method", ",", "$", "meta", ")", ";", "}", "}", "//Get the properties and primary key.", "$", "properties", "=", "$", "meta", "->", "getProperties", "(", ")", ";", "$", "properties", "[", "]", "=", "$", "meta", "->", "getPrimaryKey", "(", ")", ";", "//Filter out private properties", "$", "properties", "=", "array_filter", "(", "$", "properties", ",", "function", "(", "$", "property", ")", "{", "return", "!", "$", "property", "->", "isPrivate", "(", ")", ";", "}", ")", ";", "//Create an array map by property name", "$", "properties", "=", "array_map", "(", "function", "(", "$", "property", ")", "{", "return", "$", "property", "->", "getName", "(", ")", ";", "}", ",", "$", "properties", ")", ";", "//Create php code for properties.", "$", "properties", "=", "var_export", "(", "$", "properties", ",", "true", ")", ";", "//Create the actual class.", "$", "content", "=", " <<<CONTENT\n<?php\n\nclass $proxyClass extends $className implements LRezek\\\\Arachnid\\\\Proxy\\\\Entity\n{\n private \\$neo4j_hydrated = array();\n private \\$neo4j_meta;\n private \\$neo4j_entity;\n private \\$neo4j_loadCallback;\n\n function getEntity()\n {\n \\$entity = new $className;\n\n foreach (\\$this->neo4j_meta->getProperties() as \\$prop)\n {\n \\$prop->setValue(\\$entity, \\$prop->getValue(\\$this));\n }\n\n \\$prop = \\$this->neo4j_meta->getPrimaryKey();\n \\$prop->setValue(\\$entity, \\$prop->getValue(\\$this));\n\n return \\$entity;\n }\n\n $functions\n\n function __addHydrated(\\$name)\n {\n \\$this->neo4j_hydrated[] = \\$name;\n }\n\n function __setMeta(\\$meta)\n {\n \\$this->neo4j_meta = \\$meta;\n }\n\n function __setEntity(\\$entity)\n {\n \\$this->neo4j_entity = \\$entity;\n }\n\n function __getEntity()\n {\n return \\$this->neo4j_entity;\n }\n\n function __setLoadCallback(\\$loadCallback)\n {\n \\$this->neo4j_loadCallback = \\$loadCallback;\n }\n\n private function __load(\\$name, \\$propertyName)\n {\n //Already hydrated\n if(in_array(\\$propertyName, \\$this->neo4j_hydrated))\n {\n return;\n }\n\n if(! \\$this->neo4j_meta)\n {\n throw new \\\\LRezek\\\\Arachnid\\\\Exception('Proxy not fully initialized.');\n }\n\n \\$property = \\$this->neo4j_meta->findProperty(\\$name);\n\n if(strpos(\\$name, 'set') === 0)\n {\n \\$this->__addHydrated(\\$propertyName);\n return;\n }\n\n //Make property node\n if(\\$property->isStart() || \\$property->isEnd())\n {\n \\$loader = \\$this->neo4j_loadCallback;\n\n //Get the node\n if(\\$property->isStart())\n {\n \\$node = \\$this->neo4j_entity->getStartNode();\n }\n else\n {\n \\$node = \\$this->neo4j_entity->getEndNode();\n }\n\n \\$node = \\$loader(\\$node);\n\n //Set the property\n \\$property->setValue(\\$this, \\$node);\n }\n\n //Hydrate the property\n \\$this->__addHydrated(\\$propertyName);\n\n }\n\n function __sleep()\n {\n return $properties;\n }\n}\n\n\nCONTENT", ";", "//Make sure the proxy directory is an actual directory", "if", "(", "!", "is_dir", "(", "$", "this", "->", "proxyDir", ")", ")", "{", "if", "(", "false", "===", "@", "mkdir", "(", "$", "this", "->", "proxyDir", ",", "0775", ",", "true", ")", ")", "{", "throw", "new", "Exception", "(", "'Proxy Dir is not writable.'", ")", ";", "}", "}", "//Make sure the directory is writable", "else", "if", "(", "!", "is_writable", "(", "$", "this", "->", "proxyDir", ")", ")", "{", "throw", "new", "Exception", "(", "'Proxy Dir is not writable.'", ")", ";", "}", "//Write the file", "file_put_contents", "(", "$", "targetFile", ",", "$", "content", ")", ";", "}", "//Add file to class loader", "require", "$", "targetFile", ";", "//Return an instance of the proxy class", "return", "$", "this", "->", "newInstance", "(", "$", "proxyClass", ")", ";", "}" ]
Creates a proxy class for a graph element. This method will create a proxy class for an entity that extends the required class and implements LRezek\Arachnid\Proxy\Entity. This class will be generated and stored in the directory specified by the $proxyDir property of this class. This is done so that the object returned by a query seemingly matches the object type being queried for, while retaining its ID and other required information. @param GraphElement $meta The meta for the entity object being proxied. @return mixed An instance of the proxy class. @throws \LRezek\Arachnid\Exception If something goes wrong in file writing.
[ "Creates", "a", "proxy", "class", "for", "a", "graph", "element", "." ]
fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a
https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L137-L320
train
lrezek/Arachnid
src/LRezek/Arachnid/Proxy/Factory.php
Factory.newInstance
private function newInstance($proxyClass) { static $prototypes = array(); if(!array_key_exists($proxyClass, $prototypes)) { $prototypes[$proxyClass] = unserialize(sprintf('O:%d:"%s":0:{}', strlen($proxyClass), $proxyClass)); } return clone $prototypes[$proxyClass]; }
php
private function newInstance($proxyClass) { static $prototypes = array(); if(!array_key_exists($proxyClass, $prototypes)) { $prototypes[$proxyClass] = unserialize(sprintf('O:%d:"%s":0:{}', strlen($proxyClass), $proxyClass)); } return clone $prototypes[$proxyClass]; }
[ "private", "function", "newInstance", "(", "$", "proxyClass", ")", "{", "static", "$", "prototypes", "=", "array", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "proxyClass", ",", "$", "prototypes", ")", ")", "{", "$", "prototypes", "[", "$", "proxyClass", "]", "=", "unserialize", "(", "sprintf", "(", "'O:%d:\"%s\":0:{}'", ",", "strlen", "(", "$", "proxyClass", ")", ",", "$", "proxyClass", ")", ")", ";", "}", "return", "clone", "$", "prototypes", "[", "$", "proxyClass", "]", ";", "}" ]
Create a new instance of a proxy class object. This creates an instance of a proxy class. If the class has already been created, it is retrieved from a static prototypes array. @param mixed $proxyClass The class to create an instance of. @return mixed The new instance of <code>$proxyclass</code>.
[ "Create", "a", "new", "instance", "of", "a", "proxy", "class", "object", "." ]
fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a
https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L331-L341
train
lrezek/Arachnid
src/LRezek/Arachnid/Proxy/Factory.php
Factory.methodProxy
private function methodProxy($method, $meta) { //Find out if the method is a property getter or setter $property = $meta->findProperty($method->getName()); //If it is not, don't need the proxy if(!$property) { return; } //If the method is a straight up property setter/getter and not for a start/end node, you don't need a method proxy either. if($property->isProperty() && !$property->isStart() && !$property->isEnd()) { return; } $parts = array(); $arguments = array(); //Loop through the methods parameters foreach ($method->getParameters() as $parameter) { //Convert to a variable name, and add it to parts array $variable = '$' . $parameter->getName(); $parts[] = $variable; $arg = $variable; //If the parameter is optional, set it to its default value in the arguments list. if($parameter->isOptional()) { $arg .= ' = ' . var_export($parameter->getDefaultValue(), true); } //If the variable is passed by reference, put in an ampersand if($parameter->isPassedByReference()) { $arg = "& $arg"; } //If the variable is a set class, add the class name as the type elseif($c = $parameter->getClass()) { $arg = $c->getName() . ' ' . $arg; } //If the argument is a array, add array identifier if($parameter->isArray()) { $arg = "array $arg"; } //Add the argument to argument array $arguments[] = $arg; } //Join the argument variable names together with commas $parts = implode(', ', $parts); //Join the arguments with commas $arguments = implode(', ', $arguments); //Get the method name as a string $name = var_export($method->getName(), true); //Get the property name as a string $propertyName = var_export($property->getName(), true); return <<<FUNC function {$method->getName()}($arguments) { self::__load($name, $propertyName); return parent::{$method->getName()}($parts); } FUNC; }
php
private function methodProxy($method, $meta) { //Find out if the method is a property getter or setter $property = $meta->findProperty($method->getName()); //If it is not, don't need the proxy if(!$property) { return; } //If the method is a straight up property setter/getter and not for a start/end node, you don't need a method proxy either. if($property->isProperty() && !$property->isStart() && !$property->isEnd()) { return; } $parts = array(); $arguments = array(); //Loop through the methods parameters foreach ($method->getParameters() as $parameter) { //Convert to a variable name, and add it to parts array $variable = '$' . $parameter->getName(); $parts[] = $variable; $arg = $variable; //If the parameter is optional, set it to its default value in the arguments list. if($parameter->isOptional()) { $arg .= ' = ' . var_export($parameter->getDefaultValue(), true); } //If the variable is passed by reference, put in an ampersand if($parameter->isPassedByReference()) { $arg = "& $arg"; } //If the variable is a set class, add the class name as the type elseif($c = $parameter->getClass()) { $arg = $c->getName() . ' ' . $arg; } //If the argument is a array, add array identifier if($parameter->isArray()) { $arg = "array $arg"; } //Add the argument to argument array $arguments[] = $arg; } //Join the argument variable names together with commas $parts = implode(', ', $parts); //Join the arguments with commas $arguments = implode(', ', $arguments); //Get the method name as a string $name = var_export($method->getName(), true); //Get the property name as a string $propertyName = var_export($property->getName(), true); return <<<FUNC function {$method->getName()}($arguments) { self::__load($name, $propertyName); return parent::{$method->getName()}($parts); } FUNC; }
[ "private", "function", "methodProxy", "(", "$", "method", ",", "$", "meta", ")", "{", "//Find out if the method is a property getter or setter", "$", "property", "=", "$", "meta", "->", "findProperty", "(", "$", "method", "->", "getName", "(", ")", ")", ";", "//If it is not, don't need the proxy", "if", "(", "!", "$", "property", ")", "{", "return", ";", "}", "//If the method is a straight up property setter/getter and not for a start/end node, you don't need a method proxy either.", "if", "(", "$", "property", "->", "isProperty", "(", ")", "&&", "!", "$", "property", "->", "isStart", "(", ")", "&&", "!", "$", "property", "->", "isEnd", "(", ")", ")", "{", "return", ";", "}", "$", "parts", "=", "array", "(", ")", ";", "$", "arguments", "=", "array", "(", ")", ";", "//Loop through the methods parameters", "foreach", "(", "$", "method", "->", "getParameters", "(", ")", "as", "$", "parameter", ")", "{", "//Convert to a variable name, and add it to parts array", "$", "variable", "=", "'$'", ".", "$", "parameter", "->", "getName", "(", ")", ";", "$", "parts", "[", "]", "=", "$", "variable", ";", "$", "arg", "=", "$", "variable", ";", "//If the parameter is optional, set it to its default value in the arguments list.", "if", "(", "$", "parameter", "->", "isOptional", "(", ")", ")", "{", "$", "arg", ".=", "' = '", ".", "var_export", "(", "$", "parameter", "->", "getDefaultValue", "(", ")", ",", "true", ")", ";", "}", "//If the variable is passed by reference, put in an ampersand", "if", "(", "$", "parameter", "->", "isPassedByReference", "(", ")", ")", "{", "$", "arg", "=", "\"& $arg\"", ";", "}", "//If the variable is a set class, add the class name as the type", "elseif", "(", "$", "c", "=", "$", "parameter", "->", "getClass", "(", ")", ")", "{", "$", "arg", "=", "$", "c", "->", "getName", "(", ")", ".", "' '", ".", "$", "arg", ";", "}", "//If the argument is a array, add array identifier", "if", "(", "$", "parameter", "->", "isArray", "(", ")", ")", "{", "$", "arg", "=", "\"array $arg\"", ";", "}", "//Add the argument to argument array", "$", "arguments", "[", "]", "=", "$", "arg", ";", "}", "//Join the argument variable names together with commas", "$", "parts", "=", "implode", "(", "', '", ",", "$", "parts", ")", ";", "//Join the arguments with commas", "$", "arguments", "=", "implode", "(", "', '", ",", "$", "arguments", ")", ";", "//Get the method name as a string", "$", "name", "=", "var_export", "(", "$", "method", "->", "getName", "(", ")", ",", "true", ")", ";", "//Get the property name as a string", "$", "propertyName", "=", "var_export", "(", "$", "property", "->", "getName", "(", ")", ",", "true", ")", ";", "return", " <<<FUNC\n\n function {$method->getName()}($arguments)\n {\n self::__load($name, $propertyName);\n return parent::{$method->getName()}($parts);\n }\n\nFUNC", ";", "}" ]
Creates proxy methods from the reflection method handle and meta information. @param $method @param $meta @return string The method code.
[ "Creates", "proxy", "methods", "from", "the", "reflection", "method", "handle", "and", "meta", "information", "." ]
fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a
https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Proxy/Factory.php#L351-L429
train
kherge-abandoned/php-file
src/lib/KHerGe/File/Utility.php
Utility.remove
public static function remove($path) { if (is_dir($path)) { if (false === ($dir = opendir($path))) { throw FileException::removeFailed($path); } while (false !== ($item = readdir($dir))) { if (('.' === $item) || ('..' === $item)) { continue; } self::remove($path . DIRECTORY_SEPARATOR . $item); } closedir($dir); if (!rmdir($path)) { throw FileException::removeFailed($path); } } elseif (!unlink($path)) { throw FileException::removeFailed($path); } }
php
public static function remove($path) { if (is_dir($path)) { if (false === ($dir = opendir($path))) { throw FileException::removeFailed($path); } while (false !== ($item = readdir($dir))) { if (('.' === $item) || ('..' === $item)) { continue; } self::remove($path . DIRECTORY_SEPARATOR . $item); } closedir($dir); if (!rmdir($path)) { throw FileException::removeFailed($path); } } elseif (!unlink($path)) { throw FileException::removeFailed($path); } }
[ "public", "static", "function", "remove", "(", "$", "path", ")", "{", "if", "(", "is_dir", "(", "$", "path", ")", ")", "{", "if", "(", "false", "===", "(", "$", "dir", "=", "opendir", "(", "$", "path", ")", ")", ")", "{", "throw", "FileException", "::", "removeFailed", "(", "$", "path", ")", ";", "}", "while", "(", "false", "!==", "(", "$", "item", "=", "readdir", "(", "$", "dir", ")", ")", ")", "{", "if", "(", "(", "'.'", "===", "$", "item", ")", "||", "(", "'..'", "===", "$", "item", ")", ")", "{", "continue", ";", "}", "self", "::", "remove", "(", "$", "path", ".", "DIRECTORY_SEPARATOR", ".", "$", "item", ")", ";", "}", "closedir", "(", "$", "dir", ")", ";", "if", "(", "!", "rmdir", "(", "$", "path", ")", ")", "{", "throw", "FileException", "::", "removeFailed", "(", "$", "path", ")", ";", "}", "}", "elseif", "(", "!", "unlink", "(", "$", "path", ")", ")", "{", "throw", "FileException", "::", "removeFailed", "(", "$", "path", ")", ";", "}", "}" ]
Recursively removes a path from the file system. @param string $path The path to remove. @throws FileException If the path could not be removed.
[ "Recursively", "removes", "a", "path", "from", "the", "file", "system", "." ]
d2f0f52b2da471c36cb567840852c5041bc4c196
https://github.com/kherge-abandoned/php-file/blob/d2f0f52b2da471c36cb567840852c5041bc4c196/src/lib/KHerGe/File/Utility.php#L21-L44
train
romeOz/rock-cache
src/Cache.php
Cache.serialize
protected function serialize($value) { if (!is_array($value)) { return $value; } return Serialize::serialize($value, $this->serializer); }
php
protected function serialize($value) { if (!is_array($value)) { return $value; } return Serialize::serialize($value, $this->serializer); }
[ "protected", "function", "serialize", "(", "$", "value", ")", "{", "if", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "return", "Serialize", "::", "serialize", "(", "$", "value", ",", "$", "this", "->", "serializer", ")", ";", "}" ]
Serialize value. @param array $value @return array|string
[ "Serialize", "value", "." ]
bbd146ee323e8cc1fb11dc1803215c3656e02c57
https://github.com/romeOz/rock-cache/blob/bbd146ee323e8cc1fb11dc1803215c3656e02c57/src/Cache.php#L239-L245
train
romeOz/rock-cache
src/Cache.php
Cache.microtime
protected function microtime($microtime = null) { list($usec, $sec) = explode(" ", $microtime ?: microtime()); return (float)$usec + (float)$sec; }
php
protected function microtime($microtime = null) { list($usec, $sec) = explode(" ", $microtime ?: microtime()); return (float)$usec + (float)$sec; }
[ "protected", "function", "microtime", "(", "$", "microtime", "=", "null", ")", "{", "list", "(", "$", "usec", ",", "$", "sec", ")", "=", "explode", "(", "\" \"", ",", "$", "microtime", "?", ":", "microtime", "(", ")", ")", ";", "return", "(", "float", ")", "$", "usec", "+", "(", "float", ")", "$", "sec", ";", "}" ]
Returns a microtime. @param int|null $microtime @return float
[ "Returns", "a", "microtime", "." ]
bbd146ee323e8cc1fb11dc1803215c3656e02c57
https://github.com/romeOz/rock-cache/blob/bbd146ee323e8cc1fb11dc1803215c3656e02c57/src/Cache.php#L273-L277
train
gluephp/glue
src/Http/Response.php
Response.binaryFile
public function binaryFile($file, $status = 200, array $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) { return new BinaryFileResponse($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified); }
php
public function binaryFile($file, $status = 200, array $headers = [], $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true) { return new BinaryFileResponse($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified); }
[ "public", "function", "binaryFile", "(", "$", "file", ",", "$", "status", "=", "200", ",", "array", "$", "headers", "=", "[", "]", ",", "$", "public", "=", "true", ",", "$", "contentDisposition", "=", "null", ",", "$", "autoEtag", "=", "false", ",", "$", "autoLastModified", "=", "true", ")", "{", "return", "new", "BinaryFileResponse", "(", "$", "file", ",", "$", "status", ",", "$", "headers", ",", "$", "public", ",", "$", "contentDisposition", ",", "$", "autoEtag", ",", "$", "autoLastModified", ")", ";", "}" ]
Create a new BinaryFileResponse @param \SplFileInfo|string $file The file to stream @param int $status The response status code @param array $headers An array of response headers @param bool $public Files are public by default @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename @param bool $autoEtag Whether the ETag header should be automatically set @param bool $autoLastModified Whether the Last-Modified header should be automatically set
[ "Create", "a", "new", "BinaryFileResponse" ]
d54e0905dfe74d1c114c04f33fa89a60e2651562
https://github.com/gluephp/glue/blob/d54e0905dfe74d1c114c04f33fa89a60e2651562/src/Http/Response.php#L52-L55
train
gluephp/glue
src/Http/Response.php
Response.fileDownload
public function fileDownload($file) { $response = new SymfonyResponse(); $response->headers->set('Content-Disposition', $response->headers->makeDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file ) ); return $response; }
php
public function fileDownload($file) { $response = new SymfonyResponse(); $response->headers->set('Content-Disposition', $response->headers->makeDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file ) ); return $response; }
[ "public", "function", "fileDownload", "(", "$", "file", ")", "{", "$", "response", "=", "new", "SymfonyResponse", "(", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Disposition'", ",", "$", "response", "->", "headers", "->", "makeDisposition", "(", "ResponseHeaderBag", "::", "DISPOSITION_ATTACHMENT", ",", "$", "file", ")", ")", ";", "return", "$", "response", ";", "}" ]
Create a new file download response @param string $file The file
[ "Create", "a", "new", "file", "download", "response" ]
d54e0905dfe74d1c114c04f33fa89a60e2651562
https://github.com/gluephp/glue/blob/d54e0905dfe74d1c114c04f33fa89a60e2651562/src/Http/Response.php#L63-L75
train
apishka/easy-extend
source/Command/GenerateMeta.php
GenerateMeta.generateMeta
private function generateMeta(): void { $generator = new Meta\Generator(); $generator->register( $this->generateMetaDataForRouter(Broker::getInstance(), 'getRouter') ); $generator->register( $this->generateMetaDataForRouter(Broker::getInstance()->getRouter(Locator\ByClassName::class), 'make') ); $generator->generate('easy-extend.meta.php'); }
php
private function generateMeta(): void { $generator = new Meta\Generator(); $generator->register( $this->generateMetaDataForRouter(Broker::getInstance(), 'getRouter') ); $generator->register( $this->generateMetaDataForRouter(Broker::getInstance()->getRouter(Locator\ByClassName::class), 'make') ); $generator->generate('easy-extend.meta.php'); }
[ "private", "function", "generateMeta", "(", ")", ":", "void", "{", "$", "generator", "=", "new", "Meta", "\\", "Generator", "(", ")", ";", "$", "generator", "->", "register", "(", "$", "this", "->", "generateMetaDataForRouter", "(", "Broker", "::", "getInstance", "(", ")", ",", "'getRouter'", ")", ")", ";", "$", "generator", "->", "register", "(", "$", "this", "->", "generateMetaDataForRouter", "(", "Broker", "::", "getInstance", "(", ")", "->", "getRouter", "(", "Locator", "\\", "ByClassName", "::", "class", ")", ",", "'make'", ")", ")", ";", "$", "generator", "->", "generate", "(", "'easy-extend.meta.php'", ")", ";", "}" ]
Generates file with meta
[ "Generates", "file", "with", "meta" ]
5e5c63c2509377abc3db6956e353623683703e09
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/Command/GenerateMeta.php#L44-L57
train
alphacomm/alpharpc
src/AlphaRPC/Manager/ClientHandler/Client.php
Client.setRequest
public function setRequest($request, $waitForResult = true) { $this->previousRequest = $this->request; $this->request = $request; $this->waitForResult = $waitForResult; $this->bucket->refresh($this); return $this; }
php
public function setRequest($request, $waitForResult = true) { $this->previousRequest = $this->request; $this->request = $request; $this->waitForResult = $waitForResult; $this->bucket->refresh($this); return $this; }
[ "public", "function", "setRequest", "(", "$", "request", ",", "$", "waitForResult", "=", "true", ")", "{", "$", "this", "->", "previousRequest", "=", "$", "this", "->", "request", ";", "$", "this", "->", "request", "=", "$", "request", ";", "$", "this", "->", "waitForResult", "=", "$", "waitForResult", ";", "$", "this", "->", "bucket", "->", "refresh", "(", "$", "this", ")", ";", "return", "$", "this", ";", "}" ]
Sets the request the client is interested in. @param string $request @param boolean $waitForResult @return \AlphaRPC\Manager\ClientHandler\Client
[ "Sets", "the", "request", "the", "client", "is", "interested", "in", "." ]
cf162854500554c4ba8d39f2675de35a49c30ed0
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/ClientHandler/Client.php#L143-L151
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.seleccionarBd
public function seleccionarBd($basedatos) { if ($this->pdo->exec('USE ' . $basedatos) === false) { if ($this->arrojarExcepciones) { throw new \RuntimeException('No se pudo seleccionar base de datos.'); } return false; } return true; }
php
public function seleccionarBd($basedatos) { if ($this->pdo->exec('USE ' . $basedatos) === false) { if ($this->arrojarExcepciones) { throw new \RuntimeException('No se pudo seleccionar base de datos.'); } return false; } return true; }
[ "public", "function", "seleccionarBd", "(", "$", "basedatos", ")", "{", "if", "(", "$", "this", "->", "pdo", "->", "exec", "(", "'USE '", ".", "$", "basedatos", ")", "===", "false", ")", "{", "if", "(", "$", "this", "->", "arrojarExcepciones", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'No se pudo seleccionar base de datos.'", ")", ";", "}", "return", "false", ";", "}", "return", "true", ";", "}" ]
Selecciona la base de datos interna. @param string $basedatos @return bool @throws \RuntimeException
[ "Selecciona", "la", "base", "de", "datos", "interna", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L90-L101
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.prepararValor
public function prepararValor($valor, $tipo = 'txt', $permiteVacio = false) { if (is_array($valor)) { if (empty($valor)) { return 'NULL'; } foreach ($valor as $llave => $v) { $valor[$llave] = $this->prepararValor($v, $tipo); } return $valor; } // Retornamos valor boleano según el tipo if ($tipo == 'bol' || $tipo == 'bool') { return ($valor) ? '1' : '0'; } // Detectamos y retornamos valor nulo if ($valor === null || $valor === false) { return 'NULL'; } if (!$permiteVacio && $valor === '') { return 'NULL'; } // Retornamos valor numerico según el tipo if ($tipo == 'num' || $tipo == 'int') { if ($valor === '') return 'NULL'; return strval(floatval($valor)); } // Retornamos valor textual como valor predeterminado return $this->pdo->quote($valor); }
php
public function prepararValor($valor, $tipo = 'txt', $permiteVacio = false) { if (is_array($valor)) { if (empty($valor)) { return 'NULL'; } foreach ($valor as $llave => $v) { $valor[$llave] = $this->prepararValor($v, $tipo); } return $valor; } // Retornamos valor boleano según el tipo if ($tipo == 'bol' || $tipo == 'bool') { return ($valor) ? '1' : '0'; } // Detectamos y retornamos valor nulo if ($valor === null || $valor === false) { return 'NULL'; } if (!$permiteVacio && $valor === '') { return 'NULL'; } // Retornamos valor numerico según el tipo if ($tipo == 'num' || $tipo == 'int') { if ($valor === '') return 'NULL'; return strval(floatval($valor)); } // Retornamos valor textual como valor predeterminado return $this->pdo->quote($valor); }
[ "public", "function", "prepararValor", "(", "$", "valor", ",", "$", "tipo", "=", "'txt'", ",", "$", "permiteVacio", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "valor", ")", ")", "{", "if", "(", "empty", "(", "$", "valor", ")", ")", "{", "return", "'NULL'", ";", "}", "foreach", "(", "$", "valor", "as", "$", "llave", "=>", "$", "v", ")", "{", "$", "valor", "[", "$", "llave", "]", "=", "$", "this", "->", "prepararValor", "(", "$", "v", ",", "$", "tipo", ")", ";", "}", "return", "$", "valor", ";", "}", "// Retornamos valor boleano según el tipo", "if", "(", "$", "tipo", "==", "'bol'", "||", "$", "tipo", "==", "'bool'", ")", "{", "return", "(", "$", "valor", ")", "?", "'1'", ":", "'0'", ";", "}", "// Detectamos y retornamos valor nulo", "if", "(", "$", "valor", "===", "null", "||", "$", "valor", "===", "false", ")", "{", "return", "'NULL'", ";", "}", "if", "(", "!", "$", "permiteVacio", "&&", "$", "valor", "===", "''", ")", "{", "return", "'NULL'", ";", "}", "// Retornamos valor numerico según el tipo", "if", "(", "$", "tipo", "==", "'num'", "||", "$", "tipo", "==", "'int'", ")", "{", "if", "(", "$", "valor", "===", "''", ")", "return", "'NULL'", ";", "return", "strval", "(", "floatval", "(", "$", "valor", ")", ")", ";", "}", "// Retornamos valor textual como valor predeterminado", "return", "$", "this", "->", "pdo", "->", "quote", "(", "$", "valor", ")", ";", "}" ]
Prepara valor segun tipo especificado. @param mixed $valor Valor a preparar @param string $tipo Tipo de valor pasado: bol, txt, num, def @param bool $permiteVacio Define si permite cadena de texto vacio en vez de nulo @return string Retorna valor escapado para MySQL
[ "Prepara", "valor", "segun", "tipo", "especificado", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L112-L148
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.obtenerPrimero
public function obtenerPrimero($clase = null, array $claseArgs = []) { $resultado = $this->obtener(null, null, $clase, $claseArgs); if ($resultado !== false) { return array_shift($resultado); } return false; }
php
public function obtenerPrimero($clase = null, array $claseArgs = []) { $resultado = $this->obtener(null, null, $clase, $claseArgs); if ($resultado !== false) { return array_shift($resultado); } return false; }
[ "public", "function", "obtenerPrimero", "(", "$", "clase", "=", "null", ",", "array", "$", "claseArgs", "=", "[", "]", ")", "{", "$", "resultado", "=", "$", "this", "->", "obtener", "(", "null", ",", "null", ",", "$", "clase", ",", "$", "claseArgs", ")", ";", "if", "(", "$", "resultado", "!==", "false", ")", "{", "return", "array_shift", "(", "$", "resultado", ")", ";", "}", "return", "false", ";", "}" ]
Devuelve el primer registro generado por la consulta de la sentencia interna. @param string $clase Nombre de clase que servirá como formato de registro @param array $claseArgs Argumentos para instanciar clase formato @return array|bool @throws \RuntimeException @throws \InvalidArgumentException
[ "Devuelve", "el", "primer", "registro", "generado", "por", "la", "consulta", "de", "la", "sentencia", "interna", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L292-L301
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.ejecutar
public function ejecutar() { // Validamos la sentencia a ejecutar if (empty($this->sentencia)) { if ($this->arrojarExcepciones) { throw new \InvalidArgumentException('La sentencia a ejecutar se encuentra vacia.'); } return false; } // Ejecutamos la sentencia $resultado = $this->pdo->exec($this->sentencia); if ($resultado === false) { if ($this->arrojarExcepciones) { $error_info = $this->pdo->errorInfo(); throw new Excepcion($error_info[2], [ 'sentencia' => $this->sentencia, 'error_codigo' => $error_info[0], ], $error_info[1]); } return false; } return $resultado; }
php
public function ejecutar() { // Validamos la sentencia a ejecutar if (empty($this->sentencia)) { if ($this->arrojarExcepciones) { throw new \InvalidArgumentException('La sentencia a ejecutar se encuentra vacia.'); } return false; } // Ejecutamos la sentencia $resultado = $this->pdo->exec($this->sentencia); if ($resultado === false) { if ($this->arrojarExcepciones) { $error_info = $this->pdo->errorInfo(); throw new Excepcion($error_info[2], [ 'sentencia' => $this->sentencia, 'error_codigo' => $error_info[0], ], $error_info[1]); } return false; } return $resultado; }
[ "public", "function", "ejecutar", "(", ")", "{", "// Validamos la sentencia a ejecutar", "if", "(", "empty", "(", "$", "this", "->", "sentencia", ")", ")", "{", "if", "(", "$", "this", "->", "arrojarExcepciones", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'La sentencia a ejecutar se encuentra vacia.'", ")", ";", "}", "return", "false", ";", "}", "// Ejecutamos la sentencia", "$", "resultado", "=", "$", "this", "->", "pdo", "->", "exec", "(", "$", "this", "->", "sentencia", ")", ";", "if", "(", "$", "resultado", "===", "false", ")", "{", "if", "(", "$", "this", "->", "arrojarExcepciones", ")", "{", "$", "error_info", "=", "$", "this", "->", "pdo", "->", "errorInfo", "(", ")", ";", "throw", "new", "Excepcion", "(", "$", "error_info", "[", "2", "]", ",", "[", "'sentencia'", "=>", "$", "this", "->", "sentencia", ",", "'error_codigo'", "=>", "$", "error_info", "[", "0", "]", ",", "]", ",", "$", "error_info", "[", "1", "]", ")", ";", "}", "return", "false", ";", "}", "return", "$", "resultado", ";", "}" ]
Ejecuta la sentencia interna. @return bool @throws \InvalidArgumentException @throws Excepcion
[ "Ejecuta", "la", "sentencia", "interna", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L311-L338
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.preparar
public function preparar() { // Validamos la sentencia a preparar if (empty($this->sentencia)) { if ($this->arrojarExcepciones) { throw new \InvalidArgumentException('La sentencia a preparar se encuentra vacia.'); } } return $this->pdo->prepare($this->sentencia); }
php
public function preparar() { // Validamos la sentencia a preparar if (empty($this->sentencia)) { if ($this->arrojarExcepciones) { throw new \InvalidArgumentException('La sentencia a preparar se encuentra vacia.'); } } return $this->pdo->prepare($this->sentencia); }
[ "public", "function", "preparar", "(", ")", "{", "// Validamos la sentencia a preparar", "if", "(", "empty", "(", "$", "this", "->", "sentencia", ")", ")", "{", "if", "(", "$", "this", "->", "arrojarExcepciones", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'La sentencia a preparar se encuentra vacia.'", ")", ";", "}", "}", "return", "$", "this", "->", "pdo", "->", "prepare", "(", "$", "this", "->", "sentencia", ")", ";", "}" ]
Prepara la sentencia interna para su uso exterior. @throws \Exception @return \PDOStatement
[ "Prepara", "la", "sentencia", "interna", "para", "su", "uso", "exterior", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L359-L369
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.seleccionar
public function seleccionar($campos, $tabla) { if (is_array($campos)) { $this->sentencia = 'SELECT ' . implode(', ', $campos); } else { $this->sentencia = 'SELECT ' . $campos; } $this->sentencia .= ' FROM ' . $tabla; return $this; }
php
public function seleccionar($campos, $tabla) { if (is_array($campos)) { $this->sentencia = 'SELECT ' . implode(', ', $campos); } else { $this->sentencia = 'SELECT ' . $campos; } $this->sentencia .= ' FROM ' . $tabla; return $this; }
[ "public", "function", "seleccionar", "(", "$", "campos", ",", "$", "tabla", ")", "{", "if", "(", "is_array", "(", "$", "campos", ")", ")", "{", "$", "this", "->", "sentencia", "=", "'SELECT '", ".", "implode", "(", "', '", ",", "$", "campos", ")", ";", "}", "else", "{", "$", "this", "->", "sentencia", "=", "'SELECT '", ".", "$", "campos", ";", "}", "$", "this", "->", "sentencia", ".=", "' FROM '", ".", "$", "tabla", ";", "return", "$", "this", ";", "}" ]
Inicia la sentencia interna con SELECT. @param string|array $campos @param string $tabla @return Relacional
[ "Inicia", "la", "sentencia", "interna", "con", "SELECT", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L447-L457
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.donde
public function donde(array $params = null) { if ($params) { $terminos_sql = []; foreach ($params as $llave => $valor) { // Limpiamos la llave $llave = trim($llave); // Extraemos operador if (false === ($temp = strpos($llave, ' '))) { $restante = $llave; } else { $restante = substr($llave, 0, $temp); $operador = substr($llave, $temp + 1); } if (empty($operador)) { if (is_array($valor)) { $operador = 'IN'; } else { $operador = '='; } } // Extramos campo y su tipo if (false !== ($temp = strpos($restante, '|'))) { $tipo = substr($restante, $temp + 1); $campo = substr($restante, 0, $temp); } else { $campo = $restante; } if (empty($tipo)) $tipo = 'txt'; // Preparamos el valor segun el tipo de campo if (is_array($valor)) { $valor_preparado = '(' . implode(',', $this->prepararValor($valor, $tipo)) . ')'; } else { $valor_preparado = $this->prepararValor($valor, $tipo); } // Escribimos el termino dentro de los filtros $terminos_sql[] = "{$campo} {$operador} {$valor_preparado}"; // Limpiamos las variables repetitivas unset($restante, $campo, $operador, $tipo); } // Escribimos todos los terminos en formato SQL $this->sentencia .= ' WHERE ' . implode(' AND ', $terminos_sql); } return $this; }
php
public function donde(array $params = null) { if ($params) { $terminos_sql = []; foreach ($params as $llave => $valor) { // Limpiamos la llave $llave = trim($llave); // Extraemos operador if (false === ($temp = strpos($llave, ' '))) { $restante = $llave; } else { $restante = substr($llave, 0, $temp); $operador = substr($llave, $temp + 1); } if (empty($operador)) { if (is_array($valor)) { $operador = 'IN'; } else { $operador = '='; } } // Extramos campo y su tipo if (false !== ($temp = strpos($restante, '|'))) { $tipo = substr($restante, $temp + 1); $campo = substr($restante, 0, $temp); } else { $campo = $restante; } if (empty($tipo)) $tipo = 'txt'; // Preparamos el valor segun el tipo de campo if (is_array($valor)) { $valor_preparado = '(' . implode(',', $this->prepararValor($valor, $tipo)) . ')'; } else { $valor_preparado = $this->prepararValor($valor, $tipo); } // Escribimos el termino dentro de los filtros $terminos_sql[] = "{$campo} {$operador} {$valor_preparado}"; // Limpiamos las variables repetitivas unset($restante, $campo, $operador, $tipo); } // Escribimos todos los terminos en formato SQL $this->sentencia .= ' WHERE ' . implode(' AND ', $terminos_sql); } return $this; }
[ "public", "function", "donde", "(", "array", "$", "params", "=", "null", ")", "{", "if", "(", "$", "params", ")", "{", "$", "terminos_sql", "=", "[", "]", ";", "foreach", "(", "$", "params", "as", "$", "llave", "=>", "$", "valor", ")", "{", "// Limpiamos la llave", "$", "llave", "=", "trim", "(", "$", "llave", ")", ";", "// Extraemos operador", "if", "(", "false", "===", "(", "$", "temp", "=", "strpos", "(", "$", "llave", ",", "' '", ")", ")", ")", "{", "$", "restante", "=", "$", "llave", ";", "}", "else", "{", "$", "restante", "=", "substr", "(", "$", "llave", ",", "0", ",", "$", "temp", ")", ";", "$", "operador", "=", "substr", "(", "$", "llave", ",", "$", "temp", "+", "1", ")", ";", "}", "if", "(", "empty", "(", "$", "operador", ")", ")", "{", "if", "(", "is_array", "(", "$", "valor", ")", ")", "{", "$", "operador", "=", "'IN'", ";", "}", "else", "{", "$", "operador", "=", "'='", ";", "}", "}", "// Extramos campo y su tipo", "if", "(", "false", "!==", "(", "$", "temp", "=", "strpos", "(", "$", "restante", ",", "'|'", ")", ")", ")", "{", "$", "tipo", "=", "substr", "(", "$", "restante", ",", "$", "temp", "+", "1", ")", ";", "$", "campo", "=", "substr", "(", "$", "restante", ",", "0", ",", "$", "temp", ")", ";", "}", "else", "{", "$", "campo", "=", "$", "restante", ";", "}", "if", "(", "empty", "(", "$", "tipo", ")", ")", "$", "tipo", "=", "'txt'", ";", "// Preparamos el valor segun el tipo de campo", "if", "(", "is_array", "(", "$", "valor", ")", ")", "{", "$", "valor_preparado", "=", "'('", ".", "implode", "(", "','", ",", "$", "this", "->", "prepararValor", "(", "$", "valor", ",", "$", "tipo", ")", ")", ".", "')'", ";", "}", "else", "{", "$", "valor_preparado", "=", "$", "this", "->", "prepararValor", "(", "$", "valor", ",", "$", "tipo", ")", ";", "}", "// Escribimos el termino dentro de los filtros", "$", "terminos_sql", "[", "]", "=", "\"{$campo} {$operador} {$valor_preparado}\"", ";", "// Limpiamos las variables repetitivas", "unset", "(", "$", "restante", ",", "$", "campo", ",", "$", "operador", ",", "$", "tipo", ")", ";", "}", "// Escribimos todos los terminos en formato SQL", "$", "this", "->", "sentencia", ".=", "' WHERE '", ".", "implode", "(", "' AND '", ",", "$", "terminos_sql", ")", ";", "}", "return", "$", "this", ";", "}" ]
Prepara los campos que filtran la sentencia interna. @param array|null $params Campos parametrizados @return Relacional
[ "Prepara", "los", "campos", "que", "filtran", "la", "sentencia", "interna", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L484-L537
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.limitar
public function limitar($pos, $limite = null) { if ($limite) { $this->sentencia .= ' LIMIT ' . $pos . ',' . $limite; } else { $this->sentencia .= ' LIMIT ' . $pos; } return $this; }
php
public function limitar($pos, $limite = null) { if ($limite) { $this->sentencia .= ' LIMIT ' . $pos . ',' . $limite; } else { $this->sentencia .= ' LIMIT ' . $pos; } return $this; }
[ "public", "function", "limitar", "(", "$", "pos", ",", "$", "limite", "=", "null", ")", "{", "if", "(", "$", "limite", ")", "{", "$", "this", "->", "sentencia", ".=", "' LIMIT '", ".", "$", "pos", ".", "','", ".", "$", "limite", ";", "}", "else", "{", "$", "this", "->", "sentencia", ".=", "' LIMIT '", ".", "$", "pos", ";", "}", "return", "$", "this", ";", "}" ]
Implementa LIMIT a la sentencia interna. @param int $pos @param int $limite @return Relacional
[ "Implementa", "LIMIT", "a", "la", "sentencia", "interna", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L575-L584
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.actualizar
public function actualizar($tabla, array $params) { $terminos_sql = []; foreach ($params as $llave => $valor) { // Extramos campo y su tipo $temp = explode('|', $llave); $campo = $temp[0]; if (isset($temp[1])) { $tipo = $temp[1]; } else { $tipo = 'auto'; } $terminos_sql[] = $campo . ' = ' . $this->prepararValor($valor, $tipo); } $this->sentencia = 'UPDATE ' . $tabla . ' SET ' . implode(', ', $terminos_sql); return $this; }
php
public function actualizar($tabla, array $params) { $terminos_sql = []; foreach ($params as $llave => $valor) { // Extramos campo y su tipo $temp = explode('|', $llave); $campo = $temp[0]; if (isset($temp[1])) { $tipo = $temp[1]; } else { $tipo = 'auto'; } $terminos_sql[] = $campo . ' = ' . $this->prepararValor($valor, $tipo); } $this->sentencia = 'UPDATE ' . $tabla . ' SET ' . implode(', ', $terminos_sql); return $this; }
[ "public", "function", "actualizar", "(", "$", "tabla", ",", "array", "$", "params", ")", "{", "$", "terminos_sql", "=", "[", "]", ";", "foreach", "(", "$", "params", "as", "$", "llave", "=>", "$", "valor", ")", "{", "// Extramos campo y su tipo", "$", "temp", "=", "explode", "(", "'|'", ",", "$", "llave", ")", ";", "$", "campo", "=", "$", "temp", "[", "0", "]", ";", "if", "(", "isset", "(", "$", "temp", "[", "1", "]", ")", ")", "{", "$", "tipo", "=", "$", "temp", "[", "1", "]", ";", "}", "else", "{", "$", "tipo", "=", "'auto'", ";", "}", "$", "terminos_sql", "[", "]", "=", "$", "campo", ".", "' = '", ".", "$", "this", "->", "prepararValor", "(", "$", "valor", ",", "$", "tipo", ")", ";", "}", "$", "this", "->", "sentencia", "=", "'UPDATE '", ".", "$", "tabla", ".", "' SET '", ".", "implode", "(", "', '", ",", "$", "terminos_sql", ")", ";", "return", "$", "this", ";", "}" ]
Inicia la sentencia interna con UPDATE. @param string $tabla @param array $params Campos parametrizados @return Relacional
[ "Inicia", "la", "sentencia", "interna", "con", "UPDATE", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L594-L613
train
armazon/armazon
src/Armazon/Bd/Relacional.php
Relacional.insertar
public function insertar($tabla, array $params) { $columnas = []; $valores = []; foreach ($params as $llave => $valor) { // Extramos campo y su tipo $temp = explode('|', $llave); $campo = $temp[0]; if (isset($temp[1])) { $tipo = $temp[1]; } else { $tipo = 'auto'; } $columnas[] = $campo; $valores[] = $this->prepararValor($valor, $tipo); } $this->sentencia = 'INSERT INTO ' . $tabla . ' (' . implode(', ', $columnas) . ') VALUES (' . implode(', ', $valores) . ')'; return $this; }
php
public function insertar($tabla, array $params) { $columnas = []; $valores = []; foreach ($params as $llave => $valor) { // Extramos campo y su tipo $temp = explode('|', $llave); $campo = $temp[0]; if (isset($temp[1])) { $tipo = $temp[1]; } else { $tipo = 'auto'; } $columnas[] = $campo; $valores[] = $this->prepararValor($valor, $tipo); } $this->sentencia = 'INSERT INTO ' . $tabla . ' (' . implode(', ', $columnas) . ') VALUES (' . implode(', ', $valores) . ')'; return $this; }
[ "public", "function", "insertar", "(", "$", "tabla", ",", "array", "$", "params", ")", "{", "$", "columnas", "=", "[", "]", ";", "$", "valores", "=", "[", "]", ";", "foreach", "(", "$", "params", "as", "$", "llave", "=>", "$", "valor", ")", "{", "// Extramos campo y su tipo", "$", "temp", "=", "explode", "(", "'|'", ",", "$", "llave", ")", ";", "$", "campo", "=", "$", "temp", "[", "0", "]", ";", "if", "(", "isset", "(", "$", "temp", "[", "1", "]", ")", ")", "{", "$", "tipo", "=", "$", "temp", "[", "1", "]", ";", "}", "else", "{", "$", "tipo", "=", "'auto'", ";", "}", "$", "columnas", "[", "]", "=", "$", "campo", ";", "$", "valores", "[", "]", "=", "$", "this", "->", "prepararValor", "(", "$", "valor", ",", "$", "tipo", ")", ";", "}", "$", "this", "->", "sentencia", "=", "'INSERT INTO '", ".", "$", "tabla", ".", "' ('", ".", "implode", "(", "', '", ",", "$", "columnas", ")", ".", "') VALUES ('", ".", "implode", "(", "', '", ",", "$", "valores", ")", ".", "')'", ";", "return", "$", "this", ";", "}" ]
Inicia la sentencia interna con INSERT. @param string $tabla Tabla @param array $params Campos parametrizados @return Relacional
[ "Inicia", "la", "sentencia", "interna", "con", "INSERT", "." ]
ec76385ff80ce1659d81bc4050ef9483ab0ebe52
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Bd/Relacional.php#L623-L645
train
PopSugar/php-yesmail-api
src/Yesmail/CurlClient.php
CurlClient.get
public function get($url, $data) { curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($this->_ch, CURLOPT_URL, sprintf( "%s?%s", $url, http_build_query($data, '', '&', PHP_QUERY_RFC3986))); curl_setopt($this->_ch, CURLOPT_HTTPHEADER, array("Accept:application/json", "Content-Type: application/json")); return $this->_exec(); }
php
public function get($url, $data) { curl_setopt($this->_ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($this->_ch, CURLOPT_URL, sprintf( "%s?%s", $url, http_build_query($data, '', '&', PHP_QUERY_RFC3986))); curl_setopt($this->_ch, CURLOPT_HTTPHEADER, array("Accept:application/json", "Content-Type: application/json")); return $this->_exec(); }
[ "public", "function", "get", "(", "$", "url", ",", "$", "data", ")", "{", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'GET'", ")", ";", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_URL", ",", "sprintf", "(", "\"%s?%s\"", ",", "$", "url", ",", "http_build_query", "(", "$", "data", ",", "''", ",", "'&'", ",", "PHP_QUERY_RFC3986", ")", ")", ")", ";", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_HTTPHEADER", ",", "array", "(", "\"Accept:application/json\"", ",", "\"Content-Type: application/json\"", ")", ")", ";", "return", "$", "this", "->", "_exec", "(", ")", ";", "}" ]
Perform an HTTP GET @param string $url The URL to send the GET request to. @param array $data An array of parameters to be added to the query string. @return mixed A JSON decoded PHP variable representing the HTTP response. @access public
[ "Perform", "an", "HTTP", "GET" ]
42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c
https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/CurlClient.php#L61-L67
train
PopSugar/php-yesmail-api
src/Yesmail/CurlClient.php
CurlClient._initialize
protected function _initialize() { $this->_ch = curl_init(); $this->_last_info = FALSE; curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($this->_ch, CURLOPT_TIMEOUT, 60); curl_setopt($this->_ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($this->_ch, CURLOPT_USERPWD, "{$this->_username}:{$this->_password}"); return; }
php
protected function _initialize() { $this->_ch = curl_init(); $this->_last_info = FALSE; curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->_ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($this->_ch, CURLOPT_TIMEOUT, 60); curl_setopt($this->_ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($this->_ch, CURLOPT_USERPWD, "{$this->_username}:{$this->_password}"); return; }
[ "protected", "function", "_initialize", "(", ")", "{", "$", "this", "->", "_ch", "=", "curl_init", "(", ")", ";", "$", "this", "->", "_last_info", "=", "FALSE", ";", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "false", ")", ";", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_TIMEOUT", ",", "60", ")", ";", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_CONNECTTIMEOUT", ",", "60", ")", ";", "curl_setopt", "(", "$", "this", "->", "_ch", ",", "CURLOPT_USERPWD", ",", "\"{$this->_username}:{$this->_password}\"", ")", ";", "return", ";", "}" ]
Initialize the curl resource and options @return void @access protected
[ "Initialize", "the", "curl", "resource", "and", "options" ]
42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c
https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/CurlClient.php#L136-L146
train
PopSugar/php-yesmail-api
src/Yesmail/CurlClient.php
CurlClient._exec
protected function _exec() { $response = curl_exec($this->_ch); $this->_last_info = curl_getinfo($this->_ch); $error = curl_error( $this->_ch ); if ( $error ) { throw new \Exception($error); } return $response; }
php
protected function _exec() { $response = curl_exec($this->_ch); $this->_last_info = curl_getinfo($this->_ch); $error = curl_error( $this->_ch ); if ( $error ) { throw new \Exception($error); } return $response; }
[ "protected", "function", "_exec", "(", ")", "{", "$", "response", "=", "curl_exec", "(", "$", "this", "->", "_ch", ")", ";", "$", "this", "->", "_last_info", "=", "curl_getinfo", "(", "$", "this", "->", "_ch", ")", ";", "$", "error", "=", "curl_error", "(", "$", "this", "->", "_ch", ")", ";", "if", "(", "$", "error", ")", "{", "throw", "new", "\\", "Exception", "(", "$", "error", ")", ";", "}", "return", "$", "response", ";", "}" ]
Execute a curl request. Maintain the info from the request in a variable @return mixed A JSON decoded PHP variable representing the HTTP response. @access protected @throws Exception
[ "Execute", "a", "curl", "request", ".", "Maintain", "the", "info", "from", "the", "request", "in", "a", "variable" ]
42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c
https://github.com/PopSugar/php-yesmail-api/blob/42c20a3ded1d8f2177c792cd3aa44bcdfdcb239c/src/Yesmail/CurlClient.php#L155-L164
train
harp-orm/harp
src/Repo/LinkMap.php
LinkMap.get
public function get(AbstractModel $model) { if (! $this->repo->isModel($model)) { throw new InvalidArgumentException( sprintf('Model must be %s, was %s', $this->repo->getModelClass(), get_class($model)) ); } if ($this->map->contains($model)) { return $this->map[$model]; } else { return $this->map[$model] = new Links($model); } }
php
public function get(AbstractModel $model) { if (! $this->repo->isModel($model)) { throw new InvalidArgumentException( sprintf('Model must be %s, was %s', $this->repo->getModelClass(), get_class($model)) ); } if ($this->map->contains($model)) { return $this->map[$model]; } else { return $this->map[$model] = new Links($model); } }
[ "public", "function", "get", "(", "AbstractModel", "$", "model", ")", "{", "if", "(", "!", "$", "this", "->", "repo", "->", "isModel", "(", "$", "model", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Model must be %s, was %s'", ",", "$", "this", "->", "repo", "->", "getModelClass", "(", ")", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "}", "if", "(", "$", "this", "->", "map", "->", "contains", "(", "$", "model", ")", ")", "{", "return", "$", "this", "->", "map", "[", "$", "model", "]", ";", "}", "else", "{", "return", "$", "this", "->", "map", "[", "$", "model", "]", "=", "new", "Links", "(", "$", "model", ")", ";", "}", "}" ]
Get Links object associated with this model. If there is none, an empty Links object is created. @param AbstractModel $model @return Links @throws InvalidArgumentException If model does not belong to repo
[ "Get", "Links", "object", "associated", "with", "this", "model", ".", "If", "there", "is", "none", "an", "empty", "Links", "object", "is", "created", "." ]
e0751696521164c86ccd0a76d708df490efd8306
https://github.com/harp-orm/harp/blob/e0751696521164c86ccd0a76d708df490efd8306/src/Repo/LinkMap.php#L55-L68
train
cyberspectrum/i18n-contao
src/ContaoTableDictionary.php
ContaoTableDictionary.getKeysForSource
protected function getKeysForSource(int $sourceId): \Traversable { $row = $this->getRow($sourceId); foreach ($this->extractors as $extractor) { switch (true) { case $extractor instanceof MultiStringExtractorInterface: foreach ($extractor->keys($row) as $key) { yield $extractor->name() . '.' . $key; } break; case $extractor instanceof ExtractorInterface: if ($extractor->supports($row)) { yield $extractor->name(); } break; default: throw new \InvalidArgumentException('Unknown extractor type ' . \get_class($extractor)); } } }
php
protected function getKeysForSource(int $sourceId): \Traversable { $row = $this->getRow($sourceId); foreach ($this->extractors as $extractor) { switch (true) { case $extractor instanceof MultiStringExtractorInterface: foreach ($extractor->keys($row) as $key) { yield $extractor->name() . '.' . $key; } break; case $extractor instanceof ExtractorInterface: if ($extractor->supports($row)) { yield $extractor->name(); } break; default: throw new \InvalidArgumentException('Unknown extractor type ' . \get_class($extractor)); } } }
[ "protected", "function", "getKeysForSource", "(", "int", "$", "sourceId", ")", ":", "\\", "Traversable", "{", "$", "row", "=", "$", "this", "->", "getRow", "(", "$", "sourceId", ")", ";", "foreach", "(", "$", "this", "->", "extractors", "as", "$", "extractor", ")", "{", "switch", "(", "true", ")", "{", "case", "$", "extractor", "instanceof", "MultiStringExtractorInterface", ":", "foreach", "(", "$", "extractor", "->", "keys", "(", "$", "row", ")", "as", "$", "key", ")", "{", "yield", "$", "extractor", "->", "name", "(", ")", ".", "'.'", ".", "$", "key", ";", "}", "break", ";", "case", "$", "extractor", "instanceof", "ExtractorInterface", ":", "if", "(", "$", "extractor", "->", "supports", "(", "$", "row", ")", ")", "{", "yield", "$", "extractor", "->", "name", "(", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unknown extractor type '", ".", "\\", "get_class", "(", "$", "extractor", ")", ")", ";", "}", "}", "}" ]
Get the keys for the source id. @param int $sourceId The source id. @return \Traversable|string[] @throws \InvalidArgumentException When the extractor is unknown.
[ "Get", "the", "keys", "for", "the", "source", "id", "." ]
038cf6ea9c609a734d7476fba256bc4b0db236b7
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L297-L316
train
cyberspectrum/i18n-contao
src/ContaoTableDictionary.php
ContaoTableDictionary.createValueReader
protected function createValueReader( int $sourceId, int $targetId, ExtractorInterface $extractor, string $trail ): TranslationValueInterface { return new TranslationValue($this, $sourceId, $targetId, $extractor, $trail); }
php
protected function createValueReader( int $sourceId, int $targetId, ExtractorInterface $extractor, string $trail ): TranslationValueInterface { return new TranslationValue($this, $sourceId, $targetId, $extractor, $trail); }
[ "protected", "function", "createValueReader", "(", "int", "$", "sourceId", ",", "int", "$", "targetId", ",", "ExtractorInterface", "$", "extractor", ",", "string", "$", "trail", ")", ":", "TranslationValueInterface", "{", "return", "new", "TranslationValue", "(", "$", "this", ",", "$", "sourceId", ",", "$", "targetId", ",", "$", "extractor", ",", "$", "trail", ")", ";", "}" ]
Create a value reader instance. @param int $sourceId The source id. @param int $targetId The target id. @param ExtractorInterface $extractor The extractor to use. @param string $trail The trailing sub path. @return TranslationValueInterface
[ "Create", "a", "value", "reader", "instance", "." ]
038cf6ea9c609a734d7476fba256bc4b0db236b7
https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/ContaoTableDictionary.php#L340-L347
train