repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.getCurrentUserPrincipals
public function getCurrentUserPrincipals() { $currentUser = $this->getCurrentUserPrincipal(); if (is_null($currentUser)) { return []; } return array_merge( [$currentUser], $this->getPrincipalMembership($currentUser) ); }
php
public function getCurrentUserPrincipals() { $currentUser = $this->getCurrentUserPrincipal(); if (is_null($currentUser)) { return []; } return array_merge( [$currentUser], $this->getPrincipalMembership($currentUser) ); }
[ "public", "function", "getCurrentUserPrincipals", "(", ")", "{", "$", "currentUser", "=", "$", "this", "->", "getCurrentUserPrincipal", "(", ")", ";", "if", "(", "is_null", "(", "$", "currentUser", ")", ")", "{", "return", "[", "]", ";", "}", "return", "...
Returns a list of principals that's associated to the current user, either directly or through group membership. @return array
[ "Returns", "a", "list", "of", "principals", "that", "s", "associated", "to", "the", "current", "user", "either", "directly", "or", "through", "group", "membership", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L254-L266
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.getPrincipalMembership
public function getPrincipalMembership($mainPrincipal) { // First check our cache if (isset($this->principalMembershipCache[$mainPrincipal])) { return $this->principalMembershipCache[$mainPrincipal]; } $check = [$mainPrincipal]; $principals = []; while (count($check)) { $principal = array_shift($check); $node = $this->server->tree->getNodeForPath($principal); if ($node instanceof IPrincipal) { foreach ($node->getGroupMembership() as $groupMember) { if (!in_array($groupMember, $principals)) { $check[] = $groupMember; $principals[] = $groupMember; } } } } // Store the result in the cache $this->principalMembershipCache[$mainPrincipal] = $principals; return $principals; }
php
public function getPrincipalMembership($mainPrincipal) { // First check our cache if (isset($this->principalMembershipCache[$mainPrincipal])) { return $this->principalMembershipCache[$mainPrincipal]; } $check = [$mainPrincipal]; $principals = []; while (count($check)) { $principal = array_shift($check); $node = $this->server->tree->getNodeForPath($principal); if ($node instanceof IPrincipal) { foreach ($node->getGroupMembership() as $groupMember) { if (!in_array($groupMember, $principals)) { $check[] = $groupMember; $principals[] = $groupMember; } } } } // Store the result in the cache $this->principalMembershipCache[$mainPrincipal] = $principals; return $principals; }
[ "public", "function", "getPrincipalMembership", "(", "$", "mainPrincipal", ")", "{", "// First check our cache", "if", "(", "isset", "(", "$", "this", "->", "principalMembershipCache", "[", "$", "mainPrincipal", "]", ")", ")", "{", "return", "$", "this", "->", ...
Returns all the principal groups the specified principal is a member of. @param string $mainPrincipal @return array
[ "Returns", "all", "the", "principal", "groups", "the", "specified", "principal", "is", "a", "member", "of", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L324-L352
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.principalMatchesPrincipal
public function principalMatchesPrincipal($checkPrincipal, $currentPrincipal = null) { if (is_null($currentPrincipal)) { $currentPrincipal = $this->getCurrentUserPrincipal(); } if ($currentPrincipal === $checkPrincipal) { return true; } if (is_null($currentPrincipal)) { return false; } return in_array( $checkPrincipal, $this->getPrincipalMembership($currentPrincipal) ); }
php
public function principalMatchesPrincipal($checkPrincipal, $currentPrincipal = null) { if (is_null($currentPrincipal)) { $currentPrincipal = $this->getCurrentUserPrincipal(); } if ($currentPrincipal === $checkPrincipal) { return true; } if (is_null($currentPrincipal)) { return false; } return in_array( $checkPrincipal, $this->getPrincipalMembership($currentPrincipal) ); }
[ "public", "function", "principalMatchesPrincipal", "(", "$", "checkPrincipal", ",", "$", "currentPrincipal", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "currentPrincipal", ")", ")", "{", "$", "currentPrincipal", "=", "$", "this", "->", "getCurrentU...
Find out of a principal equals another principal. This is a quick way to find out whether a principal URI is part of a group, or any subgroups. The first argument is the principal URI you want to check against. For example the principal group, and the second argument is the principal of which you want to find out of it is the same as the first principal, or in a member of the first principal's group or subgroups. So the arguments are not interchangeable. If principal A is in group B, passing 'B', 'A' will yield true, but 'A', 'B' is false. If the second argument is not passed, we will use the current user principal. @param string $checkPrincipal @param string $currentPrincipal @return bool
[ "Find", "out", "of", "a", "principal", "equals", "another", "principal", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L376-L392
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.getSupportedPrivilegeSet
public function getSupportedPrivilegeSet($node) { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } $supportedPrivileges = null; if ($node instanceof IACL) { $supportedPrivileges = $node->getSupportedPrivilegeSet(); } if (is_null($supportedPrivileges)) { // Default $supportedPrivileges = [ '{DAV:}read' => [ 'abstract' => false, 'aggregates' => [ '{DAV:}read-acl' => [ 'abstract' => false, 'aggregates' => [], ], '{DAV:}read-current-user-privilege-set' => [ 'abstract' => false, 'aggregates' => [], ], ], ], '{DAV:}write' => [ 'abstract' => false, 'aggregates' => [ '{DAV:}write-properties' => [ 'abstract' => false, 'aggregates' => [], ], '{DAV:}write-content' => [ 'abstract' => false, 'aggregates' => [], ], '{DAV:}unlock' => [ 'abstract' => false, 'aggregates' => [], ], ], ], ]; if ($node instanceof DAV\ICollection) { $supportedPrivileges['{DAV:}write']['aggregates']['{DAV:}bind'] = [ 'abstract' => false, 'aggregates' => [], ]; $supportedPrivileges['{DAV:}write']['aggregates']['{DAV:}unbind'] = [ 'abstract' => false, 'aggregates' => [], ]; } if ($node instanceof IACL) { $supportedPrivileges['{DAV:}write']['aggregates']['{DAV:}write-acl'] = [ 'abstract' => false, 'aggregates' => [], ]; } } $this->server->emit( 'getSupportedPrivilegeSet', [$node, &$supportedPrivileges] ); return $supportedPrivileges; }
php
public function getSupportedPrivilegeSet($node) { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } $supportedPrivileges = null; if ($node instanceof IACL) { $supportedPrivileges = $node->getSupportedPrivilegeSet(); } if (is_null($supportedPrivileges)) { // Default $supportedPrivileges = [ '{DAV:}read' => [ 'abstract' => false, 'aggregates' => [ '{DAV:}read-acl' => [ 'abstract' => false, 'aggregates' => [], ], '{DAV:}read-current-user-privilege-set' => [ 'abstract' => false, 'aggregates' => [], ], ], ], '{DAV:}write' => [ 'abstract' => false, 'aggregates' => [ '{DAV:}write-properties' => [ 'abstract' => false, 'aggregates' => [], ], '{DAV:}write-content' => [ 'abstract' => false, 'aggregates' => [], ], '{DAV:}unlock' => [ 'abstract' => false, 'aggregates' => [], ], ], ], ]; if ($node instanceof DAV\ICollection) { $supportedPrivileges['{DAV:}write']['aggregates']['{DAV:}bind'] = [ 'abstract' => false, 'aggregates' => [], ]; $supportedPrivileges['{DAV:}write']['aggregates']['{DAV:}unbind'] = [ 'abstract' => false, 'aggregates' => [], ]; } if ($node instanceof IACL) { $supportedPrivileges['{DAV:}write']['aggregates']['{DAV:}write-acl'] = [ 'abstract' => false, 'aggregates' => [], ]; } } $this->server->emit( 'getSupportedPrivilegeSet', [$node, &$supportedPrivileges] ); return $supportedPrivileges; }
[ "public", "function", "getSupportedPrivilegeSet", "(", "$", "node", ")", "{", "if", "(", "is_string", "(", "$", "node", ")", ")", "{", "$", "node", "=", "$", "this", "->", "server", "->", "tree", "->", "getNodeForPath", "(", "$", "node", ")", ";", "}...
Returns a tree of supported privileges for a resource. The returned array structure should be in this form: [ [ 'privilege' => '{DAV:}read', 'abstract' => false, 'aggregates' => [] ] ] Privileges can be nested using "aggregates". Doing so means that if you assign someone the aggregating privilege, all the sub-privileges will automatically be granted. Marking a privilege as abstract means that the privilege cannot be directly assigned, but must be assigned via the parent privilege. So a more complex version might look like this: [ [ 'privilege' => '{DAV:}read', 'abstract' => false, 'aggregates' => [ [ 'privilege' => '{DAV:}read-acl', 'abstract' => false, 'aggregates' => [], ] ] ] ] @param string|INode $node @return array
[ "Returns", "a", "tree", "of", "supported", "privileges", "for", "a", "resource", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L434-L503
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.getFlatPrivilegeSet
final public function getFlatPrivilegeSet($node) { $privs = [ 'abstract' => false, 'aggregates' => $this->getSupportedPrivilegeSet($node), ]; $fpsTraverse = null; $fpsTraverse = function ($privName, $privInfo, $concrete, &$flat) use (&$fpsTraverse) { $myPriv = [ 'privilege' => $privName, 'abstract' => isset($privInfo['abstract']) && $privInfo['abstract'], 'aggregates' => [], 'concrete' => isset($privInfo['abstract']) && $privInfo['abstract'] ? $concrete : $privName, ]; if (isset($privInfo['aggregates'])) { foreach ($privInfo['aggregates'] as $subPrivName => $subPrivInfo) { $myPriv['aggregates'][] = $subPrivName; } } $flat[$privName] = $myPriv; if (isset($privInfo['aggregates'])) { foreach ($privInfo['aggregates'] as $subPrivName => $subPrivInfo) { $fpsTraverse($subPrivName, $subPrivInfo, $myPriv['concrete'], $flat); } } }; $flat = []; $fpsTraverse('{DAV:}all', $privs, null, $flat); return $flat; }
php
final public function getFlatPrivilegeSet($node) { $privs = [ 'abstract' => false, 'aggregates' => $this->getSupportedPrivilegeSet($node), ]; $fpsTraverse = null; $fpsTraverse = function ($privName, $privInfo, $concrete, &$flat) use (&$fpsTraverse) { $myPriv = [ 'privilege' => $privName, 'abstract' => isset($privInfo['abstract']) && $privInfo['abstract'], 'aggregates' => [], 'concrete' => isset($privInfo['abstract']) && $privInfo['abstract'] ? $concrete : $privName, ]; if (isset($privInfo['aggregates'])) { foreach ($privInfo['aggregates'] as $subPrivName => $subPrivInfo) { $myPriv['aggregates'][] = $subPrivName; } } $flat[$privName] = $myPriv; if (isset($privInfo['aggregates'])) { foreach ($privInfo['aggregates'] as $subPrivName => $subPrivInfo) { $fpsTraverse($subPrivName, $subPrivInfo, $myPriv['concrete'], $flat); } } }; $flat = []; $fpsTraverse('{DAV:}all', $privs, null, $flat); return $flat; }
[ "final", "public", "function", "getFlatPrivilegeSet", "(", "$", "node", ")", "{", "$", "privs", "=", "[", "'abstract'", "=>", "false", ",", "'aggregates'", "=>", "$", "this", "->", "getSupportedPrivilegeSet", "(", "$", "node", ")", ",", "]", ";", "$", "f...
Returns the supported privilege set as a flat list. This is much easier to parse. The returned list will be index by privilege name. The value is a struct containing the following properties: - aggregates - abstract - concrete @param string|INode $node @return array
[ "Returns", "the", "supported", "privilege", "set", "as", "a", "flat", "list", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L520-L555
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.getAcl
public function getAcl($node) { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } if (!$node instanceof IACL) { return $this->getDefaultAcl(); } $acl = $node->getACL(); foreach ($this->adminPrincipals as $adminPrincipal) { $acl[] = [ 'principal' => $adminPrincipal, 'privilege' => '{DAV:}all', 'protected' => true, ]; } return $acl; }
php
public function getAcl($node) { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } if (!$node instanceof IACL) { return $this->getDefaultAcl(); } $acl = $node->getACL(); foreach ($this->adminPrincipals as $adminPrincipal) { $acl[] = [ 'principal' => $adminPrincipal, 'privilege' => '{DAV:}all', 'protected' => true, ]; } return $acl; }
[ "public", "function", "getAcl", "(", "$", "node", ")", "{", "if", "(", "is_string", "(", "$", "node", ")", ")", "{", "$", "node", "=", "$", "this", "->", "server", "->", "tree", "->", "getNodeForPath", "(", "$", "node", ")", ";", "}", "if", "(", ...
Returns the full ACL list. Either a uri or a INode may be passed. null will be returned if the node doesn't support ACLs. @param string|DAV\INode $node @return array
[ "Returns", "the", "full", "ACL", "list", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L568-L586
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.getCurrentUserPrivilegeSet
public function getCurrentUserPrivilegeSet($node) { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } $acl = $this->getACL($node); $collected = []; $isAuthenticated = null !== $this->getCurrentUserPrincipal(); foreach ($acl as $ace) { $principal = $ace['principal']; switch ($principal) { case '{DAV:}owner': $owner = $node->getOwner(); if ($owner && $this->principalMatchesPrincipal($owner)) { $collected[] = $ace; } break; // 'all' matches for every user case '{DAV:}all': $collected[] = $ace; break; case '{DAV:}authenticated': // Authenticated users only if ($isAuthenticated) { $collected[] = $ace; } break; case '{DAV:}unauthenticated': // Unauthenticated users only if (!$isAuthenticated) { $collected[] = $ace; } break; default: if ($this->principalMatchesPrincipal($ace['principal'])) { $collected[] = $ace; } break; } } // Now we deduct all aggregated privileges. $flat = $this->getFlatPrivilegeSet($node); $collected2 = []; while (count($collected)) { $current = array_pop($collected); $collected2[] = $current['privilege']; if (!isset($flat[$current['privilege']])) { // Ignoring privileges that are not in the supported-privileges list. $this->server->getLogger()->debug('A node has the "'.$current['privilege'].'" in its ACL list, but this privilege was not reported in the supportedPrivilegeSet list. This will be ignored.'); continue; } foreach ($flat[$current['privilege']]['aggregates'] as $subPriv) { $collected2[] = $subPriv; $collected[] = $flat[$subPriv]; } } return array_values(array_unique($collected2)); }
php
public function getCurrentUserPrivilegeSet($node) { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } $acl = $this->getACL($node); $collected = []; $isAuthenticated = null !== $this->getCurrentUserPrincipal(); foreach ($acl as $ace) { $principal = $ace['principal']; switch ($principal) { case '{DAV:}owner': $owner = $node->getOwner(); if ($owner && $this->principalMatchesPrincipal($owner)) { $collected[] = $ace; } break; // 'all' matches for every user case '{DAV:}all': $collected[] = $ace; break; case '{DAV:}authenticated': // Authenticated users only if ($isAuthenticated) { $collected[] = $ace; } break; case '{DAV:}unauthenticated': // Unauthenticated users only if (!$isAuthenticated) { $collected[] = $ace; } break; default: if ($this->principalMatchesPrincipal($ace['principal'])) { $collected[] = $ace; } break; } } // Now we deduct all aggregated privileges. $flat = $this->getFlatPrivilegeSet($node); $collected2 = []; while (count($collected)) { $current = array_pop($collected); $collected2[] = $current['privilege']; if (!isset($flat[$current['privilege']])) { // Ignoring privileges that are not in the supported-privileges list. $this->server->getLogger()->debug('A node has the "'.$current['privilege'].'" in its ACL list, but this privilege was not reported in the supportedPrivilegeSet list. This will be ignored.'); continue; } foreach ($flat[$current['privilege']]['aggregates'] as $subPriv) { $collected2[] = $subPriv; $collected[] = $flat[$subPriv]; } } return array_values(array_unique($collected2)); }
[ "public", "function", "getCurrentUserPrivilegeSet", "(", "$", "node", ")", "{", "if", "(", "is_string", "(", "$", "node", ")", ")", "{", "$", "node", "=", "$", "this", "->", "server", "->", "tree", "->", "getNodeForPath", "(", "$", "node", ")", ";", ...
Returns a list of privileges the current user has on a particular node. Either a uri or a DAV\INode may be passed. null will be returned if the node doesn't support ACLs. @param string|DAV\INode $node @return array
[ "Returns", "a", "list", "of", "privileges", "the", "current", "user", "has", "on", "a", "particular", "node", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L600-L670
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.getPrincipalByUri
public function getPrincipalByUri($uri) { $result = null; $collections = $this->principalCollectionSet; foreach ($collections as $collection) { try { $principalCollection = $this->server->tree->getNodeForPath($collection); } catch (NotFound $e) { // Ignore and move on continue; } if (!$principalCollection instanceof IPrincipalCollection) { // Not a principal collection, we're simply going to ignore // this. continue; } $result = $principalCollection->findByUri($uri); if ($result) { return $result; } } }
php
public function getPrincipalByUri($uri) { $result = null; $collections = $this->principalCollectionSet; foreach ($collections as $collection) { try { $principalCollection = $this->server->tree->getNodeForPath($collection); } catch (NotFound $e) { // Ignore and move on continue; } if (!$principalCollection instanceof IPrincipalCollection) { // Not a principal collection, we're simply going to ignore // this. continue; } $result = $principalCollection->findByUri($uri); if ($result) { return $result; } } }
[ "public", "function", "getPrincipalByUri", "(", "$", "uri", ")", "{", "$", "result", "=", "null", ";", "$", "collections", "=", "$", "this", "->", "principalCollectionSet", ";", "foreach", "(", "$", "collections", "as", "$", "collection", ")", "{", "try", ...
Returns a principal based on its uri. Returns null if the principal could not be found. @param string $uri @return string|null
[ "Returns", "a", "principal", "based", "on", "its", "uri", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L681-L704
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.principalSearch
public function principalSearch(array $searchProperties, array $requestedProperties, $collectionUri = null, $test = 'allof') { if (!is_null($collectionUri)) { $uris = [$collectionUri]; } else { $uris = $this->principalCollectionSet; } $lookupResults = []; foreach ($uris as $uri) { $principalCollection = $this->server->tree->getNodeForPath($uri); if (!$principalCollection instanceof IPrincipalCollection) { // Not a principal collection, we're simply going to ignore // this. continue; } $results = $principalCollection->searchPrincipals($searchProperties, $test); foreach ($results as $result) { $lookupResults[] = rtrim($uri, '/').'/'.$result; } } $matches = []; foreach ($lookupResults as $lookupResult) { list($matches[]) = $this->server->getPropertiesForPath($lookupResult, $requestedProperties, 0); } return $matches; }
php
public function principalSearch(array $searchProperties, array $requestedProperties, $collectionUri = null, $test = 'allof') { if (!is_null($collectionUri)) { $uris = [$collectionUri]; } else { $uris = $this->principalCollectionSet; } $lookupResults = []; foreach ($uris as $uri) { $principalCollection = $this->server->tree->getNodeForPath($uri); if (!$principalCollection instanceof IPrincipalCollection) { // Not a principal collection, we're simply going to ignore // this. continue; } $results = $principalCollection->searchPrincipals($searchProperties, $test); foreach ($results as $result) { $lookupResults[] = rtrim($uri, '/').'/'.$result; } } $matches = []; foreach ($lookupResults as $lookupResult) { list($matches[]) = $this->server->getPropertiesForPath($lookupResult, $requestedProperties, 0); } return $matches; }
[ "public", "function", "principalSearch", "(", "array", "$", "searchProperties", ",", "array", "$", "requestedProperties", ",", "$", "collectionUri", "=", "null", ",", "$", "test", "=", "'allof'", ")", "{", "if", "(", "!", "is_null", "(", "$", "collectionUri"...
Principal property search. This method can search for principals matching certain values in properties. This method will return a list of properties for the matched properties. @param array $searchProperties The properties to search on. This is a key-value list. The keys are property names, and the values the strings to match them on. @param array $requestedProperties this is the list of properties to return for every match @param string $collectionUri the principal collection to search on. If this is ommitted, the standard principal collection-set will be used @param string $test "allof" to use AND to search the properties. 'anyof' for OR. @return array This method returns an array structure similar to Sabre\DAV\Server::getPropertiesForPath. Returned properties are index by a HTTP status code.
[ "Principal", "property", "search", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L730-L760
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.beforeMethod
public function beforeMethod(RequestInterface $request, ResponseInterface $response) { $method = $request->getMethod(); $path = $request->getPath(); $exists = $this->server->tree->nodeExists($path); // If the node doesn't exists, none of these checks apply if (!$exists) { return; } switch ($method) { case 'GET': case 'HEAD': case 'OPTIONS': // For these 3 we only need to know if the node is readable. $this->checkPrivileges($path, '{DAV:}read'); break; case 'PUT': case 'LOCK': // This method requires the write-content priv if the node // already exists, and bind on the parent if the node is being // created. // The bind privilege is handled in the beforeBind event. $this->checkPrivileges($path, '{DAV:}write-content'); break; case 'UNLOCK': // Unlock is always allowed at the moment. break; case 'PROPPATCH': $this->checkPrivileges($path, '{DAV:}write-properties'); break; case 'ACL': $this->checkPrivileges($path, '{DAV:}write-acl'); break; case 'COPY': case 'MOVE': // Copy requires read privileges on the entire source tree. // If the target exists write-content normally needs to be // checked, however, we're deleting the node beforehand and // creating a new one after, so this is handled by the // beforeUnbind event. // // The creation of the new node is handled by the beforeBind // event. // // If MOVE is used beforeUnbind will also be used to check if // the sourcenode can be deleted. $this->checkPrivileges($path, '{DAV:}read', self::R_RECURSIVE); break; } }
php
public function beforeMethod(RequestInterface $request, ResponseInterface $response) { $method = $request->getMethod(); $path = $request->getPath(); $exists = $this->server->tree->nodeExists($path); // If the node doesn't exists, none of these checks apply if (!$exists) { return; } switch ($method) { case 'GET': case 'HEAD': case 'OPTIONS': // For these 3 we only need to know if the node is readable. $this->checkPrivileges($path, '{DAV:}read'); break; case 'PUT': case 'LOCK': // This method requires the write-content priv if the node // already exists, and bind on the parent if the node is being // created. // The bind privilege is handled in the beforeBind event. $this->checkPrivileges($path, '{DAV:}write-content'); break; case 'UNLOCK': // Unlock is always allowed at the moment. break; case 'PROPPATCH': $this->checkPrivileges($path, '{DAV:}write-properties'); break; case 'ACL': $this->checkPrivileges($path, '{DAV:}write-acl'); break; case 'COPY': case 'MOVE': // Copy requires read privileges on the entire source tree. // If the target exists write-content normally needs to be // checked, however, we're deleting the node beforehand and // creating a new one after, so this is handled by the // beforeUnbind event. // // The creation of the new node is handled by the beforeBind // event. // // If MOVE is used beforeUnbind will also be used to check if // the sourcenode can be deleted. $this->checkPrivileges($path, '{DAV:}read', self::R_RECURSIVE); break; } }
[ "public", "function", "beforeMethod", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "method", "=", "$", "request", "->", "getMethod", "(", ")", ";", "$", "path", "=", "$", "request", "->", "getPath", "("...
Triggered before any method is handled. @param RequestInterface $request @param ResponseInterface $response
[ "Triggered", "before", "any", "method", "is", "handled", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L836-L893
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.beforeBind
public function beforeBind($uri) { list($parentUri) = Uri\split($uri); $this->checkPrivileges($parentUri, '{DAV:}bind'); }
php
public function beforeBind($uri) { list($parentUri) = Uri\split($uri); $this->checkPrivileges($parentUri, '{DAV:}bind'); }
[ "public", "function", "beforeBind", "(", "$", "uri", ")", "{", "list", "(", "$", "parentUri", ")", "=", "Uri", "\\", "split", "(", "$", "uri", ")", ";", "$", "this", "->", "checkPrivileges", "(", "$", "parentUri", ",", "'{DAV:}bind'", ")", ";", "}" ]
Triggered before a new node is created. This allows us to check permissions for any operation that creates a new node, such as PUT, MKCOL, MKCALENDAR, LOCK, COPY and MOVE. @param string $uri
[ "Triggered", "before", "a", "new", "node", "is", "created", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L903-L907
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.beforeUnbind
public function beforeUnbind($uri) { list($parentUri) = Uri\split($uri); $this->checkPrivileges($parentUri, '{DAV:}unbind', self::R_RECURSIVEPARENTS); }
php
public function beforeUnbind($uri) { list($parentUri) = Uri\split($uri); $this->checkPrivileges($parentUri, '{DAV:}unbind', self::R_RECURSIVEPARENTS); }
[ "public", "function", "beforeUnbind", "(", "$", "uri", ")", "{", "list", "(", "$", "parentUri", ")", "=", "Uri", "\\", "split", "(", "$", "uri", ")", ";", "$", "this", "->", "checkPrivileges", "(", "$", "parentUri", ",", "'{DAV:}unbind'", ",", "self", ...
Triggered before a node is deleted. This allows us to check permissions for any operation that will delete an existing node. @param string $uri
[ "Triggered", "before", "a", "node", "is", "deleted", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L917-L921
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.propPatch
public function propPatch($path, DAV\PropPatch $propPatch) { $propPatch->handle('{DAV:}group-member-set', function ($value) use ($path) { if (is_null($value)) { $memberSet = []; } elseif ($value instanceof Href) { $memberSet = array_map( [$this->server, 'calculateUri'], $value->getHrefs() ); } else { throw new DAV\Exception('The group-member-set property MUST be an instance of Sabre\DAV\Property\HrefList or null'); } $node = $this->server->tree->getNodeForPath($path); if (!($node instanceof IPrincipal)) { // Fail return false; } $node->setGroupMemberSet($memberSet); // We must also clear our cache, just in case $this->principalMembershipCache = []; return true; }); }
php
public function propPatch($path, DAV\PropPatch $propPatch) { $propPatch->handle('{DAV:}group-member-set', function ($value) use ($path) { if (is_null($value)) { $memberSet = []; } elseif ($value instanceof Href) { $memberSet = array_map( [$this->server, 'calculateUri'], $value->getHrefs() ); } else { throw new DAV\Exception('The group-member-set property MUST be an instance of Sabre\DAV\Property\HrefList or null'); } $node = $this->server->tree->getNodeForPath($path); if (!($node instanceof IPrincipal)) { // Fail return false; } $node->setGroupMemberSet($memberSet); // We must also clear our cache, just in case $this->principalMembershipCache = []; return true; }); }
[ "public", "function", "propPatch", "(", "$", "path", ",", "DAV", "\\", "PropPatch", "$", "propPatch", ")", "{", "$", "propPatch", "->", "handle", "(", "'{DAV:}group-member-set'", ",", "function", "(", "$", "value", ")", "use", "(", "$", "path", ")", "{",...
This method intercepts PROPPATCH methods and make sure the group-member-set is updated correctly. @param string $path @param DAV\PropPatch $propPatch
[ "This", "method", "intercepts", "PROPPATCH", "methods", "and", "make", "sure", "the", "group", "-", "member", "-", "set", "is", "updated", "correctly", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L1050-L1076
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.report
public function report($reportName, $report, $path) { switch ($reportName) { case '{DAV:}principal-property-search': $this->server->transactionType = 'report-principal-property-search'; $this->principalPropertySearchReport($path, $report); return false; case '{DAV:}principal-search-property-set': $this->server->transactionType = 'report-principal-search-property-set'; $this->principalSearchPropertySetReport($path, $report); return false; case '{DAV:}expand-property': $this->server->transactionType = 'report-expand-property'; $this->expandPropertyReport($path, $report); return false; case '{DAV:}principal-match': $this->server->transactionType = 'report-principal-match'; $this->principalMatchReport($path, $report); return false; case '{DAV:}acl-principal-prop-set': $this->server->transactionType = 'acl-principal-prop-set'; $this->aclPrincipalPropSetReport($path, $report); return false; } }
php
public function report($reportName, $report, $path) { switch ($reportName) { case '{DAV:}principal-property-search': $this->server->transactionType = 'report-principal-property-search'; $this->principalPropertySearchReport($path, $report); return false; case '{DAV:}principal-search-property-set': $this->server->transactionType = 'report-principal-search-property-set'; $this->principalSearchPropertySetReport($path, $report); return false; case '{DAV:}expand-property': $this->server->transactionType = 'report-expand-property'; $this->expandPropertyReport($path, $report); return false; case '{DAV:}principal-match': $this->server->transactionType = 'report-principal-match'; $this->principalMatchReport($path, $report); return false; case '{DAV:}acl-principal-prop-set': $this->server->transactionType = 'acl-principal-prop-set'; $this->aclPrincipalPropSetReport($path, $report); return false; } }
[ "public", "function", "report", "(", "$", "reportName", ",", "$", "report", ",", "$", "path", ")", "{", "switch", "(", "$", "reportName", ")", "{", "case", "'{DAV:}principal-property-search'", ":", "$", "this", "->", "server", "->", "transactionType", "=", ...
This method handles HTTP REPORT requests. @param string $reportName @param mixed $report @param mixed $path @return bool
[ "This", "method", "handles", "HTTP", "REPORT", "requests", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L1087-L1116
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.principalMatchReport
protected function principalMatchReport($path, Xml\Request\PrincipalMatchReport $report) { $depth = $this->server->getHTTPDepth(0); if (0 !== $depth) { throw new BadRequest('The principal-match report is only defined on Depth: 0'); } $currentPrincipals = $this->getCurrentUserPrincipals(); $result = []; if (Xml\Request\PrincipalMatchReport::SELF === $report->type) { // Finding all principals under the request uri that match the // current principal. foreach ($currentPrincipals as $currentPrincipal) { if ($currentPrincipal === $path || 0 === strpos($currentPrincipal, $path.'/')) { $result[] = $currentPrincipal; } } } else { // We need to find all resources that have a property that matches // one of the current principals. $candidates = $this->server->getPropertiesForPath( $path, [$report->principalProperty], 1 ); foreach ($candidates as $candidate) { if (!isset($candidate[200][$report->principalProperty])) { continue; } $hrefs = $candidate[200][$report->principalProperty]; if (!$hrefs instanceof Href) { continue; } foreach ($hrefs->getHrefs() as $href) { if (in_array(trim($href, '/'), $currentPrincipals)) { $result[] = $candidate['href']; continue 2; } } } } $responses = []; foreach ($result as $item) { $properties = []; if ($report->properties) { $foo = $this->server->getPropertiesForPath($item, $report->properties); $foo = $foo[0]; $item = $foo['href']; unset($foo['href']); $properties = $foo; } $responses[] = new DAV\Xml\Element\Response( $item, $properties, '200' ); } $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setBody( $this->server->xml->write( '{DAV:}multistatus', $responses, $this->server->getBaseUri() ) ); }
php
protected function principalMatchReport($path, Xml\Request\PrincipalMatchReport $report) { $depth = $this->server->getHTTPDepth(0); if (0 !== $depth) { throw new BadRequest('The principal-match report is only defined on Depth: 0'); } $currentPrincipals = $this->getCurrentUserPrincipals(); $result = []; if (Xml\Request\PrincipalMatchReport::SELF === $report->type) { // Finding all principals under the request uri that match the // current principal. foreach ($currentPrincipals as $currentPrincipal) { if ($currentPrincipal === $path || 0 === strpos($currentPrincipal, $path.'/')) { $result[] = $currentPrincipal; } } } else { // We need to find all resources that have a property that matches // one of the current principals. $candidates = $this->server->getPropertiesForPath( $path, [$report->principalProperty], 1 ); foreach ($candidates as $candidate) { if (!isset($candidate[200][$report->principalProperty])) { continue; } $hrefs = $candidate[200][$report->principalProperty]; if (!$hrefs instanceof Href) { continue; } foreach ($hrefs->getHrefs() as $href) { if (in_array(trim($href, '/'), $currentPrincipals)) { $result[] = $candidate['href']; continue 2; } } } } $responses = []; foreach ($result as $item) { $properties = []; if ($report->properties) { $foo = $this->server->getPropertiesForPath($item, $report->properties); $foo = $foo[0]; $item = $foo['href']; unset($foo['href']); $properties = $foo; } $responses[] = new DAV\Xml\Element\Response( $item, $properties, '200' ); } $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setBody( $this->server->xml->write( '{DAV:}multistatus', $responses, $this->server->getBaseUri() ) ); }
[ "protected", "function", "principalMatchReport", "(", "$", "path", ",", "Xml", "\\", "Request", "\\", "PrincipalMatchReport", "$", "report", ")", "{", "$", "depth", "=", "$", "this", "->", "server", "->", "getHTTPDepth", "(", "0", ")", ";", "if", "(", "0...
The principal-match report is defined in RFC3744, section 9.3. This report allows a client to figure out based on the current user, or a principal URL, the principal URL and principal URLs of groups that principal belongs to. @param string $path @param Xml\Request\PrincipalMatchReport $report
[ "The", "principal", "-", "match", "report", "is", "defined", "in", "RFC3744", "section", "9", ".", "3", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L1217-L1294
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.expandPropertyReport
protected function expandPropertyReport($path, $report) { $depth = $this->server->getHTTPDepth(0); $result = $this->expandProperties($path, $report->properties, $depth); $xml = $this->server->xml->write( '{DAV:}multistatus', new DAV\Xml\Response\MultiStatus($result), $this->server->getBaseUri() ); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setBody($xml); }
php
protected function expandPropertyReport($path, $report) { $depth = $this->server->getHTTPDepth(0); $result = $this->expandProperties($path, $report->properties, $depth); $xml = $this->server->xml->write( '{DAV:}multistatus', new DAV\Xml\Response\MultiStatus($result), $this->server->getBaseUri() ); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setBody($xml); }
[ "protected", "function", "expandPropertyReport", "(", "$", "path", ",", "$", "report", ")", "{", "$", "depth", "=", "$", "this", "->", "server", "->", "getHTTPDepth", "(", "0", ")", ";", "$", "result", "=", "$", "this", "->", "expandProperties", "(", "...
The expand-property report is defined in RFC3253 section 3.8. This report is very similar to a standard PROPFIND. The difference is that it has the additional ability to look at properties containing a {DAV:}href element, follow that property and grab additional elements there. Other rfc's, such as ACL rely on this report, so it made sense to put it in this plugin. @param string $path @param Xml\Request\ExpandPropertyReport $report
[ "The", "expand", "-", "property", "report", "is", "defined", "in", "RFC3253", "section", "3", ".", "8", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L1310-L1324
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.expandProperties
protected function expandProperties($path, array $requestedProperties, $depth) { $foundProperties = $this->server->getPropertiesForPath($path, array_keys($requestedProperties), $depth); $result = []; foreach ($foundProperties as $node) { foreach ($requestedProperties as $propertyName => $childRequestedProperties) { // We're only traversing if sub-properties were requested if (!is_array($childRequestedProperties) || 0 === count($childRequestedProperties)) { continue; } // We only have to do the expansion if the property was found // and it contains an href element. if (!array_key_exists($propertyName, $node[200])) { continue; } if (!$node[200][$propertyName] instanceof DAV\Xml\Property\Href) { continue; } $childHrefs = $node[200][$propertyName]->getHrefs(); $childProps = []; foreach ($childHrefs as $href) { // Gathering the result of the children $childProps[] = [ 'name' => '{DAV:}response', 'value' => $this->expandProperties($href, $childRequestedProperties, 0)[0], ]; } // Replacing the property with its expanded form. $node[200][$propertyName] = $childProps; } $result[] = new DAV\Xml\Element\Response($node['href'], $node); } return $result; }
php
protected function expandProperties($path, array $requestedProperties, $depth) { $foundProperties = $this->server->getPropertiesForPath($path, array_keys($requestedProperties), $depth); $result = []; foreach ($foundProperties as $node) { foreach ($requestedProperties as $propertyName => $childRequestedProperties) { // We're only traversing if sub-properties were requested if (!is_array($childRequestedProperties) || 0 === count($childRequestedProperties)) { continue; } // We only have to do the expansion if the property was found // and it contains an href element. if (!array_key_exists($propertyName, $node[200])) { continue; } if (!$node[200][$propertyName] instanceof DAV\Xml\Property\Href) { continue; } $childHrefs = $node[200][$propertyName]->getHrefs(); $childProps = []; foreach ($childHrefs as $href) { // Gathering the result of the children $childProps[] = [ 'name' => '{DAV:}response', 'value' => $this->expandProperties($href, $childRequestedProperties, 0)[0], ]; } // Replacing the property with its expanded form. $node[200][$propertyName] = $childProps; } $result[] = new DAV\Xml\Element\Response($node['href'], $node); } return $result; }
[ "protected", "function", "expandProperties", "(", "$", "path", ",", "array", "$", "requestedProperties", ",", "$", "depth", ")", "{", "$", "foundProperties", "=", "$", "this", "->", "server", "->", "getPropertiesForPath", "(", "$", "path", ",", "array_keys", ...
This method expands all the properties and returns a list with property values. @param array $path @param array $requestedProperties the list of required properties @param int $depth @return array
[ "This", "method", "expands", "all", "the", "properties", "and", "returns", "a", "list", "with", "property", "values", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L1336-L1377
train
sabre-io/dav
lib/DAVACL/Plugin.php
Plugin.aclPrincipalPropSetReport
protected function aclPrincipalPropSetReport($path, Xml\Request\AclPrincipalPropSetReport $report) { if (0 !== $this->server->getHTTPDepth(0)) { throw new BadRequest('The {DAV:}acl-principal-prop-set REPORT only supports Depth 0'); } // Fetching ACL rules for the given path. We're using the property // API and not the local getACL, because it will ensure that all // business rules and restrictions are applied. $acl = $this->server->getProperties($path, '{DAV:}acl'); if (!$acl || !isset($acl['{DAV:}acl'])) { throw new Forbidden('Could not fetch ACL rules for this path'); } $principals = []; foreach ($acl['{DAV:}acl']->getPrivileges() as $ace) { if ('{' === $ace['principal'][0]) { // It's not a principal, it's one of the special rules such as {DAV:}authenticated continue; } $principals[] = $ace['principal']; } $properties = $this->server->getPropertiesForMultiplePaths( $principals, $report->properties ); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setBody( $this->server->generateMultiStatus($properties) ); }
php
protected function aclPrincipalPropSetReport($path, Xml\Request\AclPrincipalPropSetReport $report) { if (0 !== $this->server->getHTTPDepth(0)) { throw new BadRequest('The {DAV:}acl-principal-prop-set REPORT only supports Depth 0'); } // Fetching ACL rules for the given path. We're using the property // API and not the local getACL, because it will ensure that all // business rules and restrictions are applied. $acl = $this->server->getProperties($path, '{DAV:}acl'); if (!$acl || !isset($acl['{DAV:}acl'])) { throw new Forbidden('Could not fetch ACL rules for this path'); } $principals = []; foreach ($acl['{DAV:}acl']->getPrivileges() as $ace) { if ('{' === $ace['principal'][0]) { // It's not a principal, it's one of the special rules such as {DAV:}authenticated continue; } $principals[] = $ace['principal']; } $properties = $this->server->getPropertiesForMultiplePaths( $principals, $report->properties ); $this->server->httpResponse->setStatus(207); $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->setBody( $this->server->generateMultiStatus($properties) ); }
[ "protected", "function", "aclPrincipalPropSetReport", "(", "$", "path", ",", "Xml", "\\", "Request", "\\", "AclPrincipalPropSetReport", "$", "report", ")", "{", "if", "(", "0", "!==", "$", "this", "->", "server", "->", "getHTTPDepth", "(", "0", ")", ")", "...
aclPrincipalPropSet REPORT. This method is responsible for handling the {DAV:}acl-principal-prop-set REPORT, as defined in: https://tools.ietf.org/html/rfc3744#section-9.2 This REPORT allows a user to quickly fetch information about all principals specified in the access control list. Most commonly this is used to for example generate a UI with ACL rules, allowing you to show names for principals for every entry. @param string $path @param Xml\Request\AclPrincipalPropSetReport $report
[ "aclPrincipalPropSet", "REPORT", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAVACL/Plugin.php#L1479-L1514
train
sabre-io/dav
lib/DAV/Exception/MethodNotAllowed.php
MethodNotAllowed.getHTTPHeaders
public function getHTTPHeaders(\Sabre\DAV\Server $server) { $methods = $server->getAllowedMethods($server->getRequestUri()); return [ 'Allow' => strtoupper(implode(', ', $methods)), ]; }
php
public function getHTTPHeaders(\Sabre\DAV\Server $server) { $methods = $server->getAllowedMethods($server->getRequestUri()); return [ 'Allow' => strtoupper(implode(', ', $methods)), ]; }
[ "public", "function", "getHTTPHeaders", "(", "\\", "Sabre", "\\", "DAV", "\\", "Server", "$", "server", ")", "{", "$", "methods", "=", "$", "server", "->", "getAllowedMethods", "(", "$", "server", "->", "getRequestUri", "(", ")", ")", ";", "return", "[",...
This method allows the exception to return any extra HTTP response headers. The headers must be returned as an array. @param \Sabre\DAV\Server $server @return array
[ "This", "method", "allows", "the", "exception", "to", "return", "any", "extra", "HTTP", "response", "headers", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Exception/MethodNotAllowed.php#L39-L46
train
sabre-io/dav
lib/DAV/PropertyStorage/Plugin.php
Plugin.propFind
public function propFind(PropFind $propFind, INode $node) { $path = $propFind->getPath(); $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($path)) { return; } $this->backend->propFind($propFind->getPath(), $propFind); }
php
public function propFind(PropFind $propFind, INode $node) { $path = $propFind->getPath(); $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($path)) { return; } $this->backend->propFind($propFind->getPath(), $propFind); }
[ "public", "function", "propFind", "(", "PropFind", "$", "propFind", ",", "INode", "$", "node", ")", "{", "$", "path", "=", "$", "propFind", "->", "getPath", "(", ")", ";", "$", "pathFilter", "=", "$", "this", "->", "pathFilter", ";", "if", "(", "$", ...
Called during PROPFIND operations. If there's any requested properties that don't have a value yet, this plugin will look in the property storage backend to find them. @param PropFind $propFind @param INode $node
[ "Called", "during", "PROPFIND", "operations", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropertyStorage/Plugin.php#L84-L92
train
sabre-io/dav
lib/DAV/PropertyStorage/Plugin.php
Plugin.propPatch
public function propPatch($path, PropPatch $propPatch) { $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($path)) { return; } $this->backend->propPatch($path, $propPatch); }
php
public function propPatch($path, PropPatch $propPatch) { $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($path)) { return; } $this->backend->propPatch($path, $propPatch); }
[ "public", "function", "propPatch", "(", "$", "path", ",", "PropPatch", "$", "propPatch", ")", "{", "$", "pathFilter", "=", "$", "this", "->", "pathFilter", ";", "if", "(", "$", "pathFilter", "&&", "!", "$", "pathFilter", "(", "$", "path", ")", ")", "...
Called during PROPPATCH operations. If there's any updated properties that haven't been stored, the propertystorage backend can handle it. @param string $path @param PropPatch $propPatch
[ "Called", "during", "PROPPATCH", "operations", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropertyStorage/Plugin.php#L103-L110
train
sabre-io/dav
lib/DAV/PropertyStorage/Plugin.php
Plugin.afterUnbind
public function afterUnbind($path) { $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($path)) { return; } $this->backend->delete($path); }
php
public function afterUnbind($path) { $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($path)) { return; } $this->backend->delete($path); }
[ "public", "function", "afterUnbind", "(", "$", "path", ")", "{", "$", "pathFilter", "=", "$", "this", "->", "pathFilter", ";", "if", "(", "$", "pathFilter", "&&", "!", "$", "pathFilter", "(", "$", "path", ")", ")", "{", "return", ";", "}", "$", "th...
Called after a node is deleted. This allows the backend to clean up any properties still in the database. @param string $path
[ "Called", "after", "a", "node", "is", "deleted", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropertyStorage/Plugin.php#L120-L127
train
sabre-io/dav
lib/DAV/PropertyStorage/Plugin.php
Plugin.afterMove
public function afterMove($source, $destination) { $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($source)) { return; } // If the destination is filtered, afterUnbind will handle cleaning up // the properties. if ($pathFilter && !$pathFilter($destination)) { return; } $this->backend->move($source, $destination); }
php
public function afterMove($source, $destination) { $pathFilter = $this->pathFilter; if ($pathFilter && !$pathFilter($source)) { return; } // If the destination is filtered, afterUnbind will handle cleaning up // the properties. if ($pathFilter && !$pathFilter($destination)) { return; } $this->backend->move($source, $destination); }
[ "public", "function", "afterMove", "(", "$", "source", ",", "$", "destination", ")", "{", "$", "pathFilter", "=", "$", "this", "->", "pathFilter", ";", "if", "(", "$", "pathFilter", "&&", "!", "$", "pathFilter", "(", "$", "source", ")", ")", "{", "re...
Called after a node is moved. This allows the backend to move all the associated properties. @param string $source @param string $destination
[ "Called", "after", "a", "node", "is", "moved", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropertyStorage/Plugin.php#L137-L150
train
sabre-io/dav
lib/CalDAV/Calendar.php
Calendar.getProperties
public function getProperties($requestedProperties) { $response = []; foreach ($this->calendarInfo as $propName => $propValue) { if (!is_null($propValue) && '{' === $propName[0]) { $response[$propName] = $this->calendarInfo[$propName]; } } return $response; }
php
public function getProperties($requestedProperties) { $response = []; foreach ($this->calendarInfo as $propName => $propValue) { if (!is_null($propValue) && '{' === $propName[0]) { $response[$propName] = $this->calendarInfo[$propName]; } } return $response; }
[ "public", "function", "getProperties", "(", "$", "requestedProperties", ")", "{", "$", "response", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "calendarInfo", "as", "$", "propName", "=>", "$", "propValue", ")", "{", "if", "(", "!", "is_null", ...
Returns the list of properties. @param array $requestedProperties @return array
[ "Returns", "the", "list", "of", "properties", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Calendar.php#L84-L95
train
sabre-io/dav
lib/CalDAV/Calendar.php
Calendar.getChild
public function getChild($name) { $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name); if (!$obj) { throw new DAV\Exception\NotFound('Calendar object not found'); } $obj['acl'] = $this->getChildACL(); return new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj); }
php
public function getChild($name) { $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name); if (!$obj) { throw new DAV\Exception\NotFound('Calendar object not found'); } $obj['acl'] = $this->getChildACL(); return new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj); }
[ "public", "function", "getChild", "(", "$", "name", ")", "{", "$", "obj", "=", "$", "this", "->", "caldavBackend", "->", "getCalendarObject", "(", "$", "this", "->", "calendarInfo", "[", "'id'", "]", ",", "$", "name", ")", ";", "if", "(", "!", "$", ...
Returns a calendar object. The contained calendar objects are for example Events or Todo's. @param string $name @return \Sabre\CalDAV\ICalendarObject
[ "Returns", "a", "calendar", "object", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Calendar.php#L106-L116
train
sabre-io/dav
lib/CalDAV/Calendar.php
Calendar.getChildren
public function getChildren() { $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); $children = []; foreach ($objs as $obj) { $obj['acl'] = $this->getChildACL(); $children[] = new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj); } return $children; }
php
public function getChildren() { $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); $children = []; foreach ($objs as $obj) { $obj['acl'] = $this->getChildACL(); $children[] = new CalendarObject($this->caldavBackend, $this->calendarInfo, $obj); } return $children; }
[ "public", "function", "getChildren", "(", ")", "{", "$", "objs", "=", "$", "this", "->", "caldavBackend", "->", "getCalendarObjects", "(", "$", "this", "->", "calendarInfo", "[", "'id'", "]", ")", ";", "$", "children", "=", "[", "]", ";", "foreach", "(...
Returns the full list of calendar objects. @return array
[ "Returns", "the", "full", "list", "of", "calendar", "objects", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Calendar.php#L123-L133
train
sabre-io/dav
lib/CalDAV/Calendar.php
Calendar.childExists
public function childExists($name) { $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name); if (!$obj) { return false; } else { return true; } }
php
public function childExists($name) { $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name); if (!$obj) { return false; } else { return true; } }
[ "public", "function", "childExists", "(", "$", "name", ")", "{", "$", "obj", "=", "$", "this", "->", "caldavBackend", "->", "getCalendarObject", "(", "$", "this", "->", "calendarInfo", "[", "'id'", "]", ",", "$", "name", ")", ";", "if", "(", "!", "$"...
Checks if a child-node exists. @param string $name @return bool
[ "Checks", "if", "a", "child", "-", "node", "exists", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Calendar.php#L164-L172
train
sabre-io/dav
lib/DAV/Auth/Backend/IMAP.php
IMAP.imapOpen
protected function imapOpen($username, $password) { $success = false; try { $imap = imap_open($this->mailbox, $username, $password, OP_HALFOPEN | OP_READONLY, 1); if ($imap) { $success = true; } } catch (\ErrorException $e) { error_log($e->getMessage()); } $errors = imap_errors(); if ($errors) { foreach ($errors as $error) { error_log($error); } } if (isset($imap) && $imap) { imap_close($imap); } return $success; }
php
protected function imapOpen($username, $password) { $success = false; try { $imap = imap_open($this->mailbox, $username, $password, OP_HALFOPEN | OP_READONLY, 1); if ($imap) { $success = true; } } catch (\ErrorException $e) { error_log($e->getMessage()); } $errors = imap_errors(); if ($errors) { foreach ($errors as $error) { error_log($error); } } if (isset($imap) && $imap) { imap_close($imap); } return $success; }
[ "protected", "function", "imapOpen", "(", "$", "username", ",", "$", "password", ")", "{", "$", "success", "=", "false", ";", "try", "{", "$", "imap", "=", "imap_open", "(", "$", "this", "->", "mailbox", ",", "$", "username", ",", "$", "password", ",...
Connects to an IMAP server and tries to authenticate. @param string $username @param string $password @return bool
[ "Connects", "to", "an", "IMAP", "server", "and", "tries", "to", "authenticate", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/Auth/Backend/IMAP.php#L43-L68
train
sabre-io/dav
lib/DAV/UUIDUtil.php
UUIDUtil.getUUID
public static function getUUID() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" mt_rand(0, 0xffff), mt_rand(0, 0xffff), // 16 bits for "time_mid" mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); }
php
public static function getUUID() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" mt_rand(0, 0xffff), mt_rand(0, 0xffff), // 16 bits for "time_mid" mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); }
[ "public", "static", "function", "getUUID", "(", ")", "{", "return", "sprintf", "(", "'%04x%04x-%04x-%04x-%04x-%04x%04x%04x'", ",", "// 32 bits for \"time_low\"", "mt_rand", "(", "0", ",", "0xffff", ")", ",", "mt_rand", "(", "0", ",", "0xffff", ")", ",", "// 16 b...
Returns a pseudo-random v4 UUID. This function is based on a comment by Andrew Moore on php.net @see http://www.php.net/manual/en/function.uniqid.php#94959 @return string
[ "Returns", "a", "pseudo", "-", "random", "v4", "UUID", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/UUIDUtil.php#L29-L50
train
sabre-io/dav
lib/CardDAV/VCFExportPlugin.php
VCFExportPlugin.initialize
public function initialize(DAV\Server $server) { $this->server = $server; $this->server->on('method:GET', [$this, 'httpGet'], 90); $server->on('browserButtonActions', function ($path, $node, &$actions) { if ($node instanceof IAddressBook) { $actions .= '<a href="'.htmlspecialchars($path, ENT_QUOTES, 'UTF-8').'?export"><span class="oi" data-glyph="book"></span></a>'; } }); }
php
public function initialize(DAV\Server $server) { $this->server = $server; $this->server->on('method:GET', [$this, 'httpGet'], 90); $server->on('browserButtonActions', function ($path, $node, &$actions) { if ($node instanceof IAddressBook) { $actions .= '<a href="'.htmlspecialchars($path, ENT_QUOTES, 'UTF-8').'?export"><span class="oi" data-glyph="book"></span></a>'; } }); }
[ "public", "function", "initialize", "(", "DAV", "\\", "Server", "$", "server", ")", "{", "$", "this", "->", "server", "=", "$", "server", ";", "$", "this", "->", "server", "->", "on", "(", "'method:GET'", ",", "[", "$", "this", ",", "'httpGet'", "]",...
Initializes the plugin and registers event handlers. @param DAV\Server $server
[ "Initializes", "the", "plugin", "and", "registers", "event", "handlers", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/VCFExportPlugin.php#L38-L47
train
sabre-io/dav
lib/CardDAV/VCFExportPlugin.php
VCFExportPlugin.httpGet
public function httpGet(RequestInterface $request, ResponseInterface $response) { $queryParams = $request->getQueryParameters(); if (!array_key_exists('export', $queryParams)) { return; } $path = $request->getPath(); $node = $this->server->tree->getNodeForPath($path); if (!($node instanceof IAddressBook)) { return; } $this->server->transactionType = 'get-addressbook-export'; // Checking ACL, if available. if ($aclPlugin = $this->server->getPlugin('acl')) { $aclPlugin->checkPrivileges($path, '{DAV:}read'); } $nodes = $this->server->getPropertiesForPath($path, [ '{'.Plugin::NS_CARDDAV.'}address-data', ], 1); $format = 'text/directory'; $output = null; $filenameExtension = null; switch ($format) { case 'text/directory': $output = $this->generateVCF($nodes); $filenameExtension = '.vcf'; break; } $filename = preg_replace( '/[^a-zA-Z0-9-_ ]/um', '', $node->getName() ); $filename .= '-'.date('Y-m-d').$filenameExtension; $response->setHeader('Content-Disposition', 'attachment; filename="'.$filename.'"'); $response->setHeader('Content-Type', $format); $response->setStatus(200); $response->setBody($output); // Returning false to break the event chain return false; }
php
public function httpGet(RequestInterface $request, ResponseInterface $response) { $queryParams = $request->getQueryParameters(); if (!array_key_exists('export', $queryParams)) { return; } $path = $request->getPath(); $node = $this->server->tree->getNodeForPath($path); if (!($node instanceof IAddressBook)) { return; } $this->server->transactionType = 'get-addressbook-export'; // Checking ACL, if available. if ($aclPlugin = $this->server->getPlugin('acl')) { $aclPlugin->checkPrivileges($path, '{DAV:}read'); } $nodes = $this->server->getPropertiesForPath($path, [ '{'.Plugin::NS_CARDDAV.'}address-data', ], 1); $format = 'text/directory'; $output = null; $filenameExtension = null; switch ($format) { case 'text/directory': $output = $this->generateVCF($nodes); $filenameExtension = '.vcf'; break; } $filename = preg_replace( '/[^a-zA-Z0-9-_ ]/um', '', $node->getName() ); $filename .= '-'.date('Y-m-d').$filenameExtension; $response->setHeader('Content-Disposition', 'attachment; filename="'.$filename.'"'); $response->setHeader('Content-Type', $format); $response->setStatus(200); $response->setBody($output); // Returning false to break the event chain return false; }
[ "public", "function", "httpGet", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "queryParams", "=", "$", "request", "->", "getQueryParameters", "(", ")", ";", "if", "(", "!", "array_key_exists", "(", "'export...
Intercepts GET requests on addressbook urls ending with ?export. @param RequestInterface $request @param ResponseInterface $response @return bool
[ "Intercepts", "GET", "requests", "on", "addressbook", "urls", "ending", "with", "?export", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/VCFExportPlugin.php#L57-L110
train
sabre-io/dav
lib/CardDAV/VCFExportPlugin.php
VCFExportPlugin.generateVCF
public function generateVCF(array $nodes) { $output = ''; foreach ($nodes as $node) { if (!isset($node[200]['{'.Plugin::NS_CARDDAV.'}address-data'])) { continue; } $nodeData = $node[200]['{'.Plugin::NS_CARDDAV.'}address-data']; // Parsing this node so VObject can clean up the output. $vcard = VObject\Reader::read($nodeData); $output .= $vcard->serialize(); // Destroy circular references to PHP will GC the object. $vcard->destroy(); } return $output; }
php
public function generateVCF(array $nodes) { $output = ''; foreach ($nodes as $node) { if (!isset($node[200]['{'.Plugin::NS_CARDDAV.'}address-data'])) { continue; } $nodeData = $node[200]['{'.Plugin::NS_CARDDAV.'}address-data']; // Parsing this node so VObject can clean up the output. $vcard = VObject\Reader::read($nodeData); $output .= $vcard->serialize(); // Destroy circular references to PHP will GC the object. $vcard->destroy(); } return $output; }
[ "public", "function", "generateVCF", "(", "array", "$", "nodes", ")", "{", "$", "output", "=", "''", ";", "foreach", "(", "$", "nodes", "as", "$", "node", ")", "{", "if", "(", "!", "isset", "(", "$", "node", "[", "200", "]", "[", "'{'", ".", "P...
Merges all vcard objects, and builds one big vcf export. @param array $nodes @return string
[ "Merges", "all", "vcard", "objects", "and", "builds", "one", "big", "vcf", "export", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CardDAV/VCFExportPlugin.php#L119-L138
train
sabre-io/dav
lib/CalDAV/Subscriptions/Plugin.php
Plugin.propFind
public function propFind(PropFind $propFind, INode $node) { // There's a bunch of properties that must appear as a self-closing // xml-element. This event handler ensures that this will be the case. $props = [ '{http://calendarserver.org/ns/}subscribed-strip-alarms', '{http://calendarserver.org/ns/}subscribed-strip-attachments', '{http://calendarserver.org/ns/}subscribed-strip-todos', ]; foreach ($props as $prop) { if (200 === $propFind->getStatus($prop)) { $propFind->set($prop, '', 200); } } }
php
public function propFind(PropFind $propFind, INode $node) { // There's a bunch of properties that must appear as a self-closing // xml-element. This event handler ensures that this will be the case. $props = [ '{http://calendarserver.org/ns/}subscribed-strip-alarms', '{http://calendarserver.org/ns/}subscribed-strip-attachments', '{http://calendarserver.org/ns/}subscribed-strip-todos', ]; foreach ($props as $prop) { if (200 === $propFind->getStatus($prop)) { $propFind->set($prop, '', 200); } } }
[ "public", "function", "propFind", "(", "PropFind", "$", "propFind", ",", "INode", "$", "node", ")", "{", "// There's a bunch of properties that must appear as a self-closing", "// xml-element. This event handler ensures that this will be the case.", "$", "props", "=", "[", "'{h...
Triggered after properties have been fetched. @param PropFind $propFind @param INode $node
[ "Triggered", "after", "properties", "have", "been", "fetched", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Subscriptions/Plugin.php#L64-L79
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.httpPost
public function httpPost(RequestInterface $request, ResponseInterface $response) { // Checking if this is a text/calendar content type $contentType = $request->getHeader('Content-Type'); if (!$contentType || 0 !== strpos($contentType, 'text/calendar')) { return; } $path = $request->getPath(); // Checking if we're talking to an outbox try { $node = $this->server->tree->getNodeForPath($path); } catch (NotFound $e) { return; } if (!$node instanceof IOutbox) { return; } $this->server->transactionType = 'post-caldav-outbox'; $this->outboxRequest($node, $request, $response); // Returning false breaks the event chain and tells the server we've // handled the request. return false; }
php
public function httpPost(RequestInterface $request, ResponseInterface $response) { // Checking if this is a text/calendar content type $contentType = $request->getHeader('Content-Type'); if (!$contentType || 0 !== strpos($contentType, 'text/calendar')) { return; } $path = $request->getPath(); // Checking if we're talking to an outbox try { $node = $this->server->tree->getNodeForPath($path); } catch (NotFound $e) { return; } if (!$node instanceof IOutbox) { return; } $this->server->transactionType = 'post-caldav-outbox'; $this->outboxRequest($node, $request, $response); // Returning false breaks the event chain and tells the server we've // handled the request. return false; }
[ "public", "function", "httpPost", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "// Checking if this is a text/calendar content type", "$", "contentType", "=", "$", "request", "->", "getHeader", "(", "'Content-Type'", ")",...
This method handles POST request for the outbox. @param RequestInterface $request @param ResponseInterface $response @return bool
[ "This", "method", "handles", "POST", "request", "for", "the", "outbox", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L166-L192
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.calendarObjectChange
public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) { if (!$this->scheduleReply($this->server->httpRequest)) { return; } $calendarNode = $this->server->tree->getNodeForPath($calendarPath); $addresses = $this->getAddressesForPrincipal( $calendarNode->getOwner() ); if (!$isNew) { $node = $this->server->tree->getNodeForPath($request->getPath()); $oldObj = Reader::read($node->get()); } else { $oldObj = null; } $this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified); if ($oldObj) { // Destroy circular references so PHP will GC the object. $oldObj->destroy(); } }
php
public function calendarObjectChange(RequestInterface $request, ResponseInterface $response, VCalendar $vCal, $calendarPath, &$modified, $isNew) { if (!$this->scheduleReply($this->server->httpRequest)) { return; } $calendarNode = $this->server->tree->getNodeForPath($calendarPath); $addresses = $this->getAddressesForPrincipal( $calendarNode->getOwner() ); if (!$isNew) { $node = $this->server->tree->getNodeForPath($request->getPath()); $oldObj = Reader::read($node->get()); } else { $oldObj = null; } $this->processICalendarChange($oldObj, $vCal, $addresses, [], $modified); if ($oldObj) { // Destroy circular references so PHP will GC the object. $oldObj->destroy(); } }
[ "public", "function", "calendarObjectChange", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ",", "VCalendar", "$", "vCal", ",", "$", "calendarPath", ",", "&", "$", "modified", ",", "$", "isNew", ")", "{", "if", "(", "!",...
This method is triggered whenever there was a calendar object gets created or updated. @param RequestInterface $request HTTP request @param ResponseInterface $response HTTP Response @param VCalendar $vCal Parsed iCalendar object @param mixed $calendarPath Path to calendar collection @param mixed $modified the iCalendar object has been touched @param mixed $isNew Whether this was a new item or we're updating one
[ "This", "method", "is", "triggered", "whenever", "there", "was", "a", "calendar", "object", "gets", "created", "or", "updated", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L327-L352
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.deliver
public function deliver(ITip\Message $iTipMessage) { $this->server->emit('schedule', [$iTipMessage]); if (!$iTipMessage->scheduleStatus) { $iTipMessage->scheduleStatus = '5.2;There was no system capable of delivering the scheduling message'; } // In case the change was considered 'insignificant', we are going to // remove any error statuses, if any. See ticket #525. list($baseCode) = explode('.', $iTipMessage->scheduleStatus); if (!$iTipMessage->significantChange && in_array($baseCode, ['3', '5'])) { $iTipMessage->scheduleStatus = null; } }
php
public function deliver(ITip\Message $iTipMessage) { $this->server->emit('schedule', [$iTipMessage]); if (!$iTipMessage->scheduleStatus) { $iTipMessage->scheduleStatus = '5.2;There was no system capable of delivering the scheduling message'; } // In case the change was considered 'insignificant', we are going to // remove any error statuses, if any. See ticket #525. list($baseCode) = explode('.', $iTipMessage->scheduleStatus); if (!$iTipMessage->significantChange && in_array($baseCode, ['3', '5'])) { $iTipMessage->scheduleStatus = null; } }
[ "public", "function", "deliver", "(", "ITip", "\\", "Message", "$", "iTipMessage", ")", "{", "$", "this", "->", "server", "->", "emit", "(", "'schedule'", ",", "[", "$", "iTipMessage", "]", ")", ";", "if", "(", "!", "$", "iTipMessage", "->", "scheduleS...
This method is responsible for delivering the ITip message. @param ITip\Message $iTipMessage
[ "This", "method", "is", "responsible", "for", "delivering", "the", "ITip", "message", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L359-L371
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.beforeUnbind
public function beforeUnbind($path) { // FIXME: We shouldn't trigger this functionality when we're issuing a // MOVE. This is a hack. if ('MOVE' === $this->server->httpRequest->getMethod()) { return; } $node = $this->server->tree->getNodeForPath($path); if (!$node instanceof ICalendarObject || $node instanceof ISchedulingObject) { return; } if (!$this->scheduleReply($this->server->httpRequest)) { return; } $addresses = $this->getAddressesForPrincipal( $node->getOwner() ); $broker = new ITip\Broker(); $messages = $broker->parseEvent(null, $addresses, $node->get()); foreach ($messages as $message) { $this->deliver($message); } }
php
public function beforeUnbind($path) { // FIXME: We shouldn't trigger this functionality when we're issuing a // MOVE. This is a hack. if ('MOVE' === $this->server->httpRequest->getMethod()) { return; } $node = $this->server->tree->getNodeForPath($path); if (!$node instanceof ICalendarObject || $node instanceof ISchedulingObject) { return; } if (!$this->scheduleReply($this->server->httpRequest)) { return; } $addresses = $this->getAddressesForPrincipal( $node->getOwner() ); $broker = new ITip\Broker(); $messages = $broker->parseEvent(null, $addresses, $node->get()); foreach ($messages as $message) { $this->deliver($message); } }
[ "public", "function", "beforeUnbind", "(", "$", "path", ")", "{", "// FIXME: We shouldn't trigger this functionality when we're issuing a", "// MOVE. This is a hack.", "if", "(", "'MOVE'", "===", "$", "this", "->", "server", "->", "httpRequest", "->", "getMethod", "(", ...
This method is triggered before a file gets deleted. We use this event to make sure that when this happens, attendees get cancellations, and organizers get 'DECLINED' statuses. @param string $path
[ "This", "method", "is", "triggered", "before", "a", "file", "gets", "deleted", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L381-L409
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.getSupportedPrivilegeSet
public function getSupportedPrivilegeSet(INode $node, array &$supportedPrivilegeSet) { $ns = '{'.self::NS_CALDAV.'}'; if ($node instanceof IOutbox) { $supportedPrivilegeSet[$ns.'schedule-send'] = [ 'abstract' => false, 'aggregates' => [ $ns.'schedule-send-invite' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-send-reply' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-send-freebusy' => [ 'abstract' => false, 'aggregates' => [], ], // Privilege from an earlier scheduling draft, but still // used by some clients. $ns.'schedule-post-vevent' => [ 'abstract' => false, 'aggregates' => [], ], ], ]; } if ($node instanceof IInbox) { $supportedPrivilegeSet[$ns.'schedule-deliver'] = [ 'abstract' => false, 'aggregates' => [ $ns.'schedule-deliver-invite' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-deliver-reply' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-query-freebusy' => [ 'abstract' => false, 'aggregates' => [], ], ], ]; } }
php
public function getSupportedPrivilegeSet(INode $node, array &$supportedPrivilegeSet) { $ns = '{'.self::NS_CALDAV.'}'; if ($node instanceof IOutbox) { $supportedPrivilegeSet[$ns.'schedule-send'] = [ 'abstract' => false, 'aggregates' => [ $ns.'schedule-send-invite' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-send-reply' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-send-freebusy' => [ 'abstract' => false, 'aggregates' => [], ], // Privilege from an earlier scheduling draft, but still // used by some clients. $ns.'schedule-post-vevent' => [ 'abstract' => false, 'aggregates' => [], ], ], ]; } if ($node instanceof IInbox) { $supportedPrivilegeSet[$ns.'schedule-deliver'] = [ 'abstract' => false, 'aggregates' => [ $ns.'schedule-deliver-invite' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-deliver-reply' => [ 'abstract' => false, 'aggregates' => [], ], $ns.'schedule-query-freebusy' => [ 'abstract' => false, 'aggregates' => [], ], ], ]; } }
[ "public", "function", "getSupportedPrivilegeSet", "(", "INode", "$", "node", ",", "array", "&", "$", "supportedPrivilegeSet", ")", "{", "$", "ns", "=", "'{'", ".", "self", "::", "NS_CALDAV", ".", "'}'", ";", "if", "(", "$", "node", "instanceof", "IOutbox",...
This method is triggered whenever a subsystem requests the privileges that are supported on a particular node. We need to add a number of privileges for scheduling purposes. @param INode $node @param array $supportedPrivilegeSet
[ "This", "method", "is", "triggered", "whenever", "a", "subsystem", "requests", "the", "privileges", "that", "are", "supported", "on", "a", "particular", "node", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L564-L611
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.processICalendarChange
protected function processICalendarChange($oldObject = null, VCalendar $newObject, array $addresses, array $ignore = [], &$modified = false) { $broker = new ITip\Broker(); $messages = $broker->parseEvent($newObject, $addresses, $oldObject); if ($messages) { $modified = true; } foreach ($messages as $message) { if (in_array($message->recipient, $ignore)) { continue; } $this->deliver($message); if (isset($newObject->VEVENT->ORGANIZER) && ($newObject->VEVENT->ORGANIZER->getNormalizedValue() === $message->recipient)) { if ($message->scheduleStatus) { $newObject->VEVENT->ORGANIZER['SCHEDULE-STATUS'] = $message->getScheduleStatus(); } unset($newObject->VEVENT->ORGANIZER['SCHEDULE-FORCE-SEND']); } else { if (isset($newObject->VEVENT->ATTENDEE)) { foreach ($newObject->VEVENT->ATTENDEE as $attendee) { if ($attendee->getNormalizedValue() === $message->recipient) { if ($message->scheduleStatus) { $attendee['SCHEDULE-STATUS'] = $message->getScheduleStatus(); } unset($attendee['SCHEDULE-FORCE-SEND']); break; } } } } } }
php
protected function processICalendarChange($oldObject = null, VCalendar $newObject, array $addresses, array $ignore = [], &$modified = false) { $broker = new ITip\Broker(); $messages = $broker->parseEvent($newObject, $addresses, $oldObject); if ($messages) { $modified = true; } foreach ($messages as $message) { if (in_array($message->recipient, $ignore)) { continue; } $this->deliver($message); if (isset($newObject->VEVENT->ORGANIZER) && ($newObject->VEVENT->ORGANIZER->getNormalizedValue() === $message->recipient)) { if ($message->scheduleStatus) { $newObject->VEVENT->ORGANIZER['SCHEDULE-STATUS'] = $message->getScheduleStatus(); } unset($newObject->VEVENT->ORGANIZER['SCHEDULE-FORCE-SEND']); } else { if (isset($newObject->VEVENT->ATTENDEE)) { foreach ($newObject->VEVENT->ATTENDEE as $attendee) { if ($attendee->getNormalizedValue() === $message->recipient) { if ($message->scheduleStatus) { $attendee['SCHEDULE-STATUS'] = $message->getScheduleStatus(); } unset($attendee['SCHEDULE-FORCE-SEND']); break; } } } } } }
[ "protected", "function", "processICalendarChange", "(", "$", "oldObject", "=", "null", ",", "VCalendar", "$", "newObject", ",", "array", "$", "addresses", ",", "array", "$", "ignore", "=", "[", "]", ",", "&", "$", "modified", "=", "false", ")", "{", "$",...
This method looks at an old iCalendar object, a new iCalendar object and starts sending scheduling messages based on the changes. A list of addresses needs to be specified, so the system knows who made the update, because the behavior may be different based on if it's an attendee or an organizer. This method may update $newObject to add any status changes. @param VCalendar|string $oldObject @param VCalendar $newObject @param array $addresses @param array $ignore any addresses to not send messages to @param bool $modified a marker to indicate that the original object modified by this process
[ "This", "method", "looks", "at", "an", "old", "iCalendar", "object", "a", "new", "iCalendar", "object", "and", "starts", "sending", "scheduling", "messages", "based", "on", "the", "changes", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L630-L665
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.getAddressesForPrincipal
protected function getAddressesForPrincipal($principal) { $CUAS = '{'.self::NS_CALDAV.'}calendar-user-address-set'; $properties = $this->server->getProperties( $principal, [$CUAS] ); // If we can't find this information, we'll stop processing if (!isset($properties[$CUAS])) { return []; } $addresses = $properties[$CUAS]->getHrefs(); return $addresses; }
php
protected function getAddressesForPrincipal($principal) { $CUAS = '{'.self::NS_CALDAV.'}calendar-user-address-set'; $properties = $this->server->getProperties( $principal, [$CUAS] ); // If we can't find this information, we'll stop processing if (!isset($properties[$CUAS])) { return []; } $addresses = $properties[$CUAS]->getHrefs(); return $addresses; }
[ "protected", "function", "getAddressesForPrincipal", "(", "$", "principal", ")", "{", "$", "CUAS", "=", "'{'", ".", "self", "::", "NS_CALDAV", ".", "'}calendar-user-address-set'", ";", "$", "properties", "=", "$", "this", "->", "server", "->", "getProperties", ...
Returns a list of addresses that are associated with a principal. @param string $principal @return array
[ "Returns", "a", "list", "of", "addresses", "that", "are", "associated", "with", "a", "principal", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L674-L691
train
sabre-io/dav
lib/CalDAV/Schedule/Plugin.php
Plugin.outboxRequest
public function outboxRequest(IOutbox $outboxNode, RequestInterface $request, ResponseInterface $response) { $outboxPath = $request->getPath(); // Parsing the request body try { $vObject = VObject\Reader::read($request->getBody()); } catch (VObject\ParseException $e) { throw new BadRequest('The request body must be a valid iCalendar object. Parse error: '.$e->getMessage()); } // The incoming iCalendar object must have a METHOD property, and a // component. The combination of both determines what type of request // this is. $componentType = null; foreach ($vObject->getComponents() as $component) { if ('VTIMEZONE' !== $component->name) { $componentType = $component->name; break; } } if (is_null($componentType)) { throw new BadRequest('We expected at least one VTODO, VJOURNAL, VFREEBUSY or VEVENT component'); } // Validating the METHOD $method = strtoupper((string) $vObject->METHOD); if (!$method) { throw new BadRequest('A METHOD property must be specified in iTIP messages'); } // So we support one type of request: // // REQUEST with a VFREEBUSY component $acl = $this->server->getPlugin('acl'); if ('VFREEBUSY' === $componentType && 'REQUEST' === $method) { $acl && $acl->checkPrivileges($outboxPath, '{'.self::NS_CALDAV.'}schedule-send-freebusy'); $this->handleFreeBusyRequest($outboxNode, $vObject, $request, $response); // Destroy circular references so PHP can GC the object. $vObject->destroy(); unset($vObject); } else { throw new NotImplemented('We only support VFREEBUSY (REQUEST) on this endpoint'); } }
php
public function outboxRequest(IOutbox $outboxNode, RequestInterface $request, ResponseInterface $response) { $outboxPath = $request->getPath(); // Parsing the request body try { $vObject = VObject\Reader::read($request->getBody()); } catch (VObject\ParseException $e) { throw new BadRequest('The request body must be a valid iCalendar object. Parse error: '.$e->getMessage()); } // The incoming iCalendar object must have a METHOD property, and a // component. The combination of both determines what type of request // this is. $componentType = null; foreach ($vObject->getComponents() as $component) { if ('VTIMEZONE' !== $component->name) { $componentType = $component->name; break; } } if (is_null($componentType)) { throw new BadRequest('We expected at least one VTODO, VJOURNAL, VFREEBUSY or VEVENT component'); } // Validating the METHOD $method = strtoupper((string) $vObject->METHOD); if (!$method) { throw new BadRequest('A METHOD property must be specified in iTIP messages'); } // So we support one type of request: // // REQUEST with a VFREEBUSY component $acl = $this->server->getPlugin('acl'); if ('VFREEBUSY' === $componentType && 'REQUEST' === $method) { $acl && $acl->checkPrivileges($outboxPath, '{'.self::NS_CALDAV.'}schedule-send-freebusy'); $this->handleFreeBusyRequest($outboxNode, $vObject, $request, $response); // Destroy circular references so PHP can GC the object. $vObject->destroy(); unset($vObject); } else { throw new NotImplemented('We only support VFREEBUSY (REQUEST) on this endpoint'); } }
[ "public", "function", "outboxRequest", "(", "IOutbox", "$", "outboxNode", ",", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "outboxPath", "=", "$", "request", "->", "getPath", "(", ")", ";", "// Parsing the reques...
This method handles POST requests to the schedule-outbox. Currently, two types of requests are supported: * FREEBUSY requests from RFC 6638 * Simple iTIP messages from draft-desruisseaux-caldav-sched-04 The latter is from an expired early draft of the CalDAV scheduling extensions, but iCal depends on a feature from that spec, so we implement it. @param IOutbox $outboxNode @param RequestInterface $request @param ResponseInterface $response
[ "This", "method", "handles", "POST", "requests", "to", "the", "schedule", "-", "outbox", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/CalDAV/Schedule/Plugin.php#L708-L755
train
sabre-io/dav
lib/DAV/PropFind.php
PropFind.getStatus
public function getStatus($propertyName) { return isset($this->result[$propertyName]) ? $this->result[$propertyName][0] : null; }
php
public function getStatus($propertyName) { return isset($this->result[$propertyName]) ? $this->result[$propertyName][0] : null; }
[ "public", "function", "getStatus", "(", "$", "propertyName", ")", "{", "return", "isset", "(", "$", "this", "->", "result", "[", "$", "propertyName", "]", ")", "?", "$", "this", "->", "result", "[", "$", "propertyName", "]", "[", "0", "]", ":", "null...
Returns the current status code for a property name. If the property does not appear in the list of requested properties, null will be returned. @param string $propertyName @return int|null
[ "Returns", "the", "current", "status", "code", "for", "a", "property", "name", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropFind.php#L161-L164
train
sabre-io/dav
lib/DAV/PropFind.php
PropFind.getResultForMultiStatus
public function getResultForMultiStatus() { $r = [ 200 => [], 404 => [], ]; foreach ($this->result as $propertyName => $info) { if (!isset($r[$info[0]])) { $r[$info[0]] = [$propertyName => $info[1]]; } else { $r[$info[0]][$propertyName] = $info[1]; } } // Removing the 404's for multi-status requests. if (self::ALLPROPS === $this->requestType) { unset($r[404]); } return $r; }
php
public function getResultForMultiStatus() { $r = [ 200 => [], 404 => [], ]; foreach ($this->result as $propertyName => $info) { if (!isset($r[$info[0]])) { $r[$info[0]] = [$propertyName => $info[1]]; } else { $r[$info[0]][$propertyName] = $info[1]; } } // Removing the 404's for multi-status requests. if (self::ALLPROPS === $this->requestType) { unset($r[404]); } return $r; }
[ "public", "function", "getResultForMultiStatus", "(", ")", "{", "$", "r", "=", "[", "200", "=>", "[", "]", ",", "404", "=>", "[", "]", ",", "]", ";", "foreach", "(", "$", "this", "->", "result", "as", "$", "propertyName", "=>", "$", "info", ")", ...
Returns a result array that's often used in multistatus responses. The array uses status codes as keys, and property names and value pairs as the value of the top array.. such as : [ 200 => [ '{DAV:}displayname' => 'foo' ], ] @return array
[ "Returns", "a", "result", "array", "that", "s", "often", "used", "in", "multistatus", "responses", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PropFind.php#L261-L280
train
sabre-io/dav
lib/DAV/PartialUpdate/Plugin.php
Plugin.httpPatch
public function httpPatch(RequestInterface $request, ResponseInterface $response) { $path = $request->getPath(); // Get the node. Will throw a 404 if not found $node = $this->server->tree->getNodeForPath($path); if (!$node instanceof IPatchSupport) { throw new DAV\Exception\MethodNotAllowed('The target resource does not support the PATCH method.'); } $range = $this->getHTTPUpdateRange($request); if (!$range) { throw new DAV\Exception\BadRequest('No valid "X-Update-Range" found in the headers'); } $contentType = strtolower( (string) $request->getHeader('Content-Type') ); if ('application/x-sabredav-partialupdate' != $contentType) { throw new DAV\Exception\UnsupportedMediaType('Unknown Content-Type header "'.$contentType.'"'); } $len = $this->server->httpRequest->getHeader('Content-Length'); if (!$len) { throw new DAV\Exception\LengthRequired('A Content-Length header is required'); } switch ($range[0]) { case self::RANGE_START: // Calculate the end-range if it doesn't exist. if (!$range[2]) { $range[2] = $range[1] + $len - 1; } else { if ($range[2] < $range[1]) { throw new DAV\Exception\RequestedRangeNotSatisfiable('The end offset ('.$range[2].') is lower than the start offset ('.$range[1].')'); } if ($range[2] - $range[1] + 1 != $len) { throw new DAV\Exception\RequestedRangeNotSatisfiable('Actual data length ('.$len.') is not consistent with begin ('.$range[1].') and end ('.$range[2].') offsets'); } } break; } if (!$this->server->emit('beforeWriteContent', [$path, $node, null])) { return; } $body = $this->server->httpRequest->getBody(); $etag = $node->patch($body, $range[0], isset($range[1]) ? $range[1] : null); $this->server->emit('afterWriteContent', [$path, $node]); $response->setHeader('Content-Length', '0'); if ($etag) { $response->setHeader('ETag', $etag); } $response->setStatus(204); // Breaks the event chain return false; }
php
public function httpPatch(RequestInterface $request, ResponseInterface $response) { $path = $request->getPath(); // Get the node. Will throw a 404 if not found $node = $this->server->tree->getNodeForPath($path); if (!$node instanceof IPatchSupport) { throw new DAV\Exception\MethodNotAllowed('The target resource does not support the PATCH method.'); } $range = $this->getHTTPUpdateRange($request); if (!$range) { throw new DAV\Exception\BadRequest('No valid "X-Update-Range" found in the headers'); } $contentType = strtolower( (string) $request->getHeader('Content-Type') ); if ('application/x-sabredav-partialupdate' != $contentType) { throw new DAV\Exception\UnsupportedMediaType('Unknown Content-Type header "'.$contentType.'"'); } $len = $this->server->httpRequest->getHeader('Content-Length'); if (!$len) { throw new DAV\Exception\LengthRequired('A Content-Length header is required'); } switch ($range[0]) { case self::RANGE_START: // Calculate the end-range if it doesn't exist. if (!$range[2]) { $range[2] = $range[1] + $len - 1; } else { if ($range[2] < $range[1]) { throw new DAV\Exception\RequestedRangeNotSatisfiable('The end offset ('.$range[2].') is lower than the start offset ('.$range[1].')'); } if ($range[2] - $range[1] + 1 != $len) { throw new DAV\Exception\RequestedRangeNotSatisfiable('Actual data length ('.$len.') is not consistent with begin ('.$range[1].') and end ('.$range[2].') offsets'); } } break; } if (!$this->server->emit('beforeWriteContent', [$path, $node, null])) { return; } $body = $this->server->httpRequest->getBody(); $etag = $node->patch($body, $range[0], isset($range[1]) ? $range[1] : null); $this->server->emit('afterWriteContent', [$path, $node]); $response->setHeader('Content-Length', '0'); if ($etag) { $response->setHeader('ETag', $etag); } $response->setStatus(204); // Breaks the event chain return false; }
[ "public", "function", "httpPatch", "(", "RequestInterface", "$", "request", ",", "ResponseInterface", "$", "response", ")", "{", "$", "path", "=", "$", "request", "->", "getPath", "(", ")", ";", "// Get the node. Will throw a 404 if not found", "$", "node", "=", ...
Patch an uri. The WebDAV patch request can be used to modify only a part of an existing resource. If the resource does not exist yet and the first offset is not 0, the request fails @param RequestInterface $request @param ResponseInterface $response
[ "Patch", "an", "uri", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PartialUpdate/Plugin.php#L113-L175
train
sabre-io/dav
lib/DAV/PartialUpdate/Plugin.php
Plugin.getHTTPUpdateRange
public function getHTTPUpdateRange(RequestInterface $request) { $range = $request->getHeader('X-Update-Range'); if (is_null($range)) { return null; } // Matching "Range: bytes=1234-5678: both numbers are optional if (!preg_match('/^(append)|(?:bytes=([0-9]+)-([0-9]*))|(?:bytes=(-[0-9]+))$/i', $range, $matches)) { return null; } if ('append' === $matches[1]) { return [self::RANGE_APPEND]; } elseif (strlen($matches[2]) > 0) { return [self::RANGE_START, (int) $matches[2], (int) $matches[3] ?: null]; } else { return [self::RANGE_END, (int) $matches[4]]; } }
php
public function getHTTPUpdateRange(RequestInterface $request) { $range = $request->getHeader('X-Update-Range'); if (is_null($range)) { return null; } // Matching "Range: bytes=1234-5678: both numbers are optional if (!preg_match('/^(append)|(?:bytes=([0-9]+)-([0-9]*))|(?:bytes=(-[0-9]+))$/i', $range, $matches)) { return null; } if ('append' === $matches[1]) { return [self::RANGE_APPEND]; } elseif (strlen($matches[2]) > 0) { return [self::RANGE_START, (int) $matches[2], (int) $matches[3] ?: null]; } else { return [self::RANGE_END, (int) $matches[4]]; } }
[ "public", "function", "getHTTPUpdateRange", "(", "RequestInterface", "$", "request", ")", "{", "$", "range", "=", "$", "request", "->", "getHeader", "(", "'X-Update-Range'", ")", ";", "if", "(", "is_null", "(", "$", "range", ")", ")", "{", "return", "null"...
Returns the HTTP custom range update header. This method returns null if there is no well-formed HTTP range request header. It returns array(1) if it was an append request, array(2, $start, $end) if it's a start and end range, lastly it's array(3, $endoffset) if the offset was negative, and should be calculated from the end of the file. Examples: null - invalid [1] - append [2,10,15] - update bytes 10, 11, 12, 13, 14, 15 [2,10,null] - update bytes 10 until the end of the patch body [3,-5] - update from 5 bytes from the end of the file. @param RequestInterface $request @return array|null
[ "Returns", "the", "HTTP", "custom", "range", "update", "header", "." ]
44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0
https://github.com/sabre-io/dav/blob/44b0f2d07fd9e6e44b65f7edf2238d3bf0b428e0/lib/DAV/PartialUpdate/Plugin.php#L198-L218
train
phpDocumentor/ReflectionDocBlock
src/DocBlock/Description.php
Description.render
public function render(?Formatter $formatter = null): string { if ($formatter === null) { $formatter = new PassthroughFormatter(); } $tags = []; foreach ($this->tags as $tag) { $tags[] = '{' . $formatter->format($tag) . '}'; } return vsprintf($this->bodyTemplate, $tags); }
php
public function render(?Formatter $formatter = null): string { if ($formatter === null) { $formatter = new PassthroughFormatter(); } $tags = []; foreach ($this->tags as $tag) { $tags[] = '{' . $formatter->format($tag) . '}'; } return vsprintf($this->bodyTemplate, $tags); }
[ "public", "function", "render", "(", "?", "Formatter", "$", "formatter", "=", "null", ")", ":", "string", "{", "if", "(", "$", "formatter", "===", "null", ")", "{", "$", "formatter", "=", "new", "PassthroughFormatter", "(", ")", ";", "}", "$", "tags", ...
Renders this description as a string where the provided formatter will format the tags in the expected string format.
[ "Renders", "this", "description", "as", "a", "string", "where", "the", "provided", "formatter", "will", "format", "the", "tags", "in", "the", "expected", "string", "format", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock/Description.php#L84-L96
train
phpDocumentor/ReflectionDocBlock
examples/04-adding-your-own-tag.php
MyTag.create
public static function create(string $body, DescriptionFactory $descriptionFactory = null, Context $context = null): MyTag { Assert::notNull($descriptionFactory); return new static($descriptionFactory->create($body, $context)); }
php
public static function create(string $body, DescriptionFactory $descriptionFactory = null, Context $context = null): MyTag { Assert::notNull($descriptionFactory); return new static($descriptionFactory->create($body, $context)); }
[ "public", "static", "function", "create", "(", "string", "$", "body", ",", "DescriptionFactory", "$", "descriptionFactory", "=", "null", ",", "Context", "$", "context", "=", "null", ")", ":", "MyTag", "{", "Assert", "::", "notNull", "(", "$", "descriptionFac...
A static Factory that creates a new instance of the current Tag. In this example the MyTag tag can be created by passing a description text as $body. Because we have added a $descriptionFactory that is type-hinted as DescriptionFactory we can now construct a new Description object and pass that to the constructor. > You could directly instantiate a Description object here but that won't be parsed for inline tags and Types > won't be resolved. The DescriptionFactory will take care of those actions. The `create` method's interface states that this method only features a single parameter (`$body`) but the {@see TagFactory} will read the signature of this method and if it has more parameters then it will try to find declarations for it in the ServiceLocator of the TagFactory (see {@see TagFactory::$serviceLocator}). > Important: all properties following the `$body` should default to `null`, otherwise PHP will error because > it no longer matches the interface. This is why you often see the default tags check that an optional argument > is not null nonetheless. @param string $body @param DescriptionFactory $descriptionFactory @param Context|null $context The Context is used to resolve Types and FQSENs, although optional it is highly recommended to pass it. If you omit it then it is assumed that the DocBlock is in the global namespace and has no `use` statements. @see Tag for the interface declaration of the `create` method. @see Tag::create() for more information on this method's workings.
[ "A", "static", "Factory", "that", "creates", "a", "new", "instance", "of", "the", "current", "Tag", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/examples/04-adding-your-own-tag.php#L87-L92
train
phpDocumentor/ReflectionDocBlock
src/DocBlock.php
DocBlock.getTagsByName
public function getTagsByName(string $name): array { $result = []; /** @var Tag $tag */ foreach ($this->getTags() as $tag) { if ($tag->getName() !== $name) { continue; } $result[] = $tag; } return $result; }
php
public function getTagsByName(string $name): array { $result = []; /** @var Tag $tag */ foreach ($this->getTags() as $tag) { if ($tag->getName() !== $name) { continue; } $result[] = $tag; } return $result; }
[ "public", "function", "getTagsByName", "(", "string", "$", "name", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "/** @var Tag $tag */", "foreach", "(", "$", "this", "->", "getTags", "(", ")", "as", "$", "tag", ")", "{", "if", "(", "$", ...
Returns an array of tags matching the given name. If no tags are found an empty array is returned. @param string $name String to search by. @return Tag[]
[ "Returns", "an", "array", "of", "tags", "matching", "the", "given", "name", ".", "If", "no", "tags", "are", "found", "an", "empty", "array", "is", "returned", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock.php#L149-L163
train
phpDocumentor/ReflectionDocBlock
src/DocBlock.php
DocBlock.hasTag
public function hasTag(string $name): bool { /** @var Tag $tag */ foreach ($this->getTags() as $tag) { if ($tag->getName() === $name) { return true; } } return false; }
php
public function hasTag(string $name): bool { /** @var Tag $tag */ foreach ($this->getTags() as $tag) { if ($tag->getName() === $name) { return true; } } return false; }
[ "public", "function", "hasTag", "(", "string", "$", "name", ")", ":", "bool", "{", "/** @var Tag $tag */", "foreach", "(", "$", "this", "->", "getTags", "(", ")", "as", "$", "tag", ")", "{", "if", "(", "$", "tag", "->", "getName", "(", ")", "===", ...
Checks if a tag of a certain type is present in this DocBlock. @param string $name Tag name to check for.
[ "Checks", "if", "a", "tag", "of", "a", "certain", "type", "is", "present", "in", "this", "DocBlock", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock.php#L170-L180
train
phpDocumentor/ReflectionDocBlock
src/DocBlock.php
DocBlock.removeTag
public function removeTag(Tag $tagToRemove): void { foreach ($this->tags as $key => $tag) { if ($tag === $tagToRemove) { unset($this->tags[$key]); break; } } }
php
public function removeTag(Tag $tagToRemove): void { foreach ($this->tags as $key => $tag) { if ($tag === $tagToRemove) { unset($this->tags[$key]); break; } } }
[ "public", "function", "removeTag", "(", "Tag", "$", "tagToRemove", ")", ":", "void", "{", "foreach", "(", "$", "this", "->", "tags", "as", "$", "key", "=>", "$", "tag", ")", "{", "if", "(", "$", "tag", "===", "$", "tagToRemove", ")", "{", "unset", ...
Remove a tag from this DocBlock. @param Tag $tagToRemove The tag to remove.
[ "Remove", "a", "tag", "from", "this", "DocBlock", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock.php#L187-L195
train
phpDocumentor/ReflectionDocBlock
src/DocBlock/Tags/Generic.php
Generic.create
public static function create( string $body, string $name = '', ?DescriptionFactory $descriptionFactory = null, ?TypeContext $context = null ): self { Assert::stringNotEmpty($name); Assert::notNull($descriptionFactory); $description = $descriptionFactory && $body !== "" ? $descriptionFactory->create($body, $context) : null; return new static($name, $description); }
php
public static function create( string $body, string $name = '', ?DescriptionFactory $descriptionFactory = null, ?TypeContext $context = null ): self { Assert::stringNotEmpty($name); Assert::notNull($descriptionFactory); $description = $descriptionFactory && $body !== "" ? $descriptionFactory->create($body, $context) : null; return new static($name, $description); }
[ "public", "static", "function", "create", "(", "string", "$", "body", ",", "string", "$", "name", "=", "''", ",", "?", "DescriptionFactory", "$", "descriptionFactory", "=", "null", ",", "?", "TypeContext", "$", "context", "=", "null", ")", ":", "self", "...
Creates a new tag that represents any unknown tag type. @return static
[ "Creates", "a", "new", "tag", "that", "represents", "any", "unknown", "tag", "type", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock/Tags/Generic.php#L47-L59
train
phpDocumentor/ReflectionDocBlock
src/DocBlock/Tags/Generic.php
Generic.validateTagName
private function validateTagName(string $name): void { if (! preg_match('/^' . StandardTagFactory::REGEX_TAGNAME . '$/u', $name)) { throw new \InvalidArgumentException( 'The tag name "' . $name . '" is not wellformed. Tags may only consist of letters, underscores, ' . 'hyphens and backslashes.' ); } }
php
private function validateTagName(string $name): void { if (! preg_match('/^' . StandardTagFactory::REGEX_TAGNAME . '$/u', $name)) { throw new \InvalidArgumentException( 'The tag name "' . $name . '" is not wellformed. Tags may only consist of letters, underscores, ' . 'hyphens and backslashes.' ); } }
[ "private", "function", "validateTagName", "(", "string", "$", "name", ")", ":", "void", "{", "if", "(", "!", "preg_match", "(", "'/^'", ".", "StandardTagFactory", "::", "REGEX_TAGNAME", ".", "'$/u'", ",", "$", "name", ")", ")", "{", "throw", "new", "\\",...
Validates if the tag name matches the expected format, otherwise throws an exception.
[ "Validates", "if", "the", "tag", "name", "matches", "the", "expected", "format", "otherwise", "throws", "an", "exception", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock/Tags/Generic.php#L72-L80
train
phpDocumentor/ReflectionDocBlock
src/DocBlock/DescriptionFactory.php
DescriptionFactory.lex
private function lex(string $contents): array { $contents = $this->removeSuperfluousStartingWhitespace($contents); // performance optimalization; if there is no inline tag, don't bother splitting it up. if (strpos($contents, '{@') === false) { return [$contents]; } return preg_split( '/\{ # "{@}" is not a valid inline tag. This ensures that we do not treat it as one, but treat it literally. (?!@\}) # We want to capture the whole tag line, but without the inline tag delimiters. (\@ # Match everything up to the next delimiter. [^{}]* # Nested inline tag content should not be captured, or it will appear in the result separately. (?: # Match nested inline tags. (?: # Because we did not catch the tag delimiters earlier, we must be explicit with them here. # Notice that this also matches "{}", as a way to later introduce it as an escape sequence. \{(?1)?\} | # Make sure we match hanging "{". \{ ) # Match content after the nested inline tag. [^{}]* )* # If there are more inline tags, match them as well. We use "*" since there may not be any # nested inline tags. ) \}/Sux', $contents, 0, PREG_SPLIT_DELIM_CAPTURE ); }
php
private function lex(string $contents): array { $contents = $this->removeSuperfluousStartingWhitespace($contents); // performance optimalization; if there is no inline tag, don't bother splitting it up. if (strpos($contents, '{@') === false) { return [$contents]; } return preg_split( '/\{ # "{@}" is not a valid inline tag. This ensures that we do not treat it as one, but treat it literally. (?!@\}) # We want to capture the whole tag line, but without the inline tag delimiters. (\@ # Match everything up to the next delimiter. [^{}]* # Nested inline tag content should not be captured, or it will appear in the result separately. (?: # Match nested inline tags. (?: # Because we did not catch the tag delimiters earlier, we must be explicit with them here. # Notice that this also matches "{}", as a way to later introduce it as an escape sequence. \{(?1)?\} | # Make sure we match hanging "{". \{ ) # Match content after the nested inline tag. [^{}]* )* # If there are more inline tags, match them as well. We use "*" since there may not be any # nested inline tags. ) \}/Sux', $contents, 0, PREG_SPLIT_DELIM_CAPTURE ); }
[ "private", "function", "lex", "(", "string", "$", "contents", ")", ":", "array", "{", "$", "contents", "=", "$", "this", "->", "removeSuperfluousStartingWhitespace", "(", "$", "contents", ")", ";", "// performance optimalization; if there is no inline tag, don't bother ...
Strips the contents from superfluous whitespace and splits the description into a series of tokens. @return string[] A series of tokens of which the description text is composed.
[ "Strips", "the", "contents", "from", "superfluous", "whitespace", "and", "splits", "the", "description", "into", "a", "series", "of", "tokens", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock/DescriptionFactory.php#L64-L102
train
phpDocumentor/ReflectionDocBlock
src/DocBlock/DescriptionFactory.php
DescriptionFactory.parse
private function parse($tokens, ?TypeContext $context = null): array { $count = count($tokens); $tagCount = 0; $tags = []; for ($i = 1; $i < $count; $i += 2) { $tags[] = $this->tagFactory->create($tokens[$i], $context); $tokens[$i] = '%' . ++$tagCount . '$s'; } //In order to allow "literal" inline tags, the otherwise invalid //sequence "{@}" is changed to "@", and "{}" is changed to "}". //"%" is escaped to "%%" because of vsprintf. //See unit tests for examples. for ($i = 0; $i < $count; $i += 2) { $tokens[$i] = str_replace(['{@}', '{}', '%'], ['@', '}', '%%'], $tokens[$i]); } return [implode('', $tokens), $tags]; }
php
private function parse($tokens, ?TypeContext $context = null): array { $count = count($tokens); $tagCount = 0; $tags = []; for ($i = 1; $i < $count; $i += 2) { $tags[] = $this->tagFactory->create($tokens[$i], $context); $tokens[$i] = '%' . ++$tagCount . '$s'; } //In order to allow "literal" inline tags, the otherwise invalid //sequence "{@}" is changed to "@", and "{}" is changed to "}". //"%" is escaped to "%%" because of vsprintf. //See unit tests for examples. for ($i = 0; $i < $count; $i += 2) { $tokens[$i] = str_replace(['{@}', '{}', '%'], ['@', '}', '%%'], $tokens[$i]); } return [implode('', $tokens), $tags]; }
[ "private", "function", "parse", "(", "$", "tokens", ",", "?", "TypeContext", "$", "context", "=", "null", ")", ":", "array", "{", "$", "count", "=", "count", "(", "$", "tokens", ")", ";", "$", "tagCount", "=", "0", ";", "$", "tags", "=", "[", "]"...
Parses the stream of tokens in to a new set of tokens containing Tags. @param string[] $tokens @return string[]|Tag[]
[ "Parses", "the", "stream", "of", "tokens", "in", "to", "a", "new", "set", "of", "tokens", "containing", "Tags", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock/DescriptionFactory.php#L111-L131
train
phpDocumentor/ReflectionDocBlock
src/DocBlock/DescriptionFactory.php
DescriptionFactory.removeSuperfluousStartingWhitespace
private function removeSuperfluousStartingWhitespace(string $contents): string { $lines = explode("\n", $contents); // if there is only one line then we don't have lines with superfluous whitespace and // can use the contents as-is if (count($lines) <= 1) { return $contents; } // determine how many whitespace characters need to be stripped $startingSpaceCount = 9999999; for ($i = 1; $i < count($lines); ++$i) { // lines with a no length do not count as they are not indented at all if (strlen(trim($lines[$i])) === 0) { continue; } // determine the number of prefixing spaces by checking the difference in line length before and after // an ltrim $startingSpaceCount = min($startingSpaceCount, strlen($lines[$i]) - strlen(ltrim($lines[$i]))); } // strip the number of spaces from each line if ($startingSpaceCount > 0) { for ($i = 1; $i < count($lines); ++$i) { $lines[$i] = substr($lines[$i], $startingSpaceCount); } } return implode("\n", $lines); }
php
private function removeSuperfluousStartingWhitespace(string $contents): string { $lines = explode("\n", $contents); // if there is only one line then we don't have lines with superfluous whitespace and // can use the contents as-is if (count($lines) <= 1) { return $contents; } // determine how many whitespace characters need to be stripped $startingSpaceCount = 9999999; for ($i = 1; $i < count($lines); ++$i) { // lines with a no length do not count as they are not indented at all if (strlen(trim($lines[$i])) === 0) { continue; } // determine the number of prefixing spaces by checking the difference in line length before and after // an ltrim $startingSpaceCount = min($startingSpaceCount, strlen($lines[$i]) - strlen(ltrim($lines[$i]))); } // strip the number of spaces from each line if ($startingSpaceCount > 0) { for ($i = 1; $i < count($lines); ++$i) { $lines[$i] = substr($lines[$i], $startingSpaceCount); } } return implode("\n", $lines); }
[ "private", "function", "removeSuperfluousStartingWhitespace", "(", "string", "$", "contents", ")", ":", "string", "{", "$", "lines", "=", "explode", "(", "\"\\n\"", ",", "$", "contents", ")", ";", "// if there is only one line then we don't have lines with superfluous whi...
Removes the superfluous from a multi-line description. When a description has more than one line then it can happen that the second and subsequent lines have an additional indentation. This is commonly in use with tags like this: {@}since 1.1.0 This is an example description where we have an indentation in the second and subsequent lines. If we do not normalize the indentation then we have superfluous whitespace on the second and subsequent lines and this may cause rendering issues when, for example, using a Markdown converter.
[ "Removes", "the", "superfluous", "from", "a", "multi", "-", "line", "description", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock/DescriptionFactory.php#L147-L178
train
phpDocumentor/ReflectionDocBlock
src/DocBlockFactory.php
DocBlockFactory.createInstance
public static function createInstance(array $additionalTags = []): self { $fqsenResolver = new FqsenResolver(); $tagFactory = new StandardTagFactory($fqsenResolver); $descriptionFactory = new DescriptionFactory($tagFactory); $tagFactory->addService($descriptionFactory); $tagFactory->addService(new TypeResolver($fqsenResolver)); $docBlockFactory = new self($descriptionFactory, $tagFactory); foreach ($additionalTags as $tagName => $tagHandler) { $docBlockFactory->registerTagHandler($tagName, $tagHandler); } return $docBlockFactory; }
php
public static function createInstance(array $additionalTags = []): self { $fqsenResolver = new FqsenResolver(); $tagFactory = new StandardTagFactory($fqsenResolver); $descriptionFactory = new DescriptionFactory($tagFactory); $tagFactory->addService($descriptionFactory); $tagFactory->addService(new TypeResolver($fqsenResolver)); $docBlockFactory = new self($descriptionFactory, $tagFactory); foreach ($additionalTags as $tagName => $tagHandler) { $docBlockFactory->registerTagHandler($tagName, $tagHandler); } return $docBlockFactory; }
[ "public", "static", "function", "createInstance", "(", "array", "$", "additionalTags", "=", "[", "]", ")", ":", "self", "{", "$", "fqsenResolver", "=", "new", "FqsenResolver", "(", ")", ";", "$", "tagFactory", "=", "new", "StandardTagFactory", "(", "$", "f...
Factory method for easy instantiation. @param string[] $additionalTags
[ "Factory", "method", "for", "easy", "instantiation", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlockFactory.php#L44-L59
train
phpDocumentor/ReflectionDocBlock
src/DocBlockFactory.php
DocBlockFactory.splitDocBlock
private function splitDocBlock(string $comment): array { // Performance improvement cheat: if the first character is an @ then only tags are in this DocBlock. This // method does not split tags so we return this verbatim as the fourth result (tags). This saves us the // performance impact of running a regular expression if (strpos($comment, '@') === 0) { return ['', '', '', $comment]; } // clears all extra horizontal whitespace from the line endings to prevent parsing issues $comment = preg_replace('/\h*$/Sum', '', $comment); /* * Splits the docblock into a template marker, summary, description and tags section. * * - The template marker is empty, #@+ or #@- if the DocBlock starts with either of those (a newline may * occur after it and will be stripped). * - The short description is started from the first character until a dot is encountered followed by a * newline OR two consecutive newlines (horizontal whitespace is taken into account to consider spacing * errors). This is optional. * - The long description, any character until a new line is encountered followed by an @ and word * characters (a tag). This is optional. * - Tags; the remaining characters * * Big thanks to RichardJ for contributing this Regular Expression */ preg_match( '/ \A # 1. Extract the template marker (?:(\#\@\+|\#\@\-)\n?)? # 2. Extract the summary (?: (?! @\pL ) # The summary may not start with an @ ( [^\n.]+ (?: (?! \. \n | \n{2} ) # End summary upon a dot followed by newline or two newlines [\n.]* (?! [ \t]* @\pL ) # End summary when an @ is found as first character on a new line [^\n.]+ # Include anything else )* \.? )? ) # 3. Extract the description (?: \s* # Some form of whitespace _must_ precede a description because a summary must be there (?! @\pL ) # The description may not start with an @ ( [^\n]+ (?: \n+ (?! [ \t]* @\pL ) # End description when an @ is found as first character on a new line [^\n]+ # Include anything else )* ) )? # 4. Extract the tags (anything that follows) (\s+ [\s\S]*)? # everything that follows /ux', $comment, $matches ); array_shift($matches); while (count($matches) < 4) { $matches[] = ''; } return $matches; }
php
private function splitDocBlock(string $comment): array { // Performance improvement cheat: if the first character is an @ then only tags are in this DocBlock. This // method does not split tags so we return this verbatim as the fourth result (tags). This saves us the // performance impact of running a regular expression if (strpos($comment, '@') === 0) { return ['', '', '', $comment]; } // clears all extra horizontal whitespace from the line endings to prevent parsing issues $comment = preg_replace('/\h*$/Sum', '', $comment); /* * Splits the docblock into a template marker, summary, description and tags section. * * - The template marker is empty, #@+ or #@- if the DocBlock starts with either of those (a newline may * occur after it and will be stripped). * - The short description is started from the first character until a dot is encountered followed by a * newline OR two consecutive newlines (horizontal whitespace is taken into account to consider spacing * errors). This is optional. * - The long description, any character until a new line is encountered followed by an @ and word * characters (a tag). This is optional. * - Tags; the remaining characters * * Big thanks to RichardJ for contributing this Regular Expression */ preg_match( '/ \A # 1. Extract the template marker (?:(\#\@\+|\#\@\-)\n?)? # 2. Extract the summary (?: (?! @\pL ) # The summary may not start with an @ ( [^\n.]+ (?: (?! \. \n | \n{2} ) # End summary upon a dot followed by newline or two newlines [\n.]* (?! [ \t]* @\pL ) # End summary when an @ is found as first character on a new line [^\n.]+ # Include anything else )* \.? )? ) # 3. Extract the description (?: \s* # Some form of whitespace _must_ precede a description because a summary must be there (?! @\pL ) # The description may not start with an @ ( [^\n]+ (?: \n+ (?! [ \t]* @\pL ) # End description when an @ is found as first character on a new line [^\n]+ # Include anything else )* ) )? # 4. Extract the tags (anything that follows) (\s+ [\s\S]*)? # everything that follows /ux', $comment, $matches ); array_shift($matches); while (count($matches) < 4) { $matches[] = ''; } return $matches; }
[ "private", "function", "splitDocBlock", "(", "string", "$", "comment", ")", ":", "array", "{", "// Performance improvement cheat: if the first character is an @ then only tags are in this DocBlock. This", "// method does not split tags so we return this verbatim as the fourth result (tags). ...
Splits the DocBlock into a template marker, summary, description and block of tags. @param string $comment Comment to split into the sub-parts. @author Richard van Velzen (@_richardJ) Special thanks to Richard for the regex responsible for the split. @author Mike van Riel <me@mikevanriel.com> for extending the regex with template marker support. @return string[] containing the template marker (if any), summary, description and a string containing the tags.
[ "Splits", "the", "DocBlock", "into", "a", "template", "marker", "summary", "description", "and", "block", "of", "tags", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlockFactory.php#L130-L202
train
phpDocumentor/ReflectionDocBlock
src/DocBlock/Tags/Formatter/AlignFormatter.php
AlignFormatter.format
public function format(Tag $tag): string { return '@' . $tag->getName() . str_repeat(' ', $this->maxLen - strlen($tag->getName()) + 1) . (string) $tag; }
php
public function format(Tag $tag): string { return '@' . $tag->getName() . str_repeat(' ', $this->maxLen - strlen($tag->getName()) + 1) . (string) $tag; }
[ "public", "function", "format", "(", "Tag", "$", "tag", ")", ":", "string", "{", "return", "'@'", ".", "$", "tag", "->", "getName", "(", ")", ".", "str_repeat", "(", "' '", ",", "$", "this", "->", "maxLen", "-", "strlen", "(", "$", "tag", "->", "...
Formats the given tag to return a simple plain text version.
[ "Formats", "the", "given", "tag", "to", "return", "a", "simple", "plain", "text", "version", "." ]
48351665a881883231add24fbb7ef869adca2316
https://github.com/phpDocumentor/ReflectionDocBlock/blob/48351665a881883231add24fbb7ef869adca2316/src/DocBlock/Tags/Formatter/AlignFormatter.php#L40-L43
train
ARCANEDEV/Breadcrumbs
src/Entities/BreadcrumbCollection.php
BreadcrumbCollection.addOne
public function addOne($title, $url, array $data = []) { return $this->addBreadcrumb( BreadcrumbItem::make($title, $url, $data) ); }
php
public function addOne($title, $url, array $data = []) { return $this->addBreadcrumb( BreadcrumbItem::make($title, $url, $data) ); }
[ "public", "function", "addOne", "(", "$", "title", ",", "$", "url", ",", "array", "$", "data", "=", "[", "]", ")", "{", "return", "$", "this", "->", "addBreadcrumb", "(", "BreadcrumbItem", "::", "make", "(", "$", "title", ",", "$", "url", ",", "$",...
Add a breadcrumb item to collection. @param string $title @param string $url @param array $data @return self
[ "Add", "a", "breadcrumb", "item", "to", "collection", "." ]
ce6a8cd4213cef2ebb978fe7d53850e886735a08
https://github.com/ARCANEDEV/Breadcrumbs/blob/ce6a8cd4213cef2ebb978fe7d53850e886735a08/src/Entities/BreadcrumbCollection.php#L27-L32
train
ARCANEDEV/Breadcrumbs
src/Entities/BreadcrumbCollection.php
BreadcrumbCollection.order
private function order() { $count = $this->count(); $this->map(function (BreadcrumbItem $crumb, $key) use ($count) { $crumb->resetPosition(); if ($key === 0) $crumb->setFirst(); if ($key === ($count - 1)) $crumb->setLast(); return $crumb; }); return $this; }
php
private function order() { $count = $this->count(); $this->map(function (BreadcrumbItem $crumb, $key) use ($count) { $crumb->resetPosition(); if ($key === 0) $crumb->setFirst(); if ($key === ($count - 1)) $crumb->setLast(); return $crumb; }); return $this; }
[ "private", "function", "order", "(", ")", "{", "$", "count", "=", "$", "this", "->", "count", "(", ")", ";", "$", "this", "->", "map", "(", "function", "(", "BreadcrumbItem", "$", "crumb", ",", "$", "key", ")", "use", "(", "$", "count", ")", "{",...
Order all breadcrumbs items. @return self
[ "Order", "all", "breadcrumbs", "items", "." ]
ce6a8cd4213cef2ebb978fe7d53850e886735a08
https://github.com/ARCANEDEV/Breadcrumbs/blob/ce6a8cd4213cef2ebb978fe7d53850e886735a08/src/Entities/BreadcrumbCollection.php#L58-L75
train
AlfredoRamos/parsedown-extra-laravel
src/ParsedownExtraLaravel.php
ParsedownExtraLaravel.parse
public function parse($text = '', $options = []) { // Extend default options $options = array_merge([ 'config' => [], 'purifier' => true ], $options); // Parsedown Extra $markdown = parent::text($text); // HTML Purifier if (config('parsedownextra.purifier.enabled') && $options['purifier']) { $purifier = app(HTMLPurifierLaravel::class); // Filter HTML $markdown = $purifier->purify($markdown, $options['config']); } return $markdown; }
php
public function parse($text = '', $options = []) { // Extend default options $options = array_merge([ 'config' => [], 'purifier' => true ], $options); // Parsedown Extra $markdown = parent::text($text); // HTML Purifier if (config('parsedownextra.purifier.enabled') && $options['purifier']) { $purifier = app(HTMLPurifierLaravel::class); // Filter HTML $markdown = $purifier->purify($markdown, $options['config']); } return $markdown; }
[ "public", "function", "parse", "(", "$", "text", "=", "''", ",", "$", "options", "=", "[", "]", ")", "{", "// Extend default options", "$", "options", "=", "array_merge", "(", "[", "'config'", "=>", "[", "]", ",", "'purifier'", "=>", "true", "]", ",", ...
Convert Markdown text to HTML and sanitize the output. @see \Parsedown::parse() @param string $text The Markdown text to convert. @param array $options Options for HTML Purifier. @return string The resulting HTML from the Markdown text conversion.
[ "Convert", "Markdown", "text", "to", "HTML", "and", "sanitize", "the", "output", "." ]
ff2b86306a5e8c5263e941afd4e48311df4f27b2
https://github.com/AlfredoRamos/parsedown-extra-laravel/blob/ff2b86306a5e8c5263e941afd4e48311df4f27b2/src/ParsedownExtraLaravel.php#L27-L46
train
billogram/billogram-v2-api-php-lib
Billogram/Api/Query.php
Query.makeQuery
private function makeQuery($pageNumber = 1) { $params = array( 'page_size' => $this->pageSize, 'page' => $pageNumber ); $params = array_merge($params, $this->filter); $params = array_merge($params, $this->order); $response = $this->api->get($this->typeClass->url(), $params); $this->countCached = $response->meta->total_count; return $response; }
php
private function makeQuery($pageNumber = 1) { $params = array( 'page_size' => $this->pageSize, 'page' => $pageNumber ); $params = array_merge($params, $this->filter); $params = array_merge($params, $this->order); $response = $this->api->get($this->typeClass->url(), $params); $this->countCached = $response->meta->total_count; return $response; }
[ "private", "function", "makeQuery", "(", "$", "pageNumber", "=", "1", ")", "{", "$", "params", "=", "array", "(", "'page_size'", "=>", "$", "this", "->", "pageSize", ",", "'page'", "=>", "$", "pageNumber", ")", ";", "$", "params", "=", "array_merge", "...
Makes a GET request to the API with parameters for page size, page number, filtering and order values. Returns the API response. @param int $pageNumber @return mixed
[ "Makes", "a", "GET", "request", "to", "the", "API", "with", "parameters", "for", "page", "size", "page", "number", "filtering", "and", "order", "values", ".", "Returns", "the", "API", "response", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api/Query.php#L74-L86
train
billogram/billogram-v2-api-php-lib
Billogram/Api/Query.php
Query.count
public function count() { if ($this->countCached === null) { $pageSize = $this->pageSize; $this->pageSize = 1; $this->makeQuery(1); $this->pageSize = $pageSize; } return $this->countCached; }
php
public function count() { if ($this->countCached === null) { $pageSize = $this->pageSize; $this->pageSize = 1; $this->makeQuery(1); $this->pageSize = $pageSize; } return $this->countCached; }
[ "public", "function", "count", "(", ")", "{", "if", "(", "$", "this", "->", "countCached", "===", "null", ")", "{", "$", "pageSize", "=", "$", "this", "->", "pageSize", ";", "$", "this", "->", "pageSize", "=", "1", ";", "$", "this", "->", "makeQuer...
Total amount of objects matched by the current query, reading this may cause a remote request. @return null
[ "Total", "amount", "of", "objects", "matched", "by", "the", "current", "query", "reading", "this", "may", "cause", "a", "remote", "request", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api/Query.php#L124-L134
train
billogram/billogram-v2-api-php-lib
Billogram/Api/Query.php
Query.makeFilter
public function makeFilter( $filterType = null, $filterField = null, $filterValue = null ) { if ($filterType === null && $filterField === null && $filterValue === null) $this->filter = array(); else $this->filter = array( 'filter_type' => $filterType, 'filter_field' => $filterField, 'filter_value' => $filterValue ); return $this; }
php
public function makeFilter( $filterType = null, $filterField = null, $filterValue = null ) { if ($filterType === null && $filterField === null && $filterValue === null) $this->filter = array(); else $this->filter = array( 'filter_type' => $filterType, 'filter_field' => $filterField, 'filter_value' => $filterValue ); return $this; }
[ "public", "function", "makeFilter", "(", "$", "filterType", "=", "null", ",", "$", "filterField", "=", "null", ",", "$", "filterValue", "=", "null", ")", "{", "if", "(", "$", "filterType", "===", "null", "&&", "$", "filterField", "===", "null", "&&", "...
Sets up filtering rules for the query. @param null $filterType @param null $filterField @param null $filterValue @return $this
[ "Sets", "up", "filtering", "rules", "for", "the", "query", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api/Query.php#L155-L172
train
billogram/billogram-v2-api-php-lib
Billogram/Api/Query.php
Query.getPage
public function getPage($pageNumber) { $response = $this->makeQuery($pageNumber); $className = $this->typeClass->objectClass; $objects = array(); if (!isset($response->data) || !$response->data) return array(); foreach ($response->data as $object) { $objects[] = new $className($this->api, $this->typeClass, $object); } return $objects; }
php
public function getPage($pageNumber) { $response = $this->makeQuery($pageNumber); $className = $this->typeClass->objectClass; $objects = array(); if (!isset($response->data) || !$response->data) return array(); foreach ($response->data as $object) { $objects[] = new $className($this->api, $this->typeClass, $object); } return $objects; }
[ "public", "function", "getPage", "(", "$", "pageNumber", ")", "{", "$", "response", "=", "$", "this", "->", "makeQuery", "(", "$", "pageNumber", ")", ";", "$", "className", "=", "$", "this", "->", "typeClass", "->", "objectClass", ";", "$", "objects", ...
Fetch objects for the one-based page number. @param $pageNumber @return array
[ "Fetch", "objects", "for", "the", "one", "-", "based", "page", "number", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api/Query.php#L251-L263
train
phpcr/phpcr-shell
src/PHPCR/Shell/Phpcr/SessionManager.php
SessionManager.initSession
private function initSession() { $transport = $this->transportRegistry->getTransport($this->profile->get('transport', 'name')); $repository = $transport->getRepository($this->profile->get('transport')); $credentials = new SimpleCredentials( $this->profile->get('phpcr', 'username'), $this->profile->get('phpcr', 'password') ); $session = $repository->login($credentials, $this->profile->get('phpcr', 'workspace')); // if you are wondering wtf here -- we wrap the PhpcrSession if (!$this->session) { $this->session = new PhpcrSession($session); } else { $this->session->setPhpcrSession($session); } }
php
private function initSession() { $transport = $this->transportRegistry->getTransport($this->profile->get('transport', 'name')); $repository = $transport->getRepository($this->profile->get('transport')); $credentials = new SimpleCredentials( $this->profile->get('phpcr', 'username'), $this->profile->get('phpcr', 'password') ); $session = $repository->login($credentials, $this->profile->get('phpcr', 'workspace')); // if you are wondering wtf here -- we wrap the PhpcrSession if (!$this->session) { $this->session = new PhpcrSession($session); } else { $this->session->setPhpcrSession($session); } }
[ "private", "function", "initSession", "(", ")", "{", "$", "transport", "=", "$", "this", "->", "transportRegistry", "->", "getTransport", "(", "$", "this", "->", "profile", "->", "get", "(", "'transport'", ",", "'name'", ")", ")", ";", "$", "repository", ...
Initialize the PHPCR session.
[ "Initialize", "the", "PHPCR", "session", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Phpcr/SessionManager.php#L66-L84
train
phpcr/phpcr-shell
src/PHPCR/Shell/Phpcr/SessionManager.php
SessionManager.changeWorkspace
public function changeWorkspace($workspaceName) { $this->init(); $this->session->logout(); $this->profile->set('phpcr', 'workspace', $workspaceName); $this->initSession($this->profile); }
php
public function changeWorkspace($workspaceName) { $this->init(); $this->session->logout(); $this->profile->set('phpcr', 'workspace', $workspaceName); $this->initSession($this->profile); }
[ "public", "function", "changeWorkspace", "(", "$", "workspaceName", ")", "{", "$", "this", "->", "init", "(", ")", ";", "$", "this", "->", "session", "->", "logout", "(", ")", ";", "$", "this", "->", "profile", "->", "set", "(", "'phpcr'", ",", "'wor...
Change the current workspace. @param string $workspaceName
[ "Change", "the", "current", "workspace", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Phpcr/SessionManager.php#L91-L97
train
bldr-io/bldr
src/DependencyInjection/Loader/TomlFileLoader.php
TomlFileLoader.loadFile
protected function loadFile($file) { if (!stream_is_local($file)) { throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file)); } if (!file_exists($file)) { throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); } return Toml::Parse($file); }
php
protected function loadFile($file) { if (!stream_is_local($file)) { throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file)); } if (!file_exists($file)) { throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); } return Toml::Parse($file); }
[ "protected", "function", "loadFile", "(", "$", "file", ")", "{", "if", "(", "!", "stream_is_local", "(", "$", "file", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'This is not a local file \"%s\".'", ",", "$", "file", ")", ...
Loads the Toml File @param string $file @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException @return array
[ "Loads", "the", "Toml", "File" ]
60bc51ff248bd237c13f1811c95a9a33f9d38aab
https://github.com/bldr-io/bldr/blob/60bc51ff248bd237c13f1811c95a9a33f9d38aab/src/DependencyInjection/Loader/TomlFileLoader.php#L32-L43
train
titledk/silverstripe-calendar
code/colors/ColorpaletteHelper.php
ColorpaletteHelper.get_palette
public static function get_palette($numColors = 50, $type='hsv') { //overwriting with the palette from the calendar settings $s = CalendarConfig::subpackage_settings('colors'); $arr = $s['basepalette']; return $arr; if ($type == 'hsv') { $s = 1; $v = 1; $arr = array(); for ($i = 0; $i <= $numColors; $i++) { $c = new Color(); $h = $i / $numColors; $hex = $c->fromHSV($h, $s, $v)->toHexString(); $arr[$hex] = $hex; } return $arr; } elseif ($type == 'websafe') { //websafe colors $cs = array('00', '33', '66', '99', 'CC', 'FF'); $arr = array(); for ($i = 0; $i < 6; $i++) { for ($j = 0; $j < 6; $j++) { for ($k = 0; $k < 6; $k++) { $c = $cs[$i] . $cs[$j] . $cs[$k]; $arr["$c"] = "#$c"; } } } return $arr; } }
php
public static function get_palette($numColors = 50, $type='hsv') { //overwriting with the palette from the calendar settings $s = CalendarConfig::subpackage_settings('colors'); $arr = $s['basepalette']; return $arr; if ($type == 'hsv') { $s = 1; $v = 1; $arr = array(); for ($i = 0; $i <= $numColors; $i++) { $c = new Color(); $h = $i / $numColors; $hex = $c->fromHSV($h, $s, $v)->toHexString(); $arr[$hex] = $hex; } return $arr; } elseif ($type == 'websafe') { //websafe colors $cs = array('00', '33', '66', '99', 'CC', 'FF'); $arr = array(); for ($i = 0; $i < 6; $i++) { for ($j = 0; $j < 6; $j++) { for ($k = 0; $k < 6; $k++) { $c = $cs[$i] . $cs[$j] . $cs[$k]; $arr["$c"] = "#$c"; } } } return $arr; } }
[ "public", "static", "function", "get_palette", "(", "$", "numColors", "=", "50", ",", "$", "type", "=", "'hsv'", ")", "{", "//overwriting with the palette from the calendar settings", "$", "s", "=", "CalendarConfig", "::", "subpackage_settings", "(", "'colors'", ")"...
Getting a color palette For now we only have a hsv palette, could be extended with more options Potential options: Standard CKEditor color palette http://stackoverflow.com/questions/13455922/display-only-few-desired-colors-in-a-ckeditor-palette 000,800000,8B4513,2F4F4F,008080,000080,4B0082,696969,B22222,A52A2A,DAA520,006400,40E0D0,0000CD,800080,808080,F00,FF8C00,FFD700,008000,0FF,00F,EE82EE,A9A9A9,FFA07A,FFA500,FFFF00,00FF00,AFEEEE,ADD8E6,DDA0DD,D3D3D3,FFF0F5,FAEBD7,FFFFE0,F0FFF0,F0FFFF,F0F8FF,E6E6FA,FFF Consider adding color names like this: http://stackoverflow.com/questions/2993970/function-that-converts-hex-color-values-to-an-approximate-color-name Color variation: http://stackoverflow.com/questions/1177826/simple-color-variation @param int $numColors Number of colors - default: 30 @return null
[ "Getting", "a", "color", "palette", "For", "now", "we", "only", "have", "a", "hsv", "palette", "could", "be", "extended", "with", "more", "options" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/colors/ColorpaletteHelper.php#L53-L94
train
Arara/Process
src/Arara/Process/Child.php
Child.sendSignal
protected function sendSignal($signalNumber) { if (! $this->context->isRunning || ! $this->context->processId) { return false; } $result = $this->control->signal()->send($signalNumber, $this->context->processId); if (in_array($signalNumber, [SIGTERM, SIGKILL])) { $this->context->isRunning = false; $this->context->processId = null; } return $result; }
php
protected function sendSignal($signalNumber) { if (! $this->context->isRunning || ! $this->context->processId) { return false; } $result = $this->control->signal()->send($signalNumber, $this->context->processId); if (in_array($signalNumber, [SIGTERM, SIGKILL])) { $this->context->isRunning = false; $this->context->processId = null; } return $result; }
[ "protected", "function", "sendSignal", "(", "$", "signalNumber", ")", "{", "if", "(", "!", "$", "this", "->", "context", "->", "isRunning", "||", "!", "$", "this", "->", "context", "->", "processId", ")", "{", "return", "false", ";", "}", "$", "result"...
Sends a signal to the current process and returns its results. @param int $signalNumber @return bool
[ "Sends", "a", "signal", "to", "the", "current", "process", "and", "returns", "its", "results", "." ]
98d42b5b466870f93eb0c85d62b1d7a1241040c3
https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Child.php#L124-L137
train
Arara/Process
src/Arara/Process/Child.php
Child.setHandlerAlarm
protected function setHandlerAlarm() { $handler = new SignalAlarm($this->control, $this->action, $this->context); $this->control->signal()->setHandler('alarm', $handler); $this->control->signal()->alarm($this->context->timeout); }
php
protected function setHandlerAlarm() { $handler = new SignalAlarm($this->control, $this->action, $this->context); $this->control->signal()->setHandler('alarm', $handler); $this->control->signal()->alarm($this->context->timeout); }
[ "protected", "function", "setHandlerAlarm", "(", ")", "{", "$", "handler", "=", "new", "SignalAlarm", "(", "$", "this", "->", "control", ",", "$", "this", "->", "action", ",", "$", "this", "->", "context", ")", ";", "$", "this", "->", "control", "->", ...
Define the timeout handler.
[ "Define", "the", "timeout", "handler", "." ]
98d42b5b466870f93eb0c85d62b1d7a1241040c3
https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Child.php#L150-L155
train
Arara/Process
src/Arara/Process/Child.php
Child.silentRunActionTrigger
protected function silentRunActionTrigger($event) { try { $this->action->trigger($event, $this->control, $this->context); } catch (Exception $exception) { // Pokémon Exception Handling } }
php
protected function silentRunActionTrigger($event) { try { $this->action->trigger($event, $this->control, $this->context); } catch (Exception $exception) { // Pokémon Exception Handling } }
[ "protected", "function", "silentRunActionTrigger", "(", "$", "event", ")", "{", "try", "{", "$", "this", "->", "action", "->", "trigger", "(", "$", "event", ",", "$", "this", "->", "control", ",", "$", "this", "->", "context", ")", ";", "}", "catch", ...
Runs action trigger by the given event ignoring all exception.
[ "Runs", "action", "trigger", "by", "the", "given", "event", "ignoring", "all", "exception", "." ]
98d42b5b466870f93eb0c85d62b1d7a1241040c3
https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Child.php#L170-L177
train
Arara/Process
src/Arara/Process/Child.php
Child.run
protected function run() { $this->silentRunActionTrigger(Action::EVENT_START); try { $event = $this->action->execute($this->control, $this->context) ?: Action::EVENT_SUCCESS; $this->context->exitCode = 0; } catch (ErrorException $errorException) { $event = Action::EVENT_ERROR; $this->context->exception = $errorException; $this->context->exitCode = 2; } catch (Exception $exception) { $event = Action::EVENT_FAILURE; $this->context->exception = $exception; $this->context->exitCode = 1; } $this->context->finishTime = time(); $this->silentRunActionTrigger($event); $this->silentRunActionTrigger(Action::EVENT_FINISH); }
php
protected function run() { $this->silentRunActionTrigger(Action::EVENT_START); try { $event = $this->action->execute($this->control, $this->context) ?: Action::EVENT_SUCCESS; $this->context->exitCode = 0; } catch (ErrorException $errorException) { $event = Action::EVENT_ERROR; $this->context->exception = $errorException; $this->context->exitCode = 2; } catch (Exception $exception) { $event = Action::EVENT_FAILURE; $this->context->exception = $exception; $this->context->exitCode = 1; } $this->context->finishTime = time(); $this->silentRunActionTrigger($event); $this->silentRunActionTrigger(Action::EVENT_FINISH); }
[ "protected", "function", "run", "(", ")", "{", "$", "this", "->", "silentRunActionTrigger", "(", "Action", "::", "EVENT_START", ")", ";", "try", "{", "$", "event", "=", "$", "this", "->", "action", "->", "execute", "(", "$", "this", "->", "control", ",...
Execute the action, triggers the events and then exit the program.
[ "Execute", "the", "action", "triggers", "the", "events", "and", "then", "exit", "the", "program", "." ]
98d42b5b466870f93eb0c85d62b1d7a1241040c3
https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Child.php#L182-L200
train
phpcr/phpcr-shell
src/PHPCR/Shell/Query/UpdateParser.php
UpdateParser.doParse
private function doParse($sql2) { $this->implicitSelectorName = null; $this->sql2 = $sql2; $source = null; $constraint = null; $updates = []; $applies = []; while ($this->scanner->lookupNextToken() !== '') { switch (strtoupper($this->scanner->lookupNextToken())) { case 'UPDATE': $this->scanner->expectToken('UPDATE'); $source = $this->parseSource(); break; case 'SET': $this->scanner->expectToken('SET'); $updates = $this->parseUpdates(); break; case 'APPLY': $this->scanner->expectToken('APPLY'); $applies = $this->parseApply(); break; case 'WHERE': $this->scanner->expectToken('WHERE'); $constraint = $this->parseConstraint(); break; default: throw new InvalidQueryException('Expected end of query, got "'.$this->scanner->lookupNextToken().'" in '.$this->sql2); } } if (!$source instanceof SourceInterface) { throw new InvalidQueryException('Invalid query, source could not be determined: '.$sql2); } $query = $this->factory->createQuery($source, $constraint); $res = new \ArrayObject([$query, $updates, $constraint, $applies]); return $res; }
php
private function doParse($sql2) { $this->implicitSelectorName = null; $this->sql2 = $sql2; $source = null; $constraint = null; $updates = []; $applies = []; while ($this->scanner->lookupNextToken() !== '') { switch (strtoupper($this->scanner->lookupNextToken())) { case 'UPDATE': $this->scanner->expectToken('UPDATE'); $source = $this->parseSource(); break; case 'SET': $this->scanner->expectToken('SET'); $updates = $this->parseUpdates(); break; case 'APPLY': $this->scanner->expectToken('APPLY'); $applies = $this->parseApply(); break; case 'WHERE': $this->scanner->expectToken('WHERE'); $constraint = $this->parseConstraint(); break; default: throw new InvalidQueryException('Expected end of query, got "'.$this->scanner->lookupNextToken().'" in '.$this->sql2); } } if (!$source instanceof SourceInterface) { throw new InvalidQueryException('Invalid query, source could not be determined: '.$sql2); } $query = $this->factory->createQuery($source, $constraint); $res = new \ArrayObject([$query, $updates, $constraint, $applies]); return $res; }
[ "private", "function", "doParse", "(", "$", "sql2", ")", "{", "$", "this", "->", "implicitSelectorName", "=", "null", ";", "$", "this", "->", "sql2", "=", "$", "sql2", ";", "$", "source", "=", "null", ";", "$", "constraint", "=", "null", ";", "$", ...
Parse an "SQL2" UPDATE statement and construct a query builder for selecting the rows and build a field => value mapping for the update. @param string $sql2 @return array($query, $updates)
[ "Parse", "an", "SQL2", "UPDATE", "statement", "and", "construct", "a", "query", "builder", "for", "selecting", "the", "rows", "and", "build", "a", "field", "=", ">", "value", "mapping", "for", "the", "update", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Query/UpdateParser.php#L47-L88
train
phpcr/phpcr-shell
src/PHPCR/Shell/Subscriber/AliasSubscriber.php
AliasSubscriber.handleAlias
public function handleAlias(CommandPreRunEvent $event) { $input = $event->getInput(); $commandName = $input->getFirstArgument(); $aliasConfig = $this->configManager->getConfig('alias'); if (!isset($aliasConfig[$commandName])) { return; } $command = $aliasConfig[$commandName]; $command = $command .= substr($input->getRawCommand(), strlen($commandName)); $newInput = new StringInput($command); $event->setInput($newInput); return $command; }
php
public function handleAlias(CommandPreRunEvent $event) { $input = $event->getInput(); $commandName = $input->getFirstArgument(); $aliasConfig = $this->configManager->getConfig('alias'); if (!isset($aliasConfig[$commandName])) { return; } $command = $aliasConfig[$commandName]; $command = $command .= substr($input->getRawCommand(), strlen($commandName)); $newInput = new StringInput($command); $event->setInput($newInput); return $command; }
[ "public", "function", "handleAlias", "(", "CommandPreRunEvent", "$", "event", ")", "{", "$", "input", "=", "$", "event", "->", "getInput", "(", ")", ";", "$", "commandName", "=", "$", "input", "->", "getFirstArgument", "(", ")", ";", "$", "aliasConfig", ...
Check for an alias and replace the input with a new string command if the alias exists. @return string New command string (for testing purposes)
[ "Check", "for", "an", "alias", "and", "replace", "the", "input", "with", "a", "new", "string", "command", "if", "the", "alias", "exists", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Subscriber/AliasSubscriber.php#L52-L71
train
sonata-project/SonataCommentBundle
src/Model/Comment.php
Comment.getStateLabel
public function getStateLabel() { $list = self::getStateList(); return isset($list[$this->getState()]) ? $list[$this->getState()] : null; }
php
public function getStateLabel() { $list = self::getStateList(); return isset($list[$this->getState()]) ? $list[$this->getState()] : null; }
[ "public", "function", "getStateLabel", "(", ")", "{", "$", "list", "=", "self", "::", "getStateList", "(", ")", ";", "return", "isset", "(", "$", "list", "[", "$", "this", "->", "getState", "(", ")", "]", ")", "?", "$", "list", "[", "$", "this", ...
Returns comment state label. @return int|null
[ "Returns", "comment", "state", "label", "." ]
f78a08e64434242d1d1f0bbd82a7f9e27939d546
https://github.com/sonata-project/SonataCommentBundle/blob/f78a08e64434242d1d1f0bbd82a7f9e27939d546/src/Model/Comment.php#L176-L181
train
adam-boduch/laravel-grid
src/GridHelper.php
GridHelper.tag
public function tag($tag, $content, array $attributes = []) { return $this->htmlBuilder->tag($tag, $content, $attributes); }
php
public function tag($tag, $content, array $attributes = []) { return $this->htmlBuilder->tag($tag, $content, $attributes); }
[ "public", "function", "tag", "(", "$", "tag", ",", "$", "content", ",", "array", "$", "attributes", "=", "[", "]", ")", "{", "return", "$", "this", "->", "htmlBuilder", "->", "tag", "(", "$", "tag", ",", "$", "content", ",", "$", "attributes", ")",...
Generate an html tag. @param string $tag @param string $content @param array $attributes @return \Illuminate\Support\HtmlString
[ "Generate", "an", "html", "tag", "." ]
543ffa06e715fe5b6fb6caa0c8d6b5b55f8c18ae
https://github.com/adam-boduch/laravel-grid/blob/543ffa06e715fe5b6fb6caa0c8d6b5b55f8c18ae/src/GridHelper.php#L117-L120
train
Arara/Process
src/Arara/Process/Context.php
Context.normalize
protected function normalize($value) { if ($value instanceof Exception) { $value = [ 'class' => get_class($value), 'message' => $value->getMessage(), 'code' => $value->getCode(), 'file' => $value->getFile(), 'line' => $value->getLine(), ]; } return $value; }
php
protected function normalize($value) { if ($value instanceof Exception) { $value = [ 'class' => get_class($value), 'message' => $value->getMessage(), 'code' => $value->getCode(), 'file' => $value->getFile(), 'line' => $value->getLine(), ]; } return $value; }
[ "protected", "function", "normalize", "(", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "Exception", ")", "{", "$", "value", "=", "[", "'class'", "=>", "get_class", "(", "$", "value", ")", ",", "'message'", "=>", "$", "value", "->", ...
Normalizes the given value. @param mixed $value @return mixed
[ "Normalizes", "the", "given", "value", "." ]
98d42b5b466870f93eb0c85d62b1d7a1241040c3
https://github.com/Arara/Process/blob/98d42b5b466870f93eb0c85d62b1d7a1241040c3/src/Arara/Process/Context.php#L92-L105
train
phpcr/phpcr-shell
src/PHPCR/Shell/Console/Application/ShellApplication.php
ShellApplication.configureFormatter
private function configureFormatter(OutputFormatter $formatter) { $style = new OutputFormatterStyle('yellow', null, ['bold']); $formatter->setStyle('pathbold', $style); $style = new OutputFormatterStyle('green'); $formatter->setStyle('localname', $style); $style = new OutputFormatterStyle(null, null, ['bold']); $formatter->setStyle('node', $style); $style = new OutputFormatterStyle('blue', null, ['bold']); $formatter->setStyle('templatenode', $style); $style = new OutputFormatterStyle('blue', null, []); $formatter->setStyle('templateproperty', $style); $style = new OutputFormatterStyle(null, null, []); $formatter->setStyle('property', $style); $style = new OutputFormatterStyle('magenta', null, ['bold']); $formatter->setStyle('node-type', $style); $style = new OutputFormatterStyle('magenta', null, []); $formatter->setStyle('property-type', $style); $style = new OutputFormatterStyle(null, null, []); $formatter->setStyle('property-value', $style); $style = new OutputFormatterStyle(null, 'red', []); $formatter->setStyle('exception', $style); }
php
private function configureFormatter(OutputFormatter $formatter) { $style = new OutputFormatterStyle('yellow', null, ['bold']); $formatter->setStyle('pathbold', $style); $style = new OutputFormatterStyle('green'); $formatter->setStyle('localname', $style); $style = new OutputFormatterStyle(null, null, ['bold']); $formatter->setStyle('node', $style); $style = new OutputFormatterStyle('blue', null, ['bold']); $formatter->setStyle('templatenode', $style); $style = new OutputFormatterStyle('blue', null, []); $formatter->setStyle('templateproperty', $style); $style = new OutputFormatterStyle(null, null, []); $formatter->setStyle('property', $style); $style = new OutputFormatterStyle('magenta', null, ['bold']); $formatter->setStyle('node-type', $style); $style = new OutputFormatterStyle('magenta', null, []); $formatter->setStyle('property-type', $style); $style = new OutputFormatterStyle(null, null, []); $formatter->setStyle('property-value', $style); $style = new OutputFormatterStyle(null, 'red', []); $formatter->setStyle('exception', $style); }
[ "private", "function", "configureFormatter", "(", "OutputFormatter", "$", "formatter", ")", "{", "$", "style", "=", "new", "OutputFormatterStyle", "(", "'yellow'", ",", "null", ",", "[", "'bold'", "]", ")", ";", "$", "formatter", "->", "setStyle", "(", "'pat...
Configure the output formatter.
[ "Configure", "the", "output", "formatter", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Console/Application/ShellApplication.php#L199-L230
train
phpcr/phpcr-shell
src/PHPCR/Shell/Console/Application/ShellApplication.php
ShellApplication.add
public function add(Command $command) { if ($command instanceof ContainerAwareInterface) { $command->setContainer($this->container); } if ($command instanceof BasePhpcrCommand) { if ($this->showUnsupported || $command->isSupported()) { parent::add($command); } } else { parent::add($command); } }
php
public function add(Command $command) { if ($command instanceof ContainerAwareInterface) { $command->setContainer($this->container); } if ($command instanceof BasePhpcrCommand) { if ($this->showUnsupported || $command->isSupported()) { parent::add($command); } } else { parent::add($command); } }
[ "public", "function", "add", "(", "Command", "$", "command", ")", "{", "if", "(", "$", "command", "instanceof", "ContainerAwareInterface", ")", "{", "$", "command", "->", "setContainer", "(", "$", "this", "->", "container", ")", ";", "}", "if", "(", "$",...
Wrap the add method and do not register commands which are unsupported by the current transport. {@inheritdoc}
[ "Wrap", "the", "add", "method", "and", "do", "not", "register", "commands", "which", "are", "unsupported", "by", "the", "current", "transport", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Console/Application/ShellApplication.php#L277-L290
train
FluidTYPO3/site
Classes/Service/KickStarterService.php
KickStarterService.prepareSettings
protected function prepareSettings( $mass, $makeResources, $makeMountPoint, $extensionKey, $author, $title, $description, $useVhs, $useFluidcontentCore, $pages, $content, $backend, $controllers ) { return [ $mass, (boolean) $makeResources, (boolean) $makeMountPoint, false === is_null($extensionKey) ? $extensionKey : self::DEFAULT_EXTENSION_KEY, $this->getAuthor($author), false === empty($title) ? $title : self::DEFAULT_EXTENSION_TITLE, false === empty($description) ? $description : self::DEFAULT_EXTENSION_DESCRIPTION, (boolean) $useVhs, (boolean) $useFluidcontentCore, (boolean) $pages, (boolean) $content, (boolean) $backend, (boolean) $controllers ]; }
php
protected function prepareSettings( $mass, $makeResources, $makeMountPoint, $extensionKey, $author, $title, $description, $useVhs, $useFluidcontentCore, $pages, $content, $backend, $controllers ) { return [ $mass, (boolean) $makeResources, (boolean) $makeMountPoint, false === is_null($extensionKey) ? $extensionKey : self::DEFAULT_EXTENSION_KEY, $this->getAuthor($author), false === empty($title) ? $title : self::DEFAULT_EXTENSION_TITLE, false === empty($description) ? $description : self::DEFAULT_EXTENSION_DESCRIPTION, (boolean) $useVhs, (boolean) $useFluidcontentCore, (boolean) $pages, (boolean) $content, (boolean) $backend, (boolean) $controllers ]; }
[ "protected", "function", "prepareSettings", "(", "$", "mass", ",", "$", "makeResources", ",", "$", "makeMountPoint", ",", "$", "extensionKey", ",", "$", "author", ",", "$", "title", ",", "$", "description", ",", "$", "useVhs", ",", "$", "useFluidcontentCore"...
Prepare values to avoid problems @param string $mass [default,minimalist,small,medium,large] Site enterprise level: If you wish, select the expected size of your site here. Depending on your selection, system extensions will be installed or uninstalled to create a sane default extension collection that suits your site. The "medium" option is approximately the same as the default except without the documentation-related extensions. Choose "large" if your site is targed at multiple editors, languages or otherwise requires many CMS features. @param boolean $makeResources Create resources: Check this checkbox to create a top-level page with preset template selections, three sub-pages, one domain record based on the current host name you use and one root TypoScript record in which the necessary static TypoScript templates are pre-included. @param boolean $makeMountPoint Create FAL mount point: Check this to create a file system mount point allowing you to access your templates and asset files using the "File list" module" and reference your templates and asset files from "file" type fields in your pages and content properties. @param string $extensionKey [ext:builder] The extension key which should be generated. Must not exist. @param string $author [ext:builder] The author of the extension, in the format "Name Lastname <name@example.com>" with optional company name, in which case form is "Name Lastname <name@example.com>, Company Name" @param string $title [ext:builder] The title of the resulting extension, by default "Provider extension for $enabledFeaturesList" @param string $description [ext:builder] The description of the resulting extension, by default "Provider extension for $enabledFeaturesList" @param boolean $useVhs [ext:builder] If TRUE, adds the VHS extension as dependency - recommended, on by default @param boolean $useFluidcontentCor [ext:builder] If TRUE, adds the FluidcontentCore extension as dependency - recommended, on by default @param boolean $pages [ext:builder] If TRUE, generates basic files for implementing Fluid Page templates @param boolean $content [ext:builder] IF TRUE, generates basic files for implementing Fluid Content templates @param boolean $backend [ext:builder] If TRUE, generates basic files for implementing Fluid Backend modules @param boolean $controllers [ext:builder] If TRUE, generates controllers for each enabled feature. Enabling $backend will always generate a controller regardless of this toggle. @return array
[ "Prepare", "values", "to", "avoid", "problems" ]
d62468f12028258d51e942ef18959bfc91827598
https://github.com/FluidTYPO3/site/blob/d62468f12028258d51e942ef18959bfc91827598/Classes/Service/KickStarterService.php#L147-L177
train
FluidTYPO3/site
Classes/Service/KickStarterService.php
KickStarterService.gatherInformation
private function gatherInformation() { /** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager */ $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(ObjectManager::class); /** @var ListUtility $service */ $service = $objectManager->get('TYPO3\\CMS\\Extensionmanager\\Utility\\ListUtility'); $extensionInformation = $service->getAvailableExtensions(); foreach ($extensionInformation as $extensionKey => $info) { if (true === array_key_exists($extensionKey, $GLOBALS['TYPO3_LOADED_EXT'])) { $extensionInformation[$extensionKey]['installed'] = 1; } else { $extensionInformation[$extensionKey]['installed'] = 0; } } return $extensionInformation; }
php
private function gatherInformation() { /** @var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager */ $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(ObjectManager::class); /** @var ListUtility $service */ $service = $objectManager->get('TYPO3\\CMS\\Extensionmanager\\Utility\\ListUtility'); $extensionInformation = $service->getAvailableExtensions(); foreach ($extensionInformation as $extensionKey => $info) { if (true === array_key_exists($extensionKey, $GLOBALS['TYPO3_LOADED_EXT'])) { $extensionInformation[$extensionKey]['installed'] = 1; } else { $extensionInformation[$extensionKey]['installed'] = 0; } } return $extensionInformation; }
[ "private", "function", "gatherInformation", "(", ")", "{", "/** @var \\TYPO3\\CMS\\Extbase\\Object\\ObjectManagerInterface $objectManager */", "$", "objectManager", "=", "\\", "TYPO3", "\\", "CMS", "\\", "Core", "\\", "Utility", "\\", "GeneralUtility", "::", "makeInstance",...
Gathers Extension Information @return array
[ "Gathers", "Extension", "Information" ]
d62468f12028258d51e942ef18959bfc91827598
https://github.com/FluidTYPO3/site/blob/d62468f12028258d51e942ef18959bfc91827598/Classes/Service/KickStarterService.php#L510-L526
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.fromHexString
public static function fromHexString($color) { $color = rtrim($color, '#'); preg_match_all('([0-9a-f][0-9a-f])', $color, $rgb); $c = new self(); list($c->r, $c->g, $c->b) = array_map('hexdec', $rgb[0]); return $c; }
php
public static function fromHexString($color) { $color = rtrim($color, '#'); preg_match_all('([0-9a-f][0-9a-f])', $color, $rgb); $c = new self(); list($c->r, $c->g, $c->b) = array_map('hexdec', $rgb[0]); return $c; }
[ "public", "static", "function", "fromHexString", "(", "$", "color", ")", "{", "$", "color", "=", "rtrim", "(", "$", "color", ",", "'#'", ")", ";", "preg_match_all", "(", "'([0-9a-f][0-9a-f])'", ",", "$", "color", ",", "$", "rgb", ")", ";", "$", "c", ...
Construct a Color from hex string @param string $color The hex string @returns Color the color object
[ "Construct", "a", "Color", "from", "hex", "string" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L52-L61
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.fromRGBString
public static function fromRGBString($color) { $color = rtrim($color, "rgb (\t)"); $rgb = preg_split('\s+,\s+', $color); $c = new self(); list($c->r, $c->g, $c->b) = array_map('intval', $rgb); return $c; }
php
public static function fromRGBString($color) { $color = rtrim($color, "rgb (\t)"); $rgb = preg_split('\s+,\s+', $color); $c = new self(); list($c->r, $c->g, $c->b) = array_map('intval', $rgb); return $c; }
[ "public", "static", "function", "fromRGBString", "(", "$", "color", ")", "{", "$", "color", "=", "rtrim", "(", "$", "color", ",", "\"rgb (\\t)\"", ")", ";", "$", "rgb", "=", "preg_split", "(", "'\\s+,\\s+'", ",", "$", "color", ")", ";", "$", "c", "="...
Construct Color object from an rgb string @param string $color The rgb string representing the color @returns Color object with for the rgb string
[ "Construct", "Color", "object", "from", "an", "rgb", "string" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L69-L78
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.toHexString
public function toHexString() { return '#' . $this->decToHex($this->r) . $this->decToHex($this->g) . $this->decToHex($this->b); }
php
public function toHexString() { return '#' . $this->decToHex($this->r) . $this->decToHex($this->g) . $this->decToHex($this->b); }
[ "public", "function", "toHexString", "(", ")", "{", "return", "'#'", ".", "$", "this", "->", "decToHex", "(", "$", "this", "->", "r", ")", ".", "$", "this", "->", "decToHex", "(", "$", "this", "->", "g", ")", ".", "$", "this", "->", "decToHex", "...
Convert color object to hex string @returns string The hex string
[ "Convert", "color", "object", "to", "hex", "string" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L85-L91
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.fromHSL
public static function fromHSL($h, $s, $l) { // theta plus 360 degrees $h -= floor($h); $c = new self(); if ($s == 0) { $c->r = $c->g = $c->b = $l * 255; return $c; } $chroma = floatval(1 - abs(2*$l - 1)) * $s; // Divide $h by 60 degrees i.e by (60 / 360) $h_ = $h * 6; // intermediate $k = intval($h_); $h_mod2 = $k % 2 + $h_ - floor($h_); $x = $chroma * abs(1 - abs($h_mod2 - 1)); $r = $g = $b = 0.0; switch ($k) { case 0: case 6: $r = $chroma; $g = $x; break; case 1: $r = $x; $g = $chroma; break; case 2: $g = $chroma; $b = $x; break; case 3: $g = $x; $b = $chroma; break; case 4: $r = $x; $b = $chroma; break; case 5: $r = $chroma; $b = $x; break; } $m = $l - 0.5 * $chroma; $c->r = (($r + $m) * 255); $c->g = (($g + $m) * 255); $c->b = (($b + $m) * 255); return $c; }
php
public static function fromHSL($h, $s, $l) { // theta plus 360 degrees $h -= floor($h); $c = new self(); if ($s == 0) { $c->r = $c->g = $c->b = $l * 255; return $c; } $chroma = floatval(1 - abs(2*$l - 1)) * $s; // Divide $h by 60 degrees i.e by (60 / 360) $h_ = $h * 6; // intermediate $k = intval($h_); $h_mod2 = $k % 2 + $h_ - floor($h_); $x = $chroma * abs(1 - abs($h_mod2 - 1)); $r = $g = $b = 0.0; switch ($k) { case 0: case 6: $r = $chroma; $g = $x; break; case 1: $r = $x; $g = $chroma; break; case 2: $g = $chroma; $b = $x; break; case 3: $g = $x; $b = $chroma; break; case 4: $r = $x; $b = $chroma; break; case 5: $r = $chroma; $b = $x; break; } $m = $l - 0.5 * $chroma; $c->r = (($r + $m) * 255); $c->g = (($g + $m) * 255); $c->b = (($b + $m) * 255); return $c; }
[ "public", "static", "function", "fromHSL", "(", "$", "h", ",", "$", "s", ",", "$", "l", ")", "{", "// theta plus 360 degrees", "$", "h", "-=", "floor", "(", "$", "h", ")", ";", "$", "c", "=", "new", "self", "(", ")", ";", "if", "(", "$", "s", ...
Construct a Color object from H, S, L values @param float $h Hue @param float $s Saturation @param float $l Lightness @retuns Color the color object for the HSL values
[ "Construct", "a", "Color", "object", "from", "H", "S", "L", "values" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L110-L169
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.fromHSV
public static function fromHSV($h, $s, $v) { $h -= floor($h); $c = new self(); if ($s == 0) { $c->r = $c->g = $c->b = $v * 255; return $c; } $chroma = $v * $s; // Divide $h by 60 degrees i.e by (60 / 360) $h_ = $h * 6; // intermediate $k = intval($h_); $h_mod2 = $k % 2 + $h_ - floor($h_); $x = $chroma * abs(1 - abs($h_mod2 - 1)); $r = $g = $b = 0.0; switch ($k) { case 0: case 6: $r = $chroma; $g = $x; break; case 1: $r = $x; $g = $chroma; break; case 2: $g = $chroma; $b = $x; break; case 3: $g = $x; $b = $chroma; break; case 4: $r = $x; $b = $chroma; break; case 5: $r = $chroma; $b = $x; break; } $m = $v - $chroma; $c->r = (($r + $m) * 255); $c->g = (($g + $m) * 255); $c->b = (($b + $m) * 255); return $c; }
php
public static function fromHSV($h, $s, $v) { $h -= floor($h); $c = new self(); if ($s == 0) { $c->r = $c->g = $c->b = $v * 255; return $c; } $chroma = $v * $s; // Divide $h by 60 degrees i.e by (60 / 360) $h_ = $h * 6; // intermediate $k = intval($h_); $h_mod2 = $k % 2 + $h_ - floor($h_); $x = $chroma * abs(1 - abs($h_mod2 - 1)); $r = $g = $b = 0.0; switch ($k) { case 0: case 6: $r = $chroma; $g = $x; break; case 1: $r = $x; $g = $chroma; break; case 2: $g = $chroma; $b = $x; break; case 3: $g = $x; $b = $chroma; break; case 4: $r = $x; $b = $chroma; break; case 5: $r = $chroma; $b = $x; break; } $m = $v - $chroma; $c->r = (($r + $m) * 255); $c->g = (($g + $m) * 255); $c->b = (($b + $m) * 255); return $c; }
[ "public", "static", "function", "fromHSV", "(", "$", "h", ",", "$", "s", ",", "$", "v", ")", "{", "$", "h", "-=", "floor", "(", "$", "h", ")", ";", "$", "c", "=", "new", "self", "(", ")", ";", "if", "(", "$", "s", "==", "0", ")", "{", "...
Construct a Color object from HSV values @param float $h Hue @param float $s Saturation @param float $v Value @returns Color The color object for the HSV values
[ "Construct", "a", "Color", "object", "from", "HSV", "values" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L180-L236
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.darken
public function darken($fraction=0.1) { $hsl = $this->toHSL(); $l = $hsl[2]; // so that 100% darker = black $dl = -$l * $fraction; return $this->changeHSL(0, 0, $dl); }
php
public function darken($fraction=0.1) { $hsl = $this->toHSL(); $l = $hsl[2]; // so that 100% darker = black $dl = -$l * $fraction; return $this->changeHSL(0, 0, $dl); }
[ "public", "function", "darken", "(", "$", "fraction", "=", "0.1", ")", "{", "$", "hsl", "=", "$", "this", "->", "toHSL", "(", ")", ";", "$", "l", "=", "$", "hsl", "[", "2", "]", ";", "// so that 100% darker = black", "$", "dl", "=", "-", "$", "l"...
Darken the current color by a fraction @param float $fraction (default=0.1) a number between 0 and 1 @returns Color The darker color object
[ "Darken", "the", "current", "color", "by", "a", "fraction" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L245-L253
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.lighten
public function lighten($fraction=0.1) { $hsl = $this->toHSL(); $l = $hsl[2]; // so that 100% lighter = white $dl = (1 - $l) * $fraction; return $this->changeHSL(0, 0, $dl); }
php
public function lighten($fraction=0.1) { $hsl = $this->toHSL(); $l = $hsl[2]; // so that 100% lighter = white $dl = (1 - $l) * $fraction; return $this->changeHSL(0, 0, $dl); }
[ "public", "function", "lighten", "(", "$", "fraction", "=", "0.1", ")", "{", "$", "hsl", "=", "$", "this", "->", "toHSL", "(", ")", ";", "$", "l", "=", "$", "hsl", "[", "2", "]", ";", "// so that 100% lighter = white", "$", "dl", "=", "(", "1", "...
Lighten the current color by a fraction @param float $fraction (default=0.1) a number between 0 and 1 @returns Color The lighter color object
[ "Lighten", "the", "current", "color", "by", "a", "fraction" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L262-L270
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.changeHSL
public function changeHSL($dh=0, $ds=0, $dl=0) { list($h, $s, $l) = $this->toHSL(); $h += $dh; $s += $ds; $l += $dl; $c = self::fromHSL($h, $s, $l); $this->r = $c->r; $this->g = $c->g; $this->b = $c->b; return $this; }
php
public function changeHSL($dh=0, $ds=0, $dl=0) { list($h, $s, $l) = $this->toHSL(); $h += $dh; $s += $ds; $l += $dl; $c = self::fromHSL($h, $s, $l); $this->r = $c->r; $this->g = $c->g; $this->b = $c->b; return $this; }
[ "public", "function", "changeHSL", "(", "$", "dh", "=", "0", ",", "$", "ds", "=", "0", ",", "$", "dl", "=", "0", ")", "{", "list", "(", "$", "h", ",", "$", "s", ",", "$", "l", ")", "=", "$", "this", "->", "toHSL", "(", ")", ";", "$", "h...
Change HSL values by given deltas @param float $dh Change in Hue @param float $ds Change in Saturation @param float $dl Change in Lightness @returns Color The color object with the required changes
[ "Change", "HSL", "values", "by", "given", "deltas" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L308-L323
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.toHSL
public function toHSL() { // r, g, b as fractions of 1 $r = $this->r / 255.0; $g = $this->g / 255.0; $b = $this->b / 255.0; // most prominent primary color $max = max($r, $g, $b); // least prominent primary color $min = min($r, $g, $b); // maximum delta $dmax = $max - $min; // intensity = (r + g + b) / 3 // lightness = (r + g + b - (non-extreme color)) / 2 $l = ($min + $max) / 2; if ($dmax == 0) { // This means R=G=B, so: $h = 0; $s = 0; } else { // remember ligtness = (min+max) / 2 $s = ($l < 0.5) ? $dmax / ($l * 2) : $dmax / ((1 - $l) * 2); $dr = ((($max - $r) / 6) + ($dmax / 2)) / $dmax; $dg = ((($max - $g) / 6) + ($dmax / 2)) / $dmax; $db = ((($max - $b) / 6) + ($dmax / 2)) / $dmax; if ($r == $max) { $h = (0.0 / 3) + $db - $dg; } elseif ($g == $max) { $h = (1.0 / 3) + $dr - $db; } elseif ($b == $max) { $h = (2.0 / 3) + $dg - $dr; } // the case of less than 0 radians if ($h < 0) { $h += 1; } if ($h > 1) { $h -= 1; } } return array($h, $s, $l); }
php
public function toHSL() { // r, g, b as fractions of 1 $r = $this->r / 255.0; $g = $this->g / 255.0; $b = $this->b / 255.0; // most prominent primary color $max = max($r, $g, $b); // least prominent primary color $min = min($r, $g, $b); // maximum delta $dmax = $max - $min; // intensity = (r + g + b) / 3 // lightness = (r + g + b - (non-extreme color)) / 2 $l = ($min + $max) / 2; if ($dmax == 0) { // This means R=G=B, so: $h = 0; $s = 0; } else { // remember ligtness = (min+max) / 2 $s = ($l < 0.5) ? $dmax / ($l * 2) : $dmax / ((1 - $l) * 2); $dr = ((($max - $r) / 6) + ($dmax / 2)) / $dmax; $dg = ((($max - $g) / 6) + ($dmax / 2)) / $dmax; $db = ((($max - $b) / 6) + ($dmax / 2)) / $dmax; if ($r == $max) { $h = (0.0 / 3) + $db - $dg; } elseif ($g == $max) { $h = (1.0 / 3) + $dr - $db; } elseif ($b == $max) { $h = (2.0 / 3) + $dg - $dr; } // the case of less than 0 radians if ($h < 0) { $h += 1; } if ($h > 1) { $h -= 1; } } return array($h, $s, $l); }
[ "public", "function", "toHSL", "(", ")", "{", "// r, g, b as fractions of 1", "$", "r", "=", "$", "this", "->", "r", "/", "255.0", ";", "$", "g", "=", "$", "this", "->", "g", "/", "255.0", ";", "$", "b", "=", "$", "this", "->", "b", "/", "255.0",...
Convert the current color to HSL values @returns array An array with 3 elements: Hue, Saturation and Lightness
[ "Convert", "the", "current", "color", "to", "HSL", "values" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L366-L418
train
titledk/silverstripe-calendar
code/libs/colorpool/Color.php
Color.toHSV
public function toHSV() { // r, g, b as fractions of 1 $r = $this->r / 255.0; $g = $this->g / 255.0; $b = $this->b / 255.0; // most prominent primary color $max = max($r, $g, $b); // least prominent primary color $min = min($r, $g, $b); // maximum delta $dmax = $max - $min; // value is just the fraction of // the most prominent primary color $v = $max; if ($dmax == 0) { // This means R=G=B, so: $h = 0; $s = 0; } else { $s = $dmax / $max; $dr = ((($max - $r) / 6) + ($dmax / 2)) / $dmax; $dg = ((($max - $g) / 6) + ($dmax / 2)) / $dmax; $db = ((($max - $b) / 6) + ($dmax / 2)) / $dmax; if ($r == $max) { $h = (0.0 / 3) + $db - $dg; } elseif ($g == $max) { $h = (1.0 / 3) + $dr - $db; } elseif ($b == $max) { $h = (2.0 / 3) + $dg - $dr; } // the case of less than 0 radians if ($h < 0) { $h += 1; } if ($h > 1) { $h -= 1; } } return array($h, $s, $v); }
php
public function toHSV() { // r, g, b as fractions of 1 $r = $this->r / 255.0; $g = $this->g / 255.0; $b = $this->b / 255.0; // most prominent primary color $max = max($r, $g, $b); // least prominent primary color $min = min($r, $g, $b); // maximum delta $dmax = $max - $min; // value is just the fraction of // the most prominent primary color $v = $max; if ($dmax == 0) { // This means R=G=B, so: $h = 0; $s = 0; } else { $s = $dmax / $max; $dr = ((($max - $r) / 6) + ($dmax / 2)) / $dmax; $dg = ((($max - $g) / 6) + ($dmax / 2)) / $dmax; $db = ((($max - $b) / 6) + ($dmax / 2)) / $dmax; if ($r == $max) { $h = (0.0 / 3) + $db - $dg; } elseif ($g == $max) { $h = (1.0 / 3) + $dr - $db; } elseif ($b == $max) { $h = (2.0 / 3) + $dg - $dr; } // the case of less than 0 radians if ($h < 0) { $h += 1; } if ($h > 1) { $h -= 1; } } return array($h, $s, $v); }
[ "public", "function", "toHSV", "(", ")", "{", "// r, g, b as fractions of 1", "$", "r", "=", "$", "this", "->", "r", "/", "255.0", ";", "$", "g", "=", "$", "this", "->", "g", "/", "255.0", ";", "$", "b", "=", "$", "this", "->", "b", "/", "255.0",...
Convert the current color to HSV values @returns array An array with three elements: Hue, Saturation and Value.
[ "Convert", "the", "current", "color", "to", "HSV", "values" ]
afba392d26f28d6e5c9a44765eab5a3a171cc850
https://github.com/titledk/silverstripe-calendar/blob/afba392d26f28d6e5c9a44765eab5a3a171cc850/code/libs/colorpool/Color.php#L425-L473
train
phpcr/phpcr-shell
src/PHPCR/Shell/Phpcr/PhpcrSession.php
PhpcrSession.getAbsTargetPath
public function getAbsTargetPath($srcPath, $targetPath) { $targetPath = $this->getAbsPath($targetPath); try { $this->getNode($targetPath); } catch (PathNotFoundException $e) { return $targetPath; } $basename = basename($this->getAbsPath($srcPath)); return $this->getAbsPath(sprintf('%s/%s', $targetPath, $basename)); }
php
public function getAbsTargetPath($srcPath, $targetPath) { $targetPath = $this->getAbsPath($targetPath); try { $this->getNode($targetPath); } catch (PathNotFoundException $e) { return $targetPath; } $basename = basename($this->getAbsPath($srcPath)); return $this->getAbsPath(sprintf('%s/%s', $targetPath, $basename)); }
[ "public", "function", "getAbsTargetPath", "(", "$", "srcPath", ",", "$", "targetPath", ")", "{", "$", "targetPath", "=", "$", "this", "->", "getAbsPath", "(", "$", "targetPath", ")", ";", "try", "{", "$", "this", "->", "getNode", "(", "$", "targetPath", ...
Infer the absolute target path for a given source path. This means that if there is a node at targetPath then we will return append the basename of $srcPath to $targetPath. @param string $srcPath @param string $targetPath @return string
[ "Infer", "the", "absolute", "target", "path", "for", "a", "given", "source", "path", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Phpcr/PhpcrSession.php#L149-L162
train
phpcr/phpcr-shell
src/PHPCR/Shell/Phpcr/PhpcrSession.php
PhpcrSession.getNodeByPathOrIdentifier
public function getNodeByPathOrIdentifier($pathOrId) { if (true === UUIDHelper::isUUID($pathOrId)) { return $this->getNodeByIdentifier($pathOrId); } $pathOrId = $this->getAbsPath($pathOrId); return $this->getNode($pathOrId); }
php
public function getNodeByPathOrIdentifier($pathOrId) { if (true === UUIDHelper::isUUID($pathOrId)) { return $this->getNodeByIdentifier($pathOrId); } $pathOrId = $this->getAbsPath($pathOrId); return $this->getNode($pathOrId); }
[ "public", "function", "getNodeByPathOrIdentifier", "(", "$", "pathOrId", ")", "{", "if", "(", "true", "===", "UUIDHelper", "::", "isUUID", "(", "$", "pathOrId", ")", ")", "{", "return", "$", "this", "->", "getNodeByIdentifier", "(", "$", "pathOrId", ")", "...
If the given parameter looks like a UUID retrieve by Identifier, otherwise by path. @param string $pathOrId @throws PathNotFoundException if no accessible node is found at the specified path. @throws ItemNotFoundException if no node with the specified identifier exists or if this Session does not have read access to the node with the specified identifier. @return NodeInterface
[ "If", "the", "given", "parameter", "looks", "like", "a", "UUID", "retrieve", "by", "Identifier", "otherwise", "by", "path", "." ]
360febfaf4760cafcd22d6a0c7503bd8d6e79eea
https://github.com/phpcr/phpcr-shell/blob/360febfaf4760cafcd22d6a0c7503bd8d6e79eea/src/PHPCR/Shell/Phpcr/PhpcrSession.php#L187-L196
train
schmittjoh/php-manipulator
src/JMS/PhpManipulator/TokenStream.php
TokenStream.normalizeTokens
private function normalizeTokens(array $tokens) { $nTokens = array(); for ($i=0,$c=count($tokens); $i<$c; $i++) { $token = $tokens[$i]; if (is_string($token)) { $nTokens[] = new LiteralToken($token, end($nTokens)->getEndLine()); continue; } switch ($token[0]) { case T_WHITESPACE: $lines = explode("\n", $token[1]); for ($j=0,$k=count($lines); $j<$k; $j++) { $line = $lines[$j].($j+1 === $k ? '' : "\n"); if ($j+1 === $k && '' === $line) { break; } $nTokens[] = new PhpToken(array(T_WHITESPACE, $line, $token[2] + $j)); } break; default: // remove any trailing whitespace of the token if (preg_match('/^(.*?)(\s+)$/', $token[1], $match)) { $nTokens[] = new PhpToken(array($token[0], $match[1], $token[2])); // if the next token is whitespace, change it if (isset($tokens[$i+1]) && !is_string($tokens[$i+1]) && T_WHITESPACE === $tokens[$i+1][0]) { $tokens[$i+1][1] = $match[2].$tokens[$i+1][1]; $tokens[$i+1][2] = $token[2]; } else { $nTokens[] = new PhpToken(array(T_WHITESPACE, $match[2], $token[2])); } } else { $nTokens[] = new PhpToken($token); } } } return $nTokens; }
php
private function normalizeTokens(array $tokens) { $nTokens = array(); for ($i=0,$c=count($tokens); $i<$c; $i++) { $token = $tokens[$i]; if (is_string($token)) { $nTokens[] = new LiteralToken($token, end($nTokens)->getEndLine()); continue; } switch ($token[0]) { case T_WHITESPACE: $lines = explode("\n", $token[1]); for ($j=0,$k=count($lines); $j<$k; $j++) { $line = $lines[$j].($j+1 === $k ? '' : "\n"); if ($j+1 === $k && '' === $line) { break; } $nTokens[] = new PhpToken(array(T_WHITESPACE, $line, $token[2] + $j)); } break; default: // remove any trailing whitespace of the token if (preg_match('/^(.*?)(\s+)$/', $token[1], $match)) { $nTokens[] = new PhpToken(array($token[0], $match[1], $token[2])); // if the next token is whitespace, change it if (isset($tokens[$i+1]) && !is_string($tokens[$i+1]) && T_WHITESPACE === $tokens[$i+1][0]) { $tokens[$i+1][1] = $match[2].$tokens[$i+1][1]; $tokens[$i+1][2] = $token[2]; } else { $nTokens[] = new PhpToken(array(T_WHITESPACE, $match[2], $token[2])); } } else { $nTokens[] = new PhpToken($token); } } } return $nTokens; }
[ "private", "function", "normalizeTokens", "(", "array", "$", "tokens", ")", "{", "$", "nTokens", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ",", "$", "c", "=", "count", "(", "$", "tokens", ")", ";", "$", "i", "<", "$", "c", ...
Normalizes the original PHP token stream into a format which is more usable for analysis. @param array $tokens the format returned by ``token_get_all`` @return array the normalized tokens
[ "Normalizes", "the", "original", "PHP", "token", "stream", "into", "a", "format", "which", "is", "more", "usable", "for", "analysis", "." ]
9ea6f165c861b02c3b842df71d5829cdcf0c810b
https://github.com/schmittjoh/php-manipulator/blob/9ea6f165c861b02c3b842df71d5829cdcf0c810b/src/JMS/PhpManipulator/TokenStream.php#L142-L187
train
schmittjoh/php-manipulator
src/JMS/PhpManipulator/TokenStream.php
TokenStream.insertBefore
public function insertBefore(AbstractToken $token, $type, $value = null) { $this->insertAllTokensBefore($token, array(array($type, $value, $token->getLine()))); }
php
public function insertBefore(AbstractToken $token, $type, $value = null) { $this->insertAllTokensBefore($token, array(array($type, $value, $token->getLine()))); }
[ "public", "function", "insertBefore", "(", "AbstractToken", "$", "token", ",", "$", "type", ",", "$", "value", "=", "null", ")", "{", "$", "this", "->", "insertAllTokensBefore", "(", "$", "token", ",", "array", "(", "array", "(", "$", "type", ",", "$",...
Inserts a new token before the passed token. @param \JMS\PhpManipulator\TokenStream\AbstractToken $token @param string|integer $type either one of PHP's T_??? constants, or a literal @param string|null $value When type is a T_??? constant, this should be its value.
[ "Inserts", "a", "new", "token", "before", "the", "passed", "token", "." ]
9ea6f165c861b02c3b842df71d5829cdcf0c810b
https://github.com/schmittjoh/php-manipulator/blob/9ea6f165c861b02c3b842df71d5829cdcf0c810b/src/JMS/PhpManipulator/TokenStream.php#L196-L199
train
billogram/billogram-v2-api-php-lib
Billogram/Api.php
Api.httpRequest
private function httpRequest( $url, $request, $data = array(), $sendHeaders = array(), $timeout = 10 ) { $streamParams = array( 'http' => array( 'method' => $request, 'ignore_errors' => true, 'timeout' => $timeout, 'header' => "User-Agent: " . $this->userAgent . "\r\n" ) ); foreach ($sendHeaders as $header => $value) { $streamParams['http']['header'] .= $header . ': ' . $value . "\r\n"; } foreach ($this->extraHeaders as $header => $value) { $streamParams['http']['header'] .= $header . ': ' . $value . "\r\n"; } if (is_array($data)) { if (in_array($request, array('POST', 'PUT'))) $streamParams['http']['content'] = http_build_query($data); elseif ($data && count($data)) $url .= '?' . http_build_query($data); } elseif ($data !== null) { if (in_array($request, array('POST', 'PUT'))) $streamParams['http']['content'] = $data; } $streamParams['cURL'] = $streamParams['http']; $context = stream_context_create($streamParams); $fp = @fopen($url, 'rb', false, $context); if (!$fp) $content = false; else $content = stream_get_contents($fp); $status = null; $statusCode = null; $headers = array(); if ($content !== false) { $metadata = stream_get_meta_data($fp); if (isset($metadata['wrapper_data']['headers'])) $headerMetadata = $metadata['wrapper_data']['headers']; else $headerMetadata = $metadata['wrapper_data']; foreach ($headerMetadata as $row) { if (preg_match('/^HTTP\/1\.[01] (\d{3})\s*(.*)/', $row, $m)) { $statusCode = $m[1]; $status = $m[2]; } elseif (preg_match('/^([^:]+):\s*(.*)$/', $row, $m)) { $headers[mb_strtolower($m[1])] = $m[2]; } } } return (object) array( 'ok' => $statusCode == 200, 'statusCode' => $statusCode, 'status' => $status, 'content' => $content, 'headers' => $headers ); }
php
private function httpRequest( $url, $request, $data = array(), $sendHeaders = array(), $timeout = 10 ) { $streamParams = array( 'http' => array( 'method' => $request, 'ignore_errors' => true, 'timeout' => $timeout, 'header' => "User-Agent: " . $this->userAgent . "\r\n" ) ); foreach ($sendHeaders as $header => $value) { $streamParams['http']['header'] .= $header . ': ' . $value . "\r\n"; } foreach ($this->extraHeaders as $header => $value) { $streamParams['http']['header'] .= $header . ': ' . $value . "\r\n"; } if (is_array($data)) { if (in_array($request, array('POST', 'PUT'))) $streamParams['http']['content'] = http_build_query($data); elseif ($data && count($data)) $url .= '?' . http_build_query($data); } elseif ($data !== null) { if (in_array($request, array('POST', 'PUT'))) $streamParams['http']['content'] = $data; } $streamParams['cURL'] = $streamParams['http']; $context = stream_context_create($streamParams); $fp = @fopen($url, 'rb', false, $context); if (!$fp) $content = false; else $content = stream_get_contents($fp); $status = null; $statusCode = null; $headers = array(); if ($content !== false) { $metadata = stream_get_meta_data($fp); if (isset($metadata['wrapper_data']['headers'])) $headerMetadata = $metadata['wrapper_data']['headers']; else $headerMetadata = $metadata['wrapper_data']; foreach ($headerMetadata as $row) { if (preg_match('/^HTTP\/1\.[01] (\d{3})\s*(.*)/', $row, $m)) { $statusCode = $m[1]; $status = $m[2]; } elseif (preg_match('/^([^:]+):\s*(.*)$/', $row, $m)) { $headers[mb_strtolower($m[1])] = $m[2]; } } } return (object) array( 'ok' => $statusCode == 200, 'statusCode' => $statusCode, 'status' => $status, 'content' => $content, 'headers' => $headers ); }
[ "private", "function", "httpRequest", "(", "$", "url", ",", "$", "request", ",", "$", "data", "=", "array", "(", ")", ",", "$", "sendHeaders", "=", "array", "(", ")", ",", "$", "timeout", "=", "10", ")", "{", "$", "streamParams", "=", "array", "(",...
Opens a socket and makes a request to the url of choice. Returns an object with statusCode, status, content and the received headers.
[ "Opens", "a", "socket", "and", "makes", "a", "request", "to", "the", "url", "of", "choice", ".", "Returns", "an", "object", "with", "statusCode", "status", "content", "and", "the", "received", "headers", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api.php#L209-L277
train
billogram/billogram-v2-api-php-lib
Billogram/Api.php
Api.get
public function get($objectUrl, $data = null, $expectContentType = null) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest($url, 'GET', $data, $this->authHeader()), $expectContentType ); }
php
public function get($objectUrl, $data = null, $expectContentType = null) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest($url, 'GET', $data, $this->authHeader()), $expectContentType ); }
[ "public", "function", "get", "(", "$", "objectUrl", ",", "$", "data", "=", "null", ",", "$", "expectContentType", "=", "null", ")", "{", "$", "url", "=", "$", "this", "->", "apiBase", ".", "'/'", ".", "$", "objectUrl", ";", "return", "$", "this", "...
Makes a GET request to an API object. Used for receiving an existing object or a list of resources.
[ "Makes", "a", "GET", "request", "to", "an", "API", "object", ".", "Used", "for", "receiving", "an", "existing", "object", "or", "a", "list", "of", "resources", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api.php#L295-L303
train
billogram/billogram-v2-api-php-lib
Billogram/Api.php
Api.put
public function put($objectUrl, $data) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest( $url, 'PUT', json_encode($data), array_merge( $this->authHeader(), array('Content-type' => 'application/json') ) ) ); }
php
public function put($objectUrl, $data) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest( $url, 'PUT', json_encode($data), array_merge( $this->authHeader(), array('Content-type' => 'application/json') ) ) ); }
[ "public", "function", "put", "(", "$", "objectUrl", ",", "$", "data", ")", "{", "$", "url", "=", "$", "this", "->", "apiBase", ".", "'/'", ".", "$", "objectUrl", ";", "return", "$", "this", "->", "checkApiResponse", "(", "$", "this", "->", "httpReque...
Makes a PUT request to an API object. Used for updating a single existing object.
[ "Makes", "a", "PUT", "request", "to", "an", "API", "object", ".", "Used", "for", "updating", "a", "single", "existing", "object", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api.php#L332-L347
train
billogram/billogram-v2-api-php-lib
Billogram/Api.php
Api.delete
public function delete($objectUrl) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest( $url, 'DELETE', null, $this->authHeader() ) ); }
php
public function delete($objectUrl) { $url = $this->apiBase . '/' . $objectUrl; return $this->checkApiResponse( $this->httpRequest( $url, 'DELETE', null, $this->authHeader() ) ); }
[ "public", "function", "delete", "(", "$", "objectUrl", ")", "{", "$", "url", "=", "$", "this", "->", "apiBase", ".", "'/'", ".", "$", "objectUrl", ";", "return", "$", "this", "->", "checkApiResponse", "(", "$", "this", "->", "httpRequest", "(", "$", ...
Makes a DELETE request to an API object. Used to delete a single existing object.
[ "Makes", "a", "DELETE", "request", "to", "an", "API", "object", ".", "Used", "to", "delete", "a", "single", "existing", "object", "." ]
0200670e5de0ddf4c3481183a6bd68661b783b8e
https://github.com/billogram/billogram-v2-api-php-lib/blob/0200670e5de0ddf4c3481183a6bd68661b783b8e/Billogram/Api.php#L354-L366
train