repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
mgp25/Chat-API
src/whatsprot.class.php
WhatsProt.sendReceipt
public function sendReceipt($node, $type = 'read', $participant = null, $callId = null) { $messageHash = []; if ($type == 'read') { $messageHash['type'] = $type; } if ($participant != null) { $messageHash['participant'] = $participant; } $messageHash['to'] = $node->getAttribute('from'); $messageHash['id'] = $node->getAttribute('id'); $messageHash['t'] = $node->getAttribute('t'); if ($callId != null) { $offerNode = new ProtocolNode('offer', ['call-id' => $callId], null, null); $messageNode = new ProtocolNode('receipt', $messageHash, [$offerNode], null); } else { $messageNode = new ProtocolNode('receipt', $messageHash, null, null); } $this->sendNode($messageNode); $this->eventManager()->fire('onSendMessageReceived', [ $this->phoneNumber, $node->getAttribute('id'), $node->getAttribute('from'), $type, ]); }
php
public function sendReceipt($node, $type = 'read', $participant = null, $callId = null) { $messageHash = []; if ($type == 'read') { $messageHash['type'] = $type; } if ($participant != null) { $messageHash['participant'] = $participant; } $messageHash['to'] = $node->getAttribute('from'); $messageHash['id'] = $node->getAttribute('id'); $messageHash['t'] = $node->getAttribute('t'); if ($callId != null) { $offerNode = new ProtocolNode('offer', ['call-id' => $callId], null, null); $messageNode = new ProtocolNode('receipt', $messageHash, [$offerNode], null); } else { $messageNode = new ProtocolNode('receipt', $messageHash, null, null); } $this->sendNode($messageNode); $this->eventManager()->fire('onSendMessageReceived', [ $this->phoneNumber, $node->getAttribute('id'), $node->getAttribute('from'), $type, ]); }
[ "public", "function", "sendReceipt", "(", "$", "node", ",", "$", "type", "=", "'read'", ",", "$", "participant", "=", "null", ",", "$", "callId", "=", "null", ")", "{", "$", "messageHash", "=", "[", "]", ";", "if", "(", "$", "type", "==", "'read'", ")", "{", "$", "messageHash", "[", "'type'", "]", "=", "$", "type", ";", "}", "if", "(", "$", "participant", "!=", "null", ")", "{", "$", "messageHash", "[", "'participant'", "]", "=", "$", "participant", ";", "}", "$", "messageHash", "[", "'to'", "]", "=", "$", "node", "->", "getAttribute", "(", "'from'", ")", ";", "$", "messageHash", "[", "'id'", "]", "=", "$", "node", "->", "getAttribute", "(", "'id'", ")", ";", "$", "messageHash", "[", "'t'", "]", "=", "$", "node", "->", "getAttribute", "(", "'t'", ")", ";", "if", "(", "$", "callId", "!=", "null", ")", "{", "$", "offerNode", "=", "new", "ProtocolNode", "(", "'offer'", ",", "[", "'call-id'", "=>", "$", "callId", "]", ",", "null", ",", "null", ")", ";", "$", "messageNode", "=", "new", "ProtocolNode", "(", "'receipt'", ",", "$", "messageHash", ",", "[", "$", "offerNode", "]", ",", "null", ")", ";", "}", "else", "{", "$", "messageNode", "=", "new", "ProtocolNode", "(", "'receipt'", ",", "$", "messageHash", ",", "null", ",", "null", ")", ";", "}", "$", "this", "->", "sendNode", "(", "$", "messageNode", ")", ";", "$", "this", "->", "eventManager", "(", ")", "->", "fire", "(", "'onSendMessageReceived'", ",", "[", "$", "this", "->", "phoneNumber", ",", "$", "node", "->", "getAttribute", "(", "'id'", ")", ",", "$", "node", "->", "getAttribute", "(", "'from'", ")", ",", "$", "type", ",", "]", ")", ";", "}" ]
Tell the server we received the message. @param ProtocolNode $node The ProtocolTreeNode that contains the message. @param string $type @param string $participant @param string $callId
[ "Tell", "the", "server", "we", "received", "the", "message", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/whatsprot.class.php#L2861-L2888
train
mgp25/Chat-API
src/whatsprot.class.php
WhatsProt.sendMessageRead
public function sendMessageRead($to, $id) { $listNode = null; $idNode = $id; if (is_array($id) && count($id > 1)) { $idNode = array_shift($id); foreach ($id as $itemId) { $items[] = new ProtocolNode('item', [ 'id' => $itemId, ], null, null); } $listNode = new ProtocolNode('list', null, $items, null); } $messageNode = new ProtocolNode('receipt', [ 'type' => 'read', 't' => time(), 'to' => $this->getJID($to), 'id' => $idNode, ], [$listNode], null); $this->sendNode($messageNode); }
php
public function sendMessageRead($to, $id) { $listNode = null; $idNode = $id; if (is_array($id) && count($id > 1)) { $idNode = array_shift($id); foreach ($id as $itemId) { $items[] = new ProtocolNode('item', [ 'id' => $itemId, ], null, null); } $listNode = new ProtocolNode('list', null, $items, null); } $messageNode = new ProtocolNode('receipt', [ 'type' => 'read', 't' => time(), 'to' => $this->getJID($to), 'id' => $idNode, ], [$listNode], null); $this->sendNode($messageNode); }
[ "public", "function", "sendMessageRead", "(", "$", "to", ",", "$", "id", ")", "{", "$", "listNode", "=", "null", ";", "$", "idNode", "=", "$", "id", ";", "if", "(", "is_array", "(", "$", "id", ")", "&&", "count", "(", "$", "id", ">", "1", ")", ")", "{", "$", "idNode", "=", "array_shift", "(", "$", "id", ")", ";", "foreach", "(", "$", "id", "as", "$", "itemId", ")", "{", "$", "items", "[", "]", "=", "new", "ProtocolNode", "(", "'item'", ",", "[", "'id'", "=>", "$", "itemId", ",", "]", ",", "null", ",", "null", ")", ";", "}", "$", "listNode", "=", "new", "ProtocolNode", "(", "'list'", ",", "null", ",", "$", "items", ",", "null", ")", ";", "}", "$", "messageNode", "=", "new", "ProtocolNode", "(", "'receipt'", ",", "[", "'type'", "=>", "'read'", ",", "'t'", "=>", "time", "(", ")", ",", "'to'", "=>", "$", "this", "->", "getJID", "(", "$", "to", ")", ",", "'id'", "=>", "$", "idNode", ",", "]", ",", "[", "$", "listNode", "]", ",", "null", ")", ";", "$", "this", "->", "sendNode", "(", "$", "messageNode", ")", ";", "}" ]
Send a read receipt to a message. @param string $to The recipient. @param mixed String or Array $id
[ "Send", "a", "read", "receipt", "to", "a", "message", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/whatsprot.class.php#L2896-L2920
train
mgp25/Chat-API
src/whatsprot.class.php
WhatsProt.sendNode
public function sendNode($node, $encrypt = true) { $this->timeout = time(); $this->debugPrint($node->nodeString('tx ')."\n"); $this->sendData($this->writer->write($node, $encrypt)); }
php
public function sendNode($node, $encrypt = true) { $this->timeout = time(); $this->debugPrint($node->nodeString('tx ')."\n"); $this->sendData($this->writer->write($node, $encrypt)); }
[ "public", "function", "sendNode", "(", "$", "node", ",", "$", "encrypt", "=", "true", ")", "{", "$", "this", "->", "timeout", "=", "time", "(", ")", ";", "$", "this", "->", "debugPrint", "(", "$", "node", "->", "nodeString", "(", "'tx '", ")", ".", "\"\\n\"", ")", ";", "$", "this", "->", "sendData", "(", "$", "this", "->", "writer", "->", "write", "(", "$", "node", ",", "$", "encrypt", ")", ")", ";", "}" ]
Send node to the WhatsApp server. @param ProtocolNode $node @param bool $encrypt
[ "Send", "node", "to", "the", "WhatsApp", "server", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/whatsprot.class.php#L2928-L2933
train
mgp25/Chat-API
src/whatsprot.class.php
WhatsProt.sendRequestFileUpload
protected function sendRequestFileUpload($b64hash, $type, $size, $filepath, $to, $caption = '') { $id = $this->createIqId(); if (!is_array($to)) { $to = $this->getJID($to); } $mediaNode = new ProtocolNode('media', [ 'hash' => $b64hash, 'type' => $type, 'size' => $size, ], null, null); $node = new ProtocolNode('iq', [ 'id' => $id, 'to' => Constants::WHATSAPP_SERVER, 'type' => 'set', 'xmlns' => 'w:m', ], [$mediaNode], null); //add to queue $messageId = $this->createMsgId(); $this->mediaQueue[$id] = [ 'messageNode' => $node, 'filePath' => $filepath, 'to' => $to, 'message_id' => $messageId, 'caption' => $caption, ]; $this->sendNode($node); $this->waitForServer($id); // Return message ID. Make pull request for this. return $messageId; }
php
protected function sendRequestFileUpload($b64hash, $type, $size, $filepath, $to, $caption = '') { $id = $this->createIqId(); if (!is_array($to)) { $to = $this->getJID($to); } $mediaNode = new ProtocolNode('media', [ 'hash' => $b64hash, 'type' => $type, 'size' => $size, ], null, null); $node = new ProtocolNode('iq', [ 'id' => $id, 'to' => Constants::WHATSAPP_SERVER, 'type' => 'set', 'xmlns' => 'w:m', ], [$mediaNode], null); //add to queue $messageId = $this->createMsgId(); $this->mediaQueue[$id] = [ 'messageNode' => $node, 'filePath' => $filepath, 'to' => $to, 'message_id' => $messageId, 'caption' => $caption, ]; $this->sendNode($node); $this->waitForServer($id); // Return message ID. Make pull request for this. return $messageId; }
[ "protected", "function", "sendRequestFileUpload", "(", "$", "b64hash", ",", "$", "type", ",", "$", "size", ",", "$", "filepath", ",", "$", "to", ",", "$", "caption", "=", "''", ")", "{", "$", "id", "=", "$", "this", "->", "createIqId", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "to", ")", ")", "{", "$", "to", "=", "$", "this", "->", "getJID", "(", "$", "to", ")", ";", "}", "$", "mediaNode", "=", "new", "ProtocolNode", "(", "'media'", ",", "[", "'hash'", "=>", "$", "b64hash", ",", "'type'", "=>", "$", "type", ",", "'size'", "=>", "$", "size", ",", "]", ",", "null", ",", "null", ")", ";", "$", "node", "=", "new", "ProtocolNode", "(", "'iq'", ",", "[", "'id'", "=>", "$", "id", ",", "'to'", "=>", "Constants", "::", "WHATSAPP_SERVER", ",", "'type'", "=>", "'set'", ",", "'xmlns'", "=>", "'w:m'", ",", "]", ",", "[", "$", "mediaNode", "]", ",", "null", ")", ";", "//add to queue", "$", "messageId", "=", "$", "this", "->", "createMsgId", "(", ")", ";", "$", "this", "->", "mediaQueue", "[", "$", "id", "]", "=", "[", "'messageNode'", "=>", "$", "node", ",", "'filePath'", "=>", "$", "filepath", ",", "'to'", "=>", "$", "to", ",", "'message_id'", "=>", "$", "messageId", ",", "'caption'", "=>", "$", "caption", ",", "]", ";", "$", "this", "->", "sendNode", "(", "$", "node", ")", ";", "$", "this", "->", "waitForServer", "(", "$", "id", ")", ";", "// Return message ID. Make pull request for this.", "return", "$", "messageId", ";", "}" ]
Send request to upload file. @param string $b64hash A base64 hash of file @param string $type File type @param string $size File size @param string $filepath Path to image file @param mixed $to Recipient(s) @param string $caption @return string Message ID
[ "Send", "request", "to", "upload", "file", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/whatsprot.class.php#L2947-L2983
train
mgp25/Chat-API
src/whatsprot.class.php
WhatsProt.sendSetPicture
protected function sendSetPicture($jid, $filepath) { $nodeID = $this->createIqId(); $data = preprocessProfilePicture($filepath); $preview = createIconGD($filepath, 96, true); $picture = new ProtocolNode('picture', ['type' => 'image'], null, $data); $preview = new ProtocolNode('picture', ['type' => 'preview'], null, $preview); $node = new ProtocolNode('iq', [ 'id' => $nodeID, 'to' => $this->getJID($jid), 'type' => 'set', 'xmlns' => 'w:profile:picture', ], [$picture, $preview], null); $this->sendNode($node); }
php
protected function sendSetPicture($jid, $filepath) { $nodeID = $this->createIqId(); $data = preprocessProfilePicture($filepath); $preview = createIconGD($filepath, 96, true); $picture = new ProtocolNode('picture', ['type' => 'image'], null, $data); $preview = new ProtocolNode('picture', ['type' => 'preview'], null, $preview); $node = new ProtocolNode('iq', [ 'id' => $nodeID, 'to' => $this->getJID($jid), 'type' => 'set', 'xmlns' => 'w:profile:picture', ], [$picture, $preview], null); $this->sendNode($node); }
[ "protected", "function", "sendSetPicture", "(", "$", "jid", ",", "$", "filepath", ")", "{", "$", "nodeID", "=", "$", "this", "->", "createIqId", "(", ")", ";", "$", "data", "=", "preprocessProfilePicture", "(", "$", "filepath", ")", ";", "$", "preview", "=", "createIconGD", "(", "$", "filepath", ",", "96", ",", "true", ")", ";", "$", "picture", "=", "new", "ProtocolNode", "(", "'picture'", ",", "[", "'type'", "=>", "'image'", "]", ",", "null", ",", "$", "data", ")", ";", "$", "preview", "=", "new", "ProtocolNode", "(", "'picture'", ",", "[", "'type'", "=>", "'preview'", "]", ",", "null", ",", "$", "preview", ")", ";", "$", "node", "=", "new", "ProtocolNode", "(", "'iq'", ",", "[", "'id'", "=>", "$", "nodeID", ",", "'to'", "=>", "$", "this", "->", "getJID", "(", "$", "jid", ")", ",", "'type'", "=>", "'set'", ",", "'xmlns'", "=>", "'w:profile:picture'", ",", "]", ",", "[", "$", "picture", ",", "$", "preview", "]", ",", "null", ")", ";", "$", "this", "->", "sendNode", "(", "$", "node", ")", ";", "}" ]
Set your profile picture. @param string $jid @param string $filepath URL or localpath to image file
[ "Set", "your", "profile", "picture", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/whatsprot.class.php#L2991-L3009
train
mgp25/Chat-API
src/protocol.class.php
ProtocolNode.isCli
private static function isCli() { if (self::$cli === null) { //initial setter if (php_sapi_name() == 'cli') { self::$cli = true; } else { self::$cli = false; } } return self::$cli; }
php
private static function isCli() { if (self::$cli === null) { //initial setter if (php_sapi_name() == 'cli') { self::$cli = true; } else { self::$cli = false; } } return self::$cli; }
[ "private", "static", "function", "isCli", "(", ")", "{", "if", "(", "self", "::", "$", "cli", "===", "null", ")", "{", "//initial setter", "if", "(", "php_sapi_name", "(", ")", "==", "'cli'", ")", "{", "self", "::", "$", "cli", "=", "true", ";", "}", "else", "{", "self", "::", "$", "cli", "=", "false", ";", "}", "}", "return", "self", "::", "$", "cli", ";", "}" ]
check if call is from command line. @return bool
[ "check", "if", "call", "is", "from", "command", "line", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/protocol.class.php#L38-L50
train
mgp25/Chat-API
src/Login.php
Login.doLogin
public function doLogin() { if ($this->parent->isLoggedIn()) { return true; } $this->parent->writer->resetKey(); $this->parent->reader->resetKey(); $resource = Constants::PLATFORM.'-'.Constants::WHATSAPP_VER; $data = $this->parent->writer->StartStream(Constants::WHATSAPP_SERVER, $resource); $feat = $this->createFeaturesNode(); $auth = $this->createAuthNode(); $this->parent->sendData($data); $this->parent->sendNode($feat); $this->parent->sendNode($auth); $this->parent->pollMessage(); $this->parent->pollMessage(); $this->parent->pollMessage(); if ($this->parent->getChallengeData() != null) { $data = $this->createAuthResponseNode(); $this->parent->sendNode($data); $this->parent->reader->setKey($this->inputKey); $this->parent->writer->setKey($this->outputKey); while (!$this->parent->pollMessage()) { }; } if ($this->parent->getLoginStatus() === Constants::DISCONNECTED_STATUS) { throw new LoginFailureException(); } $this->parent->logFile('info', '{number} successfully logged in', ['number' => $this->phoneNumber]); $this->parent->sendAvailableForChat(); $this->parent->sendGetPrivacyBlockedList(); $this->parent->sendGetClientConfig(); $this->parent->setMessageId(substr(bin2hex(mcrypt_create_iv(64, MCRYPT_DEV_URANDOM)), 0, 22)); // 11 char hex if (extension_loaded('curve25519') || extension_loaded('protobuf')) { if (file_exists($this->parent->dataFolder.'axolotl-'.$this->phoneNumber.'.db')) { $pre_keys = $this->parent->getAxolotlStore()->loadPreKeys(); if (empty($pre_keys)) { $this->parent->sendSetPreKeys(); $this->parent->logFile('info', 'Sending prekeys to WA server'); } } } return true; }
php
public function doLogin() { if ($this->parent->isLoggedIn()) { return true; } $this->parent->writer->resetKey(); $this->parent->reader->resetKey(); $resource = Constants::PLATFORM.'-'.Constants::WHATSAPP_VER; $data = $this->parent->writer->StartStream(Constants::WHATSAPP_SERVER, $resource); $feat = $this->createFeaturesNode(); $auth = $this->createAuthNode(); $this->parent->sendData($data); $this->parent->sendNode($feat); $this->parent->sendNode($auth); $this->parent->pollMessage(); $this->parent->pollMessage(); $this->parent->pollMessage(); if ($this->parent->getChallengeData() != null) { $data = $this->createAuthResponseNode(); $this->parent->sendNode($data); $this->parent->reader->setKey($this->inputKey); $this->parent->writer->setKey($this->outputKey); while (!$this->parent->pollMessage()) { }; } if ($this->parent->getLoginStatus() === Constants::DISCONNECTED_STATUS) { throw new LoginFailureException(); } $this->parent->logFile('info', '{number} successfully logged in', ['number' => $this->phoneNumber]); $this->parent->sendAvailableForChat(); $this->parent->sendGetPrivacyBlockedList(); $this->parent->sendGetClientConfig(); $this->parent->setMessageId(substr(bin2hex(mcrypt_create_iv(64, MCRYPT_DEV_URANDOM)), 0, 22)); // 11 char hex if (extension_loaded('curve25519') || extension_loaded('protobuf')) { if (file_exists($this->parent->dataFolder.'axolotl-'.$this->phoneNumber.'.db')) { $pre_keys = $this->parent->getAxolotlStore()->loadPreKeys(); if (empty($pre_keys)) { $this->parent->sendSetPreKeys(); $this->parent->logFile('info', 'Sending prekeys to WA server'); } } } return true; }
[ "public", "function", "doLogin", "(", ")", "{", "if", "(", "$", "this", "->", "parent", "->", "isLoggedIn", "(", ")", ")", "{", "return", "true", ";", "}", "$", "this", "->", "parent", "->", "writer", "->", "resetKey", "(", ")", ";", "$", "this", "->", "parent", "->", "reader", "->", "resetKey", "(", ")", ";", "$", "resource", "=", "Constants", "::", "PLATFORM", ".", "'-'", ".", "Constants", "::", "WHATSAPP_VER", ";", "$", "data", "=", "$", "this", "->", "parent", "->", "writer", "->", "StartStream", "(", "Constants", "::", "WHATSAPP_SERVER", ",", "$", "resource", ")", ";", "$", "feat", "=", "$", "this", "->", "createFeaturesNode", "(", ")", ";", "$", "auth", "=", "$", "this", "->", "createAuthNode", "(", ")", ";", "$", "this", "->", "parent", "->", "sendData", "(", "$", "data", ")", ";", "$", "this", "->", "parent", "->", "sendNode", "(", "$", "feat", ")", ";", "$", "this", "->", "parent", "->", "sendNode", "(", "$", "auth", ")", ";", "$", "this", "->", "parent", "->", "pollMessage", "(", ")", ";", "$", "this", "->", "parent", "->", "pollMessage", "(", ")", ";", "$", "this", "->", "parent", "->", "pollMessage", "(", ")", ";", "if", "(", "$", "this", "->", "parent", "->", "getChallengeData", "(", ")", "!=", "null", ")", "{", "$", "data", "=", "$", "this", "->", "createAuthResponseNode", "(", ")", ";", "$", "this", "->", "parent", "->", "sendNode", "(", "$", "data", ")", ";", "$", "this", "->", "parent", "->", "reader", "->", "setKey", "(", "$", "this", "->", "inputKey", ")", ";", "$", "this", "->", "parent", "->", "writer", "->", "setKey", "(", "$", "this", "->", "outputKey", ")", ";", "while", "(", "!", "$", "this", "->", "parent", "->", "pollMessage", "(", ")", ")", "{", "}", ";", "}", "if", "(", "$", "this", "->", "parent", "->", "getLoginStatus", "(", ")", "===", "Constants", "::", "DISCONNECTED_STATUS", ")", "{", "throw", "new", "LoginFailureException", "(", ")", ";", "}", "$", "this", "->", "parent", "->", "logFile", "(", "'info'", ",", "'{number} successfully logged in'", ",", "[", "'number'", "=>", "$", "this", "->", "phoneNumber", "]", ")", ";", "$", "this", "->", "parent", "->", "sendAvailableForChat", "(", ")", ";", "$", "this", "->", "parent", "->", "sendGetPrivacyBlockedList", "(", ")", ";", "$", "this", "->", "parent", "->", "sendGetClientConfig", "(", ")", ";", "$", "this", "->", "parent", "->", "setMessageId", "(", "substr", "(", "bin2hex", "(", "mcrypt_create_iv", "(", "64", ",", "MCRYPT_DEV_URANDOM", ")", ")", ",", "0", ",", "22", ")", ")", ";", "// 11 char hex", "if", "(", "extension_loaded", "(", "'curve25519'", ")", "||", "extension_loaded", "(", "'protobuf'", ")", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "parent", "->", "dataFolder", ".", "'axolotl-'", ".", "$", "this", "->", "phoneNumber", ".", "'.db'", ")", ")", "{", "$", "pre_keys", "=", "$", "this", "->", "parent", "->", "getAxolotlStore", "(", ")", "->", "loadPreKeys", "(", ")", ";", "if", "(", "empty", "(", "$", "pre_keys", ")", ")", "{", "$", "this", "->", "parent", "->", "sendSetPreKeys", "(", ")", ";", "$", "this", "->", "parent", "->", "logFile", "(", "'info'", ",", "'Sending prekeys to WA server'", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
Send the nodes to the WhatsApp server to log in. @throws Exception
[ "Send", "the", "nodes", "to", "the", "WhatsApp", "server", "to", "log", "in", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Login.php#L24-L74
train
mgp25/Chat-API
src/Login.php
Login.createAuthNode
protected function createAuthNode() { $data = $this->createAuthBlob(); $attributes = [ 'user' => $this->phoneNumber, 'mechanism' => 'WAUTH-2', ]; $node = new ProtocolNode('auth', $attributes, null, $data); return $node; }
php
protected function createAuthNode() { $data = $this->createAuthBlob(); $attributes = [ 'user' => $this->phoneNumber, 'mechanism' => 'WAUTH-2', ]; $node = new ProtocolNode('auth', $attributes, null, $data); return $node; }
[ "protected", "function", "createAuthNode", "(", ")", "{", "$", "data", "=", "$", "this", "->", "createAuthBlob", "(", ")", ";", "$", "attributes", "=", "[", "'user'", "=>", "$", "this", "->", "phoneNumber", ",", "'mechanism'", "=>", "'WAUTH-2'", ",", "]", ";", "$", "node", "=", "new", "ProtocolNode", "(", "'auth'", ",", "$", "attributes", ",", "null", ",", "$", "data", ")", ";", "return", "$", "node", ";", "}" ]
Add the authentication nodes. @return ProtocolNode Returns an authentication node.
[ "Add", "the", "authentication", "nodes", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Login.php#L97-L108
train
mgp25/Chat-API
src/Login.php
Login.authenticate
protected function authenticate() { $keys = KeyStream::GenerateKeys(base64_decode($this->password), $this->parent->getChallengeData()); $this->inputKey = new KeyStream($keys[2], $keys[3]); $this->outputKey = new KeyStream($keys[0], $keys[1]); $array = "\0\0\0\0".$this->phoneNumber.$this->parent->getChallengeData().''.time().'000'.hex2bin('00').'000'.hex2bin('00') .Constants::OS_VERSION.hex2bin('00').Constants::MANUFACTURER.hex2bin('00').Constants::DEVICE.hex2bin('00').Constants::BUILD_VERSION; $response = $this->outputKey->EncodeMessage($array, 0, 4, strlen($array) - 4); $this->parent->setOutputKey($this->outputKey); return $response; }
php
protected function authenticate() { $keys = KeyStream::GenerateKeys(base64_decode($this->password), $this->parent->getChallengeData()); $this->inputKey = new KeyStream($keys[2], $keys[3]); $this->outputKey = new KeyStream($keys[0], $keys[1]); $array = "\0\0\0\0".$this->phoneNumber.$this->parent->getChallengeData().''.time().'000'.hex2bin('00').'000'.hex2bin('00') .Constants::OS_VERSION.hex2bin('00').Constants::MANUFACTURER.hex2bin('00').Constants::DEVICE.hex2bin('00').Constants::BUILD_VERSION; $response = $this->outputKey->EncodeMessage($array, 0, 4, strlen($array) - 4); $this->parent->setOutputKey($this->outputKey); return $response; }
[ "protected", "function", "authenticate", "(", ")", "{", "$", "keys", "=", "KeyStream", "::", "GenerateKeys", "(", "base64_decode", "(", "$", "this", "->", "password", ")", ",", "$", "this", "->", "parent", "->", "getChallengeData", "(", ")", ")", ";", "$", "this", "->", "inputKey", "=", "new", "KeyStream", "(", "$", "keys", "[", "2", "]", ",", "$", "keys", "[", "3", "]", ")", ";", "$", "this", "->", "outputKey", "=", "new", "KeyStream", "(", "$", "keys", "[", "0", "]", ",", "$", "keys", "[", "1", "]", ")", ";", "$", "array", "=", "\"\\0\\0\\0\\0\"", ".", "$", "this", "->", "phoneNumber", ".", "$", "this", "->", "parent", "->", "getChallengeData", "(", ")", ".", "''", ".", "time", "(", ")", ".", "'000'", ".", "hex2bin", "(", "'00'", ")", ".", "'000'", ".", "hex2bin", "(", "'00'", ")", ".", "Constants", "::", "OS_VERSION", ".", "hex2bin", "(", "'00'", ")", ".", "Constants", "::", "MANUFACTURER", ".", "hex2bin", "(", "'00'", ")", ".", "Constants", "::", "DEVICE", ".", "hex2bin", "(", "'00'", ")", ".", "Constants", "::", "BUILD_VERSION", ";", "$", "response", "=", "$", "this", "->", "outputKey", "->", "EncodeMessage", "(", "$", "array", ",", "0", ",", "4", ",", "strlen", "(", "$", "array", ")", "-", "4", ")", ";", "$", "this", "->", "parent", "->", "setOutputKey", "(", "$", "this", "->", "outputKey", ")", ";", "return", "$", "response", ";", "}" ]
Authenticate with the WhatsApp Server. @return string Returns binary string
[ "Authenticate", "with", "the", "WhatsApp", "Server", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Login.php#L140-L151
train
mgp25/Chat-API
src/vCard.php
vCard.set
public function set($key, $value) { // Check if the specified property is defined. if (property_exists($this, $key) && $key != 'data') { $this->{$key} = trim($value); return $this; } elseif (property_exists($this, $key) && $key == 'data') { foreach ($value as $v_key => $v_value) { $this->{$key}[$v_key] = trim($v_value); } return $this; } else { return false; } }
php
public function set($key, $value) { // Check if the specified property is defined. if (property_exists($this, $key) && $key != 'data') { $this->{$key} = trim($value); return $this; } elseif (property_exists($this, $key) && $key == 'data') { foreach ($value as $v_key => $v_value) { $this->{$key}[$v_key] = trim($v_value); } return $this; } else { return false; } }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "// Check if the specified property is defined.", "if", "(", "property_exists", "(", "$", "this", ",", "$", "key", ")", "&&", "$", "key", "!=", "'data'", ")", "{", "$", "this", "->", "{", "$", "key", "}", "=", "trim", "(", "$", "value", ")", ";", "return", "$", "this", ";", "}", "elseif", "(", "property_exists", "(", "$", "this", ",", "$", "key", ")", "&&", "$", "key", "==", "'data'", ")", "{", "foreach", "(", "$", "value", "as", "$", "v_key", "=>", "$", "v_value", ")", "{", "$", "this", "->", "{", "$", "key", "}", "[", "$", "v_key", "]", "=", "trim", "(", "$", "v_value", ")", ";", "}", "return", "$", "this", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Global setter. @param string $key Name of the property. @param mixed $value Value to set. @return vCard Return itself.
[ "Global", "setter", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/vCard.php#L79-L95
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.cleanPostInputs
private function cleanPostInputs() { $args = [ 'action' => FILTER_SANITIZE_STRING, 'password' => FILTER_SANITIZE_STRING, 'from' => FILTER_SANITIZE_STRING, 'to' => [ 'filter' => FILTER_SANITIZE_NUMBER_INT, 'flags' => FILTER_REQUIRE_ARRAY, ], 'message' => FILTER_UNSAFE_RAW, 'image' => FILTER_VALIDATE_URL, 'audio' => FILTER_VALIDATE_URL, 'video' => FILTER_VALIDATE_URL, 'locationname' => FILTER_SANITIZE_STRING, 'status' => FILTER_SANITIZE_STRING, 'userlat' => FILTER_SANITIZE_STRING, 'userlong' => FILTER_SANITIZE_STRING, ]; $myinputs = filter_input_array(INPUT_POST, $args); if (!$myinputs) { throw Exception('Problem Filtering the inputs'); } return $myinputs; }
php
private function cleanPostInputs() { $args = [ 'action' => FILTER_SANITIZE_STRING, 'password' => FILTER_SANITIZE_STRING, 'from' => FILTER_SANITIZE_STRING, 'to' => [ 'filter' => FILTER_SANITIZE_NUMBER_INT, 'flags' => FILTER_REQUIRE_ARRAY, ], 'message' => FILTER_UNSAFE_RAW, 'image' => FILTER_VALIDATE_URL, 'audio' => FILTER_VALIDATE_URL, 'video' => FILTER_VALIDATE_URL, 'locationname' => FILTER_SANITIZE_STRING, 'status' => FILTER_SANITIZE_STRING, 'userlat' => FILTER_SANITIZE_STRING, 'userlong' => FILTER_SANITIZE_STRING, ]; $myinputs = filter_input_array(INPUT_POST, $args); if (!$myinputs) { throw Exception('Problem Filtering the inputs'); } return $myinputs; }
[ "private", "function", "cleanPostInputs", "(", ")", "{", "$", "args", "=", "[", "'action'", "=>", "FILTER_SANITIZE_STRING", ",", "'password'", "=>", "FILTER_SANITIZE_STRING", ",", "'from'", "=>", "FILTER_SANITIZE_STRING", ",", "'to'", "=>", "[", "'filter'", "=>", "FILTER_SANITIZE_NUMBER_INT", ",", "'flags'", "=>", "FILTER_REQUIRE_ARRAY", ",", "]", ",", "'message'", "=>", "FILTER_UNSAFE_RAW", ",", "'image'", "=>", "FILTER_VALIDATE_URL", ",", "'audio'", "=>", "FILTER_VALIDATE_URL", ",", "'video'", "=>", "FILTER_VALIDATE_URL", ",", "'locationname'", "=>", "FILTER_SANITIZE_STRING", ",", "'status'", "=>", "FILTER_SANITIZE_STRING", ",", "'userlat'", "=>", "FILTER_SANITIZE_STRING", ",", "'userlong'", "=>", "FILTER_SANITIZE_STRING", ",", "]", ";", "$", "myinputs", "=", "filter_input_array", "(", "INPUT_POST", ",", "$", "args", ")", ";", "if", "(", "!", "$", "myinputs", ")", "{", "throw", "Exception", "(", "'Problem Filtering the inputs'", ")", ";", "}", "return", "$", "myinputs", ";", "}" ]
Clean and Filter the inputted Form values. This function attempts to clean and filter input values from the form in the $_POST array. As nothing is currently put into a database etc, this is probably not required, but it should help if someone wishes to extend this project later. @throws Exception If no $_POST values submitted. @return array array with values that have been filtered.
[ "Clean", "and", "Filter", "the", "inputted", "Form", "values", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L359-L385
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.process
public function process() { switch ($this->inputs['action']) { case 'login': $this->webLogin(); break; case 'logout': $this->webLogout(); exit($this->showWebLoginForm()); break; case 'getContacts': $this->getContacts(); break; case 'updateStatus': $this->updateStatus(); break; case 'sendMessage': $this->sendMessage(); break; case 'sendBroadcast': $this->sendBroadcast(); break; default: if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) { exit($this->showWebForm()); } exit($this->showWebLoginForm()); break; } }
php
public function process() { switch ($this->inputs['action']) { case 'login': $this->webLogin(); break; case 'logout': $this->webLogout(); exit($this->showWebLoginForm()); break; case 'getContacts': $this->getContacts(); break; case 'updateStatus': $this->updateStatus(); break; case 'sendMessage': $this->sendMessage(); break; case 'sendBroadcast': $this->sendBroadcast(); break; default: if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) { exit($this->showWebForm()); } exit($this->showWebLoginForm()); break; } }
[ "public", "function", "process", "(", ")", "{", "switch", "(", "$", "this", "->", "inputs", "[", "'action'", "]", ")", "{", "case", "'login'", ":", "$", "this", "->", "webLogin", "(", ")", ";", "break", ";", "case", "'logout'", ":", "$", "this", "->", "webLogout", "(", ")", ";", "exit", "(", "$", "this", "->", "showWebLoginForm", "(", ")", ")", ";", "break", ";", "case", "'getContacts'", ":", "$", "this", "->", "getContacts", "(", ")", ";", "break", ";", "case", "'updateStatus'", ":", "$", "this", "->", "updateStatus", "(", ")", ";", "break", ";", "case", "'sendMessage'", ":", "$", "this", "->", "sendMessage", "(", ")", ";", "break", ";", "case", "'sendBroadcast'", ":", "$", "this", "->", "sendBroadcast", "(", ")", ";", "break", ";", "default", ":", "if", "(", "isset", "(", "$", "_SESSION", "[", "'logged_in'", "]", ")", "&&", "$", "_SESSION", "[", "'logged_in'", "]", "==", "true", ")", "{", "exit", "(", "$", "this", "->", "showWebForm", "(", ")", ")", ";", "}", "exit", "(", "$", "this", "->", "showWebLoginForm", "(", ")", ")", ";", "break", ";", "}", "}" ]
Process the latest request. Decide what course of action to take with the latest request/post to this script. @return void
[ "Process", "the", "latest", "request", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L395-L424
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.getContacts
private function getContacts() { try { //Get whatsapp's Groups this user belongs to. $this->waGroupList = []; $this->getGroupList(); if (is_array($this->waGroupList)) { $this->contacts = array_merge($this->contacts, $this->waGroupList); } //Get contacts from google if gmail account configured. $googleContacts = []; if (isset($this->config[$this->from]['email'])) { $email = $this->config[$this->from]['email']; if (stripos($email, 'gmail') !== false || stripos($email, 'googlemail') !== false) { $google = new GoogleContacts(); $googleContacts = $google->getContacts($this->config, $this->from); if (is_array($googleContacts)) { $this->contacts = array_merge($this->contacts, $googleContacts); } } } if (isset($this->contacts)) { exit(json_encode([ 'success' => true, 'type' => 'contacts', 'data' => $this->contacts, 'messages' => $this->messages, ])); } } catch (Exception $e) { exit(json_encode([ 'success' => false, 'type' => 'contacts', 'errormsg' => $e->getMessage(), ])); } }
php
private function getContacts() { try { //Get whatsapp's Groups this user belongs to. $this->waGroupList = []; $this->getGroupList(); if (is_array($this->waGroupList)) { $this->contacts = array_merge($this->contacts, $this->waGroupList); } //Get contacts from google if gmail account configured. $googleContacts = []; if (isset($this->config[$this->from]['email'])) { $email = $this->config[$this->from]['email']; if (stripos($email, 'gmail') !== false || stripos($email, 'googlemail') !== false) { $google = new GoogleContacts(); $googleContacts = $google->getContacts($this->config, $this->from); if (is_array($googleContacts)) { $this->contacts = array_merge($this->contacts, $googleContacts); } } } if (isset($this->contacts)) { exit(json_encode([ 'success' => true, 'type' => 'contacts', 'data' => $this->contacts, 'messages' => $this->messages, ])); } } catch (Exception $e) { exit(json_encode([ 'success' => false, 'type' => 'contacts', 'errormsg' => $e->getMessage(), ])); } }
[ "private", "function", "getContacts", "(", ")", "{", "try", "{", "//Get whatsapp's Groups this user belongs to.", "$", "this", "->", "waGroupList", "=", "[", "]", ";", "$", "this", "->", "getGroupList", "(", ")", ";", "if", "(", "is_array", "(", "$", "this", "->", "waGroupList", ")", ")", "{", "$", "this", "->", "contacts", "=", "array_merge", "(", "$", "this", "->", "contacts", ",", "$", "this", "->", "waGroupList", ")", ";", "}", "//Get contacts from google if gmail account configured.", "$", "googleContacts", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "config", "[", "$", "this", "->", "from", "]", "[", "'email'", "]", ")", ")", "{", "$", "email", "=", "$", "this", "->", "config", "[", "$", "this", "->", "from", "]", "[", "'email'", "]", ";", "if", "(", "stripos", "(", "$", "email", ",", "'gmail'", ")", "!==", "false", "||", "stripos", "(", "$", "email", ",", "'googlemail'", ")", "!==", "false", ")", "{", "$", "google", "=", "new", "GoogleContacts", "(", ")", ";", "$", "googleContacts", "=", "$", "google", "->", "getContacts", "(", "$", "this", "->", "config", ",", "$", "this", "->", "from", ")", ";", "if", "(", "is_array", "(", "$", "googleContacts", ")", ")", "{", "$", "this", "->", "contacts", "=", "array_merge", "(", "$", "this", "->", "contacts", ",", "$", "googleContacts", ")", ";", "}", "}", "}", "if", "(", "isset", "(", "$", "this", "->", "contacts", ")", ")", "{", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "true", ",", "'type'", "=>", "'contacts'", ",", "'data'", "=>", "$", "this", "->", "contacts", ",", "'messages'", "=>", "$", "this", "->", "messages", ",", "]", ")", ")", ";", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "false", ",", "'type'", "=>", "'contacts'", ",", "'errormsg'", "=>", "$", "e", "->", "getMessage", "(", ")", ",", "]", ")", ")", ";", "}", "}" ]
Get Contacts from various sources to display in form. This method will allow you to add contacts from external sources to add to the "to box" dropdown list on the form. Currently this can include: - Whatsapp Groups for the current user - Google Contacts (if username/password was supplied in config) @return void
[ "Get", "Contacts", "from", "various", "sources", "to", "display", "in", "form", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L437-L476
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.connectToWhatsApp
private function connectToWhatsApp() { if (isset($this->wa)) { $this->wa->connect(); $this->wa->loginWithPassword($this->password); return true; } return false; }
php
private function connectToWhatsApp() { if (isset($this->wa)) { $this->wa->connect(); $this->wa->loginWithPassword($this->password); return true; } return false; }
[ "private", "function", "connectToWhatsApp", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "wa", ")", ")", "{", "$", "this", "->", "wa", "->", "connect", "(", ")", ";", "$", "this", "->", "wa", "->", "loginWithPassword", "(", "$", "this", "->", "password", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Connect to Whatsapp. Create a connection to the whatsapp servers using the supplied password. @return bool
[ "Connect", "to", "Whatsapp", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L501-L511
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.processReceivedMessage
public function processReceivedMessage($phone, $from, $id, $type, $time, $name, $data) { $matches = null; $time = date('Y-m-d H:i:s', $time); if (preg_match('/\d*/', $from, $matches)) { $from = $matches[0]; } $this->messages[] = ['phone' => $phone, 'from' => $from, 'id' => $id, 'type' => $type, 'time' => $time, 'name' => $name, 'data' => $data]; }
php
public function processReceivedMessage($phone, $from, $id, $type, $time, $name, $data) { $matches = null; $time = date('Y-m-d H:i:s', $time); if (preg_match('/\d*/', $from, $matches)) { $from = $matches[0]; } $this->messages[] = ['phone' => $phone, 'from' => $from, 'id' => $id, 'type' => $type, 'time' => $time, 'name' => $name, 'data' => $data]; }
[ "public", "function", "processReceivedMessage", "(", "$", "phone", ",", "$", "from", ",", "$", "id", ",", "$", "type", ",", "$", "time", ",", "$", "name", ",", "$", "data", ")", "{", "$", "matches", "=", "null", ";", "$", "time", "=", "date", "(", "'Y-m-d H:i:s'", ",", "$", "time", ")", ";", "if", "(", "preg_match", "(", "'/\\d*/'", ",", "$", "from", ",", "$", "matches", ")", ")", "{", "$", "from", "=", "$", "matches", "[", "0", "]", ";", "}", "$", "this", "->", "messages", "[", "]", "=", "[", "'phone'", "=>", "$", "phone", ",", "'from'", "=>", "$", "from", ",", "'id'", "=>", "$", "id", ",", "'type'", "=>", "$", "type", ",", "'time'", "=>", "$", "time", ",", "'name'", "=>", "$", "name", ",", "'data'", "=>", "$", "data", "]", ";", "}" ]
Process inbound text messages. If an inbound message is detected, this method will store the details so that it can be shown to the user at a suitable time. @param string $phone The number that is receiving the message @param string $from The number that is sending the message @param string $id The unique ID for the message @param string $type Type of inbound message @param string $time Y-m-d H:m:s formatted string @param string $name The Name of sender (nick) @param string $data The actual message @return void
[ "Process", "inbound", "text", "messages", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L544-L552
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.processGroupArray
public function processGroupArray($phone, $groupArray) { $formattedGroups = []; if (!empty($groupArray)) { foreach ($groupArray as $group) { $formattedGroups[] = ['name' => 'GROUP: '.$group['subject'], 'id' => $group['id']]; } $this->waGroupList = $formattedGroups; return true; } return false; }
php
public function processGroupArray($phone, $groupArray) { $formattedGroups = []; if (!empty($groupArray)) { foreach ($groupArray as $group) { $formattedGroups[] = ['name' => 'GROUP: '.$group['subject'], 'id' => $group['id']]; } $this->waGroupList = $formattedGroups; return true; } return false; }
[ "public", "function", "processGroupArray", "(", "$", "phone", ",", "$", "groupArray", ")", "{", "$", "formattedGroups", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "groupArray", ")", ")", "{", "foreach", "(", "$", "groupArray", "as", "$", "group", ")", "{", "$", "formattedGroups", "[", "]", "=", "[", "'name'", "=>", "'GROUP: '", ".", "$", "group", "[", "'subject'", "]", ",", "'id'", "=>", "$", "group", "[", "'id'", "]", "]", ";", "}", "$", "this", "->", "waGroupList", "=", "$", "formattedGroups", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Process the event onGetGroupList and sets a formatted array of groups the user belongs to. @param string $phone The phone number (jid ) of the user @param array $groupArray Array with details of all groups user eitehr belongs to or owns. @return array|bool
[ "Process", "the", "event", "onGetGroupList", "and", "sets", "a", "formatted", "array", "of", "groups", "the", "user", "belongs", "to", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L562-L577
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.updateStatus
private function updateStatus() { if (isset($this->inputs['status']) && trim($this->inputs['status']) !== '') { $this->connectToWhatsApp(); $this->wa->sendStatusUpdate($this->inputs['status']); exit(json_encode([ 'success' => true, 'data' => "<br />Your status was updated to - <b>{$this->inputs['status']}</b>", 'messages' => $this->messages, ])); } else { exit(json_encode([ 'success' => false, 'errormsg' => 'There was no text in the submitted status box!', ])); } }
php
private function updateStatus() { if (isset($this->inputs['status']) && trim($this->inputs['status']) !== '') { $this->connectToWhatsApp(); $this->wa->sendStatusUpdate($this->inputs['status']); exit(json_encode([ 'success' => true, 'data' => "<br />Your status was updated to - <b>{$this->inputs['status']}</b>", 'messages' => $this->messages, ])); } else { exit(json_encode([ 'success' => false, 'errormsg' => 'There was no text in the submitted status box!', ])); } }
[ "private", "function", "updateStatus", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'status'", "]", ")", "&&", "trim", "(", "$", "this", "->", "inputs", "[", "'status'", "]", ")", "!==", "''", ")", "{", "$", "this", "->", "connectToWhatsApp", "(", ")", ";", "$", "this", "->", "wa", "->", "sendStatusUpdate", "(", "$", "this", "->", "inputs", "[", "'status'", "]", ")", ";", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "true", ",", "'data'", "=>", "\"<br />Your status was updated to - <b>{$this->inputs['status']}</b>\"", ",", "'messages'", "=>", "$", "this", "->", "messages", ",", "]", ")", ")", ";", "}", "else", "{", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "false", ",", "'errormsg'", "=>", "'There was no text in the submitted status box!'", ",", "]", ")", ")", ";", "}", "}" ]
Update a users Status. @return void
[ "Update", "a", "users", "Status", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L584-L600
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.sendMessage
private function sendMessage() { if (is_array($this->inputs['to'])) { $this->connectToWhatsApp(); foreach ($this->inputs['to'] as $to) { if (trim($to) !== '') { if (isset($this->inputs['message']) && trim($this->inputs['message'] !== '')) { $this->wa->sendMessageComposing($to); $this->wa->sendMessage($to, $this->inputs['message']); } if (isset($this->inputs['image']) && $this->inputs['image'] !== false) { $this->wa->sendMessageImage($to, $this->inputs['image']); } if (isset($this->inputs['audio']) && $this->inputs['audio'] !== false) { $this->wa->sendMessageAudio($to, $this->inputs['audio']); } if (isset($this->inputs['video']) && $this->inputs['video'] !== false) { $this->wa->sendMessageVideo($to, $this->inputs['video']); } if (isset($this->inputs['locationname']) && trim($this->inputs['locationname'] !== '')) { $this->wa->sendMessageLocation($to, $this->inputs['userlong'], $this->inputs['userlat'], $this->inputs['locationname'], null); } } else { exit(json_encode([ 'success' => false, 'errormsg' => 'A blank number was provided!', 'messages' => $this->messages, ])); } } exit(json_encode([ 'success' => true, 'data' => 'Message Sent!', 'messages' => $this->messages, ])); } exit(json_encode([ 'success' => false, 'errormsg' => 'Provided numbers to send message to were not in valid format.', ])); }
php
private function sendMessage() { if (is_array($this->inputs['to'])) { $this->connectToWhatsApp(); foreach ($this->inputs['to'] as $to) { if (trim($to) !== '') { if (isset($this->inputs['message']) && trim($this->inputs['message'] !== '')) { $this->wa->sendMessageComposing($to); $this->wa->sendMessage($to, $this->inputs['message']); } if (isset($this->inputs['image']) && $this->inputs['image'] !== false) { $this->wa->sendMessageImage($to, $this->inputs['image']); } if (isset($this->inputs['audio']) && $this->inputs['audio'] !== false) { $this->wa->sendMessageAudio($to, $this->inputs['audio']); } if (isset($this->inputs['video']) && $this->inputs['video'] !== false) { $this->wa->sendMessageVideo($to, $this->inputs['video']); } if (isset($this->inputs['locationname']) && trim($this->inputs['locationname'] !== '')) { $this->wa->sendMessageLocation($to, $this->inputs['userlong'], $this->inputs['userlat'], $this->inputs['locationname'], null); } } else { exit(json_encode([ 'success' => false, 'errormsg' => 'A blank number was provided!', 'messages' => $this->messages, ])); } } exit(json_encode([ 'success' => true, 'data' => 'Message Sent!', 'messages' => $this->messages, ])); } exit(json_encode([ 'success' => false, 'errormsg' => 'Provided numbers to send message to were not in valid format.', ])); }
[ "private", "function", "sendMessage", "(", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "inputs", "[", "'to'", "]", ")", ")", "{", "$", "this", "->", "connectToWhatsApp", "(", ")", ";", "foreach", "(", "$", "this", "->", "inputs", "[", "'to'", "]", "as", "$", "to", ")", "{", "if", "(", "trim", "(", "$", "to", ")", "!==", "''", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'message'", "]", ")", "&&", "trim", "(", "$", "this", "->", "inputs", "[", "'message'", "]", "!==", "''", ")", ")", "{", "$", "this", "->", "wa", "->", "sendMessageComposing", "(", "$", "to", ")", ";", "$", "this", "->", "wa", "->", "sendMessage", "(", "$", "to", ",", "$", "this", "->", "inputs", "[", "'message'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'image'", "]", ")", "&&", "$", "this", "->", "inputs", "[", "'image'", "]", "!==", "false", ")", "{", "$", "this", "->", "wa", "->", "sendMessageImage", "(", "$", "to", ",", "$", "this", "->", "inputs", "[", "'image'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'audio'", "]", ")", "&&", "$", "this", "->", "inputs", "[", "'audio'", "]", "!==", "false", ")", "{", "$", "this", "->", "wa", "->", "sendMessageAudio", "(", "$", "to", ",", "$", "this", "->", "inputs", "[", "'audio'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'video'", "]", ")", "&&", "$", "this", "->", "inputs", "[", "'video'", "]", "!==", "false", ")", "{", "$", "this", "->", "wa", "->", "sendMessageVideo", "(", "$", "to", ",", "$", "this", "->", "inputs", "[", "'video'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'locationname'", "]", ")", "&&", "trim", "(", "$", "this", "->", "inputs", "[", "'locationname'", "]", "!==", "''", ")", ")", "{", "$", "this", "->", "wa", "->", "sendMessageLocation", "(", "$", "to", ",", "$", "this", "->", "inputs", "[", "'userlong'", "]", ",", "$", "this", "->", "inputs", "[", "'userlat'", "]", ",", "$", "this", "->", "inputs", "[", "'locationname'", "]", ",", "null", ")", ";", "}", "}", "else", "{", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "false", ",", "'errormsg'", "=>", "'A blank number was provided!'", ",", "'messages'", "=>", "$", "this", "->", "messages", ",", "]", ")", ")", ";", "}", "}", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "true", ",", "'data'", "=>", "'Message Sent!'", ",", "'messages'", "=>", "$", "this", "->", "messages", ",", "]", ")", ")", ";", "}", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "false", ",", "'errormsg'", "=>", "'Provided numbers to send message to were not in valid format.'", ",", "]", ")", ")", ";", "}" ]
Sends a message to a contact. Depending on the inputs sends a message/video/image/location message to a contact. @return void
[ "Sends", "a", "message", "to", "a", "contact", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L611-L652
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.sendBroadcast
private function sendBroadcast() { if (isset($this->inputs['action']) && trim($this->inputs['action']) == 'sendBroadcast') { $this->connectToWhatsApp(); if (isset($this->inputs['message']) && trim($this->inputs['message'] !== '')) { $this->wa->sendBroadcastMessage($this->inputs['to'], $this->inputs['message']); } if (isset($this->inputs['image']) && $this->inputs['image'] !== false) { $this->wa->sendBroadcastImage($this->inputs['to'], $this->inputs['image']); } if (isset($this->inputs['audio']) && $this->inputs['audio'] !== false) { $this->wa->sendBroadcastAudio($this->inputs['to'], $this->inputs['audio']); } if (isset($this->inputs['video']) && $this->inputs['video'] !== false) { $this->wa->sendBroadcastVideo($this->inputs['to'], $this->inputs['video']); } if (isset($this->inputs['locationname']) && trim($this->inputs['locationname'] !== '')) { $this->wa->sendBroadcastPlace($this->inputs['to'], $this->inputs['userlong'], $this->inputs['userlat'], $this->inputs['locationname'], null); } exit(json_encode([ 'success' => true, 'data' => 'Broadcast Message Sent!', 'messages' => $this->messages, ])); } }
php
private function sendBroadcast() { if (isset($this->inputs['action']) && trim($this->inputs['action']) == 'sendBroadcast') { $this->connectToWhatsApp(); if (isset($this->inputs['message']) && trim($this->inputs['message'] !== '')) { $this->wa->sendBroadcastMessage($this->inputs['to'], $this->inputs['message']); } if (isset($this->inputs['image']) && $this->inputs['image'] !== false) { $this->wa->sendBroadcastImage($this->inputs['to'], $this->inputs['image']); } if (isset($this->inputs['audio']) && $this->inputs['audio'] !== false) { $this->wa->sendBroadcastAudio($this->inputs['to'], $this->inputs['audio']); } if (isset($this->inputs['video']) && $this->inputs['video'] !== false) { $this->wa->sendBroadcastVideo($this->inputs['to'], $this->inputs['video']); } if (isset($this->inputs['locationname']) && trim($this->inputs['locationname'] !== '')) { $this->wa->sendBroadcastPlace($this->inputs['to'], $this->inputs['userlong'], $this->inputs['userlat'], $this->inputs['locationname'], null); } exit(json_encode([ 'success' => true, 'data' => 'Broadcast Message Sent!', 'messages' => $this->messages, ])); } }
[ "private", "function", "sendBroadcast", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'action'", "]", ")", "&&", "trim", "(", "$", "this", "->", "inputs", "[", "'action'", "]", ")", "==", "'sendBroadcast'", ")", "{", "$", "this", "->", "connectToWhatsApp", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'message'", "]", ")", "&&", "trim", "(", "$", "this", "->", "inputs", "[", "'message'", "]", "!==", "''", ")", ")", "{", "$", "this", "->", "wa", "->", "sendBroadcastMessage", "(", "$", "this", "->", "inputs", "[", "'to'", "]", ",", "$", "this", "->", "inputs", "[", "'message'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'image'", "]", ")", "&&", "$", "this", "->", "inputs", "[", "'image'", "]", "!==", "false", ")", "{", "$", "this", "->", "wa", "->", "sendBroadcastImage", "(", "$", "this", "->", "inputs", "[", "'to'", "]", ",", "$", "this", "->", "inputs", "[", "'image'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'audio'", "]", ")", "&&", "$", "this", "->", "inputs", "[", "'audio'", "]", "!==", "false", ")", "{", "$", "this", "->", "wa", "->", "sendBroadcastAudio", "(", "$", "this", "->", "inputs", "[", "'to'", "]", ",", "$", "this", "->", "inputs", "[", "'audio'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'video'", "]", ")", "&&", "$", "this", "->", "inputs", "[", "'video'", "]", "!==", "false", ")", "{", "$", "this", "->", "wa", "->", "sendBroadcastVideo", "(", "$", "this", "->", "inputs", "[", "'to'", "]", ",", "$", "this", "->", "inputs", "[", "'video'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "inputs", "[", "'locationname'", "]", ")", "&&", "trim", "(", "$", "this", "->", "inputs", "[", "'locationname'", "]", "!==", "''", ")", ")", "{", "$", "this", "->", "wa", "->", "sendBroadcastPlace", "(", "$", "this", "->", "inputs", "[", "'to'", "]", ",", "$", "this", "->", "inputs", "[", "'userlong'", "]", ",", "$", "this", "->", "inputs", "[", "'userlat'", "]", ",", "$", "this", "->", "inputs", "[", "'locationname'", "]", ",", "null", ")", ";", "}", "exit", "(", "json_encode", "(", "[", "'success'", "=>", "true", ",", "'data'", "=>", "'Broadcast Message Sent!'", ",", "'messages'", "=>", "$", "this", "->", "messages", ",", "]", ")", ")", ";", "}", "}" ]
Sends a broadcast Message to a group of contacts. Currenly only sends a normal message to a group of contacts. @return void
[ "Sends", "a", "broadcast", "Message", "to", "a", "group", "of", "contacts", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L662-L687
train
mgp25/Chat-API
examples/whatsapp.php
Whatsapp.webLogin
private function webLogin() { if ($this->inputs['password'] == $this->config['webpassword']) { $_SESSION['logged_in'] = true; exit($this->showWebForm()); } else { $error = 'Sorry your password was incorrect.'; exit($this->showWebLoginForm($error)); } }
php
private function webLogin() { if ($this->inputs['password'] == $this->config['webpassword']) { $_SESSION['logged_in'] = true; exit($this->showWebForm()); } else { $error = 'Sorry your password was incorrect.'; exit($this->showWebLoginForm($error)); } }
[ "private", "function", "webLogin", "(", ")", "{", "if", "(", "$", "this", "->", "inputs", "[", "'password'", "]", "==", "$", "this", "->", "config", "[", "'webpassword'", "]", ")", "{", "$", "_SESSION", "[", "'logged_in'", "]", "=", "true", ";", "exit", "(", "$", "this", "->", "showWebForm", "(", ")", ")", ";", "}", "else", "{", "$", "error", "=", "'Sorry your password was incorrect.'", ";", "exit", "(", "$", "this", "->", "showWebLoginForm", "(", "$", "error", ")", ")", ";", "}", "}" ]
Process the web login page. @return void
[ "Process", "the", "web", "login", "page", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/examples/whatsapp.php#L694-L703
train
mgp25/Chat-API
src/Registration.php
Registration.checkCredentials
public function checkCredentials() { if (!$phone = $this->dissectPhone()) { throw new Exception('The provided phone number is not valid.'); } $countryCode = ($phone['ISO3166'] != '') ? $phone['ISO3166'] : 'US'; $langCode = ($phone['ISO639'] != '') ? $phone['ISO639'] : 'en'; // Build the url. $host = 'https://'.Constants::WHATSAPP_CHECK_HOST; $query = [ 'cc' => $phone['cc'], 'in' => $phone['phone'], 'lg' => $langCode, 'lc' => $countryCode, 'id' => $this->identity, 'mistyped' => '6', 'network_radio_type' => '1', 'simnum' => '1', 's' => '', 'copiedrc' => '1', 'hasinrc' => '1', 'rcmatch' => '1', 'pid' => mt_rand(100, 9999), //'rchash' => hash('sha256', openssl_random_pseudo_bytes(20)), //'anhash' => md5(openssl_random_pseudo_bytes(20)), 'extexist' => '1', 'extstate' => '1', ]; $this->debugPrint($query); $response = $this->getResponse($host, $query); $this->debugPrint($response); if ($response->status != 'ok') { $this->eventManager()->fire('onCredentialsBad', [ $this->phoneNumber, $response->status, $response->reason, ]); throw new Exception('There was a problem trying to request the code.'); } else { $this->eventManager()->fire('onCredentialsGood', [ $this->phoneNumber, $response->login, $response->pw, $response->type, $response->expiration, $response->kind, $response->price, $response->cost, $response->currency, $response->price_expiration, ]); } return $response; }
php
public function checkCredentials() { if (!$phone = $this->dissectPhone()) { throw new Exception('The provided phone number is not valid.'); } $countryCode = ($phone['ISO3166'] != '') ? $phone['ISO3166'] : 'US'; $langCode = ($phone['ISO639'] != '') ? $phone['ISO639'] : 'en'; // Build the url. $host = 'https://'.Constants::WHATSAPP_CHECK_HOST; $query = [ 'cc' => $phone['cc'], 'in' => $phone['phone'], 'lg' => $langCode, 'lc' => $countryCode, 'id' => $this->identity, 'mistyped' => '6', 'network_radio_type' => '1', 'simnum' => '1', 's' => '', 'copiedrc' => '1', 'hasinrc' => '1', 'rcmatch' => '1', 'pid' => mt_rand(100, 9999), //'rchash' => hash('sha256', openssl_random_pseudo_bytes(20)), //'anhash' => md5(openssl_random_pseudo_bytes(20)), 'extexist' => '1', 'extstate' => '1', ]; $this->debugPrint($query); $response = $this->getResponse($host, $query); $this->debugPrint($response); if ($response->status != 'ok') { $this->eventManager()->fire('onCredentialsBad', [ $this->phoneNumber, $response->status, $response->reason, ]); throw new Exception('There was a problem trying to request the code.'); } else { $this->eventManager()->fire('onCredentialsGood', [ $this->phoneNumber, $response->login, $response->pw, $response->type, $response->expiration, $response->kind, $response->price, $response->cost, $response->currency, $response->price_expiration, ]); } return $response; }
[ "public", "function", "checkCredentials", "(", ")", "{", "if", "(", "!", "$", "phone", "=", "$", "this", "->", "dissectPhone", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'The provided phone number is not valid.'", ")", ";", "}", "$", "countryCode", "=", "(", "$", "phone", "[", "'ISO3166'", "]", "!=", "''", ")", "?", "$", "phone", "[", "'ISO3166'", "]", ":", "'US'", ";", "$", "langCode", "=", "(", "$", "phone", "[", "'ISO639'", "]", "!=", "''", ")", "?", "$", "phone", "[", "'ISO639'", "]", ":", "'en'", ";", "// Build the url.", "$", "host", "=", "'https://'", ".", "Constants", "::", "WHATSAPP_CHECK_HOST", ";", "$", "query", "=", "[", "'cc'", "=>", "$", "phone", "[", "'cc'", "]", ",", "'in'", "=>", "$", "phone", "[", "'phone'", "]", ",", "'lg'", "=>", "$", "langCode", ",", "'lc'", "=>", "$", "countryCode", ",", "'id'", "=>", "$", "this", "->", "identity", ",", "'mistyped'", "=>", "'6'", ",", "'network_radio_type'", "=>", "'1'", ",", "'simnum'", "=>", "'1'", ",", "'s'", "=>", "''", ",", "'copiedrc'", "=>", "'1'", ",", "'hasinrc'", "=>", "'1'", ",", "'rcmatch'", "=>", "'1'", ",", "'pid'", "=>", "mt_rand", "(", "100", ",", "9999", ")", ",", "//'rchash' => hash('sha256', openssl_random_pseudo_bytes(20)),", "//'anhash' => md5(openssl_random_pseudo_bytes(20)),", "'extexist'", "=>", "'1'", ",", "'extstate'", "=>", "'1'", ",", "]", ";", "$", "this", "->", "debugPrint", "(", "$", "query", ")", ";", "$", "response", "=", "$", "this", "->", "getResponse", "(", "$", "host", ",", "$", "query", ")", ";", "$", "this", "->", "debugPrint", "(", "$", "response", ")", ";", "if", "(", "$", "response", "->", "status", "!=", "'ok'", ")", "{", "$", "this", "->", "eventManager", "(", ")", "->", "fire", "(", "'onCredentialsBad'", ",", "[", "$", "this", "->", "phoneNumber", ",", "$", "response", "->", "status", ",", "$", "response", "->", "reason", ",", "]", ")", ";", "throw", "new", "Exception", "(", "'There was a problem trying to request the code.'", ")", ";", "}", "else", "{", "$", "this", "->", "eventManager", "(", ")", "->", "fire", "(", "'onCredentialsGood'", ",", "[", "$", "this", "->", "phoneNumber", ",", "$", "response", "->", "login", ",", "$", "response", "->", "pw", ",", "$", "response", "->", "type", ",", "$", "response", "->", "expiration", ",", "$", "response", "->", "kind", ",", "$", "response", "->", "price", ",", "$", "response", "->", "cost", ",", "$", "response", "->", "currency", ",", "$", "response", "->", "price_expiration", ",", "]", ")", ";", "}", "return", "$", "response", ";", "}" ]
Check if account credentials are valid. NOTE: WhatsApp changes your password everytime you use this. Make sure you update your config file if the output informs about a password change. @throws Exception @return object An object with server response. - status: Account status. - login: Phone number with country code. - pw: Account password. - type: Type of account. - expiration: Expiration date in UNIX TimeStamp. - kind: Kind of account. - price: Formatted price of account. - cost: Decimal amount of account. - currency: Currency price of account. - price_expiration: Price expiration in UNIX TimeStamp.
[ "Check", "if", "account", "credentials", "are", "valid", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Registration.php#L45-L108
train
mgp25/Chat-API
src/Registration.php
Registration.codeRegister
public function codeRegister($code) { if (!$phone = $this->dissectPhone()) { throw new Exception('The provided phone number is not valid.'); } $code = str_replace('-', '', $code); $countryCode = ($phone['ISO3166'] != '') ? $phone['ISO3166'] : 'US'; $langCode = ($phone['ISO639'] != '') ? $phone['ISO639'] : 'en'; // Build the url. $host = 'https://'.Constants::WHATSAPP_REGISTER_HOST; $query = [ 'cc' => $phone['cc'], 'in' => $phone['phone'], 'lg' => $langCode, 'lc' => $countryCode, 'id' => $this->identity, 'mistyped' => '6', 'network_radio_type' => '1', 'simnum' => '1', 's' => '', 'copiedrc' => '1', 'hasinrc' => '1', 'rcmatch' => '1', 'pid' => mt_rand(100, 9999), 'rchash' => hash('sha256', openssl_random_pseudo_bytes(20)), 'anhash' => md5(openssl_random_pseudo_bytes(20)), 'extexist' => '1', 'extstate' => '1', 'code' => $code, ]; $this->debugPrint($query); $response = $this->getResponse($host, $query); $this->debugPrint($response); if ($response->status != 'ok') { $this->eventManager()->fire('onCodeRegisterFailed', [ $this->phoneNumber, $response->status, $response->reason, isset($response->retry_after) ? $response->retry_after : null, ]); if ($response->reason == 'old_version') { $this->update(); } throw new Exception("An error occurred registering the registration code from WhatsApp. Reason: $response->reason"); } else { $this->eventManager()->fire('onCodeRegister', [ $this->phoneNumber, $response->login, $response->pw, $response->type, $response->expiration, $response->kind, $response->price, $response->cost, $response->currency, $response->price_expiration, ]); } return $response; }
php
public function codeRegister($code) { if (!$phone = $this->dissectPhone()) { throw new Exception('The provided phone number is not valid.'); } $code = str_replace('-', '', $code); $countryCode = ($phone['ISO3166'] != '') ? $phone['ISO3166'] : 'US'; $langCode = ($phone['ISO639'] != '') ? $phone['ISO639'] : 'en'; // Build the url. $host = 'https://'.Constants::WHATSAPP_REGISTER_HOST; $query = [ 'cc' => $phone['cc'], 'in' => $phone['phone'], 'lg' => $langCode, 'lc' => $countryCode, 'id' => $this->identity, 'mistyped' => '6', 'network_radio_type' => '1', 'simnum' => '1', 's' => '', 'copiedrc' => '1', 'hasinrc' => '1', 'rcmatch' => '1', 'pid' => mt_rand(100, 9999), 'rchash' => hash('sha256', openssl_random_pseudo_bytes(20)), 'anhash' => md5(openssl_random_pseudo_bytes(20)), 'extexist' => '1', 'extstate' => '1', 'code' => $code, ]; $this->debugPrint($query); $response = $this->getResponse($host, $query); $this->debugPrint($response); if ($response->status != 'ok') { $this->eventManager()->fire('onCodeRegisterFailed', [ $this->phoneNumber, $response->status, $response->reason, isset($response->retry_after) ? $response->retry_after : null, ]); if ($response->reason == 'old_version') { $this->update(); } throw new Exception("An error occurred registering the registration code from WhatsApp. Reason: $response->reason"); } else { $this->eventManager()->fire('onCodeRegister', [ $this->phoneNumber, $response->login, $response->pw, $response->type, $response->expiration, $response->kind, $response->price, $response->cost, $response->currency, $response->price_expiration, ]); } return $response; }
[ "public", "function", "codeRegister", "(", "$", "code", ")", "{", "if", "(", "!", "$", "phone", "=", "$", "this", "->", "dissectPhone", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'The provided phone number is not valid.'", ")", ";", "}", "$", "code", "=", "str_replace", "(", "'-'", ",", "''", ",", "$", "code", ")", ";", "$", "countryCode", "=", "(", "$", "phone", "[", "'ISO3166'", "]", "!=", "''", ")", "?", "$", "phone", "[", "'ISO3166'", "]", ":", "'US'", ";", "$", "langCode", "=", "(", "$", "phone", "[", "'ISO639'", "]", "!=", "''", ")", "?", "$", "phone", "[", "'ISO639'", "]", ":", "'en'", ";", "// Build the url.", "$", "host", "=", "'https://'", ".", "Constants", "::", "WHATSAPP_REGISTER_HOST", ";", "$", "query", "=", "[", "'cc'", "=>", "$", "phone", "[", "'cc'", "]", ",", "'in'", "=>", "$", "phone", "[", "'phone'", "]", ",", "'lg'", "=>", "$", "langCode", ",", "'lc'", "=>", "$", "countryCode", ",", "'id'", "=>", "$", "this", "->", "identity", ",", "'mistyped'", "=>", "'6'", ",", "'network_radio_type'", "=>", "'1'", ",", "'simnum'", "=>", "'1'", ",", "'s'", "=>", "''", ",", "'copiedrc'", "=>", "'1'", ",", "'hasinrc'", "=>", "'1'", ",", "'rcmatch'", "=>", "'1'", ",", "'pid'", "=>", "mt_rand", "(", "100", ",", "9999", ")", ",", "'rchash'", "=>", "hash", "(", "'sha256'", ",", "openssl_random_pseudo_bytes", "(", "20", ")", ")", ",", "'anhash'", "=>", "md5", "(", "openssl_random_pseudo_bytes", "(", "20", ")", ")", ",", "'extexist'", "=>", "'1'", ",", "'extstate'", "=>", "'1'", ",", "'code'", "=>", "$", "code", ",", "]", ";", "$", "this", "->", "debugPrint", "(", "$", "query", ")", ";", "$", "response", "=", "$", "this", "->", "getResponse", "(", "$", "host", ",", "$", "query", ")", ";", "$", "this", "->", "debugPrint", "(", "$", "response", ")", ";", "if", "(", "$", "response", "->", "status", "!=", "'ok'", ")", "{", "$", "this", "->", "eventManager", "(", ")", "->", "fire", "(", "'onCodeRegisterFailed'", ",", "[", "$", "this", "->", "phoneNumber", ",", "$", "response", "->", "status", ",", "$", "response", "->", "reason", ",", "isset", "(", "$", "response", "->", "retry_after", ")", "?", "$", "response", "->", "retry_after", ":", "null", ",", "]", ")", ";", "if", "(", "$", "response", "->", "reason", "==", "'old_version'", ")", "{", "$", "this", "->", "update", "(", ")", ";", "}", "throw", "new", "Exception", "(", "\"An error occurred registering the registration code from WhatsApp. Reason: $response->reason\"", ")", ";", "}", "else", "{", "$", "this", "->", "eventManager", "(", ")", "->", "fire", "(", "'onCodeRegister'", ",", "[", "$", "this", "->", "phoneNumber", ",", "$", "response", "->", "login", ",", "$", "response", "->", "pw", ",", "$", "response", "->", "type", ",", "$", "response", "->", "expiration", ",", "$", "response", "->", "kind", ",", "$", "response", "->", "price", ",", "$", "response", "->", "cost", ",", "$", "response", "->", "currency", ",", "$", "response", "->", "price_expiration", ",", "]", ")", ";", "}", "return", "$", "response", ";", "}" ]
Register account on WhatsApp using the provided code. @param int $code Numeric code value provided on requestCode(). @throws Exception @return object An object with server response. - status: Account status. - login: Phone number with country code. - pw: Account password. - type: Type of account. - expiration: Expiration date in UNIX TimeStamp. - kind: Kind of account. - price: Formatted price of account. - cost: Decimal amount of account. - currency: Currency price of account. - price_expiration: Price expiration in UNIX TimeStamp.
[ "Register", "account", "on", "WhatsApp", "using", "the", "provided", "code", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Registration.php#L131-L201
train
mgp25/Chat-API
src/Registration.php
Registration.getResponse
protected function getResponse($host, $query) { // Build the url. $url = $host.'?'.http_build_query($query); // Open connection. $ch = curl_init(); // Configure the connection. curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, Constants::WHATSAPP_USER_AGENT); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: text/json']); // This makes CURL accept any peer! curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Get the response. $response = curl_exec($ch); // Close the connection. curl_close($ch); return json_decode($response); }
php
protected function getResponse($host, $query) { // Build the url. $url = $host.'?'.http_build_query($query); // Open connection. $ch = curl_init(); // Configure the connection. curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, Constants::WHATSAPP_USER_AGENT); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: text/json']); // This makes CURL accept any peer! curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Get the response. $response = curl_exec($ch); // Close the connection. curl_close($ch); return json_decode($response); }
[ "protected", "function", "getResponse", "(", "$", "host", ",", "$", "query", ")", "{", "// Build the url.", "$", "url", "=", "$", "host", ".", "'?'", ".", "http_build_query", "(", "$", "query", ")", ";", "// Open connection.", "$", "ch", "=", "curl_init", "(", ")", ";", "// Configure the connection.", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "0", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "Constants", "::", "WHATSAPP_USER_AGENT", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPHEADER", ",", "[", "'Accept: text/json'", "]", ")", ";", "// This makes CURL accept any peer!", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "false", ")", ";", "// Get the response.", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "// Close the connection.", "curl_close", "(", "$", "ch", ")", ";", "return", "json_decode", "(", "$", "response", ")", ";", "}" ]
Get a decoded JSON response from Whatsapp server. @param string $host The host URL @param array $query A associative array of keys and values to send to server. @return null|object NULL if the json cannot be decoded or if the encoded data is deeper than the recursion limit
[ "Get", "a", "decoded", "JSON", "response", "from", "Whatsapp", "server", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Registration.php#L338-L362
train
mgp25/Chat-API
src/Registration.php
Registration.dissectPhone
protected function dissectPhone() { if (($handle = fopen(dirname(__FILE__).'/countries.csv', 'rb')) !== false) { while (($data = fgetcsv($handle, 1000)) !== false) { if (strpos($this->phoneNumber, $data[1]) === 0) { // Return the first appearance. fclose($handle); $mcc = explode('|', $data[2]); $mcc = $mcc[0]; //hook: //fix country code for North America if ($data[1][0] == '1') { $data[1] = '1'; } $phone = [ 'country' => $data[0], 'cc' => $data[1], 'phone' => substr($this->phoneNumber, strlen($data[1]), strlen($this->phoneNumber)), 'mcc' => $mcc, 'ISO3166' => @$data[3], 'ISO639' => @$data[4], 'mnc' => $data[5], ]; $this->eventManager()->fire('onDissectPhone', [ $this->phoneNumber, $phone['country'], $phone['cc'], $phone['phone'], $phone['mcc'], $phone['ISO3166'], $phone['ISO639'], $phone['mnc'], ] ); return $phone; } } fclose($handle); } $this->eventManager()->fire('onDissectPhoneFailed', [ $this->phoneNumber, ]); return false; }
php
protected function dissectPhone() { if (($handle = fopen(dirname(__FILE__).'/countries.csv', 'rb')) !== false) { while (($data = fgetcsv($handle, 1000)) !== false) { if (strpos($this->phoneNumber, $data[1]) === 0) { // Return the first appearance. fclose($handle); $mcc = explode('|', $data[2]); $mcc = $mcc[0]; //hook: //fix country code for North America if ($data[1][0] == '1') { $data[1] = '1'; } $phone = [ 'country' => $data[0], 'cc' => $data[1], 'phone' => substr($this->phoneNumber, strlen($data[1]), strlen($this->phoneNumber)), 'mcc' => $mcc, 'ISO3166' => @$data[3], 'ISO639' => @$data[4], 'mnc' => $data[5], ]; $this->eventManager()->fire('onDissectPhone', [ $this->phoneNumber, $phone['country'], $phone['cc'], $phone['phone'], $phone['mcc'], $phone['ISO3166'], $phone['ISO639'], $phone['mnc'], ] ); return $phone; } } fclose($handle); } $this->eventManager()->fire('onDissectPhoneFailed', [ $this->phoneNumber, ]); return false; }
[ "protected", "function", "dissectPhone", "(", ")", "{", "if", "(", "(", "$", "handle", "=", "fopen", "(", "dirname", "(", "__FILE__", ")", ".", "'/countries.csv'", ",", "'rb'", ")", ")", "!==", "false", ")", "{", "while", "(", "(", "$", "data", "=", "fgetcsv", "(", "$", "handle", ",", "1000", ")", ")", "!==", "false", ")", "{", "if", "(", "strpos", "(", "$", "this", "->", "phoneNumber", ",", "$", "data", "[", "1", "]", ")", "===", "0", ")", "{", "// Return the first appearance.", "fclose", "(", "$", "handle", ")", ";", "$", "mcc", "=", "explode", "(", "'|'", ",", "$", "data", "[", "2", "]", ")", ";", "$", "mcc", "=", "$", "mcc", "[", "0", "]", ";", "//hook:", "//fix country code for North America", "if", "(", "$", "data", "[", "1", "]", "[", "0", "]", "==", "'1'", ")", "{", "$", "data", "[", "1", "]", "=", "'1'", ";", "}", "$", "phone", "=", "[", "'country'", "=>", "$", "data", "[", "0", "]", ",", "'cc'", "=>", "$", "data", "[", "1", "]", ",", "'phone'", "=>", "substr", "(", "$", "this", "->", "phoneNumber", ",", "strlen", "(", "$", "data", "[", "1", "]", ")", ",", "strlen", "(", "$", "this", "->", "phoneNumber", ")", ")", ",", "'mcc'", "=>", "$", "mcc", ",", "'ISO3166'", "=>", "@", "$", "data", "[", "3", "]", ",", "'ISO639'", "=>", "@", "$", "data", "[", "4", "]", ",", "'mnc'", "=>", "$", "data", "[", "5", "]", ",", "]", ";", "$", "this", "->", "eventManager", "(", ")", "->", "fire", "(", "'onDissectPhone'", ",", "[", "$", "this", "->", "phoneNumber", ",", "$", "phone", "[", "'country'", "]", ",", "$", "phone", "[", "'cc'", "]", ",", "$", "phone", "[", "'phone'", "]", ",", "$", "phone", "[", "'mcc'", "]", ",", "$", "phone", "[", "'ISO3166'", "]", ",", "$", "phone", "[", "'ISO639'", "]", ",", "$", "phone", "[", "'mnc'", "]", ",", "]", ")", ";", "return", "$", "phone", ";", "}", "}", "fclose", "(", "$", "handle", ")", ";", "}", "$", "this", "->", "eventManager", "(", ")", "->", "fire", "(", "'onDissectPhoneFailed'", ",", "[", "$", "this", "->", "phoneNumber", ",", "]", ")", ";", "return", "false", ";", "}" ]
Dissect country code from phone number. @return array An associative array with country code and phone number. - country: The detected country name. - cc: The detected country code (phone prefix). - phone: The phone number. - ISO3166: 2-Letter country code - ISO639: 2-Letter language code Return false if country code is not found.
[ "Dissect", "country", "code", "from", "phone", "number", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Registration.php#L376-L428
train
mgp25/Chat-API
src/Registration.php
Registration.detectMnc
protected function detectMnc($lc, $carrierName) { $fp = fopen(__DIR__.DIRECTORY_SEPARATOR.'networkinfo.csv', 'r'); $mnc = null; while ($data = fgetcsv($fp, 0, ',')) { if ($data[4] === $lc && $data[7] === $carrierName) { $mnc = $data[2]; break; } } if ($mnc == null) { $mnc = '000'; } fclose($fp); return $mnc; }
php
protected function detectMnc($lc, $carrierName) { $fp = fopen(__DIR__.DIRECTORY_SEPARATOR.'networkinfo.csv', 'r'); $mnc = null; while ($data = fgetcsv($fp, 0, ',')) { if ($data[4] === $lc && $data[7] === $carrierName) { $mnc = $data[2]; break; } } if ($mnc == null) { $mnc = '000'; } fclose($fp); return $mnc; }
[ "protected", "function", "detectMnc", "(", "$", "lc", ",", "$", "carrierName", ")", "{", "$", "fp", "=", "fopen", "(", "__DIR__", ".", "DIRECTORY_SEPARATOR", ".", "'networkinfo.csv'", ",", "'r'", ")", ";", "$", "mnc", "=", "null", ";", "while", "(", "$", "data", "=", "fgetcsv", "(", "$", "fp", ",", "0", ",", "','", ")", ")", "{", "if", "(", "$", "data", "[", "4", "]", "===", "$", "lc", "&&", "$", "data", "[", "7", "]", "===", "$", "carrierName", ")", "{", "$", "mnc", "=", "$", "data", "[", "2", "]", ";", "break", ";", "}", "}", "if", "(", "$", "mnc", "==", "null", ")", "{", "$", "mnc", "=", "'000'", ";", "}", "fclose", "(", "$", "fp", ")", ";", "return", "$", "mnc", ";", "}" ]
Detects mnc from specified carrier. @param string $lc LangCode @param string $carrierName Name of the carrier @return string Returns mnc value
[ "Detects", "mnc", "from", "specified", "carrier", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Registration.php#L440-L459
train
mgp25/Chat-API
src/Registration.php
Registration.buildIdentity
protected function buildIdentity($identity_file = false) { if ($identity_file === false) { $identity_file = sprintf('%s%s%sid.%s.dat', __DIR__, DIRECTORY_SEPARATOR, Constants::DATA_FOLDER.DIRECTORY_SEPARATOR, $this->phoneNumber); } // Check if the provided is not a file but a directory if (is_dir($identity_file)) { $identity_file = sprintf('%s/id.%s.dat', rtrim($identity_file, "/"), $this->phoneNumber ); } if (is_readable($identity_file)) { $data = urldecode(file_get_contents($identity_file)); $length = strlen($data); if ($length == 20 || $length == 16) { return $data; } } $bytes = strtolower(openssl_random_pseudo_bytes(20)); if (file_put_contents($identity_file, urlencode($bytes)) === false) { throw new Exception('Unable to write identity file to '.$identity_file); } return $bytes; }
php
protected function buildIdentity($identity_file = false) { if ($identity_file === false) { $identity_file = sprintf('%s%s%sid.%s.dat', __DIR__, DIRECTORY_SEPARATOR, Constants::DATA_FOLDER.DIRECTORY_SEPARATOR, $this->phoneNumber); } // Check if the provided is not a file but a directory if (is_dir($identity_file)) { $identity_file = sprintf('%s/id.%s.dat', rtrim($identity_file, "/"), $this->phoneNumber ); } if (is_readable($identity_file)) { $data = urldecode(file_get_contents($identity_file)); $length = strlen($data); if ($length == 20 || $length == 16) { return $data; } } $bytes = strtolower(openssl_random_pseudo_bytes(20)); if (file_put_contents($identity_file, urlencode($bytes)) === false) { throw new Exception('Unable to write identity file to '.$identity_file); } return $bytes; }
[ "protected", "function", "buildIdentity", "(", "$", "identity_file", "=", "false", ")", "{", "if", "(", "$", "identity_file", "===", "false", ")", "{", "$", "identity_file", "=", "sprintf", "(", "'%s%s%sid.%s.dat'", ",", "__DIR__", ",", "DIRECTORY_SEPARATOR", ",", "Constants", "::", "DATA_FOLDER", ".", "DIRECTORY_SEPARATOR", ",", "$", "this", "->", "phoneNumber", ")", ";", "}", "// Check if the provided is not a file but a directory", "if", "(", "is_dir", "(", "$", "identity_file", ")", ")", "{", "$", "identity_file", "=", "sprintf", "(", "'%s/id.%s.dat'", ",", "rtrim", "(", "$", "identity_file", ",", "\"/\"", ")", ",", "$", "this", "->", "phoneNumber", ")", ";", "}", "if", "(", "is_readable", "(", "$", "identity_file", ")", ")", "{", "$", "data", "=", "urldecode", "(", "file_get_contents", "(", "$", "identity_file", ")", ")", ";", "$", "length", "=", "strlen", "(", "$", "data", ")", ";", "if", "(", "$", "length", "==", "20", "||", "$", "length", "==", "16", ")", "{", "return", "$", "data", ";", "}", "}", "$", "bytes", "=", "strtolower", "(", "openssl_random_pseudo_bytes", "(", "20", ")", ")", ";", "if", "(", "file_put_contents", "(", "$", "identity_file", ",", "urlencode", "(", "$", "bytes", ")", ")", "===", "false", ")", "{", "throw", "new", "Exception", "(", "'Unable to write identity file to '", ".", "$", "identity_file", ")", ";", "}", "return", "$", "bytes", ";", "}" ]
Create an identity string. @param mixed $identity_file IdentityFile (optional). @throws Exception Error when cannot write identity data to file. @return string Correctly formatted identity
[ "Create", "an", "identity", "string", "." ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/Registration.php#L481-L511
train
mgp25/Chat-API
src/libaxolotl-php/logging/Log.php
Log.writeLog
public static function writeLog($priority, $tag, $msg) // [int priority, String tag, String msg] { $logger = AxolotlLoggerProvider::getProvider(); if (($logger != null)) { $logger->log($priority, $tag, $msg); } }
php
public static function writeLog($priority, $tag, $msg) // [int priority, String tag, String msg] { $logger = AxolotlLoggerProvider::getProvider(); if (($logger != null)) { $logger->log($priority, $tag, $msg); } }
[ "public", "static", "function", "writeLog", "(", "$", "priority", ",", "$", "tag", ",", "$", "msg", ")", "// [int priority, String tag, String msg]", "{", "$", "logger", "=", "AxolotlLoggerProvider", "::", "getProvider", "(", ")", ";", "if", "(", "(", "$", "logger", "!=", "null", ")", ")", "{", "$", "logger", "->", "log", "(", "$", "priority", ",", "$", "tag", ",", "$", "msg", ")", ";", "}", "}" ]
old function name log
[ "old", "function", "name", "log" ]
bfe098d148d9f0c7cff3675d30fdd34c9d970b41
https://github.com/mgp25/Chat-API/blob/bfe098d148d9f0c7cff3675d30fdd34c9d970b41/src/libaxolotl-php/logging/Log.php#L73-L79
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.rawColumns
public function rawColumns(array $columns, $merge = false) { if ($merge) { $config = $this->config->get('datatables.columns'); $this->columnDef['raw'] = array_merge($config['raw'], $columns); } else { $this->columnDef['raw'] = $columns; } return $this; }
php
public function rawColumns(array $columns, $merge = false) { if ($merge) { $config = $this->config->get('datatables.columns'); $this->columnDef['raw'] = array_merge($config['raw'], $columns); } else { $this->columnDef['raw'] = $columns; } return $this; }
[ "public", "function", "rawColumns", "(", "array", "$", "columns", ",", "$", "merge", "=", "false", ")", "{", "if", "(", "$", "merge", ")", "{", "$", "config", "=", "$", "this", "->", "config", "->", "get", "(", "'datatables.columns'", ")", ";", "$", "this", "->", "columnDef", "[", "'raw'", "]", "=", "array_merge", "(", "$", "config", "[", "'raw'", "]", ",", "$", "columns", ")", ";", "}", "else", "{", "$", "this", "->", "columnDef", "[", "'raw'", "]", "=", "$", "columns", ";", "}", "return", "$", "this", ";", "}" ]
Set columns that should not be escaped. Optionally merge the defaults from config. @param array $columns @param bool $merge @return $this
[ "Set", "columns", "that", "should", "not", "be", "escaped", ".", "Optionally", "merge", "the", "defaults", "from", "config", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L257-L268
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.with
public function with($key, $value = '') { if (is_array($key)) { $this->appends = $key; } elseif (is_callable($value)) { $this->appends[$key] = value($value); } else { $this->appends[$key] = value($value); } return $this; }
php
public function with($key, $value = '') { if (is_array($key)) { $this->appends = $key; } elseif (is_callable($value)) { $this->appends[$key] = value($value); } else { $this->appends[$key] = value($value); } return $this; }
[ "public", "function", "with", "(", "$", "key", ",", "$", "value", "=", "''", ")", "{", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "$", "this", "->", "appends", "=", "$", "key", ";", "}", "elseif", "(", "is_callable", "(", "$", "value", ")", ")", "{", "$", "this", "->", "appends", "[", "$", "key", "]", "=", "value", "(", "$", "value", ")", ";", "}", "else", "{", "$", "this", "->", "appends", "[", "$", "key", "]", "=", "value", "(", "$", "value", ")", ";", "}", "return", "$", "this", ";", "}" ]
Append data on json response. @param mixed $key @param mixed $value @return $this
[ "Append", "data", "on", "json", "response", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L360-L371
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.getColumnsDefinition
protected function getColumnsDefinition() { $config = $this->config->get('datatables.columns'); $allowed = ['excess', 'escape', 'raw', 'blacklist', 'whitelist']; return array_replace_recursive(array_only($config, $allowed), $this->columnDef); }
php
protected function getColumnsDefinition() { $config = $this->config->get('datatables.columns'); $allowed = ['excess', 'escape', 'raw', 'blacklist', 'whitelist']; return array_replace_recursive(array_only($config, $allowed), $this->columnDef); }
[ "protected", "function", "getColumnsDefinition", "(", ")", "{", "$", "config", "=", "$", "this", "->", "config", "->", "get", "(", "'datatables.columns'", ")", ";", "$", "allowed", "=", "[", "'excess'", ",", "'escape'", ",", "'raw'", ",", "'blacklist'", ",", "'whitelist'", "]", ";", "return", "array_replace_recursive", "(", "array_only", "(", "$", "config", ",", "$", "allowed", ")", ",", "$", "this", "->", "columnDef", ")", ";", "}" ]
Get columns definition. @return array
[ "Get", "columns", "definition", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L518-L524
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.filter
public function filter(callable $callback, $globalSearch = false) { $this->autoFilter = $globalSearch; $this->isFilterApplied = true; $this->filterCallback = $callback; return $this; }
php
public function filter(callable $callback, $globalSearch = false) { $this->autoFilter = $globalSearch; $this->isFilterApplied = true; $this->filterCallback = $callback; return $this; }
[ "public", "function", "filter", "(", "callable", "$", "callback", ",", "$", "globalSearch", "=", "false", ")", "{", "$", "this", "->", "autoFilter", "=", "$", "globalSearch", ";", "$", "this", "->", "isFilterApplied", "=", "true", ";", "$", "this", "->", "filterCallback", "=", "$", "callback", ";", "return", "$", "this", ";", "}" ]
Set auto filter off and run your own filter. Overrides global search. @param callable $callback @param bool $globalSearch @return $this
[ "Set", "auto", "filter", "off", "and", "run", "your", "own", "filter", ".", "Overrides", "global", "search", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L558-L565
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.smartGlobalSearch
protected function smartGlobalSearch($keyword) { collect(explode(' ', $keyword)) ->reject(function ($keyword) { return trim($keyword) === ''; }) ->each(function ($keyword) { $this->globalSearch($keyword); }); }
php
protected function smartGlobalSearch($keyword) { collect(explode(' ', $keyword)) ->reject(function ($keyword) { return trim($keyword) === ''; }) ->each(function ($keyword) { $this->globalSearch($keyword); }); }
[ "protected", "function", "smartGlobalSearch", "(", "$", "keyword", ")", "{", "collect", "(", "explode", "(", "' '", ",", "$", "keyword", ")", ")", "->", "reject", "(", "function", "(", "$", "keyword", ")", "{", "return", "trim", "(", "$", "keyword", ")", "===", "''", ";", "}", ")", "->", "each", "(", "function", "(", "$", "keyword", ")", "{", "$", "this", "->", "globalSearch", "(", "$", "keyword", ")", ";", "}", ")", ";", "}" ]
Perform multi-term search by splitting keyword into individual words and searches for each of them. @param string $keyword
[ "Perform", "multi", "-", "term", "search", "by", "splitting", "keyword", "into", "individual", "words", "and", "searches", "for", "each", "of", "them", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L645-L654
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.transform
protected function transform($results, $processed) { if (isset($this->transformer) && class_exists('Yajra\\DataTables\\Transformers\\FractalTransformer')) { return app('datatables.transformer')->transform( $results, $this->transformer, $this->serializer ?? null ); } return Helper::transform($processed); }
php
protected function transform($results, $processed) { if (isset($this->transformer) && class_exists('Yajra\\DataTables\\Transformers\\FractalTransformer')) { return app('datatables.transformer')->transform( $results, $this->transformer, $this->serializer ?? null ); } return Helper::transform($processed); }
[ "protected", "function", "transform", "(", "$", "results", ",", "$", "processed", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "transformer", ")", "&&", "class_exists", "(", "'Yajra\\\\DataTables\\\\Transformers\\\\FractalTransformer'", ")", ")", "{", "return", "app", "(", "'datatables.transformer'", ")", "->", "transform", "(", "$", "results", ",", "$", "this", "->", "transformer", ",", "$", "this", "->", "serializer", "??", "null", ")", ";", "}", "return", "Helper", "::", "transform", "(", "$", "processed", ")", ";", "}" ]
Transform output. @param mixed $results @param mixed $processed @return array
[ "Transform", "output", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L682-L693
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.processResults
protected function processResults($results, $object = false) { $processor = new DataProcessor( $results, $this->getColumnsDefinition(), $this->templates, $this->request->input('start') ); return $processor->process($object); }
php
protected function processResults($results, $object = false) { $processor = new DataProcessor( $results, $this->getColumnsDefinition(), $this->templates, $this->request->input('start') ); return $processor->process($object); }
[ "protected", "function", "processResults", "(", "$", "results", ",", "$", "object", "=", "false", ")", "{", "$", "processor", "=", "new", "DataProcessor", "(", "$", "results", ",", "$", "this", "->", "getColumnsDefinition", "(", ")", ",", "$", "this", "->", "templates", ",", "$", "this", "->", "request", "->", "input", "(", "'start'", ")", ")", ";", "return", "$", "processor", "->", "process", "(", "$", "object", ")", ";", "}" ]
Get processed data. @param mixed $results @param bool $object @return array
[ "Get", "processed", "data", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L702-L712
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.errorResponse
protected function errorResponse(\Exception $exception) { $error = $this->config->get('datatables.error'); $debug = $this->config->get('app.debug'); if ($error === 'throw' || (! $error && ! $debug)) { throw new Exception($exception->getMessage(), $code = 0, $exception); } $this->getLogger()->error($exception); return new JsonResponse([ 'draw' => (int) $this->request->input('draw'), 'recordsTotal' => $this->totalRecords, 'recordsFiltered' => 0, 'data' => [], 'error' => $error ? __($error) : "Exception Message:\n\n".$exception->getMessage(), ]); }
php
protected function errorResponse(\Exception $exception) { $error = $this->config->get('datatables.error'); $debug = $this->config->get('app.debug'); if ($error === 'throw' || (! $error && ! $debug)) { throw new Exception($exception->getMessage(), $code = 0, $exception); } $this->getLogger()->error($exception); return new JsonResponse([ 'draw' => (int) $this->request->input('draw'), 'recordsTotal' => $this->totalRecords, 'recordsFiltered' => 0, 'data' => [], 'error' => $error ? __($error) : "Exception Message:\n\n".$exception->getMessage(), ]); }
[ "protected", "function", "errorResponse", "(", "\\", "Exception", "$", "exception", ")", "{", "$", "error", "=", "$", "this", "->", "config", "->", "get", "(", "'datatables.error'", ")", ";", "$", "debug", "=", "$", "this", "->", "config", "->", "get", "(", "'app.debug'", ")", ";", "if", "(", "$", "error", "===", "'throw'", "||", "(", "!", "$", "error", "&&", "!", "$", "debug", ")", ")", "{", "throw", "new", "Exception", "(", "$", "exception", "->", "getMessage", "(", ")", ",", "$", "code", "=", "0", ",", "$", "exception", ")", ";", "}", "$", "this", "->", "getLogger", "(", ")", "->", "error", "(", "$", "exception", ")", ";", "return", "new", "JsonResponse", "(", "[", "'draw'", "=>", "(", "int", ")", "$", "this", "->", "request", "->", "input", "(", "'draw'", ")", ",", "'recordsTotal'", "=>", "$", "this", "->", "totalRecords", ",", "'recordsFiltered'", "=>", "0", ",", "'data'", "=>", "[", "]", ",", "'error'", "=>", "$", "error", "?", "__", "(", "$", "error", ")", ":", "\"Exception Message:\\n\\n\"", ".", "$", "exception", "->", "getMessage", "(", ")", ",", "]", ")", ";", "}" ]
Return an error json response. @param \Exception $exception @return \Illuminate\Http\JsonResponse @throws \Yajra\DataTables\Exceptions\Exception
[ "Return", "an", "error", "json", "response", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L772-L790
train
yajra/laravel-datatables
src/DataTableAbstract.php
DataTableAbstract.getColumnNameByIndex
protected function getColumnNameByIndex($index) { $name = (isset($this->columns[$index]) && $this->columns[$index] != '*') ? $this->columns[$index] : $this->getPrimaryKeyName(); return in_array($name, $this->extraColumns, true) ? $this->getPrimaryKeyName() : $name; }
php
protected function getColumnNameByIndex($index) { $name = (isset($this->columns[$index]) && $this->columns[$index] != '*') ? $this->columns[$index] : $this->getPrimaryKeyName(); return in_array($name, $this->extraColumns, true) ? $this->getPrimaryKeyName() : $name; }
[ "protected", "function", "getColumnNameByIndex", "(", "$", "index", ")", "{", "$", "name", "=", "(", "isset", "(", "$", "this", "->", "columns", "[", "$", "index", "]", ")", "&&", "$", "this", "->", "columns", "[", "$", "index", "]", "!=", "'*'", ")", "?", "$", "this", "->", "columns", "[", "$", "index", "]", ":", "$", "this", "->", "getPrimaryKeyName", "(", ")", ";", "return", "in_array", "(", "$", "name", ",", "$", "this", "->", "extraColumns", ",", "true", ")", "?", "$", "this", "->", "getPrimaryKeyName", "(", ")", ":", "$", "name", ";", "}" ]
Get column name by order column index. @param int $index @return string
[ "Get", "column", "name", "by", "order", "column", "index", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTableAbstract.php#L868-L874
train
yajra/laravel-datatables
src/EloquentDataTable.php
EloquentDataTable.addColumns
public function addColumns(array $names, $order = false) { foreach ($names as $name => $attribute) { if (is_int($name)) { $name = $attribute; } $this->addColumn($name, function ($model) use ($attribute) { return $model->getAttribute($attribute); }, is_int($order) ? $order++ : $order); } return $this; }
php
public function addColumns(array $names, $order = false) { foreach ($names as $name => $attribute) { if (is_int($name)) { $name = $attribute; } $this->addColumn($name, function ($model) use ($attribute) { return $model->getAttribute($attribute); }, is_int($order) ? $order++ : $order); } return $this; }
[ "public", "function", "addColumns", "(", "array", "$", "names", ",", "$", "order", "=", "false", ")", "{", "foreach", "(", "$", "names", "as", "$", "name", "=>", "$", "attribute", ")", "{", "if", "(", "is_int", "(", "$", "name", ")", ")", "{", "$", "name", "=", "$", "attribute", ";", "}", "$", "this", "->", "addColumn", "(", "$", "name", ",", "function", "(", "$", "model", ")", "use", "(", "$", "attribute", ")", "{", "return", "$", "model", "->", "getAttribute", "(", "$", "attribute", ")", ";", "}", ",", "is_int", "(", "$", "order", ")", "?", "$", "order", "++", ":", "$", "order", ")", ";", "}", "return", "$", "this", ";", "}" ]
Add columns in collection. @param array $names @param bool|int $order @return $this
[ "Add", "columns", "in", "collection", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/EloquentDataTable.php#L50-L63
train
yajra/laravel-datatables
src/EloquentDataTable.php
EloquentDataTable.resolveRelationColumn
protected function resolveRelationColumn($column) { $parts = explode('.', $column); $columnName = array_pop($parts); $relation = implode('.', $parts); if ($this->isNotEagerLoaded($relation)) { return $column; } return $this->joinEagerLoadedColumn($relation, $columnName); }
php
protected function resolveRelationColumn($column) { $parts = explode('.', $column); $columnName = array_pop($parts); $relation = implode('.', $parts); if ($this->isNotEagerLoaded($relation)) { return $column; } return $this->joinEagerLoadedColumn($relation, $columnName); }
[ "protected", "function", "resolveRelationColumn", "(", "$", "column", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "column", ")", ";", "$", "columnName", "=", "array_pop", "(", "$", "parts", ")", ";", "$", "relation", "=", "implode", "(", "'.'", ",", "$", "parts", ")", ";", "if", "(", "$", "this", "->", "isNotEagerLoaded", "(", "$", "relation", ")", ")", "{", "return", "$", "column", ";", "}", "return", "$", "this", "->", "joinEagerLoadedColumn", "(", "$", "relation", ",", "$", "columnName", ")", ";", "}" ]
Resolve the proper column name be used. @param string $column @return string
[ "Resolve", "the", "proper", "column", "name", "be", "used", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/EloquentDataTable.php#L104-L115
train
yajra/laravel-datatables
src/EloquentDataTable.php
EloquentDataTable.isNotEagerLoaded
protected function isNotEagerLoaded($relation) { return ! $relation || ! array_key_exists($relation, $this->query->getEagerLoads()) || $relation === $this->query->getModel()->getTable(); }
php
protected function isNotEagerLoaded($relation) { return ! $relation || ! array_key_exists($relation, $this->query->getEagerLoads()) || $relation === $this->query->getModel()->getTable(); }
[ "protected", "function", "isNotEagerLoaded", "(", "$", "relation", ")", "{", "return", "!", "$", "relation", "||", "!", "array_key_exists", "(", "$", "relation", ",", "$", "this", "->", "query", "->", "getEagerLoads", "(", ")", ")", "||", "$", "relation", "===", "$", "this", "->", "query", "->", "getModel", "(", ")", "->", "getTable", "(", ")", ";", "}" ]
Check if a relation was not used on eager loading. @param string $relation @return bool
[ "Check", "if", "a", "relation", "was", "not", "used", "on", "eager", "loading", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/EloquentDataTable.php#L123-L128
train
yajra/laravel-datatables
src/DataTablesServiceProvider.php
DataTablesServiceProvider.boot
public function boot() { $engines = config('datatables.engines'); foreach ($engines as $engine => $class) { $engine = camel_case($engine); if (! method_exists(DataTables::class, $engine) && ! DataTables::hasMacro($engine)) { DataTables::macro($engine, function () use ($class) { if (! call_user_func_array([$class, 'canCreate'], func_get_args())) { throw new \InvalidArgumentException(); } return call_user_func_array([$class, 'create'], func_get_args()); }); } } }
php
public function boot() { $engines = config('datatables.engines'); foreach ($engines as $engine => $class) { $engine = camel_case($engine); if (! method_exists(DataTables::class, $engine) && ! DataTables::hasMacro($engine)) { DataTables::macro($engine, function () use ($class) { if (! call_user_func_array([$class, 'canCreate'], func_get_args())) { throw new \InvalidArgumentException(); } return call_user_func_array([$class, 'create'], func_get_args()); }); } } }
[ "public", "function", "boot", "(", ")", "{", "$", "engines", "=", "config", "(", "'datatables.engines'", ")", ";", "foreach", "(", "$", "engines", "as", "$", "engine", "=>", "$", "class", ")", "{", "$", "engine", "=", "camel_case", "(", "$", "engine", ")", ";", "if", "(", "!", "method_exists", "(", "DataTables", "::", "class", ",", "$", "engine", ")", "&&", "!", "DataTables", "::", "hasMacro", "(", "$", "engine", ")", ")", "{", "DataTables", "::", "macro", "(", "$", "engine", ",", "function", "(", ")", "use", "(", "$", "class", ")", "{", "if", "(", "!", "call_user_func_array", "(", "[", "$", "class", ",", "'canCreate'", "]", ",", "func_get_args", "(", ")", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", ")", ";", "}", "return", "call_user_func_array", "(", "[", "$", "class", ",", "'create'", "]", ",", "func_get_args", "(", ")", ")", ";", "}", ")", ";", "}", "}", "}" ]
Boot the instance, add macros for datatable engines. @return void
[ "Boot", "the", "instance", "add", "macros", "for", "datatable", "engines", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTablesServiceProvider.php#L41-L57
train
yajra/laravel-datatables
src/Processors/RowProcessor.php
RowProcessor.rowValue
public function rowValue($attribute, $template) { if (! empty($template)) { if (! is_callable($template) && Arr::get($this->data, $template)) { $this->data[$attribute] = Arr::get($this->data, $template); } else { $this->data[$attribute] = Helper::compileContent($template, $this->data, $this->row); } } return $this; }
php
public function rowValue($attribute, $template) { if (! empty($template)) { if (! is_callable($template) && Arr::get($this->data, $template)) { $this->data[$attribute] = Arr::get($this->data, $template); } else { $this->data[$attribute] = Helper::compileContent($template, $this->data, $this->row); } } return $this; }
[ "public", "function", "rowValue", "(", "$", "attribute", ",", "$", "template", ")", "{", "if", "(", "!", "empty", "(", "$", "template", ")", ")", "{", "if", "(", "!", "is_callable", "(", "$", "template", ")", "&&", "Arr", "::", "get", "(", "$", "this", "->", "data", ",", "$", "template", ")", ")", "{", "$", "this", "->", "data", "[", "$", "attribute", "]", "=", "Arr", "::", "get", "(", "$", "this", "->", "data", ",", "$", "template", ")", ";", "}", "else", "{", "$", "this", "->", "data", "[", "$", "attribute", "]", "=", "Helper", "::", "compileContent", "(", "$", "template", ",", "$", "this", "->", "data", ",", "$", "this", "->", "row", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Process DT RowId and Class value. @param string $attribute @param string|callable $template @return $this
[ "Process", "DT", "RowId", "and", "Class", "value", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/RowProcessor.php#L37-L48
train
yajra/laravel-datatables
src/Processors/RowProcessor.php
RowProcessor.rowData
public function rowData($attribute, array $template) { if (count($template)) { $this->data[$attribute] = []; foreach ($template as $key => $value) { $this->data[$attribute][$key] = Helper::compileContent($value, $this->data, $this->row); } } return $this; }
php
public function rowData($attribute, array $template) { if (count($template)) { $this->data[$attribute] = []; foreach ($template as $key => $value) { $this->data[$attribute][$key] = Helper::compileContent($value, $this->data, $this->row); } } return $this; }
[ "public", "function", "rowData", "(", "$", "attribute", ",", "array", "$", "template", ")", "{", "if", "(", "count", "(", "$", "template", ")", ")", "{", "$", "this", "->", "data", "[", "$", "attribute", "]", "=", "[", "]", ";", "foreach", "(", "$", "template", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "data", "[", "$", "attribute", "]", "[", "$", "key", "]", "=", "Helper", "::", "compileContent", "(", "$", "value", ",", "$", "this", "->", "data", ",", "$", "this", "->", "row", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Process DT Row Data and Attr. @param string $attribute @param array $template @return $this
[ "Process", "DT", "Row", "Data", "and", "Attr", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/RowProcessor.php#L57-L67
train
yajra/laravel-datatables
src/Utilities/Request.php
Request.orderableColumns
public function orderableColumns() { if (! $this->isOrderable()) { return []; } $orderable = []; for ($i = 0, $c = count($this->request->input('order')); $i < $c; $i++) { $order_col = (int) $this->request->input("order.$i.column"); $order_dir = strtolower($this->request->input("order.$i.dir")) === 'asc' ? 'asc' : 'desc'; if ($this->isColumnOrderable($order_col)) { $orderable[] = ['column' => $order_col, 'direction' => $order_dir]; } } return $orderable; }
php
public function orderableColumns() { if (! $this->isOrderable()) { return []; } $orderable = []; for ($i = 0, $c = count($this->request->input('order')); $i < $c; $i++) { $order_col = (int) $this->request->input("order.$i.column"); $order_dir = strtolower($this->request->input("order.$i.dir")) === 'asc' ? 'asc' : 'desc'; if ($this->isColumnOrderable($order_col)) { $orderable[] = ['column' => $order_col, 'direction' => $order_dir]; } } return $orderable; }
[ "public", "function", "orderableColumns", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isOrderable", "(", ")", ")", "{", "return", "[", "]", ";", "}", "$", "orderable", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ",", "$", "c", "=", "count", "(", "$", "this", "->", "request", "->", "input", "(", "'order'", ")", ")", ";", "$", "i", "<", "$", "c", ";", "$", "i", "++", ")", "{", "$", "order_col", "=", "(", "int", ")", "$", "this", "->", "request", "->", "input", "(", "\"order.$i.column\"", ")", ";", "$", "order_dir", "=", "strtolower", "(", "$", "this", "->", "request", "->", "input", "(", "\"order.$i.dir\"", ")", ")", "===", "'asc'", "?", "'asc'", ":", "'desc'", ";", "if", "(", "$", "this", "->", "isColumnOrderable", "(", "$", "order_col", ")", ")", "{", "$", "orderable", "[", "]", "=", "[", "'column'", "=>", "$", "order_col", ",", "'direction'", "=>", "$", "order_dir", "]", ";", "}", "}", "return", "$", "orderable", ";", "}" ]
Get orderable columns. @return array
[ "Get", "orderable", "columns", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Request.php#L91-L107
train
yajra/laravel-datatables
src/Utilities/Request.php
Request.searchableColumnIndex
public function searchableColumnIndex() { $searchable = []; for ($i = 0, $c = count($this->request->input('columns')); $i < $c; $i++) { if ($this->isColumnSearchable($i, false)) { $searchable[] = $i; } } return $searchable; }
php
public function searchableColumnIndex() { $searchable = []; for ($i = 0, $c = count($this->request->input('columns')); $i < $c; $i++) { if ($this->isColumnSearchable($i, false)) { $searchable[] = $i; } } return $searchable; }
[ "public", "function", "searchableColumnIndex", "(", ")", "{", "$", "searchable", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ",", "$", "c", "=", "count", "(", "$", "this", "->", "request", "->", "input", "(", "'columns'", ")", ")", ";", "$", "i", "<", "$", "c", ";", "$", "i", "++", ")", "{", "if", "(", "$", "this", "->", "isColumnSearchable", "(", "$", "i", ",", "false", ")", ")", "{", "$", "searchable", "[", "]", "=", "$", "i", ";", "}", "}", "return", "$", "searchable", ";", "}" ]
Get searchable column indexes. @return array
[ "Get", "searchable", "column", "indexes", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Request.php#L135-L145
train
yajra/laravel-datatables
src/Utilities/Request.php
Request.isColumnSearchable
public function isColumnSearchable($i, $column_search = true) { if ($column_search) { return ( $this->request->input("columns.$i.searchable", 'true') === 'true' || $this->request->input("columns.$i.searchable", 'true') === true ) && $this->columnKeyword($i) != ''; } return $this->request->input("columns.$i.searchable", 'true') === 'true' || $this->request->input("columns.$i.searchable", 'true') === true; }
php
public function isColumnSearchable($i, $column_search = true) { if ($column_search) { return ( $this->request->input("columns.$i.searchable", 'true') === 'true' || $this->request->input("columns.$i.searchable", 'true') === true ) && $this->columnKeyword($i) != ''; } return $this->request->input("columns.$i.searchable", 'true') === 'true' || $this->request->input("columns.$i.searchable", 'true') === true; }
[ "public", "function", "isColumnSearchable", "(", "$", "i", ",", "$", "column_search", "=", "true", ")", "{", "if", "(", "$", "column_search", ")", "{", "return", "(", "$", "this", "->", "request", "->", "input", "(", "\"columns.$i.searchable\"", ",", "'true'", ")", "===", "'true'", "||", "$", "this", "->", "request", "->", "input", "(", "\"columns.$i.searchable\"", ",", "'true'", ")", "===", "true", ")", "&&", "$", "this", "->", "columnKeyword", "(", "$", "i", ")", "!=", "''", ";", "}", "return", "$", "this", "->", "request", "->", "input", "(", "\"columns.$i.searchable\"", ",", "'true'", ")", "===", "'true'", "||", "$", "this", "->", "request", "->", "input", "(", "\"columns.$i.searchable\"", ",", "'true'", ")", "===", "true", ";", "}" ]
Check if a column is searchable. @param int $i @param bool $column_search @return bool
[ "Check", "if", "a", "column", "is", "searchable", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Request.php#L154-L170
train
yajra/laravel-datatables
src/Utilities/Request.php
Request.columnName
public function columnName($i) { $column = $this->request->input("columns.$i"); return isset($column['name']) && $column['name'] != '' ? $column['name'] : $column['data']; }
php
public function columnName($i) { $column = $this->request->input("columns.$i"); return isset($column['name']) && $column['name'] != '' ? $column['name'] : $column['data']; }
[ "public", "function", "columnName", "(", "$", "i", ")", "{", "$", "column", "=", "$", "this", "->", "request", "->", "input", "(", "\"columns.$i\"", ")", ";", "return", "isset", "(", "$", "column", "[", "'name'", "]", ")", "&&", "$", "column", "[", "'name'", "]", "!=", "''", "?", "$", "column", "[", "'name'", "]", ":", "$", "column", "[", "'data'", "]", ";", "}" ]
Get column identity from input or database. @param int $i @return string
[ "Get", "column", "identity", "from", "input", "or", "database", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Request.php#L218-L223
train
yajra/laravel-datatables
src/Utilities/Request.php
Request.isPaginationable
public function isPaginationable() { return ! is_null($this->request->input('start')) && ! is_null($this->request->input('length')) && $this->request->input('length') != -1; }
php
public function isPaginationable() { return ! is_null($this->request->input('start')) && ! is_null($this->request->input('length')) && $this->request->input('length') != -1; }
[ "public", "function", "isPaginationable", "(", ")", "{", "return", "!", "is_null", "(", "$", "this", "->", "request", "->", "input", "(", "'start'", ")", ")", "&&", "!", "is_null", "(", "$", "this", "->", "request", "->", "input", "(", "'length'", ")", ")", "&&", "$", "this", "->", "request", "->", "input", "(", "'length'", ")", "!=", "-", "1", ";", "}" ]
Check if DataTables allow pagination. @return bool
[ "Check", "if", "DataTables", "allow", "pagination", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Request.php#L230-L235
train
yajra/laravel-datatables
src/CollectionDataTable.php
CollectionDataTable.create
public static function create($source) { if (is_array($source)) { $source = new Collection($source); } return parent::create($source); }
php
public static function create($source) { if (is_array($source)) { $source = new Collection($source); } return parent::create($source); }
[ "public", "static", "function", "create", "(", "$", "source", ")", "{", "if", "(", "is_array", "(", "$", "source", ")", ")", "{", "$", "source", "=", "new", "Collection", "(", "$", "source", ")", ";", "}", "return", "parent", "::", "create", "(", "$", "source", ")", ";", "}" ]
Factory method, create and return an instance for the DataTable engine. @param array|\Illuminate\Support\Collection $source @return CollectionDataTable|DataTableAbstract
[ "Factory", "method", "create", "and", "return", "an", "instance", "for", "the", "DataTable", "engine", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/CollectionDataTable.php#L43-L50
train
yajra/laravel-datatables
src/CollectionDataTable.php
CollectionDataTable.count
public function count() { return $this->collection->count() > $this->totalRecords ? $this->totalRecords : $this->collection->count(); }
php
public function count() { return $this->collection->count() > $this->totalRecords ? $this->totalRecords : $this->collection->count(); }
[ "public", "function", "count", "(", ")", "{", "return", "$", "this", "->", "collection", "->", "count", "(", ")", ">", "$", "this", "->", "totalRecords", "?", "$", "this", "->", "totalRecords", ":", "$", "this", "->", "collection", "->", "count", "(", ")", ";", "}" ]
Count results. @return int
[ "Count", "results", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/CollectionDataTable.php#L82-L85
train
yajra/laravel-datatables
src/CollectionDataTable.php
CollectionDataTable.revertIndexColumn
private function revertIndexColumn($mDataSupport) { if ($this->columnDef['index']) { $index = $mDataSupport ? config('datatables.index_column', 'DT_RowIndex') : 0; $start = (int) $this->request->input('start'); $this->collection->transform(function ($data) use ($index, &$start) { $data[$index] = ++$start; return $data; }); } }
php
private function revertIndexColumn($mDataSupport) { if ($this->columnDef['index']) { $index = $mDataSupport ? config('datatables.index_column', 'DT_RowIndex') : 0; $start = (int) $this->request->input('start'); $this->collection->transform(function ($data) use ($index, &$start) { $data[$index] = ++$start; return $data; }); } }
[ "private", "function", "revertIndexColumn", "(", "$", "mDataSupport", ")", "{", "if", "(", "$", "this", "->", "columnDef", "[", "'index'", "]", ")", "{", "$", "index", "=", "$", "mDataSupport", "?", "config", "(", "'datatables.index_column'", ",", "'DT_RowIndex'", ")", ":", "0", ";", "$", "start", "=", "(", "int", ")", "$", "this", "->", "request", "->", "input", "(", "'start'", ")", ";", "$", "this", "->", "collection", "->", "transform", "(", "function", "(", "$", "data", ")", "use", "(", "$", "index", ",", "&", "$", "start", ")", "{", "$", "data", "[", "$", "index", "]", "=", "++", "$", "start", ";", "return", "$", "data", ";", "}", ")", ";", "}", "}" ]
Revert transformed DT_RowIndex back to it's original values. @param bool $mDataSupport
[ "Revert", "transformed", "DT_RowIndex", "back", "to", "it", "s", "original", "values", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/CollectionDataTable.php#L196-L207
train
yajra/laravel-datatables
src/CollectionDataTable.php
CollectionDataTable.getSorter
protected function getSorter(array $criteria) { $sorter = function ($a, $b) use ($criteria) { foreach ($criteria as $orderable) { $column = $this->getColumnName($orderable['column']); $direction = $orderable['direction']; if ($direction === 'desc') { $first = $b; $second = $a; } else { $first = $a; $second = $b; } if ($this->config->isCaseInsensitive()) { $cmp = strnatcasecmp($first[$column], $second[$column]); } else { $cmp = strnatcmp($first[$column], $second[$column]); } if ($cmp != 0) { return $cmp; } } // all elements were equal return 0; }; return $sorter; }
php
protected function getSorter(array $criteria) { $sorter = function ($a, $b) use ($criteria) { foreach ($criteria as $orderable) { $column = $this->getColumnName($orderable['column']); $direction = $orderable['direction']; if ($direction === 'desc') { $first = $b; $second = $a; } else { $first = $a; $second = $b; } if ($this->config->isCaseInsensitive()) { $cmp = strnatcasecmp($first[$column], $second[$column]); } else { $cmp = strnatcmp($first[$column], $second[$column]); } if ($cmp != 0) { return $cmp; } } // all elements were equal return 0; }; return $sorter; }
[ "protected", "function", "getSorter", "(", "array", "$", "criteria", ")", "{", "$", "sorter", "=", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "criteria", ")", "{", "foreach", "(", "$", "criteria", "as", "$", "orderable", ")", "{", "$", "column", "=", "$", "this", "->", "getColumnName", "(", "$", "orderable", "[", "'column'", "]", ")", ";", "$", "direction", "=", "$", "orderable", "[", "'direction'", "]", ";", "if", "(", "$", "direction", "===", "'desc'", ")", "{", "$", "first", "=", "$", "b", ";", "$", "second", "=", "$", "a", ";", "}", "else", "{", "$", "first", "=", "$", "a", ";", "$", "second", "=", "$", "b", ";", "}", "if", "(", "$", "this", "->", "config", "->", "isCaseInsensitive", "(", ")", ")", "{", "$", "cmp", "=", "strnatcasecmp", "(", "$", "first", "[", "$", "column", "]", ",", "$", "second", "[", "$", "column", "]", ")", ";", "}", "else", "{", "$", "cmp", "=", "strnatcmp", "(", "$", "first", "[", "$", "column", "]", ",", "$", "second", "[", "$", "column", "]", ")", ";", "}", "if", "(", "$", "cmp", "!=", "0", ")", "{", "return", "$", "cmp", ";", "}", "}", "// all elements were equal", "return", "0", ";", "}", ";", "return", "$", "sorter", ";", "}" ]
Get array sorter closure. @param array $criteria @return \Closure
[ "Get", "array", "sorter", "closure", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/CollectionDataTable.php#L274-L302
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.prepareQuery
protected function prepareQuery() { if (! $this->prepared) { $this->totalRecords = $this->totalCount(); if ($this->totalRecords) { $this->filterRecords(); $this->ordering(); $this->paginate(); } } $this->prepared = true; }
php
protected function prepareQuery() { if (! $this->prepared) { $this->totalRecords = $this->totalCount(); if ($this->totalRecords) { $this->filterRecords(); $this->ordering(); $this->paginate(); } } $this->prepared = true; }
[ "protected", "function", "prepareQuery", "(", ")", "{", "if", "(", "!", "$", "this", "->", "prepared", ")", "{", "$", "this", "->", "totalRecords", "=", "$", "this", "->", "totalCount", "(", ")", ";", "if", "(", "$", "this", "->", "totalRecords", ")", "{", "$", "this", "->", "filterRecords", "(", ")", ";", "$", "this", "->", "ordering", "(", ")", ";", "$", "this", "->", "paginate", "(", ")", ";", "}", "}", "$", "this", "->", "prepared", "=", "true", ";", "}" ]
Prepare query by executing count, filter, order and paginate.
[ "Prepare", "query", "by", "executing", "count", "filter", "order", "and", "paginate", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L113-L126
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.totalCount
public function totalCount() { if ($this->skipTotalRecords) { return true; } return $this->totalRecords ? $this->totalRecords : $this->count(); }
php
public function totalCount() { if ($this->skipTotalRecords) { return true; } return $this->totalRecords ? $this->totalRecords : $this->count(); }
[ "public", "function", "totalCount", "(", ")", "{", "if", "(", "$", "this", "->", "skipTotalRecords", ")", "{", "return", "true", ";", "}", "return", "$", "this", "->", "totalRecords", "?", "$", "this", "->", "totalRecords", ":", "$", "this", "->", "count", "(", ")", ";", "}" ]
Count total items. @return int
[ "Count", "total", "items", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L158-L165
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.filteredCount
protected function filteredCount() { $this->filteredRecords = $this->filteredRecords ?: $this->count(); if ($this->skipTotalRecords) { $this->totalRecords = $this->filteredRecords; } return $this->filteredRecords; }
php
protected function filteredCount() { $this->filteredRecords = $this->filteredRecords ?: $this->count(); if ($this->skipTotalRecords) { $this->totalRecords = $this->filteredRecords; } return $this->filteredRecords; }
[ "protected", "function", "filteredCount", "(", ")", "{", "$", "this", "->", "filteredRecords", "=", "$", "this", "->", "filteredRecords", "?", ":", "$", "this", "->", "count", "(", ")", ";", "if", "(", "$", "this", "->", "skipTotalRecords", ")", "{", "$", "this", "->", "totalRecords", "=", "$", "this", "->", "filteredRecords", ";", "}", "return", "$", "this", "->", "filteredRecords", ";", "}" ]
Count filtered items. @return int
[ "Count", "filtered", "items", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L172-L180
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.prepareCountQuery
protected function prepareCountQuery() { $builder = clone $this->query; if (! $this->isComplexQuery($builder)) { $row_count = $this->wrap('row_count'); $builder->select($this->connection->raw("'1' as {$row_count}")); if (! $this->keepSelectBindings) { $builder->setBindings([], 'select'); } } return $builder; }
php
protected function prepareCountQuery() { $builder = clone $this->query; if (! $this->isComplexQuery($builder)) { $row_count = $this->wrap('row_count'); $builder->select($this->connection->raw("'1' as {$row_count}")); if (! $this->keepSelectBindings) { $builder->setBindings([], 'select'); } } return $builder; }
[ "protected", "function", "prepareCountQuery", "(", ")", "{", "$", "builder", "=", "clone", "$", "this", "->", "query", ";", "if", "(", "!", "$", "this", "->", "isComplexQuery", "(", "$", "builder", ")", ")", "{", "$", "row_count", "=", "$", "this", "->", "wrap", "(", "'row_count'", ")", ";", "$", "builder", "->", "select", "(", "$", "this", "->", "connection", "->", "raw", "(", "\"'1' as {$row_count}\"", ")", ")", ";", "if", "(", "!", "$", "this", "->", "keepSelectBindings", ")", "{", "$", "builder", "->", "setBindings", "(", "[", "]", ",", "'select'", ")", ";", "}", "}", "return", "$", "builder", ";", "}" ]
Prepare count query builder. @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
[ "Prepare", "count", "query", "builder", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L202-L215
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.getColumnSearchKeyword
protected function getColumnSearchKeyword($i, $raw = false) { $keyword = $this->request->columnKeyword($i); if ($raw || $this->request->isRegex($i)) { return $keyword; } return $this->setupKeyword($keyword); }
php
protected function getColumnSearchKeyword($i, $raw = false) { $keyword = $this->request->columnKeyword($i); if ($raw || $this->request->isRegex($i)) { return $keyword; } return $this->setupKeyword($keyword); }
[ "protected", "function", "getColumnSearchKeyword", "(", "$", "i", ",", "$", "raw", "=", "false", ")", "{", "$", "keyword", "=", "$", "this", "->", "request", "->", "columnKeyword", "(", "$", "i", ")", ";", "if", "(", "$", "raw", "||", "$", "this", "->", "request", "->", "isRegex", "(", "$", "i", ")", ")", "{", "return", "$", "keyword", ";", "}", "return", "$", "this", "->", "setupKeyword", "(", "$", "keyword", ")", ";", "}" ]
Get column keyword to use for search. @param int $i @param bool $raw @return string
[ "Get", "column", "keyword", "to", "use", "for", "search", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L318-L326
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.applyFilterColumn
protected function applyFilterColumn($query, $columnName, $keyword, $boolean = 'and') { $query = $this->getBaseQueryBuilder($query); $callback = $this->columnDef['filter'][$columnName]['method']; if ($this->query instanceof EloquentBuilder) { $builder = $this->query->newModelInstance()->newQuery(); } else { $builder = $this->query->newQuery(); } $callback($builder, $keyword); $query->addNestedWhereQuery($this->getBaseQueryBuilder($builder), $boolean); }
php
protected function applyFilterColumn($query, $columnName, $keyword, $boolean = 'and') { $query = $this->getBaseQueryBuilder($query); $callback = $this->columnDef['filter'][$columnName]['method']; if ($this->query instanceof EloquentBuilder) { $builder = $this->query->newModelInstance()->newQuery(); } else { $builder = $this->query->newQuery(); } $callback($builder, $keyword); $query->addNestedWhereQuery($this->getBaseQueryBuilder($builder), $boolean); }
[ "protected", "function", "applyFilterColumn", "(", "$", "query", ",", "$", "columnName", ",", "$", "keyword", ",", "$", "boolean", "=", "'and'", ")", "{", "$", "query", "=", "$", "this", "->", "getBaseQueryBuilder", "(", "$", "query", ")", ";", "$", "callback", "=", "$", "this", "->", "columnDef", "[", "'filter'", "]", "[", "$", "columnName", "]", "[", "'method'", "]", ";", "if", "(", "$", "this", "->", "query", "instanceof", "EloquentBuilder", ")", "{", "$", "builder", "=", "$", "this", "->", "query", "->", "newModelInstance", "(", ")", "->", "newQuery", "(", ")", ";", "}", "else", "{", "$", "builder", "=", "$", "this", "->", "query", "->", "newQuery", "(", ")", ";", "}", "$", "callback", "(", "$", "builder", ",", "$", "keyword", ")", ";", "$", "query", "->", "addNestedWhereQuery", "(", "$", "this", "->", "getBaseQueryBuilder", "(", "$", "builder", ")", ",", "$", "boolean", ")", ";", "}" ]
Apply filterColumn api search. @param mixed $query @param string $columnName @param string $keyword @param string $boolean
[ "Apply", "filterColumn", "api", "search", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L336-L350
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.getBaseQueryBuilder
protected function getBaseQueryBuilder($instance = null) { if (! $instance) { $instance = $this->query; } if ($instance instanceof EloquentBuilder) { return $instance->getQuery(); } return $instance; }
php
protected function getBaseQueryBuilder($instance = null) { if (! $instance) { $instance = $this->query; } if ($instance instanceof EloquentBuilder) { return $instance->getQuery(); } return $instance; }
[ "protected", "function", "getBaseQueryBuilder", "(", "$", "instance", "=", "null", ")", "{", "if", "(", "!", "$", "instance", ")", "{", "$", "instance", "=", "$", "this", "->", "query", ";", "}", "if", "(", "$", "instance", "instanceof", "EloquentBuilder", ")", "{", "return", "$", "instance", "->", "getQuery", "(", ")", ";", "}", "return", "$", "instance", ";", "}" ]
Get the base query builder instance. @param mixed $instance @return \Illuminate\Database\Query\Builder
[ "Get", "the", "base", "query", "builder", "instance", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L358-L369
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.addTablePrefix
protected function addTablePrefix($query, $column) { if (strpos($column, '.') === false) { $q = $this->getBaseQueryBuilder($query); if (! $q->from instanceof Expression) { $column = $q->from . '.' . $column; } } return $this->wrap($column); }
php
protected function addTablePrefix($query, $column) { if (strpos($column, '.') === false) { $q = $this->getBaseQueryBuilder($query); if (! $q->from instanceof Expression) { $column = $q->from . '.' . $column; } } return $this->wrap($column); }
[ "protected", "function", "addTablePrefix", "(", "$", "query", ",", "$", "column", ")", "{", "if", "(", "strpos", "(", "$", "column", ",", "'.'", ")", "===", "false", ")", "{", "$", "q", "=", "$", "this", "->", "getBaseQueryBuilder", "(", "$", "query", ")", ";", "if", "(", "!", "$", "q", "->", "from", "instanceof", "Expression", ")", "{", "$", "column", "=", "$", "q", "->", "from", ".", "'.'", ".", "$", "column", ";", "}", "}", "return", "$", "this", "->", "wrap", "(", "$", "column", ")", ";", "}" ]
Patch for fix about ambiguous field. Ambiguous field error will appear when query use join table and search with keyword. @param mixed $query @param string $column @return string
[ "Patch", "for", "fix", "about", "ambiguous", "field", ".", "Ambiguous", "field", "error", "will", "appear", "when", "query", "use", "join", "table", "and", "search", "with", "keyword", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L476-L486
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.prepareKeyword
protected function prepareKeyword($keyword) { if ($this->config->isCaseInsensitive()) { $keyword = Str::lower($keyword); } if ($this->config->isWildcard()) { $keyword = Helper::wildcardLikeString($keyword); } if ($this->config->isSmartSearch()) { $keyword = "%$keyword%"; } return $keyword; }
php
protected function prepareKeyword($keyword) { if ($this->config->isCaseInsensitive()) { $keyword = Str::lower($keyword); } if ($this->config->isWildcard()) { $keyword = Helper::wildcardLikeString($keyword); } if ($this->config->isSmartSearch()) { $keyword = "%$keyword%"; } return $keyword; }
[ "protected", "function", "prepareKeyword", "(", "$", "keyword", ")", "{", "if", "(", "$", "this", "->", "config", "->", "isCaseInsensitive", "(", ")", ")", "{", "$", "keyword", "=", "Str", "::", "lower", "(", "$", "keyword", ")", ";", "}", "if", "(", "$", "this", "->", "config", "->", "isWildcard", "(", ")", ")", "{", "$", "keyword", "=", "Helper", "::", "wildcardLikeString", "(", "$", "keyword", ")", ";", "}", "if", "(", "$", "this", "->", "config", "->", "isSmartSearch", "(", ")", ")", "{", "$", "keyword", "=", "\"%$keyword%\"", ";", "}", "return", "$", "keyword", ";", "}" ]
Prepare search keyword based on configurations. @param string $keyword @return string
[ "Prepare", "search", "keyword", "based", "on", "configurations", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L494-L509
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.orderColumns
public function orderColumns(array $columns, $sql, $bindings = []) { foreach ($columns as $column) { $this->orderColumn($column, str_replace(':column', $column, $sql), $bindings); } return $this; }
php
public function orderColumns(array $columns, $sql, $bindings = []) { foreach ($columns as $column) { $this->orderColumn($column, str_replace(':column', $column, $sql), $bindings); } return $this; }
[ "public", "function", "orderColumns", "(", "array", "$", "columns", ",", "$", "sql", ",", "$", "bindings", "=", "[", "]", ")", "{", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "$", "this", "->", "orderColumn", "(", "$", "column", ",", "str_replace", "(", "':column'", ",", "$", "column", ",", "$", "sql", ")", ",", "$", "bindings", ")", ";", "}", "return", "$", "this", ";", "}" ]
Order each given columns versus the given custom sql. @param array $columns @param string $sql @param array $bindings @return $this
[ "Order", "each", "given", "columns", "versus", "the", "given", "custom", "sql", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L533-L540
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.applyOrderColumn
protected function applyOrderColumn($column, $orderable) { $sql = $this->columnDef['order'][$column]['sql']; $sql = str_replace('$1', $orderable['direction'], $sql); $bindings = $this->columnDef['order'][$column]['bindings']; $this->query->orderByRaw($sql, $bindings); }
php
protected function applyOrderColumn($column, $orderable) { $sql = $this->columnDef['order'][$column]['sql']; $sql = str_replace('$1', $orderable['direction'], $sql); $bindings = $this->columnDef['order'][$column]['bindings']; $this->query->orderByRaw($sql, $bindings); }
[ "protected", "function", "applyOrderColumn", "(", "$", "column", ",", "$", "orderable", ")", "{", "$", "sql", "=", "$", "this", "->", "columnDef", "[", "'order'", "]", "[", "$", "column", "]", "[", "'sql'", "]", ";", "$", "sql", "=", "str_replace", "(", "'$1'", ",", "$", "orderable", "[", "'direction'", "]", ",", "$", "sql", ")", ";", "$", "bindings", "=", "$", "this", "->", "columnDef", "[", "'order'", "]", "[", "$", "column", "]", "[", "'bindings'", "]", ";", "$", "this", "->", "query", "->", "orderByRaw", "(", "$", "sql", ",", "$", "bindings", ")", ";", "}" ]
Apply orderColumn custom query. @param string $column @param array $orderable
[ "Apply", "orderColumn", "custom", "query", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L670-L676
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.getNullsLastSql
protected function getNullsLastSql($column, $direction) { $sql = $this->config->get('datatables.nulls_last_sql', '%s %s NULLS LAST'); return sprintf($sql, $column, $direction); }
php
protected function getNullsLastSql($column, $direction) { $sql = $this->config->get('datatables.nulls_last_sql', '%s %s NULLS LAST'); return sprintf($sql, $column, $direction); }
[ "protected", "function", "getNullsLastSql", "(", "$", "column", ",", "$", "direction", ")", "{", "$", "sql", "=", "$", "this", "->", "config", "->", "get", "(", "'datatables.nulls_last_sql'", ",", "'%s %s NULLS LAST'", ")", ";", "return", "sprintf", "(", "$", "sql", ",", "$", "column", ",", "$", "direction", ")", ";", "}" ]
Get NULLS LAST SQL. @param string $column @param string $direction @return string
[ "Get", "NULLS", "LAST", "SQL", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L685-L690
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.showDebugger
protected function showDebugger(array $output) { $output['queries'] = $this->connection->getQueryLog(); $output['input'] = $this->request->all(); return $output; }
php
protected function showDebugger(array $output) { $output['queries'] = $this->connection->getQueryLog(); $output['input'] = $this->request->all(); return $output; }
[ "protected", "function", "showDebugger", "(", "array", "$", "output", ")", "{", "$", "output", "[", "'queries'", "]", "=", "$", "this", "->", "connection", "->", "getQueryLog", "(", ")", ";", "$", "output", "[", "'input'", "]", "=", "$", "this", "->", "request", "->", "all", "(", ")", ";", "return", "$", "output", ";", "}" ]
Append debug parameters on output. @param array $output @return array
[ "Append", "debug", "parameters", "on", "output", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L725-L731
train
yajra/laravel-datatables
src/QueryDataTable.php
QueryDataTable.attachAppends
protected function attachAppends(array $data) { $appends = []; foreach ($this->appends as $key => $value) { if (is_callable($value)) { $appends[$key] = value($value($this->getFilteredQuery())); } else { $appends[$key] = $value; } } return array_merge($data, $appends); }
php
protected function attachAppends(array $data) { $appends = []; foreach ($this->appends as $key => $value) { if (is_callable($value)) { $appends[$key] = value($value($this->getFilteredQuery())); } else { $appends[$key] = $value; } } return array_merge($data, $appends); }
[ "protected", "function", "attachAppends", "(", "array", "$", "data", ")", "{", "$", "appends", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "appends", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_callable", "(", "$", "value", ")", ")", "{", "$", "appends", "[", "$", "key", "]", "=", "value", "(", "$", "value", "(", "$", "this", "->", "getFilteredQuery", "(", ")", ")", ")", ";", "}", "else", "{", "$", "appends", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "array_merge", "(", "$", "data", ",", "$", "appends", ")", ";", "}" ]
Attach custom with meta on response. @param array $data @return array
[ "Attach", "custom", "with", "meta", "on", "response", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/QueryDataTable.php#L739-L751
train
yajra/laravel-datatables
src/DataTables.php
DataTables.make
public static function make($source) { $engines = config('datatables.engines'); $builders = config('datatables.builders'); $args = func_get_args(); foreach ($builders as $class => $engine) { if ($source instanceof $class) { return call_user_func_array([$engines[$engine], 'create'], $args); } } foreach ($engines as $engine => $class) { if (call_user_func_array([$engines[$engine], 'canCreate'], $args)) { return call_user_func_array([$engines[$engine], 'create'], $args); } } throw new \Exception('No available engine for ' . get_class($source)); }
php
public static function make($source) { $engines = config('datatables.engines'); $builders = config('datatables.builders'); $args = func_get_args(); foreach ($builders as $class => $engine) { if ($source instanceof $class) { return call_user_func_array([$engines[$engine], 'create'], $args); } } foreach ($engines as $engine => $class) { if (call_user_func_array([$engines[$engine], 'canCreate'], $args)) { return call_user_func_array([$engines[$engine], 'create'], $args); } } throw new \Exception('No available engine for ' . get_class($source)); }
[ "public", "static", "function", "make", "(", "$", "source", ")", "{", "$", "engines", "=", "config", "(", "'datatables.engines'", ")", ";", "$", "builders", "=", "config", "(", "'datatables.builders'", ")", ";", "$", "args", "=", "func_get_args", "(", ")", ";", "foreach", "(", "$", "builders", "as", "$", "class", "=>", "$", "engine", ")", "{", "if", "(", "$", "source", "instanceof", "$", "class", ")", "{", "return", "call_user_func_array", "(", "[", "$", "engines", "[", "$", "engine", "]", ",", "'create'", "]", ",", "$", "args", ")", ";", "}", "}", "foreach", "(", "$", "engines", "as", "$", "engine", "=>", "$", "class", ")", "{", "if", "(", "call_user_func_array", "(", "[", "$", "engines", "[", "$", "engine", "]", ",", "'canCreate'", "]", ",", "$", "args", ")", ")", "{", "return", "call_user_func_array", "(", "[", "$", "engines", "[", "$", "engine", "]", ",", "'create'", "]", ",", "$", "args", ")", ";", "}", "}", "throw", "new", "\\", "Exception", "(", "'No available engine for '", ".", "get_class", "(", "$", "source", ")", ")", ";", "}" ]
Make a DataTable instance from source. @param mixed $source @return mixed @throws \Exception
[ "Make", "a", "DataTable", "instance", "from", "source", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/DataTables.php#L45-L64
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.process
public function process($object = false) { $this->output = []; $indexColumn = config('datatables.index_column', 'DT_RowIndex'); foreach ($this->results as $row) { $data = Helper::convertToArray($row); $value = $this->addColumns($data, $row); $value = $this->editColumns($value, $row); $value = $this->setupRowVariables($value, $row); $value = $this->selectOnlyNeededColumns($value); $value = $this->removeExcessColumns($value); if ($this->includeIndex) { $value[$indexColumn] = ++$this->start; } $this->output[] = $object ? $value : $this->flatten($value); } return $this->escapeColumns($this->output); }
php
public function process($object = false) { $this->output = []; $indexColumn = config('datatables.index_column', 'DT_RowIndex'); foreach ($this->results as $row) { $data = Helper::convertToArray($row); $value = $this->addColumns($data, $row); $value = $this->editColumns($value, $row); $value = $this->setupRowVariables($value, $row); $value = $this->selectOnlyNeededColumns($value); $value = $this->removeExcessColumns($value); if ($this->includeIndex) { $value[$indexColumn] = ++$this->start; } $this->output[] = $object ? $value : $this->flatten($value); } return $this->escapeColumns($this->output); }
[ "public", "function", "process", "(", "$", "object", "=", "false", ")", "{", "$", "this", "->", "output", "=", "[", "]", ";", "$", "indexColumn", "=", "config", "(", "'datatables.index_column'", ",", "'DT_RowIndex'", ")", ";", "foreach", "(", "$", "this", "->", "results", "as", "$", "row", ")", "{", "$", "data", "=", "Helper", "::", "convertToArray", "(", "$", "row", ")", ";", "$", "value", "=", "$", "this", "->", "addColumns", "(", "$", "data", ",", "$", "row", ")", ";", "$", "value", "=", "$", "this", "->", "editColumns", "(", "$", "value", ",", "$", "row", ")", ";", "$", "value", "=", "$", "this", "->", "setupRowVariables", "(", "$", "value", ",", "$", "row", ")", ";", "$", "value", "=", "$", "this", "->", "selectOnlyNeededColumns", "(", "$", "value", ")", ";", "$", "value", "=", "$", "this", "->", "removeExcessColumns", "(", "$", "value", ")", ";", "if", "(", "$", "this", "->", "includeIndex", ")", "{", "$", "value", "[", "$", "indexColumn", "]", "=", "++", "$", "this", "->", "start", ";", "}", "$", "this", "->", "output", "[", "]", "=", "$", "object", "?", "$", "value", ":", "$", "this", "->", "flatten", "(", "$", "value", ")", ";", "}", "return", "$", "this", "->", "escapeColumns", "(", "$", "this", "->", "output", ")", ";", "}" ]
Process data to output on browser. @param bool $object @return array
[ "Process", "data", "to", "output", "on", "browser", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L95-L116
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.addColumns
protected function addColumns($data, $row) { foreach ($this->appendColumns as $key => $value) { $value['content'] = Helper::compileContent($value['content'], $data, $row); $data = Helper::includeInArray($value, $data); } return $data; }
php
protected function addColumns($data, $row) { foreach ($this->appendColumns as $key => $value) { $value['content'] = Helper::compileContent($value['content'], $data, $row); $data = Helper::includeInArray($value, $data); } return $data; }
[ "protected", "function", "addColumns", "(", "$", "data", ",", "$", "row", ")", "{", "foreach", "(", "$", "this", "->", "appendColumns", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "value", "[", "'content'", "]", "=", "Helper", "::", "compileContent", "(", "$", "value", "[", "'content'", "]", ",", "$", "data", ",", "$", "row", ")", ";", "$", "data", "=", "Helper", "::", "includeInArray", "(", "$", "value", ",", "$", "data", ")", ";", "}", "return", "$", "data", ";", "}" ]
Process add columns. @param mixed $data @param mixed $row @return array
[ "Process", "add", "columns", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L125-L133
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.editColumns
protected function editColumns($data, $row) { foreach ($this->editColumns as $key => $value) { $value['content'] = Helper::compileContent($value['content'], $data, $row); Arr::set($data, $value['name'], $value['content']); } return $data; }
php
protected function editColumns($data, $row) { foreach ($this->editColumns as $key => $value) { $value['content'] = Helper::compileContent($value['content'], $data, $row); Arr::set($data, $value['name'], $value['content']); } return $data; }
[ "protected", "function", "editColumns", "(", "$", "data", ",", "$", "row", ")", "{", "foreach", "(", "$", "this", "->", "editColumns", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "value", "[", "'content'", "]", "=", "Helper", "::", "compileContent", "(", "$", "value", "[", "'content'", "]", ",", "$", "data", ",", "$", "row", ")", ";", "Arr", "::", "set", "(", "$", "data", ",", "$", "value", "[", "'name'", "]", ",", "$", "value", "[", "'content'", "]", ")", ";", "}", "return", "$", "data", ";", "}" ]
Process edit columns. @param mixed $data @param mixed $row @return array
[ "Process", "edit", "columns", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L142-L150
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.setupRowVariables
protected function setupRowVariables($data, $row) { $processor = new RowProcessor($data, $row); return $processor ->rowValue('DT_RowId', $this->templates['DT_RowId']) ->rowValue('DT_RowClass', $this->templates['DT_RowClass']) ->rowData('DT_RowData', $this->templates['DT_RowData']) ->rowData('DT_RowAttr', $this->templates['DT_RowAttr']) ->getData(); }
php
protected function setupRowVariables($data, $row) { $processor = new RowProcessor($data, $row); return $processor ->rowValue('DT_RowId', $this->templates['DT_RowId']) ->rowValue('DT_RowClass', $this->templates['DT_RowClass']) ->rowData('DT_RowData', $this->templates['DT_RowData']) ->rowData('DT_RowAttr', $this->templates['DT_RowAttr']) ->getData(); }
[ "protected", "function", "setupRowVariables", "(", "$", "data", ",", "$", "row", ")", "{", "$", "processor", "=", "new", "RowProcessor", "(", "$", "data", ",", "$", "row", ")", ";", "return", "$", "processor", "->", "rowValue", "(", "'DT_RowId'", ",", "$", "this", "->", "templates", "[", "'DT_RowId'", "]", ")", "->", "rowValue", "(", "'DT_RowClass'", ",", "$", "this", "->", "templates", "[", "'DT_RowClass'", "]", ")", "->", "rowData", "(", "'DT_RowData'", ",", "$", "this", "->", "templates", "[", "'DT_RowData'", "]", ")", "->", "rowData", "(", "'DT_RowAttr'", ",", "$", "this", "->", "templates", "[", "'DT_RowAttr'", "]", ")", "->", "getData", "(", ")", ";", "}" ]
Setup additional DT row variables. @param mixed $data @param mixed $row @return array
[ "Setup", "additional", "DT", "row", "variables", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L159-L169
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.selectOnlyNeededColumns
protected function selectOnlyNeededColumns(array $data) { if (is_null($this->onlyColumns)) { return $data; } else { return array_intersect_key($data, array_flip(array_merge($this->onlyColumns, $this->exceptions))); } }
php
protected function selectOnlyNeededColumns(array $data) { if (is_null($this->onlyColumns)) { return $data; } else { return array_intersect_key($data, array_flip(array_merge($this->onlyColumns, $this->exceptions))); } }
[ "protected", "function", "selectOnlyNeededColumns", "(", "array", "$", "data", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "onlyColumns", ")", ")", "{", "return", "$", "data", ";", "}", "else", "{", "return", "array_intersect_key", "(", "$", "data", ",", "array_flip", "(", "array_merge", "(", "$", "this", "->", "onlyColumns", ",", "$", "this", "->", "exceptions", ")", ")", ")", ";", "}", "}" ]
Get only needed columns. @param array $data @return array
[ "Get", "only", "needed", "columns", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L177-L184
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.flatten
public function flatten(array $array) { $return = []; foreach ($array as $key => $value) { if (in_array($key, $this->exceptions)) { $return[$key] = $value; } else { $return[] = $value; } } return $return; }
php
public function flatten(array $array) { $return = []; foreach ($array as $key => $value) { if (in_array($key, $this->exceptions)) { $return[$key] = $value; } else { $return[] = $value; } } return $return; }
[ "public", "function", "flatten", "(", "array", "$", "array", ")", "{", "$", "return", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "key", ",", "$", "this", "->", "exceptions", ")", ")", "{", "$", "return", "[", "$", "key", "]", "=", "$", "value", ";", "}", "else", "{", "$", "return", "[", "]", "=", "$", "value", ";", "}", "}", "return", "$", "return", ";", "}" ]
Flatten array with exceptions. @param array $array @return array
[ "Flatten", "array", "with", "exceptions", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L207-L219
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.escapeColumns
protected function escapeColumns(array $output) { return array_map(function ($row) { if ($this->escapeColumns == '*') { $row = $this->escapeRow($row); } elseif (is_array($this->escapeColumns)) { $columns = array_diff($this->escapeColumns, $this->rawColumns); foreach ($columns as $key) { array_set($row, $key, e(array_get($row, $key))); } } return $row; }, $output); }
php
protected function escapeColumns(array $output) { return array_map(function ($row) { if ($this->escapeColumns == '*') { $row = $this->escapeRow($row); } elseif (is_array($this->escapeColumns)) { $columns = array_diff($this->escapeColumns, $this->rawColumns); foreach ($columns as $key) { array_set($row, $key, e(array_get($row, $key))); } } return $row; }, $output); }
[ "protected", "function", "escapeColumns", "(", "array", "$", "output", ")", "{", "return", "array_map", "(", "function", "(", "$", "row", ")", "{", "if", "(", "$", "this", "->", "escapeColumns", "==", "'*'", ")", "{", "$", "row", "=", "$", "this", "->", "escapeRow", "(", "$", "row", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "this", "->", "escapeColumns", ")", ")", "{", "$", "columns", "=", "array_diff", "(", "$", "this", "->", "escapeColumns", ",", "$", "this", "->", "rawColumns", ")", ";", "foreach", "(", "$", "columns", "as", "$", "key", ")", "{", "array_set", "(", "$", "row", ",", "$", "key", ",", "e", "(", "array_get", "(", "$", "row", ",", "$", "key", ")", ")", ")", ";", "}", "}", "return", "$", "row", ";", "}", ",", "$", "output", ")", ";", "}" ]
Escape column values as declared. @param array $output @return array
[ "Escape", "column", "values", "as", "declared", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L227-L241
train
yajra/laravel-datatables
src/Processors/DataProcessor.php
DataProcessor.escapeRow
protected function escapeRow(array $row) { $arrayDot = array_filter(array_dot($row)); foreach ($arrayDot as $key => $value) { if (! in_array($key, $this->rawColumns)) { $arrayDot[$key] = e($value); } } foreach ($arrayDot as $key => $value) { array_set($row, $key, $value); } return $row; }
php
protected function escapeRow(array $row) { $arrayDot = array_filter(array_dot($row)); foreach ($arrayDot as $key => $value) { if (! in_array($key, $this->rawColumns)) { $arrayDot[$key] = e($value); } } foreach ($arrayDot as $key => $value) { array_set($row, $key, $value); } return $row; }
[ "protected", "function", "escapeRow", "(", "array", "$", "row", ")", "{", "$", "arrayDot", "=", "array_filter", "(", "array_dot", "(", "$", "row", ")", ")", ";", "foreach", "(", "$", "arrayDot", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "this", "->", "rawColumns", ")", ")", "{", "$", "arrayDot", "[", "$", "key", "]", "=", "e", "(", "$", "value", ")", ";", "}", "}", "foreach", "(", "$", "arrayDot", "as", "$", "key", "=>", "$", "value", ")", "{", "array_set", "(", "$", "row", ",", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "row", ";", "}" ]
Escape all values of row. @param array $row @return array
[ "Escape", "all", "values", "of", "row", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Processors/DataProcessor.php#L249-L263
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.includeInArray
public static function includeInArray($item, $array) { if (self::isItemOrderInvalid($item, $array)) { return array_merge($array, [$item['name'] => $item['content']]); } $count = 0; $last = $array; $first = []; foreach ($array as $key => $value) { if ($count == $item['order']) { return array_merge($first, [$item['name'] => $item['content']], $last); } unset($last[$key]); $first[$key] = $value; $count++; } }
php
public static function includeInArray($item, $array) { if (self::isItemOrderInvalid($item, $array)) { return array_merge($array, [$item['name'] => $item['content']]); } $count = 0; $last = $array; $first = []; foreach ($array as $key => $value) { if ($count == $item['order']) { return array_merge($first, [$item['name'] => $item['content']], $last); } unset($last[$key]); $first[$key] = $value; $count++; } }
[ "public", "static", "function", "includeInArray", "(", "$", "item", ",", "$", "array", ")", "{", "if", "(", "self", "::", "isItemOrderInvalid", "(", "$", "item", ",", "$", "array", ")", ")", "{", "return", "array_merge", "(", "$", "array", ",", "[", "$", "item", "[", "'name'", "]", "=>", "$", "item", "[", "'content'", "]", "]", ")", ";", "}", "$", "count", "=", "0", ";", "$", "last", "=", "$", "array", ";", "$", "first", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "count", "==", "$", "item", "[", "'order'", "]", ")", "{", "return", "array_merge", "(", "$", "first", ",", "[", "$", "item", "[", "'name'", "]", "=>", "$", "item", "[", "'content'", "]", "]", ",", "$", "last", ")", ";", "}", "unset", "(", "$", "last", "[", "$", "key", "]", ")", ";", "$", "first", "[", "$", "key", "]", "=", "$", "value", ";", "$", "count", "++", ";", "}", "}" ]
Places item of extra columns into results by care of their order. @param array $item @param array $array @return array
[ "Places", "item", "of", "extra", "columns", "into", "results", "by", "care", "of", "their", "order", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L18-L37
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.compileContent
public static function compileContent($content, array $data, $param) { if (is_string($content)) { return static::compileBlade($content, static::getMixedValue($data, $param)); } elseif (is_callable($content)) { return $content($param); } return $content; }
php
public static function compileContent($content, array $data, $param) { if (is_string($content)) { return static::compileBlade($content, static::getMixedValue($data, $param)); } elseif (is_callable($content)) { return $content($param); } return $content; }
[ "public", "static", "function", "compileContent", "(", "$", "content", ",", "array", "$", "data", ",", "$", "param", ")", "{", "if", "(", "is_string", "(", "$", "content", ")", ")", "{", "return", "static", "::", "compileBlade", "(", "$", "content", ",", "static", "::", "getMixedValue", "(", "$", "data", ",", "$", "param", ")", ")", ";", "}", "elseif", "(", "is_callable", "(", "$", "content", ")", ")", "{", "return", "$", "content", "(", "$", "param", ")", ";", "}", "return", "$", "content", ";", "}" ]
Determines if content is callable or blade string, processes and returns. @param mixed $content Pre-processed content @param array $data data to use with blade template @param mixed $param parameter to call with callable @return mixed
[ "Determines", "if", "content", "is", "callable", "or", "blade", "string", "processes", "and", "returns", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L59-L68
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.compileBlade
public static function compileBlade($str, $data = []) { if (view()->exists($str)) { return view($str, $data)->render(); } ob_start() && extract($data, EXTR_SKIP); eval('?>' . app('blade.compiler')->compileString($str)); $str = ob_get_contents(); ob_end_clean(); return $str; }
php
public static function compileBlade($str, $data = []) { if (view()->exists($str)) { return view($str, $data)->render(); } ob_start() && extract($data, EXTR_SKIP); eval('?>' . app('blade.compiler')->compileString($str)); $str = ob_get_contents(); ob_end_clean(); return $str; }
[ "public", "static", "function", "compileBlade", "(", "$", "str", ",", "$", "data", "=", "[", "]", ")", "{", "if", "(", "view", "(", ")", "->", "exists", "(", "$", "str", ")", ")", "{", "return", "view", "(", "$", "str", ",", "$", "data", ")", "->", "render", "(", ")", ";", "}", "ob_start", "(", ")", "&&", "extract", "(", "$", "data", ",", "EXTR_SKIP", ")", ";", "eval", "(", "'?>'", ".", "app", "(", "'blade.compiler'", ")", "->", "compileString", "(", "$", "str", ")", ")", ";", "$", "str", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "return", "$", "str", ";", "}" ]
Parses and compiles strings by using Blade Template System. @param string $str @param array $data @return mixed @throws \Exception
[ "Parses", "and", "compiles", "strings", "by", "using", "Blade", "Template", "System", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L78-L90
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.getMixedValue
public static function getMixedValue(array $data, $param) { $casted = self::castToArray($param); $data['model'] = $param; foreach ($data as $key => $value) { if (isset($casted[$key])) { $data[$key] = $casted[$key]; } } return $data; }
php
public static function getMixedValue(array $data, $param) { $casted = self::castToArray($param); $data['model'] = $param; foreach ($data as $key => $value) { if (isset($casted[$key])) { $data[$key] = $casted[$key]; } } return $data; }
[ "public", "static", "function", "getMixedValue", "(", "array", "$", "data", ",", "$", "param", ")", "{", "$", "casted", "=", "self", "::", "castToArray", "(", "$", "param", ")", ";", "$", "data", "[", "'model'", "]", "=", "$", "param", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "isset", "(", "$", "casted", "[", "$", "key", "]", ")", ")", "{", "$", "data", "[", "$", "key", "]", "=", "$", "casted", "[", "$", "key", "]", ";", "}", "}", "return", "$", "data", ";", "}" ]
Get a mixed value of custom data and the parameters. @param array $data @param mixed $param @return array
[ "Get", "a", "mixed", "value", "of", "custom", "data", "and", "the", "parameters", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L99-L112
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.castToArray
public static function castToArray($param) { if ($param instanceof \stdClass) { $param = (array) $param; return $param; } if ($param instanceof Arrayable) { return $param->toArray(); } return $param; }
php
public static function castToArray($param) { if ($param instanceof \stdClass) { $param = (array) $param; return $param; } if ($param instanceof Arrayable) { return $param->toArray(); } return $param; }
[ "public", "static", "function", "castToArray", "(", "$", "param", ")", "{", "if", "(", "$", "param", "instanceof", "\\", "stdClass", ")", "{", "$", "param", "=", "(", "array", ")", "$", "param", ";", "return", "$", "param", ";", "}", "if", "(", "$", "param", "instanceof", "Arrayable", ")", "{", "return", "$", "param", "->", "toArray", "(", ")", ";", "}", "return", "$", "param", ";", "}" ]
Cast the parameter into an array. @param mixed $param @return array
[ "Cast", "the", "parameter", "into", "an", "array", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L120-L133
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.getOrMethod
public static function getOrMethod($method) { if (! Str::contains(Str::lower($method), 'or')) { return 'or' . ucfirst($method); } return $method; }
php
public static function getOrMethod($method) { if (! Str::contains(Str::lower($method), 'or')) { return 'or' . ucfirst($method); } return $method; }
[ "public", "static", "function", "getOrMethod", "(", "$", "method", ")", "{", "if", "(", "!", "Str", "::", "contains", "(", "Str", "::", "lower", "(", "$", "method", ")", ",", "'or'", ")", ")", "{", "return", "'or'", ".", "ucfirst", "(", "$", "method", ")", ";", "}", "return", "$", "method", ";", "}" ]
Get equivalent or method of query builder. @param string $method @return string
[ "Get", "equivalent", "or", "method", "of", "query", "builder", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L141-L148
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.convertToArray
public static function convertToArray($row) { $data = $row instanceof Arrayable ? $row->toArray() : (array) $row; foreach ($data as &$value) { if (is_object($value) || is_array($value)) { $value = self::convertToArray($value); } unset($value); } return $data; }
php
public static function convertToArray($row) { $data = $row instanceof Arrayable ? $row->toArray() : (array) $row; foreach ($data as &$value) { if (is_object($value) || is_array($value)) { $value = self::convertToArray($value); } unset($value); } return $data; }
[ "public", "static", "function", "convertToArray", "(", "$", "row", ")", "{", "$", "data", "=", "$", "row", "instanceof", "Arrayable", "?", "$", "row", "->", "toArray", "(", ")", ":", "(", "array", ")", "$", "row", ";", "foreach", "(", "$", "data", "as", "&", "$", "value", ")", "{", "if", "(", "is_object", "(", "$", "value", ")", "||", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "self", "::", "convertToArray", "(", "$", "value", ")", ";", "}", "unset", "(", "$", "value", ")", ";", "}", "return", "$", "data", ";", "}" ]
Converts array object values to associative array. @param mixed $row @return array
[ "Converts", "array", "object", "values", "to", "associative", "array", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L156-L169
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.transformRow
protected static function transformRow($row) { foreach ($row as $key => $value) { if ($value instanceof DateTime) { $row[$key] = $value->format('Y-m-d H:i:s'); } else { if (is_object($value)) { $row[$key] = (string) $value; } else { $row[$key] = $value; } } } return $row; }
php
protected static function transformRow($row) { foreach ($row as $key => $value) { if ($value instanceof DateTime) { $row[$key] = $value->format('Y-m-d H:i:s'); } else { if (is_object($value)) { $row[$key] = (string) $value; } else { $row[$key] = $value; } } } return $row; }
[ "protected", "static", "function", "transformRow", "(", "$", "row", ")", "{", "foreach", "(", "$", "row", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "DateTime", ")", "{", "$", "row", "[", "$", "key", "]", "=", "$", "value", "->", "format", "(", "'Y-m-d H:i:s'", ")", ";", "}", "else", "{", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "$", "row", "[", "$", "key", "]", "=", "(", "string", ")", "$", "value", ";", "}", "else", "{", "$", "row", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "row", ";", "}" ]
Transform row data into an array. @param mixed $row @return array
[ "Transform", "row", "data", "into", "an", "array", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L188-L203
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.replacePatternWithKeyword
public static function replacePatternWithKeyword(array $subject, $keyword, $pattern = '$1') { $parameters = []; foreach ($subject as $param) { if (is_array($param)) { $parameters[] = self::replacePatternWithKeyword($param, $keyword, $pattern); } else { $parameters[] = str_replace($pattern, $keyword, $param); } } return $parameters; }
php
public static function replacePatternWithKeyword(array $subject, $keyword, $pattern = '$1') { $parameters = []; foreach ($subject as $param) { if (is_array($param)) { $parameters[] = self::replacePatternWithKeyword($param, $keyword, $pattern); } else { $parameters[] = str_replace($pattern, $keyword, $param); } } return $parameters; }
[ "public", "static", "function", "replacePatternWithKeyword", "(", "array", "$", "subject", ",", "$", "keyword", ",", "$", "pattern", "=", "'$1'", ")", "{", "$", "parameters", "=", "[", "]", ";", "foreach", "(", "$", "subject", "as", "$", "param", ")", "{", "if", "(", "is_array", "(", "$", "param", ")", ")", "{", "$", "parameters", "[", "]", "=", "self", "::", "replacePatternWithKeyword", "(", "$", "param", ",", "$", "keyword", ",", "$", "pattern", ")", ";", "}", "else", "{", "$", "parameters", "[", "]", "=", "str_replace", "(", "$", "pattern", ",", "$", "keyword", ",", "$", "param", ")", ";", "}", "}", "return", "$", "parameters", ";", "}" ]
Replace all pattern occurrences with keyword. @param array $subject @param string $keyword @param string $pattern @return array
[ "Replace", "all", "pattern", "occurrences", "with", "keyword", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L237-L249
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.extractColumnName
public static function extractColumnName($str, $wantsAlias) { $matches = explode(' as ', Str::lower($str)); if (! empty($matches)) { if ($wantsAlias) { return array_pop($matches); } return array_shift($matches); } elseif (strpos($str, '.')) { $array = explode('.', $str); return array_pop($array); } return $str; }
php
public static function extractColumnName($str, $wantsAlias) { $matches = explode(' as ', Str::lower($str)); if (! empty($matches)) { if ($wantsAlias) { return array_pop($matches); } return array_shift($matches); } elseif (strpos($str, '.')) { $array = explode('.', $str); return array_pop($array); } return $str; }
[ "public", "static", "function", "extractColumnName", "(", "$", "str", ",", "$", "wantsAlias", ")", "{", "$", "matches", "=", "explode", "(", "' as '", ",", "Str", "::", "lower", "(", "$", "str", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "matches", ")", ")", "{", "if", "(", "$", "wantsAlias", ")", "{", "return", "array_pop", "(", "$", "matches", ")", ";", "}", "return", "array_shift", "(", "$", "matches", ")", ";", "}", "elseif", "(", "strpos", "(", "$", "str", ",", "'.'", ")", ")", "{", "$", "array", "=", "explode", "(", "'.'", ",", "$", "str", ")", ";", "return", "array_pop", "(", "$", "array", ")", ";", "}", "return", "$", "str", ";", "}" ]
Get column name from string. @param string $str @param bool $wantsAlias @return string
[ "Get", "column", "name", "from", "string", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L258-L275
train
yajra/laravel-datatables
src/Utilities/Helper.php
Helper.wildcardString
public static function wildcardString($str, $wildcard, $lowercase = true) { $wild = $wildcard; $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY); if (count($chars) > 0) { foreach ($chars as $char) { $wild .= $char . $wildcard; } } if ($lowercase) { $wild = Str::lower($wild); } return $wild; }
php
public static function wildcardString($str, $wildcard, $lowercase = true) { $wild = $wildcard; $chars = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY); if (count($chars) > 0) { foreach ($chars as $char) { $wild .= $char . $wildcard; } } if ($lowercase) { $wild = Str::lower($wild); } return $wild; }
[ "public", "static", "function", "wildcardString", "(", "$", "str", ",", "$", "wildcard", ",", "$", "lowercase", "=", "true", ")", "{", "$", "wild", "=", "$", "wildcard", ";", "$", "chars", "=", "preg_split", "(", "'//u'", ",", "$", "str", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "if", "(", "count", "(", "$", "chars", ")", ">", "0", ")", "{", "foreach", "(", "$", "chars", "as", "$", "char", ")", "{", "$", "wild", ".=", "$", "char", ".", "$", "wildcard", ";", "}", "}", "if", "(", "$", "lowercase", ")", "{", "$", "wild", "=", "Str", "::", "lower", "(", "$", "wild", ")", ";", "}", "return", "$", "wild", ";", "}" ]
Adds wildcards to the given string. @param string $str @param string $wildcard @param bool $lowercase @return string
[ "Adds", "wildcards", "to", "the", "given", "string", "." ]
1fc2ca80b867441a6717b15684f78a3670427c94
https://github.com/yajra/laravel-datatables/blob/1fc2ca80b867441a6717b15684f78a3670427c94/src/Utilities/Helper.php#L297-L313
train
spatie/laravel-medialibrary
src/MediaRepository.php
MediaRepository.getCollection
public function getCollection(HasMedia $model, string $collectionName, $filter = []): Collection { return $this->applyFilterToMediaCollection($model->loadMedia($collectionName), $filter); }
php
public function getCollection(HasMedia $model, string $collectionName, $filter = []): Collection { return $this->applyFilterToMediaCollection($model->loadMedia($collectionName), $filter); }
[ "public", "function", "getCollection", "(", "HasMedia", "$", "model", ",", "string", "$", "collectionName", ",", "$", "filter", "=", "[", "]", ")", ":", "Collection", "{", "return", "$", "this", "->", "applyFilterToMediaCollection", "(", "$", "model", "->", "loadMedia", "(", "$", "collectionName", ")", ",", "$", "filter", ")", ";", "}" ]
Get all media in the collection. @param \Spatie\MediaLibrary\HasMedia\HasMedia $model @param string $collectionName @param array|callable $filter @return \Illuminate\Support\Collection
[ "Get", "all", "media", "in", "the", "collection", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/MediaRepository.php#L32-L35
train
spatie/laravel-medialibrary
src/MediaRepository.php
MediaRepository.applyFilterToMediaCollection
protected function applyFilterToMediaCollection(Collection $media, $filter): Collection { if (is_array($filter)) { $filter = $this->getDefaultFilterFunction($filter); } return $media->filter($filter); }
php
protected function applyFilterToMediaCollection(Collection $media, $filter): Collection { if (is_array($filter)) { $filter = $this->getDefaultFilterFunction($filter); } return $media->filter($filter); }
[ "protected", "function", "applyFilterToMediaCollection", "(", "Collection", "$", "media", ",", "$", "filter", ")", ":", "Collection", "{", "if", "(", "is_array", "(", "$", "filter", ")", ")", "{", "$", "filter", "=", "$", "this", "->", "getDefaultFilterFunction", "(", "$", "filter", ")", ";", "}", "return", "$", "media", "->", "filter", "(", "$", "filter", ")", ";", "}" ]
Apply given filters on media. @param \Illuminate\Support\Collection $media @param array|callable $filter @return \Illuminate\Support\Collection
[ "Apply", "given", "filters", "on", "media", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/MediaRepository.php#L45-L52
train
spatie/laravel-medialibrary
src/MediaRepository.php
MediaRepository.getDefaultFilterFunction
protected function getDefaultFilterFunction(array $filters): Closure { return function (Media $media) use ($filters) { foreach ($filters as $property => $value) { if (! Arr::has($media->custom_properties, $property)) { return false; } if (Arr::get($media->custom_properties, $property) !== $value) { return false; } } return true; }; }
php
protected function getDefaultFilterFunction(array $filters): Closure { return function (Media $media) use ($filters) { foreach ($filters as $property => $value) { if (! Arr::has($media->custom_properties, $property)) { return false; } if (Arr::get($media->custom_properties, $property) !== $value) { return false; } } return true; }; }
[ "protected", "function", "getDefaultFilterFunction", "(", "array", "$", "filters", ")", ":", "Closure", "{", "return", "function", "(", "Media", "$", "media", ")", "use", "(", "$", "filters", ")", "{", "foreach", "(", "$", "filters", "as", "$", "property", "=>", "$", "value", ")", "{", "if", "(", "!", "Arr", "::", "has", "(", "$", "media", "->", "custom_properties", ",", "$", "property", ")", ")", "{", "return", "false", ";", "}", "if", "(", "Arr", "::", "get", "(", "$", "media", "->", "custom_properties", ",", "$", "property", ")", "!==", "$", "value", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", ";", "}" ]
Convert the given array to a filter function. @param $filters @return \Closure
[ "Convert", "the", "given", "array", "to", "a", "filter", "function", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/MediaRepository.php#L91-L106
train
spatie/laravel-medialibrary
src/Conversion/Conversion.php
Conversion.setManipulations
public function setManipulations($manipulations) : self { if ($manipulations instanceof Manipulations) { $this->manipulations = $this->manipulations->mergeManipulations($manipulations); } if (is_callable($manipulations)) { $manipulations($this->manipulations); } return $this; }
php
public function setManipulations($manipulations) : self { if ($manipulations instanceof Manipulations) { $this->manipulations = $this->manipulations->mergeManipulations($manipulations); } if (is_callable($manipulations)) { $manipulations($this->manipulations); } return $this; }
[ "public", "function", "setManipulations", "(", "$", "manipulations", ")", ":", "self", "{", "if", "(", "$", "manipulations", "instanceof", "Manipulations", ")", "{", "$", "this", "->", "manipulations", "=", "$", "this", "->", "manipulations", "->", "mergeManipulations", "(", "$", "manipulations", ")", ";", "}", "if", "(", "is_callable", "(", "$", "manipulations", ")", ")", "{", "$", "manipulations", "(", "$", "this", "->", "manipulations", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set the manipulations for this conversion. @param \Spatie\Image\Manipulations|closure $manipulations @return $this
[ "Set", "the", "manipulations", "for", "this", "conversion", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/Conversion/Conversion.php#L116-L127
train
spatie/laravel-medialibrary
src/Conversion/Conversion.php
Conversion.addAsFirstManipulations
public function addAsFirstManipulations(Manipulations $manipulations) : self { $manipulationSequence = $manipulations->getManipulationSequence()->toArray(); $this->manipulations ->getManipulationSequence() ->mergeArray($manipulationSequence); return $this; }
php
public function addAsFirstManipulations(Manipulations $manipulations) : self { $manipulationSequence = $manipulations->getManipulationSequence()->toArray(); $this->manipulations ->getManipulationSequence() ->mergeArray($manipulationSequence); return $this; }
[ "public", "function", "addAsFirstManipulations", "(", "Manipulations", "$", "manipulations", ")", ":", "self", "{", "$", "manipulationSequence", "=", "$", "manipulations", "->", "getManipulationSequence", "(", ")", "->", "toArray", "(", ")", ";", "$", "this", "->", "manipulations", "->", "getManipulationSequence", "(", ")", "->", "mergeArray", "(", "$", "manipulationSequence", ")", ";", "return", "$", "this", ";", "}" ]
Add the given manipulations as the first ones. @param \Spatie\Image\Manipulations $manipulations @return $this
[ "Add", "the", "given", "manipulations", "as", "the", "first", "ones", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/Conversion/Conversion.php#L136-L145
train
spatie/laravel-medialibrary
src/FileManipulator.php
FileManipulator.createDerivedFiles
public function createDerivedFiles(Media $media, array $only = [], $onlyIfMissing = false) { $profileCollection = ConversionCollection::createForMedia($media); if (! empty($only)) { $profileCollection = $profileCollection->filter(function ($collection) use ($only) { return in_array($collection->getName(), $only); }); } $this->performConversions( $profileCollection->getNonQueuedConversions($media->collection_name), $media, $onlyIfMissing ); $queuedConversions = $profileCollection->getQueuedConversions($media->collection_name); if ($queuedConversions->isNotEmpty()) { $this->dispatchQueuedConversions($media, $queuedConversions); } }
php
public function createDerivedFiles(Media $media, array $only = [], $onlyIfMissing = false) { $profileCollection = ConversionCollection::createForMedia($media); if (! empty($only)) { $profileCollection = $profileCollection->filter(function ($collection) use ($only) { return in_array($collection->getName(), $only); }); } $this->performConversions( $profileCollection->getNonQueuedConversions($media->collection_name), $media, $onlyIfMissing ); $queuedConversions = $profileCollection->getQueuedConversions($media->collection_name); if ($queuedConversions->isNotEmpty()) { $this->dispatchQueuedConversions($media, $queuedConversions); } }
[ "public", "function", "createDerivedFiles", "(", "Media", "$", "media", ",", "array", "$", "only", "=", "[", "]", ",", "$", "onlyIfMissing", "=", "false", ")", "{", "$", "profileCollection", "=", "ConversionCollection", "::", "createForMedia", "(", "$", "media", ")", ";", "if", "(", "!", "empty", "(", "$", "only", ")", ")", "{", "$", "profileCollection", "=", "$", "profileCollection", "->", "filter", "(", "function", "(", "$", "collection", ")", "use", "(", "$", "only", ")", "{", "return", "in_array", "(", "$", "collection", "->", "getName", "(", ")", ",", "$", "only", ")", ";", "}", ")", ";", "}", "$", "this", "->", "performConversions", "(", "$", "profileCollection", "->", "getNonQueuedConversions", "(", "$", "media", "->", "collection_name", ")", ",", "$", "media", ",", "$", "onlyIfMissing", ")", ";", "$", "queuedConversions", "=", "$", "profileCollection", "->", "getQueuedConversions", "(", "$", "media", "->", "collection_name", ")", ";", "if", "(", "$", "queuedConversions", "->", "isNotEmpty", "(", ")", ")", "{", "$", "this", "->", "dispatchQueuedConversions", "(", "$", "media", ",", "$", "queuedConversions", ")", ";", "}", "}" ]
Create all derived files for the given media. @param \Spatie\MediaLibrary\Models\Media $media @param array $only @param bool $onlyIfMissing
[ "Create", "all", "derived", "files", "for", "the", "given", "media", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/FileManipulator.php#L30-L51
train
spatie/laravel-medialibrary
src/FileManipulator.php
FileManipulator.performConversions
public function performConversions(ConversionCollection $conversions, Media $media, $onlyIfMissing = false) { if ($conversions->isEmpty()) { return; } $imageGenerator = $this->determineImageGenerator($media); if (! $imageGenerator) { return; } $temporaryDirectory = TemporaryDirectory::create(); $copiedOriginalFile = app(Filesystem::class)->copyFromMediaLibrary( $media, $temporaryDirectory->path(str_random(16).'.'.$media->extension) ); $conversions ->reject(function (Conversion $conversion) use ($onlyIfMissing, $media) { $relativePath = $media->getPath($conversion->getName()); $rootPath = config('filesystems.disks.'.$media->disk.'.root'); if ($rootPath) { $relativePath = str_replace($rootPath, '', $relativePath); } return $onlyIfMissing && Storage::disk($media->disk)->exists($relativePath); }) ->each(function (Conversion $conversion) use ($media, $imageGenerator, $copiedOriginalFile) { event(new ConversionWillStart($media, $conversion, $copiedOriginalFile)); $copiedOriginalFile = $imageGenerator->convert($copiedOriginalFile, $conversion); $manipulationResult = $this->performManipulations($media, $conversion, $copiedOriginalFile); $newFileName = pathinfo($media->file_name, PATHINFO_FILENAME). '-'.$conversion->getName(). '.'.$conversion->getResultExtension(pathinfo($copiedOriginalFile, PATHINFO_EXTENSION)); $renamedFile = MediaLibraryFileHelper::renameInDirectory($manipulationResult, $newFileName); if ($conversion->shouldGenerateResponsiveImages()) { app(ResponsiveImageGenerator::class)->generateResponsiveImagesForConversion( $media, $conversion, $renamedFile ); } app(Filesystem::class)->copyToMediaLibrary($renamedFile, $media, 'conversions'); $media->markAsConversionGenerated($conversion->getName(), true); event(new ConversionHasBeenCompleted($media, $conversion)); }); $temporaryDirectory->delete(); }
php
public function performConversions(ConversionCollection $conversions, Media $media, $onlyIfMissing = false) { if ($conversions->isEmpty()) { return; } $imageGenerator = $this->determineImageGenerator($media); if (! $imageGenerator) { return; } $temporaryDirectory = TemporaryDirectory::create(); $copiedOriginalFile = app(Filesystem::class)->copyFromMediaLibrary( $media, $temporaryDirectory->path(str_random(16).'.'.$media->extension) ); $conversions ->reject(function (Conversion $conversion) use ($onlyIfMissing, $media) { $relativePath = $media->getPath($conversion->getName()); $rootPath = config('filesystems.disks.'.$media->disk.'.root'); if ($rootPath) { $relativePath = str_replace($rootPath, '', $relativePath); } return $onlyIfMissing && Storage::disk($media->disk)->exists($relativePath); }) ->each(function (Conversion $conversion) use ($media, $imageGenerator, $copiedOriginalFile) { event(new ConversionWillStart($media, $conversion, $copiedOriginalFile)); $copiedOriginalFile = $imageGenerator->convert($copiedOriginalFile, $conversion); $manipulationResult = $this->performManipulations($media, $conversion, $copiedOriginalFile); $newFileName = pathinfo($media->file_name, PATHINFO_FILENAME). '-'.$conversion->getName(). '.'.$conversion->getResultExtension(pathinfo($copiedOriginalFile, PATHINFO_EXTENSION)); $renamedFile = MediaLibraryFileHelper::renameInDirectory($manipulationResult, $newFileName); if ($conversion->shouldGenerateResponsiveImages()) { app(ResponsiveImageGenerator::class)->generateResponsiveImagesForConversion( $media, $conversion, $renamedFile ); } app(Filesystem::class)->copyToMediaLibrary($renamedFile, $media, 'conversions'); $media->markAsConversionGenerated($conversion->getName(), true); event(new ConversionHasBeenCompleted($media, $conversion)); }); $temporaryDirectory->delete(); }
[ "public", "function", "performConversions", "(", "ConversionCollection", "$", "conversions", ",", "Media", "$", "media", ",", "$", "onlyIfMissing", "=", "false", ")", "{", "if", "(", "$", "conversions", "->", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "$", "imageGenerator", "=", "$", "this", "->", "determineImageGenerator", "(", "$", "media", ")", ";", "if", "(", "!", "$", "imageGenerator", ")", "{", "return", ";", "}", "$", "temporaryDirectory", "=", "TemporaryDirectory", "::", "create", "(", ")", ";", "$", "copiedOriginalFile", "=", "app", "(", "Filesystem", "::", "class", ")", "->", "copyFromMediaLibrary", "(", "$", "media", ",", "$", "temporaryDirectory", "->", "path", "(", "str_random", "(", "16", ")", ".", "'.'", ".", "$", "media", "->", "extension", ")", ")", ";", "$", "conversions", "->", "reject", "(", "function", "(", "Conversion", "$", "conversion", ")", "use", "(", "$", "onlyIfMissing", ",", "$", "media", ")", "{", "$", "relativePath", "=", "$", "media", "->", "getPath", "(", "$", "conversion", "->", "getName", "(", ")", ")", ";", "$", "rootPath", "=", "config", "(", "'filesystems.disks.'", ".", "$", "media", "->", "disk", ".", "'.root'", ")", ";", "if", "(", "$", "rootPath", ")", "{", "$", "relativePath", "=", "str_replace", "(", "$", "rootPath", ",", "''", ",", "$", "relativePath", ")", ";", "}", "return", "$", "onlyIfMissing", "&&", "Storage", "::", "disk", "(", "$", "media", "->", "disk", ")", "->", "exists", "(", "$", "relativePath", ")", ";", "}", ")", "->", "each", "(", "function", "(", "Conversion", "$", "conversion", ")", "use", "(", "$", "media", ",", "$", "imageGenerator", ",", "$", "copiedOriginalFile", ")", "{", "event", "(", "new", "ConversionWillStart", "(", "$", "media", ",", "$", "conversion", ",", "$", "copiedOriginalFile", ")", ")", ";", "$", "copiedOriginalFile", "=", "$", "imageGenerator", "->", "convert", "(", "$", "copiedOriginalFile", ",", "$", "conversion", ")", ";", "$", "manipulationResult", "=", "$", "this", "->", "performManipulations", "(", "$", "media", ",", "$", "conversion", ",", "$", "copiedOriginalFile", ")", ";", "$", "newFileName", "=", "pathinfo", "(", "$", "media", "->", "file_name", ",", "PATHINFO_FILENAME", ")", ".", "'-'", ".", "$", "conversion", "->", "getName", "(", ")", ".", "'.'", ".", "$", "conversion", "->", "getResultExtension", "(", "pathinfo", "(", "$", "copiedOriginalFile", ",", "PATHINFO_EXTENSION", ")", ")", ";", "$", "renamedFile", "=", "MediaLibraryFileHelper", "::", "renameInDirectory", "(", "$", "manipulationResult", ",", "$", "newFileName", ")", ";", "if", "(", "$", "conversion", "->", "shouldGenerateResponsiveImages", "(", ")", ")", "{", "app", "(", "ResponsiveImageGenerator", "::", "class", ")", "->", "generateResponsiveImagesForConversion", "(", "$", "media", ",", "$", "conversion", ",", "$", "renamedFile", ")", ";", "}", "app", "(", "Filesystem", "::", "class", ")", "->", "copyToMediaLibrary", "(", "$", "renamedFile", ",", "$", "media", ",", "'conversions'", ")", ";", "$", "media", "->", "markAsConversionGenerated", "(", "$", "conversion", "->", "getName", "(", ")", ",", "true", ")", ";", "event", "(", "new", "ConversionHasBeenCompleted", "(", "$", "media", ",", "$", "conversion", ")", ")", ";", "}", ")", ";", "$", "temporaryDirectory", "->", "delete", "(", ")", ";", "}" ]
Perform the given conversions for the given media. @param \Spatie\MediaLibrary\Conversion\ConversionCollection $conversions @param \Spatie\MediaLibrary\Models\Media $media @param bool $onlyIfMissing
[ "Perform", "the", "given", "conversions", "for", "the", "given", "media", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/FileManipulator.php#L60-L120
train
spatie/laravel-medialibrary
src/UrlGenerator/LocalUrlGenerator.php
LocalUrlGenerator.getResponsiveImagesDirectoryUrl
public function getResponsiveImagesDirectoryUrl(): string { return url($this->getBaseMediaDirectoryUrl().'/'.$this->pathGenerator->getPathForResponsiveImages($this->media)).'/'; }
php
public function getResponsiveImagesDirectoryUrl(): string { return url($this->getBaseMediaDirectoryUrl().'/'.$this->pathGenerator->getPathForResponsiveImages($this->media)).'/'; }
[ "public", "function", "getResponsiveImagesDirectoryUrl", "(", ")", ":", "string", "{", "return", "url", "(", "$", "this", "->", "getBaseMediaDirectoryUrl", "(", ")", ".", "'/'", ".", "$", "this", "->", "pathGenerator", "->", "getPathForResponsiveImages", "(", "$", "this", "->", "media", ")", ")", ".", "'/'", ";", "}" ]
Get the url to the directory containing responsive images. @return string
[ "Get", "the", "url", "to", "the", "directory", "containing", "responsive", "images", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/UrlGenerator/LocalUrlGenerator.php#L94-L97
train
spatie/laravel-medialibrary
src/Conversion/ConversionCollection.php
ConversionCollection.getByName
public function getByName(string $name): Conversion { $conversion = $this->first(function (Conversion $conversion) use ($name) { return $conversion->getName() === $name; }); if (! $conversion) { throw InvalidConversion::unknownName($name); } return $conversion; }
php
public function getByName(string $name): Conversion { $conversion = $this->first(function (Conversion $conversion) use ($name) { return $conversion->getName() === $name; }); if (! $conversion) { throw InvalidConversion::unknownName($name); } return $conversion; }
[ "public", "function", "getByName", "(", "string", "$", "name", ")", ":", "Conversion", "{", "$", "conversion", "=", "$", "this", "->", "first", "(", "function", "(", "Conversion", "$", "conversion", ")", "use", "(", "$", "name", ")", "{", "return", "$", "conversion", "->", "getName", "(", ")", "===", "$", "name", ";", "}", ")", ";", "if", "(", "!", "$", "conversion", ")", "{", "throw", "InvalidConversion", "::", "unknownName", "(", "$", "name", ")", ";", "}", "return", "$", "conversion", ";", "}" ]
Get a conversion by it's name. @param string $name @return mixed @throws \Spatie\MediaLibrary\Exceptions\InvalidConversion
[ "Get", "a", "conversion", "by", "it", "s", "name", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/Conversion/ConversionCollection.php#L54-L65
train
spatie/laravel-medialibrary
src/Conversion/ConversionCollection.php
ConversionCollection.addConversionsFromRelatedModel
protected function addConversionsFromRelatedModel(Media $media) { $modelName = Arr::get(Relation::morphMap(), $media->model_type, $media->model_type); /** @var \Spatie\MediaLibrary\HasMedia\HasMedia $model */ $model = new $modelName(); /* * In some cases the user might want to get the actual model * instance so conversion parameters can depend on model * properties. This will causes extra queries. */ if ($model->registerMediaConversionsUsingModelInstance) { $model = $media->model; $model->mediaConversion = []; } $model->registerAllMediaConversions($media); $this->items = $model->mediaConversions; }
php
protected function addConversionsFromRelatedModel(Media $media) { $modelName = Arr::get(Relation::morphMap(), $media->model_type, $media->model_type); /** @var \Spatie\MediaLibrary\HasMedia\HasMedia $model */ $model = new $modelName(); /* * In some cases the user might want to get the actual model * instance so conversion parameters can depend on model * properties. This will causes extra queries. */ if ($model->registerMediaConversionsUsingModelInstance) { $model = $media->model; $model->mediaConversion = []; } $model->registerAllMediaConversions($media); $this->items = $model->mediaConversions; }
[ "protected", "function", "addConversionsFromRelatedModel", "(", "Media", "$", "media", ")", "{", "$", "modelName", "=", "Arr", "::", "get", "(", "Relation", "::", "morphMap", "(", ")", ",", "$", "media", "->", "model_type", ",", "$", "media", "->", "model_type", ")", ";", "/** @var \\Spatie\\MediaLibrary\\HasMedia\\HasMedia $model */", "$", "model", "=", "new", "$", "modelName", "(", ")", ";", "/*\n * In some cases the user might want to get the actual model\n * instance so conversion parameters can depend on model\n * properties. This will causes extra queries.\n */", "if", "(", "$", "model", "->", "registerMediaConversionsUsingModelInstance", ")", "{", "$", "model", "=", "$", "media", "->", "model", ";", "$", "model", "->", "mediaConversion", "=", "[", "]", ";", "}", "$", "model", "->", "registerAllMediaConversions", "(", "$", "media", ")", ";", "$", "this", "->", "items", "=", "$", "model", "->", "mediaConversions", ";", "}" ]
Add the conversion that are defined on the related model of the given media. @param \Spatie\MediaLibrary\Models\Media $media
[ "Add", "the", "conversion", "that", "are", "defined", "on", "the", "related", "model", "of", "the", "given", "media", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/Conversion/ConversionCollection.php#L73-L94
train
spatie/laravel-medialibrary
src/Conversion/ConversionCollection.php
ConversionCollection.addManipulationsFromDb
protected function addManipulationsFromDb(Media $media) { collect($media->manipulations)->each(function ($manipulations, $conversionName) { $this->addManipulationToConversion(new Manipulations([$manipulations]), $conversionName); }); }
php
protected function addManipulationsFromDb(Media $media) { collect($media->manipulations)->each(function ($manipulations, $conversionName) { $this->addManipulationToConversion(new Manipulations([$manipulations]), $conversionName); }); }
[ "protected", "function", "addManipulationsFromDb", "(", "Media", "$", "media", ")", "{", "collect", "(", "$", "media", "->", "manipulations", ")", "->", "each", "(", "function", "(", "$", "manipulations", ",", "$", "conversionName", ")", "{", "$", "this", "->", "addManipulationToConversion", "(", "new", "Manipulations", "(", "[", "$", "manipulations", "]", ")", ",", "$", "conversionName", ")", ";", "}", ")", ";", "}" ]
Add the extra manipulations that are defined on the given media. @param \Spatie\MediaLibrary\Models\Media $media
[ "Add", "the", "extra", "manipulations", "that", "are", "defined", "on", "the", "given", "media", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/Conversion/ConversionCollection.php#L101-L106
train
spatie/laravel-medialibrary
src/UrlGenerator/S3UrlGenerator.php
S3UrlGenerator.getTemporaryUrl
public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string { return $this ->filesystemManager ->disk($this->media->disk) ->temporaryUrl($this->getPath(), $expiration, $options); }
php
public function getTemporaryUrl(DateTimeInterface $expiration, array $options = []): string { return $this ->filesystemManager ->disk($this->media->disk) ->temporaryUrl($this->getPath(), $expiration, $options); }
[ "public", "function", "getTemporaryUrl", "(", "DateTimeInterface", "$", "expiration", ",", "array", "$", "options", "=", "[", "]", ")", ":", "string", "{", "return", "$", "this", "->", "filesystemManager", "->", "disk", "(", "$", "this", "->", "media", "->", "disk", ")", "->", "temporaryUrl", "(", "$", "this", "->", "getPath", "(", ")", ",", "$", "expiration", ",", "$", "options", ")", ";", "}" ]
Get the temporary url for a media item. @param \DateTimeInterface $expiration @param array $options @return string
[ "Get", "the", "temporary", "url", "for", "a", "media", "item", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/UrlGenerator/S3UrlGenerator.php#L47-L53
train
spatie/laravel-medialibrary
src/HasMedia/HasMediaTrait.php
HasMediaTrait.addMediaFromUrl
public function addMediaFromUrl(string $url, ...$allowedMimeTypes) { if (! $stream = @fopen($url, 'r')) { throw UnreachableUrl::create($url); } $temporaryFile = tempnam(sys_get_temp_dir(), 'media-library'); file_put_contents($temporaryFile, $stream); $this->guardAgainstInvalidMimeType($temporaryFile, $allowedMimeTypes); $filename = basename(parse_url($url, PHP_URL_PATH)); $filename = str_replace('%20', ' ', $filename); if ($filename === '') { $filename = 'file'; } $mediaExtension = explode('/', mime_content_type($temporaryFile)); if (! str_contains($filename, '.')) { $filename = "{$filename}.{$mediaExtension[1]}"; } return app(FileAdderFactory::class) ->create($this, $temporaryFile) ->usingName(pathinfo($filename, PATHINFO_FILENAME)) ->usingFileName($filename); }
php
public function addMediaFromUrl(string $url, ...$allowedMimeTypes) { if (! $stream = @fopen($url, 'r')) { throw UnreachableUrl::create($url); } $temporaryFile = tempnam(sys_get_temp_dir(), 'media-library'); file_put_contents($temporaryFile, $stream); $this->guardAgainstInvalidMimeType($temporaryFile, $allowedMimeTypes); $filename = basename(parse_url($url, PHP_URL_PATH)); $filename = str_replace('%20', ' ', $filename); if ($filename === '') { $filename = 'file'; } $mediaExtension = explode('/', mime_content_type($temporaryFile)); if (! str_contains($filename, '.')) { $filename = "{$filename}.{$mediaExtension[1]}"; } return app(FileAdderFactory::class) ->create($this, $temporaryFile) ->usingName(pathinfo($filename, PATHINFO_FILENAME)) ->usingFileName($filename); }
[ "public", "function", "addMediaFromUrl", "(", "string", "$", "url", ",", "...", "$", "allowedMimeTypes", ")", "{", "if", "(", "!", "$", "stream", "=", "@", "fopen", "(", "$", "url", ",", "'r'", ")", ")", "{", "throw", "UnreachableUrl", "::", "create", "(", "$", "url", ")", ";", "}", "$", "temporaryFile", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "'media-library'", ")", ";", "file_put_contents", "(", "$", "temporaryFile", ",", "$", "stream", ")", ";", "$", "this", "->", "guardAgainstInvalidMimeType", "(", "$", "temporaryFile", ",", "$", "allowedMimeTypes", ")", ";", "$", "filename", "=", "basename", "(", "parse_url", "(", "$", "url", ",", "PHP_URL_PATH", ")", ")", ";", "$", "filename", "=", "str_replace", "(", "'%20'", ",", "' '", ",", "$", "filename", ")", ";", "if", "(", "$", "filename", "===", "''", ")", "{", "$", "filename", "=", "'file'", ";", "}", "$", "mediaExtension", "=", "explode", "(", "'/'", ",", "mime_content_type", "(", "$", "temporaryFile", ")", ")", ";", "if", "(", "!", "str_contains", "(", "$", "filename", ",", "'.'", ")", ")", "{", "$", "filename", "=", "\"{$filename}.{$mediaExtension[1]}\"", ";", "}", "return", "app", "(", "FileAdderFactory", "::", "class", ")", "->", "create", "(", "$", "this", ",", "$", "temporaryFile", ")", "->", "usingName", "(", "pathinfo", "(", "$", "filename", ",", "PATHINFO_FILENAME", ")", ")", "->", "usingFileName", "(", "$", "filename", ")", ";", "}" ]
Add a remote file to the medialibrary. @param string $url @param string|array ...$allowedMimeTypes @return \Spatie\MediaLibrary\FileAdder\FileAdder @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded
[ "Add", "a", "remote", "file", "to", "the", "medialibrary", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/HasMedia/HasMediaTrait.php#L120-L148
train
spatie/laravel-medialibrary
src/HasMedia/HasMediaTrait.php
HasMediaTrait.addMediaFromBase64
public function addMediaFromBase64(string $base64data, ...$allowedMimeTypes): FileAdder { // strip out data uri scheme information (see RFC 2397) if (strpos($base64data, ';base64') !== false) { [$_, $base64data] = explode(';', $base64data); [$_, $base64data] = explode(',', $base64data); } // strict mode filters for non-base64 alphabet characters if (base64_decode($base64data, true) === false) { throw InvalidBase64Data::create(); } // decoding and then reencoding should not change the data if (base64_encode(base64_decode($base64data)) !== $base64data) { throw InvalidBase64Data::create(); } $binaryData = base64_decode($base64data); // temporarily store the decoded data on the filesystem to be able to pass it to the fileAdder $tmpFile = tempnam(sys_get_temp_dir(), 'medialibrary'); file_put_contents($tmpFile, $binaryData); $this->guardAgainstInvalidMimeType($tmpFile, $allowedMimeTypes); $file = app(FileAdderFactory::class)->create($this, $tmpFile); return $file; }
php
public function addMediaFromBase64(string $base64data, ...$allowedMimeTypes): FileAdder { // strip out data uri scheme information (see RFC 2397) if (strpos($base64data, ';base64') !== false) { [$_, $base64data] = explode(';', $base64data); [$_, $base64data] = explode(',', $base64data); } // strict mode filters for non-base64 alphabet characters if (base64_decode($base64data, true) === false) { throw InvalidBase64Data::create(); } // decoding and then reencoding should not change the data if (base64_encode(base64_decode($base64data)) !== $base64data) { throw InvalidBase64Data::create(); } $binaryData = base64_decode($base64data); // temporarily store the decoded data on the filesystem to be able to pass it to the fileAdder $tmpFile = tempnam(sys_get_temp_dir(), 'medialibrary'); file_put_contents($tmpFile, $binaryData); $this->guardAgainstInvalidMimeType($tmpFile, $allowedMimeTypes); $file = app(FileAdderFactory::class)->create($this, $tmpFile); return $file; }
[ "public", "function", "addMediaFromBase64", "(", "string", "$", "base64data", ",", "...", "$", "allowedMimeTypes", ")", ":", "FileAdder", "{", "// strip out data uri scheme information (see RFC 2397)", "if", "(", "strpos", "(", "$", "base64data", ",", "';base64'", ")", "!==", "false", ")", "{", "[", "$", "_", ",", "$", "base64data", "]", "=", "explode", "(", "';'", ",", "$", "base64data", ")", ";", "[", "$", "_", ",", "$", "base64data", "]", "=", "explode", "(", "','", ",", "$", "base64data", ")", ";", "}", "// strict mode filters for non-base64 alphabet characters", "if", "(", "base64_decode", "(", "$", "base64data", ",", "true", ")", "===", "false", ")", "{", "throw", "InvalidBase64Data", "::", "create", "(", ")", ";", "}", "// decoding and then reencoding should not change the data", "if", "(", "base64_encode", "(", "base64_decode", "(", "$", "base64data", ")", ")", "!==", "$", "base64data", ")", "{", "throw", "InvalidBase64Data", "::", "create", "(", ")", ";", "}", "$", "binaryData", "=", "base64_decode", "(", "$", "base64data", ")", ";", "// temporarily store the decoded data on the filesystem to be able to pass it to the fileAdder", "$", "tmpFile", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "'medialibrary'", ")", ";", "file_put_contents", "(", "$", "tmpFile", ",", "$", "binaryData", ")", ";", "$", "this", "->", "guardAgainstInvalidMimeType", "(", "$", "tmpFile", ",", "$", "allowedMimeTypes", ")", ";", "$", "file", "=", "app", "(", "FileAdderFactory", "::", "class", ")", "->", "create", "(", "$", "this", ",", "$", "tmpFile", ")", ";", "return", "$", "file", ";", "}" ]
Add a base64 encoded file to the medialibrary. @param string $base64data @param string|array ...$allowedMimeTypes @throws InvalidBase64Data @throws \Spatie\MediaLibrary\Exceptions\FileCannotBeAdded @return \Spatie\MediaLibrary\FileAdder\FileAdder
[ "Add", "a", "base64", "encoded", "file", "to", "the", "medialibrary", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/HasMedia/HasMediaTrait.php#L161-L190
train
spatie/laravel-medialibrary
src/HasMedia/HasMediaTrait.php
HasMediaTrait.updateMedia
public function updateMedia(array $newMediaArray, string $collectionName = 'default'): Collection { $this->removeMediaItemsNotPresentInArray($newMediaArray, $collectionName); return collect($newMediaArray) ->map(function (array $newMediaItem) use ($collectionName) { static $orderColumn = 1; $mediaClass = config('medialibrary.media_model'); $currentMedia = $mediaClass::findOrFail($newMediaItem['id']); if ($currentMedia->collection_name !== $collectionName) { throw MediaCannotBeUpdated::doesNotBelongToCollection($collectionName, $currentMedia); } if (array_key_exists('name', $newMediaItem)) { $currentMedia->name = $newMediaItem['name']; } if (array_key_exists('custom_properties', $newMediaItem)) { $currentMedia->custom_properties = $newMediaItem['custom_properties']; } $currentMedia->order_column = $orderColumn++; $currentMedia->save(); return $currentMedia; }); }
php
public function updateMedia(array $newMediaArray, string $collectionName = 'default'): Collection { $this->removeMediaItemsNotPresentInArray($newMediaArray, $collectionName); return collect($newMediaArray) ->map(function (array $newMediaItem) use ($collectionName) { static $orderColumn = 1; $mediaClass = config('medialibrary.media_model'); $currentMedia = $mediaClass::findOrFail($newMediaItem['id']); if ($currentMedia->collection_name !== $collectionName) { throw MediaCannotBeUpdated::doesNotBelongToCollection($collectionName, $currentMedia); } if (array_key_exists('name', $newMediaItem)) { $currentMedia->name = $newMediaItem['name']; } if (array_key_exists('custom_properties', $newMediaItem)) { $currentMedia->custom_properties = $newMediaItem['custom_properties']; } $currentMedia->order_column = $orderColumn++; $currentMedia->save(); return $currentMedia; }); }
[ "public", "function", "updateMedia", "(", "array", "$", "newMediaArray", ",", "string", "$", "collectionName", "=", "'default'", ")", ":", "Collection", "{", "$", "this", "->", "removeMediaItemsNotPresentInArray", "(", "$", "newMediaArray", ",", "$", "collectionName", ")", ";", "return", "collect", "(", "$", "newMediaArray", ")", "->", "map", "(", "function", "(", "array", "$", "newMediaItem", ")", "use", "(", "$", "collectionName", ")", "{", "static", "$", "orderColumn", "=", "1", ";", "$", "mediaClass", "=", "config", "(", "'medialibrary.media_model'", ")", ";", "$", "currentMedia", "=", "$", "mediaClass", "::", "findOrFail", "(", "$", "newMediaItem", "[", "'id'", "]", ")", ";", "if", "(", "$", "currentMedia", "->", "collection_name", "!==", "$", "collectionName", ")", "{", "throw", "MediaCannotBeUpdated", "::", "doesNotBelongToCollection", "(", "$", "collectionName", ",", "$", "currentMedia", ")", ";", "}", "if", "(", "array_key_exists", "(", "'name'", ",", "$", "newMediaItem", ")", ")", "{", "$", "currentMedia", "->", "name", "=", "$", "newMediaItem", "[", "'name'", "]", ";", "}", "if", "(", "array_key_exists", "(", "'custom_properties'", ",", "$", "newMediaItem", ")", ")", "{", "$", "currentMedia", "->", "custom_properties", "=", "$", "newMediaItem", "[", "'custom_properties'", "]", ";", "}", "$", "currentMedia", "->", "order_column", "=", "$", "orderColumn", "++", ";", "$", "currentMedia", "->", "save", "(", ")", ";", "return", "$", "currentMedia", ";", "}", ")", ";", "}" ]
Update a media collection by deleting and inserting again with new values. @param array $newMediaArray @param string $collectionName @return \Illuminate\Support\Collection @throws \Spatie\MediaLibrary\Exceptions\MediaCannotBeUpdated
[ "Update", "a", "media", "collection", "by", "deleting", "and", "inserting", "again", "with", "new", "values", "." ]
6ffb8a41e60f024abd35ff47e08628354d6efd0e
https://github.com/spatie/laravel-medialibrary/blob/6ffb8a41e60f024abd35ff47e08628354d6efd0e/src/HasMedia/HasMediaTrait.php#L290-L319
train