repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
bestit/amazon-pay-oxid
ext/bestitamazonpay4oxid_order.php
bestitAmazonPay4Oxid_order.setBasketHash
protected function setBasketHash() { $oContainer = $this->_getContainer(); $sBasketHash = $oContainer->getConfig()->getRequestParameter('amazonBasketHash'); if ($sBasketHash) { $oContainer->getSession()->setVariable('sAmazonBasketHash', $sBasketHash); } }
php
protected function setBasketHash() { $oContainer = $this->_getContainer(); $sBasketHash = $oContainer->getConfig()->getRequestParameter('amazonBasketHash'); if ($sBasketHash) { $oContainer->getSession()->setVariable('sAmazonBasketHash', $sBasketHash); } }
[ "protected", "function", "setBasketHash", "(", ")", "{", "$", "oContainer", "=", "$", "this", "->", "_getContainer", "(", ")", ";", "$", "sBasketHash", "=", "$", "oContainer", "->", "getConfig", "(", ")", "->", "getRequestParameter", "(", "'amazonBasketHash'", ")", ";", "if", "(", "$", "sBasketHash", ")", "{", "$", "oContainer", "->", "getSession", "(", ")", "->", "setVariable", "(", "'sAmazonBasketHash'", ",", "$", "sBasketHash", ")", ";", "}", "}" ]
Sets the basket hash. @throws oxSystemComponentException
[ "Sets", "the", "basket", "hash", "." ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/ext/bestitamazonpay4oxid_order.php#L119-L127
train
bestit/amazon-pay-oxid
ext/bestitamazonpay4oxid_order.php
bestitAmazonPay4Oxid_order.render
public function render() { $sTemplate = parent::render(); $oPayment = $this->getPayment(); $oConfig = $this->_getContainer()->getConfig(); //payment is set and not oxempty if amazon selected? if ($oPayment !== false) { $sPaymentId = (string)$this->getPayment()->getId(); $sAmazonOrderReferenceId = (string)$this->_getContainer() ->getSession()->getVariable('amazonOrderReferenceId'); if ($sAmazonOrderReferenceId !== '') { if ($sPaymentId === 'oxempty') { $this->_setErrorAndRedirect( 'BESTITAMAZONPAY_NO_PAYMENTS_FOR_SHIPPING_ADDRESS', $oConfig->getShopSecureHomeUrl().'cl=user' ); return $sTemplate; } elseif ($sPaymentId === 'bestitamazon' && (string)$oConfig->getRequestParameter('fnc') !== 'execute' && (string)$oConfig->getRequestParameter('action') !== 'changePayment' ) { //Send Order reference details to Amazon if payment id is bestitamazon and amazonreferenceid exists //Send SetOrderReferenceDetails request $oData = $this->_getContainer()->getClient()->setOrderReferenceDetails($this->getBasket()); $oReferenceDetails = isset($oData->SetOrderReferenceDetailsResult->OrderReferenceDetails) ? $oData->SetOrderReferenceDetailsResult->OrderReferenceDetails : null; //If payment method is not valid to choose if ($oReferenceDetails !== null && (string)$oReferenceDetails->Constraints->Constraint->ConstraintID === 'PaymentMethodNotAllowed' ) { $this->_setErrorAndRedirect( 'BESTITAMAZONPAY_CHANGE_PAYMENT', $oConfig->getShopSecureHomeUrl().'cl=payment' ); return $sTemplate; } //If there's some other unexpected error if ($oReferenceDetails === null || (string)$oReferenceDetails->OrderReferenceStatus->State !== 'Draft' ) { $sAdditionalParameters = ''; // check if there is any information about an error if ($oData->Error->Code) { $sAdditionalParameters = '&bestitAmazonPay4OxidErrorCode='.$oData->Error->Code .'&error='.$oData->Error->Message; } $this->_getContainer()->getUtils()->redirect( $oConfig->getShopSecureHomeUrl().'cl=user&fnc=cleanAmazonPay'.$sAdditionalParameters, false ); return $sTemplate; } } } elseif ($sPaymentId === 'bestitamazon') { // If selected payment was bestitamazon but there's no amazonreferenceid, // redirect back to second step and show message $this->_setErrorAndRedirect( 'BESTITAMAZONPAY_CHANGE_PAYMENT', $oConfig->getShopSecureHomeUrl().'cl=basket' ); } } $this->setBasketHash(); return $sTemplate; }
php
public function render() { $sTemplate = parent::render(); $oPayment = $this->getPayment(); $oConfig = $this->_getContainer()->getConfig(); //payment is set and not oxempty if amazon selected? if ($oPayment !== false) { $sPaymentId = (string)$this->getPayment()->getId(); $sAmazonOrderReferenceId = (string)$this->_getContainer() ->getSession()->getVariable('amazonOrderReferenceId'); if ($sAmazonOrderReferenceId !== '') { if ($sPaymentId === 'oxempty') { $this->_setErrorAndRedirect( 'BESTITAMAZONPAY_NO_PAYMENTS_FOR_SHIPPING_ADDRESS', $oConfig->getShopSecureHomeUrl().'cl=user' ); return $sTemplate; } elseif ($sPaymentId === 'bestitamazon' && (string)$oConfig->getRequestParameter('fnc') !== 'execute' && (string)$oConfig->getRequestParameter('action') !== 'changePayment' ) { //Send Order reference details to Amazon if payment id is bestitamazon and amazonreferenceid exists //Send SetOrderReferenceDetails request $oData = $this->_getContainer()->getClient()->setOrderReferenceDetails($this->getBasket()); $oReferenceDetails = isset($oData->SetOrderReferenceDetailsResult->OrderReferenceDetails) ? $oData->SetOrderReferenceDetailsResult->OrderReferenceDetails : null; //If payment method is not valid to choose if ($oReferenceDetails !== null && (string)$oReferenceDetails->Constraints->Constraint->ConstraintID === 'PaymentMethodNotAllowed' ) { $this->_setErrorAndRedirect( 'BESTITAMAZONPAY_CHANGE_PAYMENT', $oConfig->getShopSecureHomeUrl().'cl=payment' ); return $sTemplate; } //If there's some other unexpected error if ($oReferenceDetails === null || (string)$oReferenceDetails->OrderReferenceStatus->State !== 'Draft' ) { $sAdditionalParameters = ''; // check if there is any information about an error if ($oData->Error->Code) { $sAdditionalParameters = '&bestitAmazonPay4OxidErrorCode='.$oData->Error->Code .'&error='.$oData->Error->Message; } $this->_getContainer()->getUtils()->redirect( $oConfig->getShopSecureHomeUrl().'cl=user&fnc=cleanAmazonPay'.$sAdditionalParameters, false ); return $sTemplate; } } } elseif ($sPaymentId === 'bestitamazon') { // If selected payment was bestitamazon but there's no amazonreferenceid, // redirect back to second step and show message $this->_setErrorAndRedirect( 'BESTITAMAZONPAY_CHANGE_PAYMENT', $oConfig->getShopSecureHomeUrl().'cl=basket' ); } } $this->setBasketHash(); return $sTemplate; }
[ "public", "function", "render", "(", ")", "{", "$", "sTemplate", "=", "parent", "::", "render", "(", ")", ";", "$", "oPayment", "=", "$", "this", "->", "getPayment", "(", ")", ";", "$", "oConfig", "=", "$", "this", "->", "_getContainer", "(", ")", "->", "getConfig", "(", ")", ";", "//payment is set and not oxempty if amazon selected?", "if", "(", "$", "oPayment", "!==", "false", ")", "{", "$", "sPaymentId", "=", "(", "string", ")", "$", "this", "->", "getPayment", "(", ")", "->", "getId", "(", ")", ";", "$", "sAmazonOrderReferenceId", "=", "(", "string", ")", "$", "this", "->", "_getContainer", "(", ")", "->", "getSession", "(", ")", "->", "getVariable", "(", "'amazonOrderReferenceId'", ")", ";", "if", "(", "$", "sAmazonOrderReferenceId", "!==", "''", ")", "{", "if", "(", "$", "sPaymentId", "===", "'oxempty'", ")", "{", "$", "this", "->", "_setErrorAndRedirect", "(", "'BESTITAMAZONPAY_NO_PAYMENTS_FOR_SHIPPING_ADDRESS'", ",", "$", "oConfig", "->", "getShopSecureHomeUrl", "(", ")", ".", "'cl=user'", ")", ";", "return", "$", "sTemplate", ";", "}", "elseif", "(", "$", "sPaymentId", "===", "'bestitamazon'", "&&", "(", "string", ")", "$", "oConfig", "->", "getRequestParameter", "(", "'fnc'", ")", "!==", "'execute'", "&&", "(", "string", ")", "$", "oConfig", "->", "getRequestParameter", "(", "'action'", ")", "!==", "'changePayment'", ")", "{", "//Send Order reference details to Amazon if payment id is bestitamazon and amazonreferenceid exists", "//Send SetOrderReferenceDetails request", "$", "oData", "=", "$", "this", "->", "_getContainer", "(", ")", "->", "getClient", "(", ")", "->", "setOrderReferenceDetails", "(", "$", "this", "->", "getBasket", "(", ")", ")", ";", "$", "oReferenceDetails", "=", "isset", "(", "$", "oData", "->", "SetOrderReferenceDetailsResult", "->", "OrderReferenceDetails", ")", "?", "$", "oData", "->", "SetOrderReferenceDetailsResult", "->", "OrderReferenceDetails", ":", "null", ";", "//If payment method is not valid to choose", "if", "(", "$", "oReferenceDetails", "!==", "null", "&&", "(", "string", ")", "$", "oReferenceDetails", "->", "Constraints", "->", "Constraint", "->", "ConstraintID", "===", "'PaymentMethodNotAllowed'", ")", "{", "$", "this", "->", "_setErrorAndRedirect", "(", "'BESTITAMAZONPAY_CHANGE_PAYMENT'", ",", "$", "oConfig", "->", "getShopSecureHomeUrl", "(", ")", ".", "'cl=payment'", ")", ";", "return", "$", "sTemplate", ";", "}", "//If there's some other unexpected error", "if", "(", "$", "oReferenceDetails", "===", "null", "||", "(", "string", ")", "$", "oReferenceDetails", "->", "OrderReferenceStatus", "->", "State", "!==", "'Draft'", ")", "{", "$", "sAdditionalParameters", "=", "''", ";", "// check if there is any information about an error", "if", "(", "$", "oData", "->", "Error", "->", "Code", ")", "{", "$", "sAdditionalParameters", "=", "'&bestitAmazonPay4OxidErrorCode='", ".", "$", "oData", "->", "Error", "->", "Code", ".", "'&error='", ".", "$", "oData", "->", "Error", "->", "Message", ";", "}", "$", "this", "->", "_getContainer", "(", ")", "->", "getUtils", "(", ")", "->", "redirect", "(", "$", "oConfig", "->", "getShopSecureHomeUrl", "(", ")", ".", "'cl=user&fnc=cleanAmazonPay'", ".", "$", "sAdditionalParameters", ",", "false", ")", ";", "return", "$", "sTemplate", ";", "}", "}", "}", "elseif", "(", "$", "sPaymentId", "===", "'bestitamazon'", ")", "{", "// If selected payment was bestitamazon but there's no amazonreferenceid,", "// redirect back to second step and show message", "$", "this", "->", "_setErrorAndRedirect", "(", "'BESTITAMAZONPAY_CHANGE_PAYMENT'", ",", "$", "oConfig", "->", "getShopSecureHomeUrl", "(", ")", ".", "'cl=basket'", ")", ";", "}", "}", "$", "this", "->", "setBasketHash", "(", ")", ";", "return", "$", "sTemplate", ";", "}" ]
The main render function with additional payment checks. @return mixed @throws Exception @throws oxSystemComponentException
[ "The", "main", "render", "function", "with", "additional", "payment", "checks", "." ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/ext/bestitamazonpay4oxid_order.php#L137-L210
train
bestit/amazon-pay-oxid
application/models/bestitamazonpay4oxidipnhandler.php
bestitAmazonPay4OxidIpnHandler.logIPNResponse
public function logIPNResponse($sLevel, $sMessage, $oIpnMessage = null) { if ((bool)$this->getConfig()->getConfigParam('blAmazonLogging') !== true) { return; } $aContext = ($oIpnMessage !== null) ? array('ipnMessage' => $oIpnMessage) : array(); $this->_getLogger()->log($sLevel, $sMessage, $aContext); }
php
public function logIPNResponse($sLevel, $sMessage, $oIpnMessage = null) { if ((bool)$this->getConfig()->getConfigParam('blAmazonLogging') !== true) { return; } $aContext = ($oIpnMessage !== null) ? array('ipnMessage' => $oIpnMessage) : array(); $this->_getLogger()->log($sLevel, $sMessage, $aContext); }
[ "public", "function", "logIPNResponse", "(", "$", "sLevel", ",", "$", "sMessage", ",", "$", "oIpnMessage", "=", "null", ")", "{", "if", "(", "(", "bool", ")", "$", "this", "->", "getConfig", "(", ")", "->", "getConfigParam", "(", "'blAmazonLogging'", ")", "!==", "true", ")", "{", "return", ";", "}", "$", "aContext", "=", "(", "$", "oIpnMessage", "!==", "null", ")", "?", "array", "(", "'ipnMessage'", "=>", "$", "oIpnMessage", ")", ":", "array", "(", ")", ";", "$", "this", "->", "_getLogger", "(", ")", "->", "log", "(", "$", "sLevel", ",", "$", "sMessage", ",", "$", "aContext", ")", ";", "}" ]
Method logs IPN response to text file @param string $sLevel @param string $sMessage @param array $oIpnMessage @throws Exception
[ "Method", "logs", "IPN", "response", "to", "text", "file" ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/application/models/bestitamazonpay4oxidipnhandler.php#L74-L82
train
bestit/amazon-pay-oxid
application/models/bestitamazonpay4oxidipnhandler.php
bestitAmazonPay4OxidIpnHandler._getMessage
protected function _getMessage($sBody) { //Load response xml to object try { // Get the IPN headers and Message body $aHeaders = array(); foreach ($_SERVER as $sKey => $sValue) { if (substr($sKey, 0, 5) !== 'HTTP_') { continue; } $sHeader = str_replace(' ', '-', str_replace('_', ' ', strtolower(substr($sKey, 5)))); $aHeaders[$sHeader] = $sValue; } $ipnHandler = $this->getObjectFactory()->createIpnHandler($aHeaders, $sBody); $ipnHandler->setLogger($this->_getLogger()); return json_decode($ipnHandler->toJson()); } catch (Exception $oException) { $this->logIPNResponse(Logger::ERROR, 'Unable to parse ipn message'); } return false; }
php
protected function _getMessage($sBody) { //Load response xml to object try { // Get the IPN headers and Message body $aHeaders = array(); foreach ($_SERVER as $sKey => $sValue) { if (substr($sKey, 0, 5) !== 'HTTP_') { continue; } $sHeader = str_replace(' ', '-', str_replace('_', ' ', strtolower(substr($sKey, 5)))); $aHeaders[$sHeader] = $sValue; } $ipnHandler = $this->getObjectFactory()->createIpnHandler($aHeaders, $sBody); $ipnHandler->setLogger($this->_getLogger()); return json_decode($ipnHandler->toJson()); } catch (Exception $oException) { $this->logIPNResponse(Logger::ERROR, 'Unable to parse ipn message'); } return false; }
[ "protected", "function", "_getMessage", "(", "$", "sBody", ")", "{", "//Load response xml to object", "try", "{", "// Get the IPN headers and Message body", "$", "aHeaders", "=", "array", "(", ")", ";", "foreach", "(", "$", "_SERVER", "as", "$", "sKey", "=>", "$", "sValue", ")", "{", "if", "(", "substr", "(", "$", "sKey", ",", "0", ",", "5", ")", "!==", "'HTTP_'", ")", "{", "continue", ";", "}", "$", "sHeader", "=", "str_replace", "(", "' '", ",", "'-'", ",", "str_replace", "(", "'_'", ",", "' '", ",", "strtolower", "(", "substr", "(", "$", "sKey", ",", "5", ")", ")", ")", ")", ";", "$", "aHeaders", "[", "$", "sHeader", "]", "=", "$", "sValue", ";", "}", "$", "ipnHandler", "=", "$", "this", "->", "getObjectFactory", "(", ")", "->", "createIpnHandler", "(", "$", "aHeaders", ",", "$", "sBody", ")", ";", "$", "ipnHandler", "->", "setLogger", "(", "$", "this", "->", "_getLogger", "(", ")", ")", ";", "return", "json_decode", "(", "$", "ipnHandler", "->", "toJson", "(", ")", ")", ";", "}", "catch", "(", "Exception", "$", "oException", ")", "{", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "ERROR", ",", "'Unable to parse ipn message'", ")", ";", "}", "return", "false", ";", "}" ]
Parses SNS message and saves as simplified IPN message into array @param string $sBody @return stdClass|bool @throws Exception
[ "Parses", "SNS", "message", "and", "saves", "as", "simplified", "IPN", "message", "into", "array" ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/application/models/bestitamazonpay4oxidipnhandler.php#L92-L116
train
bestit/amazon-pay-oxid
application/models/bestitamazonpay4oxidipnhandler.php
bestitAmazonPay4OxidIpnHandler._orderReferenceUpdate
protected function _orderReferenceUpdate($oData) { $sId = $oData->OrderReference->AmazonOrderReferenceId; $oOrder = $this->_loadOrderById('BESTITAMAZONORDERREFERENCEID', $sId); if ($oOrder !== false && isset($oData->OrderReference->OrderReferenceStatus->State)) { $this->getClient()->processOrderReference($oOrder, $oData->OrderReference); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Order with Order Reference ID: {$sId} not found", $oData); return false; }
php
protected function _orderReferenceUpdate($oData) { $sId = $oData->OrderReference->AmazonOrderReferenceId; $oOrder = $this->_loadOrderById('BESTITAMAZONORDERREFERENCEID', $sId); if ($oOrder !== false && isset($oData->OrderReference->OrderReferenceStatus->State)) { $this->getClient()->processOrderReference($oOrder, $oData->OrderReference); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Order with Order Reference ID: {$sId} not found", $oData); return false; }
[ "protected", "function", "_orderReferenceUpdate", "(", "$", "oData", ")", "{", "$", "sId", "=", "$", "oData", "->", "OrderReference", "->", "AmazonOrderReferenceId", ";", "$", "oOrder", "=", "$", "this", "->", "_loadOrderById", "(", "'BESTITAMAZONORDERREFERENCEID'", ",", "$", "sId", ")", ";", "if", "(", "$", "oOrder", "!==", "false", "&&", "isset", "(", "$", "oData", "->", "OrderReference", "->", "OrderReferenceStatus", "->", "State", ")", ")", "{", "$", "this", "->", "getClient", "(", ")", "->", "processOrderReference", "(", "$", "oOrder", ",", "$", "oData", "->", "OrderReference", ")", ";", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "INFO", ",", "'OK'", ",", "$", "oData", ")", ";", "return", "true", ";", "}", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "ERROR", ",", "\"Order with Order Reference ID: {$sId} not found\"", ",", "$", "oData", ")", ";", "return", "false", ";", "}" ]
Handles response for NotificationType = OrderReferenceNotification @param stdClass $oData @return boolean @throws Exception
[ "Handles", "response", "for", "NotificationType", "=", "OrderReferenceNotification" ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/application/models/bestitamazonpay4oxidipnhandler.php#L152-L165
train
bestit/amazon-pay-oxid
application/models/bestitamazonpay4oxidipnhandler.php
bestitAmazonPay4OxidIpnHandler._paymentAuthorize
protected function _paymentAuthorize($oData) { $sId = $oData->AuthorizationDetails->AmazonAuthorizationId; $oOrder = $this->_loadOrderById('BESTITAMAZONAUTHORIZATIONID', $sId); if ($oOrder !== false && isset($oData->AuthorizationDetails->AuthorizationStatus->State)) { $this->getClient()->processAuthorization($oOrder, $oData->AuthorizationDetails); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Order with Authorization ID: {$sId} not found", $oData); return false; }
php
protected function _paymentAuthorize($oData) { $sId = $oData->AuthorizationDetails->AmazonAuthorizationId; $oOrder = $this->_loadOrderById('BESTITAMAZONAUTHORIZATIONID', $sId); if ($oOrder !== false && isset($oData->AuthorizationDetails->AuthorizationStatus->State)) { $this->getClient()->processAuthorization($oOrder, $oData->AuthorizationDetails); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Order with Authorization ID: {$sId} not found", $oData); return false; }
[ "protected", "function", "_paymentAuthorize", "(", "$", "oData", ")", "{", "$", "sId", "=", "$", "oData", "->", "AuthorizationDetails", "->", "AmazonAuthorizationId", ";", "$", "oOrder", "=", "$", "this", "->", "_loadOrderById", "(", "'BESTITAMAZONAUTHORIZATIONID'", ",", "$", "sId", ")", ";", "if", "(", "$", "oOrder", "!==", "false", "&&", "isset", "(", "$", "oData", "->", "AuthorizationDetails", "->", "AuthorizationStatus", "->", "State", ")", ")", "{", "$", "this", "->", "getClient", "(", ")", "->", "processAuthorization", "(", "$", "oOrder", ",", "$", "oData", "->", "AuthorizationDetails", ")", ";", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "INFO", ",", "'OK'", ",", "$", "oData", ")", ";", "return", "true", ";", "}", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "ERROR", ",", "\"Order with Authorization ID: {$sId} not found\"", ",", "$", "oData", ")", ";", "return", "false", ";", "}" ]
Handles response for NotificationType = PaymentAuthorize @param stdClass $oData @return boolean @throws Exception
[ "Handles", "response", "for", "NotificationType", "=", "PaymentAuthorize" ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/application/models/bestitamazonpay4oxidipnhandler.php#L176-L189
train
bestit/amazon-pay-oxid
application/models/bestitamazonpay4oxidipnhandler.php
bestitAmazonPay4OxidIpnHandler._paymentCapture
protected function _paymentCapture($oData) { $sId = $oData->CaptureDetails->AmazonCaptureId; $oOrder = $this->_loadOrderById('BESTITAMAZONCAPTUREID', $sId); if ($oOrder !== false && isset($oData->CaptureDetails->CaptureStatus->State)) { $this->getClient()->setCaptureState($oOrder, $oData->CaptureDetails, true); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Order with Capture ID: {$sId} not found", $oData); return false; }
php
protected function _paymentCapture($oData) { $sId = $oData->CaptureDetails->AmazonCaptureId; $oOrder = $this->_loadOrderById('BESTITAMAZONCAPTUREID', $sId); if ($oOrder !== false && isset($oData->CaptureDetails->CaptureStatus->State)) { $this->getClient()->setCaptureState($oOrder, $oData->CaptureDetails, true); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Order with Capture ID: {$sId} not found", $oData); return false; }
[ "protected", "function", "_paymentCapture", "(", "$", "oData", ")", "{", "$", "sId", "=", "$", "oData", "->", "CaptureDetails", "->", "AmazonCaptureId", ";", "$", "oOrder", "=", "$", "this", "->", "_loadOrderById", "(", "'BESTITAMAZONCAPTUREID'", ",", "$", "sId", ")", ";", "if", "(", "$", "oOrder", "!==", "false", "&&", "isset", "(", "$", "oData", "->", "CaptureDetails", "->", "CaptureStatus", "->", "State", ")", ")", "{", "$", "this", "->", "getClient", "(", ")", "->", "setCaptureState", "(", "$", "oOrder", ",", "$", "oData", "->", "CaptureDetails", ",", "true", ")", ";", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "INFO", ",", "'OK'", ",", "$", "oData", ")", ";", "return", "true", ";", "}", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "ERROR", ",", "\"Order with Capture ID: {$sId} not found\"", ",", "$", "oData", ")", ";", "return", "false", ";", "}" ]
Handles response for NotificationType = PaymentCapture @param stdClass $oData @return boolean @throws Exception
[ "Handles", "response", "for", "NotificationType", "=", "PaymentCapture" ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/application/models/bestitamazonpay4oxidipnhandler.php#L200-L213
train
bestit/amazon-pay-oxid
application/models/bestitamazonpay4oxidipnhandler.php
bestitAmazonPay4OxidIpnHandler._paymentRefund
protected function _paymentRefund($oData) { $sAmazonRefundId = $oData->RefundDetails->AmazonRefundId; $sSql = "SELECT COUNT(*) FROM bestitamazonrefunds WHERE BESTITAMAZONREFUNDID = {$this->getDatabase()->quote($sAmazonRefundId)} LIMIT 1"; $iMatches = (int)$this->getDatabase()->getOne($sSql); //Update Refund info if ($iMatches > 0 && isset($oData->RefundDetails->RefundStatus->State)) { $this->getClient()->updateRefund( $oData->RefundDetails->RefundStatus->State, $sAmazonRefundId ); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Refund with Refund ID: {$sAmazonRefundId} not found", $oData); return false; }
php
protected function _paymentRefund($oData) { $sAmazonRefundId = $oData->RefundDetails->AmazonRefundId; $sSql = "SELECT COUNT(*) FROM bestitamazonrefunds WHERE BESTITAMAZONREFUNDID = {$this->getDatabase()->quote($sAmazonRefundId)} LIMIT 1"; $iMatches = (int)$this->getDatabase()->getOne($sSql); //Update Refund info if ($iMatches > 0 && isset($oData->RefundDetails->RefundStatus->State)) { $this->getClient()->updateRefund( $oData->RefundDetails->RefundStatus->State, $sAmazonRefundId ); $this->logIPNResponse(Logger::INFO, 'OK', $oData); return true; } $this->logIPNResponse(Logger::ERROR, "Refund with Refund ID: {$sAmazonRefundId} not found", $oData); return false; }
[ "protected", "function", "_paymentRefund", "(", "$", "oData", ")", "{", "$", "sAmazonRefundId", "=", "$", "oData", "->", "RefundDetails", "->", "AmazonRefundId", ";", "$", "sSql", "=", "\"SELECT COUNT(*)\n FROM bestitamazonrefunds \n WHERE BESTITAMAZONREFUNDID = {$this->getDatabase()->quote($sAmazonRefundId)}\n LIMIT 1\"", ";", "$", "iMatches", "=", "(", "int", ")", "$", "this", "->", "getDatabase", "(", ")", "->", "getOne", "(", "$", "sSql", ")", ";", "//Update Refund info", "if", "(", "$", "iMatches", ">", "0", "&&", "isset", "(", "$", "oData", "->", "RefundDetails", "->", "RefundStatus", "->", "State", ")", ")", "{", "$", "this", "->", "getClient", "(", ")", "->", "updateRefund", "(", "$", "oData", "->", "RefundDetails", "->", "RefundStatus", "->", "State", ",", "$", "sAmazonRefundId", ")", ";", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "INFO", ",", "'OK'", ",", "$", "oData", ")", ";", "return", "true", ";", "}", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "ERROR", ",", "\"Refund with Refund ID: {$sAmazonRefundId} not found\"", ",", "$", "oData", ")", ";", "return", "false", ";", "}" ]
Handles response for NotificationType = PaymentRefund @param stdClass $oData @return boolean @throws oxConnectionException @throws Exception
[ "Handles", "response", "for", "NotificationType", "=", "PaymentRefund" ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/application/models/bestitamazonpay4oxidipnhandler.php#L224-L245
train
bestit/amazon-pay-oxid
application/models/bestitamazonpay4oxidipnhandler.php
bestitAmazonPay4OxidIpnHandler.processIPNAction
public function processIPNAction($sBody) { $oMessage = $this->_getMessage($sBody); if (isset($oMessage->NotificationData)) { $oData = $oMessage->NotificationData; switch ($oMessage->NotificationType) { case 'OrderReferenceNotification': return $this->_orderReferenceUpdate($oData); case 'PaymentAuthorize': return $this->_paymentAuthorize($oData); case 'PaymentCapture': return $this->_paymentCapture($oData); case 'PaymentRefund': return $this->_paymentRefund($oData); default: $this->logIPNResponse(Logger::ERROR, 'NotificationType in response not found', $oMessage); return false; } } $this->logIPNResponse(Logger::ERROR, 'Invalid ipn message'); return false; }
php
public function processIPNAction($sBody) { $oMessage = $this->_getMessage($sBody); if (isset($oMessage->NotificationData)) { $oData = $oMessage->NotificationData; switch ($oMessage->NotificationType) { case 'OrderReferenceNotification': return $this->_orderReferenceUpdate($oData); case 'PaymentAuthorize': return $this->_paymentAuthorize($oData); case 'PaymentCapture': return $this->_paymentCapture($oData); case 'PaymentRefund': return $this->_paymentRefund($oData); default: $this->logIPNResponse(Logger::ERROR, 'NotificationType in response not found', $oMessage); return false; } } $this->logIPNResponse(Logger::ERROR, 'Invalid ipn message'); return false; }
[ "public", "function", "processIPNAction", "(", "$", "sBody", ")", "{", "$", "oMessage", "=", "$", "this", "->", "_getMessage", "(", "$", "sBody", ")", ";", "if", "(", "isset", "(", "$", "oMessage", "->", "NotificationData", ")", ")", "{", "$", "oData", "=", "$", "oMessage", "->", "NotificationData", ";", "switch", "(", "$", "oMessage", "->", "NotificationType", ")", "{", "case", "'OrderReferenceNotification'", ":", "return", "$", "this", "->", "_orderReferenceUpdate", "(", "$", "oData", ")", ";", "case", "'PaymentAuthorize'", ":", "return", "$", "this", "->", "_paymentAuthorize", "(", "$", "oData", ")", ";", "case", "'PaymentCapture'", ":", "return", "$", "this", "->", "_paymentCapture", "(", "$", "oData", ")", ";", "case", "'PaymentRefund'", ":", "return", "$", "this", "->", "_paymentRefund", "(", "$", "oData", ")", ";", "default", ":", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "ERROR", ",", "'NotificationType in response not found'", ",", "$", "oMessage", ")", ";", "return", "false", ";", "}", "}", "$", "this", "->", "logIPNResponse", "(", "Logger", "::", "ERROR", ",", "'Invalid ipn message'", ")", ";", "return", "false", ";", "}" ]
Process actions by NotificationType @param string $sBody @return bool @throws Exception @throws oxConnectionException
[ "Process", "actions", "by", "NotificationType" ]
d32254664e2f148d58bfafe36f5ce67ca30560d9
https://github.com/bestit/amazon-pay-oxid/blob/d32254664e2f148d58bfafe36f5ce67ca30560d9/application/models/bestitamazonpay4oxidipnhandler.php#L256-L280
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.initializeNode
public function initializeNode($weightClasses) { if (!$this->isInitialized()) { $contentScore = 0; switch ($this->nodeName) { case 'div': $contentScore += 5; break; case 'pre': case 'td': case 'blockquote': $contentScore += 3; break; case 'address': case 'ol': case 'ul': case 'dl': case 'dd': case 'dt': case 'li': case 'form': $contentScore -= 3; break; case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': case 'th': $contentScore -= 5; break; } $this->contentScore = $contentScore + ($weightClasses ? $this->getClassWeight() : 0); $this->initialized = true; } return $this; }
php
public function initializeNode($weightClasses) { if (!$this->isInitialized()) { $contentScore = 0; switch ($this->nodeName) { case 'div': $contentScore += 5; break; case 'pre': case 'td': case 'blockquote': $contentScore += 3; break; case 'address': case 'ol': case 'ul': case 'dl': case 'dd': case 'dt': case 'li': case 'form': $contentScore -= 3; break; case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': case 'th': $contentScore -= 5; break; } $this->contentScore = $contentScore + ($weightClasses ? $this->getClassWeight() : 0); $this->initialized = true; } return $this; }
[ "public", "function", "initializeNode", "(", "$", "weightClasses", ")", "{", "if", "(", "!", "$", "this", "->", "isInitialized", "(", ")", ")", "{", "$", "contentScore", "=", "0", ";", "switch", "(", "$", "this", "->", "nodeName", ")", "{", "case", "'div'", ":", "$", "contentScore", "+=", "5", ";", "break", ";", "case", "'pre'", ":", "case", "'td'", ":", "case", "'blockquote'", ":", "$", "contentScore", "+=", "3", ";", "break", ";", "case", "'address'", ":", "case", "'ol'", ":", "case", "'ul'", ":", "case", "'dl'", ":", "case", "'dd'", ":", "case", "'dt'", ":", "case", "'li'", ":", "case", "'form'", ":", "$", "contentScore", "-=", "3", ";", "break", ";", "case", "'h1'", ":", "case", "'h2'", ":", "case", "'h3'", ":", "case", "'h4'", ":", "case", "'h5'", ":", "case", "'h6'", ":", "case", "'th'", ":", "$", "contentScore", "-=", "5", ";", "break", ";", "}", "$", "this", "->", "contentScore", "=", "$", "contentScore", "+", "(", "$", "weightClasses", "?", "$", "this", "->", "getClassWeight", "(", ")", ":", "0", ")", ";", "$", "this", "->", "initialized", "=", "true", ";", "}", "return", "$", "this", ";", "}" ]
Initializer. Calculates the current score of the node and returns a full Readability object. @ TODO: I don't like the weightClasses param. How can we get the config here? @param $weightClasses bool Weight classes? @return static
[ "Initializer", ".", "Calculates", "the", "current", "score", "of", "the", "node", "and", "returns", "a", "full", "Readability", "object", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L118-L162
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.getNodeAncestors
public function getNodeAncestors($maxLevel = 3) { $ancestors = []; $level = 0; $node = $this->parentNode; while ($node && !($node instanceof DOMDocument)) { $ancestors[] = $node; $level++; if ($level === $maxLevel) { break; } $node = $node->parentNode; } return $ancestors; }
php
public function getNodeAncestors($maxLevel = 3) { $ancestors = []; $level = 0; $node = $this->parentNode; while ($node && !($node instanceof DOMDocument)) { $ancestors[] = $node; $level++; if ($level === $maxLevel) { break; } $node = $node->parentNode; } return $ancestors; }
[ "public", "function", "getNodeAncestors", "(", "$", "maxLevel", "=", "3", ")", "{", "$", "ancestors", "=", "[", "]", ";", "$", "level", "=", "0", ";", "$", "node", "=", "$", "this", "->", "parentNode", ";", "while", "(", "$", "node", "&&", "!", "(", "$", "node", "instanceof", "DOMDocument", ")", ")", "{", "$", "ancestors", "[", "]", "=", "$", "node", ";", "$", "level", "++", ";", "if", "(", "$", "level", "===", "$", "maxLevel", ")", "{", "break", ";", "}", "$", "node", "=", "$", "node", "->", "parentNode", ";", "}", "return", "$", "ancestors", ";", "}" ]
Get the ancestors of the current node. @param int|bool $maxLevel Max amount of ancestors to get. False for all of them @return array
[ "Get", "the", "ancestors", "of", "the", "current", "node", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L206-L223
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.getLinkDensity
public function getLinkDensity() { $linkLength = 0; $textLength = mb_strlen($this->getTextContent(true)); if (!$textLength) { return 0; } $links = $this->getAllLinks(); if ($links) { /** @var DOMElement $link */ foreach ($links as $link) { $linkLength += mb_strlen($link->getTextContent(true)); } } return $linkLength / $textLength; }
php
public function getLinkDensity() { $linkLength = 0; $textLength = mb_strlen($this->getTextContent(true)); if (!$textLength) { return 0; } $links = $this->getAllLinks(); if ($links) { /** @var DOMElement $link */ foreach ($links as $link) { $linkLength += mb_strlen($link->getTextContent(true)); } } return $linkLength / $textLength; }
[ "public", "function", "getLinkDensity", "(", ")", "{", "$", "linkLength", "=", "0", ";", "$", "textLength", "=", "mb_strlen", "(", "$", "this", "->", "getTextContent", "(", "true", ")", ")", ";", "if", "(", "!", "$", "textLength", ")", "{", "return", "0", ";", "}", "$", "links", "=", "$", "this", "->", "getAllLinks", "(", ")", ";", "if", "(", "$", "links", ")", "{", "/** @var DOMElement $link */", "foreach", "(", "$", "links", "as", "$", "link", ")", "{", "$", "linkLength", "+=", "mb_strlen", "(", "$", "link", "->", "getTextContent", "(", "true", ")", ")", ";", "}", "}", "return", "$", "linkLength", "/", "$", "textLength", ";", "}" ]
Get the density of links as a percentage of the content This is the amount of text that is inside a link divided by the total text in the node. @return int
[ "Get", "the", "density", "of", "links", "as", "a", "percentage", "of", "the", "content", "This", "is", "the", "amount", "of", "text", "that", "is", "inside", "a", "link", "divided", "by", "the", "total", "text", "in", "the", "node", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L241-L260
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.getTextContent
public function getTextContent($normalize = false) { $nodeValue = $this->nodeValue; if ($normalize) { $nodeValue = trim(preg_replace('/\s{2,}/', ' ', $nodeValue)); } return $nodeValue; }
php
public function getTextContent($normalize = false) { $nodeValue = $this->nodeValue; if ($normalize) { $nodeValue = trim(preg_replace('/\s{2,}/', ' ', $nodeValue)); } return $nodeValue; }
[ "public", "function", "getTextContent", "(", "$", "normalize", "=", "false", ")", "{", "$", "nodeValue", "=", "$", "this", "->", "nodeValue", ";", "if", "(", "$", "normalize", ")", "{", "$", "nodeValue", "=", "trim", "(", "preg_replace", "(", "'/\\s{2,}/'", ",", "' '", ",", "$", "nodeValue", ")", ")", ";", "}", "return", "$", "nodeValue", ";", "}" ]
Returns the full text of the node. @param bool $normalize Normalize white space? @return string
[ "Returns", "the", "full", "text", "of", "the", "node", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L305-L313
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.getChildren
public function getChildren($filterEmptyDOMText = false) { $ret = iterator_to_array($this->childNodes); if ($filterEmptyDOMText) { // Array values is used to discard the key order. Needs to be 0 to whatever without skipping any number $ret = array_values(array_filter($ret, function ($node) { return $node->nodeName !== '#text' || mb_strlen(trim($node->nodeValue)); })); } return $ret; }
php
public function getChildren($filterEmptyDOMText = false) { $ret = iterator_to_array($this->childNodes); if ($filterEmptyDOMText) { // Array values is used to discard the key order. Needs to be 0 to whatever without skipping any number $ret = array_values(array_filter($ret, function ($node) { return $node->nodeName !== '#text' || mb_strlen(trim($node->nodeValue)); })); } return $ret; }
[ "public", "function", "getChildren", "(", "$", "filterEmptyDOMText", "=", "false", ")", "{", "$", "ret", "=", "iterator_to_array", "(", "$", "this", "->", "childNodes", ")", ";", "if", "(", "$", "filterEmptyDOMText", ")", "{", "// Array values is used to discard the key order. Needs to be 0 to whatever without skipping any number", "$", "ret", "=", "array_values", "(", "array_filter", "(", "$", "ret", ",", "function", "(", "$", "node", ")", "{", "return", "$", "node", "->", "nodeName", "!==", "'#text'", "||", "mb_strlen", "(", "trim", "(", "$", "node", "->", "nodeValue", ")", ")", ";", "}", ")", ")", ";", "}", "return", "$", "ret", ";", "}" ]
Returns the children of the current node. @param bool $filterEmptyDOMText Filter empty DOMText nodes? @return array
[ "Returns", "the", "children", "of", "the", "current", "node", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L322-L333
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.getRowAndColumnCount
public function getRowAndColumnCount() { $rows = $columns = 0; $trs = $this->getElementsByTagName('tr'); foreach ($trs as $tr) { /** @var \DOMElement $tr */ $rowspan = $tr->getAttribute('rowspan'); $rows += ($rowspan || 1); // Now look for column-related info $columnsInThisRow = 0; $cells = $tr->getElementsByTagName('td'); foreach ($cells as $cell) { /** @var \DOMElement $cell */ $colspan = $cell->getAttribute('colspan'); $columnsInThisRow += ($colspan || 1); } $columns = max($columns, $columnsInThisRow); } return ['rows' => $rows, 'columns' => $columns]; }
php
public function getRowAndColumnCount() { $rows = $columns = 0; $trs = $this->getElementsByTagName('tr'); foreach ($trs as $tr) { /** @var \DOMElement $tr */ $rowspan = $tr->getAttribute('rowspan'); $rows += ($rowspan || 1); // Now look for column-related info $columnsInThisRow = 0; $cells = $tr->getElementsByTagName('td'); foreach ($cells as $cell) { /** @var \DOMElement $cell */ $colspan = $cell->getAttribute('colspan'); $columnsInThisRow += ($colspan || 1); } $columns = max($columns, $columnsInThisRow); } return ['rows' => $rows, 'columns' => $columns]; }
[ "public", "function", "getRowAndColumnCount", "(", ")", "{", "$", "rows", "=", "$", "columns", "=", "0", ";", "$", "trs", "=", "$", "this", "->", "getElementsByTagName", "(", "'tr'", ")", ";", "foreach", "(", "$", "trs", "as", "$", "tr", ")", "{", "/** @var \\DOMElement $tr */", "$", "rowspan", "=", "$", "tr", "->", "getAttribute", "(", "'rowspan'", ")", ";", "$", "rows", "+=", "(", "$", "rowspan", "||", "1", ")", ";", "// Now look for column-related info", "$", "columnsInThisRow", "=", "0", ";", "$", "cells", "=", "$", "tr", "->", "getElementsByTagName", "(", "'td'", ")", ";", "foreach", "(", "$", "cells", "as", "$", "cell", ")", "{", "/** @var \\DOMElement $cell */", "$", "colspan", "=", "$", "cell", "->", "getAttribute", "(", "'colspan'", ")", ";", "$", "columnsInThisRow", "+=", "(", "$", "colspan", "||", "1", ")", ";", "}", "$", "columns", "=", "max", "(", "$", "columns", ",", "$", "columnsInThisRow", ")", ";", "}", "return", "[", "'rows'", "=>", "$", "rows", ",", "'columns'", "=>", "$", "columns", "]", ";", "}" ]
Return an array indicating how many rows and columns this table has. @return array
[ "Return", "an", "array", "indicating", "how", "many", "rows", "and", "columns", "this", "table", "has", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L340-L361
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.createNode
public function createNode($originalNode, $tagName) { $text = $originalNode->getTextContent(); $newNode = $originalNode->ownerDocument->createElement($tagName, $text); return $newNode; }
php
public function createNode($originalNode, $tagName) { $text = $originalNode->getTextContent(); $newNode = $originalNode->ownerDocument->createElement($tagName, $text); return $newNode; }
[ "public", "function", "createNode", "(", "$", "originalNode", ",", "$", "tagName", ")", "{", "$", "text", "=", "$", "originalNode", "->", "getTextContent", "(", ")", ";", "$", "newNode", "=", "$", "originalNode", "->", "ownerDocument", "->", "createElement", "(", "$", "tagName", ",", "$", "text", ")", ";", "return", "$", "newNode", ";", "}" ]
Creates a new node based on the text content of the original node. @param $originalNode DOMNode @param $tagName string @return DOMElement
[ "Creates", "a", "new", "node", "based", "on", "the", "text", "content", "of", "the", "original", "node", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L371-L377
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.hasAncestorTag
public function hasAncestorTag($tagName, $maxDepth = 3, callable $filterFn = null) { $depth = 0; $node = $this; while ($node->parentNode) { if ($maxDepth > 0 && $depth > $maxDepth) { return false; } if ($node->parentNode->nodeName === $tagName && (!$filterFn || $filterFn($node->parentNode))) { return true; } $node = $node->parentNode; $depth++; } return false; }
php
public function hasAncestorTag($tagName, $maxDepth = 3, callable $filterFn = null) { $depth = 0; $node = $this; while ($node->parentNode) { if ($maxDepth > 0 && $depth > $maxDepth) { return false; } if ($node->parentNode->nodeName === $tagName && (!$filterFn || $filterFn($node->parentNode))) { return true; } $node = $node->parentNode; $depth++; } return false; }
[ "public", "function", "hasAncestorTag", "(", "$", "tagName", ",", "$", "maxDepth", "=", "3", ",", "callable", "$", "filterFn", "=", "null", ")", "{", "$", "depth", "=", "0", ";", "$", "node", "=", "$", "this", ";", "while", "(", "$", "node", "->", "parentNode", ")", "{", "if", "(", "$", "maxDepth", ">", "0", "&&", "$", "depth", ">", "$", "maxDepth", ")", "{", "return", "false", ";", "}", "if", "(", "$", "node", "->", "parentNode", "->", "nodeName", "===", "$", "tagName", "&&", "(", "!", "$", "filterFn", "||", "$", "filterFn", "(", "$", "node", "->", "parentNode", ")", ")", ")", "{", "return", "true", ";", "}", "$", "node", "=", "$", "node", "->", "parentNode", ";", "$", "depth", "++", ";", "}", "return", "false", ";", "}" ]
Check if a given node has one of its ancestor tag name matching the provided one. @param string $tagName @param int $maxDepth @param callable $filterFn @return bool
[ "Check", "if", "a", "given", "node", "has", "one", "of", "its", "ancestor", "tag", "name", "matching", "the", "provided", "one", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L389-L408
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.hasSingleTagInsideElement
public function hasSingleTagInsideElement($tag) { // There should be exactly 1 element child with given tag if (count($children = $this->getChildren(true)) !== 1 || $children[0]->nodeName !== $tag) { return false; } // And there should be no text nodes with real content return array_reduce($children, function ($carry, $child) { if (!$carry === false) { return false; } /* @var DOMNode $child */ return !($child->nodeType === XML_TEXT_NODE && !preg_match('/\S$/', $child->getTextContent())); }); }
php
public function hasSingleTagInsideElement($tag) { // There should be exactly 1 element child with given tag if (count($children = $this->getChildren(true)) !== 1 || $children[0]->nodeName !== $tag) { return false; } // And there should be no text nodes with real content return array_reduce($children, function ($carry, $child) { if (!$carry === false) { return false; } /* @var DOMNode $child */ return !($child->nodeType === XML_TEXT_NODE && !preg_match('/\S$/', $child->getTextContent())); }); }
[ "public", "function", "hasSingleTagInsideElement", "(", "$", "tag", ")", "{", "// There should be exactly 1 element child with given tag", "if", "(", "count", "(", "$", "children", "=", "$", "this", "->", "getChildren", "(", "true", ")", ")", "!==", "1", "||", "$", "children", "[", "0", "]", "->", "nodeName", "!==", "$", "tag", ")", "{", "return", "false", ";", "}", "// And there should be no text nodes with real content", "return", "array_reduce", "(", "$", "children", ",", "function", "(", "$", "carry", ",", "$", "child", ")", "{", "if", "(", "!", "$", "carry", "===", "false", ")", "{", "return", "false", ";", "}", "/* @var DOMNode $child */", "return", "!", "(", "$", "child", "->", "nodeType", "===", "XML_TEXT_NODE", "&&", "!", "preg_match", "(", "'/\\S$/'", ",", "$", "child", "->", "getTextContent", "(", ")", ")", ")", ";", "}", ")", ";", "}" ]
Check if this node has only whitespace and a single element with given tag or if it contains no element with given tag or more than 1 element. @param $tag string Name of tag @return bool
[ "Check", "if", "this", "node", "has", "only", "whitespace", "and", "a", "single", "element", "with", "given", "tag", "or", "if", "it", "contains", "no", "element", "with", "given", "tag", "or", "more", "than", "1", "element", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L418-L434
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.hasSingleChildBlockElement
public function hasSingleChildBlockElement() { $result = false; if ($this->hasChildNodes()) { foreach ($this->getChildren() as $child) { if (in_array($child->nodeName, $this->divToPElements)) { $result = true; } else { // If any of the hasSingleChildBlockElement calls return true, return true then. /** @var $child DOMElement */ $result = ($result || $child->hasSingleChildBlockElement()); } } } return $result; }
php
public function hasSingleChildBlockElement() { $result = false; if ($this->hasChildNodes()) { foreach ($this->getChildren() as $child) { if (in_array($child->nodeName, $this->divToPElements)) { $result = true; } else { // If any of the hasSingleChildBlockElement calls return true, return true then. /** @var $child DOMElement */ $result = ($result || $child->hasSingleChildBlockElement()); } } } return $result; }
[ "public", "function", "hasSingleChildBlockElement", "(", ")", "{", "$", "result", "=", "false", ";", "if", "(", "$", "this", "->", "hasChildNodes", "(", ")", ")", "{", "foreach", "(", "$", "this", "->", "getChildren", "(", ")", "as", "$", "child", ")", "{", "if", "(", "in_array", "(", "$", "child", "->", "nodeName", ",", "$", "this", "->", "divToPElements", ")", ")", "{", "$", "result", "=", "true", ";", "}", "else", "{", "// If any of the hasSingleChildBlockElement calls return true, return true then.", "/** @var $child DOMElement */", "$", "result", "=", "(", "$", "result", "||", "$", "child", "->", "hasSingleChildBlockElement", "(", ")", ")", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Check if the current element has a single child block element. Block elements are the ones defined in the divToPElements array. @return bool
[ "Check", "if", "the", "current", "element", "has", "a", "single", "child", "block", "element", ".", "Block", "elements", "are", "the", "ones", "defined", "in", "the", "divToPElements", "array", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L442-L458
train
andreskrey/readability.php
src/Nodes/NodeTrait.php
NodeTrait.shiftingAwareGetElementsByTagName
public function shiftingAwareGetElementsByTagName($tag) { /** @var $nodes DOMNodeList */ $nodes = $this->getElementsByTagName($tag); $count = $nodes->length; for ($i = 0; $i < $count; $i = max(++$i, 0)) { yield $nodes->item($i); // Search for all the nodes again $nodes = $this->getElementsByTagName($tag); // Subtract the amount of nodes removed from the current index $i -= $count - $nodes->length; // Subtract the amount of nodes removed from the current count $count -= ($count - $nodes->length); } }
php
public function shiftingAwareGetElementsByTagName($tag) { /** @var $nodes DOMNodeList */ $nodes = $this->getElementsByTagName($tag); $count = $nodes->length; for ($i = 0; $i < $count; $i = max(++$i, 0)) { yield $nodes->item($i); // Search for all the nodes again $nodes = $this->getElementsByTagName($tag); // Subtract the amount of nodes removed from the current index $i -= $count - $nodes->length; // Subtract the amount of nodes removed from the current count $count -= ($count - $nodes->length); } }
[ "public", "function", "shiftingAwareGetElementsByTagName", "(", "$", "tag", ")", "{", "/** @var $nodes DOMNodeList */", "$", "nodes", "=", "$", "this", "->", "getElementsByTagName", "(", "$", "tag", ")", ";", "$", "count", "=", "$", "nodes", "->", "length", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "$", "i", "=", "max", "(", "++", "$", "i", ",", "0", ")", ")", "{", "yield", "$", "nodes", "->", "item", "(", "$", "i", ")", ";", "// Search for all the nodes again", "$", "nodes", "=", "$", "this", "->", "getElementsByTagName", "(", "$", "tag", ")", ";", "// Subtract the amount of nodes removed from the current index", "$", "i", "-=", "$", "count", "-", "$", "nodes", "->", "length", ";", "// Subtract the amount of nodes removed from the current count", "$", "count", "-=", "(", "$", "count", "-", "$", "nodes", "->", "length", ")", ";", "}", "}" ]
This is a hack that overcomes the issue of node shifting when scanning and removing nodes. In the JS version of getElementsByTagName, if you remove a node it will not appear during the foreach. This does not happen in PHP DOMDocument, because if you remove a node, it will still appear but as an orphan node and will give an exception if you try to do anything with it. Shifting also occurs when converting parent nodes (like a P to a DIV), which in that case the found nodes are removed from the foreach "pool" but the internal index of the foreach is not aware and skips over nodes that never looped over. (index is at position 5, 2 nodes are removed, next one should be node 3, but the foreach tries to access node 6) This function solves this by searching for the nodes on every loop and keeping track of the count differences. Because on every loop we call getElementsByTagName again, this could cause a performance impact and should be used only when the results of the search are going to be used to remove the nodes. @param string $tag @return \Generator
[ "This", "is", "a", "hack", "that", "overcomes", "the", "issue", "of", "node", "shifting", "when", "scanning", "and", "removing", "nodes", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeTrait.php#L541-L559
train
andreskrey/readability.php
src/Readability.php
Readability.getMetadata
private function getMetadata() { $this->logger->debug('[Metadata] Retrieving metadata...'); $values = []; // property is a space-separated list of values $propertyPattern = '/\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|image)\s*/i'; // name is a single value $namePattern = '/^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|image)\s*$/i'; // Find description tags. foreach ($this->dom->getElementsByTagName('meta') as $meta) { /* @var DOMNode $meta */ $elementName = $meta->getAttribute('name'); $elementProperty = $meta->getAttribute('property'); $content = $meta->getAttribute('content'); $matches = null; $name = null; if ($elementProperty) { if (preg_match($propertyPattern, $elementProperty, $matches)) { for ($i = count($matches) - 1; $i >= 0; $i--) { // Convert to lowercase, and remove any whitespace // so we can match below. $name = preg_replace('/\s/', '', mb_strtolower($matches[$i])); // multiple authors $values[$name] = trim($content); } } } if (!$matches && $elementName && preg_match($namePattern, $elementName)) { $name = $elementName; if ($content) { // Convert to lowercase, remove any whitespace, and convert dots // to colons so we can match below. $name = preg_replace(['/\s/', '/\./'], ['', ':'], mb_strtolower($name)); $values[$name] = trim($content); } } } // get title /* * This is a very convoluted way of extracting the first matching key of the $values array * against a set of options. * * This could be easily replaced with an ugly set of isset($values['key']) or a bunch of ??s. * Will probably replace it with ??s after dropping support of PHP5.6 */ $key = current(array_intersect([ 'dc:title', 'dcterm:title', 'og:title', 'weibo:article:title', 'weibo:webpage:title', 'title', 'twitter:title' ], array_keys($values))); $this->setTitle(isset($values[$key]) ? trim($values[$key]) : null); if (!$this->getTitle()) { $this->setTitle($this->getArticleTitle()); } // get author $key = current(array_intersect([ 'dc:creator', 'dcterm:creator', 'author' ], array_keys($values))); $this->setAuthor(isset($values[$key]) ? $values[$key] : null); // get description $key = current(array_intersect([ 'dc:description', 'dcterm:description', 'og:description', 'weibo:article:description', 'weibo:webpage:description', 'description', 'twitter:description' ], array_keys($values))); $this->setExcerpt(isset($values[$key]) ? $values[$key] : null); // get main image $key = current(array_intersect([ 'og:image', 'twitter:image' ], array_keys($values))); $this->setImage(isset($values[$key]) ? $values[$key] : null); }
php
private function getMetadata() { $this->logger->debug('[Metadata] Retrieving metadata...'); $values = []; // property is a space-separated list of values $propertyPattern = '/\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|image)\s*/i'; // name is a single value $namePattern = '/^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|image)\s*$/i'; // Find description tags. foreach ($this->dom->getElementsByTagName('meta') as $meta) { /* @var DOMNode $meta */ $elementName = $meta->getAttribute('name'); $elementProperty = $meta->getAttribute('property'); $content = $meta->getAttribute('content'); $matches = null; $name = null; if ($elementProperty) { if (preg_match($propertyPattern, $elementProperty, $matches)) { for ($i = count($matches) - 1; $i >= 0; $i--) { // Convert to lowercase, and remove any whitespace // so we can match below. $name = preg_replace('/\s/', '', mb_strtolower($matches[$i])); // multiple authors $values[$name] = trim($content); } } } if (!$matches && $elementName && preg_match($namePattern, $elementName)) { $name = $elementName; if ($content) { // Convert to lowercase, remove any whitespace, and convert dots // to colons so we can match below. $name = preg_replace(['/\s/', '/\./'], ['', ':'], mb_strtolower($name)); $values[$name] = trim($content); } } } // get title /* * This is a very convoluted way of extracting the first matching key of the $values array * against a set of options. * * This could be easily replaced with an ugly set of isset($values['key']) or a bunch of ??s. * Will probably replace it with ??s after dropping support of PHP5.6 */ $key = current(array_intersect([ 'dc:title', 'dcterm:title', 'og:title', 'weibo:article:title', 'weibo:webpage:title', 'title', 'twitter:title' ], array_keys($values))); $this->setTitle(isset($values[$key]) ? trim($values[$key]) : null); if (!$this->getTitle()) { $this->setTitle($this->getArticleTitle()); } // get author $key = current(array_intersect([ 'dc:creator', 'dcterm:creator', 'author' ], array_keys($values))); $this->setAuthor(isset($values[$key]) ? $values[$key] : null); // get description $key = current(array_intersect([ 'dc:description', 'dcterm:description', 'og:description', 'weibo:article:description', 'weibo:webpage:description', 'description', 'twitter:description' ], array_keys($values))); $this->setExcerpt(isset($values[$key]) ? $values[$key] : null); // get main image $key = current(array_intersect([ 'og:image', 'twitter:image' ], array_keys($values))); $this->setImage(isset($values[$key]) ? $values[$key] : null); }
[ "private", "function", "getMetadata", "(", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'[Metadata] Retrieving metadata...'", ")", ";", "$", "values", "=", "[", "]", ";", "// property is a space-separated list of values", "$", "propertyPattern", "=", "'/\\s*(dc|dcterm|og|twitter)\\s*:\\s*(author|creator|description|title|image)\\s*/i'", ";", "// name is a single value", "$", "namePattern", "=", "'/^\\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\\s*[\\.:]\\s*)?(author|creator|description|title|image)\\s*$/i'", ";", "// Find description tags.", "foreach", "(", "$", "this", "->", "dom", "->", "getElementsByTagName", "(", "'meta'", ")", "as", "$", "meta", ")", "{", "/* @var DOMNode $meta */", "$", "elementName", "=", "$", "meta", "->", "getAttribute", "(", "'name'", ")", ";", "$", "elementProperty", "=", "$", "meta", "->", "getAttribute", "(", "'property'", ")", ";", "$", "content", "=", "$", "meta", "->", "getAttribute", "(", "'content'", ")", ";", "$", "matches", "=", "null", ";", "$", "name", "=", "null", ";", "if", "(", "$", "elementProperty", ")", "{", "if", "(", "preg_match", "(", "$", "propertyPattern", ",", "$", "elementProperty", ",", "$", "matches", ")", ")", "{", "for", "(", "$", "i", "=", "count", "(", "$", "matches", ")", "-", "1", ";", "$", "i", ">=", "0", ";", "$", "i", "--", ")", "{", "// Convert to lowercase, and remove any whitespace", "// so we can match below.", "$", "name", "=", "preg_replace", "(", "'/\\s/'", ",", "''", ",", "mb_strtolower", "(", "$", "matches", "[", "$", "i", "]", ")", ")", ";", "// multiple authors", "$", "values", "[", "$", "name", "]", "=", "trim", "(", "$", "content", ")", ";", "}", "}", "}", "if", "(", "!", "$", "matches", "&&", "$", "elementName", "&&", "preg_match", "(", "$", "namePattern", ",", "$", "elementName", ")", ")", "{", "$", "name", "=", "$", "elementName", ";", "if", "(", "$", "content", ")", "{", "// Convert to lowercase, remove any whitespace, and convert dots", "// to colons so we can match below.", "$", "name", "=", "preg_replace", "(", "[", "'/\\s/'", ",", "'/\\./'", "]", ",", "[", "''", ",", "':'", "]", ",", "mb_strtolower", "(", "$", "name", ")", ")", ";", "$", "values", "[", "$", "name", "]", "=", "trim", "(", "$", "content", ")", ";", "}", "}", "}", "// get title", "/*\n * This is a very convoluted way of extracting the first matching key of the $values array\n * against a set of options.\n *\n * This could be easily replaced with an ugly set of isset($values['key']) or a bunch of ??s.\n * Will probably replace it with ??s after dropping support of PHP5.6\n */", "$", "key", "=", "current", "(", "array_intersect", "(", "[", "'dc:title'", ",", "'dcterm:title'", ",", "'og:title'", ",", "'weibo:article:title'", ",", "'weibo:webpage:title'", ",", "'title'", ",", "'twitter:title'", "]", ",", "array_keys", "(", "$", "values", ")", ")", ")", ";", "$", "this", "->", "setTitle", "(", "isset", "(", "$", "values", "[", "$", "key", "]", ")", "?", "trim", "(", "$", "values", "[", "$", "key", "]", ")", ":", "null", ")", ";", "if", "(", "!", "$", "this", "->", "getTitle", "(", ")", ")", "{", "$", "this", "->", "setTitle", "(", "$", "this", "->", "getArticleTitle", "(", ")", ")", ";", "}", "// get author", "$", "key", "=", "current", "(", "array_intersect", "(", "[", "'dc:creator'", ",", "'dcterm:creator'", ",", "'author'", "]", ",", "array_keys", "(", "$", "values", ")", ")", ")", ";", "$", "this", "->", "setAuthor", "(", "isset", "(", "$", "values", "[", "$", "key", "]", ")", "?", "$", "values", "[", "$", "key", "]", ":", "null", ")", ";", "// get description", "$", "key", "=", "current", "(", "array_intersect", "(", "[", "'dc:description'", ",", "'dcterm:description'", ",", "'og:description'", ",", "'weibo:article:description'", ",", "'weibo:webpage:description'", ",", "'description'", ",", "'twitter:description'", "]", ",", "array_keys", "(", "$", "values", ")", ")", ")", ";", "$", "this", "->", "setExcerpt", "(", "isset", "(", "$", "values", "[", "$", "key", "]", ")", "?", "$", "values", "[", "$", "key", "]", ":", "null", ")", ";", "// get main image", "$", "key", "=", "current", "(", "array_intersect", "(", "[", "'og:image'", ",", "'twitter:image'", "]", ",", "array_keys", "(", "$", "values", ")", ")", ")", ";", "$", "this", "->", "setImage", "(", "isset", "(", "$", "values", "[", "$", "key", "]", ")", "?", "$", "values", "[", "$", "key", "]", ":", "null", ")", ";", "}" ]
Tries to guess relevant info from metadata of the html. Sets the results in the Readability properties.
[ "Tries", "to", "guess", "relevant", "info", "from", "metadata", "of", "the", "html", ".", "Sets", "the", "results", "in", "the", "Readability", "properties", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L284-L381
train
andreskrey/readability.php
src/Readability.php
Readability.getImages
public function getImages() { $result = []; if ($this->getImage()) { $result[] = $this->getImage(); } if (null == $this->getDOMDocument()) { return $result; } foreach ($this->getDOMDocument()->getElementsByTagName('img') as $img) { if ($src = $img->getAttribute('src')) { $result[] = $src; } } if ($this->configuration->getFixRelativeURLs()) { foreach ($result as &$imgSrc) { $imgSrc = $this->toAbsoluteURI($imgSrc); } } $result = array_unique(array_filter($result)); return $result; }
php
public function getImages() { $result = []; if ($this->getImage()) { $result[] = $this->getImage(); } if (null == $this->getDOMDocument()) { return $result; } foreach ($this->getDOMDocument()->getElementsByTagName('img') as $img) { if ($src = $img->getAttribute('src')) { $result[] = $src; } } if ($this->configuration->getFixRelativeURLs()) { foreach ($result as &$imgSrc) { $imgSrc = $this->toAbsoluteURI($imgSrc); } } $result = array_unique(array_filter($result)); return $result; }
[ "public", "function", "getImages", "(", ")", "{", "$", "result", "=", "[", "]", ";", "if", "(", "$", "this", "->", "getImage", "(", ")", ")", "{", "$", "result", "[", "]", "=", "$", "this", "->", "getImage", "(", ")", ";", "}", "if", "(", "null", "==", "$", "this", "->", "getDOMDocument", "(", ")", ")", "{", "return", "$", "result", ";", "}", "foreach", "(", "$", "this", "->", "getDOMDocument", "(", ")", "->", "getElementsByTagName", "(", "'img'", ")", "as", "$", "img", ")", "{", "if", "(", "$", "src", "=", "$", "img", "->", "getAttribute", "(", "'src'", ")", ")", "{", "$", "result", "[", "]", "=", "$", "src", ";", "}", "}", "if", "(", "$", "this", "->", "configuration", "->", "getFixRelativeURLs", "(", ")", ")", "{", "foreach", "(", "$", "result", "as", "&", "$", "imgSrc", ")", "{", "$", "imgSrc", "=", "$", "this", "->", "toAbsoluteURI", "(", "$", "imgSrc", ")", ";", "}", "}", "$", "result", "=", "array_unique", "(", "array_filter", "(", "$", "result", ")", ")", ";", "return", "$", "result", ";", "}" ]
Returns all the images of the parsed article. @return array
[ "Returns", "all", "the", "images", "of", "the", "parsed", "article", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L388-L414
train
andreskrey/readability.php
src/Readability.php
Readability.getMainImage
public function getMainImage() { $imgUrl = false; if ($this->getImage() !== null) { $imgUrl = $this->getImage(); } if (!$imgUrl) { foreach ($this->dom->getElementsByTagName('link') as $link) { /** @var \DOMElement $link */ /* * Check for the rel attribute, then check if the rel attribute is either img_src or image_src, and * finally check for the existence of the href attribute, which should hold the image url. */ if ($link->hasAttribute('rel') && ($link->getAttribute('rel') === 'img_src' || $link->getAttribute('rel') === 'image_src') && $link->hasAttribute('href')) { $imgUrl = $link->getAttribute('href'); break; } } } if (!empty($imgUrl) && $this->configuration->getFixRelativeURLs()) { $this->setImage($this->toAbsoluteURI($imgUrl)); } }
php
public function getMainImage() { $imgUrl = false; if ($this->getImage() !== null) { $imgUrl = $this->getImage(); } if (!$imgUrl) { foreach ($this->dom->getElementsByTagName('link') as $link) { /** @var \DOMElement $link */ /* * Check for the rel attribute, then check if the rel attribute is either img_src or image_src, and * finally check for the existence of the href attribute, which should hold the image url. */ if ($link->hasAttribute('rel') && ($link->getAttribute('rel') === 'img_src' || $link->getAttribute('rel') === 'image_src') && $link->hasAttribute('href')) { $imgUrl = $link->getAttribute('href'); break; } } } if (!empty($imgUrl) && $this->configuration->getFixRelativeURLs()) { $this->setImage($this->toAbsoluteURI($imgUrl)); } }
[ "public", "function", "getMainImage", "(", ")", "{", "$", "imgUrl", "=", "false", ";", "if", "(", "$", "this", "->", "getImage", "(", ")", "!==", "null", ")", "{", "$", "imgUrl", "=", "$", "this", "->", "getImage", "(", ")", ";", "}", "if", "(", "!", "$", "imgUrl", ")", "{", "foreach", "(", "$", "this", "->", "dom", "->", "getElementsByTagName", "(", "'link'", ")", "as", "$", "link", ")", "{", "/** @var \\DOMElement $link */", "/*\n * Check for the rel attribute, then check if the rel attribute is either img_src or image_src, and\n * finally check for the existence of the href attribute, which should hold the image url.\n */", "if", "(", "$", "link", "->", "hasAttribute", "(", "'rel'", ")", "&&", "(", "$", "link", "->", "getAttribute", "(", "'rel'", ")", "===", "'img_src'", "||", "$", "link", "->", "getAttribute", "(", "'rel'", ")", "===", "'image_src'", ")", "&&", "$", "link", "->", "hasAttribute", "(", "'href'", ")", ")", "{", "$", "imgUrl", "=", "$", "link", "->", "getAttribute", "(", "'href'", ")", ";", "break", ";", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "imgUrl", ")", "&&", "$", "this", "->", "configuration", "->", "getFixRelativeURLs", "(", ")", ")", "{", "$", "this", "->", "setImage", "(", "$", "this", "->", "toAbsoluteURI", "(", "$", "imgUrl", ")", ")", ";", "}", "}" ]
Tries to get the main article image. Will only update the metadata if the getMetadata function couldn't find a correct image.
[ "Tries", "to", "get", "the", "main", "article", "image", ".", "Will", "only", "update", "the", "metadata", "if", "the", "getMetadata", "function", "couldn", "t", "find", "a", "correct", "image", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L420-L445
train
andreskrey/readability.php
src/Readability.php
Readability.toAbsoluteURI
private function toAbsoluteURI($uri) { list($pathBase, $scheme, $prePath) = $this->getPathInfo($this->configuration->getOriginalURL()); // If this is already an absolute URI, return it. if (preg_match('/^[a-zA-Z][a-zA-Z0-9\+\-\.]*:/', $uri)) { return $uri; } // Scheme-rooted relative URI. if (substr($uri, 0, 2) === '//') { return $scheme . '://' . substr($uri, 2); } // Prepath-rooted relative URI. if (substr($uri, 0, 1) === '/') { return $prePath . $uri; } // Dotslash relative URI. if (strpos($uri, './') === 0) { return $pathBase . substr($uri, 2); } // Ignore hash URIs: if (substr($uri, 0, 1) === '#') { return $uri; } // Standard relative URI; add entire path. pathBase already includes a // trailing "/". return $pathBase . $uri; }
php
private function toAbsoluteURI($uri) { list($pathBase, $scheme, $prePath) = $this->getPathInfo($this->configuration->getOriginalURL()); // If this is already an absolute URI, return it. if (preg_match('/^[a-zA-Z][a-zA-Z0-9\+\-\.]*:/', $uri)) { return $uri; } // Scheme-rooted relative URI. if (substr($uri, 0, 2) === '//') { return $scheme . '://' . substr($uri, 2); } // Prepath-rooted relative URI. if (substr($uri, 0, 1) === '/') { return $prePath . $uri; } // Dotslash relative URI. if (strpos($uri, './') === 0) { return $pathBase . substr($uri, 2); } // Ignore hash URIs: if (substr($uri, 0, 1) === '#') { return $uri; } // Standard relative URI; add entire path. pathBase already includes a // trailing "/". return $pathBase . $uri; }
[ "private", "function", "toAbsoluteURI", "(", "$", "uri", ")", "{", "list", "(", "$", "pathBase", ",", "$", "scheme", ",", "$", "prePath", ")", "=", "$", "this", "->", "getPathInfo", "(", "$", "this", "->", "configuration", "->", "getOriginalURL", "(", ")", ")", ";", "// If this is already an absolute URI, return it.", "if", "(", "preg_match", "(", "'/^[a-zA-Z][a-zA-Z0-9\\+\\-\\.]*:/'", ",", "$", "uri", ")", ")", "{", "return", "$", "uri", ";", "}", "// Scheme-rooted relative URI.", "if", "(", "substr", "(", "$", "uri", ",", "0", ",", "2", ")", "===", "'//'", ")", "{", "return", "$", "scheme", ".", "'://'", ".", "substr", "(", "$", "uri", ",", "2", ")", ";", "}", "// Prepath-rooted relative URI.", "if", "(", "substr", "(", "$", "uri", ",", "0", ",", "1", ")", "===", "'/'", ")", "{", "return", "$", "prePath", ".", "$", "uri", ";", "}", "// Dotslash relative URI.", "if", "(", "strpos", "(", "$", "uri", ",", "'./'", ")", "===", "0", ")", "{", "return", "$", "pathBase", ".", "substr", "(", "$", "uri", ",", "2", ")", ";", "}", "// Ignore hash URIs:", "if", "(", "substr", "(", "$", "uri", ",", "0", ",", "1", ")", "===", "'#'", ")", "{", "return", "$", "uri", ";", "}", "// Standard relative URI; add entire path. pathBase already includes a", "// trailing \"/\".", "return", "$", "pathBase", ".", "$", "uri", ";", "}" ]
Convert URI to an absolute URI. @param $uri string URI to convert @return string
[ "Convert", "URI", "to", "an", "absolute", "URI", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L558-L589
train
andreskrey/readability.php
src/Readability.php
Readability.getPathInfo
public function getPathInfo($url) { // Check for base URLs if ($this->dom->baseURI !== null) { if (substr($this->dom->baseURI, 0, 1) === '/') { // URLs starting with '/' override completely the URL defined in the link $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . $this->dom->baseURI; } else { // Otherwise just prepend the base to the actual path $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . dirname(parse_url($url, PHP_URL_PATH)) . '/' . rtrim($this->dom->baseURI, '/') . '/'; } } else { $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . dirname(parse_url($url, PHP_URL_PATH)) . '/'; } $scheme = parse_url($pathBase, PHP_URL_SCHEME); $prePath = $scheme . '://' . parse_url($pathBase, PHP_URL_HOST); return [$pathBase, $scheme, $prePath]; }
php
public function getPathInfo($url) { // Check for base URLs if ($this->dom->baseURI !== null) { if (substr($this->dom->baseURI, 0, 1) === '/') { // URLs starting with '/' override completely the URL defined in the link $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . $this->dom->baseURI; } else { // Otherwise just prepend the base to the actual path $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . dirname(parse_url($url, PHP_URL_PATH)) . '/' . rtrim($this->dom->baseURI, '/') . '/'; } } else { $pathBase = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . dirname(parse_url($url, PHP_URL_PATH)) . '/'; } $scheme = parse_url($pathBase, PHP_URL_SCHEME); $prePath = $scheme . '://' . parse_url($pathBase, PHP_URL_HOST); return [$pathBase, $scheme, $prePath]; }
[ "public", "function", "getPathInfo", "(", "$", "url", ")", "{", "// Check for base URLs", "if", "(", "$", "this", "->", "dom", "->", "baseURI", "!==", "null", ")", "{", "if", "(", "substr", "(", "$", "this", "->", "dom", "->", "baseURI", ",", "0", ",", "1", ")", "===", "'/'", ")", "{", "// URLs starting with '/' override completely the URL defined in the link", "$", "pathBase", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_SCHEME", ")", ".", "'://'", ".", "parse_url", "(", "$", "url", ",", "PHP_URL_HOST", ")", ".", "$", "this", "->", "dom", "->", "baseURI", ";", "}", "else", "{", "// Otherwise just prepend the base to the actual path", "$", "pathBase", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_SCHEME", ")", ".", "'://'", ".", "parse_url", "(", "$", "url", ",", "PHP_URL_HOST", ")", ".", "dirname", "(", "parse_url", "(", "$", "url", ",", "PHP_URL_PATH", ")", ")", ".", "'/'", ".", "rtrim", "(", "$", "this", "->", "dom", "->", "baseURI", ",", "'/'", ")", ".", "'/'", ";", "}", "}", "else", "{", "$", "pathBase", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_SCHEME", ")", ".", "'://'", ".", "parse_url", "(", "$", "url", ",", "PHP_URL_HOST", ")", ".", "dirname", "(", "parse_url", "(", "$", "url", ",", "PHP_URL_PATH", ")", ")", ".", "'/'", ";", "}", "$", "scheme", "=", "parse_url", "(", "$", "pathBase", ",", "PHP_URL_SCHEME", ")", ";", "$", "prePath", "=", "$", "scheme", ".", "'://'", ".", "parse_url", "(", "$", "pathBase", ",", "PHP_URL_HOST", ")", ";", "return", "[", "$", "pathBase", ",", "$", "scheme", ",", "$", "prePath", "]", ";", "}" ]
Returns full path info of an URL. @param string $url @return array [$pathBase, $scheme, $prePath]
[ "Returns", "full", "path", "info", "of", "an", "URL", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L598-L617
train
andreskrey/readability.php
src/Readability.php
Readability.checkByline
private function checkByline($node, $matchString) { if (!$this->configuration->getArticleByLine()) { return false; } /* * Check if the byline is already set */ if ($this->getAuthor()) { return false; } $rel = $node->getAttribute('rel'); if ($rel === 'author' || preg_match(NodeUtility::$regexps['byline'], $matchString) && $this->isValidByline($node->getTextContent())) { $this->logger->info(sprintf('[Metadata] Found article author: \'%s\'', $node->getTextContent())); $this->setAuthor(trim($node->getTextContent())); return true; } return false; }
php
private function checkByline($node, $matchString) { if (!$this->configuration->getArticleByLine()) { return false; } /* * Check if the byline is already set */ if ($this->getAuthor()) { return false; } $rel = $node->getAttribute('rel'); if ($rel === 'author' || preg_match(NodeUtility::$regexps['byline'], $matchString) && $this->isValidByline($node->getTextContent())) { $this->logger->info(sprintf('[Metadata] Found article author: \'%s\'', $node->getTextContent())); $this->setAuthor(trim($node->getTextContent())); return true; } return false; }
[ "private", "function", "checkByline", "(", "$", "node", ",", "$", "matchString", ")", "{", "if", "(", "!", "$", "this", "->", "configuration", "->", "getArticleByLine", "(", ")", ")", "{", "return", "false", ";", "}", "/*\n * Check if the byline is already set\n */", "if", "(", "$", "this", "->", "getAuthor", "(", ")", ")", "{", "return", "false", ";", "}", "$", "rel", "=", "$", "node", "->", "getAttribute", "(", "'rel'", ")", ";", "if", "(", "$", "rel", "===", "'author'", "||", "preg_match", "(", "NodeUtility", "::", "$", "regexps", "[", "'byline'", "]", ",", "$", "matchString", ")", "&&", "$", "this", "->", "isValidByline", "(", "$", "node", "->", "getTextContent", "(", ")", ")", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "sprintf", "(", "'[Metadata] Found article author: \\'%s\\''", ",", "$", "node", "->", "getTextContent", "(", ")", ")", ")", ";", "$", "this", "->", "setAuthor", "(", "trim", "(", "$", "node", "->", "getTextContent", "(", ")", ")", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks if the node is a byline. @param DOMNode $node @param string $matchString @return bool
[ "Checks", "if", "the", "node", "is", "a", "byline", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L750-L773
train
andreskrey/readability.php
src/Readability.php
Readability.isValidByline
private function isValidByline($text) { if (gettype($text) == 'string') { $byline = trim($text); return (mb_strlen($byline) > 0) && (mb_strlen($byline) < 100); } return false; }
php
private function isValidByline($text) { if (gettype($text) == 'string') { $byline = trim($text); return (mb_strlen($byline) > 0) && (mb_strlen($byline) < 100); } return false; }
[ "private", "function", "isValidByline", "(", "$", "text", ")", "{", "if", "(", "gettype", "(", "$", "text", ")", "==", "'string'", ")", "{", "$", "byline", "=", "trim", "(", "$", "text", ")", ";", "return", "(", "mb_strlen", "(", "$", "byline", ")", ">", "0", ")", "&&", "(", "mb_strlen", "(", "$", "byline", ")", "<", "100", ")", ";", "}", "return", "false", ";", "}" ]
Checks the validity of a byLine. Based on string length. @param string $text @return bool
[ "Checks", "the", "validity", "of", "a", "byLine", ".", "Based", "on", "string", "length", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L782-L791
train
andreskrey/readability.php
src/Readability.php
Readability.removeScripts
private function removeScripts(DOMDocument $dom) { foreach (['script', 'noscript'] as $tag) { $nodes = $dom->getElementsByTagName($tag); foreach (iterator_to_array($nodes) as $node) { NodeUtility::removeNode($node); } } }
php
private function removeScripts(DOMDocument $dom) { foreach (['script', 'noscript'] as $tag) { $nodes = $dom->getElementsByTagName($tag); foreach (iterator_to_array($nodes) as $node) { NodeUtility::removeNode($node); } } }
[ "private", "function", "removeScripts", "(", "DOMDocument", "$", "dom", ")", "{", "foreach", "(", "[", "'script'", ",", "'noscript'", "]", "as", "$", "tag", ")", "{", "$", "nodes", "=", "$", "dom", "->", "getElementsByTagName", "(", "$", "tag", ")", ";", "foreach", "(", "iterator_to_array", "(", "$", "nodes", ")", "as", "$", "node", ")", "{", "NodeUtility", "::", "removeNode", "(", "$", "node", ")", ";", "}", "}", "}" ]
Removes all the scripts of the html. @param DOMDocument $dom
[ "Removes", "all", "the", "scripts", "of", "the", "html", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L798-L806
train
andreskrey/readability.php
src/Readability.php
Readability.prepDocument
private function prepDocument(DOMDocument $dom) { $this->logger->info('[PrepDocument] Preparing document for parsing...'); foreach ($dom->shiftingAwareGetElementsByTagName('br') as $br) { $next = $br->nextSibling; /* * Whether 2 or more <br> elements have been found and replaced with a * <p> block. */ $replaced = false; /* * If we find a <br> chain, remove the <br>s until we hit another element * or non-whitespace. This leaves behind the first <br> in the chain * (which will be replaced with a <p> later). */ while (($next = NodeUtility::nextElement($next)) && ($next->nodeName === 'br')) { $this->logger->debug('[PrepDocument] Removing chain of BR nodes...'); $replaced = true; $brSibling = $next->nextSibling; $next->parentNode->removeChild($next); $next = $brSibling; } /* * If we removed a <br> chain, replace the remaining <br> with a <p>. Add * all sibling nodes as children of the <p> until we hit another <br> * chain. */ if ($replaced) { $p = $dom->createElement('p'); $br->parentNode->replaceChild($p, $br); $next = $p->nextSibling; while ($next) { // If we've hit another <br><br>, we're done adding children to this <p>. if ($next->nodeName === 'br') { $nextElem = NodeUtility::nextElement($next->nextSibling); if ($nextElem && $nextElem->nodeName === 'br') { break; } } if (!$next->isPhrasingContent()) { break; } $this->logger->debug('[PrepDocument] Replacing BR with a P node...'); // Otherwise, make this node a child of the new <p>. $sibling = $next->nextSibling; $p->appendChild($next); $next = $sibling; } while ($p->lastChild && $p->lastChild->isWhitespace()) { $p->removeChild($p->lastChild); } if ($p->parentNode->tagName === 'p') { NodeUtility::setNodeTag($p->parentNode, 'div'); } } } // Replace font tags with span $fonts = $dom->getElementsByTagName('font'); $length = $fonts->length; for ($i = 0; $i < $length; $i++) { $this->logger->debug('[PrepDocument] Converting font tag into a span tag.'); $font = $fonts->item($length - 1 - $i); NodeUtility::setNodeTag($font, 'span'); } }
php
private function prepDocument(DOMDocument $dom) { $this->logger->info('[PrepDocument] Preparing document for parsing...'); foreach ($dom->shiftingAwareGetElementsByTagName('br') as $br) { $next = $br->nextSibling; /* * Whether 2 or more <br> elements have been found and replaced with a * <p> block. */ $replaced = false; /* * If we find a <br> chain, remove the <br>s until we hit another element * or non-whitespace. This leaves behind the first <br> in the chain * (which will be replaced with a <p> later). */ while (($next = NodeUtility::nextElement($next)) && ($next->nodeName === 'br')) { $this->logger->debug('[PrepDocument] Removing chain of BR nodes...'); $replaced = true; $brSibling = $next->nextSibling; $next->parentNode->removeChild($next); $next = $brSibling; } /* * If we removed a <br> chain, replace the remaining <br> with a <p>. Add * all sibling nodes as children of the <p> until we hit another <br> * chain. */ if ($replaced) { $p = $dom->createElement('p'); $br->parentNode->replaceChild($p, $br); $next = $p->nextSibling; while ($next) { // If we've hit another <br><br>, we're done adding children to this <p>. if ($next->nodeName === 'br') { $nextElem = NodeUtility::nextElement($next->nextSibling); if ($nextElem && $nextElem->nodeName === 'br') { break; } } if (!$next->isPhrasingContent()) { break; } $this->logger->debug('[PrepDocument] Replacing BR with a P node...'); // Otherwise, make this node a child of the new <p>. $sibling = $next->nextSibling; $p->appendChild($next); $next = $sibling; } while ($p->lastChild && $p->lastChild->isWhitespace()) { $p->removeChild($p->lastChild); } if ($p->parentNode->tagName === 'p') { NodeUtility::setNodeTag($p->parentNode, 'div'); } } } // Replace font tags with span $fonts = $dom->getElementsByTagName('font'); $length = $fonts->length; for ($i = 0; $i < $length; $i++) { $this->logger->debug('[PrepDocument] Converting font tag into a span tag.'); $font = $fonts->item($length - 1 - $i); NodeUtility::setNodeTag($font, 'span'); } }
[ "private", "function", "prepDocument", "(", "DOMDocument", "$", "dom", ")", "{", "$", "this", "->", "logger", "->", "info", "(", "'[PrepDocument] Preparing document for parsing...'", ")", ";", "foreach", "(", "$", "dom", "->", "shiftingAwareGetElementsByTagName", "(", "'br'", ")", "as", "$", "br", ")", "{", "$", "next", "=", "$", "br", "->", "nextSibling", ";", "/*\n * Whether 2 or more <br> elements have been found and replaced with a\n * <p> block.\n */", "$", "replaced", "=", "false", ";", "/*\n * If we find a <br> chain, remove the <br>s until we hit another element\n * or non-whitespace. This leaves behind the first <br> in the chain\n * (which will be replaced with a <p> later).\n */", "while", "(", "(", "$", "next", "=", "NodeUtility", "::", "nextElement", "(", "$", "next", ")", ")", "&&", "(", "$", "next", "->", "nodeName", "===", "'br'", ")", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'[PrepDocument] Removing chain of BR nodes...'", ")", ";", "$", "replaced", "=", "true", ";", "$", "brSibling", "=", "$", "next", "->", "nextSibling", ";", "$", "next", "->", "parentNode", "->", "removeChild", "(", "$", "next", ")", ";", "$", "next", "=", "$", "brSibling", ";", "}", "/*\n * If we removed a <br> chain, replace the remaining <br> with a <p>. Add\n * all sibling nodes as children of the <p> until we hit another <br>\n * chain.\n */", "if", "(", "$", "replaced", ")", "{", "$", "p", "=", "$", "dom", "->", "createElement", "(", "'p'", ")", ";", "$", "br", "->", "parentNode", "->", "replaceChild", "(", "$", "p", ",", "$", "br", ")", ";", "$", "next", "=", "$", "p", "->", "nextSibling", ";", "while", "(", "$", "next", ")", "{", "// If we've hit another <br><br>, we're done adding children to this <p>.", "if", "(", "$", "next", "->", "nodeName", "===", "'br'", ")", "{", "$", "nextElem", "=", "NodeUtility", "::", "nextElement", "(", "$", "next", "->", "nextSibling", ")", ";", "if", "(", "$", "nextElem", "&&", "$", "nextElem", "->", "nodeName", "===", "'br'", ")", "{", "break", ";", "}", "}", "if", "(", "!", "$", "next", "->", "isPhrasingContent", "(", ")", ")", "{", "break", ";", "}", "$", "this", "->", "logger", "->", "debug", "(", "'[PrepDocument] Replacing BR with a P node...'", ")", ";", "// Otherwise, make this node a child of the new <p>.", "$", "sibling", "=", "$", "next", "->", "nextSibling", ";", "$", "p", "->", "appendChild", "(", "$", "next", ")", ";", "$", "next", "=", "$", "sibling", ";", "}", "while", "(", "$", "p", "->", "lastChild", "&&", "$", "p", "->", "lastChild", "->", "isWhitespace", "(", ")", ")", "{", "$", "p", "->", "removeChild", "(", "$", "p", "->", "lastChild", ")", ";", "}", "if", "(", "$", "p", "->", "parentNode", "->", "tagName", "===", "'p'", ")", "{", "NodeUtility", "::", "setNodeTag", "(", "$", "p", "->", "parentNode", ",", "'div'", ")", ";", "}", "}", "}", "// Replace font tags with span", "$", "fonts", "=", "$", "dom", "->", "getElementsByTagName", "(", "'font'", ")", ";", "$", "length", "=", "$", "fonts", "->", "length", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "++", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'[PrepDocument] Converting font tag into a span tag.'", ")", ";", "$", "font", "=", "$", "fonts", "->", "item", "(", "$", "length", "-", "1", "-", "$", "i", ")", ";", "NodeUtility", "::", "setNodeTag", "(", "$", "font", ",", "'span'", ")", ";", "}", "}" ]
Prepares the document for parsing. @param DOMDocument $dom
[ "Prepares", "the", "document", "for", "parsing", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L813-L890
train
andreskrey/readability.php
src/Readability.php
Readability._cleanStyles
public function _cleanStyles($node) { if (property_exists($node, 'tagName') && $node->tagName === 'svg') { return; } // Do not bother if there's no method to remove an attribute if (method_exists($node, 'removeAttribute')) { $presentational_attributes = ['align', 'background', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'frame', 'hspace', 'rules', 'style', 'valign', 'vspace']; // Remove `style` and deprecated presentational attributes foreach ($presentational_attributes as $presentational_attribute) { $node->removeAttribute($presentational_attribute); } $deprecated_size_attribute_elems = ['table', 'th', 'td', 'hr', 'pre']; if (property_exists($node, 'tagName') && in_array($node->tagName, $deprecated_size_attribute_elems)) { $node->removeAttribute('width'); $node->removeAttribute('height'); } } $cur = $node->firstChild; while ($cur !== null) { $this->_cleanStyles($cur); $cur = $cur->nextSibling; } }
php
public function _cleanStyles($node) { if (property_exists($node, 'tagName') && $node->tagName === 'svg') { return; } // Do not bother if there's no method to remove an attribute if (method_exists($node, 'removeAttribute')) { $presentational_attributes = ['align', 'background', 'bgcolor', 'border', 'cellpadding', 'cellspacing', 'frame', 'hspace', 'rules', 'style', 'valign', 'vspace']; // Remove `style` and deprecated presentational attributes foreach ($presentational_attributes as $presentational_attribute) { $node->removeAttribute($presentational_attribute); } $deprecated_size_attribute_elems = ['table', 'th', 'td', 'hr', 'pre']; if (property_exists($node, 'tagName') && in_array($node->tagName, $deprecated_size_attribute_elems)) { $node->removeAttribute('width'); $node->removeAttribute('height'); } } $cur = $node->firstChild; while ($cur !== null) { $this->_cleanStyles($cur); $cur = $cur->nextSibling; } }
[ "public", "function", "_cleanStyles", "(", "$", "node", ")", "{", "if", "(", "property_exists", "(", "$", "node", ",", "'tagName'", ")", "&&", "$", "node", "->", "tagName", "===", "'svg'", ")", "{", "return", ";", "}", "// Do not bother if there's no method to remove an attribute", "if", "(", "method_exists", "(", "$", "node", ",", "'removeAttribute'", ")", ")", "{", "$", "presentational_attributes", "=", "[", "'align'", ",", "'background'", ",", "'bgcolor'", ",", "'border'", ",", "'cellpadding'", ",", "'cellspacing'", ",", "'frame'", ",", "'hspace'", ",", "'rules'", ",", "'style'", ",", "'valign'", ",", "'vspace'", "]", ";", "// Remove `style` and deprecated presentational attributes", "foreach", "(", "$", "presentational_attributes", "as", "$", "presentational_attribute", ")", "{", "$", "node", "->", "removeAttribute", "(", "$", "presentational_attribute", ")", ";", "}", "$", "deprecated_size_attribute_elems", "=", "[", "'table'", ",", "'th'", ",", "'td'", ",", "'hr'", ",", "'pre'", "]", ";", "if", "(", "property_exists", "(", "$", "node", ",", "'tagName'", ")", "&&", "in_array", "(", "$", "node", "->", "tagName", ",", "$", "deprecated_size_attribute_elems", ")", ")", "{", "$", "node", "->", "removeAttribute", "(", "'width'", ")", ";", "$", "node", "->", "removeAttribute", "(", "'height'", ")", ";", "}", "}", "$", "cur", "=", "$", "node", "->", "firstChild", ";", "while", "(", "$", "cur", "!==", "null", ")", "{", "$", "this", "->", "_cleanStyles", "(", "$", "cur", ")", ";", "$", "cur", "=", "$", "cur", "->", "nextSibling", ";", "}", "}" ]
Remove the style attribute on every e and under. @param $node DOMDocument|DOMNode
[ "Remove", "the", "style", "attribute", "on", "every", "e", "and", "under", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L1350-L1376
train
andreskrey/readability.php
src/Readability.php
Readability._cleanClasses
public function _cleanClasses($node) { if ($node->getAttribute('class') !== '') { $node->removeAttribute('class'); } for ($node = $node->firstChild; $node !== null; $node = $node->nextSibling) { $this->_cleanClasses($node); } }
php
public function _cleanClasses($node) { if ($node->getAttribute('class') !== '') { $node->removeAttribute('class'); } for ($node = $node->firstChild; $node !== null; $node = $node->nextSibling) { $this->_cleanClasses($node); } }
[ "public", "function", "_cleanClasses", "(", "$", "node", ")", "{", "if", "(", "$", "node", "->", "getAttribute", "(", "'class'", ")", "!==", "''", ")", "{", "$", "node", "->", "removeAttribute", "(", "'class'", ")", ";", "}", "for", "(", "$", "node", "=", "$", "node", "->", "firstChild", ";", "$", "node", "!==", "null", ";", "$", "node", "=", "$", "node", "->", "nextSibling", ")", "{", "$", "this", "->", "_cleanClasses", "(", "$", "node", ")", ";", "}", "}" ]
Removes the class="" attribute from every element in the given subtree. Readability.js has a special filter to avoid cleaning the classes that the algorithm adds. We don't add classes here so no need to filter those. @param DOMDocument|DOMNode $node @return void
[ "Removes", "the", "class", "=", "attribute", "from", "every", "element", "in", "the", "given", "subtree", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Readability.php#L1594-L1603
train
andreskrey/readability.php
src/Configuration.php
Configuration.toArray
public function toArray() { $out = []; foreach ($this as $key => $value) { $getter = sprintf('get%s', $key); if (!is_object($value) && method_exists($this, $getter)) { $out[$key] = call_user_func([$this, $getter]); } } return $out; }
php
public function toArray() { $out = []; foreach ($this as $key => $value) { $getter = sprintf('get%s', $key); if (!is_object($value) && method_exists($this, $getter)) { $out[$key] = call_user_func([$this, $getter]); } } return $out; }
[ "public", "function", "toArray", "(", ")", "{", "$", "out", "=", "[", "]", ";", "foreach", "(", "$", "this", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "getter", "=", "sprintf", "(", "'get%s'", ",", "$", "key", ")", ";", "if", "(", "!", "is_object", "(", "$", "value", ")", "&&", "method_exists", "(", "$", "this", ",", "$", "getter", ")", ")", "{", "$", "out", "[", "$", "key", "]", "=", "call_user_func", "(", "[", "$", "this", ",", "$", "getter", "]", ")", ";", "}", "}", "return", "$", "out", ";", "}" ]
Returns an array-representation of configuration. @return array
[ "Returns", "an", "array", "-", "representation", "of", "configuration", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Configuration.php#L91-L102
train
andreskrey/readability.php
src/Nodes/NodeUtility.php
NodeUtility.nextElement
public static function nextElement($node) { $next = $node; while ($next && $next->nodeType !== XML_ELEMENT_NODE && $next->isWhitespace()) { $next = $next->nextSibling; } return $next; }
php
public static function nextElement($node) { $next = $node; while ($next && $next->nodeType !== XML_ELEMENT_NODE && $next->isWhitespace()) { $next = $next->nextSibling; } return $next; }
[ "public", "static", "function", "nextElement", "(", "$", "node", ")", "{", "$", "next", "=", "$", "node", ";", "while", "(", "$", "next", "&&", "$", "next", "->", "nodeType", "!==", "XML_ELEMENT_NODE", "&&", "$", "next", "->", "isWhitespace", "(", ")", ")", "{", "$", "next", "=", "$", "next", "->", "nextSibling", ";", "}", "return", "$", "next", ";", "}" ]
Imported from the Element class on league\html-to-markdown. @param $node @return DOMElement
[ "Imported", "from", "the", "Element", "class", "on", "league", "\\", "html", "-", "to", "-", "markdown", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeUtility.php#L44-L54
train
andreskrey/readability.php
src/Nodes/NodeUtility.php
NodeUtility.setNodeTag
public static function setNodeTag($node, $value, $importAttributes = true) { $new = new DOMDocument('1.0', 'utf-8'); $new->appendChild($new->createElement($value)); $children = $node->childNodes; /** @var $children \DOMNodeList $i */ for ($i = 0; $i < $children->length; $i++) { $import = $new->importNode($children->item($i), true); $new->firstChild->appendChild($import); } if ($importAttributes) { // Import attributes from the original node. foreach ($node->attributes as $attribute) { $new->firstChild->setAttribute($attribute->nodeName, $attribute->nodeValue); } } // The import must be done on the firstChild of $new, since $new is a DOMDocument and not a DOMElement. $import = $node->ownerDocument->importNode($new->firstChild, true); $node->parentNode->replaceChild($import, $node); return $import; }
php
public static function setNodeTag($node, $value, $importAttributes = true) { $new = new DOMDocument('1.0', 'utf-8'); $new->appendChild($new->createElement($value)); $children = $node->childNodes; /** @var $children \DOMNodeList $i */ for ($i = 0; $i < $children->length; $i++) { $import = $new->importNode($children->item($i), true); $new->firstChild->appendChild($import); } if ($importAttributes) { // Import attributes from the original node. foreach ($node->attributes as $attribute) { $new->firstChild->setAttribute($attribute->nodeName, $attribute->nodeValue); } } // The import must be done on the firstChild of $new, since $new is a DOMDocument and not a DOMElement. $import = $node->ownerDocument->importNode($new->firstChild, true); $node->parentNode->replaceChild($import, $node); return $import; }
[ "public", "static", "function", "setNodeTag", "(", "$", "node", ",", "$", "value", ",", "$", "importAttributes", "=", "true", ")", "{", "$", "new", "=", "new", "DOMDocument", "(", "'1.0'", ",", "'utf-8'", ")", ";", "$", "new", "->", "appendChild", "(", "$", "new", "->", "createElement", "(", "$", "value", ")", ")", ";", "$", "children", "=", "$", "node", "->", "childNodes", ";", "/** @var $children \\DOMNodeList $i */", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "children", "->", "length", ";", "$", "i", "++", ")", "{", "$", "import", "=", "$", "new", "->", "importNode", "(", "$", "children", "->", "item", "(", "$", "i", ")", ",", "true", ")", ";", "$", "new", "->", "firstChild", "->", "appendChild", "(", "$", "import", ")", ";", "}", "if", "(", "$", "importAttributes", ")", "{", "// Import attributes from the original node.", "foreach", "(", "$", "node", "->", "attributes", "as", "$", "attribute", ")", "{", "$", "new", "->", "firstChild", "->", "setAttribute", "(", "$", "attribute", "->", "nodeName", ",", "$", "attribute", "->", "nodeValue", ")", ";", "}", "}", "// The import must be done on the firstChild of $new, since $new is a DOMDocument and not a DOMElement.", "$", "import", "=", "$", "node", "->", "ownerDocument", "->", "importNode", "(", "$", "new", "->", "firstChild", ",", "true", ")", ";", "$", "node", "->", "parentNode", "->", "replaceChild", "(", "$", "import", ",", "$", "node", ")", ";", "return", "$", "import", ";", "}" ]
Changes the node tag name. Since tagName on DOMElement is a read only value, this must be done creating a new element with the new tag name and importing it to the main DOMDocument. @param DOMNode $node @param string $value @param bool $importAttributes @return DOMNode
[ "Changes", "the", "node", "tag", "name", ".", "Since", "tagName", "on", "DOMElement", "is", "a", "read", "only", "value", "this", "must", "be", "done", "creating", "a", "new", "element", "with", "the", "new", "tag", "name", "and", "importing", "it", "to", "the", "main", "DOMDocument", "." ]
23f21756562adbd04c172d14995802030bf81595
https://github.com/andreskrey/readability.php/blob/23f21756562adbd04c172d14995802030bf81595/src/Nodes/NodeUtility.php#L66-L90
train
Rebilly/rebilly-php
src/Rest/Factory.php
Factory.generatePatterns
private function generatePatterns() { foreach ($this->builders as $uri => $builder) { $pattern = '/' . ltrim($uri, '/'); if (preg_match_all('/{[\w]+}/i', $uri, $matches)) { foreach (array_unique($matches[0]) as $match) { $pattern = str_replace($match, '[\w\d\@_~\-\.]+', $pattern); } } $this->patterns['#^' . $pattern . '$#i'] = $uri; } // Sort patterns to ensure that longer more precisely pattern comes first krsort($this->patterns); }
php
private function generatePatterns() { foreach ($this->builders as $uri => $builder) { $pattern = '/' . ltrim($uri, '/'); if (preg_match_all('/{[\w]+}/i', $uri, $matches)) { foreach (array_unique($matches[0]) as $match) { $pattern = str_replace($match, '[\w\d\@_~\-\.]+', $pattern); } } $this->patterns['#^' . $pattern . '$#i'] = $uri; } // Sort patterns to ensure that longer more precisely pattern comes first krsort($this->patterns); }
[ "private", "function", "generatePatterns", "(", ")", "{", "foreach", "(", "$", "this", "->", "builders", "as", "$", "uri", "=>", "$", "builder", ")", "{", "$", "pattern", "=", "'/'", ".", "ltrim", "(", "$", "uri", ",", "'/'", ")", ";", "if", "(", "preg_match_all", "(", "'/{[\\w]+}/i'", ",", "$", "uri", ",", "$", "matches", ")", ")", "{", "foreach", "(", "array_unique", "(", "$", "matches", "[", "0", "]", ")", "as", "$", "match", ")", "{", "$", "pattern", "=", "str_replace", "(", "$", "match", ",", "'[\\w\\d\\@_~\\-\\.]+'", ",", "$", "pattern", ")", ";", "}", "}", "$", "this", "->", "patterns", "[", "'#^'", ".", "$", "pattern", ".", "'$#i'", "]", "=", "$", "uri", ";", "}", "// Sort patterns to ensure that longer more precisely pattern comes first", "krsort", "(", "$", "this", "->", "patterns", ")", ";", "}" ]
Generate regex patterns for URI templates.
[ "Generate", "regex", "patterns", "for", "URI", "templates", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/Rest/Factory.php#L43-L59
train
Rebilly/rebilly-php
src/Rest/Factory.php
Factory.create
public function create($uri, $content) { $uri = '/' . trim($uri, '/'); foreach ($this->patterns as $pattern => $key) { if (preg_match($pattern, $uri)) { return call_user_func($this->builders[$key], (array) $content); } } throw new RuntimeException(sprintf('Cannot create resource by URI "%s"', $uri)); }
php
public function create($uri, $content) { $uri = '/' . trim($uri, '/'); foreach ($this->patterns as $pattern => $key) { if (preg_match($pattern, $uri)) { return call_user_func($this->builders[$key], (array) $content); } } throw new RuntimeException(sprintf('Cannot create resource by URI "%s"', $uri)); }
[ "public", "function", "create", "(", "$", "uri", ",", "$", "content", ")", "{", "$", "uri", "=", "'/'", ".", "trim", "(", "$", "uri", ",", "'/'", ")", ";", "foreach", "(", "$", "this", "->", "patterns", "as", "$", "pattern", "=>", "$", "key", ")", "{", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "uri", ")", ")", "{", "return", "call_user_func", "(", "$", "this", "->", "builders", "[", "$", "key", "]", ",", "(", "array", ")", "$", "content", ")", ";", "}", "}", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'Cannot create resource by URI \"%s\"'", ",", "$", "uri", ")", ")", ";", "}" ]
Create resource object by URI template and resource data. @param string $uri @param array $content @throws RuntimeException @return mixed|Collection|Entity|Entity[]
[ "Create", "resource", "object", "by", "URI", "template", "and", "resource", "data", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/Rest/Factory.php#L71-L82
train
burzum/cakephp-html-purifier
src/Lib/Purifier.php
Purifier.config
public static function config($configName, $config = null) { $_this = Purifier::getInstance(); if (empty($config)) { if (!isset($_this->_configs[$configName])) { throw new \InvalidArgumentException(sprintf('Purifier configuration `%s` does not exist!', $configName)); } return $_this->_configs[$configName]; } if (is_array($config)) { $purifierConfig = \HTMLPurifier_Config::createDefault(); foreach ($config as $key => $value) { $purifierConfig->set($key, $value); } return $_this->_configs[$configName] = $purifierConfig; } elseif (is_object($config) && is_a($config, 'HTMLPurifier_Config')) { return $_this->_configs[$configName] = $config; } else { throw new \InvalidArgumentException('Invalid purifier config passed!'); } }
php
public static function config($configName, $config = null) { $_this = Purifier::getInstance(); if (empty($config)) { if (!isset($_this->_configs[$configName])) { throw new \InvalidArgumentException(sprintf('Purifier configuration `%s` does not exist!', $configName)); } return $_this->_configs[$configName]; } if (is_array($config)) { $purifierConfig = \HTMLPurifier_Config::createDefault(); foreach ($config as $key => $value) { $purifierConfig->set($key, $value); } return $_this->_configs[$configName] = $purifierConfig; } elseif (is_object($config) && is_a($config, 'HTMLPurifier_Config')) { return $_this->_configs[$configName] = $config; } else { throw new \InvalidArgumentException('Invalid purifier config passed!'); } }
[ "public", "static", "function", "config", "(", "$", "configName", ",", "$", "config", "=", "null", ")", "{", "$", "_this", "=", "Purifier", "::", "getInstance", "(", ")", ";", "if", "(", "empty", "(", "$", "config", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "_this", "->", "_configs", "[", "$", "configName", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Purifier configuration `%s` does not exist!'", ",", "$", "configName", ")", ")", ";", "}", "return", "$", "_this", "->", "_configs", "[", "$", "configName", "]", ";", "}", "if", "(", "is_array", "(", "$", "config", ")", ")", "{", "$", "purifierConfig", "=", "\\", "HTMLPurifier_Config", "::", "createDefault", "(", ")", ";", "foreach", "(", "$", "config", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "purifierConfig", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "}", "return", "$", "_this", "->", "_configs", "[", "$", "configName", "]", "=", "$", "purifierConfig", ";", "}", "elseif", "(", "is_object", "(", "$", "config", ")", "&&", "is_a", "(", "$", "config", ",", "'HTMLPurifier_Config'", ")", ")", "{", "return", "$", "_this", "->", "_configs", "[", "$", "configName", "]", "=", "$", "config", ";", "}", "else", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid purifier config passed!'", ")", ";", "}", "}" ]
Gets and sets purifier configuration sets. @param string $configName @param string $config @throws \InvalidArgumentException @return \HTMLPurifier
[ "Gets", "and", "sets", "purifier", "configuration", "sets", "." ]
26b991ade6590d0115cd15ef5d25db9a4603a0fb
https://github.com/burzum/cakephp-html-purifier/blob/26b991ade6590d0115cd15ef5d25db9a4603a0fb/src/Lib/Purifier.php#L49-L72
train
burzum/cakephp-html-purifier
src/Lib/Purifier.php
Purifier.getPurifierInstance
public static function getPurifierInstance($configName = 'default') { $_this = Purifier::getInstance(); if (!isset($_this->_instances[$configName])) { if (!isset($_this->_configs[$configName])) { throw new \InvalidArgumentException(sprintf('Configuration and instance `%s` does not exist!', $configName)); } $_this->_instances[$configName] = new \HTMLPurifier($_this->_configs[$configName]); } return $_this->_instances[$configName]; }
php
public static function getPurifierInstance($configName = 'default') { $_this = Purifier::getInstance(); if (!isset($_this->_instances[$configName])) { if (!isset($_this->_configs[$configName])) { throw new \InvalidArgumentException(sprintf('Configuration and instance `%s` does not exist!', $configName)); } $_this->_instances[$configName] = new \HTMLPurifier($_this->_configs[$configName]); } return $_this->_instances[$configName]; }
[ "public", "static", "function", "getPurifierInstance", "(", "$", "configName", "=", "'default'", ")", "{", "$", "_this", "=", "Purifier", "::", "getInstance", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "_this", "->", "_instances", "[", "$", "configName", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "_this", "->", "_configs", "[", "$", "configName", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Configuration and instance `%s` does not exist!'", ",", "$", "configName", ")", ")", ";", "}", "$", "_this", "->", "_instances", "[", "$", "configName", "]", "=", "new", "\\", "HTMLPurifier", "(", "$", "_this", "->", "_configs", "[", "$", "configName", "]", ")", ";", "}", "return", "$", "_this", "->", "_instances", "[", "$", "configName", "]", ";", "}" ]
Gets an instance of the purifier lib only when needed, lazy loading it @param string $configName @return HTMLPurifier
[ "Gets", "an", "instance", "of", "the", "purifier", "lib", "only", "when", "needed", "lazy", "loading", "it" ]
26b991ade6590d0115cd15ef5d25db9a4603a0fb
https://github.com/burzum/cakephp-html-purifier/blob/26b991ade6590d0115cd15ef5d25db9a4603a0fb/src/Lib/Purifier.php#L80-L92
train
burzum/cakephp-html-purifier
src/Lib/Purifier.php
Purifier.clean
public static function clean($markup, $configName = 'default') { $_this = Purifier::getInstance(); if (!isset($_this->_configs[$configName])) { throw new \InvalidArgumentException(sprintf('Invalid HtmlPurifier configuration "%s"!', $configName)); } return $_this->getPurifierInstance($configName)->purify($markup); }
php
public static function clean($markup, $configName = 'default') { $_this = Purifier::getInstance(); if (!isset($_this->_configs[$configName])) { throw new \InvalidArgumentException(sprintf('Invalid HtmlPurifier configuration "%s"!', $configName)); } return $_this->getPurifierInstance($configName)->purify($markup); }
[ "public", "static", "function", "clean", "(", "$", "markup", ",", "$", "configName", "=", "'default'", ")", "{", "$", "_this", "=", "Purifier", "::", "getInstance", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "_this", "->", "_configs", "[", "$", "configName", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid HtmlPurifier configuration \"%s\"!'", ",", "$", "configName", ")", ")", ";", "}", "return", "$", "_this", "->", "getPurifierInstance", "(", "$", "configName", ")", "->", "purify", "(", "$", "markup", ")", ";", "}" ]
Cleans Markup using a given config @param string $markup @param string $configName
[ "Cleans", "Markup", "using", "a", "given", "config" ]
26b991ade6590d0115cd15ef5d25db9a4603a0fb
https://github.com/burzum/cakephp-html-purifier/blob/26b991ade6590d0115cd15ef5d25db9a4603a0fb/src/Lib/Purifier.php#L100-L109
train
Rebilly/rebilly-php
src/Http/CurlHandler.php
CurlHandler.execute
protected function execute(array $options = []) { $session = $this->createSession(); $result = []; try { if ($session->open() === false) { throw new RuntimeException('Cannot initialize a cURL session'); } $session->setOptions($options + $this->options); $result = $session->execute(); if ($result === false) { throw new TransferException($session->getErrorMessage(), $session->getErrorCode()); } $headerSize = $session->getInfo(CURLINFO_HEADER_SIZE); if (strlen($result) < $headerSize) { throw new TransferException( 'Header size(' . $headerSize . ') does not match result: ' . $result ); } $result = [ substr($result, $headerSize) ?: null, substr($result, 0, $headerSize) ?: null, ]; } finally { $session->close(); } return $result; }
php
protected function execute(array $options = []) { $session = $this->createSession(); $result = []; try { if ($session->open() === false) { throw new RuntimeException('Cannot initialize a cURL session'); } $session->setOptions($options + $this->options); $result = $session->execute(); if ($result === false) { throw new TransferException($session->getErrorMessage(), $session->getErrorCode()); } $headerSize = $session->getInfo(CURLINFO_HEADER_SIZE); if (strlen($result) < $headerSize) { throw new TransferException( 'Header size(' . $headerSize . ') does not match result: ' . $result ); } $result = [ substr($result, $headerSize) ?: null, substr($result, 0, $headerSize) ?: null, ]; } finally { $session->close(); } return $result; }
[ "protected", "function", "execute", "(", "array", "$", "options", "=", "[", "]", ")", "{", "$", "session", "=", "$", "this", "->", "createSession", "(", ")", ";", "$", "result", "=", "[", "]", ";", "try", "{", "if", "(", "$", "session", "->", "open", "(", ")", "===", "false", ")", "{", "throw", "new", "RuntimeException", "(", "'Cannot initialize a cURL session'", ")", ";", "}", "$", "session", "->", "setOptions", "(", "$", "options", "+", "$", "this", "->", "options", ")", ";", "$", "result", "=", "$", "session", "->", "execute", "(", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "throw", "new", "TransferException", "(", "$", "session", "->", "getErrorMessage", "(", ")", ",", "$", "session", "->", "getErrorCode", "(", ")", ")", ";", "}", "$", "headerSize", "=", "$", "session", "->", "getInfo", "(", "CURLINFO_HEADER_SIZE", ")", ";", "if", "(", "strlen", "(", "$", "result", ")", "<", "$", "headerSize", ")", "{", "throw", "new", "TransferException", "(", "'Header size('", ".", "$", "headerSize", ".", "') does not match result: '", ".", "$", "result", ")", ";", "}", "$", "result", "=", "[", "substr", "(", "$", "result", ",", "$", "headerSize", ")", "?", ":", "null", ",", "substr", "(", "$", "result", ",", "0", ",", "$", "headerSize", ")", "?", ":", "null", ",", "]", ";", "}", "finally", "{", "$", "session", "->", "close", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Execute cURL session. @param array $options @throws RuntimeException @throws TransferException @return array
[ "Execute", "cURL", "session", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/Http/CurlHandler.php#L168-L203
train
burzum/cakephp-html-purifier
src/Shell/PurifierShell.php
PurifierShell._getTable
protected function _getTable() { $table = TableRegistry::get($this->args[0]); $connection = $table->connection(); $tables = $connection->schemaCollection()->listTables(); if (!in_array($table->table(), $tables)) { $this->abort(__d('Burzum/HtmlPurifier', 'Table `{0}` does not exist in connection `{1}`!', $table->table(), $connection->configName())); } return $table; }
php
protected function _getTable() { $table = TableRegistry::get($this->args[0]); $connection = $table->connection(); $tables = $connection->schemaCollection()->listTables(); if (!in_array($table->table(), $tables)) { $this->abort(__d('Burzum/HtmlPurifier', 'Table `{0}` does not exist in connection `{1}`!', $table->table(), $connection->configName())); } return $table; }
[ "protected", "function", "_getTable", "(", ")", "{", "$", "table", "=", "TableRegistry", "::", "get", "(", "$", "this", "->", "args", "[", "0", "]", ")", ";", "$", "connection", "=", "$", "table", "->", "connection", "(", ")", ";", "$", "tables", "=", "$", "connection", "->", "schemaCollection", "(", ")", "->", "listTables", "(", ")", ";", "if", "(", "!", "in_array", "(", "$", "table", "->", "table", "(", ")", ",", "$", "tables", ")", ")", "{", "$", "this", "->", "abort", "(", "__d", "(", "'Burzum/HtmlPurifier'", ",", "'Table `{0}` does not exist in connection `{1}`!'", ",", "$", "table", "->", "table", "(", ")", ",", "$", "connection", "->", "configName", "(", ")", ")", ")", ";", "}", "return", "$", "table", ";", "}" ]
Gets the table from the shell args. @return \Cake\ORM\Table;
[ "Gets", "the", "table", "from", "the", "shell", "args", "." ]
26b991ade6590d0115cd15ef5d25db9a4603a0fb
https://github.com/burzum/cakephp-html-purifier/blob/26b991ade6590d0115cd15ef5d25db9a4603a0fb/src/Shell/PurifierShell.php#L33-L42
train
burzum/cakephp-html-purifier
src/Shell/PurifierShell.php
PurifierShell._loadBehavior
protected function _loadBehavior(Table $table, $fields) { if (!in_array('HtmlPurifier', $table->behaviors()->loaded())) { $table->addBehavior('Burzum/HtmlPurifier.HtmlPurifier', [ 'fields' => $fields, 'purifierConfig' => $this->param('config') ]); } }
php
protected function _loadBehavior(Table $table, $fields) { if (!in_array('HtmlPurifier', $table->behaviors()->loaded())) { $table->addBehavior('Burzum/HtmlPurifier.HtmlPurifier', [ 'fields' => $fields, 'purifierConfig' => $this->param('config') ]); } }
[ "protected", "function", "_loadBehavior", "(", "Table", "$", "table", ",", "$", "fields", ")", "{", "if", "(", "!", "in_array", "(", "'HtmlPurifier'", ",", "$", "table", "->", "behaviors", "(", ")", "->", "loaded", "(", ")", ")", ")", "{", "$", "table", "->", "addBehavior", "(", "'Burzum/HtmlPurifier.HtmlPurifier'", ",", "[", "'fields'", "=>", "$", "fields", ",", "'purifierConfig'", "=>", "$", "this", "->", "param", "(", "'config'", ")", "]", ")", ";", "}", "}" ]
Loads the purifier behavior for the given table if not already attached. @param \Cake\ORM\Table $table Table object. @param array Set of fields to sanitize @return void
[ "Loads", "the", "purifier", "behavior", "for", "the", "given", "table", "if", "not", "already", "attached", "." ]
26b991ade6590d0115cd15ef5d25db9a4603a0fb
https://github.com/burzum/cakephp-html-purifier/blob/26b991ade6590d0115cd15ef5d25db9a4603a0fb/src/Shell/PurifierShell.php#L69-L77
train
burzum/cakephp-html-purifier
src/Shell/PurifierShell.php
PurifierShell.purify
public function purify() { $table = $this->_getTable(); $fields = $this->_getFields($table); $this->_loadBehavior($table, $fields); $query = $table->find(); if ($table->hasFinder('purifier')) { $query->find('purifier'); } $total = $query->all()->count(); $this->info(__d('Burzum/HtmlPurifier', 'Sanitizing fields `{0}` in table `{1}`', implode(',', $fields), $table->table())); $this->helper('progress')->output([ 'total' => $total, 'callback' => function ($progress) use ($total, $table, $fields) { $chunkSize = 25; $chunkCount = 0; while ($chunkCount <= $total) { $this->_process($table, $chunkCount, $chunkSize, $fields); $chunkCount = $chunkCount + $chunkSize; $progress->increment($chunkSize); $progress->draw(); } return; } ]); }
php
public function purify() { $table = $this->_getTable(); $fields = $this->_getFields($table); $this->_loadBehavior($table, $fields); $query = $table->find(); if ($table->hasFinder('purifier')) { $query->find('purifier'); } $total = $query->all()->count(); $this->info(__d('Burzum/HtmlPurifier', 'Sanitizing fields `{0}` in table `{1}`', implode(',', $fields), $table->table())); $this->helper('progress')->output([ 'total' => $total, 'callback' => function ($progress) use ($total, $table, $fields) { $chunkSize = 25; $chunkCount = 0; while ($chunkCount <= $total) { $this->_process($table, $chunkCount, $chunkSize, $fields); $chunkCount = $chunkCount + $chunkSize; $progress->increment($chunkSize); $progress->draw(); } return; } ]); }
[ "public", "function", "purify", "(", ")", "{", "$", "table", "=", "$", "this", "->", "_getTable", "(", ")", ";", "$", "fields", "=", "$", "this", "->", "_getFields", "(", "$", "table", ")", ";", "$", "this", "->", "_loadBehavior", "(", "$", "table", ",", "$", "fields", ")", ";", "$", "query", "=", "$", "table", "->", "find", "(", ")", ";", "if", "(", "$", "table", "->", "hasFinder", "(", "'purifier'", ")", ")", "{", "$", "query", "->", "find", "(", "'purifier'", ")", ";", "}", "$", "total", "=", "$", "query", "->", "all", "(", ")", "->", "count", "(", ")", ";", "$", "this", "->", "info", "(", "__d", "(", "'Burzum/HtmlPurifier'", ",", "'Sanitizing fields `{0}` in table `{1}`'", ",", "implode", "(", "','", ",", "$", "fields", ")", ",", "$", "table", "->", "table", "(", ")", ")", ")", ";", "$", "this", "->", "helper", "(", "'progress'", ")", "->", "output", "(", "[", "'total'", "=>", "$", "total", ",", "'callback'", "=>", "function", "(", "$", "progress", ")", "use", "(", "$", "total", ",", "$", "table", ",", "$", "fields", ")", "{", "$", "chunkSize", "=", "25", ";", "$", "chunkCount", "=", "0", ";", "while", "(", "$", "chunkCount", "<=", "$", "total", ")", "{", "$", "this", "->", "_process", "(", "$", "table", ",", "$", "chunkCount", ",", "$", "chunkSize", ",", "$", "fields", ")", ";", "$", "chunkCount", "=", "$", "chunkCount", "+", "$", "chunkSize", ";", "$", "progress", "->", "increment", "(", "$", "chunkSize", ")", ";", "$", "progress", "->", "draw", "(", ")", ";", "}", "return", ";", "}", "]", ")", ";", "}" ]
Purifies data base content. @return void
[ "Purifies", "data", "base", "content", "." ]
26b991ade6590d0115cd15ef5d25db9a4603a0fb
https://github.com/burzum/cakephp-html-purifier/blob/26b991ade6590d0115cd15ef5d25db9a4603a0fb/src/Shell/PurifierShell.php#L84-L112
train
burzum/cakephp-html-purifier
src/Shell/PurifierShell.php
PurifierShell._process
protected function _process(Table $table, $chunkCount, $chunkSize, $fields) { $query = $table->find(); if ($table->hasFinder('purifier')) { $query->find('purifier'); } $fields[] = $table->primaryKey(); $results = $query ->select($fields) ->offset($chunkCount) ->limit($chunkSize) ->orderDesc($table->aliasField($table->primaryKey())) ->all(); if (empty($results)) { return; } foreach ($results as $result) { try { $table->save($result); $chunkCount++; } catch (\Exception $e) { $this->abort($e->getMessage()); } } }
php
protected function _process(Table $table, $chunkCount, $chunkSize, $fields) { $query = $table->find(); if ($table->hasFinder('purifier')) { $query->find('purifier'); } $fields[] = $table->primaryKey(); $results = $query ->select($fields) ->offset($chunkCount) ->limit($chunkSize) ->orderDesc($table->aliasField($table->primaryKey())) ->all(); if (empty($results)) { return; } foreach ($results as $result) { try { $table->save($result); $chunkCount++; } catch (\Exception $e) { $this->abort($e->getMessage()); } } }
[ "protected", "function", "_process", "(", "Table", "$", "table", ",", "$", "chunkCount", ",", "$", "chunkSize", ",", "$", "fields", ")", "{", "$", "query", "=", "$", "table", "->", "find", "(", ")", ";", "if", "(", "$", "table", "->", "hasFinder", "(", "'purifier'", ")", ")", "{", "$", "query", "->", "find", "(", "'purifier'", ")", ";", "}", "$", "fields", "[", "]", "=", "$", "table", "->", "primaryKey", "(", ")", ";", "$", "results", "=", "$", "query", "->", "select", "(", "$", "fields", ")", "->", "offset", "(", "$", "chunkCount", ")", "->", "limit", "(", "$", "chunkSize", ")", "->", "orderDesc", "(", "$", "table", "->", "aliasField", "(", "$", "table", "->", "primaryKey", "(", ")", ")", ")", "->", "all", "(", ")", ";", "if", "(", "empty", "(", "$", "results", ")", ")", "{", "return", ";", "}", "foreach", "(", "$", "results", "as", "$", "result", ")", "{", "try", "{", "$", "table", "->", "save", "(", "$", "result", ")", ";", "$", "chunkCount", "++", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "abort", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}", "}" ]
Processes the records. @param \Cake\ORM\Table $table @param int $chunkCount @param int $chunkSize @return void
[ "Processes", "the", "records", "." ]
26b991ade6590d0115cd15ef5d25db9a4603a0fb
https://github.com/burzum/cakephp-html-purifier/blob/26b991ade6590d0115cd15ef5d25db9a4603a0fb/src/Shell/PurifierShell.php#L122-L149
train
miserenkov/yii2-sms
src/Sms.php
Sms.allowedTypes
protected function allowedTypes() { return [ self::TYPE_DEFAULT_MESSAGE, self::TYPE_REGISTRATION_MESSAGE, self::TYPE_RESET_PASSWORD_MESSAGE, self::TYPE_LOGIN_MESSAGE, self::TYPE_NOTIFICATION_MESSAGE, ]; }
php
protected function allowedTypes() { return [ self::TYPE_DEFAULT_MESSAGE, self::TYPE_REGISTRATION_MESSAGE, self::TYPE_RESET_PASSWORD_MESSAGE, self::TYPE_LOGIN_MESSAGE, self::TYPE_NOTIFICATION_MESSAGE, ]; }
[ "protected", "function", "allowedTypes", "(", ")", "{", "return", "[", "self", "::", "TYPE_DEFAULT_MESSAGE", ",", "self", "::", "TYPE_REGISTRATION_MESSAGE", ",", "self", "::", "TYPE_RESET_PASSWORD_MESSAGE", ",", "self", "::", "TYPE_LOGIN_MESSAGE", ",", "self", "::", "TYPE_NOTIFICATION_MESSAGE", ",", "]", ";", "}" ]
Allowed message types @return array
[ "Allowed", "message", "types" ]
0ee671ca4a0e8f727b29b07a8f6ed60cc9d5daa1
https://github.com/miserenkov/yii2-sms/blob/0ee671ca4a0e8f727b29b07a8f6ed60cc9d5daa1/src/Sms.php#L99-L108
train
miserenkov/yii2-sms
src/Sms.php
Sms.send
public function send($numbers, $message, $type = self::TYPE_DEFAULT_MESSAGE) { if (!in_array($type, $this->allowedTypes())) { throw new NotSupportedException("Message type \"$type\" doesn't support."); } if (empty($numbers) || (is_array($numbers) && count($numbers) === 0) || empty($message)) { throw new \InvalidArgumentException('For sending sms, please, set phone number and message'); } $response = $this->_client->sendMessage([ 'phones' => $numbers, 'message' => $message, 'id' => $this->smsIdGenerator(), ]); if ($this->_logger instanceof LoggerInterface) { if (is_array($numbers)) { foreach ($numbers as $number) { $this->_logger->setRecord([ 'sms_id' => isset($response['id']) ? $response['id'] : '', 'phone' => $number, 'message' => $message, 'error' => isset($response['error']) ? $response['error'] : 0, ]); } } else { $this->_logger->setRecord([ 'sms_id' => isset($response['id']) ? $response['id'] : '', 'phone' => $numbers, 'message' => $message, 'error' => isset($response['error']) ? $response['error'] : 0, ]); } } return isset($response['id']) ? $response['id'] : false; }
php
public function send($numbers, $message, $type = self::TYPE_DEFAULT_MESSAGE) { if (!in_array($type, $this->allowedTypes())) { throw new NotSupportedException("Message type \"$type\" doesn't support."); } if (empty($numbers) || (is_array($numbers) && count($numbers) === 0) || empty($message)) { throw new \InvalidArgumentException('For sending sms, please, set phone number and message'); } $response = $this->_client->sendMessage([ 'phones' => $numbers, 'message' => $message, 'id' => $this->smsIdGenerator(), ]); if ($this->_logger instanceof LoggerInterface) { if (is_array($numbers)) { foreach ($numbers as $number) { $this->_logger->setRecord([ 'sms_id' => isset($response['id']) ? $response['id'] : '', 'phone' => $number, 'message' => $message, 'error' => isset($response['error']) ? $response['error'] : 0, ]); } } else { $this->_logger->setRecord([ 'sms_id' => isset($response['id']) ? $response['id'] : '', 'phone' => $numbers, 'message' => $message, 'error' => isset($response['error']) ? $response['error'] : 0, ]); } } return isset($response['id']) ? $response['id'] : false; }
[ "public", "function", "send", "(", "$", "numbers", ",", "$", "message", ",", "$", "type", "=", "self", "::", "TYPE_DEFAULT_MESSAGE", ")", "{", "if", "(", "!", "in_array", "(", "$", "type", ",", "$", "this", "->", "allowedTypes", "(", ")", ")", ")", "{", "throw", "new", "NotSupportedException", "(", "\"Message type \\\"$type\\\" doesn't support.\"", ")", ";", "}", "if", "(", "empty", "(", "$", "numbers", ")", "||", "(", "is_array", "(", "$", "numbers", ")", "&&", "count", "(", "$", "numbers", ")", "===", "0", ")", "||", "empty", "(", "$", "message", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'For sending sms, please, set phone number and message'", ")", ";", "}", "$", "response", "=", "$", "this", "->", "_client", "->", "sendMessage", "(", "[", "'phones'", "=>", "$", "numbers", ",", "'message'", "=>", "$", "message", ",", "'id'", "=>", "$", "this", "->", "smsIdGenerator", "(", ")", ",", "]", ")", ";", "if", "(", "$", "this", "->", "_logger", "instanceof", "LoggerInterface", ")", "{", "if", "(", "is_array", "(", "$", "numbers", ")", ")", "{", "foreach", "(", "$", "numbers", "as", "$", "number", ")", "{", "$", "this", "->", "_logger", "->", "setRecord", "(", "[", "'sms_id'", "=>", "isset", "(", "$", "response", "[", "'id'", "]", ")", "?", "$", "response", "[", "'id'", "]", ":", "''", ",", "'phone'", "=>", "$", "number", ",", "'message'", "=>", "$", "message", ",", "'error'", "=>", "isset", "(", "$", "response", "[", "'error'", "]", ")", "?", "$", "response", "[", "'error'", "]", ":", "0", ",", "]", ")", ";", "}", "}", "else", "{", "$", "this", "->", "_logger", "->", "setRecord", "(", "[", "'sms_id'", "=>", "isset", "(", "$", "response", "[", "'id'", "]", ")", "?", "$", "response", "[", "'id'", "]", ":", "''", ",", "'phone'", "=>", "$", "numbers", ",", "'message'", "=>", "$", "message", ",", "'error'", "=>", "isset", "(", "$", "response", "[", "'error'", "]", ")", "?", "$", "response", "[", "'error'", "]", ":", "0", ",", "]", ")", ";", "}", "}", "return", "isset", "(", "$", "response", "[", "'id'", "]", ")", "?", "$", "response", "[", "'id'", "]", ":", "false", ";", "}" ]
Send sms message @param string|array $numbers @param string $message @param int $type @return bool|string @throws NotSupportedException|\InvalidArgumentException
[ "Send", "sms", "message" ]
0ee671ca4a0e8f727b29b07a8f6ed60cc9d5daa1
https://github.com/miserenkov/yii2-sms/blob/0ee671ca4a0e8f727b29b07a8f6ed60cc9d5daa1/src/Sms.php#L173-L210
train
miserenkov/yii2-sms
src/Sms.php
Sms.getStatus
public function getStatus($id, $phone, $all = 2) { if (empty($id) || empty($phone)) { throw new \InvalidArgumentException('For getting sms status, please, set id and phone'); } $data = $this->_client->getMessageStatus($id, $phone, $all); if ($this->_logger instanceof LoggerInterface) { $this->_logger->updateRecordBySmsIdAndPhone($id, $phone, $data); } return $data; }
php
public function getStatus($id, $phone, $all = 2) { if (empty($id) || empty($phone)) { throw new \InvalidArgumentException('For getting sms status, please, set id and phone'); } $data = $this->_client->getMessageStatus($id, $phone, $all); if ($this->_logger instanceof LoggerInterface) { $this->_logger->updateRecordBySmsIdAndPhone($id, $phone, $data); } return $data; }
[ "public", "function", "getStatus", "(", "$", "id", ",", "$", "phone", ",", "$", "all", "=", "2", ")", "{", "if", "(", "empty", "(", "$", "id", ")", "||", "empty", "(", "$", "phone", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'For getting sms status, please, set id and phone'", ")", ";", "}", "$", "data", "=", "$", "this", "->", "_client", "->", "getMessageStatus", "(", "$", "id", ",", "$", "phone", ",", "$", "all", ")", ";", "if", "(", "$", "this", "->", "_logger", "instanceof", "LoggerInterface", ")", "{", "$", "this", "->", "_logger", "->", "updateRecordBySmsIdAndPhone", "(", "$", "id", ",", "$", "phone", ",", "$", "data", ")", ";", "}", "return", "$", "data", ";", "}" ]
Get sms status by id and phone @param string $id @param string $phone @param int $all @return array|bool @throws \InvalidArgumentException
[ "Get", "sms", "status", "by", "id", "and", "phone" ]
0ee671ca4a0e8f727b29b07a8f6ed60cc9d5daa1
https://github.com/miserenkov/yii2-sms/blob/0ee671ca4a0e8f727b29b07a8f6ed60cc9d5daa1/src/Sms.php#L221-L234
train
Rebilly/rebilly-php
src/Client.php
Client.createRequest
public function createRequest($method, $uri, $payload, array $headers = []) { return new GuzzleRequest($method, $uri, $headers, $payload); }
php
public function createRequest($method, $uri, $payload, array $headers = []) { return new GuzzleRequest($method, $uri, $headers, $payload); }
[ "public", "function", "createRequest", "(", "$", "method", ",", "$", "uri", ",", "$", "payload", ",", "array", "$", "headers", "=", "[", "]", ")", "{", "return", "new", "GuzzleRequest", "(", "$", "method", ",", "$", "uri", ",", "$", "headers", ",", "$", "payload", ")", ";", "}" ]
Factory method to create a new Request object. @param string $method @param mixed $uri @param mixed $payload @param array $headers @return Request
[ "Factory", "method", "to", "create", "a", "new", "Request", "object", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/Client.php#L518-L521
train
Rebilly/rebilly-php
src/Client.php
Client.createUri
public function createUri($uri, array $params = []) { if ($uri instanceof GuzzleUri) { if (!empty($params)) { $uri = $uri->withQuery(http_build_query($params)); } return $uri; } // If URL template given, prepare URI if (preg_match_all('/{[\w]+}/i', $uri, $matches)) { foreach (array_unique($matches[0]) as $match) { $param = substr($match, 1, -1); if (isset($params[$param])) { $uri = str_replace($match, $params[$param], $uri); unset($params[$param]); } } } if (!empty($params)) { $uri .= '?' . http_build_query($params); } return new GuzzleUri($uri); }
php
public function createUri($uri, array $params = []) { if ($uri instanceof GuzzleUri) { if (!empty($params)) { $uri = $uri->withQuery(http_build_query($params)); } return $uri; } // If URL template given, prepare URI if (preg_match_all('/{[\w]+}/i', $uri, $matches)) { foreach (array_unique($matches[0]) as $match) { $param = substr($match, 1, -1); if (isset($params[$param])) { $uri = str_replace($match, $params[$param], $uri); unset($params[$param]); } } } if (!empty($params)) { $uri .= '?' . http_build_query($params); } return new GuzzleUri($uri); }
[ "public", "function", "createUri", "(", "$", "uri", ",", "array", "$", "params", "=", "[", "]", ")", "{", "if", "(", "$", "uri", "instanceof", "GuzzleUri", ")", "{", "if", "(", "!", "empty", "(", "$", "params", ")", ")", "{", "$", "uri", "=", "$", "uri", "->", "withQuery", "(", "http_build_query", "(", "$", "params", ")", ")", ";", "}", "return", "$", "uri", ";", "}", "// If URL template given, prepare URI", "if", "(", "preg_match_all", "(", "'/{[\\w]+}/i'", ",", "$", "uri", ",", "$", "matches", ")", ")", "{", "foreach", "(", "array_unique", "(", "$", "matches", "[", "0", "]", ")", "as", "$", "match", ")", "{", "$", "param", "=", "substr", "(", "$", "match", ",", "1", ",", "-", "1", ")", ";", "if", "(", "isset", "(", "$", "params", "[", "$", "param", "]", ")", ")", "{", "$", "uri", "=", "str_replace", "(", "$", "match", ",", "$", "params", "[", "$", "param", "]", ",", "$", "uri", ")", ";", "unset", "(", "$", "params", "[", "$", "param", "]", ")", ";", "}", "}", "}", "if", "(", "!", "empty", "(", "$", "params", ")", ")", "{", "$", "uri", ".=", "'?'", ".", "http_build_query", "(", "$", "params", ")", ";", "}", "return", "new", "GuzzleUri", "(", "$", "uri", ")", ";", "}" ]
Factory method to create a new Uri object. @param string $uri @param array $params @return GuzzleUri
[ "Factory", "method", "to", "create", "a", "new", "Uri", "object", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/Client.php#L541-L568
train
Rebilly/rebilly-php
src/Util/RebillySignature.php
RebillySignature.generateSignature
public static function generateSignature($apiUser, $apiKey) { $serverTimezone = date_default_timezone_get(); date_default_timezone_set('UTC'); $nonce = self::generateNonce(self::NONCE_LENGTH); $time = time(); $signature = hash_hmac('sha1', $apiUser . $nonce . $time, $apiKey); $data = [ 'REB-APIUSER' => $apiUser, 'REB-NONCE' => $nonce, 'REB-TIMESTAMP' => $time, 'REB-SIGNATURE' => $signature, ]; date_default_timezone_set($serverTimezone); return base64_encode(json_encode($data)); }
php
public static function generateSignature($apiUser, $apiKey) { $serverTimezone = date_default_timezone_get(); date_default_timezone_set('UTC'); $nonce = self::generateNonce(self::NONCE_LENGTH); $time = time(); $signature = hash_hmac('sha1', $apiUser . $nonce . $time, $apiKey); $data = [ 'REB-APIUSER' => $apiUser, 'REB-NONCE' => $nonce, 'REB-TIMESTAMP' => $time, 'REB-SIGNATURE' => $signature, ]; date_default_timezone_set($serverTimezone); return base64_encode(json_encode($data)); }
[ "public", "static", "function", "generateSignature", "(", "$", "apiUser", ",", "$", "apiKey", ")", "{", "$", "serverTimezone", "=", "date_default_timezone_get", "(", ")", ";", "date_default_timezone_set", "(", "'UTC'", ")", ";", "$", "nonce", "=", "self", "::", "generateNonce", "(", "self", "::", "NONCE_LENGTH", ")", ";", "$", "time", "=", "time", "(", ")", ";", "$", "signature", "=", "hash_hmac", "(", "'sha1'", ",", "$", "apiUser", ".", "$", "nonce", ".", "$", "time", ",", "$", "apiKey", ")", ";", "$", "data", "=", "[", "'REB-APIUSER'", "=>", "$", "apiUser", ",", "'REB-NONCE'", "=>", "$", "nonce", ",", "'REB-TIMESTAMP'", "=>", "$", "time", ",", "'REB-SIGNATURE'", "=>", "$", "signature", ",", "]", ";", "date_default_timezone_set", "(", "$", "serverTimezone", ")", ";", "return", "base64_encode", "(", "json_encode", "(", "$", "data", ")", ")", ";", "}" ]
This method returns an array with the header name and header values for the nonce, timestamp and signature. @param string $apiUser @param string $apiKey @return string
[ "This", "method", "returns", "an", "array", "with", "the", "header", "name", "and", "header", "values", "for", "the", "nonce", "timestamp", "and", "signature", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/Util/RebillySignature.php#L37-L56
train
Rebilly/rebilly-php
src/ApiKeyProvider.php
ApiKeyProvider.ini
public static function ini($profile = null, $filename = null) { $filename = $filename ?: (self::getHomeDir() . self::INI_DEFAULT_FILE); $profile = $profile ?: self::INI_PROFILE; return function () use ($profile, $filename) { if (!is_readable($filename)) { throw new RuntimeException("Cannot read credentials from $filename"); } $data = @parse_ini_file($filename, true); if ($data === false) { throw new UnexpectedValueException("Invalid credentials file: $filename"); } if (!isset($data[$profile])) { throw new UnexpectedValueException("'$profile' not found in credentials file"); } if (!isset($data[$profile][self::INI_APIKEY])) { throw new UnexpectedValueException('No APIKEY present in INI profile ' . "'$profile' ($filename)"); } return $data[$profile][self::INI_APIKEY]; }; }
php
public static function ini($profile = null, $filename = null) { $filename = $filename ?: (self::getHomeDir() . self::INI_DEFAULT_FILE); $profile = $profile ?: self::INI_PROFILE; return function () use ($profile, $filename) { if (!is_readable($filename)) { throw new RuntimeException("Cannot read credentials from $filename"); } $data = @parse_ini_file($filename, true); if ($data === false) { throw new UnexpectedValueException("Invalid credentials file: $filename"); } if (!isset($data[$profile])) { throw new UnexpectedValueException("'$profile' not found in credentials file"); } if (!isset($data[$profile][self::INI_APIKEY])) { throw new UnexpectedValueException('No APIKEY present in INI profile ' . "'$profile' ($filename)"); } return $data[$profile][self::INI_APIKEY]; }; }
[ "public", "static", "function", "ini", "(", "$", "profile", "=", "null", ",", "$", "filename", "=", "null", ")", "{", "$", "filename", "=", "$", "filename", "?", ":", "(", "self", "::", "getHomeDir", "(", ")", ".", "self", "::", "INI_DEFAULT_FILE", ")", ";", "$", "profile", "=", "$", "profile", "?", ":", "self", "::", "INI_PROFILE", ";", "return", "function", "(", ")", "use", "(", "$", "profile", ",", "$", "filename", ")", "{", "if", "(", "!", "is_readable", "(", "$", "filename", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Cannot read credentials from $filename\"", ")", ";", "}", "$", "data", "=", "@", "parse_ini_file", "(", "$", "filename", ",", "true", ")", ";", "if", "(", "$", "data", "===", "false", ")", "{", "throw", "new", "UnexpectedValueException", "(", "\"Invalid credentials file: $filename\"", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "$", "profile", "]", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "\"'$profile' not found in credentials file\"", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "data", "[", "$", "profile", "]", "[", "self", "::", "INI_APIKEY", "]", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'No APIKEY present in INI profile '", ".", "\"'$profile' ($filename)\"", ")", ";", "}", "return", "$", "data", "[", "$", "profile", "]", "[", "self", "::", "INI_APIKEY", "]", ";", "}", ";", "}" ]
APIKEY provider that read APIKEY in an ini file stored in the current user's home directory. @param string|null $profile Profile to use. If not specified will use the "default" profile. @param string|null $filename If provided, uses a custom filename rather than looking in the home directory. @return callable
[ "APIKEY", "provider", "that", "read", "APIKEY", "in", "an", "ini", "file", "stored", "in", "the", "current", "user", "s", "home", "directory", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/ApiKeyProvider.php#L52-L78
train
Rebilly/rebilly-php
src/ApiKeyProvider.php
ApiKeyProvider.getHomeDir
private static function getHomeDir() { // On Linux/Unix-like systems, use the HOME environment variable if ($homeDir = getenv('HOME')) { return $homeDir; } // Get the HOMEDRIVE and HOMEPATH values for Windows hosts if (($homeDrive = getenv('HOMEDRIVE')) && ($homePath = getenv('HOMEPATH'))) { return $homeDrive . $homePath; } throw new BadMethodCallException('Cannot establish the home directory'); }
php
private static function getHomeDir() { // On Linux/Unix-like systems, use the HOME environment variable if ($homeDir = getenv('HOME')) { return $homeDir; } // Get the HOMEDRIVE and HOMEPATH values for Windows hosts if (($homeDrive = getenv('HOMEDRIVE')) && ($homePath = getenv('HOMEPATH'))) { return $homeDrive . $homePath; } throw new BadMethodCallException('Cannot establish the home directory'); }
[ "private", "static", "function", "getHomeDir", "(", ")", "{", "// On Linux/Unix-like systems, use the HOME environment variable", "if", "(", "$", "homeDir", "=", "getenv", "(", "'HOME'", ")", ")", "{", "return", "$", "homeDir", ";", "}", "// Get the HOMEDRIVE and HOMEPATH values for Windows hosts", "if", "(", "(", "$", "homeDrive", "=", "getenv", "(", "'HOMEDRIVE'", ")", ")", "&&", "(", "$", "homePath", "=", "getenv", "(", "'HOMEPATH'", ")", ")", ")", "{", "return", "$", "homeDrive", ".", "$", "homePath", ";", "}", "throw", "new", "BadMethodCallException", "(", "'Cannot establish the home directory'", ")", ";", "}" ]
Gets the environment's HOME directory if available. @return null|string
[ "Gets", "the", "environment", "s", "HOME", "directory", "if", "available", "." ]
12703396740b8e6ef1a58ded217a155a3bcb6dc9
https://github.com/Rebilly/rebilly-php/blob/12703396740b8e6ef1a58ded217a155a3bcb6dc9/src/ApiKeyProvider.php#L85-L98
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.init
public function init() { $git_repo = exec('basename `git rev-parse --show-toplevel`'); // Remove instructions for creating a new repo, because we've got one now. $readme_contents = file_get_contents('README.md'); $start_string = '### Initial build (new repo)'; $end_string = '### Initial build (existing repo)'; $from = $this->findAllTextBetween($start_string, $end_string, $readme_contents); $find_replaces = array( array( 'source' => 'composer.json', 'from' => '"name": "thinkshout/drupal-project",', 'to' => '"name": "thinkshout/' . $git_repo . '",', ), array( 'source' => '.env.dist', 'from' => 'TS_PROJECT="SITE"', 'to' => 'TS_PROJECT="' . $git_repo . '"', ), array( 'source' => 'README.md', 'from' => array($from, 'new-project-name'), 'to' => array($end_string, $git_repo), ), ); foreach ($find_replaces as $find_replace) { $this->taskReplaceInFile($find_replace['source']) ->from($find_replace['from']) ->to($find_replace['to']) ->run(); } }
php
public function init() { $git_repo = exec('basename `git rev-parse --show-toplevel`'); // Remove instructions for creating a new repo, because we've got one now. $readme_contents = file_get_contents('README.md'); $start_string = '### Initial build (new repo)'; $end_string = '### Initial build (existing repo)'; $from = $this->findAllTextBetween($start_string, $end_string, $readme_contents); $find_replaces = array( array( 'source' => 'composer.json', 'from' => '"name": "thinkshout/drupal-project",', 'to' => '"name": "thinkshout/' . $git_repo . '",', ), array( 'source' => '.env.dist', 'from' => 'TS_PROJECT="SITE"', 'to' => 'TS_PROJECT="' . $git_repo . '"', ), array( 'source' => 'README.md', 'from' => array($from, 'new-project-name'), 'to' => array($end_string, $git_repo), ), ); foreach ($find_replaces as $find_replace) { $this->taskReplaceInFile($find_replace['source']) ->from($find_replace['from']) ->to($find_replace['to']) ->run(); } }
[ "public", "function", "init", "(", ")", "{", "$", "git_repo", "=", "exec", "(", "'basename `git rev-parse --show-toplevel`'", ")", ";", "// Remove instructions for creating a new repo, because we've got one now.", "$", "readme_contents", "=", "file_get_contents", "(", "'README.md'", ")", ";", "$", "start_string", "=", "'### Initial build (new repo)'", ";", "$", "end_string", "=", "'### Initial build (existing repo)'", ";", "$", "from", "=", "$", "this", "->", "findAllTextBetween", "(", "$", "start_string", ",", "$", "end_string", ",", "$", "readme_contents", ")", ";", "$", "find_replaces", "=", "array", "(", "array", "(", "'source'", "=>", "'composer.json'", ",", "'from'", "=>", "'\"name\": \"thinkshout/drupal-project\",'", ",", "'to'", "=>", "'\"name\": \"thinkshout/'", ".", "$", "git_repo", ".", "'\",'", ",", ")", ",", "array", "(", "'source'", "=>", "'.env.dist'", ",", "'from'", "=>", "'TS_PROJECT=\"SITE\"'", ",", "'to'", "=>", "'TS_PROJECT=\"'", ".", "$", "git_repo", ".", "'\"'", ",", ")", ",", "array", "(", "'source'", "=>", "'README.md'", ",", "'from'", "=>", "array", "(", "$", "from", ",", "'new-project-name'", ")", ",", "'to'", "=>", "array", "(", "$", "end_string", ",", "$", "git_repo", ")", ",", ")", ",", ")", ";", "foreach", "(", "$", "find_replaces", "as", "$", "find_replace", ")", "{", "$", "this", "->", "taskReplaceInFile", "(", "$", "find_replace", "[", "'source'", "]", ")", "->", "from", "(", "$", "find_replace", "[", "'from'", "]", ")", "->", "to", "(", "$", "find_replace", "[", "'to'", "]", ")", "->", "run", "(", ")", ";", "}", "}" ]
Initialize the project for the first time. @return \Robo\Result
[ "Initialize", "the", "project", "for", "the", "first", "time", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L51-L84
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.setUpBehat
function setUpBehat() { // Ensure that this system has headless Chrome. if (!$this->taskExec('which chromedriver')->run()->wasSuccessful()) { $os = exec('uname'); // Here we assume either OS X (a dev's env) or not (a CI env). if ($os == 'Darwin') { $this->taskExec('brew install chromedriver') ->run(); } else { $version = exec('curl http://chromedriver.storage.googleapis.com/LATEST_RELEASE'); $this->taskExec("wget http://chromedriver.storage.googleapis.com/{$version}/chromedriver_linux64.zip") ->run(); $this->taskExec('unzip chromedriver_linux64.zip') ->run(); $this->taskFilesystemStack() ->rename('chromedriver', 'vendor/bin/chromedriver') ->run(); $this->taskFilesystemStack() ->remove('chromedriver_linux64.zip') ->run(); } } }
php
function setUpBehat() { // Ensure that this system has headless Chrome. if (!$this->taskExec('which chromedriver')->run()->wasSuccessful()) { $os = exec('uname'); // Here we assume either OS X (a dev's env) or not (a CI env). if ($os == 'Darwin') { $this->taskExec('brew install chromedriver') ->run(); } else { $version = exec('curl http://chromedriver.storage.googleapis.com/LATEST_RELEASE'); $this->taskExec("wget http://chromedriver.storage.googleapis.com/{$version}/chromedriver_linux64.zip") ->run(); $this->taskExec('unzip chromedriver_linux64.zip') ->run(); $this->taskFilesystemStack() ->rename('chromedriver', 'vendor/bin/chromedriver') ->run(); $this->taskFilesystemStack() ->remove('chromedriver_linux64.zip') ->run(); } } }
[ "function", "setUpBehat", "(", ")", "{", "// Ensure that this system has headless Chrome.", "if", "(", "!", "$", "this", "->", "taskExec", "(", "'which chromedriver'", ")", "->", "run", "(", ")", "->", "wasSuccessful", "(", ")", ")", "{", "$", "os", "=", "exec", "(", "'uname'", ")", ";", "// Here we assume either OS X (a dev's env) or not (a CI env).", "if", "(", "$", "os", "==", "'Darwin'", ")", "{", "$", "this", "->", "taskExec", "(", "'brew install chromedriver'", ")", "->", "run", "(", ")", ";", "}", "else", "{", "$", "version", "=", "exec", "(", "'curl http://chromedriver.storage.googleapis.com/LATEST_RELEASE'", ")", ";", "$", "this", "->", "taskExec", "(", "\"wget http://chromedriver.storage.googleapis.com/{$version}/chromedriver_linux64.zip\"", ")", "->", "run", "(", ")", ";", "$", "this", "->", "taskExec", "(", "'unzip chromedriver_linux64.zip'", ")", "->", "run", "(", ")", ";", "$", "this", "->", "taskFilesystemStack", "(", ")", "->", "rename", "(", "'chromedriver'", ",", "'vendor/bin/chromedriver'", ")", "->", "run", "(", ")", ";", "$", "this", "->", "taskFilesystemStack", "(", ")", "->", "remove", "(", "'chromedriver_linux64.zip'", ")", "->", "run", "(", ")", ";", "}", "}", "}" ]
Ensure that the filesystem has everything Behat needs. At present, that's only chromedriver, AKA "Headless Chrome".
[ "Ensure", "that", "the", "filesystem", "has", "everything", "Behat", "needs", ".", "At", "present", "that", "s", "only", "chromedriver", "AKA", "Headless", "Chrome", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L401-L424
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.pantheonInstall
function pantheonInstall() { $admin_name = $this->projectProperties['admin_name']; $install_cmd = 'site-install ' . $this->projectProperties['install_profile'] . ' --account-name=' . $admin_name . ' -y'; $terminus_site_env = $this->getPantheonSiteEnv(); $install_cmd = "terminus remote:drush $terminus_site_env -- $install_cmd"; // Pantheon wants the site in SFTP for installs. $this->_exec("terminus connection:set $terminus_site_env sftp"); // Even in SFTP mode, the settings.php file might have too restrictive // permissions. We use SFTP to chmod the settings file before installing. $sftp_command = trim(exec("terminus connection:info --field=sftp_command $terminus_site_env")); $sftp_command = str_replace('sftp', 'sftp -b -', $sftp_command); // Use webroot to find settings.php assume webroot is the gitroot if no // webroot is specified. if (getenv('TS_WEB_ROOT')) { $web_root = getenv('TS_WEB_ROOT') . '/'; } else { $web_root = ''; } $default_dir = 'code/' . $web_root . 'sites/default'; // We use 755 instead of 644 so settings.php is executable, and the // directory is stat-able (otherwise we can't chmod the php file) $sftp_command .= ' << EOF chmod 755 ' . $default_dir . ' chmod 755 ' . $default_dir . '/settings.php'; // Note that we don't use $this->_exec on purpose. SFTP command fails // with that operation: a fix would be great but this actually works. exec($sftp_command); // Run the installation. $result = $this->taskExec($install_cmd) ->run(); // Put the site back into git mode. $this->_exec("terminus connection:set $terminus_site_env git"); if ($result->wasSuccessful()) { $this->say('Install complete'); } return $result; }
php
function pantheonInstall() { $admin_name = $this->projectProperties['admin_name']; $install_cmd = 'site-install ' . $this->projectProperties['install_profile'] . ' --account-name=' . $admin_name . ' -y'; $terminus_site_env = $this->getPantheonSiteEnv(); $install_cmd = "terminus remote:drush $terminus_site_env -- $install_cmd"; // Pantheon wants the site in SFTP for installs. $this->_exec("terminus connection:set $terminus_site_env sftp"); // Even in SFTP mode, the settings.php file might have too restrictive // permissions. We use SFTP to chmod the settings file before installing. $sftp_command = trim(exec("terminus connection:info --field=sftp_command $terminus_site_env")); $sftp_command = str_replace('sftp', 'sftp -b -', $sftp_command); // Use webroot to find settings.php assume webroot is the gitroot if no // webroot is specified. if (getenv('TS_WEB_ROOT')) { $web_root = getenv('TS_WEB_ROOT') . '/'; } else { $web_root = ''; } $default_dir = 'code/' . $web_root . 'sites/default'; // We use 755 instead of 644 so settings.php is executable, and the // directory is stat-able (otherwise we can't chmod the php file) $sftp_command .= ' << EOF chmod 755 ' . $default_dir . ' chmod 755 ' . $default_dir . '/settings.php'; // Note that we don't use $this->_exec on purpose. SFTP command fails // with that operation: a fix would be great but this actually works. exec($sftp_command); // Run the installation. $result = $this->taskExec($install_cmd) ->run(); // Put the site back into git mode. $this->_exec("terminus connection:set $terminus_site_env git"); if ($result->wasSuccessful()) { $this->say('Install complete'); } return $result; }
[ "function", "pantheonInstall", "(", ")", "{", "$", "admin_name", "=", "$", "this", "->", "projectProperties", "[", "'admin_name'", "]", ";", "$", "install_cmd", "=", "'site-install '", ".", "$", "this", "->", "projectProperties", "[", "'install_profile'", "]", ".", "' --account-name='", ".", "$", "admin_name", ".", "' -y'", ";", "$", "terminus_site_env", "=", "$", "this", "->", "getPantheonSiteEnv", "(", ")", ";", "$", "install_cmd", "=", "\"terminus remote:drush $terminus_site_env -- $install_cmd\"", ";", "// Pantheon wants the site in SFTP for installs.", "$", "this", "->", "_exec", "(", "\"terminus connection:set $terminus_site_env sftp\"", ")", ";", "// Even in SFTP mode, the settings.php file might have too restrictive", "// permissions. We use SFTP to chmod the settings file before installing.", "$", "sftp_command", "=", "trim", "(", "exec", "(", "\"terminus connection:info --field=sftp_command $terminus_site_env\"", ")", ")", ";", "$", "sftp_command", "=", "str_replace", "(", "'sftp'", ",", "'sftp -b -'", ",", "$", "sftp_command", ")", ";", "// Use webroot to find settings.php assume webroot is the gitroot if no", "// webroot is specified.", "if", "(", "getenv", "(", "'TS_WEB_ROOT'", ")", ")", "{", "$", "web_root", "=", "getenv", "(", "'TS_WEB_ROOT'", ")", ".", "'/'", ";", "}", "else", "{", "$", "web_root", "=", "''", ";", "}", "$", "default_dir", "=", "'code/'", ".", "$", "web_root", ".", "'sites/default'", ";", "// We use 755 instead of 644 so settings.php is executable, and the", "// directory is stat-able (otherwise we can't chmod the php file)", "$", "sftp_command", ".=", "' << EOF\nchmod 755 '", ".", "$", "default_dir", ".", "'\nchmod 755 '", ".", "$", "default_dir", ".", "'/settings.php'", ";", "// Note that we don't use $this->_exec on purpose. SFTP command fails", "// with that operation: a fix would be great but this actually works.", "exec", "(", "$", "sftp_command", ")", ";", "// Run the installation.", "$", "result", "=", "$", "this", "->", "taskExec", "(", "$", "install_cmd", ")", "->", "run", "(", ")", ";", "// Put the site back into git mode.", "$", "this", "->", "_exec", "(", "\"terminus connection:set $terminus_site_env git\"", ")", ";", "if", "(", "$", "result", "->", "wasSuccessful", "(", ")", ")", "{", "$", "this", "->", "say", "(", "'Install complete'", ")", ";", "}", "return", "$", "result", ";", "}" ]
Install site on Pantheon. @return \Robo\Result
[ "Install", "site", "on", "Pantheon", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L494-L536
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.replaceArraySetting
protected function replaceArraySetting($file, $key, $value) { $this->taskReplaceInFile($file) ->regex("/'$key' => '[^'\\\\]*(?:\\\\.[^'\\\\]*)*',/s") ->to("'$key' => '". $value . "',") ->run(); }
php
protected function replaceArraySetting($file, $key, $value) { $this->taskReplaceInFile($file) ->regex("/'$key' => '[^'\\\\]*(?:\\\\.[^'\\\\]*)*',/s") ->to("'$key' => '". $value . "',") ->run(); }
[ "protected", "function", "replaceArraySetting", "(", "$", "file", ",", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "taskReplaceInFile", "(", "$", "file", ")", "->", "regex", "(", "\"/'$key' => '[^'\\\\\\\\]*(?:\\\\\\\\.[^'\\\\\\\\]*)*',/s\"", ")", "->", "to", "(", "\"'$key' => '\"", ".", "$", "value", ".", "\"',\"", ")", "->", "run", "(", ")", ";", "}" ]
Use regex to replace a 'key' => 'value', pair in a file like a settings file. @param $file @param $key @param $value
[ "Use", "regex", "to", "replace", "a", "key", "=", ">", "value", "pair", "in", "a", "file", "like", "a", "settings", "file", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L624-L629
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.findAllTextBetween
private function findAllTextBetween($beginning, $end, $string) { $beginningPos = strpos($string, $beginning); $endPos = strpos($string, $end); if ($beginningPos === false || $endPos === false) { return ''; } $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos); return $textToDelete; }
php
private function findAllTextBetween($beginning, $end, $string) { $beginningPos = strpos($string, $beginning); $endPos = strpos($string, $end); if ($beginningPos === false || $endPos === false) { return ''; } $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos); return $textToDelete; }
[ "private", "function", "findAllTextBetween", "(", "$", "beginning", ",", "$", "end", ",", "$", "string", ")", "{", "$", "beginningPos", "=", "strpos", "(", "$", "string", ",", "$", "beginning", ")", ";", "$", "endPos", "=", "strpos", "(", "$", "string", ",", "$", "end", ")", ";", "if", "(", "$", "beginningPos", "===", "false", "||", "$", "endPos", "===", "false", ")", "{", "return", "''", ";", "}", "$", "textToDelete", "=", "substr", "(", "$", "string", ",", "$", "beginningPos", ",", "(", "$", "endPos", "+", "strlen", "(", "$", "end", ")", ")", "-", "$", "beginningPos", ")", ";", "return", "$", "textToDelete", ";", "}" ]
Finds the text between two strings within a third string. @param $beginning @param $end @param $string @return string String containing $beginning, $end, and everything in between.
[ "Finds", "the", "text", "between", "two", "strings", "within", "a", "third", "string", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L722-L732
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.postDeploy
public function postDeploy() { $terminus_site_env = $this->getPantheonSiteEnv(); $pantheon_prefix = getenv('TERMINUS_SITE'); if ($terminus_site_env == $pantheon_prefix . '.develop' || $terminus_site_env == $pantheon_prefix . '.dev') { $drush_commands = [ 'drush_partial_config_import' => "terminus remote:drush $terminus_site_env -- config-import --partial -y", 'drush_cache_clear' => "terminus remote:drush $terminus_site_env -- cr", 'drush_entity_updates' => "terminus remote:drush $terminus_site_env -- entity-updates -y", 'drush_update_database' => "terminus remote:drush $terminus_site_env -- updb -y", 'drush_full_config_import' => "terminus remote:drush $terminus_site_env -- config-import -y", ]; // Run the installation. $result = $this->taskExec(implode(' && ', $drush_commands)) ->run(); } }
php
public function postDeploy() { $terminus_site_env = $this->getPantheonSiteEnv(); $pantheon_prefix = getenv('TERMINUS_SITE'); if ($terminus_site_env == $pantheon_prefix . '.develop' || $terminus_site_env == $pantheon_prefix . '.dev') { $drush_commands = [ 'drush_partial_config_import' => "terminus remote:drush $terminus_site_env -- config-import --partial -y", 'drush_cache_clear' => "terminus remote:drush $terminus_site_env -- cr", 'drush_entity_updates' => "terminus remote:drush $terminus_site_env -- entity-updates -y", 'drush_update_database' => "terminus remote:drush $terminus_site_env -- updb -y", 'drush_full_config_import' => "terminus remote:drush $terminus_site_env -- config-import -y", ]; // Run the installation. $result = $this->taskExec(implode(' && ', $drush_commands)) ->run(); } }
[ "public", "function", "postDeploy", "(", ")", "{", "$", "terminus_site_env", "=", "$", "this", "->", "getPantheonSiteEnv", "(", ")", ";", "$", "pantheon_prefix", "=", "getenv", "(", "'TERMINUS_SITE'", ")", ";", "if", "(", "$", "terminus_site_env", "==", "$", "pantheon_prefix", ".", "'.develop'", "||", "$", "terminus_site_env", "==", "$", "pantheon_prefix", ".", "'.dev'", ")", "{", "$", "drush_commands", "=", "[", "'drush_partial_config_import'", "=>", "\"terminus remote:drush $terminus_site_env -- config-import --partial -y\"", ",", "'drush_cache_clear'", "=>", "\"terminus remote:drush $terminus_site_env -- cr\"", ",", "'drush_entity_updates'", "=>", "\"terminus remote:drush $terminus_site_env -- entity-updates -y\"", ",", "'drush_update_database'", "=>", "\"terminus remote:drush $terminus_site_env -- updb -y\"", ",", "'drush_full_config_import'", "=>", "\"terminus remote:drush $terminus_site_env -- config-import -y\"", ",", "]", ";", "// Run the installation.", "$", "result", "=", "$", "this", "->", "taskExec", "(", "implode", "(", "' && '", ",", "$", "drush_commands", ")", ")", "->", "run", "(", ")", ";", "}", "}" ]
Clean up state of Pantheon dev & develop environments after deploying. Run this by adding the line: robo post:deploy right after this line: robo pantheon:deploy --y in your .circleci/config.yml file.
[ "Clean", "up", "state", "of", "Pantheon", "dev", "&", "develop", "environments", "after", "deploying", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L745-L760
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.pullConfig
public function pullConfig() { $project_properties = $this->getProjectProperties(); $terminus_site_env = $this->getPantheonSiteEnv($this->databaseSourceOfTruth()); $grab_database = $this->confirm("To pull the latest config, you should create a new backup on Pantheon. Create backup now?"); if ($grab_database == 'y') { $terminus_url_request = $this->taskExec('terminus backup:create ' . $terminus_site_env . ' --element="db"') ->dir($project_properties['web_root']) ->interactive(false) ->run(); if (!$terminus_url_request->wasSuccessful()) { $this->yell('Could not make a Database backup of "'. $terminus_site_env . '"! See if you can make one manually.'); return FALSE; } } $do_composer_install = $this->downloadPantheonBackup($this->databaseSourceOfTruth()); if ($do_composer_install && $this->importLocal()) { $this->taskComposerInstall() ->optimizeAutoloader() ->run(); $drush_commands = [ 'drush_clear_cache_again' => 'drush cr', 'drush_grab_config_changes' => 'drush config-export -y', ]; $this->taskExec(implode(' && ', $drush_commands)) ->dir($project_properties['web_root']) ->run(); // Ignore config-local changes -- the $database_of_truth site doesn't know about them. $this->taskGitStack() ->stopOnFail() ->checkout('config-local') ->run(); $this->yell('"'. $this->databaseSourceOfTruth() . '" site config exported to your local. Commit this branch and make a PR against master. Don\'t forget to `robo install` again before resuming development!'); } }
php
public function pullConfig() { $project_properties = $this->getProjectProperties(); $terminus_site_env = $this->getPantheonSiteEnv($this->databaseSourceOfTruth()); $grab_database = $this->confirm("To pull the latest config, you should create a new backup on Pantheon. Create backup now?"); if ($grab_database == 'y') { $terminus_url_request = $this->taskExec('terminus backup:create ' . $terminus_site_env . ' --element="db"') ->dir($project_properties['web_root']) ->interactive(false) ->run(); if (!$terminus_url_request->wasSuccessful()) { $this->yell('Could not make a Database backup of "'. $terminus_site_env . '"! See if you can make one manually.'); return FALSE; } } $do_composer_install = $this->downloadPantheonBackup($this->databaseSourceOfTruth()); if ($do_composer_install && $this->importLocal()) { $this->taskComposerInstall() ->optimizeAutoloader() ->run(); $drush_commands = [ 'drush_clear_cache_again' => 'drush cr', 'drush_grab_config_changes' => 'drush config-export -y', ]; $this->taskExec(implode(' && ', $drush_commands)) ->dir($project_properties['web_root']) ->run(); // Ignore config-local changes -- the $database_of_truth site doesn't know about them. $this->taskGitStack() ->stopOnFail() ->checkout('config-local') ->run(); $this->yell('"'. $this->databaseSourceOfTruth() . '" site config exported to your local. Commit this branch and make a PR against master. Don\'t forget to `robo install` again before resuming development!'); } }
[ "public", "function", "pullConfig", "(", ")", "{", "$", "project_properties", "=", "$", "this", "->", "getProjectProperties", "(", ")", ";", "$", "terminus_site_env", "=", "$", "this", "->", "getPantheonSiteEnv", "(", "$", "this", "->", "databaseSourceOfTruth", "(", ")", ")", ";", "$", "grab_database", "=", "$", "this", "->", "confirm", "(", "\"To pull the latest config, you should create a new backup on Pantheon. Create backup now?\"", ")", ";", "if", "(", "$", "grab_database", "==", "'y'", ")", "{", "$", "terminus_url_request", "=", "$", "this", "->", "taskExec", "(", "'terminus backup:create '", ".", "$", "terminus_site_env", ".", "' --element=\"db\"'", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "interactive", "(", "false", ")", "->", "run", "(", ")", ";", "if", "(", "!", "$", "terminus_url_request", "->", "wasSuccessful", "(", ")", ")", "{", "$", "this", "->", "yell", "(", "'Could not make a Database backup of \"'", ".", "$", "terminus_site_env", ".", "'\"! See if you can make one manually.'", ")", ";", "return", "FALSE", ";", "}", "}", "$", "do_composer_install", "=", "$", "this", "->", "downloadPantheonBackup", "(", "$", "this", "->", "databaseSourceOfTruth", "(", ")", ")", ";", "if", "(", "$", "do_composer_install", "&&", "$", "this", "->", "importLocal", "(", ")", ")", "{", "$", "this", "->", "taskComposerInstall", "(", ")", "->", "optimizeAutoloader", "(", ")", "->", "run", "(", ")", ";", "$", "drush_commands", "=", "[", "'drush_clear_cache_again'", "=>", "'drush cr'", ",", "'drush_grab_config_changes'", "=>", "'drush config-export -y'", ",", "]", ";", "$", "this", "->", "taskExec", "(", "implode", "(", "' && '", ",", "$", "drush_commands", ")", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "run", "(", ")", ";", "// Ignore config-local changes -- the $database_of_truth site doesn't know about them.", "$", "this", "->", "taskGitStack", "(", ")", "->", "stopOnFail", "(", ")", "->", "checkout", "(", "'config-local'", ")", "->", "run", "(", ")", ";", "$", "this", "->", "yell", "(", "'\"'", ".", "$", "this", "->", "databaseSourceOfTruth", "(", ")", ".", "'\" site config exported to your local. Commit this branch and make a PR against master. Don\\'t forget to `robo install` again before resuming development!'", ")", ";", "}", "}" ]
Pull the config from the live site down to your local. Run this command from a branch based off the last release tag on github. For example: git checkout my_last_release git checkout -b this_release_date robo pull:config git commit . git push Afterwards, make a PR against master for these changes and merge them. Do this BEFORE merging develop into master.
[ "Pull", "the", "config", "from", "the", "live", "site", "down", "to", "your", "local", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L776-L815
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.prepareLocal
public function prepareLocal() { $do_composer_install = TRUE; $project_properties = $this->getProjectProperties(); $grab_database = $this->confirm("Load a database backup?"); if ($grab_database == 'y') { $do_composer_install = $this->getDatabaseOfTruth(); } if ($do_composer_install) { $this->taskComposerInstall() ->optimizeAutoloader() ->run(); $drush_commands = [ 'drush_clear_cache' => 'drush cr', 'drush_update_database' => 'drush updb', 'drush_grab_config_changes' => 'drush config-import -y', 'drush_grab_config_local_changes' => 'drush config-split:import local -y', ]; $this->taskExec(implode(' && ', $drush_commands)) ->dir($project_properties['web_root']) ->run(); } }
php
public function prepareLocal() { $do_composer_install = TRUE; $project_properties = $this->getProjectProperties(); $grab_database = $this->confirm("Load a database backup?"); if ($grab_database == 'y') { $do_composer_install = $this->getDatabaseOfTruth(); } if ($do_composer_install) { $this->taskComposerInstall() ->optimizeAutoloader() ->run(); $drush_commands = [ 'drush_clear_cache' => 'drush cr', 'drush_update_database' => 'drush updb', 'drush_grab_config_changes' => 'drush config-import -y', 'drush_grab_config_local_changes' => 'drush config-split:import local -y', ]; $this->taskExec(implode(' && ', $drush_commands)) ->dir($project_properties['web_root']) ->run(); } }
[ "public", "function", "prepareLocal", "(", ")", "{", "$", "do_composer_install", "=", "TRUE", ";", "$", "project_properties", "=", "$", "this", "->", "getProjectProperties", "(", ")", ";", "$", "grab_database", "=", "$", "this", "->", "confirm", "(", "\"Load a database backup?\"", ")", ";", "if", "(", "$", "grab_database", "==", "'y'", ")", "{", "$", "do_composer_install", "=", "$", "this", "->", "getDatabaseOfTruth", "(", ")", ";", "}", "if", "(", "$", "do_composer_install", ")", "{", "$", "this", "->", "taskComposerInstall", "(", ")", "->", "optimizeAutoloader", "(", ")", "->", "run", "(", ")", ";", "$", "drush_commands", "=", "[", "'drush_clear_cache'", "=>", "'drush cr'", ",", "'drush_update_database'", "=>", "'drush updb'", ",", "'drush_grab_config_changes'", "=>", "'drush config-import -y'", ",", "'drush_grab_config_local_changes'", "=>", "'drush config-split:import local -y'", ",", "]", ";", "$", "this", "->", "taskExec", "(", "implode", "(", "' && '", ",", "$", "drush_commands", ")", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "run", "(", ")", ";", "}", "}" ]
Prepare your local machine for development. Pulls the database of truth, brings the database in line with local config, and enables local development modules, including config suite.
[ "Prepare", "your", "local", "machine", "for", "development", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L823-L844
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.postInstall
public function postInstall() { // Sample method code with instructions for use. $this->say("The post:install command should be customized per project. Copy the postInstall() method from the `/vendor/robo-drupal/src/Tasks.php` folder into your RoboFile.php file and alter it to suit your needs."); return TRUE; // Code you'll want to use starts below. $terminus_site_env = $this->getPantheonSiteEnv(); $project_properties = $this->getProjectProperties(); $pantheon_prefix = getenv('TERMINUS_SITE'); $needs_directory = FALSE; // These are the remote domains we want to run the migration on. $install_domains = [ $pantheon_prefix . '.develop', $pantheon_prefix . '.dev', ]; if ((in_array($terminus_site_env, $install_domains)) && getenv('CIRCLECI')) { $cmd_prefix = "terminus remote:drush $terminus_site_env --"; $needs_directory = FALSE; } elseif (!getenv('CIRCLECI')) { $cmd_prefix = "drush"; $needs_directory = TRUE; } if (!isset($cmd_prefix)) { return; } if (in_array($terminus_site_env, $install_domains)) { $drush_commands = [ 'wake_old_multidev' => "terminus env:wake wfw8.d7database", 'drush_create_admin' => "$cmd_prefix ucrt [email protected] [email protected] --password=admin", 'drush_assign_admin' => "$cmd_prefix urol administrator [email protected]", 'drush_migrate_prep' => "$cmd_prefix mim --group=migrate_drupal_7 --limit=50", ]; // Run the commands you listed. $query = $this->taskExec(implode(' && ', $drush_commands)); if ($needs_directory) { $query->dir($project_properties['web_root']); } $query->run(); } }
php
public function postInstall() { // Sample method code with instructions for use. $this->say("The post:install command should be customized per project. Copy the postInstall() method from the `/vendor/robo-drupal/src/Tasks.php` folder into your RoboFile.php file and alter it to suit your needs."); return TRUE; // Code you'll want to use starts below. $terminus_site_env = $this->getPantheonSiteEnv(); $project_properties = $this->getProjectProperties(); $pantheon_prefix = getenv('TERMINUS_SITE'); $needs_directory = FALSE; // These are the remote domains we want to run the migration on. $install_domains = [ $pantheon_prefix . '.develop', $pantheon_prefix . '.dev', ]; if ((in_array($terminus_site_env, $install_domains)) && getenv('CIRCLECI')) { $cmd_prefix = "terminus remote:drush $terminus_site_env --"; $needs_directory = FALSE; } elseif (!getenv('CIRCLECI')) { $cmd_prefix = "drush"; $needs_directory = TRUE; } if (!isset($cmd_prefix)) { return; } if (in_array($terminus_site_env, $install_domains)) { $drush_commands = [ 'wake_old_multidev' => "terminus env:wake wfw8.d7database", 'drush_create_admin' => "$cmd_prefix ucrt [email protected] [email protected] --password=admin", 'drush_assign_admin' => "$cmd_prefix urol administrator [email protected]", 'drush_migrate_prep' => "$cmd_prefix mim --group=migrate_drupal_7 --limit=50", ]; // Run the commands you listed. $query = $this->taskExec(implode(' && ', $drush_commands)); if ($needs_directory) { $query->dir($project_properties['web_root']); } $query->run(); } }
[ "public", "function", "postInstall", "(", ")", "{", "// Sample method code with instructions for use.", "$", "this", "->", "say", "(", "\"The post:install command should be customized per project. Copy the postInstall() method from the `/vendor/robo-drupal/src/Tasks.php` folder into your RoboFile.php file and alter it to suit your needs.\"", ")", ";", "return", "TRUE", ";", "// Code you'll want to use starts below.", "$", "terminus_site_env", "=", "$", "this", "->", "getPantheonSiteEnv", "(", ")", ";", "$", "project_properties", "=", "$", "this", "->", "getProjectProperties", "(", ")", ";", "$", "pantheon_prefix", "=", "getenv", "(", "'TERMINUS_SITE'", ")", ";", "$", "needs_directory", "=", "FALSE", ";", "// These are the remote domains we want to run the migration on.", "$", "install_domains", "=", "[", "$", "pantheon_prefix", ".", "'.develop'", ",", "$", "pantheon_prefix", ".", "'.dev'", ",", "]", ";", "if", "(", "(", "in_array", "(", "$", "terminus_site_env", ",", "$", "install_domains", ")", ")", "&&", "getenv", "(", "'CIRCLECI'", ")", ")", "{", "$", "cmd_prefix", "=", "\"terminus remote:drush $terminus_site_env --\"", ";", "$", "needs_directory", "=", "FALSE", ";", "}", "elseif", "(", "!", "getenv", "(", "'CIRCLECI'", ")", ")", "{", "$", "cmd_prefix", "=", "\"drush\"", ";", "$", "needs_directory", "=", "TRUE", ";", "}", "if", "(", "!", "isset", "(", "$", "cmd_prefix", ")", ")", "{", "return", ";", "}", "if", "(", "in_array", "(", "$", "terminus_site_env", ",", "$", "install_domains", ")", ")", "{", "$", "drush_commands", "=", "[", "'wake_old_multidev'", "=>", "\"terminus env:wake wfw8.d7database\"", ",", "'drush_create_admin'", "=>", "\"$cmd_prefix ucrt [email protected] [email protected] --password=admin\"", ",", "'drush_assign_admin'", "=>", "\"$cmd_prefix urol administrator [email protected]\"", ",", "'drush_migrate_prep'", "=>", "\"$cmd_prefix mim --group=migrate_drupal_7 --limit=50\"", ",", "]", ";", "// Run the commands you listed.", "$", "query", "=", "$", "this", "->", "taskExec", "(", "implode", "(", "' && '", ",", "$", "drush_commands", ")", ")", ";", "if", "(", "$", "needs_directory", ")", "{", "$", "query", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", ";", "}", "$", "query", "->", "run", "(", ")", ";", "}", "}" ]
Prepare a freshly-installed site with some dummy data for site editors. This is sample code, not intended to be used as-is, but intended to be implemented in your RoboFile.php. It's not an abstract function, because its implementation shouldn't be required, and I wanted to add sample code.
[ "Prepare", "a", "freshly", "-", "installed", "site", "with", "some", "dummy", "data", "for", "site", "editors", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L853-L894
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.getDatabaseOfTruth
private function getDatabaseOfTruth() { $project_properties = $this->getProjectProperties(); $default_database = $this->databaseSourceOfTruth(); if (file_exists('vendor/database.sql.gz')) { $default_database = 'local'; } $this->say('This command will drop all tables in your local database and re-populate from a backup .sql.gz file.'); $this->say('If you already have a database backup in your vendor folder, the "local" option will be available.'); $this->say('If you want to grab a more recent backup from Pantheon, type in the environment name (i.e. dev, test, live, my-multidev). This will be saved to your vendor folder for future re-installs.'); $this->say('Backups are generated on Pantheon regularly, but might be old.'); $this->say('If you need the very latest data from a Pantheon site, go create a new backup using either the Pantheon backend, or Terminus.'); $which_database = $this->askDefault( 'Which database backup should we load (i.e. local/dev/live)?', $default_database ); $getDB = TRUE; if ($which_database !== 'local') { $getDB = $this->downloadPantheonBackup($which_database); } if ($getDB) { $this->say('Emptying existing database.'); $empty_database = $this->taskExec('drush sql:drop -y')->dir($project_properties['web_root'])->run(); return $this->importLocal(); } else { $this->yell('Failed to download a Pantheon backup. Database was not refreshed.'); return false; } }
php
private function getDatabaseOfTruth() { $project_properties = $this->getProjectProperties(); $default_database = $this->databaseSourceOfTruth(); if (file_exists('vendor/database.sql.gz')) { $default_database = 'local'; } $this->say('This command will drop all tables in your local database and re-populate from a backup .sql.gz file.'); $this->say('If you already have a database backup in your vendor folder, the "local" option will be available.'); $this->say('If you want to grab a more recent backup from Pantheon, type in the environment name (i.e. dev, test, live, my-multidev). This will be saved to your vendor folder for future re-installs.'); $this->say('Backups are generated on Pantheon regularly, but might be old.'); $this->say('If you need the very latest data from a Pantheon site, go create a new backup using either the Pantheon backend, or Terminus.'); $which_database = $this->askDefault( 'Which database backup should we load (i.e. local/dev/live)?', $default_database ); $getDB = TRUE; if ($which_database !== 'local') { $getDB = $this->downloadPantheonBackup($which_database); } if ($getDB) { $this->say('Emptying existing database.'); $empty_database = $this->taskExec('drush sql:drop -y')->dir($project_properties['web_root'])->run(); return $this->importLocal(); } else { $this->yell('Failed to download a Pantheon backup. Database was not refreshed.'); return false; } }
[ "private", "function", "getDatabaseOfTruth", "(", ")", "{", "$", "project_properties", "=", "$", "this", "->", "getProjectProperties", "(", ")", ";", "$", "default_database", "=", "$", "this", "->", "databaseSourceOfTruth", "(", ")", ";", "if", "(", "file_exists", "(", "'vendor/database.sql.gz'", ")", ")", "{", "$", "default_database", "=", "'local'", ";", "}", "$", "this", "->", "say", "(", "'This command will drop all tables in your local database and re-populate from a backup .sql.gz file.'", ")", ";", "$", "this", "->", "say", "(", "'If you already have a database backup in your vendor folder, the \"local\" option will be available.'", ")", ";", "$", "this", "->", "say", "(", "'If you want to grab a more recent backup from Pantheon, type in the environment name (i.e. dev, test, live, my-multidev). This will be saved to your vendor folder for future re-installs.'", ")", ";", "$", "this", "->", "say", "(", "'Backups are generated on Pantheon regularly, but might be old.'", ")", ";", "$", "this", "->", "say", "(", "'If you need the very latest data from a Pantheon site, go create a new backup using either the Pantheon backend, or Terminus.'", ")", ";", "$", "which_database", "=", "$", "this", "->", "askDefault", "(", "'Which database backup should we load (i.e. local/dev/live)?'", ",", "$", "default_database", ")", ";", "$", "getDB", "=", "TRUE", ";", "if", "(", "$", "which_database", "!==", "'local'", ")", "{", "$", "getDB", "=", "$", "this", "->", "downloadPantheonBackup", "(", "$", "which_database", ")", ";", "}", "if", "(", "$", "getDB", ")", "{", "$", "this", "->", "say", "(", "'Emptying existing database.'", ")", ";", "$", "empty_database", "=", "$", "this", "->", "taskExec", "(", "'drush sql:drop -y'", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "run", "(", ")", ";", "return", "$", "this", "->", "importLocal", "(", ")", ";", "}", "else", "{", "$", "this", "->", "yell", "(", "'Failed to download a Pantheon backup. Database was not refreshed.'", ")", ";", "return", "false", ";", "}", "}" ]
Helper function to pull the database of truth to your local machine. @return bool If the remote database was reached and downloaded, return TRUE.
[ "Helper", "function", "to", "pull", "the", "database", "of", "truth", "to", "your", "local", "machine", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L902-L934
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.downloadPantheonBackup
private function downloadPantheonBackup($env) { $project_properties = $this->getProjectProperties(); $terminus_site_env = $this->getPantheonSiteEnv($env); $terminus_url_request = $this->taskExec('terminus backup:get ' . $terminus_site_env . ' --element="db"') ->dir($project_properties['web_root']) ->interactive(false) ->run(); if ($terminus_url_request->wasSuccessful()) { $terminus_url = $terminus_url_request->getMessage(); } else { $this->yell('Failed to find a recent backup for the ' . $terminus_site_env . ' site. Does one exist?'); return FALSE; } $wget_database = $this->taskExec('wget -O vendor/database.sql.gz "' . trim($terminus_url) . '"')->run(); if (!$wget_database->wasSuccessful()) { $this->yell('Remote database sync failed.'); return FALSE; } return TRUE; }
php
private function downloadPantheonBackup($env) { $project_properties = $this->getProjectProperties(); $terminus_site_env = $this->getPantheonSiteEnv($env); $terminus_url_request = $this->taskExec('terminus backup:get ' . $terminus_site_env . ' --element="db"') ->dir($project_properties['web_root']) ->interactive(false) ->run(); if ($terminus_url_request->wasSuccessful()) { $terminus_url = $terminus_url_request->getMessage(); } else { $this->yell('Failed to find a recent backup for the ' . $terminus_site_env . ' site. Does one exist?'); return FALSE; } $wget_database = $this->taskExec('wget -O vendor/database.sql.gz "' . trim($terminus_url) . '"')->run(); if (!$wget_database->wasSuccessful()) { $this->yell('Remote database sync failed.'); return FALSE; } return TRUE; }
[ "private", "function", "downloadPantheonBackup", "(", "$", "env", ")", "{", "$", "project_properties", "=", "$", "this", "->", "getProjectProperties", "(", ")", ";", "$", "terminus_site_env", "=", "$", "this", "->", "getPantheonSiteEnv", "(", "$", "env", ")", ";", "$", "terminus_url_request", "=", "$", "this", "->", "taskExec", "(", "'terminus backup:get '", ".", "$", "terminus_site_env", ".", "' --element=\"db\"'", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "interactive", "(", "false", ")", "->", "run", "(", ")", ";", "if", "(", "$", "terminus_url_request", "->", "wasSuccessful", "(", ")", ")", "{", "$", "terminus_url", "=", "$", "terminus_url_request", "->", "getMessage", "(", ")", ";", "}", "else", "{", "$", "this", "->", "yell", "(", "'Failed to find a recent backup for the '", ".", "$", "terminus_site_env", ".", "' site. Does one exist?'", ")", ";", "return", "FALSE", ";", "}", "$", "wget_database", "=", "$", "this", "->", "taskExec", "(", "'wget -O vendor/database.sql.gz \"'", ".", "trim", "(", "$", "terminus_url", ")", ".", "'\"'", ")", "->", "run", "(", ")", ";", "if", "(", "!", "$", "wget_database", "->", "wasSuccessful", "(", ")", ")", "{", "$", "this", "->", "yell", "(", "'Remote database sync failed.'", ")", ";", "return", "FALSE", ";", "}", "return", "TRUE", ";", "}" ]
Grabs a backup from Pantheon. @param $env The environemnt to get the backup from. @return bool True if the backup was downloaded.
[ "Grabs", "a", "backup", "from", "Pantheon", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L945-L970
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.importLocal
public function importLocal() { $project_properties = $this->getProjectProperties(); $drush_commands = [ 'drush_import_database' => 'zcat < ../vendor/database.sql.gz | drush @self sqlc # Importing local copy of db.' ]; $database_import = $this->taskExec(implode(' && ', $drush_commands))->dir($project_properties['web_root'])->run(); if ($database_import->wasSuccessful()) { return TRUE; } else { $this->yell('Could not read vendor/database.sql.gz into your local database. See if the command "zcat < vendor/database.sql.gz | drush @self sqlc" works outside of robo.'); return FALSE; } }
php
public function importLocal() { $project_properties = $this->getProjectProperties(); $drush_commands = [ 'drush_import_database' => 'zcat < ../vendor/database.sql.gz | drush @self sqlc # Importing local copy of db.' ]; $database_import = $this->taskExec(implode(' && ', $drush_commands))->dir($project_properties['web_root'])->run(); if ($database_import->wasSuccessful()) { return TRUE; } else { $this->yell('Could not read vendor/database.sql.gz into your local database. See if the command "zcat < vendor/database.sql.gz | drush @self sqlc" works outside of robo.'); return FALSE; } }
[ "public", "function", "importLocal", "(", ")", "{", "$", "project_properties", "=", "$", "this", "->", "getProjectProperties", "(", ")", ";", "$", "drush_commands", "=", "[", "'drush_import_database'", "=>", "'zcat < ../vendor/database.sql.gz | drush @self sqlc # Importing local copy of db.'", "]", ";", "$", "database_import", "=", "$", "this", "->", "taskExec", "(", "implode", "(", "' && '", ",", "$", "drush_commands", ")", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "run", "(", ")", ";", "if", "(", "$", "database_import", "->", "wasSuccessful", "(", ")", ")", "{", "return", "TRUE", ";", "}", "else", "{", "$", "this", "->", "yell", "(", "'Could not read vendor/database.sql.gz into your local database. See if the command \"zcat < vendor/database.sql.gz | drush @self sqlc\" works outside of robo.'", ")", ";", "return", "FALSE", ";", "}", "}" ]
Imports a local database. @return bool True if import succeeded.
[ "Imports", "a", "local", "database", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L978-L993
train
thinkshout/robo-drupal
src/Tasks.php
Tasks.migrateCleanup
public function migrateCleanup($opts = ['migrations' => '']) { if ($opts['migrations'] && ($this->migrationSourceFolder() || $this->usesMigrationPlugins)) { $migrations = explode(',', $opts['migrations']); $project_properties = $this->getProjectProperties(); foreach ($migrations as $migration) { $this->taskExec('drush mrs ' . $migration) ->dir($project_properties['web_root']) ->run(); } } if ($this->migrationSourceFolder()) { $this->taskExec('drush mr --all && drush cim --partial --source=' . $this->migrationSourceFolder() . ' -y && drush ms') ->dir($project_properties['web_root']) ->run(); } else if ($this->usesMigrationPlugins) { $this->taskExec('drush cr && drush mr --all && drush ms') ->dir($project_properties['web_root']) ->run(); } else { $this->say('No migration sources configured.'); $this->say('To use this command, you must either return a folder path from the migrationSourceFolder() method or set $usesMigrationPlugins to TRUE in your project\'s RoboFile.php.'); return FALSE; } }
php
public function migrateCleanup($opts = ['migrations' => '']) { if ($opts['migrations'] && ($this->migrationSourceFolder() || $this->usesMigrationPlugins)) { $migrations = explode(',', $opts['migrations']); $project_properties = $this->getProjectProperties(); foreach ($migrations as $migration) { $this->taskExec('drush mrs ' . $migration) ->dir($project_properties['web_root']) ->run(); } } if ($this->migrationSourceFolder()) { $this->taskExec('drush mr --all && drush cim --partial --source=' . $this->migrationSourceFolder() . ' -y && drush ms') ->dir($project_properties['web_root']) ->run(); } else if ($this->usesMigrationPlugins) { $this->taskExec('drush cr && drush mr --all && drush ms') ->dir($project_properties['web_root']) ->run(); } else { $this->say('No migration sources configured.'); $this->say('To use this command, you must either return a folder path from the migrationSourceFolder() method or set $usesMigrationPlugins to TRUE in your project\'s RoboFile.php.'); return FALSE; } }
[ "public", "function", "migrateCleanup", "(", "$", "opts", "=", "[", "'migrations'", "=>", "''", "]", ")", "{", "if", "(", "$", "opts", "[", "'migrations'", "]", "&&", "(", "$", "this", "->", "migrationSourceFolder", "(", ")", "||", "$", "this", "->", "usesMigrationPlugins", ")", ")", "{", "$", "migrations", "=", "explode", "(", "','", ",", "$", "opts", "[", "'migrations'", "]", ")", ";", "$", "project_properties", "=", "$", "this", "->", "getProjectProperties", "(", ")", ";", "foreach", "(", "$", "migrations", "as", "$", "migration", ")", "{", "$", "this", "->", "taskExec", "(", "'drush mrs '", ".", "$", "migration", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "run", "(", ")", ";", "}", "}", "if", "(", "$", "this", "->", "migrationSourceFolder", "(", ")", ")", "{", "$", "this", "->", "taskExec", "(", "'drush mr --all && drush cim --partial --source='", ".", "$", "this", "->", "migrationSourceFolder", "(", ")", ".", "' -y && drush ms'", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "run", "(", ")", ";", "}", "else", "if", "(", "$", "this", "->", "usesMigrationPlugins", ")", "{", "$", "this", "->", "taskExec", "(", "'drush cr && drush mr --all && drush ms'", ")", "->", "dir", "(", "$", "project_properties", "[", "'web_root'", "]", ")", "->", "run", "(", ")", ";", "}", "else", "{", "$", "this", "->", "say", "(", "'No migration sources configured.'", ")", ";", "$", "this", "->", "say", "(", "'To use this command, you must either return a folder path from the migrationSourceFolder() method or set $usesMigrationPlugins to TRUE in your project\\'s RoboFile.php.'", ")", ";", "return", "FALSE", ";", "}", "}" ]
Cleanup migrations. @option string migrations Optional list of migrations to reset, separated by commmas.
[ "Cleanup", "migrations", "." ]
63ca81e07bd357d4ebbe133818fd53c8a623c889
https://github.com/thinkshout/robo-drupal/blob/63ca81e07bd357d4ebbe133818fd53c8a623c889/src/Tasks.php#L1001-L1027
train
nabble/semalt-blocker
src/SemaltBlocker/Updater.php
Updater.update
public static function update($force = false) { if (!defined('SEMALT_UNIT_TESTING') && !self::isWritable()) { return; } if (!$force && !self::isOutdated()) { return; } self::doUpdate(); }
php
public static function update($force = false) { if (!defined('SEMALT_UNIT_TESTING') && !self::isWritable()) { return; } if (!$force && !self::isOutdated()) { return; } self::doUpdate(); }
[ "public", "static", "function", "update", "(", "$", "force", "=", "false", ")", "{", "if", "(", "!", "defined", "(", "'SEMALT_UNIT_TESTING'", ")", "&&", "!", "self", "::", "isWritable", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", "$", "force", "&&", "!", "self", "::", "isOutdated", "(", ")", ")", "{", "return", ";", "}", "self", "::", "doUpdate", "(", ")", ";", "}" ]
Try to update the blocked domains list. @param bool $force
[ "Try", "to", "update", "the", "blocked", "domains", "list", "." ]
39a1c7b50cc4ef37b863fd13735f7934f846c44f
https://github.com/nabble/semalt-blocker/blob/39a1c7b50cc4ef37b863fd13735f7934f846c44f/src/SemaltBlocker/Updater.php#L24-L35
train
nabble/semalt-blocker
src/SemaltBlocker/Domainparser.php
Domainparser.getRootDomain
public static function getRootDomain($url) { $host = $domain = self::getHostname($url); $root = false; if (($dotsCount = substr_count($host, '.')) > 0) { $last = $domain; while ($dotsCount > -1) { if (self::isHostInSuffixList($domain)) { $root = $last; break; } $last = trim($domain, '.'); $domain = substr($last, strpos($last, '.')); $dotsCount = $dotsCount - 1; } } return $root; }
php
public static function getRootDomain($url) { $host = $domain = self::getHostname($url); $root = false; if (($dotsCount = substr_count($host, '.')) > 0) { $last = $domain; while ($dotsCount > -1) { if (self::isHostInSuffixList($domain)) { $root = $last; break; } $last = trim($domain, '.'); $domain = substr($last, strpos($last, '.')); $dotsCount = $dotsCount - 1; } } return $root; }
[ "public", "static", "function", "getRootDomain", "(", "$", "url", ")", "{", "$", "host", "=", "$", "domain", "=", "self", "::", "getHostname", "(", "$", "url", ")", ";", "$", "root", "=", "false", ";", "if", "(", "(", "$", "dotsCount", "=", "substr_count", "(", "$", "host", ",", "'.'", ")", ")", ">", "0", ")", "{", "$", "last", "=", "$", "domain", ";", "while", "(", "$", "dotsCount", ">", "-", "1", ")", "{", "if", "(", "self", "::", "isHostInSuffixList", "(", "$", "domain", ")", ")", "{", "$", "root", "=", "$", "last", ";", "break", ";", "}", "$", "last", "=", "trim", "(", "$", "domain", ",", "'.'", ")", ";", "$", "domain", "=", "substr", "(", "$", "last", ",", "strpos", "(", "$", "last", ",", "'.'", ")", ")", ";", "$", "dotsCount", "=", "$", "dotsCount", "-", "1", ";", "}", "}", "return", "$", "root", ";", "}" ]
Extracts lower-case ASCII root domain from URL if it is available and valid, returns false otherwise. @param string $url @return false|string
[ "Extracts", "lower", "-", "case", "ASCII", "root", "domain", "from", "URL", "if", "it", "is", "available", "and", "valid", "returns", "false", "otherwise", "." ]
39a1c7b50cc4ef37b863fd13735f7934f846c44f
https://github.com/nabble/semalt-blocker/blob/39a1c7b50cc4ef37b863fd13735f7934f846c44f/src/SemaltBlocker/Domainparser.php#L24-L43
train
nabble/semalt-blocker
src/SemaltBlocker/Domainparser.php
Domainparser.parseUrl
private static function parseUrl($url, $component) { if (!isset(self::$cache[$url]['url'])) { // Strip protocol $scheme = parse_url($url, PHP_URL_SCHEME); $url = str_replace($scheme . '://', '', $url); $url = str_replace($scheme . ':', '', $url); // Punycode encode domain $host = parse_url('http://' . $url, PHP_URL_HOST); $punycode = new Punycode(); $url = str_replace($host, $punycode->encode($host), $url); // Add back normalized protocol $url = 'http://' . $url; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Sanity check if (($check = filter_var($url, FILTER_VALIDATE_URL)) === false) { $url = false; } self::$cache[$url]['url'] = $url; } return parse_url(strtolower(self::$cache[$url]['url']), $component); }
php
private static function parseUrl($url, $component) { if (!isset(self::$cache[$url]['url'])) { // Strip protocol $scheme = parse_url($url, PHP_URL_SCHEME); $url = str_replace($scheme . '://', '', $url); $url = str_replace($scheme . ':', '', $url); // Punycode encode domain $host = parse_url('http://' . $url, PHP_URL_HOST); $punycode = new Punycode(); $url = str_replace($host, $punycode->encode($host), $url); // Add back normalized protocol $url = 'http://' . $url; // Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL); // Sanity check if (($check = filter_var($url, FILTER_VALIDATE_URL)) === false) { $url = false; } self::$cache[$url]['url'] = $url; } return parse_url(strtolower(self::$cache[$url]['url']), $component); }
[ "private", "static", "function", "parseUrl", "(", "$", "url", ",", "$", "component", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "cache", "[", "$", "url", "]", "[", "'url'", "]", ")", ")", "{", "// Strip protocol\r", "$", "scheme", "=", "parse_url", "(", "$", "url", ",", "PHP_URL_SCHEME", ")", ";", "$", "url", "=", "str_replace", "(", "$", "scheme", ".", "'://'", ",", "''", ",", "$", "url", ")", ";", "$", "url", "=", "str_replace", "(", "$", "scheme", ".", "':'", ",", "''", ",", "$", "url", ")", ";", "// Punycode encode domain\r", "$", "host", "=", "parse_url", "(", "'http://'", ".", "$", "url", ",", "PHP_URL_HOST", ")", ";", "$", "punycode", "=", "new", "Punycode", "(", ")", ";", "$", "url", "=", "str_replace", "(", "$", "host", ",", "$", "punycode", "->", "encode", "(", "$", "host", ")", ",", "$", "url", ")", ";", "// Add back normalized protocol\r", "$", "url", "=", "'http://'", ".", "$", "url", ";", "// Remove all illegal characters from a url\r", "$", "url", "=", "filter_var", "(", "$", "url", ",", "FILTER_SANITIZE_URL", ")", ";", "// Sanity check\r", "if", "(", "(", "$", "check", "=", "filter_var", "(", "$", "url", ",", "FILTER_VALIDATE_URL", ")", ")", "===", "false", ")", "{", "$", "url", "=", "false", ";", "}", "self", "::", "$", "cache", "[", "$", "url", "]", "[", "'url'", "]", "=", "$", "url", ";", "}", "return", "parse_url", "(", "strtolower", "(", "self", "::", "$", "cache", "[", "$", "url", "]", "[", "'url'", "]", ")", ",", "$", "component", ")", ";", "}" ]
Checks an URL for validity, and punycode encode the returned component. @param string $url @param int $component @return string|false
[ "Checks", "an", "URL", "for", "validity", "and", "punycode", "encode", "the", "returned", "component", "." ]
39a1c7b50cc4ef37b863fd13735f7934f846c44f
https://github.com/nabble/semalt-blocker/blob/39a1c7b50cc4ef37b863fd13735f7934f846c44f/src/SemaltBlocker/Domainparser.php#L81-L109
train
ArkEcosystem/php-crypto
src/Transactions/Builder/MultiSignatureRegistration.php
MultiSignatureRegistration.keysgroup
public function keysgroup(array $keysgroup): self { $this->transaction->asset['multisignature']['keysgroup'] = $keysgroup; $this->transaction->fee = (count($keysgroup) + 1) * $this->transaction->fee; return $this; }
php
public function keysgroup(array $keysgroup): self { $this->transaction->asset['multisignature']['keysgroup'] = $keysgroup; $this->transaction->fee = (count($keysgroup) + 1) * $this->transaction->fee; return $this; }
[ "public", "function", "keysgroup", "(", "array", "$", "keysgroup", ")", ":", "self", "{", "$", "this", "->", "transaction", "->", "asset", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", "=", "$", "keysgroup", ";", "$", "this", "->", "transaction", "->", "fee", "=", "(", "count", "(", "$", "keysgroup", ")", "+", "1", ")", "*", "$", "this", "->", "transaction", "->", "fee", ";", "return", "$", "this", ";", "}" ]
Set the keysgroup of signatures. @param array $keysgroup @return \ArkEcosystem\Crypto\Transactions\Builder\MultiSignatureRegistration
[ "Set", "the", "keysgroup", "of", "signatures", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Builder/MultiSignatureRegistration.php#L68-L75
train
ArkEcosystem/php-crypto
src/Transactions/Serializers/DelegateRegistration.php
DelegateRegistration.serialize
public function serialize(): void { $delegateBytes = bin2hex($this->transaction['asset']['delegate']['username']); $this->buffer->writeUInt8(strlen($delegateBytes) / 2); $this->buffer->writeHexBytes($delegateBytes); }
php
public function serialize(): void { $delegateBytes = bin2hex($this->transaction['asset']['delegate']['username']); $this->buffer->writeUInt8(strlen($delegateBytes) / 2); $this->buffer->writeHexBytes($delegateBytes); }
[ "public", "function", "serialize", "(", ")", ":", "void", "{", "$", "delegateBytes", "=", "bin2hex", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'delegate'", "]", "[", "'username'", "]", ")", ";", "$", "this", "->", "buffer", "->", "writeUInt8", "(", "strlen", "(", "$", "delegateBytes", ")", "/", "2", ")", ";", "$", "this", "->", "buffer", "->", "writeHexBytes", "(", "$", "delegateBytes", ")", ";", "}" ]
Handle the serialization of "vote" data. @return string
[ "Handle", "the", "serialization", "of", "vote", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Serializers/DelegateRegistration.php#L28-L34
train
ArkEcosystem/php-crypto
src/Transactions/Deserializers/Vote.php
Vote.deserialize
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $voteLength = $this->buffer->readUInt8() & 0xff; $this->transaction->asset = ['votes' => []]; $vote = null; for ($i = 0; $i < $voteLength; $i++) { $this->buffer->position($this->assetOffset + 2 + $i * 2 * 34); $vote = $this->buffer->readHexRaw(34 * 2); $vote = ('1' === $vote[1] ? '+' : '-').substr($vote, 2); $this->transaction->asset['votes'][] = $vote; } return $this->parseSignatures($this->assetOffset + 2 + $voteLength * 34 * 2); }
php
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $voteLength = $this->buffer->readUInt8() & 0xff; $this->transaction->asset = ['votes' => []]; $vote = null; for ($i = 0; $i < $voteLength; $i++) { $this->buffer->position($this->assetOffset + 2 + $i * 2 * 34); $vote = $this->buffer->readHexRaw(34 * 2); $vote = ('1' === $vote[1] ? '+' : '-').substr($vote, 2); $this->transaction->asset['votes'][] = $vote; } return $this->parseSignatures($this->assetOffset + 2 + $voteLength * 34 * 2); }
[ "public", "function", "deserialize", "(", ")", ":", "object", "{", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", "/", "2", ")", ";", "$", "voteLength", "=", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", "&", "0xff", ";", "$", "this", "->", "transaction", "->", "asset", "=", "[", "'votes'", "=>", "[", "]", "]", ";", "$", "vote", "=", "null", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "voteLength", ";", "$", "i", "++", ")", "{", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", "+", "2", "+", "$", "i", "*", "2", "*", "34", ")", ";", "$", "vote", "=", "$", "this", "->", "buffer", "->", "readHexRaw", "(", "34", "*", "2", ")", ";", "$", "vote", "=", "(", "'1'", "===", "$", "vote", "[", "1", "]", "?", "'+'", ":", "'-'", ")", ".", "substr", "(", "$", "vote", ",", "2", ")", ";", "$", "this", "->", "transaction", "->", "asset", "[", "'votes'", "]", "[", "]", "=", "$", "vote", ";", "}", "return", "$", "this", "->", "parseSignatures", "(", "$", "this", "->", "assetOffset", "+", "2", "+", "$", "voteLength", "*", "34", "*", "2", ")", ";", "}" ]
Handle the deserialization of "second signature registration" data. @return object
[ "Handle", "the", "deserialization", "of", "second", "signature", "registration", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializers/Vote.php#L28-L46
train
ArkEcosystem/php-crypto
src/Transactions/Deserializers/MultiPayment.php
MultiPayment.deserialize
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->asset = ['payments' => []]; $count = $this->buffer->readUInt16() & 0xff; $offset = $this->assetOffset / 2 + 1; for ($i = 0; $i < $count; $i++) { $this->transaction->asset['payments'][] = [ 'amount' => $this->buffer->readUInt64(), 'recipientId' => Base58::encodeCheck(new Buffer(hex2bin($this->buffer->readHex(21)))), ]; $offset += 22; } $this->transaction->amount = array_sum(array_column($this->transaction->asset['payments'], 'amount')); return $this->parseSignatures($offset * 2); }
php
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->asset = ['payments' => []]; $count = $this->buffer->readUInt16() & 0xff; $offset = $this->assetOffset / 2 + 1; for ($i = 0; $i < $count; $i++) { $this->transaction->asset['payments'][] = [ 'amount' => $this->buffer->readUInt64(), 'recipientId' => Base58::encodeCheck(new Buffer(hex2bin($this->buffer->readHex(21)))), ]; $offset += 22; } $this->transaction->amount = array_sum(array_column($this->transaction->asset['payments'], 'amount')); return $this->parseSignatures($offset * 2); }
[ "public", "function", "deserialize", "(", ")", ":", "object", "{", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", "/", "2", ")", ";", "$", "this", "->", "transaction", "->", "asset", "=", "[", "'payments'", "=>", "[", "]", "]", ";", "$", "count", "=", "$", "this", "->", "buffer", "->", "readUInt16", "(", ")", "&", "0xff", ";", "$", "offset", "=", "$", "this", "->", "assetOffset", "/", "2", "+", "1", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "$", "this", "->", "transaction", "->", "asset", "[", "'payments'", "]", "[", "]", "=", "[", "'amount'", "=>", "$", "this", "->", "buffer", "->", "readUInt64", "(", ")", ",", "'recipientId'", "=>", "Base58", "::", "encodeCheck", "(", "new", "Buffer", "(", "hex2bin", "(", "$", "this", "->", "buffer", "->", "readHex", "(", "21", ")", ")", ")", ")", ",", "]", ";", "$", "offset", "+=", "22", ";", "}", "$", "this", "->", "transaction", "->", "amount", "=", "array_sum", "(", "array_column", "(", "$", "this", "->", "transaction", "->", "asset", "[", "'payments'", "]", ",", "'amount'", ")", ")", ";", "return", "$", "this", "->", "parseSignatures", "(", "$", "offset", "*", "2", ")", ";", "}" ]
Handle the deserialization of "multi payment" data. @return object
[ "Handle", "the", "deserialization", "of", "multi", "payment", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializers/MultiPayment.php#L31-L52
train
ArkEcosystem/php-crypto
src/Transactions/Deserializer.php
Deserializer.deserialize
public function deserialize(): Transaction { $transaction = new Transaction(); $transaction->version = $this->buffer->readUInt8(); $transaction->network = $this->buffer->readUInt8(); $transaction->type = $this->buffer->readUInt8(); $transaction->timestamp = $this->buffer->readUInt32(); $transaction->senderPublicKey = $this->buffer->readHex(33); $transaction->fee = $this->buffer->readUInt64(); $vendorFieldLength = $this->buffer->readUInt8(); if ($vendorFieldLength > 0) { $transaction->vendorFieldHex = $this->buffer->readHex($vendorFieldLength); } $assetOffset = (41 + 8 + 1) * 2 + $vendorFieldLength * 2; $transaction = $this->handleType($assetOffset, $transaction); if (! isset($transaction->amount)) { $transaction->amount = 0; } if (! isset($transaction->version) || 1 === $transaction->version) { $transaction = $this->handleVersionOne($transaction); } if (2 === $transaction->version) { $transaction = $this->handleVersionTwo($transaction); } return $transaction; }
php
public function deserialize(): Transaction { $transaction = new Transaction(); $transaction->version = $this->buffer->readUInt8(); $transaction->network = $this->buffer->readUInt8(); $transaction->type = $this->buffer->readUInt8(); $transaction->timestamp = $this->buffer->readUInt32(); $transaction->senderPublicKey = $this->buffer->readHex(33); $transaction->fee = $this->buffer->readUInt64(); $vendorFieldLength = $this->buffer->readUInt8(); if ($vendorFieldLength > 0) { $transaction->vendorFieldHex = $this->buffer->readHex($vendorFieldLength); } $assetOffset = (41 + 8 + 1) * 2 + $vendorFieldLength * 2; $transaction = $this->handleType($assetOffset, $transaction); if (! isset($transaction->amount)) { $transaction->amount = 0; } if (! isset($transaction->version) || 1 === $transaction->version) { $transaction = $this->handleVersionOne($transaction); } if (2 === $transaction->version) { $transaction = $this->handleVersionTwo($transaction); } return $transaction; }
[ "public", "function", "deserialize", "(", ")", ":", "Transaction", "{", "$", "transaction", "=", "new", "Transaction", "(", ")", ";", "$", "transaction", "->", "version", "=", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", ";", "$", "transaction", "->", "network", "=", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", ";", "$", "transaction", "->", "type", "=", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", ";", "$", "transaction", "->", "timestamp", "=", "$", "this", "->", "buffer", "->", "readUInt32", "(", ")", ";", "$", "transaction", "->", "senderPublicKey", "=", "$", "this", "->", "buffer", "->", "readHex", "(", "33", ")", ";", "$", "transaction", "->", "fee", "=", "$", "this", "->", "buffer", "->", "readUInt64", "(", ")", ";", "$", "vendorFieldLength", "=", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", ";", "if", "(", "$", "vendorFieldLength", ">", "0", ")", "{", "$", "transaction", "->", "vendorFieldHex", "=", "$", "this", "->", "buffer", "->", "readHex", "(", "$", "vendorFieldLength", ")", ";", "}", "$", "assetOffset", "=", "(", "41", "+", "8", "+", "1", ")", "*", "2", "+", "$", "vendorFieldLength", "*", "2", ";", "$", "transaction", "=", "$", "this", "->", "handleType", "(", "$", "assetOffset", ",", "$", "transaction", ")", ";", "if", "(", "!", "isset", "(", "$", "transaction", "->", "amount", ")", ")", "{", "$", "transaction", "->", "amount", "=", "0", ";", "}", "if", "(", "!", "isset", "(", "$", "transaction", "->", "version", ")", "||", "1", "===", "$", "transaction", "->", "version", ")", "{", "$", "transaction", "=", "$", "this", "->", "handleVersionOne", "(", "$", "transaction", ")", ";", "}", "if", "(", "2", "===", "$", "transaction", "->", "version", ")", "{", "$", "transaction", "=", "$", "this", "->", "handleVersionTwo", "(", "$", "transaction", ")", ";", "}", "return", "$", "transaction", ";", "}" ]
Perform AIP11 compliant deserialization. @return \ArkEcosystem\Crypto\Transactions\Transaction
[ "Perform", "AIP11", "compliant", "deserialization", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializer.php#L76-L108
train
ArkEcosystem/php-crypto
src/Transactions/Deserializer.php
Deserializer.handleType
public function handleType(int $assetOffset, Transaction $transaction): Transaction { $deserializer = $this->deserializers[$transaction->type]; return (new $deserializer($this->buffer, $assetOffset, $transaction))->deserialize(); }
php
public function handleType(int $assetOffset, Transaction $transaction): Transaction { $deserializer = $this->deserializers[$transaction->type]; return (new $deserializer($this->buffer, $assetOffset, $transaction))->deserialize(); }
[ "public", "function", "handleType", "(", "int", "$", "assetOffset", ",", "Transaction", "$", "transaction", ")", ":", "Transaction", "{", "$", "deserializer", "=", "$", "this", "->", "deserializers", "[", "$", "transaction", "->", "type", "]", ";", "return", "(", "new", "$", "deserializer", "(", "$", "this", "->", "buffer", ",", "$", "assetOffset", ",", "$", "transaction", ")", ")", "->", "deserialize", "(", ")", ";", "}" ]
Handle the deserialization of transaction data. @param int $assetOffset @param \ArkEcosystem\Crypto\Transaction $transaction @return \ArkEcosystem\Crypto\Transactions\Transaction
[ "Handle", "the", "deserialization", "of", "transaction", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializer.php#L118-L123
train
ArkEcosystem/php-crypto
src/Transactions/Deserializer.php
Deserializer.handleVersionOne
public function handleVersionOne(Transaction $transaction): Transaction { if (isset($transaction->secondSignature)) { $transaction->signSignature = $transaction->secondSignature; } if (Types::VOTE === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } if (Types::MULTI_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->asset['multisignature']['keysgroup'] = array_map(function ($key) { return '+'.$key; }, $transaction->asset['multisignature']['keysgroup']); } if (isset($transaction->vendorFieldHex)) { $transaction->vendorField = hex2bin($transaction->vendorFieldHex); } if (! isset($transaction->id)) { $transaction->id = $transaction->getId(); } if (Types::SECOND_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } if (Types::MULTI_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } return $transaction; }
php
public function handleVersionOne(Transaction $transaction): Transaction { if (isset($transaction->secondSignature)) { $transaction->signSignature = $transaction->secondSignature; } if (Types::VOTE === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } if (Types::MULTI_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->asset['multisignature']['keysgroup'] = array_map(function ($key) { return '+'.$key; }, $transaction->asset['multisignature']['keysgroup']); } if (isset($transaction->vendorFieldHex)) { $transaction->vendorField = hex2bin($transaction->vendorFieldHex); } if (! isset($transaction->id)) { $transaction->id = $transaction->getId(); } if (Types::SECOND_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } if (Types::MULTI_SIGNATURE_REGISTRATION === $transaction->type) { $transaction->recipientId = Address::fromPublicKey($transaction->senderPublicKey, $transaction->network); } return $transaction; }
[ "public", "function", "handleVersionOne", "(", "Transaction", "$", "transaction", ")", ":", "Transaction", "{", "if", "(", "isset", "(", "$", "transaction", "->", "secondSignature", ")", ")", "{", "$", "transaction", "->", "signSignature", "=", "$", "transaction", "->", "secondSignature", ";", "}", "if", "(", "Types", "::", "VOTE", "===", "$", "transaction", "->", "type", ")", "{", "$", "transaction", "->", "recipientId", "=", "Address", "::", "fromPublicKey", "(", "$", "transaction", "->", "senderPublicKey", ",", "$", "transaction", "->", "network", ")", ";", "}", "if", "(", "Types", "::", "MULTI_SIGNATURE_REGISTRATION", "===", "$", "transaction", "->", "type", ")", "{", "$", "transaction", "->", "asset", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", "=", "array_map", "(", "function", "(", "$", "key", ")", "{", "return", "'+'", ".", "$", "key", ";", "}", ",", "$", "transaction", "->", "asset", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "transaction", "->", "vendorFieldHex", ")", ")", "{", "$", "transaction", "->", "vendorField", "=", "hex2bin", "(", "$", "transaction", "->", "vendorFieldHex", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "transaction", "->", "id", ")", ")", "{", "$", "transaction", "->", "id", "=", "$", "transaction", "->", "getId", "(", ")", ";", "}", "if", "(", "Types", "::", "SECOND_SIGNATURE_REGISTRATION", "===", "$", "transaction", "->", "type", ")", "{", "$", "transaction", "->", "recipientId", "=", "Address", "::", "fromPublicKey", "(", "$", "transaction", "->", "senderPublicKey", ",", "$", "transaction", "->", "network", ")", ";", "}", "if", "(", "Types", "::", "MULTI_SIGNATURE_REGISTRATION", "===", "$", "transaction", "->", "type", ")", "{", "$", "transaction", "->", "recipientId", "=", "Address", "::", "fromPublicKey", "(", "$", "transaction", "->", "senderPublicKey", ",", "$", "transaction", "->", "network", ")", ";", "}", "return", "$", "transaction", ";", "}" ]
Handle the deserialization of transaction data with a version of 1.0. @param \ArkEcosystem\Crypto\Transaction $transaction @return \ArkEcosystem\Crypto\Transactions\Transaction
[ "Handle", "the", "deserialization", "of", "transaction", "data", "with", "a", "version", "of", "1", ".", "0", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializer.php#L132-L165
train
ArkEcosystem/php-crypto
src/Transactions/Deserializer.php
Deserializer.handleVersionTwo
public function handleVersionTwo(Transaction $transaction): Transaction { $transaction->id = Hash::sha256($transaction->serialize())->getHex(); return $transaction; }
php
public function handleVersionTwo(Transaction $transaction): Transaction { $transaction->id = Hash::sha256($transaction->serialize())->getHex(); return $transaction; }
[ "public", "function", "handleVersionTwo", "(", "Transaction", "$", "transaction", ")", ":", "Transaction", "{", "$", "transaction", "->", "id", "=", "Hash", "::", "sha256", "(", "$", "transaction", "->", "serialize", "(", ")", ")", "->", "getHex", "(", ")", ";", "return", "$", "transaction", ";", "}" ]
Handle the deserialization of transaction data with a version of 2.0. @param \ArkEcosystem\Crypto\Transaction $transaction @return \ArkEcosystem\Crypto\Transactions\Transaction
[ "Handle", "the", "deserialization", "of", "transaction", "data", "with", "a", "version", "of", "2", ".", "0", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializer.php#L174-L179
train
ArkEcosystem/php-crypto
src/Transactions/Serializers/IPFS.php
IPFS.serialize
public function serialize(): void { $dag = $this->transaction['asset']['ipfs']['dag']; $this->buffer->writeUInt8(strlen($dag) / 2); $this->buffer->writeHexBytes($dag); }
php
public function serialize(): void { $dag = $this->transaction['asset']['ipfs']['dag']; $this->buffer->writeUInt8(strlen($dag) / 2); $this->buffer->writeHexBytes($dag); }
[ "public", "function", "serialize", "(", ")", ":", "void", "{", "$", "dag", "=", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'ipfs'", "]", "[", "'dag'", "]", ";", "$", "this", "->", "buffer", "->", "writeUInt8", "(", "strlen", "(", "$", "dag", ")", "/", "2", ")", ";", "$", "this", "->", "buffer", "->", "writeHexBytes", "(", "$", "dag", ")", ";", "}" ]
Handle the serialization of "ipfs" data. @return string
[ "Handle", "the", "serialization", "of", "ipfs", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Serializers/IPFS.php#L28-L34
train
ArkEcosystem/php-crypto
src/Transactions/Deserializers/Transfer.php
Transfer.deserialize
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->amount = $this->buffer->readUInt64(); $this->transaction->expiration = $this->buffer->readUInt32(); $this->transaction->recipientId = Base58::encodeCheck(new Buffer(hex2bin($this->buffer->readHex(21)))); return $this->parseSignatures($this->assetOffset + (8 + 4 + 21) * 2); }
php
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->amount = $this->buffer->readUInt64(); $this->transaction->expiration = $this->buffer->readUInt32(); $this->transaction->recipientId = Base58::encodeCheck(new Buffer(hex2bin($this->buffer->readHex(21)))); return $this->parseSignatures($this->assetOffset + (8 + 4 + 21) * 2); }
[ "public", "function", "deserialize", "(", ")", ":", "object", "{", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", "/", "2", ")", ";", "$", "this", "->", "transaction", "->", "amount", "=", "$", "this", "->", "buffer", "->", "readUInt64", "(", ")", ";", "$", "this", "->", "transaction", "->", "expiration", "=", "$", "this", "->", "buffer", "->", "readUInt32", "(", ")", ";", "$", "this", "->", "transaction", "->", "recipientId", "=", "Base58", "::", "encodeCheck", "(", "new", "Buffer", "(", "hex2bin", "(", "$", "this", "->", "buffer", "->", "readHex", "(", "21", ")", ")", ")", ")", ";", "return", "$", "this", "->", "parseSignatures", "(", "$", "this", "->", "assetOffset", "+", "(", "8", "+", "4", "+", "21", ")", "*", "2", ")", ";", "}" ]
Handle the deserialization of "transfer" data. @return object
[ "Handle", "the", "deserialization", "of", "transfer", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializers/Transfer.php#L31-L40
train
ArkEcosystem/php-crypto
src/Identities/Address.php
Address.fromPassphrase
public static function fromPassphrase(string $passphrase, AbstractNetwork $network = null): string { return static::fromPrivateKey(PrivateKey::fromPassphrase($passphrase), $network); }
php
public static function fromPassphrase(string $passphrase, AbstractNetwork $network = null): string { return static::fromPrivateKey(PrivateKey::fromPassphrase($passphrase), $network); }
[ "public", "static", "function", "fromPassphrase", "(", "string", "$", "passphrase", ",", "AbstractNetwork", "$", "network", "=", "null", ")", ":", "string", "{", "return", "static", "::", "fromPrivateKey", "(", "PrivateKey", "::", "fromPassphrase", "(", "$", "passphrase", ")", ",", "$", "network", ")", ";", "}" ]
Derive the address from the given passphrase. @param string $passphrase @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
[ "Derive", "the", "address", "from", "the", "given", "passphrase", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Identities/Address.php#L42-L45
train
ArkEcosystem/php-crypto
src/Identities/Address.php
Address.fromPublicKey
public static function fromPublicKey(string $publicKey, $network = null): string { $network = $network ?? NetworkConfiguration::get(); $ripemd160 = Hash::ripemd160(PublicKey::fromHex($publicKey)->getBuffer()); $seed = Writer::bit8(Helpers::version($network)).$ripemd160->getBinary(); return Base58::encodeCheck(new Buffer($seed)); }
php
public static function fromPublicKey(string $publicKey, $network = null): string { $network = $network ?? NetworkConfiguration::get(); $ripemd160 = Hash::ripemd160(PublicKey::fromHex($publicKey)->getBuffer()); $seed = Writer::bit8(Helpers::version($network)).$ripemd160->getBinary(); return Base58::encodeCheck(new Buffer($seed)); }
[ "public", "static", "function", "fromPublicKey", "(", "string", "$", "publicKey", ",", "$", "network", "=", "null", ")", ":", "string", "{", "$", "network", "=", "$", "network", "??", "NetworkConfiguration", "::", "get", "(", ")", ";", "$", "ripemd160", "=", "Hash", "::", "ripemd160", "(", "PublicKey", "::", "fromHex", "(", "$", "publicKey", ")", "->", "getBuffer", "(", ")", ")", ";", "$", "seed", "=", "Writer", "::", "bit8", "(", "Helpers", "::", "version", "(", "$", "network", ")", ")", ".", "$", "ripemd160", "->", "getBinary", "(", ")", ";", "return", "Base58", "::", "encodeCheck", "(", "new", "Buffer", "(", "$", "seed", ")", ")", ";", "}" ]
Derive the address from the given public key. @param string $publicKey @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
[ "Derive", "the", "address", "from", "the", "given", "public", "key", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Identities/Address.php#L55-L63
train
ArkEcosystem/php-crypto
src/Identities/Address.php
Address.fromPrivateKey
public static function fromPrivateKey(EccPrivateKey $privateKey, AbstractNetwork $network = null): string { $digest = Hash::ripemd160($privateKey->getPublicKey()->getBuffer()); return (new PayToPubKeyHashAddress($digest))->getAddress($network); }
php
public static function fromPrivateKey(EccPrivateKey $privateKey, AbstractNetwork $network = null): string { $digest = Hash::ripemd160($privateKey->getPublicKey()->getBuffer()); return (new PayToPubKeyHashAddress($digest))->getAddress($network); }
[ "public", "static", "function", "fromPrivateKey", "(", "EccPrivateKey", "$", "privateKey", ",", "AbstractNetwork", "$", "network", "=", "null", ")", ":", "string", "{", "$", "digest", "=", "Hash", "::", "ripemd160", "(", "$", "privateKey", "->", "getPublicKey", "(", ")", "->", "getBuffer", "(", ")", ")", ";", "return", "(", "new", "PayToPubKeyHashAddress", "(", "$", "digest", ")", ")", "->", "getAddress", "(", "$", "network", ")", ";", "}" ]
Derive the address from the given private key. @param \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey $privateKey @param ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
[ "Derive", "the", "address", "from", "the", "given", "private", "key", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Identities/Address.php#L73-L78
train
ArkEcosystem/php-crypto
src/Identities/Address.php
Address.validate
public static function validate(string $address, $network = null): bool { try { $addressCreator = new AddressCreator(); $addressCreator->fromString($address, $network); return true; } catch (\Exception $e) { return false; } }
php
public static function validate(string $address, $network = null): bool { try { $addressCreator = new AddressCreator(); $addressCreator->fromString($address, $network); return true; } catch (\Exception $e) { return false; } }
[ "public", "static", "function", "validate", "(", "string", "$", "address", ",", "$", "network", "=", "null", ")", ":", "bool", "{", "try", "{", "$", "addressCreator", "=", "new", "AddressCreator", "(", ")", ";", "$", "addressCreator", "->", "fromString", "(", "$", "address", ",", "$", "network", ")", ";", "return", "true", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
Validate the given address. @param string $address @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|int|null $network @return bool
[ "Validate", "the", "given", "address", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Identities/Address.php#L88-L98
train
ArkEcosystem/php-crypto
src/Transactions/Deserializers/DelegateRegistration.php
DelegateRegistration.deserialize
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $usernameLength = $this->buffer->readUInt8(); $this->transaction->asset = [ 'delegate' => [ 'username' => $this->buffer->position($this->assetOffset + 2)->readHexBytes($usernameLength * 2), ], ]; return $this->parseSignatures($this->assetOffset + ($usernameLength + 1) * 2); }
php
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $usernameLength = $this->buffer->readUInt8(); $this->transaction->asset = [ 'delegate' => [ 'username' => $this->buffer->position($this->assetOffset + 2)->readHexBytes($usernameLength * 2), ], ]; return $this->parseSignatures($this->assetOffset + ($usernameLength + 1) * 2); }
[ "public", "function", "deserialize", "(", ")", ":", "object", "{", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", "/", "2", ")", ";", "$", "usernameLength", "=", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", ";", "$", "this", "->", "transaction", "->", "asset", "=", "[", "'delegate'", "=>", "[", "'username'", "=>", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", "+", "2", ")", "->", "readHexBytes", "(", "$", "usernameLength", "*", "2", ")", ",", "]", ",", "]", ";", "return", "$", "this", "->", "parseSignatures", "(", "$", "this", "->", "assetOffset", "+", "(", "$", "usernameLength", "+", "1", ")", "*", "2", ")", ";", "}" ]
Handle the deserialization of "vote" data. @return object
[ "Handle", "the", "deserialization", "of", "vote", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializers/DelegateRegistration.php#L28-L41
train
ArkEcosystem/php-crypto
src/Transactions/Serializers/Vote.php
Vote.serialize
public function serialize(): void { $voteBytes = []; foreach ($this->transaction['asset']['votes'] as $vote) { $voteBytes[] = '+' === substr($vote, 0, 1) ? '01'.substr($vote, 1) : '00'.substr($vote, 1); } $this->buffer->writeUInt8(count($this->transaction['asset']['votes'])); $this->buffer->writeHexBytes(implode('', $voteBytes)); }
php
public function serialize(): void { $voteBytes = []; foreach ($this->transaction['asset']['votes'] as $vote) { $voteBytes[] = '+' === substr($vote, 0, 1) ? '01'.substr($vote, 1) : '00'.substr($vote, 1); } $this->buffer->writeUInt8(count($this->transaction['asset']['votes'])); $this->buffer->writeHexBytes(implode('', $voteBytes)); }
[ "public", "function", "serialize", "(", ")", ":", "void", "{", "$", "voteBytes", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'votes'", "]", "as", "$", "vote", ")", "{", "$", "voteBytes", "[", "]", "=", "'+'", "===", "substr", "(", "$", "vote", ",", "0", ",", "1", ")", "?", "'01'", ".", "substr", "(", "$", "vote", ",", "1", ")", ":", "'00'", ".", "substr", "(", "$", "vote", ",", "1", ")", ";", "}", "$", "this", "->", "buffer", "->", "writeUInt8", "(", "count", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'votes'", "]", ")", ")", ";", "$", "this", "->", "buffer", "->", "writeHexBytes", "(", "implode", "(", "''", ",", "$", "voteBytes", ")", ")", ";", "}" ]
Handle the serialization of "second signature registration" data. @return string
[ "Handle", "the", "serialization", "of", "second", "signature", "registration", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Serializers/Vote.php#L28-L40
train
ArkEcosystem/php-crypto
src/Identities/WIF.php
WIF.fromPassphrase
public static function fromPassphrase(string $passphrase, AbstractNetwork $network = null): string { return PrivateKey::fromPassphrase($passphrase)->toWif($network); }
php
public static function fromPassphrase(string $passphrase, AbstractNetwork $network = null): string { return PrivateKey::fromPassphrase($passphrase)->toWif($network); }
[ "public", "static", "function", "fromPassphrase", "(", "string", "$", "passphrase", ",", "AbstractNetwork", "$", "network", "=", "null", ")", ":", "string", "{", "return", "PrivateKey", "::", "fromPassphrase", "(", "$", "passphrase", ")", "->", "toWif", "(", "$", "network", ")", ";", "}" ]
Derive the WIF from the given passphrase. @param string $passphrase @param \ArkEcosystem\Crypto\Networks\AbstractNetwork|null $network @return string
[ "Derive", "the", "WIF", "from", "the", "given", "passphrase", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Identities/WIF.php#L33-L36
train
ArkEcosystem/php-crypto
src/Transactions/Serializers/Transfer.php
Transfer.serialize
public function serialize(): void { $this->buffer->writeUInt64($this->transaction['amount']); $this->buffer->writeUInt32($this->transaction['expiration'] ?? 0); $this->buffer->writeHex(Base58::decodeCheck($this->transaction['recipientId'])->getHex()); }
php
public function serialize(): void { $this->buffer->writeUInt64($this->transaction['amount']); $this->buffer->writeUInt32($this->transaction['expiration'] ?? 0); $this->buffer->writeHex(Base58::decodeCheck($this->transaction['recipientId'])->getHex()); }
[ "public", "function", "serialize", "(", ")", ":", "void", "{", "$", "this", "->", "buffer", "->", "writeUInt64", "(", "$", "this", "->", "transaction", "[", "'amount'", "]", ")", ";", "$", "this", "->", "buffer", "->", "writeUInt32", "(", "$", "this", "->", "transaction", "[", "'expiration'", "]", "??", "0", ")", ";", "$", "this", "->", "buffer", "->", "writeHex", "(", "Base58", "::", "decodeCheck", "(", "$", "this", "->", "transaction", "[", "'recipientId'", "]", ")", "->", "getHex", "(", ")", ")", ";", "}" ]
Handle the serialization of "transfer" data. @return string
[ "Handle", "the", "serialization", "of", "transfer", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Serializers/Transfer.php#L30-L35
train
ArkEcosystem/php-crypto
src/Transactions/Serializers/MultiPayment.php
MultiPayment.serialize
public function serialize(): void { $this->buffer->writeUInt16(count($this->transaction['asset']['payments'])); foreach ($this->transaction['asset']['payments'] as $payment) { $this->buffer->writeUInt64($payment['amount']); $this->buffer->writeHex(Base58::decodeCheck($payment['recipientId'])->getHex()); } }
php
public function serialize(): void { $this->buffer->writeUInt16(count($this->transaction['asset']['payments'])); foreach ($this->transaction['asset']['payments'] as $payment) { $this->buffer->writeUInt64($payment['amount']); $this->buffer->writeHex(Base58::decodeCheck($payment['recipientId'])->getHex()); } }
[ "public", "function", "serialize", "(", ")", ":", "void", "{", "$", "this", "->", "buffer", "->", "writeUInt16", "(", "count", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'payments'", "]", ")", ")", ";", "foreach", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'payments'", "]", "as", "$", "payment", ")", "{", "$", "this", "->", "buffer", "->", "writeUInt64", "(", "$", "payment", "[", "'amount'", "]", ")", ";", "$", "this", "->", "buffer", "->", "writeHex", "(", "Base58", "::", "decodeCheck", "(", "$", "payment", "[", "'recipientId'", "]", ")", "->", "getHex", "(", ")", ")", ";", "}", "}" ]
Handle the serialization of "multi payment" data. @return string
[ "Handle", "the", "serialization", "of", "multi", "payment", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Serializers/MultiPayment.php#L30-L38
train
ArkEcosystem/php-crypto
src/Transactions/Deserializers/AbstractDeserializer.php
AbstractDeserializer.parseSignatures
protected function parseSignatures(int $startOffset): object { return $this->transaction->parseSignatures($this->buffer->toHex(), $startOffset); }
php
protected function parseSignatures(int $startOffset): object { return $this->transaction->parseSignatures($this->buffer->toHex(), $startOffset); }
[ "protected", "function", "parseSignatures", "(", "int", "$", "startOffset", ")", ":", "object", "{", "return", "$", "this", "->", "transaction", "->", "parseSignatures", "(", "$", "this", "->", "buffer", "->", "toHex", "(", ")", ",", "$", "startOffset", ")", ";", "}" ]
Parse the signatures of the given transaction. @param int $startOffset @return object
[ "Parse", "the", "signatures", "of", "the", "given", "transaction", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializers/AbstractDeserializer.php#L72-L75
train
ArkEcosystem/php-crypto
src/Transactions/Builder/MultiPayment.php
MultiPayment.add
public function add(string $recipientId, int $amount): self { $this->transaction->asset['payments'][] = compact('recipientId', 'amount'); return $this; }
php
public function add(string $recipientId, int $amount): self { $this->transaction->asset['payments'][] = compact('recipientId', 'amount'); return $this; }
[ "public", "function", "add", "(", "string", "$", "recipientId", ",", "int", "$", "amount", ")", ":", "self", "{", "$", "this", "->", "transaction", "->", "asset", "[", "'payments'", "]", "[", "]", "=", "compact", "(", "'recipientId'", ",", "'amount'", ")", ";", "return", "$", "this", ";", "}" ]
Add a new payment to the collection. @param string $recipientId @param int $amount @return \ArkEcosystem\Crypto\Transactions\Builder\MultiPayment
[ "Add", "a", "new", "payment", "to", "the", "collection", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Builder/MultiPayment.php#L41-L46
train
ArkEcosystem/php-crypto
src/Transactions/Serializers/MultiSignatureRegistration.php
MultiSignatureRegistration.serialize
public function serialize(): void { $keysgroup = []; if (! isset($this->transaction['version']) || 1 === $this->transaction['version']) { foreach ($this->transaction['asset']['multisignature']['keysgroup'] as $key) { $keysgroup[] = '+' === substr($key, 0, 1) ? substr($key, 1) : $key; } } else { $keysgroup = $this->transaction['asset']['multisignature']['keysgroup']; } $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['min']); $this->buffer->writeUInt8(count($this->transaction['asset']['multisignature']['keysgroup'])); $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['lifetime']); $this->buffer->writeHexBytes(implode('', $keysgroup)); }
php
public function serialize(): void { $keysgroup = []; if (! isset($this->transaction['version']) || 1 === $this->transaction['version']) { foreach ($this->transaction['asset']['multisignature']['keysgroup'] as $key) { $keysgroup[] = '+' === substr($key, 0, 1) ? substr($key, 1) : $key; } } else { $keysgroup = $this->transaction['asset']['multisignature']['keysgroup']; } $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['min']); $this->buffer->writeUInt8(count($this->transaction['asset']['multisignature']['keysgroup'])); $this->buffer->writeUInt8($this->transaction['asset']['multisignature']['lifetime']); $this->buffer->writeHexBytes(implode('', $keysgroup)); }
[ "public", "function", "serialize", "(", ")", ":", "void", "{", "$", "keysgroup", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "transaction", "[", "'version'", "]", ")", "||", "1", "===", "$", "this", "->", "transaction", "[", "'version'", "]", ")", "{", "foreach", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", "as", "$", "key", ")", "{", "$", "keysgroup", "[", "]", "=", "'+'", "===", "substr", "(", "$", "key", ",", "0", ",", "1", ")", "?", "substr", "(", "$", "key", ",", "1", ")", ":", "$", "key", ";", "}", "}", "else", "{", "$", "keysgroup", "=", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", ";", "}", "$", "this", "->", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'multisignature'", "]", "[", "'min'", "]", ")", ";", "$", "this", "->", "buffer", "->", "writeUInt8", "(", "count", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", ")", ")", ";", "$", "this", "->", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "transaction", "[", "'asset'", "]", "[", "'multisignature'", "]", "[", "'lifetime'", "]", ")", ";", "$", "this", "->", "buffer", "->", "writeHexBytes", "(", "implode", "(", "''", ",", "$", "keysgroup", ")", ")", ";", "}" ]
Handle the serialization of "multi signature registration" data. @return string
[ "Handle", "the", "serialization", "of", "multi", "signature", "registration", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Serializers/MultiSignatureRegistration.php#L28-L46
train
ArkEcosystem/php-crypto
src/Transactions/Builder/SecondSignatureRegistration.php
SecondSignatureRegistration.signature
public function signature(string $secondPassphrase): self { $this->transaction->asset = [ 'signature' => [ 'publicKey' => PublicKey::fromPassphrase($secondPassphrase)->getHex(), ], ]; return $this; }
php
public function signature(string $secondPassphrase): self { $this->transaction->asset = [ 'signature' => [ 'publicKey' => PublicKey::fromPassphrase($secondPassphrase)->getHex(), ], ]; return $this; }
[ "public", "function", "signature", "(", "string", "$", "secondPassphrase", ")", ":", "self", "{", "$", "this", "->", "transaction", "->", "asset", "=", "[", "'signature'", "=>", "[", "'publicKey'", "=>", "PublicKey", "::", "fromPassphrase", "(", "$", "secondPassphrase", ")", "->", "getHex", "(", ")", ",", "]", ",", "]", ";", "return", "$", "this", ";", "}" ]
Set the signature asset to register the second passphrase. @param string $secondPassphrase @return \ArkEcosystem\Crypto\Transactions\Builder\SecondSignatureRegistration
[ "Set", "the", "signature", "asset", "to", "register", "the", "second", "passphrase", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Builder/SecondSignatureRegistration.php#L32-L41
train
ArkEcosystem/php-crypto
src/Transactions/Deserializers/SecondSignatureRegistration.php
SecondSignatureRegistration.deserialize
public function deserialize(): object { $this->buffer->position($this->assetOffset); $this->transaction->asset = [ 'signature' => [ 'publicKey' => $this->buffer->readHexRaw(66), ], ]; return $this->parseSignatures($this->assetOffset + 66); }
php
public function deserialize(): object { $this->buffer->position($this->assetOffset); $this->transaction->asset = [ 'signature' => [ 'publicKey' => $this->buffer->readHexRaw(66), ], ]; return $this->parseSignatures($this->assetOffset + 66); }
[ "public", "function", "deserialize", "(", ")", ":", "object", "{", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", ")", ";", "$", "this", "->", "transaction", "->", "asset", "=", "[", "'signature'", "=>", "[", "'publicKey'", "=>", "$", "this", "->", "buffer", "->", "readHexRaw", "(", "66", ")", ",", "]", ",", "]", ";", "return", "$", "this", "->", "parseSignatures", "(", "$", "this", "->", "assetOffset", "+", "66", ")", ";", "}" ]
Handle the deserialization of "delegate registration" data. @return object
[ "Handle", "the", "deserialization", "of", "delegate", "registration", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializers/SecondSignatureRegistration.php#L28-L39
train
ArkEcosystem/php-crypto
src/Transactions/Deserializers/MultiSignatureRegistration.php
MultiSignatureRegistration.deserialize
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->asset = [ 'multisignature' => [ 'min' => $this->buffer->readUInt8() & 0xff, 'lifetime' => $this->buffer->skip(1)->readUInt8() & 0xff, ], ]; $count = $this->buffer->readUInt8() & 0xff; for ($i = 0; $i < $count; $i++) { $indexStart = $this->assetOffset + 6; if ($i > 0) { $indexStart += $i * 66; } $this->transaction->asset['multisignature']['keysgroup'][] = $this->buffer->position($indexStart)->readHexRaw(66); } return $this->parseSignatures($this->assetOffset + 6 + $count * 66); }
php
public function deserialize(): object { $this->buffer->position($this->assetOffset / 2); $this->transaction->asset = [ 'multisignature' => [ 'min' => $this->buffer->readUInt8() & 0xff, 'lifetime' => $this->buffer->skip(1)->readUInt8() & 0xff, ], ]; $count = $this->buffer->readUInt8() & 0xff; for ($i = 0; $i < $count; $i++) { $indexStart = $this->assetOffset + 6; if ($i > 0) { $indexStart += $i * 66; } $this->transaction->asset['multisignature']['keysgroup'][] = $this->buffer->position($indexStart)->readHexRaw(66); } return $this->parseSignatures($this->assetOffset + 6 + $count * 66); }
[ "public", "function", "deserialize", "(", ")", ":", "object", "{", "$", "this", "->", "buffer", "->", "position", "(", "$", "this", "->", "assetOffset", "/", "2", ")", ";", "$", "this", "->", "transaction", "->", "asset", "=", "[", "'multisignature'", "=>", "[", "'min'", "=>", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", "&", "0xff", ",", "'lifetime'", "=>", "$", "this", "->", "buffer", "->", "skip", "(", "1", ")", "->", "readUInt8", "(", ")", "&", "0xff", ",", "]", ",", "]", ";", "$", "count", "=", "$", "this", "->", "buffer", "->", "readUInt8", "(", ")", "&", "0xff", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "$", "indexStart", "=", "$", "this", "->", "assetOffset", "+", "6", ";", "if", "(", "$", "i", ">", "0", ")", "{", "$", "indexStart", "+=", "$", "i", "*", "66", ";", "}", "$", "this", "->", "transaction", "->", "asset", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", "[", "]", "=", "$", "this", "->", "buffer", "->", "position", "(", "$", "indexStart", ")", "->", "readHexRaw", "(", "66", ")", ";", "}", "return", "$", "this", "->", "parseSignatures", "(", "$", "this", "->", "assetOffset", "+", "6", "+", "$", "count", "*", "66", ")", ";", "}" ]
Handle the deserialization of "multi signature registration" data. @return object
[ "Handle", "the", "deserialization", "of", "multi", "signature", "registration", "data", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Deserializers/MultiSignatureRegistration.php#L28-L51
train
ArkEcosystem/php-crypto
src/Transactions/Transaction.php
Transaction.verify
public function verify(): bool { $factory = new PublicKeyFactory; $publicKey = $factory->fromHex($this->senderPublicKey); return $publicKey->verify( Hash::sha256($this->toBytes()), SignatureFactory::fromHex($this->signature) ); }
php
public function verify(): bool { $factory = new PublicKeyFactory; $publicKey = $factory->fromHex($this->senderPublicKey); return $publicKey->verify( Hash::sha256($this->toBytes()), SignatureFactory::fromHex($this->signature) ); }
[ "public", "function", "verify", "(", ")", ":", "bool", "{", "$", "factory", "=", "new", "PublicKeyFactory", ";", "$", "publicKey", "=", "$", "factory", "->", "fromHex", "(", "$", "this", "->", "senderPublicKey", ")", ";", "return", "$", "publicKey", "->", "verify", "(", "Hash", "::", "sha256", "(", "$", "this", "->", "toBytes", "(", ")", ")", ",", "SignatureFactory", "::", "fromHex", "(", "$", "this", "->", "signature", ")", ")", ";", "}" ]
Verify the transaction. @return bool
[ "Verify", "the", "transaction", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Transaction.php#L78-L87
train
ArkEcosystem/php-crypto
src/Transactions/Transaction.php
Transaction.secondVerify
public function secondVerify(string $secondPublicKey): bool { $factory = new PublicKeyFactory; $secondPublicKey = $factory->fromHex($secondPublicKey); return $secondPublicKey->verify( Hash::sha256($this->toBytes(false)), SignatureFactory::fromHex($this->signSignature) ); }
php
public function secondVerify(string $secondPublicKey): bool { $factory = new PublicKeyFactory; $secondPublicKey = $factory->fromHex($secondPublicKey); return $secondPublicKey->verify( Hash::sha256($this->toBytes(false)), SignatureFactory::fromHex($this->signSignature) ); }
[ "public", "function", "secondVerify", "(", "string", "$", "secondPublicKey", ")", ":", "bool", "{", "$", "factory", "=", "new", "PublicKeyFactory", ";", "$", "secondPublicKey", "=", "$", "factory", "->", "fromHex", "(", "$", "secondPublicKey", ")", ";", "return", "$", "secondPublicKey", "->", "verify", "(", "Hash", "::", "sha256", "(", "$", "this", "->", "toBytes", "(", "false", ")", ")", ",", "SignatureFactory", "::", "fromHex", "(", "$", "this", "->", "signSignature", ")", ")", ";", "}" ]
Verify the transaction with a second public key. @param string $secondPublicKey @return bool
[ "Verify", "the", "transaction", "with", "a", "second", "public", "key", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Transaction.php#L96-L105
train
ArkEcosystem/php-crypto
src/Transactions/Transaction.php
Transaction.parseSignatures
public function parseSignatures(string $serialized, int $startOffset): self { $this->signature = substr($serialized, $startOffset); $multiSignatureOffset = 0; if (0 === strlen($this->signature)) { unset($this->signature); } else { $signatureLength = intval(substr($this->signature, 2, 2), 16) + 2; $this->signature = substr($serialized, $startOffset, $signatureLength * 2); $multiSignatureOffset += $signatureLength * 2; $this->secondSignature = substr($serialized, $startOffset + $signatureLength * 2); if (! $this->secondSignature || 0 === strlen($this->secondSignature)) { unset($this->secondSignature); } else { if ('ff' === substr($this->secondSignature, 0, 2)) { unset($this->secondSignature); } else { $secondSignatureLength = intval(substr($this->secondSignature, 2, 2), 16) + 2; $this->secondSignature = substr($this->secondSignature, 0, $secondSignatureLength * 2); $multiSignatureOffset += $secondSignatureLength * 2; } } $signatures = substr($serialized, $startOffset + $multiSignatureOffset); if (! $signatures || 0 === strlen($signatures)) { return $this; } if ('ff' !== substr($signatures, 0, 2)) { return $this; } $signatures = substr($signatures, 2); $this->signatures = []; $moreSignatures = true; while ($moreSignatures) { $mLength = intval(substr($signatures, 2, 2), 16); if ($mLength > 0) { $this->signatures[] = substr($signatures, 0, ($mLength + 2) * 2); } else { $moreSignatures = false; } $signatures = substr($signatures, ($mLength + 2) * 2); } } return $this; }
php
public function parseSignatures(string $serialized, int $startOffset): self { $this->signature = substr($serialized, $startOffset); $multiSignatureOffset = 0; if (0 === strlen($this->signature)) { unset($this->signature); } else { $signatureLength = intval(substr($this->signature, 2, 2), 16) + 2; $this->signature = substr($serialized, $startOffset, $signatureLength * 2); $multiSignatureOffset += $signatureLength * 2; $this->secondSignature = substr($serialized, $startOffset + $signatureLength * 2); if (! $this->secondSignature || 0 === strlen($this->secondSignature)) { unset($this->secondSignature); } else { if ('ff' === substr($this->secondSignature, 0, 2)) { unset($this->secondSignature); } else { $secondSignatureLength = intval(substr($this->secondSignature, 2, 2), 16) + 2; $this->secondSignature = substr($this->secondSignature, 0, $secondSignatureLength * 2); $multiSignatureOffset += $secondSignatureLength * 2; } } $signatures = substr($serialized, $startOffset + $multiSignatureOffset); if (! $signatures || 0 === strlen($signatures)) { return $this; } if ('ff' !== substr($signatures, 0, 2)) { return $this; } $signatures = substr($signatures, 2); $this->signatures = []; $moreSignatures = true; while ($moreSignatures) { $mLength = intval(substr($signatures, 2, 2), 16); if ($mLength > 0) { $this->signatures[] = substr($signatures, 0, ($mLength + 2) * 2); } else { $moreSignatures = false; } $signatures = substr($signatures, ($mLength + 2) * 2); } } return $this; }
[ "public", "function", "parseSignatures", "(", "string", "$", "serialized", ",", "int", "$", "startOffset", ")", ":", "self", "{", "$", "this", "->", "signature", "=", "substr", "(", "$", "serialized", ",", "$", "startOffset", ")", ";", "$", "multiSignatureOffset", "=", "0", ";", "if", "(", "0", "===", "strlen", "(", "$", "this", "->", "signature", ")", ")", "{", "unset", "(", "$", "this", "->", "signature", ")", ";", "}", "else", "{", "$", "signatureLength", "=", "intval", "(", "substr", "(", "$", "this", "->", "signature", ",", "2", ",", "2", ")", ",", "16", ")", "+", "2", ";", "$", "this", "->", "signature", "=", "substr", "(", "$", "serialized", ",", "$", "startOffset", ",", "$", "signatureLength", "*", "2", ")", ";", "$", "multiSignatureOffset", "+=", "$", "signatureLength", "*", "2", ";", "$", "this", "->", "secondSignature", "=", "substr", "(", "$", "serialized", ",", "$", "startOffset", "+", "$", "signatureLength", "*", "2", ")", ";", "if", "(", "!", "$", "this", "->", "secondSignature", "||", "0", "===", "strlen", "(", "$", "this", "->", "secondSignature", ")", ")", "{", "unset", "(", "$", "this", "->", "secondSignature", ")", ";", "}", "else", "{", "if", "(", "'ff'", "===", "substr", "(", "$", "this", "->", "secondSignature", ",", "0", ",", "2", ")", ")", "{", "unset", "(", "$", "this", "->", "secondSignature", ")", ";", "}", "else", "{", "$", "secondSignatureLength", "=", "intval", "(", "substr", "(", "$", "this", "->", "secondSignature", ",", "2", ",", "2", ")", ",", "16", ")", "+", "2", ";", "$", "this", "->", "secondSignature", "=", "substr", "(", "$", "this", "->", "secondSignature", ",", "0", ",", "$", "secondSignatureLength", "*", "2", ")", ";", "$", "multiSignatureOffset", "+=", "$", "secondSignatureLength", "*", "2", ";", "}", "}", "$", "signatures", "=", "substr", "(", "$", "serialized", ",", "$", "startOffset", "+", "$", "multiSignatureOffset", ")", ";", "if", "(", "!", "$", "signatures", "||", "0", "===", "strlen", "(", "$", "signatures", ")", ")", "{", "return", "$", "this", ";", "}", "if", "(", "'ff'", "!==", "substr", "(", "$", "signatures", ",", "0", ",", "2", ")", ")", "{", "return", "$", "this", ";", "}", "$", "signatures", "=", "substr", "(", "$", "signatures", ",", "2", ")", ";", "$", "this", "->", "signatures", "=", "[", "]", ";", "$", "moreSignatures", "=", "true", ";", "while", "(", "$", "moreSignatures", ")", "{", "$", "mLength", "=", "intval", "(", "substr", "(", "$", "signatures", ",", "2", ",", "2", ")", ",", "16", ")", ";", "if", "(", "$", "mLength", ">", "0", ")", "{", "$", "this", "->", "signatures", "[", "]", "=", "substr", "(", "$", "signatures", ",", "0", ",", "(", "$", "mLength", "+", "2", ")", "*", "2", ")", ";", "}", "else", "{", "$", "moreSignatures", "=", "false", ";", "}", "$", "signatures", "=", "substr", "(", "$", "signatures", ",", "(", "$", "mLength", "+", "2", ")", "*", "2", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Parse the signature, second signature and multi signatures. @param string $serialized @param int $startOffset @return \ArkEcosystem\Crypto\Transactions\Transaction
[ "Parse", "the", "signature", "second", "signature", "and", "multi", "signatures", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Transaction.php#L115-L169
train
ArkEcosystem/php-crypto
src/Transactions/Transaction.php
Transaction.toBytes
public function toBytes(bool $skipSignature = true, bool $skipSecondSignature = true): Buffer { $buffer = new Writer(); $buffer->writeUInt8($this->type); $buffer->writeUInt32($this->timestamp); $buffer->writeHex($this->senderPublicKey); $skipRecipientId = $this->type === Types::SECOND_SIGNATURE_REGISTRATION || $this->type === Types::MULTI_SIGNATURE_REGISTRATION; if (isset($this->recipientId) && ! $skipRecipientId) { $buffer->writeHex(Base58::decodeCheck($this->recipientId)->getHex()); } else { $buffer->fill(21); } if (isset($this->vendorField) && strlen($this->vendorField) <= 64) { $buffer->writeString($this->vendorField); $vendorFieldLength = strlen($this->vendorField); if ($vendorFieldLength < 64) { $buffer->fill(64 - $vendorFieldLength); } } else { $buffer->fill(64); } $buffer->writeUInt64($this->amount); $buffer->writeUInt64($this->fee); if (Types::SECOND_SIGNATURE_REGISTRATION === $this->type) { $buffer->writeHex($this->asset['signature']['publicKey']); } if (Types::DELEGATE_REGISTRATION === $this->type) { $buffer->writeString($this->asset['delegate']['username']); } if (Types::VOTE === $this->type) { $buffer->writeString(implode('', $this->asset['votes'])); } if (Types::MULTI_SIGNATURE_REGISTRATION === $this->type) { $buffer->writeUInt8($this->asset['multisignature']['min']); $buffer->writeUInt8($this->asset['multisignature']['lifetime']); $buffer->writeString(implode('', $this->asset['multisignature']['keysgroup'])); } if (! $skipSignature && $this->signature) { $buffer->writeHex($this->signature); } if (! $skipSecondSignature && isset($this->signSignature)) { $buffer->writeHex($this->signSignature); } return new Buffer($buffer->toBytes()); }
php
public function toBytes(bool $skipSignature = true, bool $skipSecondSignature = true): Buffer { $buffer = new Writer(); $buffer->writeUInt8($this->type); $buffer->writeUInt32($this->timestamp); $buffer->writeHex($this->senderPublicKey); $skipRecipientId = $this->type === Types::SECOND_SIGNATURE_REGISTRATION || $this->type === Types::MULTI_SIGNATURE_REGISTRATION; if (isset($this->recipientId) && ! $skipRecipientId) { $buffer->writeHex(Base58::decodeCheck($this->recipientId)->getHex()); } else { $buffer->fill(21); } if (isset($this->vendorField) && strlen($this->vendorField) <= 64) { $buffer->writeString($this->vendorField); $vendorFieldLength = strlen($this->vendorField); if ($vendorFieldLength < 64) { $buffer->fill(64 - $vendorFieldLength); } } else { $buffer->fill(64); } $buffer->writeUInt64($this->amount); $buffer->writeUInt64($this->fee); if (Types::SECOND_SIGNATURE_REGISTRATION === $this->type) { $buffer->writeHex($this->asset['signature']['publicKey']); } if (Types::DELEGATE_REGISTRATION === $this->type) { $buffer->writeString($this->asset['delegate']['username']); } if (Types::VOTE === $this->type) { $buffer->writeString(implode('', $this->asset['votes'])); } if (Types::MULTI_SIGNATURE_REGISTRATION === $this->type) { $buffer->writeUInt8($this->asset['multisignature']['min']); $buffer->writeUInt8($this->asset['multisignature']['lifetime']); $buffer->writeString(implode('', $this->asset['multisignature']['keysgroup'])); } if (! $skipSignature && $this->signature) { $buffer->writeHex($this->signature); } if (! $skipSecondSignature && isset($this->signSignature)) { $buffer->writeHex($this->signSignature); } return new Buffer($buffer->toBytes()); }
[ "public", "function", "toBytes", "(", "bool", "$", "skipSignature", "=", "true", ",", "bool", "$", "skipSecondSignature", "=", "true", ")", ":", "Buffer", "{", "$", "buffer", "=", "new", "Writer", "(", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "type", ")", ";", "$", "buffer", "->", "writeUInt32", "(", "$", "this", "->", "timestamp", ")", ";", "$", "buffer", "->", "writeHex", "(", "$", "this", "->", "senderPublicKey", ")", ";", "$", "skipRecipientId", "=", "$", "this", "->", "type", "===", "Types", "::", "SECOND_SIGNATURE_REGISTRATION", "||", "$", "this", "->", "type", "===", "Types", "::", "MULTI_SIGNATURE_REGISTRATION", ";", "if", "(", "isset", "(", "$", "this", "->", "recipientId", ")", "&&", "!", "$", "skipRecipientId", ")", "{", "$", "buffer", "->", "writeHex", "(", "Base58", "::", "decodeCheck", "(", "$", "this", "->", "recipientId", ")", "->", "getHex", "(", ")", ")", ";", "}", "else", "{", "$", "buffer", "->", "fill", "(", "21", ")", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "vendorField", ")", "&&", "strlen", "(", "$", "this", "->", "vendorField", ")", "<=", "64", ")", "{", "$", "buffer", "->", "writeString", "(", "$", "this", "->", "vendorField", ")", ";", "$", "vendorFieldLength", "=", "strlen", "(", "$", "this", "->", "vendorField", ")", ";", "if", "(", "$", "vendorFieldLength", "<", "64", ")", "{", "$", "buffer", "->", "fill", "(", "64", "-", "$", "vendorFieldLength", ")", ";", "}", "}", "else", "{", "$", "buffer", "->", "fill", "(", "64", ")", ";", "}", "$", "buffer", "->", "writeUInt64", "(", "$", "this", "->", "amount", ")", ";", "$", "buffer", "->", "writeUInt64", "(", "$", "this", "->", "fee", ")", ";", "if", "(", "Types", "::", "SECOND_SIGNATURE_REGISTRATION", "===", "$", "this", "->", "type", ")", "{", "$", "buffer", "->", "writeHex", "(", "$", "this", "->", "asset", "[", "'signature'", "]", "[", "'publicKey'", "]", ")", ";", "}", "if", "(", "Types", "::", "DELEGATE_REGISTRATION", "===", "$", "this", "->", "type", ")", "{", "$", "buffer", "->", "writeString", "(", "$", "this", "->", "asset", "[", "'delegate'", "]", "[", "'username'", "]", ")", ";", "}", "if", "(", "Types", "::", "VOTE", "===", "$", "this", "->", "type", ")", "{", "$", "buffer", "->", "writeString", "(", "implode", "(", "''", ",", "$", "this", "->", "asset", "[", "'votes'", "]", ")", ")", ";", "}", "if", "(", "Types", "::", "MULTI_SIGNATURE_REGISTRATION", "===", "$", "this", "->", "type", ")", "{", "$", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "asset", "[", "'multisignature'", "]", "[", "'min'", "]", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "asset", "[", "'multisignature'", "]", "[", "'lifetime'", "]", ")", ";", "$", "buffer", "->", "writeString", "(", "implode", "(", "''", ",", "$", "this", "->", "asset", "[", "'multisignature'", "]", "[", "'keysgroup'", "]", ")", ")", ";", "}", "if", "(", "!", "$", "skipSignature", "&&", "$", "this", "->", "signature", ")", "{", "$", "buffer", "->", "writeHex", "(", "$", "this", "->", "signature", ")", ";", "}", "if", "(", "!", "$", "skipSecondSignature", "&&", "isset", "(", "$", "this", "->", "signSignature", ")", ")", "{", "$", "buffer", "->", "writeHex", "(", "$", "this", "->", "signSignature", ")", ";", "}", "return", "new", "Buffer", "(", "$", "buffer", "->", "toBytes", "(", ")", ")", ";", "}" ]
Convert the transaction to its byte representation. @param bool $skipSignature @param bool $skipSecondSignature @return string
[ "Convert", "the", "transaction", "to", "its", "byte", "representation", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Transaction.php#L179-L234
train
ArkEcosystem/php-crypto
src/Transactions/Transaction.php
Transaction.toArray
public function toArray(): array { return array_filter([ 'amount' => $this->amount, 'asset' => $this->asset ?? null, 'fee' => $this->fee, 'id' => $this->id, 'network' => $this->network ?? Network::get()->version(), 'recipientId' => $this->recipientId ?? null, 'secondSignature' => $this->secondSignature ?? null, 'senderPublicKey' => $this->senderPublicKey, 'signature' => $this->signature, 'signatures' => $this->signatures ?? null, 'signSignature' => $this->signSignature ?? null, 'timestamp' => $this->timestamp, 'type' => $this->type, 'vendorField' => $this->vendorField ?? null, 'version' => $this->version ?? 1, ], function ($element) { if (null !== $element) { return true; } return false; }); }
php
public function toArray(): array { return array_filter([ 'amount' => $this->amount, 'asset' => $this->asset ?? null, 'fee' => $this->fee, 'id' => $this->id, 'network' => $this->network ?? Network::get()->version(), 'recipientId' => $this->recipientId ?? null, 'secondSignature' => $this->secondSignature ?? null, 'senderPublicKey' => $this->senderPublicKey, 'signature' => $this->signature, 'signatures' => $this->signatures ?? null, 'signSignature' => $this->signSignature ?? null, 'timestamp' => $this->timestamp, 'type' => $this->type, 'vendorField' => $this->vendorField ?? null, 'version' => $this->version ?? 1, ], function ($element) { if (null !== $element) { return true; } return false; }); }
[ "public", "function", "toArray", "(", ")", ":", "array", "{", "return", "array_filter", "(", "[", "'amount'", "=>", "$", "this", "->", "amount", ",", "'asset'", "=>", "$", "this", "->", "asset", "??", "null", ",", "'fee'", "=>", "$", "this", "->", "fee", ",", "'id'", "=>", "$", "this", "->", "id", ",", "'network'", "=>", "$", "this", "->", "network", "??", "Network", "::", "get", "(", ")", "->", "version", "(", ")", ",", "'recipientId'", "=>", "$", "this", "->", "recipientId", "??", "null", ",", "'secondSignature'", "=>", "$", "this", "->", "secondSignature", "??", "null", ",", "'senderPublicKey'", "=>", "$", "this", "->", "senderPublicKey", ",", "'signature'", "=>", "$", "this", "->", "signature", ",", "'signatures'", "=>", "$", "this", "->", "signatures", "??", "null", ",", "'signSignature'", "=>", "$", "this", "->", "signSignature", "??", "null", ",", "'timestamp'", "=>", "$", "this", "->", "timestamp", ",", "'type'", "=>", "$", "this", "->", "type", ",", "'vendorField'", "=>", "$", "this", "->", "vendorField", "??", "null", ",", "'version'", "=>", "$", "this", "->", "version", "??", "1", ",", "]", ",", "function", "(", "$", "element", ")", "{", "if", "(", "null", "!==", "$", "element", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "}" ]
Convert the transaction to its array representation. @return array
[ "Convert", "the", "transaction", "to", "its", "array", "representation", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Transaction.php#L261-L286
train
ArkEcosystem/php-crypto
src/Transactions/Serializer.php
Serializer.serialize
public function serialize(): Buffer { $buffer = new Writer(); $buffer->writeUInt8(0xff); $buffer->writeUInt8($this->transaction['version'] ?? 0x01); $buffer->writeUInt8($this->transaction['network'] ?? Network::version()); $buffer->writeUInt8($this->transaction['type']); $buffer->writeUInt32($this->transaction['timestamp']); $buffer->writeHex($this->transaction['senderPublicKey']); $buffer->writeUInt64($this->transaction['fee']); if (isset($this->transaction['vendorField'])) { $vendorFieldLength = strlen($this->transaction['vendorField']); $buffer->writeUInt8($vendorFieldLength); $buffer->writeString($this->transaction['vendorField']); } elseif (isset($this->transaction['vendorFieldHex'])) { $vendorFieldHexLength = strlen($this->transaction['vendorFieldHex']); $buffer->writeUInt8($vendorFieldHexLength / 2); $buffer->writeHex($this->transaction['vendorFieldHex']); } else { $buffer->writeUInt8(0x00); } $this->handleType($buffer); $this->handleSignatures($buffer); return new Buffer($buffer->toBytes()); }
php
public function serialize(): Buffer { $buffer = new Writer(); $buffer->writeUInt8(0xff); $buffer->writeUInt8($this->transaction['version'] ?? 0x01); $buffer->writeUInt8($this->transaction['network'] ?? Network::version()); $buffer->writeUInt8($this->transaction['type']); $buffer->writeUInt32($this->transaction['timestamp']); $buffer->writeHex($this->transaction['senderPublicKey']); $buffer->writeUInt64($this->transaction['fee']); if (isset($this->transaction['vendorField'])) { $vendorFieldLength = strlen($this->transaction['vendorField']); $buffer->writeUInt8($vendorFieldLength); $buffer->writeString($this->transaction['vendorField']); } elseif (isset($this->transaction['vendorFieldHex'])) { $vendorFieldHexLength = strlen($this->transaction['vendorFieldHex']); $buffer->writeUInt8($vendorFieldHexLength / 2); $buffer->writeHex($this->transaction['vendorFieldHex']); } else { $buffer->writeUInt8(0x00); } $this->handleType($buffer); $this->handleSignatures($buffer); return new Buffer($buffer->toBytes()); }
[ "public", "function", "serialize", "(", ")", ":", "Buffer", "{", "$", "buffer", "=", "new", "Writer", "(", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "0xff", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "transaction", "[", "'version'", "]", "??", "0x01", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "transaction", "[", "'network'", "]", "??", "Network", "::", "version", "(", ")", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "$", "this", "->", "transaction", "[", "'type'", "]", ")", ";", "$", "buffer", "->", "writeUInt32", "(", "$", "this", "->", "transaction", "[", "'timestamp'", "]", ")", ";", "$", "buffer", "->", "writeHex", "(", "$", "this", "->", "transaction", "[", "'senderPublicKey'", "]", ")", ";", "$", "buffer", "->", "writeUInt64", "(", "$", "this", "->", "transaction", "[", "'fee'", "]", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "transaction", "[", "'vendorField'", "]", ")", ")", "{", "$", "vendorFieldLength", "=", "strlen", "(", "$", "this", "->", "transaction", "[", "'vendorField'", "]", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "$", "vendorFieldLength", ")", ";", "$", "buffer", "->", "writeString", "(", "$", "this", "->", "transaction", "[", "'vendorField'", "]", ")", ";", "}", "elseif", "(", "isset", "(", "$", "this", "->", "transaction", "[", "'vendorFieldHex'", "]", ")", ")", "{", "$", "vendorFieldHexLength", "=", "strlen", "(", "$", "this", "->", "transaction", "[", "'vendorFieldHex'", "]", ")", ";", "$", "buffer", "->", "writeUInt8", "(", "$", "vendorFieldHexLength", "/", "2", ")", ";", "$", "buffer", "->", "writeHex", "(", "$", "this", "->", "transaction", "[", "'vendorFieldHex'", "]", ")", ";", "}", "else", "{", "$", "buffer", "->", "writeUInt8", "(", "0x00", ")", ";", "}", "$", "this", "->", "handleType", "(", "$", "buffer", ")", ";", "$", "this", "->", "handleSignatures", "(", "$", "buffer", ")", ";", "return", "new", "Buffer", "(", "$", "buffer", "->", "toBytes", "(", ")", ")", ";", "}" ]
Perform AIP11 compliant serialization. @return \BitWasp\Buffertools\Buffer
[ "Perform", "AIP11", "compliant", "serialization", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Transactions/Serializer.php#L73-L100
train
ArkEcosystem/php-crypto
src/Identities/PrivateKey.php
PrivateKey.fromPassphrase
public static function fromPassphrase(string $passphrase): EcPrivateKey { $passphrase = Hash::sha256(new Buffer($passphrase)); return (new PrivateKeyFactory())->fromHexCompressed($passphrase->getHex()); }
php
public static function fromPassphrase(string $passphrase): EcPrivateKey { $passphrase = Hash::sha256(new Buffer($passphrase)); return (new PrivateKeyFactory())->fromHexCompressed($passphrase->getHex()); }
[ "public", "static", "function", "fromPassphrase", "(", "string", "$", "passphrase", ")", ":", "EcPrivateKey", "{", "$", "passphrase", "=", "Hash", "::", "sha256", "(", "new", "Buffer", "(", "$", "passphrase", ")", ")", ";", "return", "(", "new", "PrivateKeyFactory", "(", ")", ")", "->", "fromHexCompressed", "(", "$", "passphrase", "->", "getHex", "(", ")", ")", ";", "}" ]
Derive the private key for the given passphrase. @param string $passphrase @return \BitWasp\Bitcoin\Crypto\EcAdapter\Impl\PhpEcc\Key\PrivateKey
[ "Derive", "the", "private", "key", "for", "the", "given", "passphrase", "." ]
6b0a597ec056991d355b214e5afd209c7cccaa66
https://github.com/ArkEcosystem/php-crypto/blob/6b0a597ec056991d355b214e5afd209c7cccaa66/src/Identities/PrivateKey.php#L36-L41
train