repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
ezsystems/BehatBundle
Context/Resolver/AnnotationArgumentResolver.php
AnnotationArgumentResolver.getMethodAnnotations
private function getMethodAnnotations($refClass, $method = '__construct') { $refMethod = $refClass->getMethod($method); preg_match_all('#@(.*?)\n#s', $refMethod->getDocComment(), $matches); return $matches[1]; }
php
private function getMethodAnnotations($refClass, $method = '__construct') { $refMethod = $refClass->getMethod($method); preg_match_all('#@(.*?)\n#s', $refMethod->getDocComment(), $matches); return $matches[1]; }
[ "private", "function", "getMethodAnnotations", "(", "$", "refClass", ",", "$", "method", "=", "'__construct'", ")", "{", "$", "refMethod", "=", "$", "refClass", "->", "getMethod", "(", "$", "method", ")", ";", "preg_match_all", "(", "'#@(.*?)\\n#s'", ",", "$", "refMethod", "->", "getDocComment", "(", ")", ",", "$", "matches", ")", ";", "return", "$", "matches", "[", "1", "]", ";", "}" ]
Returns a array with the method annotations @return array array annotations
[ "Returns", "a", "array", "with", "the", "method", "annotations" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Resolver/AnnotationArgumentResolver.php#L50-L56
ezsystems/BehatBundle
ObjectManager/Role.php
Role.ensureRoleExists
public function ensureRoleExists( $name ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $that = $this; $role = $repository->sudo( function() use( $repository, $name, $that ) { $role = null; $roleService = $repository->getRoleService(); // make sure role name starts with uppercase as this is what default setup provides if ($name !== ucfirst($name)) { @trigger_error( "'{$name}' role name should start with uppercase letter", E_USER_DEPRECATED ); } try { $role = $roleService->loadRoleByIdentifier(ucfirst($name)); } catch ( ApiExceptions\NotFoundException $e ) { $roleCreateStruct = $roleService->newRoleCreateStruct(ucfirst($name)); $roleDraft = $roleService->createRole( $roleCreateStruct ); $roleService->publishRoleDraft($roleDraft); $role = $roleService->loadRole($roleDraft->id); $that->addObjectToList( $role ); } return $role; } ); return $role; }
php
public function ensureRoleExists( $name ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $that = $this; $role = $repository->sudo( function() use( $repository, $name, $that ) { $role = null; $roleService = $repository->getRoleService(); // make sure role name starts with uppercase as this is what default setup provides if ($name !== ucfirst($name)) { @trigger_error( "'{$name}' role name should start with uppercase letter", E_USER_DEPRECATED ); } try { $role = $roleService->loadRoleByIdentifier(ucfirst($name)); } catch ( ApiExceptions\NotFoundException $e ) { $roleCreateStruct = $roleService->newRoleCreateStruct(ucfirst($name)); $roleDraft = $roleService->createRole( $roleCreateStruct ); $roleService->publishRoleDraft($roleDraft); $role = $roleService->loadRole($roleDraft->id); $that->addObjectToList( $role ); } return $role; } ); return $role; }
[ "public", "function", "ensureRoleExists", "(", "$", "name", ")", "{", "/** @var \\eZ\\Publish\\API\\Repository\\Repository $repository */", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "that", "=", "$", "this", ";", "$", "role", "=", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "repository", ",", "$", "name", ",", "$", "that", ")", "{", "$", "role", "=", "null", ";", "$", "roleService", "=", "$", "repository", "->", "getRoleService", "(", ")", ";", "// make sure role name starts with uppercase as this is what default setup provides", "if", "(", "$", "name", "!==", "ucfirst", "(", "$", "name", ")", ")", "{", "@", "trigger_error", "(", "\"'{$name}' role name should start with uppercase letter\"", ",", "E_USER_DEPRECATED", ")", ";", "}", "try", "{", "$", "role", "=", "$", "roleService", "->", "loadRoleByIdentifier", "(", "ucfirst", "(", "$", "name", ")", ")", ";", "}", "catch", "(", "ApiExceptions", "\\", "NotFoundException", "$", "e", ")", "{", "$", "roleCreateStruct", "=", "$", "roleService", "->", "newRoleCreateStruct", "(", "ucfirst", "(", "$", "name", ")", ")", ";", "$", "roleDraft", "=", "$", "roleService", "->", "createRole", "(", "$", "roleCreateStruct", ")", ";", "$", "roleService", "->", "publishRoleDraft", "(", "$", "roleDraft", ")", ";", "$", "role", "=", "$", "roleService", "->", "loadRole", "(", "$", "roleDraft", "->", "id", ")", ";", "$", "that", "->", "addObjectToList", "(", "$", "role", ")", ";", "}", "return", "$", "role", ";", "}", ")", ";", "return", "$", "role", ";", "}" ]
Make sure a Role with name $name exists in parent group @param string $name Role identifier @return \eZ\Publish\API\Repository\Values\User\Role
[ "Make", "sure", "a", "Role", "with", "name", "$name", "exists", "in", "parent", "group" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/Role.php#L29-L66
ezsystems/BehatBundle
ObjectManager/Role.php
Role.getRole
public function getRole( $identifier ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $role = $repository->sudo( function() use( $repository, $identifier ) { $role = null; $roleService = $repository->getRoleService(); try { // make sure role name starts with uppercase as this is what default setup provides if ($identifier !== ucfirst($identifier)) { @trigger_error( "'{$identifier}' role name should start with uppercase letter", E_USER_DEPRECATED ); } $role = $roleService->loadRoleByIdentifier(ucfirst($identifier)); } catch ( ApiExceptions\NotFoundException $e ) { // Role not found, do nothing, returns null } return $role; } ); return $role; }
php
public function getRole( $identifier ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $role = $repository->sudo( function() use( $repository, $identifier ) { $role = null; $roleService = $repository->getRoleService(); try { // make sure role name starts with uppercase as this is what default setup provides if ($identifier !== ucfirst($identifier)) { @trigger_error( "'{$identifier}' role name should start with uppercase letter", E_USER_DEPRECATED ); } $role = $roleService->loadRoleByIdentifier(ucfirst($identifier)); } catch ( ApiExceptions\NotFoundException $e ) { // Role not found, do nothing, returns null } return $role; } ); return $role; }
[ "public", "function", "getRole", "(", "$", "identifier", ")", "{", "/** @var \\eZ\\Publish\\API\\Repository\\Repository $repository */", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "role", "=", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "repository", ",", "$", "identifier", ")", "{", "$", "role", "=", "null", ";", "$", "roleService", "=", "$", "repository", "->", "getRoleService", "(", ")", ";", "try", "{", "// make sure role name starts with uppercase as this is what default setup provides", "if", "(", "$", "identifier", "!==", "ucfirst", "(", "$", "identifier", ")", ")", "{", "@", "trigger_error", "(", "\"'{$identifier}' role name should start with uppercase letter\"", ",", "E_USER_DEPRECATED", ")", ";", "}", "$", "role", "=", "$", "roleService", "->", "loadRoleByIdentifier", "(", "ucfirst", "(", "$", "identifier", ")", ")", ";", "}", "catch", "(", "ApiExceptions", "\\", "NotFoundException", "$", "e", ")", "{", "// Role not found, do nothing, returns null", "}", "return", "$", "role", ";", "}", ")", ";", "return", "$", "role", ";", "}" ]
Fetches the role with identifier @param string $identifier Role identifier @return \eZ\Publish\API\Repository\Values\User\Role
[ "Fetches", "the", "role", "with", "identifier" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/Role.php#L75-L105
ezsystems/BehatBundle
ObjectManager/Role.php
Role.destroy
protected function destroy( ValueObject $object ) { // Ignore warnings about not empty cache directory. See: https://github.com/ezsystems/BehatBundle/pull/71 $currentErrorReportingLevel = error_reporting(); error_reporting($currentErrorReportingLevel & ~E_WARNING); /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $repository->sudo( function() use( $repository, $object ) { $roleService = $repository->getRoleService(); try { $objectToBeRemoved = $roleService->loadRole( $object->id ); $roleService->deleteRole( $objectToBeRemoved ); } catch ( ApiExceptions\NotFoundException $e ) { // nothing to do } } ); error_reporting($currentErrorReportingLevel); }
php
protected function destroy( ValueObject $object ) { // Ignore warnings about not empty cache directory. See: https://github.com/ezsystems/BehatBundle/pull/71 $currentErrorReportingLevel = error_reporting(); error_reporting($currentErrorReportingLevel & ~E_WARNING); /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $repository->sudo( function() use( $repository, $object ) { $roleService = $repository->getRoleService(); try { $objectToBeRemoved = $roleService->loadRole( $object->id ); $roleService->deleteRole( $objectToBeRemoved ); } catch ( ApiExceptions\NotFoundException $e ) { // nothing to do } } ); error_reporting($currentErrorReportingLevel); }
[ "protected", "function", "destroy", "(", "ValueObject", "$", "object", ")", "{", "// Ignore warnings about not empty cache directory. See: https://github.com/ezsystems/BehatBundle/pull/71", "$", "currentErrorReportingLevel", "=", "error_reporting", "(", ")", ";", "error_reporting", "(", "$", "currentErrorReportingLevel", "&", "~", "E_WARNING", ")", ";", "/** @var \\eZ\\Publish\\API\\Repository\\Repository $repository */", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "repository", ",", "$", "object", ")", "{", "$", "roleService", "=", "$", "repository", "->", "getRoleService", "(", ")", ";", "try", "{", "$", "objectToBeRemoved", "=", "$", "roleService", "->", "loadRole", "(", "$", "object", "->", "id", ")", ";", "$", "roleService", "->", "deleteRole", "(", "$", "objectToBeRemoved", ")", ";", "}", "catch", "(", "ApiExceptions", "\\", "NotFoundException", "$", "e", ")", "{", "// nothing to do", "}", "}", ")", ";", "error_reporting", "(", "$", "currentErrorReportingLevel", ")", ";", "}" ]
[destroy description] @param ValueObject $object [description] @return [type] [description]
[ "[", "destroy", "description", "]" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/Role.php#L112-L137
ezsystems/BehatBundle
Context/EzContext.php
EzContext.prepareKernel
public function prepareKernel( $event ) { // temporary class alias // for PHPUnit v6 adoption time if (!class_exists('PHPUnit_Framework_Assert')) { class_alias('PHPUnit\Framework\Assert', 'PHPUnit_Framework_Assert'); } $container = $this->getKernel()->getContainer(); // Inject a properly generated siteaccess if the kernel is booted, and thus container is available. $container->set( 'ezpublish.siteaccess', $this->generateSiteAccess() ); }
php
public function prepareKernel( $event ) { // temporary class alias // for PHPUnit v6 adoption time if (!class_exists('PHPUnit_Framework_Assert')) { class_alias('PHPUnit\Framework\Assert', 'PHPUnit_Framework_Assert'); } $container = $this->getKernel()->getContainer(); // Inject a properly generated siteaccess if the kernel is booted, and thus container is available. $container->set( 'ezpublish.siteaccess', $this->generateSiteAccess() ); }
[ "public", "function", "prepareKernel", "(", "$", "event", ")", "{", "// temporary class alias", "// for PHPUnit v6 adoption time", "if", "(", "!", "class_exists", "(", "'PHPUnit_Framework_Assert'", ")", ")", "{", "class_alias", "(", "'PHPUnit\\Framework\\Assert'", ",", "'PHPUnit_Framework_Assert'", ")", ";", "}", "$", "container", "=", "$", "this", "->", "getKernel", "(", ")", "->", "getContainer", "(", ")", ";", "// Inject a properly generated siteaccess if the kernel is booted, and thus container is available.", "$", "container", "->", "set", "(", "'ezpublish.siteaccess'", ",", "$", "this", "->", "generateSiteAccess", "(", ")", ")", ";", "}" ]
@BeforeScenario @param \Behat\Behat\Event\ScenarioEvent|\Behat\Behat\Event\OutlineExampleEvent $event
[ "@BeforeScenario" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/EzContext.php#L106-L118
ezsystems/BehatBundle
Context/EzContext.php
EzContext.getObjectManager
protected function getObjectManager( $object ) { $namespace = '\\EzSystems\\BehatBundle\\ObjectManager\\'; if ( empty( $this->objectManagers[$object] ) ) { $class = $namespace . $object; if ( ! class_exists( $class ) && is_subclass_of( $class, $namespace . 'ObjectManagerInterface' ) ) { throw new \Exception( "Class '{$object}' not found or it doesn't implement '{$namespace}ObjectManagerInterface'" ); } $this->objectManagers[$object] = $class::instance( $this ); } return $this->objectManagers[$object]; }
php
protected function getObjectManager( $object ) { $namespace = '\\EzSystems\\BehatBundle\\ObjectManager\\'; if ( empty( $this->objectManagers[$object] ) ) { $class = $namespace . $object; if ( ! class_exists( $class ) && is_subclass_of( $class, $namespace . 'ObjectManagerInterface' ) ) { throw new \Exception( "Class '{$object}' not found or it doesn't implement '{$namespace}ObjectManagerInterface'" ); } $this->objectManagers[$object] = $class::instance( $this ); } return $this->objectManagers[$object]; }
[ "protected", "function", "getObjectManager", "(", "$", "object", ")", "{", "$", "namespace", "=", "'\\\\EzSystems\\\\BehatBundle\\\\ObjectManager\\\\'", ";", "if", "(", "empty", "(", "$", "this", "->", "objectManagers", "[", "$", "object", "]", ")", ")", "{", "$", "class", "=", "$", "namespace", ".", "$", "object", ";", "if", "(", "!", "class_exists", "(", "$", "class", ")", "&&", "is_subclass_of", "(", "$", "class", ",", "$", "namespace", ".", "'ObjectManagerInterface'", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Class '{$object}' not found or it doesn't implement '{$namespace}ObjectManagerInterface'\"", ")", ";", "}", "$", "this", "->", "objectManagers", "[", "$", "object", "]", "=", "$", "class", "::", "instance", "(", "$", "this", ")", ";", "}", "return", "$", "this", "->", "objectManagers", "[", "$", "object", "]", ";", "}" ]
Get a specific object manager @param string $object Name of the object manager @return \EzSystems\BehatBundle\ObjectManager\ObjectManagerInterface @throws \Exception $object isn't found or doesn't implement \EzSystems\BehatBundle\ObjectManager\ObjectManagerInterface
[ "Get", "a", "specific", "object", "manager" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/EzContext.php#L148-L167
ezsystems/BehatBundle
Context/EzContext.php
EzContext.addValuesToKeyMap
protected function addValuesToKeyMap( $key, $values ) { if ( empty( $key ) ) { throw new InvalidArgumentException( 'key', "can't be empty" ); } if ( ! empty( $this->keyMap[$key] ) ) { throw new InvalidArgumentException( 'key', 'key exists' ); } $this->keyMap[$key] = $values; }
php
protected function addValuesToKeyMap( $key, $values ) { if ( empty( $key ) ) { throw new InvalidArgumentException( 'key', "can't be empty" ); } if ( ! empty( $this->keyMap[$key] ) ) { throw new InvalidArgumentException( 'key', 'key exists' ); } $this->keyMap[$key] = $values; }
[ "protected", "function", "addValuesToKeyMap", "(", "$", "key", ",", "$", "values", ")", "{", "if", "(", "empty", "(", "$", "key", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'key'", ",", "\"can't be empty\"", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "keyMap", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'key'", ",", "'key exists'", ")", ";", "}", "$", "this", "->", "keyMap", "[", "$", "key", "]", "=", "$", "values", ";", "}" ]
Store (map) values needed for testing that can't be passed through gherkin @param string $key (Unique) Identifier key on the array @param mixed $values Any kind of value/object to store @throws \eZ\Publish\Core\Base\Exceptions\InvalidArgumentException if $key is empty
[ "Store", "(", "map", ")", "values", "needed", "for", "testing", "that", "can", "t", "be", "passed", "through", "gherkin" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/EzContext.php#L177-L190
ezsystems/BehatBundle
Context/EzContext.php
EzContext.getValuesFromKeyMap
protected function getValuesFromKeyMap( $key ) { if ( empty( $key ) || empty( $this->keyMap[$key] ) ) { return null; } return $this->keyMap[$key]; }
php
protected function getValuesFromKeyMap( $key ) { if ( empty( $key ) || empty( $this->keyMap[$key] ) ) { return null; } return $this->keyMap[$key]; }
[ "protected", "function", "getValuesFromKeyMap", "(", "$", "key", ")", "{", "if", "(", "empty", "(", "$", "key", ")", "||", "empty", "(", "$", "this", "->", "keyMap", "[", "$", "key", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "keyMap", "[", "$", "key", "]", ";", "}" ]
Fetches values needed for testing stored on mapping @param string $key (Unique) Identifier key on the array @return mixed|null Mapped value or null if not found
[ "Fetches", "values", "needed", "for", "testing", "stored", "on", "mapping" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/EzContext.php#L199-L207
ezsystems/BehatBundle
Context/EzContext.php
EzContext.changeMappedValuesOnUrl
protected function changeMappedValuesOnUrl( $url ) { $newUrl = ""; foreach ( explode( '/', $url ) as $chunk ) { $newChunk = $this->getValuesFromKeyMap( $chunk ); if ( empty( $newChunk ) ) { $newChunk = $chunk; } $newUrl .= '/' . $newChunk; } return preg_replace( '/\/\//', '/', $newUrl ); }
php
protected function changeMappedValuesOnUrl( $url ) { $newUrl = ""; foreach ( explode( '/', $url ) as $chunk ) { $newChunk = $this->getValuesFromKeyMap( $chunk ); if ( empty( $newChunk ) ) { $newChunk = $chunk; } $newUrl .= '/' . $newChunk; } return preg_replace( '/\/\//', '/', $newUrl ); }
[ "protected", "function", "changeMappedValuesOnUrl", "(", "$", "url", ")", "{", "$", "newUrl", "=", "\"\"", ";", "foreach", "(", "explode", "(", "'/'", ",", "$", "url", ")", "as", "$", "chunk", ")", "{", "$", "newChunk", "=", "$", "this", "->", "getValuesFromKeyMap", "(", "$", "chunk", ")", ";", "if", "(", "empty", "(", "$", "newChunk", ")", ")", "{", "$", "newChunk", "=", "$", "chunk", ";", "}", "$", "newUrl", ".=", "'/'", ".", "$", "newChunk", ";", "}", "return", "preg_replace", "(", "'/\\/\\//'", ",", "'/'", ",", "$", "newUrl", ")", ";", "}" ]
Change the mapped values in key map into the intended URL ex: $keyMap = array( '{id}' => 123, 'another' => 'test', '{extraId}' => 321 ); URL: before: '/some/url/with/another/and/{id}' after: '/some/url/with/test/and/123' @param string $url URL to update key mapped values @return string Updated URL
[ "Change", "the", "mapped", "values", "in", "key", "map", "into", "the", "intended", "URL" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/EzContext.php#L226-L241
ezsystems/BehatBundle
Context/EzContext.php
EzContext.getCredentialsFor
protected function getCredentialsFor( $roleIdentifier ) { $roleService = $this->getRepository()->getRoleService(); // First try to load role, throws exception if not found. $role = $this->getRepository()->sudo( function() use ( $roleService, $roleIdentifier ) { // make sure role name starts with uppercase as this is what default setup provides if ($roleIdentifier !== ucfirst($roleIdentifier)) { @trigger_error( "'{$roleIdentifier}' role name should start with uppercase letter", E_USER_DEPRECATED ); } return $roleService->loadRoleByIdentifier(ucfirst($roleIdentifier)); } ); // create a new user, uses 'User' trait $username = $this->findNonExistingUserName(); $password = $this->getUserManager()->getDefaultPassword(); $email = "${username}@ez.no"; $user = $this->getUserManager()->ensureUserExists( $username, $email, $password ); // Assign role to created user (without limitation) $this->getRepository()->sudo( function() use ( $roleService, $role, $user ) { return $roleService->assignRoleToUser( $role, $user ); } ); return array( 'login' => $username, 'password' => $password, ); }
php
protected function getCredentialsFor( $roleIdentifier ) { $roleService = $this->getRepository()->getRoleService(); // First try to load role, throws exception if not found. $role = $this->getRepository()->sudo( function() use ( $roleService, $roleIdentifier ) { // make sure role name starts with uppercase as this is what default setup provides if ($roleIdentifier !== ucfirst($roleIdentifier)) { @trigger_error( "'{$roleIdentifier}' role name should start with uppercase letter", E_USER_DEPRECATED ); } return $roleService->loadRoleByIdentifier(ucfirst($roleIdentifier)); } ); // create a new user, uses 'User' trait $username = $this->findNonExistingUserName(); $password = $this->getUserManager()->getDefaultPassword(); $email = "${username}@ez.no"; $user = $this->getUserManager()->ensureUserExists( $username, $email, $password ); // Assign role to created user (without limitation) $this->getRepository()->sudo( function() use ( $roleService, $role, $user ) { return $roleService->assignRoleToUser( $role, $user ); } ); return array( 'login' => $username, 'password' => $password, ); }
[ "protected", "function", "getCredentialsFor", "(", "$", "roleIdentifier", ")", "{", "$", "roleService", "=", "$", "this", "->", "getRepository", "(", ")", "->", "getRoleService", "(", ")", ";", "// First try to load role, throws exception if not found.", "$", "role", "=", "$", "this", "->", "getRepository", "(", ")", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "roleService", ",", "$", "roleIdentifier", ")", "{", "// make sure role name starts with uppercase as this is what default setup provides", "if", "(", "$", "roleIdentifier", "!==", "ucfirst", "(", "$", "roleIdentifier", ")", ")", "{", "@", "trigger_error", "(", "\"'{$roleIdentifier}' role name should start with uppercase letter\"", ",", "E_USER_DEPRECATED", ")", ";", "}", "return", "$", "roleService", "->", "loadRoleByIdentifier", "(", "ucfirst", "(", "$", "roleIdentifier", ")", ")", ";", "}", ")", ";", "// create a new user, uses 'User' trait", "$", "username", "=", "$", "this", "->", "findNonExistingUserName", "(", ")", ";", "$", "password", "=", "$", "this", "->", "getUserManager", "(", ")", "->", "getDefaultPassword", "(", ")", ";", "$", "email", "=", "\"${username}@ez.no\"", ";", "$", "user", "=", "$", "this", "->", "getUserManager", "(", ")", "->", "ensureUserExists", "(", "$", "username", ",", "$", "email", ",", "$", "password", ")", ";", "// Assign role to created user (without limitation)", "$", "this", "->", "getRepository", "(", ")", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "roleService", ",", "$", "role", ",", "$", "user", ")", "{", "return", "$", "roleService", "->", "assignRoleToUser", "(", "$", "role", ",", "$", "user", ")", ";", "}", ")", ";", "return", "array", "(", "'login'", "=>", "$", "username", ",", "'password'", "=>", "$", "password", ",", ")", ";", "}" ]
Get credentials for a specific role @uses \EzSystems\BehatBundle\Context\Object\User @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException @param string $role Role intended for testing @return array Associative with 'login' and 'password'
[ "Get", "credentials", "for", "a", "specific", "role" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/EzContext.php#L253-L294
ezsystems/BehatBundle
ObjectManager/UserGroup.php
UserGroup.loadUserGroup
public function loadUserGroup( $id ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $userService = $repository->getUserService(); $userGroup = $repository->sudo( function() use( $id, $userService ) { return $userService->loadUserGroup( $id ); } ); return $userGroup; }
php
public function loadUserGroup( $id ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $userService = $repository->getUserService(); $userGroup = $repository->sudo( function() use( $id, $userService ) { return $userService->loadUserGroup( $id ); } ); return $userGroup; }
[ "public", "function", "loadUserGroup", "(", "$", "id", ")", "{", "/** @var \\eZ\\Publish\\API\\Repository\\Repository $repository */", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "userService", "=", "$", "repository", "->", "getUserService", "(", ")", ";", "$", "userGroup", "=", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "id", ",", "$", "userService", ")", "{", "return", "$", "userService", "->", "loadUserGroup", "(", "$", "id", ")", ";", "}", ")", ";", "return", "$", "userGroup", ";", "}" ]
Load a User Group by id @param int $id User Group content identifier @return \eZ\Publish\API\Repository\Values\User\UserGroup
[ "Load", "a", "User", "Group", "by", "id" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/UserGroup.php#L36-L50
ezsystems/BehatBundle
ObjectManager/UserGroup.php
UserGroup.createUserGroup
public function createUserGroup( $name, $parentGroup = null ) { $repository = $this->getRepository(); $userService = $repository->getUserService(); if ( !$parentGroup ) { $parentGroup = $this->loadUserGroup( self::USERGROUP_ROOT_CONTENT_ID ); } $userGroup = $repository->sudo( function() use( $name, $parentGroup, $userService ) { $userGroupCreateStruct = $userService->newUserGroupCreateStruct( 'eng-GB' ); $userGroupCreateStruct->setField( 'name', $name ); return $userService->createUserGroup( $userGroupCreateStruct, $parentGroup ); } ); $this->addObjectToList( $userGroup ); return $userGroup; }
php
public function createUserGroup( $name, $parentGroup = null ) { $repository = $this->getRepository(); $userService = $repository->getUserService(); if ( !$parentGroup ) { $parentGroup = $this->loadUserGroup( self::USERGROUP_ROOT_CONTENT_ID ); } $userGroup = $repository->sudo( function() use( $name, $parentGroup, $userService ) { $userGroupCreateStruct = $userService->newUserGroupCreateStruct( 'eng-GB' ); $userGroupCreateStruct->setField( 'name', $name ); return $userService->createUserGroup( $userGroupCreateStruct, $parentGroup ); } ); $this->addObjectToList( $userGroup ); return $userGroup; }
[ "public", "function", "createUserGroup", "(", "$", "name", ",", "$", "parentGroup", "=", "null", ")", "{", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "userService", "=", "$", "repository", "->", "getUserService", "(", ")", ";", "if", "(", "!", "$", "parentGroup", ")", "{", "$", "parentGroup", "=", "$", "this", "->", "loadUserGroup", "(", "self", "::", "USERGROUP_ROOT_CONTENT_ID", ")", ";", "}", "$", "userGroup", "=", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "name", ",", "$", "parentGroup", ",", "$", "userService", ")", "{", "$", "userGroupCreateStruct", "=", "$", "userService", "->", "newUserGroupCreateStruct", "(", "'eng-GB'", ")", ";", "$", "userGroupCreateStruct", "->", "setField", "(", "'name'", ",", "$", "name", ")", ";", "return", "$", "userService", "->", "createUserGroup", "(", "$", "userGroupCreateStruct", ",", "$", "parentGroup", ")", ";", "}", ")", ";", "$", "this", "->", "addObjectToList", "(", "$", "userGroup", ")", ";", "return", "$", "userGroup", ";", "}" ]
Create new User Group inside existing parent User Group @param string $name User Group name @param \eZ\Publish\API\Repository\Values\User\UserGroup $parentGroup (optional) parent user group, defaults to UserGroup "/Users" @return \eZ\Publish\API\Repository\Values\User\UserGroup
[ "Create", "new", "User", "Group", "inside", "existing", "parent", "User", "Group" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/UserGroup.php#L94-L114
ezsystems/BehatBundle
ObjectManager/UserGroup.php
UserGroup.ensureUserGroupExists
public function ensureUserGroupExists( $name, $parentGroupName = null ) { if ( $parentGroupName ) { // find parent group name $searchResults = $this->searchUserGroups( $parentGroupName ); if ( !empty( $searchResults ) ) { $parentGroup = $this->loadUserGroup( $searchResults[0]->valueObject->contentInfo->id ); $parentGroupLocationId = $searchResults[0]->valueObject->contentInfo->mainLocationId; } else { // parent group not found, create it $parentGroup = $this->createUserGroup( $parentGroupName ); $parentGroupLocationId = $parentGroup->getVersionInfo()->getContentInfo()->mainLocationId; } } else { $parentGroup = null; $parentGroupLocationId = null; } $searchResults = $this->searchUserGroups( $name, $parentGroupLocationId ); if ( !empty( $searchResults ) ) { // found existing child group, return it return $this->loadUserGroup( $searchResults[0]->valueObject->contentInfo->id ); } // else, did not find existing group - create one with given name. return $this->createUserGroup( $name, $parentGroup ); }
php
public function ensureUserGroupExists( $name, $parentGroupName = null ) { if ( $parentGroupName ) { // find parent group name $searchResults = $this->searchUserGroups( $parentGroupName ); if ( !empty( $searchResults ) ) { $parentGroup = $this->loadUserGroup( $searchResults[0]->valueObject->contentInfo->id ); $parentGroupLocationId = $searchResults[0]->valueObject->contentInfo->mainLocationId; } else { // parent group not found, create it $parentGroup = $this->createUserGroup( $parentGroupName ); $parentGroupLocationId = $parentGroup->getVersionInfo()->getContentInfo()->mainLocationId; } } else { $parentGroup = null; $parentGroupLocationId = null; } $searchResults = $this->searchUserGroups( $name, $parentGroupLocationId ); if ( !empty( $searchResults ) ) { // found existing child group, return it return $this->loadUserGroup( $searchResults[0]->valueObject->contentInfo->id ); } // else, did not find existing group - create one with given name. return $this->createUserGroup( $name, $parentGroup ); }
[ "public", "function", "ensureUserGroupExists", "(", "$", "name", ",", "$", "parentGroupName", "=", "null", ")", "{", "if", "(", "$", "parentGroupName", ")", "{", "// find parent group name", "$", "searchResults", "=", "$", "this", "->", "searchUserGroups", "(", "$", "parentGroupName", ")", ";", "if", "(", "!", "empty", "(", "$", "searchResults", ")", ")", "{", "$", "parentGroup", "=", "$", "this", "->", "loadUserGroup", "(", "$", "searchResults", "[", "0", "]", "->", "valueObject", "->", "contentInfo", "->", "id", ")", ";", "$", "parentGroupLocationId", "=", "$", "searchResults", "[", "0", "]", "->", "valueObject", "->", "contentInfo", "->", "mainLocationId", ";", "}", "else", "{", "// parent group not found, create it", "$", "parentGroup", "=", "$", "this", "->", "createUserGroup", "(", "$", "parentGroupName", ")", ";", "$", "parentGroupLocationId", "=", "$", "parentGroup", "->", "getVersionInfo", "(", ")", "->", "getContentInfo", "(", ")", "->", "mainLocationId", ";", "}", "}", "else", "{", "$", "parentGroup", "=", "null", ";", "$", "parentGroupLocationId", "=", "null", ";", "}", "$", "searchResults", "=", "$", "this", "->", "searchUserGroups", "(", "$", "name", ",", "$", "parentGroupLocationId", ")", ";", "if", "(", "!", "empty", "(", "$", "searchResults", ")", ")", "{", "// found existing child group, return it", "return", "$", "this", "->", "loadUserGroup", "(", "$", "searchResults", "[", "0", "]", "->", "valueObject", "->", "contentInfo", "->", "id", ")", ";", "}", "// else, did not find existing group - create one with given name.", "return", "$", "this", "->", "createUserGroup", "(", "$", "name", ",", "$", "parentGroup", ")", ";", "}" ]
Make sure a User Group with name $name exists in parent group @param string $name User Group name @param string $parentGroupName (optional) name of the parent group to check @return \eZ\Publish\API\Repository\Values\User\UserGroup
[ "Make", "sure", "a", "User", "Group", "with", "name", "$name", "exists", "in", "parent", "group" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/UserGroup.php#L124-L157
ezsystems/BehatBundle
ObjectManager/UserGroup.php
UserGroup.ensureUserGroupDoesntExist
public function ensureUserGroupDoesntExist( $name, $parentGroupName = null ) { $repository = $this->getRepository(); $userService = $repository->getUserService(); if ( $parentGroupName ) { // find parent group name $searchResults = $this->searchUserGroups( $parentGroupName ); if ( empty( $searchResults ) ) { throw new \Exception( "Could not find parent User Group with name '$name'." ); } $parentGroupLocationId = $searchResults[0]->valueObject->contentInfo->mainLocationId; } else { $parentGroupLocationId = null; } $searchResults = $this->searchUserGroups( $name, $parentGroupLocationId ); if ( empty( $searchResults ) ) { // no existing User Groups found return; } // else, remove existing groups $repository->sudo( function() use( $searchResults, $userService ) { foreach ( $searchResults as $searchHit ) { //Attempt to delete User Group try { $userGroup = $userService->loadUserGroup( $searchHit->valueObject->contentInfo->id ); $userService->deleteUserGroup( $userGroup ); } catch ( ApiExceptions\NotFoundException $e ) { // nothing to do } } } ); }
php
public function ensureUserGroupDoesntExist( $name, $parentGroupName = null ) { $repository = $this->getRepository(); $userService = $repository->getUserService(); if ( $parentGroupName ) { // find parent group name $searchResults = $this->searchUserGroups( $parentGroupName ); if ( empty( $searchResults ) ) { throw new \Exception( "Could not find parent User Group with name '$name'." ); } $parentGroupLocationId = $searchResults[0]->valueObject->contentInfo->mainLocationId; } else { $parentGroupLocationId = null; } $searchResults = $this->searchUserGroups( $name, $parentGroupLocationId ); if ( empty( $searchResults ) ) { // no existing User Groups found return; } // else, remove existing groups $repository->sudo( function() use( $searchResults, $userService ) { foreach ( $searchResults as $searchHit ) { //Attempt to delete User Group try { $userGroup = $userService->loadUserGroup( $searchHit->valueObject->contentInfo->id ); $userService->deleteUserGroup( $userGroup ); } catch ( ApiExceptions\NotFoundException $e ) { // nothing to do } } } ); }
[ "public", "function", "ensureUserGroupDoesntExist", "(", "$", "name", ",", "$", "parentGroupName", "=", "null", ")", "{", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "userService", "=", "$", "repository", "->", "getUserService", "(", ")", ";", "if", "(", "$", "parentGroupName", ")", "{", "// find parent group name", "$", "searchResults", "=", "$", "this", "->", "searchUserGroups", "(", "$", "parentGroupName", ")", ";", "if", "(", "empty", "(", "$", "searchResults", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could not find parent User Group with name '$name'.\"", ")", ";", "}", "$", "parentGroupLocationId", "=", "$", "searchResults", "[", "0", "]", "->", "valueObject", "->", "contentInfo", "->", "mainLocationId", ";", "}", "else", "{", "$", "parentGroupLocationId", "=", "null", ";", "}", "$", "searchResults", "=", "$", "this", "->", "searchUserGroups", "(", "$", "name", ",", "$", "parentGroupLocationId", ")", ";", "if", "(", "empty", "(", "$", "searchResults", ")", ")", "{", "// no existing User Groups found", "return", ";", "}", "// else, remove existing groups", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "searchResults", ",", "$", "userService", ")", "{", "foreach", "(", "$", "searchResults", "as", "$", "searchHit", ")", "{", "//Attempt to delete User Group", "try", "{", "$", "userGroup", "=", "$", "userService", "->", "loadUserGroup", "(", "$", "searchHit", "->", "valueObject", "->", "contentInfo", "->", "id", ")", ";", "$", "userService", "->", "deleteUserGroup", "(", "$", "userGroup", ")", ";", "}", "catch", "(", "ApiExceptions", "\\", "NotFoundException", "$", "e", ")", "{", "// nothing to do", "}", "}", "}", ")", ";", "}" ]
Make sure a User Group with name $name doesn't exist in parent group @param string $name name of the User Group to check/remove @param string $parentGroupName (optional) parent group to search in
[ "Make", "sure", "a", "User", "Group", "with", "name", "$name", "doesn", "t", "exist", "in", "parent", "group" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/UserGroup.php#L165-L212
ezsystems/BehatBundle
ObjectManager/UserGroup.php
UserGroup.checkUserGroupExistence
public function checkUserGroupExistence( $id ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $userService = $repository->getUserService(); return $repository->sudo( function() use( $id, $userService ) { // attempt to load the content type group with the id try { $userService->loadUserGroup( $id ); return true; } catch ( ApiExceptions\NotFoundException $e ) { return false; } } ); }
php
public function checkUserGroupExistence( $id ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $userService = $repository->getUserService(); return $repository->sudo( function() use( $id, $userService ) { // attempt to load the content type group with the id try { $userService->loadUserGroup( $id ); return true; } catch ( ApiExceptions\NotFoundException $e ) { return false; } } ); }
[ "public", "function", "checkUserGroupExistence", "(", "$", "id", ")", "{", "/** @var \\eZ\\Publish\\API\\Repository\\Repository $repository */", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "userService", "=", "$", "repository", "->", "getUserService", "(", ")", ";", "return", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "id", ",", "$", "userService", ")", "{", "// attempt to load the content type group with the id", "try", "{", "$", "userService", "->", "loadUserGroup", "(", "$", "id", ")", ";", "return", "true", ";", "}", "catch", "(", "ApiExceptions", "\\", "NotFoundException", "$", "e", ")", "{", "return", "false", ";", "}", "}", ")", ";", "}" ]
Checks if the UserGroup with $id exists @param string $id Identifier of the possible content @return boolean true if it exists, false if not
[ "Checks", "if", "the", "UserGroup", "with", "$id", "exists" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/UserGroup.php#L221-L242
ezsystems/BehatBundle
ObjectManager/UserGroup.php
UserGroup.checkUserGroupExistenceByName
public function checkUserGroupExistenceByName( $name, $parentGroupName = null ) { if ( $parentGroupName ) { // find parent group name $searchResults = $this->searchUserGroups( $parentGroupName ); if ( empty( $searchResults ) ) { throw new \Exception( "Could not find parent User Group with name '$parentGroupName'." ); } $parentGroup = $this->loadUserGroup( $searchResults[0]->valueObject->contentInfo->id ); $parentGroupLocationId = $searchResults[0]->valueObject->contentInfo->mainLocationId; $searchResults = $this->searchUserGroups( $name, $parentGroupLocationId ); } else { $searchResults = $this->searchUserGroups( $name ); } return empty( $searchResults ) ? false : true; }
php
public function checkUserGroupExistenceByName( $name, $parentGroupName = null ) { if ( $parentGroupName ) { // find parent group name $searchResults = $this->searchUserGroups( $parentGroupName ); if ( empty( $searchResults ) ) { throw new \Exception( "Could not find parent User Group with name '$parentGroupName'." ); } $parentGroup = $this->loadUserGroup( $searchResults[0]->valueObject->contentInfo->id ); $parentGroupLocationId = $searchResults[0]->valueObject->contentInfo->mainLocationId; $searchResults = $this->searchUserGroups( $name, $parentGroupLocationId ); } else { $searchResults = $this->searchUserGroups( $name ); } return empty( $searchResults ) ? false : true; }
[ "public", "function", "checkUserGroupExistenceByName", "(", "$", "name", ",", "$", "parentGroupName", "=", "null", ")", "{", "if", "(", "$", "parentGroupName", ")", "{", "// find parent group name", "$", "searchResults", "=", "$", "this", "->", "searchUserGroups", "(", "$", "parentGroupName", ")", ";", "if", "(", "empty", "(", "$", "searchResults", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Could not find parent User Group with name '$parentGroupName'.\"", ")", ";", "}", "$", "parentGroup", "=", "$", "this", "->", "loadUserGroup", "(", "$", "searchResults", "[", "0", "]", "->", "valueObject", "->", "contentInfo", "->", "id", ")", ";", "$", "parentGroupLocationId", "=", "$", "searchResults", "[", "0", "]", "->", "valueObject", "->", "contentInfo", "->", "mainLocationId", ";", "$", "searchResults", "=", "$", "this", "->", "searchUserGroups", "(", "$", "name", ",", "$", "parentGroupLocationId", ")", ";", "}", "else", "{", "$", "searchResults", "=", "$", "this", "->", "searchUserGroups", "(", "$", "name", ")", ";", "}", "return", "empty", "(", "$", "searchResults", ")", "?", "false", ":", "true", ";", "}" ]
Checks if the UserGroup with name $name exists @param string $name User Group name @return boolean true if it exists, false if not
[ "Checks", "if", "the", "UserGroup", "with", "name", "$name", "exists" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/UserGroup.php#L251-L271
ezsystems/BehatBundle
ObjectManager/UserGroup.php
UserGroup.destroy
protected function destroy( ValueObject $object ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $repository->sudo( function() use( $repository, $object ) { $userService = $repository->getUserService(); try { $objectToBeRemoved = $userService->loadUserGroup( $object->id ); $userService->deleteUserGroup( $objectToBeRemoved ); } catch ( ApiExceptions\NotFoundException $e ) { // nothing to do } } ); }
php
protected function destroy( ValueObject $object ) { /** @var \eZ\Publish\API\Repository\Repository $repository */ $repository = $this->getRepository(); $repository->sudo( function() use( $repository, $object ) { $userService = $repository->getUserService(); try { $objectToBeRemoved = $userService->loadUserGroup( $object->id ); $userService->deleteUserGroup( $objectToBeRemoved ); } catch ( ApiExceptions\NotFoundException $e ) { // nothing to do } } ); }
[ "protected", "function", "destroy", "(", "ValueObject", "$", "object", ")", "{", "/** @var \\eZ\\Publish\\API\\Repository\\Repository $repository */", "$", "repository", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "repository", "->", "sudo", "(", "function", "(", ")", "use", "(", "$", "repository", ",", "$", "object", ")", "{", "$", "userService", "=", "$", "repository", "->", "getUserService", "(", ")", ";", "try", "{", "$", "objectToBeRemoved", "=", "$", "userService", "->", "loadUserGroup", "(", "$", "object", "->", "id", ")", ";", "$", "userService", "->", "deleteUserGroup", "(", "$", "objectToBeRemoved", ")", ";", "}", "catch", "(", "ApiExceptions", "\\", "NotFoundException", "$", "e", ")", "{", "// nothing to do", "}", "}", ")", ";", "}" ]
[destroy description] @param ValueObject $object [description] @return [type] [description]
[ "[", "destroy", "description", "]" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/UserGroup.php#L278-L297
ezsystems/BehatBundle
Helper/Gherkin.php
Gherkin.convertTableToArrayOfData
static function convertTableToArrayOfData( TableNode $table, array $data = null ) { if( empty( $data ) ) $data = array(); // prepare given data $i = 0; $rows = $table->getRows(); $headers = array_shift( $rows ); // this is needed to take the first row ( readability only ) foreach ( $rows as $row ) { $count = count( array_filter( $row ) ); // check if the field is supposed to be empty // or it simply has only 1 element if ( $count == 1 && count( $row ) && !method_exists( $table, "getCleanRows" ) ) { $count = 2; } $key = $row[0]; switch( $count ){ // case 1 is for the cases where there is an Examples table and it // gets the values from there, so the field name/id shold be on the // examples table (ex: "| <field_name> |") case 1: $value = $key; $aux = $table->getCleanRows(); $k = ( count( $aux ) === count( array_keys( $table ) ) ) ? $i : $i + 1; $key = str_replace( array( '<', '>' ), array( '', '' ), $aux[$k][0] ); break; // case 2 is the most simple case where "| field1 | as value 1 |" case 2: if ( count( $headers ) === 1 ) { $value = $row[0]; } else { $value = $row[1]; } break; // this is for the cases where there are several values for the same // field (ex: author) and the gherkin table should look like default: $value = array_slice( $row, 1 ); break; } $data[$key] = $value; $i++; } // if its empty return false otherwise return the array with data return empty( $data ) ? false : $data; }
php
static function convertTableToArrayOfData( TableNode $table, array $data = null ) { if( empty( $data ) ) $data = array(); // prepare given data $i = 0; $rows = $table->getRows(); $headers = array_shift( $rows ); // this is needed to take the first row ( readability only ) foreach ( $rows as $row ) { $count = count( array_filter( $row ) ); // check if the field is supposed to be empty // or it simply has only 1 element if ( $count == 1 && count( $row ) && !method_exists( $table, "getCleanRows" ) ) { $count = 2; } $key = $row[0]; switch( $count ){ // case 1 is for the cases where there is an Examples table and it // gets the values from there, so the field name/id shold be on the // examples table (ex: "| <field_name> |") case 1: $value = $key; $aux = $table->getCleanRows(); $k = ( count( $aux ) === count( array_keys( $table ) ) ) ? $i : $i + 1; $key = str_replace( array( '<', '>' ), array( '', '' ), $aux[$k][0] ); break; // case 2 is the most simple case where "| field1 | as value 1 |" case 2: if ( count( $headers ) === 1 ) { $value = $row[0]; } else { $value = $row[1]; } break; // this is for the cases where there are several values for the same // field (ex: author) and the gherkin table should look like default: $value = array_slice( $row, 1 ); break; } $data[$key] = $value; $i++; } // if its empty return false otherwise return the array with data return empty( $data ) ? false : $data; }
[ "static", "function", "convertTableToArrayOfData", "(", "TableNode", "$", "table", ",", "array", "$", "data", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "$", "data", "=", "array", "(", ")", ";", "// prepare given data", "$", "i", "=", "0", ";", "$", "rows", "=", "$", "table", "->", "getRows", "(", ")", ";", "$", "headers", "=", "array_shift", "(", "$", "rows", ")", ";", "// this is needed to take the first row ( readability only )", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "$", "count", "=", "count", "(", "array_filter", "(", "$", "row", ")", ")", ";", "// check if the field is supposed to be empty", "// or it simply has only 1 element", "if", "(", "$", "count", "==", "1", "&&", "count", "(", "$", "row", ")", "&&", "!", "method_exists", "(", "$", "table", ",", "\"getCleanRows\"", ")", ")", "{", "$", "count", "=", "2", ";", "}", "$", "key", "=", "$", "row", "[", "0", "]", ";", "switch", "(", "$", "count", ")", "{", "// case 1 is for the cases where there is an Examples table and it", "// gets the values from there, so the field name/id shold be on the", "// examples table (ex: \"| <field_name> |\")", "case", "1", ":", "$", "value", "=", "$", "key", ";", "$", "aux", "=", "$", "table", "->", "getCleanRows", "(", ")", ";", "$", "k", "=", "(", "count", "(", "$", "aux", ")", "===", "count", "(", "array_keys", "(", "$", "table", ")", ")", ")", "?", "$", "i", ":", "$", "i", "+", "1", ";", "$", "key", "=", "str_replace", "(", "array", "(", "'<'", ",", "'>'", ")", ",", "array", "(", "''", ",", "''", ")", ",", "$", "aux", "[", "$", "k", "]", "[", "0", "]", ")", ";", "break", ";", "// case 2 is the most simple case where \"| field1 | as value 1 |\"", "case", "2", ":", "if", "(", "count", "(", "$", "headers", ")", "===", "1", ")", "{", "$", "value", "=", "$", "row", "[", "0", "]", ";", "}", "else", "{", "$", "value", "=", "$", "row", "[", "1", "]", ";", "}", "break", ";", "// this is for the cases where there are several values for the same", "// field (ex: author) and the gherkin table should look like", "default", ":", "$", "value", "=", "array_slice", "(", "$", "row", ",", "1", ")", ";", "break", ";", "}", "$", "data", "[", "$", "key", "]", "=", "$", "value", ";", "$", "i", "++", ";", "}", "// if its empty return false otherwise return the array with data", "return", "empty", "(", "$", "data", ")", "?", "false", ":", "$", "data", ";", "}" ]
This function will convert Gherkin tables into structure array of data if Gherkin table look like | field | value1 | value2 | ... | valueN | | field1 | single value 1 | | ... | | | field2 | single value 2 | | ... | | | field3 | multiple | value | ... | here | the returned array should look like: $data = array( "field1" => "single value 1", "field2" => "single value 2", "field3" => array( "multiple", "value", ... ,"here"), ... ); or if the Gherkin table values comes from a examples table: | value | | <field1> | | <field2> | | ... | | <fieldN> | Examples: | <field1> | <field2> | ... | <fieldN> | | value1 | value2 | ... | valueN | the returned array should look like $data = array( "field1" => "value1", "field2" => "value2", ... "fieldN" => "valueN", ); @param \Behat\Gherkin\Node\TableNode $table The Gherkin table to extract the values @param array $data If passed the values are concatenated/updated @return false|array @todo Define better the intended results in all (possible) variations
[ "This", "function", "will", "convert", "Gherkin", "tables", "into", "structure", "array", "of", "data" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Helper/Gherkin.php#L63-L122
ezsystems/BehatBundle
ObjectManager/Base.php
Base.setContext
protected function setContext( KernelAwareContext $context ) { $this->context = $context; $this->kernel = $context->getKernel(); }
php
protected function setContext( KernelAwareContext $context ) { $this->context = $context; $this->kernel = $context->getKernel(); }
[ "protected", "function", "setContext", "(", "KernelAwareContext", "$", "context", ")", "{", "$", "this", "->", "context", "=", "$", "context", ";", "$", "this", "->", "kernel", "=", "$", "context", "->", "getKernel", "(", ")", ";", "}" ]
Set kernel @param \Symfony\Component\HttpKernel\KernelInterface $kernel
[ "Set", "kernel" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/Base.php#L45-L49
ezsystems/BehatBundle
ObjectManager/Base.php
Base.instance
static public function instance( KernelAwareContext $context ) { static $instance = null; if ( $instance === null ) { $class = get_called_class(); $instance = new $class(); $instance->setContext( $context ); } return $instance; }
php
static public function instance( KernelAwareContext $context ) { static $instance = null; if ( $instance === null ) { $class = get_called_class(); $instance = new $class(); $instance->setContext( $context ); } return $instance; }
[ "static", "public", "function", "instance", "(", "KernelAwareContext", "$", "context", ")", "{", "static", "$", "instance", "=", "null", ";", "if", "(", "$", "instance", "===", "null", ")", "{", "$", "class", "=", "get_called_class", "(", ")", ";", "$", "instance", "=", "new", "$", "class", "(", ")", ";", "$", "instance", "->", "setContext", "(", "$", "context", ")", ";", "}", "return", "$", "instance", ";", "}" ]
Get instance These objects should be singletons, so Object::instance() should take care of returning the instance and create it when it's not created @param \Symfony\Component\HttpKernel\KernelInterface @return \EzSystems\BehatBundle\ObjectManager\Base
[ "Get", "instance" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/Base.php#L61-L72
ezsystems/BehatBundle
ObjectManager/Base.php
Base.clean
public function clean() { foreach ( $this->createdObjects as $object ) { $this->destroy( $object ); } $this->createdObjects = array(); }
php
public function clean() { foreach ( $this->createdObjects as $object ) { $this->destroy( $object ); } $this->createdObjects = array(); }
[ "public", "function", "clean", "(", ")", "{", "foreach", "(", "$", "this", "->", "createdObjects", "as", "$", "object", ")", "{", "$", "this", "->", "destroy", "(", "$", "object", ")", ";", "}", "$", "this", "->", "createdObjects", "=", "array", "(", ")", ";", "}" ]
Destroy/remove/delete all created objects (from given steps)
[ "Destroy", "/", "remove", "/", "delete", "all", "created", "objects", "(", "from", "given", "steps", ")" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/ObjectManager/Base.php#L122-L130
ezsystems/BehatBundle
Context/Browser/Context.php
Context.getPathByPageIdentifier
public function getPathByPageIdentifier( $pageIdentifier ) { if ( !isset( $this->pageIdentifierMap[strtolower( $pageIdentifier )] ) ) { throw new \RuntimeException( "Unknown page identifier '{$pageIdentifier}'." ); } return $this->pageIdentifierMap[strtolower( $pageIdentifier )]; }
php
public function getPathByPageIdentifier( $pageIdentifier ) { if ( !isset( $this->pageIdentifierMap[strtolower( $pageIdentifier )] ) ) { throw new \RuntimeException( "Unknown page identifier '{$pageIdentifier}'." ); } return $this->pageIdentifierMap[strtolower( $pageIdentifier )]; }
[ "public", "function", "getPathByPageIdentifier", "(", "$", "pageIdentifier", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "pageIdentifierMap", "[", "strtolower", "(", "$", "pageIdentifier", ")", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Unknown page identifier '{$pageIdentifier}'.\"", ")", ";", "}", "return", "$", "this", "->", "pageIdentifierMap", "[", "strtolower", "(", "$", "pageIdentifier", ")", "]", ";", "}" ]
Returns the path associated with $pageIdentifier @param string $pageIdentifier @return string URL path @throws \RuntimeException If $pageIdentifier is not set
[ "Returns", "the", "path", "associated", "with", "$pageIdentifier" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L103-L111
ezsystems/BehatBundle
Context/Browser/Context.php
Context.concatTagsWithXpath
public function concatTagsWithXpath( array $tags, $xpath = null ) { $finalXpath = ""; for ( $i = 0; !empty( $tags[$i] ); $i++ ) { $finalXpath .= "//{$tags[$i]}$xpath"; if ( !empty( $tags[$i + 1] ) ) { $finalXpath .= " | "; } } return $finalXpath; }
php
public function concatTagsWithXpath( array $tags, $xpath = null ) { $finalXpath = ""; for ( $i = 0; !empty( $tags[$i] ); $i++ ) { $finalXpath .= "//{$tags[$i]}$xpath"; if ( !empty( $tags[$i + 1] ) ) { $finalXpath .= " | "; } } return $finalXpath; }
[ "public", "function", "concatTagsWithXpath", "(", "array", "$", "tags", ",", "$", "xpath", "=", "null", ")", "{", "$", "finalXpath", "=", "\"\"", ";", "for", "(", "$", "i", "=", "0", ";", "!", "empty", "(", "$", "tags", "[", "$", "i", "]", ")", ";", "$", "i", "++", ")", "{", "$", "finalXpath", ".=", "\"//{$tags[$i]}$xpath\"", ";", "if", "(", "!", "empty", "(", "$", "tags", "[", "$", "i", "+", "1", "]", ")", ")", "{", "$", "finalXpath", ".=", "\" | \"", ";", "}", "}", "return", "$", "finalXpath", ";", "}" ]
This should be seen as a complement to self::getTagsFor() where it will get the respective tags from there and will make a valid Xpath string with all OR's needed @param array $tags Array of tags strings (ex: array( "a", "p", "h3", "table" ) ) @param string $xpath String to be concatenated to each tag @return string Final xpath
[ "This", "should", "be", "seen", "as", "a", "complement", "to", "self", "::", "getTagsFor", "()", "where", "it", "will", "get", "the", "respective", "tags", "from", "there", "and", "will", "make", "a", "valid", "Xpath", "string", "with", "all", "OR", "s", "needed" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L123-L136
ezsystems/BehatBundle
Context/Browser/Context.php
Context.getUrlWithoutQueryString
public function getUrlWithoutQueryString( $url ) { if ( strpos( $url, '?' ) !== false ) { $url = substr( $url, 0, strpos( $url, '?' ) ); } return $url; }
php
public function getUrlWithoutQueryString( $url ) { if ( strpos( $url, '?' ) !== false ) { $url = substr( $url, 0, strpos( $url, '?' ) ); } return $url; }
[ "public", "function", "getUrlWithoutQueryString", "(", "$", "url", ")", "{", "if", "(", "strpos", "(", "$", "url", ",", "'?'", ")", "!==", "false", ")", "{", "$", "url", "=", "substr", "(", "$", "url", ",", "0", ",", "strpos", "(", "$", "url", ",", "'?'", ")", ")", ";", "}", "return", "$", "url", ";", "}" ]
Returns $url without its query string @param string $url @return string Complete url without the query string
[ "Returns", "$url", "without", "its", "query", "string" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L172-L180
ezsystems/BehatBundle
Context/Browser/Context.php
Context.checkLinksExistence
protected function checkLinksExistence( array $links, array $available, $checkOrder = false ) { $i = $passed = 0; $last = ''; $messageAfter = ''; foreach ( $links as $link ) { if ( ! $checkOrder ) { $i = 0; } // find the object while ( !empty( $available[$i] ) && strpos( $available[$i]->getText(), $link ) === false ) $i++; if ( $checkOrder && ! empty( $last ) ) { $messageAfter = "after '$last'"; } // check if the link was found or the $i >= $count $test = true; if ( empty( $available[$i] ) ) { $test = false; } Assertion::assertTrue( $test, "Couldn't find '$link'" . $messageAfter ); $passed++; $last = $link; } Assertion::assertEquals( count( $links ), $passed, "Expected to evaluate '" . count( $links ) . "' links evaluated '{$passed}'" ); }
php
protected function checkLinksExistence( array $links, array $available, $checkOrder = false ) { $i = $passed = 0; $last = ''; $messageAfter = ''; foreach ( $links as $link ) { if ( ! $checkOrder ) { $i = 0; } // find the object while ( !empty( $available[$i] ) && strpos( $available[$i]->getText(), $link ) === false ) $i++; if ( $checkOrder && ! empty( $last ) ) { $messageAfter = "after '$last'"; } // check if the link was found or the $i >= $count $test = true; if ( empty( $available[$i] ) ) { $test = false; } Assertion::assertTrue( $test, "Couldn't find '$link'" . $messageAfter ); $passed++; $last = $link; } Assertion::assertEquals( count( $links ), $passed, "Expected to evaluate '" . count( $links ) . "' links evaluated '{$passed}'" ); }
[ "protected", "function", "checkLinksExistence", "(", "array", "$", "links", ",", "array", "$", "available", ",", "$", "checkOrder", "=", "false", ")", "{", "$", "i", "=", "$", "passed", "=", "0", ";", "$", "last", "=", "''", ";", "$", "messageAfter", "=", "''", ";", "foreach", "(", "$", "links", "as", "$", "link", ")", "{", "if", "(", "!", "$", "checkOrder", ")", "{", "$", "i", "=", "0", ";", "}", "// find the object", "while", "(", "!", "empty", "(", "$", "available", "[", "$", "i", "]", ")", "&&", "strpos", "(", "$", "available", "[", "$", "i", "]", "->", "getText", "(", ")", ",", "$", "link", ")", "===", "false", ")", "$", "i", "++", ";", "if", "(", "$", "checkOrder", "&&", "!", "empty", "(", "$", "last", ")", ")", "{", "$", "messageAfter", "=", "\"after '$last'\"", ";", "}", "// check if the link was found or the $i >= $count", "$", "test", "=", "true", ";", "if", "(", "empty", "(", "$", "available", "[", "$", "i", "]", ")", ")", "{", "$", "test", "=", "false", ";", "}", "Assertion", "::", "assertTrue", "(", "$", "test", ",", "\"Couldn't find '$link'\"", ".", "$", "messageAfter", ")", ";", "$", "passed", "++", ";", "$", "last", "=", "$", "link", ";", "}", "Assertion", "::", "assertEquals", "(", "count", "(", "$", "links", ")", ",", "$", "passed", ",", "\"Expected to evaluate '\"", ".", "count", "(", "$", "links", ")", ".", "\"' links evaluated '{$passed}'\"", ")", ";", "}" ]
Checks if links exist and in the following order (if intended) Notice: if there are 3 links and we omit the middle link it will also be correct. It only checks order, not if there should be anything in between them @param array $links Array with link text/title @param Behat\Mink\Element\NodeElement[] $available @param boolean $checkOrder Boolean to verify (or not) the link order @return void @throws \PHPUnit_Framework_AssertionFailedError
[ "Checks", "if", "links", "exist", "and", "in", "the", "following", "order", "(", "if", "intended", ")", "Notice", ":", "if", "there", "are", "3", "links", "and", "we", "omit", "the", "middle", "link", "it", "will", "also", "be", "correct", ".", "It", "only", "checks", "order", "not", "if", "there", "should", "be", "anything", "in", "between", "them" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L196-L237
ezsystems/BehatBundle
Context/Browser/Context.php
Context.getNumberFromString
public function getNumberFromString( $string ) { preg_match( '/(?P<digit>\d+)/', $string, $result ); Assertion::assertNotEmpty( $result['digit'], "Expected to find a number in '$string' found none" ); return (int)$result['digit']; }
php
public function getNumberFromString( $string ) { preg_match( '/(?P<digit>\d+)/', $string, $result ); Assertion::assertNotEmpty( $result['digit'], "Expected to find a number in '$string' found none" ); return (int)$result['digit']; }
[ "public", "function", "getNumberFromString", "(", "$", "string", ")", "{", "preg_match", "(", "'/(?P<digit>\\d+)/'", ",", "$", "string", ",", "$", "result", ")", ";", "Assertion", "::", "assertNotEmpty", "(", "$", "result", "[", "'digit'", "]", ",", "\"Expected to find a number in '$string' found none\"", ")", ";", "return", "(", "int", ")", "$", "result", "[", "'digit'", "]", ";", "}" ]
Fetchs the first integer in the string @param string $string Text @return int Integer found on text @throws \PHPUnit_Framework_AssertionFailedError
[ "Fetchs", "the", "first", "integer", "in", "the", "string" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L248-L253
ezsystems/BehatBundle
Context/Browser/Context.php
Context.existTableRow
public function existTableRow( NodeElement $row, array $columns, array $columnsPositions = null ) { // find which kind of column is in this row $elType = $row->find( 'xpath', "/th" ); $type = ( empty( $elType ) ) ? '/td' : '/th'; $max = count( $columns ); for ( $i = 0; $i < $max; $i++ ) { $position = ""; if ( !empty( $columnsPositions[$i] ) ) { $position = "[{$this->getNumberFromString( $columnsPositions[$i] )}]"; } $el = $row->find( "xpath", "$type$position" ); // check if match with expected if not return false if ( $el === null || $columns[$i] !== $el->getText() ) { return false; } } // if we're here then it means all have ran as expected return true; }
php
public function existTableRow( NodeElement $row, array $columns, array $columnsPositions = null ) { // find which kind of column is in this row $elType = $row->find( 'xpath', "/th" ); $type = ( empty( $elType ) ) ? '/td' : '/th'; $max = count( $columns ); for ( $i = 0; $i < $max; $i++ ) { $position = ""; if ( !empty( $columnsPositions[$i] ) ) { $position = "[{$this->getNumberFromString( $columnsPositions[$i] )}]"; } $el = $row->find( "xpath", "$type$position" ); // check if match with expected if not return false if ( $el === null || $columns[$i] !== $el->getText() ) { return false; } } // if we're here then it means all have ran as expected return true; }
[ "public", "function", "existTableRow", "(", "NodeElement", "$", "row", ",", "array", "$", "columns", ",", "array", "$", "columnsPositions", "=", "null", ")", "{", "// find which kind of column is in this row", "$", "elType", "=", "$", "row", "->", "find", "(", "'xpath'", ",", "\"/th\"", ")", ";", "$", "type", "=", "(", "empty", "(", "$", "elType", ")", ")", "?", "'/td'", ":", "'/th'", ";", "$", "max", "=", "count", "(", "$", "columns", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "max", ";", "$", "i", "++", ")", "{", "$", "position", "=", "\"\"", ";", "if", "(", "!", "empty", "(", "$", "columnsPositions", "[", "$", "i", "]", ")", ")", "{", "$", "position", "=", "\"[{$this->getNumberFromString( $columnsPositions[$i] )}]\"", ";", "}", "$", "el", "=", "$", "row", "->", "find", "(", "\"xpath\"", ",", "\"$type$position\"", ")", ";", "// check if match with expected if not return false", "if", "(", "$", "el", "===", "null", "||", "$", "columns", "[", "$", "i", "]", "!==", "$", "el", "->", "getText", "(", ")", ")", "{", "return", "false", ";", "}", "}", "// if we're here then it means all have ran as expected", "return", "true", ";", "}" ]
Verifies if a row as the expected columns, position of columns can be added for a more accurated assertion @param \Behat\Mink\Element\NodeElement $row Table row node element @param string[] $columns Column text to assert @param string[]|int[] $columnsPositions Columns positions in int or string (number must be in string) @return boolean @throws \PHPUnit_Framework_AssertionFailedError
[ "Verifies", "if", "a", "row", "as", "the", "expected", "columns", "position", "of", "columns", "can", "be", "added", "for", "a", "more", "accurated", "assertion" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L267-L293
ezsystems/BehatBundle
Context/Browser/Context.php
Context.getTableRow
public function getTableRow( $text, $column = null, $tableXpath = null ) { // check column if ( !empty( $column ) ) { if ( is_integer( $column ) ) { $columnNumber = "[$column]"; } else { $columnNumber = "[{$this->getNumberFromString( $column )}]"; } } else { $columnNumber = ""; } // get all possible elements $elements = array_merge( $this->getXpath()->findXpath( "$tableXpath//tr/th$columnNumber" ), $this->getXpath()->findXpath( "$tableXpath//tr/td$columnNumber" ) ); $foundXpath = array(); $total = count( $elements ); $i = 0; while ( $i < $total ) { if ( strpos( $elements[$i]->getText(), $text ) !== false ) { $foundXpath[] = $elements[$i]->getParent(); } $i++; } return $foundXpath; }
php
public function getTableRow( $text, $column = null, $tableXpath = null ) { // check column if ( !empty( $column ) ) { if ( is_integer( $column ) ) { $columnNumber = "[$column]"; } else { $columnNumber = "[{$this->getNumberFromString( $column )}]"; } } else { $columnNumber = ""; } // get all possible elements $elements = array_merge( $this->getXpath()->findXpath( "$tableXpath//tr/th$columnNumber" ), $this->getXpath()->findXpath( "$tableXpath//tr/td$columnNumber" ) ); $foundXpath = array(); $total = count( $elements ); $i = 0; while ( $i < $total ) { if ( strpos( $elements[$i]->getText(), $text ) !== false ) { $foundXpath[] = $elements[$i]->getParent(); } $i++; } return $foundXpath; }
[ "public", "function", "getTableRow", "(", "$", "text", ",", "$", "column", "=", "null", ",", "$", "tableXpath", "=", "null", ")", "{", "// check column", "if", "(", "!", "empty", "(", "$", "column", ")", ")", "{", "if", "(", "is_integer", "(", "$", "column", ")", ")", "{", "$", "columnNumber", "=", "\"[$column]\"", ";", "}", "else", "{", "$", "columnNumber", "=", "\"[{$this->getNumberFromString( $column )}]\"", ";", "}", "}", "else", "{", "$", "columnNumber", "=", "\"\"", ";", "}", "// get all possible elements", "$", "elements", "=", "array_merge", "(", "$", "this", "->", "getXpath", "(", ")", "->", "findXpath", "(", "\"$tableXpath//tr/th$columnNumber\"", ")", ",", "$", "this", "->", "getXpath", "(", ")", "->", "findXpath", "(", "\"$tableXpath//tr/td$columnNumber\"", ")", ")", ";", "$", "foundXpath", "=", "array", "(", ")", ";", "$", "total", "=", "count", "(", "$", "elements", ")", ";", "$", "i", "=", "0", ";", "while", "(", "$", "i", "<", "$", "total", ")", "{", "if", "(", "strpos", "(", "$", "elements", "[", "$", "i", "]", "->", "getText", "(", ")", ",", "$", "text", ")", "!==", "false", ")", "{", "$", "foundXpath", "[", "]", "=", "$", "elements", "[", "$", "i", "]", "->", "getParent", "(", ")", ";", "}", "$", "i", "++", ";", "}", "return", "$", "foundXpath", ";", "}" ]
Find a(all) table row(s) that match the column text @param string $text Text to be found @param string|int $column In which column the text should be found @param string $tableXpath If there is a specific table @return \Behat\Mink\Element\NodeElement[]
[ "Find", "a", "(", "all", ")", "table", "row", "(", "s", ")", "that", "match", "the", "column", "text" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L304-L343
ezsystems/BehatBundle
Context/Browser/Context.php
Context.findRow
public function findRow( NodeElement $element ) { $initialTag = $element->getTagName(); while ( strtolower( $element->getTagName() ) !== "tr" && strtolower( $element->getTagName() ) !== "body" ) { $element = $element->getParent(); } Assertion::assertEquals( strtolower( $element->getTagName() ), "tr", "Couldn't find a parent of '$initialTag' that is a table row" ); return $element; }
php
public function findRow( NodeElement $element ) { $initialTag = $element->getTagName(); while ( strtolower( $element->getTagName() ) !== "tr" && strtolower( $element->getTagName() ) !== "body" ) { $element = $element->getParent(); } Assertion::assertEquals( strtolower( $element->getTagName() ), "tr", "Couldn't find a parent of '$initialTag' that is a table row" ); return $element; }
[ "public", "function", "findRow", "(", "NodeElement", "$", "element", ")", "{", "$", "initialTag", "=", "$", "element", "->", "getTagName", "(", ")", ";", "while", "(", "strtolower", "(", "$", "element", "->", "getTagName", "(", ")", ")", "!==", "\"tr\"", "&&", "strtolower", "(", "$", "element", "->", "getTagName", "(", ")", ")", "!==", "\"body\"", ")", "{", "$", "element", "=", "$", "element", "->", "getParent", "(", ")", ";", "}", "Assertion", "::", "assertEquals", "(", "strtolower", "(", "$", "element", "->", "getTagName", "(", ")", ")", ",", "\"tr\"", ",", "\"Couldn't find a parent of '$initialTag' that is a table row\"", ")", ";", "return", "$", "element", ";", "}" ]
Find and return the row (<tr>) where the passed element is This is useful when you intend to know if another element is in the same row @param \Behat\Mink\Element\NodeElement $element The element in the intended row @return \Behat\Mink\Element\NodeElement The <tr> element node @throws \PHPUnit_Framework_AssertionFailedError
[ "Find", "and", "return", "the", "row", "(", "<tr", ">", ")", "where", "the", "passed", "element", "is", "This", "is", "useful", "when", "you", "intend", "to", "know", "if", "another", "element", "is", "in", "the", "same", "row" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L356-L375
ezsystems/BehatBundle
Context/Browser/Context.php
Context.findElementAfterElement
public function findElementAfterElement( array $elements, $firstXpath, $secondXpath ) { $foundFirstXpath = false; foreach ( $elements as $element ) { // choose what xpath to use if ( ! $foundFirstXpath ) { $xpath = $firstXpath; } else { $xpath = $secondXpath; } $foundElement = $element->find( "xpath", $xpath ); // element found, if first start to look for the second one // if second, than return this one if ( !empty( $foundElement) ) { if ( !$foundFirstXpath ) { $foundFirstXpath = true; } else { return $foundElement; } } } return null; }
php
public function findElementAfterElement( array $elements, $firstXpath, $secondXpath ) { $foundFirstXpath = false; foreach ( $elements as $element ) { // choose what xpath to use if ( ! $foundFirstXpath ) { $xpath = $firstXpath; } else { $xpath = $secondXpath; } $foundElement = $element->find( "xpath", $xpath ); // element found, if first start to look for the second one // if second, than return this one if ( !empty( $foundElement) ) { if ( !$foundFirstXpath ) { $foundFirstXpath = true; } else { return $foundElement; } } } return null; }
[ "public", "function", "findElementAfterElement", "(", "array", "$", "elements", ",", "$", "firstXpath", ",", "$", "secondXpath", ")", "{", "$", "foundFirstXpath", "=", "false", ";", "foreach", "(", "$", "elements", "as", "$", "element", ")", "{", "// choose what xpath to use", "if", "(", "!", "$", "foundFirstXpath", ")", "{", "$", "xpath", "=", "$", "firstXpath", ";", "}", "else", "{", "$", "xpath", "=", "$", "secondXpath", ";", "}", "$", "foundElement", "=", "$", "element", "->", "find", "(", "\"xpath\"", ",", "$", "xpath", ")", ";", "// element found, if first start to look for the second one", "// if second, than return this one", "if", "(", "!", "empty", "(", "$", "foundElement", ")", ")", "{", "if", "(", "!", "$", "foundFirstXpath", ")", "{", "$", "foundFirstXpath", "=", "true", ";", "}", "else", "{", "return", "$", "foundElement", ";", "}", "}", "}", "return", "null", ";", "}" ]
In a list of elements returns a certain element (found through xpath) that is after a specific element (that is also found through xpath) <code> findElementAfterElement( $arrayWithAllCellsOfARow, $xpathForALabel $xpathForAnInput ); </code> @param array $elements @param string $firstXpath @param string $secondXpath @return \Behat\Mink\Element\NodeElement|null Element if found null otherwise
[ "In", "a", "list", "of", "elements", "returns", "a", "certain", "element", "(", "found", "through", "xpath", ")", "that", "is", "after", "a", "specific", "element", "(", "that", "is", "also", "found", "through", "xpath", ")" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L395-L428
ezsystems/BehatBundle
Context/Browser/Context.php
Context.isElementEmphasized
public function isElementEmphasized( NodeElement $el, $characteristic = null, $attribute = "style" ) { // verify it has the attribute we're looking for if ( !$el->hasAttribute( $attribute ) ) { return false; } // get the attribute $attr = $el->getAttribute( $attribute ); // check if want to test specific characteristic and if it is present if ( !empty( $characteristic ) && strpos( $attr, $characteristic ) === false ) { return false; } // if we're here it is emphasized return true; }
php
public function isElementEmphasized( NodeElement $el, $characteristic = null, $attribute = "style" ) { // verify it has the attribute we're looking for if ( !$el->hasAttribute( $attribute ) ) { return false; } // get the attribute $attr = $el->getAttribute( $attribute ); // check if want to test specific characteristic and if it is present if ( !empty( $characteristic ) && strpos( $attr, $characteristic ) === false ) { return false; } // if we're here it is emphasized return true; }
[ "public", "function", "isElementEmphasized", "(", "NodeElement", "$", "el", ",", "$", "characteristic", "=", "null", ",", "$", "attribute", "=", "\"style\"", ")", "{", "// verify it has the attribute we're looking for", "if", "(", "!", "$", "el", "->", "hasAttribute", "(", "$", "attribute", ")", ")", "{", "return", "false", ";", "}", "// get the attribute", "$", "attr", "=", "$", "el", "->", "getAttribute", "(", "$", "attribute", ")", ";", "// check if want to test specific characteristic and if it is present", "if", "(", "!", "empty", "(", "$", "characteristic", ")", "&&", "strpos", "(", "$", "attr", ",", "$", "characteristic", ")", "===", "false", ")", "{", "return", "false", ";", "}", "// if we're here it is emphasized", "return", "true", ";", "}" ]
Verifies if the element has 'special' configuration on a attribute (default -> style) @param \Behat\Mink\Element\NodeElement $el The element that we want to test @param string $characteristic Verify a specific characteristic from attribute @param string $attribute Verify a specific attribute @return boolean
[ "Verifies", "if", "the", "element", "has", "special", "configuration", "on", "a", "attribute", "(", "default", "-", ">", "style", ")" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L439-L458
ezsystems/BehatBundle
Context/Browser/Context.php
Context.makeXpathForBlock
public function makeXpathForBlock( $block = null ) { if ( empty( $block ) ) { return null; } $parameter = ( isset( $this->mainAttributes[strtolower( $block )] ) ) ? $this->mainAttributes[strtolower( $block )] : NULL; Assertion::assertNotNull( $parameter, "Element {$block} is not defined" ); $xpath = $this->mainAttributes[strtolower( $block )]; // check if value is a composed array if ( is_array( $xpath ) ) { // if there is an xpath defined look no more! if ( isset( $xpath['xpath'] ) ) { return $xpath['xpath']; } $nuXpath = ""; // verify if there is a tag if ( isset( $xpath['tag'] ) ) { if ( strpos( $xpath['tag'], "/" ) === 0 || strpos( $xpath['tag'], "(" ) === 0 ) { $nuXpath = $xpath['tag']; } else { $nuXpath = "//" . $xpath['tag']; } unset( $xpath['tag'] ); } else { $nuXpath = "//*"; } foreach ( $xpath as $key => $value ) { switch ( $key ) { case "text": $att = "text()"; break; default: $att = "@$key"; } $nuXpath .= "[contains($att, {$this->getXpath()->literal( $value )})]"; } return $nuXpath; } // if the string is an Xpath if ( strpos( $xpath, "/" ) === 0 || strpos( $xpath, "(" ) === 0 ) { return $xpath; } // if xpath is an simple tag return "//$xpath"; }
php
public function makeXpathForBlock( $block = null ) { if ( empty( $block ) ) { return null; } $parameter = ( isset( $this->mainAttributes[strtolower( $block )] ) ) ? $this->mainAttributes[strtolower( $block )] : NULL; Assertion::assertNotNull( $parameter, "Element {$block} is not defined" ); $xpath = $this->mainAttributes[strtolower( $block )]; // check if value is a composed array if ( is_array( $xpath ) ) { // if there is an xpath defined look no more! if ( isset( $xpath['xpath'] ) ) { return $xpath['xpath']; } $nuXpath = ""; // verify if there is a tag if ( isset( $xpath['tag'] ) ) { if ( strpos( $xpath['tag'], "/" ) === 0 || strpos( $xpath['tag'], "(" ) === 0 ) { $nuXpath = $xpath['tag']; } else { $nuXpath = "//" . $xpath['tag']; } unset( $xpath['tag'] ); } else { $nuXpath = "//*"; } foreach ( $xpath as $key => $value ) { switch ( $key ) { case "text": $att = "text()"; break; default: $att = "@$key"; } $nuXpath .= "[contains($att, {$this->getXpath()->literal( $value )})]"; } return $nuXpath; } // if the string is an Xpath if ( strpos( $xpath, "/" ) === 0 || strpos( $xpath, "(" ) === 0 ) { return $xpath; } // if xpath is an simple tag return "//$xpath"; }
[ "public", "function", "makeXpathForBlock", "(", "$", "block", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "block", ")", ")", "{", "return", "null", ";", "}", "$", "parameter", "=", "(", "isset", "(", "$", "this", "->", "mainAttributes", "[", "strtolower", "(", "$", "block", ")", "]", ")", ")", "?", "$", "this", "->", "mainAttributes", "[", "strtolower", "(", "$", "block", ")", "]", ":", "NULL", ";", "Assertion", "::", "assertNotNull", "(", "$", "parameter", ",", "\"Element {$block} is not defined\"", ")", ";", "$", "xpath", "=", "$", "this", "->", "mainAttributes", "[", "strtolower", "(", "$", "block", ")", "]", ";", "// check if value is a composed array", "if", "(", "is_array", "(", "$", "xpath", ")", ")", "{", "// if there is an xpath defined look no more!", "if", "(", "isset", "(", "$", "xpath", "[", "'xpath'", "]", ")", ")", "{", "return", "$", "xpath", "[", "'xpath'", "]", ";", "}", "$", "nuXpath", "=", "\"\"", ";", "// verify if there is a tag", "if", "(", "isset", "(", "$", "xpath", "[", "'tag'", "]", ")", ")", "{", "if", "(", "strpos", "(", "$", "xpath", "[", "'tag'", "]", ",", "\"/\"", ")", "===", "0", "||", "strpos", "(", "$", "xpath", "[", "'tag'", "]", ",", "\"(\"", ")", "===", "0", ")", "{", "$", "nuXpath", "=", "$", "xpath", "[", "'tag'", "]", ";", "}", "else", "{", "$", "nuXpath", "=", "\"//\"", ".", "$", "xpath", "[", "'tag'", "]", ";", "}", "unset", "(", "$", "xpath", "[", "'tag'", "]", ")", ";", "}", "else", "{", "$", "nuXpath", "=", "\"//*\"", ";", "}", "foreach", "(", "$", "xpath", "as", "$", "key", "=>", "$", "value", ")", "{", "switch", "(", "$", "key", ")", "{", "case", "\"text\"", ":", "$", "att", "=", "\"text()\"", ";", "break", ";", "default", ":", "$", "att", "=", "\"@$key\"", ";", "}", "$", "nuXpath", ".=", "\"[contains($att, {$this->getXpath()->literal( $value )})]\"", ";", "}", "return", "$", "nuXpath", ";", "}", "// if the string is an Xpath", "if", "(", "strpos", "(", "$", "xpath", ",", "\"/\"", ")", "===", "0", "||", "strpos", "(", "$", "xpath", ",", "\"(\"", ")", "===", "0", ")", "{", "return", "$", "xpath", ";", "}", "// if xpath is an simple tag", "return", "\"//$xpath\"", ";", "}" ]
This method works is a complement to the $mainAttributes var @param string $block This should be an identifier for the block to use @return null|string XPath for the @see $this->mainAttributes
[ "This", "method", "works", "is", "a", "complement", "to", "the", "$mainAttributes", "var" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/Context.php#L469-L536
ezsystems/BehatBundle
Context/Browser/SubContext/Authentication.php
Authentication.iAmLoggedInAsAn
public function iAmLoggedInAsAn( $role ) { trigger_error( "iAmLoggedInAsAn is deprecated since v6.3.0 and will be removed in v7.0.0", E_USER_DEPRECATED ); if ( $role == 'Anonymous' ) { $this->iAmNotLoggedIn(); } else { $credentials = $this->getCredentialsFor( $role ); $this->iAmLoggedInAsWithPassword( $credentials['login'], $credentials['password'] ); } }
php
public function iAmLoggedInAsAn( $role ) { trigger_error( "iAmLoggedInAsAn is deprecated since v6.3.0 and will be removed in v7.0.0", E_USER_DEPRECATED ); if ( $role == 'Anonymous' ) { $this->iAmNotLoggedIn(); } else { $credentials = $this->getCredentialsFor( $role ); $this->iAmLoggedInAsWithPassword( $credentials['login'], $credentials['password'] ); } }
[ "public", "function", "iAmLoggedInAsAn", "(", "$", "role", ")", "{", "trigger_error", "(", "\"iAmLoggedInAsAn is deprecated since v6.3.0 and will be removed in v7.0.0\"", ",", "E_USER_DEPRECATED", ")", ";", "if", "(", "$", "role", "==", "'Anonymous'", ")", "{", "$", "this", "->", "iAmNotLoggedIn", "(", ")", ";", "}", "else", "{", "$", "credentials", "=", "$", "this", "->", "getCredentialsFor", "(", "$", "role", ")", ";", "$", "this", "->", "iAmLoggedInAsWithPassword", "(", "$", "credentials", "[", "'login'", "]", ",", "$", "credentials", "[", "'password'", "]", ")", ";", "}", "}" ]
@Given I am logged (in) as a(n) :role @Given I have :role permissions Logs in a (new) user with the role identified by ':role' assigned. @deprecated deprecated since version 6.3.0
[ "@Given", "I", "am", "logged", "(", "in", ")", "as", "a", "(", "n", ")", ":", "role", "@Given", "I", "have", ":", "role", "permissions" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/SubContext/Authentication.php#L25-L41
ezsystems/BehatBundle
Context/Browser/SubContext/Authentication.php
Authentication.iAmLoggedInAsWithPassword
public function iAmLoggedInAsWithPassword( $user, $password ) { trigger_error( "iAmLoggedInAsWithPassword is deprecated since v6.3.0 and will be removed in v7.0.0", E_USER_DEPRECATED ); $this->iAmOnPage( 'login' ); $this->fillFieldWithValue( 'Username', $user ); $this->fillFieldWithValue( 'Password', $password ); $this->iClickAtButton( 'Login' ); $this->iShouldBeOnPage( 'home' ); }
php
public function iAmLoggedInAsWithPassword( $user, $password ) { trigger_error( "iAmLoggedInAsWithPassword is deprecated since v6.3.0 and will be removed in v7.0.0", E_USER_DEPRECATED ); $this->iAmOnPage( 'login' ); $this->fillFieldWithValue( 'Username', $user ); $this->fillFieldWithValue( 'Password', $password ); $this->iClickAtButton( 'Login' ); $this->iShouldBeOnPage( 'home' ); }
[ "public", "function", "iAmLoggedInAsWithPassword", "(", "$", "user", ",", "$", "password", ")", "{", "trigger_error", "(", "\"iAmLoggedInAsWithPassword is deprecated since v6.3.0 and will be removed in v7.0.0\"", ",", "E_USER_DEPRECATED", ")", ";", "$", "this", "->", "iAmOnPage", "(", "'login'", ")", ";", "$", "this", "->", "fillFieldWithValue", "(", "'Username'", ",", "$", "user", ")", ";", "$", "this", "->", "fillFieldWithValue", "(", "'Password'", ",", "$", "password", ")", ";", "$", "this", "->", "iClickAtButton", "(", "'Login'", ")", ";", "$", "this", "->", "iShouldBeOnPage", "(", "'home'", ")", ";", "}" ]
@Given I am logged in as :user with password :password Performs the login action with username ':user' and password ':password'. Checks that the resulting page is the homepage. @deprecated deprecated since version 6.3.0
[ "@Given", "I", "am", "logged", "in", "as", ":", "user", "with", "password", ":", "password" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Context/Browser/SubContext/Authentication.php#L51-L63
ezsystems/BehatBundle
Helper/EzAssertion.php
EzAssertion.assertSingleElement
static function assertSingleElement( $search, $element, $pageSection = null, $type = 'element' ) { $section = ( $pageSection === null ) ? "" : " in '$pageSection' page section"; Assertion::assertNotEmpty( $element, "Couldn't find '$search' $type" . $section ); Assertion::assertEquals( 1, count( $element ), "Unexpectedly found more than 1 '$search' $type" . $section ); }
php
static function assertSingleElement( $search, $element, $pageSection = null, $type = 'element' ) { $section = ( $pageSection === null ) ? "" : " in '$pageSection' page section"; Assertion::assertNotEmpty( $element, "Couldn't find '$search' $type" . $section ); Assertion::assertEquals( 1, count( $element ), "Unexpectedly found more than 1 '$search' $type" . $section ); }
[ "static", "function", "assertSingleElement", "(", "$", "search", ",", "$", "element", ",", "$", "pageSection", "=", "null", ",", "$", "type", "=", "'element'", ")", "{", "$", "section", "=", "(", "$", "pageSection", "===", "null", ")", "?", "\"\"", ":", "\" in '$pageSection' page section\"", ";", "Assertion", "::", "assertNotEmpty", "(", "$", "element", ",", "\"Couldn't find '$search' $type\"", ".", "$", "section", ")", ";", "Assertion", "::", "assertEquals", "(", "1", ",", "count", "(", "$", "element", ")", ",", "\"Unexpectedly found more than 1 '$search' $type\"", ".", "$", "section", ")", ";", "}" ]
Assert that 1 page element was found @param string $search Search text @param mixed $element Elements found @param null|string $pageSection Page section @param null|string $type HTML element (ex: link, button, input, ...) @return void
[ "Assert", "that", "1", "page", "element", "was", "found" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Helper/EzAssertion.php#L29-L38
ezsystems/BehatBundle
Helper/EzAssertion.php
EzAssertion.assertElementFound
static function assertElementFound( $search, $element, $pageSection = null, $type = 'element' ) { $section = ( $pageSection === null ) ? "" : " in '$pageSection' page section"; Assertion::assertNotEmpty( $element, "Couldn't find '$search' $type" . $section ); }
php
static function assertElementFound( $search, $element, $pageSection = null, $type = 'element' ) { $section = ( $pageSection === null ) ? "" : " in '$pageSection' page section"; Assertion::assertNotEmpty( $element, "Couldn't find '$search' $type" . $section ); }
[ "static", "function", "assertElementFound", "(", "$", "search", ",", "$", "element", ",", "$", "pageSection", "=", "null", ",", "$", "type", "=", "'element'", ")", "{", "$", "section", "=", "(", "$", "pageSection", "===", "null", ")", "?", "\"\"", ":", "\" in '$pageSection' page section\"", ";", "Assertion", "::", "assertNotEmpty", "(", "$", "element", ",", "\"Couldn't find '$search' $type\"", ".", "$", "section", ")", ";", "}" ]
Assert that at least 1 page element was found @param string $search Search text @param mixed $element Elements found @param null|string $pageSection Page section @param null|string $type HTML element (ex: link, button, input, ...) @return void
[ "Assert", "that", "at", "least", "1", "page", "element", "was", "found" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Helper/EzAssertion.php#L50-L54
ezsystems/BehatBundle
Helper/EzAssertion.php
EzAssertion.assertElementNotFound
static function assertElementNotFound( $search, $element, $pageSection = null, $type = 'element' ) { $section = ( $pageSection === null ) ? "" : " in '$pageSection' page section"; Assertion::assertEmpty( $element, "Found '$search' $type" . $section ); }
php
static function assertElementNotFound( $search, $element, $pageSection = null, $type = 'element' ) { $section = ( $pageSection === null ) ? "" : " in '$pageSection' page section"; Assertion::assertEmpty( $element, "Found '$search' $type" . $section ); }
[ "static", "function", "assertElementNotFound", "(", "$", "search", ",", "$", "element", ",", "$", "pageSection", "=", "null", ",", "$", "type", "=", "'element'", ")", "{", "$", "section", "=", "(", "$", "pageSection", "===", "null", ")", "?", "\"\"", ":", "\" in '$pageSection' page section\"", ";", "Assertion", "::", "assertEmpty", "(", "$", "element", ",", "\"Found '$search' $type\"", ".", "$", "section", ")", ";", "}" ]
Assert that no page element was found @param string $search Search text @param mixed $element Elements found @param null|string $pageSection Page section @param null|string $type HTML element (ex: link, button, input, ...) @return void
[ "Assert", "that", "no", "page", "element", "was", "found" ]
train
https://github.com/ezsystems/BehatBundle/blob/7d6d409545ec7cb69a3ab6636a59159df033695d/Helper/EzAssertion.php#L66-L70
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap.getBrowser
public function getBrowser($user_agent = null, $return_array = false) { // Load the cache at the first request if (!$this->_cacheLoaded) { $cache_file = $this->cacheDir . $this->cacheFilename; $ini_file = $this->cacheDir . $this->iniFilename; // Set the interval only if needed if ($this->doAutoUpdate && file_exists($ini_file)) { $interval = time() - filemtime($ini_file); } else { $interval = 0; } $update_cache = true; if (file_exists($cache_file) && file_exists($ini_file) && ($interval <= $this->updateInterval)) { if ($this->_loadCache($cache_file)) { $update_cache = false; } } if ($update_cache) { try { $this->updateCache(); } catch (Exception $e) { if (file_exists($ini_file)) { // Adjust the filemtime to the $errorInterval touch($ini_file, time() - $this->updateInterval + $this->errorInterval); } elseif ($this->silent) { // Return an array if silent mode is active and the ini db doesn't exsist return array(); } if (!$this->silent) { throw $e; } } if (!$this->_loadCache($cache_file)) { throw new Exception("Cannot load this cache version - the cache format is not compatible."); } } } // Automatically detect the useragent if (!isset($user_agent)) { if (isset($_SERVER['HTTP_USER_AGENT'])) { $user_agent = $_SERVER['HTTP_USER_AGENT']; } else { $user_agent = ''; } } $browser = array(); foreach ($this->_patterns as $pattern => $pattern_data) { if (preg_match($pattern . 'i', $user_agent, $matches)) { if (1 == count($matches)) { // standard match $key = $pattern_data; $simple_match = true; } else { $pattern_data = unserialize($pattern_data); // match with numeric replacements array_shift($matches); $match_string = self::COMPRESSION_PATTERN_START . implode(self::COMPRESSION_PATTERN_DELIMITER, $matches); if (!isset($pattern_data[$match_string])) { // partial match - numbers are not present, but everything else is ok continue; } $key = $pattern_data[$match_string]; $simple_match = false; } $browser = array( $user_agent, // Original useragent trim(strtolower($pattern), self::REGEX_DELIMITER), $this->_pregUnQuote($pattern, $simple_match ? false : $matches) ); $browser = $value = $browser + unserialize($this->_browsers[$key]); while (array_key_exists(3, $value)) { $value = unserialize($this->_browsers[$value[3]]); $browser += $value; } if (!empty($browser[3])) { $browser[3] = $this->_userAgents[$browser[3]]; } break; } } // Add the keys for each property $array = array(); foreach ($browser as $key => $value) { if ($value === 'true') { $value = true; } elseif ($value === 'false') { $value = false; } $array[$this->_properties[$key]] = $value; } return $return_array ? $array : (object) $array; }
php
public function getBrowser($user_agent = null, $return_array = false) { // Load the cache at the first request if (!$this->_cacheLoaded) { $cache_file = $this->cacheDir . $this->cacheFilename; $ini_file = $this->cacheDir . $this->iniFilename; // Set the interval only if needed if ($this->doAutoUpdate && file_exists($ini_file)) { $interval = time() - filemtime($ini_file); } else { $interval = 0; } $update_cache = true; if (file_exists($cache_file) && file_exists($ini_file) && ($interval <= $this->updateInterval)) { if ($this->_loadCache($cache_file)) { $update_cache = false; } } if ($update_cache) { try { $this->updateCache(); } catch (Exception $e) { if (file_exists($ini_file)) { // Adjust the filemtime to the $errorInterval touch($ini_file, time() - $this->updateInterval + $this->errorInterval); } elseif ($this->silent) { // Return an array if silent mode is active and the ini db doesn't exsist return array(); } if (!$this->silent) { throw $e; } } if (!$this->_loadCache($cache_file)) { throw new Exception("Cannot load this cache version - the cache format is not compatible."); } } } // Automatically detect the useragent if (!isset($user_agent)) { if (isset($_SERVER['HTTP_USER_AGENT'])) { $user_agent = $_SERVER['HTTP_USER_AGENT']; } else { $user_agent = ''; } } $browser = array(); foreach ($this->_patterns as $pattern => $pattern_data) { if (preg_match($pattern . 'i', $user_agent, $matches)) { if (1 == count($matches)) { // standard match $key = $pattern_data; $simple_match = true; } else { $pattern_data = unserialize($pattern_data); // match with numeric replacements array_shift($matches); $match_string = self::COMPRESSION_PATTERN_START . implode(self::COMPRESSION_PATTERN_DELIMITER, $matches); if (!isset($pattern_data[$match_string])) { // partial match - numbers are not present, but everything else is ok continue; } $key = $pattern_data[$match_string]; $simple_match = false; } $browser = array( $user_agent, // Original useragent trim(strtolower($pattern), self::REGEX_DELIMITER), $this->_pregUnQuote($pattern, $simple_match ? false : $matches) ); $browser = $value = $browser + unserialize($this->_browsers[$key]); while (array_key_exists(3, $value)) { $value = unserialize($this->_browsers[$value[3]]); $browser += $value; } if (!empty($browser[3])) { $browser[3] = $this->_userAgents[$browser[3]]; } break; } } // Add the keys for each property $array = array(); foreach ($browser as $key => $value) { if ($value === 'true') { $value = true; } elseif ($value === 'false') { $value = false; } $array[$this->_properties[$key]] = $value; } return $return_array ? $array : (object) $array; }
[ "public", "function", "getBrowser", "(", "$", "user_agent", "=", "null", ",", "$", "return_array", "=", "false", ")", "{", "// Load the cache at the first request", "if", "(", "!", "$", "this", "->", "_cacheLoaded", ")", "{", "$", "cache_file", "=", "$", "this", "->", "cacheDir", ".", "$", "this", "->", "cacheFilename", ";", "$", "ini_file", "=", "$", "this", "->", "cacheDir", ".", "$", "this", "->", "iniFilename", ";", "// Set the interval only if needed", "if", "(", "$", "this", "->", "doAutoUpdate", "&&", "file_exists", "(", "$", "ini_file", ")", ")", "{", "$", "interval", "=", "time", "(", ")", "-", "filemtime", "(", "$", "ini_file", ")", ";", "}", "else", "{", "$", "interval", "=", "0", ";", "}", "$", "update_cache", "=", "true", ";", "if", "(", "file_exists", "(", "$", "cache_file", ")", "&&", "file_exists", "(", "$", "ini_file", ")", "&&", "(", "$", "interval", "<=", "$", "this", "->", "updateInterval", ")", ")", "{", "if", "(", "$", "this", "->", "_loadCache", "(", "$", "cache_file", ")", ")", "{", "$", "update_cache", "=", "false", ";", "}", "}", "if", "(", "$", "update_cache", ")", "{", "try", "{", "$", "this", "->", "updateCache", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "if", "(", "file_exists", "(", "$", "ini_file", ")", ")", "{", "// Adjust the filemtime to the $errorInterval", "touch", "(", "$", "ini_file", ",", "time", "(", ")", "-", "$", "this", "->", "updateInterval", "+", "$", "this", "->", "errorInterval", ")", ";", "}", "elseif", "(", "$", "this", "->", "silent", ")", "{", "// Return an array if silent mode is active and the ini db doesn't exsist", "return", "array", "(", ")", ";", "}", "if", "(", "!", "$", "this", "->", "silent", ")", "{", "throw", "$", "e", ";", "}", "}", "if", "(", "!", "$", "this", "->", "_loadCache", "(", "$", "cache_file", ")", ")", "{", "throw", "new", "Exception", "(", "\"Cannot load this cache version - the cache format is not compatible.\"", ")", ";", "}", "}", "}", "// Automatically detect the useragent", "if", "(", "!", "isset", "(", "$", "user_agent", ")", ")", "{", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ")", ")", "{", "$", "user_agent", "=", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ";", "}", "else", "{", "$", "user_agent", "=", "''", ";", "}", "}", "$", "browser", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "_patterns", "as", "$", "pattern", "=>", "$", "pattern_data", ")", "{", "if", "(", "preg_match", "(", "$", "pattern", ".", "'i'", ",", "$", "user_agent", ",", "$", "matches", ")", ")", "{", "if", "(", "1", "==", "count", "(", "$", "matches", ")", ")", "{", "// standard match", "$", "key", "=", "$", "pattern_data", ";", "$", "simple_match", "=", "true", ";", "}", "else", "{", "$", "pattern_data", "=", "unserialize", "(", "$", "pattern_data", ")", ";", "// match with numeric replacements", "array_shift", "(", "$", "matches", ")", ";", "$", "match_string", "=", "self", "::", "COMPRESSION_PATTERN_START", ".", "implode", "(", "self", "::", "COMPRESSION_PATTERN_DELIMITER", ",", "$", "matches", ")", ";", "if", "(", "!", "isset", "(", "$", "pattern_data", "[", "$", "match_string", "]", ")", ")", "{", "// partial match - numbers are not present, but everything else is ok", "continue", ";", "}", "$", "key", "=", "$", "pattern_data", "[", "$", "match_string", "]", ";", "$", "simple_match", "=", "false", ";", "}", "$", "browser", "=", "array", "(", "$", "user_agent", ",", "// Original useragent", "trim", "(", "strtolower", "(", "$", "pattern", ")", ",", "self", "::", "REGEX_DELIMITER", ")", ",", "$", "this", "->", "_pregUnQuote", "(", "$", "pattern", ",", "$", "simple_match", "?", "false", ":", "$", "matches", ")", ")", ";", "$", "browser", "=", "$", "value", "=", "$", "browser", "+", "unserialize", "(", "$", "this", "->", "_browsers", "[", "$", "key", "]", ")", ";", "while", "(", "array_key_exists", "(", "3", ",", "$", "value", ")", ")", "{", "$", "value", "=", "unserialize", "(", "$", "this", "->", "_browsers", "[", "$", "value", "[", "3", "]", "]", ")", ";", "$", "browser", "+=", "$", "value", ";", "}", "if", "(", "!", "empty", "(", "$", "browser", "[", "3", "]", ")", ")", "{", "$", "browser", "[", "3", "]", "=", "$", "this", "->", "_userAgents", "[", "$", "browser", "[", "3", "]", "]", ";", "}", "break", ";", "}", "}", "// Add the keys for each property", "$", "array", "=", "array", "(", ")", ";", "foreach", "(", "$", "browser", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "===", "'true'", ")", "{", "$", "value", "=", "true", ";", "}", "elseif", "(", "$", "value", "===", "'false'", ")", "{", "$", "value", "=", "false", ";", "}", "$", "array", "[", "$", "this", "->", "_properties", "[", "$", "key", "]", "]", "=", "$", "value", ";", "}", "return", "$", "return_array", "?", "$", "array", ":", "(", "object", ")", "$", "array", ";", "}" ]
XXX parse Gets the information about the browser by User Agent @param string $user_agent the user agent string @param bool $return_array whether return an array or an object @throws Exception @return stdClass|array the object containing the browsers details. Array if $return_array is set to true.
[ "XXX", "parse" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L262-L379
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap.autodetectProxySettings
public function autodetectProxySettings() { $wrappers = array('http', 'https', 'ftp'); foreach ($wrappers as $wrapper) { $url = getenv($wrapper.'_proxy'); if (!empty($url)) { $params = array_merge(array( 'port' => null, 'user' => null, 'pass' => null, ), parse_url($url)); $this->addProxySettings($params['host'], $params['port'], $wrapper, $params['user'], $params['pass']); } } }
php
public function autodetectProxySettings() { $wrappers = array('http', 'https', 'ftp'); foreach ($wrappers as $wrapper) { $url = getenv($wrapper.'_proxy'); if (!empty($url)) { $params = array_merge(array( 'port' => null, 'user' => null, 'pass' => null, ), parse_url($url)); $this->addProxySettings($params['host'], $params['port'], $wrapper, $params['user'], $params['pass']); } } }
[ "public", "function", "autodetectProxySettings", "(", ")", "{", "$", "wrappers", "=", "array", "(", "'http'", ",", "'https'", ",", "'ftp'", ")", ";", "foreach", "(", "$", "wrappers", "as", "$", "wrapper", ")", "{", "$", "url", "=", "getenv", "(", "$", "wrapper", ".", "'_proxy'", ")", ";", "if", "(", "!", "empty", "(", "$", "url", ")", ")", "{", "$", "params", "=", "array_merge", "(", "array", "(", "'port'", "=>", "null", ",", "'user'", "=>", "null", ",", "'pass'", "=>", "null", ",", ")", ",", "parse_url", "(", "$", "url", ")", ")", ";", "$", "this", "->", "addProxySettings", "(", "$", "params", "[", "'host'", "]", ",", "$", "params", "[", "'port'", "]", ",", "$", "wrapper", ",", "$", "params", "[", "'user'", "]", ",", "$", "params", "[", "'pass'", "]", ")", ";", "}", "}", "}" ]
Load (auto-set) proxy settings from environment variables.
[ "Load", "(", "auto", "-", "set", ")", "proxy", "settings", "from", "environment", "variables", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L384-L399
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap.addProxySettings
public function addProxySettings($server, $port = 3128, $wrapper = 'http', $username = null, $password = null) { $settings = array($wrapper => array( 'proxy' => sprintf('tcp://%s:%d', $server, $port), 'request_fulluri' => true, )); // Proxy authentication (optional) if (isset($username) && isset($password)) { $settings[$wrapper]['header'] = 'Proxy-Authorization: Basic '.base64_encode($username.':'.$password); } // Add these new settings to the stream context options array $this->_streamContextOptions = array_merge( $this->_streamContextOptions, $settings ); /* Return $this so we can chain addProxySettings() calls like this: * $browscap-> * addProxySettings('http')-> * addProxySettings('https')-> * addProxySettings('ftp'); */ return $this; }
php
public function addProxySettings($server, $port = 3128, $wrapper = 'http', $username = null, $password = null) { $settings = array($wrapper => array( 'proxy' => sprintf('tcp://%s:%d', $server, $port), 'request_fulluri' => true, )); // Proxy authentication (optional) if (isset($username) && isset($password)) { $settings[$wrapper]['header'] = 'Proxy-Authorization: Basic '.base64_encode($username.':'.$password); } // Add these new settings to the stream context options array $this->_streamContextOptions = array_merge( $this->_streamContextOptions, $settings ); /* Return $this so we can chain addProxySettings() calls like this: * $browscap-> * addProxySettings('http')-> * addProxySettings('https')-> * addProxySettings('ftp'); */ return $this; }
[ "public", "function", "addProxySettings", "(", "$", "server", ",", "$", "port", "=", "3128", ",", "$", "wrapper", "=", "'http'", ",", "$", "username", "=", "null", ",", "$", "password", "=", "null", ")", "{", "$", "settings", "=", "array", "(", "$", "wrapper", "=>", "array", "(", "'proxy'", "=>", "sprintf", "(", "'tcp://%s:%d'", ",", "$", "server", ",", "$", "port", ")", ",", "'request_fulluri'", "=>", "true", ",", ")", ")", ";", "// Proxy authentication (optional)", "if", "(", "isset", "(", "$", "username", ")", "&&", "isset", "(", "$", "password", ")", ")", "{", "$", "settings", "[", "$", "wrapper", "]", "[", "'header'", "]", "=", "'Proxy-Authorization: Basic '", ".", "base64_encode", "(", "$", "username", ".", "':'", ".", "$", "password", ")", ";", "}", "// Add these new settings to the stream context options array", "$", "this", "->", "_streamContextOptions", "=", "array_merge", "(", "$", "this", "->", "_streamContextOptions", ",", "$", "settings", ")", ";", "/* Return $this so we can chain addProxySettings() calls like this:\n * $browscap->\n * addProxySettings('http')->\n * addProxySettings('https')->\n * addProxySettings('ftp');\n */", "return", "$", "this", ";", "}" ]
Add proxy settings to the stream context array. @param string $server Proxy server/host @param int $port Port @param string $wrapper Wrapper: "http", "https", "ftp", others... @param string $username Username (when requiring authentication) @param string $password Password (when requiring authentication) @return Browscap
[ "Add", "proxy", "settings", "to", "the", "stream", "context", "array", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L412-L437
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap.clearProxySettings
public function clearProxySettings($wrapper = null) { $wrappers = isset($wrapper) ? array($wrapper) : array_keys($this->_streamContextOptions); $clearedWrappers = array(); $options = array('proxy', 'request_fulluri', 'header'); foreach ($wrappers as $wrapper) { // remove wrapper options related to proxy settings if (isset($this->_streamContextOptions[$wrapper]['proxy'])) { foreach ($options as $option){ unset($this->_streamContextOptions[$wrapper][$option]); } // remove wrapper entry if there are no other options left if (empty($this->_streamContextOptions[$wrapper])) { unset($this->_streamContextOptions[$wrapper]); } $clearedWrappers[] = $wrapper; } } return $clearedWrappers; }
php
public function clearProxySettings($wrapper = null) { $wrappers = isset($wrapper) ? array($wrapper) : array_keys($this->_streamContextOptions); $clearedWrappers = array(); $options = array('proxy', 'request_fulluri', 'header'); foreach ($wrappers as $wrapper) { // remove wrapper options related to proxy settings if (isset($this->_streamContextOptions[$wrapper]['proxy'])) { foreach ($options as $option){ unset($this->_streamContextOptions[$wrapper][$option]); } // remove wrapper entry if there are no other options left if (empty($this->_streamContextOptions[$wrapper])) { unset($this->_streamContextOptions[$wrapper]); } $clearedWrappers[] = $wrapper; } } return $clearedWrappers; }
[ "public", "function", "clearProxySettings", "(", "$", "wrapper", "=", "null", ")", "{", "$", "wrappers", "=", "isset", "(", "$", "wrapper", ")", "?", "array", "(", "$", "wrapper", ")", ":", "array_keys", "(", "$", "this", "->", "_streamContextOptions", ")", ";", "$", "clearedWrappers", "=", "array", "(", ")", ";", "$", "options", "=", "array", "(", "'proxy'", ",", "'request_fulluri'", ",", "'header'", ")", ";", "foreach", "(", "$", "wrappers", "as", "$", "wrapper", ")", "{", "// remove wrapper options related to proxy settings", "if", "(", "isset", "(", "$", "this", "->", "_streamContextOptions", "[", "$", "wrapper", "]", "[", "'proxy'", "]", ")", ")", "{", "foreach", "(", "$", "options", "as", "$", "option", ")", "{", "unset", "(", "$", "this", "->", "_streamContextOptions", "[", "$", "wrapper", "]", "[", "$", "option", "]", ")", ";", "}", "// remove wrapper entry if there are no other options left", "if", "(", "empty", "(", "$", "this", "->", "_streamContextOptions", "[", "$", "wrapper", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "_streamContextOptions", "[", "$", "wrapper", "]", ")", ";", "}", "$", "clearedWrappers", "[", "]", "=", "$", "wrapper", ";", "}", "}", "return", "$", "clearedWrappers", ";", "}" ]
Clear proxy settings from the stream context options array. @param string $wrapper Remove settings from this wrapper only @return array Wrappers cleared
[ "Clear", "proxy", "settings", "from", "the", "stream", "context", "options", "array", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L446-L470
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap.updateCache
public function updateCache() { $ini_path = $this->cacheDir . $this->iniFilename; $cache_path = $this->cacheDir . $this->cacheFilename; // Choose the right url if ($this->_getUpdateMethod() == self::UPDATE_LOCAL) { $url = $this->localFile; } else { $url = $this->remoteIniUrl; } $this->_getRemoteIniFile($url, $ini_path); if (version_compare(PHP_VERSION, '5.3.0', '>=')) { $browsers = parse_ini_file($ini_path, true, INI_SCANNER_RAW); } else { $browsers = parse_ini_file($ini_path, true); } $this->_source_version = $browsers[self::BROWSCAP_VERSION_KEY]['Version']; unset($browsers[self::BROWSCAP_VERSION_KEY]); unset($browsers['DefaultProperties']['RenderingEngine_Description']); $this->_properties = array_keys($browsers['DefaultProperties']); array_unshift( $this->_properties, 'browser_name', 'browser_name_regex', 'browser_name_pattern', 'Parent' ); $tmp_user_agents = array_keys($browsers); usort($tmp_user_agents, array($this, 'compareBcStrings')); $user_agents_keys = array_flip($tmp_user_agents); $properties_keys = array_flip($this->_properties); $tmp_patterns = array(); foreach ($tmp_user_agents as $i => $user_agent) { if (empty($browsers[$user_agent]['Comment']) || strpos($user_agent, '*') !== false || strpos($user_agent, '?') !== false) { $pattern = $this->_pregQuote($user_agent); $matches_count = preg_match_all('@\d@', $pattern, $matches); if (!$matches_count) { $tmp_patterns[$pattern] = $i; } else { $compressed_pattern = preg_replace('@\d@', '(\d)', $pattern); if (!isset($tmp_patterns[$compressed_pattern])) { $tmp_patterns[$compressed_pattern] = array('first' => $pattern); } $tmp_patterns[$compressed_pattern][$i] = $matches[0]; } } if (!empty($browsers[$user_agent]['Parent'])) { $parent = $browsers[$user_agent]['Parent']; $parent_key = $user_agents_keys[$parent]; $browsers[$user_agent]['Parent'] = $parent_key; $this->_userAgents[$parent_key . '.0'] = $tmp_user_agents[$parent_key]; }; $browser = array(); foreach ($browsers[$user_agent] as $key => $value) { if (!isset($properties_keys[$key])) { continue; } $key = $properties_keys[$key]; $browser[$key] = $value; } $this->_browsers[] = $browser; } foreach ($tmp_patterns as $pattern => $pattern_data) { if (is_int($pattern_data)) { $this->_patterns[$pattern] = $pattern_data; } elseif (2 == count($pattern_data)) { end($pattern_data); $this->_patterns[$pattern_data['first']] = key($pattern_data); } else { unset($pattern_data['first']); $pattern_data = $this->deduplicateCompressionPattern($pattern_data, $pattern); $this->_patterns[$pattern] = $pattern_data; } } // Save the keys lowercased if needed if ($this->lowercase) { $this->_properties = array_map('strtolower', $this->_properties); } // Get the whole PHP code $cache = $this->_buildCache(); // Save and return return (bool) file_put_contents($cache_path, $cache, LOCK_EX); }
php
public function updateCache() { $ini_path = $this->cacheDir . $this->iniFilename; $cache_path = $this->cacheDir . $this->cacheFilename; // Choose the right url if ($this->_getUpdateMethod() == self::UPDATE_LOCAL) { $url = $this->localFile; } else { $url = $this->remoteIniUrl; } $this->_getRemoteIniFile($url, $ini_path); if (version_compare(PHP_VERSION, '5.3.0', '>=')) { $browsers = parse_ini_file($ini_path, true, INI_SCANNER_RAW); } else { $browsers = parse_ini_file($ini_path, true); } $this->_source_version = $browsers[self::BROWSCAP_VERSION_KEY]['Version']; unset($browsers[self::BROWSCAP_VERSION_KEY]); unset($browsers['DefaultProperties']['RenderingEngine_Description']); $this->_properties = array_keys($browsers['DefaultProperties']); array_unshift( $this->_properties, 'browser_name', 'browser_name_regex', 'browser_name_pattern', 'Parent' ); $tmp_user_agents = array_keys($browsers); usort($tmp_user_agents, array($this, 'compareBcStrings')); $user_agents_keys = array_flip($tmp_user_agents); $properties_keys = array_flip($this->_properties); $tmp_patterns = array(); foreach ($tmp_user_agents as $i => $user_agent) { if (empty($browsers[$user_agent]['Comment']) || strpos($user_agent, '*') !== false || strpos($user_agent, '?') !== false) { $pattern = $this->_pregQuote($user_agent); $matches_count = preg_match_all('@\d@', $pattern, $matches); if (!$matches_count) { $tmp_patterns[$pattern] = $i; } else { $compressed_pattern = preg_replace('@\d@', '(\d)', $pattern); if (!isset($tmp_patterns[$compressed_pattern])) { $tmp_patterns[$compressed_pattern] = array('first' => $pattern); } $tmp_patterns[$compressed_pattern][$i] = $matches[0]; } } if (!empty($browsers[$user_agent]['Parent'])) { $parent = $browsers[$user_agent]['Parent']; $parent_key = $user_agents_keys[$parent]; $browsers[$user_agent]['Parent'] = $parent_key; $this->_userAgents[$parent_key . '.0'] = $tmp_user_agents[$parent_key]; }; $browser = array(); foreach ($browsers[$user_agent] as $key => $value) { if (!isset($properties_keys[$key])) { continue; } $key = $properties_keys[$key]; $browser[$key] = $value; } $this->_browsers[] = $browser; } foreach ($tmp_patterns as $pattern => $pattern_data) { if (is_int($pattern_data)) { $this->_patterns[$pattern] = $pattern_data; } elseif (2 == count($pattern_data)) { end($pattern_data); $this->_patterns[$pattern_data['first']] = key($pattern_data); } else { unset($pattern_data['first']); $pattern_data = $this->deduplicateCompressionPattern($pattern_data, $pattern); $this->_patterns[$pattern] = $pattern_data; } } // Save the keys lowercased if needed if ($this->lowercase) { $this->_properties = array_map('strtolower', $this->_properties); } // Get the whole PHP code $cache = $this->_buildCache(); // Save and return return (bool) file_put_contents($cache_path, $cache, LOCK_EX); }
[ "public", "function", "updateCache", "(", ")", "{", "$", "ini_path", "=", "$", "this", "->", "cacheDir", ".", "$", "this", "->", "iniFilename", ";", "$", "cache_path", "=", "$", "this", "->", "cacheDir", ".", "$", "this", "->", "cacheFilename", ";", "// Choose the right url", "if", "(", "$", "this", "->", "_getUpdateMethod", "(", ")", "==", "self", "::", "UPDATE_LOCAL", ")", "{", "$", "url", "=", "$", "this", "->", "localFile", ";", "}", "else", "{", "$", "url", "=", "$", "this", "->", "remoteIniUrl", ";", "}", "$", "this", "->", "_getRemoteIniFile", "(", "$", "url", ",", "$", "ini_path", ")", ";", "if", "(", "version_compare", "(", "PHP_VERSION", ",", "'5.3.0'", ",", "'>='", ")", ")", "{", "$", "browsers", "=", "parse_ini_file", "(", "$", "ini_path", ",", "true", ",", "INI_SCANNER_RAW", ")", ";", "}", "else", "{", "$", "browsers", "=", "parse_ini_file", "(", "$", "ini_path", ",", "true", ")", ";", "}", "$", "this", "->", "_source_version", "=", "$", "browsers", "[", "self", "::", "BROWSCAP_VERSION_KEY", "]", "[", "'Version'", "]", ";", "unset", "(", "$", "browsers", "[", "self", "::", "BROWSCAP_VERSION_KEY", "]", ")", ";", "unset", "(", "$", "browsers", "[", "'DefaultProperties'", "]", "[", "'RenderingEngine_Description'", "]", ")", ";", "$", "this", "->", "_properties", "=", "array_keys", "(", "$", "browsers", "[", "'DefaultProperties'", "]", ")", ";", "array_unshift", "(", "$", "this", "->", "_properties", ",", "'browser_name'", ",", "'browser_name_regex'", ",", "'browser_name_pattern'", ",", "'Parent'", ")", ";", "$", "tmp_user_agents", "=", "array_keys", "(", "$", "browsers", ")", ";", "usort", "(", "$", "tmp_user_agents", ",", "array", "(", "$", "this", ",", "'compareBcStrings'", ")", ")", ";", "$", "user_agents_keys", "=", "array_flip", "(", "$", "tmp_user_agents", ")", ";", "$", "properties_keys", "=", "array_flip", "(", "$", "this", "->", "_properties", ")", ";", "$", "tmp_patterns", "=", "array", "(", ")", ";", "foreach", "(", "$", "tmp_user_agents", "as", "$", "i", "=>", "$", "user_agent", ")", "{", "if", "(", "empty", "(", "$", "browsers", "[", "$", "user_agent", "]", "[", "'Comment'", "]", ")", "||", "strpos", "(", "$", "user_agent", ",", "'*'", ")", "!==", "false", "||", "strpos", "(", "$", "user_agent", ",", "'?'", ")", "!==", "false", ")", "{", "$", "pattern", "=", "$", "this", "->", "_pregQuote", "(", "$", "user_agent", ")", ";", "$", "matches_count", "=", "preg_match_all", "(", "'@\\d@'", ",", "$", "pattern", ",", "$", "matches", ")", ";", "if", "(", "!", "$", "matches_count", ")", "{", "$", "tmp_patterns", "[", "$", "pattern", "]", "=", "$", "i", ";", "}", "else", "{", "$", "compressed_pattern", "=", "preg_replace", "(", "'@\\d@'", ",", "'(\\d)'", ",", "$", "pattern", ")", ";", "if", "(", "!", "isset", "(", "$", "tmp_patterns", "[", "$", "compressed_pattern", "]", ")", ")", "{", "$", "tmp_patterns", "[", "$", "compressed_pattern", "]", "=", "array", "(", "'first'", "=>", "$", "pattern", ")", ";", "}", "$", "tmp_patterns", "[", "$", "compressed_pattern", "]", "[", "$", "i", "]", "=", "$", "matches", "[", "0", "]", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "browsers", "[", "$", "user_agent", "]", "[", "'Parent'", "]", ")", ")", "{", "$", "parent", "=", "$", "browsers", "[", "$", "user_agent", "]", "[", "'Parent'", "]", ";", "$", "parent_key", "=", "$", "user_agents_keys", "[", "$", "parent", "]", ";", "$", "browsers", "[", "$", "user_agent", "]", "[", "'Parent'", "]", "=", "$", "parent_key", ";", "$", "this", "->", "_userAgents", "[", "$", "parent_key", ".", "'.0'", "]", "=", "$", "tmp_user_agents", "[", "$", "parent_key", "]", ";", "}", ";", "$", "browser", "=", "array", "(", ")", ";", "foreach", "(", "$", "browsers", "[", "$", "user_agent", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "properties_keys", "[", "$", "key", "]", ")", ")", "{", "continue", ";", "}", "$", "key", "=", "$", "properties_keys", "[", "$", "key", "]", ";", "$", "browser", "[", "$", "key", "]", "=", "$", "value", ";", "}", "$", "this", "->", "_browsers", "[", "]", "=", "$", "browser", ";", "}", "foreach", "(", "$", "tmp_patterns", "as", "$", "pattern", "=>", "$", "pattern_data", ")", "{", "if", "(", "is_int", "(", "$", "pattern_data", ")", ")", "{", "$", "this", "->", "_patterns", "[", "$", "pattern", "]", "=", "$", "pattern_data", ";", "}", "elseif", "(", "2", "==", "count", "(", "$", "pattern_data", ")", ")", "{", "end", "(", "$", "pattern_data", ")", ";", "$", "this", "->", "_patterns", "[", "$", "pattern_data", "[", "'first'", "]", "]", "=", "key", "(", "$", "pattern_data", ")", ";", "}", "else", "{", "unset", "(", "$", "pattern_data", "[", "'first'", "]", ")", ";", "$", "pattern_data", "=", "$", "this", "->", "deduplicateCompressionPattern", "(", "$", "pattern_data", ",", "$", "pattern", ")", ";", "$", "this", "->", "_patterns", "[", "$", "pattern", "]", "=", "$", "pattern_data", ";", "}", "}", "// Save the keys lowercased if needed", "if", "(", "$", "this", "->", "lowercase", ")", "{", "$", "this", "->", "_properties", "=", "array_map", "(", "'strtolower'", ",", "$", "this", "->", "_properties", ")", ";", "}", "// Get the whole PHP code", "$", "cache", "=", "$", "this", "->", "_buildCache", "(", ")", ";", "// Save and return", "return", "(", "bool", ")", "file_put_contents", "(", "$", "cache_path", ",", "$", "cache", ",", "LOCK_EX", ")", ";", "}" ]
XXX save Parses the ini file and updates the cache files @return bool whether the file was correctly written to the disk
[ "XXX", "save" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L489-L602
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap.deduplicateCompressionPattern
protected function deduplicateCompressionPattern($matches, &$pattern) { $tmp_matches = $matches; $first_match = array_shift($tmp_matches); $differences = array(); foreach ($tmp_matches as $some_match) { $differences += array_diff_assoc($first_match, $some_match); } $identical = array_diff_key($first_match, $differences); $prepared_matches = array(); foreach ($matches as $i => $some_match) { $prepared_matches[self::COMPRESSION_PATTERN_START . implode(self::COMPRESSION_PATTERN_DELIMITER, array_diff_assoc($some_match, $identical))] = $i; } $pattern_parts = explode('(\d)', $pattern); foreach ($identical as $position => $value) { $pattern_parts[$position + 1] = $pattern_parts[$position] . $value . $pattern_parts[$position + 1]; unset($pattern_parts[$position]); } $pattern = implode('(\d)', $pattern_parts); return $prepared_matches; }
php
protected function deduplicateCompressionPattern($matches, &$pattern) { $tmp_matches = $matches; $first_match = array_shift($tmp_matches); $differences = array(); foreach ($tmp_matches as $some_match) { $differences += array_diff_assoc($first_match, $some_match); } $identical = array_diff_key($first_match, $differences); $prepared_matches = array(); foreach ($matches as $i => $some_match) { $prepared_matches[self::COMPRESSION_PATTERN_START . implode(self::COMPRESSION_PATTERN_DELIMITER, array_diff_assoc($some_match, $identical))] = $i; } $pattern_parts = explode('(\d)', $pattern); foreach ($identical as $position => $value) { $pattern_parts[$position + 1] = $pattern_parts[$position] . $value . $pattern_parts[$position + 1]; unset($pattern_parts[$position]); } $pattern = implode('(\d)', $pattern_parts); return $prepared_matches; }
[ "protected", "function", "deduplicateCompressionPattern", "(", "$", "matches", ",", "&", "$", "pattern", ")", "{", "$", "tmp_matches", "=", "$", "matches", ";", "$", "first_match", "=", "array_shift", "(", "$", "tmp_matches", ")", ";", "$", "differences", "=", "array", "(", ")", ";", "foreach", "(", "$", "tmp_matches", "as", "$", "some_match", ")", "{", "$", "differences", "+=", "array_diff_assoc", "(", "$", "first_match", ",", "$", "some_match", ")", ";", "}", "$", "identical", "=", "array_diff_key", "(", "$", "first_match", ",", "$", "differences", ")", ";", "$", "prepared_matches", "=", "array", "(", ")", ";", "foreach", "(", "$", "matches", "as", "$", "i", "=>", "$", "some_match", ")", "{", "$", "prepared_matches", "[", "self", "::", "COMPRESSION_PATTERN_START", ".", "implode", "(", "self", "::", "COMPRESSION_PATTERN_DELIMITER", ",", "array_diff_assoc", "(", "$", "some_match", ",", "$", "identical", ")", ")", "]", "=", "$", "i", ";", "}", "$", "pattern_parts", "=", "explode", "(", "'(\\d)'", ",", "$", "pattern", ")", ";", "foreach", "(", "$", "identical", "as", "$", "position", "=>", "$", "value", ")", "{", "$", "pattern_parts", "[", "$", "position", "+", "1", "]", "=", "$", "pattern_parts", "[", "$", "position", "]", ".", "$", "value", ".", "$", "pattern_parts", "[", "$", "position", "+", "1", "]", ";", "unset", "(", "$", "pattern_parts", "[", "$", "position", "]", ")", ";", "}", "$", "pattern", "=", "implode", "(", "'(\\d)'", ",", "$", "pattern_parts", ")", ";", "return", "$", "prepared_matches", ";", "}" ]
That looks complicated... All numbers are taken out into $matches, so we check if any of those numbers are identical in all the $matches and if they are we restore them to the $pattern, removing from the $matches. This gives us patterns with "(\d)" only in places that differ for some matches. @param array $matches @param string $pattern @return array of $matches
[ "That", "looks", "complicated", "..." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L633-L666
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._pregQuote
protected function _pregQuote($user_agent) { $pattern = preg_quote($user_agent, self::REGEX_DELIMITER); // the \\x replacement is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match return self::REGEX_DELIMITER . '^' . str_replace(array('\*', '\?', '\\x'), array('.*', '.', '\\\\x'), $pattern) . '$' . self::REGEX_DELIMITER; }
php
protected function _pregQuote($user_agent) { $pattern = preg_quote($user_agent, self::REGEX_DELIMITER); // the \\x replacement is a fix for "Der gro\xdfe BilderSauger 2.00u" user agent match return self::REGEX_DELIMITER . '^' . str_replace(array('\*', '\?', '\\x'), array('.*', '.', '\\\\x'), $pattern) . '$' . self::REGEX_DELIMITER; }
[ "protected", "function", "_pregQuote", "(", "$", "user_agent", ")", "{", "$", "pattern", "=", "preg_quote", "(", "$", "user_agent", ",", "self", "::", "REGEX_DELIMITER", ")", ";", "// the \\\\x replacement is a fix for \"Der gro\\xdfe BilderSauger 2.00u\" user agent match", "return", "self", "::", "REGEX_DELIMITER", ".", "'^'", ".", "str_replace", "(", "array", "(", "'\\*'", ",", "'\\?'", ",", "'\\\\x'", ")", ",", "array", "(", "'.*'", ",", "'.'", ",", "'\\\\\\\\x'", ")", ",", "$", "pattern", ")", ".", "'$'", ".", "self", "::", "REGEX_DELIMITER", ";", "}" ]
Converts browscap match patterns into preg match patterns. @param string $user_agent @return string
[ "Converts", "browscap", "match", "patterns", "into", "preg", "match", "patterns", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L675-L686
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._pregUnQuote
protected function _pregUnQuote($pattern, $matches) { // list of escaped characters: http://www.php.net/manual/en/function.preg-quote.php // to properly unescape '?' which was changed to '.', I replace '\.' (real dot) with '\?', then change '.' to '?' and then '\?' to '.'. $search = array('\\' . self::REGEX_DELIMITER, '\\.', '\\\\', '\\+', '\\[', '\\^', '\\]', '\\$', '\\(', '\\)', '\\{', '\\}', '\\=', '\\!', '\\<', '\\>', '\\|', '\\:', '\\-', '.*', '.', '\\?'); $replace = array(self::REGEX_DELIMITER, '\\?', '\\', '+', '[', '^', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', '-', '*', '?', '.'); $result = substr(str_replace($search, $replace, $pattern), 2, -2); if ($matches) { foreach ($matches as $one_match) { $num_pos = strpos($result, '(\d)'); $result = substr_replace($result, $one_match, $num_pos, 4); } } return $result; }
php
protected function _pregUnQuote($pattern, $matches) { // list of escaped characters: http://www.php.net/manual/en/function.preg-quote.php // to properly unescape '?' which was changed to '.', I replace '\.' (real dot) with '\?', then change '.' to '?' and then '\?' to '.'. $search = array('\\' . self::REGEX_DELIMITER, '\\.', '\\\\', '\\+', '\\[', '\\^', '\\]', '\\$', '\\(', '\\)', '\\{', '\\}', '\\=', '\\!', '\\<', '\\>', '\\|', '\\:', '\\-', '.*', '.', '\\?'); $replace = array(self::REGEX_DELIMITER, '\\?', '\\', '+', '[', '^', ']', '$', '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', '-', '*', '?', '.'); $result = substr(str_replace($search, $replace, $pattern), 2, -2); if ($matches) { foreach ($matches as $one_match) { $num_pos = strpos($result, '(\d)'); $result = substr_replace($result, $one_match, $num_pos, 4); } } return $result; }
[ "protected", "function", "_pregUnQuote", "(", "$", "pattern", ",", "$", "matches", ")", "{", "// list of escaped characters: http://www.php.net/manual/en/function.preg-quote.php", "// to properly unescape '?' which was changed to '.', I replace '\\.' (real dot) with '\\?', then change '.' to '?' and then '\\?' to '.'.", "$", "search", "=", "array", "(", "'\\\\'", ".", "self", "::", "REGEX_DELIMITER", ",", "'\\\\.'", ",", "'\\\\\\\\'", ",", "'\\\\+'", ",", "'\\\\['", ",", "'\\\\^'", ",", "'\\\\]'", ",", "'\\\\$'", ",", "'\\\\('", ",", "'\\\\)'", ",", "'\\\\{'", ",", "'\\\\}'", ",", "'\\\\='", ",", "'\\\\!'", ",", "'\\\\<'", ",", "'\\\\>'", ",", "'\\\\|'", ",", "'\\\\:'", ",", "'\\\\-'", ",", "'.*'", ",", "'.'", ",", "'\\\\?'", ")", ";", "$", "replace", "=", "array", "(", "self", "::", "REGEX_DELIMITER", ",", "'\\\\?'", ",", "'\\\\'", ",", "'+'", ",", "'['", ",", "'^'", ",", "']'", ",", "'$'", ",", "'('", ",", "')'", ",", "'{'", ",", "'}'", ",", "'='", ",", "'!'", ",", "'<'", ",", "'>'", ",", "'|'", ",", "':'", ",", "'-'", ",", "'*'", ",", "'?'", ",", "'.'", ")", ";", "$", "result", "=", "substr", "(", "str_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "pattern", ")", ",", "2", ",", "-", "2", ")", ";", "if", "(", "$", "matches", ")", "{", "foreach", "(", "$", "matches", "as", "$", "one_match", ")", "{", "$", "num_pos", "=", "strpos", "(", "$", "result", ",", "'(\\d)'", ")", ";", "$", "result", "=", "substr_replace", "(", "$", "result", ",", "$", "one_match", ",", "$", "num_pos", ",", "4", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Converts preg match patterns back to browscap match patterns. @param string $pattern @param array $matches @return string
[ "Converts", "preg", "match", "patterns", "back", "to", "browscap", "match", "patterns", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L696-L715
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._loadCache
protected function _loadCache($cache_file) { require $cache_file; if (!isset($cache_version) || $cache_version != self::CACHE_FILE_VERSION) { return false; } $this->_source_version = $source_version; $this->_browsers = $browsers; $this->_userAgents = $userAgents; $this->_patterns = $patterns; $this->_properties = $properties; $this->_cacheLoaded = true; return true; }
php
protected function _loadCache($cache_file) { require $cache_file; if (!isset($cache_version) || $cache_version != self::CACHE_FILE_VERSION) { return false; } $this->_source_version = $source_version; $this->_browsers = $browsers; $this->_userAgents = $userAgents; $this->_patterns = $patterns; $this->_properties = $properties; $this->_cacheLoaded = true; return true; }
[ "protected", "function", "_loadCache", "(", "$", "cache_file", ")", "{", "require", "$", "cache_file", ";", "if", "(", "!", "isset", "(", "$", "cache_version", ")", "||", "$", "cache_version", "!=", "self", "::", "CACHE_FILE_VERSION", ")", "{", "return", "false", ";", "}", "$", "this", "->", "_source_version", "=", "$", "source_version", ";", "$", "this", "->", "_browsers", "=", "$", "browsers", ";", "$", "this", "->", "_userAgents", "=", "$", "userAgents", ";", "$", "this", "->", "_patterns", "=", "$", "patterns", ";", "$", "this", "->", "_properties", "=", "$", "properties", ";", "$", "this", "->", "_cacheLoaded", "=", "true", ";", "return", "true", ";", "}" ]
Loads the cache into object's properties @param $cache_file @return boolean
[ "Loads", "the", "cache", "into", "object", "s", "properties" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L724-L742
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._buildCache
protected function _buildCache() { $cacheTpl = "<?php\n\$source_version=%s;\n\$cache_version=%s;\n\$properties=%s;\n\$browsers=%s;\n\$userAgents=%s;\n\$patterns=%s;\n"; $propertiesArray = $this->_array2string($this->_properties); $patternsArray = $this->_array2string($this->_patterns); $userAgentsArray = $this->_array2string($this->_userAgents); $browsersArray = $this->_array2string($this->_browsers); return sprintf( $cacheTpl, "'" . $this->_source_version . "'", "'" . self::CACHE_FILE_VERSION . "'", $propertiesArray, $browsersArray, $userAgentsArray, $patternsArray ); }
php
protected function _buildCache() { $cacheTpl = "<?php\n\$source_version=%s;\n\$cache_version=%s;\n\$properties=%s;\n\$browsers=%s;\n\$userAgents=%s;\n\$patterns=%s;\n"; $propertiesArray = $this->_array2string($this->_properties); $patternsArray = $this->_array2string($this->_patterns); $userAgentsArray = $this->_array2string($this->_userAgents); $browsersArray = $this->_array2string($this->_browsers); return sprintf( $cacheTpl, "'" . $this->_source_version . "'", "'" . self::CACHE_FILE_VERSION . "'", $propertiesArray, $browsersArray, $userAgentsArray, $patternsArray ); }
[ "protected", "function", "_buildCache", "(", ")", "{", "$", "cacheTpl", "=", "\"<?php\\n\\$source_version=%s;\\n\\$cache_version=%s;\\n\\$properties=%s;\\n\\$browsers=%s;\\n\\$userAgents=%s;\\n\\$patterns=%s;\\n\"", ";", "$", "propertiesArray", "=", "$", "this", "->", "_array2string", "(", "$", "this", "->", "_properties", ")", ";", "$", "patternsArray", "=", "$", "this", "->", "_array2string", "(", "$", "this", "->", "_patterns", ")", ";", "$", "userAgentsArray", "=", "$", "this", "->", "_array2string", "(", "$", "this", "->", "_userAgents", ")", ";", "$", "browsersArray", "=", "$", "this", "->", "_array2string", "(", "$", "this", "->", "_browsers", ")", ";", "return", "sprintf", "(", "$", "cacheTpl", ",", "\"'\"", ".", "$", "this", "->", "_source_version", ".", "\"'\"", ",", "\"'\"", ".", "self", "::", "CACHE_FILE_VERSION", ".", "\"'\"", ",", "$", "propertiesArray", ",", "$", "browsersArray", ",", "$", "userAgentsArray", ",", "$", "patternsArray", ")", ";", "}" ]
Parses the array to cache and creates the PHP string to write to disk @return string the PHP string to save into the cache file
[ "Parses", "the", "array", "to", "cache", "and", "creates", "the", "PHP", "string", "to", "write", "to", "disk" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L749-L767
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._getStreamContext
protected function _getStreamContext($recreate = false) { if (!isset($this->_streamContext) || true === $recreate) { $this->_streamContext = stream_context_create($this->_streamContextOptions); } return $this->_streamContext; }
php
protected function _getStreamContext($recreate = false) { if (!isset($this->_streamContext) || true === $recreate) { $this->_streamContext = stream_context_create($this->_streamContextOptions); } return $this->_streamContext; }
[ "protected", "function", "_getStreamContext", "(", "$", "recreate", "=", "false", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_streamContext", ")", "||", "true", "===", "$", "recreate", ")", "{", "$", "this", "->", "_streamContext", "=", "stream_context_create", "(", "$", "this", "->", "_streamContextOptions", ")", ";", "}", "return", "$", "this", "->", "_streamContext", ";", "}" ]
Lazy getter for the stream context resource. @param bool $recreate @return resource
[ "Lazy", "getter", "for", "the", "stream", "context", "resource", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L776-L783
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._getRemoteIniFile
protected function _getRemoteIniFile($url, $path) { // Check version if (file_exists($path) && filesize($path)) { $local_tmstp = filemtime($path); if ($this->_getUpdateMethod() == self::UPDATE_LOCAL) { $remote_tmstp = $this->_getLocalMTime(); } else { $remote_tmstp = $this->_getRemoteMTime(); } if ($remote_tmstp < $local_tmstp) { // No update needed, return touch($path); return false; } } // Get updated .ini file $browscap = $this->_getRemoteData($url); $browscap = explode("\n", $browscap); $pattern = self::REGEX_DELIMITER . '(' . self::VALUES_TO_QUOTE . ')="?([^"]*)"?$' . self::REGEX_DELIMITER; // Ok, lets read the file $content = ''; foreach ($browscap as $subject) { $subject = trim($subject); $content .= preg_replace($pattern, '$1="$2"', $subject) . "\n"; } if ($url != $path) { if (!file_put_contents($path, $content)) { throw new Exception("Could not write .ini content to $path"); } } return true; }
php
protected function _getRemoteIniFile($url, $path) { // Check version if (file_exists($path) && filesize($path)) { $local_tmstp = filemtime($path); if ($this->_getUpdateMethod() == self::UPDATE_LOCAL) { $remote_tmstp = $this->_getLocalMTime(); } else { $remote_tmstp = $this->_getRemoteMTime(); } if ($remote_tmstp < $local_tmstp) { // No update needed, return touch($path); return false; } } // Get updated .ini file $browscap = $this->_getRemoteData($url); $browscap = explode("\n", $browscap); $pattern = self::REGEX_DELIMITER . '(' . self::VALUES_TO_QUOTE . ')="?([^"]*)"?$' . self::REGEX_DELIMITER; // Ok, lets read the file $content = ''; foreach ($browscap as $subject) { $subject = trim($subject); $content .= preg_replace($pattern, '$1="$2"', $subject) . "\n"; } if ($url != $path) { if (!file_put_contents($path, $content)) { throw new Exception("Could not write .ini content to $path"); } } return true; }
[ "protected", "function", "_getRemoteIniFile", "(", "$", "url", ",", "$", "path", ")", "{", "// Check version", "if", "(", "file_exists", "(", "$", "path", ")", "&&", "filesize", "(", "$", "path", ")", ")", "{", "$", "local_tmstp", "=", "filemtime", "(", "$", "path", ")", ";", "if", "(", "$", "this", "->", "_getUpdateMethod", "(", ")", "==", "self", "::", "UPDATE_LOCAL", ")", "{", "$", "remote_tmstp", "=", "$", "this", "->", "_getLocalMTime", "(", ")", ";", "}", "else", "{", "$", "remote_tmstp", "=", "$", "this", "->", "_getRemoteMTime", "(", ")", ";", "}", "if", "(", "$", "remote_tmstp", "<", "$", "local_tmstp", ")", "{", "// No update needed, return", "touch", "(", "$", "path", ")", ";", "return", "false", ";", "}", "}", "// Get updated .ini file", "$", "browscap", "=", "$", "this", "->", "_getRemoteData", "(", "$", "url", ")", ";", "$", "browscap", "=", "explode", "(", "\"\\n\"", ",", "$", "browscap", ")", ";", "$", "pattern", "=", "self", "::", "REGEX_DELIMITER", ".", "'('", ".", "self", "::", "VALUES_TO_QUOTE", ".", "')=\"?([^\"]*)\"?$'", ".", "self", "::", "REGEX_DELIMITER", ";", "// Ok, lets read the file", "$", "content", "=", "''", ";", "foreach", "(", "$", "browscap", "as", "$", "subject", ")", "{", "$", "subject", "=", "trim", "(", "$", "subject", ")", ";", "$", "content", ".=", "preg_replace", "(", "$", "pattern", ",", "'$1=\"$2\"'", ",", "$", "subject", ")", ".", "\"\\n\"", ";", "}", "if", "(", "$", "url", "!=", "$", "path", ")", "{", "if", "(", "!", "file_put_contents", "(", "$", "path", ",", "$", "content", ")", ")", "{", "throw", "new", "Exception", "(", "\"Could not write .ini content to $path\"", ")", ";", "}", "}", "return", "true", ";", "}" ]
Updates the local copy of the ini file (by version checking) and adapts his syntax to the PHP ini parser @param string $url the url of the remote server @param string $path the path of the ini file to update @throws Exception @return bool if the ini file was updated
[ "Updates", "the", "local", "copy", "of", "the", "ini", "file", "(", "by", "version", "checking", ")", "and", "adapts", "his", "syntax", "to", "the", "PHP", "ini", "parser" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L794-L841
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._getRemoteMTime
protected function _getRemoteMTime() { $remote_datetime = $this->_getRemoteData($this->remoteVerUrl); $remote_tmstp = strtotime($remote_datetime); if (!$remote_tmstp) { throw new Exception("Bad datetime format from {$this->remoteVerUrl}"); } return $remote_tmstp; }
php
protected function _getRemoteMTime() { $remote_datetime = $this->_getRemoteData($this->remoteVerUrl); $remote_tmstp = strtotime($remote_datetime); if (!$remote_tmstp) { throw new Exception("Bad datetime format from {$this->remoteVerUrl}"); } return $remote_tmstp; }
[ "protected", "function", "_getRemoteMTime", "(", ")", "{", "$", "remote_datetime", "=", "$", "this", "->", "_getRemoteData", "(", "$", "this", "->", "remoteVerUrl", ")", ";", "$", "remote_tmstp", "=", "strtotime", "(", "$", "remote_datetime", ")", ";", "if", "(", "!", "$", "remote_tmstp", ")", "{", "throw", "new", "Exception", "(", "\"Bad datetime format from {$this->remoteVerUrl}\"", ")", ";", "}", "return", "$", "remote_tmstp", ";", "}" ]
Gets the remote ini file update timestamp @throws Exception @return int the remote modification timestamp
[ "Gets", "the", "remote", "ini", "file", "update", "timestamp" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L849-L859
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._getLocalMTime
protected function _getLocalMTime() { if (!is_readable($this->localFile) || !is_file($this->localFile)) { throw new Exception("Local file is not readable"); } return filemtime($this->localFile); }
php
protected function _getLocalMTime() { if (!is_readable($this->localFile) || !is_file($this->localFile)) { throw new Exception("Local file is not readable"); } return filemtime($this->localFile); }
[ "protected", "function", "_getLocalMTime", "(", ")", "{", "if", "(", "!", "is_readable", "(", "$", "this", "->", "localFile", ")", "||", "!", "is_file", "(", "$", "this", "->", "localFile", ")", ")", "{", "throw", "new", "Exception", "(", "\"Local file is not readable\"", ")", ";", "}", "return", "filemtime", "(", "$", "this", "->", "localFile", ")", ";", "}" ]
Gets the local ini file update timestamp @throws Exception @return int the local modification timestamp
[ "Gets", "the", "local", "ini", "file", "update", "timestamp" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L867-L874
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._array2string
protected function _array2string($array) { $strings = array(); foreach ($array as $key => $value) { if (is_int($key)) { $key = ''; } elseif (ctype_digit((string) $key) || '.0' === substr($key, -2)) { $key = intval($key) . '=>' ; } else { $key = "'" . str_replace("'", "\'", $key) . "'=>" ; } if (is_array($value)) { $value = "'" . addcslashes(serialize($value), "'") . "'"; } elseif (ctype_digit((string) $value)) { $value = intval($value); } else { $value = "'" . str_replace("'", "\'", $value) . "'"; } $strings[] = $key . $value; } return "array(\n" . implode(",\n", $strings) . "\n)"; }
php
protected function _array2string($array) { $strings = array(); foreach ($array as $key => $value) { if (is_int($key)) { $key = ''; } elseif (ctype_digit((string) $key) || '.0' === substr($key, -2)) { $key = intval($key) . '=>' ; } else { $key = "'" . str_replace("'", "\'", $key) . "'=>" ; } if (is_array($value)) { $value = "'" . addcslashes(serialize($value), "'") . "'"; } elseif (ctype_digit((string) $value)) { $value = intval($value); } else { $value = "'" . str_replace("'", "\'", $value) . "'"; } $strings[] = $key . $value; } return "array(\n" . implode(",\n", $strings) . "\n)"; }
[ "protected", "function", "_array2string", "(", "$", "array", ")", "{", "$", "strings", "=", "array", "(", ")", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "key", "=", "''", ";", "}", "elseif", "(", "ctype_digit", "(", "(", "string", ")", "$", "key", ")", "||", "'.0'", "===", "substr", "(", "$", "key", ",", "-", "2", ")", ")", "{", "$", "key", "=", "intval", "(", "$", "key", ")", ".", "'=>'", ";", "}", "else", "{", "$", "key", "=", "\"'\"", ".", "str_replace", "(", "\"'\"", ",", "\"\\'\"", ",", "$", "key", ")", ".", "\"'=>\"", ";", "}", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "\"'\"", ".", "addcslashes", "(", "serialize", "(", "$", "value", ")", ",", "\"'\"", ")", ".", "\"'\"", ";", "}", "elseif", "(", "ctype_digit", "(", "(", "string", ")", "$", "value", ")", ")", "{", "$", "value", "=", "intval", "(", "$", "value", ")", ";", "}", "else", "{", "$", "value", "=", "\"'\"", ".", "str_replace", "(", "\"'\"", ",", "\"\\'\"", ",", "$", "value", ")", ".", "\"'\"", ";", "}", "$", "strings", "[", "]", "=", "$", "key", ".", "$", "value", ";", "}", "return", "\"array(\\n\"", ".", "implode", "(", "\",\\n\"", ",", "$", "strings", ")", ".", "\"\\n)\"", ";", "}" ]
Converts the given array to the PHP string which represent it. This method optimizes the PHP code and the output differs form the var_export one as the internal PHP function does not strip whitespace or convert strings to numbers. @param array $array the array to parse and convert @return string the array parsed into a PHP string
[ "Converts", "the", "given", "array", "to", "the", "PHP", "string", "which", "represent", "it", ".", "This", "method", "optimizes", "the", "PHP", "code", "and", "the", "output", "differs", "form", "the", "var_export", "one", "as", "the", "internal", "PHP", "function", "does", "not", "strip", "whitespace", "or", "convert", "strings", "to", "numbers", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L885-L910
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._getUpdateMethod
protected function _getUpdateMethod() { // Caches the result if ($this->updateMethod === null) { if ($this->localFile !== null) { $this->updateMethod = self::UPDATE_LOCAL; } elseif (ini_get('allow_url_fopen') && function_exists('file_get_contents')) { $this->updateMethod = self::UPDATE_FOPEN; } elseif (function_exists('fsockopen')) { $this->updateMethod = self::UPDATE_FSOCKOPEN; } elseif (extension_loaded('curl')) { $this->updateMethod = self::UPDATE_CURL; } else { $this->updateMethod = false; } } return $this->updateMethod; }
php
protected function _getUpdateMethod() { // Caches the result if ($this->updateMethod === null) { if ($this->localFile !== null) { $this->updateMethod = self::UPDATE_LOCAL; } elseif (ini_get('allow_url_fopen') && function_exists('file_get_contents')) { $this->updateMethod = self::UPDATE_FOPEN; } elseif (function_exists('fsockopen')) { $this->updateMethod = self::UPDATE_FSOCKOPEN; } elseif (extension_loaded('curl')) { $this->updateMethod = self::UPDATE_CURL; } else { $this->updateMethod = false; } } return $this->updateMethod; }
[ "protected", "function", "_getUpdateMethod", "(", ")", "{", "// Caches the result", "if", "(", "$", "this", "->", "updateMethod", "===", "null", ")", "{", "if", "(", "$", "this", "->", "localFile", "!==", "null", ")", "{", "$", "this", "->", "updateMethod", "=", "self", "::", "UPDATE_LOCAL", ";", "}", "elseif", "(", "ini_get", "(", "'allow_url_fopen'", ")", "&&", "function_exists", "(", "'file_get_contents'", ")", ")", "{", "$", "this", "->", "updateMethod", "=", "self", "::", "UPDATE_FOPEN", ";", "}", "elseif", "(", "function_exists", "(", "'fsockopen'", ")", ")", "{", "$", "this", "->", "updateMethod", "=", "self", "::", "UPDATE_FSOCKOPEN", ";", "}", "elseif", "(", "extension_loaded", "(", "'curl'", ")", ")", "{", "$", "this", "->", "updateMethod", "=", "self", "::", "UPDATE_CURL", ";", "}", "else", "{", "$", "this", "->", "updateMethod", "=", "false", ";", "}", "}", "return", "$", "this", "->", "updateMethod", ";", "}" ]
Checks for the various possibilities offered by the current configuration of PHP to retrieve external HTTP data @return string the name of function to use to retrieve the file
[ "Checks", "for", "the", "various", "possibilities", "offered", "by", "the", "current", "configuration", "of", "PHP", "to", "retrieve", "external", "HTTP", "data" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L918-L936
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._getRemoteData
protected function _getRemoteData($url) { ini_set('user_agent', $this->_getUserAgent()); switch ($this->_getUpdateMethod()) { case self::UPDATE_LOCAL: $file = file_get_contents($url); if ($file !== false) { return $file; } else { throw new Exception('Cannot open the local file'); } case self::UPDATE_FOPEN: // include proxy settings in the file_get_contents() call $context = $this->_getStreamContext(); $file = file_get_contents($url, false, $context); if ($file !== false) { return $file; } // else try with the next possibility (break omitted) case self::UPDATE_FSOCKOPEN: $remote_url = parse_url($url); $remote_handler = fsockopen($remote_url['host'], 80, $c, $e, $this->timeout); if ($remote_handler) { stream_set_timeout($remote_handler, $this->timeout); if (isset($remote_url['query'])) { $remote_url['path'] .= '?' . $remote_url['query']; } $out = sprintf( self::REQUEST_HEADERS, $remote_url['path'], $remote_url['host'], $this->_getUserAgent() ); fwrite($remote_handler, $out); $response = fgets($remote_handler); if (strpos($response, '200 OK') !== false) { $file = ''; while (!feof($remote_handler)) { $file .= fgets($remote_handler); } $file = str_replace("\r\n", "\n", $file); $file = explode("\n\n", $file); array_shift($file); $file = implode("\n\n", $file); fclose($remote_handler); return $file; } } // else try with the next possibility case self::UPDATE_CURL: $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout); curl_setopt($ch, CURLOPT_USERAGENT, $this->_getUserAgent()); $file = curl_exec($ch); curl_close($ch); if ($file !== false) { return $file; } // else try with the next possibility case false: throw new Exception('Your server can\'t connect to external resources. Please update the file manually.'); } return ''; }
php
protected function _getRemoteData($url) { ini_set('user_agent', $this->_getUserAgent()); switch ($this->_getUpdateMethod()) { case self::UPDATE_LOCAL: $file = file_get_contents($url); if ($file !== false) { return $file; } else { throw new Exception('Cannot open the local file'); } case self::UPDATE_FOPEN: // include proxy settings in the file_get_contents() call $context = $this->_getStreamContext(); $file = file_get_contents($url, false, $context); if ($file !== false) { return $file; } // else try with the next possibility (break omitted) case self::UPDATE_FSOCKOPEN: $remote_url = parse_url($url); $remote_handler = fsockopen($remote_url['host'], 80, $c, $e, $this->timeout); if ($remote_handler) { stream_set_timeout($remote_handler, $this->timeout); if (isset($remote_url['query'])) { $remote_url['path'] .= '?' . $remote_url['query']; } $out = sprintf( self::REQUEST_HEADERS, $remote_url['path'], $remote_url['host'], $this->_getUserAgent() ); fwrite($remote_handler, $out); $response = fgets($remote_handler); if (strpos($response, '200 OK') !== false) { $file = ''; while (!feof($remote_handler)) { $file .= fgets($remote_handler); } $file = str_replace("\r\n", "\n", $file); $file = explode("\n\n", $file); array_shift($file); $file = implode("\n\n", $file); fclose($remote_handler); return $file; } } // else try with the next possibility case self::UPDATE_CURL: $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout); curl_setopt($ch, CURLOPT_USERAGENT, $this->_getUserAgent()); $file = curl_exec($ch); curl_close($ch); if ($file !== false) { return $file; } // else try with the next possibility case false: throw new Exception('Your server can\'t connect to external resources. Please update the file manually.'); } return ''; }
[ "protected", "function", "_getRemoteData", "(", "$", "url", ")", "{", "ini_set", "(", "'user_agent'", ",", "$", "this", "->", "_getUserAgent", "(", ")", ")", ";", "switch", "(", "$", "this", "->", "_getUpdateMethod", "(", ")", ")", "{", "case", "self", "::", "UPDATE_LOCAL", ":", "$", "file", "=", "file_get_contents", "(", "$", "url", ")", ";", "if", "(", "$", "file", "!==", "false", ")", "{", "return", "$", "file", ";", "}", "else", "{", "throw", "new", "Exception", "(", "'Cannot open the local file'", ")", ";", "}", "case", "self", "::", "UPDATE_FOPEN", ":", "// include proxy settings in the file_get_contents() call", "$", "context", "=", "$", "this", "->", "_getStreamContext", "(", ")", ";", "$", "file", "=", "file_get_contents", "(", "$", "url", ",", "false", ",", "$", "context", ")", ";", "if", "(", "$", "file", "!==", "false", ")", "{", "return", "$", "file", ";", "}", "// else try with the next possibility (break omitted)", "case", "self", "::", "UPDATE_FSOCKOPEN", ":", "$", "remote_url", "=", "parse_url", "(", "$", "url", ")", ";", "$", "remote_handler", "=", "fsockopen", "(", "$", "remote_url", "[", "'host'", "]", ",", "80", ",", "$", "c", ",", "$", "e", ",", "$", "this", "->", "timeout", ")", ";", "if", "(", "$", "remote_handler", ")", "{", "stream_set_timeout", "(", "$", "remote_handler", ",", "$", "this", "->", "timeout", ")", ";", "if", "(", "isset", "(", "$", "remote_url", "[", "'query'", "]", ")", ")", "{", "$", "remote_url", "[", "'path'", "]", ".=", "'?'", ".", "$", "remote_url", "[", "'query'", "]", ";", "}", "$", "out", "=", "sprintf", "(", "self", "::", "REQUEST_HEADERS", ",", "$", "remote_url", "[", "'path'", "]", ",", "$", "remote_url", "[", "'host'", "]", ",", "$", "this", "->", "_getUserAgent", "(", ")", ")", ";", "fwrite", "(", "$", "remote_handler", ",", "$", "out", ")", ";", "$", "response", "=", "fgets", "(", "$", "remote_handler", ")", ";", "if", "(", "strpos", "(", "$", "response", ",", "'200 OK'", ")", "!==", "false", ")", "{", "$", "file", "=", "''", ";", "while", "(", "!", "feof", "(", "$", "remote_handler", ")", ")", "{", "$", "file", ".=", "fgets", "(", "$", "remote_handler", ")", ";", "}", "$", "file", "=", "str_replace", "(", "\"\\r\\n\"", ",", "\"\\n\"", ",", "$", "file", ")", ";", "$", "file", "=", "explode", "(", "\"\\n\\n\"", ",", "$", "file", ")", ";", "array_shift", "(", "$", "file", ")", ";", "$", "file", "=", "implode", "(", "\"\\n\\n\"", ",", "$", "file", ")", ";", "fclose", "(", "$", "remote_handler", ")", ";", "return", "$", "file", ";", "}", "}", "// else try with the next possibility", "case", "self", "::", "UPDATE_CURL", ":", "$", "ch", "=", "curl_init", "(", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CONNECTTIMEOUT", ",", "$", "this", "->", "timeout", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "$", "this", "->", "_getUserAgent", "(", ")", ")", ";", "$", "file", "=", "curl_exec", "(", "$", "ch", ")", ";", "curl_close", "(", "$", "ch", ")", ";", "if", "(", "$", "file", "!==", "false", ")", "{", "return", "$", "file", ";", "}", "// else try with the next possibility", "case", "false", ":", "throw", "new", "Exception", "(", "'Your server can\\'t connect to external resources. Please update the file manually.'", ")", ";", "}", "return", "''", ";", "}" ]
Retrieve the data identified by the URL @param string $url the url of the data @throws Exception @return string the retrieved data
[ "Retrieve", "the", "data", "identified", "by", "the", "URL" ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L945-L1023
GaretJax/phpbrowscap
src/phpbrowscap/Browscap.php
Browscap._getUserAgent
protected function _getUserAgent() { $ua = str_replace('%v', self::VERSION, $this->userAgent); $ua = str_replace('%m', $this->_getUpdateMethod(), $ua); return $ua; }
php
protected function _getUserAgent() { $ua = str_replace('%v', self::VERSION, $this->userAgent); $ua = str_replace('%m', $this->_getUpdateMethod(), $ua); return $ua; }
[ "protected", "function", "_getUserAgent", "(", ")", "{", "$", "ua", "=", "str_replace", "(", "'%v'", ",", "self", "::", "VERSION", ",", "$", "this", "->", "userAgent", ")", ";", "$", "ua", "=", "str_replace", "(", "'%m'", ",", "$", "this", "->", "_getUpdateMethod", "(", ")", ",", "$", "ua", ")", ";", "return", "$", "ua", ";", "}" ]
Format the useragent string to be used in the remote requests made by the class during the update process. @return string the formatted user agent
[ "Format", "the", "useragent", "string", "to", "be", "used", "in", "the", "remote", "requests", "made", "by", "the", "class", "during", "the", "update", "process", "." ]
train
https://github.com/GaretJax/phpbrowscap/blob/ed661716d0d9158bac6ab3b074b18b70f8d18bef/src/phpbrowscap/Browscap.php#L1031-L1037
varspool/Wrench
lib/Socket/UriSocket.php
UriSocket.getStreamContext
protected function getStreamContext($listen = false) { $options = []; if ($this->scheme == Protocol::SCHEME_UNDERLYING_SECURE || $this->scheme == Protocol::SCHEME_UNDERLYING ) { $options['socket'] = $this->getSocketStreamContextOptions(); } if ($this->scheme == Protocol::SCHEME_UNDERLYING_SECURE) { $options['ssl'] = $this->getSslStreamContextOptions(); } return stream_context_create( $options, [] ); }
php
protected function getStreamContext($listen = false) { $options = []; if ($this->scheme == Protocol::SCHEME_UNDERLYING_SECURE || $this->scheme == Protocol::SCHEME_UNDERLYING ) { $options['socket'] = $this->getSocketStreamContextOptions(); } if ($this->scheme == Protocol::SCHEME_UNDERLYING_SECURE) { $options['ssl'] = $this->getSslStreamContextOptions(); } return stream_context_create( $options, [] ); }
[ "protected", "function", "getStreamContext", "(", "$", "listen", "=", "false", ")", "{", "$", "options", "=", "[", "]", ";", "if", "(", "$", "this", "->", "scheme", "==", "Protocol", "::", "SCHEME_UNDERLYING_SECURE", "||", "$", "this", "->", "scheme", "==", "Protocol", "::", "SCHEME_UNDERLYING", ")", "{", "$", "options", "[", "'socket'", "]", "=", "$", "this", "->", "getSocketStreamContextOptions", "(", ")", ";", "}", "if", "(", "$", "this", "->", "scheme", "==", "Protocol", "::", "SCHEME_UNDERLYING_SECURE", ")", "{", "$", "options", "[", "'ssl'", "]", "=", "$", "this", "->", "getSslStreamContextOptions", "(", ")", ";", "}", "return", "stream_context_create", "(", "$", "options", ",", "[", "]", ")", ";", "}" ]
Gets a stream context @return resource
[ "Gets", "a", "stream", "context" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/UriSocket.php#L79-L97
varspool/Wrench
lib/Connection.php
Connection.handlePayload
public function handlePayload(Payload $payload): void { $app = $this->getClientApplication(); $this->logger->debug('Handling payload: ' . $payload->getPayload()); switch ($type = $payload->getType()) { case Protocol::TYPE_TEXT: if (method_exists($app, 'onData')) { $app->onData((string)$payload, $this); } return; case Protocol::TYPE_BINARY: if (method_exists($app, 'onBinaryData')) { $app->onBinaryData((string)$payload, $this); } else { $this->close(1003); } break; case Protocol::TYPE_PING: $this->logger->info('Ping received', 'notice'); $this->send($payload->getPayload(), Protocol::TYPE_PONG); $this->logger->info('Pong!', 'debug'); break; /** * A Pong frame MAY be sent unsolicited. This serves as a * unidirectional heartbeat. A response to an unsolicited Pong * frame is not expected. */ case Protocol::TYPE_PONG: $this->logger->info('Received unsolicited pong'); break; case Protocol::TYPE_CLOSE: $this->logger->notice('Close frame received'); $this->close(); $this->logger->info('Disconnected'); break; default: throw new ConnectionException('Unhandled payload type'); } }
php
public function handlePayload(Payload $payload): void { $app = $this->getClientApplication(); $this->logger->debug('Handling payload: ' . $payload->getPayload()); switch ($type = $payload->getType()) { case Protocol::TYPE_TEXT: if (method_exists($app, 'onData')) { $app->onData((string)$payload, $this); } return; case Protocol::TYPE_BINARY: if (method_exists($app, 'onBinaryData')) { $app->onBinaryData((string)$payload, $this); } else { $this->close(1003); } break; case Protocol::TYPE_PING: $this->logger->info('Ping received', 'notice'); $this->send($payload->getPayload(), Protocol::TYPE_PONG); $this->logger->info('Pong!', 'debug'); break; /** * A Pong frame MAY be sent unsolicited. This serves as a * unidirectional heartbeat. A response to an unsolicited Pong * frame is not expected. */ case Protocol::TYPE_PONG: $this->logger->info('Received unsolicited pong'); break; case Protocol::TYPE_CLOSE: $this->logger->notice('Close frame received'); $this->close(); $this->logger->info('Disconnected'); break; default: throw new ConnectionException('Unhandled payload type'); } }
[ "public", "function", "handlePayload", "(", "Payload", "$", "payload", ")", ":", "void", "{", "$", "app", "=", "$", "this", "->", "getClientApplication", "(", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "'Handling payload: '", ".", "$", "payload", "->", "getPayload", "(", ")", ")", ";", "switch", "(", "$", "type", "=", "$", "payload", "->", "getType", "(", ")", ")", "{", "case", "Protocol", "::", "TYPE_TEXT", ":", "if", "(", "method_exists", "(", "$", "app", ",", "'onData'", ")", ")", "{", "$", "app", "->", "onData", "(", "(", "string", ")", "$", "payload", ",", "$", "this", ")", ";", "}", "return", ";", "case", "Protocol", "::", "TYPE_BINARY", ":", "if", "(", "method_exists", "(", "$", "app", ",", "'onBinaryData'", ")", ")", "{", "$", "app", "->", "onBinaryData", "(", "(", "string", ")", "$", "payload", ",", "$", "this", ")", ";", "}", "else", "{", "$", "this", "->", "close", "(", "1003", ")", ";", "}", "break", ";", "case", "Protocol", "::", "TYPE_PING", ":", "$", "this", "->", "logger", "->", "info", "(", "'Ping received'", ",", "'notice'", ")", ";", "$", "this", "->", "send", "(", "$", "payload", "->", "getPayload", "(", ")", ",", "Protocol", "::", "TYPE_PONG", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "'Pong!'", ",", "'debug'", ")", ";", "break", ";", "/**\n * A Pong frame MAY be sent unsolicited. This serves as a\n * unidirectional heartbeat. A response to an unsolicited Pong\n * frame is not expected.\n */", "case", "Protocol", "::", "TYPE_PONG", ":", "$", "this", "->", "logger", "->", "info", "(", "'Received unsolicited pong'", ")", ";", "break", ";", "case", "Protocol", "::", "TYPE_CLOSE", ":", "$", "this", "->", "logger", "->", "notice", "(", "'Close frame received'", ")", ";", "$", "this", "->", "close", "(", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "'Disconnected'", ")", ";", "break", ";", "default", ":", "throw", "new", "ConnectionException", "(", "'Unhandled payload type'", ")", ";", "}", "}" ]
Handle a complete payload received from the client Public because called from our PayloadHandler @param Payload $payload @throws ConnectionException
[ "Handle", "a", "complete", "payload", "received", "from", "the", "client" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Connection.php#L177-L222
varspool/Wrench
lib/Connection.php
Connection.close
public function close(int $code = Protocol::CLOSE_NORMAL, string $reason = null): bool { try { if (!$this->handshaked) { $response = $this->protocol->getResponseError($code); $this->socket->send($response); } else { $response = $this->protocol->getClosePayload($code, false); $response->sendToSocket($this->socket); } } catch (Throwable $e) { $this->logger->warning('Unable to send close message'); } if ($this->application && method_exists($this->application, 'onDisconnect')) { $this->application->onDisconnect($this); } $this->socket->disconnect(); $this->manager->removeConnection($this); return true; }
php
public function close(int $code = Protocol::CLOSE_NORMAL, string $reason = null): bool { try { if (!$this->handshaked) { $response = $this->protocol->getResponseError($code); $this->socket->send($response); } else { $response = $this->protocol->getClosePayload($code, false); $response->sendToSocket($this->socket); } } catch (Throwable $e) { $this->logger->warning('Unable to send close message'); } if ($this->application && method_exists($this->application, 'onDisconnect')) { $this->application->onDisconnect($this); } $this->socket->disconnect(); $this->manager->removeConnection($this); return true; }
[ "public", "function", "close", "(", "int", "$", "code", "=", "Protocol", "::", "CLOSE_NORMAL", ",", "string", "$", "reason", "=", "null", ")", ":", "bool", "{", "try", "{", "if", "(", "!", "$", "this", "->", "handshaked", ")", "{", "$", "response", "=", "$", "this", "->", "protocol", "->", "getResponseError", "(", "$", "code", ")", ";", "$", "this", "->", "socket", "->", "send", "(", "$", "response", ")", ";", "}", "else", "{", "$", "response", "=", "$", "this", "->", "protocol", "->", "getClosePayload", "(", "$", "code", ",", "false", ")", ";", "$", "response", "->", "sendToSocket", "(", "$", "this", "->", "socket", ")", ";", "}", "}", "catch", "(", "Throwable", "$", "e", ")", "{", "$", "this", "->", "logger", "->", "warning", "(", "'Unable to send close message'", ")", ";", "}", "if", "(", "$", "this", "->", "application", "&&", "method_exists", "(", "$", "this", "->", "application", ",", "'onDisconnect'", ")", ")", "{", "$", "this", "->", "application", "->", "onDisconnect", "(", "$", "this", ")", ";", "}", "$", "this", "->", "socket", "->", "disconnect", "(", ")", ";", "$", "this", "->", "manager", "->", "removeConnection", "(", "$", "this", ")", ";", "return", "true", ";", "}" ]
Closes the connection according to the WebSocket protocol If an endpoint receives a Close frame and that endpoint did not previously send a Close frame, the endpoint MUST send a Close frame in response. It SHOULD do so as soon as is practical. An endpoint MAY delay sending a close frame until its current message is sent (for instance, if the majority of a fragmented message is already sent, an endpoint MAY send the remaining fragments before sending a Close frame). However, there is no guarantee that the endpoint which has already sent a Close frame will continue to process data. After both sending and receiving a close message, an endpoint considers the WebSocket connection closed, and MUST close the underlying TCP connection. The server MUST close the underlying TCP connection immediately; the client SHOULD wait for the server to close the connection but MAY close the connection at any time after sending and receiving a close message, e.g. if it has not received a TCP close from the server in a reasonable time period. @param int $code @param string $reason The human readable reason the connection was closed @return bool
[ "Closes", "the", "connection", "according", "to", "the", "WebSocket", "protocol" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Connection.php#L257-L279
varspool/Wrench
lib/Connection.php
Connection.send
public function send(string $data, int $type = Protocol::TYPE_TEXT): bool { if (!$this->handshaked) { throw new HandshakeException('Connection is not handshaked'); } $payload = $this->protocol->getPayload(); if (!is_scalar($data) && !$data instanceof Payload) { $data = json_encode($data); } // Servers don't send masked payloads $payload->encode($data, $type, false); if (!$payload->sendToSocket($this->socket)) { $this->logger->warning('Could not send payload to client'); throw new ConnectionException('Could not send data to connection: ' . $this->socket->getLastError()); } return true; }
php
public function send(string $data, int $type = Protocol::TYPE_TEXT): bool { if (!$this->handshaked) { throw new HandshakeException('Connection is not handshaked'); } $payload = $this->protocol->getPayload(); if (!is_scalar($data) && !$data instanceof Payload) { $data = json_encode($data); } // Servers don't send masked payloads $payload->encode($data, $type, false); if (!$payload->sendToSocket($this->socket)) { $this->logger->warning('Could not send payload to client'); throw new ConnectionException('Could not send data to connection: ' . $this->socket->getLastError()); } return true; }
[ "public", "function", "send", "(", "string", "$", "data", ",", "int", "$", "type", "=", "Protocol", "::", "TYPE_TEXT", ")", ":", "bool", "{", "if", "(", "!", "$", "this", "->", "handshaked", ")", "{", "throw", "new", "HandshakeException", "(", "'Connection is not handshaked'", ")", ";", "}", "$", "payload", "=", "$", "this", "->", "protocol", "->", "getPayload", "(", ")", ";", "if", "(", "!", "is_scalar", "(", "$", "data", ")", "&&", "!", "$", "data", "instanceof", "Payload", ")", "{", "$", "data", "=", "json_encode", "(", "$", "data", ")", ";", "}", "// Servers don't send masked payloads", "$", "payload", "->", "encode", "(", "$", "data", ",", "$", "type", ",", "false", ")", ";", "if", "(", "!", "$", "payload", "->", "sendToSocket", "(", "$", "this", "->", "socket", ")", ")", "{", "$", "this", "->", "logger", "->", "warning", "(", "'Could not send payload to client'", ")", ";", "throw", "new", "ConnectionException", "(", "'Could not send data to connection: '", ".", "$", "this", "->", "socket", "->", "getLastError", "(", ")", ")", ";", "}", "return", "true", ";", "}" ]
Sends the payload to the connection @param string|Payload|mixed $data @param int $type @return bool
[ "Sends", "the", "payload", "to", "the", "connection" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Connection.php#L288-L308
varspool/Wrench
lib/Connection.php
Connection.process
public function process() { $data = $this->socket->receive(); $bytes = strlen($data); if ($bytes === 0 || $data === false) { throw new CloseException('Error reading data from socket: ' . $this->socket->getLastError()); } $this->onData($data); }
php
public function process() { $data = $this->socket->receive(); $bytes = strlen($data); if ($bytes === 0 || $data === false) { throw new CloseException('Error reading data from socket: ' . $this->socket->getLastError()); } $this->onData($data); }
[ "public", "function", "process", "(", ")", "{", "$", "data", "=", "$", "this", "->", "socket", "->", "receive", "(", ")", ";", "$", "bytes", "=", "strlen", "(", "$", "data", ")", ";", "if", "(", "$", "bytes", "===", "0", "||", "$", "data", "===", "false", ")", "{", "throw", "new", "CloseException", "(", "'Error reading data from socket: '", ".", "$", "this", "->", "socket", "->", "getLastError", "(", ")", ")", ";", "}", "$", "this", "->", "onData", "(", "$", "data", ")", ";", "}" ]
Processes data on the socket @throws CloseException
[ "Processes", "data", "on", "the", "socket" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Connection.php#L315-L325
varspool/Wrench
lib/Connection.php
Connection.onData
public function onData($data) { if (!$this->handshaked) { return $this->handshake($data); } return $this->handle($data); }
php
public function onData($data) { if (!$this->handshaked) { return $this->handshake($data); } return $this->handle($data); }
[ "public", "function", "onData", "(", "$", "data", ")", "{", "if", "(", "!", "$", "this", "->", "handshaked", ")", "{", "return", "$", "this", "->", "handshake", "(", "$", "data", ")", ";", "}", "return", "$", "this", "->", "handle", "(", "$", "data", ")", ";", "}" ]
Data receiver Called by the connection manager when the connection has received data @param string $data
[ "Data", "receiver" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Connection.php#L334-L340
varspool/Wrench
lib/Connection.php
Connection.handshake
public function handshake($data) { try { list($path, $origin, $key, $extensions, $protocol, $headers, $params) = $this->protocol->validateRequestHandshake($data); $this->headers = $headers; $this->queryParams = $params; $this->application = $this->manager->getApplicationForPath($path); if (!$this->application) { throw new BadRequestException('Invalid application'); } $this->manager->getServer()->notify( Server::EVENT_HANDSHAKE_REQUEST, [$this, $path, $origin, $key, $extensions] ); $response = $this->protocol->getResponseHandshake($key); if (!$this->socket->isConnected()) { throw new HandshakeException('Socket is not connected'); } if ($this->socket->send($response) === null) { throw new HandshakeException('Could not send handshake response'); } $this->handshaked = true; $this->logger->info(sprintf( 'Handshake successful: %s:%d (%s) connected to %s', $this->getIp(), $this->getPort(), $this->getId(), $path )); $this->manager->getServer()->notify( Server::EVENT_HANDSHAKE_SUCCESSFUL, [$this] ); if (method_exists($this->application, 'onConnect')) { $this->application->onConnect($this); } } catch (WrenchException $e) { $this->logger->error('Handshake failed: {exception}', [ 'exception' => $e, ]); $this->close(Protocol::CLOSE_PROTOCOL_ERROR, (string)$e); throw $e; } }
php
public function handshake($data) { try { list($path, $origin, $key, $extensions, $protocol, $headers, $params) = $this->protocol->validateRequestHandshake($data); $this->headers = $headers; $this->queryParams = $params; $this->application = $this->manager->getApplicationForPath($path); if (!$this->application) { throw new BadRequestException('Invalid application'); } $this->manager->getServer()->notify( Server::EVENT_HANDSHAKE_REQUEST, [$this, $path, $origin, $key, $extensions] ); $response = $this->protocol->getResponseHandshake($key); if (!$this->socket->isConnected()) { throw new HandshakeException('Socket is not connected'); } if ($this->socket->send($response) === null) { throw new HandshakeException('Could not send handshake response'); } $this->handshaked = true; $this->logger->info(sprintf( 'Handshake successful: %s:%d (%s) connected to %s', $this->getIp(), $this->getPort(), $this->getId(), $path )); $this->manager->getServer()->notify( Server::EVENT_HANDSHAKE_SUCCESSFUL, [$this] ); if (method_exists($this->application, 'onConnect')) { $this->application->onConnect($this); } } catch (WrenchException $e) { $this->logger->error('Handshake failed: {exception}', [ 'exception' => $e, ]); $this->close(Protocol::CLOSE_PROTOCOL_ERROR, (string)$e); throw $e; } }
[ "public", "function", "handshake", "(", "$", "data", ")", "{", "try", "{", "list", "(", "$", "path", ",", "$", "origin", ",", "$", "key", ",", "$", "extensions", ",", "$", "protocol", ",", "$", "headers", ",", "$", "params", ")", "=", "$", "this", "->", "protocol", "->", "validateRequestHandshake", "(", "$", "data", ")", ";", "$", "this", "->", "headers", "=", "$", "headers", ";", "$", "this", "->", "queryParams", "=", "$", "params", ";", "$", "this", "->", "application", "=", "$", "this", "->", "manager", "->", "getApplicationForPath", "(", "$", "path", ")", ";", "if", "(", "!", "$", "this", "->", "application", ")", "{", "throw", "new", "BadRequestException", "(", "'Invalid application'", ")", ";", "}", "$", "this", "->", "manager", "->", "getServer", "(", ")", "->", "notify", "(", "Server", "::", "EVENT_HANDSHAKE_REQUEST", ",", "[", "$", "this", ",", "$", "path", ",", "$", "origin", ",", "$", "key", ",", "$", "extensions", "]", ")", ";", "$", "response", "=", "$", "this", "->", "protocol", "->", "getResponseHandshake", "(", "$", "key", ")", ";", "if", "(", "!", "$", "this", "->", "socket", "->", "isConnected", "(", ")", ")", "{", "throw", "new", "HandshakeException", "(", "'Socket is not connected'", ")", ";", "}", "if", "(", "$", "this", "->", "socket", "->", "send", "(", "$", "response", ")", "===", "null", ")", "{", "throw", "new", "HandshakeException", "(", "'Could not send handshake response'", ")", ";", "}", "$", "this", "->", "handshaked", "=", "true", ";", "$", "this", "->", "logger", "->", "info", "(", "sprintf", "(", "'Handshake successful: %s:%d (%s) connected to %s'", ",", "$", "this", "->", "getIp", "(", ")", ",", "$", "this", "->", "getPort", "(", ")", ",", "$", "this", "->", "getId", "(", ")", ",", "$", "path", ")", ")", ";", "$", "this", "->", "manager", "->", "getServer", "(", ")", "->", "notify", "(", "Server", "::", "EVENT_HANDSHAKE_SUCCESSFUL", ",", "[", "$", "this", "]", ")", ";", "if", "(", "method_exists", "(", "$", "this", "->", "application", ",", "'onConnect'", ")", ")", "{", "$", "this", "->", "application", "->", "onConnect", "(", "$", "this", ")", ";", "}", "}", "catch", "(", "WrenchException", "$", "e", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "'Handshake failed: {exception}'", ",", "[", "'exception'", "=>", "$", "e", ",", "]", ")", ";", "$", "this", "->", "close", "(", "Protocol", "::", "CLOSE_PROTOCOL_ERROR", ",", "(", "string", ")", "$", "e", ")", ";", "throw", "$", "e", ";", "}", "}" ]
Performs a websocket handshake @param string $data @throws BadRequestException @throws HandshakeException @throws WrenchException
[ "Performs", "a", "websocket", "handshake" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Connection.php#L350-L404
varspool/Wrench
lib/Connection.php
Connection.export
protected function export($data): string { $export = ''; foreach (str_split($data) as $chr) { $export .= '\\x' . ord($chr); } }
php
protected function export($data): string { $export = ''; foreach (str_split($data) as $chr) { $export .= '\\x' . ord($chr); } }
[ "protected", "function", "export", "(", "$", "data", ")", ":", "string", "{", "$", "export", "=", "''", ";", "foreach", "(", "str_split", "(", "$", "data", ")", "as", "$", "chr", ")", "{", "$", "export", ".=", "'\\\\x'", ".", "ord", "(", "$", "chr", ")", ";", "}", "}" ]
Returns a string export of the given binary data @param string $data @return string
[ "Returns", "a", "string", "export", "of", "the", "given", "binary", "data" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Connection.php#L502-L508
varspool/Wrench
lib/Listener/OriginPolicy.php
OriginPolicy.onHandshakeRequest
public function onHandshakeRequest( Connection $connection, string $path, string $origin, string $key, array $extensions ): void { if (!$this->isAllowed($origin)) { $connection->close(Protocol::CLOSE_NORMAL, 'Not allowed origin during handshake request'); } }
php
public function onHandshakeRequest( Connection $connection, string $path, string $origin, string $key, array $extensions ): void { if (!$this->isAllowed($origin)) { $connection->close(Protocol::CLOSE_NORMAL, 'Not allowed origin during handshake request'); } }
[ "public", "function", "onHandshakeRequest", "(", "Connection", "$", "connection", ",", "string", "$", "path", ",", "string", "$", "origin", ",", "string", "$", "key", ",", "array", "$", "extensions", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "isAllowed", "(", "$", "origin", ")", ")", "{", "$", "connection", "->", "close", "(", "Protocol", "::", "CLOSE_NORMAL", ",", "'Not allowed origin during handshake request'", ")", ";", "}", "}" ]
Handshake request listener Closes the connection on handshake from an origin that isn't allowed @param Connection $connection @param string $path @param string $origin @param string $key @param array $extensions
[ "Handshake", "request", "listener", "Closes", "the", "connection", "on", "handshake", "from", "an", "origin", "that", "isn", "t", "allowed" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/OriginPolicy.php#L29-L39
varspool/Wrench
lib/Listener/OriginPolicy.php
OriginPolicy.isAllowed
public function isAllowed(string $origin): bool { $scheme = parse_url($origin, PHP_URL_SCHEME); $host = parse_url($origin, PHP_URL_HOST) ?: $origin; foreach ($this->allowed as $allowed) { $allowed_scheme = parse_url($allowed, PHP_URL_SCHEME); if ($allowed_scheme && $scheme != $allowed_scheme) { continue; } $allowed_host = parse_url($allowed, PHP_URL_HOST) ?: $allowed; if ($host != $allowed_host) { continue; } return true; } return false; }
php
public function isAllowed(string $origin): bool { $scheme = parse_url($origin, PHP_URL_SCHEME); $host = parse_url($origin, PHP_URL_HOST) ?: $origin; foreach ($this->allowed as $allowed) { $allowed_scheme = parse_url($allowed, PHP_URL_SCHEME); if ($allowed_scheme && $scheme != $allowed_scheme) { continue; } $allowed_host = parse_url($allowed, PHP_URL_HOST) ?: $allowed; if ($host != $allowed_host) { continue; } return true; } return false; }
[ "public", "function", "isAllowed", "(", "string", "$", "origin", ")", ":", "bool", "{", "$", "scheme", "=", "parse_url", "(", "$", "origin", ",", "PHP_URL_SCHEME", ")", ";", "$", "host", "=", "parse_url", "(", "$", "origin", ",", "PHP_URL_HOST", ")", "?", ":", "$", "origin", ";", "foreach", "(", "$", "this", "->", "allowed", "as", "$", "allowed", ")", "{", "$", "allowed_scheme", "=", "parse_url", "(", "$", "allowed", ",", "PHP_URL_SCHEME", ")", ";", "if", "(", "$", "allowed_scheme", "&&", "$", "scheme", "!=", "$", "allowed_scheme", ")", "{", "continue", ";", "}", "$", "allowed_host", "=", "parse_url", "(", "$", "allowed", ",", "PHP_URL_HOST", ")", "?", ":", "$", "allowed", ";", "if", "(", "$", "host", "!=", "$", "allowed_host", ")", "{", "continue", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Whether the specified origin is allowed under this policy @param string $origin @return bool
[ "Whether", "the", "specified", "origin", "is", "allowed", "under", "this", "policy" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/OriginPolicy.php#L47-L69
varspool/Wrench
lib/Payload/Payload.php
Payload.encode
public function encode(string $data, int $type = Protocol::TYPE_TEXT, bool $masked = false) { $this->frames = []; $frame = $this->getFrame(); array_push($this->frames, $frame); $frame->encode($data, $type, $masked); return $this; }
php
public function encode(string $data, int $type = Protocol::TYPE_TEXT, bool $masked = false) { $this->frames = []; $frame = $this->getFrame(); array_push($this->frames, $frame); $frame->encode($data, $type, $masked); return $this; }
[ "public", "function", "encode", "(", "string", "$", "data", ",", "int", "$", "type", "=", "Protocol", "::", "TYPE_TEXT", ",", "bool", "$", "masked", "=", "false", ")", "{", "$", "this", "->", "frames", "=", "[", "]", ";", "$", "frame", "=", "$", "this", "->", "getFrame", "(", ")", ";", "array_push", "(", "$", "this", "->", "frames", ",", "$", "frame", ")", ";", "$", "frame", "->", "encode", "(", "$", "data", ",", "$", "type", ",", "$", "masked", ")", ";", "return", "$", "this", ";", "}" ]
Encodes a payload @param string $data @param int $type @param boolean $masked @return Payload @todo No splitting into multiple frames just yet
[ "Encodes", "a", "payload" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Payload/Payload.php#L42-L52
varspool/Wrench
lib/Payload/Payload.php
Payload.getRemainingData
public function getRemainingData(): ?int { if ($this->isComplete()) { return 0; } try { if ($this->getCurrentFrame()->isFinal()) { return $this->getCurrentFrame()->getRemainingData(); } } catch (FrameException $e) { return null; } return null; }
php
public function getRemainingData(): ?int { if ($this->isComplete()) { return 0; } try { if ($this->getCurrentFrame()->isFinal()) { return $this->getCurrentFrame()->getRemainingData(); } } catch (FrameException $e) { return null; } return null; }
[ "public", "function", "getRemainingData", "(", ")", ":", "?", "int", "{", "if", "(", "$", "this", "->", "isComplete", "(", ")", ")", "{", "return", "0", ";", "}", "try", "{", "if", "(", "$", "this", "->", "getCurrentFrame", "(", ")", "->", "isFinal", "(", ")", ")", "{", "return", "$", "this", "->", "getCurrentFrame", "(", ")", "->", "getRemainingData", "(", ")", ";", "}", "}", "catch", "(", "FrameException", "$", "e", ")", "{", "return", "null", ";", "}", "return", "null", ";", "}" ]
Gets the number of remaining bytes before this payload will be complete May return 0 (no more bytes required) or null (unknown number of bytes required). @return int|null
[ "Gets", "the", "number", "of", "remaining", "bytes", "before", "this", "payload", "will", "be", "complete", "May", "return", "0", "(", "no", "more", "bytes", "required", ")", "or", "null", "(", "unknown", "number", "of", "bytes", "required", ")", "." ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Payload/Payload.php#L79-L94
varspool/Wrench
lib/Payload/Payload.php
Payload.getCurrentFrame
protected function getCurrentFrame() { if (empty($this->frames)) { array_push($this->frames, $this->getFrame()); } return end($this->frames); }
php
protected function getCurrentFrame() { if (empty($this->frames)) { array_push($this->frames, $this->getFrame()); } return end($this->frames); }
[ "protected", "function", "getCurrentFrame", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "frames", ")", ")", "{", "array_push", "(", "$", "this", "->", "frames", ",", "$", "this", "->", "getFrame", "(", ")", ")", ";", "}", "return", "end", "(", "$", "this", "->", "frames", ")", ";", "}" ]
Gets the current frame for the payload @return mixed
[ "Gets", "the", "current", "frame", "for", "the", "payload" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Payload/Payload.php#L111-L117
varspool/Wrench
lib/Payload/Payload.php
Payload.receiveData
public function receiveData(string $data): void { $chunkSize = null; while ($data) { $frame = $this->getReceivingFrame(); $remaining = $frame->getRemainingData(); if ($remaining === null) { $chunkSize = 2; } elseif ($remaining > 0) { $chunkSize = $remaining; } $chunkSize = min(strlen($data), $chunkSize); $chunk = substr($data, 0, $chunkSize); $data = substr($data, $chunkSize); $frame->receiveData($chunk); } }
php
public function receiveData(string $data): void { $chunkSize = null; while ($data) { $frame = $this->getReceivingFrame(); $remaining = $frame->getRemainingData(); if ($remaining === null) { $chunkSize = 2; } elseif ($remaining > 0) { $chunkSize = $remaining; } $chunkSize = min(strlen($data), $chunkSize); $chunk = substr($data, 0, $chunkSize); $data = substr($data, $chunkSize); $frame->receiveData($chunk); } }
[ "public", "function", "receiveData", "(", "string", "$", "data", ")", ":", "void", "{", "$", "chunkSize", "=", "null", ";", "while", "(", "$", "data", ")", "{", "$", "frame", "=", "$", "this", "->", "getReceivingFrame", "(", ")", ";", "$", "remaining", "=", "$", "frame", "->", "getRemainingData", "(", ")", ";", "if", "(", "$", "remaining", "===", "null", ")", "{", "$", "chunkSize", "=", "2", ";", "}", "elseif", "(", "$", "remaining", ">", "0", ")", "{", "$", "chunkSize", "=", "$", "remaining", ";", "}", "$", "chunkSize", "=", "min", "(", "strlen", "(", "$", "data", ")", ",", "$", "chunkSize", ")", ";", "$", "chunk", "=", "substr", "(", "$", "data", ",", "0", ",", "$", "chunkSize", ")", ";", "$", "data", "=", "substr", "(", "$", "data", ",", "$", "chunkSize", ")", ";", "$", "frame", "->", "receiveData", "(", "$", "chunk", ")", ";", "}", "}" ]
Receive raw data into the payload @param string $data @return void @throws PayloadException
[ "Receive", "raw", "data", "into", "the", "payload" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Payload/Payload.php#L145-L166
varspool/Wrench
lib/Payload/Payload.php
Payload.getReceivingFrame
protected function getReceivingFrame(): Frame { $current = $this->getCurrentFrame(); if ($current->isComplete()) { if ($current->isFinal()) { throw new PayloadException('Payload cannot receive data: it is already complete'); } else { $this->frames[] = $current = $this->getFrame(); } } return $current; }
php
protected function getReceivingFrame(): Frame { $current = $this->getCurrentFrame(); if ($current->isComplete()) { if ($current->isFinal()) { throw new PayloadException('Payload cannot receive data: it is already complete'); } else { $this->frames[] = $current = $this->getFrame(); } } return $current; }
[ "protected", "function", "getReceivingFrame", "(", ")", ":", "Frame", "{", "$", "current", "=", "$", "this", "->", "getCurrentFrame", "(", ")", ";", "if", "(", "$", "current", "->", "isComplete", "(", ")", ")", "{", "if", "(", "$", "current", "->", "isFinal", "(", ")", ")", "{", "throw", "new", "PayloadException", "(", "'Payload cannot receive data: it is already complete'", ")", ";", "}", "else", "{", "$", "this", "->", "frames", "[", "]", "=", "$", "current", "=", "$", "this", "->", "getFrame", "(", ")", ";", "}", "}", "return", "$", "current", ";", "}" ]
Gets the frame into which data should be receieved @throws PayloadException @return Frame
[ "Gets", "the", "frame", "into", "which", "data", "should", "be", "receieved" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Payload/Payload.php#L174-L187
varspool/Wrench
lib/Socket/Socket.php
Socket.getIp
public function getIp(): string { $name = $this->getName(); if ($name) { return self::getNamePart($name, self::NAME_PART_IP); } else { throw new SocketException('Cannot get socket IP address'); } }
php
public function getIp(): string { $name = $this->getName(); if ($name) { return self::getNamePart($name, self::NAME_PART_IP); } else { throw new SocketException('Cannot get socket IP address'); } }
[ "public", "function", "getIp", "(", ")", ":", "string", "{", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "$", "name", ")", "{", "return", "self", "::", "getNamePart", "(", "$", "name", ",", "self", "::", "NAME_PART_IP", ")", ";", "}", "else", "{", "throw", "new", "SocketException", "(", "'Cannot get socket IP address'", ")", ";", "}", "}" ]
Gets the IP address of the socket @throws \Wrench\Exception\SocketException If the IP address cannot be obtained @return string
[ "Gets", "the", "IP", "address", "of", "the", "socket" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L74-L83
varspool/Wrench
lib/Socket/Socket.php
Socket.getName
protected function getName(): string { if (!isset($this->name) || !$this->name) { $this->name = @stream_socket_get_name($this->socket, true); } return $this->name; }
php
protected function getName(): string { if (!isset($this->name) || !$this->name) { $this->name = @stream_socket_get_name($this->socket, true); } return $this->name; }
[ "protected", "function", "getName", "(", ")", ":", "string", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "name", ")", "||", "!", "$", "this", "->", "name", ")", "{", "$", "this", "->", "name", "=", "@", "stream_socket_get_name", "(", "$", "this", "->", "socket", ",", "true", ")", ";", "}", "return", "$", "this", "->", "name", ";", "}" ]
Gets the name of the socket @return string
[ "Gets", "the", "name", "of", "the", "socket" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L90-L96
varspool/Wrench
lib/Socket/Socket.php
Socket.getNamePart
public static function getNamePart(string $name, int $part): string { if (!$name) { throw new InvalidArgumentException('Invalid name'); } $parts = explode(':', $name); if (count($parts) < 2) { throw new SocketException('Could not parse name parts: ' . $name); } if ($part == self::NAME_PART_PORT) { return end($parts); } elseif ($part == self::NAME_PART_IP) { return implode(':', array_slice($parts, 0, -1)); } else { throw new InvalidArgumentException('Invalid name part'); } }
php
public static function getNamePart(string $name, int $part): string { if (!$name) { throw new InvalidArgumentException('Invalid name'); } $parts = explode(':', $name); if (count($parts) < 2) { throw new SocketException('Could not parse name parts: ' . $name); } if ($part == self::NAME_PART_PORT) { return end($parts); } elseif ($part == self::NAME_PART_IP) { return implode(':', array_slice($parts, 0, -1)); } else { throw new InvalidArgumentException('Invalid name part'); } }
[ "public", "static", "function", "getNamePart", "(", "string", "$", "name", ",", "int", "$", "part", ")", ":", "string", "{", "if", "(", "!", "$", "name", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid name'", ")", ";", "}", "$", "parts", "=", "explode", "(", "':'", ",", "$", "name", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "<", "2", ")", "{", "throw", "new", "SocketException", "(", "'Could not parse name parts: '", ".", "$", "name", ")", ";", "}", "if", "(", "$", "part", "==", "self", "::", "NAME_PART_PORT", ")", "{", "return", "end", "(", "$", "parts", ")", ";", "}", "elseif", "(", "$", "part", "==", "self", "::", "NAME_PART_IP", ")", "{", "return", "implode", "(", "':'", ",", "array_slice", "(", "$", "parts", ",", "0", ",", "-", "1", ")", ")", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid name part'", ")", ";", "}", "}" ]
Gets part of the name of the socket PHP seems to return IPV6 address/port combos like this: ::1:1234, where ::1 is the address and 1234 the port So, the part number here is either the last : delimited section (the port) or all the other sections (the whole initial part, the address). @param string $name (from $this->getName() usually) @param int <0, 1> $part @return string @throws SocketException
[ "Gets", "part", "of", "the", "name", "of", "the", "socket", "PHP", "seems", "to", "return", "IPV6", "address", "/", "port", "combos", "like", "this", ":", "::", "1", ":", "1234", "where", "::", "1", "is", "the", "address", "and", "1234", "the", "port", "So", "the", "part", "number", "here", "is", "either", "the", "last", ":", "delimited", "section", "(", "the", "port", ")", "or", "all", "the", "other", "sections", "(", "the", "whole", "initial", "part", "the", "address", ")", "." ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L110-L129
varspool/Wrench
lib/Socket/Socket.php
Socket.getPort
public function getPort(): int { $name = $this->getName(); if ($name) { return (int)self::getNamePart($name, self::NAME_PART_PORT); } else { throw new SocketException('Cannot get socket IP address'); } }
php
public function getPort(): int { $name = $this->getName(); if ($name) { return (int)self::getNamePart($name, self::NAME_PART_PORT); } else { throw new SocketException('Cannot get socket IP address'); } }
[ "public", "function", "getPort", "(", ")", ":", "int", "{", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "$", "name", ")", "{", "return", "(", "int", ")", "self", "::", "getNamePart", "(", "$", "name", ",", "self", "::", "NAME_PART_PORT", ")", ";", "}", "else", "{", "throw", "new", "SocketException", "(", "'Cannot get socket IP address'", ")", ";", "}", "}" ]
Gets the port of the socket @throws \Wrench\Exception\SocketException If the port cannot be obtained @return int
[ "Gets", "the", "port", "of", "the", "socket" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L137-L146
varspool/Wrench
lib/Socket/Socket.php
Socket.getLastError
public function getLastError(): string { if ($this->isConnected() && $this->socket) { $err = @socket_last_error($this->socket); if ($err) { $err = socket_strerror($err); } if (!$err) { $err = 'Unknown error'; } return $err; } else { return 'Not connected'; } }
php
public function getLastError(): string { if ($this->isConnected() && $this->socket) { $err = @socket_last_error($this->socket); if ($err) { $err = socket_strerror($err); } if (!$err) { $err = 'Unknown error'; } return $err; } else { return 'Not connected'; } }
[ "public", "function", "getLastError", "(", ")", ":", "string", "{", "if", "(", "$", "this", "->", "isConnected", "(", ")", "&&", "$", "this", "->", "socket", ")", "{", "$", "err", "=", "@", "socket_last_error", "(", "$", "this", "->", "socket", ")", ";", "if", "(", "$", "err", ")", "{", "$", "err", "=", "socket_strerror", "(", "$", "err", ")", ";", "}", "if", "(", "!", "$", "err", ")", "{", "$", "err", "=", "'Unknown error'", ";", "}", "return", "$", "err", ";", "}", "else", "{", "return", "'Not connected'", ";", "}", "}" ]
Get the last error that occurred on the socket @return string
[ "Get", "the", "last", "error", "that", "occurred", "on", "the", "socket" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L153-L167
varspool/Wrench
lib/Socket/Socket.php
Socket.receive
public function receive(int $length = self::DEFAULT_RECEIVE_LENGTH): string { $buffer = ''; $metadata['unread_bytes'] = 0; $makeBlockingAfterRead = false; try { do { // feof means socket has been closed // also, sometimes in long running processes the system seems to kill the underlying socket if (!$this->socket || feof($this->socket)) { $this->disconnect(); return $buffer; } $result = fread($this->socket, $length); if ($makeBlockingAfterRead) { stream_set_blocking($this->socket, true); $makeBlockingAfterRead = false; } // fread FALSE means socket has been closed if ($result === false) { $this->disconnect(); return $buffer; } $buffer .= $result; // feof means socket has been closed if (feof($this->socket)) { $this->disconnect(); return $buffer; } $continue = false; if (strlen($result) == 1) { // Workaround Chrome behavior (still needed?) $continue = true; } if (strlen($result) == $length) { $continue = true; } // Continue if more data to be read $metadata = stream_get_meta_data($this->socket); if ($metadata && isset($metadata['unread_bytes'])) { if (!$metadata['unread_bytes']) { // stop it, if we read a full message in previous time $continue = false; } else { $continue = true; // it makes sense only if unread_bytes less than DEFAULT_RECEIVE_LENGTH if ($length > $metadata['unread_bytes']) { // http://php.net/manual/en/function.stream-get-meta-data.php // 'unread_bytes' don't describes real length correctly. //$length = $metadata['unread_bytes']; // Socket is a blocking by default. When we do a blocking read from an empty // queue it will block and the server will hang. https://bugs.php.net/bug.php?id=1739 stream_set_blocking($this->socket, false); $makeBlockingAfterRead = true; } } } } while ($continue); return $buffer; } finally { if ($this->socket && !feof($this->socket) && $makeBlockingAfterRead) { stream_set_blocking($this->socket, true); } } }
php
public function receive(int $length = self::DEFAULT_RECEIVE_LENGTH): string { $buffer = ''; $metadata['unread_bytes'] = 0; $makeBlockingAfterRead = false; try { do { // feof means socket has been closed // also, sometimes in long running processes the system seems to kill the underlying socket if (!$this->socket || feof($this->socket)) { $this->disconnect(); return $buffer; } $result = fread($this->socket, $length); if ($makeBlockingAfterRead) { stream_set_blocking($this->socket, true); $makeBlockingAfterRead = false; } // fread FALSE means socket has been closed if ($result === false) { $this->disconnect(); return $buffer; } $buffer .= $result; // feof means socket has been closed if (feof($this->socket)) { $this->disconnect(); return $buffer; } $continue = false; if (strlen($result) == 1) { // Workaround Chrome behavior (still needed?) $continue = true; } if (strlen($result) == $length) { $continue = true; } // Continue if more data to be read $metadata = stream_get_meta_data($this->socket); if ($metadata && isset($metadata['unread_bytes'])) { if (!$metadata['unread_bytes']) { // stop it, if we read a full message in previous time $continue = false; } else { $continue = true; // it makes sense only if unread_bytes less than DEFAULT_RECEIVE_LENGTH if ($length > $metadata['unread_bytes']) { // http://php.net/manual/en/function.stream-get-meta-data.php // 'unread_bytes' don't describes real length correctly. //$length = $metadata['unread_bytes']; // Socket is a blocking by default. When we do a blocking read from an empty // queue it will block and the server will hang. https://bugs.php.net/bug.php?id=1739 stream_set_blocking($this->socket, false); $makeBlockingAfterRead = true; } } } } while ($continue); return $buffer; } finally { if ($this->socket && !feof($this->socket) && $makeBlockingAfterRead) { stream_set_blocking($this->socket, true); } } }
[ "public", "function", "receive", "(", "int", "$", "length", "=", "self", "::", "DEFAULT_RECEIVE_LENGTH", ")", ":", "string", "{", "$", "buffer", "=", "''", ";", "$", "metadata", "[", "'unread_bytes'", "]", "=", "0", ";", "$", "makeBlockingAfterRead", "=", "false", ";", "try", "{", "do", "{", "// feof means socket has been closed", "// also, sometimes in long running processes the system seems to kill the underlying socket", "if", "(", "!", "$", "this", "->", "socket", "||", "feof", "(", "$", "this", "->", "socket", ")", ")", "{", "$", "this", "->", "disconnect", "(", ")", ";", "return", "$", "buffer", ";", "}", "$", "result", "=", "fread", "(", "$", "this", "->", "socket", ",", "$", "length", ")", ";", "if", "(", "$", "makeBlockingAfterRead", ")", "{", "stream_set_blocking", "(", "$", "this", "->", "socket", ",", "true", ")", ";", "$", "makeBlockingAfterRead", "=", "false", ";", "}", "// fread FALSE means socket has been closed", "if", "(", "$", "result", "===", "false", ")", "{", "$", "this", "->", "disconnect", "(", ")", ";", "return", "$", "buffer", ";", "}", "$", "buffer", ".=", "$", "result", ";", "// feof means socket has been closed", "if", "(", "feof", "(", "$", "this", "->", "socket", ")", ")", "{", "$", "this", "->", "disconnect", "(", ")", ";", "return", "$", "buffer", ";", "}", "$", "continue", "=", "false", ";", "if", "(", "strlen", "(", "$", "result", ")", "==", "1", ")", "{", "// Workaround Chrome behavior (still needed?)", "$", "continue", "=", "true", ";", "}", "if", "(", "strlen", "(", "$", "result", ")", "==", "$", "length", ")", "{", "$", "continue", "=", "true", ";", "}", "// Continue if more data to be read", "$", "metadata", "=", "stream_get_meta_data", "(", "$", "this", "->", "socket", ")", ";", "if", "(", "$", "metadata", "&&", "isset", "(", "$", "metadata", "[", "'unread_bytes'", "]", ")", ")", "{", "if", "(", "!", "$", "metadata", "[", "'unread_bytes'", "]", ")", "{", "// stop it, if we read a full message in previous time", "$", "continue", "=", "false", ";", "}", "else", "{", "$", "continue", "=", "true", ";", "// it makes sense only if unread_bytes less than DEFAULT_RECEIVE_LENGTH", "if", "(", "$", "length", ">", "$", "metadata", "[", "'unread_bytes'", "]", ")", "{", "// http://php.net/manual/en/function.stream-get-meta-data.php", "// 'unread_bytes' don't describes real length correctly.", "//$length = $metadata['unread_bytes'];", "// Socket is a blocking by default. When we do a blocking read from an empty", "// queue it will block and the server will hang. https://bugs.php.net/bug.php?id=1739", "stream_set_blocking", "(", "$", "this", "->", "socket", ",", "false", ")", ";", "$", "makeBlockingAfterRead", "=", "true", ";", "}", "}", "}", "}", "while", "(", "$", "continue", ")", ";", "return", "$", "buffer", ";", "}", "finally", "{", "if", "(", "$", "this", "->", "socket", "&&", "!", "feof", "(", "$", "this", "->", "socket", ")", "&&", "$", "makeBlockingAfterRead", ")", "{", "stream_set_blocking", "(", "$", "this", "->", "socket", ",", "true", ")", ";", "}", "}", "}" ]
Receive data from the socket @param int $length @return string
[ "Receive", "data", "from", "the", "socket" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L228-L308
varspool/Wrench
lib/Socket/Socket.php
Socket.disconnect
public function disconnect(): void { if ($this->socket) { stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR); } $this->socket = null; $this->connected = false; }
php
public function disconnect(): void { if ($this->socket) { stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR); } $this->socket = null; $this->connected = false; }
[ "public", "function", "disconnect", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "socket", ")", "{", "stream_socket_shutdown", "(", "$", "this", "->", "socket", ",", "STREAM_SHUT_RDWR", ")", ";", "}", "$", "this", "->", "socket", "=", "null", ";", "$", "this", "->", "connected", "=", "false", ";", "}" ]
Disconnect the socket @return void
[ "Disconnect", "the", "socket" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L315-L322
varspool/Wrench
lib/Socket/Socket.php
Socket.configure
protected function configure(array $options): void { $options = array_merge([ 'timeout_socket' => self::TIMEOUT_SOCKET, ], $options); parent::configure($options); }
php
protected function configure(array $options): void { $options = array_merge([ 'timeout_socket' => self::TIMEOUT_SOCKET, ], $options); parent::configure($options); }
[ "protected", "function", "configure", "(", "array", "$", "options", ")", ":", "void", "{", "$", "options", "=", "array_merge", "(", "[", "'timeout_socket'", "=>", "self", "::", "TIMEOUT_SOCKET", ",", "]", ",", "$", "options", ")", ";", "parent", "::", "configure", "(", "$", "options", ")", ";", "}" ]
Configure options Options include - timeout_socket => int, seconds, default 5 @param array $options @return void
[ "Configure", "options", "Options", "include", "-", "timeout_socket", "=", ">", "int", "seconds", "default", "5" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/Socket.php#L332-L339
varspool/Wrench
lib/Server.php
Server.run
public function run(): void { $this->connectionManager->listen(); while ($this->loop->shouldContinue()) { /* * If there's nothing changed on any of the sockets, the server * will sleep and other processes will have a change to run. Control * this behaviour with the timeout options. */ $this->connectionManager->selectAndProcess(); /* * If the application wants to perform periodic operations or queries * and push updates to clients based on the result then that logic can * be implemented in the 'onUpdate' method. */ foreach ($this->applications as $application) { if (method_exists($application, 'onUpdate')) { $application->onUpdate(); } } } }
php
public function run(): void { $this->connectionManager->listen(); while ($this->loop->shouldContinue()) { /* * If there's nothing changed on any of the sockets, the server * will sleep and other processes will have a change to run. Control * this behaviour with the timeout options. */ $this->connectionManager->selectAndProcess(); /* * If the application wants to perform periodic operations or queries * and push updates to clients based on the result then that logic can * be implemented in the 'onUpdate' method. */ foreach ($this->applications as $application) { if (method_exists($application, 'onUpdate')) { $application->onUpdate(); } } } }
[ "public", "function", "run", "(", ")", ":", "void", "{", "$", "this", "->", "connectionManager", "->", "listen", "(", ")", ";", "while", "(", "$", "this", "->", "loop", "->", "shouldContinue", "(", ")", ")", "{", "/*\n * If there's nothing changed on any of the sockets, the server\n * will sleep and other processes will have a change to run. Control\n * this behaviour with the timeout options.\n */", "$", "this", "->", "connectionManager", "->", "selectAndProcess", "(", ")", ";", "/*\n * If the application wants to perform periodic operations or queries\n * and push updates to clients based on the result then that logic can\n * be implemented in the 'onUpdate' method.\n */", "foreach", "(", "$", "this", "->", "applications", "as", "$", "application", ")", "{", "if", "(", "method_exists", "(", "$", "application", ",", "'onUpdate'", ")", ")", "{", "$", "application", "->", "onUpdate", "(", ")", ";", "}", "}", "}", "}" ]
Main server loop @return void This method does not return!
[ "Main", "server", "loop" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Server.php#L126-L149
varspool/Wrench
lib/Server.php
Server.notify
public function notify($event, array $arguments = []): void { if (!isset($this->listeners[$event])) { return; } foreach ($this->listeners[$event] as $listener) { call_user_func_array($listener, $arguments); } }
php
public function notify($event, array $arguments = []): void { if (!isset($this->listeners[$event])) { return; } foreach ($this->listeners[$event] as $listener) { call_user_func_array($listener, $arguments); } }
[ "public", "function", "notify", "(", "$", "event", ",", "array", "$", "arguments", "=", "[", "]", ")", ":", "void", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "listeners", "[", "$", "event", "]", ")", ")", "{", "return", ";", "}", "foreach", "(", "$", "this", "->", "listeners", "[", "$", "event", "]", "as", "$", "listener", ")", "{", "call_user_func_array", "(", "$", "listener", ",", "$", "arguments", ")", ";", "}", "}" ]
Notifies listeners of an event @param string $event @param array $arguments Event arguments @return void
[ "Notifies", "listeners", "of", "an", "event" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Server.php#L158-L167
varspool/Wrench
lib/Server.php
Server.addListener
public function addListener($event, callable $callback): void { if (!isset($this->listeners[$event])) { $this->listeners[$event] = []; } if (!is_callable($callback)) { throw new InvalidArgumentException('Invalid listener'); } $this->listeners[$event][] = $callback; }
php
public function addListener($event, callable $callback): void { if (!isset($this->listeners[$event])) { $this->listeners[$event] = []; } if (!is_callable($callback)) { throw new InvalidArgumentException('Invalid listener'); } $this->listeners[$event][] = $callback; }
[ "public", "function", "addListener", "(", "$", "event", ",", "callable", "$", "callback", ")", ":", "void", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "listeners", "[", "$", "event", "]", ")", ")", "{", "$", "this", "->", "listeners", "[", "$", "event", "]", "=", "[", "]", ";", "}", "if", "(", "!", "is_callable", "(", "$", "callback", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid listener'", ")", ";", "}", "$", "this", "->", "listeners", "[", "$", "event", "]", "[", "]", "=", "$", "callback", ";", "}" ]
Adds a listener Provide an event (see the Server::EVENT_* constants) and a callback closure. Some arguments may be provided to your callback, such as the connection the caused the event. @param string $event @param callable $callback @return void @throws InvalidArgumentException
[ "Adds", "a", "listener", "Provide", "an", "event", "(", "see", "the", "Server", "::", "EVENT_", "*", "constants", ")", "and", "a", "callback", "closure", ".", "Some", "arguments", "may", "be", "provided", "to", "your", "callback", "such", "as", "the", "connection", "the", "caused", "the", "event", "." ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Server.php#L180-L191
varspool/Wrench
lib/Server.php
Server.getApplication
public function getApplication($key) { if (empty($key)) { return null; } if (array_key_exists($key, $this->applications)) { return $this->applications[$key]; } return null; }
php
public function getApplication($key) { if (empty($key)) { return null; } if (array_key_exists($key, $this->applications)) { return $this->applications[$key]; } return null; }
[ "public", "function", "getApplication", "(", "$", "key", ")", "{", "if", "(", "empty", "(", "$", "key", ")", ")", "{", "return", "null", ";", "}", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "applications", ")", ")", "{", "return", "$", "this", "->", "applications", "[", "$", "key", "]", ";", "}", "return", "null", ";", "}" ]
Returns a server application. @param string $key Name of application. @return null|DataHandlerInterface|ConnectionHandlerInterface|UpdateHandlerInterface The application object
[ "Returns", "a", "server", "application", "." ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Server.php#L199-L210
varspool/Wrench
lib/Server.php
Server.configure
protected function configure(array $options): void { $options = array_merge([ 'connection_manager' => null, 'connection_manager_class' => ConnectionManager::class, 'connection_manager_options' => [], ], $options); parent::configure($options); $this->configureConnectionManager(); }
php
protected function configure(array $options): void { $options = array_merge([ 'connection_manager' => null, 'connection_manager_class' => ConnectionManager::class, 'connection_manager_options' => [], ], $options); parent::configure($options); $this->configureConnectionManager(); }
[ "protected", "function", "configure", "(", "array", "$", "options", ")", ":", "void", "{", "$", "options", "=", "array_merge", "(", "[", "'connection_manager'", "=>", "null", ",", "'connection_manager_class'", "=>", "ConnectionManager", "::", "class", ",", "'connection_manager_options'", "=>", "[", "]", ",", "]", ",", "$", "options", ")", ";", "parent", "::", "configure", "(", "$", "options", ")", ";", "$", "this", "->", "configureConnectionManager", "(", ")", ";", "}" ]
Configure options Options include - socket_class => The socket class to use, defaults to ServerSocket - socket_options => An array of socket options - logger => Closure($message, $priority = 'info'), used for logging @param array $options @return void
[ "Configure", "options" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Server.php#L236-L247
varspool/Wrench
lib/Server.php
Server.configureConnectionManager
protected function configureConnectionManager(): void { if ($this->options['connection_manager']) { $this->connectionManager = $this->options['connection_manager']; } else { $class = $this->options['connection_manager_class']; $options = $this->options['connection_manager_options']; $this->connectionManager = new $class($this, $options); } $this->connectionManager->setLogger($this->logger); }
php
protected function configureConnectionManager(): void { if ($this->options['connection_manager']) { $this->connectionManager = $this->options['connection_manager']; } else { $class = $this->options['connection_manager_class']; $options = $this->options['connection_manager_options']; $this->connectionManager = new $class($this, $options); } $this->connectionManager->setLogger($this->logger); }
[ "protected", "function", "configureConnectionManager", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "options", "[", "'connection_manager'", "]", ")", "{", "$", "this", "->", "connectionManager", "=", "$", "this", "->", "options", "[", "'connection_manager'", "]", ";", "}", "else", "{", "$", "class", "=", "$", "this", "->", "options", "[", "'connection_manager_class'", "]", ";", "$", "options", "=", "$", "this", "->", "options", "[", "'connection_manager_options'", "]", ";", "$", "this", "->", "connectionManager", "=", "new", "$", "class", "(", "$", "this", ",", "$", "options", ")", ";", "}", "$", "this", "->", "connectionManager", "->", "setLogger", "(", "$", "this", "->", "logger", ")", ";", "}" ]
Configures the connection manager @return void
[ "Configures", "the", "connection", "manager" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Server.php#L254-L266
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.generateKey
public function generateKey() { if (extension_loaded('openssl')) { $key = openssl_random_pseudo_bytes(16); } else { // SHA1 is 128 bit (= 16 bytes) $key = sha1(spl_object_hash($this) . mt_rand(0, PHP_INT_MAX) . uniqid('', true), true); } return base64_encode($key); }
php
public function generateKey() { if (extension_loaded('openssl')) { $key = openssl_random_pseudo_bytes(16); } else { // SHA1 is 128 bit (= 16 bytes) $key = sha1(spl_object_hash($this) . mt_rand(0, PHP_INT_MAX) . uniqid('', true), true); } return base64_encode($key); }
[ "public", "function", "generateKey", "(", ")", "{", "if", "(", "extension_loaded", "(", "'openssl'", ")", ")", "{", "$", "key", "=", "openssl_random_pseudo_bytes", "(", "16", ")", ";", "}", "else", "{", "// SHA1 is 128 bit (= 16 bytes)", "$", "key", "=", "sha1", "(", "spl_object_hash", "(", "$", "this", ")", ".", "mt_rand", "(", "0", ",", "PHP_INT_MAX", ")", ".", "uniqid", "(", "''", ",", "true", ")", ",", "true", ")", ";", "}", "return", "base64_encode", "(", "$", "key", ")", ";", "}" ]
Generates a key suitable for use in the protocol This base implementation returns a 16-byte (128 bit) random key as a binary string. @return string
[ "Generates", "a", "key", "suitable", "for", "use", "in", "the", "protocol", "This", "base", "implementation", "returns", "a", "16", "-", "byte", "(", "128", "bit", ")", "random", "key", "as", "a", "binary", "string", "." ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L226-L236
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getRequestHandshake
public function getRequestHandshake( $uri, $key, $origin, array $headers = [] ) { if (!$uri || !$key || !$origin) { throw new InvalidArgumentException('You must supply a URI, key and origin'); } list($scheme, $host, $port, $path, $query) = self::validateUri($uri); if ($query) { $path .= '?' . $query; } if ($scheme == self::SCHEME_WEBSOCKET && $port == 80) { // do nothing } elseif ($scheme == self::SCHEME_WEBSOCKET_SECURE && $port == 443) { // do nothing } else { $host = $host . ':' . $port; } $handshake = [ sprintf(self::REQUEST_LINE_FORMAT, $path), ]; $headers = array_merge( $this->getDefaultRequestHeaders( $host, $key, $origin ), $headers ); foreach ($headers as $name => $value) { $handshake[] = sprintf(self::HEADER_LINE_FORMAT, $name, $value); } return implode($handshake, "\r\n") . "\r\n\r\n"; }
php
public function getRequestHandshake( $uri, $key, $origin, array $headers = [] ) { if (!$uri || !$key || !$origin) { throw new InvalidArgumentException('You must supply a URI, key and origin'); } list($scheme, $host, $port, $path, $query) = self::validateUri($uri); if ($query) { $path .= '?' . $query; } if ($scheme == self::SCHEME_WEBSOCKET && $port == 80) { // do nothing } elseif ($scheme == self::SCHEME_WEBSOCKET_SECURE && $port == 443) { // do nothing } else { $host = $host . ':' . $port; } $handshake = [ sprintf(self::REQUEST_LINE_FORMAT, $path), ]; $headers = array_merge( $this->getDefaultRequestHeaders( $host, $key, $origin ), $headers ); foreach ($headers as $name => $value) { $handshake[] = sprintf(self::HEADER_LINE_FORMAT, $name, $value); } return implode($handshake, "\r\n") . "\r\n\r\n"; }
[ "public", "function", "getRequestHandshake", "(", "$", "uri", ",", "$", "key", ",", "$", "origin", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "if", "(", "!", "$", "uri", "||", "!", "$", "key", "||", "!", "$", "origin", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'You must supply a URI, key and origin'", ")", ";", "}", "list", "(", "$", "scheme", ",", "$", "host", ",", "$", "port", ",", "$", "path", ",", "$", "query", ")", "=", "self", "::", "validateUri", "(", "$", "uri", ")", ";", "if", "(", "$", "query", ")", "{", "$", "path", ".=", "'?'", ".", "$", "query", ";", "}", "if", "(", "$", "scheme", "==", "self", "::", "SCHEME_WEBSOCKET", "&&", "$", "port", "==", "80", ")", "{", "// do nothing", "}", "elseif", "(", "$", "scheme", "==", "self", "::", "SCHEME_WEBSOCKET_SECURE", "&&", "$", "port", "==", "443", ")", "{", "// do nothing", "}", "else", "{", "$", "host", "=", "$", "host", ".", "':'", ".", "$", "port", ";", "}", "$", "handshake", "=", "[", "sprintf", "(", "self", "::", "REQUEST_LINE_FORMAT", ",", "$", "path", ")", ",", "]", ";", "$", "headers", "=", "array_merge", "(", "$", "this", "->", "getDefaultRequestHeaders", "(", "$", "host", ",", "$", "key", ",", "$", "origin", ")", ",", "$", "headers", ")", ";", "foreach", "(", "$", "headers", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "handshake", "[", "]", "=", "sprintf", "(", "self", "::", "HEADER_LINE_FORMAT", ",", "$", "name", ",", "$", "value", ")", ";", "}", "return", "implode", "(", "$", "handshake", ",", "\"\\r\\n\"", ")", ".", "\"\\r\\n\\r\\n\"", ";", "}" ]
Gets request handshake string The leading line from the client follows the Request-Line format. The leading line from the server follows the Status-Line format. The Request-Line and Status-Line productions are defined in [RFC2616]. An unordered set of header fields comes after the leading line in both cases. The meaning of these header fields is specified in Section 4 of this document. Additional header fields may also be present, such as cookies [RFC6265]. The format and parsing of headers is as defined in [RFC2616]. @param string $uri WebSocket URI, e.g. ws://example.org:8000/chat @param string $key 16 byte binary string key @param string $origin Origin of the request @return string
[ "Gets", "request", "handshake", "string", "The", "leading", "line", "from", "the", "client", "follows", "the", "Request", "-", "Line", "format", ".", "The", "leading", "line", "from", "the", "server", "follows", "the", "Status", "-", "Line", "format", ".", "The", "Request", "-", "Line", "and", "Status", "-", "Line", "productions", "are", "defined", "in", "[", "RFC2616", "]", ".", "An", "unordered", "set", "of", "header", "fields", "comes", "after", "the", "leading", "line", "in", "both", "cases", ".", "The", "meaning", "of", "these", "header", "fields", "is", "specified", "in", "Section", "4", "of", "this", "document", ".", "Additional", "header", "fields", "may", "also", "be", "present", "such", "as", "cookies", "[", "RFC6265", "]", ".", "The", "format", "and", "parsing", "of", "headers", "is", "as", "defined", "in", "[", "RFC2616", "]", "." ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L254-L295
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.validateUri
public function validateUri($uri) { $uri = (string)$uri; if (!$uri) { throw new InvalidArgumentException('Invalid URI'); } $scheme = parse_url($uri, PHP_URL_SCHEME); $this->validateScheme($scheme); $host = parse_url($uri, PHP_URL_HOST); if (!$host) { throw new InvalidArgumentException("Invalid host"); } $port = parse_url($uri, PHP_URL_PORT); if (!$port) { $port = $this->getPort($scheme); } $path = parse_url($uri, PHP_URL_PATH); if (!$path) { throw new InvalidArgumentException('Invalid path'); } $query = parse_url($uri, PHP_URL_QUERY); return [$scheme, $host, $port, $path, $query]; }
php
public function validateUri($uri) { $uri = (string)$uri; if (!$uri) { throw new InvalidArgumentException('Invalid URI'); } $scheme = parse_url($uri, PHP_URL_SCHEME); $this->validateScheme($scheme); $host = parse_url($uri, PHP_URL_HOST); if (!$host) { throw new InvalidArgumentException("Invalid host"); } $port = parse_url($uri, PHP_URL_PORT); if (!$port) { $port = $this->getPort($scheme); } $path = parse_url($uri, PHP_URL_PATH); if (!$path) { throw new InvalidArgumentException('Invalid path'); } $query = parse_url($uri, PHP_URL_QUERY); return [$scheme, $host, $port, $path, $query]; }
[ "public", "function", "validateUri", "(", "$", "uri", ")", "{", "$", "uri", "=", "(", "string", ")", "$", "uri", ";", "if", "(", "!", "$", "uri", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid URI'", ")", ";", "}", "$", "scheme", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_SCHEME", ")", ";", "$", "this", "->", "validateScheme", "(", "$", "scheme", ")", ";", "$", "host", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_HOST", ")", ";", "if", "(", "!", "$", "host", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid host\"", ")", ";", "}", "$", "port", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_PORT", ")", ";", "if", "(", "!", "$", "port", ")", "{", "$", "port", "=", "$", "this", "->", "getPort", "(", "$", "scheme", ")", ";", "}", "$", "path", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_PATH", ")", ";", "if", "(", "!", "$", "path", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid path'", ")", ";", "}", "$", "query", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_QUERY", ")", ";", "return", "[", "$", "scheme", ",", "$", "host", ",", "$", "port", ",", "$", "path", ",", "$", "query", "]", ";", "}" ]
Validates a WebSocket URI @param string $uri @return array(string $scheme, string $host, int $port, string $path)
[ "Validates", "a", "WebSocket", "URI" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L303-L331
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.validateScheme
protected function validateScheme($scheme) { if (!$scheme) { throw new InvalidArgumentException('No scheme specified'); } if (!in_array($scheme, self::$schemes)) { throw new InvalidArgumentException( 'Unknown socket scheme: ' . $scheme ); } if ($scheme == self::SCHEME_WEBSOCKET_SECURE) { return self::SCHEME_UNDERLYING_SECURE; } return self::SCHEME_UNDERLYING; }
php
protected function validateScheme($scheme) { if (!$scheme) { throw new InvalidArgumentException('No scheme specified'); } if (!in_array($scheme, self::$schemes)) { throw new InvalidArgumentException( 'Unknown socket scheme: ' . $scheme ); } if ($scheme == self::SCHEME_WEBSOCKET_SECURE) { return self::SCHEME_UNDERLYING_SECURE; } return self::SCHEME_UNDERLYING; }
[ "protected", "function", "validateScheme", "(", "$", "scheme", ")", "{", "if", "(", "!", "$", "scheme", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'No scheme specified'", ")", ";", "}", "if", "(", "!", "in_array", "(", "$", "scheme", ",", "self", "::", "$", "schemes", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Unknown socket scheme: '", ".", "$", "scheme", ")", ";", "}", "if", "(", "$", "scheme", "==", "self", "::", "SCHEME_WEBSOCKET_SECURE", ")", "{", "return", "self", "::", "SCHEME_UNDERLYING_SECURE", ";", "}", "return", "self", "::", "SCHEME_UNDERLYING", ";", "}" ]
Validates a scheme @param string $scheme @return string Underlying scheme @throws InvalidArgumentException
[ "Validates", "a", "scheme" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L340-L355
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getPort
protected function getPort($scheme) { if ($scheme == self::SCHEME_WEBSOCKET) { return 80; } elseif ($scheme == self::SCHEME_WEBSOCKET_SECURE) { return 443; } elseif ($scheme == self::SCHEME_UNDERLYING) { return 80; } elseif ($scheme == self::SCHEME_UNDERLYING_SECURE) { return 443; } else { throw new InvalidArgumentException('Unknown websocket scheme'); } }
php
protected function getPort($scheme) { if ($scheme == self::SCHEME_WEBSOCKET) { return 80; } elseif ($scheme == self::SCHEME_WEBSOCKET_SECURE) { return 443; } elseif ($scheme == self::SCHEME_UNDERLYING) { return 80; } elseif ($scheme == self::SCHEME_UNDERLYING_SECURE) { return 443; } else { throw new InvalidArgumentException('Unknown websocket scheme'); } }
[ "protected", "function", "getPort", "(", "$", "scheme", ")", "{", "if", "(", "$", "scheme", "==", "self", "::", "SCHEME_WEBSOCKET", ")", "{", "return", "80", ";", "}", "elseif", "(", "$", "scheme", "==", "self", "::", "SCHEME_WEBSOCKET_SECURE", ")", "{", "return", "443", ";", "}", "elseif", "(", "$", "scheme", "==", "self", "::", "SCHEME_UNDERLYING", ")", "{", "return", "80", ";", "}", "elseif", "(", "$", "scheme", "==", "self", "::", "SCHEME_UNDERLYING_SECURE", ")", "{", "return", "443", ";", "}", "else", "{", "throw", "new", "InvalidArgumentException", "(", "'Unknown websocket scheme'", ")", ";", "}", "}" ]
Gets the default port for a scheme By default, the WebSocket Protocol uses port 80 for regular WebSocket connections and port 443 for WebSocket connections tunneled over Transport Layer Security @param string|false $scheme @return int
[ "Gets", "the", "default", "port", "for", "a", "scheme", "By", "default", "the", "WebSocket", "Protocol", "uses", "port", "80", "for", "regular", "WebSocket", "connections", "and", "port", "443", "for", "WebSocket", "connections", "tunneled", "over", "Transport", "Layer", "Security" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L366-L379
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getDefaultRequestHeaders
protected function getDefaultRequestHeaders($host, $key, $origin) { return [ self::HEADER_HOST => $host, self::HEADER_UPGRADE => self::UPGRADE_VALUE, self::HEADER_CONNECTION => self::CONNECTION_VALUE, self::HEADER_KEY => $key, self::HEADER_ORIGIN => $origin, self::HEADER_VERSION => $this->getVersion(), ]; }
php
protected function getDefaultRequestHeaders($host, $key, $origin) { return [ self::HEADER_HOST => $host, self::HEADER_UPGRADE => self::UPGRADE_VALUE, self::HEADER_CONNECTION => self::CONNECTION_VALUE, self::HEADER_KEY => $key, self::HEADER_ORIGIN => $origin, self::HEADER_VERSION => $this->getVersion(), ]; }
[ "protected", "function", "getDefaultRequestHeaders", "(", "$", "host", ",", "$", "key", ",", "$", "origin", ")", "{", "return", "[", "self", "::", "HEADER_HOST", "=>", "$", "host", ",", "self", "::", "HEADER_UPGRADE", "=>", "self", "::", "UPGRADE_VALUE", ",", "self", "::", "HEADER_CONNECTION", "=>", "self", "::", "CONNECTION_VALUE", ",", "self", "::", "HEADER_KEY", "=>", "$", "key", ",", "self", "::", "HEADER_ORIGIN", "=>", "$", "origin", ",", "self", "::", "HEADER_VERSION", "=>", "$", "this", "->", "getVersion", "(", ")", ",", "]", ";", "}" ]
Gets the default request headers @param string $host @param string $key @param string $origin @return string[]
[ "Gets", "the", "default", "request", "headers" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L389-L399
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getResponseHandshake
public function getResponseHandshake($key, array $headers = []) { $headers = array_merge( $this->getSuccessResponseHeaders( $key ), $headers ); return $this->getHttpResponse(self::HTTP_SWITCHING_PROTOCOLS, $headers); }
php
public function getResponseHandshake($key, array $headers = []) { $headers = array_merge( $this->getSuccessResponseHeaders( $key ), $headers ); return $this->getHttpResponse(self::HTTP_SWITCHING_PROTOCOLS, $headers); }
[ "public", "function", "getResponseHandshake", "(", "$", "key", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "$", "headers", "=", "array_merge", "(", "$", "this", "->", "getSuccessResponseHeaders", "(", "$", "key", ")", ",", "$", "headers", ")", ";", "return", "$", "this", "->", "getHttpResponse", "(", "self", "::", "HTTP_SWITCHING_PROTOCOLS", ",", "$", "headers", ")", ";", "}" ]
Gets a handshake response body @param string $key @param array $headers
[ "Gets", "a", "handshake", "response", "body" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L414-L424
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getSuccessResponseHeaders
protected function getSuccessResponseHeaders($key) { return [ self::HEADER_UPGRADE => self::UPGRADE_VALUE, self::HEADER_CONNECTION => self::CONNECTION_VALUE, self::HEADER_ACCEPT => $this->getAcceptValue($key), ]; }
php
protected function getSuccessResponseHeaders($key) { return [ self::HEADER_UPGRADE => self::UPGRADE_VALUE, self::HEADER_CONNECTION => self::CONNECTION_VALUE, self::HEADER_ACCEPT => $this->getAcceptValue($key), ]; }
[ "protected", "function", "getSuccessResponseHeaders", "(", "$", "key", ")", "{", "return", "[", "self", "::", "HEADER_UPGRADE", "=>", "self", "::", "UPGRADE_VALUE", ",", "self", "::", "HEADER_CONNECTION", "=>", "self", "::", "CONNECTION_VALUE", ",", "self", "::", "HEADER_ACCEPT", "=>", "$", "this", "->", "getAcceptValue", "(", "$", "key", ")", ",", "]", ";", "}" ]
Gets the default response headers @param string $key @return string[]
[ "Gets", "the", "default", "response", "headers" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L432-L439
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getHttpResponse
protected function getHttpResponse($status, array $headers = []) { if (array_key_exists($status, self::HTTP_RESPONSES)) { $response = self::HTTP_RESPONSES[$status]; } else { $response = self::HTTP_RESPONSES[self::HTTP_NOT_IMPLEMENTED]; } $handshake = [ sprintf(self::RESPONSE_LINE_FORMAT, $status, $response), ]; foreach ($headers as $name => $value) { $handshake[] = sprintf(self::HEADER_LINE_FORMAT, $name, $value); } return implode($handshake, "\r\n") . "\r\n\r\n"; }
php
protected function getHttpResponse($status, array $headers = []) { if (array_key_exists($status, self::HTTP_RESPONSES)) { $response = self::HTTP_RESPONSES[$status]; } else { $response = self::HTTP_RESPONSES[self::HTTP_NOT_IMPLEMENTED]; } $handshake = [ sprintf(self::RESPONSE_LINE_FORMAT, $status, $response), ]; foreach ($headers as $name => $value) { $handshake[] = sprintf(self::HEADER_LINE_FORMAT, $name, $value); } return implode($handshake, "\r\n") . "\r\n\r\n"; }
[ "protected", "function", "getHttpResponse", "(", "$", "status", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "if", "(", "array_key_exists", "(", "$", "status", ",", "self", "::", "HTTP_RESPONSES", ")", ")", "{", "$", "response", "=", "self", "::", "HTTP_RESPONSES", "[", "$", "status", "]", ";", "}", "else", "{", "$", "response", "=", "self", "::", "HTTP_RESPONSES", "[", "self", "::", "HTTP_NOT_IMPLEMENTED", "]", ";", "}", "$", "handshake", "=", "[", "sprintf", "(", "self", "::", "RESPONSE_LINE_FORMAT", ",", "$", "status", ",", "$", "response", ")", ",", "]", ";", "foreach", "(", "$", "headers", "as", "$", "name", "=>", "$", "value", ")", "{", "$", "handshake", "[", "]", "=", "sprintf", "(", "self", "::", "HEADER_LINE_FORMAT", ",", "$", "name", ",", "$", "value", ")", ";", "}", "return", "implode", "(", "$", "handshake", ",", "\"\\r\\n\"", ")", ".", "\"\\r\\n\\r\\n\"", ";", "}" ]
Gets an HTTP response @param int $status @param array $headers @return string
[ "Gets", "an", "HTTP", "response" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L462-L479
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getResponseError
public function getResponseError($e, array $headers = []) { $code = false; if ($e instanceof Exception) { $code = $e->getCode(); } elseif (is_numeric($e)) { $code = (int)$e; } if (!$code || $code < 400 || $code > 599) { $code = self::HTTP_SERVER_ERROR; } return $this->getHttpResponse($code, $headers); }
php
public function getResponseError($e, array $headers = []) { $code = false; if ($e instanceof Exception) { $code = $e->getCode(); } elseif (is_numeric($e)) { $code = (int)$e; } if (!$code || $code < 400 || $code > 599) { $code = self::HTTP_SERVER_ERROR; } return $this->getHttpResponse($code, $headers); }
[ "public", "function", "getResponseError", "(", "$", "e", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "$", "code", "=", "false", ";", "if", "(", "$", "e", "instanceof", "Exception", ")", "{", "$", "code", "=", "$", "e", "->", "getCode", "(", ")", ";", "}", "elseif", "(", "is_numeric", "(", "$", "e", ")", ")", "{", "$", "code", "=", "(", "int", ")", "$", "e", ";", "}", "if", "(", "!", "$", "code", "||", "$", "code", "<", "400", "||", "$", "code", ">", "599", ")", "{", "$", "code", "=", "self", "::", "HTTP_SERVER_ERROR", ";", "}", "return", "$", "this", "->", "getHttpResponse", "(", "$", "code", ",", "$", "headers", ")", ";", "}" ]
Gets a response to an error in the handshake @param int|Exception $e Exception or HTTP error @param array $headers @return string
[ "Gets", "a", "response", "to", "an", "error", "in", "the", "handshake" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L488-L503
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getHeaders
protected function getHeaders($response, &$request_line = null) { $parts = explode("\r\n\r\n", $response, 2); if (count($parts) < 2) { $parts[] = ''; } list($headers, $body) = $parts; $return = []; foreach (explode("\r\n", $headers) as $header) { $parts = explode(': ', $header, 2); if (count($parts) == 2) { list($name, $value) = $parts; if (!isset($return[$name])) { $return[$name] = $value; } else { if (is_array($return[$name])) { $return[$name][] = $value; } else { $return[$name] = [$return[$name], $value]; } } } } return array_change_key_case($return); }
php
protected function getHeaders($response, &$request_line = null) { $parts = explode("\r\n\r\n", $response, 2); if (count($parts) < 2) { $parts[] = ''; } list($headers, $body) = $parts; $return = []; foreach (explode("\r\n", $headers) as $header) { $parts = explode(': ', $header, 2); if (count($parts) == 2) { list($name, $value) = $parts; if (!isset($return[$name])) { $return[$name] = $value; } else { if (is_array($return[$name])) { $return[$name][] = $value; } else { $return[$name] = [$return[$name], $value]; } } } } return array_change_key_case($return); }
[ "protected", "function", "getHeaders", "(", "$", "response", ",", "&", "$", "request_line", "=", "null", ")", "{", "$", "parts", "=", "explode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "response", ",", "2", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "<", "2", ")", "{", "$", "parts", "[", "]", "=", "''", ";", "}", "list", "(", "$", "headers", ",", "$", "body", ")", "=", "$", "parts", ";", "$", "return", "=", "[", "]", ";", "foreach", "(", "explode", "(", "\"\\r\\n\"", ",", "$", "headers", ")", "as", "$", "header", ")", "{", "$", "parts", "=", "explode", "(", "': '", ",", "$", "header", ",", "2", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "==", "2", ")", "{", "list", "(", "$", "name", ",", "$", "value", ")", "=", "$", "parts", ";", "if", "(", "!", "isset", "(", "$", "return", "[", "$", "name", "]", ")", ")", "{", "$", "return", "[", "$", "name", "]", "=", "$", "value", ";", "}", "else", "{", "if", "(", "is_array", "(", "$", "return", "[", "$", "name", "]", ")", ")", "{", "$", "return", "[", "$", "name", "]", "[", "]", "=", "$", "value", ";", "}", "else", "{", "$", "return", "[", "$", "name", "]", "=", "[", "$", "return", "[", "$", "name", "]", ",", "$", "value", "]", ";", "}", "}", "}", "}", "return", "array_change_key_case", "(", "$", "return", ")", ";", "}" ]
Gets the headers from a full response @param string $response @return array() @throws InvalidArgumentException
[ "Gets", "the", "headers", "from", "a", "full", "response" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L545-L573
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.validateRequestHandshake
public function validateRequestHandshake( $request ) { if (!$request) { return false; } list($request, $headers) = $this->getRequestHeaders($request); // make a copy of the headers array to store all extra headers $extraHeaders = $headers; // parse the resulting url to separate query parameters from the path $url = parse_url($this->validateRequestLine($request)); $path = isset($url['path']) ? $url['path'] : null; $urlParams = []; if (isset($url['query'])) { parse_str($url['query'], $urlParams); } if (empty($headers[self::HEADER_ORIGIN])) { throw new BadRequestException('No origin header'); } else { unset($extraHeaders[self::HEADER_ORIGIN]); } $origin = $headers[self::HEADER_ORIGIN]; if (!isset($headers[self::HEADER_UPGRADE]) || strtolower($headers[self::HEADER_UPGRADE]) != self::UPGRADE_VALUE ) { throw new BadRequestException('Invalid upgrade header'); } else { unset($extraHeaders[self::HEADER_UPGRADE]); } if (!isset($headers[self::HEADER_CONNECTION]) || stripos($headers[self::HEADER_CONNECTION], self::CONNECTION_VALUE) === false ) { throw new BadRequestException('Invalid connection header'); } else { unset($extraHeaders[self::HEADER_CONNECTION]); } if (!isset($headers[self::HEADER_HOST])) { // @todo Validate host == listening socket? Or would that break // TCP proxies? throw new BadRequestException('No host header'); } else { unset($extraHeaders[self::HEADER_HOST]); } if (!isset($headers[self::HEADER_VERSION])) { throw new BadRequestException('No version header received on handshake request'); } if (!$this->acceptsVersion($headers[self::HEADER_VERSION])) { throw new BadRequestException('Unsupported version: ' . $headers[self::HEADER_VERSION]); } else { unset($extraHeaders[self::HEADER_VERSION]); } if (!isset($headers[self::HEADER_KEY])) { throw new BadRequestException('No key header received'); } $key = trim($headers[self::HEADER_KEY]); if (!$key) { throw new BadRequestException('Invalid key'); } else { unset($extraHeaders[self::HEADER_KEY]); } // Optional $protocol = null; if (isset($headers[self::HEADER_PROTOCOL])) { $protocol = $headers[self::HEADER_PROTOCOL]; unset($extraHeaders[self::HEADER_PROTOCOL]); } $extensions = []; if (!empty($headers[self::HEADER_EXTENSIONS])) { $extensions = $headers[self::HEADER_EXTENSIONS]; if (is_scalar($extensions)) { $extensions = [$extensions]; } } unset($extraHeaders[self::HEADER_EXTENSIONS]); return [$path, $origin, $key, $extensions, $protocol, $extraHeaders, $urlParams]; }
php
public function validateRequestHandshake( $request ) { if (!$request) { return false; } list($request, $headers) = $this->getRequestHeaders($request); // make a copy of the headers array to store all extra headers $extraHeaders = $headers; // parse the resulting url to separate query parameters from the path $url = parse_url($this->validateRequestLine($request)); $path = isset($url['path']) ? $url['path'] : null; $urlParams = []; if (isset($url['query'])) { parse_str($url['query'], $urlParams); } if (empty($headers[self::HEADER_ORIGIN])) { throw new BadRequestException('No origin header'); } else { unset($extraHeaders[self::HEADER_ORIGIN]); } $origin = $headers[self::HEADER_ORIGIN]; if (!isset($headers[self::HEADER_UPGRADE]) || strtolower($headers[self::HEADER_UPGRADE]) != self::UPGRADE_VALUE ) { throw new BadRequestException('Invalid upgrade header'); } else { unset($extraHeaders[self::HEADER_UPGRADE]); } if (!isset($headers[self::HEADER_CONNECTION]) || stripos($headers[self::HEADER_CONNECTION], self::CONNECTION_VALUE) === false ) { throw new BadRequestException('Invalid connection header'); } else { unset($extraHeaders[self::HEADER_CONNECTION]); } if (!isset($headers[self::HEADER_HOST])) { // @todo Validate host == listening socket? Or would that break // TCP proxies? throw new BadRequestException('No host header'); } else { unset($extraHeaders[self::HEADER_HOST]); } if (!isset($headers[self::HEADER_VERSION])) { throw new BadRequestException('No version header received on handshake request'); } if (!$this->acceptsVersion($headers[self::HEADER_VERSION])) { throw new BadRequestException('Unsupported version: ' . $headers[self::HEADER_VERSION]); } else { unset($extraHeaders[self::HEADER_VERSION]); } if (!isset($headers[self::HEADER_KEY])) { throw new BadRequestException('No key header received'); } $key = trim($headers[self::HEADER_KEY]); if (!$key) { throw new BadRequestException('Invalid key'); } else { unset($extraHeaders[self::HEADER_KEY]); } // Optional $protocol = null; if (isset($headers[self::HEADER_PROTOCOL])) { $protocol = $headers[self::HEADER_PROTOCOL]; unset($extraHeaders[self::HEADER_PROTOCOL]); } $extensions = []; if (!empty($headers[self::HEADER_EXTENSIONS])) { $extensions = $headers[self::HEADER_EXTENSIONS]; if (is_scalar($extensions)) { $extensions = [$extensions]; } } unset($extraHeaders[self::HEADER_EXTENSIONS]); return [$path, $origin, $key, $extensions, $protocol, $extraHeaders, $urlParams]; }
[ "public", "function", "validateRequestHandshake", "(", "$", "request", ")", "{", "if", "(", "!", "$", "request", ")", "{", "return", "false", ";", "}", "list", "(", "$", "request", ",", "$", "headers", ")", "=", "$", "this", "->", "getRequestHeaders", "(", "$", "request", ")", ";", "// make a copy of the headers array to store all extra headers", "$", "extraHeaders", "=", "$", "headers", ";", "// parse the resulting url to separate query parameters from the path", "$", "url", "=", "parse_url", "(", "$", "this", "->", "validateRequestLine", "(", "$", "request", ")", ")", ";", "$", "path", "=", "isset", "(", "$", "url", "[", "'path'", "]", ")", "?", "$", "url", "[", "'path'", "]", ":", "null", ";", "$", "urlParams", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "url", "[", "'query'", "]", ")", ")", "{", "parse_str", "(", "$", "url", "[", "'query'", "]", ",", "$", "urlParams", ")", ";", "}", "if", "(", "empty", "(", "$", "headers", "[", "self", "::", "HEADER_ORIGIN", "]", ")", ")", "{", "throw", "new", "BadRequestException", "(", "'No origin header'", ")", ";", "}", "else", "{", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_ORIGIN", "]", ")", ";", "}", "$", "origin", "=", "$", "headers", "[", "self", "::", "HEADER_ORIGIN", "]", ";", "if", "(", "!", "isset", "(", "$", "headers", "[", "self", "::", "HEADER_UPGRADE", "]", ")", "||", "strtolower", "(", "$", "headers", "[", "self", "::", "HEADER_UPGRADE", "]", ")", "!=", "self", "::", "UPGRADE_VALUE", ")", "{", "throw", "new", "BadRequestException", "(", "'Invalid upgrade header'", ")", ";", "}", "else", "{", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_UPGRADE", "]", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "headers", "[", "self", "::", "HEADER_CONNECTION", "]", ")", "||", "stripos", "(", "$", "headers", "[", "self", "::", "HEADER_CONNECTION", "]", ",", "self", "::", "CONNECTION_VALUE", ")", "===", "false", ")", "{", "throw", "new", "BadRequestException", "(", "'Invalid connection header'", ")", ";", "}", "else", "{", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_CONNECTION", "]", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "headers", "[", "self", "::", "HEADER_HOST", "]", ")", ")", "{", "// @todo Validate host == listening socket? Or would that break", "// TCP proxies?", "throw", "new", "BadRequestException", "(", "'No host header'", ")", ";", "}", "else", "{", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_HOST", "]", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "headers", "[", "self", "::", "HEADER_VERSION", "]", ")", ")", "{", "throw", "new", "BadRequestException", "(", "'No version header received on handshake request'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "acceptsVersion", "(", "$", "headers", "[", "self", "::", "HEADER_VERSION", "]", ")", ")", "{", "throw", "new", "BadRequestException", "(", "'Unsupported version: '", ".", "$", "headers", "[", "self", "::", "HEADER_VERSION", "]", ")", ";", "}", "else", "{", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_VERSION", "]", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "headers", "[", "self", "::", "HEADER_KEY", "]", ")", ")", "{", "throw", "new", "BadRequestException", "(", "'No key header received'", ")", ";", "}", "$", "key", "=", "trim", "(", "$", "headers", "[", "self", "::", "HEADER_KEY", "]", ")", ";", "if", "(", "!", "$", "key", ")", "{", "throw", "new", "BadRequestException", "(", "'Invalid key'", ")", ";", "}", "else", "{", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_KEY", "]", ")", ";", "}", "// Optional", "$", "protocol", "=", "null", ";", "if", "(", "isset", "(", "$", "headers", "[", "self", "::", "HEADER_PROTOCOL", "]", ")", ")", "{", "$", "protocol", "=", "$", "headers", "[", "self", "::", "HEADER_PROTOCOL", "]", ";", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_PROTOCOL", "]", ")", ";", "}", "$", "extensions", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "headers", "[", "self", "::", "HEADER_EXTENSIONS", "]", ")", ")", "{", "$", "extensions", "=", "$", "headers", "[", "self", "::", "HEADER_EXTENSIONS", "]", ";", "if", "(", "is_scalar", "(", "$", "extensions", ")", ")", "{", "$", "extensions", "=", "[", "$", "extensions", "]", ";", "}", "}", "unset", "(", "$", "extraHeaders", "[", "self", "::", "HEADER_EXTENSIONS", "]", ")", ";", "return", "[", "$", "path", ",", "$", "origin", ",", "$", "key", ",", "$", "extensions", ",", "$", "protocol", ",", "$", "extraHeaders", ",", "$", "urlParams", "]", ";", "}" ]
Validates a request handshake @param string $request @throws BadRequestException
[ "Validates", "a", "request", "handshake" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L592-L682
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getRequestHeaders
protected function getRequestHeaders($response) { $eol = stripos($response, "\r\n"); if ($eol === false) { throw new InvalidArgumentException('Invalid request line'); } $request = substr($response, 0, $eol); $headers = $this->getHeaders(substr($response, $eol + 2)); return [$request, $headers]; }
php
protected function getRequestHeaders($response) { $eol = stripos($response, "\r\n"); if ($eol === false) { throw new InvalidArgumentException('Invalid request line'); } $request = substr($response, 0, $eol); $headers = $this->getHeaders(substr($response, $eol + 2)); return [$request, $headers]; }
[ "protected", "function", "getRequestHeaders", "(", "$", "response", ")", "{", "$", "eol", "=", "stripos", "(", "$", "response", ",", "\"\\r\\n\"", ")", ";", "if", "(", "$", "eol", "===", "false", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid request line'", ")", ";", "}", "$", "request", "=", "substr", "(", "$", "response", ",", "0", ",", "$", "eol", ")", ";", "$", "headers", "=", "$", "this", "->", "getHeaders", "(", "substr", "(", "$", "response", ",", "$", "eol", "+", "2", ")", ")", ";", "return", "[", "$", "request", ",", "$", "headers", "]", ";", "}" ]
Gets request headers @param string $response @return array<string, array<string>> The request line, and an array of headers @throws InvalidArgumentException
[ "Gets", "request", "headers" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L692-L704
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.validateRequestLine
protected function validateRequestLine($line) { $matches = [0 => null, 1 => null]; if (!preg_match(self::REQUEST_LINE_REGEX, $line, $matches) || !$matches[1]) { throw new BadRequestException('Invalid request line', 400); } return $matches[1]; }
php
protected function validateRequestLine($line) { $matches = [0 => null, 1 => null]; if (!preg_match(self::REQUEST_LINE_REGEX, $line, $matches) || !$matches[1]) { throw new BadRequestException('Invalid request line', 400); } return $matches[1]; }
[ "protected", "function", "validateRequestLine", "(", "$", "line", ")", "{", "$", "matches", "=", "[", "0", "=>", "null", ",", "1", "=>", "null", "]", ";", "if", "(", "!", "preg_match", "(", "self", "::", "REQUEST_LINE_REGEX", ",", "$", "line", ",", "$", "matches", ")", "||", "!", "$", "matches", "[", "1", "]", ")", "{", "throw", "new", "BadRequestException", "(", "'Invalid request line'", ",", "400", ")", ";", "}", "return", "$", "matches", "[", "1", "]", ";", "}" ]
Validates a request line @param string $line @throws BadRequestException
[ "Validates", "a", "request", "line" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L712-L721
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.getClosePayload
public function getClosePayload($e, $masked = true) { $code = false; if ($e instanceof Exception) { $code = $e->getCode(); } elseif (is_numeric($e)) { $code = (int)$e; } if (!$code || !key_exists($code, self::CLOSE_REASONS)) { $code = self::CLOSE_UNEXPECTED; } $body = pack('n', $code) . self::CLOSE_REASONS[$code]; $payload = $this->getPayload(); return $payload->encode($body, self::TYPE_CLOSE, $masked); }
php
public function getClosePayload($e, $masked = true) { $code = false; if ($e instanceof Exception) { $code = $e->getCode(); } elseif (is_numeric($e)) { $code = (int)$e; } if (!$code || !key_exists($code, self::CLOSE_REASONS)) { $code = self::CLOSE_UNEXPECTED; } $body = pack('n', $code) . self::CLOSE_REASONS[$code]; $payload = $this->getPayload(); return $payload->encode($body, self::TYPE_CLOSE, $masked); }
[ "public", "function", "getClosePayload", "(", "$", "e", ",", "$", "masked", "=", "true", ")", "{", "$", "code", "=", "false", ";", "if", "(", "$", "e", "instanceof", "Exception", ")", "{", "$", "code", "=", "$", "e", "->", "getCode", "(", ")", ";", "}", "elseif", "(", "is_numeric", "(", "$", "e", ")", ")", "{", "$", "code", "=", "(", "int", ")", "$", "e", ";", "}", "if", "(", "!", "$", "code", "||", "!", "key_exists", "(", "$", "code", ",", "self", "::", "CLOSE_REASONS", ")", ")", "{", "$", "code", "=", "self", "::", "CLOSE_UNEXPECTED", ";", "}", "$", "body", "=", "pack", "(", "'n'", ",", "$", "code", ")", ".", "self", "::", "CLOSE_REASONS", "[", "$", "code", "]", ";", "$", "payload", "=", "$", "this", "->", "getPayload", "(", ")", ";", "return", "$", "payload", "->", "encode", "(", "$", "body", ",", "self", "::", "TYPE_CLOSE", ",", "$", "masked", ")", ";", "}" ]
Gets a suitable WebSocket close frame. Please set `masked` to false if you send a close frame from server side. @param Exception|int $e @param boolean $masked @return Payload
[ "Gets", "a", "suitable", "WebSocket", "close", "frame", ".", "Please", "set", "masked", "to", "false", "if", "you", "send", "a", "close", "frame", "from", "server", "side", "." ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L740-L758
varspool/Wrench
lib/Protocol/Protocol.php
Protocol.validateSocketUri
public function validateSocketUri($uri) { $uri = (string)$uri; if (!$uri) { throw new InvalidArgumentException('Invalid URI'); } $scheme = parse_url($uri, PHP_URL_SCHEME); $scheme = $this->validateScheme($scheme); $host = parse_url($uri, PHP_URL_HOST); if (!$host) { throw new InvalidArgumentException("Invalid host"); } $port = parse_url($uri, PHP_URL_PORT); if (!$port) { $port = $this->getPort($scheme); } return [$scheme, $host, $port]; }
php
public function validateSocketUri($uri) { $uri = (string)$uri; if (!$uri) { throw new InvalidArgumentException('Invalid URI'); } $scheme = parse_url($uri, PHP_URL_SCHEME); $scheme = $this->validateScheme($scheme); $host = parse_url($uri, PHP_URL_HOST); if (!$host) { throw new InvalidArgumentException("Invalid host"); } $port = parse_url($uri, PHP_URL_PORT); if (!$port) { $port = $this->getPort($scheme); } return [$scheme, $host, $port]; }
[ "public", "function", "validateSocketUri", "(", "$", "uri", ")", "{", "$", "uri", "=", "(", "string", ")", "$", "uri", ";", "if", "(", "!", "$", "uri", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid URI'", ")", ";", "}", "$", "scheme", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_SCHEME", ")", ";", "$", "scheme", "=", "$", "this", "->", "validateScheme", "(", "$", "scheme", ")", ";", "$", "host", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_HOST", ")", ";", "if", "(", "!", "$", "host", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Invalid host\"", ")", ";", "}", "$", "port", "=", "parse_url", "(", "$", "uri", ",", "PHP_URL_PORT", ")", ";", "if", "(", "!", "$", "port", ")", "{", "$", "port", "=", "$", "this", "->", "getPort", "(", "$", "scheme", ")", ";", "}", "return", "[", "$", "scheme", ",", "$", "host", ",", "$", "port", "]", ";", "}" ]
Validates a socket URI @param string $uri @throws InvalidArgumentException @return array(string $scheme, string $host, string $port)
[ "Validates", "a", "socket", "URI" ]
train
https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L775-L796