id
int32
0
241k
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
228,700
mariano/disque-php
src/Connection/Socket.php
Socket.getSocket
protected function getSocket($host, $port, $timeout) { return stream_socket_client("tcp://{$host}:{$port}", $error, $message, $timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT); }
php
protected function getSocket($host, $port, $timeout) { return stream_socket_client("tcp://{$host}:{$port}", $error, $message, $timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT); }
[ "protected", "function", "getSocket", "(", "$", "host", ",", "$", "port", ",", "$", "timeout", ")", "{", "return", "stream_socket_client", "(", "\"tcp://{$host}:{$port}\"", ",", "$", "error", ",", "$", "message", ",", "$", "timeout", ",", "STREAM_CLIENT_CONNECT", "|", "STREAM_CLIENT_PERSISTENT", ")", ";", "}" ]
Build actual socket @param string $host Host @param int $port Port @param float $timeout Timeout @return resource Socket
[ "Build", "actual", "socket" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Socket.php#L178-L181
228,701
mariano/disque-php
src/Connection/Socket.php
Socket.getType
private function getType($keepWaiting = false) { $type = null; while (!feof($this->socket)) { $type = fgetc($this->socket); if ($type !== false && $type !== '') { break; } $info = stream_get_meta_data($this->socket); if (!$keepWaiting || !$info['timed_out']) { break; } } if ($type === false || $type === '') { throw new ConnectionException('Nothing received while reading from client'); } return $type; }
php
private function getType($keepWaiting = false) { $type = null; while (!feof($this->socket)) { $type = fgetc($this->socket); if ($type !== false && $type !== '') { break; } $info = stream_get_meta_data($this->socket); if (!$keepWaiting || !$info['timed_out']) { break; } } if ($type === false || $type === '') { throw new ConnectionException('Nothing received while reading from client'); } return $type; }
[ "private", "function", "getType", "(", "$", "keepWaiting", "=", "false", ")", "{", "$", "type", "=", "null", ";", "while", "(", "!", "feof", "(", "$", "this", "->", "socket", ")", ")", "{", "$", "type", "=", "fgetc", "(", "$", "this", "->", "socket", ")", ";", "if", "(", "$", "type", "!==", "false", "&&", "$", "type", "!==", "''", ")", "{", "break", ";", "}", "$", "info", "=", "stream_get_meta_data", "(", "$", "this", "->", "socket", ")", ";", "if", "(", "!", "$", "keepWaiting", "||", "!", "$", "info", "[", "'timed_out'", "]", ")", "{", "break", ";", "}", "}", "if", "(", "$", "type", "===", "false", "||", "$", "type", "===", "''", ")", "{", "throw", "new", "ConnectionException", "(", "'Nothing received while reading from client'", ")", ";", "}", "return", "$", "type", ";", "}" ]
Get the first byte from Disque, which contains the data type @param bool $keepWaiting If `true`, timeouts on stream read will be ignored @return string A single char @throws ConnectionException
[ "Get", "the", "first", "byte", "from", "Disque", "which", "contains", "the", "data", "type" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Socket.php#L190-L210
228,702
mariano/disque-php
src/Connection/Socket.php
Socket.getData
private function getData() { $data = fgets($this->socket); if ($data === false || $data === '') { throw new ConnectionException('Nothing received while reading from client'); } return $data; }
php
private function getData() { $data = fgets($this->socket); if ($data === false || $data === '') { throw new ConnectionException('Nothing received while reading from client'); } return $data; }
[ "private", "function", "getData", "(", ")", "{", "$", "data", "=", "fgets", "(", "$", "this", "->", "socket", ")", ";", "if", "(", "$", "data", "===", "false", "||", "$", "data", "===", "''", ")", "{", "throw", "new", "ConnectionException", "(", "'Nothing received while reading from client'", ")", ";", "}", "return", "$", "data", ";", "}" ]
Get a line of data @return string Line of data @throws ConnectionException
[ "Get", "a", "line", "of", "data" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Socket.php#L218-L225
228,703
czim/laravel-cms-upload-module
src/Http/Controllers/FileController.php
FileController.getCustomValidator
protected function getCustomValidator(UploadedFile $file, $rules) { if (null === $rules) { return null; } if ( ! is_array($rules)) { $rules = explode('|', $rules); } return Validator::make(['file' => $file], ['file' => $rules]); }
php
protected function getCustomValidator(UploadedFile $file, $rules) { if (null === $rules) { return null; } if ( ! is_array($rules)) { $rules = explode('|', $rules); } return Validator::make(['file' => $file], ['file' => $rules]); }
[ "protected", "function", "getCustomValidator", "(", "UploadedFile", "$", "file", ",", "$", "rules", ")", "{", "if", "(", "null", "===", "$", "rules", ")", "{", "return", "null", ";", "}", "if", "(", "!", "is_array", "(", "$", "rules", ")", ")", "{", "$", "rules", "=", "explode", "(", "'|'", ",", "$", "rules", ")", ";", "}", "return", "Validator", "::", "make", "(", "[", "'file'", "=>", "$", "file", "]", ",", "[", "'file'", "=>", "$", "rules", "]", ")", ";", "}" ]
Gets a validator for the uploaded file with custom request-specified rules. @param UploadedFile $file @param array|string|null $rules @return \Illuminate\Validation\Validator|null
[ "Gets", "a", "validator", "for", "the", "uploaded", "file", "with", "custom", "request", "-", "specified", "rules", "." ]
3599801efcfdcf9164e8c75c3e1b2c6e7e3692c3
https://github.com/czim/laravel-cms-upload-module/blob/3599801efcfdcf9164e8c75c3e1b2c6e7e3692c3/src/Http/Controllers/FileController.php#L193-L204
228,704
czim/laravel-cms-upload-module
src/Http/Controllers/FileController.php
FileController.performGarbageCollection
protected function performGarbageCollection() { if ( ! config('cms-upload-module.gc.enabled', true)) { return; } list($probability, $total) = config('cms-upload-module.gc.lottery', [0, 0]); if ($probability < 1 || $total < 1 || rand(0, $total) > $probability) { return; } $this->fileRepository->cleanup(); }
php
protected function performGarbageCollection() { if ( ! config('cms-upload-module.gc.enabled', true)) { return; } list($probability, $total) = config('cms-upload-module.gc.lottery', [0, 0]); if ($probability < 1 || $total < 1 || rand(0, $total) > $probability) { return; } $this->fileRepository->cleanup(); }
[ "protected", "function", "performGarbageCollection", "(", ")", "{", "if", "(", "!", "config", "(", "'cms-upload-module.gc.enabled'", ",", "true", ")", ")", "{", "return", ";", "}", "list", "(", "$", "probability", ",", "$", "total", ")", "=", "config", "(", "'cms-upload-module.gc.lottery'", ",", "[", "0", ",", "0", "]", ")", ";", "if", "(", "$", "probability", "<", "1", "||", "$", "total", "<", "1", "||", "rand", "(", "0", ",", "$", "total", ")", ">", "$", "probability", ")", "{", "return", ";", "}", "$", "this", "->", "fileRepository", "->", "cleanup", "(", ")", ";", "}" ]
Performs garbage collection based on lottery.
[ "Performs", "garbage", "collection", "based", "on", "lottery", "." ]
3599801efcfdcf9164e8c75c3e1b2c6e7e3692c3
https://github.com/czim/laravel-cms-upload-module/blob/3599801efcfdcf9164e8c75c3e1b2c6e7e3692c3/src/Http/Controllers/FileController.php#L209-L222
228,705
mariano/disque-php
src/Command/GetJob.php
GetJob.isBlocking
public function isBlocking() { $arguments = $this->getArguments(); $options = end($arguments); if (is_array($options) && !empty($options['nohang'])) { return false; } return true; }
php
public function isBlocking() { $arguments = $this->getArguments(); $options = end($arguments); if (is_array($options) && !empty($options['nohang'])) { return false; } return true; }
[ "public", "function", "isBlocking", "(", ")", "{", "$", "arguments", "=", "$", "this", "->", "getArguments", "(", ")", ";", "$", "options", "=", "end", "(", "$", "arguments", ")", ";", "if", "(", "is_array", "(", "$", "options", ")", "&&", "!", "empty", "(", "$", "options", "[", "'nohang'", "]", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Tells if this command blocks while waiting for a response, to avoid being affected by connection timeouts. @return bool If true, this command blocks
[ "Tells", "if", "this", "command", "blocks", "while", "waiting", "for", "a", "response", "to", "avoid", "being", "affected", "by", "connection", "timeouts", "." ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/GetJob.php#L60-L68
228,706
mariano/disque-php
src/Connection/Manager.php
Manager.findAvailableConnection
protected function findAvailableConnection() { $servers = $this->credentials; shuffle($servers); $previous = null; foreach ($servers as $server) { try { $node = $this->getNodeConnection($server); } catch (ConnectionException $e) { $previous = $e; continue; } if ($node->isConnected()) { return $node; } } throw new ConnectionException('No servers available', 0, $previous); }
php
protected function findAvailableConnection() { $servers = $this->credentials; shuffle($servers); $previous = null; foreach ($servers as $server) { try { $node = $this->getNodeConnection($server); } catch (ConnectionException $e) { $previous = $e; continue; } if ($node->isConnected()) { return $node; } } throw new ConnectionException('No servers available', 0, $previous); }
[ "protected", "function", "findAvailableConnection", "(", ")", "{", "$", "servers", "=", "$", "this", "->", "credentials", ";", "shuffle", "(", "$", "servers", ")", ";", "$", "previous", "=", "null", ";", "foreach", "(", "$", "servers", "as", "$", "server", ")", "{", "try", "{", "$", "node", "=", "$", "this", "->", "getNodeConnection", "(", "$", "server", ")", ";", "}", "catch", "(", "ConnectionException", "$", "e", ")", "{", "$", "previous", "=", "$", "e", ";", "continue", ";", "}", "if", "(", "$", "node", "->", "isConnected", "(", ")", ")", "{", "return", "$", "node", ";", "}", "}", "throw", "new", "ConnectionException", "(", "'No servers available'", ",", "0", ",", "$", "previous", ")", ";", "}" ]
Get a functional connection to any known node Disque suggests the first connection should be chosen randomly We go through the user-supplied credentials randomly and try to connect. @return Node A connected node @throws ConnectionException
[ "Get", "a", "functional", "connection", "to", "any", "known", "node" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L212-L232
228,707
mariano/disque-php
src/Connection/Manager.php
Manager.getNodeConnection
protected function getNodeConnection(Credentials $server) { $node = $this->createNode($server); $node->connect(); return $node; }
php
protected function getNodeConnection(Credentials $server) { $node = $this->createNode($server); $node->connect(); return $node; }
[ "protected", "function", "getNodeConnection", "(", "Credentials", "$", "server", ")", "{", "$", "node", "=", "$", "this", "->", "createNode", "(", "$", "server", ")", ";", "$", "node", "->", "connect", "(", ")", ";", "return", "$", "node", ";", "}" ]
Connect to the node given in the credentials @param Credentials $server @return Node A connected node @throws ConnectionException @throws AuthenticationException
[ "Connect", "to", "the", "node", "given", "in", "the", "credentials" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L244-L249
228,708
mariano/disque-php
src/Connection/Manager.php
Manager.postprocessExecution
protected function postprocessExecution( CommandInterface $command, $response ) { if ($command instanceof GetJob) { $this->updateNodeStats($command->parse($response)); $this->switchNodeIfNeeded(); } return $response; }
php
protected function postprocessExecution( CommandInterface $command, $response ) { if ($command instanceof GetJob) { $this->updateNodeStats($command->parse($response)); $this->switchNodeIfNeeded(); } return $response; }
[ "protected", "function", "postprocessExecution", "(", "CommandInterface", "$", "command", ",", "$", "response", ")", "{", "if", "(", "$", "command", "instanceof", "GetJob", ")", "{", "$", "this", "->", "updateNodeStats", "(", "$", "command", "->", "parse", "(", "$", "response", ")", ")", ";", "$", "this", "->", "switchNodeIfNeeded", "(", ")", ";", "}", "return", "$", "response", ";", "}" ]
Postprocess the command execution, eg. update node stats @param CommandInterface $command @param mixed $response @return mixed @throws ConnectionException
[ "Postprocess", "the", "command", "execution", "eg", ".", "update", "node", "stats" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L284-L294
228,709
mariano/disque-php
src/Connection/Manager.php
Manager.updateNodeStats
protected function updateNodeStats(array $jobs) { foreach ($jobs as $job) { $jobId = $job[JobsResponse::KEY_ID]; $nodeId = $this->getNodeIdFromJobId($jobId); if (!isset($nodeId) || !isset($this->nodes[$nodeId])) { continue; } $node = $this->nodes[$nodeId]; $node->addJobCount(1); } }
php
protected function updateNodeStats(array $jobs) { foreach ($jobs as $job) { $jobId = $job[JobsResponse::KEY_ID]; $nodeId = $this->getNodeIdFromJobId($jobId); if (!isset($nodeId) || !isset($this->nodes[$nodeId])) { continue; } $node = $this->nodes[$nodeId]; $node->addJobCount(1); } }
[ "protected", "function", "updateNodeStats", "(", "array", "$", "jobs", ")", "{", "foreach", "(", "$", "jobs", "as", "$", "job", ")", "{", "$", "jobId", "=", "$", "job", "[", "JobsResponse", "::", "KEY_ID", "]", ";", "$", "nodeId", "=", "$", "this", "->", "getNodeIdFromJobId", "(", "$", "jobId", ")", ";", "if", "(", "!", "isset", "(", "$", "nodeId", ")", "||", "!", "isset", "(", "$", "this", "->", "nodes", "[", "$", "nodeId", "]", ")", ")", "{", "continue", ";", "}", "$", "node", "=", "$", "this", "->", "nodes", "[", "$", "nodeId", "]", ";", "$", "node", "->", "addJobCount", "(", "1", ")", ";", "}", "}" ]
Update node counters indicating how many jobs the node has produced @param array $jobs Jobs
[ "Update", "node", "counters", "indicating", "how", "many", "jobs", "the", "node", "has", "produced" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L301-L313
228,710
mariano/disque-php
src/Connection/Manager.php
Manager.switchNodeIfNeeded
private function switchNodeIfNeeded() { $sortedNodes = $this->priorityStrategy->sort( $this->nodes, $this->nodeId ); $previous = null; // Try to connect by priority, continue on error, return on success foreach($sortedNodes as $nodeCandidate) { // If the first recommended node is our current node and it has // a working connection, return early. // If its connection is not working, let's try and reconnect further // below, or find the first best connected node. if ($nodeCandidate->getId() === $this->nodeId && $nodeCandidate->isConnected()) { return; } try { if ($nodeCandidate->isConnected()) { // Say a new HELLO to the node, the cluster might have changed $nodeCandidate->sayHello(); } else { $nodeCandidate->connect(); } } catch (ConnectionException $e) { $previous = $e; continue; } $this->switchToNode($nodeCandidate); return; } throw new ConnectionException('Could not switch to any node', 0, $previous); }
php
private function switchNodeIfNeeded() { $sortedNodes = $this->priorityStrategy->sort( $this->nodes, $this->nodeId ); $previous = null; // Try to connect by priority, continue on error, return on success foreach($sortedNodes as $nodeCandidate) { // If the first recommended node is our current node and it has // a working connection, return early. // If its connection is not working, let's try and reconnect further // below, or find the first best connected node. if ($nodeCandidate->getId() === $this->nodeId && $nodeCandidate->isConnected()) { return; } try { if ($nodeCandidate->isConnected()) { // Say a new HELLO to the node, the cluster might have changed $nodeCandidate->sayHello(); } else { $nodeCandidate->connect(); } } catch (ConnectionException $e) { $previous = $e; continue; } $this->switchToNode($nodeCandidate); return; } throw new ConnectionException('Could not switch to any node', 0, $previous); }
[ "private", "function", "switchNodeIfNeeded", "(", ")", "{", "$", "sortedNodes", "=", "$", "this", "->", "priorityStrategy", "->", "sort", "(", "$", "this", "->", "nodes", ",", "$", "this", "->", "nodeId", ")", ";", "$", "previous", "=", "null", ";", "// Try to connect by priority, continue on error, return on success", "foreach", "(", "$", "sortedNodes", "as", "$", "nodeCandidate", ")", "{", "// If the first recommended node is our current node and it has", "// a working connection, return early.", "// If its connection is not working, let's try and reconnect further", "// below, or find the first best connected node.", "if", "(", "$", "nodeCandidate", "->", "getId", "(", ")", "===", "$", "this", "->", "nodeId", "&&", "$", "nodeCandidate", "->", "isConnected", "(", ")", ")", "{", "return", ";", "}", "try", "{", "if", "(", "$", "nodeCandidate", "->", "isConnected", "(", ")", ")", "{", "// Say a new HELLO to the node, the cluster might have changed", "$", "nodeCandidate", "->", "sayHello", "(", ")", ";", "}", "else", "{", "$", "nodeCandidate", "->", "connect", "(", ")", ";", "}", "}", "catch", "(", "ConnectionException", "$", "e", ")", "{", "$", "previous", "=", "$", "e", ";", "continue", ";", "}", "$", "this", "->", "switchToNode", "(", "$", "nodeCandidate", ")", ";", "return", ";", "}", "throw", "new", "ConnectionException", "(", "'Could not switch to any node'", ",", "0", ",", "$", "previous", ")", ";", "}" ]
Decide if we should switch to a better node @throws ConnectionException
[ "Decide", "if", "we", "should", "switch", "to", "a", "better", "node" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L320-L357
228,711
mariano/disque-php
src/Connection/Manager.php
Manager.getNodeIdFromJobId
private function getNodeIdFromJobId($jobId) { $nodePrefix = $this->getNodePrefixFromJobId($jobId); if ( isset($this->nodePrefixes[$nodePrefix]) && array_key_exists($this->nodePrefixes[$nodePrefix], $this->nodes) ) { return $this->nodePrefixes[$nodePrefix]; } return null; }
php
private function getNodeIdFromJobId($jobId) { $nodePrefix = $this->getNodePrefixFromJobId($jobId); if ( isset($this->nodePrefixes[$nodePrefix]) && array_key_exists($this->nodePrefixes[$nodePrefix], $this->nodes) ) { return $this->nodePrefixes[$nodePrefix]; } return null; }
[ "private", "function", "getNodeIdFromJobId", "(", "$", "jobId", ")", "{", "$", "nodePrefix", "=", "$", "this", "->", "getNodePrefixFromJobId", "(", "$", "jobId", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "nodePrefixes", "[", "$", "nodePrefix", "]", ")", "&&", "array_key_exists", "(", "$", "this", "->", "nodePrefixes", "[", "$", "nodePrefix", "]", ",", "$", "this", "->", "nodes", ")", ")", "{", "return", "$", "this", "->", "nodePrefixes", "[", "$", "nodePrefix", "]", ";", "}", "return", "null", ";", "}" ]
Get a node ID based off a Job ID @param string $jobId Job ID @return string|null Node ID
[ "Get", "a", "node", "ID", "based", "off", "a", "Job", "ID" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L365-L376
228,712
mariano/disque-php
src/Connection/Manager.php
Manager.getNodePrefixFromJobId
private function getNodePrefixFromJobId($jobId) { $nodePrefix = substr( $jobId, JobsResponse::ID_NODE_PREFIX_START, Node::PREFIX_LENGTH ); return $nodePrefix; }
php
private function getNodePrefixFromJobId($jobId) { $nodePrefix = substr( $jobId, JobsResponse::ID_NODE_PREFIX_START, Node::PREFIX_LENGTH ); return $nodePrefix; }
[ "private", "function", "getNodePrefixFromJobId", "(", "$", "jobId", ")", "{", "$", "nodePrefix", "=", "substr", "(", "$", "jobId", ",", "JobsResponse", "::", "ID_NODE_PREFIX_START", ",", "Node", "::", "PREFIX_LENGTH", ")", ";", "return", "$", "nodePrefix", ";", "}" ]
Get the node prefix from the job ID @param string $jobId @return string Node prefix
[ "Get", "the", "node", "prefix", "from", "the", "job", "ID" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L384-L393
228,713
mariano/disque-php
src/Connection/Manager.php
Manager.shouldBeConnected
protected function shouldBeConnected() { // If we lost the connection, first let's try and reconnect if (!$this->isConnected()) { try { $this->switchNodeIfNeeded(); } catch (ConnectionException $e) { throw new ConnectionException('Not connected. ' . $e->getMessage(), 0, $e); } } }
php
protected function shouldBeConnected() { // If we lost the connection, first let's try and reconnect if (!$this->isConnected()) { try { $this->switchNodeIfNeeded(); } catch (ConnectionException $e) { throw new ConnectionException('Not connected. ' . $e->getMessage(), 0, $e); } } }
[ "protected", "function", "shouldBeConnected", "(", ")", "{", "// If we lost the connection, first let's try and reconnect", "if", "(", "!", "$", "this", "->", "isConnected", "(", ")", ")", "{", "try", "{", "$", "this", "->", "switchNodeIfNeeded", "(", ")", ";", "}", "catch", "(", "ConnectionException", "$", "e", ")", "{", "throw", "new", "ConnectionException", "(", "'Not connected. '", ".", "$", "e", "->", "getMessage", "(", ")", ",", "0", ",", "$", "e", ")", ";", "}", "}", "}" ]
We should be connected @return void @throws ConnectionException
[ "We", "should", "be", "connected" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L401-L411
228,714
mariano/disque-php
src/Connection/Manager.php
Manager.createNode
private function createNode(Credentials $credentials) { $host = $credentials->getHost(); $port = $credentials->getPort(); $connection = $this->connectionFactory->create($host, $port); return new Node($credentials, $connection); }
php
private function createNode(Credentials $credentials) { $host = $credentials->getHost(); $port = $credentials->getPort(); $connection = $this->connectionFactory->create($host, $port); return new Node($credentials, $connection); }
[ "private", "function", "createNode", "(", "Credentials", "$", "credentials", ")", "{", "$", "host", "=", "$", "credentials", "->", "getHost", "(", ")", ";", "$", "port", "=", "$", "credentials", "->", "getPort", "(", ")", ";", "$", "connection", "=", "$", "this", "->", "connectionFactory", "->", "create", "(", "$", "host", ",", "$", "port", ")", ";", "return", "new", "Node", "(", "$", "credentials", ",", "$", "connection", ")", ";", "}" ]
Create a new Node object @param Credentials $credentials @return Node An unconnected Node
[ "Create", "a", "new", "Node", "object" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L420-L427
228,715
mariano/disque-php
src/Connection/Manager.php
Manager.switchToNode
private function switchToNode(Node $node) { $nodeId = $node->getId(); // Return early if we're trying to switch to the current node. if (($this->nodeId === $nodeId)) { // But return early only if the current node is connected to Disque. // If it is disconnected, we want to overwrite it with the node // from the method argument, because that one is connected. if ($this->getCurrentNode()->isConnected()) { return; } // Copy the stats from the now-disconnected node object $this->copyNodeStats($this->getCurrentNode(), $node); } $this->resetNodeCounters(); $this->nodeId = $nodeId; $this->nodes[$nodeId] = $node; $this->revealClusterFromHello($node); }
php
private function switchToNode(Node $node) { $nodeId = $node->getId(); // Return early if we're trying to switch to the current node. if (($this->nodeId === $nodeId)) { // But return early only if the current node is connected to Disque. // If it is disconnected, we want to overwrite it with the node // from the method argument, because that one is connected. if ($this->getCurrentNode()->isConnected()) { return; } // Copy the stats from the now-disconnected node object $this->copyNodeStats($this->getCurrentNode(), $node); } $this->resetNodeCounters(); $this->nodeId = $nodeId; $this->nodes[$nodeId] = $node; $this->revealClusterFromHello($node); }
[ "private", "function", "switchToNode", "(", "Node", "$", "node", ")", "{", "$", "nodeId", "=", "$", "node", "->", "getId", "(", ")", ";", "// Return early if we're trying to switch to the current node.", "if", "(", "(", "$", "this", "->", "nodeId", "===", "$", "nodeId", ")", ")", "{", "// But return early only if the current node is connected to Disque.", "// If it is disconnected, we want to overwrite it with the node", "// from the method argument, because that one is connected.", "if", "(", "$", "this", "->", "getCurrentNode", "(", ")", "->", "isConnected", "(", ")", ")", "{", "return", ";", "}", "// Copy the stats from the now-disconnected node object", "$", "this", "->", "copyNodeStats", "(", "$", "this", "->", "getCurrentNode", "(", ")", ",", "$", "node", ")", ";", "}", "$", "this", "->", "resetNodeCounters", "(", ")", ";", "$", "this", "->", "nodeId", "=", "$", "nodeId", ";", "$", "this", "->", "nodes", "[", "$", "nodeId", "]", "=", "$", "node", ";", "$", "this", "->", "revealClusterFromHello", "(", "$", "node", ")", ";", "}" ]
Switch to the given node and map the cluster from its HELLO @param Node $node
[ "Switch", "to", "the", "given", "node", "and", "map", "the", "cluster", "from", "its", "HELLO" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L434-L455
228,716
mariano/disque-php
src/Connection/Manager.php
Manager.revealClusterFromHello
private function revealClusterFromHello(Node $node) { $hello = $node->getHello(); $revealedNodes = []; foreach ($hello[HelloResponse::NODES] as $node) { $id = $node[HelloResponse::NODE_ID]; $revealedNode = $this->revealNodeFromHello($id, $node); // Update or set the node's priority as determined by Disque $priority = $node[HelloResponse::NODE_PRIORITY]; $revealedNode->setPriority($priority); $revealedNodes[$id] = $revealedNode; } $this->nodes = $revealedNodes; }
php
private function revealClusterFromHello(Node $node) { $hello = $node->getHello(); $revealedNodes = []; foreach ($hello[HelloResponse::NODES] as $node) { $id = $node[HelloResponse::NODE_ID]; $revealedNode = $this->revealNodeFromHello($id, $node); // Update or set the node's priority as determined by Disque $priority = $node[HelloResponse::NODE_PRIORITY]; $revealedNode->setPriority($priority); $revealedNodes[$id] = $revealedNode; } $this->nodes = $revealedNodes; }
[ "private", "function", "revealClusterFromHello", "(", "Node", "$", "node", ")", "{", "$", "hello", "=", "$", "node", "->", "getHello", "(", ")", ";", "$", "revealedNodes", "=", "[", "]", ";", "foreach", "(", "$", "hello", "[", "HelloResponse", "::", "NODES", "]", "as", "$", "node", ")", "{", "$", "id", "=", "$", "node", "[", "HelloResponse", "::", "NODE_ID", "]", ";", "$", "revealedNode", "=", "$", "this", "->", "revealNodeFromHello", "(", "$", "id", ",", "$", "node", ")", ";", "// Update or set the node's priority as determined by Disque", "$", "priority", "=", "$", "node", "[", "HelloResponse", "::", "NODE_PRIORITY", "]", ";", "$", "revealedNode", "->", "setPriority", "(", "$", "priority", ")", ";", "$", "revealedNodes", "[", "$", "id", "]", "=", "$", "revealedNode", ";", "}", "$", "this", "->", "nodes", "=", "$", "revealedNodes", ";", "}" ]
Reveal the whole Disque cluster from a node HELLO response The HELLO response from a Disque node contains addresses of all other nodes in the cluster. We want to learn about them and save them, so that we can switch to them later, if needed. @param Node $node The current node
[ "Reveal", "the", "whole", "Disque", "cluster", "from", "a", "node", "HELLO", "response" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L466-L483
228,717
mariano/disque-php
src/Connection/Manager.php
Manager.revealNodeFromHello
private function revealNodeFromHello($nodeId, array $node) { /** * Add the node prefix to the pool. We create the prefix manually * from the node ID rather than asking the Node object. Newly created * Nodes aren't connected and thus don't know their ID or prefix. * * @see Node::sayHello() */ $prefix = substr($nodeId, Node::PREFIX_START, Node::PREFIX_LENGTH); $this->nodePrefixes[$prefix] = $nodeId; // If the node already exists in our pool, use it, don't overwrite it // with a new one. We would lose its stats and connection. if (isset($this->nodes[$nodeId])) { return $this->nodes[$nodeId]; } $host = $node[HelloResponse::NODE_HOST]; $port = $node[HelloResponse::NODE_PORT]; $credentials = new Credentials($host, $port); $address = $credentials->getAddress(); // If there are user-supplied credentials for this node, use them. // They may contain a password if (isset($this->credentials[$address])) { $credentials = $this->credentials[$address]; } // Instantiate a new Node object for the newly revealed node return $this->createNode($credentials); }
php
private function revealNodeFromHello($nodeId, array $node) { /** * Add the node prefix to the pool. We create the prefix manually * from the node ID rather than asking the Node object. Newly created * Nodes aren't connected and thus don't know their ID or prefix. * * @see Node::sayHello() */ $prefix = substr($nodeId, Node::PREFIX_START, Node::PREFIX_LENGTH); $this->nodePrefixes[$prefix] = $nodeId; // If the node already exists in our pool, use it, don't overwrite it // with a new one. We would lose its stats and connection. if (isset($this->nodes[$nodeId])) { return $this->nodes[$nodeId]; } $host = $node[HelloResponse::NODE_HOST]; $port = $node[HelloResponse::NODE_PORT]; $credentials = new Credentials($host, $port); $address = $credentials->getAddress(); // If there are user-supplied credentials for this node, use them. // They may contain a password if (isset($this->credentials[$address])) { $credentials = $this->credentials[$address]; } // Instantiate a new Node object for the newly revealed node return $this->createNode($credentials); }
[ "private", "function", "revealNodeFromHello", "(", "$", "nodeId", ",", "array", "$", "node", ")", "{", "/**\n * Add the node prefix to the pool. We create the prefix manually\n * from the node ID rather than asking the Node object. Newly created\n * Nodes aren't connected and thus don't know their ID or prefix.\n *\n * @see Node::sayHello()\n */", "$", "prefix", "=", "substr", "(", "$", "nodeId", ",", "Node", "::", "PREFIX_START", ",", "Node", "::", "PREFIX_LENGTH", ")", ";", "$", "this", "->", "nodePrefixes", "[", "$", "prefix", "]", "=", "$", "nodeId", ";", "// If the node already exists in our pool, use it, don't overwrite it", "// with a new one. We would lose its stats and connection.", "if", "(", "isset", "(", "$", "this", "->", "nodes", "[", "$", "nodeId", "]", ")", ")", "{", "return", "$", "this", "->", "nodes", "[", "$", "nodeId", "]", ";", "}", "$", "host", "=", "$", "node", "[", "HelloResponse", "::", "NODE_HOST", "]", ";", "$", "port", "=", "$", "node", "[", "HelloResponse", "::", "NODE_PORT", "]", ";", "$", "credentials", "=", "new", "Credentials", "(", "$", "host", ",", "$", "port", ")", ";", "$", "address", "=", "$", "credentials", "->", "getAddress", "(", ")", ";", "// If there are user-supplied credentials for this node, use them.", "// They may contain a password", "if", "(", "isset", "(", "$", "this", "->", "credentials", "[", "$", "address", "]", ")", ")", "{", "$", "credentials", "=", "$", "this", "->", "credentials", "[", "$", "address", "]", ";", "}", "// Instantiate a new Node object for the newly revealed node", "return", "$", "this", "->", "createNode", "(", "$", "credentials", ")", ";", "}" ]
Reveal a single node from a HELLO response, or use an existing node @param string $nodeId The node ID @param array $node Node information as returned by the HELLO command @return Node $node A node in the current cluster
[ "Reveal", "a", "single", "node", "from", "a", "HELLO", "response", "or", "use", "an", "existing", "node" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L493-L524
228,718
mariano/disque-php
src/Connection/Manager.php
Manager.copyNodeStats
private function copyNodeStats(Node $oldNode, Node $newNode) { $oldNodeJobCount = $oldNode->getTotalJobCount(); $newNode->addJobCount($oldNodeJobCount); }
php
private function copyNodeStats(Node $oldNode, Node $newNode) { $oldNodeJobCount = $oldNode->getTotalJobCount(); $newNode->addJobCount($oldNodeJobCount); }
[ "private", "function", "copyNodeStats", "(", "Node", "$", "oldNode", ",", "Node", "$", "newNode", ")", "{", "$", "oldNodeJobCount", "=", "$", "oldNode", "->", "getTotalJobCount", "(", ")", ";", "$", "newNode", "->", "addJobCount", "(", "$", "oldNodeJobCount", ")", ";", "}" ]
Copy node stats from the old to the new node @param Node $oldNode @param Node $newNode
[ "Copy", "node", "stats", "from", "the", "old", "to", "the", "new", "node" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Connection/Manager.php#L542-L546
228,719
stanislav-web/phalcon-sms-factory
src/SMSFactory/Providers/SmsUkraine.php
SmsUkraine.send
final public function send($message) { $response = $this->client()->{$this->config->getRequestMethod()}($this->config->getMessageUri(), array_merge( $this->config->getProviderConfig(), [ 'command' => 'send', 'to' => $this->recipient, 'message' => $message, ]) ); return $this->getResponse($response); }
php
final public function send($message) { $response = $this->client()->{$this->config->getRequestMethod()}($this->config->getMessageUri(), array_merge( $this->config->getProviderConfig(), [ 'command' => 'send', 'to' => $this->recipient, 'message' => $message, ]) ); return $this->getResponse($response); }
[ "final", "public", "function", "send", "(", "$", "message", ")", "{", "$", "response", "=", "$", "this", "->", "client", "(", ")", "->", "{", "$", "this", "->", "config", "->", "getRequestMethod", "(", ")", "}", "(", "$", "this", "->", "config", "->", "getMessageUri", "(", ")", ",", "array_merge", "(", "$", "this", "->", "config", "->", "getProviderConfig", "(", ")", ",", "[", "'command'", "=>", "'send'", ",", "'to'", "=>", "$", "this", "->", "recipient", ",", "'message'", "=>", "$", "message", ",", "]", ")", ")", ";", "return", "$", "this", "->", "getResponse", "(", "$", "response", ")", ";", "}" ]
Final send function @param string $message @return \Phalcon\Http\Client\Response|string
[ "Final", "send", "function" ]
75e5b61819ae24705e87073508f99341b64da2cd
https://github.com/stanislav-web/phalcon-sms-factory/blob/75e5b61819ae24705e87073508f99341b64da2cd/src/SMSFactory/Providers/SmsUkraine.php#L95-L107
228,720
jeremeamia/FunctionParser
src/FunctionParser.php
FunctionParser.fromCallable
public static function fromCallable($callable) { if (!is_callable($callable)) { throw new \InvalidArgumentException('You must provide a vaild PHP callable.'); } elseif (is_string($callable) && strpos($callable, '::') > 0) { $callable = explode('::', $callable); } if (is_array($callable)) { list($class, $method) = $callable; $reflection = new \ReflectionMethod($class, $method); } else { $reflection = new \ReflectionFunction($callable); } return new static($reflection); }
php
public static function fromCallable($callable) { if (!is_callable($callable)) { throw new \InvalidArgumentException('You must provide a vaild PHP callable.'); } elseif (is_string($callable) && strpos($callable, '::') > 0) { $callable = explode('::', $callable); } if (is_array($callable)) { list($class, $method) = $callable; $reflection = new \ReflectionMethod($class, $method); } else { $reflection = new \ReflectionFunction($callable); } return new static($reflection); }
[ "public", "static", "function", "fromCallable", "(", "$", "callable", ")", "{", "if", "(", "!", "is_callable", "(", "$", "callable", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'You must provide a vaild PHP callable.'", ")", ";", "}", "elseif", "(", "is_string", "(", "$", "callable", ")", "&&", "strpos", "(", "$", "callable", ",", "'::'", ")", ">", "0", ")", "{", "$", "callable", "=", "explode", "(", "'::'", ",", "$", "callable", ")", ";", "}", "if", "(", "is_array", "(", "$", "callable", ")", ")", "{", "list", "(", "$", "class", ",", "$", "method", ")", "=", "$", "callable", ";", "$", "reflection", "=", "new", "\\", "ReflectionMethod", "(", "$", "class", ",", "$", "method", ")", ";", "}", "else", "{", "$", "reflection", "=", "new", "\\", "ReflectionFunction", "(", "$", "callable", ")", ";", "}", "return", "new", "static", "(", "$", "reflection", ")", ";", "}" ]
A factory method that creates a FunctionParser from any PHP callable. @param mixed $callable A PHP callable to be parsed. @return FunctionParser An instance of FunctionParser. @throws \InvalidArgumentException
[ "A", "factory", "method", "that", "creates", "a", "FunctionParser", "from", "any", "PHP", "callable", "." ]
035b52000b88ea8d72a6647dd4cd39f080cf7ada
https://github.com/jeremeamia/FunctionParser/blob/035b52000b88ea8d72a6647dd4cd39f080cf7ada/src/FunctionParser.php#L55-L77
228,721
jeremeamia/FunctionParser
src/FunctionParser.php
FunctionParser.getName
public function getName() { $name = $this->reflection->getName(); if (strpos($name, '{closure}') !== false) { return null; } return $name; }
php
public function getName() { $name = $this->reflection->getName(); if (strpos($name, '{closure}') !== false) { return null; } return $name; }
[ "public", "function", "getName", "(", ")", "{", "$", "name", "=", "$", "this", "->", "reflection", "->", "getName", "(", ")", ";", "if", "(", "strpos", "(", "$", "name", ",", "'{closure}'", ")", "!==", "false", ")", "{", "return", "null", ";", "}", "return", "$", "name", ";", "}" ]
Returns the name of the function, if there is one. @return null|string The name of the function.
[ "Returns", "the", "name", "of", "the", "function", "if", "there", "is", "one", "." ]
035b52000b88ea8d72a6647dd4cd39f080cf7ada
https://github.com/jeremeamia/FunctionParser/blob/035b52000b88ea8d72a6647dd4cd39f080cf7ada/src/FunctionParser.php#L114-L124
228,722
jeremeamia/FunctionParser
src/FunctionParser.php
FunctionParser.fetchTokenizer
protected function fetchTokenizer() { // Load the file containing the code for the function $file = new \SplFileObject($this->reflection->getFileName()); // Identify the first and last lines of the code for the function $first_line = $this->reflection->getStartLine(); $last_line = $this->reflection->getEndLine(); // Retrieve all of the lines that contain code for the function $code = ''; $file->seek($first_line - 1); while ($file->key() < $last_line) { $code .= $file->current(); $file->next(); } // Setup the tokenizer with the code from the file $tokenizer = new Tokenizer($code); // Eliminate tokens that are definitely not a part of the function code $start = $tokenizer->findToken(T_FUNCTION); $finish = $tokenizer->findToken('}', -1); $tokenizer = $tokenizer->getTokenRange($start, $finish + 1); return $tokenizer; }
php
protected function fetchTokenizer() { // Load the file containing the code for the function $file = new \SplFileObject($this->reflection->getFileName()); // Identify the first and last lines of the code for the function $first_line = $this->reflection->getStartLine(); $last_line = $this->reflection->getEndLine(); // Retrieve all of the lines that contain code for the function $code = ''; $file->seek($first_line - 1); while ($file->key() < $last_line) { $code .= $file->current(); $file->next(); } // Setup the tokenizer with the code from the file $tokenizer = new Tokenizer($code); // Eliminate tokens that are definitely not a part of the function code $start = $tokenizer->findToken(T_FUNCTION); $finish = $tokenizer->findToken('}', -1); $tokenizer = $tokenizer->getTokenRange($start, $finish + 1); return $tokenizer; }
[ "protected", "function", "fetchTokenizer", "(", ")", "{", "// Load the file containing the code for the function", "$", "file", "=", "new", "\\", "SplFileObject", "(", "$", "this", "->", "reflection", "->", "getFileName", "(", ")", ")", ";", "// Identify the first and last lines of the code for the function", "$", "first_line", "=", "$", "this", "->", "reflection", "->", "getStartLine", "(", ")", ";", "$", "last_line", "=", "$", "this", "->", "reflection", "->", "getEndLine", "(", ")", ";", "// Retrieve all of the lines that contain code for the function", "$", "code", "=", "''", ";", "$", "file", "->", "seek", "(", "$", "first_line", "-", "1", ")", ";", "while", "(", "$", "file", "->", "key", "(", ")", "<", "$", "last_line", ")", "{", "$", "code", ".=", "$", "file", "->", "current", "(", ")", ";", "$", "file", "->", "next", "(", ")", ";", "}", "// Setup the tokenizer with the code from the file", "$", "tokenizer", "=", "new", "Tokenizer", "(", "$", "code", ")", ";", "// Eliminate tokens that are definitely not a part of the function code", "$", "start", "=", "$", "tokenizer", "->", "findToken", "(", "T_FUNCTION", ")", ";", "$", "finish", "=", "$", "tokenizer", "->", "findToken", "(", "'}'", ",", "-", "1", ")", ";", "$", "tokenizer", "=", "$", "tokenizer", "->", "getTokenRange", "(", "$", "start", ",", "$", "finish", "+", "1", ")", ";", "return", "$", "tokenizer", ";", "}" ]
Creates a tokenizer representing the code that is the best candidate for representing the function. It uses reflection to find the file and lines of the code and then puts that code into the tokenizer. @return \FunctionParser\Tokenizer The tokenizer of the function's code.
[ "Creates", "a", "tokenizer", "representing", "the", "code", "that", "is", "the", "best", "candidate", "for", "representing", "the", "function", ".", "It", "uses", "reflection", "to", "find", "the", "file", "and", "lines", "of", "the", "code", "and", "then", "puts", "that", "code", "into", "the", "tokenizer", "." ]
035b52000b88ea8d72a6647dd4cd39f080cf7ada
https://github.com/jeremeamia/FunctionParser/blob/035b52000b88ea8d72a6647dd4cd39f080cf7ada/src/FunctionParser.php#L215-L242
228,723
jeremeamia/FunctionParser
src/FunctionParser.php
FunctionParser.parseCode
protected function parseCode() { $brace_level = 0; $parsed_code = ''; $parsing_complete = false; // Parse the code looking for the end of the function /** @var $token \FunctionParser\Token */ foreach ($this->tokenizer as $token) { /*********************************************************************************************************** * AFTER PARSING * * After the parsing is complete, we need to make sure there are no other T_FUNCTION tokens found, which * would indicate a possible ambiguity in the function code we retrieved. This should only happen in * situations where the code is minified or poorly formatted. */ if ($parsing_complete) { if ($token->is(T_FUNCTION)) { throw new \RuntimeException('Cannot parse the function; multiple, non-nested functions were defined' . ' in the code block containing the desired function.'); } else { continue; } } /*********************************************************************************************************** * WHILE PARSING * * Scan through the tokens (while keeping track of braces) and reconstruct the code from the parsed tokens. */ // Keep track of opening and closing braces if ($token->isOpeningBrace()) { $brace_level++; } elseif ($token->isClosingBrace()) { $brace_level--; // Once we reach the function's closing brace, mark as complete if ($brace_level === 0) { $parsing_complete = true; } } // Reconstruct the code token by token $parsed_code .= $token->code; } /* * If all tokens have been looked at and the closing brace was not found, then there is a * problem with the code defining the Closure. This should probably never happen, but just * in case... */ if (!$parsing_complete) { // @codeCoverageIgnoreStart throw new \RuntimeException('Cannot parse the function because the code appeared to be invalid.'); // @codeCoverageIgnoreEnd } return $parsed_code; }
php
protected function parseCode() { $brace_level = 0; $parsed_code = ''; $parsing_complete = false; // Parse the code looking for the end of the function /** @var $token \FunctionParser\Token */ foreach ($this->tokenizer as $token) { /*********************************************************************************************************** * AFTER PARSING * * After the parsing is complete, we need to make sure there are no other T_FUNCTION tokens found, which * would indicate a possible ambiguity in the function code we retrieved. This should only happen in * situations where the code is minified or poorly formatted. */ if ($parsing_complete) { if ($token->is(T_FUNCTION)) { throw new \RuntimeException('Cannot parse the function; multiple, non-nested functions were defined' . ' in the code block containing the desired function.'); } else { continue; } } /*********************************************************************************************************** * WHILE PARSING * * Scan through the tokens (while keeping track of braces) and reconstruct the code from the parsed tokens. */ // Keep track of opening and closing braces if ($token->isOpeningBrace()) { $brace_level++; } elseif ($token->isClosingBrace()) { $brace_level--; // Once we reach the function's closing brace, mark as complete if ($brace_level === 0) { $parsing_complete = true; } } // Reconstruct the code token by token $parsed_code .= $token->code; } /* * If all tokens have been looked at and the closing brace was not found, then there is a * problem with the code defining the Closure. This should probably never happen, but just * in case... */ if (!$parsing_complete) { // @codeCoverageIgnoreStart throw new \RuntimeException('Cannot parse the function because the code appeared to be invalid.'); // @codeCoverageIgnoreEnd } return $parsed_code; }
[ "protected", "function", "parseCode", "(", ")", "{", "$", "brace_level", "=", "0", ";", "$", "parsed_code", "=", "''", ";", "$", "parsing_complete", "=", "false", ";", "// Parse the code looking for the end of the function", "/** @var $token \\FunctionParser\\Token */", "foreach", "(", "$", "this", "->", "tokenizer", "as", "$", "token", ")", "{", "/***********************************************************************************************************\n * AFTER PARSING\n *\n * After the parsing is complete, we need to make sure there are no other T_FUNCTION tokens found, which\n * would indicate a possible ambiguity in the function code we retrieved. This should only happen in\n * situations where the code is minified or poorly formatted.\n */", "if", "(", "$", "parsing_complete", ")", "{", "if", "(", "$", "token", "->", "is", "(", "T_FUNCTION", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot parse the function; multiple, non-nested functions were defined'", ".", "' in the code block containing the desired function.'", ")", ";", "}", "else", "{", "continue", ";", "}", "}", "/***********************************************************************************************************\n * WHILE PARSING\n *\n * Scan through the tokens (while keeping track of braces) and reconstruct the code from the parsed tokens.\n */", "// Keep track of opening and closing braces", "if", "(", "$", "token", "->", "isOpeningBrace", "(", ")", ")", "{", "$", "brace_level", "++", ";", "}", "elseif", "(", "$", "token", "->", "isClosingBrace", "(", ")", ")", "{", "$", "brace_level", "--", ";", "// Once we reach the function's closing brace, mark as complete", "if", "(", "$", "brace_level", "===", "0", ")", "{", "$", "parsing_complete", "=", "true", ";", "}", "}", "// Reconstruct the code token by token", "$", "parsed_code", ".=", "$", "token", "->", "code", ";", "}", "/*\n * If all tokens have been looked at and the closing brace was not found, then there is a\n * problem with the code defining the Closure. This should probably never happen, but just\n * in case...\n */", "if", "(", "!", "$", "parsing_complete", ")", "{", "// @codeCoverageIgnoreStart", "throw", "new", "\\", "RuntimeException", "(", "'Cannot parse the function because the code appeared to be invalid.'", ")", ";", "// @codeCoverageIgnoreEnd", "}", "return", "$", "parsed_code", ";", "}" ]
Parses the code using the tokenizer and keeping track of matching braces. @return string The code representing the function. @throws \RuntimeException on invalid code.
[ "Parses", "the", "code", "using", "the", "tokenizer", "and", "keeping", "track", "of", "matching", "braces", "." ]
035b52000b88ea8d72a6647dd4cd39f080cf7ada
https://github.com/jeremeamia/FunctionParser/blob/035b52000b88ea8d72a6647dd4cd39f080cf7ada/src/FunctionParser.php#L250-L319
228,724
jeremeamia/FunctionParser
src/FunctionParser.php
FunctionParser.parseBody
protected function parseBody() { // Remove the function signature and outer braces $start = strpos($this->code, '{'); $finish = strrpos($this->code, '}'); $body = ltrim(rtrim(substr($this->code, $start + 1, $finish - $start - 1)), "\n"); return $body; }
php
protected function parseBody() { // Remove the function signature and outer braces $start = strpos($this->code, '{'); $finish = strrpos($this->code, '}'); $body = ltrim(rtrim(substr($this->code, $start + 1, $finish - $start - 1)), "\n"); return $body; }
[ "protected", "function", "parseBody", "(", ")", "{", "// Remove the function signature and outer braces", "$", "start", "=", "strpos", "(", "$", "this", "->", "code", ",", "'{'", ")", ";", "$", "finish", "=", "strrpos", "(", "$", "this", "->", "code", ",", "'}'", ")", ";", "$", "body", "=", "ltrim", "(", "rtrim", "(", "substr", "(", "$", "this", "->", "code", ",", "$", "start", "+", "1", ",", "$", "finish", "-", "$", "start", "-", "1", ")", ")", ",", "\"\\n\"", ")", ";", "return", "$", "body", ";", "}" ]
Removes the function signature and braces to expose only the procedural body of the function. @return string The body of the function.
[ "Removes", "the", "function", "signature", "and", "braces", "to", "expose", "only", "the", "procedural", "body", "of", "the", "function", "." ]
035b52000b88ea8d72a6647dd4cd39f080cf7ada
https://github.com/jeremeamia/FunctionParser/blob/035b52000b88ea8d72a6647dd4cd39f080cf7ada/src/FunctionParser.php#L326-L334
228,725
sokil/php-fraud-detect
src/Detector.php
Detector.check
public function check() { $this->state = self::STATE_UNCHECKED; // check all conditions /* @var $processor \Sokil\FraudDetector\ProcessorInterface */ foreach($this->processorDeclarationList->getKeys() as $processorName) { $processor = $this->getProcessor($processorName); if($processor->isPassed()) { $processor->afterCheckPassed(); $this->trigger(self::STATE_PASSED . ':' . $processorName); // check passed if all processors passes their cheks if ($this->state === self::STATE_UNCHECKED) { $this->state = self::STATE_PASSED; } } else { $processor->afterCheckFailed(); $this->trigger(self::STATE_FAILED . ':' . $processorName); // if any processor failed - all check failed $this->state = self::STATE_FAILED; } } $this->trigger($this->state); }
php
public function check() { $this->state = self::STATE_UNCHECKED; // check all conditions /* @var $processor \Sokil\FraudDetector\ProcessorInterface */ foreach($this->processorDeclarationList->getKeys() as $processorName) { $processor = $this->getProcessor($processorName); if($processor->isPassed()) { $processor->afterCheckPassed(); $this->trigger(self::STATE_PASSED . ':' . $processorName); // check passed if all processors passes their cheks if ($this->state === self::STATE_UNCHECKED) { $this->state = self::STATE_PASSED; } } else { $processor->afterCheckFailed(); $this->trigger(self::STATE_FAILED . ':' . $processorName); // if any processor failed - all check failed $this->state = self::STATE_FAILED; } } $this->trigger($this->state); }
[ "public", "function", "check", "(", ")", "{", "$", "this", "->", "state", "=", "self", "::", "STATE_UNCHECKED", ";", "// check all conditions", "/* @var $processor \\Sokil\\FraudDetector\\ProcessorInterface */", "foreach", "(", "$", "this", "->", "processorDeclarationList", "->", "getKeys", "(", ")", "as", "$", "processorName", ")", "{", "$", "processor", "=", "$", "this", "->", "getProcessor", "(", "$", "processorName", ")", ";", "if", "(", "$", "processor", "->", "isPassed", "(", ")", ")", "{", "$", "processor", "->", "afterCheckPassed", "(", ")", ";", "$", "this", "->", "trigger", "(", "self", "::", "STATE_PASSED", ".", "':'", ".", "$", "processorName", ")", ";", "// check passed if all processors passes their cheks", "if", "(", "$", "this", "->", "state", "===", "self", "::", "STATE_UNCHECKED", ")", "{", "$", "this", "->", "state", "=", "self", "::", "STATE_PASSED", ";", "}", "}", "else", "{", "$", "processor", "->", "afterCheckFailed", "(", ")", ";", "$", "this", "->", "trigger", "(", "self", "::", "STATE_FAILED", ".", "':'", ".", "$", "processorName", ")", ";", "// if any processor failed - all check failed", "$", "this", "->", "state", "=", "self", "::", "STATE_FAILED", ";", "}", "}", "$", "this", "->", "trigger", "(", "$", "this", "->", "state", ")", ";", "}" ]
Check if request is not fraud
[ "Check", "if", "request", "is", "not", "fraud" ]
b92f99fff7432febb813a9162748fa3b299c8474
https://github.com/sokil/php-fraud-detect/blob/b92f99fff7432febb813a9162748fa3b299c8474/src/Detector.php#L79-L105
228,726
sokil/php-fraud-detect
src/Detector.php
Detector.declareProcessor
public function declareProcessor($name, $callable = null, $priority = 0) { $this->processorDeclarationList->set($name, $callable, $priority); return $this; }
php
public function declareProcessor($name, $callable = null, $priority = 0) { $this->processorDeclarationList->set($name, $callable, $priority); return $this; }
[ "public", "function", "declareProcessor", "(", "$", "name", ",", "$", "callable", "=", "null", ",", "$", "priority", "=", "0", ")", "{", "$", "this", "->", "processorDeclarationList", "->", "set", "(", "$", "name", ",", "$", "callable", ",", "$", "priority", ")", ";", "return", "$", "this", ";", "}" ]
Add processor identified by its name. If processor already added, it will be replaced by new instance. @param string $name name of processor @param callable $callable configurator callable @return \Sokil\FraudDetector\Detector
[ "Add", "processor", "identified", "by", "its", "name", ".", "If", "processor", "already", "added", "it", "will", "be", "replaced", "by", "new", "instance", "." ]
b92f99fff7432febb813a9162748fa3b299c8474
https://github.com/sokil/php-fraud-detect/blob/b92f99fff7432febb813a9162748fa3b299c8474/src/Detector.php#L121-L125
228,727
sokil/php-fraud-detect
src/Detector.php
Detector.getProcessorClassName
private function getProcessorClassName($name) { $className = ucfirst($name) . 'Processor'; foreach($this->processorNamespaces as $namespace) { $fullyQualifiedClassName = $namespace . '\\' . $className; if(class_exists($fullyQualifiedClassName)) { return $fullyQualifiedClassName; } } throw new \Exception('Class ' . $fullyQualifiedClassName . ' not found'); }
php
private function getProcessorClassName($name) { $className = ucfirst($name) . 'Processor'; foreach($this->processorNamespaces as $namespace) { $fullyQualifiedClassName = $namespace . '\\' . $className; if(class_exists($fullyQualifiedClassName)) { return $fullyQualifiedClassName; } } throw new \Exception('Class ' . $fullyQualifiedClassName . ' not found'); }
[ "private", "function", "getProcessorClassName", "(", "$", "name", ")", "{", "$", "className", "=", "ucfirst", "(", "$", "name", ")", ".", "'Processor'", ";", "foreach", "(", "$", "this", "->", "processorNamespaces", "as", "$", "namespace", ")", "{", "$", "fullyQualifiedClassName", "=", "$", "namespace", ".", "'\\\\'", ".", "$", "className", ";", "if", "(", "class_exists", "(", "$", "fullyQualifiedClassName", ")", ")", "{", "return", "$", "fullyQualifiedClassName", ";", "}", "}", "throw", "new", "\\", "Exception", "(", "'Class '", ".", "$", "fullyQualifiedClassName", ".", "' not found'", ")", ";", "}" ]
Factory method to create new check condition @param string $name name of check condition @return \Sokil\FraudDetector\ProcessorInterface @throws \Exception
[ "Factory", "method", "to", "create", "new", "check", "condition" ]
b92f99fff7432febb813a9162748fa3b299c8474
https://github.com/sokil/php-fraud-detect/blob/b92f99fff7432febb813a9162748fa3b299c8474/src/Detector.php#L147-L159
228,728
sop/crypto-types
lib/CryptoTypes/Asymmetric/EC/ECConversion.php
ECConversion.bitStringToOctetString
public static function bitStringToOctetString(BitString $bs): OctetString { $str = $bs->string(); if ($bs->unusedBits()) { // @todo pad string throw new \RuntimeException("Unaligned bitstrings to supported"); } return new OctetString($str); }
php
public static function bitStringToOctetString(BitString $bs): OctetString { $str = $bs->string(); if ($bs->unusedBits()) { // @todo pad string throw new \RuntimeException("Unaligned bitstrings to supported"); } return new OctetString($str); }
[ "public", "static", "function", "bitStringToOctetString", "(", "BitString", "$", "bs", ")", ":", "OctetString", "{", "$", "str", "=", "$", "bs", "->", "string", "(", ")", ";", "if", "(", "$", "bs", "->", "unusedBits", "(", ")", ")", "{", "// @todo pad string", "throw", "new", "\\", "RuntimeException", "(", "\"Unaligned bitstrings to supported\"", ")", ";", "}", "return", "new", "OctetString", "(", "$", "str", ")", ";", "}" ]
Perform Bit-String-to-Octet-String Conversion. Defined in SEC 1 section 2.3.1. @param BitString $bs @throws \RuntimeException @return OctetString
[ "Perform", "Bit", "-", "String", "-", "to", "-", "Octet", "-", "String", "Conversion", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/EC/ECConversion.php#L27-L35
228,729
sop/crypto-types
lib/CryptoTypes/Asymmetric/EC/ECConversion.php
ECConversion.integerToOctetString
public static function integerToOctetString(Integer $num, $mlen = null): OctetString { $gmp = gmp_init($num->number(), 10); $str = gmp_export($gmp, 1, GMP_MSW_FIRST | GMP_BIG_ENDIAN); if (null !== $mlen) { $len = strlen($str); if ($len > $mlen) { throw new \RangeException("Number is too large."); } // pad with zeroes if ($len < $mlen) { $str = str_repeat("\0", $mlen - $len) . $str; } } return new OctetString($str); }
php
public static function integerToOctetString(Integer $num, $mlen = null): OctetString { $gmp = gmp_init($num->number(), 10); $str = gmp_export($gmp, 1, GMP_MSW_FIRST | GMP_BIG_ENDIAN); if (null !== $mlen) { $len = strlen($str); if ($len > $mlen) { throw new \RangeException("Number is too large."); } // pad with zeroes if ($len < $mlen) { $str = str_repeat("\0", $mlen - $len) . $str; } } return new OctetString($str); }
[ "public", "static", "function", "integerToOctetString", "(", "Integer", "$", "num", ",", "$", "mlen", "=", "null", ")", ":", "OctetString", "{", "$", "gmp", "=", "gmp_init", "(", "$", "num", "->", "number", "(", ")", ",", "10", ")", ";", "$", "str", "=", "gmp_export", "(", "$", "gmp", ",", "1", ",", "GMP_MSW_FIRST", "|", "GMP_BIG_ENDIAN", ")", ";", "if", "(", "null", "!==", "$", "mlen", ")", "{", "$", "len", "=", "strlen", "(", "$", "str", ")", ";", "if", "(", "$", "len", ">", "$", "mlen", ")", "{", "throw", "new", "\\", "RangeException", "(", "\"Number is too large.\"", ")", ";", "}", "// pad with zeroes", "if", "(", "$", "len", "<", "$", "mlen", ")", "{", "$", "str", "=", "str_repeat", "(", "\"\\0\"", ",", "$", "mlen", "-", "$", "len", ")", ".", "$", "str", ";", "}", "}", "return", "new", "OctetString", "(", "$", "str", ")", ";", "}" ]
Perform Integer-to-Octet-String Conversion. Defined in SEC 1 section 2.3.7. @param Integer $num @param int|null $mlen Optional desired output length @throws \UnexpectedValueException @return OctetString
[ "Perform", "Integer", "-", "to", "-", "Octet", "-", "String", "Conversion", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/EC/ECConversion.php#L60-L75
228,730
sop/crypto-types
lib/CryptoTypes/Asymmetric/EC/ECConversion.php
ECConversion.octetStringToInteger
public static function octetStringToInteger(OctetString $os): Integer { $num = gmp_import($os->string(), 1, GMP_MSW_FIRST | GMP_BIG_ENDIAN); return new Integer(gmp_strval($num, 10)); }
php
public static function octetStringToInteger(OctetString $os): Integer { $num = gmp_import($os->string(), 1, GMP_MSW_FIRST | GMP_BIG_ENDIAN); return new Integer(gmp_strval($num, 10)); }
[ "public", "static", "function", "octetStringToInteger", "(", "OctetString", "$", "os", ")", ":", "Integer", "{", "$", "num", "=", "gmp_import", "(", "$", "os", "->", "string", "(", ")", ",", "1", ",", "GMP_MSW_FIRST", "|", "GMP_BIG_ENDIAN", ")", ";", "return", "new", "Integer", "(", "gmp_strval", "(", "$", "num", ",", "10", ")", ")", ";", "}" ]
Perform Octet-String-to-Integer Conversion. Defined in SEC 1 section 2.3.8. @param OctetString $os @return Integer
[ "Perform", "Octet", "-", "String", "-", "to", "-", "Integer", "Conversion", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/EC/ECConversion.php#L85-L89
228,731
sop/crypto-types
lib/CryptoTypes/Asymmetric/EC/ECConversion.php
ECConversion.numberToOctets
public static function numberToOctets($num, $mlen = null): string { return self::integerToOctetString(new Integer($num), $mlen)->string(); }
php
public static function numberToOctets($num, $mlen = null): string { return self::integerToOctetString(new Integer($num), $mlen)->string(); }
[ "public", "static", "function", "numberToOctets", "(", "$", "num", ",", "$", "mlen", "=", "null", ")", ":", "string", "{", "return", "self", "::", "integerToOctetString", "(", "new", "Integer", "(", "$", "num", ")", ",", "$", "mlen", ")", "->", "string", "(", ")", ";", "}" ]
Convert a base-10 number to octets. This is a convenicence method for integer <-> octet string conversion without the need for external ASN.1 dependencies. @param int|string $num Number in base-10 @param int|null $mlen Optional desired output length @return string
[ "Convert", "a", "base", "-", "10", "number", "to", "octets", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/EC/ECConversion.php#L101-L104
228,732
sudocode/ohmy-auth
src/ohmy/Auth/Promise.php
Promise._resolve
public function _resolve($value) { if ($this->state === self::PENDING) { $this->value = $value; for ($i = 0; $i < count($this->success_pending); $i++) { $callback = $this->success_pending[$i]; $callback($value); } $this->state = self::RESOLVED; } }
php
public function _resolve($value) { if ($this->state === self::PENDING) { $this->value = $value; for ($i = 0; $i < count($this->success_pending); $i++) { $callback = $this->success_pending[$i]; $callback($value); } $this->state = self::RESOLVED; } }
[ "public", "function", "_resolve", "(", "$", "value", ")", "{", "if", "(", "$", "this", "->", "state", "===", "self", "::", "PENDING", ")", "{", "$", "this", "->", "value", "=", "$", "value", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "this", "->", "success_pending", ")", ";", "$", "i", "++", ")", "{", "$", "callback", "=", "$", "this", "->", "success_pending", "[", "$", "i", "]", ";", "$", "callback", "(", "$", "value", ")", ";", "}", "$", "this", "->", "state", "=", "self", "::", "RESOLVED", ";", "}", "}" ]
Dispatch queued callbacks. Also sets state to RESOLVED. @param $value
[ "Dispatch", "queued", "callbacks", ".", "Also", "sets", "state", "to", "RESOLVED", "." ]
8536acc01fef30737e2a66af1a3d037d5fb5c6ad
https://github.com/sudocode/ohmy-auth/blob/8536acc01fef30737e2a66af1a3d037d5fb5c6ad/src/ohmy/Auth/Promise.php#L35-L44
228,733
sudocode/ohmy-auth
src/ohmy/Auth/Promise.php
Promise._reject
public function _reject($value) { if ($this->state === self::PENDING) { $this->value = $value; for ($i = 0; $i < count($this->failure_pending); $i++) { $callback = $this->failure_pending[$i]; $callback($value); } $this->state = self::REJECTED; } }
php
public function _reject($value) { if ($this->state === self::PENDING) { $this->value = $value; for ($i = 0; $i < count($this->failure_pending); $i++) { $callback = $this->failure_pending[$i]; $callback($value); } $this->state = self::REJECTED; } }
[ "public", "function", "_reject", "(", "$", "value", ")", "{", "if", "(", "$", "this", "->", "state", "===", "self", "::", "PENDING", ")", "{", "$", "this", "->", "value", "=", "$", "value", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "this", "->", "failure_pending", ")", ";", "$", "i", "++", ")", "{", "$", "callback", "=", "$", "this", "->", "failure_pending", "[", "$", "i", "]", ";", "$", "callback", "(", "$", "value", ")", ";", "}", "$", "this", "->", "state", "=", "self", "::", "REJECTED", ";", "}", "}" ]
Dispatch queued callbacks. Also sets state to REJECTED. @param $value
[ "Dispatch", "queued", "callbacks", ".", "Also", "sets", "state", "to", "REJECTED", "." ]
8536acc01fef30737e2a66af1a3d037d5fb5c6ad
https://github.com/sudocode/ohmy-auth/blob/8536acc01fef30737e2a66af1a3d037d5fb5c6ad/src/ohmy/Auth/Promise.php#L73-L82
228,734
sudocode/ohmy-auth
src/ohmy/Auth/Promise.php
Promise._catch
private function _catch($callback) { if ($this->state === self::REJECTED) { $this->value = $callback($this->value); } return $this; }
php
private function _catch($callback) { if ($this->state === self::REJECTED) { $this->value = $callback($this->value); } return $this; }
[ "private", "function", "_catch", "(", "$", "callback", ")", "{", "if", "(", "$", "this", "->", "state", "===", "self", "::", "REJECTED", ")", "{", "$", "this", "->", "value", "=", "$", "callback", "(", "$", "this", "->", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Execute a callback if the promise has been rejected. @param $callback @return $this
[ "Execute", "a", "callback", "if", "the", "promise", "has", "been", "rejected", "." ]
8536acc01fef30737e2a66af1a3d037d5fb5c6ad
https://github.com/sudocode/ohmy-auth/blob/8536acc01fef30737e2a66af1a3d037d5fb5c6ad/src/ohmy/Auth/Promise.php#L119-L124
228,735
sudocode/ohmy-auth
src/ohmy/Auth/Promise.php
Promise._finally
private function _finally($callback) { if ($this->state !== self::PENDING) { $callback($this->value); } return $this; }
php
private function _finally($callback) { if ($this->state !== self::PENDING) { $callback($this->value); } return $this; }
[ "private", "function", "_finally", "(", "$", "callback", ")", "{", "if", "(", "$", "this", "->", "state", "!==", "self", "::", "PENDING", ")", "{", "$", "callback", "(", "$", "this", "->", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Execute a callback without changing value of promise. @param $callback @return $this
[ "Execute", "a", "callback", "without", "changing", "value", "of", "promise", "." ]
8536acc01fef30737e2a66af1a3d037d5fb5c6ad
https://github.com/sudocode/ohmy-auth/blob/8536acc01fef30737e2a66af1a3d037d5fb5c6ad/src/ohmy/Auth/Promise.php#L131-L136
228,736
contao-bootstrap/templates
src/View/FormRenderer.php
FormRenderer.render
public function render(string $templatePrefix, array $data): string { $formLayout = $this->layoutManager->getDefaultLayout(); if ($formLayout instanceof HorizontalFormLayout) { $templateName = $templatePrefix . '_horizontal'; } else { $templateName = $templatePrefix . '_default'; } $template = new FrontendTemplate($templateName); $template->setData($data); $this->prepare($template); return $template->parse(); }
php
public function render(string $templatePrefix, array $data): string { $formLayout = $this->layoutManager->getDefaultLayout(); if ($formLayout instanceof HorizontalFormLayout) { $templateName = $templatePrefix . '_horizontal'; } else { $templateName = $templatePrefix . '_default'; } $template = new FrontendTemplate($templateName); $template->setData($data); $this->prepare($template); return $template->parse(); }
[ "public", "function", "render", "(", "string", "$", "templatePrefix", ",", "array", "$", "data", ")", ":", "string", "{", "$", "formLayout", "=", "$", "this", "->", "layoutManager", "->", "getDefaultLayout", "(", ")", ";", "if", "(", "$", "formLayout", "instanceof", "HorizontalFormLayout", ")", "{", "$", "templateName", "=", "$", "templatePrefix", ".", "'_horizontal'", ";", "}", "else", "{", "$", "templateName", "=", "$", "templatePrefix", ".", "'_default'", ";", "}", "$", "template", "=", "new", "FrontendTemplate", "(", "$", "templateName", ")", ";", "$", "template", "->", "setData", "(", "$", "data", ")", ";", "$", "this", "->", "prepare", "(", "$", "template", ")", ";", "return", "$", "template", "->", "parse", "(", ")", ";", "}" ]
Generate the form view. @param string $templatePrefix The template prefix which gets an _horizontal or _default suffix. @param array $data Template data being used in the new template. @return string
[ "Generate", "the", "form", "view", "." ]
cf507af3a194895923c6b84d97aa224e8b5b6d2f
https://github.com/contao-bootstrap/templates/blob/cf507af3a194895923c6b84d97aa224e8b5b6d2f/src/View/FormRenderer.php#L63-L78
228,737
contao-bootstrap/templates
src/View/FormRenderer.php
FormRenderer.prepare
public function prepare(Template $template): void { $formLayout = $this->layoutManager->getDefaultLayout(); if ($formLayout instanceof HorizontalFormLayout) { $template->labelColClass = $formLayout->getLabelColumnClass(); $template->colClass = $formLayout->getColumnClass(); $template->colOffsetClass = $formLayout->getColumnClass(true); $template->rowClass = $formLayout->getRowClass(); $template->isHorizontal = true; } else { $template->labelColClass = null; $template->colClass = null; $template->colOffsetClass = null; $template->rowClass = null; $template->isHorizontal = false; } $template->formLayout = $formLayout; $template->buttonClass = $this->getButtonClass(); }
php
public function prepare(Template $template): void { $formLayout = $this->layoutManager->getDefaultLayout(); if ($formLayout instanceof HorizontalFormLayout) { $template->labelColClass = $formLayout->getLabelColumnClass(); $template->colClass = $formLayout->getColumnClass(); $template->colOffsetClass = $formLayout->getColumnClass(true); $template->rowClass = $formLayout->getRowClass(); $template->isHorizontal = true; } else { $template->labelColClass = null; $template->colClass = null; $template->colOffsetClass = null; $template->rowClass = null; $template->isHorizontal = false; } $template->formLayout = $formLayout; $template->buttonClass = $this->getButtonClass(); }
[ "public", "function", "prepare", "(", "Template", "$", "template", ")", ":", "void", "{", "$", "formLayout", "=", "$", "this", "->", "layoutManager", "->", "getDefaultLayout", "(", ")", ";", "if", "(", "$", "formLayout", "instanceof", "HorizontalFormLayout", ")", "{", "$", "template", "->", "labelColClass", "=", "$", "formLayout", "->", "getLabelColumnClass", "(", ")", ";", "$", "template", "->", "colClass", "=", "$", "formLayout", "->", "getColumnClass", "(", ")", ";", "$", "template", "->", "colOffsetClass", "=", "$", "formLayout", "->", "getColumnClass", "(", "true", ")", ";", "$", "template", "->", "rowClass", "=", "$", "formLayout", "->", "getRowClass", "(", ")", ";", "$", "template", "->", "isHorizontal", "=", "true", ";", "}", "else", "{", "$", "template", "->", "labelColClass", "=", "null", ";", "$", "template", "->", "colClass", "=", "null", ";", "$", "template", "->", "colOffsetClass", "=", "null", ";", "$", "template", "->", "rowClass", "=", "null", ";", "$", "template", "->", "isHorizontal", "=", "false", ";", "}", "$", "template", "->", "formLayout", "=", "$", "formLayout", ";", "$", "template", "->", "buttonClass", "=", "$", "this", "->", "getButtonClass", "(", ")", ";", "}" ]
Prepare the template by adding grid related classes. @param Template $template The template. @return void
[ "Prepare", "the", "template", "by", "adding", "grid", "related", "classes", "." ]
cf507af3a194895923c6b84d97aa224e8b5b6d2f
https://github.com/contao-bootstrap/templates/blob/cf507af3a194895923c6b84d97aa224e8b5b6d2f/src/View/FormRenderer.php#L87-L107
228,738
coolcsn/CsnCms
src/CsnCms/View/Helper/Vote.php
Vote.hasUserVoted
protected function hasUserVoted($vote) { $dql = "SELECT count(v.id) FROM CsnCms\Entity\Vote v LEFT JOIN v.usersVoted u WHERE v.id = ?0 AND u.id =?1"; $query = $this->entityManager->createQuery($dql); $voteId = $vote->getId(); $user = $this->getView()->identity(); $hasUserVoted = -1; if ($voteId != null && $user != null) { $userId = $user->getId(); $query->setParameter(0, $voteId); $query->setParameter(1, $userId); $hasUserVoted = $query->getSingleScalarResult(); } return $hasUserVoted; }
php
protected function hasUserVoted($vote) { $dql = "SELECT count(v.id) FROM CsnCms\Entity\Vote v LEFT JOIN v.usersVoted u WHERE v.id = ?0 AND u.id =?1"; $query = $this->entityManager->createQuery($dql); $voteId = $vote->getId(); $user = $this->getView()->identity(); $hasUserVoted = -1; if ($voteId != null && $user != null) { $userId = $user->getId(); $query->setParameter(0, $voteId); $query->setParameter(1, $userId); $hasUserVoted = $query->getSingleScalarResult(); } return $hasUserVoted; }
[ "protected", "function", "hasUserVoted", "(", "$", "vote", ")", "{", "$", "dql", "=", "\"SELECT count(v.id) FROM CsnCms\\Entity\\Vote v LEFT JOIN v.usersVoted u WHERE v.id = ?0 AND u.id =?1\"", ";", "$", "query", "=", "$", "this", "->", "entityManager", "->", "createQuery", "(", "$", "dql", ")", ";", "$", "voteId", "=", "$", "vote", "->", "getId", "(", ")", ";", "$", "user", "=", "$", "this", "->", "getView", "(", ")", "->", "identity", "(", ")", ";", "$", "hasUserVoted", "=", "-", "1", ";", "if", "(", "$", "voteId", "!=", "null", "&&", "$", "user", "!=", "null", ")", "{", "$", "userId", "=", "$", "user", "->", "getId", "(", ")", ";", "$", "query", "->", "setParameter", "(", "0", ",", "$", "voteId", ")", ";", "$", "query", "->", "setParameter", "(", "1", ",", "$", "userId", ")", ";", "$", "hasUserVoted", "=", "$", "query", "->", "getSingleScalarResult", "(", ")", ";", "}", "return", "$", "hasUserVoted", ";", "}" ]
Checks if the current user has already voted for the entity @param \CsnCms\Entity\Vote $vote @return integer 1 if voted, 0 if not, -1 if is not allowed to vote.
[ "Checks", "if", "the", "current", "user", "has", "already", "voted", "for", "the", "entity" ]
fd2b163e292836b9f672400694a86f75225b725a
https://github.com/coolcsn/CsnCms/blob/fd2b163e292836b9f672400694a86f75225b725a/src/CsnCms/View/Helper/Vote.php#L67-L84
228,739
silverstripe/silverstripe-mimevalidator
src/MimeUploadValidator.php
MimeUploadValidator.isValidMime
public function isValidMime() { $extension = strtolower(pathinfo($this->tmpFile['name'], PATHINFO_EXTENSION)); // we can't check filenames without an extension or no temp file path, let them pass validation. if (!$extension || !$this->tmpFile['tmp_name']) { return true; } $expectedMimes = $this->getExpectedMimeTypes($this->tmpFile); if (empty($expectedMimes)) { throw new MimeUploadValidatorException( sprintf('Could not find a MIME type for extension %s', $extension) ); } $fileInfo = new finfo(FILEINFO_MIME_TYPE); $foundMime = $fileInfo->file($this->tmpFile['tmp_name']); if (!$foundMime) { throw new MimeUploadValidatorException( sprintf('Could not find a MIME type for file %s', $this->tmpFile['tmp_name']) ); } foreach ($expectedMimes as $expected) { if ($this->compareMime($foundMime, $expected)) { return true; } } return false; }
php
public function isValidMime() { $extension = strtolower(pathinfo($this->tmpFile['name'], PATHINFO_EXTENSION)); // we can't check filenames without an extension or no temp file path, let them pass validation. if (!$extension || !$this->tmpFile['tmp_name']) { return true; } $expectedMimes = $this->getExpectedMimeTypes($this->tmpFile); if (empty($expectedMimes)) { throw new MimeUploadValidatorException( sprintf('Could not find a MIME type for extension %s', $extension) ); } $fileInfo = new finfo(FILEINFO_MIME_TYPE); $foundMime = $fileInfo->file($this->tmpFile['tmp_name']); if (!$foundMime) { throw new MimeUploadValidatorException( sprintf('Could not find a MIME type for file %s', $this->tmpFile['tmp_name']) ); } foreach ($expectedMimes as $expected) { if ($this->compareMime($foundMime, $expected)) { return true; } } return false; }
[ "public", "function", "isValidMime", "(", ")", "{", "$", "extension", "=", "strtolower", "(", "pathinfo", "(", "$", "this", "->", "tmpFile", "[", "'name'", "]", ",", "PATHINFO_EXTENSION", ")", ")", ";", "// we can't check filenames without an extension or no temp file path, let them pass validation.", "if", "(", "!", "$", "extension", "||", "!", "$", "this", "->", "tmpFile", "[", "'tmp_name'", "]", ")", "{", "return", "true", ";", "}", "$", "expectedMimes", "=", "$", "this", "->", "getExpectedMimeTypes", "(", "$", "this", "->", "tmpFile", ")", ";", "if", "(", "empty", "(", "$", "expectedMimes", ")", ")", "{", "throw", "new", "MimeUploadValidatorException", "(", "sprintf", "(", "'Could not find a MIME type for extension %s'", ",", "$", "extension", ")", ")", ";", "}", "$", "fileInfo", "=", "new", "finfo", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "foundMime", "=", "$", "fileInfo", "->", "file", "(", "$", "this", "->", "tmpFile", "[", "'tmp_name'", "]", ")", ";", "if", "(", "!", "$", "foundMime", ")", "{", "throw", "new", "MimeUploadValidatorException", "(", "sprintf", "(", "'Could not find a MIME type for file %s'", ",", "$", "this", "->", "tmpFile", "[", "'tmp_name'", "]", ")", ")", ";", "}", "foreach", "(", "$", "expectedMimes", "as", "$", "expected", ")", "{", "if", "(", "$", "this", "->", "compareMime", "(", "$", "foundMime", ",", "$", "expected", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if the temporary file has a valid MIME type for it's extension. @uses finfo php extension @return bool|null @throws MimeUploadValidatorException
[ "Check", "if", "the", "temporary", "file", "has", "a", "valid", "MIME", "type", "for", "it", "s", "extension", "." ]
12c28214d591e38ad136b27618e042e0d6f55057
https://github.com/silverstripe/silverstripe-mimevalidator/blob/12c28214d591e38ad136b27618e042e0d6f55057/src/MimeUploadValidator.php#L52-L83
228,740
silverstripe/silverstripe-mimevalidator
src/MimeUploadValidator.php
MimeUploadValidator.getExpectedMimeTypes
public function getExpectedMimeTypes($file) { $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); // if the finfo php extension isn't loaded, we can't complete this check. if (!class_exists('finfo')) { throw new MimeUploadValidatorException('PHP extension finfo is not loaded'); } // Attempt to figure out which mime types are expected/acceptable here. $expectedMimes = array(); // Get the mime types set in framework core $knownMimes = Config::inst()->get(HTTP::class, 'MimeTypes'); if (isset($knownMimes[$extension])) { $expectedMimes[] = $knownMimes[$extension]; } // Get the mime types and their variations from mime validator $knownMimes = $this->config()->get('MimeTypes'); if (isset($knownMimes[$extension])) { $mimes = (array) $knownMimes[$extension]; foreach ($mimes as $mime) { if (!in_array($mime, $expectedMimes)) { $expectedMimes[] = $mime; } } } return $expectedMimes; }
php
public function getExpectedMimeTypes($file) { $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); // if the finfo php extension isn't loaded, we can't complete this check. if (!class_exists('finfo')) { throw new MimeUploadValidatorException('PHP extension finfo is not loaded'); } // Attempt to figure out which mime types are expected/acceptable here. $expectedMimes = array(); // Get the mime types set in framework core $knownMimes = Config::inst()->get(HTTP::class, 'MimeTypes'); if (isset($knownMimes[$extension])) { $expectedMimes[] = $knownMimes[$extension]; } // Get the mime types and their variations from mime validator $knownMimes = $this->config()->get('MimeTypes'); if (isset($knownMimes[$extension])) { $mimes = (array) $knownMimes[$extension]; foreach ($mimes as $mime) { if (!in_array($mime, $expectedMimes)) { $expectedMimes[] = $mime; } } } return $expectedMimes; }
[ "public", "function", "getExpectedMimeTypes", "(", "$", "file", ")", "{", "$", "extension", "=", "strtolower", "(", "pathinfo", "(", "$", "file", "[", "'name'", "]", ",", "PATHINFO_EXTENSION", ")", ")", ";", "// if the finfo php extension isn't loaded, we can't complete this check.", "if", "(", "!", "class_exists", "(", "'finfo'", ")", ")", "{", "throw", "new", "MimeUploadValidatorException", "(", "'PHP extension finfo is not loaded'", ")", ";", "}", "// Attempt to figure out which mime types are expected/acceptable here.", "$", "expectedMimes", "=", "array", "(", ")", ";", "// Get the mime types set in framework core", "$", "knownMimes", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "HTTP", "::", "class", ",", "'MimeTypes'", ")", ";", "if", "(", "isset", "(", "$", "knownMimes", "[", "$", "extension", "]", ")", ")", "{", "$", "expectedMimes", "[", "]", "=", "$", "knownMimes", "[", "$", "extension", "]", ";", "}", "// Get the mime types and their variations from mime validator", "$", "knownMimes", "=", "$", "this", "->", "config", "(", ")", "->", "get", "(", "'MimeTypes'", ")", ";", "if", "(", "isset", "(", "$", "knownMimes", "[", "$", "extension", "]", ")", ")", "{", "$", "mimes", "=", "(", "array", ")", "$", "knownMimes", "[", "$", "extension", "]", ";", "foreach", "(", "$", "mimes", "as", "$", "mime", ")", "{", "if", "(", "!", "in_array", "(", "$", "mime", ",", "$", "expectedMimes", ")", ")", "{", "$", "expectedMimes", "[", "]", "=", "$", "mime", ";", "}", "}", "}", "return", "$", "expectedMimes", ";", "}" ]
Fetches an array of valid mimetypes. @param $file @return array @throws MimeUploadValidatorException
[ "Fetches", "an", "array", "of", "valid", "mimetypes", "." ]
12c28214d591e38ad136b27618e042e0d6f55057
https://github.com/silverstripe/silverstripe-mimevalidator/blob/12c28214d591e38ad136b27618e042e0d6f55057/src/MimeUploadValidator.php#L92-L123
228,741
silverstripe/silverstripe-mimevalidator
src/MimeUploadValidator.php
MimeUploadValidator.compareMime
public function compareMime($first, $second) { return preg_replace($this->filterPattern, '', $first) === preg_replace($this->filterPattern, '', $second); }
php
public function compareMime($first, $second) { return preg_replace($this->filterPattern, '', $first) === preg_replace($this->filterPattern, '', $second); }
[ "public", "function", "compareMime", "(", "$", "first", ",", "$", "second", ")", "{", "return", "preg_replace", "(", "$", "this", "->", "filterPattern", ",", "''", ",", "$", "first", ")", "===", "preg_replace", "(", "$", "this", "->", "filterPattern", ",", "''", ",", "$", "second", ")", ";", "}" ]
Check two MIME types roughly match eachother. Before we check MIME types, remove known prefixes "vnd.", "x-" etc. If there is a suffix, we'll use that to compare. Examples: application/x-json = json application/json = json application/xhtml+xml = xml application/xml = xml @param string $first The first MIME type to compare to the second @param string $second The second MIME type to compare to the first @return boolean
[ "Check", "two", "MIME", "types", "roughly", "match", "eachother", "." ]
12c28214d591e38ad136b27618e042e0d6f55057
https://github.com/silverstripe/silverstripe-mimevalidator/blob/12c28214d591e38ad136b27618e042e0d6f55057/src/MimeUploadValidator.php#L140-L143
228,742
mlaphp/mlaphp
src/Mlaphp/Response.php
Response.getViewPath
public function getViewPath() { if (! $this->base) { return $this->view; } return rtrim($this->base, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($this->view, DIRECTORY_SEPARATOR); }
php
public function getViewPath() { if (! $this->base) { return $this->view; } return rtrim($this->base, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($this->view, DIRECTORY_SEPARATOR); }
[ "public", "function", "getViewPath", "(", ")", "{", "if", "(", "!", "$", "this", "->", "base", ")", "{", "return", "$", "this", "->", "view", ";", "}", "return", "rtrim", "(", "$", "this", "->", "base", ",", "DIRECTORY_SEPARATOR", ")", ".", "DIRECTORY_SEPARATOR", ".", "ltrim", "(", "$", "this", "->", "view", ",", "DIRECTORY_SEPARATOR", ")", ";", "}" ]
Returns the full path to the view. @return string
[ "Returns", "the", "full", "path", "to", "the", "view", "." ]
c0c90e7217c598c82bb65e5304e8076da381c1f8
https://github.com/mlaphp/mlaphp/blob/c0c90e7217c598c82bb65e5304e8076da381c1f8/src/Mlaphp/Response.php#L110-L119
228,743
mlaphp/mlaphp
src/Mlaphp/Response.php
Response.requireView
public function requireView() { if (! $this->view) { return ''; } extract($this->vars); ob_start(); require $this->getViewPath(); return ob_get_clean(); }
php
public function requireView() { if (! $this->view) { return ''; } extract($this->vars); ob_start(); require $this->getViewPath(); return ob_get_clean(); }
[ "public", "function", "requireView", "(", ")", "{", "if", "(", "!", "$", "this", "->", "view", ")", "{", "return", "''", ";", "}", "extract", "(", "$", "this", "->", "vars", ")", ";", "ob_start", "(", ")", ";", "require", "$", "this", "->", "getViewPath", "(", ")", ";", "return", "ob_get_clean", "(", ")", ";", "}" ]
Requires the view in its own scope with etracted variables and returns the buffered output. @return string
[ "Requires", "the", "view", "in", "its", "own", "scope", "with", "etracted", "variables", "and", "returns", "the", "buffered", "output", "." ]
c0c90e7217c598c82bb65e5304e8076da381c1f8
https://github.com/mlaphp/mlaphp/blob/c0c90e7217c598c82bb65e5304e8076da381c1f8/src/Mlaphp/Response.php#L259-L269
228,744
mlaphp/mlaphp
src/Mlaphp/Response.php
Response.sendHeaders
public function sendHeaders() { foreach ($this->headers as $args) { $func = array_shift($args); call_user_func_array($func, $args); } }
php
public function sendHeaders() { foreach ($this->headers as $args) { $func = array_shift($args); call_user_func_array($func, $args); } }
[ "public", "function", "sendHeaders", "(", ")", "{", "foreach", "(", "$", "this", "->", "headers", "as", "$", "args", ")", "{", "$", "func", "=", "array_shift", "(", "$", "args", ")", ";", "call_user_func_array", "(", "$", "func", ",", "$", "args", ")", ";", "}", "}" ]
Outputs the buffered calls to `header`, `setcookie`, etc. @return null
[ "Outputs", "the", "buffered", "calls", "to", "header", "setcookie", "etc", "." ]
c0c90e7217c598c82bb65e5304e8076da381c1f8
https://github.com/mlaphp/mlaphp/blob/c0c90e7217c598c82bb65e5304e8076da381c1f8/src/Mlaphp/Response.php#L276-L282
228,745
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.connect
public static function connect($config = array()) { $ldap_check = self::checkLDAPExtension(); if (self::iserror($ldap_check)) { return $ldap_check; } @$obj = new Net_LDAP2($config); // todo? better errorhandling for setConfig()? // connect and bind with credentials in config $err = $obj->bind(); if (self::isError($err)) { return $err; } return $obj; }
php
public static function connect($config = array()) { $ldap_check = self::checkLDAPExtension(); if (self::iserror($ldap_check)) { return $ldap_check; } @$obj = new Net_LDAP2($config); // todo? better errorhandling for setConfig()? // connect and bind with credentials in config $err = $obj->bind(); if (self::isError($err)) { return $err; } return $obj; }
[ "public", "static", "function", "connect", "(", "$", "config", "=", "array", "(", ")", ")", "{", "$", "ldap_check", "=", "self", "::", "checkLDAPExtension", "(", ")", ";", "if", "(", "self", "::", "iserror", "(", "$", "ldap_check", ")", ")", "{", "return", "$", "ldap_check", ";", "}", "@", "$", "obj", "=", "new", "Net_LDAP2", "(", "$", "config", ")", ";", "// todo? better errorhandling for setConfig()?", "// connect and bind with credentials in config", "$", "err", "=", "$", "obj", "->", "bind", "(", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "err", ")", ")", "{", "return", "$", "err", ";", "}", "return", "$", "obj", ";", "}" ]
Configure Net_LDAP2, connect and bind Use this method as starting point of using Net_LDAP2 to establish a connection to your LDAP server. Static function that returns either an error object or the new Net_LDAP2 object. Something like a factory. Takes a config array with the needed parameters. @param array $config Configuration array @access public @return Net_LDAP2_Error|Net_LDAP2 Net_LDAP2_Error or Net_LDAP2 object
[ "Configure", "Net_LDAP2", "connect", "and", "bind" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L195-L213
228,746
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.setConfig
protected function setConfig($config) { // // Parameter check -- probably should raise an error here if config // is not an array. // if (! is_array($config)) { return; } foreach ($config as $k => $v) { if (isset($this->_config[$k])) { $this->_config[$k] = $v; } else { // map old (Net_LDAP2) parms to new ones switch($k) { case "dn": $this->_config["binddn"] = $v; break; case "password": $this->_config["bindpw"] = $v; break; case "tls": $this->_config["starttls"] = $v; break; case "base": $this->_config["basedn"] = $v; break; } } } // // Ensure the host list is an array. // if (is_array($this->_config['host'])) { $this->_host_list = $this->_config['host']; } else { if (strlen($this->_config['host']) > 0) { $this->_host_list = array($this->_config['host']); } else { $this->_host_list = array(); // ^ this will cause an error in performConnect(), // so the user is notified about the failure } } // // Reset the down host list, which seems like a sensible thing to do // if the config is being reset for some reason. // $this->_down_host_list = array(); }
php
protected function setConfig($config) { // // Parameter check -- probably should raise an error here if config // is not an array. // if (! is_array($config)) { return; } foreach ($config as $k => $v) { if (isset($this->_config[$k])) { $this->_config[$k] = $v; } else { // map old (Net_LDAP2) parms to new ones switch($k) { case "dn": $this->_config["binddn"] = $v; break; case "password": $this->_config["bindpw"] = $v; break; case "tls": $this->_config["starttls"] = $v; break; case "base": $this->_config["basedn"] = $v; break; } } } // // Ensure the host list is an array. // if (is_array($this->_config['host'])) { $this->_host_list = $this->_config['host']; } else { if (strlen($this->_config['host']) > 0) { $this->_host_list = array($this->_config['host']); } else { $this->_host_list = array(); // ^ this will cause an error in performConnect(), // so the user is notified about the failure } } // // Reset the down host list, which seems like a sensible thing to do // if the config is being reset for some reason. // $this->_down_host_list = array(); }
[ "protected", "function", "setConfig", "(", "$", "config", ")", "{", "//", "// Parameter check -- probably should raise an error here if config", "// is not an array.", "//", "if", "(", "!", "is_array", "(", "$", "config", ")", ")", "{", "return", ";", "}", "foreach", "(", "$", "config", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "_config", "[", "$", "k", "]", ")", ")", "{", "$", "this", "->", "_config", "[", "$", "k", "]", "=", "$", "v", ";", "}", "else", "{", "// map old (Net_LDAP2) parms to new ones", "switch", "(", "$", "k", ")", "{", "case", "\"dn\"", ":", "$", "this", "->", "_config", "[", "\"binddn\"", "]", "=", "$", "v", ";", "break", ";", "case", "\"password\"", ":", "$", "this", "->", "_config", "[", "\"bindpw\"", "]", "=", "$", "v", ";", "break", ";", "case", "\"tls\"", ":", "$", "this", "->", "_config", "[", "\"starttls\"", "]", "=", "$", "v", ";", "break", ";", "case", "\"base\"", ":", "$", "this", "->", "_config", "[", "\"basedn\"", "]", "=", "$", "v", ";", "break", ";", "}", "}", "}", "//", "// Ensure the host list is an array.", "//", "if", "(", "is_array", "(", "$", "this", "->", "_config", "[", "'host'", "]", ")", ")", "{", "$", "this", "->", "_host_list", "=", "$", "this", "->", "_config", "[", "'host'", "]", ";", "}", "else", "{", "if", "(", "strlen", "(", "$", "this", "->", "_config", "[", "'host'", "]", ")", ">", "0", ")", "{", "$", "this", "->", "_host_list", "=", "array", "(", "$", "this", "->", "_config", "[", "'host'", "]", ")", ";", "}", "else", "{", "$", "this", "->", "_host_list", "=", "array", "(", ")", ";", "// ^ this will cause an error in performConnect(),", "// so the user is notified about the failure", "}", "}", "//", "// Reset the down host list, which seems like a sensible thing to do", "// if the config is being reset for some reason.", "//", "$", "this", "->", "_down_host_list", "=", "array", "(", ")", ";", "}" ]
Sets the internal configuration array @param array $config Configuration array @access protected @return void
[ "Sets", "the", "internal", "configuration", "array" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L244-L296
228,747
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.bind
public function bind($dn = null, $password = null) { // fetch current bind credentials if (is_null($dn)) { $dn = $this->_config["binddn"]; } if (is_null($password)) { $password = $this->_config["bindpw"]; } // Connect first, if we haven't so far. // This will also bind us to the server. if ($this->_link === false) { // store old credentials so we can revert them later // then overwrite config with new bind credentials $olddn = $this->_config["binddn"]; $oldpw = $this->_config["bindpw"]; // overwrite bind credentials in config // so performConnect() knows about them $this->_config["binddn"] = $dn; $this->_config["bindpw"] = $password; // try to connect with provided credentials $msg = $this->performConnect(); // reset to previous config $this->_config["binddn"] = $olddn; $this->_config["bindpw"] = $oldpw; // see if bind worked if (self::isError($msg)) { return $msg; } } else { // do the requested bind as we are // asked to bind manually if (is_null($dn)) { // anonymous bind $msg = @ldap_bind($this->_link); } else { // privileged bind $msg = @ldap_bind($this->_link, $dn, $password); } if (false === $msg) { return PEAR::raiseError("Bind failed: " . @ldap_error($this->_link), @ldap_errno($this->_link)); } } return true; }
php
public function bind($dn = null, $password = null) { // fetch current bind credentials if (is_null($dn)) { $dn = $this->_config["binddn"]; } if (is_null($password)) { $password = $this->_config["bindpw"]; } // Connect first, if we haven't so far. // This will also bind us to the server. if ($this->_link === false) { // store old credentials so we can revert them later // then overwrite config with new bind credentials $olddn = $this->_config["binddn"]; $oldpw = $this->_config["bindpw"]; // overwrite bind credentials in config // so performConnect() knows about them $this->_config["binddn"] = $dn; $this->_config["bindpw"] = $password; // try to connect with provided credentials $msg = $this->performConnect(); // reset to previous config $this->_config["binddn"] = $olddn; $this->_config["bindpw"] = $oldpw; // see if bind worked if (self::isError($msg)) { return $msg; } } else { // do the requested bind as we are // asked to bind manually if (is_null($dn)) { // anonymous bind $msg = @ldap_bind($this->_link); } else { // privileged bind $msg = @ldap_bind($this->_link, $dn, $password); } if (false === $msg) { return PEAR::raiseError("Bind failed: " . @ldap_error($this->_link), @ldap_errno($this->_link)); } } return true; }
[ "public", "function", "bind", "(", "$", "dn", "=", "null", ",", "$", "password", "=", "null", ")", "{", "// fetch current bind credentials", "if", "(", "is_null", "(", "$", "dn", ")", ")", "{", "$", "dn", "=", "$", "this", "->", "_config", "[", "\"binddn\"", "]", ";", "}", "if", "(", "is_null", "(", "$", "password", ")", ")", "{", "$", "password", "=", "$", "this", "->", "_config", "[", "\"bindpw\"", "]", ";", "}", "// Connect first, if we haven't so far.", "// This will also bind us to the server.", "if", "(", "$", "this", "->", "_link", "===", "false", ")", "{", "// store old credentials so we can revert them later", "// then overwrite config with new bind credentials", "$", "olddn", "=", "$", "this", "->", "_config", "[", "\"binddn\"", "]", ";", "$", "oldpw", "=", "$", "this", "->", "_config", "[", "\"bindpw\"", "]", ";", "// overwrite bind credentials in config", "// so performConnect() knows about them", "$", "this", "->", "_config", "[", "\"binddn\"", "]", "=", "$", "dn", ";", "$", "this", "->", "_config", "[", "\"bindpw\"", "]", "=", "$", "password", ";", "// try to connect with provided credentials", "$", "msg", "=", "$", "this", "->", "performConnect", "(", ")", ";", "// reset to previous config", "$", "this", "->", "_config", "[", "\"binddn\"", "]", "=", "$", "olddn", ";", "$", "this", "->", "_config", "[", "\"bindpw\"", "]", "=", "$", "oldpw", ";", "// see if bind worked", "if", "(", "self", "::", "isError", "(", "$", "msg", ")", ")", "{", "return", "$", "msg", ";", "}", "}", "else", "{", "// do the requested bind as we are", "// asked to bind manually", "if", "(", "is_null", "(", "$", "dn", ")", ")", "{", "// anonymous bind", "$", "msg", "=", "@", "ldap_bind", "(", "$", "this", "->", "_link", ")", ";", "}", "else", "{", "// privileged bind", "$", "msg", "=", "@", "ldap_bind", "(", "$", "this", "->", "_link", ",", "$", "dn", ",", "$", "password", ")", ";", "}", "if", "(", "false", "===", "$", "msg", ")", "{", "return", "PEAR", "::", "raiseError", "(", "\"Bind failed: \"", ".", "@", "ldap_error", "(", "$", "this", "->", "_link", ")", ",", "@", "ldap_errno", "(", "$", "this", "->", "_link", ")", ")", ";", "}", "}", "return", "true", ";", "}" ]
Bind or rebind to the ldap-server This function binds with the given dn and password to the server. In case no connection has been made yet, it will be started and startTLS issued if appropiate. The internal bind configuration is not being updated, so if you call bind() without parameters, you can rebind with the credentials provided at first connecting to the server. @param string $dn Distinguished name for binding @param string $password Password for binding @access public @return Net_LDAP2_Error|true Net_LDAP2_Error object or true
[ "Bind", "or", "rebind", "to", "the", "ldap", "-", "server" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L315-L366
228,748
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.performReconnect
protected function performReconnect() { // Return true if we are already connected. if ($this->_link !== false) { return true; } // Default error message in case all connection attempts // fail but no message is set $current_error = new PEAR_Error('Unknown connection error'); // Sleep for a backoff period in seconds. sleep($this->_config['current_backoff']); // Retry all available connections. $this->_down_host_list = array(); $msg = $this->performConnect(); // Bail out if that fails. if (self::isError($msg)) { $this->_config['current_backoff'] = $this->_config['current_backoff'] * 2; if ($this->_config['current_backoff'] > $this->_config['max_backoff']) { $this->_config['current_backoff'] = $this->_config['max_backoff']; } return $msg; } // Now we should be able to safely (re-)bind. $msg = $this->bind(); if (self::isError($msg)) { $this->_config['current_backoff'] = $this->_config['current_backoff'] * 2; if ($this->_config['current_backoff'] > $this->_config['max_backoff']) { $this->_config['current_backoff'] = $this->_config['max_backoff']; } // _config['host'] should have had the last connected host stored in it // by performConnect(). Since we are unable to bind to that host we can safely // assume that it is down or has some other problem. $this->_down_host_list[] = $this->_config['host']; return $msg; } // At this stage we have connected, bound, and set up options, // so we have a known good LDAP server. Time to go home. $this->_config['current_backoff'] = $this->_config['min_backoff']; return true; }
php
protected function performReconnect() { // Return true if we are already connected. if ($this->_link !== false) { return true; } // Default error message in case all connection attempts // fail but no message is set $current_error = new PEAR_Error('Unknown connection error'); // Sleep for a backoff period in seconds. sleep($this->_config['current_backoff']); // Retry all available connections. $this->_down_host_list = array(); $msg = $this->performConnect(); // Bail out if that fails. if (self::isError($msg)) { $this->_config['current_backoff'] = $this->_config['current_backoff'] * 2; if ($this->_config['current_backoff'] > $this->_config['max_backoff']) { $this->_config['current_backoff'] = $this->_config['max_backoff']; } return $msg; } // Now we should be able to safely (re-)bind. $msg = $this->bind(); if (self::isError($msg)) { $this->_config['current_backoff'] = $this->_config['current_backoff'] * 2; if ($this->_config['current_backoff'] > $this->_config['max_backoff']) { $this->_config['current_backoff'] = $this->_config['max_backoff']; } // _config['host'] should have had the last connected host stored in it // by performConnect(). Since we are unable to bind to that host we can safely // assume that it is down or has some other problem. $this->_down_host_list[] = $this->_config['host']; return $msg; } // At this stage we have connected, bound, and set up options, // so we have a known good LDAP server. Time to go home. $this->_config['current_backoff'] = $this->_config['min_backoff']; return true; }
[ "protected", "function", "performReconnect", "(", ")", "{", "// Return true if we are already connected.", "if", "(", "$", "this", "->", "_link", "!==", "false", ")", "{", "return", "true", ";", "}", "// Default error message in case all connection attempts", "// fail but no message is set", "$", "current_error", "=", "new", "PEAR_Error", "(", "'Unknown connection error'", ")", ";", "// Sleep for a backoff period in seconds.", "sleep", "(", "$", "this", "->", "_config", "[", "'current_backoff'", "]", ")", ";", "// Retry all available connections.", "$", "this", "->", "_down_host_list", "=", "array", "(", ")", ";", "$", "msg", "=", "$", "this", "->", "performConnect", "(", ")", ";", "// Bail out if that fails.", "if", "(", "self", "::", "isError", "(", "$", "msg", ")", ")", "{", "$", "this", "->", "_config", "[", "'current_backoff'", "]", "=", "$", "this", "->", "_config", "[", "'current_backoff'", "]", "*", "2", ";", "if", "(", "$", "this", "->", "_config", "[", "'current_backoff'", "]", ">", "$", "this", "->", "_config", "[", "'max_backoff'", "]", ")", "{", "$", "this", "->", "_config", "[", "'current_backoff'", "]", "=", "$", "this", "->", "_config", "[", "'max_backoff'", "]", ";", "}", "return", "$", "msg", ";", "}", "// Now we should be able to safely (re-)bind.", "$", "msg", "=", "$", "this", "->", "bind", "(", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "msg", ")", ")", "{", "$", "this", "->", "_config", "[", "'current_backoff'", "]", "=", "$", "this", "->", "_config", "[", "'current_backoff'", "]", "*", "2", ";", "if", "(", "$", "this", "->", "_config", "[", "'current_backoff'", "]", ">", "$", "this", "->", "_config", "[", "'max_backoff'", "]", ")", "{", "$", "this", "->", "_config", "[", "'current_backoff'", "]", "=", "$", "this", "->", "_config", "[", "'max_backoff'", "]", ";", "}", "// _config['host'] should have had the last connected host stored in it", "// by performConnect(). Since we are unable to bind to that host we can safely", "// assume that it is down or has some other problem.", "$", "this", "->", "_down_host_list", "[", "]", "=", "$", "this", "->", "_config", "[", "'host'", "]", ";", "return", "$", "msg", ";", "}", "// At this stage we have connected, bound, and set up options,", "// so we have a known good LDAP server. Time to go home.", "$", "this", "->", "_config", "[", "'current_backoff'", "]", "=", "$", "this", "->", "_config", "[", "'min_backoff'", "]", ";", "return", "true", ";", "}" ]
Reconnect to the ldap-server. In case the connection to the LDAP service has dropped out for some reason, this function will reconnect, and re-bind if a bind has been attempted in the past. It is probably most useful when the server list provided to the new() or connect() function is an array rather than a single host name, because in that case it will be able to connect to a failover or secondary server in case the primary server goes down. This doesn't return anything, it just tries to re-establish the current connection. It will sleep for the current backoff period (seconds) before attempting the connect, and if the connection fails it will double the backoff period, but not try again. If you want to ensure a reconnection during a transient period of server downtime then you need to call this function in a loop. @access protected @return Net_LDAP2_Error|true Net_LDAP2_Error object or true
[ "Reconnect", "to", "the", "ldap", "-", "server", "." ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L557-L605
228,749
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.startTLS
public function startTLS() { /* Test to see if the server supports TLS first. This is done via testing the extensions offered by the server. The OID 1.3.6.1.4.1.1466.20037 tells us, if TLS is supported. Note, that not all servers allow to feth either the rootDSE or attributes over an unencrypted channel, so we must ignore errors. */ $rootDSE = $this->rootDse(); if (self::isError($rootDSE)) { /* IGNORE this error, because server may refuse fetching the RootDSE over an unencrypted connection. */ //return $this->raiseError("Unable to fetch rootDSE entry ". //"to see if TLS is supoported: ".$rootDSE->getMessage(), $rootDSE->getCode()); } else { /* Fetch suceeded, see, if the server supports TLS. Again, we ignore errors, because the server may refuse to return attributes over unencryted connections. */ $supported_extensions = $rootDSE->getValue('supportedExtension'); if (self::isError($supported_extensions)) { /* IGNORE error, because server may refuse attribute returning over an unencrypted connection. */ //return $this->raiseError("Unable to fetch rootDSE attribute 'supportedExtension' ". //"to see if TLS is supoported: ".$supported_extensions->getMessage(), $supported_extensions->getCode()); } else { // fetch succeedet, lets see if the server supports it. // if not, then drop an error. If supported, then do nothing, // because then we try to issue TLS afterwards. if (!in_array('1.3.6.1.4.1.1466.20037', $supported_extensions)) { return $this->raiseError("Server reports that it does not support TLS."); } } } // Try to establish TLS. if (false === @ldap_start_tls($this->_link)) { // Starting TLS failed. This may be an error, or because // the server does not support it but did not enable us to // detect that above. return $this->raiseError("TLS could not be started: " . @ldap_error($this->_link), @ldap_errno($this->_link)); } else { return true; // TLS is started now. } }
php
public function startTLS() { /* Test to see if the server supports TLS first. This is done via testing the extensions offered by the server. The OID 1.3.6.1.4.1.1466.20037 tells us, if TLS is supported. Note, that not all servers allow to feth either the rootDSE or attributes over an unencrypted channel, so we must ignore errors. */ $rootDSE = $this->rootDse(); if (self::isError($rootDSE)) { /* IGNORE this error, because server may refuse fetching the RootDSE over an unencrypted connection. */ //return $this->raiseError("Unable to fetch rootDSE entry ". //"to see if TLS is supoported: ".$rootDSE->getMessage(), $rootDSE->getCode()); } else { /* Fetch suceeded, see, if the server supports TLS. Again, we ignore errors, because the server may refuse to return attributes over unencryted connections. */ $supported_extensions = $rootDSE->getValue('supportedExtension'); if (self::isError($supported_extensions)) { /* IGNORE error, because server may refuse attribute returning over an unencrypted connection. */ //return $this->raiseError("Unable to fetch rootDSE attribute 'supportedExtension' ". //"to see if TLS is supoported: ".$supported_extensions->getMessage(), $supported_extensions->getCode()); } else { // fetch succeedet, lets see if the server supports it. // if not, then drop an error. If supported, then do nothing, // because then we try to issue TLS afterwards. if (!in_array('1.3.6.1.4.1.1466.20037', $supported_extensions)) { return $this->raiseError("Server reports that it does not support TLS."); } } } // Try to establish TLS. if (false === @ldap_start_tls($this->_link)) { // Starting TLS failed. This may be an error, or because // the server does not support it but did not enable us to // detect that above. return $this->raiseError("TLS could not be started: " . @ldap_error($this->_link), @ldap_errno($this->_link)); } else { return true; // TLS is started now. } }
[ "public", "function", "startTLS", "(", ")", "{", "/* Test to see if the server supports TLS first.\n This is done via testing the extensions offered by the server.\n The OID 1.3.6.1.4.1.1466.20037 tells us, if TLS is supported.\n Note, that not all servers allow to feth either the rootDSE or\n attributes over an unencrypted channel, so we must ignore errors. */", "$", "rootDSE", "=", "$", "this", "->", "rootDse", "(", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "rootDSE", ")", ")", "{", "/* IGNORE this error, because server may refuse fetching the\n RootDSE over an unencrypted connection. */", "//return $this->raiseError(\"Unable to fetch rootDSE entry \".", "//\"to see if TLS is supoported: \".$rootDSE->getMessage(), $rootDSE->getCode());", "}", "else", "{", "/* Fetch suceeded, see, if the server supports TLS. Again, we\n ignore errors, because the server may refuse to return\n attributes over unencryted connections. */", "$", "supported_extensions", "=", "$", "rootDSE", "->", "getValue", "(", "'supportedExtension'", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "supported_extensions", ")", ")", "{", "/* IGNORE error, because server may refuse attribute\n returning over an unencrypted connection. */", "//return $this->raiseError(\"Unable to fetch rootDSE attribute 'supportedExtension' \".", "//\"to see if TLS is supoported: \".$supported_extensions->getMessage(), $supported_extensions->getCode());", "}", "else", "{", "// fetch succeedet, lets see if the server supports it.", "// if not, then drop an error. If supported, then do nothing,", "// because then we try to issue TLS afterwards.", "if", "(", "!", "in_array", "(", "'1.3.6.1.4.1.1466.20037'", ",", "$", "supported_extensions", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "\"Server reports that it does not support TLS.\"", ")", ";", "}", "}", "}", "// Try to establish TLS.", "if", "(", "false", "===", "@", "ldap_start_tls", "(", "$", "this", "->", "_link", ")", ")", "{", "// Starting TLS failed. This may be an error, or because", "// the server does not support it but did not enable us to", "// detect that above.", "return", "$", "this", "->", "raiseError", "(", "\"TLS could not be started: \"", ".", "@", "ldap_error", "(", "$", "this", "->", "_link", ")", ",", "@", "ldap_errno", "(", "$", "this", "->", "_link", ")", ")", ";", "}", "else", "{", "return", "true", ";", "// TLS is started now.", "}", "}" ]
Starts an encrypted session @access public @return Net_LDAP2_Error|true Net_LDAP2_Error object or true
[ "Starts", "an", "encrypted", "session" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L613-L657
228,750
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.add
public function add($entry) { if (!$entry instanceof Net_LDAP2_Entry) { return PEAR::raiseError('Parameter to Net_LDAP2::add() must be a Net_LDAP2_Entry object.'); } // Continue attempting the add operation in a loop until we // get a success, a definitive failure, or the world ends. $foo = 0; while (true) { $link = $this->getLink(); if ($link === false) { // We do not have a successful connection yet. The call to // getLink() would have kept trying if we wanted one. Go // home now. return PEAR::raiseError("Could not add entry " . $entry->dn() . " no valid LDAP connection could be found."); } if (@ldap_add($link, $entry->dn(), $entry->getValues())) { // entry successfully added, we should update its $ldap reference // in case it is not set so far (fresh entry) if (!$entry->getLDAP() instanceof Net_LDAP2) { $entry->setLDAP($this); } // store, that the entry is present inside the directory $entry->markAsNew(false); return true; } else { // We have a failure. What type? We may be able to reconnect // and try again. $error_code = @ldap_errno($link); $error_name = Net_LDAP2::errorMessage($error_code); if (($error_name === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a different // server. $this->_link = false; $this->performReconnect(); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return PEAR::raiseError("Could not add entry " . $entry->dn() . " " . $error_name, $error_code); } } } }
php
public function add($entry) { if (!$entry instanceof Net_LDAP2_Entry) { return PEAR::raiseError('Parameter to Net_LDAP2::add() must be a Net_LDAP2_Entry object.'); } // Continue attempting the add operation in a loop until we // get a success, a definitive failure, or the world ends. $foo = 0; while (true) { $link = $this->getLink(); if ($link === false) { // We do not have a successful connection yet. The call to // getLink() would have kept trying if we wanted one. Go // home now. return PEAR::raiseError("Could not add entry " . $entry->dn() . " no valid LDAP connection could be found."); } if (@ldap_add($link, $entry->dn(), $entry->getValues())) { // entry successfully added, we should update its $ldap reference // in case it is not set so far (fresh entry) if (!$entry->getLDAP() instanceof Net_LDAP2) { $entry->setLDAP($this); } // store, that the entry is present inside the directory $entry->markAsNew(false); return true; } else { // We have a failure. What type? We may be able to reconnect // and try again. $error_code = @ldap_errno($link); $error_name = Net_LDAP2::errorMessage($error_code); if (($error_name === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a different // server. $this->_link = false; $this->performReconnect(); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return PEAR::raiseError("Could not add entry " . $entry->dn() . " " . $error_name, $error_code); } } } }
[ "public", "function", "add", "(", "$", "entry", ")", "{", "if", "(", "!", "$", "entry", "instanceof", "Net_LDAP2_Entry", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Parameter to Net_LDAP2::add() must be a Net_LDAP2_Entry object.'", ")", ";", "}", "// Continue attempting the add operation in a loop until we", "// get a success, a definitive failure, or the world ends.", "$", "foo", "=", "0", ";", "while", "(", "true", ")", "{", "$", "link", "=", "$", "this", "->", "getLink", "(", ")", ";", "if", "(", "$", "link", "===", "false", ")", "{", "// We do not have a successful connection yet. The call to", "// getLink() would have kept trying if we wanted one. Go", "// home now.", "return", "PEAR", "::", "raiseError", "(", "\"Could not add entry \"", ".", "$", "entry", "->", "dn", "(", ")", ".", "\" no valid LDAP connection could be found.\"", ")", ";", "}", "if", "(", "@", "ldap_add", "(", "$", "link", ",", "$", "entry", "->", "dn", "(", ")", ",", "$", "entry", "->", "getValues", "(", ")", ")", ")", "{", "// entry successfully added, we should update its $ldap reference", "// in case it is not set so far (fresh entry)", "if", "(", "!", "$", "entry", "->", "getLDAP", "(", ")", "instanceof", "Net_LDAP2", ")", "{", "$", "entry", "->", "setLDAP", "(", "$", "this", ")", ";", "}", "// store, that the entry is present inside the directory", "$", "entry", "->", "markAsNew", "(", "false", ")", ";", "return", "true", ";", "}", "else", "{", "// We have a failure. What type? We may be able to reconnect", "// and try again.", "$", "error_code", "=", "@", "ldap_errno", "(", "$", "link", ")", ";", "$", "error_name", "=", "Net_LDAP2", "::", "errorMessage", "(", "$", "error_code", ")", ";", "if", "(", "(", "$", "error_name", "===", "'LDAP_OPERATIONS_ERROR'", ")", "&&", "(", "$", "this", "->", "_config", "[", "'auto_reconnect'", "]", ")", ")", "{", "// The server has become disconnected before trying the", "// operation. We should try again, possibly with a different", "// server.", "$", "this", "->", "_link", "=", "false", ";", "$", "this", "->", "performReconnect", "(", ")", ";", "}", "else", "{", "// Errors other than the above catched are just passed", "// back to the user so he may react upon them.", "return", "PEAR", "::", "raiseError", "(", "\"Could not add entry \"", ".", "$", "entry", "->", "dn", "(", ")", ".", "\" \"", ".", "$", "error_name", ",", "$", "error_code", ")", ";", "}", "}", "}", "}" ]
Add a new entryobject to a directory. Use add to add a new Net_LDAP2_Entry object to the directory. This also links the entry to the connection used for the add, if it was a fresh entry ({@link Net_LDAP2_Entry::createFresh()}) @param Net_LDAP2_Entry $entry Net_LDAP2_Entry @return Net_LDAP2_Error|true Net_LDAP2_Error object or true
[ "Add", "a", "new", "entryobject", "to", "a", "directory", "." ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L715-L767
228,751
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.delete
public function delete($dn, $recursive = false) { if ($dn instanceof Net_LDAP2_Entry) { $dn = $dn->dn(); } if (false === is_string($dn)) { return PEAR::raiseError("Parameter is not a string nor an entry object!"); } // Recursive delete searches for children and calls delete for them if ($recursive) { $result = @ldap_list($this->_link, $dn, '(objectClass=*)', array(null), 0, 0); if (@ldap_count_entries($this->_link, $result)) { $subentry = @ldap_first_entry($this->_link, $result); $this->delete(@ldap_get_dn($this->_link, $subentry), true); while ($subentry = @ldap_next_entry($this->_link, $subentry)) { $this->delete(@ldap_get_dn($this->_link, $subentry), true); } } } // Continue attempting the delete operation in a loop until we // get a success, a definitive failure, or the world ends. while (true) { $link = $this->getLink(); if ($link === false) { // We do not have a successful connection yet. The call to // getLink() would have kept trying if we wanted one. Go // home now. return PEAR::raiseError("Could not add entry " . $dn . " no valid LDAP connection could be found."); } if (@ldap_delete($link, $dn)) { // entry successfully deleted. return true; } else { // We have a failure. What type? // We may be able to reconnect and try again. $error_code = @ldap_errno($link); $error_name = Net_LDAP2::errorMessage($error_code); if ((Net_LDAP2::errorMessage($error_code) === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a // different server. $this->_link = false; $this->performReconnect(); } elseif ($error_code == 66) { // Subentries present, server refused to delete. // Deleting subentries is the clients responsibility, but // since the user may not know of the subentries, we do not // force that here but instead notify the developer so he // may take actions himself. return PEAR::raiseError("Could not delete entry $dn because of subentries. Use the recursive parameter to delete them."); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return PEAR::raiseError("Could not delete entry " . $dn . " " . $error_name, $error_code); } } } }
php
public function delete($dn, $recursive = false) { if ($dn instanceof Net_LDAP2_Entry) { $dn = $dn->dn(); } if (false === is_string($dn)) { return PEAR::raiseError("Parameter is not a string nor an entry object!"); } // Recursive delete searches for children and calls delete for them if ($recursive) { $result = @ldap_list($this->_link, $dn, '(objectClass=*)', array(null), 0, 0); if (@ldap_count_entries($this->_link, $result)) { $subentry = @ldap_first_entry($this->_link, $result); $this->delete(@ldap_get_dn($this->_link, $subentry), true); while ($subentry = @ldap_next_entry($this->_link, $subentry)) { $this->delete(@ldap_get_dn($this->_link, $subentry), true); } } } // Continue attempting the delete operation in a loop until we // get a success, a definitive failure, or the world ends. while (true) { $link = $this->getLink(); if ($link === false) { // We do not have a successful connection yet. The call to // getLink() would have kept trying if we wanted one. Go // home now. return PEAR::raiseError("Could not add entry " . $dn . " no valid LDAP connection could be found."); } if (@ldap_delete($link, $dn)) { // entry successfully deleted. return true; } else { // We have a failure. What type? // We may be able to reconnect and try again. $error_code = @ldap_errno($link); $error_name = Net_LDAP2::errorMessage($error_code); if ((Net_LDAP2::errorMessage($error_code) === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a // different server. $this->_link = false; $this->performReconnect(); } elseif ($error_code == 66) { // Subentries present, server refused to delete. // Deleting subentries is the clients responsibility, but // since the user may not know of the subentries, we do not // force that here but instead notify the developer so he // may take actions himself. return PEAR::raiseError("Could not delete entry $dn because of subentries. Use the recursive parameter to delete them."); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return PEAR::raiseError("Could not delete entry " . $dn . " " . $error_name, $error_code); } } } }
[ "public", "function", "delete", "(", "$", "dn", ",", "$", "recursive", "=", "false", ")", "{", "if", "(", "$", "dn", "instanceof", "Net_LDAP2_Entry", ")", "{", "$", "dn", "=", "$", "dn", "->", "dn", "(", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "dn", ")", ")", "{", "return", "PEAR", "::", "raiseError", "(", "\"Parameter is not a string nor an entry object!\"", ")", ";", "}", "// Recursive delete searches for children and calls delete for them", "if", "(", "$", "recursive", ")", "{", "$", "result", "=", "@", "ldap_list", "(", "$", "this", "->", "_link", ",", "$", "dn", ",", "'(objectClass=*)'", ",", "array", "(", "null", ")", ",", "0", ",", "0", ")", ";", "if", "(", "@", "ldap_count_entries", "(", "$", "this", "->", "_link", ",", "$", "result", ")", ")", "{", "$", "subentry", "=", "@", "ldap_first_entry", "(", "$", "this", "->", "_link", ",", "$", "result", ")", ";", "$", "this", "->", "delete", "(", "@", "ldap_get_dn", "(", "$", "this", "->", "_link", ",", "$", "subentry", ")", ",", "true", ")", ";", "while", "(", "$", "subentry", "=", "@", "ldap_next_entry", "(", "$", "this", "->", "_link", ",", "$", "subentry", ")", ")", "{", "$", "this", "->", "delete", "(", "@", "ldap_get_dn", "(", "$", "this", "->", "_link", ",", "$", "subentry", ")", ",", "true", ")", ";", "}", "}", "}", "// Continue attempting the delete operation in a loop until we", "// get a success, a definitive failure, or the world ends.", "while", "(", "true", ")", "{", "$", "link", "=", "$", "this", "->", "getLink", "(", ")", ";", "if", "(", "$", "link", "===", "false", ")", "{", "// We do not have a successful connection yet. The call to", "// getLink() would have kept trying if we wanted one. Go", "// home now.", "return", "PEAR", "::", "raiseError", "(", "\"Could not add entry \"", ".", "$", "dn", ".", "\" no valid LDAP connection could be found.\"", ")", ";", "}", "if", "(", "@", "ldap_delete", "(", "$", "link", ",", "$", "dn", ")", ")", "{", "// entry successfully deleted.", "return", "true", ";", "}", "else", "{", "// We have a failure. What type?", "// We may be able to reconnect and try again.", "$", "error_code", "=", "@", "ldap_errno", "(", "$", "link", ")", ";", "$", "error_name", "=", "Net_LDAP2", "::", "errorMessage", "(", "$", "error_code", ")", ";", "if", "(", "(", "Net_LDAP2", "::", "errorMessage", "(", "$", "error_code", ")", "===", "'LDAP_OPERATIONS_ERROR'", ")", "&&", "(", "$", "this", "->", "_config", "[", "'auto_reconnect'", "]", ")", ")", "{", "// The server has become disconnected before trying the", "// operation. We should try again, possibly with a ", "// different server.", "$", "this", "->", "_link", "=", "false", ";", "$", "this", "->", "performReconnect", "(", ")", ";", "}", "elseif", "(", "$", "error_code", "==", "66", ")", "{", "// Subentries present, server refused to delete.", "// Deleting subentries is the clients responsibility, but", "// since the user may not know of the subentries, we do not", "// force that here but instead notify the developer so he", "// may take actions himself.", "return", "PEAR", "::", "raiseError", "(", "\"Could not delete entry $dn because of subentries. Use the recursive parameter to delete them.\"", ")", ";", "}", "else", "{", "// Errors other than the above catched are just passed", "// back to the user so he may react upon them.", "return", "PEAR", "::", "raiseError", "(", "\"Could not delete entry \"", ".", "$", "dn", ".", "\" \"", ".", "$", "error_name", ",", "$", "error_code", ")", ";", "}", "}", "}", "}" ]
Delete an entry from the directory The object may either be a string representing the dn or a Net_LDAP2_Entry object. When the boolean paramter recursive is set, all subentries of the entry will be deleted as well. @param string|Net_LDAP2_Entry $dn DN-string or Net_LDAP2_Entry @param boolean $recursive Should we delete all children recursive as well? @access public @return Net_LDAP2_Error|true Net_LDAP2_Error object or true
[ "Delete", "an", "entry", "from", "the", "directory" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L782-L849
228,752
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.modify
public function modify($entry, $parms = array()) { if (is_string($entry)) { $entry = $this->getEntry($entry); if (self::isError($entry)) { return $entry; } } if (!$entry instanceof Net_LDAP2_Entry) { return PEAR::raiseError("Parameter is not a string nor an entry object!"); } // Perform changes mentioned separately foreach (array('add', 'delete', 'replace') as $action) { if (isset($parms[$action])) { $msg = $entry->$action($parms[$action]); if (self::isError($msg)) { return $msg; } $entry->setLDAP($this); // Because the @ldap functions are called inside Net_LDAP2_Entry::update(), // we have to trap the error codes issued from that if we want to support // reconnection. while (true) { $msg = $entry->update(); if (self::isError($msg)) { // We have a failure. What type? We may be able to reconnect // and try again. $error_code = $msg->getCode(); $error_name = Net_LDAP2::errorMessage($error_code); if ((Net_LDAP2::errorMessage($error_code) === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a different // server. $this->_link = false; $this->performReconnect(); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return PEAR::raiseError("Could not modify entry: ".$msg->getMessage()); } } else { // modification succeedet, evaluate next change break; } } } } // perform combined changes in 'changes' array if (isset($parms['changes']) && is_array($parms['changes'])) { foreach ($parms['changes'] as $action => $value) { // Because the @ldap functions are called inside Net_LDAP2_Entry::update, // we have to trap the error codes issued from that if we want to support // reconnection. while (true) { $msg = $this->modify($entry, array($action => $value)); if (self::isError($msg)) { // We have a failure. What type? We may be able to reconnect // and try again. $error_code = $msg->getCode(); $error_name = Net_LDAP2::errorMessage($error_code); if ((Net_LDAP2::errorMessage($error_code) === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a different // server. $this->_link = false; $this->performReconnect(); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return $msg; } } else { // modification succeedet, evaluate next change break; } } } } return true; }
php
public function modify($entry, $parms = array()) { if (is_string($entry)) { $entry = $this->getEntry($entry); if (self::isError($entry)) { return $entry; } } if (!$entry instanceof Net_LDAP2_Entry) { return PEAR::raiseError("Parameter is not a string nor an entry object!"); } // Perform changes mentioned separately foreach (array('add', 'delete', 'replace') as $action) { if (isset($parms[$action])) { $msg = $entry->$action($parms[$action]); if (self::isError($msg)) { return $msg; } $entry->setLDAP($this); // Because the @ldap functions are called inside Net_LDAP2_Entry::update(), // we have to trap the error codes issued from that if we want to support // reconnection. while (true) { $msg = $entry->update(); if (self::isError($msg)) { // We have a failure. What type? We may be able to reconnect // and try again. $error_code = $msg->getCode(); $error_name = Net_LDAP2::errorMessage($error_code); if ((Net_LDAP2::errorMessage($error_code) === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a different // server. $this->_link = false; $this->performReconnect(); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return PEAR::raiseError("Could not modify entry: ".$msg->getMessage()); } } else { // modification succeedet, evaluate next change break; } } } } // perform combined changes in 'changes' array if (isset($parms['changes']) && is_array($parms['changes'])) { foreach ($parms['changes'] as $action => $value) { // Because the @ldap functions are called inside Net_LDAP2_Entry::update, // we have to trap the error codes issued from that if we want to support // reconnection. while (true) { $msg = $this->modify($entry, array($action => $value)); if (self::isError($msg)) { // We have a failure. What type? We may be able to reconnect // and try again. $error_code = $msg->getCode(); $error_name = Net_LDAP2::errorMessage($error_code); if ((Net_LDAP2::errorMessage($error_code) === 'LDAP_OPERATIONS_ERROR') && ($this->_config['auto_reconnect'])) { // The server has become disconnected before trying the // operation. We should try again, possibly with a different // server. $this->_link = false; $this->performReconnect(); } else { // Errors other than the above catched are just passed // back to the user so he may react upon them. return $msg; } } else { // modification succeedet, evaluate next change break; } } } } return true; }
[ "public", "function", "modify", "(", "$", "entry", ",", "$", "parms", "=", "array", "(", ")", ")", "{", "if", "(", "is_string", "(", "$", "entry", ")", ")", "{", "$", "entry", "=", "$", "this", "->", "getEntry", "(", "$", "entry", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "entry", ")", ")", "{", "return", "$", "entry", ";", "}", "}", "if", "(", "!", "$", "entry", "instanceof", "Net_LDAP2_Entry", ")", "{", "return", "PEAR", "::", "raiseError", "(", "\"Parameter is not a string nor an entry object!\"", ")", ";", "}", "// Perform changes mentioned separately", "foreach", "(", "array", "(", "'add'", ",", "'delete'", ",", "'replace'", ")", "as", "$", "action", ")", "{", "if", "(", "isset", "(", "$", "parms", "[", "$", "action", "]", ")", ")", "{", "$", "msg", "=", "$", "entry", "->", "$", "action", "(", "$", "parms", "[", "$", "action", "]", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "msg", ")", ")", "{", "return", "$", "msg", ";", "}", "$", "entry", "->", "setLDAP", "(", "$", "this", ")", ";", "// Because the @ldap functions are called inside Net_LDAP2_Entry::update(),", "// we have to trap the error codes issued from that if we want to support", "// reconnection.", "while", "(", "true", ")", "{", "$", "msg", "=", "$", "entry", "->", "update", "(", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "msg", ")", ")", "{", "// We have a failure. What type? We may be able to reconnect", "// and try again.", "$", "error_code", "=", "$", "msg", "->", "getCode", "(", ")", ";", "$", "error_name", "=", "Net_LDAP2", "::", "errorMessage", "(", "$", "error_code", ")", ";", "if", "(", "(", "Net_LDAP2", "::", "errorMessage", "(", "$", "error_code", ")", "===", "'LDAP_OPERATIONS_ERROR'", ")", "&&", "(", "$", "this", "->", "_config", "[", "'auto_reconnect'", "]", ")", ")", "{", "// The server has become disconnected before trying the", "// operation. We should try again, possibly with a different", "// server.", "$", "this", "->", "_link", "=", "false", ";", "$", "this", "->", "performReconnect", "(", ")", ";", "}", "else", "{", "// Errors other than the above catched are just passed", "// back to the user so he may react upon them.", "return", "PEAR", "::", "raiseError", "(", "\"Could not modify entry: \"", ".", "$", "msg", "->", "getMessage", "(", ")", ")", ";", "}", "}", "else", "{", "// modification succeedet, evaluate next change", "break", ";", "}", "}", "}", "}", "// perform combined changes in 'changes' array", "if", "(", "isset", "(", "$", "parms", "[", "'changes'", "]", ")", "&&", "is_array", "(", "$", "parms", "[", "'changes'", "]", ")", ")", "{", "foreach", "(", "$", "parms", "[", "'changes'", "]", "as", "$", "action", "=>", "$", "value", ")", "{", "// Because the @ldap functions are called inside Net_LDAP2_Entry::update,", "// we have to trap the error codes issued from that if we want to support", "// reconnection.", "while", "(", "true", ")", "{", "$", "msg", "=", "$", "this", "->", "modify", "(", "$", "entry", ",", "array", "(", "$", "action", "=>", "$", "value", ")", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "msg", ")", ")", "{", "// We have a failure. What type? We may be able to reconnect", "// and try again.", "$", "error_code", "=", "$", "msg", "->", "getCode", "(", ")", ";", "$", "error_name", "=", "Net_LDAP2", "::", "errorMessage", "(", "$", "error_code", ")", ";", "if", "(", "(", "Net_LDAP2", "::", "errorMessage", "(", "$", "error_code", ")", "===", "'LDAP_OPERATIONS_ERROR'", ")", "&&", "(", "$", "this", "->", "_config", "[", "'auto_reconnect'", "]", ")", ")", "{", "// The server has become disconnected before trying the", "// operation. We should try again, possibly with a different", "// server.", "$", "this", "->", "_link", "=", "false", ";", "$", "this", "->", "performReconnect", "(", ")", ";", "}", "else", "{", "// Errors other than the above catched are just passed", "// back to the user so he may react upon them.", "return", "$", "msg", ";", "}", "}", "else", "{", "// modification succeedet, evaluate next change", "break", ";", "}", "}", "}", "}", "return", "true", ";", "}" ]
Modify an ldapentry directly on the server This one takes the DN or a Net_LDAP2_Entry object and an array of actions. This array should be something like this: array('add' => array('attribute1' => array('val1', 'val2'), 'attribute2' => array('val1')), 'delete' => array('attribute1'), 'replace' => array('attribute1' => array('val1')), 'changes' => array('add' => ..., 'replace' => ..., 'delete' => array('attribute1', 'attribute2' => array('val1'))) The changes array is there so the order of operations can be influenced (the operations are done in order of appearance). The order of execution is as following: 1. adds from 'add' array 2. deletes from 'delete' array 3. replaces from 'replace' array 4. changes (add, replace, delete) in order of appearance All subarrays (add, replace, delete, changes) may be given at the same time. The function calls the corresponding functions of an Net_LDAP2_Entry object. A detailed description of array structures can be found there. Unlike the modification methods provided by the Net_LDAP2_Entry object, this method will instantly carry out an update() after each operation, thus modifying "directly" on the server. @param string|Net_LDAP2_Entry $entry DN-string or Net_LDAP2_Entry @param array $parms Array of changes @access public @return Net_LDAP2_Error|true Net_LDAP2_Error object or true
[ "Modify", "an", "ldapentry", "directly", "on", "the", "server" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L887-L982
228,753
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.setOption
public function setOption($option, $value) { if ($this->_link) { if (defined($option)) { if (@ldap_set_option($this->_link, constant($option), $value)) { return true; } else { $err = @ldap_errno($this->_link); if ($err) { $msg = @ldap_err2str($err); } else { $err = NET_LDAP2_ERROR; $msg = Net_LDAP2::errorMessage($err); } return $this->raiseError($msg, $err); } } else { return $this->raiseError("Unkown Option requested"); } } else { return $this->raiseError("Could not set LDAP option: No LDAP connection"); } }
php
public function setOption($option, $value) { if ($this->_link) { if (defined($option)) { if (@ldap_set_option($this->_link, constant($option), $value)) { return true; } else { $err = @ldap_errno($this->_link); if ($err) { $msg = @ldap_err2str($err); } else { $err = NET_LDAP2_ERROR; $msg = Net_LDAP2::errorMessage($err); } return $this->raiseError($msg, $err); } } else { return $this->raiseError("Unkown Option requested"); } } else { return $this->raiseError("Could not set LDAP option: No LDAP connection"); } }
[ "public", "function", "setOption", "(", "$", "option", ",", "$", "value", ")", "{", "if", "(", "$", "this", "->", "_link", ")", "{", "if", "(", "defined", "(", "$", "option", ")", ")", "{", "if", "(", "@", "ldap_set_option", "(", "$", "this", "->", "_link", ",", "constant", "(", "$", "option", ")", ",", "$", "value", ")", ")", "{", "return", "true", ";", "}", "else", "{", "$", "err", "=", "@", "ldap_errno", "(", "$", "this", "->", "_link", ")", ";", "if", "(", "$", "err", ")", "{", "$", "msg", "=", "@", "ldap_err2str", "(", "$", "err", ")", ";", "}", "else", "{", "$", "err", "=", "NET_LDAP2_ERROR", ";", "$", "msg", "=", "Net_LDAP2", "::", "errorMessage", "(", "$", "err", ")", ";", "}", "return", "$", "this", "->", "raiseError", "(", "$", "msg", ",", "$", "err", ")", ";", "}", "}", "else", "{", "return", "$", "this", "->", "raiseError", "(", "\"Unkown Option requested\"", ")", ";", "}", "}", "else", "{", "return", "$", "this", "->", "raiseError", "(", "\"Could not set LDAP option: No LDAP connection\"", ")", ";", "}", "}" ]
Set an LDAP option @param string $option Option to set @param mixed $value Value to set Option to @access public @return Net_LDAP2_Error|true Net_LDAP2_Error object or true
[ "Set", "an", "LDAP", "option" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1122-L1144
228,754
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.getOption
public function getOption($option) { if ($this->_link) { if (defined($option)) { if (@ldap_get_option($this->_link, constant($option), $value)) { return $value; } else { $err = @ldap_errno($this->_link); if ($err) { $msg = @ldap_err2str($err); } else { $err = NET_LDAP2_ERROR; $msg = Net_LDAP2::errorMessage($err); } return $this->raiseError($msg, $err); } } else { $this->raiseError("Unkown Option requested"); } } else { $this->raiseError("No LDAP connection"); } }
php
public function getOption($option) { if ($this->_link) { if (defined($option)) { if (@ldap_get_option($this->_link, constant($option), $value)) { return $value; } else { $err = @ldap_errno($this->_link); if ($err) { $msg = @ldap_err2str($err); } else { $err = NET_LDAP2_ERROR; $msg = Net_LDAP2::errorMessage($err); } return $this->raiseError($msg, $err); } } else { $this->raiseError("Unkown Option requested"); } } else { $this->raiseError("No LDAP connection"); } }
[ "public", "function", "getOption", "(", "$", "option", ")", "{", "if", "(", "$", "this", "->", "_link", ")", "{", "if", "(", "defined", "(", "$", "option", ")", ")", "{", "if", "(", "@", "ldap_get_option", "(", "$", "this", "->", "_link", ",", "constant", "(", "$", "option", ")", ",", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "else", "{", "$", "err", "=", "@", "ldap_errno", "(", "$", "this", "->", "_link", ")", ";", "if", "(", "$", "err", ")", "{", "$", "msg", "=", "@", "ldap_err2str", "(", "$", "err", ")", ";", "}", "else", "{", "$", "err", "=", "NET_LDAP2_ERROR", ";", "$", "msg", "=", "Net_LDAP2", "::", "errorMessage", "(", "$", "err", ")", ";", "}", "return", "$", "this", "->", "raiseError", "(", "$", "msg", ",", "$", "err", ")", ";", "}", "}", "else", "{", "$", "this", "->", "raiseError", "(", "\"Unkown Option requested\"", ")", ";", "}", "}", "else", "{", "$", "this", "->", "raiseError", "(", "\"No LDAP connection\"", ")", ";", "}", "}" ]
Get an LDAP option value @param string $option Option to get @access public @return Net_LDAP2_Error|string Net_LDAP2_Error or option value
[ "Get", "an", "LDAP", "option", "value" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1154-L1176
228,755
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.getLDAPVersion
public function getLDAPVersion() { if ($this->_link) { $version = $this->getOption("LDAP_OPT_PROTOCOL_VERSION"); } else { $version = $this->_config['version']; } return $version; }
php
public function getLDAPVersion() { if ($this->_link) { $version = $this->getOption("LDAP_OPT_PROTOCOL_VERSION"); } else { $version = $this->_config['version']; } return $version; }
[ "public", "function", "getLDAPVersion", "(", ")", "{", "if", "(", "$", "this", "->", "_link", ")", "{", "$", "version", "=", "$", "this", "->", "getOption", "(", "\"LDAP_OPT_PROTOCOL_VERSION\"", ")", ";", "}", "else", "{", "$", "version", "=", "$", "this", "->", "_config", "[", "'version'", "]", ";", "}", "return", "$", "version", ";", "}" ]
Get the LDAP_PROTOCOL_VERSION that is used on the connection. A lot of ldap functionality is defined by what protocol version the ldap server speaks. This might be 2 or 3. @return int
[ "Get", "the", "LDAP_PROTOCOL_VERSION", "that", "is", "used", "on", "the", "connection", "." ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1186-L1194
228,756
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.setLDAPVersion
public function setLDAPVersion($version = 0, $force = false) { if (!$version) { $version = $this->_config['version']; } // // Check to see if the server supports this version first. // // Todo: Why is this so horribly slow? // $this->rootDse() is very fast, as well as Net_LDAP2_RootDSE::fetch() // seems like a problem at copiyng the object inside PHP?? // Additionally, this is not always reproducable... // if (!$force) { $rootDSE = $this->rootDse(); if ($rootDSE instanceof Net_LDAP2_Error) { return $rootDSE; } else { $supported_versions = $rootDSE->getValue('supportedLDAPVersion'); if (is_string($supported_versions)) { $supported_versions = array($supported_versions); } $check_ok = in_array($version, $supported_versions); } } if ($force || $check_ok) { return $this->setOption("LDAP_OPT_PROTOCOL_VERSION", $version); } else { return $this->raiseError("LDAP Server does not support protocol version " . $version); } }
php
public function setLDAPVersion($version = 0, $force = false) { if (!$version) { $version = $this->_config['version']; } // // Check to see if the server supports this version first. // // Todo: Why is this so horribly slow? // $this->rootDse() is very fast, as well as Net_LDAP2_RootDSE::fetch() // seems like a problem at copiyng the object inside PHP?? // Additionally, this is not always reproducable... // if (!$force) { $rootDSE = $this->rootDse(); if ($rootDSE instanceof Net_LDAP2_Error) { return $rootDSE; } else { $supported_versions = $rootDSE->getValue('supportedLDAPVersion'); if (is_string($supported_versions)) { $supported_versions = array($supported_versions); } $check_ok = in_array($version, $supported_versions); } } if ($force || $check_ok) { return $this->setOption("LDAP_OPT_PROTOCOL_VERSION", $version); } else { return $this->raiseError("LDAP Server does not support protocol version " . $version); } }
[ "public", "function", "setLDAPVersion", "(", "$", "version", "=", "0", ",", "$", "force", "=", "false", ")", "{", "if", "(", "!", "$", "version", ")", "{", "$", "version", "=", "$", "this", "->", "_config", "[", "'version'", "]", ";", "}", "//", "// Check to see if the server supports this version first.", "//", "// Todo: Why is this so horribly slow?", "// $this->rootDse() is very fast, as well as Net_LDAP2_RootDSE::fetch()", "// seems like a problem at copiyng the object inside PHP??", "// Additionally, this is not always reproducable...", "//", "if", "(", "!", "$", "force", ")", "{", "$", "rootDSE", "=", "$", "this", "->", "rootDse", "(", ")", ";", "if", "(", "$", "rootDSE", "instanceof", "Net_LDAP2_Error", ")", "{", "return", "$", "rootDSE", ";", "}", "else", "{", "$", "supported_versions", "=", "$", "rootDSE", "->", "getValue", "(", "'supportedLDAPVersion'", ")", ";", "if", "(", "is_string", "(", "$", "supported_versions", ")", ")", "{", "$", "supported_versions", "=", "array", "(", "$", "supported_versions", ")", ";", "}", "$", "check_ok", "=", "in_array", "(", "$", "version", ",", "$", "supported_versions", ")", ";", "}", "}", "if", "(", "$", "force", "||", "$", "check_ok", ")", "{", "return", "$", "this", "->", "setOption", "(", "\"LDAP_OPT_PROTOCOL_VERSION\"", ",", "$", "version", ")", ";", "}", "else", "{", "return", "$", "this", "->", "raiseError", "(", "\"LDAP Server does not support protocol version \"", ".", "$", "version", ")", ";", "}", "}" ]
Set the LDAP_PROTOCOL_VERSION that is used on the connection. @param int $version LDAP-version that should be used @param boolean $force If set to true, the check against the rootDSE will be skipped @return Net_LDAP2_Error|true Net_LDAP2_Error object or true @todo Checking via the rootDSE takes much time - why? fetching and instanciation is quick!
[ "Set", "the", "LDAP_PROTOCOL_VERSION", "that", "is", "used", "on", "the", "connection", "." ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1205-L1237
228,757
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.dnExists
public function dnExists($dn) { if (PEAR::isError($dn)) { return $dn; } if ($dn instanceof Net_LDAP2_Entry) { $dn = $dn->dn(); } if (false === is_string($dn)) { return PEAR::raiseError('Parameter $dn is not a string nor an entry object!'); } // search LDAP for that DN by performing a baselevel search for any // object. We can only find the DN in question this way, or nothing. $s_opts = array( 'scope' => 'base', 'sizelimit' => 1, 'attributes' => '1.1' // select no attrs ); $search = $this->search($dn, '(objectClass=*)', $s_opts); if (self::isError($search)) { return $search; } // retun wehter the DN exists; that is, we found an entry return ($search->count() == 0)? false : true; }
php
public function dnExists($dn) { if (PEAR::isError($dn)) { return $dn; } if ($dn instanceof Net_LDAP2_Entry) { $dn = $dn->dn(); } if (false === is_string($dn)) { return PEAR::raiseError('Parameter $dn is not a string nor an entry object!'); } // search LDAP for that DN by performing a baselevel search for any // object. We can only find the DN in question this way, or nothing. $s_opts = array( 'scope' => 'base', 'sizelimit' => 1, 'attributes' => '1.1' // select no attrs ); $search = $this->search($dn, '(objectClass=*)', $s_opts); if (self::isError($search)) { return $search; } // retun wehter the DN exists; that is, we found an entry return ($search->count() == 0)? false : true; }
[ "public", "function", "dnExists", "(", "$", "dn", ")", "{", "if", "(", "PEAR", "::", "isError", "(", "$", "dn", ")", ")", "{", "return", "$", "dn", ";", "}", "if", "(", "$", "dn", "instanceof", "Net_LDAP2_Entry", ")", "{", "$", "dn", "=", "$", "dn", "->", "dn", "(", ")", ";", "}", "if", "(", "false", "===", "is_string", "(", "$", "dn", ")", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Parameter $dn is not a string nor an entry object!'", ")", ";", "}", "// search LDAP for that DN by performing a baselevel search for any", "// object. We can only find the DN in question this way, or nothing.", "$", "s_opts", "=", "array", "(", "'scope'", "=>", "'base'", ",", "'sizelimit'", "=>", "1", ",", "'attributes'", "=>", "'1.1'", "// select no attrs", ")", ";", "$", "search", "=", "$", "this", "->", "search", "(", "$", "dn", ",", "'(objectClass=*)'", ",", "$", "s_opts", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "search", ")", ")", "{", "return", "$", "search", ";", "}", "// retun wehter the DN exists; that is, we found an entry", "return", "(", "$", "search", "->", "count", "(", ")", "==", "0", ")", "?", "false", ":", "true", ";", "}" ]
Tells if a DN does exist in the directory @param string|Net_LDAP2_Entry $dn The DN of the object to test @return boolean|Net_LDAP2_Error
[ "Tells", "if", "a", "DN", "does", "exist", "in", "the", "directory" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1247-L1274
228,758
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.getEntry
public function getEntry($dn, $attr = array()) { if (!is_array($attr)) { $attr = array($attr); } $result = $this->search($dn, '(objectClass=*)', array('scope' => 'base', 'attributes' => $attr)); if (self::isError($result)) { return $result; } elseif ($result->count() == 0) { return PEAR::raiseError('Could not fetch entry '.$dn.': no entry found'); } $entry = $result->shiftEntry(); if (false == $entry) { return PEAR::raiseError('Could not fetch entry (error retrieving entry from search result)'); } return $entry; }
php
public function getEntry($dn, $attr = array()) { if (!is_array($attr)) { $attr = array($attr); } $result = $this->search($dn, '(objectClass=*)', array('scope' => 'base', 'attributes' => $attr)); if (self::isError($result)) { return $result; } elseif ($result->count() == 0) { return PEAR::raiseError('Could not fetch entry '.$dn.': no entry found'); } $entry = $result->shiftEntry(); if (false == $entry) { return PEAR::raiseError('Could not fetch entry (error retrieving entry from search result)'); } return $entry; }
[ "public", "function", "getEntry", "(", "$", "dn", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "if", "(", "!", "is_array", "(", "$", "attr", ")", ")", "{", "$", "attr", "=", "array", "(", "$", "attr", ")", ";", "}", "$", "result", "=", "$", "this", "->", "search", "(", "$", "dn", ",", "'(objectClass=*)'", ",", "array", "(", "'scope'", "=>", "'base'", ",", "'attributes'", "=>", "$", "attr", ")", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "result", ")", ")", "{", "return", "$", "result", ";", "}", "elseif", "(", "$", "result", "->", "count", "(", ")", "==", "0", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Could not fetch entry '", ".", "$", "dn", ".", "': no entry found'", ")", ";", "}", "$", "entry", "=", "$", "result", "->", "shiftEntry", "(", ")", ";", "if", "(", "false", "==", "$", "entry", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Could not fetch entry (error retrieving entry from search result)'", ")", ";", "}", "return", "$", "entry", ";", "}" ]
Get a specific entry based on the DN @param string $dn DN of the entry that should be fetched @param array $attr Array of Attributes to select. If ommitted, all attributes are fetched. @return Net_LDAP2_Entry|Net_LDAP2_Error Reference to a Net_LDAP2_Entry object or Net_LDAP2_Error object @todo Maybe check against the shema should be done to be sure the attribute type exists
[ "Get", "a", "specific", "entry", "based", "on", "the", "DN" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1286-L1303
228,759
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.move
public function move($entry, $newdn, $target_ldap = null) { if (is_string($entry)) { $entry_o = $this->getEntry($entry); } else { $entry_o = $entry; } if (!$entry_o instanceof Net_LDAP2_Entry) { return PEAR::raiseError('Parameter $entry is expected to be a Net_LDAP2_Entry object! (If DN was passed, conversion failed)'); } if (null !== $target_ldap && !$target_ldap instanceof Net_LDAP2) { return PEAR::raiseError('Parameter $target_ldap is expected to be a Net_LDAP2 object!'); } if ($target_ldap && $target_ldap !== $this) { // cross directory move if (is_string($entry)) { return PEAR::raiseError('Unable to perform cross directory move: operation requires a Net_LDAP2_Entry object'); } if ($target_ldap->dnExists($newdn)) { return PEAR::raiseError('Unable to perform cross directory move: entry does exist in target directory'); } $entry_o->dn($newdn); $res = $target_ldap->add($entry_o); if (self::isError($res)) { return PEAR::raiseError('Unable to perform cross directory move: '.$res->getMessage().' in target directory'); } $res = $this->delete($entry_o->currentDN()); if (self::isError($res)) { $res2 = $target_ldap->delete($entry_o); // undo add if (self::isError($res2)) { $add_error_string = 'Additionally, the deletion (undo add) of $entry in target directory failed.'; } return PEAR::raiseError('Unable to perform cross directory move: '.$res->getMessage().' in source directory. '.$add_error_string); } $entry_o->setLDAP($target_ldap); return true; } else { // local move $entry_o->dn($newdn); $entry_o->setLDAP($this); return $entry_o->update(); } }
php
public function move($entry, $newdn, $target_ldap = null) { if (is_string($entry)) { $entry_o = $this->getEntry($entry); } else { $entry_o = $entry; } if (!$entry_o instanceof Net_LDAP2_Entry) { return PEAR::raiseError('Parameter $entry is expected to be a Net_LDAP2_Entry object! (If DN was passed, conversion failed)'); } if (null !== $target_ldap && !$target_ldap instanceof Net_LDAP2) { return PEAR::raiseError('Parameter $target_ldap is expected to be a Net_LDAP2 object!'); } if ($target_ldap && $target_ldap !== $this) { // cross directory move if (is_string($entry)) { return PEAR::raiseError('Unable to perform cross directory move: operation requires a Net_LDAP2_Entry object'); } if ($target_ldap->dnExists($newdn)) { return PEAR::raiseError('Unable to perform cross directory move: entry does exist in target directory'); } $entry_o->dn($newdn); $res = $target_ldap->add($entry_o); if (self::isError($res)) { return PEAR::raiseError('Unable to perform cross directory move: '.$res->getMessage().' in target directory'); } $res = $this->delete($entry_o->currentDN()); if (self::isError($res)) { $res2 = $target_ldap->delete($entry_o); // undo add if (self::isError($res2)) { $add_error_string = 'Additionally, the deletion (undo add) of $entry in target directory failed.'; } return PEAR::raiseError('Unable to perform cross directory move: '.$res->getMessage().' in source directory. '.$add_error_string); } $entry_o->setLDAP($target_ldap); return true; } else { // local move $entry_o->dn($newdn); $entry_o->setLDAP($this); return $entry_o->update(); } }
[ "public", "function", "move", "(", "$", "entry", ",", "$", "newdn", ",", "$", "target_ldap", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "entry", ")", ")", "{", "$", "entry_o", "=", "$", "this", "->", "getEntry", "(", "$", "entry", ")", ";", "}", "else", "{", "$", "entry_o", "=", "$", "entry", ";", "}", "if", "(", "!", "$", "entry_o", "instanceof", "Net_LDAP2_Entry", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Parameter $entry is expected to be a Net_LDAP2_Entry object! (If DN was passed, conversion failed)'", ")", ";", "}", "if", "(", "null", "!==", "$", "target_ldap", "&&", "!", "$", "target_ldap", "instanceof", "Net_LDAP2", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Parameter $target_ldap is expected to be a Net_LDAP2 object!'", ")", ";", "}", "if", "(", "$", "target_ldap", "&&", "$", "target_ldap", "!==", "$", "this", ")", "{", "// cross directory move", "if", "(", "is_string", "(", "$", "entry", ")", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Unable to perform cross directory move: operation requires a Net_LDAP2_Entry object'", ")", ";", "}", "if", "(", "$", "target_ldap", "->", "dnExists", "(", "$", "newdn", ")", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Unable to perform cross directory move: entry does exist in target directory'", ")", ";", "}", "$", "entry_o", "->", "dn", "(", "$", "newdn", ")", ";", "$", "res", "=", "$", "target_ldap", "->", "add", "(", "$", "entry_o", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "res", ")", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Unable to perform cross directory move: '", ".", "$", "res", "->", "getMessage", "(", ")", ".", "' in target directory'", ")", ";", "}", "$", "res", "=", "$", "this", "->", "delete", "(", "$", "entry_o", "->", "currentDN", "(", ")", ")", ";", "if", "(", "self", "::", "isError", "(", "$", "res", ")", ")", "{", "$", "res2", "=", "$", "target_ldap", "->", "delete", "(", "$", "entry_o", ")", ";", "// undo add", "if", "(", "self", "::", "isError", "(", "$", "res2", ")", ")", "{", "$", "add_error_string", "=", "'Additionally, the deletion (undo add) of $entry in target directory failed.'", ";", "}", "return", "PEAR", "::", "raiseError", "(", "'Unable to perform cross directory move: '", ".", "$", "res", "->", "getMessage", "(", ")", ".", "' in source directory. '", ".", "$", "add_error_string", ")", ";", "}", "$", "entry_o", "->", "setLDAP", "(", "$", "target_ldap", ")", ";", "return", "true", ";", "}", "else", "{", "// local move", "$", "entry_o", "->", "dn", "(", "$", "newdn", ")", ";", "$", "entry_o", "->", "setLDAP", "(", "$", "this", ")", ";", "return", "$", "entry_o", "->", "update", "(", ")", ";", "}", "}" ]
Rename or move an entry This method will instantly carry out an update() after the move, so the entry is moved instantly. You can pass an optional Net_LDAP2 object. In this case, a cross directory move will be performed which deletes the entry in the source (THIS) directory and adds it in the directory $target_ldap. A cross directory move will switch the Entrys internal LDAP reference so updates to the entry will go to the new directory. Note that if you want to do a cross directory move, you need to pass an Net_LDAP2_Entry object, otherwise the attributes will be empty. @param string|Net_LDAP2_Entry $entry Entry DN or Entry object @param string $newdn New location @param Net_LDAP2 $target_ldap (optional) Target directory for cross server move; should be passed via reference @return Net_LDAP2_Error|true
[ "Rename", "or", "move", "an", "entry" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1325-L1368
228,760
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.copy
public function copy($entry, $newdn) { if (!$entry instanceof Net_LDAP2_Entry) { return PEAR::raiseError('Parameter $entry is expected to be a Net_LDAP2_Entry object!'); } $newentry = Net_LDAP2_Entry::createFresh($newdn, $entry->getValues()); $result = $this->add($newentry); if ($result instanceof Net_LDAP2_Error) { return $result; } else { return $newentry; } }
php
public function copy($entry, $newdn) { if (!$entry instanceof Net_LDAP2_Entry) { return PEAR::raiseError('Parameter $entry is expected to be a Net_LDAP2_Entry object!'); } $newentry = Net_LDAP2_Entry::createFresh($newdn, $entry->getValues()); $result = $this->add($newentry); if ($result instanceof Net_LDAP2_Error) { return $result; } else { return $newentry; } }
[ "public", "function", "copy", "(", "$", "entry", ",", "$", "newdn", ")", "{", "if", "(", "!", "$", "entry", "instanceof", "Net_LDAP2_Entry", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Parameter $entry is expected to be a Net_LDAP2_Entry object!'", ")", ";", "}", "$", "newentry", "=", "Net_LDAP2_Entry", "::", "createFresh", "(", "$", "newdn", ",", "$", "entry", "->", "getValues", "(", ")", ")", ";", "$", "result", "=", "$", "this", "->", "add", "(", "$", "newentry", ")", ";", "if", "(", "$", "result", "instanceof", "Net_LDAP2_Error", ")", "{", "return", "$", "result", ";", "}", "else", "{", "return", "$", "newentry", ";", "}", "}" ]
Copy an entry to a new location The entry will be immediately copied. Please note that only attributes you have selected will be copied. @param Net_LDAP2_Entry $entry Entry object @param string $newdn New FQF-DN of the entry @return Net_LDAP2_Error|Net_LDAP2_Entry Error Message or reference to the copied entry
[ "Copy", "an", "entry", "to", "a", "new", "location" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1382-L1396
228,761
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.errorMessage
public static function errorMessage($errorcode) { $errorMessages = array( 0x00 => "LDAP_SUCCESS", 0x01 => "LDAP_OPERATIONS_ERROR", 0x02 => "LDAP_PROTOCOL_ERROR", 0x03 => "LDAP_TIMELIMIT_EXCEEDED", 0x04 => "LDAP_SIZELIMIT_EXCEEDED", 0x05 => "LDAP_COMPARE_FALSE", 0x06 => "LDAP_COMPARE_TRUE", 0x07 => "LDAP_AUTH_METHOD_NOT_SUPPORTED", 0x08 => "LDAP_STRONG_AUTH_REQUIRED", 0x09 => "LDAP_PARTIAL_RESULTS", 0x0a => "LDAP_REFERRAL", 0x0b => "LDAP_ADMINLIMIT_EXCEEDED", 0x0c => "LDAP_UNAVAILABLE_CRITICAL_EXTENSION", 0x0d => "LDAP_CONFIDENTIALITY_REQUIRED", 0x0e => "LDAP_SASL_BIND_INPROGRESS", 0x10 => "LDAP_NO_SUCH_ATTRIBUTE", 0x11 => "LDAP_UNDEFINED_TYPE", 0x12 => "LDAP_INAPPROPRIATE_MATCHING", 0x13 => "LDAP_CONSTRAINT_VIOLATION", 0x14 => "LDAP_TYPE_OR_VALUE_EXISTS", 0x15 => "LDAP_INVALID_SYNTAX", 0x20 => "LDAP_NO_SUCH_OBJECT", 0x21 => "LDAP_ALIAS_PROBLEM", 0x22 => "LDAP_INVALID_DN_SYNTAX", 0x23 => "LDAP_IS_LEAF", 0x24 => "LDAP_ALIAS_DEREF_PROBLEM", 0x30 => "LDAP_INAPPROPRIATE_AUTH", 0x31 => "LDAP_INVALID_CREDENTIALS", 0x32 => "LDAP_INSUFFICIENT_ACCESS", 0x33 => "LDAP_BUSY", 0x34 => "LDAP_UNAVAILABLE", 0x35 => "LDAP_UNWILLING_TO_PERFORM", 0x36 => "LDAP_LOOP_DETECT", 0x3C => "LDAP_SORT_CONTROL_MISSING", 0x3D => "LDAP_INDEX_RANGE_ERROR", 0x40 => "LDAP_NAMING_VIOLATION", 0x41 => "LDAP_OBJECT_CLASS_VIOLATION", 0x42 => "LDAP_NOT_ALLOWED_ON_NONLEAF", 0x43 => "LDAP_NOT_ALLOWED_ON_RDN", 0x44 => "LDAP_ALREADY_EXISTS", 0x45 => "LDAP_NO_OBJECT_CLASS_MODS", 0x46 => "LDAP_RESULTS_TOO_LARGE", 0x47 => "LDAP_AFFECTS_MULTIPLE_DSAS", 0x50 => "LDAP_OTHER", 0x51 => "LDAP_SERVER_DOWN", 0x52 => "LDAP_LOCAL_ERROR", 0x53 => "LDAP_ENCODING_ERROR", 0x54 => "LDAP_DECODING_ERROR", 0x55 => "LDAP_TIMEOUT", 0x56 => "LDAP_AUTH_UNKNOWN", 0x57 => "LDAP_FILTER_ERROR", 0x58 => "LDAP_USER_CANCELLED", 0x59 => "LDAP_PARAM_ERROR", 0x5a => "LDAP_NO_MEMORY", 0x5b => "LDAP_CONNECT_ERROR", 0x5c => "LDAP_NOT_SUPPORTED", 0x5d => "LDAP_CONTROL_NOT_FOUND", 0x5e => "LDAP_NO_RESULTS_RETURNED", 0x5f => "LDAP_MORE_RESULTS_TO_RETURN", 0x60 => "LDAP_CLIENT_LOOP", 0x61 => "LDAP_REFERRAL_LIMIT_EXCEEDED", 1000 => "Unknown Net_LDAP2 Error" ); return isset($errorMessages[$errorcode]) ? $errorMessages[$errorcode] : $errorMessages[NET_LDAP2_ERROR] . ' (' . $errorcode . ')'; }
php
public static function errorMessage($errorcode) { $errorMessages = array( 0x00 => "LDAP_SUCCESS", 0x01 => "LDAP_OPERATIONS_ERROR", 0x02 => "LDAP_PROTOCOL_ERROR", 0x03 => "LDAP_TIMELIMIT_EXCEEDED", 0x04 => "LDAP_SIZELIMIT_EXCEEDED", 0x05 => "LDAP_COMPARE_FALSE", 0x06 => "LDAP_COMPARE_TRUE", 0x07 => "LDAP_AUTH_METHOD_NOT_SUPPORTED", 0x08 => "LDAP_STRONG_AUTH_REQUIRED", 0x09 => "LDAP_PARTIAL_RESULTS", 0x0a => "LDAP_REFERRAL", 0x0b => "LDAP_ADMINLIMIT_EXCEEDED", 0x0c => "LDAP_UNAVAILABLE_CRITICAL_EXTENSION", 0x0d => "LDAP_CONFIDENTIALITY_REQUIRED", 0x0e => "LDAP_SASL_BIND_INPROGRESS", 0x10 => "LDAP_NO_SUCH_ATTRIBUTE", 0x11 => "LDAP_UNDEFINED_TYPE", 0x12 => "LDAP_INAPPROPRIATE_MATCHING", 0x13 => "LDAP_CONSTRAINT_VIOLATION", 0x14 => "LDAP_TYPE_OR_VALUE_EXISTS", 0x15 => "LDAP_INVALID_SYNTAX", 0x20 => "LDAP_NO_SUCH_OBJECT", 0x21 => "LDAP_ALIAS_PROBLEM", 0x22 => "LDAP_INVALID_DN_SYNTAX", 0x23 => "LDAP_IS_LEAF", 0x24 => "LDAP_ALIAS_DEREF_PROBLEM", 0x30 => "LDAP_INAPPROPRIATE_AUTH", 0x31 => "LDAP_INVALID_CREDENTIALS", 0x32 => "LDAP_INSUFFICIENT_ACCESS", 0x33 => "LDAP_BUSY", 0x34 => "LDAP_UNAVAILABLE", 0x35 => "LDAP_UNWILLING_TO_PERFORM", 0x36 => "LDAP_LOOP_DETECT", 0x3C => "LDAP_SORT_CONTROL_MISSING", 0x3D => "LDAP_INDEX_RANGE_ERROR", 0x40 => "LDAP_NAMING_VIOLATION", 0x41 => "LDAP_OBJECT_CLASS_VIOLATION", 0x42 => "LDAP_NOT_ALLOWED_ON_NONLEAF", 0x43 => "LDAP_NOT_ALLOWED_ON_RDN", 0x44 => "LDAP_ALREADY_EXISTS", 0x45 => "LDAP_NO_OBJECT_CLASS_MODS", 0x46 => "LDAP_RESULTS_TOO_LARGE", 0x47 => "LDAP_AFFECTS_MULTIPLE_DSAS", 0x50 => "LDAP_OTHER", 0x51 => "LDAP_SERVER_DOWN", 0x52 => "LDAP_LOCAL_ERROR", 0x53 => "LDAP_ENCODING_ERROR", 0x54 => "LDAP_DECODING_ERROR", 0x55 => "LDAP_TIMEOUT", 0x56 => "LDAP_AUTH_UNKNOWN", 0x57 => "LDAP_FILTER_ERROR", 0x58 => "LDAP_USER_CANCELLED", 0x59 => "LDAP_PARAM_ERROR", 0x5a => "LDAP_NO_MEMORY", 0x5b => "LDAP_CONNECT_ERROR", 0x5c => "LDAP_NOT_SUPPORTED", 0x5d => "LDAP_CONTROL_NOT_FOUND", 0x5e => "LDAP_NO_RESULTS_RETURNED", 0x5f => "LDAP_MORE_RESULTS_TO_RETURN", 0x60 => "LDAP_CLIENT_LOOP", 0x61 => "LDAP_REFERRAL_LIMIT_EXCEEDED", 1000 => "Unknown Net_LDAP2 Error" ); return isset($errorMessages[$errorcode]) ? $errorMessages[$errorcode] : $errorMessages[NET_LDAP2_ERROR] . ' (' . $errorcode . ')'; }
[ "public", "static", "function", "errorMessage", "(", "$", "errorcode", ")", "{", "$", "errorMessages", "=", "array", "(", "0x00", "=>", "\"LDAP_SUCCESS\"", ",", "0x01", "=>", "\"LDAP_OPERATIONS_ERROR\"", ",", "0x02", "=>", "\"LDAP_PROTOCOL_ERROR\"", ",", "0x03", "=>", "\"LDAP_TIMELIMIT_EXCEEDED\"", ",", "0x04", "=>", "\"LDAP_SIZELIMIT_EXCEEDED\"", ",", "0x05", "=>", "\"LDAP_COMPARE_FALSE\"", ",", "0x06", "=>", "\"LDAP_COMPARE_TRUE\"", ",", "0x07", "=>", "\"LDAP_AUTH_METHOD_NOT_SUPPORTED\"", ",", "0x08", "=>", "\"LDAP_STRONG_AUTH_REQUIRED\"", ",", "0x09", "=>", "\"LDAP_PARTIAL_RESULTS\"", ",", "0x0a", "=>", "\"LDAP_REFERRAL\"", ",", "0x0b", "=>", "\"LDAP_ADMINLIMIT_EXCEEDED\"", ",", "0x0c", "=>", "\"LDAP_UNAVAILABLE_CRITICAL_EXTENSION\"", ",", "0x0d", "=>", "\"LDAP_CONFIDENTIALITY_REQUIRED\"", ",", "0x0e", "=>", "\"LDAP_SASL_BIND_INPROGRESS\"", ",", "0x10", "=>", "\"LDAP_NO_SUCH_ATTRIBUTE\"", ",", "0x11", "=>", "\"LDAP_UNDEFINED_TYPE\"", ",", "0x12", "=>", "\"LDAP_INAPPROPRIATE_MATCHING\"", ",", "0x13", "=>", "\"LDAP_CONSTRAINT_VIOLATION\"", ",", "0x14", "=>", "\"LDAP_TYPE_OR_VALUE_EXISTS\"", ",", "0x15", "=>", "\"LDAP_INVALID_SYNTAX\"", ",", "0x20", "=>", "\"LDAP_NO_SUCH_OBJECT\"", ",", "0x21", "=>", "\"LDAP_ALIAS_PROBLEM\"", ",", "0x22", "=>", "\"LDAP_INVALID_DN_SYNTAX\"", ",", "0x23", "=>", "\"LDAP_IS_LEAF\"", ",", "0x24", "=>", "\"LDAP_ALIAS_DEREF_PROBLEM\"", ",", "0x30", "=>", "\"LDAP_INAPPROPRIATE_AUTH\"", ",", "0x31", "=>", "\"LDAP_INVALID_CREDENTIALS\"", ",", "0x32", "=>", "\"LDAP_INSUFFICIENT_ACCESS\"", ",", "0x33", "=>", "\"LDAP_BUSY\"", ",", "0x34", "=>", "\"LDAP_UNAVAILABLE\"", ",", "0x35", "=>", "\"LDAP_UNWILLING_TO_PERFORM\"", ",", "0x36", "=>", "\"LDAP_LOOP_DETECT\"", ",", "0x3C", "=>", "\"LDAP_SORT_CONTROL_MISSING\"", ",", "0x3D", "=>", "\"LDAP_INDEX_RANGE_ERROR\"", ",", "0x40", "=>", "\"LDAP_NAMING_VIOLATION\"", ",", "0x41", "=>", "\"LDAP_OBJECT_CLASS_VIOLATION\"", ",", "0x42", "=>", "\"LDAP_NOT_ALLOWED_ON_NONLEAF\"", ",", "0x43", "=>", "\"LDAP_NOT_ALLOWED_ON_RDN\"", ",", "0x44", "=>", "\"LDAP_ALREADY_EXISTS\"", ",", "0x45", "=>", "\"LDAP_NO_OBJECT_CLASS_MODS\"", ",", "0x46", "=>", "\"LDAP_RESULTS_TOO_LARGE\"", ",", "0x47", "=>", "\"LDAP_AFFECTS_MULTIPLE_DSAS\"", ",", "0x50", "=>", "\"LDAP_OTHER\"", ",", "0x51", "=>", "\"LDAP_SERVER_DOWN\"", ",", "0x52", "=>", "\"LDAP_LOCAL_ERROR\"", ",", "0x53", "=>", "\"LDAP_ENCODING_ERROR\"", ",", "0x54", "=>", "\"LDAP_DECODING_ERROR\"", ",", "0x55", "=>", "\"LDAP_TIMEOUT\"", ",", "0x56", "=>", "\"LDAP_AUTH_UNKNOWN\"", ",", "0x57", "=>", "\"LDAP_FILTER_ERROR\"", ",", "0x58", "=>", "\"LDAP_USER_CANCELLED\"", ",", "0x59", "=>", "\"LDAP_PARAM_ERROR\"", ",", "0x5a", "=>", "\"LDAP_NO_MEMORY\"", ",", "0x5b", "=>", "\"LDAP_CONNECT_ERROR\"", ",", "0x5c", "=>", "\"LDAP_NOT_SUPPORTED\"", ",", "0x5d", "=>", "\"LDAP_CONTROL_NOT_FOUND\"", ",", "0x5e", "=>", "\"LDAP_NO_RESULTS_RETURNED\"", ",", "0x5f", "=>", "\"LDAP_MORE_RESULTS_TO_RETURN\"", ",", "0x60", "=>", "\"LDAP_CLIENT_LOOP\"", ",", "0x61", "=>", "\"LDAP_REFERRAL_LIMIT_EXCEEDED\"", ",", "1000", "=>", "\"Unknown Net_LDAP2 Error\"", ")", ";", "return", "isset", "(", "$", "errorMessages", "[", "$", "errorcode", "]", ")", "?", "$", "errorMessages", "[", "$", "errorcode", "]", ":", "$", "errorMessages", "[", "NET_LDAP2_ERROR", "]", ".", "' ('", ".", "$", "errorcode", ".", "')'", ";", "}" ]
Returns the string for an ldap errorcode. Made to be able to make better errorhandling Function based on DB::errorMessage() Tip: The best description of the errorcodes is found here: http://www.directory-info.com/LDAP2/LDAPErrorCodes.html @param int $errorcode Error code @return string The errorstring for the error.
[ "Returns", "the", "string", "for", "an", "ldap", "errorcode", "." ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1411-L1481
228,762
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.rootDse
public function rootDse($attrs = null) { if ($attrs !== null && !is_array($attrs)) { return PEAR::raiseError('Parameter $attr is expected to be an array!'); } $attrs_signature = serialize($attrs); // see if we need to fetch a fresh object, or if we already // requested this object with the same attributes if (true || !array_key_exists($attrs_signature, $this->_rootDSE_cache)) { $rootdse = Net_LDAP2_RootDSE::fetch($this, $attrs); if ($rootdse instanceof Net_LDAP2_Error) { return $rootdse; } // search was ok, store rootDSE in cache $this->_rootDSE_cache[$attrs_signature] = $rootdse; } return $this->_rootDSE_cache[$attrs_signature]; }
php
public function rootDse($attrs = null) { if ($attrs !== null && !is_array($attrs)) { return PEAR::raiseError('Parameter $attr is expected to be an array!'); } $attrs_signature = serialize($attrs); // see if we need to fetch a fresh object, or if we already // requested this object with the same attributes if (true || !array_key_exists($attrs_signature, $this->_rootDSE_cache)) { $rootdse = Net_LDAP2_RootDSE::fetch($this, $attrs); if ($rootdse instanceof Net_LDAP2_Error) { return $rootdse; } // search was ok, store rootDSE in cache $this->_rootDSE_cache[$attrs_signature] = $rootdse; } return $this->_rootDSE_cache[$attrs_signature]; }
[ "public", "function", "rootDse", "(", "$", "attrs", "=", "null", ")", "{", "if", "(", "$", "attrs", "!==", "null", "&&", "!", "is_array", "(", "$", "attrs", ")", ")", "{", "return", "PEAR", "::", "raiseError", "(", "'Parameter $attr is expected to be an array!'", ")", ";", "}", "$", "attrs_signature", "=", "serialize", "(", "$", "attrs", ")", ";", "// see if we need to fetch a fresh object, or if we already", "// requested this object with the same attributes", "if", "(", "true", "||", "!", "array_key_exists", "(", "$", "attrs_signature", ",", "$", "this", "->", "_rootDSE_cache", ")", ")", "{", "$", "rootdse", "=", "Net_LDAP2_RootDSE", "::", "fetch", "(", "$", "this", ",", "$", "attrs", ")", ";", "if", "(", "$", "rootdse", "instanceof", "Net_LDAP2_Error", ")", "{", "return", "$", "rootdse", ";", "}", "// search was ok, store rootDSE in cache", "$", "this", "->", "_rootDSE_cache", "[", "$", "attrs_signature", "]", "=", "$", "rootdse", ";", "}", "return", "$", "this", "->", "_rootDSE_cache", "[", "$", "attrs_signature", "]", ";", "}" ]
Gets a rootDSE object This either fetches a fresh rootDSE object or returns it from the internal cache for performance reasons, if possible. @param array $attrs Array of attributes to search for @access public @return Net_LDAP2_Error|Net_LDAP2_RootDSE Net_LDAP2_Error or Net_LDAP2_RootDSE object
[ "Gets", "a", "rootDSE", "object" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1494-L1514
228,763
pear/Net_LDAP2
Net/LDAP2.php
Net_LDAP2.schema
public function schema($dn = null) { // Schema caching by Knut-Olav Hoven // If a schema caching object is registered, we use that to fetch // a schema object. // See registerSchemaCache() for more info on this. if ($this->_schema === null) { if ($this->_schema_cache) { $cached_schema = $this->_schema_cache->loadSchema(); if ($cached_schema instanceof Net_LDAP2_Error) { return $cached_schema; // route error to client } else { if ($cached_schema instanceof Net_LDAP2_Schema) { $this->_schema = $cached_schema; } } } } // Fetch schema, if not tried before and no cached version available. // If we are already fetching the schema, we will skip fetching. if ($this->_schema === null) { // store a temporary error message so subsequent calls to schema() can // detect, that we are fetching the schema already. // Otherwise we will get an infinite loop at Net_LDAP2_Schema::fetch() $this->_schema = new Net_LDAP2_Error('Schema not initialized'); $this->_schema = Net_LDAP2_Schema::fetch($this, $dn); // If schema caching is active, advise the cache to store the schema if ($this->_schema_cache) { $caching_result = $this->_schema_cache->storeSchema($this->_schema); if ($caching_result instanceof Net_LDAP2_Error) { return $caching_result; // route error to client } } } return $this->_schema; }
php
public function schema($dn = null) { // Schema caching by Knut-Olav Hoven // If a schema caching object is registered, we use that to fetch // a schema object. // See registerSchemaCache() for more info on this. if ($this->_schema === null) { if ($this->_schema_cache) { $cached_schema = $this->_schema_cache->loadSchema(); if ($cached_schema instanceof Net_LDAP2_Error) { return $cached_schema; // route error to client } else { if ($cached_schema instanceof Net_LDAP2_Schema) { $this->_schema = $cached_schema; } } } } // Fetch schema, if not tried before and no cached version available. // If we are already fetching the schema, we will skip fetching. if ($this->_schema === null) { // store a temporary error message so subsequent calls to schema() can // detect, that we are fetching the schema already. // Otherwise we will get an infinite loop at Net_LDAP2_Schema::fetch() $this->_schema = new Net_LDAP2_Error('Schema not initialized'); $this->_schema = Net_LDAP2_Schema::fetch($this, $dn); // If schema caching is active, advise the cache to store the schema if ($this->_schema_cache) { $caching_result = $this->_schema_cache->storeSchema($this->_schema); if ($caching_result instanceof Net_LDAP2_Error) { return $caching_result; // route error to client } } } return $this->_schema; }
[ "public", "function", "schema", "(", "$", "dn", "=", "null", ")", "{", "// Schema caching by Knut-Olav Hoven", "// If a schema caching object is registered, we use that to fetch", "// a schema object.", "// See registerSchemaCache() for more info on this.", "if", "(", "$", "this", "->", "_schema", "===", "null", ")", "{", "if", "(", "$", "this", "->", "_schema_cache", ")", "{", "$", "cached_schema", "=", "$", "this", "->", "_schema_cache", "->", "loadSchema", "(", ")", ";", "if", "(", "$", "cached_schema", "instanceof", "Net_LDAP2_Error", ")", "{", "return", "$", "cached_schema", ";", "// route error to client", "}", "else", "{", "if", "(", "$", "cached_schema", "instanceof", "Net_LDAP2_Schema", ")", "{", "$", "this", "->", "_schema", "=", "$", "cached_schema", ";", "}", "}", "}", "}", "// Fetch schema, if not tried before and no cached version available.", "// If we are already fetching the schema, we will skip fetching.", "if", "(", "$", "this", "->", "_schema", "===", "null", ")", "{", "// store a temporary error message so subsequent calls to schema() can", "// detect, that we are fetching the schema already.", "// Otherwise we will get an infinite loop at Net_LDAP2_Schema::fetch()", "$", "this", "->", "_schema", "=", "new", "Net_LDAP2_Error", "(", "'Schema not initialized'", ")", ";", "$", "this", "->", "_schema", "=", "Net_LDAP2_Schema", "::", "fetch", "(", "$", "this", ",", "$", "dn", ")", ";", "// If schema caching is active, advise the cache to store the schema", "if", "(", "$", "this", "->", "_schema_cache", ")", "{", "$", "caching_result", "=", "$", "this", "->", "_schema_cache", "->", "storeSchema", "(", "$", "this", "->", "_schema", ")", ";", "if", "(", "$", "caching_result", "instanceof", "Net_LDAP2_Error", ")", "{", "return", "$", "caching_result", ";", "// route error to client", "}", "}", "}", "return", "$", "this", "->", "_schema", ";", "}" ]
Get a schema object @param string $dn (optional) Subschema entry dn @access public @return Net_LDAP2_Schema|Net_LDAP2_Error Net_LDAP2_Schema or Net_LDAP2_Error object
[ "Get", "a", "schema", "object" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2.php#L1537-L1574
228,764
pinfirestudios/yii2-bugsnag
src/BugsnagAsset.php
BugsnagAsset.init
public function init() { if (!Yii::$app->has('bugsnag')) { throw new InvalidConfigException('BugsnagAsset requires Bugsnag component to be enabled'); } if (!in_array($this->version, [2, 3])) { throw new InvalidConfigException('Bugsnag javascript only supports version 2 or 3'); } $this->registerJavascript(); parent::init(); }
php
public function init() { if (!Yii::$app->has('bugsnag')) { throw new InvalidConfigException('BugsnagAsset requires Bugsnag component to be enabled'); } if (!in_array($this->version, [2, 3])) { throw new InvalidConfigException('Bugsnag javascript only supports version 2 or 3'); } $this->registerJavascript(); parent::init(); }
[ "public", "function", "init", "(", ")", "{", "if", "(", "!", "Yii", "::", "$", "app", "->", "has", "(", "'bugsnag'", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "'BugsnagAsset requires Bugsnag component to be enabled'", ")", ";", "}", "if", "(", "!", "in_array", "(", "$", "this", "->", "version", ",", "[", "2", ",", "3", "]", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "'Bugsnag javascript only supports version 2 or 3'", ")", ";", "}", "$", "this", "->", "registerJavascript", "(", ")", ";", "parent", "::", "init", "(", ")", ";", "}" ]
Initiates Bugsnag javascript registration
[ "Initiates", "Bugsnag", "javascript", "registration" ]
032c061e8293e41917b12fc78b59290f3219d2e4
https://github.com/pinfirestudios/yii2-bugsnag/blob/032c061e8293e41917b12fc78b59290f3219d2e4/src/BugsnagAsset.php#L37-L52
228,765
pinfirestudios/yii2-bugsnag
src/BugsnagAsset.php
BugsnagAsset.registerJavascript
private function registerJavascript() { $filePath = '//d2wy8f7a9ursnm.cloudfront.net/bugsnag-' . $this->version . '.js'; if (!$this->useCdn) { $this->sourcePath = '@bower/bugsnag/src'; $filePath = 'bugsnag.js'; if (!file_exists(Yii::getAlias($this->sourcePath . '/' . $filePath))) { throw new InvalidConfigException('Cannot find Bugsnag.js source code. Is bower-asset/bugsnag installed?'); } } $this->js[] = [ $filePath, 'data-apikey' => Yii::$app->bugsnag->bugsnag_api_key, 'data-releasestage' => Yii::$app->bugsnag->releaseStage, 'data-appversion' => Yii::$app->version, 'position' => \yii\web\View::POS_HEAD, ]; // Include this wrapper since bugsnag.js might be blocked by adblockers. We don't want to completely die if so. $js = 'var Bugsnag = Bugsnag || {};'; if (!Yii::$app->user->isGuest) { $userId = Json::htmlEncode(Yii::$app->user->id); $js .= "Bugsnag.user = { id: $userId };"; } if (!empty(Yii::$app->bugsnag->notifyReleaseStages)) { $releaseStages = Json::htmlEncode(Yii::$app->bugsnag->notifyReleaseStages); $js .= "Bugsnag.notifyReleaseStages = $releaseStages;"; } Yii::$app->view->registerJs($js, \yii\web\View::POS_BEGIN); }
php
private function registerJavascript() { $filePath = '//d2wy8f7a9ursnm.cloudfront.net/bugsnag-' . $this->version . '.js'; if (!$this->useCdn) { $this->sourcePath = '@bower/bugsnag/src'; $filePath = 'bugsnag.js'; if (!file_exists(Yii::getAlias($this->sourcePath . '/' . $filePath))) { throw new InvalidConfigException('Cannot find Bugsnag.js source code. Is bower-asset/bugsnag installed?'); } } $this->js[] = [ $filePath, 'data-apikey' => Yii::$app->bugsnag->bugsnag_api_key, 'data-releasestage' => Yii::$app->bugsnag->releaseStage, 'data-appversion' => Yii::$app->version, 'position' => \yii\web\View::POS_HEAD, ]; // Include this wrapper since bugsnag.js might be blocked by adblockers. We don't want to completely die if so. $js = 'var Bugsnag = Bugsnag || {};'; if (!Yii::$app->user->isGuest) { $userId = Json::htmlEncode(Yii::$app->user->id); $js .= "Bugsnag.user = { id: $userId };"; } if (!empty(Yii::$app->bugsnag->notifyReleaseStages)) { $releaseStages = Json::htmlEncode(Yii::$app->bugsnag->notifyReleaseStages); $js .= "Bugsnag.notifyReleaseStages = $releaseStages;"; } Yii::$app->view->registerJs($js, \yii\web\View::POS_BEGIN); }
[ "private", "function", "registerJavascript", "(", ")", "{", "$", "filePath", "=", "'//d2wy8f7a9ursnm.cloudfront.net/bugsnag-'", ".", "$", "this", "->", "version", ".", "'.js'", ";", "if", "(", "!", "$", "this", "->", "useCdn", ")", "{", "$", "this", "->", "sourcePath", "=", "'@bower/bugsnag/src'", ";", "$", "filePath", "=", "'bugsnag.js'", ";", "if", "(", "!", "file_exists", "(", "Yii", "::", "getAlias", "(", "$", "this", "->", "sourcePath", ".", "'/'", ".", "$", "filePath", ")", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "'Cannot find Bugsnag.js source code. Is bower-asset/bugsnag installed?'", ")", ";", "}", "}", "$", "this", "->", "js", "[", "]", "=", "[", "$", "filePath", ",", "'data-apikey'", "=>", "Yii", "::", "$", "app", "->", "bugsnag", "->", "bugsnag_api_key", ",", "'data-releasestage'", "=>", "Yii", "::", "$", "app", "->", "bugsnag", "->", "releaseStage", ",", "'data-appversion'", "=>", "Yii", "::", "$", "app", "->", "version", ",", "'position'", "=>", "\\", "yii", "\\", "web", "\\", "View", "::", "POS_HEAD", ",", "]", ";", "// Include this wrapper since bugsnag.js might be blocked by adblockers. We don't want to completely die if so.", "$", "js", "=", "'var Bugsnag = Bugsnag || {};'", ";", "if", "(", "!", "Yii", "::", "$", "app", "->", "user", "->", "isGuest", ")", "{", "$", "userId", "=", "Json", "::", "htmlEncode", "(", "Yii", "::", "$", "app", "->", "user", "->", "id", ")", ";", "$", "js", ".=", "\"Bugsnag.user = { id: $userId };\"", ";", "}", "if", "(", "!", "empty", "(", "Yii", "::", "$", "app", "->", "bugsnag", "->", "notifyReleaseStages", ")", ")", "{", "$", "releaseStages", "=", "Json", "::", "htmlEncode", "(", "Yii", "::", "$", "app", "->", "bugsnag", "->", "notifyReleaseStages", ")", ";", "$", "js", ".=", "\"Bugsnag.notifyReleaseStages = $releaseStages;\"", ";", "}", "Yii", "::", "$", "app", "->", "view", "->", "registerJs", "(", "$", "js", ",", "\\", "yii", "\\", "web", "\\", "View", "::", "POS_BEGIN", ")", ";", "}" ]
Registers Bugsnag JavaScript to page
[ "Registers", "Bugsnag", "JavaScript", "to", "page" ]
032c061e8293e41917b12fc78b59290f3219d2e4
https://github.com/pinfirestudios/yii2-bugsnag/blob/032c061e8293e41917b12fc78b59290f3219d2e4/src/BugsnagAsset.php#L58-L96
228,766
rexxars/morse-php
library/Table.php
Table.getCharacter
public function getCharacter($morse) { $key = strtr($morse, '.-', '01'); return isset($this->reversedTable[$key]) ? $this->reversedTable[$key] : false; }
php
public function getCharacter($morse) { $key = strtr($morse, '.-', '01'); return isset($this->reversedTable[$key]) ? $this->reversedTable[$key] : false; }
[ "public", "function", "getCharacter", "(", "$", "morse", ")", "{", "$", "key", "=", "strtr", "(", "$", "morse", ",", "'.-'", ",", "'01'", ")", ";", "return", "isset", "(", "$", "this", "->", "reversedTable", "[", "$", "key", "]", ")", "?", "$", "this", "->", "reversedTable", "[", "$", "key", "]", ":", "false", ";", "}" ]
Get character for given morse code @param string $morse @return string
[ "Get", "character", "for", "given", "morse", "code" ]
4f8b8fe15639ddd6f9f030c06e9ccce844142ac9
https://github.com/rexxars/morse-php/blob/4f8b8fe15639ddd6f9f030c06e9ccce844142ac9/library/Table.php#L167-L170
228,767
dunglas/api-platform-heroku
src/Database.php
Database.createParameters
public static function createParameters() { $database = parse_url(getenv('DATABASE_URL')); putenv(sprintf('SYMFONY__DATABASE_HOST=%s', $database['host'])); putenv(sprintf('SYMFONY__DATABASE_PORT=%s', $database['port'])); putenv(sprintf('SYMFONY__DATABASE_USER=%s', $database['user'])); putenv(sprintf('SYMFONY__DATABASE_PASSWORD=%s', $database['pass'])); putenv(sprintf('SYMFONY__DATABASE_NAME=%s', ltrim($database['path'], '/'))); }
php
public static function createParameters() { $database = parse_url(getenv('DATABASE_URL')); putenv(sprintf('SYMFONY__DATABASE_HOST=%s', $database['host'])); putenv(sprintf('SYMFONY__DATABASE_PORT=%s', $database['port'])); putenv(sprintf('SYMFONY__DATABASE_USER=%s', $database['user'])); putenv(sprintf('SYMFONY__DATABASE_PASSWORD=%s', $database['pass'])); putenv(sprintf('SYMFONY__DATABASE_NAME=%s', ltrim($database['path'], '/'))); }
[ "public", "static", "function", "createParameters", "(", ")", "{", "$", "database", "=", "parse_url", "(", "getenv", "(", "'DATABASE_URL'", ")", ")", ";", "putenv", "(", "sprintf", "(", "'SYMFONY__DATABASE_HOST=%s'", ",", "$", "database", "[", "'host'", "]", ")", ")", ";", "putenv", "(", "sprintf", "(", "'SYMFONY__DATABASE_PORT=%s'", ",", "$", "database", "[", "'port'", "]", ")", ")", ";", "putenv", "(", "sprintf", "(", "'SYMFONY__DATABASE_USER=%s'", ",", "$", "database", "[", "'user'", "]", ")", ")", ";", "putenv", "(", "sprintf", "(", "'SYMFONY__DATABASE_PASSWORD=%s'", ",", "$", "database", "[", "'pass'", "]", ")", ")", ";", "putenv", "(", "sprintf", "(", "'SYMFONY__DATABASE_NAME=%s'", ",", "ltrim", "(", "$", "database", "[", "'path'", "]", ",", "'/'", ")", ")", ")", ";", "}" ]
Creates parameters.
[ "Creates", "parameters", "." ]
6e6f68764c31e679033c82acd85430d7b4b6d482
https://github.com/dunglas/api-platform-heroku/blob/6e6f68764c31e679033c82acd85430d7b4b6d482/src/Database.php#L24-L33
228,768
denar90/yii2-wavesurfer-audio-widget
WaveSurferAudioWidget.php
WaveSurferAudioWidget.showControls
private function showControls() { //set controll btn class name $jsClassName = 'js-audio-widget-action'; foreach($this->settings['controls'] as $key => $value) { if ($value) { $cssClassName = 'audio-widget-' . $key; $options['class'] = $cssClassName . ' ' . $jsClassName; $options['data-action'] = $key; //show controll btn echo Html::button($key, $options); } } $this->widgetSettings['controls'] = [ 'btnClass' => '.' . $jsClassName ]; }
php
private function showControls() { //set controll btn class name $jsClassName = 'js-audio-widget-action'; foreach($this->settings['controls'] as $key => $value) { if ($value) { $cssClassName = 'audio-widget-' . $key; $options['class'] = $cssClassName . ' ' . $jsClassName; $options['data-action'] = $key; //show controll btn echo Html::button($key, $options); } } $this->widgetSettings['controls'] = [ 'btnClass' => '.' . $jsClassName ]; }
[ "private", "function", "showControls", "(", ")", "{", "//set controll btn class name", "$", "jsClassName", "=", "'js-audio-widget-action'", ";", "foreach", "(", "$", "this", "->", "settings", "[", "'controls'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", ")", "{", "$", "cssClassName", "=", "'audio-widget-'", ".", "$", "key", ";", "$", "options", "[", "'class'", "]", "=", "$", "cssClassName", ".", "' '", ".", "$", "jsClassName", ";", "$", "options", "[", "'data-action'", "]", "=", "$", "key", ";", "//show controll btn", "echo", "Html", "::", "button", "(", "$", "key", ",", "$", "options", ")", ";", "}", "}", "$", "this", "->", "widgetSettings", "[", "'controls'", "]", "=", "[", "'btnClass'", "=>", "'.'", ".", "$", "jsClassName", "]", ";", "}" ]
Show widget controls
[ "Show", "widget", "controls" ]
0ac6788bbd1d54db8c099eff1d41bb2102f98f71
https://github.com/denar90/yii2-wavesurfer-audio-widget/blob/0ac6788bbd1d54db8c099eff1d41bb2102f98f71/WaveSurferAudioWidget.php#L69-L85
228,769
denar90/yii2-wavesurfer-audio-widget
WaveSurferAudioWidget.php
WaveSurferAudioWidget.setSettingsForJs
private function setSettingsForJs() { //check if audio url was set if (ArrayHelper::keyExists('fileUrl', $this->settings, false) && !empty($this->settings['fileUrl'])) { $this->widgetSettings['fileUrl'] = $this->settings['fileUrl']; } else { throw new ElementNotFound('fileUrl was not set'); } if (ArrayHelper::keyExists('callbacks', $this->settings, false) && !empty($this->settings['callbacks'])) { $this->widgetSettings['callbacks'] = $this->settings['callbacks']; } $this->widgetSettings['initSettings'] = ArrayHelper::keyExists('init', $this->settings, false) ? $this->settings['init'] : []; $containerName = ArrayHelper::keyExists('container', $this->widgetSettings['initSettings'], false) ? $this->widgetSettings['initSettings']['container'] : $this->getId(); $this->widgetSettings['initSettings']['container'] = '#' . $containerName; }
php
private function setSettingsForJs() { //check if audio url was set if (ArrayHelper::keyExists('fileUrl', $this->settings, false) && !empty($this->settings['fileUrl'])) { $this->widgetSettings['fileUrl'] = $this->settings['fileUrl']; } else { throw new ElementNotFound('fileUrl was not set'); } if (ArrayHelper::keyExists('callbacks', $this->settings, false) && !empty($this->settings['callbacks'])) { $this->widgetSettings['callbacks'] = $this->settings['callbacks']; } $this->widgetSettings['initSettings'] = ArrayHelper::keyExists('init', $this->settings, false) ? $this->settings['init'] : []; $containerName = ArrayHelper::keyExists('container', $this->widgetSettings['initSettings'], false) ? $this->widgetSettings['initSettings']['container'] : $this->getId(); $this->widgetSettings['initSettings']['container'] = '#' . $containerName; }
[ "private", "function", "setSettingsForJs", "(", ")", "{", "//check if audio url was set", "if", "(", "ArrayHelper", "::", "keyExists", "(", "'fileUrl'", ",", "$", "this", "->", "settings", ",", "false", ")", "&&", "!", "empty", "(", "$", "this", "->", "settings", "[", "'fileUrl'", "]", ")", ")", "{", "$", "this", "->", "widgetSettings", "[", "'fileUrl'", "]", "=", "$", "this", "->", "settings", "[", "'fileUrl'", "]", ";", "}", "else", "{", "throw", "new", "ElementNotFound", "(", "'fileUrl was not set'", ")", ";", "}", "if", "(", "ArrayHelper", "::", "keyExists", "(", "'callbacks'", ",", "$", "this", "->", "settings", ",", "false", ")", "&&", "!", "empty", "(", "$", "this", "->", "settings", "[", "'callbacks'", "]", ")", ")", "{", "$", "this", "->", "widgetSettings", "[", "'callbacks'", "]", "=", "$", "this", "->", "settings", "[", "'callbacks'", "]", ";", "}", "$", "this", "->", "widgetSettings", "[", "'initSettings'", "]", "=", "ArrayHelper", "::", "keyExists", "(", "'init'", ",", "$", "this", "->", "settings", ",", "false", ")", "?", "$", "this", "->", "settings", "[", "'init'", "]", ":", "[", "]", ";", "$", "containerName", "=", "ArrayHelper", "::", "keyExists", "(", "'container'", ",", "$", "this", "->", "widgetSettings", "[", "'initSettings'", "]", ",", "false", ")", "?", "$", "this", "->", "widgetSettings", "[", "'initSettings'", "]", "[", "'container'", "]", ":", "$", "this", "->", "getId", "(", ")", ";", "$", "this", "->", "widgetSettings", "[", "'initSettings'", "]", "[", "'container'", "]", "=", "'#'", ".", "$", "containerName", ";", "}" ]
Set settings for js widget @throws ElementNotFound fileUrl was not set
[ "Set", "settings", "for", "js", "widget" ]
0ac6788bbd1d54db8c099eff1d41bb2102f98f71
https://github.com/denar90/yii2-wavesurfer-audio-widget/blob/0ac6788bbd1d54db8c099eff1d41bb2102f98f71/WaveSurferAudioWidget.php#L91-L105
228,770
denar90/yii2-wavesurfer-audio-widget
WaveSurferAudioWidget.php
WaveSurferAudioWidget.registerWidgetScripts
private function registerWidgetScripts() { $view = $this->getView(); $asset = Yii::$container->get(Asset::className()); $asset::register($view); $this->widgetSettings = Json::encode($this->widgetSettings); $view->registerJs("var audioWidget = new AudioWidget(" . $this->widgetSettings . "); audioWidget.init();", $view::POS_READY); }
php
private function registerWidgetScripts() { $view = $this->getView(); $asset = Yii::$container->get(Asset::className()); $asset::register($view); $this->widgetSettings = Json::encode($this->widgetSettings); $view->registerJs("var audioWidget = new AudioWidget(" . $this->widgetSettings . "); audioWidget.init();", $view::POS_READY); }
[ "private", "function", "registerWidgetScripts", "(", ")", "{", "$", "view", "=", "$", "this", "->", "getView", "(", ")", ";", "$", "asset", "=", "Yii", "::", "$", "container", "->", "get", "(", "Asset", "::", "className", "(", ")", ")", ";", "$", "asset", "::", "register", "(", "$", "view", ")", ";", "$", "this", "->", "widgetSettings", "=", "Json", "::", "encode", "(", "$", "this", "->", "widgetSettings", ")", ";", "$", "view", "->", "registerJs", "(", "\"var audioWidget = new AudioWidget(\"", ".", "$", "this", "->", "widgetSettings", ".", "\"); audioWidget.init();\"", ",", "$", "view", "::", "POS_READY", ")", ";", "}" ]
Register widget asset
[ "Register", "widget", "asset" ]
0ac6788bbd1d54db8c099eff1d41bb2102f98f71
https://github.com/denar90/yii2-wavesurfer-audio-widget/blob/0ac6788bbd1d54db8c099eff1d41bb2102f98f71/WaveSurferAudioWidget.php#L110-L117
228,771
stanislav-web/phalcon-sms-factory
src/SMSFactory/Sender.php
Sender.call
final public function call($providerName) { $configProviderClass = "SMSFactory\\Config\\$providerName"; // note: no leading backslash $providerClass = "SMSFactory\\Providers\\$providerName"; // note: no leading backslash if (class_exists($providerClass) === true) { // inject configurations return new $providerClass(new $configProviderClass($this->config[$providerName])); } else { throw new BaseException('SMS', 'Provider ' . $providerName . ' does not exist', 500); } }
php
final public function call($providerName) { $configProviderClass = "SMSFactory\\Config\\$providerName"; // note: no leading backslash $providerClass = "SMSFactory\\Providers\\$providerName"; // note: no leading backslash if (class_exists($providerClass) === true) { // inject configurations return new $providerClass(new $configProviderClass($this->config[$providerName])); } else { throw new BaseException('SMS', 'Provider ' . $providerName . ' does not exist', 500); } }
[ "final", "public", "function", "call", "(", "$", "providerName", ")", "{", "$", "configProviderClass", "=", "\"SMSFactory\\\\Config\\\\$providerName\"", ";", "// note: no leading backslash", "$", "providerClass", "=", "\"SMSFactory\\\\Providers\\\\$providerName\"", ";", "// note: no leading backslash", "if", "(", "class_exists", "(", "$", "providerClass", ")", "===", "true", ")", "{", "// inject configurations", "return", "new", "$", "providerClass", "(", "new", "$", "configProviderClass", "(", "$", "this", "->", "config", "[", "$", "providerName", "]", ")", ")", ";", "}", "else", "{", "throw", "new", "BaseException", "(", "'SMS'", ",", "'Provider '", ".", "$", "providerName", ".", "' does not exist'", ",", "500", ")", ";", "}", "}" ]
Get SMS provider @param string $providerName demanded provider @uses ProviderInterface::setRecipient() @uses ProviderInterface::send() @uses ProviderInterface::balance() @throws BaseException @return object
[ "Get", "SMS", "provider" ]
75e5b61819ae24705e87073508f99341b64da2cd
https://github.com/stanislav-web/phalcon-sms-factory/blob/75e5b61819ae24705e87073508f99341b64da2cd/src/SMSFactory/Sender.php#L47-L60
228,772
projek-xyz/slim-monolog
src/Monolog.php
Monolog.useRotatingFiles
public function useRotatingFiles($level = Logger::DEBUG, $filename = null) { $filename || $filename = $this->name.'.log'; $path = $this->settings['directory'].'/'.$filename; $this->monolog->pushHandler( $handler = new Handler\RotatingFileHandler($path, 5, $level) ); $handler->setFormatter($this->getDefaultFormatter()); return $this; }
php
public function useRotatingFiles($level = Logger::DEBUG, $filename = null) { $filename || $filename = $this->name.'.log'; $path = $this->settings['directory'].'/'.$filename; $this->monolog->pushHandler( $handler = new Handler\RotatingFileHandler($path, 5, $level) ); $handler->setFormatter($this->getDefaultFormatter()); return $this; }
[ "public", "function", "useRotatingFiles", "(", "$", "level", "=", "Logger", "::", "DEBUG", ",", "$", "filename", "=", "null", ")", "{", "$", "filename", "||", "$", "filename", "=", "$", "this", "->", "name", ".", "'.log'", ";", "$", "path", "=", "$", "this", "->", "settings", "[", "'directory'", "]", ".", "'/'", ".", "$", "filename", ";", "$", "this", "->", "monolog", "->", "pushHandler", "(", "$", "handler", "=", "new", "Handler", "\\", "RotatingFileHandler", "(", "$", "path", ",", "5", ",", "$", "level", ")", ")", ";", "$", "handler", "->", "setFormatter", "(", "$", "this", "->", "getDefaultFormatter", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Register a rotating file log handler. @param mixed $level @param null|string $filename @return \Projek\Slim\Monolog
[ "Register", "a", "rotating", "file", "log", "handler", "." ]
fdbb28a67105d22a81ad0b15d31e730f7461be26
https://github.com/projek-xyz/slim-monolog/blob/fdbb28a67105d22a81ad0b15d31e730f7461be26/src/Monolog.php#L197-L207
228,773
projek-xyz/slim-monolog
src/MonologProvider.php
MonologProvider.register
public function register(Container $container) { $settings = $container->get('settings'); if (!isset($settings['logger'])) { throw new InvalidArgumentException('Logger configuration not found'); } $basename = isset($settings['basename']) ? $settings['basename'] : 'slim-app'; $container['logger'] = new Monolog($basename, $settings['logger']); }
php
public function register(Container $container) { $settings = $container->get('settings'); if (!isset($settings['logger'])) { throw new InvalidArgumentException('Logger configuration not found'); } $basename = isset($settings['basename']) ? $settings['basename'] : 'slim-app'; $container['logger'] = new Monolog($basename, $settings['logger']); }
[ "public", "function", "register", "(", "Container", "$", "container", ")", "{", "$", "settings", "=", "$", "container", "->", "get", "(", "'settings'", ")", ";", "if", "(", "!", "isset", "(", "$", "settings", "[", "'logger'", "]", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Logger configuration not found'", ")", ";", "}", "$", "basename", "=", "isset", "(", "$", "settings", "[", "'basename'", "]", ")", "?", "$", "settings", "[", "'basename'", "]", ":", "'slim-app'", ";", "$", "container", "[", "'logger'", "]", "=", "new", "Monolog", "(", "$", "basename", ",", "$", "settings", "[", "'logger'", "]", ")", ";", "}" ]
Register this monolog provider with a Pimple container @param \Pimple\Container $container
[ "Register", "this", "monolog", "provider", "with", "a", "Pimple", "container" ]
fdbb28a67105d22a81ad0b15d31e730f7461be26
https://github.com/projek-xyz/slim-monolog/blob/fdbb28a67105d22a81ad0b15d31e730f7461be26/src/MonologProvider.php#L15-L26
228,774
sop/crypto-types
lib/CryptoTypes/Signature/Signature.php
Signature.fromSignatureData
public static function fromSignatureData(string $data, AlgorithmIdentifierType $algo): Signature { if ($algo instanceof RSASignatureAlgorithmIdentifier) { return RSASignature::fromSignatureString($data); } if ($algo instanceof ECSignatureAlgorithmIdentifier) { return ECSignature::fromDER($data); } return new GenericSignature(new BitString($data), $algo); }
php
public static function fromSignatureData(string $data, AlgorithmIdentifierType $algo): Signature { if ($algo instanceof RSASignatureAlgorithmIdentifier) { return RSASignature::fromSignatureString($data); } if ($algo instanceof ECSignatureAlgorithmIdentifier) { return ECSignature::fromDER($data); } return new GenericSignature(new BitString($data), $algo); }
[ "public", "static", "function", "fromSignatureData", "(", "string", "$", "data", ",", "AlgorithmIdentifierType", "$", "algo", ")", ":", "Signature", "{", "if", "(", "$", "algo", "instanceof", "RSASignatureAlgorithmIdentifier", ")", "{", "return", "RSASignature", "::", "fromSignatureString", "(", "$", "data", ")", ";", "}", "if", "(", "$", "algo", "instanceof", "ECSignatureAlgorithmIdentifier", ")", "{", "return", "ECSignature", "::", "fromDER", "(", "$", "data", ")", ";", "}", "return", "new", "GenericSignature", "(", "new", "BitString", "(", "$", "data", ")", ",", "$", "algo", ")", ";", "}" ]
Get signature object by signature data and used algorithm. @param string $data Signature value @param AlgorithmIdentifierType $algo Algorithm identifier @return self
[ "Get", "signature", "object", "by", "signature", "data", "and", "used", "algorithm", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Signature/Signature.php#L31-L41
228,775
mlaphp/mlaphp
src/Mlaphp/MysqlDatabase.php
MysqlDatabase.addLinkArgument
protected function addLinkArgument($func, $args) { if (! isset($this->link_arg[$func])) { return $args; } if (count($args) >= $this->link_arg[$func]) { return $args; } $args[] = $this->link; return $args; }
php
protected function addLinkArgument($func, $args) { if (! isset($this->link_arg[$func])) { return $args; } if (count($args) >= $this->link_arg[$func]) { return $args; } $args[] = $this->link; return $args; }
[ "protected", "function", "addLinkArgument", "(", "$", "func", ",", "$", "args", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "link_arg", "[", "$", "func", "]", ")", ")", "{", "return", "$", "args", ";", "}", "if", "(", "count", "(", "$", "args", ")", ">=", "$", "this", "->", "link_arg", "[", "$", "func", "]", ")", "{", "return", "$", "args", ";", "}", "$", "args", "[", "]", "=", "$", "this", "->", "link", ";", "return", "$", "args", ";", "}" ]
Given a MySQL function name and an array of arguments, adds the link identifier to the end of the arguments if one is needed. @param string $func The MySQL function name. @param array $args The arguments to the function. @return array The arguments, with the link identifier if one is needed.
[ "Given", "a", "MySQL", "function", "name", "and", "an", "array", "of", "arguments", "adds", "the", "link", "identifier", "to", "the", "end", "of", "the", "arguments", "if", "one", "is", "needed", "." ]
c0c90e7217c598c82bb65e5304e8076da381c1f8
https://github.com/mlaphp/mlaphp/blob/c0c90e7217c598c82bb65e5304e8076da381c1f8/src/Mlaphp/MysqlDatabase.php#L190-L202
228,776
mlaphp/mlaphp
src/Mlaphp/MysqlDatabase.php
MysqlDatabase.lazyConnect
protected function lazyConnect($func) { // do not reconnect if ($this->link) { return; } // connect only for functions that need a link if (! isset($this->link_arg[$func])) { return; } // connect and retain the identifier $this->link = mysql_connect( $this->server, $this->username, $this->password, $this->new_link, $this->client_flags ); // throw exception on error if (! $this->link) { throw new RuntimeException( mysql_error(), mysql_errno() ); } }
php
protected function lazyConnect($func) { // do not reconnect if ($this->link) { return; } // connect only for functions that need a link if (! isset($this->link_arg[$func])) { return; } // connect and retain the identifier $this->link = mysql_connect( $this->server, $this->username, $this->password, $this->new_link, $this->client_flags ); // throw exception on error if (! $this->link) { throw new RuntimeException( mysql_error(), mysql_errno() ); } }
[ "protected", "function", "lazyConnect", "(", "$", "func", ")", "{", "// do not reconnect", "if", "(", "$", "this", "->", "link", ")", "{", "return", ";", "}", "// connect only for functions that need a link", "if", "(", "!", "isset", "(", "$", "this", "->", "link_arg", "[", "$", "func", "]", ")", ")", "{", "return", ";", "}", "// connect and retain the identifier", "$", "this", "->", "link", "=", "mysql_connect", "(", "$", "this", "->", "server", ",", "$", "this", "->", "username", ",", "$", "this", "->", "password", ",", "$", "this", "->", "new_link", ",", "$", "this", "->", "client_flags", ")", ";", "// throw exception on error", "if", "(", "!", "$", "this", "->", "link", ")", "{", "throw", "new", "RuntimeException", "(", "mysql_error", "(", ")", ",", "mysql_errno", "(", ")", ")", ";", "}", "}" ]
Given a MySQL function name, connects to the server if there is no link and identifier and one is needed. @param string $func The MySQL function name. @return null @throws RuntimeException if the connection attempt fails.
[ "Given", "a", "MySQL", "function", "name", "connects", "to", "the", "server", "if", "there", "is", "no", "link", "and", "identifier", "and", "one", "is", "needed", "." ]
c0c90e7217c598c82bb65e5304e8076da381c1f8
https://github.com/mlaphp/mlaphp/blob/c0c90e7217c598c82bb65e5304e8076da381c1f8/src/Mlaphp/MysqlDatabase.php#L212-L240
228,777
pear/Net_LDAP2
Net/LDAP2/SimpleFileSchemaCache.php
Net_LDAP2_SimpleFileSchemaCache.loadSchema
public function loadSchema() { $return = false; // Net_LDAP2 will load schema from LDAP if (file_exists($this->config['path'])) { $cache_maxage = filemtime($this->config['path']) + $this->config['max_age']; if (time() <= $cache_maxage || $this->config['max_age'] == 0) { $return = unserialize(file_get_contents($this->config['path'])); } } return $return; }
php
public function loadSchema() { $return = false; // Net_LDAP2 will load schema from LDAP if (file_exists($this->config['path'])) { $cache_maxage = filemtime($this->config['path']) + $this->config['max_age']; if (time() <= $cache_maxage || $this->config['max_age'] == 0) { $return = unserialize(file_get_contents($this->config['path'])); } } return $return; }
[ "public", "function", "loadSchema", "(", ")", "{", "$", "return", "=", "false", ";", "// Net_LDAP2 will load schema from LDAP", "if", "(", "file_exists", "(", "$", "this", "->", "config", "[", "'path'", "]", ")", ")", "{", "$", "cache_maxage", "=", "filemtime", "(", "$", "this", "->", "config", "[", "'path'", "]", ")", "+", "$", "this", "->", "config", "[", "'max_age'", "]", ";", "if", "(", "time", "(", ")", "<=", "$", "cache_maxage", "||", "$", "this", "->", "config", "[", "'max_age'", "]", "==", "0", ")", "{", "$", "return", "=", "unserialize", "(", "file_get_contents", "(", "$", "this", "->", "config", "[", "'path'", "]", ")", ")", ";", "}", "}", "return", "$", "return", ";", "}" ]
Return the schema object from the cache If file is existent and cache has not expired yet, then the cache is deserialized and returned. @return Net_LDAP2_Schema|Net_LDAP2_Error|false
[ "Return", "the", "schema", "object", "from", "the", "cache" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/SimpleFileSchemaCache.php#L68-L78
228,778
paulzi/yii2-sortable
SortableBehavior.php
SortableBehavior.reorder
public function reorder($middle = true) { $result = 0; \Yii::$app->getDb()->transaction(function () use (&$result, $middle) { $list = $this->getQueryInternal() ->select($this->owner->primaryKey()) ->orderBy([$this->sortAttribute => SORT_ASC]) ->asArray() ->all(); $from = $middle ? count($list) >> 1 : 0; foreach ($list as $i => $item) { $result += $this->owner->updateAll([$this->sortAttribute => ($i - $from) * $this->step], $item); } }); return $result; }
php
public function reorder($middle = true) { $result = 0; \Yii::$app->getDb()->transaction(function () use (&$result, $middle) { $list = $this->getQueryInternal() ->select($this->owner->primaryKey()) ->orderBy([$this->sortAttribute => SORT_ASC]) ->asArray() ->all(); $from = $middle ? count($list) >> 1 : 0; foreach ($list as $i => $item) { $result += $this->owner->updateAll([$this->sortAttribute => ($i - $from) * $this->step], $item); } }); return $result; }
[ "public", "function", "reorder", "(", "$", "middle", "=", "true", ")", "{", "$", "result", "=", "0", ";", "\\", "Yii", "::", "$", "app", "->", "getDb", "(", ")", "->", "transaction", "(", "function", "(", ")", "use", "(", "&", "$", "result", ",", "$", "middle", ")", "{", "$", "list", "=", "$", "this", "->", "getQueryInternal", "(", ")", "->", "select", "(", "$", "this", "->", "owner", "->", "primaryKey", "(", ")", ")", "->", "orderBy", "(", "[", "$", "this", "->", "sortAttribute", "=>", "SORT_ASC", "]", ")", "->", "asArray", "(", ")", "->", "all", "(", ")", ";", "$", "from", "=", "$", "middle", "?", "count", "(", "$", "list", ")", ">>", "1", ":", "0", ";", "foreach", "(", "$", "list", "as", "$", "i", "=>", "$", "item", ")", "{", "$", "result", "+=", "$", "this", "->", "owner", "->", "updateAll", "(", "[", "$", "this", "->", "sortAttribute", "=>", "(", "$", "i", "-", "$", "from", ")", "*", "$", "this", "->", "step", "]", ",", "$", "item", ")", ";", "}", "}", ")", ";", "return", "$", "result", ";", "}" ]
Reorders items with values of sortAttribute begin from zero. @param bool $middle @return integer @throws \Exception
[ "Reorders", "items", "with", "values", "of", "sortAttribute", "begin", "from", "zero", "." ]
2d51e8a923acb4cc385e8d28faa0e8d179aa014e
https://github.com/paulzi/yii2-sortable/blob/2d51e8a923acb4cc385e8d28faa0e8d179aa014e/SortableBehavior.php#L177-L193
228,779
sop/crypto-types
lib/CryptoTypes/Asymmetric/OneAsymmetricKey.php
OneAsymmetricKey.privateKey
public function privateKey(): PrivateKey { $algo = $this->algorithmIdentifier(); switch ($algo->oid()) { // RSA case AlgorithmIdentifier::OID_RSA_ENCRYPTION: return RSA\RSAPrivateKey::fromDER($this->_privateKeyData); // elliptic curve case AlgorithmIdentifier::OID_EC_PUBLIC_KEY: $pk = EC\ECPrivateKey::fromDER($this->_privateKeyData); // NOTE: OpenSSL strips named curve from ECPrivateKey structure // when serializing into PrivateKeyInfo. However RFC 5915 dictates // that parameters (NamedCurve) must always be included. // If private key doesn't encode named curve, assign from parameters. if (!$pk->hasNamedCurve()) { if (!$algo instanceof ECPublicKeyAlgorithmIdentifier) { throw new \UnexpectedValueException( "Not an EC algorithm."); } $pk = $pk->withNamedCurve($algo->namedCurve()); } return $pk; } throw new \RuntimeException( "Private key " . $algo->name() . " not supported."); }
php
public function privateKey(): PrivateKey { $algo = $this->algorithmIdentifier(); switch ($algo->oid()) { // RSA case AlgorithmIdentifier::OID_RSA_ENCRYPTION: return RSA\RSAPrivateKey::fromDER($this->_privateKeyData); // elliptic curve case AlgorithmIdentifier::OID_EC_PUBLIC_KEY: $pk = EC\ECPrivateKey::fromDER($this->_privateKeyData); // NOTE: OpenSSL strips named curve from ECPrivateKey structure // when serializing into PrivateKeyInfo. However RFC 5915 dictates // that parameters (NamedCurve) must always be included. // If private key doesn't encode named curve, assign from parameters. if (!$pk->hasNamedCurve()) { if (!$algo instanceof ECPublicKeyAlgorithmIdentifier) { throw new \UnexpectedValueException( "Not an EC algorithm."); } $pk = $pk->withNamedCurve($algo->namedCurve()); } return $pk; } throw new \RuntimeException( "Private key " . $algo->name() . " not supported."); }
[ "public", "function", "privateKey", "(", ")", ":", "PrivateKey", "{", "$", "algo", "=", "$", "this", "->", "algorithmIdentifier", "(", ")", ";", "switch", "(", "$", "algo", "->", "oid", "(", ")", ")", "{", "// RSA", "case", "AlgorithmIdentifier", "::", "OID_RSA_ENCRYPTION", ":", "return", "RSA", "\\", "RSAPrivateKey", "::", "fromDER", "(", "$", "this", "->", "_privateKeyData", ")", ";", "// elliptic curve", "case", "AlgorithmIdentifier", "::", "OID_EC_PUBLIC_KEY", ":", "$", "pk", "=", "EC", "\\", "ECPrivateKey", "::", "fromDER", "(", "$", "this", "->", "_privateKeyData", ")", ";", "// NOTE: OpenSSL strips named curve from ECPrivateKey structure", "// when serializing into PrivateKeyInfo. However RFC 5915 dictates", "// that parameters (NamedCurve) must always be included.", "// If private key doesn't encode named curve, assign from parameters.", "if", "(", "!", "$", "pk", "->", "hasNamedCurve", "(", ")", ")", "{", "if", "(", "!", "$", "algo", "instanceof", "ECPublicKeyAlgorithmIdentifier", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", "\"Not an EC algorithm.\"", ")", ";", "}", "$", "pk", "=", "$", "pk", "->", "withNamedCurve", "(", "$", "algo", "->", "namedCurve", "(", ")", ")", ";", "}", "return", "$", "pk", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "\"Private key \"", ".", "$", "algo", "->", "name", "(", ")", ".", "\" not supported.\"", ")", ";", "}" ]
Get private key. @throws \RuntimeException @return PrivateKey
[ "Get", "private", "key", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/OneAsymmetricKey.php#L169-L194
228,780
mariano/disque-php
src/Command/Response/JscanResponse.php
JscanResponse.parseBody
protected function parseBody(array $body) { $jobs = []; if (!empty($body)) { if (is_string($body[0])) { foreach ($body as $element) { $jobs[] = ['id' => $element]; } } else { $keyValueResponse = new KeyValueResponse(); $keyValueResponse->setCommand($this->command); foreach ($body as $element) { $keyValueResponse->setBody($element); $jobs[] = $keyValueResponse->parse(); } } } return ['jobs' => $jobs]; }
php
protected function parseBody(array $body) { $jobs = []; if (!empty($body)) { if (is_string($body[0])) { foreach ($body as $element) { $jobs[] = ['id' => $element]; } } else { $keyValueResponse = new KeyValueResponse(); $keyValueResponse->setCommand($this->command); foreach ($body as $element) { $keyValueResponse->setBody($element); $jobs[] = $keyValueResponse->parse(); } } } return ['jobs' => $jobs]; }
[ "protected", "function", "parseBody", "(", "array", "$", "body", ")", "{", "$", "jobs", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "body", ")", ")", "{", "if", "(", "is_string", "(", "$", "body", "[", "0", "]", ")", ")", "{", "foreach", "(", "$", "body", "as", "$", "element", ")", "{", "$", "jobs", "[", "]", "=", "[", "'id'", "=>", "$", "element", "]", ";", "}", "}", "else", "{", "$", "keyValueResponse", "=", "new", "KeyValueResponse", "(", ")", ";", "$", "keyValueResponse", "->", "setCommand", "(", "$", "this", "->", "command", ")", ";", "foreach", "(", "$", "body", "as", "$", "element", ")", "{", "$", "keyValueResponse", "->", "setBody", "(", "$", "element", ")", ";", "$", "jobs", "[", "]", "=", "$", "keyValueResponse", "->", "parse", "(", ")", ";", "}", "}", "}", "return", "[", "'jobs'", "=>", "$", "jobs", "]", ";", "}" ]
Parse main body @param array $body Body @return array Parsed body
[ "Parse", "main", "body" ]
56cf00d97e739fec861717484657dbef2888df60
https://github.com/mariano/disque-php/blob/56cf00d97e739fec861717484657dbef2888df60/src/Command/Response/JscanResponse.php#L12-L31
228,781
sop/crypto-types
lib/CryptoTypes/AlgorithmIdentifier/Cipher/RC2CBCAlgorithmIdentifier.php
RC2CBCAlgorithmIdentifier._versionToEKB
private static function _versionToEKB(int $version): int { static $lut; if ($version > 255) { return $version; } if (!isset($lut)) { $lut = array_flip(self::EKB_TABLE); } return $lut[$version]; }
php
private static function _versionToEKB(int $version): int { static $lut; if ($version > 255) { return $version; } if (!isset($lut)) { $lut = array_flip(self::EKB_TABLE); } return $lut[$version]; }
[ "private", "static", "function", "_versionToEKB", "(", "int", "$", "version", ")", ":", "int", "{", "static", "$", "lut", ";", "if", "(", "$", "version", ">", "255", ")", "{", "return", "$", "version", ";", "}", "if", "(", "!", "isset", "(", "$", "lut", ")", ")", "{", "$", "lut", "=", "array_flip", "(", "self", "::", "EKB_TABLE", ")", ";", "}", "return", "$", "lut", "[", "$", "version", "]", ";", "}" ]
Translate version number to number of effective key bits. @param int $version @return int
[ "Translate", "version", "number", "to", "number", "of", "effective", "key", "bits", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/AlgorithmIdentifier/Cipher/RC2CBCAlgorithmIdentifier.php#L211-L221
228,782
rexxars/morse-php
library/Text.php
Text.toMorse
public function toMorse($text) { $text = strtoupper($text); $words = preg_split('#\s+#', $text); $morse = array_map([$this, 'morseWord'], $words); return implode($this->wordSeparator, $morse); }
php
public function toMorse($text) { $text = strtoupper($text); $words = preg_split('#\s+#', $text); $morse = array_map([$this, 'morseWord'], $words); return implode($this->wordSeparator, $morse); }
[ "public", "function", "toMorse", "(", "$", "text", ")", "{", "$", "text", "=", "strtoupper", "(", "$", "text", ")", ";", "$", "words", "=", "preg_split", "(", "'#\\s+#'", ",", "$", "text", ")", ";", "$", "morse", "=", "array_map", "(", "[", "$", "this", ",", "'morseWord'", "]", ",", "$", "words", ")", ";", "return", "implode", "(", "$", "this", "->", "wordSeparator", ",", "$", "morse", ")", ";", "}" ]
Translate the given text to morse code @param string $text @return string
[ "Translate", "the", "given", "text", "to", "morse", "code" ]
4f8b8fe15639ddd6f9f030c06e9ccce844142ac9
https://github.com/rexxars/morse-php/blob/4f8b8fe15639ddd6f9f030c06e9ccce844142ac9/library/Text.php#L71-L76
228,783
rexxars/morse-php
library/Text.php
Text.fromMorse
public function fromMorse($morse) { $morse = str_replace($this->invalidCharacterReplacement . ' ', '', $morse); $words = explode($this->wordSeparator, $morse); $morse = array_map([$this, 'translateMorseWord'], $words); return implode(' ', $morse); }
php
public function fromMorse($morse) { $morse = str_replace($this->invalidCharacterReplacement . ' ', '', $morse); $words = explode($this->wordSeparator, $morse); $morse = array_map([$this, 'translateMorseWord'], $words); return implode(' ', $morse); }
[ "public", "function", "fromMorse", "(", "$", "morse", ")", "{", "$", "morse", "=", "str_replace", "(", "$", "this", "->", "invalidCharacterReplacement", ".", "' '", ",", "''", ",", "$", "morse", ")", ";", "$", "words", "=", "explode", "(", "$", "this", "->", "wordSeparator", ",", "$", "morse", ")", ";", "$", "morse", "=", "array_map", "(", "[", "$", "this", ",", "'translateMorseWord'", "]", ",", "$", "words", ")", ";", "return", "implode", "(", "' '", ",", "$", "morse", ")", ";", "}" ]
Translate the given morse code to text @param string $morse @return string
[ "Translate", "the", "given", "morse", "code", "to", "text" ]
4f8b8fe15639ddd6f9f030c06e9ccce844142ac9
https://github.com/rexxars/morse-php/blob/4f8b8fe15639ddd6f9f030c06e9ccce844142ac9/library/Text.php#L84-L89
228,784
rexxars/morse-php
library/Text.php
Text.translateMorseWord
private function translateMorseWord($morse) { $morseChars = explode(' ', $morse); $characters = array_map([$this, 'translateMorseCharacter'], $morseChars); return implode('', $characters); }
php
private function translateMorseWord($morse) { $morseChars = explode(' ', $morse); $characters = array_map([$this, 'translateMorseCharacter'], $morseChars); return implode('', $characters); }
[ "private", "function", "translateMorseWord", "(", "$", "morse", ")", "{", "$", "morseChars", "=", "explode", "(", "' '", ",", "$", "morse", ")", ";", "$", "characters", "=", "array_map", "(", "[", "$", "this", ",", "'translateMorseCharacter'", "]", ",", "$", "morseChars", ")", ";", "return", "implode", "(", "''", ",", "$", "characters", ")", ";", "}" ]
Translate a "morse word" to text @param string $morse @return string
[ "Translate", "a", "morse", "word", "to", "text" ]
4f8b8fe15639ddd6f9f030c06e9ccce844142ac9
https://github.com/rexxars/morse-php/blob/4f8b8fe15639ddd6f9f030c06e9ccce844142ac9/library/Text.php#L97-L101
228,785
rexxars/morse-php
library/Text.php
Text.morseWord
private function morseWord($word) { $chars = $this->strSplit($word); $morse = array_map([$this, 'morseCharacter'], $chars); return implode(' ', $morse); }
php
private function morseWord($word) { $chars = $this->strSplit($word); $morse = array_map([$this, 'morseCharacter'], $chars); return implode(' ', $morse); }
[ "private", "function", "morseWord", "(", "$", "word", ")", "{", "$", "chars", "=", "$", "this", "->", "strSplit", "(", "$", "word", ")", ";", "$", "morse", "=", "array_map", "(", "[", "$", "this", ",", "'morseCharacter'", "]", ",", "$", "chars", ")", ";", "return", "implode", "(", "' '", ",", "$", "morse", ")", ";", "}" ]
Return the morse code for this word @param string $word @return string
[ "Return", "the", "morse", "code", "for", "this", "word" ]
4f8b8fe15639ddd6f9f030c06e9ccce844142ac9
https://github.com/rexxars/morse-php/blob/4f8b8fe15639ddd6f9f030c06e9ccce844142ac9/library/Text.php#L119-L123
228,786
rexxars/morse-php
library/Text.php
Text.morseCharacter
private function morseCharacter($char) { if (!isset($this->table[$char])) { return $this->invalidCharacterReplacement; } return $this->table->getMorse($char); }
php
private function morseCharacter($char) { if (!isset($this->table[$char])) { return $this->invalidCharacterReplacement; } return $this->table->getMorse($char); }
[ "private", "function", "morseCharacter", "(", "$", "char", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "table", "[", "$", "char", "]", ")", ")", "{", "return", "$", "this", "->", "invalidCharacterReplacement", ";", "}", "return", "$", "this", "->", "table", "->", "getMorse", "(", "$", "char", ")", ";", "}" ]
Return the morse code for this character @param string $char @return string
[ "Return", "the", "morse", "code", "for", "this", "character" ]
4f8b8fe15639ddd6f9f030c06e9ccce844142ac9
https://github.com/rexxars/morse-php/blob/4f8b8fe15639ddd6f9f030c06e9ccce844142ac9/library/Text.php#L131-L137
228,787
sop/crypto-types
lib/CryptoTypes/Asymmetric/EC/ECPublicKey.php
ECPublicKey.fromCoordinates
public static function fromCoordinates($x, $y, $named_curve = null, $bits = null): ECPublicKey { // if bitsize is not explicitly set, check from supported curves if (!isset($bits) && isset($named_curve)) { $bits = self::_curveSize($named_curve); } $mlen = null; if (isset($bits)) { $mlen = (int) ceil($bits / 8); } $x_os = ECConversion::integerToOctetString(new Integer($x), $mlen)->string(); $y_os = ECConversion::integerToOctetString(new Integer($y), $mlen)->string(); $ec_point = "\x4$x_os$y_os"; return new self($ec_point, $named_curve); }
php
public static function fromCoordinates($x, $y, $named_curve = null, $bits = null): ECPublicKey { // if bitsize is not explicitly set, check from supported curves if (!isset($bits) && isset($named_curve)) { $bits = self::_curveSize($named_curve); } $mlen = null; if (isset($bits)) { $mlen = (int) ceil($bits / 8); } $x_os = ECConversion::integerToOctetString(new Integer($x), $mlen)->string(); $y_os = ECConversion::integerToOctetString(new Integer($y), $mlen)->string(); $ec_point = "\x4$x_os$y_os"; return new self($ec_point, $named_curve); }
[ "public", "static", "function", "fromCoordinates", "(", "$", "x", ",", "$", "y", ",", "$", "named_curve", "=", "null", ",", "$", "bits", "=", "null", ")", ":", "ECPublicKey", "{", "// if bitsize is not explicitly set, check from supported curves", "if", "(", "!", "isset", "(", "$", "bits", ")", "&&", "isset", "(", "$", "named_curve", ")", ")", "{", "$", "bits", "=", "self", "::", "_curveSize", "(", "$", "named_curve", ")", ";", "}", "$", "mlen", "=", "null", ";", "if", "(", "isset", "(", "$", "bits", ")", ")", "{", "$", "mlen", "=", "(", "int", ")", "ceil", "(", "$", "bits", "/", "8", ")", ";", "}", "$", "x_os", "=", "ECConversion", "::", "integerToOctetString", "(", "new", "Integer", "(", "$", "x", ")", ",", "$", "mlen", ")", "->", "string", "(", ")", ";", "$", "y_os", "=", "ECConversion", "::", "integerToOctetString", "(", "new", "Integer", "(", "$", "y", ")", ",", "$", "mlen", ")", "->", "string", "(", ")", ";", "$", "ec_point", "=", "\"\\x4$x_os$y_os\"", ";", "return", "new", "self", "(", "$", "ec_point", ",", "$", "named_curve", ")", ";", "}" ]
Initialize from curve point coordinates. @param int|string $x X coordinate as a base10 number @param int|string $y Y coordinate as a base10 number @param string|null $named_curve Named curve OID @param int|null $bits Size of <i>p</i> in bits @return self
[ "Initialize", "from", "curve", "point", "coordinates", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/EC/ECPublicKey.php#L67-L81
228,788
sop/crypto-types
lib/CryptoTypes/Asymmetric/EC/ECPublicKey.php
ECPublicKey.curvePointOctets
public function curvePointOctets(): array { if ($this->isCompressed()) { throw new \RuntimeException("EC point compression not supported."); } $str = substr($this->_ecPoint, 1); list($x, $y) = str_split($str, (int) floor(strlen($str) / 2)); return [$x, $y]; }
php
public function curvePointOctets(): array { if ($this->isCompressed()) { throw new \RuntimeException("EC point compression not supported."); } $str = substr($this->_ecPoint, 1); list($x, $y) = str_split($str, (int) floor(strlen($str) / 2)); return [$x, $y]; }
[ "public", "function", "curvePointOctets", "(", ")", ":", "array", "{", "if", "(", "$", "this", "->", "isCompressed", "(", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"EC point compression not supported.\"", ")", ";", "}", "$", "str", "=", "substr", "(", "$", "this", "->", "_ecPoint", ",", "1", ")", ";", "list", "(", "$", "x", ",", "$", "y", ")", "=", "str_split", "(", "$", "str", ",", "(", "int", ")", "floor", "(", "strlen", "(", "$", "str", ")", "/", "2", ")", ")", ";", "return", "[", "$", "x", ",", "$", "y", "]", ";", "}" ]
Get curve point coordinates in octet string representation. @return string[] Tuple of X and Y field elements as a string.
[ "Get", "curve", "point", "coordinates", "in", "octet", "string", "representation", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/EC/ECPublicKey.php#L147-L155
228,789
sop/crypto-types
lib/CryptoTypes/Asymmetric/PublicKey.php
PublicKey.fromPEM
public static function fromPEM(PEM $pem) { switch ($pem->type()) { case PEM::TYPE_RSA_PUBLIC_KEY: return RSA\RSAPublicKey::fromDER($pem->data()); case PEM::TYPE_PUBLIC_KEY: return PublicKeyInfo::fromPEM($pem)->publicKey(); } throw new \UnexpectedValueException( "PEM type " . $pem->type() . " is not a valid public key."); }
php
public static function fromPEM(PEM $pem) { switch ($pem->type()) { case PEM::TYPE_RSA_PUBLIC_KEY: return RSA\RSAPublicKey::fromDER($pem->data()); case PEM::TYPE_PUBLIC_KEY: return PublicKeyInfo::fromPEM($pem)->publicKey(); } throw new \UnexpectedValueException( "PEM type " . $pem->type() . " is not a valid public key."); }
[ "public", "static", "function", "fromPEM", "(", "PEM", "$", "pem", ")", "{", "switch", "(", "$", "pem", "->", "type", "(", ")", ")", "{", "case", "PEM", "::", "TYPE_RSA_PUBLIC_KEY", ":", "return", "RSA", "\\", "RSAPublicKey", "::", "fromDER", "(", "$", "pem", "->", "data", "(", ")", ")", ";", "case", "PEM", "::", "TYPE_PUBLIC_KEY", ":", "return", "PublicKeyInfo", "::", "fromPEM", "(", "$", "pem", ")", "->", "publicKey", "(", ")", ";", "}", "throw", "new", "\\", "UnexpectedValueException", "(", "\"PEM type \"", ".", "$", "pem", "->", "type", "(", ")", ".", "\" is not a valid public key.\"", ")", ";", "}" ]
Initialize public key from PEM. @param PEM $pem @throws \UnexpectedValueException @return PublicKey
[ "Initialize", "public", "key", "from", "PEM", "." ]
1d36250a110b07300aeb003a20aeaadfc6445501
https://github.com/sop/crypto-types/blob/1d36250a110b07300aeb003a20aeaadfc6445501/lib/CryptoTypes/Asymmetric/PublicKey.php#L56-L66
228,790
nodes-php/counter-cache
src/CounterCache.php
CounterCache.count
public function count(IlluminateModel $model) { // If model does not implement the CounterCacheable // interface, we'll jump ship and abort. if (! $model instanceof CounterCacheable) { Log::error(sprintf('[%s] Model [%s] does not implement CounterCacheable.', __CLASS__, get_class($model))); throw new NotCounterCacheableException(sprintf('Model [%s] does not implement CounterCacheable.', __CLASS__, get_class($model))); } // Retrieve array of available counter caches $counterCaches = (array) $model->counterCaches(); // Validate counter caches if (empty($counterCaches)) { Log::error(sprintf('[%s] No counter caches found on model [%s].', __CLASS__, get_class($model))); throw new NoCounterCachesFoundException(sprintf('No counter caches found on model [%s].', __CLASS__, get_class($model))); } // Handle each available counter caches foreach ($counterCaches as $counterCacheColumnName => $relations) { // Since an available counter cache could be found // in multiple tables, we'll need to support multiple relations. foreach ((array) $relations as $relationName => $counterCacheConditions) { // Sometimes our counter cache might require additional conditions // which means, we need to support both scenarios $relationName = ! is_array($counterCacheConditions) ? $counterCacheConditions : $relationName; // When we've figured out the name of our relation // we'll just make a quick validation, that it actually exists if (! method_exists($model, $relationName)) { Log::error(sprintf('[%s] Relation [%s] was not found on model [%s]', __CLASS__, $relationName, get_class($model))); throw new RelationNotFoundException(sprintf('Relation [%s] was not found on model [%s]', __CLASS__, $relationName, get_class($model))); } // Retrieve relation query builder $relation = $model->{$relationName}(); // Update the count value for counter cache column $this->updateCount($model, $relation, $counterCacheConditions, $model->getAttribute($relation->getForeignKey()), $counterCacheColumnName); // If our model's foreign key has been updated, // we need to update the counter cache for the previous value as well if (! is_null($model->getOriginal($relation->getForeignKey())) && $model->getOriginal($relation->getForeignKey()) != $model->getAttribute($relation->getForeignKey())) { // Retrieve original foreign key $originalForeignKey = $model->getOriginal($relation->getForeignKey()); // Re-instantiate model and fill it with original foreign key $reModel = $model->newInstance([$relation->getForeignKey() => $originalForeignKey]); // Update the count value for for counter cache column $this->updateCount($reModel, $reModel->{$relationName}(), $counterCacheConditions, $originalForeignKey, $counterCacheColumnName); } } } return true; }
php
public function count(IlluminateModel $model) { // If model does not implement the CounterCacheable // interface, we'll jump ship and abort. if (! $model instanceof CounterCacheable) { Log::error(sprintf('[%s] Model [%s] does not implement CounterCacheable.', __CLASS__, get_class($model))); throw new NotCounterCacheableException(sprintf('Model [%s] does not implement CounterCacheable.', __CLASS__, get_class($model))); } // Retrieve array of available counter caches $counterCaches = (array) $model->counterCaches(); // Validate counter caches if (empty($counterCaches)) { Log::error(sprintf('[%s] No counter caches found on model [%s].', __CLASS__, get_class($model))); throw new NoCounterCachesFoundException(sprintf('No counter caches found on model [%s].', __CLASS__, get_class($model))); } // Handle each available counter caches foreach ($counterCaches as $counterCacheColumnName => $relations) { // Since an available counter cache could be found // in multiple tables, we'll need to support multiple relations. foreach ((array) $relations as $relationName => $counterCacheConditions) { // Sometimes our counter cache might require additional conditions // which means, we need to support both scenarios $relationName = ! is_array($counterCacheConditions) ? $counterCacheConditions : $relationName; // When we've figured out the name of our relation // we'll just make a quick validation, that it actually exists if (! method_exists($model, $relationName)) { Log::error(sprintf('[%s] Relation [%s] was not found on model [%s]', __CLASS__, $relationName, get_class($model))); throw new RelationNotFoundException(sprintf('Relation [%s] was not found on model [%s]', __CLASS__, $relationName, get_class($model))); } // Retrieve relation query builder $relation = $model->{$relationName}(); // Update the count value for counter cache column $this->updateCount($model, $relation, $counterCacheConditions, $model->getAttribute($relation->getForeignKey()), $counterCacheColumnName); // If our model's foreign key has been updated, // we need to update the counter cache for the previous value as well if (! is_null($model->getOriginal($relation->getForeignKey())) && $model->getOriginal($relation->getForeignKey()) != $model->getAttribute($relation->getForeignKey())) { // Retrieve original foreign key $originalForeignKey = $model->getOriginal($relation->getForeignKey()); // Re-instantiate model and fill it with original foreign key $reModel = $model->newInstance([$relation->getForeignKey() => $originalForeignKey]); // Update the count value for for counter cache column $this->updateCount($reModel, $reModel->{$relationName}(), $counterCacheConditions, $originalForeignKey, $counterCacheColumnName); } } } return true; }
[ "public", "function", "count", "(", "IlluminateModel", "$", "model", ")", "{", "// If model does not implement the CounterCacheable", "// interface, we'll jump ship and abort.", "if", "(", "!", "$", "model", "instanceof", "CounterCacheable", ")", "{", "Log", "::", "error", "(", "sprintf", "(", "'[%s] Model [%s] does not implement CounterCacheable.'", ",", "__CLASS__", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "throw", "new", "NotCounterCacheableException", "(", "sprintf", "(", "'Model [%s] does not implement CounterCacheable.'", ",", "__CLASS__", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "}", "// Retrieve array of available counter caches", "$", "counterCaches", "=", "(", "array", ")", "$", "model", "->", "counterCaches", "(", ")", ";", "// Validate counter caches", "if", "(", "empty", "(", "$", "counterCaches", ")", ")", "{", "Log", "::", "error", "(", "sprintf", "(", "'[%s] No counter caches found on model [%s].'", ",", "__CLASS__", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "throw", "new", "NoCounterCachesFoundException", "(", "sprintf", "(", "'No counter caches found on model [%s].'", ",", "__CLASS__", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "}", "// Handle each available counter caches", "foreach", "(", "$", "counterCaches", "as", "$", "counterCacheColumnName", "=>", "$", "relations", ")", "{", "// Since an available counter cache could be found", "// in multiple tables, we'll need to support multiple relations.", "foreach", "(", "(", "array", ")", "$", "relations", "as", "$", "relationName", "=>", "$", "counterCacheConditions", ")", "{", "// Sometimes our counter cache might require additional conditions", "// which means, we need to support both scenarios", "$", "relationName", "=", "!", "is_array", "(", "$", "counterCacheConditions", ")", "?", "$", "counterCacheConditions", ":", "$", "relationName", ";", "// When we've figured out the name of our relation", "// we'll just make a quick validation, that it actually exists", "if", "(", "!", "method_exists", "(", "$", "model", ",", "$", "relationName", ")", ")", "{", "Log", "::", "error", "(", "sprintf", "(", "'[%s] Relation [%s] was not found on model [%s]'", ",", "__CLASS__", ",", "$", "relationName", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "throw", "new", "RelationNotFoundException", "(", "sprintf", "(", "'Relation [%s] was not found on model [%s]'", ",", "__CLASS__", ",", "$", "relationName", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "}", "// Retrieve relation query builder", "$", "relation", "=", "$", "model", "->", "{", "$", "relationName", "}", "(", ")", ";", "// Update the count value for counter cache column", "$", "this", "->", "updateCount", "(", "$", "model", ",", "$", "relation", ",", "$", "counterCacheConditions", ",", "$", "model", "->", "getAttribute", "(", "$", "relation", "->", "getForeignKey", "(", ")", ")", ",", "$", "counterCacheColumnName", ")", ";", "// If our model's foreign key has been updated,", "// we need to update the counter cache for the previous value as well", "if", "(", "!", "is_null", "(", "$", "model", "->", "getOriginal", "(", "$", "relation", "->", "getForeignKey", "(", ")", ")", ")", "&&", "$", "model", "->", "getOriginal", "(", "$", "relation", "->", "getForeignKey", "(", ")", ")", "!=", "$", "model", "->", "getAttribute", "(", "$", "relation", "->", "getForeignKey", "(", ")", ")", ")", "{", "// Retrieve original foreign key", "$", "originalForeignKey", "=", "$", "model", "->", "getOriginal", "(", "$", "relation", "->", "getForeignKey", "(", ")", ")", ";", "// Re-instantiate model and fill it with original foreign key", "$", "reModel", "=", "$", "model", "->", "newInstance", "(", "[", "$", "relation", "->", "getForeignKey", "(", ")", "=>", "$", "originalForeignKey", "]", ")", ";", "// Update the count value for for counter cache column", "$", "this", "->", "updateCount", "(", "$", "reModel", ",", "$", "reModel", "->", "{", "$", "relationName", "}", "(", ")", ",", "$", "counterCacheConditions", ",", "$", "originalForeignKey", ",", "$", "counterCacheColumnName", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
Perform counter caching on model. @author Morten Rugaard <moru@nodes.dk> @param \Illuminate\Database\Eloquent\Model $model @return bool @throws \Nodes\CounterCache\Exceptions\NoCounterCachesFoundException @throws \Nodes\CounterCache\Exceptions\NotCounterCacheableException @throws \Nodes\CounterCache\Exceptions\RelationNotFoundException
[ "Perform", "counter", "caching", "on", "model", "." ]
623f19bdcfd15fdadfb38d9f118ea0dbdfebf7df
https://github.com/nodes-php/counter-cache/blob/623f19bdcfd15fdadfb38d9f118ea0dbdfebf7df/src/CounterCache.php#L30-L86
228,791
nodes-php/counter-cache
src/CounterCache.php
CounterCache.countAll
public function countAll(IlluminateModel $model) { // Retrieve all entities of model $entities = $model->get(); // If no entities found, we'll log the error, // throw an exception and abort. if (! $entities->isEmpty()) { Log::error(sprintf('[%s] No entities found of model [%s]', __CLASS__, get_class($model))); throw new NoEntitiesFoundException(sprintf('No entities found of model [%s]', get_class($model))); } // Perform counter caching on each found entity foreach ($entities as $entry) { $this->count($entry); } return true; }
php
public function countAll(IlluminateModel $model) { // Retrieve all entities of model $entities = $model->get(); // If no entities found, we'll log the error, // throw an exception and abort. if (! $entities->isEmpty()) { Log::error(sprintf('[%s] No entities found of model [%s]', __CLASS__, get_class($model))); throw new NoEntitiesFoundException(sprintf('No entities found of model [%s]', get_class($model))); } // Perform counter caching on each found entity foreach ($entities as $entry) { $this->count($entry); } return true; }
[ "public", "function", "countAll", "(", "IlluminateModel", "$", "model", ")", "{", "// Retrieve all entities of model", "$", "entities", "=", "$", "model", "->", "get", "(", ")", ";", "// If no entities found, we'll log the error,", "// throw an exception and abort.", "if", "(", "!", "$", "entities", "->", "isEmpty", "(", ")", ")", "{", "Log", "::", "error", "(", "sprintf", "(", "'[%s] No entities found of model [%s]'", ",", "__CLASS__", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "throw", "new", "NoEntitiesFoundException", "(", "sprintf", "(", "'No entities found of model [%s]'", ",", "get_class", "(", "$", "model", ")", ")", ")", ";", "}", "// Perform counter caching on each found entity", "foreach", "(", "$", "entities", "as", "$", "entry", ")", "{", "$", "this", "->", "count", "(", "$", "entry", ")", ";", "}", "return", "true", ";", "}" ]
Perform counter caching on all entities of model. @author Morten Rugaard <moru@nodes.dk> @param \Illuminate\Database\Eloquent\Model $model @return bool @throws \Nodes\CounterCache\Exceptions\NoEntitiesFoundException @throws \Nodes\CounterCache\Exceptions\NoCounterCachesFound @throws \Nodes\CounterCache\Exceptions\NotCounterCacheableException @throws \Nodes\CounterCache\Exceptions\RelationNotFoundException
[ "Perform", "counter", "caching", "on", "all", "entities", "of", "model", "." ]
623f19bdcfd15fdadfb38d9f118ea0dbdfebf7df
https://github.com/nodes-php/counter-cache/blob/623f19bdcfd15fdadfb38d9f118ea0dbdfebf7df/src/CounterCache.php#L100-L118
228,792
nodes-php/counter-cache
src/CounterCache.php
CounterCache.updateCount
protected function updateCount(IlluminateModel $model, IlluminateRelation $relation, $counterCacheConditions, $foreignKey, $counterCacheColumnName) { // Retrieve table name of relation $relationTableName = $relation->getModel()->getTable(); // Generate query builder for counting entries // on our model. Result will be used as value when // we're updating the counter cache column on the relation $countQuery = $model->newQuery() ->select(DB::raw(sprintf('COUNT(%s.id)', $model->getTable()))) ->join( DB::raw(sprintf('(SELECT %s.%s FROM %s) as relation', $relationTableName, $relation->getOwnerKey(), $relationTableName)), $relation->getQualifiedForeignKey(), '=', sprintf('relation.%s', $relation->getOwnerKey()) ) ->where($relation->getQualifiedForeignKey(), '=', $this->prepareValue($foreignKey)); // If our relation has additional conditions, we'll need // to add them to our query builder that counts the entries if (is_array($counterCacheConditions)) { foreach ($counterCacheConditions as $conditionType => $conditionParameters) { foreach ($conditionParameters as $parameters) { call_user_func_array([$countQuery, $conditionType], $parameters); } } } // Retrieve countQuery SQL // and prepare for binding replacements $countQuerySql = str_replace(['%', '?'], ['%%', '%s'], $countQuery->toSql()); // Fire the update query // to update counter cache column return (bool) $relation->getBaseQuery()->update([ sprintf('%s.%s', $relationTableName, $counterCacheColumnName) => DB::raw(sprintf('(%s)', vsprintf($countQuerySql, $countQuery->getBindings()))), ]); }
php
protected function updateCount(IlluminateModel $model, IlluminateRelation $relation, $counterCacheConditions, $foreignKey, $counterCacheColumnName) { // Retrieve table name of relation $relationTableName = $relation->getModel()->getTable(); // Generate query builder for counting entries // on our model. Result will be used as value when // we're updating the counter cache column on the relation $countQuery = $model->newQuery() ->select(DB::raw(sprintf('COUNT(%s.id)', $model->getTable()))) ->join( DB::raw(sprintf('(SELECT %s.%s FROM %s) as relation', $relationTableName, $relation->getOwnerKey(), $relationTableName)), $relation->getQualifiedForeignKey(), '=', sprintf('relation.%s', $relation->getOwnerKey()) ) ->where($relation->getQualifiedForeignKey(), '=', $this->prepareValue($foreignKey)); // If our relation has additional conditions, we'll need // to add them to our query builder that counts the entries if (is_array($counterCacheConditions)) { foreach ($counterCacheConditions as $conditionType => $conditionParameters) { foreach ($conditionParameters as $parameters) { call_user_func_array([$countQuery, $conditionType], $parameters); } } } // Retrieve countQuery SQL // and prepare for binding replacements $countQuerySql = str_replace(['%', '?'], ['%%', '%s'], $countQuery->toSql()); // Fire the update query // to update counter cache column return (bool) $relation->getBaseQuery()->update([ sprintf('%s.%s', $relationTableName, $counterCacheColumnName) => DB::raw(sprintf('(%s)', vsprintf($countQuerySql, $countQuery->getBindings()))), ]); }
[ "protected", "function", "updateCount", "(", "IlluminateModel", "$", "model", ",", "IlluminateRelation", "$", "relation", ",", "$", "counterCacheConditions", ",", "$", "foreignKey", ",", "$", "counterCacheColumnName", ")", "{", "// Retrieve table name of relation", "$", "relationTableName", "=", "$", "relation", "->", "getModel", "(", ")", "->", "getTable", "(", ")", ";", "// Generate query builder for counting entries", "// on our model. Result will be used as value when", "// we're updating the counter cache column on the relation", "$", "countQuery", "=", "$", "model", "->", "newQuery", "(", ")", "->", "select", "(", "DB", "::", "raw", "(", "sprintf", "(", "'COUNT(%s.id)'", ",", "$", "model", "->", "getTable", "(", ")", ")", ")", ")", "->", "join", "(", "DB", "::", "raw", "(", "sprintf", "(", "'(SELECT %s.%s FROM %s) as relation'", ",", "$", "relationTableName", ",", "$", "relation", "->", "getOwnerKey", "(", ")", ",", "$", "relationTableName", ")", ")", ",", "$", "relation", "->", "getQualifiedForeignKey", "(", ")", ",", "'='", ",", "sprintf", "(", "'relation.%s'", ",", "$", "relation", "->", "getOwnerKey", "(", ")", ")", ")", "->", "where", "(", "$", "relation", "->", "getQualifiedForeignKey", "(", ")", ",", "'='", ",", "$", "this", "->", "prepareValue", "(", "$", "foreignKey", ")", ")", ";", "// If our relation has additional conditions, we'll need", "// to add them to our query builder that counts the entries", "if", "(", "is_array", "(", "$", "counterCacheConditions", ")", ")", "{", "foreach", "(", "$", "counterCacheConditions", "as", "$", "conditionType", "=>", "$", "conditionParameters", ")", "{", "foreach", "(", "$", "conditionParameters", "as", "$", "parameters", ")", "{", "call_user_func_array", "(", "[", "$", "countQuery", ",", "$", "conditionType", "]", ",", "$", "parameters", ")", ";", "}", "}", "}", "// Retrieve countQuery SQL", "// and prepare for binding replacements", "$", "countQuerySql", "=", "str_replace", "(", "[", "'%'", ",", "'?'", "]", ",", "[", "'%%'", ",", "'%s'", "]", ",", "$", "countQuery", "->", "toSql", "(", ")", ")", ";", "// Fire the update query", "// to update counter cache column", "return", "(", "bool", ")", "$", "relation", "->", "getBaseQuery", "(", ")", "->", "update", "(", "[", "sprintf", "(", "'%s.%s'", ",", "$", "relationTableName", ",", "$", "counterCacheColumnName", ")", "=>", "DB", "::", "raw", "(", "sprintf", "(", "'(%s)'", ",", "vsprintf", "(", "$", "countQuerySql", ",", "$", "countQuery", "->", "getBindings", "(", ")", ")", ")", ")", ",", "]", ")", ";", "}" ]
Update counter cache column. @author Morten Rugaard <moru@nodes.dk> @param \Illuminate\Database\Eloquent\Model $model @param \Illuminate\Database\Eloquent\Relations\Relation $relation @param array|null $counterCacheConditions @param string $foreignKey @param string $counterCacheColumnName @return bool
[ "Update", "counter", "cache", "column", "." ]
623f19bdcfd15fdadfb38d9f118ea0dbdfebf7df
https://github.com/nodes-php/counter-cache/blob/623f19bdcfd15fdadfb38d9f118ea0dbdfebf7df/src/CounterCache.php#L132-L167
228,793
pear/Net_LDAP2
Net/LDAP2/Search.php
Net_LDAP2_Search.entries
public function entries() { $entries = array(); if (false === $this->_entry_cache) { // cache is empty: fetch from LDAP while ($entry = $this->shiftEntry()) { $entries[] = $entry; } $this->_entry_cache = $entries; // store result in cache } return $this->_entry_cache; }
php
public function entries() { $entries = array(); if (false === $this->_entry_cache) { // cache is empty: fetch from LDAP while ($entry = $this->shiftEntry()) { $entries[] = $entry; } $this->_entry_cache = $entries; // store result in cache } return $this->_entry_cache; }
[ "public", "function", "entries", "(", ")", "{", "$", "entries", "=", "array", "(", ")", ";", "if", "(", "false", "===", "$", "this", "->", "_entry_cache", ")", "{", "// cache is empty: fetch from LDAP", "while", "(", "$", "entry", "=", "$", "this", "->", "shiftEntry", "(", ")", ")", "{", "$", "entries", "[", "]", "=", "$", "entry", ";", "}", "$", "this", "->", "_entry_cache", "=", "$", "entries", ";", "// store result in cache", "}", "return", "$", "this", "->", "_entry_cache", ";", "}" ]
Returns an array of entry objects. @return array Array of entry objects.
[ "Returns", "an", "array", "of", "entry", "objects", "." ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/Search.php#L159-L172
228,794
pear/Net_LDAP2
Net/LDAP2/Search.php
Net_LDAP2_Search.shiftEntry
public function shiftEntry() { if (is_null($this->_entry)) { if(!$this->_entry = @ldap_first_entry($this->_link, $this->_search)) { $false = false; return $false; } $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry); if ($entry instanceof PEAR_Error) $entry = false; } else { if (!$this->_entry = @ldap_next_entry($this->_link, $this->_entry)) { $false = false; return $false; } $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry); if ($entry instanceof PEAR_Error) $entry = false; } return $entry; }
php
public function shiftEntry() { if (is_null($this->_entry)) { if(!$this->_entry = @ldap_first_entry($this->_link, $this->_search)) { $false = false; return $false; } $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry); if ($entry instanceof PEAR_Error) $entry = false; } else { if (!$this->_entry = @ldap_next_entry($this->_link, $this->_entry)) { $false = false; return $false; } $entry = Net_LDAP2_Entry::createConnected($this->_ldap, $this->_entry); if ($entry instanceof PEAR_Error) $entry = false; } return $entry; }
[ "public", "function", "shiftEntry", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "_entry", ")", ")", "{", "if", "(", "!", "$", "this", "->", "_entry", "=", "@", "ldap_first_entry", "(", "$", "this", "->", "_link", ",", "$", "this", "->", "_search", ")", ")", "{", "$", "false", "=", "false", ";", "return", "$", "false", ";", "}", "$", "entry", "=", "Net_LDAP2_Entry", "::", "createConnected", "(", "$", "this", "->", "_ldap", ",", "$", "this", "->", "_entry", ")", ";", "if", "(", "$", "entry", "instanceof", "PEAR_Error", ")", "$", "entry", "=", "false", ";", "}", "else", "{", "if", "(", "!", "$", "this", "->", "_entry", "=", "@", "ldap_next_entry", "(", "$", "this", "->", "_link", ",", "$", "this", "->", "_entry", ")", ")", "{", "$", "false", "=", "false", ";", "return", "$", "false", ";", "}", "$", "entry", "=", "Net_LDAP2_Entry", "::", "createConnected", "(", "$", "this", "->", "_ldap", ",", "$", "this", "->", "_entry", ")", ";", "if", "(", "$", "entry", "instanceof", "PEAR_Error", ")", "$", "entry", "=", "false", ";", "}", "return", "$", "entry", ";", "}" ]
Get the next entry in the searchresult from LDAP server. This will return a valid Net_LDAP2_Entry object or false, so you can use this method to easily iterate over the entries inside a while loop. @return Net_LDAP2_Entry|false Reference to Net_LDAP2_Entry object or false
[ "Get", "the", "next", "entry", "in", "the", "searchresult", "from", "LDAP", "server", "." ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/Search.php#L183-L201
228,795
pear/Net_LDAP2
Net/LDAP2/Search.php
Net_LDAP2_Search.popEntry
public function popEntry() { if (false === $this->_entry_cache) { // fetch entries into cache if not done so far $this->_entry_cache = $this->entries(); } $return = array_pop($this->_entry_cache); return (null === $return)? false : $return; }
php
public function popEntry() { if (false === $this->_entry_cache) { // fetch entries into cache if not done so far $this->_entry_cache = $this->entries(); } $return = array_pop($this->_entry_cache); return (null === $return)? false : $return; }
[ "public", "function", "popEntry", "(", ")", "{", "if", "(", "false", "===", "$", "this", "->", "_entry_cache", ")", "{", "// fetch entries into cache if not done so far", "$", "this", "->", "_entry_cache", "=", "$", "this", "->", "entries", "(", ")", ";", "}", "$", "return", "=", "array_pop", "(", "$", "this", "->", "_entry_cache", ")", ";", "return", "(", "null", "===", "$", "return", ")", "?", "false", ":", "$", "return", ";", "}" ]
Retrieve the next entry in the searchresult, but starting from last entry This is the opposite to {@link shiftEntry()} and is also very useful to be used inside a while loop. @return Net_LDAP2_Entry|false
[ "Retrieve", "the", "next", "entry", "in", "the", "searchresult", "but", "starting", "from", "last", "entry" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/Search.php#L223-L232
228,796
pear/Net_LDAP2
Net/LDAP2/Search.php
Net_LDAP2_Search.sorted_as_struct
public function sorted_as_struct($attrs = array('cn'), $order = SORT_ASC) { /* * Old Code, suitable and fast for single valued sorting * This code should be used if we know that single valued sorting is desired, * but we need some method to get that knowledge... */ /* $attrs = array_reverse($attrs); foreach ($attrs as $attribute) { if (!ldap_sort($this->_link, $this->_search, $attribute)){ $this->raiseError("Sorting failed for Attribute " . $attribute); } } $results = ldap_get_entries($this->_link, $this->_search); unset($results['count']); //for tidier output if ($order) { return array_reverse($results); } else { return $results; }*/ /* * New code: complete "client side" sorting */ // first some parameterchecks if (!is_array($attrs)) { return PEAR::raiseError("Sorting failed: Parameterlist must be an array!"); } if ($order != SORT_ASC && $order != SORT_DESC) { return PEAR::raiseError("Sorting failed: sorting direction not understood! (neither constant SORT_ASC nor SORT_DESC)"); } // fetch the entries data $entries = $this->as_struct(); // now sort each entries attribute values // this is neccessary because later we can only sort by one value, // so we need the highest or lowest attribute now, depending on the // selected ordering for that specific attribute foreach ($entries as $dn => $entry) { foreach ($entry as $attr_name => $attr_values) { sort($entries[$dn][$attr_name]); if ($order == SORT_DESC) { array_reverse($entries[$dn][$attr_name]); } } } // reformat entrys array for later use with array_multisort() $to_sort = array(); // <- will be a numeric array similar to ldap_get_entries foreach ($entries as $dn => $entry_attr) { $row = array(); $row['dn'] = $dn; foreach ($entry_attr as $attr_name => $attr_values) { $row[$attr_name] = $attr_values; } $to_sort[] = $row; } // Build columns for array_multisort() // each requested attribute is one row $columns = array(); foreach ($attrs as $attr_name) { foreach ($to_sort as $key => $row) { $columns[$attr_name][$key] =& $to_sort[$key][$attr_name][0]; } } // sort the colums with array_multisort, if there is something // to sort and if we have requested sort columns if (!empty($to_sort) && !empty($columns)) { $sort_params = ''; foreach ($attrs as $attr_name) { $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', '; } eval("array_multisort($sort_params \$to_sort);"); // perform sorting } return $to_sort; }
php
public function sorted_as_struct($attrs = array('cn'), $order = SORT_ASC) { /* * Old Code, suitable and fast for single valued sorting * This code should be used if we know that single valued sorting is desired, * but we need some method to get that knowledge... */ /* $attrs = array_reverse($attrs); foreach ($attrs as $attribute) { if (!ldap_sort($this->_link, $this->_search, $attribute)){ $this->raiseError("Sorting failed for Attribute " . $attribute); } } $results = ldap_get_entries($this->_link, $this->_search); unset($results['count']); //for tidier output if ($order) { return array_reverse($results); } else { return $results; }*/ /* * New code: complete "client side" sorting */ // first some parameterchecks if (!is_array($attrs)) { return PEAR::raiseError("Sorting failed: Parameterlist must be an array!"); } if ($order != SORT_ASC && $order != SORT_DESC) { return PEAR::raiseError("Sorting failed: sorting direction not understood! (neither constant SORT_ASC nor SORT_DESC)"); } // fetch the entries data $entries = $this->as_struct(); // now sort each entries attribute values // this is neccessary because later we can only sort by one value, // so we need the highest or lowest attribute now, depending on the // selected ordering for that specific attribute foreach ($entries as $dn => $entry) { foreach ($entry as $attr_name => $attr_values) { sort($entries[$dn][$attr_name]); if ($order == SORT_DESC) { array_reverse($entries[$dn][$attr_name]); } } } // reformat entrys array for later use with array_multisort() $to_sort = array(); // <- will be a numeric array similar to ldap_get_entries foreach ($entries as $dn => $entry_attr) { $row = array(); $row['dn'] = $dn; foreach ($entry_attr as $attr_name => $attr_values) { $row[$attr_name] = $attr_values; } $to_sort[] = $row; } // Build columns for array_multisort() // each requested attribute is one row $columns = array(); foreach ($attrs as $attr_name) { foreach ($to_sort as $key => $row) { $columns[$attr_name][$key] =& $to_sort[$key][$attr_name][0]; } } // sort the colums with array_multisort, if there is something // to sort and if we have requested sort columns if (!empty($to_sort) && !empty($columns)) { $sort_params = ''; foreach ($attrs as $attr_name) { $sort_params .= '$columns[\''.$attr_name.'\'], '.$order.', '; } eval("array_multisort($sort_params \$to_sort);"); // perform sorting } return $to_sort; }
[ "public", "function", "sorted_as_struct", "(", "$", "attrs", "=", "array", "(", "'cn'", ")", ",", "$", "order", "=", "SORT_ASC", ")", "{", "/*\n * Old Code, suitable and fast for single valued sorting\n * This code should be used if we know that single valued sorting is desired,\n * but we need some method to get that knowledge...\n */", "/*\n $attrs = array_reverse($attrs);\n foreach ($attrs as $attribute) {\n if (!ldap_sort($this->_link, $this->_search, $attribute)){\n $this->raiseError(\"Sorting failed for Attribute \" . $attribute);\n }\n }\n\n $results = ldap_get_entries($this->_link, $this->_search);\n\n unset($results['count']); //for tidier output\n if ($order) {\n return array_reverse($results);\n } else {\n return $results;\n }*/", "/*\n * New code: complete \"client side\" sorting\n */", "// first some parameterchecks", "if", "(", "!", "is_array", "(", "$", "attrs", ")", ")", "{", "return", "PEAR", "::", "raiseError", "(", "\"Sorting failed: Parameterlist must be an array!\"", ")", ";", "}", "if", "(", "$", "order", "!=", "SORT_ASC", "&&", "$", "order", "!=", "SORT_DESC", ")", "{", "return", "PEAR", "::", "raiseError", "(", "\"Sorting failed: sorting direction not understood! (neither constant SORT_ASC nor SORT_DESC)\"", ")", ";", "}", "// fetch the entries data", "$", "entries", "=", "$", "this", "->", "as_struct", "(", ")", ";", "// now sort each entries attribute values", "// this is neccessary because later we can only sort by one value,", "// so we need the highest or lowest attribute now, depending on the", "// selected ordering for that specific attribute", "foreach", "(", "$", "entries", "as", "$", "dn", "=>", "$", "entry", ")", "{", "foreach", "(", "$", "entry", "as", "$", "attr_name", "=>", "$", "attr_values", ")", "{", "sort", "(", "$", "entries", "[", "$", "dn", "]", "[", "$", "attr_name", "]", ")", ";", "if", "(", "$", "order", "==", "SORT_DESC", ")", "{", "array_reverse", "(", "$", "entries", "[", "$", "dn", "]", "[", "$", "attr_name", "]", ")", ";", "}", "}", "}", "// reformat entrys array for later use with array_multisort()", "$", "to_sort", "=", "array", "(", ")", ";", "// <- will be a numeric array similar to ldap_get_entries", "foreach", "(", "$", "entries", "as", "$", "dn", "=>", "$", "entry_attr", ")", "{", "$", "row", "=", "array", "(", ")", ";", "$", "row", "[", "'dn'", "]", "=", "$", "dn", ";", "foreach", "(", "$", "entry_attr", "as", "$", "attr_name", "=>", "$", "attr_values", ")", "{", "$", "row", "[", "$", "attr_name", "]", "=", "$", "attr_values", ";", "}", "$", "to_sort", "[", "]", "=", "$", "row", ";", "}", "// Build columns for array_multisort()", "// each requested attribute is one row", "$", "columns", "=", "array", "(", ")", ";", "foreach", "(", "$", "attrs", "as", "$", "attr_name", ")", "{", "foreach", "(", "$", "to_sort", "as", "$", "key", "=>", "$", "row", ")", "{", "$", "columns", "[", "$", "attr_name", "]", "[", "$", "key", "]", "=", "&", "$", "to_sort", "[", "$", "key", "]", "[", "$", "attr_name", "]", "[", "0", "]", ";", "}", "}", "// sort the colums with array_multisort, if there is something", "// to sort and if we have requested sort columns", "if", "(", "!", "empty", "(", "$", "to_sort", ")", "&&", "!", "empty", "(", "$", "columns", ")", ")", "{", "$", "sort_params", "=", "''", ";", "foreach", "(", "$", "attrs", "as", "$", "attr_name", ")", "{", "$", "sort_params", ".=", "'$columns[\\''", ".", "$", "attr_name", ".", "'\\'], '", ".", "$", "order", ".", "', '", ";", "}", "eval", "(", "\"array_multisort($sort_params \\$to_sort);\"", ")", ";", "// perform sorting", "}", "return", "$", "to_sort", ";", "}" ]
Return entries sorted as array This returns a array with sorted entries and the values. Sorting is done with PHPs {@link array_multisort()}. This method relies on {@link as_struct()} to fetch the raw data of the entries. Please note that attribute names are case sensitive! Usage example: <code> // to sort entries first by location, then by surename, but descending: $entries = $search->sorted_as_struct(array('locality','sn'), SORT_DESC); </code> @param array $attrs Array of attribute names to sort; order from left to right. @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC @return array|Net_LDAP2_Error Array with sorted entries or error @todo what about server side sorting as specified in http://www.ietf.org/rfc/rfc2891.txt?
[ "Return", "entries", "sorted", "as", "array" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/Search.php#L267-L349
228,797
pear/Net_LDAP2
Net/LDAP2/Search.php
Net_LDAP2_Search.sorted
public function sorted($attrs = array('cn'), $order = SORT_ASC) { $return = array(); $sorted = $this->sorted_as_struct($attrs, $order); if (PEAR::isError($sorted)) { return $sorted; } foreach ($sorted as $key => $row) { $entry = $this->_ldap->getEntry($row['dn'], $this->searchedAttrs()); if (!PEAR::isError($entry)) { array_push($return, $entry); } else { return $entry; } } return $return; }
php
public function sorted($attrs = array('cn'), $order = SORT_ASC) { $return = array(); $sorted = $this->sorted_as_struct($attrs, $order); if (PEAR::isError($sorted)) { return $sorted; } foreach ($sorted as $key => $row) { $entry = $this->_ldap->getEntry($row['dn'], $this->searchedAttrs()); if (!PEAR::isError($entry)) { array_push($return, $entry); } else { return $entry; } } return $return; }
[ "public", "function", "sorted", "(", "$", "attrs", "=", "array", "(", "'cn'", ")", ",", "$", "order", "=", "SORT_ASC", ")", "{", "$", "return", "=", "array", "(", ")", ";", "$", "sorted", "=", "$", "this", "->", "sorted_as_struct", "(", "$", "attrs", ",", "$", "order", ")", ";", "if", "(", "PEAR", "::", "isError", "(", "$", "sorted", ")", ")", "{", "return", "$", "sorted", ";", "}", "foreach", "(", "$", "sorted", "as", "$", "key", "=>", "$", "row", ")", "{", "$", "entry", "=", "$", "this", "->", "_ldap", "->", "getEntry", "(", "$", "row", "[", "'dn'", "]", ",", "$", "this", "->", "searchedAttrs", "(", ")", ")", ";", "if", "(", "!", "PEAR", "::", "isError", "(", "$", "entry", ")", ")", "{", "array_push", "(", "$", "return", ",", "$", "entry", ")", ";", "}", "else", "{", "return", "$", "entry", ";", "}", "}", "return", "$", "return", ";", "}" ]
Return entries sorted as objects This returns a array with sorted Net_LDAP2_Entry objects. The sorting is actually done with {@link sorted_as_struct()}. Please note that attribute names are case sensitive! Also note, that it is (depending on server capabilitys) possible to let the server sort your results. This happens through search controls and is described in detail at {@link http://www.ietf.org/rfc/rfc2891.txt} Usage example: <code> // to sort entries first by location, then by surename, but descending: $entries = $search->sorted(array('locality','sn'), SORT_DESC); </code> @param array $attrs Array of sort attributes to sort; order from left to right. @param int $order Ordering direction, either constant SORT_ASC or SORT_DESC @return array|Net_LDAP2_Error Array with sorted Net_LDAP2_Entries or error @todo Entry object construction could be faster. Maybe we could use one of the factorys instead of fetching the entry again
[ "Return", "entries", "sorted", "as", "objects" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/Search.php#L374-L390
228,798
pear/Net_LDAP2
Net/LDAP2/Search.php
Net_LDAP2_Search.as_struct
public function as_struct() { $return = array(); $entries = $this->entries(); foreach ($entries as $entry) { $attrs = array(); $entry_attributes = $entry->attributes(); foreach ($entry_attributes as $attr_name) { $attr_values = $entry->getValue($attr_name, 'all'); if (!is_array($attr_values)) { $attr_values = array($attr_values); } $attrs[$attr_name] = $attr_values; } $return[$entry->dn()] = $attrs; } return $return; }
php
public function as_struct() { $return = array(); $entries = $this->entries(); foreach ($entries as $entry) { $attrs = array(); $entry_attributes = $entry->attributes(); foreach ($entry_attributes as $attr_name) { $attr_values = $entry->getValue($attr_name, 'all'); if (!is_array($attr_values)) { $attr_values = array($attr_values); } $attrs[$attr_name] = $attr_values; } $return[$entry->dn()] = $attrs; } return $return; }
[ "public", "function", "as_struct", "(", ")", "{", "$", "return", "=", "array", "(", ")", ";", "$", "entries", "=", "$", "this", "->", "entries", "(", ")", ";", "foreach", "(", "$", "entries", "as", "$", "entry", ")", "{", "$", "attrs", "=", "array", "(", ")", ";", "$", "entry_attributes", "=", "$", "entry", "->", "attributes", "(", ")", ";", "foreach", "(", "$", "entry_attributes", "as", "$", "attr_name", ")", "{", "$", "attr_values", "=", "$", "entry", "->", "getValue", "(", "$", "attr_name", ",", "'all'", ")", ";", "if", "(", "!", "is_array", "(", "$", "attr_values", ")", ")", "{", "$", "attr_values", "=", "array", "(", "$", "attr_values", ")", ";", "}", "$", "attrs", "[", "$", "attr_name", "]", "=", "$", "attr_values", ";", "}", "$", "return", "[", "$", "entry", "->", "dn", "(", ")", "]", "=", "$", "attrs", ";", "}", "return", "$", "return", ";", "}" ]
Return entries as array This method returns the entries and the selected attributes values as array. The first array level contains all found entries where the keys are the DNs of the entries. The second level arrays contian the entries attributes such that the keys is the lowercased name of the attribute and the values are stored in another indexed array. Note that the attribute values are stored in an array even if there is no or just one value. The array has the following structure: <code> $return = array( 'cn=foo,dc=example,dc=com' => array( 'sn' => array('foo'), 'multival' => array('val1', 'val2', 'valN') ) 'cn=bar,dc=example,dc=com' => array( 'sn' => array('bar'), 'multival' => array('val1', 'valN') ) ) </code> @return array associative result array as described above
[ "Return", "entries", "as", "array" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/Search.php#L419-L436
228,799
pear/Net_LDAP2
Net/LDAP2/Search.php
Net_LDAP2_Search.count
public function count() { // this catches the situation where OL returned errno 32 = no such object! if (!$this->_search) { return 0; } // ldap_count_entries is slow (see pear bug #18752) with large results, // so we cache the result internally. if ($this->_count_cache === null) { $this->_count_cache = @ldap_count_entries($this->_link, $this->_search); } return $this->_count_cache; }
php
public function count() { // this catches the situation where OL returned errno 32 = no such object! if (!$this->_search) { return 0; } // ldap_count_entries is slow (see pear bug #18752) with large results, // so we cache the result internally. if ($this->_count_cache === null) { $this->_count_cache = @ldap_count_entries($this->_link, $this->_search); } return $this->_count_cache; }
[ "public", "function", "count", "(", ")", "{", "// this catches the situation where OL returned errno 32 = no such object!", "if", "(", "!", "$", "this", "->", "_search", ")", "{", "return", "0", ";", "}", "// ldap_count_entries is slow (see pear bug #18752) with large results,", "// so we cache the result internally.", "if", "(", "$", "this", "->", "_count_cache", "===", "null", ")", "{", "$", "this", "->", "_count_cache", "=", "@", "ldap_count_entries", "(", "$", "this", "->", "_link", ",", "$", "this", "->", "_search", ")", ";", "}", "return", "$", "this", "->", "_count_cache", ";", "}" ]
Returns the number of entries in the searchresult @return int Number of entries in search.
[ "Returns", "the", "number", "of", "entries", "in", "the", "searchresult" ]
38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8
https://github.com/pear/Net_LDAP2/blob/38f1b22a96dfbd7ec53852f0e1e7ec1a9a5eb0e8/Net/LDAP2/Search.php#L469-L482