code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function refundAmazonOrder()
{
$oConfig = $this->_getContainer()->getConfig();
$sId = $this->getEditObjectId();
if ((int)$sId !== -1
&& $sId !== null
&& (int)$oConfig->getRequestParameter('blAmazonConfirmRefund') === 1
) {
/** @var oxOrder $oOrder */
$oOrder = $this->_getContainer()->getObjectFactory()->createOxidObject('oxOrder');
$oOrder->load($sId);
$fAmazonRefundAmount = (float)str_replace(
',',
'.',
$oConfig->getRequestParameter('fAmazonRefundAmount')
);
if ($fAmazonRefundAmount > 0) {
$this->_getContainer()->getClient()->refund($oOrder, $fAmazonRefundAmount);
} else {
$this->_aViewData['bestitrefunderror'] = $this->_getContainer()->getLanguage()
->translateString('BESTITAMAZONPAY_INVALID_REFUND_AMOUNT');
}
} else {
$this->_aViewData['bestitrefunderror'] = $this->_getContainer()->getLanguage()
->translateString('BESTITAMAZONPAY_PLEASE_CHECK_REFUND_CHECKBOX');
}
}
|
Sends refund request to Amazon
@throws Exception
|
public function getRefundsStatus()
{
$sId = $this->getEditObjectId();
if ((int)$sId !== -1 && $sId !== null) {
$oDb = $this->_getContainer()->getDatabase();
$sSql = "SELECT BESTITAMAZONREFUNDID
FROM bestitamazonrefunds
WHERE STATE = 'Pending'
AND BESTITAMAZONREFUNDID != ''
AND OXORDERID = {$oDb->quote($sId)}";
$aResult = $oDb->getAll($sSql);
foreach ($aResult as $aRow) {
$this->_getContainer()->getClient()->getRefundDetails($aRow['BESTITAMAZONREFUNDID']);
}
}
}
|
Gets refunds status for the order
@throws Exception
|
public function setQuickCheckoutBasket()
{
$oObjectFactory = $this->getObjectFactory();
$oSession = $this->getSession();
// Create new temp basket and copy the products to it
$oCurrentBasket = $oSession->getBasket();
$oSession->setVariable(self::BESTITAMAZONPAY_TEMP_BASKET, serialize($oCurrentBasket));
//Reset current basket
$oSession->setBasket($oObjectFactory->createOxidObject('oxBasket'));
}
|
Stores the basket which is present before the quick checkout.
@throws oxSystemComponentException
|
protected function _validateBasket($oBasket)
{
$aCurrentContent = $oBasket->getContents();
$iCurrLang = $this->getLanguage()->getBaseLanguage();
/** @var oxBasketItem $oContent */
foreach ($aCurrentContent as $oContent) {
if ($oContent->getLanguageId() !== $iCurrLang) {
$oContent->setLanguageId($iCurrLang);
}
}
}
|
Validates the basket.
@param oxBasket $oBasket
|
public function restoreQuickCheckoutBasket()
{
$oSession = $this->getSession();
$sBasket = $oSession->getVariable(self::BESTITAMAZONPAY_TEMP_BASKET);
if ($sBasket !== null) {
//init oxbasketitem class first #1746
$this->getObjectFactory()->createOxidObject('oxBasketItem');
$oBasket = unserialize($sBasket);
$this->_validateBasket($oBasket);
//Reset old basket
$oSession->setBasket($oBasket);
}
}
|
Restores the basket which was present before the quick checkout.
@throws oxSystemComponentException
|
public function getBasketHash($sAmazonOrderReferenceId, $oBasket)
{
$aBasket = array(
'amazonOrderReferenceId' => $sAmazonOrderReferenceId,
'totalSum' => $oBasket->getBruttoSum(),
'contents' => array()
);
/** @var oxBasketItem $oBasketItem */
foreach ($oBasket->getContents() as $oBasketItem) {
$sId = $oBasketItem->getArticle()->getId();
$aBasket['contents'][$sId] = $oBasketItem->getAmount();
}
return md5(json_encode($aBasket));
}
|
Generates the basket hash.
@param string $sAmazonOrderReferenceId
@param oxBasket|\OxidEsales\Eshop\Application\Model\Basket $oBasket
@return string
@throws oxArticleException
@throws oxArticleInputException
@throws oxNoArticleException
|
public function saveConfVars()
{
$sModuleId = $this->getEditObjectId();
if ($sModuleId === 'bestitamazonpay4oxid') {
$sQuickConfig = $this->_getContainer()->getConfig()->getRequestParameter('bestitAmazonPay4OxidQuickConfig');
try {
$aQuickConfig = json_decode($sQuickConfig, true);
$aMap = array(
'merchant_id' => array('confstrs', 'sAmazonSellerId'),
'access_key' => array('confstrs', 'sAmazonAWSAccessKeyId'),
'secret_key' => array('confpassword', 'sAmazonSignature'),
'client_id' => array('confstrs', 'sAmazonLoginClientId')
);
foreach ($aMap as $sAmazonKey => $aConfigKeys) {
if (isset($aQuickConfig[$sAmazonKey]) === true) {
list($sMainKey, $sSubKey) = $aConfigKeys;
$_POST[$sMainKey][$sSubKey] = $aQuickConfig[$sAmazonKey];
}
}
} catch (\Exception $oException) {
//Do nothing
}
}
$this->_parentSaveConfVars();
}
|
Extends the save config variable function to store the amazon config vars
from the provided config json object.
@throws oxSystemComponentException
|
protected function _getShippingAvailableForPayment($sShipSet)
{
$oDatabase = $this->_getContainer()->getDatabase();
$sSql = "SELECT OXOBJECTID
FROM oxobject2payment
WHERE OXOBJECTID = {$oDatabase->quote($sShipSet)}
AND OXPAYMENTID = {$oDatabase->quote('bestitamazon')}
AND OXTYPE = 'oxdelset'
AND OXTYPE = 'oxdelset' LIMIT 1";
$sShippingId = $oDatabase->getOne($sSql);
return ($sShippingId) ? true : false;
}
|
Returns if Amazon pay is assigned available shipping ways
@param string $sShipSet the string to quote
@return boolean
@throws oxConnectionException
@throws oxSystemComponentException
|
public function getDeliverySetData($sShipSet, $oUser, $oBasket)
{
//Get $aActSets, $sActShipSet, $aActPaymentList in array from parent method
$aResult = parent::getDeliverySetData($sShipSet, $oUser, $oBasket);
return $this->_processResult($aResult, $oUser, $oBasket);
}
|
Returns the delivery set data.
@param string $sShipSet current ship set id (can be null if not set yet)
@param oxUser $oUser active user
@param oxBasket $oBasket basket object
@return array
@throws oxConnectionException
@throws oxSystemComponentException
|
public function wordPressSalts(): array
{
$generator = new Generator(new Factory);
$salts['AUTH_KEY'] = $generator->salt();
$salts['SECURE_AUTH_KEY'] = $generator->salt();
$salts['LOGGED_IN_KEY'] = $generator->salt();
$salts['NONCE_KEY'] = $generator->salt();
$salts['AUTH_SALT'] = $generator->salt();
$salts['SECURE_AUTH_SALT'] = $generator->salt();
$salts['LOGGED_IN_SALT'] = $generator->salt();
$salts['NONCE_SALT'] = $generator->salt();
return $salts;
}
|
Generate and return all the WordPress salts as an array.
@return array
|
public function traditional(): string
{
$salts = $this->wordPressSalts();
return array_reduce(array_keys($salts), function ($saltsString, $key) use ($salts) {
$saltsString .= "define('$key', '$salts[$key]');" . PHP_EOL;
return $saltsString;
}, '');
}
|
Gets an array of WordPress salts and then reduces them to a string for
output to the CLI. Returns them in the traditional WordPress define
format used in wp-config.php files.
@return string
|
public function sendorder()
{
parent::sendorder();
/** @var oxOrder $oOrder */
$oOrder = $this->_getContainer()->getObjectFactory()->createOxidObject('oxOrder');
if ($oOrder->load($this->getEditObjectId()) === true
&& $oOrder->getFieldData('oxPaymentType') === 'bestitamazon'
) {
$this->_getContainer()->getClient()->saveCapture($oOrder);
}
}
|
Capture order after changing it to shipped
@throws Exception
|
protected function _parentFinalizeOrder(oxBasket $oBasket, $oUser, $blRecalculatingOrder = false)
{
return parent::finalizeOrder($oBasket, $oUser, $blRecalculatingOrder);
}
|
@param oxBasket $oBasket
@param oxUser $oUser
@param bool $blRecalculatingOrder
@return int
|
public function cleanAmazonPay($cancelOrderReference = false)
{
$oConfig = $this->_getContainer()->getConfig();
if ($cancelOrderReference === true || (bool) $oConfig->getRequestParameter('cancelOrderReference')) {
$this->_getContainer()->getClient()->cancelOrderReference(
null,
array('amazon_order_reference_id' => $this->_getContainer()
->getSession()
->getVariable('amazonOrderReferenceId')
)
);
}
//Clean all related variables with user data and amazon reference id
$this->_getContainer()->getModule()->cleanAmazonPay();
$sErrorCode = (string)$oConfig->getRequestParameter('bestitAmazonPay4OxidErrorCode');
$sErrorMessage = (string)$oConfig->getRequestParameter('error');
if ($sErrorCode === 'CurrencyUnsupported') {
$sError = self::BESTITAMAZONPAY_ERROR_CURRENCY_UNSUPPORTED;
} elseif ($sErrorCode == 'InvalidParameterValue'
&& (stripos($sErrorMessage, 'presentmentCurrency') !== false
|| stripos($sErrorMessage, 'currencyCode') !== false)
) {
$sError = self::BESTITAMAZONPAY_ERROR_CURRENCY_UNSUPPORTED;
} elseif ($sErrorMessage !== '') {
// error message directly by amazon pay
$sError = $sErrorMessage;
} else {
$sError = self::BESTITAMAZONPAY_ERROR_AMAZON_TERMINATED;
}
/** @var oxUserException $oEx */
$oEx = $this->_getContainer()->getObjectFactory()->createOxidObject('oxUserException');
$oEx->setMessage($sError);
$this->_getContainer()->getUtilsView()->addErrorToDisplay($oEx, false, true);
//Redirect to user step
$this->_getContainer()->getUtils()->redirect($oConfig->getShopSecureHomeUrl().'cl=basket', false);
}
|
Cleans Amazon pay as the selected one, including all related variables and values
@param bool $cancelOrderReference
@throws Exception
@throws oxConnectionException
@throws oxSystemComponentException
|
public function render()
{
$sClass = $this->_getContainer()->getConfig()->getRequestParameter('cl');
//If user was let to change payment, don't let him do other shit, just payment selection
if ($sClass !== 'order'
&& $sClass !== 'thankyou'
&& (bool)$this->_getContainer()->getSession()->getVariable('blAmazonSyncChangePayment') === true
) {
$this->cleanAmazonPay(true);
}
return parent::render();
}
|
Clears amazon pay variables.
@return object
@throws Exception
@throws oxConnectionException
@throws oxSystemComponentException
|
protected function _parentToBasket(
$sProductId = null,
$dAmount = null,
$aSelectList = null,
$aPersistentParameters = null,
$blOverride = false
) {
return parent::tobasket($sProductId, $dAmount, $aSelectList, $aPersistentParameters, $blOverride);
}
|
Parent function wrapper.
@param null|string $sProductId
@param null|float $dAmount
@param null|array $aSelectList
@param null|array $aPersistentParameters
@param bool $blOverride
@return mixed
|
public function tobasket(
$sProductId = null,
$dAmount = null,
$aSelectList = null,
$aPersistentParameters = null,
$blOverride = false
) {
$oContainer = $this->_getContainer();
$oConfig = $oContainer->getConfig();
$isAmazonPay = (bool)$oConfig->getRequestParameter('bestitAmazonPayIsAmazonPay');
$sReturn = null;
if ($isAmazonPay === true) {
$oContainer->getBasketUtil()->setQuickCheckoutBasket();
$sAmazonOrderReferenceId = $oConfig->getRequestParameter('amazonOrderReferenceId');
$sAccessToken = $oConfig->getRequestParameter('access_token');
$sReturn = 'user?fnc=amazonLogin&redirectCl=user&amazonOrderReferenceId='.$sAmazonOrderReferenceId
.'&access_token='.$sAccessToken;
}
$sDefaultReturn = $this->_parentToBasket(
$sProductId,
$dAmount,
$aSelectList,
$aPersistentParameters,
$blOverride
);
if ($isAmazonPay === true) {
$oSession = $oContainer->getSession();
$oSession->setVariable('blAddedNewItem', false);
$oSession->setVariable('isAmazonPayQuickCheckout', true);
return $sReturn;
}
return $sDefaultReturn;
}
|
Check if we are using amazon quick checkout.
@param null|string $sProductId
@param null|float $dAmount
@param null|array $aSelectList
@param null|array $aPersistentParameters
@param bool $blOverride
@return mixed
@throws oxSystemComponentException
|
public function getSelfLink()
{
try {
if ((bool)$this->_getContainer()->getConfig()->getConfigParam('sSSLShopURL') === true
&& !$this->isAdmin()
&& $this->getAmazonLoginIsActive()
) {
return $this->getSslSelfLink();
}
} catch (Exception $oException) {
//Do nothing
}
return parent::getSelfLink();
}
|
Forces to return shop self link if Amazon Login is active and we already have ORO
Method is dedicated to stay always in checkout process under SSL
@return string
|
public function getBasketLink()
{
if ($this->getAmazonLoginIsActive() === true) {
$sValue = $this->getViewConfigParam('basketlink');
if ((string)$sValue === '') {
$sValue = $this->_getContainer()->getConfig()->getShopSecureHomeUrl().'cl=basket';
$this->setViewConfigParam('basketlink', $sValue);
}
return $sValue;
}
return parent::getBasketLink();
}
|
Forces to return basket link if Amazon Login is active and we already have ORO in SSL
@return string
@throws oxSystemComponentException
|
protected function _getInjectedCode()
{
$oUtils = $this->_getContainer()->getUtils();
$aCodeInjected = $oUtils->fromStaticCache(self::CODE_INJECTED_STATIC_CACHE_KEY);
return $aCodeInjected === null ? array() : $aCodeInjected;
}
|
Loads the injected code map from the static cache.
@return array|mixed
@throws oxSystemComponentException
|
public function setJSCodeInjected($sType)
{
$aCodeInjected = $this->_getInjectedCode();
$aCodeInjected[$sType] = true;
$this->_getContainer()->getUtils()->toStaticCache(self::CODE_INJECTED_STATIC_CACHE_KEY, $aCodeInjected);
}
|
Marks the type as already injected.
@param $sType
@throws oxSystemComponentException
|
public function wasJSCodeInjected($sType)
{
$aCodeInjected = $this->_getInjectedCode();
return isset($aCodeInjected[$sType]) && $aCodeInjected[$sType];
}
|
Checks if the code with given type was already injected.
@param $sType
@return bool
@throws oxSystemComponentException
|
public function getBasketCurrency()
{
$oCurrency = $this->_getContainer()->getSession()->getBasket()->getBasketCurrency();
return $oCurrency !== null ? $oCurrency->name : '';
}
|
Returns the basket currency.
@return string
@throws oxSystemComponentException
|
public function getAmazonBillingAddress()
{
$oOrderReferenceDetails = $this->_getContainer()->getClient()->getOrderReferenceDetails();
$oDetails = $oOrderReferenceDetails->GetOrderReferenceDetailsResult->OrderReferenceDetails;
if (isset($oDetails->BillingAddress) === true) {
$aParsedData = $this->_getContainer()
->getAddressUtil()
->parseAmazonAddress($oDetails->BillingAddress->PhysicalAddress);
return array(
'oxfname' => $aParsedData['FirstName'],
'oxlname' => $aParsedData['LastName'],
'oxcity' => $aParsedData['City'],
'oxstateid' => $aParsedData['StateOrRegion'],
'oxcountryid' => $aParsedData['CountryId'],
'oxzip' => $aParsedData['PostalCode'],
'oxstreet' => $aParsedData['Street'],
'oxstreetnr' => $aParsedData['StreetNr'],
'oxaddinfo' => $aParsedData['AddInfo'],
'oxcompany' => $aParsedData['CompanyName']
);
}
return null;
}
|
Returns the amazon billing address.
@return array|null
@throws Exception
@throws oxConnectionException
@throws oxSystemComponentException
|
public function getCountryName($sCountryId)
{
/** @var oxCountryList $oCountryList */
$oCountry = $this->_getContainer()->getObjectFactory()->createOxidObject('oxCountry');
return ($oCountry->load($sCountryId) === true) ? (string) $oCountry->getFieldData('oxTitle') : '';
}
|
Returns the county name for the current billing address country.
@param string $sCountryId
@return string
@throws oxSystemComponentException
|
public function updateUserWithAmazonData()
{
$billingAddress = $this->getAmazonBillingAddress();
if ($billingAddress !== null) {
$oUser = $this->getUser();
$oUser->assign($billingAddress);
$oUser->save();
}
}
|
Updates the user data with the amazon data.
@throws Exception
@throws oxConnectionException
@throws oxSystemComponentException
|
protected function setBasketHash()
{
$oContainer = $this->_getContainer();
$sBasketHash = $oContainer->getConfig()->getRequestParameter('amazonBasketHash');
if ($sBasketHash) {
$oContainer->getSession()->setVariable('sAmazonBasketHash', $sBasketHash);
}
}
|
Sets the basket hash.
@throws oxSystemComponentException
|
protected function _getLogger()
{
if ($this->_oLogger === null) {
$this->_oLogger = new Logger('AmazonPayment');
$sLogFile = $this->getConfig()->getConfigParam('sShopDir').self::LOG_DIR.'ipn.log';
$this->_oLogger->pushHandler(new StreamHandler($sLogFile));
}
return $this->_oLogger;
}
|
Returns the logger.
@return Logger
@throws Exception
|
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
|
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
|
protected function _loadOrderById($sIdName, $sId)
{
$sQuery = "SELECT OXID
FROM oxorder
WHERE {$sIdName} = {$this->getDatabase()->quote($sId)}";
$sOrderId = (string)$this->getDatabase()->getOne($sQuery);
//Update Order info
/** @var oxOrder $oOrder */
$oOrder = $this->getObjectFactory()->createOxidObject('oxOrder');
if ($oOrder->load($sOrderId) === true) {
return $oOrder;
}
return false;
}
|
@param string $sIdName
@param string $sId
@return bool|oxOrder
@throws oxSystemComponentException
@throws oxConnectionException
|
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
|
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
|
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
|
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;
}
|
Handles response for NotificationType = PaymentRefund
@param stdClass $oData
@return boolean
@throws oxConnectionException
@throws Exception
|
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
|
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
|
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
|
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
|
public function getClassWeight()
{
$weight = 0;
// Look for a special classname
$class = $this->getAttribute('class');
if (trim($class)) {
if (preg_match(NodeUtility::$regexps['negative'], $class)) {
$weight -= 25;
}
if (preg_match(NodeUtility::$regexps['positive'], $class)) {
$weight += 25;
}
}
// Look for a special ID
$id = $this->getAttribute('id');
if (trim($id)) {
if (preg_match(NodeUtility::$regexps['negative'], $id)) {
$weight -= 25;
}
if (preg_match(NodeUtility::$regexps['positive'], $id)) {
$weight += 25;
}
}
return $weight;
}
|
Calculates the weight of the class/id of the current element.
@return int
|
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
|
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
|
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
|
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
|
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
|
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
|
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
|
public function isElementWithoutContent()
{
return $this instanceof DOMElement &&
mb_strlen(preg_replace(NodeUtility::$regexps['onlyWhitespace'], '', $this->textContent)) === 0 &&
($this->childNodes->length === 0 ||
$this->childNodes->length === $this->getElementsByTagName('br')->length + $this->getElementsByTagName('hr')->length
/*
* Special PHP DOMDocument case: We also need to count how many DOMText we have inside the node.
* If there's an empty tag with an space inside and a BR (for example "<p> <br/></p>) counting only BRs and
* HRs will will say that the example has 2 nodes, instead of one. This happens because in DOMDocument,
* DOMTexts are also nodes (which doesn't happen in JS). So we need to also count how many DOMText we
* are dealing with (And at this point we know they are empty or are just whitespace, because of the
* mb_strlen in this chain of checks).
*/
+ count(array_filter(iterator_to_array($this->childNodes), function ($child) {
return $child instanceof DOMText;
}))
);
}
|
Determines if a node has no content or it is just a bunch of dividing lines and/or whitespace.
@return bool
|
public function isPhrasingContent()
{
return $this->nodeType === XML_TEXT_NODE || in_array($this->nodeName, $this->phrasing_elems) !== false ||
(!is_null($this->childNodes) &&
($this->nodeName === 'a' || $this->nodeName === 'del' || $this->nodeName === 'ins') &&
array_reduce(iterator_to_array($this->childNodes), function ($carry, $node) {
return $node->isPhrasingContent() && $carry;
}, true)
);
}
|
Determine if a node qualifies as phrasing content.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content.
@return bool
|
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
|
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
|
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));
}
}
|
Tries to get the main article image. Will only update the metadata if the getMetadata function couldn't
find a correct image.
|
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
|
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]
|
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;
}
|
Checks if the node is a byline.
@param DOMNode $node
@param string $matchString
@return bool
|
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
|
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
|
public function _markDataTables(DOMDocument $article)
{
$tables = $article->getElementsByTagName('table');
foreach ($tables as $table) {
/** @var DOMElement $table */
$role = $table->getAttribute('role');
if ($role === 'presentation') {
$table->setReadabilityDataTable(false);
continue;
}
$datatable = $table->getAttribute('datatable');
if ($datatable == '0') {
$table->setReadabilityDataTable(false);
continue;
}
$summary = $table->getAttribute('summary');
if ($summary) {
$table->setReadabilityDataTable(true);
continue;
}
$caption = $table->getElementsByTagName('caption');
if ($caption->length > 0 && $caption->item(0)->childNodes->length > 0) {
$table->setReadabilityDataTable(true);
continue;
}
// If the table has a descendant with any of these tags, consider a data table:
foreach (['col', 'colgroup', 'tfoot', 'thead', 'th'] as $dataTableDescendants) {
if ($table->getElementsByTagName($dataTableDescendants)->length > 0) {
$table->setReadabilityDataTable(true);
continue 2;
}
}
// Nested tables indicate a layout table:
if ($table->getElementsByTagName('table')->length > 0) {
$table->setReadabilityDataTable(false);
continue;
}
$sizeInfo = $table->getRowAndColumnCount();
if ($sizeInfo['rows'] >= 10 || $sizeInfo['columns'] > 4) {
$table->setReadabilityDataTable(true);
continue;
}
// Now just go by size entirely:
$table->setReadabilityDataTable($sizeInfo['rows'] * $sizeInfo['columns'] > 10);
}
}
|
Look for 'data' (as opposed to 'layout') tables, for which we use
similar checks as
https://dxr.mozilla.org/mozilla-central/rev/71224049c0b52ab190564d3ea0eab089a159a4cf/accessible/html/HTMLTableAccessible.cpp#920.
@param DOMDocument $article
@return void
|
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
|
public function _cleanMatchedNodes($node, $regex)
{
$endOfSearchMarkerNode = NodeUtility::getNextNode($node, true);
$next = NodeUtility::getNextNode($node);
while ($next && $next !== $endOfSearchMarkerNode) {
if (preg_match($regex, sprintf('%s %s', $next->getAttribute('class'), $next->getAttribute('id')))) {
$this->logger->debug(sprintf('Removing matched node with regex: \'%s\', node class was: \'%s\', id: \'%s\'', $regex, $next->getAttribute('class'), $next->getAttribute('id')));
$next = NodeUtility::removeAndGetNext($next);
} else {
$next = NodeUtility::getNextNode($next);
}
}
}
|
Clean out elements whose id/class combinations match specific string.
@param $node DOMElement Node to clean
@param $regex string Match id/class combination.
@return void
|
public function _cleanExtraParagraphs(DOMDocument $article)
{
$paragraphs = $article->getElementsByTagName('p');
$length = $paragraphs->length;
for ($i = 0; $i < $length; $i++) {
$paragraph = $paragraphs->item($length - 1 - $i);
$imgCount = $paragraph->getElementsByTagName('img')->length;
$embedCount = $paragraph->getElementsByTagName('embed')->length;
$objectCount = $paragraph->getElementsByTagName('object')->length;
// At this point, nasty iframes have been removed, only remain embedded video ones.
$iframeCount = $paragraph->getElementsByTagName('iframe')->length;
$totalCount = $imgCount + $embedCount + $objectCount + $iframeCount;
if ($totalCount === 0 && !preg_replace(NodeUtility::$regexps['onlyWhitespace'], '', $paragraph->textContent)) {
$this->logger->debug(sprintf('[PrepArticle] Removing extra paragraph. Text content was: \'%s\'', substr($paragraph->textContent, 0, 128)));
$paragraph->parentNode->removeChild($paragraph);
}
}
}
|
@param DOMDocument $article
@return void
|
public function _clean(DOMDocument $article, $tag)
{
$isEmbed = in_array($tag, ['object', 'embed', 'iframe']);
$DOMNodeList = $article->getElementsByTagName($tag);
$length = $DOMNodeList->length;
for ($i = 0; $i < $length; $i++) {
$item = $DOMNodeList->item($length - 1 - $i);
// Allow youtube and vimeo videos through as people usually want to see those.
if ($isEmbed) {
$attributeValues = [];
foreach ($item->attributes as $value) {
$attributeValues[] = $value->nodeValue;
}
$attributeValues = implode('|', $attributeValues);
// First, check the elements attributes to see if any of them contain youtube or vimeo
if (preg_match(NodeUtility::$regexps['videos'], $attributeValues)) {
continue;
}
// Then check the elements inside this element for the same.
if (preg_match(NodeUtility::$regexps['videos'], $item->C14N())) {
continue;
}
}
$this->logger->debug(sprintf('[PrepArticle] Removing node \'%s\'.', $item->tagName));
NodeUtility::removeNode($item);
}
}
|
Clean a node of all elements of type "tag".
(Unless it's a youtube/vimeo video. People love movies.).
@param $article DOMDocument
@param $tag string tag to clean
@return void
|
public function _cleanHeaders(DOMDocument $article)
{
for ($headerIndex = 1; $headerIndex < 3; $headerIndex++) {
$headers = $article->getElementsByTagName('h' . $headerIndex);
/** @var $header DOMElement */
foreach ($headers as $header) {
$weight = 0;
if ($this->configuration->getWeightClasses()) {
$weight = $header->getClassWeight();
}
if ($weight < 0) {
$this->logger->debug(sprintf('[PrepArticle] Removing H node with 0 or less weight. Content was: \'%s\'', substr($header->nodeValue, 0, 128)));
NodeUtility::removeNode($header);
}
}
}
}
|
Clean out spurious headers from an Element. Checks things like classnames and link density.
@param DOMDocument $article
@return void
|
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
|
public function postProcessContent(DOMDocument $article)
{
$this->logger->info('[PostProcess] PostProcessing content...');
// Readability cannot open relative uris so we convert them to absolute uris.
if ($this->configuration->getFixRelativeURLs()) {
foreach (iterator_to_array($article->getElementsByTagName('a')) as $link) {
/** @var DOMElement $link */
$href = $link->getAttribute('href');
if ($href) {
// Replace links with javascript: URIs with text content, since
// they won't work after scripts have been removed from the page.
if (strpos($href, 'javascript:') === 0) {
$this->logger->debug(sprintf('[PostProcess] Removing \'javascript:\' link. Content is: \'%s\'', substr($link->textContent, 0, 128)));
$text = $article->createTextNode($link->textContent);
$link->parentNode->replaceChild($text, $link);
} else {
$this->logger->debug(sprintf('[PostProcess] Converting link to absolute URI: \'%s\'', substr($href, 0, 128)));
$link->setAttribute('href', $this->toAbsoluteURI($href));
}
}
}
foreach ($article->getElementsByTagName('img') as $img) {
/** @var DOMElement $img */
/*
* Extract all possible sources of img url and select the first one on the list.
*/
$url = [
$img->getAttribute('src'),
$img->getAttribute('data-src'),
$img->getAttribute('data-original'),
$img->getAttribute('data-orig'),
$img->getAttribute('data-url')
];
$src = array_filter($url);
$src = reset($src);
if ($src) {
$this->logger->debug(sprintf('[PostProcess] Converting image URL to absolute URI: \'%s\'', substr($src, 0, 128)));
$img->setAttribute('src', $this->toAbsoluteURI($src));
}
}
}
$this->_cleanClasses($article);
return $article;
}
|
@param DOMDocument $article
@return DOMDocument
|
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
|
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
|
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
|
public static function removeAndGetNext($node)
{
$nextNode = self::getNextNode($node, true);
$node->parentNode->removeChild($node);
return $nextNode;
}
|
Removes the current node and returns the next node to be parsed (child, sibling or parent).
@param DOMNode $node
@return DOMNode
|
public static function getNextNode($originalNode, $ignoreSelfAndKids = false)
{
/*
* Traverse the DOM from node to node, starting at the node passed in.
* Pass true for the second parameter to indicate this node itself
* (and its kids) are going away, and we want the next node over.
*
* Calling this in a loop will traverse the DOM depth-first.
*/
// First check for kids if those aren't being ignored
if (!$ignoreSelfAndKids && $originalNode->firstChild) {
return $originalNode->firstChild;
}
// Then for siblings...
if ($originalNode->nextSibling) {
return $originalNode->nextSibling;
}
// And finally, move up the parent chain *and* find a sibling
// (because this is depth-first traversal, we will have already
// seen the parent nodes themselves).
do {
$originalNode = $originalNode->parentNode;
} while ($originalNode && !$originalNode->nextSibling);
return ($originalNode) ? $originalNode->nextSibling : $originalNode;
}
|
Returns the next node. First checks for children (if the flag allows it), then for siblings, and finally
for parents.
@param DOMNode $originalNode
@param bool $ignoreSelfAndKids
@return DOMNode
|
public function getGradeAllowableValues()
{
return [
self::GRADE__1,
self::GRADE__2,
self::GRADE__3,
self::GRADE__4,
self::GRADE__5,
self::GRADE__6,
self::GRADE__7,
self::GRADE__8,
self::GRADE__9,
self::GRADE__10,
self::GRADE__11,
self::GRADE__12,
self::GRADE_PRE_KINDERGARTEN,
self::GRADE_KINDERGARTEN,
self::GRADE_POST_GRADUATE,
self::GRADE_OTHER,
];
}
|
Gets allowable values of the enum
@return string[]
|
public function getRaceAllowableValues()
{
return [
self::RACE_CAUCASIAN,
self::RACE_ASIAN,
self::RACE_BLACK_OR_AFRICAN_AMERICAN,
self::RACE_AMERICAN_INDIAN,
self::RACE_HAWAIIAN_OR_OTHER_PACIFIC_ISLANDER,
self::RACE_TWO_OR_MORE_RACES,
self::RACE_UNKNOWN,
self::RACE_EMPTY,
];
}
|
Gets allowable values of the enum
@return string[]
|
public function listInvalidProperties()
{
$invalidProperties = [];
$allowedValues = $this->getEllStatusAllowableValues();
if (!in_array($this->container['ell_status'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'ell_status', must be one of '%s'",
implode("', '", $allowedValues)
);
}
$allowedValues = $this->getGenderAllowableValues();
if (!in_array($this->container['gender'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'gender', must be one of '%s'",
implode("', '", $allowedValues)
);
}
$allowedValues = $this->getGradeAllowableValues();
if (!in_array($this->container['grade'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'grade', must be one of '%s'",
implode("', '", $allowedValues)
);
}
$allowedValues = $this->getHispanicEthnicityAllowableValues();
if (!in_array($this->container['hispanic_ethnicity'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'hispanic_ethnicity', must be one of '%s'",
implode("', '", $allowedValues)
);
}
$allowedValues = $this->getHomeLanguageAllowableValues();
if (!in_array($this->container['home_language'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'home_language', must be one of '%s'",
implode("', '", $allowedValues)
);
}
$allowedValues = $this->getRaceAllowableValues();
if (!in_array($this->container['race'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'race', must be one of '%s'",
implode("', '", $allowedValues)
);
}
return $invalidProperties;
}
|
Show all the invalid properties with reasons.
@return array invalid properties with reasons
|
public function valid()
{
$allowedValues = $this->getEllStatusAllowableValues();
if (!in_array($this->container['ell_status'], $allowedValues)) {
return false;
}
$allowedValues = $this->getGenderAllowableValues();
if (!in_array($this->container['gender'], $allowedValues)) {
return false;
}
$allowedValues = $this->getGradeAllowableValues();
if (!in_array($this->container['grade'], $allowedValues)) {
return false;
}
$allowedValues = $this->getHispanicEthnicityAllowableValues();
if (!in_array($this->container['hispanic_ethnicity'], $allowedValues)) {
return false;
}
$allowedValues = $this->getHomeLanguageAllowableValues();
if (!in_array($this->container['home_language'], $allowedValues)) {
return false;
}
$allowedValues = $this->getRaceAllowableValues();
if (!in_array($this->container['race'], $allowedValues)) {
return false;
}
return true;
}
|
Validate all the properties in the model
return true if all passed
@return bool True if all properties are valid
|
public function setEllStatus($ell_status)
{
$allowedValues = $this->getEllStatusAllowableValues();
if (!is_null($ell_status) && !in_array($ell_status, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'ell_status', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['ell_status'] = $ell_status;
return $this;
}
|
Sets ell_status
@param string $ell_status ell_status
@return $this
|
public function setGender($gender)
{
$allowedValues = $this->getGenderAllowableValues();
if (!is_null($gender) && !in_array($gender, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'gender', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['gender'] = $gender;
return $this;
}
|
Sets gender
@param string $gender gender
@return $this
|
public function setGrade($grade)
{
$allowedValues = $this->getGradeAllowableValues();
if (!is_null($grade) && !in_array($grade, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'grade', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['grade'] = $grade;
return $this;
}
|
Sets grade
@param string $grade grade
@return $this
|
public function setHispanicEthnicity($hispanic_ethnicity)
{
$allowedValues = $this->getHispanicEthnicityAllowableValues();
if (!is_null($hispanic_ethnicity) && !in_array($hispanic_ethnicity, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'hispanic_ethnicity', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['hispanic_ethnicity'] = $hispanic_ethnicity;
return $this;
}
|
Sets hispanic_ethnicity
@param string $hispanic_ethnicity hispanic_ethnicity
@return $this
|
public function setHomeLanguage($home_language)
{
$allowedValues = $this->getHomeLanguageAllowableValues();
if (!is_null($home_language) && !in_array($home_language, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'home_language', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['home_language'] = $home_language;
return $this;
}
|
Sets home_language
@param string $home_language home_language
@return $this
|
public function setRace($race)
{
$allowedValues = $this->getRaceAllowableValues();
if (!is_null($race) && !in_array($race, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'race', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['race'] = $race;
return $this;
}
|
Sets race
@param string $race race
@return $this
|
public function setStatus($value)
{
if (!in_array($value, [self::STATUS_INACTIVE, self::STATUS_ACTIVE, self::STATUS_DEACTIVATED], true)) {
throw new DomainException('Payment Card status is not in the list');
}
return $this->setAttribute('status', $value);
}
|
@param $value
@return $this
|
public function setReasonCode($value)
{
$allowedReasonCodes = self::allowedReasonCodes();
if (!in_array($value, $allowedReasonCodes, true)) {
throw new DomainException(sprintf(self::MSG_UNEXPECTED_REASON_CODE, implode(', ', $allowedReasonCodes)));
}
return $this->setAttribute('reasonCode', $value);
}
|
@param string $value
@return $this
|
public function setStatus($value)
{
$allowedStatuses = self::allowedStatuses();
if (!in_array($value, $allowedStatuses, true)) {
throw new DomainException(sprintf(self::MSG_UNEXPECTED_STATUS, implode(', ', $allowedStatuses)));
}
return $this->setAttribute('status', $value);
}
|
@param string $value
@throws DomainException
@return $this
|
public function getSubjectAllowableValues()
{
return [
self::SUBJECT_ENGLISHLANGUAGE_ARTS,
self::SUBJECT_MATH,
self::SUBJECT_SCIENCE,
self::SUBJECT_SOCIAL_STUDIES,
self::SUBJECT_LANGUAGE,
self::SUBJECT_HOMEROOMADVISORY,
self::SUBJECT_INTERVENTIONSONLINE_LEARNING,
self::SUBJECT_TECHNOLOGY_AND_ENGINEERING,
self::SUBJECT_PE_AND_HEALTH,
self::SUBJECT_ARTS_AND_MUSIC,
self::SUBJECT_OTHER,
];
}
|
Gets allowable values of the enum
@return string[]
|
public function listInvalidProperties()
{
$invalidProperties = [];
$allowedValues = $this->getGradeAllowableValues();
if (!in_array($this->container['grade'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'grade', must be one of '%s'",
implode("', '", $allowedValues)
);
}
$allowedValues = $this->getSubjectAllowableValues();
if (!in_array($this->container['subject'], $allowedValues)) {
$invalidProperties[] = sprintf(
"invalid value for 'subject', must be one of '%s'",
implode("', '", $allowedValues)
);
}
return $invalidProperties;
}
|
Show all the invalid properties with reasons.
@return array invalid properties with reasons
|
public function valid()
{
$allowedValues = $this->getGradeAllowableValues();
if (!in_array($this->container['grade'], $allowedValues)) {
return false;
}
$allowedValues = $this->getSubjectAllowableValues();
if (!in_array($this->container['subject'], $allowedValues)) {
return false;
}
return true;
}
|
Validate all the properties in the model
return true if all passed
@return bool True if all properties are valid
|
public function setSubject($subject)
{
$allowedValues = $this->getSubjectAllowableValues();
if (!is_null($subject) && !in_array($subject, $allowedValues)) {
throw new \InvalidArgumentException(
sprintf(
"Invalid value for 'subject', must be one of '%s'",
implode("', '", $allowedValues)
)
);
}
$this->container['subject'] = $subject;
return $this;
}
|
Sets subject
@param string $subject subject
@return $this
|
public function offsetSet($offset, $value)
{
if (!is_callable($value)) {
throw new InvalidArgumentException();
}
$this->builders[$offset] = $value;
}
|
{@inheritdoc}
|
public static function createFromData(array $data)
{
if (!isset($data['type'])) {
throw new DomainException(self::MSG_REQUIRED_TYPE);
}
if (!in_array($data['type'], self::allowedRejectionTypes(), true)) {
throw new DomainException(self::MSG_UNSUPPORTED_TYPE);
}
return new self($data);
}
|
@param array $data
@return RejectionReason
|
public function setType($value)
{
if (!in_array($value, self::allowedRejectionTypes(), true)) {
throw new DomainException(self::MSG_UNSUPPORTED_TYPE);
}
return $this->setAttribute('type', $value);
}
|
@param string $value
@return string
|
public function setOp($value): self
{
if (!in_array($value, self::ops(), true)) {
throw new DomainException(sprintf(self::UNEXPECTED_OP, implode(', ', self::ops())));
}
return $this->setAttribute('op', $value);
}
|
@param string $value
@return $this
|
public function createConditions(array $data): array
{
return array_map(function ($data) {
if ($data instanceof self) {
return $data;
}
return self::createFromData((array) $data);
}, $data);
}
|
@param array $data
@return Condition[]|array
|
public function setItems($values)
{
$this->setAttribute('items', []);
foreach ($values as $value) {
$this->addItem($value);
}
return $this;
}
|
@param array|LayoutItem[] $values
@return $this
|
public function addItem($value)
{
if ($value instanceof LayoutItem) {
$value = $value->jsonSerialize();
} elseif (!is_array($value)) {
throw new DomainException('Invalid layout item');
}
$items = $this->getAttribute('items') ?: [];
$items[] = $value;
return $this->setAttribute('items', $items);
}
|
@param array|LayoutItem $value
@throws DomainException
@return $this
|
public function create($data, $subscriptionId = null)
{
if (isset($subscriptionId)) {
return $this->client()->put($data, 'subscriptions/{subscriptionId}', ['subscriptionId' => $subscriptionId]);
}
return $this->client()->post($data, 'subscriptions');
}
|
@param array|JsonSerializable|Subscription $data
@param string $subscriptionId
@throws UnprocessableEntityException The input data does not valid
@return Subscription
|
public static function createFromData(array $data)
{
if (!isset($data['method'])) {
throw new DomainException(self::MSG_REQUIRED_METHOD);
}
switch ($data['method']) {
case PaymentMethod::METHOD_ACH:
$paymentInstrument = new AchInstrument($data);
break;
case PaymentMethod::METHOD_CASH:
$paymentInstrument = new CashInstrument($data);
break;
case PaymentMethod::METHOD_PAYMENT_CARD:
$paymentInstrument = new PaymentCardInstrument($data);
break;
case PaymentMethod::METHOD_PAYPAL:
$paymentInstrument = new PayPalInstrument($data);
break;
default:
throw new DomainException(
sprintf(self::MSG_UNSUPPORTED_METHOD, implode(',', self::$supportMethods))
);
}
return $paymentInstrument;
}
|
@param array $data
@return PaymentMethodInstrument
|
public function setAttempts($values)
{
$this->setAttribute('attempts', []);
foreach ($values as $value) {
$this->addAttempt($value);
}
return $this;
}
|
@param array|PaymentRetryAttempt[] $values
@return $this
|
public function addAttempt($value)
{
if ($value instanceof PaymentRetryAttempt) {
$value = $value->jsonSerialize();
} elseif (!is_array($value)) {
throw new DomainException('Invalid retry attempt item');
}
$attempts = $this->getAttribute('attempts') ?: [];
$attempts[] = $value;
return $this->setAttribute('attempts', $attempts);
}
|
@param array|PaymentRetryAttempt $value
@throws DomainException
@return $this
|
public function setAfterAttemptPolicy($value)
{
if (!in_array(
$value,
[self::AFTER_ATTEMPT_POLICY_NONE, self::AFTER_ATTEMPT_POLICY_CHANGE_RENEWAL_TIME],
true
)) {
throw new DomainException('Invalid after attempt policy');
}
return $this->setAttribute('afterAttemptPolicy', $value);
}
|
@param string $value
@throws DomainException
@return $this
|
public function setAfterRetryEndPolicy($value)
{
if (!in_array(
$value,
[self::AFTER_RETRY_END_POLICY_NONE, self::AFTER_RETRY_END_POLICY_CANCEL_SUBSCRIPTION],
true
)) {
throw new DomainException('Invalid after retry end policy');
}
return $this->setAttribute('afterRetryEndPolicy', $value);
}
|
@param string $value
@throws DomainException
@return $this
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.