repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
varspool/Wrench | lib/Protocol/Protocol.php | Protocol.validateOriginUri | public function validateOriginUri($origin)
{
$origin = (string)$origin;
if (!$origin) {
throw new InvalidArgumentException('Invalid URI');
}
$scheme = parse_url($origin, PHP_URL_SCHEME);
if (!$scheme) {
throw new InvalidArgumentException('Invalid scheme');
}
$host = parse_url($origin, PHP_URL_HOST);
if (!$host) {
throw new InvalidArgumentException("Invalid host");
}
return $origin;
} | php | public function validateOriginUri($origin)
{
$origin = (string)$origin;
if (!$origin) {
throw new InvalidArgumentException('Invalid URI');
}
$scheme = parse_url($origin, PHP_URL_SCHEME);
if (!$scheme) {
throw new InvalidArgumentException('Invalid scheme');
}
$host = parse_url($origin, PHP_URL_HOST);
if (!$host) {
throw new InvalidArgumentException("Invalid host");
}
return $origin;
} | [
"public",
"function",
"validateOriginUri",
"(",
"$",
"origin",
")",
"{",
"$",
"origin",
"=",
"(",
"string",
")",
"$",
"origin",
";",
"if",
"(",
"!",
"$",
"origin",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Invalid URI'",
")",
";",
"}",
"$",
"scheme",
"=",
"parse_url",
"(",
"$",
"origin",
",",
"PHP_URL_SCHEME",
")",
";",
"if",
"(",
"!",
"$",
"scheme",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Invalid scheme'",
")",
";",
"}",
"$",
"host",
"=",
"parse_url",
"(",
"$",
"origin",
",",
"PHP_URL_HOST",
")",
";",
"if",
"(",
"!",
"$",
"host",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Invalid host\"",
")",
";",
"}",
"return",
"$",
"origin",
";",
"}"
] | Validates an origin URI
@param string $origin
@throws InvalidArgumentException
@return string | [
"Validates",
"an",
"origin",
"URI"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Protocol/Protocol.php#L805-L823 |
varspool/Wrench | lib/Client.php | Client.configureSocket | protected function configureSocket()
{
$class = $this->options['socket_class'];
$options = $this->options['socket_options'];
$this->socket = new $class($this->uri, $options);
} | php | protected function configureSocket()
{
$class = $this->options['socket_class'];
$options = $this->options['socket_options'];
$this->socket = new $class($this->uri, $options);
} | [
"protected",
"function",
"configureSocket",
"(",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"options",
"[",
"'socket_class'",
"]",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"options",
"[",
"'socket_options'",
"]",
";",
"$",
"this",
"->",
"socket",
"=",
"new",
"$",
"class",
"(",
"$",
"this",
"->",
"uri",
",",
"$",
"options",
")",
";",
"}"
] | Configures the client socket | [
"Configures",
"the",
"client",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L102-L107 |
varspool/Wrench | lib/Client.php | Client.onData | public function onData(Payload $payload)
{
$this->received[] = $payload;
if (($callback = $this->options['on_data_callback'])) {
call_user_func($callback, $payload);
}
} | php | public function onData(Payload $payload)
{
$this->received[] = $payload;
if (($callback = $this->options['on_data_callback'])) {
call_user_func($callback, $payload);
}
} | [
"public",
"function",
"onData",
"(",
"Payload",
"$",
"payload",
")",
"{",
"$",
"this",
"->",
"received",
"[",
"]",
"=",
"$",
"payload",
";",
"if",
"(",
"(",
"$",
"callback",
"=",
"$",
"this",
"->",
"options",
"[",
"'on_data_callback'",
"]",
")",
")",
"{",
"call_user_func",
"(",
"$",
"callback",
",",
"$",
"payload",
")",
";",
"}",
"}"
] | Payload receiver
Public because called from our PayloadHandler. Don't call us, we'll call
you (via the on_data_callback option).
@param Payload $payload | [
"Payload",
"receiver",
"Public",
"because",
"called",
"from",
"our",
"PayloadHandler",
".",
"Don",
"t",
"call",
"us",
"we",
"ll",
"call",
"you",
"(",
"via",
"the",
"on_data_callback",
"option",
")",
"."
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L124-L130 |
varspool/Wrench | lib/Client.php | Client.sendData | public function sendData(string $data, int $type = Protocol::TYPE_TEXT, $masked = true)
{
if (!$this->isConnected()) {
return false;
}
$payload = $this->protocol->getPayload();
$payload->encode(
$data,
$type,
$masked
);
return $payload->sendToSocket($this->socket);
} | php | public function sendData(string $data, int $type = Protocol::TYPE_TEXT, $masked = true)
{
if (!$this->isConnected()) {
return false;
}
$payload = $this->protocol->getPayload();
$payload->encode(
$data,
$type,
$masked
);
return $payload->sendToSocket($this->socket);
} | [
"public",
"function",
"sendData",
"(",
"string",
"$",
"data",
",",
"int",
"$",
"type",
"=",
"Protocol",
"::",
"TYPE_TEXT",
",",
"$",
"masked",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"payload",
"=",
"$",
"this",
"->",
"protocol",
"->",
"getPayload",
"(",
")",
";",
"$",
"payload",
"->",
"encode",
"(",
"$",
"data",
",",
"$",
"type",
",",
"$",
"masked",
")",
";",
"return",
"$",
"payload",
"->",
"sendToSocket",
"(",
"$",
"this",
"->",
"socket",
")",
";",
"}"
] | Sends data to the socket
@param string $data
@param int $type See Protocol::TYPE_*
@param boolean $masked
@return bool Success | [
"Sends",
"data",
"to",
"the",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L153-L168 |
varspool/Wrench | lib/Client.php | Client.isConnected | public function isConnected()
{
if ($this->connected === false) {
return false;
}
// Check if the socket is still connected
if ($this->socket->isConnected() === false) {
$this->connected = false;
return false;
}
return true;
} | php | public function isConnected()
{
if ($this->connected === false) {
return false;
}
// Check if the socket is still connected
if ($this->socket->isConnected() === false) {
$this->connected = false;
return false;
}
return true;
} | [
"public",
"function",
"isConnected",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"connected",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"// Check if the socket is still connected",
"if",
"(",
"$",
"this",
"->",
"socket",
"->",
"isConnected",
"(",
")",
"===",
"false",
")",
"{",
"$",
"this",
"->",
"connected",
"=",
"false",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Returns whether the client is currently connected
Also checks the state of the underlying socket
@return bool | [
"Returns",
"whether",
"the",
"client",
"is",
"currently",
"connected",
"Also",
"checks",
"the",
"state",
"of",
"the",
"underlying",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L176-L190 |
varspool/Wrench | lib/Client.php | Client.receive | public function receive(): ?array
{
if (!$this->isConnected()) {
return null;
}
$data = $this->socket->receive();
if (!$data) {
return [];
}
$this->payloadHandler->handle($data);
$received = $this->received;
$this->received = [];
return $received;
} | php | public function receive(): ?array
{
if (!$this->isConnected()) {
return null;
}
$data = $this->socket->receive();
if (!$data) {
return [];
}
$this->payloadHandler->handle($data);
$received = $this->received;
$this->received = [];
return $received;
} | [
"public",
"function",
"receive",
"(",
")",
":",
"?",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"data",
"=",
"$",
"this",
"->",
"socket",
"->",
"receive",
"(",
")",
";",
"if",
"(",
"!",
"$",
"data",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"this",
"->",
"payloadHandler",
"->",
"handle",
"(",
"$",
"data",
")",
";",
"$",
"received",
"=",
"$",
"this",
"->",
"received",
";",
"$",
"this",
"->",
"received",
"=",
"[",
"]",
";",
"return",
"$",
"received",
";",
"}"
] | Receives data sent by the server
@return array<Payload> Payload received since the last call to receive() | [
"Receives",
"data",
"sent",
"by",
"the",
"server"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L197-L213 |
varspool/Wrench | lib/Client.php | Client.connect | public function connect(): bool
{
if ($this->isConnected()) {
return false;
}
try {
$this->socket->connect();
} catch (\Exception $ex) {
return false;
}
$key = $this->protocol->generateKey();
$handshake = $this->protocol->getRequestHandshake(
$this->uri,
$key,
$this->origin,
$this->headers
);
$this->socket->send($handshake);
$response = $this->socket->receive(self::MAX_HANDSHAKE_RESPONSE);
return ($this->connected =
$this->protocol->validateResponseHandshake($response, $key));
} | php | public function connect(): bool
{
if ($this->isConnected()) {
return false;
}
try {
$this->socket->connect();
} catch (\Exception $ex) {
return false;
}
$key = $this->protocol->generateKey();
$handshake = $this->protocol->getRequestHandshake(
$this->uri,
$key,
$this->origin,
$this->headers
);
$this->socket->send($handshake);
$response = $this->socket->receive(self::MAX_HANDSHAKE_RESPONSE);
return ($this->connected =
$this->protocol->validateResponseHandshake($response, $key));
} | [
"public",
"function",
"connect",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"socket",
"->",
"connect",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"ex",
")",
"{",
"return",
"false",
";",
"}",
"$",
"key",
"=",
"$",
"this",
"->",
"protocol",
"->",
"generateKey",
"(",
")",
";",
"$",
"handshake",
"=",
"$",
"this",
"->",
"protocol",
"->",
"getRequestHandshake",
"(",
"$",
"this",
"->",
"uri",
",",
"$",
"key",
",",
"$",
"this",
"->",
"origin",
",",
"$",
"this",
"->",
"headers",
")",
";",
"$",
"this",
"->",
"socket",
"->",
"send",
"(",
"$",
"handshake",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"socket",
"->",
"receive",
"(",
"self",
"::",
"MAX_HANDSHAKE_RESPONSE",
")",
";",
"return",
"(",
"$",
"this",
"->",
"connected",
"=",
"$",
"this",
"->",
"protocol",
"->",
"validateResponseHandshake",
"(",
"$",
"response",
",",
"$",
"key",
")",
")",
";",
"}"
] | Connect to the server
@return bool Whether a new connection was made
@throws Exception\HandshakeException
@throws Exception\SocketException | [
"Connect",
"to",
"the",
"server"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L222-L246 |
varspool/Wrench | lib/Client.php | Client.disconnect | public function disconnect($reason = Protocol::CLOSE_NORMAL): bool
{
if ($this->connected === false) {
return false;
}
$payload = $this->protocol->getClosePayload($reason);
if ($this->socket) {
if (!$payload->sendToSocket($this->socket)) {
throw new FrameException("Unexpected exception when sending Close frame.");
}
// The client SHOULD wait for the server to close the connection
$this->socket->receive();
$this->socket->disconnect();
}
$this->connected = false;
return true;
} | php | public function disconnect($reason = Protocol::CLOSE_NORMAL): bool
{
if ($this->connected === false) {
return false;
}
$payload = $this->protocol->getClosePayload($reason);
if ($this->socket) {
if (!$payload->sendToSocket($this->socket)) {
throw new FrameException("Unexpected exception when sending Close frame.");
}
// The client SHOULD wait for the server to close the connection
$this->socket->receive();
$this->socket->disconnect();
}
$this->connected = false;
return true;
} | [
"public",
"function",
"disconnect",
"(",
"$",
"reason",
"=",
"Protocol",
"::",
"CLOSE_NORMAL",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"connected",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"$",
"payload",
"=",
"$",
"this",
"->",
"protocol",
"->",
"getClosePayload",
"(",
"$",
"reason",
")",
";",
"if",
"(",
"$",
"this",
"->",
"socket",
")",
"{",
"if",
"(",
"!",
"$",
"payload",
"->",
"sendToSocket",
"(",
"$",
"this",
"->",
"socket",
")",
")",
"{",
"throw",
"new",
"FrameException",
"(",
"\"Unexpected exception when sending Close frame.\"",
")",
";",
"}",
"// The client SHOULD wait for the server to close the connection",
"$",
"this",
"->",
"socket",
"->",
"receive",
"(",
")",
";",
"$",
"this",
"->",
"socket",
"->",
"disconnect",
"(",
")",
";",
"}",
"$",
"this",
"->",
"connected",
"=",
"false",
";",
"return",
"true",
";",
"}"
] | Disconnects the underlying socket, and marks the client as disconnected
@param int $reason Reason for disconnecting. See Protocol::CLOSE_
@return bool
@throws Exception\SocketException
@throws FrameException | [
"Disconnects",
"the",
"underlying",
"socket",
"and",
"marks",
"the",
"client",
"as",
"disconnected"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L256-L276 |
varspool/Wrench | lib/Client.php | Client.configure | protected function configure(array $options): void
{
$options = array_merge([
'socket_class' => ClientSocket::class,
'on_data_callback' => null,
'socket_options' => [],
], $options);
parent::configure($options);
} | php | protected function configure(array $options): void
{
$options = array_merge([
'socket_class' => ClientSocket::class,
'on_data_callback' => null,
'socket_options' => [],
], $options);
parent::configure($options);
} | [
"protected",
"function",
"configure",
"(",
"array",
"$",
"options",
")",
":",
"void",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"[",
"'socket_class'",
"=>",
"ClientSocket",
"::",
"class",
",",
"'on_data_callback'",
"=>",
"null",
",",
"'socket_options'",
"=>",
"[",
"]",
",",
"]",
",",
"$",
"options",
")",
";",
"parent",
"::",
"configure",
"(",
"$",
"options",
")",
";",
"}"
] | Configure options
@param array $options
@return void | [
"Configure",
"options"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Client.php#L284-L293 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.encode | public function encode($payload, $type = Protocol::TYPE_TEXT, $masked = false)
{
if (!is_int($type) || !in_array($type, Protocol::FRAME_TYPES)) {
throw new InvalidArgumentException('Invalid frame type');
}
$this->type = $type;
$this->masked = $masked;
$this->payload = $payload;
$this->length = strlen($this->payload);
$this->offset_mask = null;
$this->offset_payload = null;
$this->buffer = "\x00\x00";
$this->buffer[self::BYTE_HEADER] = chr(
(self::BITFIELD_TYPE & $this->type)
| (self::BITFIELD_FINAL & PHP_INT_MAX)
);
$masked_bit = (self::BITFIELD_MASKED & ($this->masked ? PHP_INT_MAX : 0));
if ($this->length <= 125) {
$this->buffer[self::BYTE_INITIAL_LENGTH] = chr(
(self::BITFIELD_INITIAL_LENGTH & $this->length) | $masked_bit
);
} elseif ($this->length <= 65536) {
$this->buffer[self::BYTE_INITIAL_LENGTH] = chr(
(self::BITFIELD_INITIAL_LENGTH & 126) | $masked_bit
);
$this->buffer .= pack('n', $this->length);
} else {
$this->buffer[self::BYTE_INITIAL_LENGTH] = chr(
(self::BITFIELD_INITIAL_LENGTH & 127) | $masked_bit
);
if (PHP_INT_MAX > 2147483647) {
$this->buffer .= pack('NN', $this->length >> 32, $this->length);
// $this->buffer .= pack('I', $this->length);
} else {
$this->buffer .= pack('NN', 0, $this->length);
}
}
if ($this->masked) {
$this->mask = $this->generateMask();
$this->buffer .= $this->mask;
$this->buffer .= $this->mask($this->payload);
} else {
$this->buffer .= $this->payload;
}
$this->offset_mask = $this->getMaskOffset();
$this->offset_payload = $this->getPayloadOffset();
return $this;
} | php | public function encode($payload, $type = Protocol::TYPE_TEXT, $masked = false)
{
if (!is_int($type) || !in_array($type, Protocol::FRAME_TYPES)) {
throw new InvalidArgumentException('Invalid frame type');
}
$this->type = $type;
$this->masked = $masked;
$this->payload = $payload;
$this->length = strlen($this->payload);
$this->offset_mask = null;
$this->offset_payload = null;
$this->buffer = "\x00\x00";
$this->buffer[self::BYTE_HEADER] = chr(
(self::BITFIELD_TYPE & $this->type)
| (self::BITFIELD_FINAL & PHP_INT_MAX)
);
$masked_bit = (self::BITFIELD_MASKED & ($this->masked ? PHP_INT_MAX : 0));
if ($this->length <= 125) {
$this->buffer[self::BYTE_INITIAL_LENGTH] = chr(
(self::BITFIELD_INITIAL_LENGTH & $this->length) | $masked_bit
);
} elseif ($this->length <= 65536) {
$this->buffer[self::BYTE_INITIAL_LENGTH] = chr(
(self::BITFIELD_INITIAL_LENGTH & 126) | $masked_bit
);
$this->buffer .= pack('n', $this->length);
} else {
$this->buffer[self::BYTE_INITIAL_LENGTH] = chr(
(self::BITFIELD_INITIAL_LENGTH & 127) | $masked_bit
);
if (PHP_INT_MAX > 2147483647) {
$this->buffer .= pack('NN', $this->length >> 32, $this->length);
// $this->buffer .= pack('I', $this->length);
} else {
$this->buffer .= pack('NN', 0, $this->length);
}
}
if ($this->masked) {
$this->mask = $this->generateMask();
$this->buffer .= $this->mask;
$this->buffer .= $this->mask($this->payload);
} else {
$this->buffer .= $this->payload;
}
$this->offset_mask = $this->getMaskOffset();
$this->offset_payload = $this->getPayloadOffset();
return $this;
} | [
"public",
"function",
"encode",
"(",
"$",
"payload",
",",
"$",
"type",
"=",
"Protocol",
"::",
"TYPE_TEXT",
",",
"$",
"masked",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"is_int",
"(",
"$",
"type",
")",
"||",
"!",
"in_array",
"(",
"$",
"type",
",",
"Protocol",
"::",
"FRAME_TYPES",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Invalid frame type'",
")",
";",
"}",
"$",
"this",
"->",
"type",
"=",
"$",
"type",
";",
"$",
"this",
"->",
"masked",
"=",
"$",
"masked",
";",
"$",
"this",
"->",
"payload",
"=",
"$",
"payload",
";",
"$",
"this",
"->",
"length",
"=",
"strlen",
"(",
"$",
"this",
"->",
"payload",
")",
";",
"$",
"this",
"->",
"offset_mask",
"=",
"null",
";",
"$",
"this",
"->",
"offset_payload",
"=",
"null",
";",
"$",
"this",
"->",
"buffer",
"=",
"\"\\x00\\x00\"",
";",
"$",
"this",
"->",
"buffer",
"[",
"self",
"::",
"BYTE_HEADER",
"]",
"=",
"chr",
"(",
"(",
"self",
"::",
"BITFIELD_TYPE",
"&",
"$",
"this",
"->",
"type",
")",
"|",
"(",
"self",
"::",
"BITFIELD_FINAL",
"&",
"PHP_INT_MAX",
")",
")",
";",
"$",
"masked_bit",
"=",
"(",
"self",
"::",
"BITFIELD_MASKED",
"&",
"(",
"$",
"this",
"->",
"masked",
"?",
"PHP_INT_MAX",
":",
"0",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"length",
"<=",
"125",
")",
"{",
"$",
"this",
"->",
"buffer",
"[",
"self",
"::",
"BYTE_INITIAL_LENGTH",
"]",
"=",
"chr",
"(",
"(",
"self",
"::",
"BITFIELD_INITIAL_LENGTH",
"&",
"$",
"this",
"->",
"length",
")",
"|",
"$",
"masked_bit",
")",
";",
"}",
"elseif",
"(",
"$",
"this",
"->",
"length",
"<=",
"65536",
")",
"{",
"$",
"this",
"->",
"buffer",
"[",
"self",
"::",
"BYTE_INITIAL_LENGTH",
"]",
"=",
"chr",
"(",
"(",
"self",
"::",
"BITFIELD_INITIAL_LENGTH",
"&",
"126",
")",
"|",
"$",
"masked_bit",
")",
";",
"$",
"this",
"->",
"buffer",
".=",
"pack",
"(",
"'n'",
",",
"$",
"this",
"->",
"length",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"buffer",
"[",
"self",
"::",
"BYTE_INITIAL_LENGTH",
"]",
"=",
"chr",
"(",
"(",
"self",
"::",
"BITFIELD_INITIAL_LENGTH",
"&",
"127",
")",
"|",
"$",
"masked_bit",
")",
";",
"if",
"(",
"PHP_INT_MAX",
">",
"2147483647",
")",
"{",
"$",
"this",
"->",
"buffer",
".=",
"pack",
"(",
"'NN'",
",",
"$",
"this",
"->",
"length",
">>",
"32",
",",
"$",
"this",
"->",
"length",
")",
";",
"// $this->buffer .= pack('I', $this->length);",
"}",
"else",
"{",
"$",
"this",
"->",
"buffer",
".=",
"pack",
"(",
"'NN'",
",",
"0",
",",
"$",
"this",
"->",
"length",
")",
";",
"}",
"}",
"if",
"(",
"$",
"this",
"->",
"masked",
")",
"{",
"$",
"this",
"->",
"mask",
"=",
"$",
"this",
"->",
"generateMask",
"(",
")",
";",
"$",
"this",
"->",
"buffer",
".=",
"$",
"this",
"->",
"mask",
";",
"$",
"this",
"->",
"buffer",
".=",
"$",
"this",
"->",
"mask",
"(",
"$",
"this",
"->",
"payload",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"buffer",
".=",
"$",
"this",
"->",
"payload",
";",
"}",
"$",
"this",
"->",
"offset_mask",
"=",
"$",
"this",
"->",
"getMaskOffset",
"(",
")",
";",
"$",
"this",
"->",
"offset_payload",
"=",
"$",
"this",
"->",
"getPayloadOffset",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Encode a frame
ws-frame = frame-fin ; 1 bit in length
frame-rsv1 ; 1 bit in length
frame-rsv2 ; 1 bit in length
frame-rsv3 ; 1 bit in length
frame-opcode ; 4 bits in length
frame-masked ; 1 bit in length
frame-payload-length ; either 7, 7+16,
; or 7+64 bits in
; length
[ frame-masking-key ] ; 32 bits in length
frame-payload-data ; n*8 bits in
; length, where
; n >= 0 | [
"Encode",
"a",
"frame"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L66-L122 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.generateMask | protected function generateMask()
{
if (extension_loaded('openssl')) {
return openssl_random_pseudo_bytes(4);
} else {
// SHA1 is 128 bit (= 16 bytes)
// So we pack it into 32 bits
return pack('N', sha1(spl_object_hash($this) . mt_rand(0, PHP_INT_MAX) . uniqid('', true), true));
}
} | php | protected function generateMask()
{
if (extension_loaded('openssl')) {
return openssl_random_pseudo_bytes(4);
} else {
// SHA1 is 128 bit (= 16 bytes)
// So we pack it into 32 bits
return pack('N', sha1(spl_object_hash($this) . mt_rand(0, PHP_INT_MAX) . uniqid('', true), true));
}
} | [
"protected",
"function",
"generateMask",
"(",
")",
"{",
"if",
"(",
"extension_loaded",
"(",
"'openssl'",
")",
")",
"{",
"return",
"openssl_random_pseudo_bytes",
"(",
"4",
")",
";",
"}",
"else",
"{",
"// SHA1 is 128 bit (= 16 bytes)",
"// So we pack it into 32 bits",
"return",
"pack",
"(",
"'N'",
",",
"sha1",
"(",
"spl_object_hash",
"(",
"$",
"this",
")",
".",
"mt_rand",
"(",
"0",
",",
"PHP_INT_MAX",
")",
".",
"uniqid",
"(",
"''",
",",
"true",
")",
",",
"true",
")",
")",
";",
"}",
"}"
] | Generates a suitable masking key
@return string | [
"Generates",
"a",
"suitable",
"masking",
"key"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L129-L138 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.mask | protected function mask($payload)
{
$length = strlen($payload);
$mask = $this->getMask();
$unmasked = '';
for ($i = 0; $i < $length; $i++) {
$unmasked .= $payload[$i] ^ $mask[$i % 4];
}
return $unmasked;
} | php | protected function mask($payload)
{
$length = strlen($payload);
$mask = $this->getMask();
$unmasked = '';
for ($i = 0; $i < $length; $i++) {
$unmasked .= $payload[$i] ^ $mask[$i % 4];
}
return $unmasked;
} | [
"protected",
"function",
"mask",
"(",
"$",
"payload",
")",
"{",
"$",
"length",
"=",
"strlen",
"(",
"$",
"payload",
")",
";",
"$",
"mask",
"=",
"$",
"this",
"->",
"getMask",
"(",
")",
";",
"$",
"unmasked",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"length",
";",
"$",
"i",
"++",
")",
"{",
"$",
"unmasked",
".=",
"$",
"payload",
"[",
"$",
"i",
"]",
"^",
"$",
"mask",
"[",
"$",
"i",
"%",
"4",
"]",
";",
"}",
"return",
"$",
"unmasked",
";",
"}"
] | Masks/Unmasks the frame
@param string $payload
@return string | [
"Masks",
"/",
"Unmasks",
"the",
"frame"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L146-L157 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.getMask | protected function getMask()
{
if (!isset($this->mask)) {
if (!$this->isMasked()) {
throw new FrameException('Cannot get mask: frame is not masked');
}
$this->mask = substr($this->buffer, $this->getMaskOffset(), $this->getMaskSize());
}
return $this->mask;
} | php | protected function getMask()
{
if (!isset($this->mask)) {
if (!$this->isMasked()) {
throw new FrameException('Cannot get mask: frame is not masked');
}
$this->mask = substr($this->buffer, $this->getMaskOffset(), $this->getMaskSize());
}
return $this->mask;
} | [
"protected",
"function",
"getMask",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"mask",
")",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isMasked",
"(",
")",
")",
"{",
"throw",
"new",
"FrameException",
"(",
"'Cannot get mask: frame is not masked'",
")",
";",
"}",
"$",
"this",
"->",
"mask",
"=",
"substr",
"(",
"$",
"this",
"->",
"buffer",
",",
"$",
"this",
"->",
"getMaskOffset",
"(",
")",
",",
"$",
"this",
"->",
"getMaskSize",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
"->",
"mask",
";",
"}"
] | Gets the mask
@throws FrameException
@return string | [
"Gets",
"the",
"mask"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L165-L174 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.isMasked | public function isMasked()
{
if (!isset($this->masked)) {
if (!isset($this->buffer[1])) {
throw new FrameException('Cannot tell if frame is masked: not enough frame data received');
}
$this->masked = (boolean)(ord($this->buffer[1]) & self::BITFIELD_MASKED);
}
return $this->masked;
} | php | public function isMasked()
{
if (!isset($this->masked)) {
if (!isset($this->buffer[1])) {
throw new FrameException('Cannot tell if frame is masked: not enough frame data received');
}
$this->masked = (boolean)(ord($this->buffer[1]) & self::BITFIELD_MASKED);
}
return $this->masked;
} | [
"public",
"function",
"isMasked",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"masked",
")",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"buffer",
"[",
"1",
"]",
")",
")",
"{",
"throw",
"new",
"FrameException",
"(",
"'Cannot tell if frame is masked: not enough frame data received'",
")",
";",
"}",
"$",
"this",
"->",
"masked",
"=",
"(",
"boolean",
")",
"(",
"ord",
"(",
"$",
"this",
"->",
"buffer",
"[",
"1",
"]",
")",
"&",
"self",
"::",
"BITFIELD_MASKED",
")",
";",
"}",
"return",
"$",
"this",
"->",
"masked",
";",
"}"
] | Whether the frame is masked
@return bool | [
"Whether",
"the",
"frame",
"is",
"masked"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L181-L190 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.getMaskOffset | protected function getMaskOffset()
{
if (!isset($this->offset_mask)) {
$offset = self::BYTE_INITIAL_LENGTH + 1;
$offset += $this->getLengthSize();
$this->offset_mask = $offset;
}
return $this->offset_mask;
} | php | protected function getMaskOffset()
{
if (!isset($this->offset_mask)) {
$offset = self::BYTE_INITIAL_LENGTH + 1;
$offset += $this->getLengthSize();
$this->offset_mask = $offset;
}
return $this->offset_mask;
} | [
"protected",
"function",
"getMaskOffset",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"offset_mask",
")",
")",
"{",
"$",
"offset",
"=",
"self",
"::",
"BYTE_INITIAL_LENGTH",
"+",
"1",
";",
"$",
"offset",
"+=",
"$",
"this",
"->",
"getLengthSize",
"(",
")",
";",
"$",
"this",
"->",
"offset_mask",
"=",
"$",
"offset",
";",
"}",
"return",
"$",
"this",
"->",
"offset_mask",
";",
"}"
] | Gets the offset in the frame to the masking bytes
@return int | [
"Gets",
"the",
"offset",
"in",
"the",
"frame",
"to",
"the",
"masking",
"bytes"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L197-L206 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.getInitialLength | protected function getInitialLength()
{
if (!isset($this->buffer[self::BYTE_INITIAL_LENGTH])) {
throw new FrameException('Cannot yet tell expected length');
}
$a = (int)(ord($this->buffer[self::BYTE_INITIAL_LENGTH]) & self::BITFIELD_INITIAL_LENGTH);
return (int)(ord($this->buffer[self::BYTE_INITIAL_LENGTH]) & self::BITFIELD_INITIAL_LENGTH);
} | php | protected function getInitialLength()
{
if (!isset($this->buffer[self::BYTE_INITIAL_LENGTH])) {
throw new FrameException('Cannot yet tell expected length');
}
$a = (int)(ord($this->buffer[self::BYTE_INITIAL_LENGTH]) & self::BITFIELD_INITIAL_LENGTH);
return (int)(ord($this->buffer[self::BYTE_INITIAL_LENGTH]) & self::BITFIELD_INITIAL_LENGTH);
} | [
"protected",
"function",
"getInitialLength",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"buffer",
"[",
"self",
"::",
"BYTE_INITIAL_LENGTH",
"]",
")",
")",
"{",
"throw",
"new",
"FrameException",
"(",
"'Cannot yet tell expected length'",
")",
";",
"}",
"$",
"a",
"=",
"(",
"int",
")",
"(",
"ord",
"(",
"$",
"this",
"->",
"buffer",
"[",
"self",
"::",
"BYTE_INITIAL_LENGTH",
"]",
")",
"&",
"self",
"::",
"BITFIELD_INITIAL_LENGTH",
")",
";",
"return",
"(",
"int",
")",
"(",
"ord",
"(",
"$",
"this",
"->",
"buffer",
"[",
"self",
"::",
"BYTE_INITIAL_LENGTH",
"]",
")",
"&",
"self",
"::",
"BITFIELD_INITIAL_LENGTH",
")",
";",
"}"
] | Gets the inital length value, stored in the first length byte
This determines how the rest of the length value is parsed out of the
frame.
@return int | [
"Gets",
"the",
"inital",
"length",
"value",
"stored",
"in",
"the",
"first",
"length",
"byte",
"This",
"determines",
"how",
"the",
"rest",
"of",
"the",
"length",
"value",
"is",
"parsed",
"out",
"of",
"the",
"frame",
"."
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L234-L242 |
varspool/Wrench | lib/Frame/HybiFrame.php | HybiFrame.getPayloadOffset | protected function getPayloadOffset()
{
if (!isset($this->offset_payload)) {
$offset = $this->getMaskOffset();
$offset += $this->getMaskSize();
$this->offset_payload = $offset;
}
return $this->offset_payload;
} | php | protected function getPayloadOffset()
{
if (!isset($this->offset_payload)) {
$offset = $this->getMaskOffset();
$offset += $this->getMaskSize();
$this->offset_payload = $offset;
}
return $this->offset_payload;
} | [
"protected",
"function",
"getPayloadOffset",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"offset_payload",
")",
")",
"{",
"$",
"offset",
"=",
"$",
"this",
"->",
"getMaskOffset",
"(",
")",
";",
"$",
"offset",
"+=",
"$",
"this",
"->",
"getMaskSize",
"(",
")",
";",
"$",
"this",
"->",
"offset_payload",
"=",
"$",
"offset",
";",
"}",
"return",
"$",
"this",
"->",
"offset_payload",
";",
"}"
] | Gets the offset of the payload in the frame
@return int | [
"Gets",
"the",
"offset",
"of",
"the",
"payload",
"in",
"the",
"frame"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/HybiFrame.php#L262-L271 |
varspool/Wrench | lib/Util/Ssl.php | Ssl.generatePemFile | public static function generatePemFile(
$pem_file,
$pem_passphrase,
$country_name,
$state_or_province_name,
$locality_name,
$organization_name,
$organizational_unit_name,
$common_name,
$email_address
): void {
// Generate PEM file
$dn = [
'countryName' => $country_name,
'stateOrProvinceName' => $state_or_province_name,
'localityName' => $locality_name,
'organizationName' => $organization_name,
'organizationalUnitName' => $organizational_unit_name,
'commonName' => $common_name,
'emailAddress' => $email_address,
];
$privkey = openssl_pkey_new();
$cert = openssl_csr_new($dn, $privkey);
$cert = openssl_csr_sign($cert, null, $privkey, 365);
$pem = [];
openssl_x509_export($cert, $pem[0]);
openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
$pem = implode($pem);
file_put_contents($pem_file, $pem);
} | php | public static function generatePemFile(
$pem_file,
$pem_passphrase,
$country_name,
$state_or_province_name,
$locality_name,
$organization_name,
$organizational_unit_name,
$common_name,
$email_address
): void {
// Generate PEM file
$dn = [
'countryName' => $country_name,
'stateOrProvinceName' => $state_or_province_name,
'localityName' => $locality_name,
'organizationName' => $organization_name,
'organizationalUnitName' => $organizational_unit_name,
'commonName' => $common_name,
'emailAddress' => $email_address,
];
$privkey = openssl_pkey_new();
$cert = openssl_csr_new($dn, $privkey);
$cert = openssl_csr_sign($cert, null, $privkey, 365);
$pem = [];
openssl_x509_export($cert, $pem[0]);
openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
$pem = implode($pem);
file_put_contents($pem_file, $pem);
} | [
"public",
"static",
"function",
"generatePemFile",
"(",
"$",
"pem_file",
",",
"$",
"pem_passphrase",
",",
"$",
"country_name",
",",
"$",
"state_or_province_name",
",",
"$",
"locality_name",
",",
"$",
"organization_name",
",",
"$",
"organizational_unit_name",
",",
"$",
"common_name",
",",
"$",
"email_address",
")",
":",
"void",
"{",
"// Generate PEM file",
"$",
"dn",
"=",
"[",
"'countryName'",
"=>",
"$",
"country_name",
",",
"'stateOrProvinceName'",
"=>",
"$",
"state_or_province_name",
",",
"'localityName'",
"=>",
"$",
"locality_name",
",",
"'organizationName'",
"=>",
"$",
"organization_name",
",",
"'organizationalUnitName'",
"=>",
"$",
"organizational_unit_name",
",",
"'commonName'",
"=>",
"$",
"common_name",
",",
"'emailAddress'",
"=>",
"$",
"email_address",
",",
"]",
";",
"$",
"privkey",
"=",
"openssl_pkey_new",
"(",
")",
";",
"$",
"cert",
"=",
"openssl_csr_new",
"(",
"$",
"dn",
",",
"$",
"privkey",
")",
";",
"$",
"cert",
"=",
"openssl_csr_sign",
"(",
"$",
"cert",
",",
"null",
",",
"$",
"privkey",
",",
"365",
")",
";",
"$",
"pem",
"=",
"[",
"]",
";",
"openssl_x509_export",
"(",
"$",
"cert",
",",
"$",
"pem",
"[",
"0",
"]",
")",
";",
"openssl_pkey_export",
"(",
"$",
"privkey",
",",
"$",
"pem",
"[",
"1",
"]",
",",
"$",
"pem_passphrase",
")",
";",
"$",
"pem",
"=",
"implode",
"(",
"$",
"pem",
")",
";",
"file_put_contents",
"(",
"$",
"pem_file",
",",
"$",
"pem",
")",
";",
"}"
] | Generates a new PEM File given the information
@param string $pem_file the path of the PEM file to create
@param string $pem_passphrase the passphrase to protect the PEM file or if you don't want to use a
passphrase
@param string $country_name the country code of the new PEM file. e.g.: EN
@param string $state_or_province_name the state or province name of the new PEM file
@param string $locality_name the name of the locality
@param string $organization_name the name of the organisation. e.g.: MyCompany
@param string $organizational_unit_name the organisation unit name
@param string $common_name the common name
@param string $email_address the email address | [
"Generates",
"a",
"new",
"PEM",
"File",
"given",
"the",
"information"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Util/Ssl.php#L21-L54 |
varspool/Wrench | lib/Payload/PayloadHandler.php | PayloadHandler.handle | public function handle(string $data)
{
if (!$this->payload) {
$this->payload = $this->protocol->getPayload();
}
while ($data) { // Each iteration pulls off a single payload chunk
$size = strlen($data);
$remaining = $this->payload->getRemainingData();
// If we don't yet know how much data is remaining, read data into
// the payload in two byte chunks (the size of a WebSocket frame
// header to get the initial length)
//
// Then re-loop. For extended lengths, this will happen once or four
// times extra, as the extended length is read in.
if ($remaining === null) {
$chunkSize = 2;
} elseif ($remaining > 0) {
$chunkSize = $remaining;
} elseif ($remaining === 0) {
$chunkSize = 0;
}
$chunkSize = min(strlen($data), $chunkSize);
$chunk = substr($data, 0, $chunkSize);
$data = substr($data, $chunkSize);
$this->payload->receiveData($chunk);
if ($remaining !== 0 && !$this->payload->isComplete()) {
continue;
}
if ($this->payload->isComplete()) {
$this->emit($this->payload);
$this->payload = $this->protocol->getPayload();
} else {
throw new PayloadException('Payload will not complete');
}
}
} | php | public function handle(string $data)
{
if (!$this->payload) {
$this->payload = $this->protocol->getPayload();
}
while ($data) { // Each iteration pulls off a single payload chunk
$size = strlen($data);
$remaining = $this->payload->getRemainingData();
// If we don't yet know how much data is remaining, read data into
// the payload in two byte chunks (the size of a WebSocket frame
// header to get the initial length)
//
// Then re-loop. For extended lengths, this will happen once or four
// times extra, as the extended length is read in.
if ($remaining === null) {
$chunkSize = 2;
} elseif ($remaining > 0) {
$chunkSize = $remaining;
} elseif ($remaining === 0) {
$chunkSize = 0;
}
$chunkSize = min(strlen($data), $chunkSize);
$chunk = substr($data, 0, $chunkSize);
$data = substr($data, $chunkSize);
$this->payload->receiveData($chunk);
if ($remaining !== 0 && !$this->payload->isComplete()) {
continue;
}
if ($this->payload->isComplete()) {
$this->emit($this->payload);
$this->payload = $this->protocol->getPayload();
} else {
throw new PayloadException('Payload will not complete');
}
}
} | [
"public",
"function",
"handle",
"(",
"string",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"payload",
")",
"{",
"$",
"this",
"->",
"payload",
"=",
"$",
"this",
"->",
"protocol",
"->",
"getPayload",
"(",
")",
";",
"}",
"while",
"(",
"$",
"data",
")",
"{",
"// Each iteration pulls off a single payload chunk",
"$",
"size",
"=",
"strlen",
"(",
"$",
"data",
")",
";",
"$",
"remaining",
"=",
"$",
"this",
"->",
"payload",
"->",
"getRemainingData",
"(",
")",
";",
"// If we don't yet know how much data is remaining, read data into",
"// the payload in two byte chunks (the size of a WebSocket frame",
"// header to get the initial length)",
"//",
"// Then re-loop. For extended lengths, this will happen once or four",
"// times extra, as the extended length is read in.",
"if",
"(",
"$",
"remaining",
"===",
"null",
")",
"{",
"$",
"chunkSize",
"=",
"2",
";",
"}",
"elseif",
"(",
"$",
"remaining",
">",
"0",
")",
"{",
"$",
"chunkSize",
"=",
"$",
"remaining",
";",
"}",
"elseif",
"(",
"$",
"remaining",
"===",
"0",
")",
"{",
"$",
"chunkSize",
"=",
"0",
";",
"}",
"$",
"chunkSize",
"=",
"min",
"(",
"strlen",
"(",
"$",
"data",
")",
",",
"$",
"chunkSize",
")",
";",
"$",
"chunk",
"=",
"substr",
"(",
"$",
"data",
",",
"0",
",",
"$",
"chunkSize",
")",
";",
"$",
"data",
"=",
"substr",
"(",
"$",
"data",
",",
"$",
"chunkSize",
")",
";",
"$",
"this",
"->",
"payload",
"->",
"receiveData",
"(",
"$",
"chunk",
")",
";",
"if",
"(",
"$",
"remaining",
"!==",
"0",
"&&",
"!",
"$",
"this",
"->",
"payload",
"->",
"isComplete",
"(",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"payload",
"->",
"isComplete",
"(",
")",
")",
"{",
"$",
"this",
"->",
"emit",
"(",
"$",
"this",
"->",
"payload",
")",
";",
"$",
"this",
"->",
"payload",
"=",
"$",
"this",
"->",
"protocol",
"->",
"getPayload",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"PayloadException",
"(",
"'Payload will not complete'",
")",
";",
"}",
"}",
"}"
] | Handles the raw socket data given
@param string $data
@throws PayloadException | [
"Handles",
"the",
"raw",
"socket",
"data",
"given"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Payload/PayloadHandler.php#L44-L85 |
varspool/Wrench | lib/Frame/Frame.php | Frame.getFramePayload | public function getFramePayload()
{
if (!$this->isComplete()) {
throw new FrameException('Cannot get payload: frame is not complete');
}
if (!$this->payload && $this->buffer) {
$this->decodeFramePayloadFromBuffer();
}
return $this->payload;
} | php | public function getFramePayload()
{
if (!$this->isComplete()) {
throw new FrameException('Cannot get payload: frame is not complete');
}
if (!$this->payload && $this->buffer) {
$this->decodeFramePayloadFromBuffer();
}
return $this->payload;
} | [
"public",
"function",
"getFramePayload",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isComplete",
"(",
")",
")",
"{",
"throw",
"new",
"FrameException",
"(",
"'Cannot get payload: frame is not complete'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"payload",
"&&",
"$",
"this",
"->",
"buffer",
")",
"{",
"$",
"this",
"->",
"decodeFramePayloadFromBuffer",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"payload",
";",
"}"
] | Gets the contents of the frame payload
The frame must be complete to call this method.
@return string
@throws FrameException | [
"Gets",
"the",
"contents",
"of",
"the",
"frame",
"payload",
"The",
"frame",
"must",
"be",
"complete",
"to",
"call",
"this",
"method",
"."
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/Frame.php#L131-L142 |
varspool/Wrench | lib/Frame/Frame.php | Frame.isComplete | public function isComplete()
{
if (!$this->buffer) {
return false;
}
try {
return $this->getBufferLength() >= $this->getExpectedBufferLength();
} catch (FrameException $e) {
return false;
}
} | php | public function isComplete()
{
if (!$this->buffer) {
return false;
}
try {
return $this->getBufferLength() >= $this->getExpectedBufferLength();
} catch (FrameException $e) {
return false;
}
} | [
"public",
"function",
"isComplete",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"buffer",
")",
"{",
"return",
"false",
";",
"}",
"try",
"{",
"return",
"$",
"this",
"->",
"getBufferLength",
"(",
")",
">=",
"$",
"this",
"->",
"getExpectedBufferLength",
"(",
")",
";",
"}",
"catch",
"(",
"FrameException",
"$",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | Whether the frame is complete
@return bool | [
"Whether",
"the",
"frame",
"is",
"complete"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Frame/Frame.php#L149-L160 |
varspool/Wrench | lib/Socket/ClientSocket.php | ClientSocket.connect | public function connect(): bool
{
if ($this->isConnected()) {
return true;
}
$errno = null;
$errstr = null;
// Supress PHP error, we're handling it
$this->socket = @stream_socket_client(
$this->getUri(),
$errno,
$errstr,
$this->options['timeout_connect'],
STREAM_CLIENT_CONNECT,
$this->getStreamContext()
);
if (!$this->socket) {
throw new \Wrench\Exception\ConnectionException(sprintf(
'Could not connect to socket: %s (%d)',
$errstr,
$errno
));
}
stream_set_timeout($this->socket, $this->options['timeout_socket']);
return ($this->connected = true);
} | php | public function connect(): bool
{
if ($this->isConnected()) {
return true;
}
$errno = null;
$errstr = null;
// Supress PHP error, we're handling it
$this->socket = @stream_socket_client(
$this->getUri(),
$errno,
$errstr,
$this->options['timeout_connect'],
STREAM_CLIENT_CONNECT,
$this->getStreamContext()
);
if (!$this->socket) {
throw new \Wrench\Exception\ConnectionException(sprintf(
'Could not connect to socket: %s (%d)',
$errstr,
$errno
));
}
stream_set_timeout($this->socket, $this->options['timeout_socket']);
return ($this->connected = true);
} | [
"public",
"function",
"connect",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnected",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"errno",
"=",
"null",
";",
"$",
"errstr",
"=",
"null",
";",
"// Supress PHP error, we're handling it",
"$",
"this",
"->",
"socket",
"=",
"@",
"stream_socket_client",
"(",
"$",
"this",
"->",
"getUri",
"(",
")",
",",
"$",
"errno",
",",
"$",
"errstr",
",",
"$",
"this",
"->",
"options",
"[",
"'timeout_connect'",
"]",
",",
"STREAM_CLIENT_CONNECT",
",",
"$",
"this",
"->",
"getStreamContext",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"socket",
")",
"{",
"throw",
"new",
"\\",
"Wrench",
"\\",
"Exception",
"\\",
"ConnectionException",
"(",
"sprintf",
"(",
"'Could not connect to socket: %s (%d)'",
",",
"$",
"errstr",
",",
"$",
"errno",
")",
")",
";",
"}",
"stream_set_timeout",
"(",
"$",
"this",
"->",
"socket",
",",
"$",
"this",
"->",
"options",
"[",
"'timeout_socket'",
"]",
")",
";",
"return",
"(",
"$",
"this",
"->",
"connected",
"=",
"true",
")",
";",
"}"
] | Connects to the given socket | [
"Connects",
"to",
"the",
"given",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/ClientSocket.php#L26-L56 |
varspool/Wrench | lib/Socket/ClientSocket.php | ClientSocket.configure | protected function configure(array $options): void
{
$options = array_merge([
'timeout_connect' => self::TIMEOUT_CONNECT,
'ssl_verify_peer' => false,
'ssl_allow_self_signed' => true,
], $options);
parent::configure($options);
} | php | protected function configure(array $options): void
{
$options = array_merge([
'timeout_connect' => self::TIMEOUT_CONNECT,
'ssl_verify_peer' => false,
'ssl_allow_self_signed' => true,
], $options);
parent::configure($options);
} | [
"protected",
"function",
"configure",
"(",
"array",
"$",
"options",
")",
":",
"void",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"[",
"'timeout_connect'",
"=>",
"self",
"::",
"TIMEOUT_CONNECT",
",",
"'ssl_verify_peer'",
"=>",
"false",
",",
"'ssl_allow_self_signed'",
"=>",
"true",
",",
"]",
",",
"$",
"options",
")",
";",
"parent",
"::",
"configure",
"(",
"$",
"options",
")",
";",
"}"
] | Configure the client socket
Options include:
- ssl_verify_peer => boolean, whether to perform peer verification
of SSL certificate used
- ssl_allow_self_signed => boolean, whether ssl_verify_peer allows
self-signed certs
- timeout_connect => int, seconds, default 2
@param array $options | [
"Configure",
"the",
"client",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/ClientSocket.php#L71-L80 |
varspool/Wrench | lib/Listener/RateLimiter.php | RateLimiter.onSocketConnect | public function onSocketConnect($socket, Connection $connection): void
{
$this->checkConnections($connection);
$this->checkConnectionsPerIp($connection);
} | php | public function onSocketConnect($socket, Connection $connection): void
{
$this->checkConnections($connection);
$this->checkConnectionsPerIp($connection);
} | [
"public",
"function",
"onSocketConnect",
"(",
"$",
"socket",
",",
"Connection",
"$",
"connection",
")",
":",
"void",
"{",
"$",
"this",
"->",
"checkConnections",
"(",
"$",
"connection",
")",
";",
"$",
"this",
"->",
"checkConnectionsPerIp",
"(",
"$",
"connection",
")",
";",
"}"
] | Event listener
@param resource $socket
@param Connection $connection | [
"Event",
"listener"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/RateLimiter.php#L76-L80 |
varspool/Wrench | lib/Listener/RateLimiter.php | RateLimiter.checkConnections | protected function checkConnections($connection)
{
$connections = $connection->getConnectionManager()->count();
if ($connections > $this->options['connections']) {
$this->limit($connection, 'Max connections');
}
} | php | protected function checkConnections($connection)
{
$connections = $connection->getConnectionManager()->count();
if ($connections > $this->options['connections']) {
$this->limit($connection, 'Max connections');
}
} | [
"protected",
"function",
"checkConnections",
"(",
"$",
"connection",
")",
"{",
"$",
"connections",
"=",
"$",
"connection",
"->",
"getConnectionManager",
"(",
")",
"->",
"count",
"(",
")",
";",
"if",
"(",
"$",
"connections",
">",
"$",
"this",
"->",
"options",
"[",
"'connections'",
"]",
")",
"{",
"$",
"this",
"->",
"limit",
"(",
"$",
"connection",
",",
"'Max connections'",
")",
";",
"}",
"}"
] | Idempotent
@param Connection $connection | [
"Idempotent"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/RateLimiter.php#L87-L94 |
varspool/Wrench | lib/Listener/RateLimiter.php | RateLimiter.limit | protected function limit($connection, $limit)
{
$this->logger->notice(sprintf(
'Limiting connection %s: %s',
$connection->getIp(),
$limit
));
$connection->close(new RateLimiterException($limit));
} | php | protected function limit($connection, $limit)
{
$this->logger->notice(sprintf(
'Limiting connection %s: %s',
$connection->getIp(),
$limit
));
$connection->close(new RateLimiterException($limit));
} | [
"protected",
"function",
"limit",
"(",
"$",
"connection",
",",
"$",
"limit",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"notice",
"(",
"sprintf",
"(",
"'Limiting connection %s: %s'",
",",
"$",
"connection",
"->",
"getIp",
"(",
")",
",",
"$",
"limit",
")",
")",
";",
"$",
"connection",
"->",
"close",
"(",
"new",
"RateLimiterException",
"(",
"$",
"limit",
")",
")",
";",
"}"
] | Limits the given connection
@param Connection $connection
@param string $limit Reason | [
"Limits",
"the",
"given",
"connection"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/RateLimiter.php#L102-L111 |
varspool/Wrench | lib/Listener/RateLimiter.php | RateLimiter.checkConnectionsPerIp | protected function checkConnectionsPerIp($connection)
{
$ip = $connection->getIp();
if (!$ip) {
$this->logger->warning('Cannot check connections per IP');
return;
}
if (!isset($this->ips[$ip])) {
$this->ips[$ip] = 1;
} else {
$this->ips[$ip] = min(
$this->options['connections_per_ip'],
$this->ips[$ip] + 1
);
}
if ($this->ips[$ip] > $this->options['connections_per_ip']) {
$this->limit($connection, 'Connections per IP');
}
} | php | protected function checkConnectionsPerIp($connection)
{
$ip = $connection->getIp();
if (!$ip) {
$this->logger->warning('Cannot check connections per IP');
return;
}
if (!isset($this->ips[$ip])) {
$this->ips[$ip] = 1;
} else {
$this->ips[$ip] = min(
$this->options['connections_per_ip'],
$this->ips[$ip] + 1
);
}
if ($this->ips[$ip] > $this->options['connections_per_ip']) {
$this->limit($connection, 'Connections per IP');
}
} | [
"protected",
"function",
"checkConnectionsPerIp",
"(",
"$",
"connection",
")",
"{",
"$",
"ip",
"=",
"$",
"connection",
"->",
"getIp",
"(",
")",
";",
"if",
"(",
"!",
"$",
"ip",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'Cannot check connections per IP'",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
")",
")",
"{",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
"=",
"1",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
"=",
"min",
"(",
"$",
"this",
"->",
"options",
"[",
"'connections_per_ip'",
"]",
",",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
"+",
"1",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
">",
"$",
"this",
"->",
"options",
"[",
"'connections_per_ip'",
"]",
")",
"{",
"$",
"this",
"->",
"limit",
"(",
"$",
"connection",
",",
"'Connections per IP'",
")",
";",
"}",
"}"
] | NOT idempotent, call once per connection
@param Connection $connection | [
"NOT",
"idempotent",
"call",
"once",
"per",
"connection"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/RateLimiter.php#L118-L139 |
varspool/Wrench | lib/Listener/RateLimiter.php | RateLimiter.releaseConnection | protected function releaseConnection(Connection $connection): void
{
$ip = $connection->getIp();
if (!$ip) {
$this->logger->warning('Cannot release connection');
return;
}
if (!isset($this->ips[$ip])) {
$this->ips[$ip] = 0;
} else {
$this->ips[$ip] = max(0, $this->ips[$ip] - 1);
}
unset($this->requests[$connection->getId()]);
} | php | protected function releaseConnection(Connection $connection): void
{
$ip = $connection->getIp();
if (!$ip) {
$this->logger->warning('Cannot release connection');
return;
}
if (!isset($this->ips[$ip])) {
$this->ips[$ip] = 0;
} else {
$this->ips[$ip] = max(0, $this->ips[$ip] - 1);
}
unset($this->requests[$connection->getId()]);
} | [
"protected",
"function",
"releaseConnection",
"(",
"Connection",
"$",
"connection",
")",
":",
"void",
"{",
"$",
"ip",
"=",
"$",
"connection",
"->",
"getIp",
"(",
")",
";",
"if",
"(",
"!",
"$",
"ip",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'Cannot release connection'",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
")",
")",
"{",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
"=",
"0",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
"=",
"max",
"(",
"0",
",",
"$",
"this",
"->",
"ips",
"[",
"$",
"ip",
"]",
"-",
"1",
")",
";",
"}",
"unset",
"(",
"$",
"this",
"->",
"requests",
"[",
"$",
"connection",
"->",
"getId",
"(",
")",
"]",
")",
";",
"}"
] | NOT idempotent, call once per disconnection
@param Connection $connection | [
"NOT",
"idempotent",
"call",
"once",
"per",
"disconnection"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/RateLimiter.php#L157-L173 |
varspool/Wrench | lib/Listener/RateLimiter.php | RateLimiter.checkRequestsPerMinute | protected function checkRequestsPerMinute(Connection $connection)
{
$id = $connection->getId();
if (!isset($this->requests[$id])) {
$this->requests[$id] = [];
}
// Add current token
$this->requests[$id][] = time();
// Expire old tokens
while (reset($this->requests[$id]) < time() - 60) {
array_shift($this->requests[$id]);
}
if (count($this->requests[$id]) > $this->options['requests_per_minute']) {
$this->limit($connection, 'Requests per minute');
}
} | php | protected function checkRequestsPerMinute(Connection $connection)
{
$id = $connection->getId();
if (!isset($this->requests[$id])) {
$this->requests[$id] = [];
}
// Add current token
$this->requests[$id][] = time();
// Expire old tokens
while (reset($this->requests[$id]) < time() - 60) {
array_shift($this->requests[$id]);
}
if (count($this->requests[$id]) > $this->options['requests_per_minute']) {
$this->limit($connection, 'Requests per minute');
}
} | [
"protected",
"function",
"checkRequestsPerMinute",
"(",
"Connection",
"$",
"connection",
")",
"{",
"$",
"id",
"=",
"$",
"connection",
"->",
"getId",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"requests",
"[",
"$",
"id",
"]",
")",
")",
"{",
"$",
"this",
"->",
"requests",
"[",
"$",
"id",
"]",
"=",
"[",
"]",
";",
"}",
"// Add current token",
"$",
"this",
"->",
"requests",
"[",
"$",
"id",
"]",
"[",
"]",
"=",
"time",
"(",
")",
";",
"// Expire old tokens",
"while",
"(",
"reset",
"(",
"$",
"this",
"->",
"requests",
"[",
"$",
"id",
"]",
")",
"<",
"time",
"(",
")",
"-",
"60",
")",
"{",
"array_shift",
"(",
"$",
"this",
"->",
"requests",
"[",
"$",
"id",
"]",
")",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"requests",
"[",
"$",
"id",
"]",
")",
">",
"$",
"this",
"->",
"options",
"[",
"'requests_per_minute'",
"]",
")",
"{",
"$",
"this",
"->",
"limit",
"(",
"$",
"connection",
",",
"'Requests per minute'",
")",
";",
"}",
"}"
] | NOT idempotent, call once per data
@param Connection $connection | [
"NOT",
"idempotent",
"call",
"once",
"per",
"data"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Listener/RateLimiter.php#L191-L210 |
varspool/Wrench | lib/Socket/ServerSocket.php | ServerSocket.listen | public function listen(): void
{
$this->socket = stream_socket_server(
$this->getUri(),
$errno,
$errstr,
STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,
$this->getStreamContext()
);
if (!$this->socket) {
throw new ConnectionException(sprintf(
'Could not listen on socket: %s (%d)',
$errstr,
$errno
));
}
$this->listening = true;
} | php | public function listen(): void
{
$this->socket = stream_socket_server(
$this->getUri(),
$errno,
$errstr,
STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,
$this->getStreamContext()
);
if (!$this->socket) {
throw new ConnectionException(sprintf(
'Could not listen on socket: %s (%d)',
$errstr,
$errno
));
}
$this->listening = true;
} | [
"public",
"function",
"listen",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"socket",
"=",
"stream_socket_server",
"(",
"$",
"this",
"->",
"getUri",
"(",
")",
",",
"$",
"errno",
",",
"$",
"errstr",
",",
"STREAM_SERVER_BIND",
"|",
"STREAM_SERVER_LISTEN",
",",
"$",
"this",
"->",
"getStreamContext",
"(",
")",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"socket",
")",
"{",
"throw",
"new",
"ConnectionException",
"(",
"sprintf",
"(",
"'Could not listen on socket: %s (%d)'",
",",
"$",
"errstr",
",",
"$",
"errno",
")",
")",
";",
"}",
"$",
"this",
"->",
"listening",
"=",
"true",
";",
"}"
] | Listens
@throws ConnectionException | [
"Listens"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/ServerSocket.php#L29-L48 |
varspool/Wrench | lib/Socket/ServerSocket.php | ServerSocket.accept | public function accept()
{
$new = stream_socket_accept(
$this->socket,
$this->options['timeout_accept']
);
if (!$new) {
throw new ConnectionException(socket_strerror(socket_last_error($new)));
}
socket_set_option(socket_import_stream($new), SOL_TCP, TCP_NODELAY, 1);
return $new;
} | php | public function accept()
{
$new = stream_socket_accept(
$this->socket,
$this->options['timeout_accept']
);
if (!$new) {
throw new ConnectionException(socket_strerror(socket_last_error($new)));
}
socket_set_option(socket_import_stream($new), SOL_TCP, TCP_NODELAY, 1);
return $new;
} | [
"public",
"function",
"accept",
"(",
")",
"{",
"$",
"new",
"=",
"stream_socket_accept",
"(",
"$",
"this",
"->",
"socket",
",",
"$",
"this",
"->",
"options",
"[",
"'timeout_accept'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"new",
")",
"{",
"throw",
"new",
"ConnectionException",
"(",
"socket_strerror",
"(",
"socket_last_error",
"(",
"$",
"new",
")",
")",
")",
";",
"}",
"socket_set_option",
"(",
"socket_import_stream",
"(",
"$",
"new",
")",
",",
"SOL_TCP",
",",
"TCP_NODELAY",
",",
"1",
")",
";",
"return",
"$",
"new",
";",
"}"
] | Accepts a new connection on the socket
@throws ConnectionException
@return resource | [
"Accepts",
"a",
"new",
"connection",
"on",
"the",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/ServerSocket.php#L56-L70 |
varspool/Wrench | lib/Socket/ServerSocket.php | ServerSocket.configure | protected function configure(array $options): void
{
$options = array_merge([
'backlog' => 50,
'ssl_cert_file' => null,
'ssl_passphrase' => null,
'ssl_allow_self_signed' => false,
'timeout_accept' => self::TIMEOUT_ACCEPT,
], $options);
parent::configure($options);
} | php | protected function configure(array $options): void
{
$options = array_merge([
'backlog' => 50,
'ssl_cert_file' => null,
'ssl_passphrase' => null,
'ssl_allow_self_signed' => false,
'timeout_accept' => self::TIMEOUT_ACCEPT,
], $options);
parent::configure($options);
} | [
"protected",
"function",
"configure",
"(",
"array",
"$",
"options",
")",
":",
"void",
"{",
"$",
"options",
"=",
"array_merge",
"(",
"[",
"'backlog'",
"=>",
"50",
",",
"'ssl_cert_file'",
"=>",
"null",
",",
"'ssl_passphrase'",
"=>",
"null",
",",
"'ssl_allow_self_signed'",
"=>",
"false",
",",
"'timeout_accept'",
"=>",
"self",
"::",
"TIMEOUT_ACCEPT",
",",
"]",
",",
"$",
"options",
")",
";",
"parent",
"::",
"configure",
"(",
"$",
"options",
")",
";",
"}"
] | Configure the server socket
Options include:
- backlog => int, used to limit the number of outstanding
connections in the socket's listen queue
- ssl_cert_file => string, server SSL certificate
file location. File should contain
certificate and private key
- ssl_passphrase => string, passphrase for the key
- timeout_accept => int, seconds, default 5 | [
"Configure",
"the",
"server",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Socket/ServerSocket.php#L84-L95 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.listen | public function listen(): void
{
$this->socket->listen();
$this->resources[$this->socket->getResourceId()] = $this->socket->getResource();
} | php | public function listen(): void
{
$this->socket->listen();
$this->resources[$this->socket->getResourceId()] = $this->socket->getResource();
} | [
"public",
"function",
"listen",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"socket",
"->",
"listen",
"(",
")",
";",
"$",
"this",
"->",
"resources",
"[",
"$",
"this",
"->",
"socket",
"->",
"getResourceId",
"(",
")",
"]",
"=",
"$",
"this",
"->",
"socket",
"->",
"getResource",
"(",
")",
";",
"}"
] | Listens on the main socket
@return void
@throws ConnectionException | [
"Listens",
"on",
"the",
"main",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L95-L99 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.selectAndProcess | public function selectAndProcess(): void
{
$read = $this->resources;
$unused_write = null;
$unsued_exception = null;
stream_select(
$read,
$unused_write,
$unused_exception,
$this->options['timeout_select'],
$this->options['timeout_select_microsec']
);
foreach ($read as $socket) {
if ($socket == $this->socket->getResource()) {
$this->processMasterSocket();
} else {
$this->processClientSocket($socket);
}
}
} | php | public function selectAndProcess(): void
{
$read = $this->resources;
$unused_write = null;
$unsued_exception = null;
stream_select(
$read,
$unused_write,
$unused_exception,
$this->options['timeout_select'],
$this->options['timeout_select_microsec']
);
foreach ($read as $socket) {
if ($socket == $this->socket->getResource()) {
$this->processMasterSocket();
} else {
$this->processClientSocket($socket);
}
}
} | [
"public",
"function",
"selectAndProcess",
"(",
")",
":",
"void",
"{",
"$",
"read",
"=",
"$",
"this",
"->",
"resources",
";",
"$",
"unused_write",
"=",
"null",
";",
"$",
"unsued_exception",
"=",
"null",
";",
"stream_select",
"(",
"$",
"read",
",",
"$",
"unused_write",
",",
"$",
"unused_exception",
",",
"$",
"this",
"->",
"options",
"[",
"'timeout_select'",
"]",
",",
"$",
"this",
"->",
"options",
"[",
"'timeout_select_microsec'",
"]",
")",
";",
"foreach",
"(",
"$",
"read",
"as",
"$",
"socket",
")",
"{",
"if",
"(",
"$",
"socket",
"==",
"$",
"this",
"->",
"socket",
"->",
"getResource",
"(",
")",
")",
"{",
"$",
"this",
"->",
"processMasterSocket",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"processClientSocket",
"(",
"$",
"socket",
")",
";",
"}",
"}",
"}"
] | Select and process an array of resources | [
"Select",
"and",
"process",
"an",
"array",
"of",
"resources"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L104-L125 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.processMasterSocket | protected function processMasterSocket(): void
{
$new = null;
try {
$new = $this->socket->accept();
} catch (Exception $e) {
$this->logger->error('Socket error: {exception}', [
'exception' => $e,
]);
return;
}
$connection = $this->createConnection($new);
$this->server->notify(Server::EVENT_SOCKET_CONNECT, [$new, $connection]);
} | php | protected function processMasterSocket(): void
{
$new = null;
try {
$new = $this->socket->accept();
} catch (Exception $e) {
$this->logger->error('Socket error: {exception}', [
'exception' => $e,
]);
return;
}
$connection = $this->createConnection($new);
$this->server->notify(Server::EVENT_SOCKET_CONNECT, [$new, $connection]);
} | [
"protected",
"function",
"processMasterSocket",
"(",
")",
":",
"void",
"{",
"$",
"new",
"=",
"null",
";",
"try",
"{",
"$",
"new",
"=",
"$",
"this",
"->",
"socket",
"->",
"accept",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"'Socket error: {exception}'",
",",
"[",
"'exception'",
"=>",
"$",
"e",
",",
"]",
")",
";",
"return",
";",
"}",
"$",
"connection",
"=",
"$",
"this",
"->",
"createConnection",
"(",
"$",
"new",
")",
";",
"$",
"this",
"->",
"server",
"->",
"notify",
"(",
"Server",
"::",
"EVENT_SOCKET_CONNECT",
",",
"[",
"$",
"new",
",",
"$",
"connection",
"]",
")",
";",
"}"
] | Process events on the master socket ($this->socket)
@return void | [
"Process",
"events",
"on",
"the",
"master",
"socket",
"(",
"$this",
"-",
">",
"socket",
")"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L132-L147 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.createConnection | protected function createConnection($resource): Connection
{
if (!$resource || !is_resource($resource)) {
throw new InvalidArgumentException('Invalid connection resource');
}
$socket_class = $this->options['socket_client_class'];
$socket_options = $this->options['socket_client_options'];
$connection_class = $this->options['connection_class'];
$connection_options = $this->options['connection_options'];
$socket = new $socket_class($resource, $socket_options);
$connection = new $connection_class($this, $socket, $connection_options);
if ($connection instanceof LoggerAwareInterface) {
$connection->setLogger($this->logger);
}
$id = $this->resourceId($resource);
$this->resources[$id] = $resource;
$this->connections[$id] = $connection;
return $connection;
} | php | protected function createConnection($resource): Connection
{
if (!$resource || !is_resource($resource)) {
throw new InvalidArgumentException('Invalid connection resource');
}
$socket_class = $this->options['socket_client_class'];
$socket_options = $this->options['socket_client_options'];
$connection_class = $this->options['connection_class'];
$connection_options = $this->options['connection_options'];
$socket = new $socket_class($resource, $socket_options);
$connection = new $connection_class($this, $socket, $connection_options);
if ($connection instanceof LoggerAwareInterface) {
$connection->setLogger($this->logger);
}
$id = $this->resourceId($resource);
$this->resources[$id] = $resource;
$this->connections[$id] = $connection;
return $connection;
} | [
"protected",
"function",
"createConnection",
"(",
"$",
"resource",
")",
":",
"Connection",
"{",
"if",
"(",
"!",
"$",
"resource",
"||",
"!",
"is_resource",
"(",
"$",
"resource",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Invalid connection resource'",
")",
";",
"}",
"$",
"socket_class",
"=",
"$",
"this",
"->",
"options",
"[",
"'socket_client_class'",
"]",
";",
"$",
"socket_options",
"=",
"$",
"this",
"->",
"options",
"[",
"'socket_client_options'",
"]",
";",
"$",
"connection_class",
"=",
"$",
"this",
"->",
"options",
"[",
"'connection_class'",
"]",
";",
"$",
"connection_options",
"=",
"$",
"this",
"->",
"options",
"[",
"'connection_options'",
"]",
";",
"$",
"socket",
"=",
"new",
"$",
"socket_class",
"(",
"$",
"resource",
",",
"$",
"socket_options",
")",
";",
"$",
"connection",
"=",
"new",
"$",
"connection_class",
"(",
"$",
"this",
",",
"$",
"socket",
",",
"$",
"connection_options",
")",
";",
"if",
"(",
"$",
"connection",
"instanceof",
"LoggerAwareInterface",
")",
"{",
"$",
"connection",
"->",
"setLogger",
"(",
"$",
"this",
"->",
"logger",
")",
";",
"}",
"$",
"id",
"=",
"$",
"this",
"->",
"resourceId",
"(",
"$",
"resource",
")",
";",
"$",
"this",
"->",
"resources",
"[",
"$",
"id",
"]",
"=",
"$",
"resource",
";",
"$",
"this",
"->",
"connections",
"[",
"$",
"id",
"]",
"=",
"$",
"connection",
";",
"return",
"$",
"connection",
";",
"}"
] | Creates a connection from a socket resource
The create connection object is based on the options passed into the
constructor ('connection_class', 'connection_options'). This connection
instance and its associated socket resource are then stored in the
manager.
@param resource $resource A socket resource
@return Connection|LoggerAwareInterface | [
"Creates",
"a",
"connection",
"from",
"a",
"socket",
"resource",
"The",
"create",
"connection",
"object",
"is",
"based",
"on",
"the",
"options",
"passed",
"into",
"the",
"constructor",
"(",
"connection_class",
"connection_options",
")",
".",
"This",
"connection",
"instance",
"and",
"its",
"associated",
"socket",
"resource",
"are",
"then",
"stored",
"in",
"the",
"manager",
"."
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L159-L183 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.processClientSocket | protected function processClientSocket($socket): void
{
$connection = $this->getConnectionForClientSocket($socket);
if (!$connection) {
$this->logger->warning('No connection for client socket');
return;
}
try {
$this->server->notify(Server::EVENT_CLIENT_DATA, [$socket, $connection]);
$connection->process();
} catch (CloseException $e) {
$this->logger->notice('Client connection closed: {exception}', [
'exception' => $e,
]);
$connection->close(Protocol::CLOSE_UNEXPECTED, $e->getMessage());
} catch (WrenchException $e) {
$this->logger->warning('Error on client socket: {exception}', [
'exception' => $e,
]);
$connection->close(Protocol::CLOSE_UNEXPECTED);
} catch (InvalidArgumentException $e) {
$this->logger->warning('Wrong input arguments: {exception}', [
'exception' => $e,
]);
$connection->close(Protocol::CLOSE_UNEXPECTED);
}
} | php | protected function processClientSocket($socket): void
{
$connection = $this->getConnectionForClientSocket($socket);
if (!$connection) {
$this->logger->warning('No connection for client socket');
return;
}
try {
$this->server->notify(Server::EVENT_CLIENT_DATA, [$socket, $connection]);
$connection->process();
} catch (CloseException $e) {
$this->logger->notice('Client connection closed: {exception}', [
'exception' => $e,
]);
$connection->close(Protocol::CLOSE_UNEXPECTED, $e->getMessage());
} catch (WrenchException $e) {
$this->logger->warning('Error on client socket: {exception}', [
'exception' => $e,
]);
$connection->close(Protocol::CLOSE_UNEXPECTED);
} catch (InvalidArgumentException $e) {
$this->logger->warning('Wrong input arguments: {exception}', [
'exception' => $e,
]);
$connection->close(Protocol::CLOSE_UNEXPECTED);
}
} | [
"protected",
"function",
"processClientSocket",
"(",
"$",
"socket",
")",
":",
"void",
"{",
"$",
"connection",
"=",
"$",
"this",
"->",
"getConnectionForClientSocket",
"(",
"$",
"socket",
")",
";",
"if",
"(",
"!",
"$",
"connection",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'No connection for client socket'",
")",
";",
"return",
";",
"}",
"try",
"{",
"$",
"this",
"->",
"server",
"->",
"notify",
"(",
"Server",
"::",
"EVENT_CLIENT_DATA",
",",
"[",
"$",
"socket",
",",
"$",
"connection",
"]",
")",
";",
"$",
"connection",
"->",
"process",
"(",
")",
";",
"}",
"catch",
"(",
"CloseException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"notice",
"(",
"'Client connection closed: {exception}'",
",",
"[",
"'exception'",
"=>",
"$",
"e",
",",
"]",
")",
";",
"$",
"connection",
"->",
"close",
"(",
"Protocol",
"::",
"CLOSE_UNEXPECTED",
",",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"WrenchException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'Error on client socket: {exception}'",
",",
"[",
"'exception'",
"=>",
"$",
"e",
",",
"]",
")",
";",
"$",
"connection",
"->",
"close",
"(",
"Protocol",
"::",
"CLOSE_UNEXPECTED",
")",
";",
"}",
"catch",
"(",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'Wrong input arguments: {exception}'",
",",
"[",
"'exception'",
"=>",
"$",
"e",
",",
"]",
")",
";",
"$",
"connection",
"->",
"close",
"(",
"Protocol",
"::",
"CLOSE_UNEXPECTED",
")",
";",
"}",
"}"
] | Process events on a client socket
@param resource $socket | [
"Process",
"events",
"on",
"a",
"client",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L206-L235 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.getConnectionForClientSocket | protected function getConnectionForClientSocket($socket): ?Connection
{
if (!isset($this->connections[$this->resourceId($socket)])) {
return null;
}
return $this->connections[$this->resourceId($socket)];
} | php | protected function getConnectionForClientSocket($socket): ?Connection
{
if (!isset($this->connections[$this->resourceId($socket)])) {
return null;
}
return $this->connections[$this->resourceId($socket)];
} | [
"protected",
"function",
"getConnectionForClientSocket",
"(",
"$",
"socket",
")",
":",
"?",
"Connection",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"connections",
"[",
"$",
"this",
"->",
"resourceId",
"(",
"$",
"socket",
")",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"this",
"->",
"connections",
"[",
"$",
"this",
"->",
"resourceId",
"(",
"$",
"socket",
")",
"]",
";",
"}"
] | Returns the Connection associated with the specified socket resource
@param resource $socket
@return Connection | [
"Returns",
"the",
"Connection",
"associated",
"with",
"the",
"specified",
"socket",
"resource"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L243-L249 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.removeConnection | public function removeConnection(Connection $connection): void
{
$socket = $connection->getSocket();
if ($socket->getResource()) {
$index = $socket->getResourceId();
} else {
$index = array_search($connection, $this->connections);
}
if (!$index) {
$this->logger->warning('Could not remove connection: not found');
}
unset($this->connections[$index]);
unset($this->resources[$index]);
$this->server->notify(
Server::EVENT_SOCKET_DISCONNECT,
[$connection->getSocket(), $connection]
);
} | php | public function removeConnection(Connection $connection): void
{
$socket = $connection->getSocket();
if ($socket->getResource()) {
$index = $socket->getResourceId();
} else {
$index = array_search($connection, $this->connections);
}
if (!$index) {
$this->logger->warning('Could not remove connection: not found');
}
unset($this->connections[$index]);
unset($this->resources[$index]);
$this->server->notify(
Server::EVENT_SOCKET_DISCONNECT,
[$connection->getSocket(), $connection]
);
} | [
"public",
"function",
"removeConnection",
"(",
"Connection",
"$",
"connection",
")",
":",
"void",
"{",
"$",
"socket",
"=",
"$",
"connection",
"->",
"getSocket",
"(",
")",
";",
"if",
"(",
"$",
"socket",
"->",
"getResource",
"(",
")",
")",
"{",
"$",
"index",
"=",
"$",
"socket",
"->",
"getResourceId",
"(",
")",
";",
"}",
"else",
"{",
"$",
"index",
"=",
"array_search",
"(",
"$",
"connection",
",",
"$",
"this",
"->",
"connections",
")",
";",
"}",
"if",
"(",
"!",
"$",
"index",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"warning",
"(",
"'Could not remove connection: not found'",
")",
";",
"}",
"unset",
"(",
"$",
"this",
"->",
"connections",
"[",
"$",
"index",
"]",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"resources",
"[",
"$",
"index",
"]",
")",
";",
"$",
"this",
"->",
"server",
"->",
"notify",
"(",
"Server",
"::",
"EVENT_SOCKET_DISCONNECT",
",",
"[",
"$",
"connection",
"->",
"getSocket",
"(",
")",
",",
"$",
"connection",
"]",
")",
";",
"}"
] | Removes a connection
@param Connection $connection | [
"Removes",
"a",
"connection"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L274-L295 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.configureMasterSocket | protected function configureMasterSocket(): void
{
$class = $this->options['socket_master_class'];
$options = $this->options['socket_master_options'];
$this->socket = new $class($this->server->getUri(), $options);
} | php | protected function configureMasterSocket(): void
{
$class = $this->options['socket_master_class'];
$options = $this->options['socket_master_options'];
$this->socket = new $class($this->server->getUri(), $options);
} | [
"protected",
"function",
"configureMasterSocket",
"(",
")",
":",
"void",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"options",
"[",
"'socket_master_class'",
"]",
";",
"$",
"options",
"=",
"$",
"this",
"->",
"options",
"[",
"'socket_master_options'",
"]",
";",
"$",
"this",
"->",
"socket",
"=",
"new",
"$",
"class",
"(",
"$",
"this",
"->",
"server",
"->",
"getUri",
"(",
")",
",",
"$",
"options",
")",
";",
"}"
] | Configures the main server socket | [
"Configures",
"the",
"main",
"server",
"socket"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L324-L329 |
varspool/Wrench | lib/ConnectionManager.php | ConnectionManager.getAllResources | protected function getAllResources(): array
{
return array_merge($this->resources, [
$this->socket->getResourceId() => $this->socket->getResource(),
]);
} | php | protected function getAllResources(): array
{
return array_merge($this->resources, [
$this->socket->getResourceId() => $this->socket->getResource(),
]);
} | [
"protected",
"function",
"getAllResources",
"(",
")",
":",
"array",
"{",
"return",
"array_merge",
"(",
"$",
"this",
"->",
"resources",
",",
"[",
"$",
"this",
"->",
"socket",
"->",
"getResourceId",
"(",
")",
"=>",
"$",
"this",
"->",
"socket",
"->",
"getResource",
"(",
")",
",",
"]",
")",
";",
"}"
] | Gets all resources
@return array<int => resource) | [
"Gets",
"all",
"resources"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/ConnectionManager.php#L336-L341 |
varspool/Wrench | lib/BasicServer.php | BasicServer.configureOriginPolicy | protected function configureOriginPolicy(): void
{
$class = $this->options['origin_policy_class'];
$this->originPolicy = new $class($this->options['allowed_origins']);
if ($this->options['check_origin']) {
$this->originPolicy->listen($this);
}
} | php | protected function configureOriginPolicy(): void
{
$class = $this->options['origin_policy_class'];
$this->originPolicy = new $class($this->options['allowed_origins']);
if ($this->options['check_origin']) {
$this->originPolicy->listen($this);
}
} | [
"protected",
"function",
"configureOriginPolicy",
"(",
")",
":",
"void",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"options",
"[",
"'origin_policy_class'",
"]",
";",
"$",
"this",
"->",
"originPolicy",
"=",
"new",
"$",
"class",
"(",
"$",
"this",
"->",
"options",
"[",
"'allowed_origins'",
"]",
")",
";",
"if",
"(",
"$",
"this",
"->",
"options",
"[",
"'check_origin'",
"]",
")",
"{",
"$",
"this",
"->",
"originPolicy",
"->",
"listen",
"(",
"$",
"this",
")",
";",
"}",
"}"
] | Configures the origin policy | [
"Configures",
"the",
"origin",
"policy"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/BasicServer.php#L37-L45 |
varspool/Wrench | lib/Util/Configurable.php | Configurable.configureProtocol | protected function configureProtocol(): void
{
$protocol = $this->options['protocol'];
if (!$protocol || !($protocol instanceof Protocol)) {
throw new InvalidArgumentException('Invalid protocol option');
}
$this->protocol = $protocol;
} | php | protected function configureProtocol(): void
{
$protocol = $this->options['protocol'];
if (!$protocol || !($protocol instanceof Protocol)) {
throw new InvalidArgumentException('Invalid protocol option');
}
$this->protocol = $protocol;
} | [
"protected",
"function",
"configureProtocol",
"(",
")",
":",
"void",
"{",
"$",
"protocol",
"=",
"$",
"this",
"->",
"options",
"[",
"'protocol'",
"]",
";",
"if",
"(",
"!",
"$",
"protocol",
"||",
"!",
"(",
"$",
"protocol",
"instanceof",
"Protocol",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Invalid protocol option'",
")",
";",
"}",
"$",
"this",
"->",
"protocol",
"=",
"$",
"protocol",
";",
"}"
] | Configures the protocol option
@throws InvalidArgumentException | [
"Configures",
"the",
"protocol",
"option"
] | train | https://github.com/varspool/Wrench/blob/2c297b5d655efaed22acbd0486d219f11b698b3c/lib/Util/Configurable.php#L56-L65 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/BelongsToSortedManyTrait.php | BelongsToSortedManyTrait.belongsToSortedMany | public function belongsToSortedMany($related, $orderColumn = 'position', $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
$parentKey = null, $relatedKey = null, $relation = null)
{
// If no relationship name was passed, we will pull backtraces to get the
// name of the calling function. We will use that function name as the
// title of this relation since that is a great convention to apply.
if (is_null($relation)) {
$relation = $this->guessBelongsToManyRelation();
}
// First, we'll need to determine the foreign key and "other key" for the
// relationship. Once we have determined the keys we'll make the query
// instances as well as the relationship instances we need for this.
$instance = $this->newRelatedInstance($related);
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
// If no table name was provided, we can guess it by concatenating the two
// models using underscores in alphabetical order. The two model names
// are transformed to snake case from their default CamelCase also.
if (is_null($table)) {
$table = $this->joiningTable($related, $instance);
}
return new BelongsToSortedMany(
$instance->newQuery(), $this, $table, $foreignPivotKey,
$relatedPivotKey, $parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(), $relation, $orderColumn
);
} | php | public function belongsToSortedMany($related, $orderColumn = 'position', $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
$parentKey = null, $relatedKey = null, $relation = null)
{
// If no relationship name was passed, we will pull backtraces to get the
// name of the calling function. We will use that function name as the
// title of this relation since that is a great convention to apply.
if (is_null($relation)) {
$relation = $this->guessBelongsToManyRelation();
}
// First, we'll need to determine the foreign key and "other key" for the
// relationship. Once we have determined the keys we'll make the query
// instances as well as the relationship instances we need for this.
$instance = $this->newRelatedInstance($related);
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
// If no table name was provided, we can guess it by concatenating the two
// models using underscores in alphabetical order. The two model names
// are transformed to snake case from their default CamelCase also.
if (is_null($table)) {
$table = $this->joiningTable($related, $instance);
}
return new BelongsToSortedMany(
$instance->newQuery(), $this, $table, $foreignPivotKey,
$relatedPivotKey, $parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(), $relation, $orderColumn
);
} | [
"public",
"function",
"belongsToSortedMany",
"(",
"$",
"related",
",",
"$",
"orderColumn",
"=",
"'position'",
",",
"$",
"table",
"=",
"null",
",",
"$",
"foreignPivotKey",
"=",
"null",
",",
"$",
"relatedPivotKey",
"=",
"null",
",",
"$",
"parentKey",
"=",
"null",
",",
"$",
"relatedKey",
"=",
"null",
",",
"$",
"relation",
"=",
"null",
")",
"{",
"// If no relationship name was passed, we will pull backtraces to get the",
"// name of the calling function. We will use that function name as the",
"// title of this relation since that is a great convention to apply.",
"if",
"(",
"is_null",
"(",
"$",
"relation",
")",
")",
"{",
"$",
"relation",
"=",
"$",
"this",
"->",
"guessBelongsToManyRelation",
"(",
")",
";",
"}",
"// First, we'll need to determine the foreign key and \"other key\" for the",
"// relationship. Once we have determined the keys we'll make the query",
"// instances as well as the relationship instances we need for this.",
"$",
"instance",
"=",
"$",
"this",
"->",
"newRelatedInstance",
"(",
"$",
"related",
")",
";",
"$",
"foreignPivotKey",
"=",
"$",
"foreignPivotKey",
"?",
":",
"$",
"this",
"->",
"getForeignKey",
"(",
")",
";",
"$",
"relatedPivotKey",
"=",
"$",
"relatedPivotKey",
"?",
":",
"$",
"instance",
"->",
"getForeignKey",
"(",
")",
";",
"// If no table name was provided, we can guess it by concatenating the two",
"// models using underscores in alphabetical order. The two model names",
"// are transformed to snake case from their default CamelCase also.",
"if",
"(",
"is_null",
"(",
"$",
"table",
")",
")",
"{",
"$",
"table",
"=",
"$",
"this",
"->",
"joiningTable",
"(",
"$",
"related",
",",
"$",
"instance",
")",
";",
"}",
"return",
"new",
"BelongsToSortedMany",
"(",
"$",
"instance",
"->",
"newQuery",
"(",
")",
",",
"$",
"this",
",",
"$",
"table",
",",
"$",
"foreignPivotKey",
",",
"$",
"relatedPivotKey",
",",
"$",
"parentKey",
"?",
":",
"$",
"this",
"->",
"getKeyName",
"(",
")",
",",
"$",
"relatedKey",
"?",
":",
"$",
"instance",
"->",
"getKeyName",
"(",
")",
",",
"$",
"relation",
",",
"$",
"orderColumn",
")",
";",
"}"
] | Define a many-to-many relationship.
Notice that signature of this method is different than ->belongsToMany: second param is pivot position column name.
Other params is the same as ->belongsToMany has.
Just copy of belongsToMany except last line where we return new BelongsToSortedMany instance with additional orderColumn param
@param string $related
@param string $orderColumn
@param string $table
@param string $foreignPivotKey
@param string $relatedPivotKey
@param string $parentKey
@param string $relatedKey
@param string $relation
@return BelongsToSortedMany | [
"Define",
"a",
"many",
"-",
"to",
"-",
"many",
"relationship",
".",
"Notice",
"that",
"signature",
"of",
"this",
"method",
"is",
"different",
"than",
"-",
">",
"belongsToMany",
":",
"second",
"param",
"is",
"pivot",
"position",
"column",
"name",
".",
"Other",
"params",
"is",
"the",
"same",
"as",
"-",
">",
"belongsToMany",
"has",
"."
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/BelongsToSortedManyTrait.php#L30-L61 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/MorphToSortedManyTrait.php | MorphToSortedManyTrait.morphToSortedMany | public function morphToSortedMany($related, $name, $orderColumn = 'position', $table = null, $foreignPivotKey = null,
$relatedPivotKey = null, $parentKey = null,
$relatedKey = null, $inverse = false)
{
$caller = $this->guessBelongsToManyRelation();
// First, we will need to determine the foreign key and "other key" for the
// relationship. Once we have determined the keys we will make the query
// instances, as well as the relationship instances we need for these.
$instance = $this->newRelatedInstance($related);
$foreignPivotKey = $foreignPivotKey ?: $name . '_id';
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
// Now we're ready to create a new query builder for this related model and
// the relationship instances for this relation. This relations will set
// appropriate query constraints then entirely manages the hydrations.
$table = $table ?: Str::plural($name);
return new MorphToSortedMany(
$instance->newQuery(), $this, $name, $table,
$foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(), $orderColumn, $caller, $inverse
);
} | php | public function morphToSortedMany($related, $name, $orderColumn = 'position', $table = null, $foreignPivotKey = null,
$relatedPivotKey = null, $parentKey = null,
$relatedKey = null, $inverse = false)
{
$caller = $this->guessBelongsToManyRelation();
// First, we will need to determine the foreign key and "other key" for the
// relationship. Once we have determined the keys we will make the query
// instances, as well as the relationship instances we need for these.
$instance = $this->newRelatedInstance($related);
$foreignPivotKey = $foreignPivotKey ?: $name . '_id';
$relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey();
// Now we're ready to create a new query builder for this related model and
// the relationship instances for this relation. This relations will set
// appropriate query constraints then entirely manages the hydrations.
$table = $table ?: Str::plural($name);
return new MorphToSortedMany(
$instance->newQuery(), $this, $name, $table,
$foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(),
$relatedKey ?: $instance->getKeyName(), $orderColumn, $caller, $inverse
);
} | [
"public",
"function",
"morphToSortedMany",
"(",
"$",
"related",
",",
"$",
"name",
",",
"$",
"orderColumn",
"=",
"'position'",
",",
"$",
"table",
"=",
"null",
",",
"$",
"foreignPivotKey",
"=",
"null",
",",
"$",
"relatedPivotKey",
"=",
"null",
",",
"$",
"parentKey",
"=",
"null",
",",
"$",
"relatedKey",
"=",
"null",
",",
"$",
"inverse",
"=",
"false",
")",
"{",
"$",
"caller",
"=",
"$",
"this",
"->",
"guessBelongsToManyRelation",
"(",
")",
";",
"// First, we will need to determine the foreign key and \"other key\" for the",
"// relationship. Once we have determined the keys we will make the query",
"// instances, as well as the relationship instances we need for these.",
"$",
"instance",
"=",
"$",
"this",
"->",
"newRelatedInstance",
"(",
"$",
"related",
")",
";",
"$",
"foreignPivotKey",
"=",
"$",
"foreignPivotKey",
"?",
":",
"$",
"name",
".",
"'_id'",
";",
"$",
"relatedPivotKey",
"=",
"$",
"relatedPivotKey",
"?",
":",
"$",
"instance",
"->",
"getForeignKey",
"(",
")",
";",
"// Now we're ready to create a new query builder for this related model and",
"// the relationship instances for this relation. This relations will set",
"// appropriate query constraints then entirely manages the hydrations.",
"$",
"table",
"=",
"$",
"table",
"?",
":",
"Str",
"::",
"plural",
"(",
"$",
"name",
")",
";",
"return",
"new",
"MorphToSortedMany",
"(",
"$",
"instance",
"->",
"newQuery",
"(",
")",
",",
"$",
"this",
",",
"$",
"name",
",",
"$",
"table",
",",
"$",
"foreignPivotKey",
",",
"$",
"relatedPivotKey",
",",
"$",
"parentKey",
"?",
":",
"$",
"this",
"->",
"getKeyName",
"(",
")",
",",
"$",
"relatedKey",
"?",
":",
"$",
"instance",
"->",
"getKeyName",
"(",
")",
",",
"$",
"orderColumn",
",",
"$",
"caller",
",",
"$",
"inverse",
")",
";",
"}"
] | Define a polymorphic many-to-many relationship.
Notice that signature of this method is different than ->belongsToMany: second param is pivot position column name.
Other params is the same as ->belongsToMany has.
Just copy of belongsToMany except last line where we return new BelongsToSortedMany instance with additional orderColumn param
@param string $related
@param string $name
@param string $orderColumn
@param string $table
@param string $foreignPivotKey
@param string $relatedPivotKey
@param string $parentKey
@param string $relatedKey
@param bool $inverse
@return MorphToSortedMany | [
"Define",
"a",
"polymorphic",
"many",
"-",
"to",
"-",
"many",
"relationship",
".",
"Notice",
"that",
"signature",
"of",
"this",
"method",
"is",
"different",
"than",
"-",
">",
"belongsToMany",
":",
"second",
"param",
"is",
"pivot",
"position",
"column",
"name",
".",
"Other",
"params",
"is",
"the",
"same",
"as",
"-",
">",
"belongsToMany",
"has",
"."
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/MorphToSortedManyTrait.php#L33-L58 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/MorphToSortedManyTrait.php | MorphToSortedManyTrait.morphedBySortedMany | public function morphedBySortedMany($related, $name, $orderColumn = 'position', $table = null, $foreignPivotKey = null,
$relatedPivotKey = null, $parentKey = null, $relatedKey = null)
{
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
// For the inverse of the polymorphic many-to-many relations, we will change
// the way we determine the foreign and other keys, as it is the opposite
// of the morph-to-many method since we're figuring out these inverses.
$relatedPivotKey = $relatedPivotKey ?: $name . '_id';
return $this->morphToSortedMany(
$related, $name, $orderColumn, $table, $foreignPivotKey,
$relatedPivotKey, $parentKey, $relatedKey, true
);
} | php | public function morphedBySortedMany($related, $name, $orderColumn = 'position', $table = null, $foreignPivotKey = null,
$relatedPivotKey = null, $parentKey = null, $relatedKey = null)
{
$foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey();
// For the inverse of the polymorphic many-to-many relations, we will change
// the way we determine the foreign and other keys, as it is the opposite
// of the morph-to-many method since we're figuring out these inverses.
$relatedPivotKey = $relatedPivotKey ?: $name . '_id';
return $this->morphToSortedMany(
$related, $name, $orderColumn, $table, $foreignPivotKey,
$relatedPivotKey, $parentKey, $relatedKey, true
);
} | [
"public",
"function",
"morphedBySortedMany",
"(",
"$",
"related",
",",
"$",
"name",
",",
"$",
"orderColumn",
"=",
"'position'",
",",
"$",
"table",
"=",
"null",
",",
"$",
"foreignPivotKey",
"=",
"null",
",",
"$",
"relatedPivotKey",
"=",
"null",
",",
"$",
"parentKey",
"=",
"null",
",",
"$",
"relatedKey",
"=",
"null",
")",
"{",
"$",
"foreignPivotKey",
"=",
"$",
"foreignPivotKey",
"?",
":",
"$",
"this",
"->",
"getForeignKey",
"(",
")",
";",
"// For the inverse of the polymorphic many-to-many relations, we will change",
"// the way we determine the foreign and other keys, as it is the opposite",
"// of the morph-to-many method since we're figuring out these inverses.",
"$",
"relatedPivotKey",
"=",
"$",
"relatedPivotKey",
"?",
":",
"$",
"name",
".",
"'_id'",
";",
"return",
"$",
"this",
"->",
"morphToSortedMany",
"(",
"$",
"related",
",",
"$",
"name",
",",
"$",
"orderColumn",
",",
"$",
"table",
",",
"$",
"foreignPivotKey",
",",
"$",
"relatedPivotKey",
",",
"$",
"parentKey",
",",
"$",
"relatedKey",
",",
"true",
")",
";",
"}"
] | Define a polymorphic, inverse many-to-many relationship.
@param string $related
@param string $name
@param string $orderColumn
@param string $table
@param string $foreignPivotKey
@param string $relatedPivotKey
@param string $parentKey
@param string $relatedKey
@return \Illuminate\Database\Eloquent\Relations\MorphToMany | [
"Define",
"a",
"polymorphic",
"inverse",
"many",
"-",
"to",
"-",
"many",
"relationship",
"."
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/MorphToSortedManyTrait.php#L74-L88 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableController.php | SortableController.sort | public function sort(Request $request)
{
$sortableEntities = app('config')->get('sortable.entities', []);
$validator = $this->getValidator($sortableEntities, $request);
if (!$validator->passes()) {
return [
'success' => false,
'errors' => $validator->errors(),
'failed' => $validator->failed(),
];
}
/** @var Model|bool $entityClass */
list($entityClass, $relation) = $this->getEntityInfo($sortableEntities, (string) $request->input('entityName'));
$method = ($request->input('type') === 'moveAfter') ? 'moveAfter' : 'moveBefore';
if (!$relation) {
/** @var SortableTrait $entity */
$entity = $entityClass::find($request->input('id'));
$postionEntity = $entityClass::find($request->input('positionEntityId'));
$entity->$method($postionEntity);
} else {
$parentEntity = $entityClass::find($request->input('parentId'));
$entity = $parentEntity->$relation()->find($request->input('id'));
$postionEntity = $parentEntity->$relation()->find($request->input('positionEntityId'));
$parentEntity->$relation()->$method($entity, $postionEntity);
}
return ['success' => true];
} | php | public function sort(Request $request)
{
$sortableEntities = app('config')->get('sortable.entities', []);
$validator = $this->getValidator($sortableEntities, $request);
if (!$validator->passes()) {
return [
'success' => false,
'errors' => $validator->errors(),
'failed' => $validator->failed(),
];
}
/** @var Model|bool $entityClass */
list($entityClass, $relation) = $this->getEntityInfo($sortableEntities, (string) $request->input('entityName'));
$method = ($request->input('type') === 'moveAfter') ? 'moveAfter' : 'moveBefore';
if (!$relation) {
/** @var SortableTrait $entity */
$entity = $entityClass::find($request->input('id'));
$postionEntity = $entityClass::find($request->input('positionEntityId'));
$entity->$method($postionEntity);
} else {
$parentEntity = $entityClass::find($request->input('parentId'));
$entity = $parentEntity->$relation()->find($request->input('id'));
$postionEntity = $parentEntity->$relation()->find($request->input('positionEntityId'));
$parentEntity->$relation()->$method($entity, $postionEntity);
}
return ['success' => true];
} | [
"public",
"function",
"sort",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"sortableEntities",
"=",
"app",
"(",
"'config'",
")",
"->",
"get",
"(",
"'sortable.entities'",
",",
"[",
"]",
")",
";",
"$",
"validator",
"=",
"$",
"this",
"->",
"getValidator",
"(",
"$",
"sortableEntities",
",",
"$",
"request",
")",
";",
"if",
"(",
"!",
"$",
"validator",
"->",
"passes",
"(",
")",
")",
"{",
"return",
"[",
"'success'",
"=>",
"false",
",",
"'errors'",
"=>",
"$",
"validator",
"->",
"errors",
"(",
")",
",",
"'failed'",
"=>",
"$",
"validator",
"->",
"failed",
"(",
")",
",",
"]",
";",
"}",
"/** @var Model|bool $entityClass */",
"list",
"(",
"$",
"entityClass",
",",
"$",
"relation",
")",
"=",
"$",
"this",
"->",
"getEntityInfo",
"(",
"$",
"sortableEntities",
",",
"(",
"string",
")",
"$",
"request",
"->",
"input",
"(",
"'entityName'",
")",
")",
";",
"$",
"method",
"=",
"(",
"$",
"request",
"->",
"input",
"(",
"'type'",
")",
"===",
"'moveAfter'",
")",
"?",
"'moveAfter'",
":",
"'moveBefore'",
";",
"if",
"(",
"!",
"$",
"relation",
")",
"{",
"/** @var SortableTrait $entity */",
"$",
"entity",
"=",
"$",
"entityClass",
"::",
"find",
"(",
"$",
"request",
"->",
"input",
"(",
"'id'",
")",
")",
";",
"$",
"postionEntity",
"=",
"$",
"entityClass",
"::",
"find",
"(",
"$",
"request",
"->",
"input",
"(",
"'positionEntityId'",
")",
")",
";",
"$",
"entity",
"->",
"$",
"method",
"(",
"$",
"postionEntity",
")",
";",
"}",
"else",
"{",
"$",
"parentEntity",
"=",
"$",
"entityClass",
"::",
"find",
"(",
"$",
"request",
"->",
"input",
"(",
"'parentId'",
")",
")",
";",
"$",
"entity",
"=",
"$",
"parentEntity",
"->",
"$",
"relation",
"(",
")",
"->",
"find",
"(",
"$",
"request",
"->",
"input",
"(",
"'id'",
")",
")",
";",
"$",
"postionEntity",
"=",
"$",
"parentEntity",
"->",
"$",
"relation",
"(",
")",
"->",
"find",
"(",
"$",
"request",
"->",
"input",
"(",
"'positionEntityId'",
")",
")",
";",
"$",
"parentEntity",
"->",
"$",
"relation",
"(",
")",
"->",
"$",
"method",
"(",
"$",
"entity",
",",
"$",
"postionEntity",
")",
";",
"}",
"return",
"[",
"'success'",
"=>",
"true",
"]",
";",
"}"
] | @param Request $request
@return array | [
"@param",
"Request",
"$request"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableController.php#L16-L46 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableController.php | SortableController.getValidator | protected function getValidator($sortableEntities, $request)
{
/** @var \Illuminate\Validation\Factory $validator */
$validator = app('validator');
$rules = [
'type' => ['required', 'in:moveAfter,moveBefore'],
'entityName' => ['required', 'in:' . implode(',', array_keys($sortableEntities))],
'id' => 'required',
'positionEntityId' => 'required',
];
/** @var Model|bool $entityClass */
list($entityClass, $relation) = $this->getEntityInfo($sortableEntities, (string) $request->input('entityName'));
if (!class_exists($entityClass)) {
$rules['entityClass'] = 'required'; // fake rule for not exist field
return $validator->make($request->all(), $rules);
}
$connectionName = with(new $entityClass())->getConnectionName();
$tableName = with(new $entityClass())->getTable();
$primaryKey = with(new $entityClass())->getKeyName();
if (!empty($connectionName)) {
$tableName = $connectionName . '.' . $tableName;
}
if (!$relation) {
$rules['id'] .= '|exists:' . $tableName . ',' . $primaryKey;
$rules['positionEntityId'] .= '|exists:' . $tableName . ',' . $primaryKey;
} else {
/** @var BelongsToSortedMany $relationObject */
$relationObject = with(new $entityClass())->$relation();
$pivotTable = $relationObject->getTable();
$rules['parentId'] = 'required|exists:' . $tableName . ',' . $primaryKey;
$rules['id'] .= '|exists:' . $pivotTable . ',' . $relationObject->getRelatedKey() . ',' . $relationObject->getForeignKey() . ',' . $request->input('parentId');
$rules['positionEntityId'] .= '|exists:' . $pivotTable . ',' . $relationObject->getRelatedKey() . ',' . $relationObject->getForeignKey() . ',' . $request->input('parentId');
}
return $validator->make($request->all(), $rules);
} | php | protected function getValidator($sortableEntities, $request)
{
/** @var \Illuminate\Validation\Factory $validator */
$validator = app('validator');
$rules = [
'type' => ['required', 'in:moveAfter,moveBefore'],
'entityName' => ['required', 'in:' . implode(',', array_keys($sortableEntities))],
'id' => 'required',
'positionEntityId' => 'required',
];
/** @var Model|bool $entityClass */
list($entityClass, $relation) = $this->getEntityInfo($sortableEntities, (string) $request->input('entityName'));
if (!class_exists($entityClass)) {
$rules['entityClass'] = 'required'; // fake rule for not exist field
return $validator->make($request->all(), $rules);
}
$connectionName = with(new $entityClass())->getConnectionName();
$tableName = with(new $entityClass())->getTable();
$primaryKey = with(new $entityClass())->getKeyName();
if (!empty($connectionName)) {
$tableName = $connectionName . '.' . $tableName;
}
if (!$relation) {
$rules['id'] .= '|exists:' . $tableName . ',' . $primaryKey;
$rules['positionEntityId'] .= '|exists:' . $tableName . ',' . $primaryKey;
} else {
/** @var BelongsToSortedMany $relationObject */
$relationObject = with(new $entityClass())->$relation();
$pivotTable = $relationObject->getTable();
$rules['parentId'] = 'required|exists:' . $tableName . ',' . $primaryKey;
$rules['id'] .= '|exists:' . $pivotTable . ',' . $relationObject->getRelatedKey() . ',' . $relationObject->getForeignKey() . ',' . $request->input('parentId');
$rules['positionEntityId'] .= '|exists:' . $pivotTable . ',' . $relationObject->getRelatedKey() . ',' . $relationObject->getForeignKey() . ',' . $request->input('parentId');
}
return $validator->make($request->all(), $rules);
} | [
"protected",
"function",
"getValidator",
"(",
"$",
"sortableEntities",
",",
"$",
"request",
")",
"{",
"/** @var \\Illuminate\\Validation\\Factory $validator */",
"$",
"validator",
"=",
"app",
"(",
"'validator'",
")",
";",
"$",
"rules",
"=",
"[",
"'type'",
"=>",
"[",
"'required'",
",",
"'in:moveAfter,moveBefore'",
"]",
",",
"'entityName'",
"=>",
"[",
"'required'",
",",
"'in:'",
".",
"implode",
"(",
"','",
",",
"array_keys",
"(",
"$",
"sortableEntities",
")",
")",
"]",
",",
"'id'",
"=>",
"'required'",
",",
"'positionEntityId'",
"=>",
"'required'",
",",
"]",
";",
"/** @var Model|bool $entityClass */",
"list",
"(",
"$",
"entityClass",
",",
"$",
"relation",
")",
"=",
"$",
"this",
"->",
"getEntityInfo",
"(",
"$",
"sortableEntities",
",",
"(",
"string",
")",
"$",
"request",
"->",
"input",
"(",
"'entityName'",
")",
")",
";",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"entityClass",
")",
")",
"{",
"$",
"rules",
"[",
"'entityClass'",
"]",
"=",
"'required'",
";",
"// fake rule for not exist field",
"return",
"$",
"validator",
"->",
"make",
"(",
"$",
"request",
"->",
"all",
"(",
")",
",",
"$",
"rules",
")",
";",
"}",
"$",
"connectionName",
"=",
"with",
"(",
"new",
"$",
"entityClass",
"(",
")",
")",
"->",
"getConnectionName",
"(",
")",
";",
"$",
"tableName",
"=",
"with",
"(",
"new",
"$",
"entityClass",
"(",
")",
")",
"->",
"getTable",
"(",
")",
";",
"$",
"primaryKey",
"=",
"with",
"(",
"new",
"$",
"entityClass",
"(",
")",
")",
"->",
"getKeyName",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"connectionName",
")",
")",
"{",
"$",
"tableName",
"=",
"$",
"connectionName",
".",
"'.'",
".",
"$",
"tableName",
";",
"}",
"if",
"(",
"!",
"$",
"relation",
")",
"{",
"$",
"rules",
"[",
"'id'",
"]",
".=",
"'|exists:'",
".",
"$",
"tableName",
".",
"','",
".",
"$",
"primaryKey",
";",
"$",
"rules",
"[",
"'positionEntityId'",
"]",
".=",
"'|exists:'",
".",
"$",
"tableName",
".",
"','",
".",
"$",
"primaryKey",
";",
"}",
"else",
"{",
"/** @var BelongsToSortedMany $relationObject */",
"$",
"relationObject",
"=",
"with",
"(",
"new",
"$",
"entityClass",
"(",
")",
")",
"->",
"$",
"relation",
"(",
")",
";",
"$",
"pivotTable",
"=",
"$",
"relationObject",
"->",
"getTable",
"(",
")",
";",
"$",
"rules",
"[",
"'parentId'",
"]",
"=",
"'required|exists:'",
".",
"$",
"tableName",
".",
"','",
".",
"$",
"primaryKey",
";",
"$",
"rules",
"[",
"'id'",
"]",
".=",
"'|exists:'",
".",
"$",
"pivotTable",
".",
"','",
".",
"$",
"relationObject",
"->",
"getRelatedKey",
"(",
")",
".",
"','",
".",
"$",
"relationObject",
"->",
"getForeignKey",
"(",
")",
".",
"','",
".",
"$",
"request",
"->",
"input",
"(",
"'parentId'",
")",
";",
"$",
"rules",
"[",
"'positionEntityId'",
"]",
".=",
"'|exists:'",
".",
"$",
"pivotTable",
".",
"','",
".",
"$",
"relationObject",
"->",
"getRelatedKey",
"(",
")",
".",
"','",
".",
"$",
"relationObject",
"->",
"getForeignKey",
"(",
")",
".",
"','",
".",
"$",
"request",
"->",
"input",
"(",
"'parentId'",
")",
";",
"}",
"return",
"$",
"validator",
"->",
"make",
"(",
"$",
"request",
"->",
"all",
"(",
")",
",",
"$",
"rules",
")",
";",
"}"
] | @param array $sortableEntities
@param Request $request
@return \Illuminate\Validation\Validator | [
"@param",
"array",
"$sortableEntities",
"@param",
"Request",
"$request"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableController.php#L54-L96 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableController.php | SortableController.getEntityInfo | protected function getEntityInfo($sortableEntities, $entityName)
{
$relation = false;
$entityConfig = $entityName ? array_get($sortableEntities, $entityName, false) : false;
if (is_array($entityConfig)) {
$entityClass = $entityConfig['entity'];
$relation = !empty($entityConfig['relation']) ? $entityConfig['relation'] : false;
} else {
$entityClass = $entityConfig;
}
return [$entityClass, $relation];
} | php | protected function getEntityInfo($sortableEntities, $entityName)
{
$relation = false;
$entityConfig = $entityName ? array_get($sortableEntities, $entityName, false) : false;
if (is_array($entityConfig)) {
$entityClass = $entityConfig['entity'];
$relation = !empty($entityConfig['relation']) ? $entityConfig['relation'] : false;
} else {
$entityClass = $entityConfig;
}
return [$entityClass, $relation];
} | [
"protected",
"function",
"getEntityInfo",
"(",
"$",
"sortableEntities",
",",
"$",
"entityName",
")",
"{",
"$",
"relation",
"=",
"false",
";",
"$",
"entityConfig",
"=",
"$",
"entityName",
"?",
"array_get",
"(",
"$",
"sortableEntities",
",",
"$",
"entityName",
",",
"false",
")",
":",
"false",
";",
"if",
"(",
"is_array",
"(",
"$",
"entityConfig",
")",
")",
"{",
"$",
"entityClass",
"=",
"$",
"entityConfig",
"[",
"'entity'",
"]",
";",
"$",
"relation",
"=",
"!",
"empty",
"(",
"$",
"entityConfig",
"[",
"'relation'",
"]",
")",
"?",
"$",
"entityConfig",
"[",
"'relation'",
"]",
":",
"false",
";",
"}",
"else",
"{",
"$",
"entityClass",
"=",
"$",
"entityConfig",
";",
"}",
"return",
"[",
"$",
"entityClass",
",",
"$",
"relation",
"]",
";",
"}"
] | @param array $sortableEntities
@param string $entityName
@return array | [
"@param",
"array",
"$sortableEntities",
"@param",
"string",
"$entityName"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableController.php#L104-L118 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableTrait.php | SortableTrait.bootSortableTrait | public static function bootSortableTrait()
{
static::creating(
function ($model) {
/* @var Model $model */
$sortableField = static::getSortableField();
$query = static::applySortableGroup(static::on($model->getConnectionName()), $model);
// only automatically calculate next position with max+1 when a position has not been set already
if ($model->$sortableField === null) {
$model->setAttribute($sortableField, $query->max($sortableField) + 1);
}
}
);
} | php | public static function bootSortableTrait()
{
static::creating(
function ($model) {
/* @var Model $model */
$sortableField = static::getSortableField();
$query = static::applySortableGroup(static::on($model->getConnectionName()), $model);
// only automatically calculate next position with max+1 when a position has not been set already
if ($model->$sortableField === null) {
$model->setAttribute($sortableField, $query->max($sortableField) + 1);
}
}
);
} | [
"public",
"static",
"function",
"bootSortableTrait",
"(",
")",
"{",
"static",
"::",
"creating",
"(",
"function",
"(",
"$",
"model",
")",
"{",
"/* @var Model $model */",
"$",
"sortableField",
"=",
"static",
"::",
"getSortableField",
"(",
")",
";",
"$",
"query",
"=",
"static",
"::",
"applySortableGroup",
"(",
"static",
"::",
"on",
"(",
"$",
"model",
"->",
"getConnectionName",
"(",
")",
")",
",",
"$",
"model",
")",
";",
"// only automatically calculate next position with max+1 when a position has not been set already",
"if",
"(",
"$",
"model",
"->",
"$",
"sortableField",
"===",
"null",
")",
"{",
"$",
"model",
"->",
"setAttribute",
"(",
"$",
"sortableField",
",",
"$",
"query",
"->",
"max",
"(",
"$",
"sortableField",
")",
"+",
"1",
")",
";",
"}",
"}",
")",
";",
"}"
] | Adds position to model on creating event. | [
"Adds",
"position",
"to",
"model",
"on",
"creating",
"event",
"."
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableTrait.php#L26-L40 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableTrait.php | SortableTrait.move | public function move($action, $entity)
{
$this->checkSortableGroupField(static::getSortableGroupField(), $entity);
$this->_transaction(function () use ($entity, $action) {
$sortableField = static::getSortableField();
$oldPosition = $this->getAttribute($sortableField);
$newPosition = $entity->getAttribute($sortableField);
if ($oldPosition === $newPosition) {
return;
}
$isMoveBefore = $action === 'moveBefore'; // otherwise moveAfter
$isMoveForward = $oldPosition < $newPosition;
if ($isMoveForward) {
$this->queryBetween($oldPosition, $newPosition)->decrement($sortableField);
} else {
$this->queryBetween($newPosition, $oldPosition)->increment($sortableField);
}
$this->setAttribute($sortableField, $this->getNewPosition($isMoveBefore, $isMoveForward, $newPosition));
$entity->setAttribute($sortableField, $this->getNewPosition(!$isMoveBefore, $isMoveForward, $newPosition));
$this->save();
$entity->save();
});
} | php | public function move($action, $entity)
{
$this->checkSortableGroupField(static::getSortableGroupField(), $entity);
$this->_transaction(function () use ($entity, $action) {
$sortableField = static::getSortableField();
$oldPosition = $this->getAttribute($sortableField);
$newPosition = $entity->getAttribute($sortableField);
if ($oldPosition === $newPosition) {
return;
}
$isMoveBefore = $action === 'moveBefore'; // otherwise moveAfter
$isMoveForward = $oldPosition < $newPosition;
if ($isMoveForward) {
$this->queryBetween($oldPosition, $newPosition)->decrement($sortableField);
} else {
$this->queryBetween($newPosition, $oldPosition)->increment($sortableField);
}
$this->setAttribute($sortableField, $this->getNewPosition($isMoveBefore, $isMoveForward, $newPosition));
$entity->setAttribute($sortableField, $this->getNewPosition(!$isMoveBefore, $isMoveForward, $newPosition));
$this->save();
$entity->save();
});
} | [
"public",
"function",
"move",
"(",
"$",
"action",
",",
"$",
"entity",
")",
"{",
"$",
"this",
"->",
"checkSortableGroupField",
"(",
"static",
"::",
"getSortableGroupField",
"(",
")",
",",
"$",
"entity",
")",
";",
"$",
"this",
"->",
"_transaction",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"entity",
",",
"$",
"action",
")",
"{",
"$",
"sortableField",
"=",
"static",
"::",
"getSortableField",
"(",
")",
";",
"$",
"oldPosition",
"=",
"$",
"this",
"->",
"getAttribute",
"(",
"$",
"sortableField",
")",
";",
"$",
"newPosition",
"=",
"$",
"entity",
"->",
"getAttribute",
"(",
"$",
"sortableField",
")",
";",
"if",
"(",
"$",
"oldPosition",
"===",
"$",
"newPosition",
")",
"{",
"return",
";",
"}",
"$",
"isMoveBefore",
"=",
"$",
"action",
"===",
"'moveBefore'",
";",
"// otherwise moveAfter",
"$",
"isMoveForward",
"=",
"$",
"oldPosition",
"<",
"$",
"newPosition",
";",
"if",
"(",
"$",
"isMoveForward",
")",
"{",
"$",
"this",
"->",
"queryBetween",
"(",
"$",
"oldPosition",
",",
"$",
"newPosition",
")",
"->",
"decrement",
"(",
"$",
"sortableField",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"queryBetween",
"(",
"$",
"newPosition",
",",
"$",
"oldPosition",
")",
"->",
"increment",
"(",
"$",
"sortableField",
")",
";",
"}",
"$",
"this",
"->",
"setAttribute",
"(",
"$",
"sortableField",
",",
"$",
"this",
"->",
"getNewPosition",
"(",
"$",
"isMoveBefore",
",",
"$",
"isMoveForward",
",",
"$",
"newPosition",
")",
")",
";",
"$",
"entity",
"->",
"setAttribute",
"(",
"$",
"sortableField",
",",
"$",
"this",
"->",
"getNewPosition",
"(",
"!",
"$",
"isMoveBefore",
",",
"$",
"isMoveForward",
",",
"$",
"newPosition",
")",
")",
";",
"$",
"this",
"->",
"save",
"(",
")",
";",
"$",
"entity",
"->",
"save",
"(",
")",
";",
"}",
")",
";",
"}"
] | @param string $action moveAfter/moveBefore
@param Model $entity
@throws SortableException | [
"@param",
"string",
"$action",
"moveAfter",
"/",
"moveBefore",
"@param",
"Model",
"$entity"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableTrait.php#L84-L113 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableTrait.php | SortableTrait.queryBetween | protected function queryBetween($left, $right)
{
$sortableField = static::getSortableField();
$query = static::applySortableGroup($this->newQuery(), $this);
return $query->where($sortableField, '>', $left)->where($sortableField, '<', $right);
} | php | protected function queryBetween($left, $right)
{
$sortableField = static::getSortableField();
$query = static::applySortableGroup($this->newQuery(), $this);
return $query->where($sortableField, '>', $left)->where($sortableField, '<', $right);
} | [
"protected",
"function",
"queryBetween",
"(",
"$",
"left",
",",
"$",
"right",
")",
"{",
"$",
"sortableField",
"=",
"static",
"::",
"getSortableField",
"(",
")",
";",
"$",
"query",
"=",
"static",
"::",
"applySortableGroup",
"(",
"$",
"this",
"->",
"newQuery",
"(",
")",
",",
"$",
"this",
")",
";",
"return",
"$",
"query",
"->",
"where",
"(",
"$",
"sortableField",
",",
"'>'",
",",
"$",
"left",
")",
"->",
"where",
"(",
"$",
"sortableField",
",",
"'<'",
",",
"$",
"right",
")",
";",
"}"
] | @param $left
@param $right
@return QueryBuilder | [
"@param",
"$left",
"@param",
"$right"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableTrait.php#L141-L147 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableTrait.php | SortableTrait.siblings | public function siblings($isNext, $limit = 0)
{
$sortableField = static::getSortableField();
$query = static::applySortableGroup($this->newQuery(), $this);
$query->where($sortableField, $isNext ? '>' : '<', $this->getAttribute($sortableField));
$query->orderBy($sortableField, $isNext ? 'asc' : 'desc');
if ($limit !== 0) {
$query->limit($limit);
}
return $query;
} | php | public function siblings($isNext, $limit = 0)
{
$sortableField = static::getSortableField();
$query = static::applySortableGroup($this->newQuery(), $this);
$query->where($sortableField, $isNext ? '>' : '<', $this->getAttribute($sortableField));
$query->orderBy($sortableField, $isNext ? 'asc' : 'desc');
if ($limit !== 0) {
$query->limit($limit);
}
return $query;
} | [
"public",
"function",
"siblings",
"(",
"$",
"isNext",
",",
"$",
"limit",
"=",
"0",
")",
"{",
"$",
"sortableField",
"=",
"static",
"::",
"getSortableField",
"(",
")",
";",
"$",
"query",
"=",
"static",
"::",
"applySortableGroup",
"(",
"$",
"this",
"->",
"newQuery",
"(",
")",
",",
"$",
"this",
")",
";",
"$",
"query",
"->",
"where",
"(",
"$",
"sortableField",
",",
"$",
"isNext",
"?",
"'>'",
":",
"'<'",
",",
"$",
"this",
"->",
"getAttribute",
"(",
"$",
"sortableField",
")",
")",
";",
"$",
"query",
"->",
"orderBy",
"(",
"$",
"sortableField",
",",
"$",
"isNext",
"?",
"'asc'",
":",
"'desc'",
")",
";",
"if",
"(",
"$",
"limit",
"!==",
"0",
")",
"{",
"$",
"query",
"->",
"limit",
"(",
"$",
"limit",
")",
";",
"}",
"return",
"$",
"query",
";",
"}"
] | @param bool $isNext is next, otherwise before
@param int $limit
@return QueryBuilder | [
"@param",
"bool",
"$isNext",
"is",
"next",
"otherwise",
"before",
"@param",
"int",
"$limit"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableTrait.php#L175-L187 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableTrait.php | SortableTrait.applySortableGroup | protected static function applySortableGroup($query, $model)
{
$sortableGroupField = static::getSortableGroupField();
if (is_array($sortableGroupField)) {
foreach ($sortableGroupField as $field) {
$query = $query->where($field, $model->$field);
}
} elseif ($sortableGroupField !== null) {
$query = $query->where($sortableGroupField, $model->$sortableGroupField);
}
return $query;
} | php | protected static function applySortableGroup($query, $model)
{
$sortableGroupField = static::getSortableGroupField();
if (is_array($sortableGroupField)) {
foreach ($sortableGroupField as $field) {
$query = $query->where($field, $model->$field);
}
} elseif ($sortableGroupField !== null) {
$query = $query->where($sortableGroupField, $model->$sortableGroupField);
}
return $query;
} | [
"protected",
"static",
"function",
"applySortableGroup",
"(",
"$",
"query",
",",
"$",
"model",
")",
"{",
"$",
"sortableGroupField",
"=",
"static",
"::",
"getSortableGroupField",
"(",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"sortableGroupField",
")",
")",
"{",
"foreach",
"(",
"$",
"sortableGroupField",
"as",
"$",
"field",
")",
"{",
"$",
"query",
"=",
"$",
"query",
"->",
"where",
"(",
"$",
"field",
",",
"$",
"model",
"->",
"$",
"field",
")",
";",
"}",
"}",
"elseif",
"(",
"$",
"sortableGroupField",
"!==",
"null",
")",
"{",
"$",
"query",
"=",
"$",
"query",
"->",
"where",
"(",
"$",
"sortableGroupField",
",",
"$",
"model",
"->",
"$",
"sortableGroupField",
")",
";",
"}",
"return",
"$",
"query",
";",
"}"
] | @param QueryBuilder $query
@param Model|SortableTrait $model
@return QueryBuilder | [
"@param",
"QueryBuilder",
"$query",
"@param",
"Model|SortableTrait",
"$model"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableTrait.php#L228-L241 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableTrait.php | SortableTrait.checkSortableGroupField | public function checkSortableGroupField($sortableGroupField, $entity)
{
if (is_array($sortableGroupField)) {
foreach ($sortableGroupField as $field) {
$this->checkFieldEquals($this, $entity, $field);
}
} else {
$this->checkFieldEquals($this, $entity, $sortableGroupField);
}
} | php | public function checkSortableGroupField($sortableGroupField, $entity)
{
if (is_array($sortableGroupField)) {
foreach ($sortableGroupField as $field) {
$this->checkFieldEquals($this, $entity, $field);
}
} else {
$this->checkFieldEquals($this, $entity, $sortableGroupField);
}
} | [
"public",
"function",
"checkSortableGroupField",
"(",
"$",
"sortableGroupField",
",",
"$",
"entity",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"sortableGroupField",
")",
")",
"{",
"foreach",
"(",
"$",
"sortableGroupField",
"as",
"$",
"field",
")",
"{",
"$",
"this",
"->",
"checkFieldEquals",
"(",
"$",
"this",
",",
"$",
"entity",
",",
"$",
"field",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"checkFieldEquals",
"(",
"$",
"this",
",",
"$",
"entity",
",",
"$",
"sortableGroupField",
")",
";",
"}",
"}"
] | @param string|array $sortableGroupField
@param Model $entity
@throws SortableException | [
"@param",
"string|array",
"$sortableGroupField",
"@param",
"Model",
"$entity"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableTrait.php#L269-L278 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/SortableTrait.php | SortableTrait.checkFieldEquals | public function checkFieldEquals($entity1, $entity2, $field)
{
if ($field === null) {
return;
}
if ($entity1->$field !== $entity2->$field) {
throw new SortableException($entity1->$field, $entity2->$field);
}
} | php | public function checkFieldEquals($entity1, $entity2, $field)
{
if ($field === null) {
return;
}
if ($entity1->$field !== $entity2->$field) {
throw new SortableException($entity1->$field, $entity2->$field);
}
} | [
"public",
"function",
"checkFieldEquals",
"(",
"$",
"entity1",
",",
"$",
"entity2",
",",
"$",
"field",
")",
"{",
"if",
"(",
"$",
"field",
"===",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"entity1",
"->",
"$",
"field",
"!==",
"$",
"entity2",
"->",
"$",
"field",
")",
"{",
"throw",
"new",
"SortableException",
"(",
"$",
"entity1",
"->",
"$",
"field",
",",
"$",
"entity2",
"->",
"$",
"field",
")",
";",
"}",
"}"
] | @param Model|SortableTrait $entity1
@param Model $entity2
@param string $field
@throws SortableException | [
"@param",
"Model|SortableTrait",
"$entity1",
"@param",
"Model",
"$entity2",
"@param",
"string",
"$field"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/SortableTrait.php#L287-L296 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/ToSortedManyTrait.php | ToSortedManyTrait.attach | public function attach($id, array $attributes = [], $touch = true)
{
$attributes[$this->getOrderColumnName()] = $this->getNextPosition();
parent::attach($id, $attributes, $touch);
} | php | public function attach($id, array $attributes = [], $touch = true)
{
$attributes[$this->getOrderColumnName()] = $this->getNextPosition();
parent::attach($id, $attributes, $touch);
} | [
"public",
"function",
"attach",
"(",
"$",
"id",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
",",
"$",
"touch",
"=",
"true",
")",
"{",
"$",
"attributes",
"[",
"$",
"this",
"->",
"getOrderColumnName",
"(",
")",
"]",
"=",
"$",
"this",
"->",
"getNextPosition",
"(",
")",
";",
"parent",
"::",
"attach",
"(",
"$",
"id",
",",
"$",
"attributes",
",",
"$",
"touch",
")",
";",
"}"
] | Attach a model to the parent.
@param mixed $id
@param array $attributes
@param bool $touch | [
"Attach",
"a",
"model",
"to",
"the",
"parent",
"."
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/ToSortedManyTrait.php#L31-L36 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/ToSortedManyTrait.php | ToSortedManyTrait.queryBetween | protected function queryBetween($left, $right, $leftIncluded = false, $rightIncluded = false)
{
$positionColumn = $this->getOrderColumnName();
$leftOperator = $leftIncluded ? '>=' : '>';
$rightOperator = $rightIncluded ? '<=' : '<';
$query = $this->newPivotQuery();
return $query->where($positionColumn, $leftOperator, $left)->where($positionColumn, $rightOperator, $right);
} | php | protected function queryBetween($left, $right, $leftIncluded = false, $rightIncluded = false)
{
$positionColumn = $this->getOrderColumnName();
$leftOperator = $leftIncluded ? '>=' : '>';
$rightOperator = $rightIncluded ? '<=' : '<';
$query = $this->newPivotQuery();
return $query->where($positionColumn, $leftOperator, $left)->where($positionColumn, $rightOperator, $right);
} | [
"protected",
"function",
"queryBetween",
"(",
"$",
"left",
",",
"$",
"right",
",",
"$",
"leftIncluded",
"=",
"false",
",",
"$",
"rightIncluded",
"=",
"false",
")",
"{",
"$",
"positionColumn",
"=",
"$",
"this",
"->",
"getOrderColumnName",
"(",
")",
";",
"$",
"leftOperator",
"=",
"$",
"leftIncluded",
"?",
"'>='",
":",
"'>'",
";",
"$",
"rightOperator",
"=",
"$",
"rightIncluded",
"?",
"'<='",
":",
"'<'",
";",
"$",
"query",
"=",
"$",
"this",
"->",
"newPivotQuery",
"(",
")",
";",
"return",
"$",
"query",
"->",
"where",
"(",
"$",
"positionColumn",
",",
"$",
"leftOperator",
",",
"$",
"left",
")",
"->",
"where",
"(",
"$",
"positionColumn",
",",
"$",
"rightOperator",
",",
"$",
"right",
")",
";",
"}"
] | @param $left
@param $right
@param $leftIncluded
@param $rightIncluded
@return \Illuminate\Database\Query\Builder | [
"@param",
"$left",
"@param",
"$right",
"@param",
"$leftIncluded",
"@param",
"$rightIncluded"
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/ToSortedManyTrait.php#L106-L116 |
boxfrommars/rutorika-sortable | src/Rutorika/Sortable/ToSortedManyTrait.php | ToSortedManyTrait.sync | public function sync($ids, $detaching = true)
{
if ($detaching) {
$this->detach();
}
return parent::sync($ids, $detaching);
} | php | public function sync($ids, $detaching = true)
{
if ($detaching) {
$this->detach();
}
return parent::sync($ids, $detaching);
} | [
"public",
"function",
"sync",
"(",
"$",
"ids",
",",
"$",
"detaching",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"detaching",
")",
"{",
"$",
"this",
"->",
"detach",
"(",
")",
";",
"}",
"return",
"parent",
"::",
"sync",
"(",
"$",
"ids",
",",
"$",
"detaching",
")",
";",
"}"
] | Sync the intermediate tables with a list of IDs or collection of models.
@param \Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection|array $ids
@param bool $detaching
@return array | [
"Sync",
"the",
"intermediate",
"tables",
"with",
"a",
"list",
"of",
"IDs",
"or",
"collection",
"of",
"models",
"."
] | train | https://github.com/boxfrommars/rutorika-sortable/blob/7f7719377aa002207530fecd6ee8ccd9c397acb5/src/Rutorika/Sortable/ToSortedManyTrait.php#L146-L153 |
schmittjoh/JMSPaymentPaypalBundle | Client/Client.php | Client.requestSetExpressCheckout | public function requestSetExpressCheckout($amount, $returnUrl, $cancelUrl, array $optionalParameters = array())
{
return $this->sendApiRequest(array_merge($optionalParameters, array(
'METHOD' => 'SetExpressCheckout',
'PAYMENTREQUEST_0_AMT' => $this->convertAmountToPaypalFormat($amount),
'RETURNURL' => $returnUrl,
'CANCELURL' => $cancelUrl,
)));
} | php | public function requestSetExpressCheckout($amount, $returnUrl, $cancelUrl, array $optionalParameters = array())
{
return $this->sendApiRequest(array_merge($optionalParameters, array(
'METHOD' => 'SetExpressCheckout',
'PAYMENTREQUEST_0_AMT' => $this->convertAmountToPaypalFormat($amount),
'RETURNURL' => $returnUrl,
'CANCELURL' => $cancelUrl,
)));
} | [
"public",
"function",
"requestSetExpressCheckout",
"(",
"$",
"amount",
",",
"$",
"returnUrl",
",",
"$",
"cancelUrl",
",",
"array",
"$",
"optionalParameters",
"=",
"array",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"sendApiRequest",
"(",
"array_merge",
"(",
"$",
"optionalParameters",
",",
"array",
"(",
"'METHOD'",
"=>",
"'SetExpressCheckout'",
",",
"'PAYMENTREQUEST_0_AMT'",
"=>",
"$",
"this",
"->",
"convertAmountToPaypalFormat",
"(",
"$",
"amount",
")",
",",
"'RETURNURL'",
"=>",
"$",
"returnUrl",
",",
"'CANCELURL'",
"=>",
"$",
"cancelUrl",
",",
")",
")",
")",
";",
"}"
] | Initiates an ExpressCheckout payment process.
Optional parameters can be found here:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_r_SetExpressCheckout
@param float $amount
@param string $returnUrl
@param string $cancelUrl
@param array $optionalParameters
@return Response | [
"Initiates",
"an",
"ExpressCheckout",
"payment",
"process",
"."
] | train | https://github.com/schmittjoh/JMSPaymentPaypalBundle/blob/7151eaf50f4cdc04273346e2327209e54c2f33de/Client/Client.php#L128-L136 |
schmittjoh/JMSPaymentPaypalBundle | Client/Client.php | Client.urlEncodeArray | protected function urlEncodeArray(array $encode)
{
$encoded = '';
foreach ($encode as $name => $value) {
$encoded .= '&'.urlencode($name).'='.urlencode($value);
}
return substr($encoded, 1);
} | php | protected function urlEncodeArray(array $encode)
{
$encoded = '';
foreach ($encode as $name => $value) {
$encoded .= '&'.urlencode($name).'='.urlencode($value);
}
return substr($encoded, 1);
} | [
"protected",
"function",
"urlEncodeArray",
"(",
"array",
"$",
"encode",
")",
"{",
"$",
"encoded",
"=",
"''",
";",
"foreach",
"(",
"$",
"encode",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"$",
"encoded",
".=",
"'&'",
".",
"urlencode",
"(",
"$",
"name",
")",
".",
"'='",
".",
"urlencode",
"(",
"$",
"value",
")",
";",
"}",
"return",
"substr",
"(",
"$",
"encoded",
",",
"1",
")",
";",
"}"
] | A small helper to url-encode an array.
@param array $encode
@return string | [
"A",
"small",
"helper",
"to",
"url",
"-",
"encode",
"an",
"array",
"."
] | train | https://github.com/schmittjoh/JMSPaymentPaypalBundle/blob/7151eaf50f4cdc04273346e2327209e54c2f33de/Client/Client.php#L217-L225 |
schmittjoh/JMSPaymentPaypalBundle | Client/Client.php | Client.request | public function request(Request $request)
{
if (!extension_loaded('curl')) {
throw new \RuntimeException('The cURL extension must be loaded.');
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, $this->curlOptions);
curl_setopt($curl, CURLOPT_URL, $request->getUri());
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
// add headers
$headers = array();
foreach ($request->headers->all() as $name => $value) {
if (is_array($value)) {
foreach ($value as $subValue) {
$headers[] = sprintf('%s: %s', $name, $subValue);
}
} else {
$headers[] = sprintf('%s: %s', $name, $value);
}
}
if (count($headers) > 0) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
// set method
$method = strtoupper($request->getMethod());
if ('POST' === $method) {
curl_setopt($curl, CURLOPT_POST, true);
if (!$request->headers->has('Content-Type') || 'multipart/form-data' !== $request->headers->get('Content-Type')) {
$postFields = $this->urlEncodeArray($request->request->all());
} else {
$postFields = $request->request->all();
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
} elseif ('PUT' === $method) {
curl_setopt($curl, CURLOPT_PUT, true);
} elseif ('HEAD' === $method) {
curl_setopt($curl, CURLOPT_NOBODY, true);
}
// perform the request
if (false === $returnTransfer = curl_exec($curl)) {
throw new CommunicationException(
'cURL Error: '.curl_error($curl), curl_errno($curl)
);
}
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = array();
if (preg_match_all('#^([^:\r\n]+):\s+([^\n\r]+)#m', substr($returnTransfer, 0, $headerSize), $matches)) {
foreach ($matches[1] as $key => $name) {
$headers[$name] = $matches[2][$key];
}
}
$response = new RawResponse(
substr($returnTransfer, $headerSize),
curl_getinfo($curl, CURLINFO_HTTP_CODE),
$headers
);
curl_close($curl);
return $response;
} | php | public function request(Request $request)
{
if (!extension_loaded('curl')) {
throw new \RuntimeException('The cURL extension must be loaded.');
}
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, $this->curlOptions);
curl_setopt($curl, CURLOPT_URL, $request->getUri());
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
// add headers
$headers = array();
foreach ($request->headers->all() as $name => $value) {
if (is_array($value)) {
foreach ($value as $subValue) {
$headers[] = sprintf('%s: %s', $name, $subValue);
}
} else {
$headers[] = sprintf('%s: %s', $name, $value);
}
}
if (count($headers) > 0) {
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
// set method
$method = strtoupper($request->getMethod());
if ('POST' === $method) {
curl_setopt($curl, CURLOPT_POST, true);
if (!$request->headers->has('Content-Type') || 'multipart/form-data' !== $request->headers->get('Content-Type')) {
$postFields = $this->urlEncodeArray($request->request->all());
} else {
$postFields = $request->request->all();
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
} elseif ('PUT' === $method) {
curl_setopt($curl, CURLOPT_PUT, true);
} elseif ('HEAD' === $method) {
curl_setopt($curl, CURLOPT_NOBODY, true);
}
// perform the request
if (false === $returnTransfer = curl_exec($curl)) {
throw new CommunicationException(
'cURL Error: '.curl_error($curl), curl_errno($curl)
);
}
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = array();
if (preg_match_all('#^([^:\r\n]+):\s+([^\n\r]+)#m', substr($returnTransfer, 0, $headerSize), $matches)) {
foreach ($matches[1] as $key => $name) {
$headers[$name] = $matches[2][$key];
}
}
$response = new RawResponse(
substr($returnTransfer, $headerSize),
curl_getinfo($curl, CURLINFO_HTTP_CODE),
$headers
);
curl_close($curl);
return $response;
} | [
"public",
"function",
"request",
"(",
"Request",
"$",
"request",
")",
"{",
"if",
"(",
"!",
"extension_loaded",
"(",
"'curl'",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'The cURL extension must be loaded.'",
")",
";",
"}",
"$",
"curl",
"=",
"curl_init",
"(",
")",
";",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_SSL_VERIFYHOST",
",",
"false",
")",
";",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_SSL_VERIFYPEER",
",",
"false",
")",
";",
"curl_setopt_array",
"(",
"$",
"curl",
",",
"$",
"this",
"->",
"curlOptions",
")",
";",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_URL",
",",
"$",
"request",
"->",
"getUri",
"(",
")",
")",
";",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_RETURNTRANSFER",
",",
"true",
")",
";",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_HEADER",
",",
"true",
")",
";",
"// add headers",
"$",
"headers",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"request",
"->",
"headers",
"->",
"all",
"(",
")",
"as",
"$",
"name",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"foreach",
"(",
"$",
"value",
"as",
"$",
"subValue",
")",
"{",
"$",
"headers",
"[",
"]",
"=",
"sprintf",
"(",
"'%s: %s'",
",",
"$",
"name",
",",
"$",
"subValue",
")",
";",
"}",
"}",
"else",
"{",
"$",
"headers",
"[",
"]",
"=",
"sprintf",
"(",
"'%s: %s'",
",",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"}",
"if",
"(",
"count",
"(",
"$",
"headers",
")",
">",
"0",
")",
"{",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_HTTPHEADER",
",",
"$",
"headers",
")",
";",
"}",
"// set method",
"$",
"method",
"=",
"strtoupper",
"(",
"$",
"request",
"->",
"getMethod",
"(",
")",
")",
";",
"if",
"(",
"'POST'",
"===",
"$",
"method",
")",
"{",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_POST",
",",
"true",
")",
";",
"if",
"(",
"!",
"$",
"request",
"->",
"headers",
"->",
"has",
"(",
"'Content-Type'",
")",
"||",
"'multipart/form-data'",
"!==",
"$",
"request",
"->",
"headers",
"->",
"get",
"(",
"'Content-Type'",
")",
")",
"{",
"$",
"postFields",
"=",
"$",
"this",
"->",
"urlEncodeArray",
"(",
"$",
"request",
"->",
"request",
"->",
"all",
"(",
")",
")",
";",
"}",
"else",
"{",
"$",
"postFields",
"=",
"$",
"request",
"->",
"request",
"->",
"all",
"(",
")",
";",
"}",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_POSTFIELDS",
",",
"$",
"postFields",
")",
";",
"}",
"elseif",
"(",
"'PUT'",
"===",
"$",
"method",
")",
"{",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_PUT",
",",
"true",
")",
";",
"}",
"elseif",
"(",
"'HEAD'",
"===",
"$",
"method",
")",
"{",
"curl_setopt",
"(",
"$",
"curl",
",",
"CURLOPT_NOBODY",
",",
"true",
")",
";",
"}",
"// perform the request",
"if",
"(",
"false",
"===",
"$",
"returnTransfer",
"=",
"curl_exec",
"(",
"$",
"curl",
")",
")",
"{",
"throw",
"new",
"CommunicationException",
"(",
"'cURL Error: '",
".",
"curl_error",
"(",
"$",
"curl",
")",
",",
"curl_errno",
"(",
"$",
"curl",
")",
")",
";",
"}",
"$",
"headerSize",
"=",
"curl_getinfo",
"(",
"$",
"curl",
",",
"CURLINFO_HEADER_SIZE",
")",
";",
"$",
"headers",
"=",
"array",
"(",
")",
";",
"if",
"(",
"preg_match_all",
"(",
"'#^([^:\\r\\n]+):\\s+([^\\n\\r]+)#m'",
",",
"substr",
"(",
"$",
"returnTransfer",
",",
"0",
",",
"$",
"headerSize",
")",
",",
"$",
"matches",
")",
")",
"{",
"foreach",
"(",
"$",
"matches",
"[",
"1",
"]",
"as",
"$",
"key",
"=>",
"$",
"name",
")",
"{",
"$",
"headers",
"[",
"$",
"name",
"]",
"=",
"$",
"matches",
"[",
"2",
"]",
"[",
"$",
"key",
"]",
";",
"}",
"}",
"$",
"response",
"=",
"new",
"RawResponse",
"(",
"substr",
"(",
"$",
"returnTransfer",
",",
"$",
"headerSize",
")",
",",
"curl_getinfo",
"(",
"$",
"curl",
",",
"CURLINFO_HTTP_CODE",
")",
",",
"$",
"headers",
")",
";",
"curl_close",
"(",
"$",
"curl",
")",
";",
"return",
"$",
"response",
";",
"}"
] | Performs a request to an external payment service.
@throws CommunicationException when an curl error occurs
@throws \RuntimeException
@param Request $request
@return RawResponse | [
"Performs",
"a",
"request",
"to",
"an",
"external",
"payment",
"service",
"."
] | train | https://github.com/schmittjoh/JMSPaymentPaypalBundle/blob/7151eaf50f4cdc04273346e2327209e54c2f33de/Client/Client.php#L237-L307 |
schmittjoh/JMSPaymentPaypalBundle | Plugin/ExpressCheckoutPlugin.php | ExpressCheckoutPlugin.obtainExpressCheckoutToken | protected function obtainExpressCheckoutToken(FinancialTransactionInterface $transaction, $paymentAction)
{
$data = $transaction->getExtendedData();
if ($data->has('express_checkout_token')) {
return $data->get('express_checkout_token');
}
$opts = $data->has('checkout_params') ? $data->get('checkout_params') : array();
$opts['PAYMENTREQUEST_0_PAYMENTACTION'] = $paymentAction;
$opts['PAYMENTREQUEST_0_CURRENCYCODE'] = $transaction->getPayment()->getPaymentInstruction()->getCurrency();
$response = $this->client->requestSetExpressCheckout(
$transaction->getRequestedAmount(),
$this->getReturnUrl($data),
$this->getCancelUrl($data),
$opts
);
$this->throwUnlessSuccessResponse($response, $transaction);
$data->set('express_checkout_token', $response->body->get('TOKEN'));
$this->throwActionRequired($response->body->get('TOKEN'), $data, $transaction);
} | php | protected function obtainExpressCheckoutToken(FinancialTransactionInterface $transaction, $paymentAction)
{
$data = $transaction->getExtendedData();
if ($data->has('express_checkout_token')) {
return $data->get('express_checkout_token');
}
$opts = $data->has('checkout_params') ? $data->get('checkout_params') : array();
$opts['PAYMENTREQUEST_0_PAYMENTACTION'] = $paymentAction;
$opts['PAYMENTREQUEST_0_CURRENCYCODE'] = $transaction->getPayment()->getPaymentInstruction()->getCurrency();
$response = $this->client->requestSetExpressCheckout(
$transaction->getRequestedAmount(),
$this->getReturnUrl($data),
$this->getCancelUrl($data),
$opts
);
$this->throwUnlessSuccessResponse($response, $transaction);
$data->set('express_checkout_token', $response->body->get('TOKEN'));
$this->throwActionRequired($response->body->get('TOKEN'), $data, $transaction);
} | [
"protected",
"function",
"obtainExpressCheckoutToken",
"(",
"FinancialTransactionInterface",
"$",
"transaction",
",",
"$",
"paymentAction",
")",
"{",
"$",
"data",
"=",
"$",
"transaction",
"->",
"getExtendedData",
"(",
")",
";",
"if",
"(",
"$",
"data",
"->",
"has",
"(",
"'express_checkout_token'",
")",
")",
"{",
"return",
"$",
"data",
"->",
"get",
"(",
"'express_checkout_token'",
")",
";",
"}",
"$",
"opts",
"=",
"$",
"data",
"->",
"has",
"(",
"'checkout_params'",
")",
"?",
"$",
"data",
"->",
"get",
"(",
"'checkout_params'",
")",
":",
"array",
"(",
")",
";",
"$",
"opts",
"[",
"'PAYMENTREQUEST_0_PAYMENTACTION'",
"]",
"=",
"$",
"paymentAction",
";",
"$",
"opts",
"[",
"'PAYMENTREQUEST_0_CURRENCYCODE'",
"]",
"=",
"$",
"transaction",
"->",
"getPayment",
"(",
")",
"->",
"getPaymentInstruction",
"(",
")",
"->",
"getCurrency",
"(",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"requestSetExpressCheckout",
"(",
"$",
"transaction",
"->",
"getRequestedAmount",
"(",
")",
",",
"$",
"this",
"->",
"getReturnUrl",
"(",
"$",
"data",
")",
",",
"$",
"this",
"->",
"getCancelUrl",
"(",
"$",
"data",
")",
",",
"$",
"opts",
")",
";",
"$",
"this",
"->",
"throwUnlessSuccessResponse",
"(",
"$",
"response",
",",
"$",
"transaction",
")",
";",
"$",
"data",
"->",
"set",
"(",
"'express_checkout_token'",
",",
"$",
"response",
"->",
"body",
"->",
"get",
"(",
"'TOKEN'",
")",
")",
";",
"$",
"this",
"->",
"throwActionRequired",
"(",
"$",
"response",
"->",
"body",
"->",
"get",
"(",
"'TOKEN'",
")",
",",
"$",
"data",
",",
"$",
"transaction",
")",
";",
"}"
] | @param \JMS\Payment\CoreBundle\Model\FinancialTransactionInterface $transaction
@param string $paymentAction
@throws \JMS\Payment\CoreBundle\Plugin\Exception\ActionRequiredException if user has to authenticate the token
@return string | [
"@param",
"\\",
"JMS",
"\\",
"Payment",
"\\",
"CoreBundle",
"\\",
"Model",
"\\",
"FinancialTransactionInterface",
"$transaction",
"@param",
"string",
"$paymentAction"
] | train | https://github.com/schmittjoh/JMSPaymentPaypalBundle/blob/7151eaf50f4cdc04273346e2327209e54c2f33de/Plugin/ExpressCheckoutPlugin.php#L249-L271 |
schmittjoh/JMSPaymentPaypalBundle | Plugin/ExpressCheckoutPlugin.php | ExpressCheckoutPlugin.throwUnlessSuccessResponse | protected function throwUnlessSuccessResponse(Response $response, FinancialTransactionInterface $transaction)
{
if ($response->isSuccess()) {
return;
}
$transaction->setResponseCode($response->body->get('ACK'));
$transaction->setReasonCode($response->body->get('L_ERRORCODE0'));
$ex = new FinancialException('PayPal-Response was not successful: '.$response);
$ex->setFinancialTransaction($transaction);
throw $ex;
} | php | protected function throwUnlessSuccessResponse(Response $response, FinancialTransactionInterface $transaction)
{
if ($response->isSuccess()) {
return;
}
$transaction->setResponseCode($response->body->get('ACK'));
$transaction->setReasonCode($response->body->get('L_ERRORCODE0'));
$ex = new FinancialException('PayPal-Response was not successful: '.$response);
$ex->setFinancialTransaction($transaction);
throw $ex;
} | [
"protected",
"function",
"throwUnlessSuccessResponse",
"(",
"Response",
"$",
"response",
",",
"FinancialTransactionInterface",
"$",
"transaction",
")",
"{",
"if",
"(",
"$",
"response",
"->",
"isSuccess",
"(",
")",
")",
"{",
"return",
";",
"}",
"$",
"transaction",
"->",
"setResponseCode",
"(",
"$",
"response",
"->",
"body",
"->",
"get",
"(",
"'ACK'",
")",
")",
";",
"$",
"transaction",
"->",
"setReasonCode",
"(",
"$",
"response",
"->",
"body",
"->",
"get",
"(",
"'L_ERRORCODE0'",
")",
")",
";",
"$",
"ex",
"=",
"new",
"FinancialException",
"(",
"'PayPal-Response was not successful: '",
".",
"$",
"response",
")",
";",
"$",
"ex",
"->",
"setFinancialTransaction",
"(",
"$",
"transaction",
")",
";",
"throw",
"$",
"ex",
";",
"}"
] | @param \JMS\Payment\CoreBundle\Model\FinancialTransactionInterface $transaction
@param \JMS\Payment\PaypalBundle\Client\Response $response
@throws \JMS\Payment\CoreBundle\Plugin\Exception\FinancialException | [
"@param",
"\\",
"JMS",
"\\",
"Payment",
"\\",
"CoreBundle",
"\\",
"Model",
"\\",
"FinancialTransactionInterface",
"$transaction",
"@param",
"\\",
"JMS",
"\\",
"Payment",
"\\",
"PaypalBundle",
"\\",
"Client",
"\\",
"Response",
"$response"
] | train | https://github.com/schmittjoh/JMSPaymentPaypalBundle/blob/7151eaf50f4cdc04273346e2327209e54c2f33de/Plugin/ExpressCheckoutPlugin.php#L279-L292 |
schmittjoh/JMSPaymentPaypalBundle | Plugin/ExpressCheckoutPlugin.php | ExpressCheckoutPlugin.throwActionRequired | protected function throwActionRequired($token, $data, $transaction)
{
$ex = new ActionRequiredException('User must authorize the transaction.');
$ex->setFinancialTransaction($transaction);
$params = array();
if ($useraction = $this->getUserAction($data)) {
$params['useraction'] = $this->getUserAction($data);
}
$ex->setAction(new VisitUrl(
$this->client->getAuthenticateExpressCheckoutTokenUrl($token, $params)
));
throw $ex;
} | php | protected function throwActionRequired($token, $data, $transaction)
{
$ex = new ActionRequiredException('User must authorize the transaction.');
$ex->setFinancialTransaction($transaction);
$params = array();
if ($useraction = $this->getUserAction($data)) {
$params['useraction'] = $this->getUserAction($data);
}
$ex->setAction(new VisitUrl(
$this->client->getAuthenticateExpressCheckoutTokenUrl($token, $params)
));
throw $ex;
} | [
"protected",
"function",
"throwActionRequired",
"(",
"$",
"token",
",",
"$",
"data",
",",
"$",
"transaction",
")",
"{",
"$",
"ex",
"=",
"new",
"ActionRequiredException",
"(",
"'User must authorize the transaction.'",
")",
";",
"$",
"ex",
"->",
"setFinancialTransaction",
"(",
"$",
"transaction",
")",
";",
"$",
"params",
"=",
"array",
"(",
")",
";",
"if",
"(",
"$",
"useraction",
"=",
"$",
"this",
"->",
"getUserAction",
"(",
"$",
"data",
")",
")",
"{",
"$",
"params",
"[",
"'useraction'",
"]",
"=",
"$",
"this",
"->",
"getUserAction",
"(",
"$",
"data",
")",
";",
"}",
"$",
"ex",
"->",
"setAction",
"(",
"new",
"VisitUrl",
"(",
"$",
"this",
"->",
"client",
"->",
"getAuthenticateExpressCheckoutTokenUrl",
"(",
"$",
"token",
",",
"$",
"params",
")",
")",
")",
";",
"throw",
"$",
"ex",
";",
"}"
] | @param string $token
@param \JMS\Payment\CoreBundle\Model\ExtendedDataInterface $data
@param \JMS\Payment\CoreBundle\Model\FinancialTransactionInterface $transaction
@throws \JMS\Payment\CoreBundle\Plugin\Exception\ActionRequiredException | [
"@param",
"string",
"$token",
"@param",
"\\",
"JMS",
"\\",
"Payment",
"\\",
"CoreBundle",
"\\",
"Model",
"\\",
"ExtendedDataInterface",
"$data",
"@param",
"\\",
"JMS",
"\\",
"Payment",
"\\",
"CoreBundle",
"\\",
"Model",
"\\",
"FinancialTransactionInterface",
"$transaction"
] | train | https://github.com/schmittjoh/JMSPaymentPaypalBundle/blob/7151eaf50f4cdc04273346e2327209e54c2f33de/Plugin/ExpressCheckoutPlugin.php#L301-L317 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/Installer.php | Installer.postInstall | public static function postInstall(CommandEvent $event)
{
// Detect path to composer.json
self::setInstallPath(
self::retrieveInstallPath()
);
// We must include autoloader - funny.
require_once self::getInstallPath() . DIRECTORY_SEPARATOR . 'vendor/autoload.php';
// Store extra from composer
self::setExtra(
$event->getComposer()->getPackage()->getExtra()
);
// Force colors
\cli\Colors::enable();
// Process event
return self::handleEvent($event);
} | php | public static function postInstall(CommandEvent $event)
{
// Detect path to composer.json
self::setInstallPath(
self::retrieveInstallPath()
);
// We must include autoloader - funny.
require_once self::getInstallPath() . DIRECTORY_SEPARATOR . 'vendor/autoload.php';
// Store extra from composer
self::setExtra(
$event->getComposer()->getPackage()->getExtra()
);
// Force colors
\cli\Colors::enable();
// Process event
return self::handleEvent($event);
} | [
"public",
"static",
"function",
"postInstall",
"(",
"CommandEvent",
"$",
"event",
")",
"{",
"// Detect path to composer.json",
"self",
"::",
"setInstallPath",
"(",
"self",
"::",
"retrieveInstallPath",
"(",
")",
")",
";",
"// We must include autoloader - funny.",
"require_once",
"self",
"::",
"getInstallPath",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"'vendor/autoload.php'",
";",
"// Store extra from composer",
"self",
"::",
"setExtra",
"(",
"$",
"event",
"->",
"getComposer",
"(",
")",
"->",
"getPackage",
"(",
")",
"->",
"getExtra",
"(",
")",
")",
";",
"// Force colors",
"\\",
"cli",
"\\",
"Colors",
"::",
"enable",
"(",
")",
";",
"// Process event",
"return",
"self",
"::",
"handleEvent",
"(",
"$",
"event",
")",
";",
"}"
] | Installer process for project based on post install event hook on composer.
@param CommandEvent $event The event passed in by Composer.
@author Benjamin Carl <opensource@clickalicious.de>
@return boolean|null TRUE on success, otherwise FALSE (signal for Composer to resolve with error)
@access public
@static | [
"Installer",
"process",
"for",
"project",
"based",
"on",
"post",
"install",
"event",
"hook",
"on",
"composer",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/Installer.php#L138-L158 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/Installer.php | Installer.handleEvent | protected static function handleEvent(CommandEvent $event)
{
$valid = false;
// Construct menus ...
$menu1 = array(
'install' => \cli\Colors::colorize('%N%gInstall ' . self::PROJECT_NAME_SHORT . '%N'),
'quit' => \cli\Colors::colorize('%N%rQuit %N'),
);
$menu2 = \cli\Colors::colorize('%NInstall to %g' . self::getInstallPath() . ' %N');
$menu3 = array(
'change' => \cli\Colors::colorize('%N%gChange path to install%N'),
'quit' => \cli\Colors::colorize('%N%rQuit%N'),
);
$menu4 = 'Enter path';
// Show the big old school banner - yeah i like :)
self::showBanner();
// Retrieve and store arguments
self::initArguments($event);
// show Version information
self::showVersion();
// Begin CLI loop
while (true) {
// Ask for OK for install in general ...
$resolved = self::resolveTree($menu1, 'install');
if ($resolved === 'quit') {
break;
} else {
// Ask if autodetected install path is ok ...
$resolved = self::resolveChoice($menu2);
if ($resolved === 'y') {
// Try to validate and use the auto detected path ...
try {
$path = self::validatePath(self::getInstallPath());
$valid = true;
} catch (Exception $e) {
return self::showError($e->getMessage());
}
// If operation failed above -> Ask user for alternative path to install
if ($valid !== true) {
self::showError('Automatic detected path seems to be invalid. Please choose another path!');
$path = self::askAlternatePath($menu4);
}
} else {
// Check for alternate path ...
$resolved = self::resolveTree($menu3, 'change');
// If user decided to change the path
if ($resolved === 'change') {
// If operation failed above -> Ask user for path to install
$valid = self::askAlternatePath($menu4);
} else {
// Quit
break;
}
}
// Check if alternate path also failed in case of exception ...
if ($valid === true) {
if (self::install(self::getInstallPath() . DIRECTORY_SEPARATOR) === true) {
self::showSuccess();
self::showVhostExample(self::getInstallPath() . DIRECTORY_SEPARATOR);
self::showOutro(self::getInstallPath());
} else {
self::showFailed();
}
}
}
// OK, continue on to composer install
return $valid;
}
// Something failed and we ended up here.
return false;
} | php | protected static function handleEvent(CommandEvent $event)
{
$valid = false;
// Construct menus ...
$menu1 = array(
'install' => \cli\Colors::colorize('%N%gInstall ' . self::PROJECT_NAME_SHORT . '%N'),
'quit' => \cli\Colors::colorize('%N%rQuit %N'),
);
$menu2 = \cli\Colors::colorize('%NInstall to %g' . self::getInstallPath() . ' %N');
$menu3 = array(
'change' => \cli\Colors::colorize('%N%gChange path to install%N'),
'quit' => \cli\Colors::colorize('%N%rQuit%N'),
);
$menu4 = 'Enter path';
// Show the big old school banner - yeah i like :)
self::showBanner();
// Retrieve and store arguments
self::initArguments($event);
// show Version information
self::showVersion();
// Begin CLI loop
while (true) {
// Ask for OK for install in general ...
$resolved = self::resolveTree($menu1, 'install');
if ($resolved === 'quit') {
break;
} else {
// Ask if autodetected install path is ok ...
$resolved = self::resolveChoice($menu2);
if ($resolved === 'y') {
// Try to validate and use the auto detected path ...
try {
$path = self::validatePath(self::getInstallPath());
$valid = true;
} catch (Exception $e) {
return self::showError($e->getMessage());
}
// If operation failed above -> Ask user for alternative path to install
if ($valid !== true) {
self::showError('Automatic detected path seems to be invalid. Please choose another path!');
$path = self::askAlternatePath($menu4);
}
} else {
// Check for alternate path ...
$resolved = self::resolveTree($menu3, 'change');
// If user decided to change the path
if ($resolved === 'change') {
// If operation failed above -> Ask user for path to install
$valid = self::askAlternatePath($menu4);
} else {
// Quit
break;
}
}
// Check if alternate path also failed in case of exception ...
if ($valid === true) {
if (self::install(self::getInstallPath() . DIRECTORY_SEPARATOR) === true) {
self::showSuccess();
self::showVhostExample(self::getInstallPath() . DIRECTORY_SEPARATOR);
self::showOutro(self::getInstallPath());
} else {
self::showFailed();
}
}
}
// OK, continue on to composer install
return $valid;
}
// Something failed and we ended up here.
return false;
} | [
"protected",
"static",
"function",
"handleEvent",
"(",
"CommandEvent",
"$",
"event",
")",
"{",
"$",
"valid",
"=",
"false",
";",
"// Construct menus ...",
"$",
"menu1",
"=",
"array",
"(",
"'install'",
"=>",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%gInstall '",
".",
"self",
"::",
"PROJECT_NAME_SHORT",
".",
"'%N'",
")",
",",
"'quit'",
"=>",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%rQuit %N'",
")",
",",
")",
";",
"$",
"menu2",
"=",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%NInstall to %g'",
".",
"self",
"::",
"getInstallPath",
"(",
")",
".",
"' %N'",
")",
";",
"$",
"menu3",
"=",
"array",
"(",
"'change'",
"=>",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%gChange path to install%N'",
")",
",",
"'quit'",
"=>",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%rQuit%N'",
")",
",",
")",
";",
"$",
"menu4",
"=",
"'Enter path'",
";",
"// Show the big old school banner - yeah i like :)",
"self",
"::",
"showBanner",
"(",
")",
";",
"// Retrieve and store arguments",
"self",
"::",
"initArguments",
"(",
"$",
"event",
")",
";",
"// show Version information",
"self",
"::",
"showVersion",
"(",
")",
";",
"// Begin CLI loop",
"while",
"(",
"true",
")",
"{",
"// Ask for OK for install in general ...",
"$",
"resolved",
"=",
"self",
"::",
"resolveTree",
"(",
"$",
"menu1",
",",
"'install'",
")",
";",
"if",
"(",
"$",
"resolved",
"===",
"'quit'",
")",
"{",
"break",
";",
"}",
"else",
"{",
"// Ask if autodetected install path is ok ...",
"$",
"resolved",
"=",
"self",
"::",
"resolveChoice",
"(",
"$",
"menu2",
")",
";",
"if",
"(",
"$",
"resolved",
"===",
"'y'",
")",
"{",
"// Try to validate and use the auto detected path ...",
"try",
"{",
"$",
"path",
"=",
"self",
"::",
"validatePath",
"(",
"self",
"::",
"getInstallPath",
"(",
")",
")",
";",
"$",
"valid",
"=",
"true",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"self",
"::",
"showError",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"}",
"// If operation failed above -> Ask user for alternative path to install",
"if",
"(",
"$",
"valid",
"!==",
"true",
")",
"{",
"self",
"::",
"showError",
"(",
"'Automatic detected path seems to be invalid. Please choose another path!'",
")",
";",
"$",
"path",
"=",
"self",
"::",
"askAlternatePath",
"(",
"$",
"menu4",
")",
";",
"}",
"}",
"else",
"{",
"// Check for alternate path ...",
"$",
"resolved",
"=",
"self",
"::",
"resolveTree",
"(",
"$",
"menu3",
",",
"'change'",
")",
";",
"// If user decided to change the path",
"if",
"(",
"$",
"resolved",
"===",
"'change'",
")",
"{",
"// If operation failed above -> Ask user for path to install",
"$",
"valid",
"=",
"self",
"::",
"askAlternatePath",
"(",
"$",
"menu4",
")",
";",
"}",
"else",
"{",
"// Quit",
"break",
";",
"}",
"}",
"// Check if alternate path also failed in case of exception ...",
"if",
"(",
"$",
"valid",
"===",
"true",
")",
"{",
"if",
"(",
"self",
"::",
"install",
"(",
"self",
"::",
"getInstallPath",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
")",
"===",
"true",
")",
"{",
"self",
"::",
"showSuccess",
"(",
")",
";",
"self",
"::",
"showVhostExample",
"(",
"self",
"::",
"getInstallPath",
"(",
")",
".",
"DIRECTORY_SEPARATOR",
")",
";",
"self",
"::",
"showOutro",
"(",
"self",
"::",
"getInstallPath",
"(",
")",
")",
";",
"}",
"else",
"{",
"self",
"::",
"showFailed",
"(",
")",
";",
"}",
"}",
"}",
"// OK, continue on to composer install",
"return",
"$",
"valid",
";",
"}",
"// Something failed and we ended up here.",
"return",
"false",
";",
"}"
] | Handles a received event - dispatcher.
@author Benjamin Carl <opensource@clickalicious.de>
@return boolean|null TRUE on success, otherwise FALSE
@access protected | [
"Handles",
"a",
"received",
"event",
"-",
"dispatcher",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/Installer.php#L167-L254 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/Installer.php | Installer.showSuccess | protected static function showSuccess()
{
\cli\line();
\cli\line(
\cli\Colors::colorize('%N%n%gInstallation of %y' . self::PROJECT_NAME_SHORT . '%g was successful.%N%n')
);
return true;
} | php | protected static function showSuccess()
{
\cli\line();
\cli\line(
\cli\Colors::colorize('%N%n%gInstallation of %y' . self::PROJECT_NAME_SHORT . '%g was successful.%N%n')
);
return true;
} | [
"protected",
"static",
"function",
"showSuccess",
"(",
")",
"{",
"\\",
"cli",
"\\",
"line",
"(",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%n%gInstallation of %y'",
".",
"self",
"::",
"PROJECT_NAME_SHORT",
".",
"'%g was successful.%N%n'",
")",
")",
";",
"return",
"true",
";",
"}"
] | Shows the success message after install was successful.
@author Benjamin Carl <opensource@clickalicious.de>
@return boolean
@access protected
@static | [
"Shows",
"the",
"success",
"message",
"after",
"install",
"was",
"successful",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/Installer.php#L286-L294 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/Installer.php | Installer.showFailed | protected static function showFailed()
{
\cli\line();
\cli\line(
\cli\Colors::colorize('%N%n%1Installation of ' . self::PROJECT_NAME_SHORT . ' failed.%N%n')
);
} | php | protected static function showFailed()
{
\cli\line();
\cli\line(
\cli\Colors::colorize('%N%n%1Installation of ' . self::PROJECT_NAME_SHORT . ' failed.%N%n')
);
} | [
"protected",
"static",
"function",
"showFailed",
"(",
")",
"{",
"\\",
"cli",
"\\",
"line",
"(",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%n%1Installation of '",
".",
"self",
"::",
"PROJECT_NAME_SHORT",
".",
"' failed.%N%n'",
")",
")",
";",
"}"
] | Shows the failed message after install failed.
@author Benjamin Carl <opensource@clickalicious.de>
@return void
@access protected
@static | [
"Shows",
"the",
"failed",
"message",
"after",
"install",
"failed",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/Installer.php#L342-L348 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/Installer.php | Installer.showOutro | protected static function showOutro($projectRoot = 'n.a.')
{
\cli\line();
\cli\line(\cli\Colors::colorize(
'%nEnjoy your installation of %y' . self::PROJECT_NAME_SHORT . ' (document root: "' . $projectRoot . '")%n')
);
\cli\line();
} | php | protected static function showOutro($projectRoot = 'n.a.')
{
\cli\line();
\cli\line(\cli\Colors::colorize(
'%nEnjoy your installation of %y' . self::PROJECT_NAME_SHORT . ' (document root: "' . $projectRoot . '")%n')
);
\cli\line();
} | [
"protected",
"static",
"function",
"showOutro",
"(",
"$",
"projectRoot",
"=",
"'n.a.'",
")",
"{",
"\\",
"cli",
"\\",
"line",
"(",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%nEnjoy your installation of %y'",
".",
"self",
"::",
"PROJECT_NAME_SHORT",
".",
"' (document root: \"'",
".",
"$",
"projectRoot",
".",
"'\")%n'",
")",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
")",
";",
"}"
] | Shows the outro message after install succeeded to inform about management console.
@author Benjamin Carl <opensource@clickalicious.de>
@return void
@access protected
@static | [
"Shows",
"the",
"outro",
"message",
"after",
"install",
"succeeded",
"to",
"inform",
"about",
"management",
"console",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/Installer.php#L358-L365 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/Installer.php | Installer.install | protected static function install($targetDirectory)
{
$notify = new \cli\notify\Spinner(\cli\Colors::colorize('%N%n%yInstalling ...%N%n'), 100);
// Define source & destination
$source = self::getSourcePath();
$destination = $targetDirectory;
// Iterate and copy ...
foreach (self::getFolders() as $folder) {
self::xcopy($source . $folder, $destination . $folder);
}
$notify->finish();
return true;
} | php | protected static function install($targetDirectory)
{
$notify = new \cli\notify\Spinner(\cli\Colors::colorize('%N%n%yInstalling ...%N%n'), 100);
// Define source & destination
$source = self::getSourcePath();
$destination = $targetDirectory;
// Iterate and copy ...
foreach (self::getFolders() as $folder) {
self::xcopy($source . $folder, $destination . $folder);
}
$notify->finish();
return true;
} | [
"protected",
"static",
"function",
"install",
"(",
"$",
"targetDirectory",
")",
"{",
"$",
"notify",
"=",
"new",
"\\",
"cli",
"\\",
"notify",
"\\",
"Spinner",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%n%yInstalling ...%N%n'",
")",
",",
"100",
")",
";",
"// Define source & destination",
"$",
"source",
"=",
"self",
"::",
"getSourcePath",
"(",
")",
";",
"$",
"destination",
"=",
"$",
"targetDirectory",
";",
"// Iterate and copy ...",
"foreach",
"(",
"self",
"::",
"getFolders",
"(",
")",
"as",
"$",
"folder",
")",
"{",
"self",
"::",
"xcopy",
"(",
"$",
"source",
".",
"$",
"folder",
",",
"$",
"destination",
".",
"$",
"folder",
")",
";",
"}",
"$",
"notify",
"->",
"finish",
"(",
")",
";",
"return",
"true",
";",
"}"
] | Installs the folders required for the bootstrap project from repo to project folder.
@param string $targetDirectory The directory where to put the files/folders.
@author Benjamin Carl <opensource@clickalicious.de>
@return bool TRUE on success, otherwise FALSE
@access protected
@static | [
"Installs",
"the",
"folders",
"required",
"for",
"the",
"bootstrap",
"project",
"from",
"repo",
"to",
"project",
"folder",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/Installer.php#L377-L393 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/Installer.php | Installer.validatePath | protected static function validatePath($path)
{
// Validate path by default logic
$path = parent::validatePath($path);
// Collection of existing folders for error message
$existingFolders = array();
// Check now if any of the target directories exists
foreach (self::getFolders() as $folder) {
if (file_exists($path . $folder)) {
$existingFolders[] = $folder . '/';
}
}
// Any folder found? => Exception
if (count($existingFolders) > 0) {
throw new Exception(
'The target directory contains the following files/folders already: ' .
implode(' & ', $existingFolders) . '.' . PHP_EOL . 'Remove those files/folders first and try again.' .
PHP_EOL
);
}
return $path;
} | php | protected static function validatePath($path)
{
// Validate path by default logic
$path = parent::validatePath($path);
// Collection of existing folders for error message
$existingFolders = array();
// Check now if any of the target directories exists
foreach (self::getFolders() as $folder) {
if (file_exists($path . $folder)) {
$existingFolders[] = $folder . '/';
}
}
// Any folder found? => Exception
if (count($existingFolders) > 0) {
throw new Exception(
'The target directory contains the following files/folders already: ' .
implode(' & ', $existingFolders) . '.' . PHP_EOL . 'Remove those files/folders first and try again.' .
PHP_EOL
);
}
return $path;
} | [
"protected",
"static",
"function",
"validatePath",
"(",
"$",
"path",
")",
"{",
"// Validate path by default logic",
"$",
"path",
"=",
"parent",
"::",
"validatePath",
"(",
"$",
"path",
")",
";",
"// Collection of existing folders for error message",
"$",
"existingFolders",
"=",
"array",
"(",
")",
";",
"// Check now if any of the target directories exists",
"foreach",
"(",
"self",
"::",
"getFolders",
"(",
")",
"as",
"$",
"folder",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"path",
".",
"$",
"folder",
")",
")",
"{",
"$",
"existingFolders",
"[",
"]",
"=",
"$",
"folder",
".",
"'/'",
";",
"}",
"}",
"// Any folder found? => Exception",
"if",
"(",
"count",
"(",
"$",
"existingFolders",
")",
">",
"0",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'The target directory contains the following files/folders already: '",
".",
"implode",
"(",
"' & '",
",",
"$",
"existingFolders",
")",
".",
"'.'",
".",
"PHP_EOL",
".",
"'Remove those files/folders first and try again.'",
".",
"PHP_EOL",
")",
";",
"}",
"return",
"$",
"path",
";",
"}"
] | Validates a path for installation.
@param string $path The path to validate
@author Benjamin Carl <opensource@clickalicious.de>
@return string TRUE if path is valid, otherwise FALSE
@access protected
@throws Exception | [
"Validates",
"a",
"path",
"for",
"installation",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/Installer.php#L431-L456 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/BaseInstaller.php | BaseInstaller.xcopy | protected static function xcopy($source, $destination, $permissions = 0755)
{
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $destination);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $destination);
}
// Make destination directory
if (!is_dir($destination)) {
mkdir($destination, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
self::xcopy(
$source . DIRECTORY_SEPARATOR . $entry,
$destination . DIRECTORY_SEPARATOR . $entry
);
}
// Clean up
$dir->close();
return true;
} | php | protected static function xcopy($source, $destination, $permissions = 0755)
{
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $destination);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $destination);
}
// Make destination directory
if (!is_dir($destination)) {
mkdir($destination, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
self::xcopy(
$source . DIRECTORY_SEPARATOR . $entry,
$destination . DIRECTORY_SEPARATOR . $entry
);
}
// Clean up
$dir->close();
return true;
} | [
"protected",
"static",
"function",
"xcopy",
"(",
"$",
"source",
",",
"$",
"destination",
",",
"$",
"permissions",
"=",
"0755",
")",
"{",
"// Check for symlinks",
"if",
"(",
"is_link",
"(",
"$",
"source",
")",
")",
"{",
"return",
"symlink",
"(",
"readlink",
"(",
"$",
"source",
")",
",",
"$",
"destination",
")",
";",
"}",
"// Simple copy for a file",
"if",
"(",
"is_file",
"(",
"$",
"source",
")",
")",
"{",
"return",
"copy",
"(",
"$",
"source",
",",
"$",
"destination",
")",
";",
"}",
"// Make destination directory",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"destination",
")",
")",
"{",
"mkdir",
"(",
"$",
"destination",
",",
"$",
"permissions",
")",
";",
"}",
"// Loop through the folder",
"$",
"dir",
"=",
"dir",
"(",
"$",
"source",
")",
";",
"while",
"(",
"false",
"!==",
"$",
"entry",
"=",
"$",
"dir",
"->",
"read",
"(",
")",
")",
"{",
"// Skip pointers",
"if",
"(",
"$",
"entry",
"==",
"'.'",
"||",
"$",
"entry",
"==",
"'..'",
")",
"{",
"continue",
";",
"}",
"// Deep copy directories",
"self",
"::",
"xcopy",
"(",
"$",
"source",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"entry",
",",
"$",
"destination",
".",
"DIRECTORY_SEPARATOR",
".",
"$",
"entry",
")",
";",
"}",
"// Clean up",
"$",
"dir",
"->",
"close",
"(",
")",
";",
"return",
"true",
";",
"}"
] | Copy a file, or recursively copy a folder and its contents
@param string $source Source path
@param string $destination Destination path
@param mixed $permissions New folder creation permissions
@author Benjamin Carl <opensource@clickalicious.de>
@return bool Returns true on success, false on failure
@access protected | [
"Copy",
"a",
"file",
"or",
"recursively",
"copy",
"a",
"folder",
"and",
"its",
"contents"
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/BaseInstaller.php#L236-L271 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/BaseInstaller.php | BaseInstaller.showVersion | protected static function showVersion()
{
\cli\line();
\cli\line(\cli\Colors::colorize('%y+----------------------------------------------------------------------+%N'));
\cli\line(\cli\Colors::colorize('%y| Installer |%N'));
\cli\line(\cli\Colors::colorize('%y| Version: ' . PROJECT_INSTALLER_VERSION . ' |%N'));
\cli\line(\cli\Colors::colorize('%y+----------------------------------------------------------------------+%N'));
} | php | protected static function showVersion()
{
\cli\line();
\cli\line(\cli\Colors::colorize('%y+----------------------------------------------------------------------+%N'));
\cli\line(\cli\Colors::colorize('%y| Installer |%N'));
\cli\line(\cli\Colors::colorize('%y| Version: ' . PROJECT_INSTALLER_VERSION . ' |%N'));
\cli\line(\cli\Colors::colorize('%y+----------------------------------------------------------------------+%N'));
} | [
"protected",
"static",
"function",
"showVersion",
"(",
")",
"{",
"\\",
"cli",
"\\",
"line",
"(",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%y+----------------------------------------------------------------------+%N'",
")",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%y| Installer |%N'",
")",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%y| Version: '",
".",
"PROJECT_INSTALLER_VERSION",
".",
"' |%N'",
")",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%y+----------------------------------------------------------------------+%N'",
")",
")",
";",
"}"
] | Shows phpMemAdmin version banner.
@author Benjamin Carl <opensource@clickalicious.de>
@return void
@access protected
@static | [
"Shows",
"phpMemAdmin",
"version",
"banner",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/BaseInstaller.php#L299-L306 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/BaseInstaller.php | BaseInstaller.initArguments | protected static function initArguments(CommandEvent $event = null)
{
// Check for retrieving arguments from Composer event ...
if ($event !== null) {
$arguments = $event->getArguments();
} else {
$arguments = $_SERVER['argv'];
}
// Check for strict mode
$strict = in_array('--strict', $arguments);
$arguments = new \cli\Arguments(compact('strict'), $arguments);
$arguments->addFlag(array('verbose', 'v'), 'Turn on verbose output');
$arguments->addFlag(array('version', 'V'), 'Display the version');
$arguments->addFlag(array('quiet', 'q'), 'Disable all output');
$arguments->addFlag(array('help', 'h'), 'Show this help screen');
// Parse the arguments
$arguments->parse();
// Store arguments ...
self::$arguments = $arguments;
if (isset(self::$arguments['help']) === true) {
self::showHelp();
}
} | php | protected static function initArguments(CommandEvent $event = null)
{
// Check for retrieving arguments from Composer event ...
if ($event !== null) {
$arguments = $event->getArguments();
} else {
$arguments = $_SERVER['argv'];
}
// Check for strict mode
$strict = in_array('--strict', $arguments);
$arguments = new \cli\Arguments(compact('strict'), $arguments);
$arguments->addFlag(array('verbose', 'v'), 'Turn on verbose output');
$arguments->addFlag(array('version', 'V'), 'Display the version');
$arguments->addFlag(array('quiet', 'q'), 'Disable all output');
$arguments->addFlag(array('help', 'h'), 'Show this help screen');
// Parse the arguments
$arguments->parse();
// Store arguments ...
self::$arguments = $arguments;
if (isset(self::$arguments['help']) === true) {
self::showHelp();
}
} | [
"protected",
"static",
"function",
"initArguments",
"(",
"CommandEvent",
"$",
"event",
"=",
"null",
")",
"{",
"// Check for retrieving arguments from Composer event ...",
"if",
"(",
"$",
"event",
"!==",
"null",
")",
"{",
"$",
"arguments",
"=",
"$",
"event",
"->",
"getArguments",
"(",
")",
";",
"}",
"else",
"{",
"$",
"arguments",
"=",
"$",
"_SERVER",
"[",
"'argv'",
"]",
";",
"}",
"// Check for strict mode",
"$",
"strict",
"=",
"in_array",
"(",
"'--strict'",
",",
"$",
"arguments",
")",
";",
"$",
"arguments",
"=",
"new",
"\\",
"cli",
"\\",
"Arguments",
"(",
"compact",
"(",
"'strict'",
")",
",",
"$",
"arguments",
")",
";",
"$",
"arguments",
"->",
"addFlag",
"(",
"array",
"(",
"'verbose'",
",",
"'v'",
")",
",",
"'Turn on verbose output'",
")",
";",
"$",
"arguments",
"->",
"addFlag",
"(",
"array",
"(",
"'version'",
",",
"'V'",
")",
",",
"'Display the version'",
")",
";",
"$",
"arguments",
"->",
"addFlag",
"(",
"array",
"(",
"'quiet'",
",",
"'q'",
")",
",",
"'Disable all output'",
")",
";",
"$",
"arguments",
"->",
"addFlag",
"(",
"array",
"(",
"'help'",
",",
"'h'",
")",
",",
"'Show this help screen'",
")",
";",
"// Parse the arguments",
"$",
"arguments",
"->",
"parse",
"(",
")",
";",
"// Store arguments ...",
"self",
"::",
"$",
"arguments",
"=",
"$",
"arguments",
";",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"arguments",
"[",
"'help'",
"]",
")",
"===",
"true",
")",
"{",
"self",
"::",
"showHelp",
"(",
")",
";",
"}",
"}"
] | Retrieve arguments from global to prepare them for further use.
@param CommandEvent $event The Composer event fired to retrieve arguments from
@author Benjamin Carl <opensource@clickalicious.de>
@return bool TRUE on success, otherwise FALSE
@access protected
@static | [
"Retrieve",
"arguments",
"from",
"global",
"to",
"prepare",
"them",
"for",
"further",
"use",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/BaseInstaller.php#L318-L345 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/BaseInstaller.php | BaseInstaller.showHelp | protected static function showHelp()
{
\cli\line();
\cli\out(self::$arguments->getHelpScreen(\cli\Colors::colorize('%N%n%gAvailable commands:')));
\cli\line();
} | php | protected static function showHelp()
{
\cli\line();
\cli\out(self::$arguments->getHelpScreen(\cli\Colors::colorize('%N%n%gAvailable commands:')));
\cli\line();
} | [
"protected",
"static",
"function",
"showHelp",
"(",
")",
"{",
"\\",
"cli",
"\\",
"line",
"(",
")",
";",
"\\",
"cli",
"\\",
"out",
"(",
"self",
"::",
"$",
"arguments",
"->",
"getHelpScreen",
"(",
"\\",
"cli",
"\\",
"Colors",
"::",
"colorize",
"(",
"'%N%n%gAvailable commands:'",
")",
")",
")",
";",
"\\",
"cli",
"\\",
"line",
"(",
")",
";",
"}"
] | Shows help dialog.
@author Benjamin Carl <opensource@clickalicious.de>
@return void
@access protected
@static | [
"Shows",
"help",
"dialog",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/BaseInstaller.php#L355-L360 |
clickalicious/phpmemadmin | lib/Clickalicious/PhpMemAdmin/BaseInstaller.php | BaseInstaller.validatePath | protected static function validatePath($path)
{
if (realpath($path) === false) {
throw new Exception(
'Path "' . $path . '" does not exist.'
);
}
if (is_dir($path) === false || is_writable($path) === false) {
throw new Exception(
'Make sure path "' . $path . '" exists and that it\'s writable.'
);
}
// Make full usable with trailing slash
$path = realpath($path) . DIRECTORY_SEPARATOR;
return $path;
} | php | protected static function validatePath($path)
{
if (realpath($path) === false) {
throw new Exception(
'Path "' . $path . '" does not exist.'
);
}
if (is_dir($path) === false || is_writable($path) === false) {
throw new Exception(
'Make sure path "' . $path . '" exists and that it\'s writable.'
);
}
// Make full usable with trailing slash
$path = realpath($path) . DIRECTORY_SEPARATOR;
return $path;
} | [
"protected",
"static",
"function",
"validatePath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"realpath",
"(",
"$",
"path",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Path \"'",
".",
"$",
"path",
".",
"'\" does not exist.'",
")",
";",
"}",
"if",
"(",
"is_dir",
"(",
"$",
"path",
")",
"===",
"false",
"||",
"is_writable",
"(",
"$",
"path",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Make sure path \"'",
".",
"$",
"path",
".",
"'\" exists and that it\\'s writable.'",
")",
";",
"}",
"// Make full usable with trailing slash",
"$",
"path",
"=",
"realpath",
"(",
"$",
"path",
")",
".",
"DIRECTORY_SEPARATOR",
";",
"return",
"$",
"path",
";",
"}"
] | Validates a path for installation.
@param string $path The path to validate
@author Benjamin Carl <opensource@clickalicious.de>
@return bool TRUE if path is valid, otherwise FALSE
@access protected
@throws Exception | [
"Validates",
"a",
"path",
"for",
"installation",
"."
] | train | https://github.com/clickalicious/phpmemadmin/blob/a945b46eaeeeab9fa7c016656a7802c538602d59/lib/Clickalicious/PhpMemAdmin/BaseInstaller.php#L417-L435 |
Yoast/wp-helpscout | src/class-helpscout-beacon.php | Yoast_HelpScout_Beacon.localize_beacon | private function localize_beacon() {
return array(
'config' => $this->get_config( $this->current_page ),
'identify' => $this->get_identify(),
'suggest' => $this->get_suggest( $this->current_page ),
'type' => $this->get_type(),
);
} | php | private function localize_beacon() {
return array(
'config' => $this->get_config( $this->current_page ),
'identify' => $this->get_identify(),
'suggest' => $this->get_suggest( $this->current_page ),
'type' => $this->get_type(),
);
} | [
"private",
"function",
"localize_beacon",
"(",
")",
"{",
"return",
"array",
"(",
"'config'",
"=>",
"$",
"this",
"->",
"get_config",
"(",
"$",
"this",
"->",
"current_page",
")",
",",
"'identify'",
"=>",
"$",
"this",
"->",
"get_identify",
"(",
")",
",",
"'suggest'",
"=>",
"$",
"this",
"->",
"get_suggest",
"(",
"$",
"this",
"->",
"current_page",
")",
",",
"'type'",
"=>",
"$",
"this",
"->",
"get_type",
"(",
")",
",",
")",
";",
"}"
] | Loads the beacon translations
@return array | [
"Loads",
"the",
"beacon",
"translations"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon.php#L77-L84 |
Yoast/wp-helpscout | src/class-helpscout-beacon.php | Yoast_HelpScout_Beacon.get_translations | private function get_translations() {
return array(
'searchLabel' => __( 'What can we help you with?', 'wordpress-seo-premium' ),
'searchErrorLabel' => __( 'Your search timed out. Please double-check your internet connection and try again.', 'wordpress-seo-premium' ),
'noResultsLabel' => __( 'No results found for', 'wordpress-seo-premium' ),
'contactLabel' => __( 'Send a Message', 'wordpress-seo-premium' ),
'attachFileLabel' => __( 'Attach a file', 'wordpress-seo-premium' ),
'attachFileError' => __( 'The maximum file size is 10 MB', 'wordpress-seo-premium' ),
'nameLabel' => __( 'Your Name', 'wordpress-seo-premium' ),
'nameError' => __( 'Please enter your name', 'wordpress-seo-premium' ),
'emailLabel' => __( 'Email address', 'wordpress-seo-premium' ),
'emailError' => __( 'Please enter a valid email address', 'wordpress-seo-premium' ),
'topicLabel' => __( 'Select a topic', 'wordpress-seo-premium' ),
'topicError' => __( 'Please select a topic from the list', 'wordpress-seo-premium' ),
'subjectLabel' => __( 'Subject', 'wordpress-seo-premium' ),
'subjectError' => __( 'Please enter a subject', 'wordpress-seo-premium' ),
'messageLabel' => __( 'How can we help you?', 'wordpress-seo-premium' ),
'messageError' => __( 'Please enter a message', 'wordpress-seo-premium' ),
'sendLabel' => __( 'Send', 'wordpress-seo-premium' ),
'contactSuccessLabel' => __( 'Message sent, thank you!', 'wordpress-seo-premium' ),
'contactSuccessDescription' => __( 'Someone from Team Yoast will get back to you soon, normally within a couple of hours.', 'wordpress-seo-premium' ),
);
} | php | private function get_translations() {
return array(
'searchLabel' => __( 'What can we help you with?', 'wordpress-seo-premium' ),
'searchErrorLabel' => __( 'Your search timed out. Please double-check your internet connection and try again.', 'wordpress-seo-premium' ),
'noResultsLabel' => __( 'No results found for', 'wordpress-seo-premium' ),
'contactLabel' => __( 'Send a Message', 'wordpress-seo-premium' ),
'attachFileLabel' => __( 'Attach a file', 'wordpress-seo-premium' ),
'attachFileError' => __( 'The maximum file size is 10 MB', 'wordpress-seo-premium' ),
'nameLabel' => __( 'Your Name', 'wordpress-seo-premium' ),
'nameError' => __( 'Please enter your name', 'wordpress-seo-premium' ),
'emailLabel' => __( 'Email address', 'wordpress-seo-premium' ),
'emailError' => __( 'Please enter a valid email address', 'wordpress-seo-premium' ),
'topicLabel' => __( 'Select a topic', 'wordpress-seo-premium' ),
'topicError' => __( 'Please select a topic from the list', 'wordpress-seo-premium' ),
'subjectLabel' => __( 'Subject', 'wordpress-seo-premium' ),
'subjectError' => __( 'Please enter a subject', 'wordpress-seo-premium' ),
'messageLabel' => __( 'How can we help you?', 'wordpress-seo-premium' ),
'messageError' => __( 'Please enter a message', 'wordpress-seo-premium' ),
'sendLabel' => __( 'Send', 'wordpress-seo-premium' ),
'contactSuccessLabel' => __( 'Message sent, thank you!', 'wordpress-seo-premium' ),
'contactSuccessDescription' => __( 'Someone from Team Yoast will get back to you soon, normally within a couple of hours.', 'wordpress-seo-premium' ),
);
} | [
"private",
"function",
"get_translations",
"(",
")",
"{",
"return",
"array",
"(",
"'searchLabel'",
"=>",
"__",
"(",
"'What can we help you with?'",
",",
"'wordpress-seo-premium'",
")",
",",
"'searchErrorLabel'",
"=>",
"__",
"(",
"'Your search timed out. Please double-check your internet connection and try again.'",
",",
"'wordpress-seo-premium'",
")",
",",
"'noResultsLabel'",
"=>",
"__",
"(",
"'No results found for'",
",",
"'wordpress-seo-premium'",
")",
",",
"'contactLabel'",
"=>",
"__",
"(",
"'Send a Message'",
",",
"'wordpress-seo-premium'",
")",
",",
"'attachFileLabel'",
"=>",
"__",
"(",
"'Attach a file'",
",",
"'wordpress-seo-premium'",
")",
",",
"'attachFileError'",
"=>",
"__",
"(",
"'The maximum file size is 10 MB'",
",",
"'wordpress-seo-premium'",
")",
",",
"'nameLabel'",
"=>",
"__",
"(",
"'Your Name'",
",",
"'wordpress-seo-premium'",
")",
",",
"'nameError'",
"=>",
"__",
"(",
"'Please enter your name'",
",",
"'wordpress-seo-premium'",
")",
",",
"'emailLabel'",
"=>",
"__",
"(",
"'Email address'",
",",
"'wordpress-seo-premium'",
")",
",",
"'emailError'",
"=>",
"__",
"(",
"'Please enter a valid email address'",
",",
"'wordpress-seo-premium'",
")",
",",
"'topicLabel'",
"=>",
"__",
"(",
"'Select a topic'",
",",
"'wordpress-seo-premium'",
")",
",",
"'topicError'",
"=>",
"__",
"(",
"'Please select a topic from the list'",
",",
"'wordpress-seo-premium'",
")",
",",
"'subjectLabel'",
"=>",
"__",
"(",
"'Subject'",
",",
"'wordpress-seo-premium'",
")",
",",
"'subjectError'",
"=>",
"__",
"(",
"'Please enter a subject'",
",",
"'wordpress-seo-premium'",
")",
",",
"'messageLabel'",
"=>",
"__",
"(",
"'How can we help you?'",
",",
"'wordpress-seo-premium'",
")",
",",
"'messageError'",
"=>",
"__",
"(",
"'Please enter a message'",
",",
"'wordpress-seo-premium'",
")",
",",
"'sendLabel'",
"=>",
"__",
"(",
"'Send'",
",",
"'wordpress-seo-premium'",
")",
",",
"'contactSuccessLabel'",
"=>",
"__",
"(",
"'Message sent, thank you!'",
",",
"'wordpress-seo-premium'",
")",
",",
"'contactSuccessDescription'",
"=>",
"__",
"(",
"'Someone from Team Yoast will get back to you soon, normally within a couple of hours.'",
",",
"'wordpress-seo-premium'",
")",
",",
")",
";",
"}"
] | Translates the values for the beacon. The array keys are the names of the translateble strings in the beacon.
@return array | [
"Translates",
"the",
"values",
"for",
"the",
"beacon",
".",
"The",
"array",
"keys",
"are",
"the",
"names",
"of",
"the",
"translateble",
"strings",
"in",
"the",
"beacon",
"."
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon.php#L104-L126 |
Yoast/wp-helpscout | src/class-helpscout-beacon.php | Yoast_HelpScout_Beacon.get_cache_key | private function get_cache_key( array $products ) {
$products_string = '';
foreach ( $products as $product ) {
$products_string .= $product->get_item_name();
}
return md5( self::YST_SEO_SUPPORT_IDENTIFY . $products_string );
} | php | private function get_cache_key( array $products ) {
$products_string = '';
foreach ( $products as $product ) {
$products_string .= $product->get_item_name();
}
return md5( self::YST_SEO_SUPPORT_IDENTIFY . $products_string );
} | [
"private",
"function",
"get_cache_key",
"(",
"array",
"$",
"products",
")",
"{",
"$",
"products_string",
"=",
"''",
";",
"foreach",
"(",
"$",
"products",
"as",
"$",
"product",
")",
"{",
"$",
"products_string",
".=",
"$",
"product",
"->",
"get_item_name",
"(",
")",
";",
"}",
"return",
"md5",
"(",
"self",
"::",
"YST_SEO_SUPPORT_IDENTIFY",
".",
"$",
"products_string",
")",
";",
"}"
] | @param Yoast_Product[] $products The products to build the cache key for.
@return string | [
"@param",
"Yoast_Product",
"[]",
"$products",
"The",
"products",
"to",
"build",
"the",
"cache",
"key",
"for",
"."
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon.php#L133-L141 |
Yoast/wp-helpscout | src/class-helpscout-beacon.php | Yoast_HelpScout_Beacon.get_identify | private function get_identify() {
$products = $this->get_products( $this->current_page );
$cache_key = $this->get_cache_key( $products );
$identify_data = get_transient( $cache_key );
if ( ! $identify_data ) {
$identifier = new Yoast_HelpScout_Beacon_Identifier( $this->get_products( $this->current_page ) );
$identify_data = $identifier->get_data();
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
set_transient( $cache_key, $identify_data, DAY_IN_SECONDS );
}
}
return $identify_data;
} | php | private function get_identify() {
$products = $this->get_products( $this->current_page );
$cache_key = $this->get_cache_key( $products );
$identify_data = get_transient( $cache_key );
if ( ! $identify_data ) {
$identifier = new Yoast_HelpScout_Beacon_Identifier( $this->get_products( $this->current_page ) );
$identify_data = $identifier->get_data();
if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
set_transient( $cache_key, $identify_data, DAY_IN_SECONDS );
}
}
return $identify_data;
} | [
"private",
"function",
"get_identify",
"(",
")",
"{",
"$",
"products",
"=",
"$",
"this",
"->",
"get_products",
"(",
"$",
"this",
"->",
"current_page",
")",
";",
"$",
"cache_key",
"=",
"$",
"this",
"->",
"get_cache_key",
"(",
"$",
"products",
")",
";",
"$",
"identify_data",
"=",
"get_transient",
"(",
"$",
"cache_key",
")",
";",
"if",
"(",
"!",
"$",
"identify_data",
")",
"{",
"$",
"identifier",
"=",
"new",
"Yoast_HelpScout_Beacon_Identifier",
"(",
"$",
"this",
"->",
"get_products",
"(",
"$",
"this",
"->",
"current_page",
")",
")",
";",
"$",
"identify_data",
"=",
"$",
"identifier",
"->",
"get_data",
"(",
")",
";",
"if",
"(",
"!",
"defined",
"(",
"'WP_DEBUG'",
")",
"||",
"!",
"WP_DEBUG",
")",
"{",
"set_transient",
"(",
"$",
"cache_key",
",",
"$",
"identify_data",
",",
"DAY_IN_SECONDS",
")",
";",
"}",
"}",
"return",
"$",
"identify_data",
";",
"}"
] | Retrieve data to populate the beacon email form
@return array | [
"Retrieve",
"data",
"to",
"populate",
"the",
"beacon",
"email",
"form"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon.php#L148-L163 |
Yoast/wp-helpscout | src/class-helpscout-beacon.php | Yoast_HelpScout_Beacon.get_suggest | private function get_suggest( $page ) {
$suggestions = array();
foreach ( $this->settings as $setting ) {
$suggestions = array_merge( $suggestions, $setting->get_suggestions( $page ) );
}
return $suggestions;
} | php | private function get_suggest( $page ) {
$suggestions = array();
foreach ( $this->settings as $setting ) {
$suggestions = array_merge( $suggestions, $setting->get_suggestions( $page ) );
}
return $suggestions;
} | [
"private",
"function",
"get_suggest",
"(",
"$",
"page",
")",
"{",
"$",
"suggestions",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"settings",
"as",
"$",
"setting",
")",
"{",
"$",
"suggestions",
"=",
"array_merge",
"(",
"$",
"suggestions",
",",
"$",
"setting",
"->",
"get_suggestions",
"(",
"$",
"page",
")",
")",
";",
"}",
"return",
"$",
"suggestions",
";",
"}"
] | Returns the suggestions for a certain page, or an empty array if there are no suggestions
@param string $page The admin page the user is on.
@return array | [
"Returns",
"the",
"suggestions",
"for",
"a",
"certain",
"page",
"or",
"an",
"empty",
"array",
"if",
"there",
"are",
"no",
"suggestions"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon.php#L172-L180 |
Yoast/wp-helpscout | src/class-helpscout-beacon.php | Yoast_HelpScout_Beacon.get_products | private function get_products( $page ) {
$products = array();
foreach ( $this->settings as $setting ) {
$products = array_merge( $products, $setting->get_products( $page ) );
}
return $products;
} | php | private function get_products( $page ) {
$products = array();
foreach ( $this->settings as $setting ) {
$products = array_merge( $products, $setting->get_products( $page ) );
}
return $products;
} | [
"private",
"function",
"get_products",
"(",
"$",
"page",
")",
"{",
"$",
"products",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"settings",
"as",
"$",
"setting",
")",
"{",
"$",
"products",
"=",
"array_merge",
"(",
"$",
"products",
",",
"$",
"setting",
"->",
"get_products",
"(",
"$",
"page",
")",
")",
";",
"}",
"return",
"$",
"products",
";",
"}"
] | Returns the products for a certain page, or an empty array if there are no products.
@param string $page The admin page the user is on.
@return array | [
"Returns",
"the",
"products",
"for",
"a",
"certain",
"page",
"or",
"an",
"empty",
"array",
"if",
"there",
"are",
"no",
"products",
"."
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon.php#L189-L197 |
Yoast/wp-helpscout | src/class-helpscout-beacon.php | Yoast_HelpScout_Beacon.get_config | private function get_config( $page ) {
// Defaults.
$config = array(
'instructions' => $this->get_instructions(),
'icon' => 'question',
'color' => '#A4286A',
'poweredBy' => false,
'translation' => $this->get_translations(),
'showSubject' => true,
'zIndex' => 1000001,
);
foreach ( $this->settings as $setting ) {
if ( method_exists( $setting, 'get_config' ) ) {
$config = array_merge( $config, $setting->get_config( $page ) );
}
}
return $config;
} | php | private function get_config( $page ) {
// Defaults.
$config = array(
'instructions' => $this->get_instructions(),
'icon' => 'question',
'color' => '#A4286A',
'poweredBy' => false,
'translation' => $this->get_translations(),
'showSubject' => true,
'zIndex' => 1000001,
);
foreach ( $this->settings as $setting ) {
if ( method_exists( $setting, 'get_config' ) ) {
$config = array_merge( $config, $setting->get_config( $page ) );
}
}
return $config;
} | [
"private",
"function",
"get_config",
"(",
"$",
"page",
")",
"{",
"// Defaults.",
"$",
"config",
"=",
"array",
"(",
"'instructions'",
"=>",
"$",
"this",
"->",
"get_instructions",
"(",
")",
",",
"'icon'",
"=>",
"'question'",
",",
"'color'",
"=>",
"'#A4286A'",
",",
"'poweredBy'",
"=>",
"false",
",",
"'translation'",
"=>",
"$",
"this",
"->",
"get_translations",
"(",
")",
",",
"'showSubject'",
"=>",
"true",
",",
"'zIndex'",
"=>",
"1000001",
",",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"settings",
"as",
"$",
"setting",
")",
"{",
"if",
"(",
"method_exists",
"(",
"$",
"setting",
",",
"'get_config'",
")",
")",
"{",
"$",
"config",
"=",
"array_merge",
"(",
"$",
"config",
",",
"$",
"setting",
"->",
"get_config",
"(",
"$",
"page",
")",
")",
";",
"}",
"}",
"return",
"$",
"config",
";",
"}"
] | Returns the configuration for a certain page
@param string $page The admin page the user is on.
@return array | [
"Returns",
"the",
"configuration",
"for",
"a",
"certain",
"page"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon.php#L215-L234 |
Yoast/wp-helpscout | src/class-helpscout-beacon-identifier.php | Yoast_HelpScout_Beacon_Identifier.get_data | public function get_data() {
// Do not make these strings translateable! They are for our support agents, the user won't see them!
$data = array(
'name' => $this->get_user_info(),
'email' => $this->get_user_info( 'email' ),
'WordPress Version' => $this->get_wordpress_version(),
'Server' => $this->get_server_info(),
'<a href="' . admin_url( 'themes.php' ) . '">Theme</a>' => $this->get_theme_info(),
'<a href="' . admin_url( 'plugins.php' ) . '">Plugins</a>' => $this->get_current_plugins(),
);
foreach ( $this->products as $product ) {
$data[ $product->get_item_name() ] = $this->get_product_info( $product );
}
return $data;
} | php | public function get_data() {
// Do not make these strings translateable! They are for our support agents, the user won't see them!
$data = array(
'name' => $this->get_user_info(),
'email' => $this->get_user_info( 'email' ),
'WordPress Version' => $this->get_wordpress_version(),
'Server' => $this->get_server_info(),
'<a href="' . admin_url( 'themes.php' ) . '">Theme</a>' => $this->get_theme_info(),
'<a href="' . admin_url( 'plugins.php' ) . '">Plugins</a>' => $this->get_current_plugins(),
);
foreach ( $this->products as $product ) {
$data[ $product->get_item_name() ] = $this->get_product_info( $product );
}
return $data;
} | [
"public",
"function",
"get_data",
"(",
")",
"{",
"// Do not make these strings translateable! They are for our support agents, the user won't see them!",
"$",
"data",
"=",
"array",
"(",
"'name'",
"=>",
"$",
"this",
"->",
"get_user_info",
"(",
")",
",",
"'email'",
"=>",
"$",
"this",
"->",
"get_user_info",
"(",
"'email'",
")",
",",
"'WordPress Version'",
"=>",
"$",
"this",
"->",
"get_wordpress_version",
"(",
")",
",",
"'Server'",
"=>",
"$",
"this",
"->",
"get_server_info",
"(",
")",
",",
"'<a href=\"'",
".",
"admin_url",
"(",
"'themes.php'",
")",
".",
"'\">Theme</a>'",
"=>",
"$",
"this",
"->",
"get_theme_info",
"(",
")",
",",
"'<a href=\"'",
".",
"admin_url",
"(",
"'plugins.php'",
")",
".",
"'\">Plugins</a>'",
"=>",
"$",
"this",
"->",
"get_current_plugins",
"(",
")",
",",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"products",
"as",
"$",
"product",
")",
"{",
"$",
"data",
"[",
"$",
"product",
"->",
"get_item_name",
"(",
")",
"]",
"=",
"$",
"this",
"->",
"get_product_info",
"(",
"$",
"product",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Build data to populate the beacon email form
@return array | [
"Build",
"data",
"to",
"populate",
"the",
"beacon",
"email",
"form"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon-identifier.php#L30-L46 |
Yoast/wp-helpscout | src/class-helpscout-beacon-identifier.php | Yoast_HelpScout_Beacon_Identifier.get_server_info | private function get_server_info() {
$out = '<table>';
// Validate if the server address is a valid IP-address.
if ( $ipaddress = filter_input( INPUT_SERVER , 'SERVER_ADDR', FILTER_VALIDATE_IP ) ) {
$out .= '<tr><td>IP</td><td>' . $ipaddress . '</td></tr>';
$out .= '<tr><td>Hostname</td><td>' . gethostbyaddr( $ipaddress ) . '</td></tr>';
}
if ( function_exists( 'php_uname' ) ) {
$out .= '<tr><td>OS</td><td>' . php_uname( 's r' ) . '</td></tr>';
}
$out .= '<tr><td>PHP</td><td>' . PHP_VERSION . '</td></tr>';
$out .= '<tr><td>CURL</td><td>' . $this->get_curl_info() . '</td></tr>';
$out .= '</table>';
return $out;
} | php | private function get_server_info() {
$out = '<table>';
// Validate if the server address is a valid IP-address.
if ( $ipaddress = filter_input( INPUT_SERVER , 'SERVER_ADDR', FILTER_VALIDATE_IP ) ) {
$out .= '<tr><td>IP</td><td>' . $ipaddress . '</td></tr>';
$out .= '<tr><td>Hostname</td><td>' . gethostbyaddr( $ipaddress ) . '</td></tr>';
}
if ( function_exists( 'php_uname' ) ) {
$out .= '<tr><td>OS</td><td>' . php_uname( 's r' ) . '</td></tr>';
}
$out .= '<tr><td>PHP</td><td>' . PHP_VERSION . '</td></tr>';
$out .= '<tr><td>CURL</td><td>' . $this->get_curl_info() . '</td></tr>';
$out .= '</table>';
return $out;
} | [
"private",
"function",
"get_server_info",
"(",
")",
"{",
"$",
"out",
"=",
"'<table>'",
";",
"// Validate if the server address is a valid IP-address.",
"if",
"(",
"$",
"ipaddress",
"=",
"filter_input",
"(",
"INPUT_SERVER",
",",
"'SERVER_ADDR'",
",",
"FILTER_VALIDATE_IP",
")",
")",
"{",
"$",
"out",
".=",
"'<tr><td>IP</td><td>'",
".",
"$",
"ipaddress",
".",
"'</td></tr>'",
";",
"$",
"out",
".=",
"'<tr><td>Hostname</td><td>'",
".",
"gethostbyaddr",
"(",
"$",
"ipaddress",
")",
".",
"'</td></tr>'",
";",
"}",
"if",
"(",
"function_exists",
"(",
"'php_uname'",
")",
")",
"{",
"$",
"out",
".=",
"'<tr><td>OS</td><td>'",
".",
"php_uname",
"(",
"'s r'",
")",
".",
"'</td></tr>'",
";",
"}",
"$",
"out",
".=",
"'<tr><td>PHP</td><td>'",
".",
"PHP_VERSION",
".",
"'</td></tr>'",
";",
"$",
"out",
".=",
"'<tr><td>CURL</td><td>'",
".",
"$",
"this",
"->",
"get_curl_info",
"(",
")",
".",
"'</td></tr>'",
";",
"$",
"out",
".=",
"'</table>'",
";",
"return",
"$",
"out",
";",
"}"
] | Returns basic info about the server software
@return string | [
"Returns",
"basic",
"info",
"about",
"the",
"server",
"software"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon-identifier.php#L53-L71 |
Yoast/wp-helpscout | src/class-helpscout-beacon-identifier.php | Yoast_HelpScout_Beacon_Identifier.get_product_info | private function get_product_info( Yoast_Product $product ) {
if ( ! class_exists( 'Yoast_Plugin_License_Manager' ) ) {
return 'License manager could not be loaded';
}
$license_manager = new Yoast_Plugin_License_Manager( $product );
$out = '<table>';
$out .= '<tr><td>Version</td><td>' . WPSEO_VERSION . '</td></tr>';
$out .= '<tr><td>License</td><td>' . '<a href=" ' . admin_url( 'admin.php?page=wpseo_licenses#top#licenses' ) . ' ">' . $license_manager->get_license_key() . '</a>' . '</td></tr>';
$out .= '<tr><td>Status</td><td>' . $license_manager->get_license_status() . '</td></tr>';
$out .= '</table>';
return $out;
} | php | private function get_product_info( Yoast_Product $product ) {
if ( ! class_exists( 'Yoast_Plugin_License_Manager' ) ) {
return 'License manager could not be loaded';
}
$license_manager = new Yoast_Plugin_License_Manager( $product );
$out = '<table>';
$out .= '<tr><td>Version</td><td>' . WPSEO_VERSION . '</td></tr>';
$out .= '<tr><td>License</td><td>' . '<a href=" ' . admin_url( 'admin.php?page=wpseo_licenses#top#licenses' ) . ' ">' . $license_manager->get_license_key() . '</a>' . '</td></tr>';
$out .= '<tr><td>Status</td><td>' . $license_manager->get_license_status() . '</td></tr>';
$out .= '</table>';
return $out;
} | [
"private",
"function",
"get_product_info",
"(",
"Yoast_Product",
"$",
"product",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"'Yoast_Plugin_License_Manager'",
")",
")",
"{",
"return",
"'License manager could not be loaded'",
";",
"}",
"$",
"license_manager",
"=",
"new",
"Yoast_Plugin_License_Manager",
"(",
"$",
"product",
")",
";",
"$",
"out",
"=",
"'<table>'",
";",
"$",
"out",
".=",
"'<tr><td>Version</td><td>'",
".",
"WPSEO_VERSION",
".",
"'</td></tr>'",
";",
"$",
"out",
".=",
"'<tr><td>License</td><td>'",
".",
"'<a href=\" '",
".",
"admin_url",
"(",
"'admin.php?page=wpseo_licenses#top#licenses'",
")",
".",
"' \">'",
".",
"$",
"license_manager",
"->",
"get_license_key",
"(",
")",
".",
"'</a>'",
".",
"'</td></tr>'",
";",
"$",
"out",
".=",
"'<tr><td>Status</td><td>'",
".",
"$",
"license_manager",
"->",
"get_license_status",
"(",
")",
".",
"'</td></tr>'",
";",
"$",
"out",
".=",
"'</table>'",
";",
"return",
"$",
"out",
";",
"}"
] | Returns info about the Yoast SEO plugin version and license
@param Yoast_Product $product The product to return information for.
@return string | [
"Returns",
"info",
"about",
"the",
"Yoast",
"SEO",
"plugin",
"version",
"and",
"license"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon-identifier.php#L80-L94 |
Yoast/wp-helpscout | src/class-helpscout-beacon-identifier.php | Yoast_HelpScout_Beacon_Identifier.get_user_info | private function get_user_info( $what = 'name' ) {
$current_user = wp_get_current_user();
switch ( $what ) {
case 'email':
$out = $current_user->user_email;
break;
case 'name':
default:
$out = trim( $current_user->user_firstname . ' ' . $current_user->user_lastname );
break;
}
return $out;
} | php | private function get_user_info( $what = 'name' ) {
$current_user = wp_get_current_user();
switch ( $what ) {
case 'email':
$out = $current_user->user_email;
break;
case 'name':
default:
$out = trim( $current_user->user_firstname . ' ' . $current_user->user_lastname );
break;
}
return $out;
} | [
"private",
"function",
"get_user_info",
"(",
"$",
"what",
"=",
"'name'",
")",
"{",
"$",
"current_user",
"=",
"wp_get_current_user",
"(",
")",
";",
"switch",
"(",
"$",
"what",
")",
"{",
"case",
"'email'",
":",
"$",
"out",
"=",
"$",
"current_user",
"->",
"user_email",
";",
"break",
";",
"case",
"'name'",
":",
"default",
":",
"$",
"out",
"=",
"trim",
"(",
"$",
"current_user",
"->",
"user_firstname",
".",
"' '",
".",
"$",
"current_user",
"->",
"user_lastname",
")",
";",
"break",
";",
"}",
"return",
"$",
"out",
";",
"}"
] | Returns info about the current user
@param string $what What to retrieve, defaults to name.
@return string | [
"Returns",
"info",
"about",
"the",
"current",
"user"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon-identifier.php#L103-L117 |
Yoast/wp-helpscout | src/class-helpscout-beacon-identifier.php | Yoast_HelpScout_Beacon_Identifier.get_curl_info | private function get_curl_info() {
if ( function_exists( 'curl_version' ) ) {
$curl = curl_version();
$msg = $curl['version'];
if ( ! $curl['features'] && CURL_VERSION_SSL ) {
$msg .= ' - NO SSL SUPPORT';
}
}
else {
$msg = 'No CURL installed';
}
return $msg;
} | php | private function get_curl_info() {
if ( function_exists( 'curl_version' ) ) {
$curl = curl_version();
$msg = $curl['version'];
if ( ! $curl['features'] && CURL_VERSION_SSL ) {
$msg .= ' - NO SSL SUPPORT';
}
}
else {
$msg = 'No CURL installed';
}
return $msg;
} | [
"private",
"function",
"get_curl_info",
"(",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'curl_version'",
")",
")",
"{",
"$",
"curl",
"=",
"curl_version",
"(",
")",
";",
"$",
"msg",
"=",
"$",
"curl",
"[",
"'version'",
"]",
";",
"if",
"(",
"!",
"$",
"curl",
"[",
"'features'",
"]",
"&&",
"CURL_VERSION_SSL",
")",
"{",
"$",
"msg",
".=",
"' - NO SSL SUPPORT'",
";",
"}",
"}",
"else",
"{",
"$",
"msg",
"=",
"'No CURL installed'",
";",
"}",
"return",
"$",
"msg",
";",
"}"
] | Returns the curl version, if curl is found
@return string | [
"Returns",
"the",
"curl",
"version",
"if",
"curl",
"is",
"found"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon-identifier.php#L139-L152 |
Yoast/wp-helpscout | src/class-helpscout-beacon-identifier.php | Yoast_HelpScout_Beacon_Identifier.get_theme_info | private function get_theme_info() {
$theme = wp_get_theme();
$msg = '<a href="' . $theme->display( 'ThemeURI' ) . '">' . $theme->display( 'Name' ) . '</a> v' . $theme->display( 'Version' ) . ' by ' . $theme->display( 'Author' );
if ( is_child_theme() ) {
$msg .= '<br />' . 'Child theme of: ' . $theme->display( 'Template' );
}
return $msg;
} | php | private function get_theme_info() {
$theme = wp_get_theme();
$msg = '<a href="' . $theme->display( 'ThemeURI' ) . '">' . $theme->display( 'Name' ) . '</a> v' . $theme->display( 'Version' ) . ' by ' . $theme->display( 'Author' );
if ( is_child_theme() ) {
$msg .= '<br />' . 'Child theme of: ' . $theme->display( 'Template' );
}
return $msg;
} | [
"private",
"function",
"get_theme_info",
"(",
")",
"{",
"$",
"theme",
"=",
"wp_get_theme",
"(",
")",
";",
"$",
"msg",
"=",
"'<a href=\"'",
".",
"$",
"theme",
"->",
"display",
"(",
"'ThemeURI'",
")",
".",
"'\">'",
".",
"$",
"theme",
"->",
"display",
"(",
"'Name'",
")",
".",
"'</a> v'",
".",
"$",
"theme",
"->",
"display",
"(",
"'Version'",
")",
".",
"' by '",
".",
"$",
"theme",
"->",
"display",
"(",
"'Author'",
")",
";",
"if",
"(",
"is_child_theme",
"(",
")",
")",
"{",
"$",
"msg",
".=",
"'<br />'",
".",
"'Child theme of: '",
".",
"$",
"theme",
"->",
"display",
"(",
"'Template'",
")",
";",
"}",
"return",
"$",
"msg",
";",
"}"
] | Returns a formatted HTML string for the current theme
@return string | [
"Returns",
"a",
"formatted",
"HTML",
"string",
"for",
"the",
"current",
"theme"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon-identifier.php#L159-L169 |
Yoast/wp-helpscout | src/class-helpscout-beacon-identifier.php | Yoast_HelpScout_Beacon_Identifier.get_current_plugins | private function get_current_plugins() {
$updates_avail = get_site_transient( 'update_plugins' );
$msg = '';
foreach ( wp_get_active_and_valid_plugins() as $plugin ) {
$plugin_data = get_plugin_data( $plugin );
$plugin_file = str_replace( trailingslashit( WP_PLUGIN_DIR ), '', $plugin );
if ( isset( $updates_avail->response[ $plugin_file ] ) ) {
$msg .= '<i class="icon-close1"></i> ';
}
$msg .= '<a href="' . $plugin_data['PluginURI'] . '">' . $plugin_data['Name'] . '</a> v' . $plugin_data['Version'] . '<br/>';
}
return $msg;
} | php | private function get_current_plugins() {
$updates_avail = get_site_transient( 'update_plugins' );
$msg = '';
foreach ( wp_get_active_and_valid_plugins() as $plugin ) {
$plugin_data = get_plugin_data( $plugin );
$plugin_file = str_replace( trailingslashit( WP_PLUGIN_DIR ), '', $plugin );
if ( isset( $updates_avail->response[ $plugin_file ] ) ) {
$msg .= '<i class="icon-close1"></i> ';
}
$msg .= '<a href="' . $plugin_data['PluginURI'] . '">' . $plugin_data['Name'] . '</a> v' . $plugin_data['Version'] . '<br/>';
}
return $msg;
} | [
"private",
"function",
"get_current_plugins",
"(",
")",
"{",
"$",
"updates_avail",
"=",
"get_site_transient",
"(",
"'update_plugins'",
")",
";",
"$",
"msg",
"=",
"''",
";",
"foreach",
"(",
"wp_get_active_and_valid_plugins",
"(",
")",
"as",
"$",
"plugin",
")",
"{",
"$",
"plugin_data",
"=",
"get_plugin_data",
"(",
"$",
"plugin",
")",
";",
"$",
"plugin_file",
"=",
"str_replace",
"(",
"trailingslashit",
"(",
"WP_PLUGIN_DIR",
")",
",",
"''",
",",
"$",
"plugin",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"updates_avail",
"->",
"response",
"[",
"$",
"plugin_file",
"]",
")",
")",
"{",
"$",
"msg",
".=",
"'<i class=\"icon-close1\"></i> '",
";",
"}",
"$",
"msg",
".=",
"'<a href=\"'",
".",
"$",
"plugin_data",
"[",
"'PluginURI'",
"]",
".",
"'\">'",
".",
"$",
"plugin_data",
"[",
"'Name'",
"]",
".",
"'</a> v'",
".",
"$",
"plugin_data",
"[",
"'Version'",
"]",
".",
"'<br/>'",
";",
"}",
"return",
"$",
"msg",
";",
"}"
] | Returns a formatted HTML list of all active plugins
@return string | [
"Returns",
"a",
"formatted",
"HTML",
"list",
"of",
"all",
"active",
"plugins"
] | train | https://github.com/Yoast/wp-helpscout/blob/ab97015cd7c32c3567ddef9bbb273ae22fcb57a3/src/class-helpscout-beacon-identifier.php#L176-L192 |
fzaninotto/Streamer | Streamer/Stream.php | Stream.read | public function read($length = null)
{
$this->assertReadable();
if (null == $length) {
$length = $this->bufferSize;
}
$ret = fread($this->stream, $length);
if (false === $ret) {
throw new RuntimeException('Cannot read stream');
}
return $ret;
} | php | public function read($length = null)
{
$this->assertReadable();
if (null == $length) {
$length = $this->bufferSize;
}
$ret = fread($this->stream, $length);
if (false === $ret) {
throw new RuntimeException('Cannot read stream');
}
return $ret;
} | [
"public",
"function",
"read",
"(",
"$",
"length",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"assertReadable",
"(",
")",
";",
"if",
"(",
"null",
"==",
"$",
"length",
")",
"{",
"$",
"length",
"=",
"$",
"this",
"->",
"bufferSize",
";",
"}",
"$",
"ret",
"=",
"fread",
"(",
"$",
"this",
"->",
"stream",
",",
"$",
"length",
")",
";",
"if",
"(",
"false",
"===",
"$",
"ret",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot read stream'",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Read data from the stream.
Binary-safe.
@param int $length Maximum number of bytes to read. Defaults to self::$bufferSize.
@return string The data read from the stream | [
"Read",
"data",
"from",
"the",
"stream",
".",
"Binary",
"-",
"safe",
"."
] | train | https://github.com/fzaninotto/Streamer/blob/043043101ca57e64ac727e09dcea3b900b215d20/Streamer/Stream.php#L133-L145 |
fzaninotto/Streamer | Streamer/Stream.php | Stream.getLine | public function getLine($length = null, $ending = "\n")
{
$this->assertReadable();
if (null == $length) {
$length = $this->bufferSize;
}
$ret = stream_get_line($this->stream, $length, $ending);
if (false === $ret) {
throw new RuntimeException('Cannot read stream');
}
return $ret;
} | php | public function getLine($length = null, $ending = "\n")
{
$this->assertReadable();
if (null == $length) {
$length = $this->bufferSize;
}
$ret = stream_get_line($this->stream, $length, $ending);
if (false === $ret) {
throw new RuntimeException('Cannot read stream');
}
return $ret;
} | [
"public",
"function",
"getLine",
"(",
"$",
"length",
"=",
"null",
",",
"$",
"ending",
"=",
"\"\\n\"",
")",
"{",
"$",
"this",
"->",
"assertReadable",
"(",
")",
";",
"if",
"(",
"null",
"==",
"$",
"length",
")",
"{",
"$",
"length",
"=",
"$",
"this",
"->",
"bufferSize",
";",
"}",
"$",
"ret",
"=",
"stream_get_line",
"(",
"$",
"this",
"->",
"stream",
",",
"$",
"length",
",",
"$",
"ending",
")",
";",
"if",
"(",
"false",
"===",
"$",
"ret",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot read stream'",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Read one line from the stream.
Binary-safe. Reading ends when length bytes have been read, when the
string specified by ending is found (which is not included in the return
value), or on EOF (whichever comes first).
@param int $length Maximum number of bytes to read. Defaults to self::$bufferSize.
@param string $ending Line ending to stop at. Defaults to "\n".
@return string The data read from the stream | [
"Read",
"one",
"line",
"from",
"the",
"stream",
"."
] | train | https://github.com/fzaninotto/Streamer/blob/043043101ca57e64ac727e09dcea3b900b215d20/Streamer/Stream.php#L159-L171 |
fzaninotto/Streamer | Streamer/Stream.php | Stream.write | public function write($string, $length = null)
{
$this->assertWritable();
if (null === $length) {
$ret = fwrite($this->stream, $string);
} else {
$ret = fwrite($this->stream, $string, $length);
}
if (false === $ret) {
throw new RuntimeException('Cannot write on stream');
}
return $ret;
} | php | public function write($string, $length = null)
{
$this->assertWritable();
if (null === $length) {
$ret = fwrite($this->stream, $string);
} else {
$ret = fwrite($this->stream, $string, $length);
}
if (false === $ret) {
throw new RuntimeException('Cannot write on stream');
}
return $ret;
} | [
"public",
"function",
"write",
"(",
"$",
"string",
",",
"$",
"length",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"assertWritable",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"length",
")",
"{",
"$",
"ret",
"=",
"fwrite",
"(",
"$",
"this",
"->",
"stream",
",",
"$",
"string",
")",
";",
"}",
"else",
"{",
"$",
"ret",
"=",
"fwrite",
"(",
"$",
"this",
"->",
"stream",
",",
"$",
"string",
",",
"$",
"length",
")",
";",
"}",
"if",
"(",
"false",
"===",
"$",
"ret",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot write on stream'",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Write data to the stream.
Binary-safe.
@param string $string The string that is to be written.
@param int $length If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.
@return int Number of bytes written | [
"Write",
"data",
"to",
"the",
"stream",
".",
"Binary",
"-",
"safe",
"."
] | train | https://github.com/fzaninotto/Streamer/blob/043043101ca57e64ac727e09dcea3b900b215d20/Streamer/Stream.php#L214-L227 |
fzaninotto/Streamer | Streamer/Stream.php | Stream.getOffset | public function getOffset()
{
$this->assertSeekable();
$ret = ftell($this->stream);
if (false === $ret) {
throw new RuntimeException('Cannot get offset of stream');
}
return $ret;
} | php | public function getOffset()
{
$this->assertSeekable();
$ret = ftell($this->stream);
if (false === $ret) {
throw new RuntimeException('Cannot get offset of stream');
}
return $ret;
} | [
"public",
"function",
"getOffset",
"(",
")",
"{",
"$",
"this",
"->",
"assertSeekable",
"(",
")",
";",
"$",
"ret",
"=",
"ftell",
"(",
"$",
"this",
"->",
"stream",
")",
";",
"if",
"(",
"false",
"===",
"$",
"ret",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Cannot get offset of stream'",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Get the position of the file pointer
@return int | [
"Get",
"the",
"position",
"of",
"the",
"file",
"pointer"
] | train | https://github.com/fzaninotto/Streamer/blob/043043101ca57e64ac727e09dcea3b900b215d20/Streamer/Stream.php#L256-L265 |
cleentfaar/slack | src/CL/Slack/Payload/ChatPostMessagePayload.php | ChatPostMessagePayload.setIconEmoji | public function setIconEmoji($iconEmoji)
{
if (substr($iconEmoji, 0, 1) !== ':') {
$iconEmoji = sprintf(':%s:', $iconEmoji);
}
$this->iconEmoji = $iconEmoji;
} | php | public function setIconEmoji($iconEmoji)
{
if (substr($iconEmoji, 0, 1) !== ':') {
$iconEmoji = sprintf(':%s:', $iconEmoji);
}
$this->iconEmoji = $iconEmoji;
} | [
"public",
"function",
"setIconEmoji",
"(",
"$",
"iconEmoji",
")",
"{",
"if",
"(",
"substr",
"(",
"$",
"iconEmoji",
",",
"0",
",",
"1",
")",
"!==",
"':'",
")",
"{",
"$",
"iconEmoji",
"=",
"sprintf",
"(",
"':%s:'",
",",
"$",
"iconEmoji",
")",
";",
"}",
"$",
"this",
"->",
"iconEmoji",
"=",
"$",
"iconEmoji",
";",
"}"
] | Sets the emoji to use as the icon for this message (overrides icon URL).
You can use one of Slack's emoji's or upload your own.
@see https://{YOURSLACKTEAMHERE}.slack.com/customize/emoji
@param string|null $iconEmoji Emoji to use as the icon for this message (overrides icon URL). | [
"Sets",
"the",
"emoji",
"to",
"use",
"as",
"the",
"icon",
"for",
"this",
"message",
"(",
"overrides",
"icon",
"URL",
")",
"."
] | train | https://github.com/cleentfaar/slack/blob/4639d48252bcbd4a9e5c7619d1f72b55d5a6eeb2/src/CL/Slack/Payload/ChatPostMessagePayload.php#L206-L213 |
cleentfaar/slack | src/CL/Slack/Serializer/PayloadSerializer.php | PayloadSerializer.serialize | public function serialize(PayloadInterface $payload)
{
if ($payload instanceof AdvancedSerializeInterface) {
$payload->beforeSerialize($this->serializer);
}
$serializedPayload = $this->serializer->serialize($payload, 'json');
if (!$serializedPayload || !is_string($serializedPayload)) {
throw new \RuntimeException(sprintf(
'Failed to serialize payload; expected it to be a string, got: %s',
var_export($serializedPayload, true)
));
}
return json_decode($serializedPayload, true);
} | php | public function serialize(PayloadInterface $payload)
{
if ($payload instanceof AdvancedSerializeInterface) {
$payload->beforeSerialize($this->serializer);
}
$serializedPayload = $this->serializer->serialize($payload, 'json');
if (!$serializedPayload || !is_string($serializedPayload)) {
throw new \RuntimeException(sprintf(
'Failed to serialize payload; expected it to be a string, got: %s',
var_export($serializedPayload, true)
));
}
return json_decode($serializedPayload, true);
} | [
"public",
"function",
"serialize",
"(",
"PayloadInterface",
"$",
"payload",
")",
"{",
"if",
"(",
"$",
"payload",
"instanceof",
"AdvancedSerializeInterface",
")",
"{",
"$",
"payload",
"->",
"beforeSerialize",
"(",
"$",
"this",
"->",
"serializer",
")",
";",
"}",
"$",
"serializedPayload",
"=",
"$",
"this",
"->",
"serializer",
"->",
"serialize",
"(",
"$",
"payload",
",",
"'json'",
")",
";",
"if",
"(",
"!",
"$",
"serializedPayload",
"||",
"!",
"is_string",
"(",
"$",
"serializedPayload",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'Failed to serialize payload; expected it to be a string, got: %s'",
",",
"var_export",
"(",
"$",
"serializedPayload",
",",
"true",
")",
")",
")",
";",
"}",
"return",
"json_decode",
"(",
"$",
"serializedPayload",
",",
"true",
")",
";",
"}"
] | @param PayloadInterface $payload
@return array The serialized payload data | [
"@param",
"PayloadInterface",
"$payload"
] | train | https://github.com/cleentfaar/slack/blob/4639d48252bcbd4a9e5c7619d1f72b55d5a6eeb2/src/CL/Slack/Serializer/PayloadSerializer.php#L27-L43 |
cleentfaar/slack | src/CL/Slack/Serializer/PayloadResponseSerializer.php | PayloadResponseSerializer.deserialize | public function deserialize(array $payloadResponse, $payloadResponseClass)
{
$payloadResponseObject = $this->serializer->deserialize(
json_encode($payloadResponse),
$payloadResponseClass,
'json'
);
if (!($payloadResponseObject instanceof PayloadResponseInterface)) {
throw new \RuntimeException(sprintf(
'The serializer expected the response data to be converted into an instance of "%s", got: %s',
$payloadResponseClass,
is_object($payloadResponseObject) ? 'instance of ' . get_class($payloadResponseObject) : gettype($payloadResponseObject)
));
}
return $payloadResponseObject;
} | php | public function deserialize(array $payloadResponse, $payloadResponseClass)
{
$payloadResponseObject = $this->serializer->deserialize(
json_encode($payloadResponse),
$payloadResponseClass,
'json'
);
if (!($payloadResponseObject instanceof PayloadResponseInterface)) {
throw new \RuntimeException(sprintf(
'The serializer expected the response data to be converted into an instance of "%s", got: %s',
$payloadResponseClass,
is_object($payloadResponseObject) ? 'instance of ' . get_class($payloadResponseObject) : gettype($payloadResponseObject)
));
}
return $payloadResponseObject;
} | [
"public",
"function",
"deserialize",
"(",
"array",
"$",
"payloadResponse",
",",
"$",
"payloadResponseClass",
")",
"{",
"$",
"payloadResponseObject",
"=",
"$",
"this",
"->",
"serializer",
"->",
"deserialize",
"(",
"json_encode",
"(",
"$",
"payloadResponse",
")",
",",
"$",
"payloadResponseClass",
",",
"'json'",
")",
";",
"if",
"(",
"!",
"(",
"$",
"payloadResponseObject",
"instanceof",
"PayloadResponseInterface",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"sprintf",
"(",
"'The serializer expected the response data to be converted into an instance of \"%s\", got: %s'",
",",
"$",
"payloadResponseClass",
",",
"is_object",
"(",
"$",
"payloadResponseObject",
")",
"?",
"'instance of '",
".",
"get_class",
"(",
"$",
"payloadResponseObject",
")",
":",
"gettype",
"(",
"$",
"payloadResponseObject",
")",
")",
")",
";",
"}",
"return",
"$",
"payloadResponseObject",
";",
"}"
] | @param array $payloadResponse
@param string $payloadResponseClass
@return PayloadResponseInterface | [
"@param",
"array",
"$payloadResponse",
"@param",
"string",
"$payloadResponseClass"
] | train | https://github.com/cleentfaar/slack/blob/4639d48252bcbd4a9e5c7619d1f72b55d5a6eeb2/src/CL/Slack/Serializer/PayloadResponseSerializer.php#L27-L44 |
cleentfaar/slack | src/CL/Slack/Transport/ApiClient.php | ApiClient.doSend | private function doSend($method, array $data, $token = null)
{
try {
$data['token'] = $token ?: $this->token;
$this->eventDispatcher->dispatch(self::EVENT_REQUEST, new RequestEvent($data));
$request = $this->createRequest($method, $data);
/** @var ResponseInterface $response */
$response = $this->client->send($request);
} catch (\Exception $e) {
throw new SlackException('Failed to send data to the Slack API', null, $e);
}
try {
$responseData = json_decode($response->getBody()->getContents(), true);
if (!is_array($responseData)) {
throw new \Exception(sprintf(
'Expected JSON-decoded response data to be of type "array", got "%s"',
gettype($responseData)
));
}
$this->eventDispatcher->dispatch(self::EVENT_RESPONSE, new ResponseEvent($responseData));
return $responseData;
} catch (\Exception $e) {
throw new SlackException('Failed to process response from the Slack API', null, $e);
}
} | php | private function doSend($method, array $data, $token = null)
{
try {
$data['token'] = $token ?: $this->token;
$this->eventDispatcher->dispatch(self::EVENT_REQUEST, new RequestEvent($data));
$request = $this->createRequest($method, $data);
/** @var ResponseInterface $response */
$response = $this->client->send($request);
} catch (\Exception $e) {
throw new SlackException('Failed to send data to the Slack API', null, $e);
}
try {
$responseData = json_decode($response->getBody()->getContents(), true);
if (!is_array($responseData)) {
throw new \Exception(sprintf(
'Expected JSON-decoded response data to be of type "array", got "%s"',
gettype($responseData)
));
}
$this->eventDispatcher->dispatch(self::EVENT_RESPONSE, new ResponseEvent($responseData));
return $responseData;
} catch (\Exception $e) {
throw new SlackException('Failed to process response from the Slack API', null, $e);
}
} | [
"private",
"function",
"doSend",
"(",
"$",
"method",
",",
"array",
"$",
"data",
",",
"$",
"token",
"=",
"null",
")",
"{",
"try",
"{",
"$",
"data",
"[",
"'token'",
"]",
"=",
"$",
"token",
"?",
":",
"$",
"this",
"->",
"token",
";",
"$",
"this",
"->",
"eventDispatcher",
"->",
"dispatch",
"(",
"self",
"::",
"EVENT_REQUEST",
",",
"new",
"RequestEvent",
"(",
"$",
"data",
")",
")",
";",
"$",
"request",
"=",
"$",
"this",
"->",
"createRequest",
"(",
"$",
"method",
",",
"$",
"data",
")",
";",
"/** @var ResponseInterface $response */",
"$",
"response",
"=",
"$",
"this",
"->",
"client",
"->",
"send",
"(",
"$",
"request",
")",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"SlackException",
"(",
"'Failed to send data to the Slack API'",
",",
"null",
",",
"$",
"e",
")",
";",
"}",
"try",
"{",
"$",
"responseData",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
"->",
"getContents",
"(",
")",
",",
"true",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"responseData",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"sprintf",
"(",
"'Expected JSON-decoded response data to be of type \"array\", got \"%s\"'",
",",
"gettype",
"(",
"$",
"responseData",
")",
")",
")",
";",
"}",
"$",
"this",
"->",
"eventDispatcher",
"->",
"dispatch",
"(",
"self",
"::",
"EVENT_RESPONSE",
",",
"new",
"ResponseEvent",
"(",
"$",
"responseData",
")",
")",
";",
"return",
"$",
"responseData",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"throw",
"new",
"SlackException",
"(",
"'Failed to process response from the Slack API'",
",",
"null",
",",
"$",
"e",
")",
";",
"}",
"}"
] | @param string $method
@param array $data
@param string|null $token
@throws SlackException
@return array | [
"@param",
"string",
"$method",
"@param",
"array",
"$data",
"@param",
"string|null",
"$token"
] | train | https://github.com/cleentfaar/slack/blob/4639d48252bcbd4a9e5c7619d1f72b55d5a6eeb2/src/CL/Slack/Transport/ApiClient.php#L145-L175 |
cleentfaar/slack | src/CL/Slack/Transport/ApiClient.php | ApiClient.createRequest | private function createRequest($method, array $payload)
{
$request = new Request(
'POST',
self::API_BASE_URL . $method,
['Content-Type' => 'application/x-www-form-urlencoded'],
http_build_query($payload)
);
return $request;
} | php | private function createRequest($method, array $payload)
{
$request = new Request(
'POST',
self::API_BASE_URL . $method,
['Content-Type' => 'application/x-www-form-urlencoded'],
http_build_query($payload)
);
return $request;
} | [
"private",
"function",
"createRequest",
"(",
"$",
"method",
",",
"array",
"$",
"payload",
")",
"{",
"$",
"request",
"=",
"new",
"Request",
"(",
"'POST'",
",",
"self",
"::",
"API_BASE_URL",
".",
"$",
"method",
",",
"[",
"'Content-Type'",
"=>",
"'application/x-www-form-urlencoded'",
"]",
",",
"http_build_query",
"(",
"$",
"payload",
")",
")",
";",
"return",
"$",
"request",
";",
"}"
] | @param string $method
@param array $payload
@return RequestInterface | [
"@param",
"string",
"$method",
"@param",
"array",
"$payload"
] | train | https://github.com/cleentfaar/slack/blob/4639d48252bcbd4a9e5c7619d1f72b55d5a6eeb2/src/CL/Slack/Transport/ApiClient.php#L183-L193 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.