repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
CPIGroup/phpAmazonMWS
includes/classes/AmazonFulfillmentOrderList.php
AmazonFulfillmentOrderList.getFullList
public function getFullList(){ if (!isset($this->orderList)){ return false; } $list = array(); $i = 0; foreach($this->orderList as $x){ $list[$i] = new AmazonFulfillmentOrder($this->storeName,$x['SellerFulfillmentOrderId'],$this->mockMode,$this->mockFiles,$this->config); $list[$i]->mockIndex = $this->mockIndex; $list[$i]->fetchOrder(); $i++; } return $list; }
php
public function getFullList(){ if (!isset($this->orderList)){ return false; } $list = array(); $i = 0; foreach($this->orderList as $x){ $list[$i] = new AmazonFulfillmentOrder($this->storeName,$x['SellerFulfillmentOrderId'],$this->mockMode,$this->mockFiles,$this->config); $list[$i]->mockIndex = $this->mockIndex; $list[$i]->fetchOrder(); $i++; } return $list; }
[ "public", "function", "getFullList", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "orderList", ")", ")", "{", "return", "false", ";", "}", "$", "list", "=", "array", "(", ")", ";", "$", "i", "=", "0", ";", "foreach", "(", "$"...
Creates a list of full order objects from the list. (Warning: could take a while.) This method automatically creates an array of <i>AmazonFulfillmentOrder</i> objects and fetches all of their full information from Amazon. Because of throttling, this could take a while if the list has more than a few orders. @return array|boolean array of <i>AmazonFulfillmentOrder</i> objects, or <b>FALSE</b> if list not filled yet
[ "Creates", "a", "list", "of", "full", "order", "objects", "from", "the", "list", ".", "(", "Warning", ":", "could", "take", "a", "while", ".", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonFulfillmentOrderList.php#L269-L282
CPIGroup/phpAmazonMWS
includes/classes/AmazonFulfillmentOrderList.php
AmazonFulfillmentOrderList.getOrder
public function getOrder($i = null){ if (!isset($this->orderList)){ return false; } if (is_numeric($i)){ return $this->orderList[$i]; } else { return $this->orderList; } }
php
public function getOrder($i = null){ if (!isset($this->orderList)){ return false; } if (is_numeric($i)){ return $this->orderList[$i]; } else { return $this->orderList; } }
[ "public", "function", "getOrder", "(", "$", "i", "=", "null", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "orderList", ")", ")", "{", "return", "false", ";", "}", "if", "(", "is_numeric", "(", "$", "i", ")", ")", "{", "return", "...
Returns the specified fulfillment order, or all of them. This method will return <b>FALSE</b> if the list has not yet been filled. The array for a single fulfillment order will have the following fields: <ul> <li><b>SellerFulfillmentOrderId</b> - the ID for the order</li> <li><b>DisplayableOrderId</b> - your ID for the order</li> <li><b>DisplayableOrderDateTime</b> - the time the order was created, in ISO 8601 date format</li> <li><b>ShippingSpeedCategory</b> - shipping speed for the order</li> <li><b>DeliveryWindow</b> (optional) - array of ISO 8601 dates with the keys "StartDateTime" and "EndDateTime"</li> <li><b>DestinationAddress</b> - address array, see <i>AmazonFulfillmentOrderCreator</i> for more details</li> <li><b>FulfillmentAction</b> (optional) - "Ship" or "Hold"</li> <li><b>FulfillmentPolicy</b> (optional) - "FillOrKill", "FillAll", or "FillAllAvailable"</li> <li><b>ReceivedDateTime</b> - the time the order was received by the Amazon fulfillment center, in ISO 8601 date format</li> <li><b>FulfillmentOrderStatus</b> - the status of the order</li> <li><b>StatusUpdatedDateTime</b> - the time the status was last updated, in ISO 8601 date format</li> <li><b>NotificationEmailList</b> (optional) - list of email addresses</li> <li><b>CODSettings</b> (optional) - array, see <i>AmazonFulfillmentOrderCreator</i> for more details</li> </ul> @param int $i [optional] <p>List index to retrieve the value from. If none is given, the entire list will be returned. Defaults to NULL.</p> @return array|boolean array, multi-dimensional array, or <b>FALSE</b> if list not filled yet
[ "Returns", "the", "specified", "fulfillment", "order", "or", "all", "of", "them", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonFulfillmentOrderList.php#L308-L317
CPIGroup/phpAmazonMWS
includes/classes/AmazonProductInfo.php
AmazonProductInfo.setSKUs
public function setSKUs($s){ if (is_string($s)){ $this->resetASINs(); $this->resetSKUs(); $this->options['SellerSKUList.SellerSKU.1'] = $s; } else if (is_array($s)){ $this->resetASINs(); $this->resetSKUs(); $i = 1; foreach ($s as $x){ $this->options['SellerSKUList.SellerSKU.'.$i] = $x; $i++; } } else { return false; } }
php
public function setSKUs($s){ if (is_string($s)){ $this->resetASINs(); $this->resetSKUs(); $this->options['SellerSKUList.SellerSKU.1'] = $s; } else if (is_array($s)){ $this->resetASINs(); $this->resetSKUs(); $i = 1; foreach ($s as $x){ $this->options['SellerSKUList.SellerSKU.'.$i] = $x; $i++; } } else { return false; } }
[ "public", "function", "setSKUs", "(", "$", "s", ")", "{", "if", "(", "is_string", "(", "$", "s", ")", ")", "{", "$", "this", "->", "resetASINs", "(", ")", ";", "$", "this", "->", "resetSKUs", "(", ")", ";", "$", "this", "->", "options", "[", "'...
Sets the feed seller SKU(s). (Required*) This method sets the list of seller SKUs to be sent in the next request. Setting this parameter tells Amazon to only return inventory supplies that match the IDs in the list. If this parameter is set, ASINs cannot be set. @param array|string $s <p>A list of Seller SKUs, or a single SKU string. (max: 20)</p> @return boolean <b>FALSE</b> if improper input
[ "Sets", "the", "feed", "seller", "SKU", "(", "s", ")", ".", "(", "Required", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonProductInfo.php#L57-L73
CPIGroup/phpAmazonMWS
includes/classes/AmazonProductInfo.php
AmazonProductInfo.resetSKUs
protected function resetSKUs(){ foreach($this->options as $op=>$junk){ if(preg_match("#SellerSKUList#",$op)){ unset($this->options[$op]); } } //remove Category-specific name unset($this->options['SellerSKU']); }
php
protected function resetSKUs(){ foreach($this->options as $op=>$junk){ if(preg_match("#SellerSKUList#",$op)){ unset($this->options[$op]); } } //remove Category-specific name unset($this->options['SellerSKU']); }
[ "protected", "function", "resetSKUs", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#SellerSKUList#\"", ",", "$", "op", ")", ")", "{", "unset", "(", "$", ...
Resets the seller SKU options. Since seller SKU is a required parameter, these options should not be removed without replacing them, so this method is not public.
[ "Resets", "the", "seller", "SKU", "options", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonProductInfo.php#L81-L89
CPIGroup/phpAmazonMWS
includes/classes/AmazonProductInfo.php
AmazonProductInfo.resetASINs
protected function resetASINs(){ foreach($this->options as $op=>$junk){ if(preg_match("#ASINList#",$op)){ unset($this->options[$op]); } } //remove Category-specific name unset($this->options['ASIN']); }
php
protected function resetASINs(){ foreach($this->options as $op=>$junk){ if(preg_match("#ASINList#",$op)){ unset($this->options[$op]); } } //remove Category-specific name unset($this->options['ASIN']); }
[ "protected", "function", "resetASINs", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#ASINList#\"", ",", "$", "op", ")", ")", "{", "unset", "(", "$", "thi...
Resets the ASIN options. Since ASIN is a required parameter, these options should not be removed without replacing them, so this method is not public.
[ "Resets", "the", "ASIN", "options", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonProductInfo.php#L124-L132
CPIGroup/phpAmazonMWS
includes/classes/AmazonProductInfo.php
AmazonProductInfo.setExcludeSelf
public function setExcludeSelf($s = 'true'){ if ($s == 'true' || (is_bool($s) && $s == true)){ $this->options['ExcludeMe'] = 'true'; } else if ($s == 'false' || (is_bool($s) && $s == false)){ $this->options['ExcludeMe'] = 'false'; } else { return false; } }
php
public function setExcludeSelf($s = 'true'){ if ($s == 'true' || (is_bool($s) && $s == true)){ $this->options['ExcludeMe'] = 'true'; } else if ($s == 'false' || (is_bool($s) && $s == false)){ $this->options['ExcludeMe'] = 'false'; } else { return false; } }
[ "public", "function", "setExcludeSelf", "(", "$", "s", "=", "'true'", ")", "{", "if", "(", "$", "s", "==", "'true'", "||", "(", "is_bool", "(", "$", "s", ")", "&&", "$", "s", "==", "true", ")", ")", "{", "$", "this", "->", "options", "[", "'Exc...
Sets the "ExcludeSelf" flag. (Optional) Sets whether or not the next Lowest Offer Listings request should exclude your own listings. @param string|boolean $s <p>"true" or "false", or boolean</p> @return boolean <b>FALSE</b> if improper input
[ "Sets", "the", "ExcludeSelf", "flag", ".", "(", "Optional", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonProductInfo.php#L158-L166
CPIGroup/phpAmazonMWS
includes/classes/AmazonProductInfo.php
AmazonProductInfo.prepareMyPrice
protected function prepareMyPrice(){ include($this->env); if(isset($THROTTLE_TIME_PRODUCTPRICE)) { $this->throttleTime = $THROTTLE_TIME_PRODUCTPRICE; } $this->throttleGroup = 'GetMyPrice'; unset($this->options['ExcludeMe']); if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ $this->options['Action'] = 'GetMyPriceForSKU'; $this->resetASINs(); } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ $this->options['Action'] = 'GetMyPriceForASIN'; $this->resetSKUs(); } }
php
protected function prepareMyPrice(){ include($this->env); if(isset($THROTTLE_TIME_PRODUCTPRICE)) { $this->throttleTime = $THROTTLE_TIME_PRODUCTPRICE; } $this->throttleGroup = 'GetMyPrice'; unset($this->options['ExcludeMe']); if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ $this->options['Action'] = 'GetMyPriceForSKU'; $this->resetASINs(); } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ $this->options['Action'] = 'GetMyPriceForASIN'; $this->resetSKUs(); } }
[ "protected", "function", "prepareMyPrice", "(", ")", "{", "include", "(", "$", "this", "->", "env", ")", ";", "if", "(", "isset", "(", "$", "THROTTLE_TIME_PRODUCTPRICE", ")", ")", "{", "$", "this", "->", "throttleTime", "=", "$", "THROTTLE_TIME_PRODUCTPRICE"...
Sets up options for using <i>fetchMyPrice</i>. This changes key options for using <i>fetchMyPrice</i>. Please note: because the operation does not use all of the parameters, the ExcludeMe parameter will be removed.
[ "Sets", "up", "options", "for", "using", "<i", ">", "fetchMyPrice<", "/", "i", ">", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonProductInfo.php#L387-L401
CPIGroup/phpAmazonMWS
includes/classes/AmazonProductInfo.php
AmazonProductInfo.prepareCategories
protected function prepareCategories(){ include($this->env); if(isset($THROTTLE_TIME_PRODUCTLIST)) { $this->throttleTime = $THROTTLE_TIME_PRODUCTLIST; } $this->throttleGroup = 'GetProductCategories'; unset($this->options['ExcludeMe']); unset($this->options['ItemCondition']); if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ $this->options['Action'] = 'GetProductCategoriesForSKU'; $this->resetASINs(); $this->options['SellerSKU'] = $this->options['SellerSKUList.SellerSKU.1']; } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ $this->options['Action'] = 'GetProductCategoriesForASIN'; $this->resetSKUs(); $this->options['ASIN'] = $this->options['ASINList.ASIN.1']; } }
php
protected function prepareCategories(){ include($this->env); if(isset($THROTTLE_TIME_PRODUCTLIST)) { $this->throttleTime = $THROTTLE_TIME_PRODUCTLIST; } $this->throttleGroup = 'GetProductCategories'; unset($this->options['ExcludeMe']); unset($this->options['ItemCondition']); if (array_key_exists('SellerSKUList.SellerSKU.1',$this->options)){ $this->options['Action'] = 'GetProductCategoriesForSKU'; $this->resetASINs(); $this->options['SellerSKU'] = $this->options['SellerSKUList.SellerSKU.1']; } else if (array_key_exists('ASINList.ASIN.1',$this->options)){ $this->options['Action'] = 'GetProductCategoriesForASIN'; $this->resetSKUs(); $this->options['ASIN'] = $this->options['ASINList.ASIN.1']; } }
[ "protected", "function", "prepareCategories", "(", ")", "{", "include", "(", "$", "this", "->", "env", ")", ";", "if", "(", "isset", "(", "$", "THROTTLE_TIME_PRODUCTLIST", ")", ")", "{", "$", "this", "->", "throttleTime", "=", "$", "THROTTLE_TIME_PRODUCTLIST...
Sets up options for using <i>fetchCategories</i>. This changes key options for using <i>fetchCategories</i>. Please note: because the operation does not use all of the parameters, some of the parameters will be removed. The following parameters are removed: ItemCondition and ExcludeMe.
[ "Sets", "up", "options", "for", "using", "<i", ">", "fetchCategories<", "/", "i", ">", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonProductInfo.php#L447-L464
CPIGroup/phpAmazonMWS
includes/classes/AmazonSubscription.php
AmazonSubscription.setDeliveryChannel
public function setDeliveryChannel($s) { if (is_string($s)){ $this->options['Destination.DeliveryChannel'] = $s; $this->options['Subscription.Destination.DeliveryChannel'] = $s; } else { return false; } }
php
public function setDeliveryChannel($s) { if (is_string($s)){ $this->options['Destination.DeliveryChannel'] = $s; $this->options['Subscription.Destination.DeliveryChannel'] = $s; } else { return false; } }
[ "public", "function", "setDeliveryChannel", "(", "$", "s", ")", "{", "if", "(", "is_string", "(", "$", "s", ")", ")", "{", "$", "this", "->", "options", "[", "'Destination.DeliveryChannel'", "]", "=", "$", "s", ";", "$", "this", "->", "options", "[", ...
Sets the delivery channel. (Required) This parameter is required for performing any actions with subscription destinations. Possible delivery channel values: "SQS". @param string $s <p>Delivery channel</p> @return boolean <b>FALSE</b> if improper input
[ "Sets", "the", "delivery", "channel", ".", "(", "Required", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonSubscription.php#L43-L50
CPIGroup/phpAmazonMWS
includes/classes/AmazonSubscription.php
AmazonSubscription.setAttributes
public function setAttributes($a) { if (empty($a) || !is_array($a)){ $this->log("Tried to set AttributeList to invalid values", 'Warning'); return false; } $this->resetAttributes(); $i = 1; foreach ($a as $k => $v){ $this->options['Destination.AttributeList.member.'.$i.'.Key'] = $k; $this->options['Destination.AttributeList.member.'.$i.'.Value'] = $v; $this->options['Subscription.Destination.AttributeList.member.'.$i.'.Key'] = $k; $this->options['Subscription.Destination.AttributeList.member.'.$i.'.Value'] = $v; $i++; } }
php
public function setAttributes($a) { if (empty($a) || !is_array($a)){ $this->log("Tried to set AttributeList to invalid values", 'Warning'); return false; } $this->resetAttributes(); $i = 1; foreach ($a as $k => $v){ $this->options['Destination.AttributeList.member.'.$i.'.Key'] = $k; $this->options['Destination.AttributeList.member.'.$i.'.Value'] = $v; $this->options['Subscription.Destination.AttributeList.member.'.$i.'.Key'] = $k; $this->options['Subscription.Destination.AttributeList.member.'.$i.'.Value'] = $v; $i++; } }
[ "public", "function", "setAttributes", "(", "$", "a", ")", "{", "if", "(", "empty", "(", "$", "a", ")", "||", "!", "is_array", "(", "$", "a", ")", ")", "{", "$", "this", "->", "log", "(", "\"Tried to set AttributeList to invalid values\"", ",", "'Warning...
Sets the destination attributes. (Required) This parameter is required for performing any actions with subscription destinations. The array provided should be an array of key/value pairs. Possible attribute keys: "sqsQueueUrl". @param array $a <p>Array of key/value pairs</p> @return boolean <b>FALSE</b> if improper input
[ "Sets", "the", "destination", "attributes", ".", "(", "Required", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonSubscription.php#L61-L75
CPIGroup/phpAmazonMWS
includes/classes/AmazonSubscription.php
AmazonSubscription.resetAttributes
protected function resetAttributes() { foreach($this->options as $op=>$junk){ if(preg_match("#Destination.AttributeList#",$op)){ unset($this->options[$op]); } } }
php
protected function resetAttributes() { foreach($this->options as $op=>$junk){ if(preg_match("#Destination.AttributeList#",$op)){ unset($this->options[$op]); } } }
[ "protected", "function", "resetAttributes", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#Destination.AttributeList#\"", ",", "$", "op", ")", ")", "{", "unset"...
Resets the destination attribute options. Since the list of attributes is a required parameter, these options should not be removed without replacing them, so this method is not public.
[ "Resets", "the", "destination", "attribute", "options", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonSubscription.php#L83-L89
CPIGroup/phpAmazonMWS
includes/classes/AmazonSubscription.php
AmazonSubscription.setNotificationType
public function setNotificationType($s) { if (is_string($s)){ $this->options['Subscription.NotificationType'] = $s; $this->options['NotificationType'] = $s; } else { return false; } /* * List of valid Notification Types: * AnyOfferChanged * FulfillmentOrderStatus */ }
php
public function setNotificationType($s) { if (is_string($s)){ $this->options['Subscription.NotificationType'] = $s; $this->options['NotificationType'] = $s; } else { return false; } /* * List of valid Notification Types: * AnyOfferChanged * FulfillmentOrderStatus */ }
[ "public", "function", "setNotificationType", "(", "$", "s", ")", "{", "if", "(", "is_string", "(", "$", "s", ")", ")", "{", "$", "this", "->", "options", "[", "'Subscription.NotificationType'", "]", "=", "$", "s", ";", "$", "this", "->", "options", "["...
Sets the notification type. (Required for subscriptions) This parameter is required for performing any actions with subscriptions. @param string $s <p>See the comment inside for a list of valid values.</p> @return boolean <b>FALSE</b> if improper input
[ "Sets", "the", "notification", "type", ".", "(", "Required", "for", "subscriptions", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonSubscription.php#L98-L110
CPIGroup/phpAmazonMWS
includes/classes/AmazonSubscription.php
AmazonSubscription.resetDestinationParams
protected function resetDestinationParams() { foreach($this->options as $op=>$junk){ if(preg_match("#^Destination.#",$op)){ unset($this->options[$op]); } } }
php
protected function resetDestinationParams() { foreach($this->options as $op=>$junk){ if(preg_match("#^Destination.#",$op)){ unset($this->options[$op]); } } }
[ "protected", "function", "resetDestinationParams", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#^Destination.#\"", ",", "$", "op", ")", ")", "{", "unset", "...
Resets the destination-specific parameters. Since these are required parameters, these options should not be removed without replacing them, so this method is not public.
[ "Resets", "the", "destination", "-", "specific", "parameters", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonSubscription.php#L132-L138
CPIGroup/phpAmazonMWS
includes/classes/AmazonSubscription.php
AmazonSubscription.resetSubscriptionParams
protected function resetSubscriptionParams() { foreach($this->options as $op=>$junk){ if(preg_match("#Subscription.#",$op)){ unset($this->options[$op]); } } }
php
protected function resetSubscriptionParams() { foreach($this->options as $op=>$junk){ if(preg_match("#Subscription.#",$op)){ unset($this->options[$op]); } } }
[ "protected", "function", "resetSubscriptionParams", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#Subscription.#\"", ",", "$", "op", ")", ")", "{", "unset", ...
Resets the subscription-specific parameters. Since these are required parameters, these options should not be removed without replacing them, so this method is not public.
[ "Resets", "the", "subscription", "-", "specific", "parameters", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonSubscription.php#L146-L152
CPIGroup/phpAmazonMWS
includes/classes/AmazonSubscription.php
AmazonSubscription.parseXml
protected function parseXml($xml) { if (!$xml){ return false; } if (isset($xml->Subscription)) { $this->data = array(); $this->data['NotificationType'] = (string)$xml->Subscription->NotificationType; $this->data['IsEnabled'] = (string)$xml->Subscription->IsEnabled; $this->data['Destination']['DeliveryChannel'] = (string)$xml->Subscription->Destination->DeliveryChannel; foreach ($xml->Subscription->Destination->AttributeList->children() as $x) { $this->data['Destination']['AttributeList'][(string)$x->Key] = (string)$x->Value; } } }
php
protected function parseXml($xml) { if (!$xml){ return false; } if (isset($xml->Subscription)) { $this->data = array(); $this->data['NotificationType'] = (string)$xml->Subscription->NotificationType; $this->data['IsEnabled'] = (string)$xml->Subscription->IsEnabled; $this->data['Destination']['DeliveryChannel'] = (string)$xml->Subscription->Destination->DeliveryChannel; foreach ($xml->Subscription->Destination->AttributeList->children() as $x) { $this->data['Destination']['AttributeList'][(string)$x->Key] = (string)$x->Value; } } }
[ "protected", "function", "parseXml", "(", "$", "xml", ")", "{", "if", "(", "!", "$", "xml", ")", "{", "return", "false", ";", "}", "if", "(", "isset", "(", "$", "xml", "->", "Subscription", ")", ")", "{", "$", "this", "->", "data", "=", "array", ...
Parses XML response into array. This is what reads the response XML and converts it into an array. @param SimpleXMLElement $xml <p>The XML response from Amazon.</p> @return boolean <b>FALSE</b> if no XML data is found
[ "Parses", "XML", "response", "into", "array", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonSubscription.php#L589-L603
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setShipmentType
public function setShipmentType($s) { $options = array( 'SP', 'LTL', ); if (in_array($s, $options)){ $this->options['ShipmentType'] = $s; } else { $this->log('Tried to set ShipmentType to invalid value', 'Warning'); return false; } }
php
public function setShipmentType($s) { $options = array( 'SP', 'LTL', ); if (in_array($s, $options)){ $this->options['ShipmentType'] = $s; } else { $this->log('Tried to set ShipmentType to invalid value', 'Warning'); return false; } }
[ "public", "function", "setShipmentType", "(", "$", "s", ")", "{", "$", "options", "=", "array", "(", "'SP'", ",", "'LTL'", ",", ")", ";", "if", "(", "in_array", "(", "$", "s", ",", "$", "options", ")", ")", "{", "$", "this", "->", "options", "[",...
Sets the shipment type. (Required for send) The other parameters that will be required will change depending on this setting. Use "SP" if the shipment is for small parcels and "LTL" when the shipment is for pallets in a truck. This parameter is required for sending transport content information to Amazon. This parameter is removed by all other actions. @param string $s <p>"SP" or "LTL"</p> @return boolean <b>FALSE</b> if improper input
[ "Sets", "the", "shipment", "type", ".", "(", "Required", "for", "send", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L98-L109
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.determineDetailOption
protected function determineDetailOption() { if (!isset($this->options['IsPartnered']) || !isset($this->options['ShipmentType'])) { $this->log('Cannot set transport details without shipment type and partner parameters!', 'Warning'); return false; } $op = 'TransportDetails.'; if ($this->options['ShipmentType'] == 'SP') { if ($this->options['IsPartnered'] == 'true') { return $op . 'PartneredSmallParcelData'; } else { return $op . 'NonPartneredSmallParcelData'; } } else if ($this->options['ShipmentType'] == 'LTL') { if ($this->options['IsPartnered'] == 'true') { return $op . 'PartneredLtlData'; } else { return $op . 'NonPartneredLtlData'; } } $this->log('Unknown shipment type, cannot set transport details!', 'Warning'); return false; }
php
protected function determineDetailOption() { if (!isset($this->options['IsPartnered']) || !isset($this->options['ShipmentType'])) { $this->log('Cannot set transport details without shipment type and partner parameters!', 'Warning'); return false; } $op = 'TransportDetails.'; if ($this->options['ShipmentType'] == 'SP') { if ($this->options['IsPartnered'] == 'true') { return $op . 'PartneredSmallParcelData'; } else { return $op . 'NonPartneredSmallParcelData'; } } else if ($this->options['ShipmentType'] == 'LTL') { if ($this->options['IsPartnered'] == 'true') { return $op . 'PartneredLtlData'; } else { return $op . 'NonPartneredLtlData'; } } $this->log('Unknown shipment type, cannot set transport details!', 'Warning'); return false; }
[ "protected", "function", "determineDetailOption", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'IsPartnered'", "]", ")", "||", "!", "isset", "(", "$", "this", "->", "options", "[", "'ShipmentType'", "]", ")", ")", "{...
Determines which of the four possible transport detail parameter prefixes should be used. The parameter to use depends on the partnered and shipment type parameters. @return string|boolean parameter prefix or <b>FALSE</b> if it could not be determined
[ "Determines", "which", "of", "the", "four", "possible", "transport", "detail", "parameter", "prefixes", "should", "be", "used", ".", "The", "parameter", "to", "use", "depends", "on", "the", "partnered", "and", "shipment", "type", "parameters", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L116-L137
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setCarrier
public function setCarrier($s){ $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set carrier name because of the shipment type and partnered parameters.', 'Warning'); return false; } if (is_string($s) && $s){ $this->options[$op.'.CarrierName'] = $s; } else { return false; } /* * Valid carrier names when shipment type is set to LTL: * BUSINESS_POST * DHL_AIRWAYS_INC * DHL_UK * PARCELFORCE * DPD * TNT_LOGISTICS_CORPORATION * TNT * YODEL * UNITED_PARCEL_SERVICE_INC * DHL_EXPRESS_USA_INC * FEDERAL_EXPRESS_CORP * UNITED_STATES_POSTAL_SERVICE * OTHER * * Valid carrier names when shipment type is set to SP: * UNITED_PARCEL_SERVICE_INC * DHL_STANDARD */ }
php
public function setCarrier($s){ $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set carrier name because of the shipment type and partnered parameters.', 'Warning'); return false; } if (is_string($s) && $s){ $this->options[$op.'.CarrierName'] = $s; } else { return false; } /* * Valid carrier names when shipment type is set to LTL: * BUSINESS_POST * DHL_AIRWAYS_INC * DHL_UK * PARCELFORCE * DPD * TNT_LOGISTICS_CORPORATION * TNT * YODEL * UNITED_PARCEL_SERVICE_INC * DHL_EXPRESS_USA_INC * FEDERAL_EXPRESS_CORP * UNITED_STATES_POSTAL_SERVICE * OTHER * * Valid carrier names when shipment type is set to SP: * UNITED_PARCEL_SERVICE_INC * DHL_STANDARD */ }
[ "public", "function", "setCarrier", "(", "$", "s", ")", "{", "$", "op", "=", "$", "this", "->", "determineDetailOption", "(", ")", ";", "if", "(", "!", "$", "op", ")", "{", "$", "this", "->", "log", "(", "'Cannot set carrier name because of the shipment ty...
Sets the carrier name used for the shipment. (Required for send*) The partnered and shipment type parameters must be set <i>before</i> setting this parameter. This parameter is required for sending transport content information to Amazon when the carrier is not partnered. This parameter is optional when the carrier is partnered and the shipment type is set to "SP" for Small Parcel. This parameter is removed by all other actions. @param string $s <p>See the comment inside for a list of valid values.</p> @return boolean <b>FALSE</b> if improper input or needed parameters are not set
[ "Sets", "the", "carrier", "name", "used", "for", "the", "shipment", ".", "(", "Required", "for", "send", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L150-L181
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.resetPackages
protected function resetPackages() { foreach($this->options as $op=>$junk){ if(preg_match("#PackageList#",$op)){ unset($this->options[$op]); } } }
php
protected function resetPackages() { foreach($this->options as $op=>$junk){ if(preg_match("#PackageList#",$op)){ unset($this->options[$op]); } } }
[ "protected", "function", "resetPackages", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#PackageList#\"", ",", "$", "op", ")", ")", "{", "unset", "(", "$", ...
Resets the package list parameters. Since package details are required, these parameters should not be removed without replacing them, so this method is not public.
[ "Resets", "the", "package", "list", "parameters", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L249-L255
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setContact
public function setContact($n, $p, $e, $f){ $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set contact info because of the shipment type and partnered parameters.', 'Warning'); return false; } if ($n && $p && $e && $f && is_string($n) && is_string($p) && is_string($e) && is_string($f)){ $this->options[$op.'.Contact.Name'] = $n; $this->options[$op.'.Contact.Phone'] = $p; $this->options[$op.'.Contact.Email'] = $e; $this->options[$op.'.Contact.Fax'] = $f; } else { return false; } }
php
public function setContact($n, $p, $e, $f){ $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set contact info because of the shipment type and partnered parameters.', 'Warning'); return false; } if ($n && $p && $e && $f && is_string($n) && is_string($p) && is_string($e) && is_string($f)){ $this->options[$op.'.Contact.Name'] = $n; $this->options[$op.'.Contact.Phone'] = $p; $this->options[$op.'.Contact.Email'] = $e; $this->options[$op.'.Contact.Fax'] = $f; } else { return false; } }
[ "public", "function", "setContact", "(", "$", "n", ",", "$", "p", ",", "$", "e", ",", "$", "f", ")", "{", "$", "op", "=", "$", "this", "->", "determineDetailOption", "(", ")", ";", "if", "(", "!", "$", "op", ")", "{", "$", "this", "->", "log"...
Sets the contact information for the shipment. (Required for send*) The partnered and shipment type parameters must be set <i>before</i> setting this parameter. This parameter is required when the carrier is partnered and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. This parameter is removed by all other actions. @param string $n <p>Name of the contact person, maximum 50 characters</p> @param string $p <p>Phone number of the contact person, maximum 20 characters</p> @param string $e <p>E-mail address of the contact person, maximum 50 characters</p> @param string $f <p>Fax number of the contact person, maximum 20 characters</p> @return boolean <b>FALSE</b> if improper input or needed parameters are not set
[ "Sets", "the", "contact", "information", "for", "the", "shipment", ".", "(", "Required", "for", "send", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L293-L307
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setFreightClass
public function setFreightClass($n){ $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set freight class because of the shipment type and partnered parameters.', 'Warning'); return false; } if (is_numeric($n) && $n){ $this->options[$op.'.SellerFreightClass'] = $n; } else { return false; } /* * Valid freight class values: * 50 * 55 * 60 * 65 * 70 * 77.5 * 85 * 92.5 * 100 * 110 * 125 * 150 * 175 * 200 * 250 * 300 * 400 * 500 */ }
php
public function setFreightClass($n){ $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set freight class because of the shipment type and partnered parameters.', 'Warning'); return false; } if (is_numeric($n) && $n){ $this->options[$op.'.SellerFreightClass'] = $n; } else { return false; } /* * Valid freight class values: * 50 * 55 * 60 * 65 * 70 * 77.5 * 85 * 92.5 * 100 * 110 * 125 * 150 * 175 * 200 * 250 * 300 * 400 * 500 */ }
[ "public", "function", "setFreightClass", "(", "$", "n", ")", "{", "$", "op", "=", "$", "this", "->", "determineDetailOption", "(", ")", ";", "if", "(", "!", "$", "op", ")", "{", "$", "this", "->", "log", "(", "'Cannot set freight class because of the shipm...
Sets the freight class for the shipment. (Optional for send*) The partnered and shipment type parameters must be set <i>before</i> setting this parameter. This parameter is optional when the carrier is partnered and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. If this parameter is not sent, Amazon will estimate the freight class on their own. This parameter is removed by all other actions. @param int $n <p>See the comment inside for a list of valid values.</p> @return boolean <b>FALSE</b> if improper input or needed parameters are not set
[ "Sets", "the", "freight", "class", "for", "the", "shipment", ".", "(", "Optional", "for", "send", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L343-L375
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setReadyDate
public function setReadyDate($d) { $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set ready date because of the shipment type and partnered parameters.', 'Warning'); return false; } try{ $this->options[$op.'.FreightReadyDate'] = strstr($this->genTime($d), 'T', true); } catch (Exception $e){ unset($this->options[$op.'.FreightReadyDate']); $this->log('Error: '.$e->getMessage(), 'Warning'); return false; } }
php
public function setReadyDate($d) { $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set ready date because of the shipment type and partnered parameters.', 'Warning'); return false; } try{ $this->options[$op.'.FreightReadyDate'] = strstr($this->genTime($d), 'T', true); } catch (Exception $e){ unset($this->options[$op.'.FreightReadyDate']); $this->log('Error: '.$e->getMessage(), 'Warning'); return false; } }
[ "public", "function", "setReadyDate", "(", "$", "d", ")", "{", "$", "op", "=", "$", "this", "->", "determineDetailOption", "(", ")", ";", "if", "(", "!", "$", "op", ")", "{", "$", "this", "->", "log", "(", "'Cannot set ready date because of the shipment ty...
Sets the date that the shipment will be ready for pickup. (Required to send*) The partnered and shipment type parameters must be set <i>before</i> setting this parameter. This parameter is required when the carrier is partnered and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. This parameter is removed by all other actions. @param string $d <p>A time string</p> @return boolean <b>FALSE</b> if improper input or needed parameters are not set
[ "Sets", "the", "date", "that", "the", "shipment", "will", "be", "ready", "for", "pickup", ".", "(", "Required", "to", "send", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L387-L400
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setPallets
public function setPallets($a, $du = 'centimeters', $wu = 'kilograms'){ if (empty($a) || !is_array($a)) { $this->log("Tried to set pallet list to invalid values",'Warning'); return false; } $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set pallets because of the shipment type and partnered parameters.', 'Warning'); return false; } $this->resetPallets(); $i = 1; foreach ($a as $x) { $prefix = $op.'.PalletList.member.'.$i; if (is_array($x)) { if (isset($x['Length']) && isset($x['Width']) && isset($x['Height'])) { $this->options[$prefix.'.Dimensions.Length'] = $x['Length']; $this->options[$prefix.'.Dimensions.Width'] = $x['Width']; $this->options[$prefix.'.Dimensions.Height'] = $x['Height']; $this->options[$prefix.'.Dimensions.Unit'] = $du; } if (isset($x['Weight'])) { $this->options[$prefix.'.Weight.Value'] = $x['Weight']; $this->options[$prefix.'.Weight.Unit'] = $wu; } if (isset($x['IsStacked'])) { if ($x['IsStacked']) { $this->options[$prefix.'.IsStacked'] = 'true'; } else { $this->options[$prefix.'.IsStacked'] = 'false'; } } $i++; } else { $this->resetPallets(); $this->log("Tried to set pallets with invalid array",'Warning'); return false; } } }
php
public function setPallets($a, $du = 'centimeters', $wu = 'kilograms'){ if (empty($a) || !is_array($a)) { $this->log("Tried to set pallet list to invalid values",'Warning'); return false; } $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set pallets because of the shipment type and partnered parameters.', 'Warning'); return false; } $this->resetPallets(); $i = 1; foreach ($a as $x) { $prefix = $op.'.PalletList.member.'.$i; if (is_array($x)) { if (isset($x['Length']) && isset($x['Width']) && isset($x['Height'])) { $this->options[$prefix.'.Dimensions.Length'] = $x['Length']; $this->options[$prefix.'.Dimensions.Width'] = $x['Width']; $this->options[$prefix.'.Dimensions.Height'] = $x['Height']; $this->options[$prefix.'.Dimensions.Unit'] = $du; } if (isset($x['Weight'])) { $this->options[$prefix.'.Weight.Value'] = $x['Weight']; $this->options[$prefix.'.Weight.Unit'] = $wu; } if (isset($x['IsStacked'])) { if ($x['IsStacked']) { $this->options[$prefix.'.IsStacked'] = 'true'; } else { $this->options[$prefix.'.IsStacked'] = 'false'; } } $i++; } else { $this->resetPallets(); $this->log("Tried to set pallets with invalid array",'Warning'); return false; } } }
[ "public", "function", "setPallets", "(", "$", "a", ",", "$", "du", "=", "'centimeters'", ",", "$", "wu", "=", "'kilograms'", ")", "{", "if", "(", "empty", "(", "$", "a", ")", "||", "!", "is_array", "(", "$", "a", ")", ")", "{", "$", "this", "->...
Sets the list of pallets. (Optional for send*) The partnered and shipment type parameters must be set <i>before</i> setting this parameter. This parameter is optional when the carrier is partnered and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. Each pallet array should have the following keys: <ul> <li><b>Length</b> - positive decimal number</li> <li><b>Width</b> - positive decimal number</li> <li><b>Height</b> - positive decimal number</li> <li><b>IsStacked</b> - boolean</li> <li><b>Weight</b> (optional) - integer</li> </ul> This parameter is removed by all other actions. @param array $a <p>See above.</p> @param string $du <p>Dimensions unit: "inches" or "centimeters", defaults to centimeters</p> @param string $wu <p>Weight unit: "pounds" or "kilograms", defaults to kilograms</p> @return boolean <b>FALSE</b> if improper input or needed parameters are not set
[ "Sets", "the", "list", "of", "pallets", ".", "(", "Optional", "for", "send", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L422-L461
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.resetPallets
public function resetPallets() { foreach($this->options as $op=>$junk){ if(preg_match("#PalletList#",$op)){ unset($this->options[$op]); } } }
php
public function resetPallets() { foreach($this->options as $op=>$junk){ if(preg_match("#PalletList#",$op)){ unset($this->options[$op]); } } }
[ "public", "function", "resetPallets", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#PalletList#\"", ",", "$", "op", ")", ")", "{", "unset", "(", "$", "th...
Resets the pallet list parameters. Use this in case you change your mind and want to remove the pallet parameters you previously set.
[ "Resets", "the", "pallet", "list", "parameters", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L468-L474
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setTotalWeight
public function setTotalWeight($v, $u = 'kilograms') { $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set total weight because of the shipment type and partnered parameters.', 'Warning'); return false; } if (!empty($v) && !empty($u) && is_numeric($v) && ($u == 'pounds' || $u == 'kilograms')){ $this->options[$op.'.TotalWeight.Value'] = $v; $this->options[$op.'.TotalWeight.Unit'] = $u; } else { return false; } }
php
public function setTotalWeight($v, $u = 'kilograms') { $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set total weight because of the shipment type and partnered parameters.', 'Warning'); return false; } if (!empty($v) && !empty($u) && is_numeric($v) && ($u == 'pounds' || $u == 'kilograms')){ $this->options[$op.'.TotalWeight.Value'] = $v; $this->options[$op.'.TotalWeight.Unit'] = $u; } else { return false; } }
[ "public", "function", "setTotalWeight", "(", "$", "v", ",", "$", "u", "=", "'kilograms'", ")", "{", "$", "op", "=", "$", "this", "->", "determineDetailOption", "(", ")", ";", "if", "(", "!", "$", "op", ")", "{", "$", "this", "->", "log", "(", "'C...
Sets the total weight for the shipment. (Optional for send*) The partnered and shipment type parameters must be set <i>before</i> setting this parameter. This parameter is optional when the carrier is partnered and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. This parameter is removed by all other actions. @param string $v <p>Decimal number</p> @param string $u <p>"pounds" or "kilograms", defaults to kilograms</p> @return boolean <b>FALSE</b> if improper input or needed parameters are not set
[ "Sets", "the", "total", "weight", "for", "the", "shipment", ".", "(", "Optional", "for", "send", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L487-L499
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.setDeclaredValue
public function setDeclaredValue($v, $c) { $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set declared value because of the shipment type and partnered parameters.', 'Warning'); return false; } if (!empty($v) && !empty($c) && is_numeric($v) && is_string($c) && !is_numeric($c)){ $this->options[$op.'.SellerDeclaredValue.Value'] = $v; $this->options[$op.'.SellerDeclaredValue.CurrencyCode'] = $c; } else { return false; } }
php
public function setDeclaredValue($v, $c) { $op = $this->determineDetailOption(); if (!$op) { $this->log('Cannot set declared value because of the shipment type and partnered parameters.', 'Warning'); return false; } if (!empty($v) && !empty($c) && is_numeric($v) && is_string($c) && !is_numeric($c)){ $this->options[$op.'.SellerDeclaredValue.Value'] = $v; $this->options[$op.'.SellerDeclaredValue.CurrencyCode'] = $c; } else { return false; } }
[ "public", "function", "setDeclaredValue", "(", "$", "v", ",", "$", "c", ")", "{", "$", "op", "=", "$", "this", "->", "determineDetailOption", "(", ")", ";", "if", "(", "!", "$", "op", ")", "{", "$", "this", "->", "log", "(", "'Cannot set declared val...
Sets the declared value for the shipment. (Optional for send*) The partnered and shipment type parameters must be set <i>before</i> setting this parameter. This parameter is optional when the carrier is partnered and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. This parameter is removed by all other actions. @param string $v <p>Money amount</p> @param string $c <p>ISO 4217 currency code (ex: USD)</p> @return boolean <b>FALSE</b> if improper input or needed parameters are not set
[ "Sets", "the", "declared", "value", "for", "the", "shipment", ".", "(", "Optional", "for", "send", "*", ")" ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L512-L524
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.resetTransportDetails
protected function resetTransportDetails() { foreach($this->options as $op=>$junk){ if(preg_match("#TransportDetails#",$op)){ unset($this->options[$op]); } } }
php
protected function resetTransportDetails() { foreach($this->options as $op=>$junk){ if(preg_match("#TransportDetails#",$op)){ unset($this->options[$op]); } } }
[ "protected", "function", "resetTransportDetails", "(", ")", "{", "foreach", "(", "$", "this", "->", "options", "as", "$", "op", "=>", "$", "junk", ")", "{", "if", "(", "preg_match", "(", "\"#TransportDetails#\"", ",", "$", "op", ")", ")", "{", "unset", ...
Resets the transport detail parameters. Since transport details are required, these parameters should not be removed without replacing them, so this method is not public.
[ "Resets", "the", "transport", "detail", "parameters", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L532-L538
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.sendTransportContents
public function sendTransportContents() { if (!$this->verifySendParams()) { return false; } $this->prepareSend(); $url = $this->urlbase.$this->urlbranch; $query = $this->genQuery(); $path = $this->options['Action'].'Result'; if ($this->mockMode){ $xml = $this->fetchMockFile(); } else { $response = $this->sendRequest($url, array('Post'=>$query)); if (!$this->checkResponse($response)){ return false; } $xml = simplexml_load_string($response['body']); } $this->parseXml($xml->$path); }
php
public function sendTransportContents() { if (!$this->verifySendParams()) { return false; } $this->prepareSend(); $url = $this->urlbase.$this->urlbranch; $query = $this->genQuery(); $path = $this->options['Action'].'Result'; if ($this->mockMode){ $xml = $this->fetchMockFile(); } else { $response = $this->sendRequest($url, array('Post'=>$query)); if (!$this->checkResponse($response)){ return false; } $xml = simplexml_load_string($response['body']); } $this->parseXml($xml->$path); }
[ "public", "function", "sendTransportContents", "(", ")", "{", "if", "(", "!", "$", "this", "->", "verifySendParams", "(", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "prepareSend", "(", ")", ";", "$", "url", "=", "$", "this", "->",...
Sends transport content information for a shipment with Amazon. Submits a <i>PutTransportContent</i> request to Amazon. In order to do this, a fulfillment shipment ID, shipment type, IsPartnered, and various details are required. The exact details required depend on the IsPartnered and shipment type parameters set. Amazon will send a status back as a response, which can be retrieved using <i>getStatus</i>. @return boolean <b>FALSE</b> if something goes wrong @see verifySendParams
[ "Sends", "transport", "content", "information", "for", "a", "shipment", "with", "Amazon", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L564-L589
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.verifySendParams
protected function verifySendParams() { $m = ' must be set in order to send transport content!'; //common requirements if (!array_key_exists('ShipmentId', $this->options)) { $this->log('Shipment ID'.$m, 'Warning'); return false; } if (!array_key_exists('IsPartnered', $this->options)) { $this->log('IsPartnered'.$m, 'Warning'); return false; } if (!array_key_exists('ShipmentType', $this->options)) { $this->log('Shipment type'.$m, 'Warning'); return false; } //requirements based on partnership and type $p = $this->options['IsPartnered'] == 'true'; $sp = $this->options['ShipmentType'] == 'SP'; $ltl = $this->options['ShipmentType'] == 'LTL'; //options could be in four possible places, so a search is needed $foundCarrier = false; $foundPackages = false; $foundPro = false; $foundContact = false; $foundBoxCount = false; $foundReady = false; foreach ($this->options as $op=>$junk) { if(preg_match("#CarrierName#",$op)){ $foundCarrier = true; } if(preg_match("#PackageList\.member\.1#",$op)){ $foundPackages = true; } if(preg_match("#ProNumber#",$op)){ $foundPro = true; } if(preg_match("#Contact\.Name#",$op)){ $foundContact = true; } if(preg_match("#BoxCount#",$op)){ $foundBoxCount = true; } if(preg_match("#FreightReadyDate#",$op)){ $foundReady = true; } } if (!$p && !$foundCarrier) { $this->log('Carrier'.$m, 'Warning'); return false; } if ($sp && !$foundPackages) { $this->log('Packages'.$m, 'Warning'); return false; } if (!$p && $ltl && !$foundPro) { $this->log('PRO number'.$m, 'Warning'); return false; } if ($p && $ltl && !$foundContact) { $this->log('Contact info'.$m, 'Warning'); return false; } if ($p && $ltl && !$foundBoxCount) { $this->log('Box count'.$m, 'Warning'); return false; } if ($p && $ltl && !$foundReady) { $this->log('Ready date'.$m, 'Warning'); return false; } //all good return true; }
php
protected function verifySendParams() { $m = ' must be set in order to send transport content!'; //common requirements if (!array_key_exists('ShipmentId', $this->options)) { $this->log('Shipment ID'.$m, 'Warning'); return false; } if (!array_key_exists('IsPartnered', $this->options)) { $this->log('IsPartnered'.$m, 'Warning'); return false; } if (!array_key_exists('ShipmentType', $this->options)) { $this->log('Shipment type'.$m, 'Warning'); return false; } //requirements based on partnership and type $p = $this->options['IsPartnered'] == 'true'; $sp = $this->options['ShipmentType'] == 'SP'; $ltl = $this->options['ShipmentType'] == 'LTL'; //options could be in four possible places, so a search is needed $foundCarrier = false; $foundPackages = false; $foundPro = false; $foundContact = false; $foundBoxCount = false; $foundReady = false; foreach ($this->options as $op=>$junk) { if(preg_match("#CarrierName#",$op)){ $foundCarrier = true; } if(preg_match("#PackageList\.member\.1#",$op)){ $foundPackages = true; } if(preg_match("#ProNumber#",$op)){ $foundPro = true; } if(preg_match("#Contact\.Name#",$op)){ $foundContact = true; } if(preg_match("#BoxCount#",$op)){ $foundBoxCount = true; } if(preg_match("#FreightReadyDate#",$op)){ $foundReady = true; } } if (!$p && !$foundCarrier) { $this->log('Carrier'.$m, 'Warning'); return false; } if ($sp && !$foundPackages) { $this->log('Packages'.$m, 'Warning'); return false; } if (!$p && $ltl && !$foundPro) { $this->log('PRO number'.$m, 'Warning'); return false; } if ($p && $ltl && !$foundContact) { $this->log('Contact info'.$m, 'Warning'); return false; } if ($p && $ltl && !$foundBoxCount) { $this->log('Box count'.$m, 'Warning'); return false; } if ($p && $ltl && !$foundReady) { $this->log('Ready date'.$m, 'Warning'); return false; } //all good return true; }
[ "protected", "function", "verifySendParams", "(", ")", "{", "$", "m", "=", "' must be set in order to send transport content!'", ";", "//common requirements", "if", "(", "!", "array_key_exists", "(", "'ShipmentId'", ",", "$", "this", "->", "options", ")", ")", "{", ...
Checks to see if all of the parameters needed for <i>sendTransportContents</i> are set. @return boolean <b>TRUE</b> if everything is good, <b>FALSE</b> if something is missing
[ "Checks", "to", "see", "if", "all", "of", "the", "parameters", "needed", "for", "<i", ">", "sendTransportContents<", "/", "i", ">", "are", "set", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L605-L678
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.parseXml
protected function parseXml($xml) { if (!$xml){ return false; } //response from send, confirm, estimate, void if (isset($xml->TransportResult->TransportStatus)) { $this->status = (string)$xml->TransportResult->TransportStatus; } //response from get if (isset($xml->TransportContent)) { $this->contents = array(); $this->status = (string)$xml->TransportContent->TransportResult->TransportStatus; $this->contents['SellerId'] = (string)$xml->TransportContent->TransportHeader->SellerId; $this->contents['ShipmentId'] = (string)$xml->TransportContent->TransportHeader->ShipmentId; $this->contents['IsPartnered'] = (string)$xml->TransportContent->TransportHeader->IsPartnered; $this->contents['ShipmentType'] = (string)$xml->TransportContent->TransportHeader->ShipmentType; //one of four possible response structures for details $this->contents['Details'] = array(); $d = array(); if (isset($xml->TransportContent->TransportDetails->PartneredSmallParcelData)) { //Partnered + SP $d = $xml->TransportContent->TransportDetails->PartneredSmallParcelData; } else if (isset($xml->TransportContent->TransportDetails->NonPartneredSmallParcelData)) { //Non-Partnered + SP $d = $xml->TransportContent->TransportDetails->NonPartneredSmallParcelData; } else if (isset($xml->TransportContent->TransportDetails->PartneredLtlData)) { //Partnered + LTL $d = $xml->TransportContent->TransportDetails->PartneredLtlData; $this->contents['Details']['Contact']['Name'] = (string)$d->Contact->Name; $this->contents['Details']['Contact']['Phone'] = (string)$d->Contact->Phone; $this->contents['Details']['Contact']['Email'] = (string)$d->Contact->Email; $this->contents['Details']['Contact']['Fax'] = (string)$d->Contact->Fax; $this->contents['Details']['BoxCount'] = (string)$d->BoxCount; if (isset($d->SellerFreightClass)) { $this->contents['Details']['SellerFreightClass'] = (string)$d->SellerFreightClass; } $this->contents['Details']['FreightReadyDate'] = (string)$d->FreightReadyDate; foreach ($d->PalletList->children() as $x) { $temp = array(); $temp['IsStacked'] = (string)$x->IsStacked; $temp['Dimensions']['Unit'] = (string)$x->Dimensions->Unit; $temp['Dimensions']['Length'] = (string)$x->Dimensions->Length; $temp['Dimensions']['Width'] = (string)$x->Dimensions->Width; $temp['Dimensions']['Height'] = (string)$x->Dimensions->Height; if (isset($x->Weight)) { $temp['Weight']['Value'] = (string)$x->Weight->Value; $temp['Weight']['Unit'] = (string)$x->Weight->Unit; } $this->contents['Details']['PalletList'][] = $temp; } $this->contents['Details']['TotalWeight']['Value'] = (string)$d->TotalWeight->Value; $this->contents['Details']['TotalWeight']['Unit'] = (string)$d->TotalWeight->Unit; if (isset($d->SellerDeclaredValue)) { $this->contents['Details']['SellerDeclaredValue']['Value'] = (string)$d->SellerDeclaredValue->Value; $this->contents['Details']['SellerDeclaredValue']['CurrencyCode'] = (string)$d->SellerDeclaredValue->CurrencyCode; } if (isset($d->AmazonCalculatedValue)) { $this->contents['Details']['AmazonCalculatedValue']['Value'] = (string)$d->AmazonCalculatedValue->Value; $this->contents['Details']['AmazonCalculatedValue']['CurrencyCode'] = (string)$d->AmazonCalculatedValue->CurrencyCode; } $this->contents['Details']['PreviewPickupDate'] = (string)$d->PreviewPickupDate; $this->contents['Details']['PreviewDeliveryDate'] = (string)$d->PreviewDeliveryDate; $this->contents['Details']['PreviewFreightClass'] = (string)$d->PreviewFreightClass; $this->contents['Details']['AmazonReferenceId'] = (string)$d->AmazonReferenceId; $this->contents['Details']['IsBillOfLadingAvailable'] = (string)$d->IsBillOfLadingAvailable; $this->contents['Details']['CarrierName'] = (string)$d->CarrierName; } else if (isset($xml->TransportContent->TransportDetails->NonPartneredLtlData)) { //Non-Partnered + LTL $d = $xml->TransportContent->TransportDetails->NonPartneredLtlData; $this->contents['Details']['CarrierName'] = (string)$d->CarrierName; $this->contents['Details']['ProNumber'] = (string)$d->ProNumber; } //shared by both SP structures if (isset($d->PackageList)) { foreach ($d->PackageList->children() as $x) { $temp = array(); $temp['TrackingId'] = (string)$x->TrackingId; $temp['PackageStatus'] = (string)$x->PackageStatus; $temp['CarrierName'] = (string)$x->CarrierName; if (isset($x->Weight)) { $temp['Weight']['Value'] = (string)$x->Weight->Value; $temp['Weight']['Unit'] = (string)$x->Weight->Unit; } if (isset($x->Dimensions)) { $temp['Dimensions']['Unit'] = (string)$x->Dimensions->Unit; $temp['Dimensions']['Length'] = (string)$x->Dimensions->Length; $temp['Dimensions']['Width'] = (string)$x->Dimensions->Width; $temp['Dimensions']['Height'] = (string)$x->Dimensions->Height; } $this->contents['Details']['PackageList'][] = $temp; } } //shared by both partnered structures if (isset($d->PartneredEstimate)) { $pe = array(); $pe['Amount']['Value'] = (string)$d->PartneredEstimate->Amount->Value; $pe['Amount']['CurrencyCode'] = (string)$d->PartneredEstimate->Amount->CurrencyCode; if (isset($d->PartneredEstimate->ConfirmDeadline)) { $pe['ConfirmDeadline'] = (string)$d->PartneredEstimate->ConfirmDeadline; } if (isset($d->PartneredEstimate->ConfirmDeadline)) { $pe['VoidDeadline'] = (string)$d->PartneredEstimate->VoidDeadline; } $this->contents['Details']['PartneredEstimate'] = $pe; } } }
php
protected function parseXml($xml) { if (!$xml){ return false; } //response from send, confirm, estimate, void if (isset($xml->TransportResult->TransportStatus)) { $this->status = (string)$xml->TransportResult->TransportStatus; } //response from get if (isset($xml->TransportContent)) { $this->contents = array(); $this->status = (string)$xml->TransportContent->TransportResult->TransportStatus; $this->contents['SellerId'] = (string)$xml->TransportContent->TransportHeader->SellerId; $this->contents['ShipmentId'] = (string)$xml->TransportContent->TransportHeader->ShipmentId; $this->contents['IsPartnered'] = (string)$xml->TransportContent->TransportHeader->IsPartnered; $this->contents['ShipmentType'] = (string)$xml->TransportContent->TransportHeader->ShipmentType; //one of four possible response structures for details $this->contents['Details'] = array(); $d = array(); if (isset($xml->TransportContent->TransportDetails->PartneredSmallParcelData)) { //Partnered + SP $d = $xml->TransportContent->TransportDetails->PartneredSmallParcelData; } else if (isset($xml->TransportContent->TransportDetails->NonPartneredSmallParcelData)) { //Non-Partnered + SP $d = $xml->TransportContent->TransportDetails->NonPartneredSmallParcelData; } else if (isset($xml->TransportContent->TransportDetails->PartneredLtlData)) { //Partnered + LTL $d = $xml->TransportContent->TransportDetails->PartneredLtlData; $this->contents['Details']['Contact']['Name'] = (string)$d->Contact->Name; $this->contents['Details']['Contact']['Phone'] = (string)$d->Contact->Phone; $this->contents['Details']['Contact']['Email'] = (string)$d->Contact->Email; $this->contents['Details']['Contact']['Fax'] = (string)$d->Contact->Fax; $this->contents['Details']['BoxCount'] = (string)$d->BoxCount; if (isset($d->SellerFreightClass)) { $this->contents['Details']['SellerFreightClass'] = (string)$d->SellerFreightClass; } $this->contents['Details']['FreightReadyDate'] = (string)$d->FreightReadyDate; foreach ($d->PalletList->children() as $x) { $temp = array(); $temp['IsStacked'] = (string)$x->IsStacked; $temp['Dimensions']['Unit'] = (string)$x->Dimensions->Unit; $temp['Dimensions']['Length'] = (string)$x->Dimensions->Length; $temp['Dimensions']['Width'] = (string)$x->Dimensions->Width; $temp['Dimensions']['Height'] = (string)$x->Dimensions->Height; if (isset($x->Weight)) { $temp['Weight']['Value'] = (string)$x->Weight->Value; $temp['Weight']['Unit'] = (string)$x->Weight->Unit; } $this->contents['Details']['PalletList'][] = $temp; } $this->contents['Details']['TotalWeight']['Value'] = (string)$d->TotalWeight->Value; $this->contents['Details']['TotalWeight']['Unit'] = (string)$d->TotalWeight->Unit; if (isset($d->SellerDeclaredValue)) { $this->contents['Details']['SellerDeclaredValue']['Value'] = (string)$d->SellerDeclaredValue->Value; $this->contents['Details']['SellerDeclaredValue']['CurrencyCode'] = (string)$d->SellerDeclaredValue->CurrencyCode; } if (isset($d->AmazonCalculatedValue)) { $this->contents['Details']['AmazonCalculatedValue']['Value'] = (string)$d->AmazonCalculatedValue->Value; $this->contents['Details']['AmazonCalculatedValue']['CurrencyCode'] = (string)$d->AmazonCalculatedValue->CurrencyCode; } $this->contents['Details']['PreviewPickupDate'] = (string)$d->PreviewPickupDate; $this->contents['Details']['PreviewDeliveryDate'] = (string)$d->PreviewDeliveryDate; $this->contents['Details']['PreviewFreightClass'] = (string)$d->PreviewFreightClass; $this->contents['Details']['AmazonReferenceId'] = (string)$d->AmazonReferenceId; $this->contents['Details']['IsBillOfLadingAvailable'] = (string)$d->IsBillOfLadingAvailable; $this->contents['Details']['CarrierName'] = (string)$d->CarrierName; } else if (isset($xml->TransportContent->TransportDetails->NonPartneredLtlData)) { //Non-Partnered + LTL $d = $xml->TransportContent->TransportDetails->NonPartneredLtlData; $this->contents['Details']['CarrierName'] = (string)$d->CarrierName; $this->contents['Details']['ProNumber'] = (string)$d->ProNumber; } //shared by both SP structures if (isset($d->PackageList)) { foreach ($d->PackageList->children() as $x) { $temp = array(); $temp['TrackingId'] = (string)$x->TrackingId; $temp['PackageStatus'] = (string)$x->PackageStatus; $temp['CarrierName'] = (string)$x->CarrierName; if (isset($x->Weight)) { $temp['Weight']['Value'] = (string)$x->Weight->Value; $temp['Weight']['Unit'] = (string)$x->Weight->Unit; } if (isset($x->Dimensions)) { $temp['Dimensions']['Unit'] = (string)$x->Dimensions->Unit; $temp['Dimensions']['Length'] = (string)$x->Dimensions->Length; $temp['Dimensions']['Width'] = (string)$x->Dimensions->Width; $temp['Dimensions']['Height'] = (string)$x->Dimensions->Height; } $this->contents['Details']['PackageList'][] = $temp; } } //shared by both partnered structures if (isset($d->PartneredEstimate)) { $pe = array(); $pe['Amount']['Value'] = (string)$d->PartneredEstimate->Amount->Value; $pe['Amount']['CurrencyCode'] = (string)$d->PartneredEstimate->Amount->CurrencyCode; if (isset($d->PartneredEstimate->ConfirmDeadline)) { $pe['ConfirmDeadline'] = (string)$d->PartneredEstimate->ConfirmDeadline; } if (isset($d->PartneredEstimate->ConfirmDeadline)) { $pe['VoidDeadline'] = (string)$d->PartneredEstimate->VoidDeadline; } $this->contents['Details']['PartneredEstimate'] = $pe; } } }
[ "protected", "function", "parseXml", "(", "$", "xml", ")", "{", "if", "(", "!", "$", "xml", ")", "{", "return", "false", ";", "}", "//response from send, confirm, estimate, void", "if", "(", "isset", "(", "$", "xml", "->", "TransportResult", "->", "Transport...
Parses XML response into array. This is what reads the response XML and converts it into an array. @param SimpleXMLElement $xml <p>The XML response from Amazon.</p> @return boolean <b>FALSE</b> if no XML data is found
[ "Parses", "XML", "response", "into", "array", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L899-L1007
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.getFreightClass
public function getFreightClass() { if (isset($this->contents['Details']['PreviewFreightClass'])){ return $this->contents['Details']['PreviewFreightClass']; } else if (isset($this->contents['Details']['SellerFreightClass'])){ return $this->contents['Details']['SellerFreightClass']; } else { return false; } }
php
public function getFreightClass() { if (isset($this->contents['Details']['PreviewFreightClass'])){ return $this->contents['Details']['PreviewFreightClass']; } else if (isset($this->contents['Details']['SellerFreightClass'])){ return $this->contents['Details']['SellerFreightClass']; } else { return false; } }
[ "public", "function", "getFreightClass", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "contents", "[", "'Details'", "]", "[", "'PreviewFreightClass'", "]", ")", ")", "{", "return", "$", "this", "->", "contents", "[", "'Details'", "]", "[", ...
Returns the freight class for the transport request. This value will only be set if the shipment is with an Amazon-partnered carrier and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. This should be the same as the value that was sent when creating the transport request. If the freight class was not sent before, this is Amazon's estimated freight class based on the description of the contents. See <i>setFreightClass</i> for a list of possible values. This method will return <b>FALSE</b> if the value has not been set yet. @return string|boolean single value, or <b>FALSE</b> if value not set yet @see setFreightClass
[ "Returns", "the", "freight", "class", "for", "the", "transport", "request", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L1315-L1323
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.getTotalWeight
public function getTotalWeight($only = false){ if (isset($this->contents['Details']['TotalWeight'])){ if ($only){ return $this->contents['Details']['TotalWeight']['Value']; } else { return $this->contents['Details']['TotalWeight']; } } else { return false; } }
php
public function getTotalWeight($only = false){ if (isset($this->contents['Details']['TotalWeight'])){ if ($only){ return $this->contents['Details']['TotalWeight']['Value']; } else { return $this->contents['Details']['TotalWeight']; } } else { return false; } }
[ "public", "function", "getTotalWeight", "(", "$", "only", "=", "false", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "contents", "[", "'Details'", "]", "[", "'TotalWeight'", "]", ")", ")", "{", "if", "(", "$", "only", ")", "{", "return", "...
Returns the total weight for the transport request. This value will only be set if the shipment is with an Amazon-partnered carrier and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. This should be the same as the data that was sent when creating the transport request. If an array is returned, it will have the keys <b>Value</b> and <b>Unit</b>. This method will return <b>FALSE</b> if the value has not been set yet. @param boolean $only [optional] <p>set to <b>TRUE</b> to get only the value</p> @return array|string|boolean array, single value, or <b>FALSE</b> if value not set yet
[ "Returns", "the", "total", "weight", "for", "the", "transport", "request", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L1387-L1397
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.getDeclaredValue
public function getDeclaredValue($only = false){ if (isset($this->contents['Details']['SellerDeclaredValue'])){ if ($only){ return $this->contents['Details']['SellerDeclaredValue']['Value']; } else { return $this->contents['Details']['SellerDeclaredValue']; } } else { return false; } }
php
public function getDeclaredValue($only = false){ if (isset($this->contents['Details']['SellerDeclaredValue'])){ if ($only){ return $this->contents['Details']['SellerDeclaredValue']['Value']; } else { return $this->contents['Details']['SellerDeclaredValue']; } } else { return false; } }
[ "public", "function", "getDeclaredValue", "(", "$", "only", "=", "false", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "contents", "[", "'Details'", "]", "[", "'SellerDeclaredValue'", "]", ")", ")", "{", "if", "(", "$", "only", ")", "{", "re...
Returns the seller's declared value for the transport request. This value will only be set if the shipment is with an Amazon-partnered carrier and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. This should be the same as the data that was sent when creating the transport request. If an array is returned, it will have the fields <b>Value</b> and <b>CurrencyCode</b>. This method will return <b>FALSE</b> if the value has not been set yet. @param boolean $only [optional] <p>set to <b>TRUE</b> to get only the value</p> @return array|string|boolean array, single value, or <b>FALSE</b> if value not set yet
[ "Returns", "the", "seller", "s", "declared", "value", "for", "the", "transport", "request", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L1410-L1420
CPIGroup/phpAmazonMWS
includes/classes/AmazonTransport.php
AmazonTransport.getCalculatedValue
public function getCalculatedValue($only = false){ if (isset($this->contents['Details']['AmazonCalculatedValue'])){ if ($only){ return $this->contents['Details']['AmazonCalculatedValue']['Value']; } else { return $this->contents['Details']['AmazonCalculatedValue']; } } else { return false; } }
php
public function getCalculatedValue($only = false){ if (isset($this->contents['Details']['AmazonCalculatedValue'])){ if ($only){ return $this->contents['Details']['AmazonCalculatedValue']['Value']; } else { return $this->contents['Details']['AmazonCalculatedValue']; } } else { return false; } }
[ "public", "function", "getCalculatedValue", "(", "$", "only", "=", "false", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "contents", "[", "'Details'", "]", "[", "'AmazonCalculatedValue'", "]", ")", ")", "{", "if", "(", "$", "only", ")", "{", ...
Returns Amazon's calculated value for the transport request. This value will only be set if the shipment is with an Amazon-partnered carrier and the shipment type is set to "LTL" for Less Than Truckload/Full Truckload. If an array is returned, it will have the fields <b>Value</b> and <b>CurrencyCode</b>. This method will return <b>FALSE</b> if the value has not been set yet. @param boolean $only [optional] <p>set to <b>TRUE</b> to get only the value</p> @return array|string|boolean array, single value, or <b>FALSE</b> if value not set yet
[ "Returns", "Amazon", "s", "calculated", "value", "for", "the", "transport", "request", "." ]
train
https://github.com/CPIGroup/phpAmazonMWS/blob/bf594dcb60e3176ec69148e90bd9e618f41a85d3/includes/classes/AmazonTransport.php#L1432-L1442
Alymosul/exponent-server-sdk-php
lib/Expo.php
Expo.notify
public function notify($interests, array $data, $debug = false) { $postData = []; if (is_string($interests)) { $interests = [$interests]; } if (count($interests) == 0) { throw new ExpoException('Interests array must not be empty.'); } // Gets the expo tokens for the interests $recipients = $this->registrar->getInterests($interests); foreach ($recipients as $token) { $postData[] = $data + ['to' => $token]; } $ch = $this->prepareCurl(); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); $response = $this->executeCurl($ch); // If the notification failed completely, throw an exception with the details if (!$debug && $this->failedCompletely($response, $interests)) { throw ExpoException::failedCompletelyException($response); } return $response; }
php
public function notify($interests, array $data, $debug = false) { $postData = []; if (is_string($interests)) { $interests = [$interests]; } if (count($interests) == 0) { throw new ExpoException('Interests array must not be empty.'); } // Gets the expo tokens for the interests $recipients = $this->registrar->getInterests($interests); foreach ($recipients as $token) { $postData[] = $data + ['to' => $token]; } $ch = $this->prepareCurl(); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); $response = $this->executeCurl($ch); // If the notification failed completely, throw an exception with the details if (!$debug && $this->failedCompletely($response, $interests)) { throw ExpoException::failedCompletelyException($response); } return $response; }
[ "public", "function", "notify", "(", "$", "interests", ",", "array", "$", "data", ",", "$", "debug", "=", "false", ")", "{", "$", "postData", "=", "[", "]", ";", "if", "(", "is_string", "(", "$", "interests", ")", ")", "{", "$", "interests", "=", ...
Send a notification via the Expo Push Notifications Api. @param $interests @param array $data @param bool $debug @throws ExpoException @return array|bool
[ "Send", "a", "notification", "via", "the", "Expo", "Push", "Notifications", "Api", "." ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Expo.php#L87-L118
Alymosul/exponent-server-sdk-php
lib/Expo.php
Expo.failedCompletely
private function failedCompletely(array $response, array $interests) { $numberOfInterests = count($interests); $numberOfFailures = 0; foreach ($response as $item) { if ($item['status'] === 'error') { $numberOfFailures++; } } return $numberOfFailures === $numberOfInterests; }
php
private function failedCompletely(array $response, array $interests) { $numberOfInterests = count($interests); $numberOfFailures = 0; foreach ($response as $item) { if ($item['status'] === 'error') { $numberOfFailures++; } } return $numberOfFailures === $numberOfInterests; }
[ "private", "function", "failedCompletely", "(", "array", "$", "response", ",", "array", "$", "interests", ")", "{", "$", "numberOfInterests", "=", "count", "(", "$", "interests", ")", ";", "$", "numberOfFailures", "=", "0", ";", "foreach", "(", "$", "respo...
Determines if the request we sent has failed completely @param array $response @param array $interests @return bool
[ "Determines", "if", "the", "request", "we", "sent", "has", "failed", "completely" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Expo.php#L128-L140
Alymosul/exponent-server-sdk-php
lib/Expo.php
Expo.prepareCurl
private function prepareCurl() { $ch = $this->getCurl(); // Set cURL opts curl_setopt($ch, CURLOPT_URL, self::EXPO_API_URL); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'accept: application/json', 'content-type: application/json', ]); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return $ch; }
php
private function prepareCurl() { $ch = $this->getCurl(); // Set cURL opts curl_setopt($ch, CURLOPT_URL, self::EXPO_API_URL); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'accept: application/json', 'content-type: application/json', ]); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return $ch; }
[ "private", "function", "prepareCurl", "(", ")", "{", "$", "ch", "=", "$", "this", "->", "getCurl", "(", ")", ";", "// Set cURL opts", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "self", "::", "EXPO_API_URL", ")", ";", "curl_setopt", "(", "$",...
Sets the request url and headers @throws ExpoException @return null|resource
[ "Sets", "the", "request", "url", "and", "headers" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Expo.php#L149-L163
Alymosul/exponent-server-sdk-php
lib/Expo.php
Expo.getCurl
public function getCurl() { // Create or reuse existing cURL handle $this->ch = $this->ch ?? curl_init(); // Throw exception if the cURL handle failed if (!$this->ch) { throw new ExpoException('Could not initialise cURL!'); } return $this->ch; }
php
public function getCurl() { // Create or reuse existing cURL handle $this->ch = $this->ch ?? curl_init(); // Throw exception if the cURL handle failed if (!$this->ch) { throw new ExpoException('Could not initialise cURL!'); } return $this->ch; }
[ "public", "function", "getCurl", "(", ")", "{", "// Create or reuse existing cURL handle", "$", "this", "->", "ch", "=", "$", "this", "->", "ch", "??", "curl_init", "(", ")", ";", "// Throw exception if the cURL handle failed", "if", "(", "!", "$", "this", "->",...
Get the cURL resource @throws ExpoException @return null|resource
[ "Get", "the", "cURL", "resource" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Expo.php#L172-L183
Alymosul/exponent-server-sdk-php
lib/Expo.php
Expo.executeCurl
private function executeCurl($ch) { $response = [ 'body' => curl_exec($ch), 'status_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE) ]; return json_decode($response['body'], true)['data']; }
php
private function executeCurl($ch) { $response = [ 'body' => curl_exec($ch), 'status_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE) ]; return json_decode($response['body'], true)['data']; }
[ "private", "function", "executeCurl", "(", "$", "ch", ")", "{", "$", "response", "=", "[", "'body'", "=>", "curl_exec", "(", "$", "ch", ")", ",", "'status_code'", "=>", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HTTP_CODE", ")", "]", ";", "return", ...
Executes cURL and captures the response @param $ch @return array
[ "Executes", "cURL", "and", "captures", "the", "response" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Expo.php#L192-L200
Alymosul/exponent-server-sdk-php
lib/Exceptions/ExpoException.php
ExpoException.failedCompletelyException
public static function failedCompletelyException($response) { $message = ''; foreach ($response as $key => $item) { if ($item['status'] === 'error') { $message .= $key == 0? "" : "\r\n"; $message .= $item['message']; } } return new static($message); }
php
public static function failedCompletelyException($response) { $message = ''; foreach ($response as $key => $item) { if ($item['status'] === 'error') { $message .= $key == 0? "" : "\r\n"; $message .= $item['message']; } } return new static($message); }
[ "public", "static", "function", "failedCompletelyException", "(", "$", "response", ")", "{", "$", "message", "=", "''", ";", "foreach", "(", "$", "response", "as", "$", "key", "=>", "$", "item", ")", "{", "if", "(", "$", "item", "[", "'status'", "]", ...
Formats the exception for a completely failed request @param $response @return static
[ "Formats", "the", "exception", "for", "a", "completely", "failed", "request" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Exceptions/ExpoException.php#L14-L25
Alymosul/exponent-server-sdk-php
lib/Repositories/ExpoFileDriver.php
ExpoFileDriver.store
public function store($key, $value): bool { $storageInstance = null; try { $storageInstance = $this->getRepository(); } catch (\Exception $e) { // Create the file, if it does not exist.. $storageInstance = $this->createFile(); } // Check for existing tokens if (isset($storageInstance->{$key})) { // If there is a single token, make it an array so we can push the additional tokens in it if (!is_array($storageInstance->{$key})) { $storageInstance->{$key} = [$storageInstance->{$key}]; } // Prevent duplicates if (!in_array($value, $storageInstance->{$key})) { // Add new token to existing key array_push($storageInstance->{$key}, $value); } } else { // First token for this key $storageInstance->{$key} = [$value]; } $file = $this->updateRepository($storageInstance); return (bool) $file; }
php
public function store($key, $value): bool { $storageInstance = null; try { $storageInstance = $this->getRepository(); } catch (\Exception $e) { // Create the file, if it does not exist.. $storageInstance = $this->createFile(); } // Check for existing tokens if (isset($storageInstance->{$key})) { // If there is a single token, make it an array so we can push the additional tokens in it if (!is_array($storageInstance->{$key})) { $storageInstance->{$key} = [$storageInstance->{$key}]; } // Prevent duplicates if (!in_array($value, $storageInstance->{$key})) { // Add new token to existing key array_push($storageInstance->{$key}, $value); } } else { // First token for this key $storageInstance->{$key} = [$value]; } $file = $this->updateRepository($storageInstance); return (bool) $file; }
[ "public", "function", "store", "(", "$", "key", ",", "$", "value", ")", ":", "bool", "{", "$", "storageInstance", "=", "null", ";", "try", "{", "$", "storageInstance", "=", "$", "this", "->", "getRepository", "(", ")", ";", "}", "catch", "(", "\\", ...
Stores an Expo token with a given identifier @param $key @param $value @return bool
[ "Stores", "an", "Expo", "token", "with", "a", "given", "identifier" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Repositories/ExpoFileDriver.php#L24-L55
Alymosul/exponent-server-sdk-php
lib/Repositories/ExpoFileDriver.php
ExpoFileDriver.retrieve
public function retrieve(string $key) { $token = null; $storageInstance = $this->getRepository(); $token = $storageInstance->{$key}?? null; return $token; }
php
public function retrieve(string $key) { $token = null; $storageInstance = $this->getRepository(); $token = $storageInstance->{$key}?? null; return $token; }
[ "public", "function", "retrieve", "(", "string", "$", "key", ")", "{", "$", "token", "=", "null", ";", "$", "storageInstance", "=", "$", "this", "->", "getRepository", "(", ")", ";", "$", "token", "=", "$", "storageInstance", "->", "{", "$", "key", "...
Retrieves an Expo token with a given identifier @param string $key @return array|string|null
[ "Retrieves", "an", "Expo", "token", "with", "a", "given", "identifier" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Repositories/ExpoFileDriver.php#L64-L73
Alymosul/exponent-server-sdk-php
lib/Repositories/ExpoFileDriver.php
ExpoFileDriver.forget
public function forget(string $key, string $value = null): bool { $storageInstance = null; try { $storageInstance = $this->getRepository(); } catch (\Exception $e) { return false; } // Delete a single token with this key and check if there are multiple tokens associated with this key if($value && isset($storageInstance->{$key}) && is_array($storageInstance->{$key}) && count($storageInstance->{$key}) > 1) { // Find our token in list of tokens $index = array_search($value, $storageInstance->{$key}); if (isset($index) && isset($storageInstance->{$key}[$index])) { // Remove single token from list unset($storageInstance->{$key}[$index]); if (count($storageInstance->{$key}) === 0) { // No more tokens left, remove key unset($storageInstance->{$key}); } else { // Reset array key after removing an key $storageInstance->{$key} = array_values($storageInstance->{$key}); } $this->updateRepository($storageInstance); return !in_array($value, $storageInstance->{$key}); } } else { // Delete all tokens with this key unset($storageInstance->{$key}); $this->updateRepository($storageInstance); return !isset($storageInstance->{$key}); } return false; }
php
public function forget(string $key, string $value = null): bool { $storageInstance = null; try { $storageInstance = $this->getRepository(); } catch (\Exception $e) { return false; } // Delete a single token with this key and check if there are multiple tokens associated with this key if($value && isset($storageInstance->{$key}) && is_array($storageInstance->{$key}) && count($storageInstance->{$key}) > 1) { // Find our token in list of tokens $index = array_search($value, $storageInstance->{$key}); if (isset($index) && isset($storageInstance->{$key}[$index])) { // Remove single token from list unset($storageInstance->{$key}[$index]); if (count($storageInstance->{$key}) === 0) { // No more tokens left, remove key unset($storageInstance->{$key}); } else { // Reset array key after removing an key $storageInstance->{$key} = array_values($storageInstance->{$key}); } $this->updateRepository($storageInstance); return !in_array($value, $storageInstance->{$key}); } } else { // Delete all tokens with this key unset($storageInstance->{$key}); $this->updateRepository($storageInstance); return !isset($storageInstance->{$key}); } return false; }
[ "public", "function", "forget", "(", "string", "$", "key", ",", "string", "$", "value", "=", "null", ")", ":", "bool", "{", "$", "storageInstance", "=", "null", ";", "try", "{", "$", "storageInstance", "=", "$", "this", "->", "getRepository", "(", ")",...
Removes an Expo token with a given identifier @param string $key @param string $value @return bool
[ "Removes", "an", "Expo", "token", "with", "a", "given", "identifier" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Repositories/ExpoFileDriver.php#L83-L125
Alymosul/exponent-server-sdk-php
lib/Repositories/ExpoFileDriver.php
ExpoFileDriver.getRepository
private function getRepository() { if (!file_exists($this->storage)) { throw new \Exception('Tokens storage file not found.'); } $file = file_get_contents($this->storage); return json_decode($file); }
php
private function getRepository() { if (!file_exists($this->storage)) { throw new \Exception('Tokens storage file not found.'); } $file = file_get_contents($this->storage); return json_decode($file); }
[ "private", "function", "getRepository", "(", ")", "{", "if", "(", "!", "file_exists", "(", "$", "this", "->", "storage", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Tokens storage file not found.'", ")", ";", "}", "$", "file", "=", "file_get_c...
Gets the storage file contents and converts it into an object @return object @throws \Exception
[ "Gets", "the", "storage", "file", "contents", "and", "converts", "it", "into", "an", "object" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Repositories/ExpoFileDriver.php#L134-L142
Alymosul/exponent-server-sdk-php
lib/Repositories/ExpoFileDriver.php
ExpoFileDriver.createFile
private function createFile() { $file = fopen($this->storage, "w"); fputs($file, '{}'); fclose($file); return json_decode('{}'); }
php
private function createFile() { $file = fopen($this->storage, "w"); fputs($file, '{}'); fclose($file); return json_decode('{}'); }
[ "private", "function", "createFile", "(", ")", "{", "$", "file", "=", "fopen", "(", "$", "this", "->", "storage", ",", "\"w\"", ")", ";", "fputs", "(", "$", "file", ",", "'{}'", ")", ";", "fclose", "(", "$", "file", ")", ";", "return", "json_decode...
Creates the storage file @return object
[ "Creates", "the", "storage", "file" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/Repositories/ExpoFileDriver.php#L162-L168
Alymosul/exponent-server-sdk-php
lib/ExpoRegistrar.php
ExpoRegistrar.registerInterest
public function registerInterest($interest, $token) { if (! $this->isValidExpoPushToken($token)) { throw ExpoRegistrarException::invalidToken(); } $stored = $this->repository->store($interest, $token); if (!$stored) { throw ExpoRegistrarException::couldNotRegisterInterest(); } return $token; }
php
public function registerInterest($interest, $token) { if (! $this->isValidExpoPushToken($token)) { throw ExpoRegistrarException::invalidToken(); } $stored = $this->repository->store($interest, $token); if (!$stored) { throw ExpoRegistrarException::couldNotRegisterInterest(); } return $token; }
[ "public", "function", "registerInterest", "(", "$", "interest", ",", "$", "token", ")", "{", "if", "(", "!", "$", "this", "->", "isValidExpoPushToken", "(", "$", "token", ")", ")", "{", "throw", "ExpoRegistrarException", "::", "invalidToken", "(", ")", ";"...
Registers the given token for the given interest @param $interest @param $token @throws ExpoRegistrarException @return string
[ "Registers", "the", "given", "token", "for", "the", "given", "interest" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/ExpoRegistrar.php#L35-L48
Alymosul/exponent-server-sdk-php
lib/ExpoRegistrar.php
ExpoRegistrar.removeInterest
public function removeInterest($interest, $token = null) { if (!$this->repository->forget($interest, $token)) { throw ExpoRegistrarException::couldNotRemoveInterest(); } return true; }
php
public function removeInterest($interest, $token = null) { if (!$this->repository->forget($interest, $token)) { throw ExpoRegistrarException::couldNotRemoveInterest(); } return true; }
[ "public", "function", "removeInterest", "(", "$", "interest", ",", "$", "token", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "repository", "->", "forget", "(", "$", "interest", ",", "$", "token", ")", ")", "{", "throw", "ExpoRegistrarExce...
Removes token of a given interest @param $interest @param $token @throws ExpoRegistrarException @return bool
[ "Removes", "token", "of", "a", "given", "interest" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/ExpoRegistrar.php#L60-L67
Alymosul/exponent-server-sdk-php
lib/ExpoRegistrar.php
ExpoRegistrar.getInterests
public function getInterests(array $interests): array { $tokens = []; foreach ($interests as $interest) { $retrieved = $this->repository->retrieve($interest); if (!is_null($retrieved)) { if(is_string($retrieved)) { $tokens[] = $retrieved; } if(is_array($retrieved)) { foreach($retrieved as $token) { if(is_string($token)) { $tokens[] = $token; } } } } } if (empty($tokens)) { throw ExpoRegistrarException::emptyInterests(); } return $tokens; }
php
public function getInterests(array $interests): array { $tokens = []; foreach ($interests as $interest) { $retrieved = $this->repository->retrieve($interest); if (!is_null($retrieved)) { if(is_string($retrieved)) { $tokens[] = $retrieved; } if(is_array($retrieved)) { foreach($retrieved as $token) { if(is_string($token)) { $tokens[] = $token; } } } } } if (empty($tokens)) { throw ExpoRegistrarException::emptyInterests(); } return $tokens; }
[ "public", "function", "getInterests", "(", "array", "$", "interests", ")", ":", "array", "{", "$", "tokens", "=", "[", "]", ";", "foreach", "(", "$", "interests", "as", "$", "interest", ")", "{", "$", "retrieved", "=", "$", "this", "->", "repository", ...
Gets the tokens of the interests @param array $interests @throws ExpoRegistrarException @return array
[ "Gets", "the", "tokens", "of", "the", "interests" ]
train
https://github.com/Alymosul/exponent-server-sdk-php/blob/63589951b6b06a40653bf9bc975e9f2f597697aa/lib/ExpoRegistrar.php#L78-L105
Paragraph1/php-fcm
src/Client.php
Client.send
public function send(Message $message) { return $this->guzzleClient->post( $this->getApiUrl(), [ 'headers' => [ 'Authorization' => sprintf('key=%s', $this->apiKey), 'Content-Type' => 'application/json' ], 'body' => json_encode($message) ] ); }
php
public function send(Message $message) { return $this->guzzleClient->post( $this->getApiUrl(), [ 'headers' => [ 'Authorization' => sprintf('key=%s', $this->apiKey), 'Content-Type' => 'application/json' ], 'body' => json_encode($message) ] ); }
[ "public", "function", "send", "(", "Message", "$", "message", ")", "{", "return", "$", "this", "->", "guzzleClient", "->", "post", "(", "$", "this", "->", "getApiUrl", "(", ")", ",", "[", "'headers'", "=>", "[", "'Authorization'", "=>", "sprintf", "(", ...
sends your notification to the google servers and returns a guzzle repsonse object containing their answer. @param Message $message @return \Psr\Http\Message\ResponseInterface @throws \GuzzleHttp\Exception\RequestException
[ "sends", "your", "notification", "to", "the", "google", "servers", "and", "returns", "a", "guzzle", "repsonse", "object", "containing", "their", "answer", "." ]
train
https://github.com/Paragraph1/php-fcm/blob/49876ebc5007ba40dd633ff62f95a1fdcce1dce2/src/Client.php#L63-L75
Paragraph1/php-fcm
src/Message.php
Message.addRecipient
public function addRecipient(Recipient $recipient) { if (!$recipient instanceof Device && !$recipient instanceof Topic) { throw new \UnexpectedValueException('currently phpFCM only supports topic and single device messages'); } if (!isset($this->recipientType)) { $this->recipientType = get_class($recipient); } if ($this->recipientType !== get_class($recipient)) { throw new \InvalidArgumentException('mixed recepient types are not supported by FCM'); } $this->recipients[] = $recipient; return $this; }
php
public function addRecipient(Recipient $recipient) { if (!$recipient instanceof Device && !$recipient instanceof Topic) { throw new \UnexpectedValueException('currently phpFCM only supports topic and single device messages'); } if (!isset($this->recipientType)) { $this->recipientType = get_class($recipient); } if ($this->recipientType !== get_class($recipient)) { throw new \InvalidArgumentException('mixed recepient types are not supported by FCM'); } $this->recipients[] = $recipient; return $this; }
[ "public", "function", "addRecipient", "(", "Recipient", "$", "recipient", ")", "{", "if", "(", "!", "$", "recipient", "instanceof", "Device", "&&", "!", "$", "recipient", "instanceof", "Topic", ")", "{", "throw", "new", "\\", "UnexpectedValueException", "(", ...
where should the message go @param Recipient $recipient @throws \UnexpectedValueException @throws \InvalidArgumentException @return \paragraph1\phpFCM\Message
[ "where", "should", "the", "message", "go" ]
train
https://github.com/Paragraph1/php-fcm/blob/49876ebc5007ba40dd633ff62f95a1fdcce1dce2/src/Message.php#L48-L64
ethercreative/simplemap
src/models/Parts.php
Parts._nominatim
private function _nominatim (array $parts) { // Add any missing values $keys = [ 'house_number', 'address29', 'type', 'pedestrian', 'footway', 'path', 'road', 'neighbourhood', 'suburb', 'village', 'town', 'city_district', 'city', 'postcode', 'county', 'state_district', 'state', 'country', ]; foreach ($keys as $key) if (!array_key_exists($key, $parts)) $parts[$key] = null; $this->number = $this->_join([ $parts['house_number'], $parts['address29'], in_array($parts['type'], [ 'pedestrian', 'footway', 'path', 'road', 'neighbourhood', 'suburb', 'village', 'town', 'city_district', 'city', ]) ? $parts[$parts['type']] : null, ]); $this->address = $this->_join([ $parts['pedestrian'], $parts['footway'], $parts['path'], $parts['road'], $parts['neighbourhood'], $parts['suburb'], ]); $this->city = $this->_join([ $parts['village'], $parts['town'], $parts['city_district'], $parts['city'], ]); $this->postcode = $parts['postcode']; $this->county = $parts['county']; $this->state = $this->_join([ $parts['state_district'], $parts['state'], ]); $this->country = $parts['country']; }
php
private function _nominatim (array $parts) { // Add any missing values $keys = [ 'house_number', 'address29', 'type', 'pedestrian', 'footway', 'path', 'road', 'neighbourhood', 'suburb', 'village', 'town', 'city_district', 'city', 'postcode', 'county', 'state_district', 'state', 'country', ]; foreach ($keys as $key) if (!array_key_exists($key, $parts)) $parts[$key] = null; $this->number = $this->_join([ $parts['house_number'], $parts['address29'], in_array($parts['type'], [ 'pedestrian', 'footway', 'path', 'road', 'neighbourhood', 'suburb', 'village', 'town', 'city_district', 'city', ]) ? $parts[$parts['type']] : null, ]); $this->address = $this->_join([ $parts['pedestrian'], $parts['footway'], $parts['path'], $parts['road'], $parts['neighbourhood'], $parts['suburb'], ]); $this->city = $this->_join([ $parts['village'], $parts['town'], $parts['city_district'], $parts['city'], ]); $this->postcode = $parts['postcode']; $this->county = $parts['county']; $this->state = $this->_join([ $parts['state_district'], $parts['state'], ]); $this->country = $parts['country']; }
[ "private", "function", "_nominatim", "(", "array", "$", "parts", ")", "{", "// Add any missing values", "$", "keys", "=", "[", "'house_number'", ",", "'address29'", ",", "'type'", ",", "'pedestrian'", ",", "'footway'", ",", "'path'", ",", "'road'", ",", "'neig...
Parse Nominatim parts @param array $parts
[ "Parse", "Nominatim", "parts" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/models/Parts.php#L85-L155
ethercreative/simplemap
src/models/Parts.php
Parts._mapbox
private function _mapbox (array $parts) { $parts = array_reduce( $parts, function ($a, $part) { $key = explode('.', $part['id'])[0]; $a[$key] = $part['text']; return $a; }, [ 'number' => $parts['address'], $parts['place_type'][0] => $parts['text'], ] ); $this->number = $parts['number']; $this->address = $parts['address']; $this->city = $parts['city']; $this->postcode = $parts['postcode']; $this->county = $parts['county']; $this->state = $parts['state']; $this->country = $parts['country']; }
php
private function _mapbox (array $parts) { $parts = array_reduce( $parts, function ($a, $part) { $key = explode('.', $part['id'])[0]; $a[$key] = $part['text']; return $a; }, [ 'number' => $parts['address'], $parts['place_type'][0] => $parts['text'], ] ); $this->number = $parts['number']; $this->address = $parts['address']; $this->city = $parts['city']; $this->postcode = $parts['postcode']; $this->county = $parts['county']; $this->state = $parts['state']; $this->country = $parts['country']; }
[ "private", "function", "_mapbox", "(", "array", "$", "parts", ")", "{", "$", "parts", "=", "array_reduce", "(", "$", "parts", ",", "function", "(", "$", "a", ",", "$", "part", ")", "{", "$", "key", "=", "explode", "(", "'.'", ",", "$", "part", "[...
Parse Mapbox parts @param array $parts
[ "Parse", "Mapbox", "parts" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/models/Parts.php#L162-L185
ethercreative/simplemap
src/models/Parts.php
Parts._google
private function _google ($parts) { if (!$this->_isAssoc($parts)) { $parts = array_reduce( $parts, function ($a, $part) { $key = $part['types'][0]; $a[$key] = $part['long_name']; return $a; }, [] ); } foreach (PartsLegacy::$legacyKeys as $key) if (!array_key_exists($key, $parts)) $parts[$key] = ''; $this->number = $this->_join([ $parts['subpremise'], $parts['premise'], $parts['street_number'], ]); $this->address = $this->_join([ $parts['route'], $parts['neighborhood'], $parts['sublocality_level_5'], $parts['sublocality_level_4'], $parts['sublocality_level_3'], $parts['sublocality_level_2'], $parts['sublocality_level_1'], $parts['sublocality'], ]); $this->city = $this->_join([ $parts['postal_town'], $parts['locality'], ]); $this->postcode = $parts['postal_code'] ?? $parts['postal_code_prefix']; $this->county = $parts['administrative_area_level_2']; $this->state = $parts['administrative_area_level_1']; $this->country = $parts['country']; }
php
private function _google ($parts) { if (!$this->_isAssoc($parts)) { $parts = array_reduce( $parts, function ($a, $part) { $key = $part['types'][0]; $a[$key] = $part['long_name']; return $a; }, [] ); } foreach (PartsLegacy::$legacyKeys as $key) if (!array_key_exists($key, $parts)) $parts[$key] = ''; $this->number = $this->_join([ $parts['subpremise'], $parts['premise'], $parts['street_number'], ]); $this->address = $this->_join([ $parts['route'], $parts['neighborhood'], $parts['sublocality_level_5'], $parts['sublocality_level_4'], $parts['sublocality_level_3'], $parts['sublocality_level_2'], $parts['sublocality_level_1'], $parts['sublocality'], ]); $this->city = $this->_join([ $parts['postal_town'], $parts['locality'], ]); $this->postcode = $parts['postal_code'] ?? $parts['postal_code_prefix']; $this->county = $parts['administrative_area_level_2']; $this->state = $parts['administrative_area_level_1']; $this->country = $parts['country']; }
[ "private", "function", "_google", "(", "$", "parts", ")", "{", "if", "(", "!", "$", "this", "->", "_isAssoc", "(", "$", "parts", ")", ")", "{", "$", "parts", "=", "array_reduce", "(", "$", "parts", ",", "function", "(", "$", "a", ",", "$", "part"...
Parse Google parts @param $parts
[ "Parse", "Google", "parts" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/models/Parts.php#L192-L238
ethercreative/simplemap
src/models/Parts.php
Parts._here
private function _here ($parts) { $parts = array_merge( $parts, array_reduce($parts['additionalData'], function ($a, $b) { $a[$b['key']] = $b['value']; return $a; }, []) ); $this->number = $parts['number']; $this->address = $this->_join([ $parts['street'], $parts['district'], ]); $this->city = $parts['city']; $this->postcode = $parts['postalCode']; $this->county = $parts['CountyName'] ?? $parts['county']; $this->state = $parts['StateName'] ?? $parts['state']; $this->country = $parts['CountryName'] ?? $parts['country']; }
php
private function _here ($parts) { $parts = array_merge( $parts, array_reduce($parts['additionalData'], function ($a, $b) { $a[$b['key']] = $b['value']; return $a; }, []) ); $this->number = $parts['number']; $this->address = $this->_join([ $parts['street'], $parts['district'], ]); $this->city = $parts['city']; $this->postcode = $parts['postalCode']; $this->county = $parts['CountyName'] ?? $parts['county']; $this->state = $parts['StateName'] ?? $parts['state']; $this->country = $parts['CountryName'] ?? $parts['country']; }
[ "private", "function", "_here", "(", "$", "parts", ")", "{", "$", "parts", "=", "array_merge", "(", "$", "parts", ",", "array_reduce", "(", "$", "parts", "[", "'additionalData'", "]", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "$", "a...
Parse Here parts @param $parts
[ "Parse", "Here", "parts" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/models/Parts.php#L245-L265
ethercreative/simplemap
src/models/Parts.php
Parts.isLegacy
public static function isLegacy (array $parts = null) { if ($parts === null) return false; $keys = PartsLegacy::$legacyKeys; unset($keys[array_search('country', $keys)]); foreach ($keys as $key) if (isset($parts[$key]) || array_key_exists($key, $parts)) return true; return false; }
php
public static function isLegacy (array $parts = null) { if ($parts === null) return false; $keys = PartsLegacy::$legacyKeys; unset($keys[array_search('country', $keys)]); foreach ($keys as $key) if (isset($parts[$key]) || array_key_exists($key, $parts)) return true; return false; }
[ "public", "static", "function", "isLegacy", "(", "array", "$", "parts", "=", "null", ")", "{", "if", "(", "$", "parts", "===", "null", ")", "return", "false", ";", "$", "keys", "=", "PartsLegacy", "::", "$", "legacyKeys", ";", "unset", "(", "$", "key...
Determines if the given array of parts contains legacy data @param array $parts @return bool
[ "Determines", "if", "the", "given", "array", "of", "parts", "contains", "legacy", "data" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/models/Parts.php#L277-L291
ethercreative/simplemap
src/models/Parts.php
Parts._fromArray
private function _fromArray (array $parts) { $this->number = $parts['number'] ?? ''; $this->address = $parts['address'] ?? ''; $this->city = $parts['city'] ?? ''; $this->postcode = $parts['postcode'] ?? ''; $this->county = $parts['county'] ?? ''; $this->state = $parts['state'] ?? ''; $this->country = $parts['country'] ?? ''; }
php
private function _fromArray (array $parts) { $this->number = $parts['number'] ?? ''; $this->address = $parts['address'] ?? ''; $this->city = $parts['city'] ?? ''; $this->postcode = $parts['postcode'] ?? ''; $this->county = $parts['county'] ?? ''; $this->state = $parts['state'] ?? ''; $this->country = $parts['country'] ?? ''; }
[ "private", "function", "_fromArray", "(", "array", "$", "parts", ")", "{", "$", "this", "->", "number", "=", "$", "parts", "[", "'number'", "]", "??", "''", ";", "$", "this", "->", "address", "=", "$", "parts", "[", "'address'", "]", "??", "''", ";...
Populates Parts from the given array @param array $parts
[ "Populates", "Parts", "from", "the", "given", "array" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/models/Parts.php#L310-L319
ethercreative/simplemap
src/elements/Map.php
Map.afterSave
public function afterSave (bool $isNew) { SimpleMap::getInstance()->map->saveRecord( $this, $this->ownerId, $this->ownerSiteId, $this->fieldId, $isNew ); parent::afterSave($isNew); }
php
public function afterSave (bool $isNew) { SimpleMap::getInstance()->map->saveRecord( $this, $this->ownerId, $this->ownerSiteId, $this->fieldId, $isNew ); parent::afterSave($isNew); }
[ "public", "function", "afterSave", "(", "bool", "$", "isNew", ")", "{", "SimpleMap", "::", "getInstance", "(", ")", "->", "map", "->", "saveRecord", "(", "$", "this", ",", "$", "this", "->", "ownerId", ",", "$", "this", "->", "ownerSiteId", ",", "$", ...
@param bool $isNew @throws \yii\db\Exception
[ "@param", "bool", "$isNew" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/elements/Map.php#L166-L177
ethercreative/simplemap
src/services/GeoService.php
GeoService.getToken
public static function getToken ($token, string $service) { switch ($service) { case GeoEnum::AppleMapKit: case MapTiles::MapKitStandard: case MapTiles::MapKitMutedStandard: case MapTiles::MapKitSatellite: case MapTiles::MapKitHybrid: return JWT::getToken( trim($token['privateKey']), trim($token['keyId']), trim($token['teamId']) ); default: return $token; } }
php
public static function getToken ($token, string $service) { switch ($service) { case GeoEnum::AppleMapKit: case MapTiles::MapKitStandard: case MapTiles::MapKitMutedStandard: case MapTiles::MapKitSatellite: case MapTiles::MapKitHybrid: return JWT::getToken( trim($token['privateKey']), trim($token['keyId']), trim($token['teamId']) ); default: return $token; } }
[ "public", "static", "function", "getToken", "(", "$", "token", ",", "string", "$", "service", ")", "{", "switch", "(", "$", "service", ")", "{", "case", "GeoEnum", "::", "AppleMapKit", ":", "case", "MapTiles", "::", "MapKitStandard", ":", "case", "MapTiles...
Parses the token based off the given service @param array|string $token @param string $service @return false|string
[ "Parses", "the", "token", "based", "off", "the", "given", "service" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/GeoService.php#L551-L568
ethercreative/simplemap
src/services/GeoService.php
GeoService.latLngFromAddress
public static function latLngFromAddress ($address, $country = null) { /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); $token = static::getToken($settings->geoToken, $settings->geoService); switch ($settings->geoService) { case GeoEnum::Here: return static::_latLngFromAddress_Here( $token, $address, $country ); case GeoEnum::GoogleMaps: return static::_latLngFromAddress_Google( $token, $address, $country ); case GeoEnum::Mapbox: return static::_latLngFromAddress_Mapbox( $token, $address, $country ); case GeoEnum::Nominatim: return static::_latLngFromAddress_Nominatim( $address, $country ); default: throw new Exception( 'Unknown geo-coding service: ' . $settings->geoService ); } }
php
public static function latLngFromAddress ($address, $country = null) { /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); $token = static::getToken($settings->geoToken, $settings->geoService); switch ($settings->geoService) { case GeoEnum::Here: return static::_latLngFromAddress_Here( $token, $address, $country ); case GeoEnum::GoogleMaps: return static::_latLngFromAddress_Google( $token, $address, $country ); case GeoEnum::Mapbox: return static::_latLngFromAddress_Mapbox( $token, $address, $country ); case GeoEnum::Nominatim: return static::_latLngFromAddress_Nominatim( $address, $country ); default: throw new Exception( 'Unknown geo-coding service: ' . $settings->geoService ); } }
[ "public", "static", "function", "latLngFromAddress", "(", "$", "address", ",", "$", "country", "=", "null", ")", "{", "/** @var Settings $settings */", "$", "settings", "=", "SimpleMap", "::", "getInstance", "(", ")", "->", "getSettings", "(", ")", ";", "$", ...
Find the lat/lng for the given address @param string $address @param string|null $country @return array|null @throws Exception
[ "Find", "the", "lat", "/", "lng", "for", "the", "given", "address" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/GeoService.php#L579-L611
ethercreative/simplemap
src/services/GeoService.php
GeoService.addressFromLatLng
public static function addressFromLatLng ($lat, $lng) { /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); $token = static::getToken($settings->geoToken, $settings->geoService); switch ($settings->geoService) { case GeoEnum::Here: return static::_addressFromLatLng_Here( $token, $lat, $lng ); case GeoEnum::GoogleMaps: return static::_addressFromLatLng_Google( $token, $lat, $lng ); case GeoEnum::Mapbox: return static::_addressFromLatLng_Mapbox( $token, $lat, $lng ); case GeoEnum::Nominatim: return static::_addressFromLatLng_Nominatim( $lat, $lng ); default: throw new Exception( 'Unknown geo-coding service: ' . $settings->geoService ); } }
php
public static function addressFromLatLng ($lat, $lng) { /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); $token = static::getToken($settings->geoToken, $settings->geoService); switch ($settings->geoService) { case GeoEnum::Here: return static::_addressFromLatLng_Here( $token, $lat, $lng ); case GeoEnum::GoogleMaps: return static::_addressFromLatLng_Google( $token, $lat, $lng ); case GeoEnum::Mapbox: return static::_addressFromLatLng_Mapbox( $token, $lat, $lng ); case GeoEnum::Nominatim: return static::_addressFromLatLng_Nominatim( $lat, $lng ); default: throw new Exception( 'Unknown geo-coding service: ' . $settings->geoService ); } }
[ "public", "static", "function", "addressFromLatLng", "(", "$", "lat", ",", "$", "lng", ")", "{", "/** @var Settings $settings */", "$", "settings", "=", "SimpleMap", "::", "getInstance", "(", ")", "->", "getSettings", "(", ")", ";", "$", "token", "=", "stati...
Find an address from the given lat/lng @param float $lat @param float $lng @return array|null - Returns the address and associated parts @throws Exception
[ "Find", "an", "address", "from", "the", "given", "lat", "/", "lng" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/GeoService.php#L622-L655
ethercreative/simplemap
src/services/GeoService.php
GeoService._latLngFromAddress_Here
private static function _latLngFromAddress_Here ($token, $address, $country) { $url = 'https://geocoder.api.here.com/6.2/geocode.json'; $url .= '?app_id=' . $token['appId']; $url .= '&app_code=' . $token['appCode']; $url .= '&language=' . \Craft::$app->locale->getLanguageID(); $url .= '&searchtext=' . rawurlencode($address); if ($country !== null) { if (static::_validateCountryCode($country)) $url .= '&country=' . rawurlencode(strtoupper($country)); else $url .= rawurlencode(', ' . $country); } $data = (string) static::_client()->get($url)->getBody(); $data = Json::decodeIfJson($data); if (!is_array($data) || empty($data['Response']['View'])) return null; $pos = $data['Response']['View'][0]['Result'][0]['Location']['DisplayPosition']; return [ 'lat' => $pos['Latitude'], 'lng' => $pos['Longitude'], ]; }
php
private static function _latLngFromAddress_Here ($token, $address, $country) { $url = 'https://geocoder.api.here.com/6.2/geocode.json'; $url .= '?app_id=' . $token['appId']; $url .= '&app_code=' . $token['appCode']; $url .= '&language=' . \Craft::$app->locale->getLanguageID(); $url .= '&searchtext=' . rawurlencode($address); if ($country !== null) { if (static::_validateCountryCode($country)) $url .= '&country=' . rawurlencode(strtoupper($country)); else $url .= rawurlencode(', ' . $country); } $data = (string) static::_client()->get($url)->getBody(); $data = Json::decodeIfJson($data); if (!is_array($data) || empty($data['Response']['View'])) return null; $pos = $data['Response']['View'][0]['Result'][0]['Location']['DisplayPosition']; return [ 'lat' => $pos['Latitude'], 'lng' => $pos['Longitude'], ]; }
[ "private", "static", "function", "_latLngFromAddress_Here", "(", "$", "token", ",", "$", "address", ",", "$", "country", ")", "{", "$", "url", "=", "'https://geocoder.api.here.com/6.2/geocode.json'", ";", "$", "url", ".=", "'?app_id='", ".", "$", "token", "[", ...
-------------------------------------------------------------------------
[ "-------------------------------------------------------------------------" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/GeoService.php#L663-L691
ethercreative/simplemap
src/services/GeoService.php
GeoService._addressFromLatLng_Here
private static function _addressFromLatLng_Here ($token, $lat, $lng) { $url = 'https://reverse.geocoder.api.here.com/6.2/reversegeocode.json'; $url .= '?app_id=' . $token['appId']; $url .= '&app_code=' . $token['appCode']; $url .= '&language=' . \Craft::$app->locale->getLanguageID(); $url .= '&mode=retrieveAddresses&limit=1&jsonattributes=1'; $url .= '&prox=' . rawurlencode($lat) . ',' . rawurldecode($lng) . ',1'; $data = (string) static::_client()->get($url)->getBody(); $data = Json::decodeIfJson($data); if (!is_array($data) || empty($data['Response']['View'])) return null; $pos = $data['Response']['View'][0]['Result'][0]['Location']; return [ 'address' => $pos['label'], 'parts' => new Parts($pos, GeoEnum::Here), ]; }
php
private static function _addressFromLatLng_Here ($token, $lat, $lng) { $url = 'https://reverse.geocoder.api.here.com/6.2/reversegeocode.json'; $url .= '?app_id=' . $token['appId']; $url .= '&app_code=' . $token['appCode']; $url .= '&language=' . \Craft::$app->locale->getLanguageID(); $url .= '&mode=retrieveAddresses&limit=1&jsonattributes=1'; $url .= '&prox=' . rawurlencode($lat) . ',' . rawurldecode($lng) . ',1'; $data = (string) static::_client()->get($url)->getBody(); $data = Json::decodeIfJson($data); if (!is_array($data) || empty($data['Response']['View'])) return null; $pos = $data['Response']['View'][0]['Result'][0]['Location']; return [ 'address' => $pos['label'], 'parts' => new Parts($pos, GeoEnum::Here), ]; }
[ "private", "static", "function", "_addressFromLatLng_Here", "(", "$", "token", ",", "$", "lat", ",", "$", "lng", ")", "{", "$", "url", "=", "'https://reverse.geocoder.api.here.com/6.2/reversegeocode.json'", ";", "$", "url", ".=", "'?app_id='", ".", "$", "token", ...
-------------------------------------------------------------------------
[ "-------------------------------------------------------------------------" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/GeoService.php#L773-L794
ethercreative/simplemap
src/elements/db/MapQuery.php
MapQuery.ownerSite
public function ownerSite ($value) { if ($value instanceof Site) { $this->ownerSiteId($value->id); } else { $site = \Craft::$app->getSites()->getSiteByHandle($value); if (!$site) throw new \Exception('Invalid site handle: ' . $value); $this->ownerSiteId($site->id); } return $this; }
php
public function ownerSite ($value) { if ($value instanceof Site) { $this->ownerSiteId($value->id); } else { $site = \Craft::$app->getSites()->getSiteByHandle($value); if (!$site) throw new \Exception('Invalid site handle: ' . $value); $this->ownerSiteId($site->id); } return $this; }
[ "public", "function", "ownerSite", "(", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "Site", ")", "{", "$", "this", "->", "ownerSiteId", "(", "$", "value", "->", "id", ")", ";", "}", "else", "{", "$", "site", "=", "\\", "Craft", ...
@param string|Site $value @return $this @throws \Exception
[ "@param", "string|Site", "$value" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/elements/db/MapQuery.php#L72-L89
ethercreative/simplemap
src/elements/db/MapQuery.php
MapQuery.beforePrepare
protected function beforePrepare (): bool { $table = Map::TableNameClean; $this->joinElementTable($table); $this->query->select($table . '.*'); if ($this->fieldId) $this->subQuery->andWhere( Db::parseParam($table . '.fieldId', $this->fieldId) ); if ($this->ownerId) $this->subQuery->andWhere( Db::parseParam($table . '.ownerId', $this->ownerId) ); if ($this->ownerSiteId) $this->subQuery->andWhere( Db::parseParam($table . '.ownerSiteId', $this->ownerSiteId) ); return parent::beforePrepare(); }
php
protected function beforePrepare (): bool { $table = Map::TableNameClean; $this->joinElementTable($table); $this->query->select($table . '.*'); if ($this->fieldId) $this->subQuery->andWhere( Db::parseParam($table . '.fieldId', $this->fieldId) ); if ($this->ownerId) $this->subQuery->andWhere( Db::parseParam($table . '.ownerId', $this->ownerId) ); if ($this->ownerSiteId) $this->subQuery->andWhere( Db::parseParam($table . '.ownerSiteId', $this->ownerSiteId) ); return parent::beforePrepare(); }
[ "protected", "function", "beforePrepare", "(", ")", ":", "bool", "{", "$", "table", "=", "Map", "::", "TableNameClean", ";", "$", "this", "->", "joinElementTable", "(", "$", "table", ")", ";", "$", "this", "->", "query", "->", "select", "(", "$", "tabl...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/elements/db/MapQuery.php#L103-L127
ethercreative/simplemap
src/enums/MapTiles.php
MapTiles.getSelectOptions
public static function getSelectOptions () { return [ ['optgroup' => SimpleMap::t('Open Source')], self::Wikimedia => SimpleMap::t('Wikimedia'), self::OpenStreetMap => SimpleMap::t('OpenStreetMap'), self::CartoVoyager => SimpleMap::t('Carto: Voyager'), self::CartoPositron => SimpleMap::t('Carto: Positron'), self::CartoDarkMatter => SimpleMap::t('Carto: Dark Matter'), ['optgroup' => SimpleMap::t('Requires API Key (Token)')], self::MapboxOutdoors => SimpleMap::t('Mapbox: Outdoors'), self::MapboxStreets => SimpleMap::t('Mapbox: Streets'), self::MapboxLight => SimpleMap::t('Mapbox: Light'), self::MapboxDark => SimpleMap::t('Mapbox: Dark'), self::GoogleRoadmap => SimpleMap::t('Google Maps: Roadmap'), self::GoogleTerrain => SimpleMap::t('Google Maps: Terrain'), self::GoogleHybrid => SimpleMap::t('Google Maps: Hybrid'), self::MapKitStandard => SimpleMap::t('Apple MapKit: Standard'), self::MapKitMutedStandard => SimpleMap::t('Apple MapKit: Muted Standard'), self::MapKitSatellite => SimpleMap::t('Apple MapKit: Satellite'), self::MapKitHybrid => SimpleMap::t('Apple MapKit: Hybrid'), self::HereNormalDay => SimpleMap::t('Here: Normal Day'), self::HereNormalDayGrey => SimpleMap::t('Here: Normal Day Grey'), self::HereNormalDayTransit => SimpleMap::t('Here: Normal Day Transit'), self::HereReduced => SimpleMap::t('Here: Reduced'), self::HerePedestrian => SimpleMap::t('Here: Pedestrian'), self::HereTerrain => SimpleMap::t('Here: Terrain'), self::HereSatellite => SimpleMap::t('Here: Satellite'), self::HereHybrid => SimpleMap::t('Here: Hybrid'), ]; }
php
public static function getSelectOptions () { return [ ['optgroup' => SimpleMap::t('Open Source')], self::Wikimedia => SimpleMap::t('Wikimedia'), self::OpenStreetMap => SimpleMap::t('OpenStreetMap'), self::CartoVoyager => SimpleMap::t('Carto: Voyager'), self::CartoPositron => SimpleMap::t('Carto: Positron'), self::CartoDarkMatter => SimpleMap::t('Carto: Dark Matter'), ['optgroup' => SimpleMap::t('Requires API Key (Token)')], self::MapboxOutdoors => SimpleMap::t('Mapbox: Outdoors'), self::MapboxStreets => SimpleMap::t('Mapbox: Streets'), self::MapboxLight => SimpleMap::t('Mapbox: Light'), self::MapboxDark => SimpleMap::t('Mapbox: Dark'), self::GoogleRoadmap => SimpleMap::t('Google Maps: Roadmap'), self::GoogleTerrain => SimpleMap::t('Google Maps: Terrain'), self::GoogleHybrid => SimpleMap::t('Google Maps: Hybrid'), self::MapKitStandard => SimpleMap::t('Apple MapKit: Standard'), self::MapKitMutedStandard => SimpleMap::t('Apple MapKit: Muted Standard'), self::MapKitSatellite => SimpleMap::t('Apple MapKit: Satellite'), self::MapKitHybrid => SimpleMap::t('Apple MapKit: Hybrid'), self::HereNormalDay => SimpleMap::t('Here: Normal Day'), self::HereNormalDayGrey => SimpleMap::t('Here: Normal Day Grey'), self::HereNormalDayTransit => SimpleMap::t('Here: Normal Day Transit'), self::HereReduced => SimpleMap::t('Here: Reduced'), self::HerePedestrian => SimpleMap::t('Here: Pedestrian'), self::HereTerrain => SimpleMap::t('Here: Terrain'), self::HereSatellite => SimpleMap::t('Here: Satellite'), self::HereHybrid => SimpleMap::t('Here: Hybrid'), ]; }
[ "public", "static", "function", "getSelectOptions", "(", ")", "{", "return", "[", "[", "'optgroup'", "=>", "SimpleMap", "::", "t", "(", "'Open Source'", ")", "]", ",", "self", "::", "Wikimedia", "=>", "SimpleMap", "::", "t", "(", "'Wikimedia'", ")", ",", ...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/enums/MapTiles.php#L75-L113
ethercreative/simplemap
src/web/Variable.php
Variable.getMapToken
public function getMapToken () { /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); return GeoService::getToken( $settings->mapToken, $settings->mapTiles ); }
php
public function getMapToken () { /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); return GeoService::getToken( $settings->mapToken, $settings->mapTiles ); }
[ "public", "function", "getMapToken", "(", ")", "{", "/** @var Settings $settings */", "$", "settings", "=", "SimpleMap", "::", "getInstance", "(", ")", "->", "getSettings", "(", ")", ";", "return", "GeoService", "::", "getToken", "(", "$", "settings", "->", "m...
Returns the map token @return string
[ "Returns", "the", "map", "token" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/web/Variable.php#L30-L39
ethercreative/simplemap
src/web/Variable.php
Variable.getLatLngFromAddress
public function getLatLngFromAddress ($address, $country = null) { try { return GeoService::latLngFromAddress($address, $country); } catch (Exception $e) { \Craft::error($e->getMessage(), 'simplemap'); return [ 'lat' => '', 'lng' => '', ]; } }
php
public function getLatLngFromAddress ($address, $country = null) { try { return GeoService::latLngFromAddress($address, $country); } catch (Exception $e) { \Craft::error($e->getMessage(), 'simplemap'); return [ 'lat' => '', 'lng' => '', ]; } }
[ "public", "function", "getLatLngFromAddress", "(", "$", "address", ",", "$", "country", "=", "null", ")", "{", "try", "{", "return", "GeoService", "::", "latLngFromAddress", "(", "$", "address", ",", "$", "country", ")", ";", "}", "catch", "(", "Exception"...
Converts the given address to lat/lng @param string $address The address to search @param string|null $country The ISO 3166-1 alpha-2 country code to restrict the search to @return array|null
[ "Converts", "the", "given", "address", "to", "lat", "/", "lng" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/web/Variable.php#L67-L82
ethercreative/simplemap
src/services/MapService.php
MapService.validateField
public function validateField (MapField $field, ElementInterface $owner) { /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); $valid = $map->validate(); foreach ($map->getErrors() as $error) $owner->addError($field->handle, $error[0]); return $valid; }
php
public function validateField (MapField $field, ElementInterface $owner) { /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); $valid = $map->validate(); foreach ($map->getErrors() as $error) $owner->addError($field->handle, $error[0]); return $valid; }
[ "public", "function", "validateField", "(", "MapField", "$", "field", ",", "ElementInterface", "$", "owner", ")", "{", "/** @var MapElement $map */", "$", "map", "=", "$", "owner", "->", "getFieldValue", "(", "$", "field", "->", "handle", ")", ";", "$", "val...
@param MapField $field @param ElementInterface|Element $owner @return bool
[ "@param", "MapField", "$field", "@param", "ElementInterface|Element", "$owner" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L45-L56
ethercreative/simplemap
src/services/MapService.php
MapService.saveField
public function saveField (MapField $field, ElementInterface $owner) { if ($owner instanceof MapElement) return; /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); $map->fieldId = $field->id; $map->ownerId = $owner->id; $map->ownerSiteId = $owner->siteId; \Craft::$app->elements->saveElement($map, true, true); }
php
public function saveField (MapField $field, ElementInterface $owner) { if ($owner instanceof MapElement) return; /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); $map->fieldId = $field->id; $map->ownerId = $owner->id; $map->ownerSiteId = $owner->siteId; \Craft::$app->elements->saveElement($map, true, true); }
[ "public", "function", "saveField", "(", "MapField", "$", "field", ",", "ElementInterface", "$", "owner", ")", "{", "if", "(", "$", "owner", "instanceof", "MapElement", ")", "return", ";", "/** @var MapElement $map */", "$", "map", "=", "$", "owner", "->", "g...
@param MapField $field @param ElementInterface|Element $owner @throws \Throwable
[ "@param", "MapField", "$field", "@param", "ElementInterface|Element", "$owner" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L64-L77
ethercreative/simplemap
src/services/MapService.php
MapService.softDeleteField
public function softDeleteField (MapField $field, ElementInterface $owner) { /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); \Craft::$app->getElements()->deleteElement($map); }
php
public function softDeleteField (MapField $field, ElementInterface $owner) { /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); \Craft::$app->getElements()->deleteElement($map); }
[ "public", "function", "softDeleteField", "(", "MapField", "$", "field", ",", "ElementInterface", "$", "owner", ")", "{", "/** @var MapElement $map */", "$", "map", "=", "$", "owner", "->", "getFieldValue", "(", "$", "field", "->", "handle", ")", ";", "\\", "...
@param MapField $field @param ElementInterface $owner @throws \Throwable
[ "@param", "MapField", "$field", "@param", "ElementInterface", "$owner" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L85-L91
ethercreative/simplemap
src/services/MapService.php
MapService.restoreField
public function restoreField (MapField $field, ElementInterface $owner) { /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); \Craft::$app->getElements()->restoreElement($map); }
php
public function restoreField (MapField $field, ElementInterface $owner) { /** @var MapElement $map */ $map = $owner->getFieldValue($field->handle); \Craft::$app->getElements()->restoreElement($map); }
[ "public", "function", "restoreField", "(", "MapField", "$", "field", ",", "ElementInterface", "$", "owner", ")", "{", "/** @var MapElement $map */", "$", "map", "=", "$", "owner", "->", "getFieldValue", "(", "$", "field", "->", "handle", ")", ";", "\\", "Cra...
@param MapField $field @param ElementInterface $owner @throws \Throwable @throws \yii\base\Exception
[ "@param", "MapField", "$field", "@param", "ElementInterface", "$owner" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L100-L106
ethercreative/simplemap
src/services/MapService.php
MapService.saveRecord
public function saveRecord (MapElement $map, $ownerId, $ownerSiteId, $fieldId, $isNew) { $record = null; if (!$isNew) { $record = MapRecord::findOne($map->id); if (!$record) throw new \Exception('Invalid map ID: ' . $map->id); } if ($record === null) { $record = new MapRecord(); $record->id = $map->id; $record->ownerId = $ownerId; $record->ownerSiteId = $ownerSiteId; $record->fieldId = $fieldId; } $record->lat = $map->lat; $record->lng = $map->lng; $record->zoom = $map->zoom; $record->address = $map->address; $record->parts = $map->parts; $this->_populateMissingData($record); $record->save(false); }
php
public function saveRecord (MapElement $map, $ownerId, $ownerSiteId, $fieldId, $isNew) { $record = null; if (!$isNew) { $record = MapRecord::findOne($map->id); if (!$record) throw new \Exception('Invalid map ID: ' . $map->id); } if ($record === null) { $record = new MapRecord(); $record->id = $map->id; $record->ownerId = $ownerId; $record->ownerSiteId = $ownerSiteId; $record->fieldId = $fieldId; } $record->lat = $map->lat; $record->lng = $map->lng; $record->zoom = $map->zoom; $record->address = $map->address; $record->parts = $map->parts; $this->_populateMissingData($record); $record->save(false); }
[ "public", "function", "saveRecord", "(", "MapElement", "$", "map", ",", "$", "ownerId", ",", "$", "ownerSiteId", ",", "$", "fieldId", ",", "$", "isNew", ")", "{", "$", "record", "=", "null", ";", "if", "(", "!", "$", "isNew", ")", "{", "$", "record...
@param MapElement $map @param $ownerId @param $ownerSiteId @param $fieldId @param $isNew @throws \yii\db\Exception @throws \Exception
[ "@param", "MapElement", "$map", "@param", "$ownerId", "@param", "$ownerSiteId", "@param", "$fieldId", "@param", "$isNew" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L118-L149
ethercreative/simplemap
src/services/MapService.php
MapService.getDistance
public function getDistance (MapElement $map) { if (!$this->_location || !$this->_distance) return null; $originLat = $this->_location['lat']; $originLng = $this->_location['lng']; $targetLat = $map->lat; $targetLng = $map->lng; return ( $this->_distance * rad2deg( acos( cos(deg2rad($originLat)) * cos(deg2rad($targetLat)) * cos(deg2rad($originLng) - deg2rad($targetLng)) + sin(deg2rad($originLat)) * sin(deg2rad($targetLat)) ) ) ); }
php
public function getDistance (MapElement $map) { if (!$this->_location || !$this->_distance) return null; $originLat = $this->_location['lat']; $originLng = $this->_location['lng']; $targetLat = $map->lat; $targetLng = $map->lng; return ( $this->_distance * rad2deg( acos( cos(deg2rad($originLat)) * cos(deg2rad($targetLat)) * cos(deg2rad($originLng) - deg2rad($targetLng)) + sin(deg2rad($originLat)) * sin(deg2rad($targetLat)) ) ) ); }
[ "public", "function", "getDistance", "(", "MapElement", "$", "map", ")", "{", "if", "(", "!", "$", "this", "->", "_location", "||", "!", "$", "this", "->", "_distance", ")", "return", "null", ";", "$", "originLat", "=", "$", "this", "->", "_location", ...
Returns the distance from the search origin (if one exists) @param MapElement $map @return float|int|null
[ "Returns", "the", "distance", "from", "the", "search", "origin", "(", "if", "one", "exists", ")" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L158-L181
ethercreative/simplemap
src/services/MapService.php
MapService.modifyElementsQuery
public function modifyElementsQuery (ElementQueryInterface $query, $value) { if (empty($value)) return; /** @var ElementQuery $query */ $table = MapRecord::TableName; $alias = MapRecord::TableNameClean . '_' . bin2hex(openssl_random_pseudo_bytes(5)); $on = [ 'and', '[[elements.id]] = [[' . $alias . '.ownerId]]', '[[elements.dateDeleted]] IS NULL', '[[elements_sites.siteId]] = [[' . $alias . '.ownerSiteId]]', ]; $query->query->join('JOIN', $table . ' ' . $alias, $on); $query->subQuery->join('JOIN', $table . ' ' . $alias, $on); $oldOrderBy = null; $search = false; if (!is_array($query->orderBy)) { $oldOrderBy = $query->orderBy; $query->orderBy = []; } if (array_key_exists('location', $value)) $search = $this->_searchLocation($query, $value, $alias); if (array_key_exists('distance', $query->orderBy)) $this->_replaceOrderBy($query, $search); if ($oldOrderBy !== null) $query->orderBy = $oldOrderBy; }
php
public function modifyElementsQuery (ElementQueryInterface $query, $value) { if (empty($value)) return; /** @var ElementQuery $query */ $table = MapRecord::TableName; $alias = MapRecord::TableNameClean . '_' . bin2hex(openssl_random_pseudo_bytes(5)); $on = [ 'and', '[[elements.id]] = [[' . $alias . '.ownerId]]', '[[elements.dateDeleted]] IS NULL', '[[elements_sites.siteId]] = [[' . $alias . '.ownerSiteId]]', ]; $query->query->join('JOIN', $table . ' ' . $alias, $on); $query->subQuery->join('JOIN', $table . ' ' . $alias, $on); $oldOrderBy = null; $search = false; if (!is_array($query->orderBy)) { $oldOrderBy = $query->orderBy; $query->orderBy = []; } if (array_key_exists('location', $value)) $search = $this->_searchLocation($query, $value, $alias); if (array_key_exists('distance', $query->orderBy)) $this->_replaceOrderBy($query, $search); if ($oldOrderBy !== null) $query->orderBy = $oldOrderBy; }
[ "public", "function", "modifyElementsQuery", "(", "ElementQueryInterface", "$", "query", ",", "$", "value", ")", "{", "if", "(", "empty", "(", "$", "value", ")", ")", "return", ";", "/** @var ElementQuery $query */", "$", "table", "=", "MapRecord", "::", "Tabl...
@param ElementQueryInterface $query @param mixed $value @throws \yii\db\Exception
[ "@param", "ElementQueryInterface", "$query", "@param", "mixed", "$value" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L189-L225
ethercreative/simplemap
src/services/MapService.php
MapService._searchLocation
private function _searchLocation (ElementQuery $query, $value, $table) { $location = $value['location']; $country = $value['country'] ?? null; $radius = $value['radius'] ?? 50.0; $unit = $value['unit'] ?? 'km'; // Normalize location if (is_string($location)) $location = GeoService::latLngFromAddress($location, $country); else if ($location instanceof Map) $location = ['lat' => $location->lat, 'lng' => $location->lng]; else if (!is_array($location) || !isset($location['lat'], $location['lng'])) $location = null; if ($location === null) return false; $lat = $location['lat']; $lng = $location['lng']; // Normalize radius if (!is_numeric($radius)) $radius = (float) $radius; if (!is_numeric($radius)) $radius = 50.0; // Normalize unit if ($unit === 'miles') $unit = 'mi'; else if ($unit === 'kilometers') $unit = 'km'; else if (!in_array($unit, ['mi', 'km'])) $unit = 'km'; // Base Distance $distance = $unit === 'km' ? '111.045' : '69.0'; // Store for populating search result distance $this->_location = $location; $this->_distance = (float) $distance; // Search Query $search = str_replace(["\r", "\n", "\t"], '', "( $distance * DEGREES( ACOS( COS(RADIANS($lat)) * COS(RADIANS([[$table.lat]])) * COS(RADIANS($lng) - RADIANS([[$table.lng]])) + SIN(RADIANS($lat)) * SIN(RADIANS([[$table.lat]])) ) ) )"); // Restrict the results $restrict = [ 'and', [ 'and', "[[$table.lat]] >= $lat - ($radius / $distance)", "[[$table.lat]] <= $lat + ($radius / $distance)", ], [ 'and', "[[$table.lng]] >= $lng - ($radius / ($distance * COS(RADIANS($lat))))", "[[$table.lng]] <= $lng + ($radius / ($distance * COS(RADIANS($lat))))", ] ]; // Filter the query $query ->subQuery ->andWhere($restrict) ->andWhere($search . ' <= ' . $radius); return $search; }
php
private function _searchLocation (ElementQuery $query, $value, $table) { $location = $value['location']; $country = $value['country'] ?? null; $radius = $value['radius'] ?? 50.0; $unit = $value['unit'] ?? 'km'; // Normalize location if (is_string($location)) $location = GeoService::latLngFromAddress($location, $country); else if ($location instanceof Map) $location = ['lat' => $location->lat, 'lng' => $location->lng]; else if (!is_array($location) || !isset($location['lat'], $location['lng'])) $location = null; if ($location === null) return false; $lat = $location['lat']; $lng = $location['lng']; // Normalize radius if (!is_numeric($radius)) $radius = (float) $radius; if (!is_numeric($radius)) $radius = 50.0; // Normalize unit if ($unit === 'miles') $unit = 'mi'; else if ($unit === 'kilometers') $unit = 'km'; else if (!in_array($unit, ['mi', 'km'])) $unit = 'km'; // Base Distance $distance = $unit === 'km' ? '111.045' : '69.0'; // Store for populating search result distance $this->_location = $location; $this->_distance = (float) $distance; // Search Query $search = str_replace(["\r", "\n", "\t"], '', "( $distance * DEGREES( ACOS( COS(RADIANS($lat)) * COS(RADIANS([[$table.lat]])) * COS(RADIANS($lng) - RADIANS([[$table.lng]])) + SIN(RADIANS($lat)) * SIN(RADIANS([[$table.lat]])) ) ) )"); // Restrict the results $restrict = [ 'and', [ 'and', "[[$table.lat]] >= $lat - ($radius / $distance)", "[[$table.lat]] <= $lat + ($radius / $distance)", ], [ 'and', "[[$table.lng]] >= $lng - ($radius / ($distance * COS(RADIANS($lat))))", "[[$table.lng]] <= $lng + ($radius / ($distance * COS(RADIANS($lat))))", ] ]; // Filter the query $query ->subQuery ->andWhere($restrict) ->andWhere($search . ' <= ' . $radius); return $search; }
[ "private", "function", "_searchLocation", "(", "ElementQuery", "$", "query", ",", "$", "value", ",", "$", "table", ")", "{", "$", "location", "=", "$", "value", "[", "'location'", "]", ";", "$", "country", "=", "$", "value", "[", "'country'", "]", "??"...
Filters the query by location. Returns either `false` if we can't filter by location, or the location search string if we can. @param ElementQuery $query @param mixed $value @param string $table @return bool|string @throws \yii\db\Exception
[ "Filters", "the", "query", "by", "location", "." ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L243-L319
ethercreative/simplemap
src/services/MapService.php
MapService._replaceOrderBy
private function _replaceOrderBy (ElementQuery $query, $search = false) { $nextOrder = []; foreach ((array) $query->orderBy as $order => $sort) { if ($order === 'distance' && $search) $nextOrder[$search] = $sort; elseif ($order !== 'distance') $nextOrder[$order] = $sort; } $query->orderBy($nextOrder); }
php
private function _replaceOrderBy (ElementQuery $query, $search = false) { $nextOrder = []; foreach ((array) $query->orderBy as $order => $sort) { if ($order === 'distance' && $search) $nextOrder[$search] = $sort; elseif ($order !== 'distance') $nextOrder[$order] = $sort; } $query->orderBy($nextOrder); }
[ "private", "function", "_replaceOrderBy", "(", "ElementQuery", "$", "query", ",", "$", "search", "=", "false", ")", "{", "$", "nextOrder", "=", "[", "]", ";", "foreach", "(", "(", "array", ")", "$", "query", "->", "orderBy", "as", "$", "order", "=>", ...
Will replace the distance search with the correct query if available, or otherwise remove it. @param ElementQuery $query @param bool $search
[ "Will", "replace", "the", "distance", "search", "with", "the", "correct", "query", "if", "available", "or", "otherwise", "remove", "it", "." ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L328-L339
ethercreative/simplemap
src/services/MapService.php
MapService._populateMissingData
private function _populateMissingData (MapRecord $record) { // Missing Lat / Lng if (!($record->lat && $record->lng) && $record->address) { $latLng = GeoService::latLngFromAddress($record->address); $record->lat = $latLng['lat']; $record->lng = $latLng['lng']; } // Missing address / parts if (!$record->address && ($record->lat && $record->lng)) { $loc = GeoService::addressFromLatLng($record->lat, $record->lng); $record->address = $loc['address']; $record->parts = array_merge( array_filter((array) $loc['parts']), array_filter((array) $record->parts) ); } }
php
private function _populateMissingData (MapRecord $record) { // Missing Lat / Lng if (!($record->lat && $record->lng) && $record->address) { $latLng = GeoService::latLngFromAddress($record->address); $record->lat = $latLng['lat']; $record->lng = $latLng['lng']; } // Missing address / parts if (!$record->address && ($record->lat && $record->lng)) { $loc = GeoService::addressFromLatLng($record->lat, $record->lng); $record->address = $loc['address']; $record->parts = array_merge( array_filter((array) $loc['parts']), array_filter((array) $record->parts) ); } }
[ "private", "function", "_populateMissingData", "(", "MapRecord", "$", "record", ")", "{", "// Missing Lat / Lng", "if", "(", "!", "(", "$", "record", "->", "lat", "&&", "$", "record", "->", "lng", ")", "&&", "$", "record", "->", "address", ")", "{", "$",...
Populates any missing location data @param MapRecord $record @throws \yii\db\Exception
[ "Populates", "any", "missing", "location", "data" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/services/MapService.php#L348-L368
ethercreative/simplemap
src/migrations/m190226_143809_craft3_upgrade.php
m190226_143809_craft3_upgrade.safeUp
public function safeUp() { // 1. Run the install migration if (!$this->db->tableExists(Map::TableName)) (new Install())->safeUp(); // 2. Upgrade the data if ($this->db->tableExists('{{%simplemap_maps}}')) $this->_upgrade2(); else $this->_upgrade3(); }
php
public function safeUp() { // 1. Run the install migration if (!$this->db->tableExists(Map::TableName)) (new Install())->safeUp(); // 2. Upgrade the data if ($this->db->tableExists('{{%simplemap_maps}}')) $this->_upgrade2(); else $this->_upgrade3(); }
[ "public", "function", "safeUp", "(", ")", "{", "// 1. Run the install migration", "if", "(", "!", "$", "this", "->", "db", "->", "tableExists", "(", "Map", "::", "TableName", ")", ")", "(", "new", "Install", "(", ")", ")", "->", "safeUp", "(", ")", ";"...
@inheritdoc @throws \Throwable @throws \craft\errors\ElementNotFoundException @throws \yii\base\Exception @throws \yii\db\Exception
[ "@inheritdoc" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/migrations/m190226_143809_craft3_upgrade.php#L40-L51
ethercreative/simplemap
src/migrations/m190226_143809_craft3_upgrade.php
m190226_143809_craft3_upgrade._upgrade2
private function _upgrade2 () { $craft = \Craft::$app; $elements = $craft->elements; // Delete the old plugin row $this->delete(Table::PLUGINS, ['handle' => 'simple-map']); // Update the old data echo ' > Start map data upgrade' . PHP_EOL; $rows = (new Query()) ->select('*') ->from('{{%simplemap_maps}}') ->all(); foreach ($rows as $row) { echo ' > Upgrade map value ' . $row['address'] . PHP_EOL; $site = $this->getSiteByLocale($row['ownerLocale']); $map = new MapElement([ 'ownerId' => $row['ownerId'], 'ownerSiteId' => $site->id, 'fieldId' => $row['fieldId'], 'lat' => $row['lat'], 'lng' => $row['lng'], 'zoom' => $row['zoom'] ?? 15, 'address' => $row['address'], 'parts' => Json::decodeIfJson($row['parts']), ]); $elements->saveElement($map, false); } $this->dropTable('{{%simplemap_maps}}'); // Update old field types echo ' > Upgrade map field type upgrade' . PHP_EOL; $rows = (new Query()) ->select(['id', 'settings', 'handle']) ->from(Table::FIELDS) ->where(['type' => 'SimpleMap_Map']) ->all(); foreach ($rows as $row) { echo ' > Upgrade map field ' . $row['handle'] . PHP_EOL; $id = $row['id']; $oldSettings = Json::decodeIfJson($row['settings']); $newSettings = [ 'lat' => $oldSettings['lat'], 'lng' => $oldSettings['lng'], 'zoom' => $oldSettings['zoom'] ?? 15, 'country' => strtoupper($oldSettings['countryRestriction'] ?? '') ?: null, 'hideMap' => $oldSettings['hideMap'], ]; $this->db->createCommand() ->update( Table::FIELDS, [ 'type' => MapField::class, 'settings' => Json::encode($newSettings), ], compact('id') ) ->execute(); } // Update the plugin settings $this->updatePluginSettings(); }
php
private function _upgrade2 () { $craft = \Craft::$app; $elements = $craft->elements; // Delete the old plugin row $this->delete(Table::PLUGINS, ['handle' => 'simple-map']); // Update the old data echo ' > Start map data upgrade' . PHP_EOL; $rows = (new Query()) ->select('*') ->from('{{%simplemap_maps}}') ->all(); foreach ($rows as $row) { echo ' > Upgrade map value ' . $row['address'] . PHP_EOL; $site = $this->getSiteByLocale($row['ownerLocale']); $map = new MapElement([ 'ownerId' => $row['ownerId'], 'ownerSiteId' => $site->id, 'fieldId' => $row['fieldId'], 'lat' => $row['lat'], 'lng' => $row['lng'], 'zoom' => $row['zoom'] ?? 15, 'address' => $row['address'], 'parts' => Json::decodeIfJson($row['parts']), ]); $elements->saveElement($map, false); } $this->dropTable('{{%simplemap_maps}}'); // Update old field types echo ' > Upgrade map field type upgrade' . PHP_EOL; $rows = (new Query()) ->select(['id', 'settings', 'handle']) ->from(Table::FIELDS) ->where(['type' => 'SimpleMap_Map']) ->all(); foreach ($rows as $row) { echo ' > Upgrade map field ' . $row['handle'] . PHP_EOL; $id = $row['id']; $oldSettings = Json::decodeIfJson($row['settings']); $newSettings = [ 'lat' => $oldSettings['lat'], 'lng' => $oldSettings['lng'], 'zoom' => $oldSettings['zoom'] ?? 15, 'country' => strtoupper($oldSettings['countryRestriction'] ?? '') ?: null, 'hideMap' => $oldSettings['hideMap'], ]; $this->db->createCommand() ->update( Table::FIELDS, [ 'type' => MapField::class, 'settings' => Json::encode($newSettings), ], compact('id') ) ->execute(); } // Update the plugin settings $this->updatePluginSettings(); }
[ "private", "function", "_upgrade2", "(", ")", "{", "$", "craft", "=", "\\", "Craft", "::", "$", "app", ";", "$", "elements", "=", "$", "craft", "->", "elements", ";", "// Delete the old plugin row", "$", "this", "->", "delete", "(", "Table", "::", "PLUGI...
Upgrade from Craft 2 @throws \Throwable @throws \craft\errors\ElementNotFoundException @throws \yii\base\Exception @throws \yii\db\Exception
[ "Upgrade", "from", "Craft", "2" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/migrations/m190226_143809_craft3_upgrade.php#L70-L146
ethercreative/simplemap
src/migrations/m190226_143809_craft3_upgrade.php
m190226_143809_craft3_upgrade._upgrade3
private function _upgrade3 () { $craft = \Craft::$app; $elements = $craft->elements; // 1. Store the old data echo ' > Start map data upgrade' . PHP_EOL; $rows = (new Query()) ->select([ 'ownerId', 'ownerSiteId', 'fieldId', 'lat', 'lng', 'zoom', 'address', 'parts', ]) ->from(Map::TableName) ->all(); // 2. Re-create the table $this->dropTable(Map::TableName); (new Install())->safeUp(); // 3. Store the old data as new foreach ($rows as $row) { echo ' > Upgrade map value ' . $row['address'] . PHP_EOL; $map = new MapElement($row); if (!$map->zoom) $map->zoom = 15; $elements->saveElement($map, false); } // 4. Update field settings echo ' > Upgrade map field type upgrade' . PHP_EOL; $rows = (new Query()) ->select(['id', 'settings', 'handle']) ->from(Table::FIELDS) ->where(['type' => MapField::class]) ->all(); foreach ($rows as $row) { echo ' > Upgrade map field ' . $row['handle'] . PHP_EOL; $id = $row['id']; $oldSettings = Json::decodeIfJson($row['settings']); $newSettings = [ 'lat' => $oldSettings['lat'], 'lng' => $oldSettings['lng'], 'zoom' => $oldSettings['zoom'] ?? 15, 'country' => strtoupper($oldSettings['countryRestriction']), 'hideMap' => $oldSettings['hideMap'], ]; $this->db->createCommand() ->update( Table::FIELDS, [ 'settings' => Json::encode($newSettings) ], compact('id') ) ->execute(); } $this->updatePluginSettings(); }
php
private function _upgrade3 () { $craft = \Craft::$app; $elements = $craft->elements; // 1. Store the old data echo ' > Start map data upgrade' . PHP_EOL; $rows = (new Query()) ->select([ 'ownerId', 'ownerSiteId', 'fieldId', 'lat', 'lng', 'zoom', 'address', 'parts', ]) ->from(Map::TableName) ->all(); // 2. Re-create the table $this->dropTable(Map::TableName); (new Install())->safeUp(); // 3. Store the old data as new foreach ($rows as $row) { echo ' > Upgrade map value ' . $row['address'] . PHP_EOL; $map = new MapElement($row); if (!$map->zoom) $map->zoom = 15; $elements->saveElement($map, false); } // 4. Update field settings echo ' > Upgrade map field type upgrade' . PHP_EOL; $rows = (new Query()) ->select(['id', 'settings', 'handle']) ->from(Table::FIELDS) ->where(['type' => MapField::class]) ->all(); foreach ($rows as $row) { echo ' > Upgrade map field ' . $row['handle'] . PHP_EOL; $id = $row['id']; $oldSettings = Json::decodeIfJson($row['settings']); $newSettings = [ 'lat' => $oldSettings['lat'], 'lng' => $oldSettings['lng'], 'zoom' => $oldSettings['zoom'] ?? 15, 'country' => strtoupper($oldSettings['countryRestriction']), 'hideMap' => $oldSettings['hideMap'], ]; $this->db->createCommand() ->update( Table::FIELDS, [ 'settings' => Json::encode($newSettings) ], compact('id') ) ->execute(); } $this->updatePluginSettings(); }
[ "private", "function", "_upgrade3", "(", ")", "{", "$", "craft", "=", "\\", "Craft", "::", "$", "app", ";", "$", "elements", "=", "$", "craft", "->", "elements", ";", "// 1. Store the old data", "echo", "' > Start map data upgrade'", ".", "PHP_EOL", ";", ...
Upgrade from SimpleMap (3.3.x) @throws \Throwable @throws \craft\errors\ElementNotFoundException @throws \yii\base\Exception
[ "Upgrade", "from", "SimpleMap", "(", "3", ".", "3", ".", "x", ")" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/migrations/m190226_143809_craft3_upgrade.php#L155-L228
ethercreative/simplemap
src/migrations/m190226_143809_craft3_upgrade.php
m190226_143809_craft3_upgrade.locale2handle
private function locale2handle (string $locale): string { if ( !preg_match('/^' . HandleValidator::$handlePattern . '$/', $locale) || in_array(strtolower($locale), HandleValidator::$baseReservedWords, true) ) { $localeParts = array_filter(preg_split('/[^a-zA-Z0-9]/', $locale)); return $localeParts ? '_' . implode('_', $localeParts) : ''; } return $locale; }
php
private function locale2handle (string $locale): string { if ( !preg_match('/^' . HandleValidator::$handlePattern . '$/', $locale) || in_array(strtolower($locale), HandleValidator::$baseReservedWords, true) ) { $localeParts = array_filter(preg_split('/[^a-zA-Z0-9]/', $locale)); return $localeParts ? '_' . implode('_', $localeParts) : ''; } return $locale; }
[ "private", "function", "locale2handle", "(", "string", "$", "locale", ")", ":", "string", "{", "if", "(", "!", "preg_match", "(", "'/^'", ".", "HandleValidator", "::", "$", "handlePattern", ".", "'$/'", ",", "$", "locale", ")", "||", "in_array", "(", "st...
Returns a site handle based on a given locale. @param string $locale @return string
[ "Returns", "a", "site", "handle", "based", "on", "a", "given", "locale", "." ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/migrations/m190226_143809_craft3_upgrade.php#L240-L252
ethercreative/simplemap
src/migrations/m190226_143809_craft3_upgrade.php
m190226_143809_craft3_upgrade.getSiteByLocale
private function getSiteByLocale ($locale) { $sites = \Craft::$app->sites; if ($locale === null) return static::$sitesByOldLocale[$locale] = $sites->primarySite; if (array_key_exists($locale, static::$sitesByOldLocale)) return static::$sitesByOldLocale[$locale]; $handle = $this->locale2handle($locale); $siteId = (new Query()) ->select('id') ->from(Table::SITES) ->where(['like', 'handle', '%' . $handle]) ->column(); if (!empty($siteId)) return static::$sitesByOldLocale[$locale] = $sites->getSiteById($siteId[0]); return static::$sitesByOldLocale[$locale] = $sites->primarySite; }
php
private function getSiteByLocale ($locale) { $sites = \Craft::$app->sites; if ($locale === null) return static::$sitesByOldLocale[$locale] = $sites->primarySite; if (array_key_exists($locale, static::$sitesByOldLocale)) return static::$sitesByOldLocale[$locale]; $handle = $this->locale2handle($locale); $siteId = (new Query()) ->select('id') ->from(Table::SITES) ->where(['like', 'handle', '%' . $handle]) ->column(); if (!empty($siteId)) return static::$sitesByOldLocale[$locale] = $sites->getSiteById($siteId[0]); return static::$sitesByOldLocale[$locale] = $sites->primarySite; }
[ "private", "function", "getSiteByLocale", "(", "$", "locale", ")", "{", "$", "sites", "=", "\\", "Craft", "::", "$", "app", "->", "sites", ";", "if", "(", "$", "locale", "===", "null", ")", "return", "static", "::", "$", "sitesByOldLocale", "[", "$", ...
Gets the new site based off the old locale @param string $locale @return \craft\models\Site
[ "Gets", "the", "new", "site", "based", "off", "the", "old", "locale" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/migrations/m190226_143809_craft3_upgrade.php#L261-L283
ethercreative/simplemap
src/migrations/m190226_143809_craft3_upgrade.php
m190226_143809_craft3_upgrade.updatePluginSettings
private function updatePluginSettings () { echo ' > Upgrade Maps settings' . PHP_EOL; /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings()->toArray(); $newSettings = SimpleMap::getInstance()->getSettings()->toArray(); $craft2Settings = \Craft::$app->projectConfig->get( Plugins::CONFIG_PLUGINS_KEY . '.simple-map.settings' ); if (is_array($craft2Settings) && !empty($craft2Settings)) { $settings = [ 'apiKey' => $craft2Settings['browserApiKey'], 'unrestrictedApiKey' => $craft2Settings['serverApiKey'], ]; } if ($settings['unrestrictedApiKey']) { $newSettings['geoService'] = GeoService::GoogleMaps; $newSettings['geoToken'] = $settings['unrestrictedApiKey']; } if ($settings['apiKey']) { $newSettings['mapTiles'] = MapTiles::GoogleRoadmap; $newSettings['mapToken'] = $settings['apiKey']; if (!$settings['unrestrictedApiKey']) { $newSettings['geoService'] = GeoService::GoogleMaps; $newSettings['geoToken'] = $settings['apiKey']; } } \Craft::$app->plugins->savePluginSettings( SimpleMap::getInstance(), $newSettings ); \Craft::$app->plugins->enablePlugin(SimpleMap::getInstance()->handle); }
php
private function updatePluginSettings () { echo ' > Upgrade Maps settings' . PHP_EOL; /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings()->toArray(); $newSettings = SimpleMap::getInstance()->getSettings()->toArray(); $craft2Settings = \Craft::$app->projectConfig->get( Plugins::CONFIG_PLUGINS_KEY . '.simple-map.settings' ); if (is_array($craft2Settings) && !empty($craft2Settings)) { $settings = [ 'apiKey' => $craft2Settings['browserApiKey'], 'unrestrictedApiKey' => $craft2Settings['serverApiKey'], ]; } if ($settings['unrestrictedApiKey']) { $newSettings['geoService'] = GeoService::GoogleMaps; $newSettings['geoToken'] = $settings['unrestrictedApiKey']; } if ($settings['apiKey']) { $newSettings['mapTiles'] = MapTiles::GoogleRoadmap; $newSettings['mapToken'] = $settings['apiKey']; if (!$settings['unrestrictedApiKey']) { $newSettings['geoService'] = GeoService::GoogleMaps; $newSettings['geoToken'] = $settings['apiKey']; } } \Craft::$app->plugins->savePluginSettings( SimpleMap::getInstance(), $newSettings ); \Craft::$app->plugins->enablePlugin(SimpleMap::getInstance()->handle); }
[ "private", "function", "updatePluginSettings", "(", ")", "{", "echo", "' > Upgrade Maps settings'", ".", "PHP_EOL", ";", "/** @var Settings $settings */", "$", "settings", "=", "SimpleMap", "::", "getInstance", "(", ")", "->", "getSettings", "(", ")", "->", "toAr...
Updates the plugins settings @throws \craft\errors\InvalidPluginException
[ "Updates", "the", "plugins", "settings" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/migrations/m190226_143809_craft3_upgrade.php#L289-L333
ethercreative/simplemap
src/enums/GeoService.php
GeoService.getSelectOptions
public static function getSelectOptions () { return [ [ 'optgroup' => SimpleMap::t('Open Source') ], self::Nominatim => SimpleMap::t('Nominatim'), [ 'optgroup' => SimpleMap::t('Requires API Key (Token)') ], self::Mapbox => SimpleMap::t('Mapbox'), self::GoogleMaps => SimpleMap::t('Google Maps'), // MapKit lacks both separate address parts and country restriction // on the front-end, and any sort of server-side API, so it's // disabled for now. // self::AppleMapKit => SimpleMap::t('Apple MapKit'), self::Here => SimpleMap::t('Here'), ]; }
php
public static function getSelectOptions () { return [ [ 'optgroup' => SimpleMap::t('Open Source') ], self::Nominatim => SimpleMap::t('Nominatim'), [ 'optgroup' => SimpleMap::t('Requires API Key (Token)') ], self::Mapbox => SimpleMap::t('Mapbox'), self::GoogleMaps => SimpleMap::t('Google Maps'), // MapKit lacks both separate address parts and country restriction // on the front-end, and any sort of server-side API, so it's // disabled for now. // self::AppleMapKit => SimpleMap::t('Apple MapKit'), self::Here => SimpleMap::t('Here'), ]; }
[ "public", "static", "function", "getSelectOptions", "(", ")", "{", "return", "[", "[", "'optgroup'", "=>", "SimpleMap", "::", "t", "(", "'Open Source'", ")", "]", ",", "self", "::", "Nominatim", "=>", "SimpleMap", "::", "t", "(", "'Nominatim'", ")", ",", ...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/enums/GeoService.php#L45-L64
ethercreative/simplemap
src/SimpleMap.php
SimpleMap.init
public function init () { parent::init(); \Craft::setAlias( 'simplemapimages', __DIR__ . '/web/assets/imgs' ); $this->setComponents([ 'map' => MapService::class, ]); Event::on( Fields::class, Fields::EVENT_REGISTER_FIELD_TYPES, [$this, 'onRegisterFieldTypes'] ); Event::on( CraftVariable::class, CraftVariable::EVENT_INIT, [$this, 'onRegisterVariable'] ); /** @noinspection PhpUndefinedNamespaceInspection */ /** @noinspection PhpUndefinedClassInspection */ if (class_exists(\markhuot\CraftQL\CraftQL::class)) { Event::on( MapField::class, 'craftQlGetFieldSchema', [new GetCraftQLSchema, 'handle'] ); } }
php
public function init () { parent::init(); \Craft::setAlias( 'simplemapimages', __DIR__ . '/web/assets/imgs' ); $this->setComponents([ 'map' => MapService::class, ]); Event::on( Fields::class, Fields::EVENT_REGISTER_FIELD_TYPES, [$this, 'onRegisterFieldTypes'] ); Event::on( CraftVariable::class, CraftVariable::EVENT_INIT, [$this, 'onRegisterVariable'] ); /** @noinspection PhpUndefinedNamespaceInspection */ /** @noinspection PhpUndefinedClassInspection */ if (class_exists(\markhuot\CraftQL\CraftQL::class)) { Event::on( MapField::class, 'craftQlGetFieldSchema', [new GetCraftQLSchema, 'handle'] ); } }
[ "public", "function", "init", "(", ")", "{", "parent", "::", "init", "(", ")", ";", "\\", "Craft", "::", "setAlias", "(", "'simplemapimages'", ",", "__DIR__", ".", "'/web/assets/imgs'", ")", ";", "$", "this", "->", "setComponents", "(", "[", "'map'", "=>...
=========================================================================
[ "=========================================================================" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/SimpleMap.php#L42-L77
ethercreative/simplemap
src/SimpleMap.php
SimpleMap.onRegisterVariable
public function onRegisterVariable (Event $event) { /** @var CraftVariable $variable */ $variable = $event->sender; $variable->set('simpleMap', Variable::class); $variable->set('maps', Variable::class); }
php
public function onRegisterVariable (Event $event) { /** @var CraftVariable $variable */ $variable = $event->sender; $variable->set('simpleMap', Variable::class); $variable->set('maps', Variable::class); }
[ "public", "function", "onRegisterVariable", "(", "Event", "$", "event", ")", "{", "/** @var CraftVariable $variable */", "$", "variable", "=", "$", "event", "->", "sender", ";", "$", "variable", "->", "set", "(", "'simpleMap'", ",", "Variable", "::", "class", ...
@param Event $event @throws \yii\base\InvalidConfigException
[ "@param", "Event", "$event" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/SimpleMap.php#L118-L124
ethercreative/simplemap
src/fields/MapField.php
MapField.normalizeValue
public function normalizeValue ($value, ElementInterface $element = null) { if (is_array($value) && !empty($value[0])) $value = $value[0]; if ($value instanceof MapElement) return $value; if ($value instanceof ElementQueryInterface) return $value->one(); if (is_string($value)) $value = Json::decodeIfJson($value); $map = null; if ($element && $element->id) { /** @var MapElement $map */ $map = MapElement::find() ->anyStatus() ->fieldId($this->id) ->ownerSiteId($element->siteId) ->ownerId($element->id) ->trashed($element->trashed) ->one(); if ($map && $value) { $map->lat = $value['lat']; $map->lng = $value['lng']; $map->zoom = $value['zoom']; $map->address = $value['address']; $map->parts = $value['parts']; } } if ($map === null) { if (is_array($value)) $map = new MapElement($value); else $map = new MapElement([ 'lat' => null, 'lng' => null, 'zoom' => $this->zoom, ]); } $map->ownerId = $element->id; $map->ownerSiteId = $element->siteId; $map->fieldId = $this->id; $handle = $this->handle; $element->$handle = $map; return $map; }
php
public function normalizeValue ($value, ElementInterface $element = null) { if (is_array($value) && !empty($value[0])) $value = $value[0]; if ($value instanceof MapElement) return $value; if ($value instanceof ElementQueryInterface) return $value->one(); if (is_string($value)) $value = Json::decodeIfJson($value); $map = null; if ($element && $element->id) { /** @var MapElement $map */ $map = MapElement::find() ->anyStatus() ->fieldId($this->id) ->ownerSiteId($element->siteId) ->ownerId($element->id) ->trashed($element->trashed) ->one(); if ($map && $value) { $map->lat = $value['lat']; $map->lng = $value['lng']; $map->zoom = $value['zoom']; $map->address = $value['address']; $map->parts = $value['parts']; } } if ($map === null) { if (is_array($value)) $map = new MapElement($value); else $map = new MapElement([ 'lat' => null, 'lng' => null, 'zoom' => $this->zoom, ]); } $map->ownerId = $element->id; $map->ownerSiteId = $element->siteId; $map->fieldId = $this->id; $handle = $this->handle; $element->$handle = $map; return $map; }
[ "public", "function", "normalizeValue", "(", "$", "value", ",", "ElementInterface", "$", "element", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "!", "empty", "(", "$", "value", "[", "0", "]", ")", ")", "$", "value", ...
@param MapElement|null $value @param ElementInterface|Element|null $element @return MapElement
[ "@param", "MapElement|null", "$value", "@param", "ElementInterface|Element|null", "$element" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L191-L248
ethercreative/simplemap
src/fields/MapField.php
MapField.getInputHtml
public function getInputHtml ($value, ElementInterface $element = null): string { if ($element !== null && $element->hasEagerLoadedElements($this->handle)) $value = $element->getEagerLoadedElements($this->handle); /** @noinspection PhpComposerExtensionStubsInspection */ return new Markup( $this->_renderMap($value), 'utf-8' ); }
php
public function getInputHtml ($value, ElementInterface $element = null): string { if ($element !== null && $element->hasEagerLoadedElements($this->handle)) $value = $element->getEagerLoadedElements($this->handle); /** @noinspection PhpComposerExtensionStubsInspection */ return new Markup( $this->_renderMap($value), 'utf-8' ); }
[ "public", "function", "getInputHtml", "(", "$", "value", ",", "ElementInterface", "$", "element", "=", "null", ")", ":", "string", "{", "if", "(", "$", "element", "!==", "null", "&&", "$", "element", "->", "hasEagerLoadedElements", "(", "$", "this", "->", ...
@param MapElement $value @param ElementInterface|Element|null $element @return string @throws InvalidConfigException
[ "@param", "MapElement", "$value", "@param", "ElementInterface|Element|null", "$element" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L309-L319
ethercreative/simplemap
src/fields/MapField.php
MapField.getTableAttributeHtml
public function getTableAttributeHtml ($value, ElementInterface $element): string { return $this->normalizeValue($value, $element)->address; }
php
public function getTableAttributeHtml ($value, ElementInterface $element): string { return $this->normalizeValue($value, $element)->address; }
[ "public", "function", "getTableAttributeHtml", "(", "$", "value", ",", "ElementInterface", "$", "element", ")", ":", "string", "{", "return", "$", "this", "->", "normalizeValue", "(", "$", "value", ",", "$", "element", ")", "->", "address", ";", "}" ]
@inheritdoc @param mixed $value @param ElementInterface $element @return string
[ "@inheritdoc" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L329-L332
ethercreative/simplemap
src/fields/MapField.php
MapField.getEagerLoadingMap
public function getEagerLoadingMap (array $sourceElements) { $sourceElementIds = []; $sourceSiteIds = []; foreach ($sourceElements as $sourceElement) { $sourceElementIds[] = $sourceElement->id; $sourceSiteIds[] = $sourceElement->siteId; } $map = (new Query()) ->select(['ownerId as source', 'id as target']) ->from([MapRecord::TableName]) ->where([ 'fieldId' => $this->id, 'ownerId' => $sourceElementIds, 'ownerSiteId' => $sourceSiteIds, ]) ->all(); return [ 'elementType' => MapElement::class, 'map' => $map, 'criteria' => ['fieldId' => $this->id], ]; }
php
public function getEagerLoadingMap (array $sourceElements) { $sourceElementIds = []; $sourceSiteIds = []; foreach ($sourceElements as $sourceElement) { $sourceElementIds[] = $sourceElement->id; $sourceSiteIds[] = $sourceElement->siteId; } $map = (new Query()) ->select(['ownerId as source', 'id as target']) ->from([MapRecord::TableName]) ->where([ 'fieldId' => $this->id, 'ownerId' => $sourceElementIds, 'ownerSiteId' => $sourceSiteIds, ]) ->all(); return [ 'elementType' => MapElement::class, 'map' => $map, 'criteria' => ['fieldId' => $this->id], ]; }
[ "public", "function", "getEagerLoadingMap", "(", "array", "$", "sourceElements", ")", "{", "$", "sourceElementIds", "=", "[", "]", ";", "$", "sourceSiteIds", "=", "[", "]", ";", "foreach", "(", "$", "sourceElements", "as", "$", "sourceElement", ")", "{", "...
@inheritdoc @param array $sourceElements @return array
[ "@inheritdoc" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L341-L367
ethercreative/simplemap
src/fields/MapField.php
MapField.modifyElementsQuery
public function modifyElementsQuery (ElementQueryInterface $query, $value) { if (!SimpleMap::getInstance()) return null; SimpleMap::getInstance()->map->modifyElementsQuery($query, $value); return null; }
php
public function modifyElementsQuery (ElementQueryInterface $query, $value) { if (!SimpleMap::getInstance()) return null; SimpleMap::getInstance()->map->modifyElementsQuery($query, $value); return null; }
[ "public", "function", "modifyElementsQuery", "(", "ElementQueryInterface", "$", "query", ",", "$", "value", ")", "{", "if", "(", "!", "SimpleMap", "::", "getInstance", "(", ")", ")", "return", "null", ";", "SimpleMap", "::", "getInstance", "(", ")", "->", ...
@param ElementQueryInterface $query @param $value @return bool|false|null @throws \yii\db\Exception
[ "@param", "ElementQueryInterface", "$query", "@param", "$value" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L376-L384
ethercreative/simplemap
src/fields/MapField.php
MapField.beforeElementSave
public function beforeElementSave (ElementInterface $element, bool $isNew): bool { if (!SimpleMap::getInstance()->map->validateField($this, $element)) return false; return parent::beforeElementSave($element, $isNew); }
php
public function beforeElementSave (ElementInterface $element, bool $isNew): bool { if (!SimpleMap::getInstance()->map->validateField($this, $element)) return false; return parent::beforeElementSave($element, $isNew); }
[ "public", "function", "beforeElementSave", "(", "ElementInterface", "$", "element", ",", "bool", "$", "isNew", ")", ":", "bool", "{", "if", "(", "!", "SimpleMap", "::", "getInstance", "(", ")", "->", "map", "->", "validateField", "(", "$", "this", ",", "...
@param ElementInterface|Element $element @param bool $isNew @return bool
[ "@param", "ElementInterface|Element", "$element", "@param", "bool", "$isNew" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L418-L424
ethercreative/simplemap
src/fields/MapField.php
MapField.afterElementSave
public function afterElementSave (ElementInterface $element, bool $isNew) { SimpleMap::getInstance()->map->saveField($this, $element); parent::afterElementSave($element, $isNew); }
php
public function afterElementSave (ElementInterface $element, bool $isNew) { SimpleMap::getInstance()->map->saveField($this, $element); parent::afterElementSave($element, $isNew); }
[ "public", "function", "afterElementSave", "(", "ElementInterface", "$", "element", ",", "bool", "$", "isNew", ")", "{", "SimpleMap", "::", "getInstance", "(", ")", "->", "map", "->", "saveField", "(", "$", "this", ",", "$", "element", ")", ";", "parent", ...
@param ElementInterface|Element $element @param bool $isNew @throws Throwable
[ "@param", "ElementInterface|Element", "$element", "@param", "bool", "$isNew" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L432-L436
ethercreative/simplemap
src/fields/MapField.php
MapField.afterElementDelete
public function afterElementDelete (ElementInterface $element) { SimpleMap::getInstance()->map->softDeleteField($this, $element); parent::afterElementDelete($element); }
php
public function afterElementDelete (ElementInterface $element) { SimpleMap::getInstance()->map->softDeleteField($this, $element); parent::afterElementDelete($element); }
[ "public", "function", "afterElementDelete", "(", "ElementInterface", "$", "element", ")", "{", "SimpleMap", "::", "getInstance", "(", ")", "->", "map", "->", "softDeleteField", "(", "$", "this", ",", "$", "element", ")", ";", "parent", "::", "afterElementDelet...
@param ElementInterface|Element $element @throws Throwable
[ "@param", "ElementInterface|Element", "$element" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L443-L447
ethercreative/simplemap
src/fields/MapField.php
MapField.afterElementRestore
public function afterElementRestore (ElementInterface $element) { SimpleMap::getInstance()->map->restoreField($this, $element); parent::afterElementRestore($element); }
php
public function afterElementRestore (ElementInterface $element) { SimpleMap::getInstance()->map->restoreField($this, $element); parent::afterElementRestore($element); }
[ "public", "function", "afterElementRestore", "(", "ElementInterface", "$", "element", ")", "{", "SimpleMap", "::", "getInstance", "(", ")", "->", "map", "->", "restoreField", "(", "$", "this", ",", "$", "element", ")", ";", "parent", "::", "afterElementRestore...
@param ElementInterface|Element $element @throws Throwable @throws Exception
[ "@param", "ElementInterface|Element", "$element" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L455-L459
ethercreative/simplemap
src/fields/MapField.php
MapField._renderMap
private function _renderMap ($value, $isSettings = false) { $view = Craft::$app->getView(); $containerId = $this->id . '-container'; $vueContainerId = $view->namespaceInputId($containerId); $view->registerJsFile('https://polyfill.io/v3/polyfill.min.js?flags=gated&features=default%2CIntersectionObserver%2CIntersectionObserverEntry'); $view->registerAssetBundle(MapAsset::class); $view->registerJs('new Vue({ el: \'#' . $vueContainerId . '\' });'); $view->registerTranslations('simplemap', [ 'Search for a location', 'Clear', 'Name / Number', 'Street Address', 'Town / City', 'Postcode', 'County', 'State', 'Country', 'Latitude', 'Longitude', ]); /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); $country = $this->country; // Convert ISO2 to ISO3 for Here autocomplete if ($country && $settings->geoService === GeoEnum::Here) $country = GeoService::$countriesIso3[$country]; $opts = [ 'config' => [ 'isSettings' => $isSettings, 'name' => $view->namespaceInputName($this->handle), 'country' => $country, 'hideSearch' => (bool) $this->hideSearch, 'hideMap' => (bool) $this->hideMap, 'hideAddress' => (bool) $this->hideAddress, 'showLatLng' => (bool) $this->showLatLng, 'mapTiles' => $settings->mapTiles, 'mapToken' => GeoService::getToken( $settings->mapToken, $settings->mapTiles ), 'geoService' => $settings->geoService, 'geoToken' => GeoService::getToken( $settings->geoToken, $settings->geoService ), 'locale' => Craft::$app->locale->getLanguageID(), ], 'value' => [ 'address' => $value->address, 'lat' => $value->lat, 'lng' => $value->lng, 'zoom' => $value->zoom, 'parts' => $value->parts, ], 'defaultValue' => [ 'address' => null, 'lat' => $this->lat, 'lng' => $this->lng, 'zoom' => $this->zoom, 'parts' => null, ], ]; // Map Services // --------------------------------------------------------------------- if (strpos($settings->mapTiles, 'google') !== false) { $view->registerJsFile( 'https://maps.googleapis.com/maps/api/js?libraries=places&key=' . $settings->mapToken ); } elseif (strpos($settings->mapTiles, 'mapkit') !== false) { $view->registerJsFile( 'https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js' ); } // Geo Services // --------------------------------------------------------------------- if ($settings->geoService === GeoEnum::GoogleMaps) { $view->registerJsFile( 'https://maps.googleapis.com/maps/api/js?libraries=places&key=' . $settings->geoToken ); } elseif ($settings->geoService === GeoEnum::AppleMapKit) { $view->registerJsFile( 'https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js' ); } $options = preg_replace( '/\'/', '&#039;', json_encode($opts) ); return '<div id="' . $containerId . '"><simple-map options=\'' . $options . '\'></simple-map></div>'; }
php
private function _renderMap ($value, $isSettings = false) { $view = Craft::$app->getView(); $containerId = $this->id . '-container'; $vueContainerId = $view->namespaceInputId($containerId); $view->registerJsFile('https://polyfill.io/v3/polyfill.min.js?flags=gated&features=default%2CIntersectionObserver%2CIntersectionObserverEntry'); $view->registerAssetBundle(MapAsset::class); $view->registerJs('new Vue({ el: \'#' . $vueContainerId . '\' });'); $view->registerTranslations('simplemap', [ 'Search for a location', 'Clear', 'Name / Number', 'Street Address', 'Town / City', 'Postcode', 'County', 'State', 'Country', 'Latitude', 'Longitude', ]); /** @var Settings $settings */ $settings = SimpleMap::getInstance()->getSettings(); $country = $this->country; // Convert ISO2 to ISO3 for Here autocomplete if ($country && $settings->geoService === GeoEnum::Here) $country = GeoService::$countriesIso3[$country]; $opts = [ 'config' => [ 'isSettings' => $isSettings, 'name' => $view->namespaceInputName($this->handle), 'country' => $country, 'hideSearch' => (bool) $this->hideSearch, 'hideMap' => (bool) $this->hideMap, 'hideAddress' => (bool) $this->hideAddress, 'showLatLng' => (bool) $this->showLatLng, 'mapTiles' => $settings->mapTiles, 'mapToken' => GeoService::getToken( $settings->mapToken, $settings->mapTiles ), 'geoService' => $settings->geoService, 'geoToken' => GeoService::getToken( $settings->geoToken, $settings->geoService ), 'locale' => Craft::$app->locale->getLanguageID(), ], 'value' => [ 'address' => $value->address, 'lat' => $value->lat, 'lng' => $value->lng, 'zoom' => $value->zoom, 'parts' => $value->parts, ], 'defaultValue' => [ 'address' => null, 'lat' => $this->lat, 'lng' => $this->lng, 'zoom' => $this->zoom, 'parts' => null, ], ]; // Map Services // --------------------------------------------------------------------- if (strpos($settings->mapTiles, 'google') !== false) { $view->registerJsFile( 'https://maps.googleapis.com/maps/api/js?libraries=places&key=' . $settings->mapToken ); } elseif (strpos($settings->mapTiles, 'mapkit') !== false) { $view->registerJsFile( 'https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js' ); } // Geo Services // --------------------------------------------------------------------- if ($settings->geoService === GeoEnum::GoogleMaps) { $view->registerJsFile( 'https://maps.googleapis.com/maps/api/js?libraries=places&key=' . $settings->geoToken ); } elseif ($settings->geoService === GeoEnum::AppleMapKit) { $view->registerJsFile( 'https://cdn.apple-mapkit.com/mk/5.x.x/mapkit.js' ); } $options = preg_replace( '/\'/', '&#039;', json_encode($opts) ); return '<div id="' . $containerId . '"><simple-map options=\'' . $options . '\'></simple-map></div>'; }
[ "private", "function", "_renderMap", "(", "$", "value", ",", "$", "isSettings", "=", "false", ")", "{", "$", "view", "=", "Craft", "::", "$", "app", "->", "getView", "(", ")", ";", "$", "containerId", "=", "$", "this", "->", "id", ".", "'-container'"...
Renders the map input @param $value @param bool $isSettings @return string @throws InvalidConfigException
[ "Renders", "the", "map", "input" ]
train
https://github.com/ethercreative/simplemap/blob/cea5a8bd8468674bc9ca2854d6bd9b22e43d64b7/src/fields/MapField.php#L473-L588
Torann/json-ld
src/ContextTypes/CreativeWork.php
CreativeWork.setAuthorAttribute
protected function setAuthorAttribute($items) { if (is_array($items) === false) { return $items; } return array_map(function ($item) { return $this->getNestedContext(Person::class, $item); }, $items); }
php
protected function setAuthorAttribute($items) { if (is_array($items) === false) { return $items; } return array_map(function ($item) { return $this->getNestedContext(Person::class, $item); }, $items); }
[ "protected", "function", "setAuthorAttribute", "(", "$", "items", ")", "{", "if", "(", "is_array", "(", "$", "items", ")", "===", "false", ")", "{", "return", "$", "items", ";", "}", "return", "array_map", "(", "function", "(", "$", "item", ")", "{", ...
Set the authors @param array $items @return array
[ "Set", "the", "authors" ]
train
https://github.com/Torann/json-ld/blob/4d439220cb012df2705e2ad6472d2426fcb14b4c/src/ContextTypes/CreativeWork.php#L65-L74
Torann/json-ld
src/ContextTypes/CreativeWork.php
CreativeWork.setCommentAttribute
protected function setCommentAttribute($items) { if (is_array($items) === false) { return $items; } return array_map(function ($item) { return $this->getNestedContext(Comment::class, $item); }, $items); }
php
protected function setCommentAttribute($items) { if (is_array($items) === false) { return $items; } return array_map(function ($item) { return $this->getNestedContext(Comment::class, $item); }, $items); }
[ "protected", "function", "setCommentAttribute", "(", "$", "items", ")", "{", "if", "(", "is_array", "(", "$", "items", ")", "===", "false", ")", "{", "return", "$", "items", ";", "}", "return", "array_map", "(", "function", "(", "$", "item", ")", "{", ...
Set the comments @param array $items @return array
[ "Set", "the", "comments" ]
train
https://github.com/Torann/json-ld/blob/4d439220cb012df2705e2ad6472d2426fcb14b4c/src/ContextTypes/CreativeWork.php#L82-L91
Torann/json-ld
src/ContextTypes/CreativeWork.php
CreativeWork.setReviewAttribute
protected function setReviewAttribute($items) { if (is_array($items) === false) { return $items; } return array_map(function ($item) { return $this->getNestedContext(Review::class, $item); }, $items); }
php
protected function setReviewAttribute($items) { if (is_array($items) === false) { return $items; } return array_map(function ($item) { return $this->getNestedContext(Review::class, $item); }, $items); }
[ "protected", "function", "setReviewAttribute", "(", "$", "items", ")", "{", "if", "(", "is_array", "(", "$", "items", ")", "===", "false", ")", "{", "return", "$", "items", ";", "}", "return", "array_map", "(", "function", "(", "$", "item", ")", "{", ...
Set the reviews @param array $items @return array
[ "Set", "the", "reviews" ]
train
https://github.com/Torann/json-ld/blob/4d439220cb012df2705e2ad6472d2426fcb14b4c/src/ContextTypes/CreativeWork.php#L99-L108
Torann/json-ld
src/Context.php
Context.getContextTypeClass
protected function getContextTypeClass($name) { // Check for custom context type if (class_exists($name)) { return $name; } // Create local context type class $class = ucwords(str_replace(['-', '_'], ' ', $name)); $class = '\\JsonLd\\ContextTypes\\' . str_replace(' ', '', $class); // Check for local context type if (class_exists($class)) { return $class; } // Backwards compatible, remove in a future version switch ($name) { case 'address': return ContextTypes\PostalAddress::class; break; case 'business': return ContextTypes\LocalBusiness::class; break; case 'breadcrumbs': return ContextTypes\BreadcrumbList::class; break; case 'geo': return ContextTypes\GeoCoordinates::class; break; } throw new InvalidArgumentException(sprintf('Undefined context type: "%s"', $name)); }
php
protected function getContextTypeClass($name) { // Check for custom context type if (class_exists($name)) { return $name; } // Create local context type class $class = ucwords(str_replace(['-', '_'], ' ', $name)); $class = '\\JsonLd\\ContextTypes\\' . str_replace(' ', '', $class); // Check for local context type if (class_exists($class)) { return $class; } // Backwards compatible, remove in a future version switch ($name) { case 'address': return ContextTypes\PostalAddress::class; break; case 'business': return ContextTypes\LocalBusiness::class; break; case 'breadcrumbs': return ContextTypes\BreadcrumbList::class; break; case 'geo': return ContextTypes\GeoCoordinates::class; break; } throw new InvalidArgumentException(sprintf('Undefined context type: "%s"', $name)); }
[ "protected", "function", "getContextTypeClass", "(", "$", "name", ")", "{", "// Check for custom context type", "if", "(", "class_exists", "(", "$", "name", ")", ")", "{", "return", "$", "name", ";", "}", "// Create local context type class", "$", "class", "=", ...
Return script tag. @param string $name @return string|null @throws InvalidArgumentException
[ "Return", "script", "tag", "." ]
train
https://github.com/Torann/json-ld/blob/4d439220cb012df2705e2ad6472d2426fcb14b4c/src/Context.php#L73-L106