repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php
StatementBuilder.select
public function select($columns) { $columns = self::removeKeyword($columns, self::SELECT); $this->select = $columns; return $this; }
php
public function select($columns) { $columns = self::removeKeyword($columns, self::SELECT); $this->select = $columns; return $this; }
[ "public", "function", "select", "(", "$", "columns", ")", "{", "$", "columns", "=", "self", "::", "removeKeyword", "(", "$", "columns", ",", "self", "::", "SELECT", ")", ";", "$", "this", "->", "select", "=", "$", "columns", ";", "return", "$", "this", ";", "}" ]
Sets the statement `SELECT` clause in the form of 'a, b, ...'. Only necessary for statements being sent to the `PublisherQueryLanguageService`. The 'SELECT ' keyword will be ignored. @param string $columns the statement select clause without `SELECT` @return StatementBuilder this builder
[ "Sets", "the", "statement", "SELECT", "clause", "in", "the", "form", "of", "a", "b", "...", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php#L139-L145
train
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php
StatementBuilder.from
public function from($table) { $table = self::removeKeyword($table, self::FROM); $this->from = $table; return $this; }
php
public function from($table) { $table = self::removeKeyword($table, self::FROM); $this->from = $table; return $this; }
[ "public", "function", "from", "(", "$", "table", ")", "{", "$", "table", "=", "self", "::", "removeKeyword", "(", "$", "table", ",", "self", "::", "FROM", ")", ";", "$", "this", "->", "from", "=", "$", "table", ";", "return", "$", "this", ";", "}" ]
Sets the statement `FROM` clause in the form of 'table'. Only necessary for statements being sent to the `PublisherQueryLanguageService`. The 'FROM ' keyword will be ignored. @param string $table the statement from clause without `FROM` @return StatementBuilder this builder
[ "Sets", "the", "statement", "FROM", "clause", "in", "the", "form", "of", "table", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php#L156-L162
train
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php
StatementBuilder.increaseOffsetBy
public function increaseOffsetBy($amount) { if ($this->offset === null) { $this->offset = 0; } $this->offset += $amount; return $this; }
php
public function increaseOffsetBy($amount) { if ($this->offset === null) { $this->offset = 0; } $this->offset += $amount; return $this; }
[ "public", "function", "increaseOffsetBy", "(", "$", "amount", ")", "{", "if", "(", "$", "this", "->", "offset", "===", "null", ")", "{", "$", "this", "->", "offset", "=", "0", ";", "}", "$", "this", "->", "offset", "+=", "$", "amount", ";", "return", "$", "this", ";", "}" ]
Increases the offset by the specified amount. @param int $amount @return StatementBuilder this builder
[ "Increases", "the", "offset", "by", "the", "specified", "amount", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php#L214-L222
train
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php
StatementBuilder.buildQuery
private function buildQuery() { $this->validateQuery(); $statement = ""; if ($this->select !== null) { $statement .= sprintf("%s %s ", self::SELECT, $this->select); } if ($this->from !== null) { $statement .= sprintf("%s %s ", self::FROM, $this->from); } if ($this->where !== null) { $statement .= sprintf("%s %s ", self::WHERE, $this->where); } if ($this->orderBy !== null) { $statement .= sprintf("%s %s ", self::ORDER_BY, $this->orderBy); } if ($this->limit !== null) { $statement .= sprintf("%s %s ", self::LIMIT, $this->limit); } if ($this->offset !== null) { $statement .= sprintf("%s %s ", self::OFFSET, $this->offset); } return trim($statement); }
php
private function buildQuery() { $this->validateQuery(); $statement = ""; if ($this->select !== null) { $statement .= sprintf("%s %s ", self::SELECT, $this->select); } if ($this->from !== null) { $statement .= sprintf("%s %s ", self::FROM, $this->from); } if ($this->where !== null) { $statement .= sprintf("%s %s ", self::WHERE, $this->where); } if ($this->orderBy !== null) { $statement .= sprintf("%s %s ", self::ORDER_BY, $this->orderBy); } if ($this->limit !== null) { $statement .= sprintf("%s %s ", self::LIMIT, $this->limit); } if ($this->offset !== null) { $statement .= sprintf("%s %s ", self::OFFSET, $this->offset); } return trim($statement); }
[ "private", "function", "buildQuery", "(", ")", "{", "$", "this", "->", "validateQuery", "(", ")", ";", "$", "statement", "=", "\"\"", ";", "if", "(", "$", "this", "->", "select", "!==", "null", ")", "{", "$", "statement", ".=", "sprintf", "(", "\"%s %s \"", ",", "self", "::", "SELECT", ",", "$", "this", "->", "select", ")", ";", "}", "if", "(", "$", "this", "->", "from", "!==", "null", ")", "{", "$", "statement", ".=", "sprintf", "(", "\"%s %s \"", ",", "self", "::", "FROM", ",", "$", "this", "->", "from", ")", ";", "}", "if", "(", "$", "this", "->", "where", "!==", "null", ")", "{", "$", "statement", ".=", "sprintf", "(", "\"%s %s \"", ",", "self", "::", "WHERE", ",", "$", "this", "->", "where", ")", ";", "}", "if", "(", "$", "this", "->", "orderBy", "!==", "null", ")", "{", "$", "statement", ".=", "sprintf", "(", "\"%s %s \"", ",", "self", "::", "ORDER_BY", ",", "$", "this", "->", "orderBy", ")", ";", "}", "if", "(", "$", "this", "->", "limit", "!==", "null", ")", "{", "$", "statement", ".=", "sprintf", "(", "\"%s %s \"", ",", "self", "::", "LIMIT", ",", "$", "this", "->", "limit", ")", ";", "}", "if", "(", "$", "this", "->", "offset", "!==", "null", ")", "{", "$", "statement", ".=", "sprintf", "(", "\"%s %s \"", ",", "self", "::", "OFFSET", ",", "$", "this", "->", "offset", ")", ";", "}", "return", "trim", "(", "$", "statement", ")", ";", "}" ]
Builds the query from the clauses. @return string the query
[ "Builds", "the", "query", "from", "the", "clauses", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/StatementBuilder.php#L292-L317
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php
ServiceQuery.validate
private static function validate($awqlString, $startIndex, $pageSize) { $validationResult = QueryValidator::validateServiceQuery( $awqlString, false ); if ($validationResult->isFailed()) { throw new InvalidArgumentException( 'The service query string is invalid. Validation fail reason: '. $validationResult->getFailReason() ); } // The `startIndex` and `pageSize` arguments are optional for // constructing a `ServiceQuery` object. They must either be both null, // or both not null. if (is_null($startIndex) !== is_null($pageSize)) { throw new InvalidArgumentException('Start index and page size' . ' must be both null, or both not null.'); } if (!is_null($startIndex)) { if (!is_int($startIndex)) { throw new InvalidArgumentException('The start index must be' . ' an integer.'); } if ($startIndex < 0) { throw new OutOfBoundsException('The start index must be 0 or' . ' a positive number.'); } } if (!is_null($pageSize)) { if (!is_int($pageSize)) { throw new InvalidArgumentException('The page size must be' . ' an integer.'); } if ($pageSize < 1) { throw new OutOfBoundsException('The page size must be a' . ' positive number.'); } } }
php
private static function validate($awqlString, $startIndex, $pageSize) { $validationResult = QueryValidator::validateServiceQuery( $awqlString, false ); if ($validationResult->isFailed()) { throw new InvalidArgumentException( 'The service query string is invalid. Validation fail reason: '. $validationResult->getFailReason() ); } // The `startIndex` and `pageSize` arguments are optional for // constructing a `ServiceQuery` object. They must either be both null, // or both not null. if (is_null($startIndex) !== is_null($pageSize)) { throw new InvalidArgumentException('Start index and page size' . ' must be both null, or both not null.'); } if (!is_null($startIndex)) { if (!is_int($startIndex)) { throw new InvalidArgumentException('The start index must be' . ' an integer.'); } if ($startIndex < 0) { throw new OutOfBoundsException('The start index must be 0 or' . ' a positive number.'); } } if (!is_null($pageSize)) { if (!is_int($pageSize)) { throw new InvalidArgumentException('The page size must be' . ' an integer.'); } if ($pageSize < 1) { throw new OutOfBoundsException('The page size must be a' . ' positive number.'); } } }
[ "private", "static", "function", "validate", "(", "$", "awqlString", ",", "$", "startIndex", ",", "$", "pageSize", ")", "{", "$", "validationResult", "=", "QueryValidator", "::", "validateServiceQuery", "(", "$", "awqlString", ",", "false", ")", ";", "if", "(", "$", "validationResult", "->", "isFailed", "(", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The service query string is invalid. Validation fail reason: '", ".", "$", "validationResult", "->", "getFailReason", "(", ")", ")", ";", "}", "// The `startIndex` and `pageSize` arguments are optional for", "// constructing a `ServiceQuery` object. They must either be both null,", "// or both not null.", "if", "(", "is_null", "(", "$", "startIndex", ")", "!==", "is_null", "(", "$", "pageSize", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Start index and page size'", ".", "' must be both null, or both not null.'", ")", ";", "}", "if", "(", "!", "is_null", "(", "$", "startIndex", ")", ")", "{", "if", "(", "!", "is_int", "(", "$", "startIndex", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The start index must be'", ".", "' an integer.'", ")", ";", "}", "if", "(", "$", "startIndex", "<", "0", ")", "{", "throw", "new", "OutOfBoundsException", "(", "'The start index must be 0 or'", ".", "' a positive number.'", ")", ";", "}", "}", "if", "(", "!", "is_null", "(", "$", "pageSize", ")", ")", "{", "if", "(", "!", "is_int", "(", "$", "pageSize", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The page size must be'", ".", "' an integer.'", ")", ";", "}", "if", "(", "$", "pageSize", "<", "1", ")", "{", "throw", "new", "OutOfBoundsException", "(", "'The page size must be a'", ".", "' positive number.'", ")", ";", "}", "}", "}" ]
Validates the arguments for constructing a service query object. @param string $awqlString the AWQL string without the LIMIT clause @param int $startIndex the start index of the first page @param int $pageSize the count of entries to be fetched in each page @throws InvalidArgumentException when the AWQL string is null or empty, or contains a LIMIT clause @throws OutOfBoundsException when the start index is a negative number, or when the page size is 0 or a negative number
[ "Validates", "the", "arguments", "for", "constructing", "a", "service", "query", "object", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php#L76-L121
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php
ServiceQuery.countLandscapePoints
private static function countLandscapePoints(Page $page) { $entries = $page->getEntries(); if (is_null($entries)) { return 0; } $totalLandscapePointsInPage = 0; foreach ($entries as $entry) { $totalLandscapePointsInPage += count($entry->getLandscapePoints()); } return $totalLandscapePointsInPage; }
php
private static function countLandscapePoints(Page $page) { $entries = $page->getEntries(); if (is_null($entries)) { return 0; } $totalLandscapePointsInPage = 0; foreach ($entries as $entry) { $totalLandscapePointsInPage += count($entry->getLandscapePoints()); } return $totalLandscapePointsInPage; }
[ "private", "static", "function", "countLandscapePoints", "(", "Page", "$", "page", ")", "{", "$", "entries", "=", "$", "page", "->", "getEntries", "(", ")", ";", "if", "(", "is_null", "(", "$", "entries", ")", ")", "{", "return", "0", ";", "}", "$", "totalLandscapePointsInPage", "=", "0", ";", "foreach", "(", "$", "entries", "as", "$", "entry", ")", "{", "$", "totalLandscapePointsInPage", "+=", "count", "(", "$", "entry", "->", "getLandscapePoints", "(", ")", ")", ";", "}", "return", "$", "totalLandscapePointsInPage", ";", "}" ]
Counts the number of landscape points in a `AdGroupBidLandscapePage` or `AdGroupBidLandscapePage` page. @param Page $page the previously fetched page which must be an instance of either `AdGroupBidLandscapePage` or `AdGroupBidLandscapePage` @return int the count of landscape points in a given page
[ "Counts", "the", "number", "of", "landscape", "points", "in", "a", "AdGroupBidLandscapePage", "or", "AdGroupBidLandscapePage", "page", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php#L132-L144
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php
ServiceQuery.nextPage
public function nextPage(Page $previousPage = null) { if (is_null($previousPage)) { $this->startIndex = $this->startIndex + $this->pageSize; return $this; } if (!($previousPage instanceof AdGroupBidLandscapePage) && !($previousPage instanceof CriterionBidLandscapePage)) { throw new InvalidArgumentException('The page object must be an' . ' instance of either `AdGroupBidLandscapePage` or' . ' `CriterionBidLandscapePage` type'); } $this->startIndex = $this->startIndex + self::countLandscapePoints($previousPage); return $this; }
php
public function nextPage(Page $previousPage = null) { if (is_null($previousPage)) { $this->startIndex = $this->startIndex + $this->pageSize; return $this; } if (!($previousPage instanceof AdGroupBidLandscapePage) && !($previousPage instanceof CriterionBidLandscapePage)) { throw new InvalidArgumentException('The page object must be an' . ' instance of either `AdGroupBidLandscapePage` or' . ' `CriterionBidLandscapePage` type'); } $this->startIndex = $this->startIndex + self::countLandscapePoints($previousPage); return $this; }
[ "public", "function", "nextPage", "(", "Page", "$", "previousPage", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "previousPage", ")", ")", "{", "$", "this", "->", "startIndex", "=", "$", "this", "->", "startIndex", "+", "$", "this", "->", "pageSize", ";", "return", "$", "this", ";", "}", "if", "(", "!", "(", "$", "previousPage", "instanceof", "AdGroupBidLandscapePage", ")", "&&", "!", "(", "$", "previousPage", "instanceof", "CriterionBidLandscapePage", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The page object must be an'", ".", "' instance of either `AdGroupBidLandscapePage` or'", ".", "' `CriterionBidLandscapePage` type'", ")", ";", "}", "$", "this", "->", "startIndex", "=", "$", "this", "->", "startIndex", "+", "self", "::", "countLandscapePoints", "(", "$", "previousPage", ")", ";", "return", "$", "this", ";", "}" ]
Increases the start index by the current page size. <p>When querying against the `DataService`, an instance of `AdGroupBidLandscapePage` or `AdGroupBidLandscapePage` is required for this function to compute the current page size. These special page classes have their own paging mechanism which is different from other services. For details, see https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results @param Page|null $previousPage optional, the previously fetched page which must be an instance of either `AdGroupBidLandscapePage` or `AdGroupBidLandscapePage` @return ServiceQuery the current `ServiceQuery` instance for chaining
[ "Increases", "the", "start", "index", "by", "the", "current", "page", "size", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php#L178-L196
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php
ServiceQuery.hasNext
public function hasNext(Page $previousPage) { if ($previousPage instanceof AdGroupBidLandscapePage || $previousPage instanceof CriterionBidLandscapePage) { return $this->pageSize <= self::countLandscapePoints($previousPage); } if (is_null($this->totalNumEntries)) { $this->totalNumEntries = $previousPage->getTotalNumEntries(); } return $this->startIndex + $this->pageSize < $this->totalNumEntries; }
php
public function hasNext(Page $previousPage) { if ($previousPage instanceof AdGroupBidLandscapePage || $previousPage instanceof CriterionBidLandscapePage) { return $this->pageSize <= self::countLandscapePoints($previousPage); } if (is_null($this->totalNumEntries)) { $this->totalNumEntries = $previousPage->getTotalNumEntries(); } return $this->startIndex + $this->pageSize < $this->totalNumEntries; }
[ "public", "function", "hasNext", "(", "Page", "$", "previousPage", ")", "{", "if", "(", "$", "previousPage", "instanceof", "AdGroupBidLandscapePage", "||", "$", "previousPage", "instanceof", "CriterionBidLandscapePage", ")", "{", "return", "$", "this", "->", "pageSize", "<=", "self", "::", "countLandscapePoints", "(", "$", "previousPage", ")", ";", "}", "if", "(", "is_null", "(", "$", "this", "->", "totalNumEntries", ")", ")", "{", "$", "this", "->", "totalNumEntries", "=", "$", "previousPage", "->", "getTotalNumEntries", "(", ")", ";", "}", "return", "$", "this", "->", "startIndex", "+", "$", "this", "->", "pageSize", "<", "$", "this", "->", "totalNumEntries", ";", "}" ]
Checks if there are still entries to be fetched on the next page. <p>When querying against the `DataService`, an instance of `AdGroupBidLandscapePage` or `AdGroupBidLandscapePage` could be returned. These special page classes have their own paging mechanism which is different from other services. For details, see https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through_results @param Page $previousPage the previously fetched page @return bool true if there are still entries to be fetched on next page; Otherwise, returns false
[ "Checks", "if", "there", "are", "still", "entries", "to", "be", "fetched", "on", "the", "next", "page", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/v201809/ServiceQuery.php#L211-L223
train
googleads/googleads-php-lib
examples/AdManager/v201811/NetworkService/GetAllNetworks.php
GetAllNetworks.runExample
public static function runExample( ServiceFactory $serviceFactory, AdManagerSession $session ) { $networkService = $serviceFactory->createNetworkService($session); // Get all networks that you have access to with the current // authentication credentials. $networks = $networkService->getAllNetworks(); if (empty($networks)) { printf('No accessible networks found.' . PHP_EOL); return; } // Print out some information for each network. foreach ($networks as $i => $network) { printf( "%d) Network with code %d and display name '%s' was found.%s", $i, $network->getNetworkCode(), $network->getDisplayName(), PHP_EOL ); } printf("Number of results found: %d%s", count($networks), PHP_EOL); }
php
public static function runExample( ServiceFactory $serviceFactory, AdManagerSession $session ) { $networkService = $serviceFactory->createNetworkService($session); // Get all networks that you have access to with the current // authentication credentials. $networks = $networkService->getAllNetworks(); if (empty($networks)) { printf('No accessible networks found.' . PHP_EOL); return; } // Print out some information for each network. foreach ($networks as $i => $network) { printf( "%d) Network with code %d and display name '%s' was found.%s", $i, $network->getNetworkCode(), $network->getDisplayName(), PHP_EOL ); } printf("Number of results found: %d%s", count($networks), PHP_EOL); }
[ "public", "static", "function", "runExample", "(", "ServiceFactory", "$", "serviceFactory", ",", "AdManagerSession", "$", "session", ")", "{", "$", "networkService", "=", "$", "serviceFactory", "->", "createNetworkService", "(", "$", "session", ")", ";", "// Get all networks that you have access to with the current", "// authentication credentials.", "$", "networks", "=", "$", "networkService", "->", "getAllNetworks", "(", ")", ";", "if", "(", "empty", "(", "$", "networks", ")", ")", "{", "printf", "(", "'No accessible networks found.'", ".", "PHP_EOL", ")", ";", "return", ";", "}", "// Print out some information for each network.", "foreach", "(", "$", "networks", "as", "$", "i", "=>", "$", "network", ")", "{", "printf", "(", "\"%d) Network with code %d and display name '%s' was found.%s\"", ",", "$", "i", ",", "$", "network", "->", "getNetworkCode", "(", ")", ",", "$", "network", "->", "getDisplayName", "(", ")", ",", "PHP_EOL", ")", ";", "}", "printf", "(", "\"Number of results found: %d%s\"", ",", "count", "(", "$", "networks", ")", ",", "PHP_EOL", ")", ";", "}" ]
Gets all networks. @param ServiceFactory $serviceFactory the factory class for creating a network service client @param AdManagerSession $session the session containing configurations for creating a network service client @throws ApiException if the request for getting all networks fails
[ "Gets", "all", "networks", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdManager/v201811/NetworkService/GetAllNetworks.php#L47-L74
train
googleads/googleads-php-lib
src/Google/AdsApi/Common/Util/EnvironmentalVariables.php
EnvironmentalVariables.getHome
public function getHome() { $home = null; if (!empty(getenv('HOME'))) { // Try the environmental variables. $home = getenv('HOME'); } elseif (!empty($_SERVER['HOME'])) { // If not in the environment variables, check the superglobal $_SERVER as // a last resort. $home = $_SERVER['HOME']; } elseif (!empty(getenv('HOMEDRIVE')) && !empty(getenv('HOMEPATH'))) { // If the 'HOME' environmental variable wasn't found, we may be on // Windows. $home = getenv('HOMEDRIVE') . getenv('HOMEPATH'); } elseif (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) { $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH']; } if ($home === null) { throw new UnexpectedValueException('Could not locate home directory.'); } return rtrim($home, '\\/'); }
php
public function getHome() { $home = null; if (!empty(getenv('HOME'))) { // Try the environmental variables. $home = getenv('HOME'); } elseif (!empty($_SERVER['HOME'])) { // If not in the environment variables, check the superglobal $_SERVER as // a last resort. $home = $_SERVER['HOME']; } elseif (!empty(getenv('HOMEDRIVE')) && !empty(getenv('HOMEPATH'))) { // If the 'HOME' environmental variable wasn't found, we may be on // Windows. $home = getenv('HOMEDRIVE') . getenv('HOMEPATH'); } elseif (!empty($_SERVER['HOMEDRIVE']) && !empty($_SERVER['HOMEPATH'])) { $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH']; } if ($home === null) { throw new UnexpectedValueException('Could not locate home directory.'); } return rtrim($home, '\\/'); }
[ "public", "function", "getHome", "(", ")", "{", "$", "home", "=", "null", ";", "if", "(", "!", "empty", "(", "getenv", "(", "'HOME'", ")", ")", ")", "{", "// Try the environmental variables.", "$", "home", "=", "getenv", "(", "'HOME'", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "_SERVER", "[", "'HOME'", "]", ")", ")", "{", "// If not in the environment variables, check the superglobal $_SERVER as", "// a last resort.", "$", "home", "=", "$", "_SERVER", "[", "'HOME'", "]", ";", "}", "elseif", "(", "!", "empty", "(", "getenv", "(", "'HOMEDRIVE'", ")", ")", "&&", "!", "empty", "(", "getenv", "(", "'HOMEPATH'", ")", ")", ")", "{", "// If the 'HOME' environmental variable wasn't found, we may be on", "// Windows.", "$", "home", "=", "getenv", "(", "'HOMEDRIVE'", ")", ".", "getenv", "(", "'HOMEPATH'", ")", ";", "}", "elseif", "(", "!", "empty", "(", "$", "_SERVER", "[", "'HOMEDRIVE'", "]", ")", "&&", "!", "empty", "(", "$", "_SERVER", "[", "'HOMEPATH'", "]", ")", ")", "{", "$", "home", "=", "$", "_SERVER", "[", "'HOMEDRIVE'", "]", ".", "$", "_SERVER", "[", "'HOMEPATH'", "]", ";", "}", "if", "(", "$", "home", "===", "null", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Could not locate home directory.'", ")", ";", "}", "return", "rtrim", "(", "$", "home", ",", "'\\\\/'", ")", ";", "}" ]
Attempts to find the home directory of the user running the PHP script. @return string the path to the home directory with any trailing directory separators removed @throws UnexpectedValueException if a home directory could not be found
[ "Attempts", "to", "find", "the", "home", "directory", "of", "the", "user", "running", "the", "PHP", "script", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/Common/Util/EnvironmentalVariables.php#L36-L60
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/v201809/ReportQueryBuilderDelegate.php
ReportQueryBuilderDelegate.copyFrom
public static function copyFrom( ReportQueryBuilderDelegate $otherInstance, ReportQueryBuilder $queryBuilder ) { $copyingInstance = new self(); // In PHP, array assignment always performs value copying. $copyingInstance->selectFields = $otherInstance->selectFields; $copyingInstance->fromReportType = $otherInstance->fromReportType; $copyingInstance->duringDateRangeType = $otherInstance->duringDateRangeType; $copyingInstance->duringStartDate = $otherInstance->duringStartDate; $copyingInstance->duringEndDate = $otherInstance->duringEndDate; if (isset($otherInstance->whereBuilders)) { $copyingInstance->whereBuilders = []; foreach ($otherInstance->whereBuilders as $whereBuilder) { $copyingInstance->whereBuilders[] = ReportQueryWhereBuilder::copyFrom( $whereBuilder, $queryBuilder ); } } return $copyingInstance; }
php
public static function copyFrom( ReportQueryBuilderDelegate $otherInstance, ReportQueryBuilder $queryBuilder ) { $copyingInstance = new self(); // In PHP, array assignment always performs value copying. $copyingInstance->selectFields = $otherInstance->selectFields; $copyingInstance->fromReportType = $otherInstance->fromReportType; $copyingInstance->duringDateRangeType = $otherInstance->duringDateRangeType; $copyingInstance->duringStartDate = $otherInstance->duringStartDate; $copyingInstance->duringEndDate = $otherInstance->duringEndDate; if (isset($otherInstance->whereBuilders)) { $copyingInstance->whereBuilders = []; foreach ($otherInstance->whereBuilders as $whereBuilder) { $copyingInstance->whereBuilders[] = ReportQueryWhereBuilder::copyFrom( $whereBuilder, $queryBuilder ); } } return $copyingInstance; }
[ "public", "static", "function", "copyFrom", "(", "ReportQueryBuilderDelegate", "$", "otherInstance", ",", "ReportQueryBuilder", "$", "queryBuilder", ")", "{", "$", "copyingInstance", "=", "new", "self", "(", ")", ";", "// In PHP, array assignment always performs value copying.", "$", "copyingInstance", "->", "selectFields", "=", "$", "otherInstance", "->", "selectFields", ";", "$", "copyingInstance", "->", "fromReportType", "=", "$", "otherInstance", "->", "fromReportType", ";", "$", "copyingInstance", "->", "duringDateRangeType", "=", "$", "otherInstance", "->", "duringDateRangeType", ";", "$", "copyingInstance", "->", "duringStartDate", "=", "$", "otherInstance", "->", "duringStartDate", ";", "$", "copyingInstance", "->", "duringEndDate", "=", "$", "otherInstance", "->", "duringEndDate", ";", "if", "(", "isset", "(", "$", "otherInstance", "->", "whereBuilders", ")", ")", "{", "$", "copyingInstance", "->", "whereBuilders", "=", "[", "]", ";", "foreach", "(", "$", "otherInstance", "->", "whereBuilders", "as", "$", "whereBuilder", ")", "{", "$", "copyingInstance", "->", "whereBuilders", "[", "]", "=", "ReportQueryWhereBuilder", "::", "copyFrom", "(", "$", "whereBuilder", ",", "$", "queryBuilder", ")", ";", "}", "}", "return", "$", "copyingInstance", ";", "}" ]
Creates a new query builder delegate object by copying field names, WHERE, FROM and DURING clauses from another query builder delegate object. @param ReportQueryBuilderDelegate $otherInstance the other query builder delegate object for copying field names, FROM and DURING clauses @param ReportQueryBuilder $queryBuilder the query builder object for continuation of building a complete AWQL string @return ReportQueryBuilderDelegate a new query builder delegate object that copies from the input one
[ "Creates", "a", "new", "query", "builder", "delegate", "object", "by", "copying", "field", "names", "WHERE", "FROM", "and", "DURING", "clauses", "from", "another", "query", "builder", "delegate", "object", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/v201809/ReportQueryBuilderDelegate.php#L58-L84
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/v201809/ReportQueryBuilderDelegate.php
ReportQueryBuilderDelegate.during
public function during($startDate, $endDate) { $validationResult = QueryValidator::validateCustomDateRange( $startDate, $endDate ); if ($validationResult->isFailed()) { throw new InvalidArgumentException('The start or end date is' . ' invalid. Validation fail reasons: ' . $validationResult->getFailReason()); } $this->duringStartDate = $startDate; $this->duringEndDate = $endDate; }
php
public function during($startDate, $endDate) { $validationResult = QueryValidator::validateCustomDateRange( $startDate, $endDate ); if ($validationResult->isFailed()) { throw new InvalidArgumentException('The start or end date is' . ' invalid. Validation fail reasons: ' . $validationResult->getFailReason()); } $this->duringStartDate = $startDate; $this->duringEndDate = $endDate; }
[ "public", "function", "during", "(", "$", "startDate", ",", "$", "endDate", ")", "{", "$", "validationResult", "=", "QueryValidator", "::", "validateCustomDateRange", "(", "$", "startDate", ",", "$", "endDate", ")", ";", "if", "(", "$", "validationResult", "->", "isFailed", "(", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The start or end date is'", ".", "' invalid. Validation fail reasons: '", ".", "$", "validationResult", "->", "getFailReason", "(", ")", ")", ";", "}", "$", "this", "->", "duringStartDate", "=", "$", "startDate", ";", "$", "this", "->", "duringEndDate", "=", "$", "endDate", ";", "}" ]
Sets a custom date range by specifying the start and end dates. @param string $startDate the start date for the DURING clause of an AWQL string @param string $endDate the end date for the DURING clause of an AWQL string
[ "Sets", "a", "custom", "date", "range", "by", "specifying", "the", "start", "and", "end", "dates", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/v201809/ReportQueryBuilderDelegate.php#L179-L193
train
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/AdManagerDateTimes.php
AdManagerDateTimes.fromDateTime
public static function fromDateTime(DateTime $dateTime) { $date = new Date(); $date->setYear(intval($dateTime->format('Y'))); $date->setMonth(intval($dateTime->format('m'))); $date->setDay(intval($dateTime->format('d'))); $result = new AdManagerDateTime(); $result->setDate($date); $result->setHour(intval($dateTime->format('H'))); $result->setMinute(intval($dateTime->format('i'))); $result->setSecond(intval($dateTime->format('s'))); $result->setTimeZoneID($dateTime->format('e')); return $result; }
php
public static function fromDateTime(DateTime $dateTime) { $date = new Date(); $date->setYear(intval($dateTime->format('Y'))); $date->setMonth(intval($dateTime->format('m'))); $date->setDay(intval($dateTime->format('d'))); $result = new AdManagerDateTime(); $result->setDate($date); $result->setHour(intval($dateTime->format('H'))); $result->setMinute(intval($dateTime->format('i'))); $result->setSecond(intval($dateTime->format('s'))); $result->setTimeZoneID($dateTime->format('e')); return $result; }
[ "public", "static", "function", "fromDateTime", "(", "DateTime", "$", "dateTime", ")", "{", "$", "date", "=", "new", "Date", "(", ")", ";", "$", "date", "->", "setYear", "(", "intval", "(", "$", "dateTime", "->", "format", "(", "'Y'", ")", ")", ")", ";", "$", "date", "->", "setMonth", "(", "intval", "(", "$", "dateTime", "->", "format", "(", "'m'", ")", ")", ")", ";", "$", "date", "->", "setDay", "(", "intval", "(", "$", "dateTime", "->", "format", "(", "'d'", ")", ")", ")", ";", "$", "result", "=", "new", "AdManagerDateTime", "(", ")", ";", "$", "result", "->", "setDate", "(", "$", "date", ")", ";", "$", "result", "->", "setHour", "(", "intval", "(", "$", "dateTime", "->", "format", "(", "'H'", ")", ")", ")", ";", "$", "result", "->", "setMinute", "(", "intval", "(", "$", "dateTime", "->", "format", "(", "'i'", ")", ")", ")", ";", "$", "result", "->", "setSecond", "(", "intval", "(", "$", "dateTime", "->", "format", "(", "'s'", ")", ")", ")", ";", "$", "result", "->", "setTimeZoneID", "(", "$", "dateTime", "->", "format", "(", "'e'", ")", ")", ";", "return", "$", "result", ";", "}" ]
Creates a Ad Manager date time from a PHP date time. @param DateTime $dateTime @return AdManagerDateTime
[ "Creates", "a", "Ad", "Manager", "date", "time", "from", "a", "PHP", "date", "time", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/AdManagerDateTimes.php#L41-L56
train
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/AdManagerDateTimes.php
AdManagerDateTimes.toDateTime
public static function toDateTime(AdManagerDateTime $adManagerDateTime) { $dateTimeString = sprintf( '%sT%02d:%02d:%02d', AdManagerDates::toDateString($adManagerDateTime->getDate()), $adManagerDateTime->getHour(), $adManagerDateTime->getMinute(), $adManagerDateTime->getSecond() ); return new DateTime( $dateTimeString, new DateTimeZone($adManagerDateTime->getTimeZoneID()) ); }
php
public static function toDateTime(AdManagerDateTime $adManagerDateTime) { $dateTimeString = sprintf( '%sT%02d:%02d:%02d', AdManagerDates::toDateString($adManagerDateTime->getDate()), $adManagerDateTime->getHour(), $adManagerDateTime->getMinute(), $adManagerDateTime->getSecond() ); return new DateTime( $dateTimeString, new DateTimeZone($adManagerDateTime->getTimeZoneID()) ); }
[ "public", "static", "function", "toDateTime", "(", "AdManagerDateTime", "$", "adManagerDateTime", ")", "{", "$", "dateTimeString", "=", "sprintf", "(", "'%sT%02d:%02d:%02d'", ",", "AdManagerDates", "::", "toDateString", "(", "$", "adManagerDateTime", "->", "getDate", "(", ")", ")", ",", "$", "adManagerDateTime", "->", "getHour", "(", ")", ",", "$", "adManagerDateTime", "->", "getMinute", "(", ")", ",", "$", "adManagerDateTime", "->", "getSecond", "(", ")", ")", ";", "return", "new", "DateTime", "(", "$", "dateTimeString", ",", "new", "DateTimeZone", "(", "$", "adManagerDateTime", "->", "getTimeZoneID", "(", ")", ")", ")", ";", "}" ]
Converts a Ad Manager date time to a PHP date time. @param AdManagerDateTime $adManagerDateTime @return DateTime
[ "Converts", "a", "Ad", "Manager", "date", "time", "to", "a", "PHP", "date", "time", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/AdManagerDateTimes.php#L78-L92
train
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/AdManagerDateTimes.php
AdManagerDateTimes.toDateTimeString
public static function toDateTimeString( AdManagerDateTime $adManagerDateTime, $timeZoneId = null ) { $dateTime = self::toDateTime($adManagerDateTime); if ($timeZoneId !== null) { $dateTime->setTimezone(new DateTimeZone($timeZoneId)); } return $dateTime->format(DateTime::ATOM); }
php
public static function toDateTimeString( AdManagerDateTime $adManagerDateTime, $timeZoneId = null ) { $dateTime = self::toDateTime($adManagerDateTime); if ($timeZoneId !== null) { $dateTime->setTimezone(new DateTimeZone($timeZoneId)); } return $dateTime->format(DateTime::ATOM); }
[ "public", "static", "function", "toDateTimeString", "(", "AdManagerDateTime", "$", "adManagerDateTime", ",", "$", "timeZoneId", "=", "null", ")", "{", "$", "dateTime", "=", "self", "::", "toDateTime", "(", "$", "adManagerDateTime", ")", ";", "if", "(", "$", "timeZoneId", "!==", "null", ")", "{", "$", "dateTime", "->", "setTimezone", "(", "new", "DateTimeZone", "(", "$", "timeZoneId", ")", ")", ";", "}", "return", "$", "dateTime", "->", "format", "(", "DateTime", "::", "ATOM", ")", ";", "}" ]
Returns an ISO 8601 string representation of the specified Ad Manager date time. Optionally, you may specify the timezone you want to view the date time in. By default the time zone from the Ad Manager date time is used. For example, if the Ad Manager date time holds `11/29/2016 21:05:30 in GMT`, the result from this method with Europe/Paris as the new time zone, would be `11/29/2016 22:05:30 in CET`. This is useful for displaying Ad Manager date times in your network's time zone. For example: ``` $timeZoneId = $networkService->getCurrentNetwork()->getTimeZone(); $dateTimeString = AdManagerDateTimes::toDateTimeString( $adManagerDateTime, $timeZoneId ); ``` @param AdManagerDateTime $adManagerDateTime @param null|string $timeZoneId optional @return string
[ "Returns", "an", "ISO", "8601", "string", "representation", "of", "the", "specified", "Ad", "Manager", "date", "time", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/AdManagerDateTimes.php#L118-L128
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/QueryValidator.php
QueryValidator.validateFieldName
public static function validateFieldName($fieldName) { if (!is_string($fieldName)) { return ValidationResult::fail('The field name must be a' . ' string.'); } if (empty(trim($fieldName))) { return ValidationResult::fail('The field name must not be' . ' null, empty, white spaces or zero.'); } return ValidationResult::pass(); }
php
public static function validateFieldName($fieldName) { if (!is_string($fieldName)) { return ValidationResult::fail('The field name must be a' . ' string.'); } if (empty(trim($fieldName))) { return ValidationResult::fail('The field name must not be' . ' null, empty, white spaces or zero.'); } return ValidationResult::pass(); }
[ "public", "static", "function", "validateFieldName", "(", "$", "fieldName", ")", "{", "if", "(", "!", "is_string", "(", "$", "fieldName", ")", ")", "{", "return", "ValidationResult", "::", "fail", "(", "'The field name must be a'", ".", "' string.'", ")", ";", "}", "if", "(", "empty", "(", "trim", "(", "$", "fieldName", ")", ")", ")", "{", "return", "ValidationResult", "::", "fail", "(", "'The field name must not be'", ".", "' null, empty, white spaces or zero.'", ")", ";", "}", "return", "ValidationResult", "::", "pass", "(", ")", ";", "}" ]
Validates a field name for using in the SELECT, WHERE or ORDER BY clauses of an AWQL string. @param string $fieldName the field name to be validated @return ValidationResult the object containing whether the validation is passed or failed with detail explanation
[ "Validates", "a", "field", "name", "for", "using", "in", "the", "SELECT", "WHERE", "or", "ORDER", "BY", "clauses", "of", "an", "AWQL", "string", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/QueryValidator.php#L50-L63
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/QueryValidator.php
QueryValidator.validateCustomDateRange
public static function validateCustomDateRange( $startDateString, $endDateString ) { $startDate = DateTime::createFromFormat('Ymd', $startDateString); $warningsFound = !empty(DateTime::getLastErrors()['warnings']); // If parsing fails with errors, the `$startDate` will be `false`. // If parsing succeeds, there could still be warnings indicating that // the parsed result might not be what the original string represents. // // For example: the string '20180231' will be parsed as March 3rd // 2018 with a warning of 'The parsed date is invalid'. if (false === $startDate || $warningsFound) { return ValidationResult::fail('The start date must be a valid' . ' date and follow YYYYMMDD format.'); } $endDate = DateTime::createFromFormat('Ymd', $endDateString); $warningsFound = !empty(DateTime::getLastErrors()['warnings']); if (false === $endDate || $warningsFound) { return ValidationResult::fail('The end date must be a valid date' . ' and follow YYYYMMDD format.'); } if ($endDate < $startDate) { return ValidationResult::fail('The end date must not be prior to' . ' the start date.'); } return ValidationResult::pass(); }
php
public static function validateCustomDateRange( $startDateString, $endDateString ) { $startDate = DateTime::createFromFormat('Ymd', $startDateString); $warningsFound = !empty(DateTime::getLastErrors()['warnings']); // If parsing fails with errors, the `$startDate` will be `false`. // If parsing succeeds, there could still be warnings indicating that // the parsed result might not be what the original string represents. // // For example: the string '20180231' will be parsed as March 3rd // 2018 with a warning of 'The parsed date is invalid'. if (false === $startDate || $warningsFound) { return ValidationResult::fail('The start date must be a valid' . ' date and follow YYYYMMDD format.'); } $endDate = DateTime::createFromFormat('Ymd', $endDateString); $warningsFound = !empty(DateTime::getLastErrors()['warnings']); if (false === $endDate || $warningsFound) { return ValidationResult::fail('The end date must be a valid date' . ' and follow YYYYMMDD format.'); } if ($endDate < $startDate) { return ValidationResult::fail('The end date must not be prior to' . ' the start date.'); } return ValidationResult::pass(); }
[ "public", "static", "function", "validateCustomDateRange", "(", "$", "startDateString", ",", "$", "endDateString", ")", "{", "$", "startDate", "=", "DateTime", "::", "createFromFormat", "(", "'Ymd'", ",", "$", "startDateString", ")", ";", "$", "warningsFound", "=", "!", "empty", "(", "DateTime", "::", "getLastErrors", "(", ")", "[", "'warnings'", "]", ")", ";", "// If parsing fails with errors, the `$startDate` will be `false`.", "// If parsing succeeds, there could still be warnings indicating that", "// the parsed result might not be what the original string represents.", "//", "// For example: the string '20180231' will be parsed as March 3rd", "// 2018 with a warning of 'The parsed date is invalid'.", "if", "(", "false", "===", "$", "startDate", "||", "$", "warningsFound", ")", "{", "return", "ValidationResult", "::", "fail", "(", "'The start date must be a valid'", ".", "' date and follow YYYYMMDD format.'", ")", ";", "}", "$", "endDate", "=", "DateTime", "::", "createFromFormat", "(", "'Ymd'", ",", "$", "endDateString", ")", ";", "$", "warningsFound", "=", "!", "empty", "(", "DateTime", "::", "getLastErrors", "(", ")", "[", "'warnings'", "]", ")", ";", "if", "(", "false", "===", "$", "endDate", "||", "$", "warningsFound", ")", "{", "return", "ValidationResult", "::", "fail", "(", "'The end date must be a valid date'", ".", "' and follow YYYYMMDD format.'", ")", ";", "}", "if", "(", "$", "endDate", "<", "$", "startDate", ")", "{", "return", "ValidationResult", "::", "fail", "(", "'The end date must not be prior to'", ".", "' the start date.'", ")", ";", "}", "return", "ValidationResult", "::", "pass", "(", ")", ";", "}" ]
Validates the start and end dates of a custom date range in the DURING clause of an AWQL string. @param string $startDateString the start date string @param string $endDateString the end date string @return ValidationResult the object containing whether the validation is passed or failed with detail explanation
[ "Validates", "the", "start", "and", "end", "dates", "of", "a", "custom", "date", "range", "in", "the", "DURING", "clause", "of", "an", "AWQL", "string", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/QueryValidator.php#L74-L105
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/QueryValidator.php
QueryValidator.containKeywords
private static function containKeywords( $awqlString, $clauseKeywords, $containAll ) { // The AWQL string may contain the clause opening keywords in the // selectable field names. // // For example: // SELECT ConversionTracker.excludeFromBidding // // Redacting all keywords embedded in words before scanning for the // keywords will avoid false positive results. // Redacted example: // SELECT ConversionTracker.redacted_literal_string // Adding each clause opening keywords to the list of patterns for // redacting. $patterns = array_map(function ($keyword) { return "/\w+$keyword\w+/i"; }, $clauseKeywords); // The AWQL string may also contain the clause opening keywords in // literal strings. // // For example: // SELECT Id // WHERE Name = 'THE LIMIT INC' // // This function concerns about the LIMIT keyword outside of all // literal strings. Redacting all literal strings before scanning // for the keywords will avoid false positive results. // // Redacted example: // SELECT Id // WHERE Name = redacted_literal_string // Prepending the literal string to the list of patterns for // prioritizing this operation over other patterns. array_unshift($patterns, self::PATTERN_LITERAL_STRING); $awqlStringWithoutLiteralStrings = preg_replace( $patterns, self::REDACTED_LITERAL_STRING, $awqlString ); $count = 0; foreach ($clauseKeywords as $clause) { if (false !== stripos($awqlStringWithoutLiteralStrings, $clause)) { if (!$containAll) { return true; } $count++; } } return $count === count($clauseKeywords); }
php
private static function containKeywords( $awqlString, $clauseKeywords, $containAll ) { // The AWQL string may contain the clause opening keywords in the // selectable field names. // // For example: // SELECT ConversionTracker.excludeFromBidding // // Redacting all keywords embedded in words before scanning for the // keywords will avoid false positive results. // Redacted example: // SELECT ConversionTracker.redacted_literal_string // Adding each clause opening keywords to the list of patterns for // redacting. $patterns = array_map(function ($keyword) { return "/\w+$keyword\w+/i"; }, $clauseKeywords); // The AWQL string may also contain the clause opening keywords in // literal strings. // // For example: // SELECT Id // WHERE Name = 'THE LIMIT INC' // // This function concerns about the LIMIT keyword outside of all // literal strings. Redacting all literal strings before scanning // for the keywords will avoid false positive results. // // Redacted example: // SELECT Id // WHERE Name = redacted_literal_string // Prepending the literal string to the list of patterns for // prioritizing this operation over other patterns. array_unshift($patterns, self::PATTERN_LITERAL_STRING); $awqlStringWithoutLiteralStrings = preg_replace( $patterns, self::REDACTED_LITERAL_STRING, $awqlString ); $count = 0; foreach ($clauseKeywords as $clause) { if (false !== stripos($awqlStringWithoutLiteralStrings, $clause)) { if (!$containAll) { return true; } $count++; } } return $count === count($clauseKeywords); }
[ "private", "static", "function", "containKeywords", "(", "$", "awqlString", ",", "$", "clauseKeywords", ",", "$", "containAll", ")", "{", "// The AWQL string may contain the clause opening keywords in the", "// selectable field names.", "//", "// For example:", "// SELECT ConversionTracker.excludeFromBidding", "//", "// Redacting all keywords embedded in words before scanning for the", "// keywords will avoid false positive results.", "// Redacted example:", "// SELECT ConversionTracker.redacted_literal_string", "// Adding each clause opening keywords to the list of patterns for", "// redacting.", "$", "patterns", "=", "array_map", "(", "function", "(", "$", "keyword", ")", "{", "return", "\"/\\w+$keyword\\w+/i\"", ";", "}", ",", "$", "clauseKeywords", ")", ";", "// The AWQL string may also contain the clause opening keywords in", "// literal strings.", "//", "// For example:", "// SELECT Id", "// WHERE Name = 'THE LIMIT INC'", "//", "// This function concerns about the LIMIT keyword outside of all", "// literal strings. Redacting all literal strings before scanning", "// for the keywords will avoid false positive results.", "//", "// Redacted example:", "// SELECT Id", "// WHERE Name = redacted_literal_string", "// Prepending the literal string to the list of patterns for", "// prioritizing this operation over other patterns.", "array_unshift", "(", "$", "patterns", ",", "self", "::", "PATTERN_LITERAL_STRING", ")", ";", "$", "awqlStringWithoutLiteralStrings", "=", "preg_replace", "(", "$", "patterns", ",", "self", "::", "REDACTED_LITERAL_STRING", ",", "$", "awqlString", ")", ";", "$", "count", "=", "0", ";", "foreach", "(", "$", "clauseKeywords", "as", "$", "clause", ")", "{", "if", "(", "false", "!==", "stripos", "(", "$", "awqlStringWithoutLiteralStrings", ",", "$", "clause", ")", ")", "{", "if", "(", "!", "$", "containAll", ")", "{", "return", "true", ";", "}", "$", "count", "++", ";", "}", "}", "return", "$", "count", "===", "count", "(", "$", "clauseKeywords", ")", ";", "}" ]
Checks if an AWQL string contains certain clauses by searching for the clause opening keywords. @param string $awqlString the AWQL string to check @param string[] $clauseKeywords the clause opening keywords (e.g. SELECT, FROM, WHERE, ORDER BY) to search @param bool $containAll whether the AWQL string should contain all of the given keywords. Set to false for checking whether the AWQL string should contain any of the given keywords @return bool true if the AWQL string contains all or any the clause keywords accordingly to the `$containAll` parameter; Otherwise, returns false
[ "Checks", "if", "an", "AWQL", "string", "contains", "certain", "clauses", "by", "searching", "for", "the", "clause", "opening", "keywords", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/QueryValidator.php#L121-L178
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/QueryValidator.php
QueryValidator.validateQuery
private static function validateQuery( $awqlString, $requiredKeywords, $forbiddenKeywords ) { if (empty($awqlString)) { return ValidationResult::fail('The AWQL string must not be' . ' null or empty'); } if (!self::containAllKeywords($awqlString, $requiredKeywords)) { return ValidationResult::fail( sprintf( 'The AWQL string must contain %s clause(s).', implode(', ', $requiredKeywords) ) ); } if (self::containAnyKeywords($awqlString, $forbiddenKeywords)) { return ValidationResult::fail( sprintf( 'The AWQL string must not contain %s clauses.', implode(', ', $forbiddenKeywords) ) ); } return ValidationResult::pass(); }
php
private static function validateQuery( $awqlString, $requiredKeywords, $forbiddenKeywords ) { if (empty($awqlString)) { return ValidationResult::fail('The AWQL string must not be' . ' null or empty'); } if (!self::containAllKeywords($awqlString, $requiredKeywords)) { return ValidationResult::fail( sprintf( 'The AWQL string must contain %s clause(s).', implode(', ', $requiredKeywords) ) ); } if (self::containAnyKeywords($awqlString, $forbiddenKeywords)) { return ValidationResult::fail( sprintf( 'The AWQL string must not contain %s clauses.', implode(', ', $forbiddenKeywords) ) ); } return ValidationResult::pass(); }
[ "private", "static", "function", "validateQuery", "(", "$", "awqlString", ",", "$", "requiredKeywords", ",", "$", "forbiddenKeywords", ")", "{", "if", "(", "empty", "(", "$", "awqlString", ")", ")", "{", "return", "ValidationResult", "::", "fail", "(", "'The AWQL string must not be'", ".", "' null or empty'", ")", ";", "}", "if", "(", "!", "self", "::", "containAllKeywords", "(", "$", "awqlString", ",", "$", "requiredKeywords", ")", ")", "{", "return", "ValidationResult", "::", "fail", "(", "sprintf", "(", "'The AWQL string must contain %s clause(s).'", ",", "implode", "(", "', '", ",", "$", "requiredKeywords", ")", ")", ")", ";", "}", "if", "(", "self", "::", "containAnyKeywords", "(", "$", "awqlString", ",", "$", "forbiddenKeywords", ")", ")", "{", "return", "ValidationResult", "::", "fail", "(", "sprintf", "(", "'The AWQL string must not contain %s clauses.'", ",", "implode", "(", "', '", ",", "$", "forbiddenKeywords", ")", ")", ")", ";", "}", "return", "ValidationResult", "::", "pass", "(", ")", ";", "}" ]
Checks if the AWQL string contains the required clause opening keywords, but not the forbidden ones. @param string $awqlString the AWQL string to check @param string[] $requiredKeywords the opening keywords (e.g. SELECT, FROM, WHERE, ORDER BY) for the required clauses @param string[] $forbiddenKeywords the opening keywords (e.g. SELECT, FROM, WHERE, ORDER BY) for the forbidden clauses @return ValidationResult the object containing whether the validation is passed or failed with detail explanation
[ "Checks", "if", "the", "AWQL", "string", "contains", "the", "required", "clause", "opening", "keywords", "but", "not", "the", "forbidden", "ones", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/QueryValidator.php#L229-L258
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/QueryValidator.php
QueryValidator.validateServiceQuery
public static function validateServiceQuery( $awqlString, $allowPagination = true ) { $forbiddenKeywords = ['FROM', 'DURING']; if (!$allowPagination) { $forbiddenKeywords []= 'LIMIT'; } return self::validateQuery( $awqlString, ['SELECT'], $forbiddenKeywords ); }
php
public static function validateServiceQuery( $awqlString, $allowPagination = true ) { $forbiddenKeywords = ['FROM', 'DURING']; if (!$allowPagination) { $forbiddenKeywords []= 'LIMIT'; } return self::validateQuery( $awqlString, ['SELECT'], $forbiddenKeywords ); }
[ "public", "static", "function", "validateServiceQuery", "(", "$", "awqlString", ",", "$", "allowPagination", "=", "true", ")", "{", "$", "forbiddenKeywords", "=", "[", "'FROM'", ",", "'DURING'", "]", ";", "if", "(", "!", "$", "allowPagination", ")", "{", "$", "forbiddenKeywords", "[", "]", "=", "'LIMIT'", ";", "}", "return", "self", "::", "validateQuery", "(", "$", "awqlString", ",", "[", "'SELECT'", "]", ",", "$", "forbiddenKeywords", ")", ";", "}" ]
Validates a service query AWQL string. @param string $awqlString the AWQL string to be validated @param bool|null $allowPagination optional, indicates whether the AWQL is allowed to have the pagination (LIMIT) clause @return ValidationResult the object containing whether the validation is passed or failed with detail explanation
[ "Validates", "a", "service", "query", "AWQL", "string", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/QueryValidator.php#L269-L282
train
googleads/googleads-php-lib
examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php
AddSitelinksUsingFeeds.createSitelinksFeed
private static function createSitelinksFeed( AdWordsServices $adWordsServices, AdWordsSession $session ) { $feedService = $adWordsServices->get($session, FeedService::class); // Holds the IDs associated to the feeds metadata. $sitelinksData = []; // Create feed attributes. $textAttribute = new FeedAttribute(); $textAttribute->setType(FeedAttributeType::STRING); $textAttribute->setName('Link Text'); $finalUrlAttribute = new FeedAttribute(); $finalUrlAttribute->setType(FeedAttributeType::URL_LIST); $finalUrlAttribute->setName('Link URL'); $line2Attribute = new FeedAttribute(); $line2Attribute->setType(FeedAttributeType::STRING); $line2Attribute->setName('Line 2'); $line3Attribute = new FeedAttribute(); $line3Attribute->setType(FeedAttributeType::STRING); $line3Attribute->setName('Line 3'); // Create the feed. $sitelinksFeed = new Feed(); $sitelinksFeed->setName('Feed For Sitelinks #' . uniqid()); $sitelinksFeed->setAttributes([ $textAttribute, $finalUrlAttribute, $line2Attribute, $line3Attribute ]); $sitelinksFeed->setOrigin(FeedOrigin::USER); // Create the feed operation and add it on the server. $operation = new FeedOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($sitelinksFeed); $result = $feedService->mutate([$operation]); // Print out some information about the created feed. $savedFeed = $result->getValue()[0]; $sitelinksData['sitelinksFeedId'] = $savedFeed->getId(); $savedAttributes = $savedFeed->getAttributes(); $sitelinksData['linkTextFeedAttributeId'] = $savedAttributes[0]->getId(); $sitelinksData['linkFinalUrlFeedAttributeId'] = $savedAttributes[1]->getId(); $sitelinksData['line2FeedAttribute'] = $savedAttributes[2]->getId(); $sitelinksData['line3FeedAttribute'] = $savedAttributes[3]->getId(); printf( "Feed with name '%s', ID %d with linkTextAttributeId %d, " . "linkFinalUrlAttributeId %d, line2AttributeId %d and " . "line3AttributeId %d was created.%s", $savedFeed->getName(), $savedFeed->getId(), $savedAttributes[0]->getId(), $savedAttributes[1]->getId(), $savedAttributes[2]->getId(), $savedAttributes[3]->getId(), PHP_EOL ); return $sitelinksData; }
php
private static function createSitelinksFeed( AdWordsServices $adWordsServices, AdWordsSession $session ) { $feedService = $adWordsServices->get($session, FeedService::class); // Holds the IDs associated to the feeds metadata. $sitelinksData = []; // Create feed attributes. $textAttribute = new FeedAttribute(); $textAttribute->setType(FeedAttributeType::STRING); $textAttribute->setName('Link Text'); $finalUrlAttribute = new FeedAttribute(); $finalUrlAttribute->setType(FeedAttributeType::URL_LIST); $finalUrlAttribute->setName('Link URL'); $line2Attribute = new FeedAttribute(); $line2Attribute->setType(FeedAttributeType::STRING); $line2Attribute->setName('Line 2'); $line3Attribute = new FeedAttribute(); $line3Attribute->setType(FeedAttributeType::STRING); $line3Attribute->setName('Line 3'); // Create the feed. $sitelinksFeed = new Feed(); $sitelinksFeed->setName('Feed For Sitelinks #' . uniqid()); $sitelinksFeed->setAttributes([ $textAttribute, $finalUrlAttribute, $line2Attribute, $line3Attribute ]); $sitelinksFeed->setOrigin(FeedOrigin::USER); // Create the feed operation and add it on the server. $operation = new FeedOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($sitelinksFeed); $result = $feedService->mutate([$operation]); // Print out some information about the created feed. $savedFeed = $result->getValue()[0]; $sitelinksData['sitelinksFeedId'] = $savedFeed->getId(); $savedAttributes = $savedFeed->getAttributes(); $sitelinksData['linkTextFeedAttributeId'] = $savedAttributes[0]->getId(); $sitelinksData['linkFinalUrlFeedAttributeId'] = $savedAttributes[1]->getId(); $sitelinksData['line2FeedAttribute'] = $savedAttributes[2]->getId(); $sitelinksData['line3FeedAttribute'] = $savedAttributes[3]->getId(); printf( "Feed with name '%s', ID %d with linkTextAttributeId %d, " . "linkFinalUrlAttributeId %d, line2AttributeId %d and " . "line3AttributeId %d was created.%s", $savedFeed->getName(), $savedFeed->getId(), $savedAttributes[0]->getId(), $savedAttributes[1]->getId(), $savedAttributes[2]->getId(), $savedAttributes[3]->getId(), PHP_EOL ); return $sitelinksData; }
[ "private", "static", "function", "createSitelinksFeed", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ")", "{", "$", "feedService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "FeedService", "::", "class", ")", ";", "// Holds the IDs associated to the feeds metadata.", "$", "sitelinksData", "=", "[", "]", ";", "// Create feed attributes.", "$", "textAttribute", "=", "new", "FeedAttribute", "(", ")", ";", "$", "textAttribute", "->", "setType", "(", "FeedAttributeType", "::", "STRING", ")", ";", "$", "textAttribute", "->", "setName", "(", "'Link Text'", ")", ";", "$", "finalUrlAttribute", "=", "new", "FeedAttribute", "(", ")", ";", "$", "finalUrlAttribute", "->", "setType", "(", "FeedAttributeType", "::", "URL_LIST", ")", ";", "$", "finalUrlAttribute", "->", "setName", "(", "'Link URL'", ")", ";", "$", "line2Attribute", "=", "new", "FeedAttribute", "(", ")", ";", "$", "line2Attribute", "->", "setType", "(", "FeedAttributeType", "::", "STRING", ")", ";", "$", "line2Attribute", "->", "setName", "(", "'Line 2'", ")", ";", "$", "line3Attribute", "=", "new", "FeedAttribute", "(", ")", ";", "$", "line3Attribute", "->", "setType", "(", "FeedAttributeType", "::", "STRING", ")", ";", "$", "line3Attribute", "->", "setName", "(", "'Line 3'", ")", ";", "// Create the feed.", "$", "sitelinksFeed", "=", "new", "Feed", "(", ")", ";", "$", "sitelinksFeed", "->", "setName", "(", "'Feed For Sitelinks #'", ".", "uniqid", "(", ")", ")", ";", "$", "sitelinksFeed", "->", "setAttributes", "(", "[", "$", "textAttribute", ",", "$", "finalUrlAttribute", ",", "$", "line2Attribute", ",", "$", "line3Attribute", "]", ")", ";", "$", "sitelinksFeed", "->", "setOrigin", "(", "FeedOrigin", "::", "USER", ")", ";", "// Create the feed operation and add it on the server.", "$", "operation", "=", "new", "FeedOperation", "(", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "sitelinksFeed", ")", ";", "$", "result", "=", "$", "feedService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "// Print out some information about the created feed.", "$", "savedFeed", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "$", "sitelinksData", "[", "'sitelinksFeedId'", "]", "=", "$", "savedFeed", "->", "getId", "(", ")", ";", "$", "savedAttributes", "=", "$", "savedFeed", "->", "getAttributes", "(", ")", ";", "$", "sitelinksData", "[", "'linkTextFeedAttributeId'", "]", "=", "$", "savedAttributes", "[", "0", "]", "->", "getId", "(", ")", ";", "$", "sitelinksData", "[", "'linkFinalUrlFeedAttributeId'", "]", "=", "$", "savedAttributes", "[", "1", "]", "->", "getId", "(", ")", ";", "$", "sitelinksData", "[", "'line2FeedAttribute'", "]", "=", "$", "savedAttributes", "[", "2", "]", "->", "getId", "(", ")", ";", "$", "sitelinksData", "[", "'line3FeedAttribute'", "]", "=", "$", "savedAttributes", "[", "3", "]", "->", "getId", "(", ")", ";", "printf", "(", "\"Feed with name '%s', ID %d with linkTextAttributeId %d, \"", ".", "\"linkFinalUrlAttributeId %d, line2AttributeId %d and \"", ".", "\"line3AttributeId %d was created.%s\"", ",", "$", "savedFeed", "->", "getName", "(", ")", ",", "$", "savedFeed", "->", "getId", "(", ")", ",", "$", "savedAttributes", "[", "0", "]", "->", "getId", "(", ")", ",", "$", "savedAttributes", "[", "1", "]", "->", "getId", "(", ")", ",", "$", "savedAttributes", "[", "2", "]", "->", "getId", "(", ")", ",", "$", "savedAttributes", "[", "3", "]", "->", "getId", "(", ")", ",", "PHP_EOL", ")", ";", "return", "$", "sitelinksData", ";", "}" ]
Creates the feed that holds the sitelinks data.
[ "Creates", "the", "feed", "that", "holds", "the", "sitelinks", "data", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php#L115-L180
train
googleads/googleads-php-lib
examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php
AddSitelinksUsingFeeds.createSitelinksFeedItems
private static function createSitelinksFeedItems( AdWordsServices $adWordsServices, AdWordsSession $session, array $sitelinksData ) { $feedItemService = $adWordsServices->get($session, FeedItemService::class); // Create operations to add feed items. $home = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Home', 'http://www.example.com', 'Home line 2', 'Home line 3' ); $stores = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Stores', 'http://www.example.com/stores', 'Stores line 2', 'Stores line 3' ); $onSale = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'On Sale', 'http://www.example.com/sale', 'On Sale line 2', 'On Sale line 3' ); $support = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Support', 'http://www.example.com/support', 'Support line 2', 'Support line 3' ); $products = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Products', 'http://www.example.com/products', 'Products line 2', 'Products line 3' ); // This site link is using geographical targeting to use // LOCATION_OF_PRESENCE. $aboutUs = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'About Us', 'http://www.example.com/about', 'About Us line 2', 'About Us line 3', true ); // Add feed item operations on the server and print out some information. $result = $feedItemService->mutate( [$home, $stores, $onSale, $support, $products, $aboutUs] ); $sitelinksData['sitelinkFeedItemIds'] = []; foreach ($result->getValue() as $feedItem) { printf( 'Feed item with feed item ID %d was added.%s', $feedItem->getFeedItemId(), PHP_EOL ); $sitelinksData['sitelinkFeedItemIds'][] = $feedItem->getFeedItemId(); } // Target the "aboutUs" sitelink to geographically target California. // See https://developers.google.com/adwords/api/docs/appendix/geotargeting // for location criteria of supported locations. self::restrictFeedItemToGeoTarget( $adWordsServices, $session, $result->getValue()[5], 21137 ); return $sitelinksData; }
php
private static function createSitelinksFeedItems( AdWordsServices $adWordsServices, AdWordsSession $session, array $sitelinksData ) { $feedItemService = $adWordsServices->get($session, FeedItemService::class); // Create operations to add feed items. $home = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Home', 'http://www.example.com', 'Home line 2', 'Home line 3' ); $stores = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Stores', 'http://www.example.com/stores', 'Stores line 2', 'Stores line 3' ); $onSale = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'On Sale', 'http://www.example.com/sale', 'On Sale line 2', 'On Sale line 3' ); $support = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Support', 'http://www.example.com/support', 'Support line 2', 'Support line 3' ); $products = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'Products', 'http://www.example.com/products', 'Products line 2', 'Products line 3' ); // This site link is using geographical targeting to use // LOCATION_OF_PRESENCE. $aboutUs = self::newSitelinkFeedItemAddOperation( $sitelinksData, 'About Us', 'http://www.example.com/about', 'About Us line 2', 'About Us line 3', true ); // Add feed item operations on the server and print out some information. $result = $feedItemService->mutate( [$home, $stores, $onSale, $support, $products, $aboutUs] ); $sitelinksData['sitelinkFeedItemIds'] = []; foreach ($result->getValue() as $feedItem) { printf( 'Feed item with feed item ID %d was added.%s', $feedItem->getFeedItemId(), PHP_EOL ); $sitelinksData['sitelinkFeedItemIds'][] = $feedItem->getFeedItemId(); } // Target the "aboutUs" sitelink to geographically target California. // See https://developers.google.com/adwords/api/docs/appendix/geotargeting // for location criteria of supported locations. self::restrictFeedItemToGeoTarget( $adWordsServices, $session, $result->getValue()[5], 21137 ); return $sitelinksData; }
[ "private", "static", "function", "createSitelinksFeedItems", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "array", "$", "sitelinksData", ")", "{", "$", "feedItemService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "FeedItemService", "::", "class", ")", ";", "// Create operations to add feed items.", "$", "home", "=", "self", "::", "newSitelinkFeedItemAddOperation", "(", "$", "sitelinksData", ",", "'Home'", ",", "'http://www.example.com'", ",", "'Home line 2'", ",", "'Home line 3'", ")", ";", "$", "stores", "=", "self", "::", "newSitelinkFeedItemAddOperation", "(", "$", "sitelinksData", ",", "'Stores'", ",", "'http://www.example.com/stores'", ",", "'Stores line 2'", ",", "'Stores line 3'", ")", ";", "$", "onSale", "=", "self", "::", "newSitelinkFeedItemAddOperation", "(", "$", "sitelinksData", ",", "'On Sale'", ",", "'http://www.example.com/sale'", ",", "'On Sale line 2'", ",", "'On Sale line 3'", ")", ";", "$", "support", "=", "self", "::", "newSitelinkFeedItemAddOperation", "(", "$", "sitelinksData", ",", "'Support'", ",", "'http://www.example.com/support'", ",", "'Support line 2'", ",", "'Support line 3'", ")", ";", "$", "products", "=", "self", "::", "newSitelinkFeedItemAddOperation", "(", "$", "sitelinksData", ",", "'Products'", ",", "'http://www.example.com/products'", ",", "'Products line 2'", ",", "'Products line 3'", ")", ";", "// This site link is using geographical targeting to use", "// LOCATION_OF_PRESENCE.", "$", "aboutUs", "=", "self", "::", "newSitelinkFeedItemAddOperation", "(", "$", "sitelinksData", ",", "'About Us'", ",", "'http://www.example.com/about'", ",", "'About Us line 2'", ",", "'About Us line 3'", ",", "true", ")", ";", "// Add feed item operations on the server and print out some information.", "$", "result", "=", "$", "feedItemService", "->", "mutate", "(", "[", "$", "home", ",", "$", "stores", ",", "$", "onSale", ",", "$", "support", ",", "$", "products", ",", "$", "aboutUs", "]", ")", ";", "$", "sitelinksData", "[", "'sitelinkFeedItemIds'", "]", "=", "[", "]", ";", "foreach", "(", "$", "result", "->", "getValue", "(", ")", "as", "$", "feedItem", ")", "{", "printf", "(", "'Feed item with feed item ID %d was added.%s'", ",", "$", "feedItem", "->", "getFeedItemId", "(", ")", ",", "PHP_EOL", ")", ";", "$", "sitelinksData", "[", "'sitelinkFeedItemIds'", "]", "[", "]", "=", "$", "feedItem", "->", "getFeedItemId", "(", ")", ";", "}", "// Target the \"aboutUs\" sitelink to geographically target California.", "// See https://developers.google.com/adwords/api/docs/appendix/geotargeting", "// for location criteria of supported locations.", "self", "::", "restrictFeedItemToGeoTarget", "(", "$", "adWordsServices", ",", "$", "session", ",", "$", "result", "->", "getValue", "(", ")", "[", "5", "]", ",", "21137", ")", ";", "return", "$", "sitelinksData", ";", "}" ]
Creates sitelinks feed items and add it to the feed.
[ "Creates", "sitelinks", "feed", "items", "and", "add", "it", "to", "the", "feed", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php#L185-L267
train
googleads/googleads-php-lib
examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php
AddSitelinksUsingFeeds.createSitelinksFeedMapping
private static function createSitelinksFeedMapping( AdWordsServices $adWordsServices, AdWordsSession $session, array $sitelinksData ) { $feedMappingService = $adWordsServices->get($session, FeedMappingService::class); // Map the feed attribute IDs to the field ID constants. $linkTextFieldMapping = new AttributeFieldMapping(); $linkTextFieldMapping->setFeedAttributeId( $sitelinksData['linkTextFeedAttributeId'] ); $linkTextFieldMapping->setFieldId( self::PLACEHOLDER_FIELD_SITELINK_LINK_TEXT ); $linkFinalUrlFieldMapping = new AttributeFieldMapping(); $linkFinalUrlFieldMapping->setFeedAttributeId( $sitelinksData['linkFinalUrlFeedAttributeId'] ); $linkFinalUrlFieldMapping->setFieldId( self::PLACEHOLDER_FIELD_SITELINK_FINAL_URL ); $line2FieldMapping = new AttributeFieldMapping(); $line2FieldMapping->setFeedAttributeId( $sitelinksData['line2FeedAttribute'] ); $line2FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_2_TEXT); $line3FieldMapping = new AttributeFieldMapping(); $line3FieldMapping->setFeedAttributeId( $sitelinksData['line3FeedAttribute'] ); $line3FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_3_TEXT); // Create the feed mapping and feed mapping operation. $feedMapping = new FeedMapping(); $feedMapping->setPlaceholderType(self::PLACEHOLDER_SITELINKS); $feedMapping->setFeedId($sitelinksData['sitelinksFeedId']); $feedMapping->setAttributeFieldMappings( [ $linkTextFieldMapping, $linkFinalUrlFieldMapping, $line2FieldMapping, $line3FieldMapping ] ); $operation = new FeedMappingOperation(); $operation->setOperand($feedMapping); $operation->setOperator(Operator::ADD); // Create the feed mapping operation on the server and print out some // information. $result = $feedMappingService->mutate([$operation]); foreach ($result->getValue() as $feedMapping) { printf( 'Feed mapping with ID %d and placeholder type %d was ' . 'saved for feed with ID %d.%s', $feedMapping->getFeedMappingId(), $feedMapping->getPlaceholderType(), $feedMapping->getFeedId(), PHP_EOL ); } }
php
private static function createSitelinksFeedMapping( AdWordsServices $adWordsServices, AdWordsSession $session, array $sitelinksData ) { $feedMappingService = $adWordsServices->get($session, FeedMappingService::class); // Map the feed attribute IDs to the field ID constants. $linkTextFieldMapping = new AttributeFieldMapping(); $linkTextFieldMapping->setFeedAttributeId( $sitelinksData['linkTextFeedAttributeId'] ); $linkTextFieldMapping->setFieldId( self::PLACEHOLDER_FIELD_SITELINK_LINK_TEXT ); $linkFinalUrlFieldMapping = new AttributeFieldMapping(); $linkFinalUrlFieldMapping->setFeedAttributeId( $sitelinksData['linkFinalUrlFeedAttributeId'] ); $linkFinalUrlFieldMapping->setFieldId( self::PLACEHOLDER_FIELD_SITELINK_FINAL_URL ); $line2FieldMapping = new AttributeFieldMapping(); $line2FieldMapping->setFeedAttributeId( $sitelinksData['line2FeedAttribute'] ); $line2FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_2_TEXT); $line3FieldMapping = new AttributeFieldMapping(); $line3FieldMapping->setFeedAttributeId( $sitelinksData['line3FeedAttribute'] ); $line3FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_3_TEXT); // Create the feed mapping and feed mapping operation. $feedMapping = new FeedMapping(); $feedMapping->setPlaceholderType(self::PLACEHOLDER_SITELINKS); $feedMapping->setFeedId($sitelinksData['sitelinksFeedId']); $feedMapping->setAttributeFieldMappings( [ $linkTextFieldMapping, $linkFinalUrlFieldMapping, $line2FieldMapping, $line3FieldMapping ] ); $operation = new FeedMappingOperation(); $operation->setOperand($feedMapping); $operation->setOperator(Operator::ADD); // Create the feed mapping operation on the server and print out some // information. $result = $feedMappingService->mutate([$operation]); foreach ($result->getValue() as $feedMapping) { printf( 'Feed mapping with ID %d and placeholder type %d was ' . 'saved for feed with ID %d.%s', $feedMapping->getFeedMappingId(), $feedMapping->getPlaceholderType(), $feedMapping->getFeedId(), PHP_EOL ); } }
[ "private", "static", "function", "createSitelinksFeedMapping", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "array", "$", "sitelinksData", ")", "{", "$", "feedMappingService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "FeedMappingService", "::", "class", ")", ";", "// Map the feed attribute IDs to the field ID constants.", "$", "linkTextFieldMapping", "=", "new", "AttributeFieldMapping", "(", ")", ";", "$", "linkTextFieldMapping", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'linkTextFeedAttributeId'", "]", ")", ";", "$", "linkTextFieldMapping", "->", "setFieldId", "(", "self", "::", "PLACEHOLDER_FIELD_SITELINK_LINK_TEXT", ")", ";", "$", "linkFinalUrlFieldMapping", "=", "new", "AttributeFieldMapping", "(", ")", ";", "$", "linkFinalUrlFieldMapping", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'linkFinalUrlFeedAttributeId'", "]", ")", ";", "$", "linkFinalUrlFieldMapping", "->", "setFieldId", "(", "self", "::", "PLACEHOLDER_FIELD_SITELINK_FINAL_URL", ")", ";", "$", "line2FieldMapping", "=", "new", "AttributeFieldMapping", "(", ")", ";", "$", "line2FieldMapping", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'line2FeedAttribute'", "]", ")", ";", "$", "line2FieldMapping", "->", "setFieldId", "(", "self", "::", "PLACEHOLDER_FIELD_LINE_2_TEXT", ")", ";", "$", "line3FieldMapping", "=", "new", "AttributeFieldMapping", "(", ")", ";", "$", "line3FieldMapping", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'line3FeedAttribute'", "]", ")", ";", "$", "line3FieldMapping", "->", "setFieldId", "(", "self", "::", "PLACEHOLDER_FIELD_LINE_3_TEXT", ")", ";", "// Create the feed mapping and feed mapping operation.", "$", "feedMapping", "=", "new", "FeedMapping", "(", ")", ";", "$", "feedMapping", "->", "setPlaceholderType", "(", "self", "::", "PLACEHOLDER_SITELINKS", ")", ";", "$", "feedMapping", "->", "setFeedId", "(", "$", "sitelinksData", "[", "'sitelinksFeedId'", "]", ")", ";", "$", "feedMapping", "->", "setAttributeFieldMappings", "(", "[", "$", "linkTextFieldMapping", ",", "$", "linkFinalUrlFieldMapping", ",", "$", "line2FieldMapping", ",", "$", "line3FieldMapping", "]", ")", ";", "$", "operation", "=", "new", "FeedMappingOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "feedMapping", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the feed mapping operation on the server and print out some", "// information.", "$", "result", "=", "$", "feedMappingService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "foreach", "(", "$", "result", "->", "getValue", "(", ")", "as", "$", "feedMapping", ")", "{", "printf", "(", "'Feed mapping with ID %d and placeholder type %d was '", ".", "'saved for feed with ID %d.%s'", ",", "$", "feedMapping", "->", "getFeedMappingId", "(", ")", ",", "$", "feedMapping", "->", "getPlaceholderType", "(", ")", ",", "$", "feedMapping", "->", "getFeedId", "(", ")", ",", "PHP_EOL", ")", ";", "}", "}" ]
Maps the feed attributes to the sitelink placeholders.
[ "Maps", "the", "feed", "attributes", "to", "the", "sitelink", "placeholders", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php#L272-L336
train
googleads/googleads-php-lib
examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php
AddSitelinksUsingFeeds.createSitelinksCampaignFeed
private static function createSitelinksCampaignFeed( AdWordsServices $adWordsServices, AdWordsSession $session, array $sitelinksData, $campaignId ) { $campaignFeedService = $adWordsServices->get($session, CampaignFeedService::class); $matchingFunctionString = sprintf( 'AND( IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, "Mobile") )', implode(',', $sitelinksData['sitelinkFeedItemIds']) ); // Create a campaign feed and its feed function. $campaignFeed = new CampaignFeed(); $campaignFeed->setFeedId($sitelinksData['sitelinksFeedId']); $campaignFeed->setCampaignId($campaignId); $matchingFunction = new MatchingFunction(); $matchingFunction->setFunctionString($matchingFunctionString); $campaignFeed->setMatchingFunction($matchingFunction); $campaignFeed->setPlaceholderTypes([self::PLACEHOLDER_SITELINKS]); // Create the campaign feed operation. $operation = new CampaignFeedOperation(); $operation->setOperand($campaignFeed); $operation->setOperator(Operator::ADD); // Create the campaign feed on the server and print out some information. $result = $campaignFeedService->mutate([$operation]); foreach ($result->getValue() as $savedCampaignFeed) { printf( 'Campaign with ID %d was associated with feed with ID %d.%s', $savedCampaignFeed->getCampaignId(), $savedCampaignFeed->getFeedId(), PHP_EOL ); } }
php
private static function createSitelinksCampaignFeed( AdWordsServices $adWordsServices, AdWordsSession $session, array $sitelinksData, $campaignId ) { $campaignFeedService = $adWordsServices->get($session, CampaignFeedService::class); $matchingFunctionString = sprintf( 'AND( IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, "Mobile") )', implode(',', $sitelinksData['sitelinkFeedItemIds']) ); // Create a campaign feed and its feed function. $campaignFeed = new CampaignFeed(); $campaignFeed->setFeedId($sitelinksData['sitelinksFeedId']); $campaignFeed->setCampaignId($campaignId); $matchingFunction = new MatchingFunction(); $matchingFunction->setFunctionString($matchingFunctionString); $campaignFeed->setMatchingFunction($matchingFunction); $campaignFeed->setPlaceholderTypes([self::PLACEHOLDER_SITELINKS]); // Create the campaign feed operation. $operation = new CampaignFeedOperation(); $operation->setOperand($campaignFeed); $operation->setOperator(Operator::ADD); // Create the campaign feed on the server and print out some information. $result = $campaignFeedService->mutate([$operation]); foreach ($result->getValue() as $savedCampaignFeed) { printf( 'Campaign with ID %d was associated with feed with ID %d.%s', $savedCampaignFeed->getCampaignId(), $savedCampaignFeed->getFeedId(), PHP_EOL ); } }
[ "private", "static", "function", "createSitelinksCampaignFeed", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "array", "$", "sitelinksData", ",", "$", "campaignId", ")", "{", "$", "campaignFeedService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "CampaignFeedService", "::", "class", ")", ";", "$", "matchingFunctionString", "=", "sprintf", "(", "'AND( IN(FEED_ITEM_ID, {%s}), EQUALS(CONTEXT.DEVICE, \"Mobile\") )'", ",", "implode", "(", "','", ",", "$", "sitelinksData", "[", "'sitelinkFeedItemIds'", "]", ")", ")", ";", "// Create a campaign feed and its feed function.", "$", "campaignFeed", "=", "new", "CampaignFeed", "(", ")", ";", "$", "campaignFeed", "->", "setFeedId", "(", "$", "sitelinksData", "[", "'sitelinksFeedId'", "]", ")", ";", "$", "campaignFeed", "->", "setCampaignId", "(", "$", "campaignId", ")", ";", "$", "matchingFunction", "=", "new", "MatchingFunction", "(", ")", ";", "$", "matchingFunction", "->", "setFunctionString", "(", "$", "matchingFunctionString", ")", ";", "$", "campaignFeed", "->", "setMatchingFunction", "(", "$", "matchingFunction", ")", ";", "$", "campaignFeed", "->", "setPlaceholderTypes", "(", "[", "self", "::", "PLACEHOLDER_SITELINKS", "]", ")", ";", "// Create the campaign feed operation.", "$", "operation", "=", "new", "CampaignFeedOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "campaignFeed", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the campaign feed on the server and print out some information.", "$", "result", "=", "$", "campaignFeedService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "foreach", "(", "$", "result", "->", "getValue", "(", ")", "as", "$", "savedCampaignFeed", ")", "{", "printf", "(", "'Campaign with ID %d was associated with feed with ID %d.%s'", ",", "$", "savedCampaignFeed", "->", "getCampaignId", "(", ")", ",", "$", "savedCampaignFeed", "->", "getFeedId", "(", ")", ",", "PHP_EOL", ")", ";", "}", "}" ]
Creates the campaign feed associated to the populated feed data for the specified campaign ID.
[ "Creates", "the", "campaign", "feed", "associated", "to", "the", "populated", "feed", "data", "for", "the", "specified", "campaign", "ID", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php#L342-L380
train
googleads/googleads-php-lib
examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php
AddSitelinksUsingFeeds.restrictFeedItemToAdGroup
private static function restrictFeedItemToAdGroup( AdWordsServices $adWordsServices, AdWordsSession $session, $feedId, $feedItemId, $adGroupId ) { $feedItemTargetService = $adWordsServices->get( $session, FeedItemTargetService::class ); // Create a feed item ad group target. $feedItemAdGroupTarget = new FeedItemAdGroupTarget(); $feedItemAdGroupTarget->setFeedId($feedId); $feedItemAdGroupTarget->setFeedItemId($feedItemId); $feedItemAdGroupTarget->setAdGroupId($adGroupId); // Create a feed item ad group target operation. $operation = new FeedItemTargetOperation(); $operation->setOperand($feedItemAdGroupTarget); $operation->setOperator(Operator::ADD); // Create the feed item ad group target on the server and print out // some information. $result = $feedItemTargetService->mutate([$operation]); $feedItemAdGroupTarget = $result->getValue()[0]; printf( 'Feed item target for feed ID %d and feed item ID %d was ' . 'created to restrict serving to ad group ID %d.%s', $feedItemAdGroupTarget->getFeedId(), $feedItemAdGroupTarget->getFeedItemId(), $feedItemAdGroupTarget->getAdGroupId(), PHP_EOL ); }
php
private static function restrictFeedItemToAdGroup( AdWordsServices $adWordsServices, AdWordsSession $session, $feedId, $feedItemId, $adGroupId ) { $feedItemTargetService = $adWordsServices->get( $session, FeedItemTargetService::class ); // Create a feed item ad group target. $feedItemAdGroupTarget = new FeedItemAdGroupTarget(); $feedItemAdGroupTarget->setFeedId($feedId); $feedItemAdGroupTarget->setFeedItemId($feedItemId); $feedItemAdGroupTarget->setAdGroupId($adGroupId); // Create a feed item ad group target operation. $operation = new FeedItemTargetOperation(); $operation->setOperand($feedItemAdGroupTarget); $operation->setOperator(Operator::ADD); // Create the feed item ad group target on the server and print out // some information. $result = $feedItemTargetService->mutate([$operation]); $feedItemAdGroupTarget = $result->getValue()[0]; printf( 'Feed item target for feed ID %d and feed item ID %d was ' . 'created to restrict serving to ad group ID %d.%s', $feedItemAdGroupTarget->getFeedId(), $feedItemAdGroupTarget->getFeedItemId(), $feedItemAdGroupTarget->getAdGroupId(), PHP_EOL ); }
[ "private", "static", "function", "restrictFeedItemToAdGroup", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "$", "feedId", ",", "$", "feedItemId", ",", "$", "adGroupId", ")", "{", "$", "feedItemTargetService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "FeedItemTargetService", "::", "class", ")", ";", "// Create a feed item ad group target.", "$", "feedItemAdGroupTarget", "=", "new", "FeedItemAdGroupTarget", "(", ")", ";", "$", "feedItemAdGroupTarget", "->", "setFeedId", "(", "$", "feedId", ")", ";", "$", "feedItemAdGroupTarget", "->", "setFeedItemId", "(", "$", "feedItemId", ")", ";", "$", "feedItemAdGroupTarget", "->", "setAdGroupId", "(", "$", "adGroupId", ")", ";", "// Create a feed item ad group target operation.", "$", "operation", "=", "new", "FeedItemTargetOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "feedItemAdGroupTarget", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the feed item ad group target on the server and print out", "// some information.", "$", "result", "=", "$", "feedItemTargetService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "feedItemAdGroupTarget", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "'Feed item target for feed ID %d and feed item ID %d was '", ".", "'created to restrict serving to ad group ID %d.%s'", ",", "$", "feedItemAdGroupTarget", "->", "getFeedId", "(", ")", ",", "$", "feedItemAdGroupTarget", "->", "getFeedItemId", "(", ")", ",", "$", "feedItemAdGroupTarget", "->", "getAdGroupId", "(", ")", ",", "PHP_EOL", ")", ";", "}" ]
Creates feed item ad group target for a specified feed ID, feed item ID, and ad group ID.
[ "Creates", "feed", "item", "ad", "group", "target", "for", "a", "specified", "feed", "ID", "feed", "item", "ID", "and", "ad", "group", "ID", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php#L386-L421
train
googleads/googleads-php-lib
examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php
AddSitelinksUsingFeeds.restrictFeedItemToGeoTarget
private static function restrictFeedItemToGeoTarget( AdWordsServices $adWordsServices, AdWordsSession $session, FeedItem $feedItem, $locationId ) { $feedItemTargetService = $adWordsServices->get( $session, FeedItemTargetService::class ); // Optional: Restrict the feed item to only serve with ads for the // specified geo target. $feedItemCriterionTarget = new FeedItemCriterionTarget(); $feedItemCriterionTarget->setFeedId($feedItem->getFeedId()); $feedItemCriterionTarget->setFeedItemId($feedItem->getFeedItemId()); $location = new Location(); // The IDs can be found in the documentation or retrieved with the // LocationCriterionService. $location->setId($locationId); $feedItemCriterionTarget->setCriterion($location); // Create a feed item target operation. $operation = new FeedItemTargetOperation(); $operation->setOperand($feedItemCriterionTarget); $operation->setOperator(Operator::ADD); // Create the feed item target on the server and print out // some information. $result = $feedItemTargetService->mutate([$operation]); $feedItemCriterionTarget = $result->getValue()[0]; printf( 'Feed item target for feed ID %d and feed item ID %d was ' . 'created to restrict serving to location ID %d.%s', $feedItemCriterionTarget->getFeedId(), $feedItemCriterionTarget->getFeedItemId(), $feedItemCriterionTarget->getCriterion()->getId(), PHP_EOL ); }
php
private static function restrictFeedItemToGeoTarget( AdWordsServices $adWordsServices, AdWordsSession $session, FeedItem $feedItem, $locationId ) { $feedItemTargetService = $adWordsServices->get( $session, FeedItemTargetService::class ); // Optional: Restrict the feed item to only serve with ads for the // specified geo target. $feedItemCriterionTarget = new FeedItemCriterionTarget(); $feedItemCriterionTarget->setFeedId($feedItem->getFeedId()); $feedItemCriterionTarget->setFeedItemId($feedItem->getFeedItemId()); $location = new Location(); // The IDs can be found in the documentation or retrieved with the // LocationCriterionService. $location->setId($locationId); $feedItemCriterionTarget->setCriterion($location); // Create a feed item target operation. $operation = new FeedItemTargetOperation(); $operation->setOperand($feedItemCriterionTarget); $operation->setOperator(Operator::ADD); // Create the feed item target on the server and print out // some information. $result = $feedItemTargetService->mutate([$operation]); $feedItemCriterionTarget = $result->getValue()[0]; printf( 'Feed item target for feed ID %d and feed item ID %d was ' . 'created to restrict serving to location ID %d.%s', $feedItemCriterionTarget->getFeedId(), $feedItemCriterionTarget->getFeedItemId(), $feedItemCriterionTarget->getCriterion()->getId(), PHP_EOL ); }
[ "private", "static", "function", "restrictFeedItemToGeoTarget", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "FeedItem", "$", "feedItem", ",", "$", "locationId", ")", "{", "$", "feedItemTargetService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "FeedItemTargetService", "::", "class", ")", ";", "// Optional: Restrict the feed item to only serve with ads for the", "// specified geo target.", "$", "feedItemCriterionTarget", "=", "new", "FeedItemCriterionTarget", "(", ")", ";", "$", "feedItemCriterionTarget", "->", "setFeedId", "(", "$", "feedItem", "->", "getFeedId", "(", ")", ")", ";", "$", "feedItemCriterionTarget", "->", "setFeedItemId", "(", "$", "feedItem", "->", "getFeedItemId", "(", ")", ")", ";", "$", "location", "=", "new", "Location", "(", ")", ";", "// The IDs can be found in the documentation or retrieved with the", "// LocationCriterionService.", "$", "location", "->", "setId", "(", "$", "locationId", ")", ";", "$", "feedItemCriterionTarget", "->", "setCriterion", "(", "$", "location", ")", ";", "// Create a feed item target operation.", "$", "operation", "=", "new", "FeedItemTargetOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "feedItemCriterionTarget", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the feed item target on the server and print out", "// some information.", "$", "result", "=", "$", "feedItemTargetService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "feedItemCriterionTarget", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "'Feed item target for feed ID %d and feed item ID %d was '", ".", "'created to restrict serving to location ID %d.%s'", ",", "$", "feedItemCriterionTarget", "->", "getFeedId", "(", ")", ",", "$", "feedItemCriterionTarget", "->", "getFeedItemId", "(", ")", ",", "$", "feedItemCriterionTarget", "->", "getCriterion", "(", ")", "->", "getId", "(", ")", ",", "PHP_EOL", ")", ";", "}" ]
Restricts the first feed item to only serve with ads for the specified location ID. @param AdWordsServices $adWordsServices the AdWords services @param AdWordsSession $session the AdWords session @param FeedItem $feedItem the feed item to restrict @param int $locationId the location ID to which the feed item will be restricted
[ "Restricts", "the", "first", "feed", "item", "to", "only", "serve", "with", "ads", "for", "the", "specified", "location", "ID", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php#L433-L473
train
googleads/googleads-php-lib
examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php
AddSitelinksUsingFeeds.newSitelinkFeedItemAddOperation
private static function newSitelinkFeedItemAddOperation( array $sitelinksData, $text, $finalUrl, $line2, $line3, $restrictToLop = null ) { // Create the feed item attribute values for our text values. $linkTextAttributeValue = new FeedItemAttributeValue(); $linkTextAttributeValue->setFeedAttributeId( $sitelinksData['linkTextFeedAttributeId'] ); $linkTextAttributeValue->setStringValue($text); $linkFinalUrlAttributeValue = new FeedItemAttributeValue(); $linkFinalUrlAttributeValue->setFeedAttributeId( $sitelinksData['linkFinalUrlFeedAttributeId'] ); $linkFinalUrlAttributeValue->setStringValues([$finalUrl]); $line2AttributeValue = new FeedItemAttributeValue(); $line2AttributeValue->setFeedAttributeId( $sitelinksData['line2FeedAttribute'] ); $line2AttributeValue->setStringValue($line2); $line3AttributeValue = new FeedItemAttributeValue(); $line3AttributeValue->setFeedAttributeId( $sitelinksData['line3FeedAttribute'] ); $line3AttributeValue->setStringValue($line3); // Create the feed item. $item = new FeedItem(); $item->setFeedId($sitelinksData['sitelinksFeedId']); $item->setAttributeValues( [ $linkTextAttributeValue, $linkFinalUrlAttributeValue, $line2AttributeValue, $line3AttributeValue ] ); // OPTIONAL: Restrict targeting only to people physically within the // location. if ($restrictToLop === true) { $item->setGeoTargetingRestriction( new FeedItemGeoRestriction(GeoRestriction::LOCATION_OF_PRESENCE) ); } // Create the feed item operation. $operation = new FeedItemOperation(); $operation->setOperand($item); $operation->setOperator(Operator::ADD); return $operation; }
php
private static function newSitelinkFeedItemAddOperation( array $sitelinksData, $text, $finalUrl, $line2, $line3, $restrictToLop = null ) { // Create the feed item attribute values for our text values. $linkTextAttributeValue = new FeedItemAttributeValue(); $linkTextAttributeValue->setFeedAttributeId( $sitelinksData['linkTextFeedAttributeId'] ); $linkTextAttributeValue->setStringValue($text); $linkFinalUrlAttributeValue = new FeedItemAttributeValue(); $linkFinalUrlAttributeValue->setFeedAttributeId( $sitelinksData['linkFinalUrlFeedAttributeId'] ); $linkFinalUrlAttributeValue->setStringValues([$finalUrl]); $line2AttributeValue = new FeedItemAttributeValue(); $line2AttributeValue->setFeedAttributeId( $sitelinksData['line2FeedAttribute'] ); $line2AttributeValue->setStringValue($line2); $line3AttributeValue = new FeedItemAttributeValue(); $line3AttributeValue->setFeedAttributeId( $sitelinksData['line3FeedAttribute'] ); $line3AttributeValue->setStringValue($line3); // Create the feed item. $item = new FeedItem(); $item->setFeedId($sitelinksData['sitelinksFeedId']); $item->setAttributeValues( [ $linkTextAttributeValue, $linkFinalUrlAttributeValue, $line2AttributeValue, $line3AttributeValue ] ); // OPTIONAL: Restrict targeting only to people physically within the // location. if ($restrictToLop === true) { $item->setGeoTargetingRestriction( new FeedItemGeoRestriction(GeoRestriction::LOCATION_OF_PRESENCE) ); } // Create the feed item operation. $operation = new FeedItemOperation(); $operation->setOperand($item); $operation->setOperator(Operator::ADD); return $operation; }
[ "private", "static", "function", "newSitelinkFeedItemAddOperation", "(", "array", "$", "sitelinksData", ",", "$", "text", ",", "$", "finalUrl", ",", "$", "line2", ",", "$", "line3", ",", "$", "restrictToLop", "=", "null", ")", "{", "// Create the feed item attribute values for our text values.", "$", "linkTextAttributeValue", "=", "new", "FeedItemAttributeValue", "(", ")", ";", "$", "linkTextAttributeValue", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'linkTextFeedAttributeId'", "]", ")", ";", "$", "linkTextAttributeValue", "->", "setStringValue", "(", "$", "text", ")", ";", "$", "linkFinalUrlAttributeValue", "=", "new", "FeedItemAttributeValue", "(", ")", ";", "$", "linkFinalUrlAttributeValue", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'linkFinalUrlFeedAttributeId'", "]", ")", ";", "$", "linkFinalUrlAttributeValue", "->", "setStringValues", "(", "[", "$", "finalUrl", "]", ")", ";", "$", "line2AttributeValue", "=", "new", "FeedItemAttributeValue", "(", ")", ";", "$", "line2AttributeValue", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'line2FeedAttribute'", "]", ")", ";", "$", "line2AttributeValue", "->", "setStringValue", "(", "$", "line2", ")", ";", "$", "line3AttributeValue", "=", "new", "FeedItemAttributeValue", "(", ")", ";", "$", "line3AttributeValue", "->", "setFeedAttributeId", "(", "$", "sitelinksData", "[", "'line3FeedAttribute'", "]", ")", ";", "$", "line3AttributeValue", "->", "setStringValue", "(", "$", "line3", ")", ";", "// Create the feed item.", "$", "item", "=", "new", "FeedItem", "(", ")", ";", "$", "item", "->", "setFeedId", "(", "$", "sitelinksData", "[", "'sitelinksFeedId'", "]", ")", ";", "$", "item", "->", "setAttributeValues", "(", "[", "$", "linkTextAttributeValue", ",", "$", "linkFinalUrlAttributeValue", ",", "$", "line2AttributeValue", ",", "$", "line3AttributeValue", "]", ")", ";", "// OPTIONAL: Restrict targeting only to people physically within the", "// location.", "if", "(", "$", "restrictToLop", "===", "true", ")", "{", "$", "item", "->", "setGeoTargetingRestriction", "(", "new", "FeedItemGeoRestriction", "(", "GeoRestriction", "::", "LOCATION_OF_PRESENCE", ")", ")", ";", "}", "// Create the feed item operation.", "$", "operation", "=", "new", "FeedItemOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "item", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "return", "$", "operation", ";", "}" ]
Creates a site link feed item and wraps it in an ADD operation. @param array $sitelinksData IDs associated to created sitelinks feed metadata @param string $text the text of the sitelink @param string $finalUrl the final URL of the sitelink @param string $line2 the first line of the sitelink description @param string $line3 the second line of the sitelink description @param bool|null $restrictToLop whether to restrict the feed item to location of presence @return FeedItemOperation the created ADD operation of site link feed item
[ "Creates", "a", "site", "link", "feed", "item", "and", "wraps", "it", "in", "an", "ADD", "operation", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Extensions/AddSitelinksUsingFeeds.php#L489-L545
train
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/Util/v201805/AdManagerDates.php
AdManagerDates.toDateString
public static function toDateString(Date $adManagerDate) { return sprintf( '%d-%02d-%02d', $adManagerDate->getYear(), $adManagerDate->getMonth(), $adManagerDate->getDay() ); }
php
public static function toDateString(Date $adManagerDate) { return sprintf( '%d-%02d-%02d', $adManagerDate->getYear(), $adManagerDate->getMonth(), $adManagerDate->getDay() ); }
[ "public", "static", "function", "toDateString", "(", "Date", "$", "adManagerDate", ")", "{", "return", "sprintf", "(", "'%d-%02d-%02d'", ",", "$", "adManagerDate", "->", "getYear", "(", ")", ",", "$", "adManagerDate", "->", "getMonth", "(", ")", ",", "$", "adManagerDate", "->", "getDay", "(", ")", ")", ";", "}" ]
Returns string representation of the specified Ad Manager date in `yyyy-MM-dd` format. @param Date $adManagerDate @return string
[ "Returns", "string", "representation", "of", "the", "specified", "Ad", "Manager", "date", "in", "yyyy", "-", "MM", "-", "dd", "format", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdManager/Util/v201805/AdManagerDates.php#L39-L47
train
googleads/googleads-php-lib
src/Google/AdsApi/Common/Util/SoapRequests.php
SoapRequests.replaceReferences
public static function replaceReferences($request) { $requestDom = new DOMDocument(); try { set_error_handler([self::class, 'handleLoadXmlWarnings']); $requestDom->loadXML($request); } catch (DOMException $e) { return $request; } finally { restore_error_handler(); } $xpath = new DOMXPath($requestDom); $references = $xpath->query('//*[@href]'); // Cache of referenced element IDs to their nodes. $referencedElementsCache = []; // Replace each reference. foreach ($references as $reference) { // References begin with a hash, e,g., #ref1, remove the hash sign. $id = substr($reference->getAttribute('href'), 1); // If we haven't seen this referenced node before we need to find it and // cache it. if (!array_key_exists($id, $referencedElementsCache)) { $referencedElements = $xpath->query(sprintf("//*[@id='%s']", $id)); // There may be more than one element with the same ID if we replaced // a reference to an element that has a child node that something else // is referencing. if ($referencedElements->length > 0) { $referencedElementsCache[$id] = $referencedElements->item(0); } else { // If for some reason we can't find it, it's probably a malformed SOAP // request XML and we skip this reference so the issue bubbles up. continue; } } // Deep copy all the nodes from the referenced element. foreach ($referencedElementsCache[$id]->childNodes as $childNode) { $reference->appendChild($childNode->cloneNode(true)); } $reference->removeAttribute('href'); } // Once all references are replaced, remove the obsolete ID tags from each // referenced element. foreach (array_keys($referencedElementsCache) as $id) { // For the same reason stated above, there may be more than one element // with the same ID due to replacement. $referencedElements = $xpath->query(sprintf("//*[@id='%s']", $id)); foreach ($referencedElements as $referencedElement) { $referencedElement->removeAttribute('id'); } } return $requestDom->saveXML(); }
php
public static function replaceReferences($request) { $requestDom = new DOMDocument(); try { set_error_handler([self::class, 'handleLoadXmlWarnings']); $requestDom->loadXML($request); } catch (DOMException $e) { return $request; } finally { restore_error_handler(); } $xpath = new DOMXPath($requestDom); $references = $xpath->query('//*[@href]'); // Cache of referenced element IDs to their nodes. $referencedElementsCache = []; // Replace each reference. foreach ($references as $reference) { // References begin with a hash, e,g., #ref1, remove the hash sign. $id = substr($reference->getAttribute('href'), 1); // If we haven't seen this referenced node before we need to find it and // cache it. if (!array_key_exists($id, $referencedElementsCache)) { $referencedElements = $xpath->query(sprintf("//*[@id='%s']", $id)); // There may be more than one element with the same ID if we replaced // a reference to an element that has a child node that something else // is referencing. if ($referencedElements->length > 0) { $referencedElementsCache[$id] = $referencedElements->item(0); } else { // If for some reason we can't find it, it's probably a malformed SOAP // request XML and we skip this reference so the issue bubbles up. continue; } } // Deep copy all the nodes from the referenced element. foreach ($referencedElementsCache[$id]->childNodes as $childNode) { $reference->appendChild($childNode->cloneNode(true)); } $reference->removeAttribute('href'); } // Once all references are replaced, remove the obsolete ID tags from each // referenced element. foreach (array_keys($referencedElementsCache) as $id) { // For the same reason stated above, there may be more than one element // with the same ID due to replacement. $referencedElements = $xpath->query(sprintf("//*[@id='%s']", $id)); foreach ($referencedElements as $referencedElement) { $referencedElement->removeAttribute('id'); } } return $requestDom->saveXML(); }
[ "public", "static", "function", "replaceReferences", "(", "$", "request", ")", "{", "$", "requestDom", "=", "new", "DOMDocument", "(", ")", ";", "try", "{", "set_error_handler", "(", "[", "self", "::", "class", ",", "'handleLoadXmlWarnings'", "]", ")", ";", "$", "requestDom", "->", "loadXML", "(", "$", "request", ")", ";", "}", "catch", "(", "DOMException", "$", "e", ")", "{", "return", "$", "request", ";", "}", "finally", "{", "restore_error_handler", "(", ")", ";", "}", "$", "xpath", "=", "new", "DOMXPath", "(", "$", "requestDom", ")", ";", "$", "references", "=", "$", "xpath", "->", "query", "(", "'//*[@href]'", ")", ";", "// Cache of referenced element IDs to their nodes.", "$", "referencedElementsCache", "=", "[", "]", ";", "// Replace each reference.", "foreach", "(", "$", "references", "as", "$", "reference", ")", "{", "// References begin with a hash, e,g., #ref1, remove the hash sign.", "$", "id", "=", "substr", "(", "$", "reference", "->", "getAttribute", "(", "'href'", ")", ",", "1", ")", ";", "// If we haven't seen this referenced node before we need to find it and", "// cache it.", "if", "(", "!", "array_key_exists", "(", "$", "id", ",", "$", "referencedElementsCache", ")", ")", "{", "$", "referencedElements", "=", "$", "xpath", "->", "query", "(", "sprintf", "(", "\"//*[@id='%s']\"", ",", "$", "id", ")", ")", ";", "// There may be more than one element with the same ID if we replaced", "// a reference to an element that has a child node that something else", "// is referencing.", "if", "(", "$", "referencedElements", "->", "length", ">", "0", ")", "{", "$", "referencedElementsCache", "[", "$", "id", "]", "=", "$", "referencedElements", "->", "item", "(", "0", ")", ";", "}", "else", "{", "// If for some reason we can't find it, it's probably a malformed SOAP", "// request XML and we skip this reference so the issue bubbles up.", "continue", ";", "}", "}", "// Deep copy all the nodes from the referenced element.", "foreach", "(", "$", "referencedElementsCache", "[", "$", "id", "]", "->", "childNodes", "as", "$", "childNode", ")", "{", "$", "reference", "->", "appendChild", "(", "$", "childNode", "->", "cloneNode", "(", "true", ")", ")", ";", "}", "$", "reference", "->", "removeAttribute", "(", "'href'", ")", ";", "}", "// Once all references are replaced, remove the obsolete ID tags from each", "// referenced element.", "foreach", "(", "array_keys", "(", "$", "referencedElementsCache", ")", "as", "$", "id", ")", "{", "// For the same reason stated above, there may be more than one element", "// with the same ID due to replacement.", "$", "referencedElements", "=", "$", "xpath", "->", "query", "(", "sprintf", "(", "\"//*[@id='%s']\"", ",", "$", "id", ")", ")", ";", "foreach", "(", "$", "referencedElements", "as", "$", "referencedElement", ")", "{", "$", "referencedElement", "->", "removeAttribute", "(", "'id'", ")", ";", "}", "}", "return", "$", "requestDom", "->", "saveXML", "(", ")", ";", "}" ]
Iterates through all nodes with an 'href' attribute in the specified request SOAP XML string and replaces them with the node they are referencing. If replacement fails in any way, return the original request so any issues bubble up. @param string $request @return string the request SOAP XML string with references replaced
[ "Iterates", "through", "all", "nodes", "with", "an", "href", "attribute", "in", "the", "specified", "request", "SOAP", "XML", "string", "and", "replaces", "them", "with", "the", "node", "they", "are", "referencing", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/Common/Util/SoapRequests.php#L41-L98
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/WhereClauseAppender.php
WhereClauseAppender.appendWhereClause
public static function appendWhereClause( $whereBuilders, $awql ) { if (empty($whereBuilders)) { return $awql; } $conditions = []; foreach ($whereBuilders as $whereBuilder) { $conditions[] = $whereBuilder->buildWhere(); } return sprintf('%s WHERE %s', $awql, implode(' AND ', $conditions)); }
php
public static function appendWhereClause( $whereBuilders, $awql ) { if (empty($whereBuilders)) { return $awql; } $conditions = []; foreach ($whereBuilders as $whereBuilder) { $conditions[] = $whereBuilder->buildWhere(); } return sprintf('%s WHERE %s', $awql, implode(' AND ', $conditions)); }
[ "public", "static", "function", "appendWhereClause", "(", "$", "whereBuilders", ",", "$", "awql", ")", "{", "if", "(", "empty", "(", "$", "whereBuilders", ")", ")", "{", "return", "$", "awql", ";", "}", "$", "conditions", "=", "[", "]", ";", "foreach", "(", "$", "whereBuilders", "as", "$", "whereBuilder", ")", "{", "$", "conditions", "[", "]", "=", "$", "whereBuilder", "->", "buildWhere", "(", ")", ";", "}", "return", "sprintf", "(", "'%s WHERE %s'", ",", "$", "awql", ",", "implode", "(", "' AND '", ",", "$", "conditions", ")", ")", ";", "}" ]
Builds and appends a WHERE clause to a partial AWQL string. If there is no expressions specified, the input AWQL string will be returned without modifications. @param WhereBuilderInterface[] $whereBuilders an array of builders for logic expressions in a WHERE clause @param string $awql a partial AWQL string without the WHERE clause @return string an AWQL string with the WHERE clause if at least one expression was specified
[ "Builds", "and", "appends", "a", "WHERE", "clause", "to", "a", "partial", "AWQL", "string", ".", "If", "there", "is", "no", "expressions", "specified", "the", "input", "AWQL", "string", "will", "be", "returned", "without", "modifications", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/WhereClauseAppender.php#L37-L51
train
googleads/googleads-php-lib
examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php
AddSmartShoppingAd.createSmartCampaign
private static function createSmartCampaign( AdWordsServices $adWordsServices, AdWordsSession $session, $budgetId, $merchantId ) { $campaignService = $adWordsServices->get($session, CampaignService::class); // Create a campaign with required and optional settings. $campaign = new Campaign(); $campaign->setName('Smart Shopping campaign #' . uniqid()); // The advertisingChannelType is what makes this a Shopping campaign. $campaign->setAdvertisingChannelType(AdvertisingChannelType::SHOPPING); // Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to // make this a Smart Shopping campaign. $campaign->setAdvertisingChannelSubType( AdvertisingChannelSubType::SHOPPING_GOAL_OPTIMIZED_ADS ); // Recommendation: Set the campaign to PAUSED when creating it to stop // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); // Set a budget. $budget = new Budget(); $budget->setBudgetId($budgetId); $campaign->setBudget($budget); // Set a bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyType( BiddingStrategyType::MAXIMIZE_CONVERSION_VALUE ); $campaign->setBiddingStrategyConfiguration( $biddingStrategyConfiguration ); // All Shopping campaigns need a ShoppingSetting. $shoppingSetting = new ShoppingSetting(); $shoppingSetting->setSalesCountry('US'); $shoppingSetting->setMerchantId($merchantId); $campaign->setSettings([$shoppingSetting]); // Create a campaign operation and add it to the operations list. $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); // Create the campaign on the server and print out some information. $addedCampaign = $campaignService->mutate([$operation])->getValue()[0]; printf( "Smart Shopping campaign with name '%s' and ID %d was added.%s", $addedCampaign->getName(), $addedCampaign->getId(), PHP_EOL ); return $addedCampaign->getId(); }
php
private static function createSmartCampaign( AdWordsServices $adWordsServices, AdWordsSession $session, $budgetId, $merchantId ) { $campaignService = $adWordsServices->get($session, CampaignService::class); // Create a campaign with required and optional settings. $campaign = new Campaign(); $campaign->setName('Smart Shopping campaign #' . uniqid()); // The advertisingChannelType is what makes this a Shopping campaign. $campaign->setAdvertisingChannelType(AdvertisingChannelType::SHOPPING); // Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to // make this a Smart Shopping campaign. $campaign->setAdvertisingChannelSubType( AdvertisingChannelSubType::SHOPPING_GOAL_OPTIMIZED_ADS ); // Recommendation: Set the campaign to PAUSED when creating it to stop // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); // Set a budget. $budget = new Budget(); $budget->setBudgetId($budgetId); $campaign->setBudget($budget); // Set a bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyType( BiddingStrategyType::MAXIMIZE_CONVERSION_VALUE ); $campaign->setBiddingStrategyConfiguration( $biddingStrategyConfiguration ); // All Shopping campaigns need a ShoppingSetting. $shoppingSetting = new ShoppingSetting(); $shoppingSetting->setSalesCountry('US'); $shoppingSetting->setMerchantId($merchantId); $campaign->setSettings([$shoppingSetting]); // Create a campaign operation and add it to the operations list. $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); // Create the campaign on the server and print out some information. $addedCampaign = $campaignService->mutate([$operation])->getValue()[0]; printf( "Smart Shopping campaign with name '%s' and ID %d was added.%s", $addedCampaign->getName(), $addedCampaign->getId(), PHP_EOL ); return $addedCampaign->getId(); }
[ "private", "static", "function", "createSmartCampaign", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "$", "budgetId", ",", "$", "merchantId", ")", "{", "$", "campaignService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "CampaignService", "::", "class", ")", ";", "// Create a campaign with required and optional settings.", "$", "campaign", "=", "new", "Campaign", "(", ")", ";", "$", "campaign", "->", "setName", "(", "'Smart Shopping campaign #'", ".", "uniqid", "(", ")", ")", ";", "// The advertisingChannelType is what makes this a Shopping campaign.", "$", "campaign", "->", "setAdvertisingChannelType", "(", "AdvertisingChannelType", "::", "SHOPPING", ")", ";", "// Sets the advertisingChannelSubType to SHOPPING_GOAL_OPTIMIZED_ADS to", "// make this a Smart Shopping campaign.", "$", "campaign", "->", "setAdvertisingChannelSubType", "(", "AdvertisingChannelSubType", "::", "SHOPPING_GOAL_OPTIMIZED_ADS", ")", ";", "// Recommendation: Set the campaign to PAUSED when creating it to stop", "// the ads from immediately serving. Set to ENABLED once you've added", "// targeting and the ads are ready to serve.", "$", "campaign", "->", "setStatus", "(", "CampaignStatus", "::", "PAUSED", ")", ";", "// Set a budget.", "$", "budget", "=", "new", "Budget", "(", ")", ";", "$", "budget", "->", "setBudgetId", "(", "$", "budgetId", ")", ";", "$", "campaign", "->", "setBudget", "(", "$", "budget", ")", ";", "// Set a bidding strategy. Only MAXIMIZE_CONVERSION_VALUE is supported.", "$", "biddingStrategyConfiguration", "=", "new", "BiddingStrategyConfiguration", "(", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBiddingStrategyType", "(", "BiddingStrategyType", "::", "MAXIMIZE_CONVERSION_VALUE", ")", ";", "$", "campaign", "->", "setBiddingStrategyConfiguration", "(", "$", "biddingStrategyConfiguration", ")", ";", "// All Shopping campaigns need a ShoppingSetting.", "$", "shoppingSetting", "=", "new", "ShoppingSetting", "(", ")", ";", "$", "shoppingSetting", "->", "setSalesCountry", "(", "'US'", ")", ";", "$", "shoppingSetting", "->", "setMerchantId", "(", "$", "merchantId", ")", ";", "$", "campaign", "->", "setSettings", "(", "[", "$", "shoppingSetting", "]", ")", ";", "// Create a campaign operation and add it to the operations list.", "$", "operation", "=", "new", "CampaignOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "campaign", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the campaign on the server and print out some information.", "$", "addedCampaign", "=", "$", "campaignService", "->", "mutate", "(", "[", "$", "operation", "]", ")", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Smart Shopping campaign with name '%s' and ID %d was added.%s\"", ",", "$", "addedCampaign", "->", "getName", "(", ")", ",", "$", "addedCampaign", "->", "getId", "(", ")", ",", "PHP_EOL", ")", ";", "return", "$", "addedCampaign", "->", "getId", "(", ")", ";", "}" ]
Creates a Smart Shopping campaign. @param AdWordsServices $adWordsServices the AdWords services @param AdWordsSession $session the AdWords session @param int $budgetId the budget ID @param int $merchantId the Merchant center ID @return int the created campaign ID
[ "Creates", "a", "Smart", "Shopping", "campaign", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php#L150-L210
train
googleads/googleads-php-lib
examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php
AddSmartShoppingAd.createSmartShoppingAdGroup
private static function createSmartShoppingAdGroup( AdWordsServices $adWordsServices, AdWordsSession $session, $campaignId ) { $adGroupService = $adWordsServices->get($session, AdGroupService::class); // Create an ad group. $adGroup = new AdGroup(); $adGroup->setCampaignId($campaignId); $adGroup->setName('Smart Shopping ad group #' . uniqid()); // Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS. $adGroup->setAdGroupType(AdGroupType::SHOPPING_GOAL_OPTIMIZED_ADS); // Create operation. $adGroupOperation = new AdGroupOperation(); $adGroupOperation->setOperand($adGroup); $adGroupOperation->setOperator(Operator::ADD); // Create the ad group on the server and print out some information. $addedAdGroup = $adGroupService->mutate([$adGroupOperation]) ->getValue()[0]; printf( "Smart Shopping ad group with name '%s' and ID %d was added.%s", $addedAdGroup->getName(), $addedAdGroup->getId(), PHP_EOL ); return $addedAdGroup->getId(); }
php
private static function createSmartShoppingAdGroup( AdWordsServices $adWordsServices, AdWordsSession $session, $campaignId ) { $adGroupService = $adWordsServices->get($session, AdGroupService::class); // Create an ad group. $adGroup = new AdGroup(); $adGroup->setCampaignId($campaignId); $adGroup->setName('Smart Shopping ad group #' . uniqid()); // Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS. $adGroup->setAdGroupType(AdGroupType::SHOPPING_GOAL_OPTIMIZED_ADS); // Create operation. $adGroupOperation = new AdGroupOperation(); $adGroupOperation->setOperand($adGroup); $adGroupOperation->setOperator(Operator::ADD); // Create the ad group on the server and print out some information. $addedAdGroup = $adGroupService->mutate([$adGroupOperation]) ->getValue()[0]; printf( "Smart Shopping ad group with name '%s' and ID %d was added.%s", $addedAdGroup->getName(), $addedAdGroup->getId(), PHP_EOL ); return $addedAdGroup->getId(); }
[ "private", "static", "function", "createSmartShoppingAdGroup", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "$", "campaignId", ")", "{", "$", "adGroupService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "AdGroupService", "::", "class", ")", ";", "// Create an ad group.", "$", "adGroup", "=", "new", "AdGroup", "(", ")", ";", "$", "adGroup", "->", "setCampaignId", "(", "$", "campaignId", ")", ";", "$", "adGroup", "->", "setName", "(", "'Smart Shopping ad group #'", ".", "uniqid", "(", ")", ")", ";", "// Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS.", "$", "adGroup", "->", "setAdGroupType", "(", "AdGroupType", "::", "SHOPPING_GOAL_OPTIMIZED_ADS", ")", ";", "// Create operation.", "$", "adGroupOperation", "=", "new", "AdGroupOperation", "(", ")", ";", "$", "adGroupOperation", "->", "setOperand", "(", "$", "adGroup", ")", ";", "$", "adGroupOperation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the ad group on the server and print out some information.", "$", "addedAdGroup", "=", "$", "adGroupService", "->", "mutate", "(", "[", "$", "adGroupOperation", "]", ")", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Smart Shopping ad group with name '%s' and ID %d was added.%s\"", ",", "$", "addedAdGroup", "->", "getName", "(", ")", ",", "$", "addedAdGroup", "->", "getId", "(", ")", ",", "PHP_EOL", ")", ";", "return", "$", "addedAdGroup", "->", "getId", "(", ")", ";", "}" ]
Creates a Smart Shopping ad group by setting the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS. @param AdWordsServices $adWordsServices the AdWords services @param AdWordsSession $session the AdWords session @param int $campaignId the campaign ID @return int the ad group ID
[ "Creates", "a", "Smart", "Shopping", "ad", "group", "by", "setting", "the", "ad", "group", "type", "to", "SHOPPING_GOAL_OPTIMIZED_ADS", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php#L221-L253
train
googleads/googleads-php-lib
examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php
AddSmartShoppingAd.createSmartShoppingAd
private static function createSmartShoppingAd( AdWordsServices $adWordsServices, AdWordsSession $session, $adGroupId ) { $adGroupAdService = $adWordsServices->get($session, AdGroupAdService::class); // Create a Smart Shopping ad (Goal-optimized Shopping ad). $smartShoppingAd = new GoalOptimizedShoppingAd(); // Create an ad group ad. $adGroupAd = new AdGroupAd(); $adGroupAd->setAdGroupId($adGroupId); $adGroupAd->setAd($smartShoppingAd); // Create an ad group ad operation and add it to the operations list. $operation = new AdGroupAdOperation(); $operation->setOperand($adGroupAd); $operation->setOperator(Operator::ADD); // Create the ad group ad on the server and print out some information. $addedAdGroupAd = $adGroupAdService->mutate([$operation]) ->getValue()[0]; printf( "Smart Shopping ad with ID %d was added.%s", $addedAdGroupAd->getAd()->getId(), PHP_EOL ); }
php
private static function createSmartShoppingAd( AdWordsServices $adWordsServices, AdWordsSession $session, $adGroupId ) { $adGroupAdService = $adWordsServices->get($session, AdGroupAdService::class); // Create a Smart Shopping ad (Goal-optimized Shopping ad). $smartShoppingAd = new GoalOptimizedShoppingAd(); // Create an ad group ad. $adGroupAd = new AdGroupAd(); $adGroupAd->setAdGroupId($adGroupId); $adGroupAd->setAd($smartShoppingAd); // Create an ad group ad operation and add it to the operations list. $operation = new AdGroupAdOperation(); $operation->setOperand($adGroupAd); $operation->setOperator(Operator::ADD); // Create the ad group ad on the server and print out some information. $addedAdGroupAd = $adGroupAdService->mutate([$operation]) ->getValue()[0]; printf( "Smart Shopping ad with ID %d was added.%s", $addedAdGroupAd->getAd()->getId(), PHP_EOL ); }
[ "private", "static", "function", "createSmartShoppingAd", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "$", "adGroupId", ")", "{", "$", "adGroupAdService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "AdGroupAdService", "::", "class", ")", ";", "// Create a Smart Shopping ad (Goal-optimized Shopping ad).", "$", "smartShoppingAd", "=", "new", "GoalOptimizedShoppingAd", "(", ")", ";", "// Create an ad group ad.", "$", "adGroupAd", "=", "new", "AdGroupAd", "(", ")", ";", "$", "adGroupAd", "->", "setAdGroupId", "(", "$", "adGroupId", ")", ";", "$", "adGroupAd", "->", "setAd", "(", "$", "smartShoppingAd", ")", ";", "// Create an ad group ad operation and add it to the operations list.", "$", "operation", "=", "new", "AdGroupAdOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "adGroupAd", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the ad group ad on the server and print out some information.", "$", "addedAdGroupAd", "=", "$", "adGroupAdService", "->", "mutate", "(", "[", "$", "operation", "]", ")", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Smart Shopping ad with ID %d was added.%s\"", ",", "$", "addedAdGroupAd", "->", "getAd", "(", ")", "->", "getId", "(", ")", ",", "PHP_EOL", ")", ";", "}" ]
Creates a Smart Shopping ad. @param AdWordsServices $adWordsServices the AdWords services @param AdWordsSession $session the AdWords session @param int $adGroupId the ad group ID
[ "Creates", "a", "Smart", "Shopping", "ad", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php#L262-L291
train
googleads/googleads-php-lib
examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php
AddSmartShoppingAd.createDefaultPartition
private static function createDefaultPartition( AdWordsServices $adWordsServices, AdWordsSession $session, $adGroupId ) { $adGroupCriterionService = $adWordsServices->get($session, AdGroupCriterionService::class); // Creates an ad group criterion for 'All products'. $productPartition = new ProductPartition(); $productPartition->setPartitionType(ProductPartitionType::UNIT); // Creates a biddable ad group criterion. $criterion = new BiddableAdGroupCriterion(); $criterion->setAdGroupId($adGroupId); $criterion->setCriterion($productPartition); // Creates an ad group criterion operation. $operation = new AdGroupCriterionOperation(); $operation->setOperand($criterion); $operation->setOperator(Operator::ADD); $addedAdGroupCriterion = $adGroupCriterionService->mutate([$operation]) ->getValue()[0]; printf( "Ad group criterion with ID %d in ad group with ID %d" . " was added.%s", $addedAdGroupCriterion->getCriterion()->getId(), $addedAdGroupCriterion->getAdGroupId(), PHP_EOL ); }
php
private static function createDefaultPartition( AdWordsServices $adWordsServices, AdWordsSession $session, $adGroupId ) { $adGroupCriterionService = $adWordsServices->get($session, AdGroupCriterionService::class); // Creates an ad group criterion for 'All products'. $productPartition = new ProductPartition(); $productPartition->setPartitionType(ProductPartitionType::UNIT); // Creates a biddable ad group criterion. $criterion = new BiddableAdGroupCriterion(); $criterion->setAdGroupId($adGroupId); $criterion->setCriterion($productPartition); // Creates an ad group criterion operation. $operation = new AdGroupCriterionOperation(); $operation->setOperand($criterion); $operation->setOperator(Operator::ADD); $addedAdGroupCriterion = $adGroupCriterionService->mutate([$operation]) ->getValue()[0]; printf( "Ad group criterion with ID %d in ad group with ID %d" . " was added.%s", $addedAdGroupCriterion->getCriterion()->getId(), $addedAdGroupCriterion->getAdGroupId(), PHP_EOL ); }
[ "private", "static", "function", "createDefaultPartition", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "$", "adGroupId", ")", "{", "$", "adGroupCriterionService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "AdGroupCriterionService", "::", "class", ")", ";", "// Creates an ad group criterion for 'All products'.", "$", "productPartition", "=", "new", "ProductPartition", "(", ")", ";", "$", "productPartition", "->", "setPartitionType", "(", "ProductPartitionType", "::", "UNIT", ")", ";", "// Creates a biddable ad group criterion.", "$", "criterion", "=", "new", "BiddableAdGroupCriterion", "(", ")", ";", "$", "criterion", "->", "setAdGroupId", "(", "$", "adGroupId", ")", ";", "$", "criterion", "->", "setCriterion", "(", "$", "productPartition", ")", ";", "// Creates an ad group criterion operation.", "$", "operation", "=", "new", "AdGroupCriterionOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "criterion", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "addedAdGroupCriterion", "=", "$", "adGroupCriterionService", "->", "mutate", "(", "[", "$", "operation", "]", ")", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Ad group criterion with ID %d in ad group with ID %d\"", ".", "\" was added.%s\"", ",", "$", "addedAdGroupCriterion", "->", "getCriterion", "(", ")", "->", "getId", "(", ")", ",", "$", "addedAdGroupCriterion", "->", "getAdGroupId", "(", ")", ",", "PHP_EOL", ")", ";", "}" ]
Creates a default product partition as an ad group criterion. @param AdWordsServices $adWordsServices the AdWords services @param AdWordsSession $session the AdWords session @param int $adGroupId the ad group ID
[ "Creates", "a", "default", "product", "partition", "as", "an", "ad", "group", "criterion", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/ShoppingCampaigns/AddSmartShoppingAd.php#L300-L331
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Reporting/v201809/RequestOptionsFactory.php
RequestOptionsFactory.createRequestOptionsWithReportDefinition
public function createRequestOptionsWithReportDefinition( ReportDefinition $reportDefinition, ReportSettings $reportSettingsOverride = null ) { $params = []; $context = ['xml_root_node_name' => 'reportDefinition']; $params['__rdxml'] = $this->reportDefinitionSerializer->serialize( $reportDefinition, 'xml', $context ); return array_merge( $this->options, [ RequestOptions::HEADERS => $this->createHeaders($reportSettingsOverride), RequestOptions::FORM_PARAMS => $params, ] ); }
php
public function createRequestOptionsWithReportDefinition( ReportDefinition $reportDefinition, ReportSettings $reportSettingsOverride = null ) { $params = []; $context = ['xml_root_node_name' => 'reportDefinition']; $params['__rdxml'] = $this->reportDefinitionSerializer->serialize( $reportDefinition, 'xml', $context ); return array_merge( $this->options, [ RequestOptions::HEADERS => $this->createHeaders($reportSettingsOverride), RequestOptions::FORM_PARAMS => $params, ] ); }
[ "public", "function", "createRequestOptionsWithReportDefinition", "(", "ReportDefinition", "$", "reportDefinition", ",", "ReportSettings", "$", "reportSettingsOverride", "=", "null", ")", "{", "$", "params", "=", "[", "]", ";", "$", "context", "=", "[", "'xml_root_node_name'", "=>", "'reportDefinition'", "]", ";", "$", "params", "[", "'__rdxml'", "]", "=", "$", "this", "->", "reportDefinitionSerializer", "->", "serialize", "(", "$", "reportDefinition", ",", "'xml'", ",", "$", "context", ")", ";", "return", "array_merge", "(", "$", "this", "->", "options", ",", "[", "RequestOptions", "::", "HEADERS", "=>", "$", "this", "->", "createHeaders", "(", "$", "reportSettingsOverride", ")", ",", "RequestOptions", "::", "FORM_PARAMS", "=>", "$", "params", ",", "]", ")", ";", "}" ]
Creates request options for downloading a report using an XML-based report definition. @see https://developers.google.com/adwords/api/docs/guides/reporting#create-a-report-definition @param ReportDefinition $reportDefinition the report definition @param null|ReportSettings $reportSettingsOverride the report settings used to override the report settings of the AdWords session for this request @return array the request options
[ "Creates", "request", "options", "for", "downloading", "a", "report", "using", "an", "XML", "-", "based", "report", "definition", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Reporting/v201809/RequestOptionsFactory.php#L140-L160
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Reporting/v201809/RequestOptionsFactory.php
RequestOptionsFactory.createRequestOptionsWithAwqlQuery
public function createRequestOptionsWithAwqlQuery( $reportDefinition, $reportFormat, ReportSettings $reportSettingsOverride = null ) { $params = ['__rdquery' => $reportDefinition, '__fmt' => $reportFormat]; return array_merge( $this->options, [ RequestOptions::HEADERS => $this->createHeaders($reportSettingsOverride), RequestOptions::FORM_PARAMS => $params, ] ); }
php
public function createRequestOptionsWithAwqlQuery( $reportDefinition, $reportFormat, ReportSettings $reportSettingsOverride = null ) { $params = ['__rdquery' => $reportDefinition, '__fmt' => $reportFormat]; return array_merge( $this->options, [ RequestOptions::HEADERS => $this->createHeaders($reportSettingsOverride), RequestOptions::FORM_PARAMS => $params, ] ); }
[ "public", "function", "createRequestOptionsWithAwqlQuery", "(", "$", "reportDefinition", ",", "$", "reportFormat", ",", "ReportSettings", "$", "reportSettingsOverride", "=", "null", ")", "{", "$", "params", "=", "[", "'__rdquery'", "=>", "$", "reportDefinition", ",", "'__fmt'", "=>", "$", "reportFormat", "]", ";", "return", "array_merge", "(", "$", "this", "->", "options", ",", "[", "RequestOptions", "::", "HEADERS", "=>", "$", "this", "->", "createHeaders", "(", "$", "reportSettingsOverride", ")", ",", "RequestOptions", "::", "FORM_PARAMS", "=>", "$", "params", ",", "]", ")", ";", "}" ]
Creates request options for downloading a report using an AWQL-based report definition. @see https://developers.google.com/adwords/api/docs/guides/reporting#create-a-report-definition @param string $reportDefinition the report definition in AWQL format @param string $reportFormat the format to download report as @param null|ReportSettings $reportSettingsOverride the report settings used to override the report settings of the AdWords session for this request @return array the request options
[ "Creates", "request", "options", "for", "downloading", "a", "report", "using", "an", "AWQL", "-", "based", "report", "definition", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Reporting/v201809/RequestOptionsFactory.php#L175-L190
train
googleads/googleads-php-lib
examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php
AddCompleteCampaignsUsingBatchJob.buildAdGroupAdOperations
private static function buildAdGroupAdOperations(array $adGroupOperations) { $operations = []; foreach ($adGroupOperations as $adGroupOperation) { $adGroupId = $adGroupOperation->getOperand()->getId(); $adGroupAd = new AdGroupAd(); $adGroupAd->setAdGroupId($adGroupId); $expandedTextAd = new ExpandedTextAd(); $expandedTextAd->setHeadlinePart1('Luxury Cruise to Mars'); $expandedTextAd->setHeadlinePart2('Visit the Red Planet in style.'); $expandedTextAd->setDescription('Low-gravity fun for everyone!'); $expandedTextAd->setFinalUrls(['http://www.example.com/1']); $adGroupAd->setAd($expandedTextAd); $operation = new AdGroupAdOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($adGroupAd); $operations[] = $operation; } return $operations; }
php
private static function buildAdGroupAdOperations(array $adGroupOperations) { $operations = []; foreach ($adGroupOperations as $adGroupOperation) { $adGroupId = $adGroupOperation->getOperand()->getId(); $adGroupAd = new AdGroupAd(); $adGroupAd->setAdGroupId($adGroupId); $expandedTextAd = new ExpandedTextAd(); $expandedTextAd->setHeadlinePart1('Luxury Cruise to Mars'); $expandedTextAd->setHeadlinePart2('Visit the Red Planet in style.'); $expandedTextAd->setDescription('Low-gravity fun for everyone!'); $expandedTextAd->setFinalUrls(['http://www.example.com/1']); $adGroupAd->setAd($expandedTextAd); $operation = new AdGroupAdOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($adGroupAd); $operations[] = $operation; } return $operations; }
[ "private", "static", "function", "buildAdGroupAdOperations", "(", "array", "$", "adGroupOperations", ")", "{", "$", "operations", "=", "[", "]", ";", "foreach", "(", "$", "adGroupOperations", "as", "$", "adGroupOperation", ")", "{", "$", "adGroupId", "=", "$", "adGroupOperation", "->", "getOperand", "(", ")", "->", "getId", "(", ")", ";", "$", "adGroupAd", "=", "new", "AdGroupAd", "(", ")", ";", "$", "adGroupAd", "->", "setAdGroupId", "(", "$", "adGroupId", ")", ";", "$", "expandedTextAd", "=", "new", "ExpandedTextAd", "(", ")", ";", "$", "expandedTextAd", "->", "setHeadlinePart1", "(", "'Luxury Cruise to Mars'", ")", ";", "$", "expandedTextAd", "->", "setHeadlinePart2", "(", "'Visit the Red Planet in style.'", ")", ";", "$", "expandedTextAd", "->", "setDescription", "(", "'Low-gravity fun for everyone!'", ")", ";", "$", "expandedTextAd", "->", "setFinalUrls", "(", "[", "'http://www.example.com/1'", "]", ")", ";", "$", "adGroupAd", "->", "setAd", "(", "$", "expandedTextAd", ")", ";", "$", "operation", "=", "new", "AdGroupAdOperation", "(", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "adGroupAd", ")", ";", "$", "operations", "[", "]", "=", "$", "operation", ";", "}", "return", "$", "operations", ";", "}" ]
Builds objects of AdGroupAdOperation for creating an ad group ad for ad groups in the specified ad group operations. @param AdGroupOperation[] $adGroupOperations an array of AdGroupOperation @return array an array of AdGroupAdOperation
[ "Builds", "objects", "of", "AdGroupAdOperation", "for", "creating", "an", "ad", "group", "ad", "for", "ad", "groups", "in", "the", "specified", "ad", "group", "operations", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php#L225-L249
train
googleads/googleads-php-lib
examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php
AddCompleteCampaignsUsingBatchJob.buildAdGroupOperations
private static function buildAdGroupOperations( $namePrefix, array $campaignOperations ) { $operations = []; foreach ($campaignOperations as $campaignOperation) { for ($i = 0; $i < self::NUMBER_OF_ADGROUPS_TO_ADD; $i++) { $adGroup = new AdGroup(); $adGroup->setCampaignId($campaignOperation->getOperand()->getId()); $adGroup->setId(--self::$temporaryId); $adGroup->setName( sprintf( 'Batch Ad Group %s.%s', $namePrefix, strval($adGroup->getId()) ) ); $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $money = new Money(); $money->setMicroAmount(10000000); $bid = new CpcBid(); $bid->setBid($money); $biddingStrategyConfiguration->setBids([$bid]); $adGroup->setBiddingStrategyConfiguration( $biddingStrategyConfiguration ); $operation = new AdGroupOperation(); $operation->setOperand($adGroup); $operation->setOperator(Operator::ADD); $operations[] = $operation; } } return $operations; }
php
private static function buildAdGroupOperations( $namePrefix, array $campaignOperations ) { $operations = []; foreach ($campaignOperations as $campaignOperation) { for ($i = 0; $i < self::NUMBER_OF_ADGROUPS_TO_ADD; $i++) { $adGroup = new AdGroup(); $adGroup->setCampaignId($campaignOperation->getOperand()->getId()); $adGroup->setId(--self::$temporaryId); $adGroup->setName( sprintf( 'Batch Ad Group %s.%s', $namePrefix, strval($adGroup->getId()) ) ); $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $money = new Money(); $money->setMicroAmount(10000000); $bid = new CpcBid(); $bid->setBid($money); $biddingStrategyConfiguration->setBids([$bid]); $adGroup->setBiddingStrategyConfiguration( $biddingStrategyConfiguration ); $operation = new AdGroupOperation(); $operation->setOperand($adGroup); $operation->setOperator(Operator::ADD); $operations[] = $operation; } } return $operations; }
[ "private", "static", "function", "buildAdGroupOperations", "(", "$", "namePrefix", ",", "array", "$", "campaignOperations", ")", "{", "$", "operations", "=", "[", "]", ";", "foreach", "(", "$", "campaignOperations", "as", "$", "campaignOperation", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "self", "::", "NUMBER_OF_ADGROUPS_TO_ADD", ";", "$", "i", "++", ")", "{", "$", "adGroup", "=", "new", "AdGroup", "(", ")", ";", "$", "adGroup", "->", "setCampaignId", "(", "$", "campaignOperation", "->", "getOperand", "(", ")", "->", "getId", "(", ")", ")", ";", "$", "adGroup", "->", "setId", "(", "--", "self", "::", "$", "temporaryId", ")", ";", "$", "adGroup", "->", "setName", "(", "sprintf", "(", "'Batch Ad Group %s.%s'", ",", "$", "namePrefix", ",", "strval", "(", "$", "adGroup", "->", "getId", "(", ")", ")", ")", ")", ";", "$", "biddingStrategyConfiguration", "=", "new", "BiddingStrategyConfiguration", "(", ")", ";", "$", "money", "=", "new", "Money", "(", ")", ";", "$", "money", "->", "setMicroAmount", "(", "10000000", ")", ";", "$", "bid", "=", "new", "CpcBid", "(", ")", ";", "$", "bid", "->", "setBid", "(", "$", "money", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBids", "(", "[", "$", "bid", "]", ")", ";", "$", "adGroup", "->", "setBiddingStrategyConfiguration", "(", "$", "biddingStrategyConfiguration", ")", ";", "$", "operation", "=", "new", "AdGroupOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "adGroup", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operations", "[", "]", "=", "$", "operation", ";", "}", "}", "return", "$", "operations", ";", "}" ]
Builds objects of AdGroupOperation for creating ad groups for campaigns in the specified campaign operations. @param string $namePrefix a prefix string used to name ad groups @param CampaignOperation[] $campaignOperations an array of CampaignOperation @return array an array of AdGroupOperation
[ "Builds", "objects", "of", "AdGroupOperation", "for", "creating", "ad", "groups", "for", "campaigns", "in", "the", "specified", "campaign", "operations", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php#L306-L344
train
googleads/googleads-php-lib
examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php
AddCompleteCampaignsUsingBatchJob.buildCampaignOperations
private static function buildCampaignOperations( $namePrefix, BudgetOperation $budgetOperation ) { $budgetId = $budgetOperation->getOperand()->getBudgetId(); $operations = []; for ($i = 0; $i < self::NUMBER_OF_CAMPAIGNS_TO_ADD; $i++) { $campaign = new Campaign(); $campaign->setId(--self::$temporaryId); $campaign->setName( sprintf( 'Batch Campaign %s.%s', $namePrefix, strval($campaign->getId()) ) ); // Recommendation: Set the campaign to PAUSED when creating it to stop // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH); $budget = new Budget(); $budget->setBudgetId($budgetId); $campaign->setBudget($budget); $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyType( BiddingStrategyType::MANUAL_CPC ); // You can optionally provide a bidding scheme in place of the type. $cpcBiddingScheme = new ManualCpcBiddingScheme(); $biddingStrategyConfiguration->setBiddingScheme($cpcBiddingScheme); $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration); $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); $operations[] = $operation; } return $operations; }
php
private static function buildCampaignOperations( $namePrefix, BudgetOperation $budgetOperation ) { $budgetId = $budgetOperation->getOperand()->getBudgetId(); $operations = []; for ($i = 0; $i < self::NUMBER_OF_CAMPAIGNS_TO_ADD; $i++) { $campaign = new Campaign(); $campaign->setId(--self::$temporaryId); $campaign->setName( sprintf( 'Batch Campaign %s.%s', $namePrefix, strval($campaign->getId()) ) ); // Recommendation: Set the campaign to PAUSED when creating it to stop // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH); $budget = new Budget(); $budget->setBudgetId($budgetId); $campaign->setBudget($budget); $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyType( BiddingStrategyType::MANUAL_CPC ); // You can optionally provide a bidding scheme in place of the type. $cpcBiddingScheme = new ManualCpcBiddingScheme(); $biddingStrategyConfiguration->setBiddingScheme($cpcBiddingScheme); $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration); $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); $operations[] = $operation; } return $operations; }
[ "private", "static", "function", "buildCampaignOperations", "(", "$", "namePrefix", ",", "BudgetOperation", "$", "budgetOperation", ")", "{", "$", "budgetId", "=", "$", "budgetOperation", "->", "getOperand", "(", ")", "->", "getBudgetId", "(", ")", ";", "$", "operations", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "self", "::", "NUMBER_OF_CAMPAIGNS_TO_ADD", ";", "$", "i", "++", ")", "{", "$", "campaign", "=", "new", "Campaign", "(", ")", ";", "$", "campaign", "->", "setId", "(", "--", "self", "::", "$", "temporaryId", ")", ";", "$", "campaign", "->", "setName", "(", "sprintf", "(", "'Batch Campaign %s.%s'", ",", "$", "namePrefix", ",", "strval", "(", "$", "campaign", "->", "getId", "(", ")", ")", ")", ")", ";", "// Recommendation: Set the campaign to PAUSED when creating it to stop", "// the ads from immediately serving. Set to ENABLED once you've added", "// targeting and the ads are ready to serve.", "$", "campaign", "->", "setStatus", "(", "CampaignStatus", "::", "PAUSED", ")", ";", "$", "campaign", "->", "setAdvertisingChannelType", "(", "AdvertisingChannelType", "::", "SEARCH", ")", ";", "$", "budget", "=", "new", "Budget", "(", ")", ";", "$", "budget", "->", "setBudgetId", "(", "$", "budgetId", ")", ";", "$", "campaign", "->", "setBudget", "(", "$", "budget", ")", ";", "$", "biddingStrategyConfiguration", "=", "new", "BiddingStrategyConfiguration", "(", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBiddingStrategyType", "(", "BiddingStrategyType", "::", "MANUAL_CPC", ")", ";", "// You can optionally provide a bidding scheme in place of the type.", "$", "cpcBiddingScheme", "=", "new", "ManualCpcBiddingScheme", "(", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBiddingScheme", "(", "$", "cpcBiddingScheme", ")", ";", "$", "campaign", "->", "setBiddingStrategyConfiguration", "(", "$", "biddingStrategyConfiguration", ")", ";", "$", "operation", "=", "new", "CampaignOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "campaign", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operations", "[", "]", "=", "$", "operation", ";", "}", "return", "$", "operations", ";", "}" ]
Builds objects of CampaignOperation for creating a campaign using the ID of budget in the specified budget operation. @param string $namePrefix a prefix string used to name campaigns @param BudgetOperation $budgetOperation an object of BudgetOperation @return array an array of CampaignOperation
[ "Builds", "objects", "of", "CampaignOperation", "for", "creating", "a", "campaign", "using", "the", "ID", "of", "budget", "in", "the", "specified", "budget", "operation", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php#L388-L433
train
googleads/googleads-php-lib
examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php
AddCompleteCampaignsUsingBatchJob.buildBudgetOperation
private static function buildBudgetOperation($namePrefix) { $budget = new Budget(); $budget->setBudgetId(--self::$temporaryId); $budget->setName('Interplanetary Cruise #' . $namePrefix); $budgetAmount = new Money(); $budgetAmount->setMicroAmount(50000000); $budget->setAmount($budgetAmount); $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD); $budgetOperation = new BudgetOperation(); $budgetOperation->setOperand($budget); $budgetOperation->setOperator(Operator::ADD); return $budgetOperation; }
php
private static function buildBudgetOperation($namePrefix) { $budget = new Budget(); $budget->setBudgetId(--self::$temporaryId); $budget->setName('Interplanetary Cruise #' . $namePrefix); $budgetAmount = new Money(); $budgetAmount->setMicroAmount(50000000); $budget->setAmount($budgetAmount); $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD); $budgetOperation = new BudgetOperation(); $budgetOperation->setOperand($budget); $budgetOperation->setOperator(Operator::ADD); return $budgetOperation; }
[ "private", "static", "function", "buildBudgetOperation", "(", "$", "namePrefix", ")", "{", "$", "budget", "=", "new", "Budget", "(", ")", ";", "$", "budget", "->", "setBudgetId", "(", "--", "self", "::", "$", "temporaryId", ")", ";", "$", "budget", "->", "setName", "(", "'Interplanetary Cruise #'", ".", "$", "namePrefix", ")", ";", "$", "budgetAmount", "=", "new", "Money", "(", ")", ";", "$", "budgetAmount", "->", "setMicroAmount", "(", "50000000", ")", ";", "$", "budget", "->", "setAmount", "(", "$", "budgetAmount", ")", ";", "$", "budget", "->", "setDeliveryMethod", "(", "BudgetBudgetDeliveryMethod", "::", "STANDARD", ")", ";", "$", "budgetOperation", "=", "new", "BudgetOperation", "(", ")", ";", "$", "budgetOperation", "->", "setOperand", "(", "$", "budget", ")", ";", "$", "budgetOperation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "return", "$", "budgetOperation", ";", "}" ]
Builds BudgetOperation for creating a budget. @param string $namePrefix a prefix string used to name a budget @return BudgetOperation an object of BudgetOperation
[ "Builds", "BudgetOperation", "for", "creating", "a", "budget", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/CampaignManagement/AddCompleteCampaignsUsingBatchJob.php#L441-L456
train
googleads/googleads-php-lib
examples/AdWords/v201809/Remarketing/UploadOfflineData.php
UploadOfflineData.createOfflineData
private static function createOfflineData( \DateTime $transactionTime, $transactionMicroAmount, $transactionCurrency, $conversionName, array $userIdentifierList ) { $storeSalesTransaction = new StoreSalesTransaction(); // For times use the format yyyyMMdd HHmmss [tz]. // For details, see // https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats $storeSalesTransaction->setTransactionTime( $transactionTime->format('Ymd His') ); $storeSalesTransaction->setConversionName($conversionName); $storeSalesTransaction->setUserIdentifiers($userIdentifierList); $money = new Money(); $money->setMicroAmount($transactionMicroAmount); $moneyWithCurrency = new MoneyWithCurrency(); $moneyWithCurrency->setMoney($money); $moneyWithCurrency->setCurrencyCode($transactionCurrency); $storeSalesTransaction->setTransactionAmount($moneyWithCurrency); $offlineData = new OfflineData(); $offlineData->setStoreSalesTransaction($storeSalesTransaction); return $offlineData; }
php
private static function createOfflineData( \DateTime $transactionTime, $transactionMicroAmount, $transactionCurrency, $conversionName, array $userIdentifierList ) { $storeSalesTransaction = new StoreSalesTransaction(); // For times use the format yyyyMMdd HHmmss [tz]. // For details, see // https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats $storeSalesTransaction->setTransactionTime( $transactionTime->format('Ymd His') ); $storeSalesTransaction->setConversionName($conversionName); $storeSalesTransaction->setUserIdentifiers($userIdentifierList); $money = new Money(); $money->setMicroAmount($transactionMicroAmount); $moneyWithCurrency = new MoneyWithCurrency(); $moneyWithCurrency->setMoney($money); $moneyWithCurrency->setCurrencyCode($transactionCurrency); $storeSalesTransaction->setTransactionAmount($moneyWithCurrency); $offlineData = new OfflineData(); $offlineData->setStoreSalesTransaction($storeSalesTransaction); return $offlineData; }
[ "private", "static", "function", "createOfflineData", "(", "\\", "DateTime", "$", "transactionTime", ",", "$", "transactionMicroAmount", ",", "$", "transactionCurrency", ",", "$", "conversionName", ",", "array", "$", "userIdentifierList", ")", "{", "$", "storeSalesTransaction", "=", "new", "StoreSalesTransaction", "(", ")", ";", "// For times use the format yyyyMMdd HHmmss [tz].", "// For details, see", "// https://developers.google.com/adwords/api/docs/appendix/codes-formats#date-and-time-formats", "$", "storeSalesTransaction", "->", "setTransactionTime", "(", "$", "transactionTime", "->", "format", "(", "'Ymd His'", ")", ")", ";", "$", "storeSalesTransaction", "->", "setConversionName", "(", "$", "conversionName", ")", ";", "$", "storeSalesTransaction", "->", "setUserIdentifiers", "(", "$", "userIdentifierList", ")", ";", "$", "money", "=", "new", "Money", "(", ")", ";", "$", "money", "->", "setMicroAmount", "(", "$", "transactionMicroAmount", ")", ";", "$", "moneyWithCurrency", "=", "new", "MoneyWithCurrency", "(", ")", ";", "$", "moneyWithCurrency", "->", "setMoney", "(", "$", "money", ")", ";", "$", "moneyWithCurrency", "->", "setCurrencyCode", "(", "$", "transactionCurrency", ")", ";", "$", "storeSalesTransaction", "->", "setTransactionAmount", "(", "$", "moneyWithCurrency", ")", ";", "$", "offlineData", "=", "new", "OfflineData", "(", ")", ";", "$", "offlineData", "->", "setStoreSalesTransaction", "(", "$", "storeSalesTransaction", ")", ";", "return", "$", "offlineData", ";", "}" ]
Creates the offline data from the specified transaction time, transaction micro amount, transaction currency, conversion name and user identifier list.
[ "Creates", "the", "offline", "data", "from", "the", "specified", "transaction", "time", "transaction", "micro", "amount", "transaction", "currency", "conversion", "name", "and", "user", "identifier", "list", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Remarketing/UploadOfflineData.php#L240-L269
train
googleads/googleads-php-lib
examples/AdWords/v201809/Remarketing/UploadOfflineData.php
UploadOfflineData.createUserIdentifier
private static function createUserIdentifier($type, $value) { // If the user identifier type is a hashed type, normalize and hash the // value. if (0 === strpos($type, 'HASHED_')) { $value = hash('sha256', strtolower(trim($value))); } $userIdentifier = new UserIdentifier(); $userIdentifier->setUserIdentifierType($type); $userIdentifier->setValue($value); return $userIdentifier; }
php
private static function createUserIdentifier($type, $value) { // If the user identifier type is a hashed type, normalize and hash the // value. if (0 === strpos($type, 'HASHED_')) { $value = hash('sha256', strtolower(trim($value))); } $userIdentifier = new UserIdentifier(); $userIdentifier->setUserIdentifierType($type); $userIdentifier->setValue($value); return $userIdentifier; }
[ "private", "static", "function", "createUserIdentifier", "(", "$", "type", ",", "$", "value", ")", "{", "// If the user identifier type is a hashed type, normalize and hash the", "// value.", "if", "(", "0", "===", "strpos", "(", "$", "type", ",", "'HASHED_'", ")", ")", "{", "$", "value", "=", "hash", "(", "'sha256'", ",", "strtolower", "(", "trim", "(", "$", "value", ")", ")", ")", ";", "}", "$", "userIdentifier", "=", "new", "UserIdentifier", "(", ")", ";", "$", "userIdentifier", "->", "setUserIdentifierType", "(", "$", "type", ")", ";", "$", "userIdentifier", "->", "setValue", "(", "$", "value", ")", ";", "return", "$", "userIdentifier", ";", "}" ]
Creates a user identifier from the specified type and value.
[ "Creates", "a", "user", "identifier", "from", "the", "specified", "type", "and", "value", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/Remarketing/UploadOfflineData.php#L274-L286
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/UsePortfolioBiddingStrategy.php
UsePortfolioBiddingStrategy.createBiddingStrategy
private static function createBiddingStrategy( AdWordsServices $adWordsServices, AdWordsSession $session ) { $biddingStrategyService = $adWordsServices->get($session, BiddingStrategyService::class); // Create a portfolio bidding strategy. $biddingStrategy = new SharedBiddingStrategy(); $biddingStrategy->setName("Maximize Clicks " . uniqid()); $biddingScheme = new TargetSpendBiddingScheme(); // Optionally set additional bidding scheme parameters. $bidCeiling = new Money(); $bidCeiling->setMicroAmount(2000000); $biddingScheme->setBidCeiling($bidCeiling); $spendTarget = new Money(); $spendTarget->setMicroAmount(20000000); $biddingScheme->setSpendTarget($spendTarget); $biddingStrategy->setBiddingScheme($biddingScheme); // Create the bidding strategy operation. $operation = new BiddingStrategyOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($biddingStrategy); $result = $biddingStrategyService->mutate([$operation]); $newBiddingStrategy = $result->getValue()[0]; printf( "Portfolio bidding strategy with name '%s' and ID %d of type %s was created.\n", $newBiddingStrategy->getName(), $newBiddingStrategy->getId(), $newBiddingStrategy->getType() ); return $newBiddingStrategy; }
php
private static function createBiddingStrategy( AdWordsServices $adWordsServices, AdWordsSession $session ) { $biddingStrategyService = $adWordsServices->get($session, BiddingStrategyService::class); // Create a portfolio bidding strategy. $biddingStrategy = new SharedBiddingStrategy(); $biddingStrategy->setName("Maximize Clicks " . uniqid()); $biddingScheme = new TargetSpendBiddingScheme(); // Optionally set additional bidding scheme parameters. $bidCeiling = new Money(); $bidCeiling->setMicroAmount(2000000); $biddingScheme->setBidCeiling($bidCeiling); $spendTarget = new Money(); $spendTarget->setMicroAmount(20000000); $biddingScheme->setSpendTarget($spendTarget); $biddingStrategy->setBiddingScheme($biddingScheme); // Create the bidding strategy operation. $operation = new BiddingStrategyOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($biddingStrategy); $result = $biddingStrategyService->mutate([$operation]); $newBiddingStrategy = $result->getValue()[0]; printf( "Portfolio bidding strategy with name '%s' and ID %d of type %s was created.\n", $newBiddingStrategy->getName(), $newBiddingStrategy->getId(), $newBiddingStrategy->getType() ); return $newBiddingStrategy; }
[ "private", "static", "function", "createBiddingStrategy", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ")", "{", "$", "biddingStrategyService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "BiddingStrategyService", "::", "class", ")", ";", "// Create a portfolio bidding strategy.", "$", "biddingStrategy", "=", "new", "SharedBiddingStrategy", "(", ")", ";", "$", "biddingStrategy", "->", "setName", "(", "\"Maximize Clicks \"", ".", "uniqid", "(", ")", ")", ";", "$", "biddingScheme", "=", "new", "TargetSpendBiddingScheme", "(", ")", ";", "// Optionally set additional bidding scheme parameters.", "$", "bidCeiling", "=", "new", "Money", "(", ")", ";", "$", "bidCeiling", "->", "setMicroAmount", "(", "2000000", ")", ";", "$", "biddingScheme", "->", "setBidCeiling", "(", "$", "bidCeiling", ")", ";", "$", "spendTarget", "=", "new", "Money", "(", ")", ";", "$", "spendTarget", "->", "setMicroAmount", "(", "20000000", ")", ";", "$", "biddingScheme", "->", "setSpendTarget", "(", "$", "spendTarget", ")", ";", "$", "biddingStrategy", "->", "setBiddingScheme", "(", "$", "biddingScheme", ")", ";", "// Create the bidding strategy operation.", "$", "operation", "=", "new", "BiddingStrategyOperation", "(", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "biddingStrategy", ")", ";", "$", "result", "=", "$", "biddingStrategyService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "newBiddingStrategy", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Portfolio bidding strategy with name '%s' and ID %d of type %s was created.\\n\"", ",", "$", "newBiddingStrategy", "->", "getName", "(", ")", ",", "$", "newBiddingStrategy", "->", "getId", "(", ")", ",", "$", "newBiddingStrategy", "->", "getType", "(", ")", ")", ";", "return", "$", "newBiddingStrategy", ";", "}" ]
Creates a shared bidding strategy.
[ "Creates", "a", "shared", "bidding", "strategy", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/UsePortfolioBiddingStrategy.php#L76-L112
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/UsePortfolioBiddingStrategy.php
UsePortfolioBiddingStrategy.createCampaignWithBiddingStrategy
private static function createCampaignWithBiddingStrategy( AdWordsServices $adWordsServices, AdWordsSession $session, $biddingStrategyId, $sharedBudgetId ) { $campaignService = $adWordsServices->get($session, CampaignService::class); // Create campaign with some properties set. $campaign = new Campaign(); $campaign->setName('Interplanetary Cruise #' . uniqid()); // Set the budget. $campaign->setBudget(new Budget()); $campaign->getBudget()->setBudgetId($sharedBudgetId); $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH); // Set the campaign's bidding strategy. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyId($biddingStrategyId); $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration); // Set network targeting (recommended). $networkSetting = new NetworkSetting(); $networkSetting->setTargetGoogleSearch(true); $networkSetting->setTargetSearchNetwork(true); $networkSetting->setTargetContentNetwork(true); $campaign->setNetworkSetting($networkSetting); // Recommendation: Set the campaign to PAUSED when creating it to stop // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); // Create a campaign operation. $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); // Create the campaign on the server and print out some information for the // campaign. $result = $campaignService->mutate([$operation]); $newCampaign = $result->getValue()[0]; printf( "Campaign with name '%s', ID %d and bidding scheme ID %d was created.\n", $newCampaign->getName(), $newCampaign->getId(), $newCampaign->getBiddingStrategyConfiguration()->getBiddingStrategyId() ); }
php
private static function createCampaignWithBiddingStrategy( AdWordsServices $adWordsServices, AdWordsSession $session, $biddingStrategyId, $sharedBudgetId ) { $campaignService = $adWordsServices->get($session, CampaignService::class); // Create campaign with some properties set. $campaign = new Campaign(); $campaign->setName('Interplanetary Cruise #' . uniqid()); // Set the budget. $campaign->setBudget(new Budget()); $campaign->getBudget()->setBudgetId($sharedBudgetId); $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH); // Set the campaign's bidding strategy. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyId($biddingStrategyId); $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration); // Set network targeting (recommended). $networkSetting = new NetworkSetting(); $networkSetting->setTargetGoogleSearch(true); $networkSetting->setTargetSearchNetwork(true); $networkSetting->setTargetContentNetwork(true); $campaign->setNetworkSetting($networkSetting); // Recommendation: Set the campaign to PAUSED when creating it to stop // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); // Create a campaign operation. $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); // Create the campaign on the server and print out some information for the // campaign. $result = $campaignService->mutate([$operation]); $newCampaign = $result->getValue()[0]; printf( "Campaign with name '%s', ID %d and bidding scheme ID %d was created.\n", $newCampaign->getName(), $newCampaign->getId(), $newCampaign->getBiddingStrategyConfiguration()->getBiddingStrategyId() ); }
[ "private", "static", "function", "createCampaignWithBiddingStrategy", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "$", "biddingStrategyId", ",", "$", "sharedBudgetId", ")", "{", "$", "campaignService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "CampaignService", "::", "class", ")", ";", "// Create campaign with some properties set.", "$", "campaign", "=", "new", "Campaign", "(", ")", ";", "$", "campaign", "->", "setName", "(", "'Interplanetary Cruise #'", ".", "uniqid", "(", ")", ")", ";", "// Set the budget.", "$", "campaign", "->", "setBudget", "(", "new", "Budget", "(", ")", ")", ";", "$", "campaign", "->", "getBudget", "(", ")", "->", "setBudgetId", "(", "$", "sharedBudgetId", ")", ";", "$", "campaign", "->", "setAdvertisingChannelType", "(", "AdvertisingChannelType", "::", "SEARCH", ")", ";", "// Set the campaign's bidding strategy.", "$", "biddingStrategyConfiguration", "=", "new", "BiddingStrategyConfiguration", "(", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBiddingStrategyId", "(", "$", "biddingStrategyId", ")", ";", "$", "campaign", "->", "setBiddingStrategyConfiguration", "(", "$", "biddingStrategyConfiguration", ")", ";", "// Set network targeting (recommended).", "$", "networkSetting", "=", "new", "NetworkSetting", "(", ")", ";", "$", "networkSetting", "->", "setTargetGoogleSearch", "(", "true", ")", ";", "$", "networkSetting", "->", "setTargetSearchNetwork", "(", "true", ")", ";", "$", "networkSetting", "->", "setTargetContentNetwork", "(", "true", ")", ";", "$", "campaign", "->", "setNetworkSetting", "(", "$", "networkSetting", ")", ";", "// Recommendation: Set the campaign to PAUSED when creating it to stop", "// the ads from immediately serving. Set to ENABLED once you've added", "// targeting and the ads are ready to serve.", "$", "campaign", "->", "setStatus", "(", "CampaignStatus", "::", "PAUSED", ")", ";", "// Create a campaign operation.", "$", "operation", "=", "new", "CampaignOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "campaign", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the campaign on the server and print out some information for the", "// campaign.", "$", "result", "=", "$", "campaignService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "newCampaign", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Campaign with name '%s', ID %d and bidding scheme ID %d was created.\\n\"", ",", "$", "newCampaign", "->", "getName", "(", ")", ",", "$", "newCampaign", "->", "getId", "(", ")", ",", "$", "newCampaign", "->", "getBiddingStrategyConfiguration", "(", ")", "->", "getBiddingStrategyId", "(", ")", ")", ";", "}" ]
Create a campaign with a portfolio bidding strategy.
[ "Create", "a", "campaign", "with", "a", "portfolio", "bidding", "strategy", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/UsePortfolioBiddingStrategy.php#L149-L199
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/AdWordsHeaderHandler.php
AdWordsHeaderHandler.createSoapHeaderObject
private function createSoapHeaderObject( AdsServiceDescriptor $serviceDescriptor ) { // The SOAP header object is in the same base namespace (without the group) // as the AdWords service we are generating headers for. $reflectionClass = new ReflectionClass($serviceDescriptor->getServiceClass()); $namespaceParts = explode('\\', trim($reflectionClass->getNamespaceName(), '\\')); // Remove the group. array_pop($namespaceParts); $soapHeaderClassName = sprintf( '%s\\%s', implode('\\', $namespaceParts), self::DEFAULT_SOAP_HEADER_CLASS_NAME ); return $this->reflection->createInstance($soapHeaderClassName); }
php
private function createSoapHeaderObject( AdsServiceDescriptor $serviceDescriptor ) { // The SOAP header object is in the same base namespace (without the group) // as the AdWords service we are generating headers for. $reflectionClass = new ReflectionClass($serviceDescriptor->getServiceClass()); $namespaceParts = explode('\\', trim($reflectionClass->getNamespaceName(), '\\')); // Remove the group. array_pop($namespaceParts); $soapHeaderClassName = sprintf( '%s\\%s', implode('\\', $namespaceParts), self::DEFAULT_SOAP_HEADER_CLASS_NAME ); return $this->reflection->createInstance($soapHeaderClassName); }
[ "private", "function", "createSoapHeaderObject", "(", "AdsServiceDescriptor", "$", "serviceDescriptor", ")", "{", "// The SOAP header object is in the same base namespace (without the group)", "// as the AdWords service we are generating headers for.", "$", "reflectionClass", "=", "new", "ReflectionClass", "(", "$", "serviceDescriptor", "->", "getServiceClass", "(", ")", ")", ";", "$", "namespaceParts", "=", "explode", "(", "'\\\\'", ",", "trim", "(", "$", "reflectionClass", "->", "getNamespaceName", "(", ")", ",", "'\\\\'", ")", ")", ";", "// Remove the group.", "array_pop", "(", "$", "namespaceParts", ")", ";", "$", "soapHeaderClassName", "=", "sprintf", "(", "'%s\\\\%s'", ",", "implode", "(", "'\\\\'", ",", "$", "namespaceParts", ")", ",", "self", "::", "DEFAULT_SOAP_HEADER_CLASS_NAME", ")", ";", "return", "$", "this", "->", "reflection", "->", "createInstance", "(", "$", "soapHeaderClassName", ")", ";", "}" ]
Creates a new instance of the SOAP header object used by the AdWords API.
[ "Creates", "a", "new", "instance", "of", "the", "SOAP", "header", "object", "used", "by", "the", "AdWords", "API", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/AdWordsHeaderHandler.php#L111-L129
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php
AddDynamicSearchAdsCampaign.createBudget
private static function createBudget( AdWordsServices $adWordsServices, AdWordsSession $session ) { $budgetService = $adWordsServices->get($session, BudgetService::class); // Create a budget, which can be shared by multiple campaigns. $sharedBudget = new Budget(); $sharedBudget->setName('Interplanetary Cruise #' . uniqid()); $money = new Money(); $money->setMicroAmount(50000000); $sharedBudget->setAmount($money); $sharedBudget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD); // Create a budget operation. $operation = new BudgetOperation(); $operation->setOperand($sharedBudget); $operation->setOperator(Operator::ADD); // Create the budget on the server. $result = $budgetService->mutate([$operation]); $sharedBudget = $result->getValue()[0]; return $sharedBudget; }
php
private static function createBudget( AdWordsServices $adWordsServices, AdWordsSession $session ) { $budgetService = $adWordsServices->get($session, BudgetService::class); // Create a budget, which can be shared by multiple campaigns. $sharedBudget = new Budget(); $sharedBudget->setName('Interplanetary Cruise #' . uniqid()); $money = new Money(); $money->setMicroAmount(50000000); $sharedBudget->setAmount($money); $sharedBudget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD); // Create a budget operation. $operation = new BudgetOperation(); $operation->setOperand($sharedBudget); $operation->setOperator(Operator::ADD); // Create the budget on the server. $result = $budgetService->mutate([$operation]); $sharedBudget = $result->getValue()[0]; return $sharedBudget; }
[ "private", "static", "function", "createBudget", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ")", "{", "$", "budgetService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "BudgetService", "::", "class", ")", ";", "// Create a budget, which can be shared by multiple campaigns.", "$", "sharedBudget", "=", "new", "Budget", "(", ")", ";", "$", "sharedBudget", "->", "setName", "(", "'Interplanetary Cruise #'", ".", "uniqid", "(", ")", ")", ";", "$", "money", "=", "new", "Money", "(", ")", ";", "$", "money", "->", "setMicroAmount", "(", "50000000", ")", ";", "$", "sharedBudget", "->", "setAmount", "(", "$", "money", ")", ";", "$", "sharedBudget", "->", "setDeliveryMethod", "(", "BudgetBudgetDeliveryMethod", "::", "STANDARD", ")", ";", "// Create a budget operation.", "$", "operation", "=", "new", "BudgetOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "sharedBudget", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the budget on the server.", "$", "result", "=", "$", "budgetService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "sharedBudget", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "return", "$", "sharedBudget", ";", "}" ]
Creates the budget.
[ "Creates", "the", "budget", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php#L82-L106
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php
AddDynamicSearchAdsCampaign.createCampaign
private static function createCampaign( AdWordsServices $adWordsServices, AdWordsSession $session, Budget $budget ) { $campaignService = $adWordsServices->get($session, CampaignService::class); // Create campaign with some properties set. $campaign = new Campaign(); $campaign->setName('Interplanetary Cruise #' . uniqid()); $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH); // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyType( BiddingStrategyType::MANUAL_CPC ); $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration); // Only the budgetId should be sent, all other fields will be ignored by // CampaignService. $campaignBudget = new Budget(); $campaignBudget->setBudgetId($budget->getBudgetId()); $campaign->setBudget($campaignBudget); // Required: Set the campaign's Dynamic Search Ads settings. $dynamicSearchAdsSetting = new DynamicSearchAdsSetting(); // Required: Set the domain name and language. $dynamicSearchAdsSetting->setDomainName('example.com'); $dynamicSearchAdsSetting->setLanguageCode('en'); // Set the campaign settings. $campaign->setSettings([$dynamicSearchAdsSetting]); // Optional: Set the start date. $campaign->setStartDate(date('Ymd', strtotime('+1 day'))); // Optional: Set the end date. $campaign->setEndDate(date('Ymd', strtotime('+1 year'))); // Create a campaign operation. $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); // Create the campaign on the server and print out some information. $result = $campaignService->mutate([$operation]); $campaign = $result->getValue()[0]; printf( "Campaign with name '%s' and ID %d was added.\n", $campaign->getName(), $campaign->getId() ); return $campaign; }
php
private static function createCampaign( AdWordsServices $adWordsServices, AdWordsSession $session, Budget $budget ) { $campaignService = $adWordsServices->get($session, CampaignService::class); // Create campaign with some properties set. $campaign = new Campaign(); $campaign->setName('Interplanetary Cruise #' . uniqid()); $campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH); // Recommendation: Set the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENABLED once you've added // targeting and the ads are ready to serve. $campaign->setStatus(CampaignStatus::PAUSED); $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $biddingStrategyConfiguration->setBiddingStrategyType( BiddingStrategyType::MANUAL_CPC ); $campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration); // Only the budgetId should be sent, all other fields will be ignored by // CampaignService. $campaignBudget = new Budget(); $campaignBudget->setBudgetId($budget->getBudgetId()); $campaign->setBudget($campaignBudget); // Required: Set the campaign's Dynamic Search Ads settings. $dynamicSearchAdsSetting = new DynamicSearchAdsSetting(); // Required: Set the domain name and language. $dynamicSearchAdsSetting->setDomainName('example.com'); $dynamicSearchAdsSetting->setLanguageCode('en'); // Set the campaign settings. $campaign->setSettings([$dynamicSearchAdsSetting]); // Optional: Set the start date. $campaign->setStartDate(date('Ymd', strtotime('+1 day'))); // Optional: Set the end date. $campaign->setEndDate(date('Ymd', strtotime('+1 year'))); // Create a campaign operation. $operation = new CampaignOperation(); $operation->setOperand($campaign); $operation->setOperator(Operator::ADD); // Create the campaign on the server and print out some information. $result = $campaignService->mutate([$operation]); $campaign = $result->getValue()[0]; printf( "Campaign with name '%s' and ID %d was added.\n", $campaign->getName(), $campaign->getId() ); return $campaign; }
[ "private", "static", "function", "createCampaign", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "Budget", "$", "budget", ")", "{", "$", "campaignService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "CampaignService", "::", "class", ")", ";", "// Create campaign with some properties set.", "$", "campaign", "=", "new", "Campaign", "(", ")", ";", "$", "campaign", "->", "setName", "(", "'Interplanetary Cruise #'", ".", "uniqid", "(", ")", ")", ";", "$", "campaign", "->", "setAdvertisingChannelType", "(", "AdvertisingChannelType", "::", "SEARCH", ")", ";", "// Recommendation: Set the campaign to PAUSED when creating it to prevent", "// the ads from immediately serving. Set to ENABLED once you've added", "// targeting and the ads are ready to serve.", "$", "campaign", "->", "setStatus", "(", "CampaignStatus", "::", "PAUSED", ")", ";", "$", "biddingStrategyConfiguration", "=", "new", "BiddingStrategyConfiguration", "(", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBiddingStrategyType", "(", "BiddingStrategyType", "::", "MANUAL_CPC", ")", ";", "$", "campaign", "->", "setBiddingStrategyConfiguration", "(", "$", "biddingStrategyConfiguration", ")", ";", "// Only the budgetId should be sent, all other fields will be ignored by", "// CampaignService.", "$", "campaignBudget", "=", "new", "Budget", "(", ")", ";", "$", "campaignBudget", "->", "setBudgetId", "(", "$", "budget", "->", "getBudgetId", "(", ")", ")", ";", "$", "campaign", "->", "setBudget", "(", "$", "campaignBudget", ")", ";", "// Required: Set the campaign's Dynamic Search Ads settings.", "$", "dynamicSearchAdsSetting", "=", "new", "DynamicSearchAdsSetting", "(", ")", ";", "// Required: Set the domain name and language.", "$", "dynamicSearchAdsSetting", "->", "setDomainName", "(", "'example.com'", ")", ";", "$", "dynamicSearchAdsSetting", "->", "setLanguageCode", "(", "'en'", ")", ";", "// Set the campaign settings.", "$", "campaign", "->", "setSettings", "(", "[", "$", "dynamicSearchAdsSetting", "]", ")", ";", "// Optional: Set the start date.", "$", "campaign", "->", "setStartDate", "(", "date", "(", "'Ymd'", ",", "strtotime", "(", "'+1 day'", ")", ")", ")", ";", "// Optional: Set the end date.", "$", "campaign", "->", "setEndDate", "(", "date", "(", "'Ymd'", ",", "strtotime", "(", "'+1 year'", ")", ")", ")", ";", "// Create a campaign operation.", "$", "operation", "=", "new", "CampaignOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "campaign", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the campaign on the server and print out some information.", "$", "result", "=", "$", "campaignService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "campaign", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Campaign with name '%s' and ID %d was added.\\n\"", ",", "$", "campaign", "->", "getName", "(", ")", ",", "$", "campaign", "->", "getId", "(", ")", ")", ";", "return", "$", "campaign", ";", "}" ]
Creates the campaign.
[ "Creates", "the", "campaign", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php#L111-L169
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php
AddDynamicSearchAdsCampaign.createAdGroup
private static function createAdGroup( AdWordsServices $adWordsServices, AdWordsSession $session, Campaign $campaign ) { $adGroupService = $adWordsServices->get($session, AdGroupService::class); // Create the ad group. $adGroup = new AdGroup(); // Required: Set the ad group's type to Dynamic Search Ads. $adGroup->setAdGroupType(AdGroupType::SEARCH_DYNAMIC_ADS); $adGroup->setName('Interplanetary Cruise #' . uniqid()); $adGroup->setCampaignId($campaign->getId()); $adGroup->setStatus(AdGroupStatus::PAUSED); // Recommended: Set a tracking URL template for your ad group if you want to // use URL tracking software. $adGroup->setTrackingUrlTemplate( 'http://tracker.example.com/traveltracker/{escapedlpurl}' ); // Set the ad group bids. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $cpcBid = new CpcBid(); $money = new Money(); $money->setMicroAmount(3000000); $cpcBid->setBid($money); $biddingStrategyConfiguration->setBids([$cpcBid]); $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration); // Create an ad group operation. $operation = new AdGroupOperation(); $operation->setOperand($adGroup); $operation->setOperator(Operator::ADD); // Create the ad group on the server and print out some information. $result = $adGroupService->mutate([$operation]); $adGroup = $result->getValue()[0]; printf( "Ad group with name '%s' and ID %d was added.\n", $adGroup->getName(), $adGroup->getId() ); return $adGroup; }
php
private static function createAdGroup( AdWordsServices $adWordsServices, AdWordsSession $session, Campaign $campaign ) { $adGroupService = $adWordsServices->get($session, AdGroupService::class); // Create the ad group. $adGroup = new AdGroup(); // Required: Set the ad group's type to Dynamic Search Ads. $adGroup->setAdGroupType(AdGroupType::SEARCH_DYNAMIC_ADS); $adGroup->setName('Interplanetary Cruise #' . uniqid()); $adGroup->setCampaignId($campaign->getId()); $adGroup->setStatus(AdGroupStatus::PAUSED); // Recommended: Set a tracking URL template for your ad group if you want to // use URL tracking software. $adGroup->setTrackingUrlTemplate( 'http://tracker.example.com/traveltracker/{escapedlpurl}' ); // Set the ad group bids. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); $cpcBid = new CpcBid(); $money = new Money(); $money->setMicroAmount(3000000); $cpcBid->setBid($money); $biddingStrategyConfiguration->setBids([$cpcBid]); $adGroup->setBiddingStrategyConfiguration($biddingStrategyConfiguration); // Create an ad group operation. $operation = new AdGroupOperation(); $operation->setOperand($adGroup); $operation->setOperator(Operator::ADD); // Create the ad group on the server and print out some information. $result = $adGroupService->mutate([$operation]); $adGroup = $result->getValue()[0]; printf( "Ad group with name '%s' and ID %d was added.\n", $adGroup->getName(), $adGroup->getId() ); return $adGroup; }
[ "private", "static", "function", "createAdGroup", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "Campaign", "$", "campaign", ")", "{", "$", "adGroupService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "AdGroupService", "::", "class", ")", ";", "// Create the ad group.", "$", "adGroup", "=", "new", "AdGroup", "(", ")", ";", "// Required: Set the ad group's type to Dynamic Search Ads.", "$", "adGroup", "->", "setAdGroupType", "(", "AdGroupType", "::", "SEARCH_DYNAMIC_ADS", ")", ";", "$", "adGroup", "->", "setName", "(", "'Interplanetary Cruise #'", ".", "uniqid", "(", ")", ")", ";", "$", "adGroup", "->", "setCampaignId", "(", "$", "campaign", "->", "getId", "(", ")", ")", ";", "$", "adGroup", "->", "setStatus", "(", "AdGroupStatus", "::", "PAUSED", ")", ";", "// Recommended: Set a tracking URL template for your ad group if you want to", "// use URL tracking software.", "$", "adGroup", "->", "setTrackingUrlTemplate", "(", "'http://tracker.example.com/traveltracker/{escapedlpurl}'", ")", ";", "// Set the ad group bids.", "$", "biddingStrategyConfiguration", "=", "new", "BiddingStrategyConfiguration", "(", ")", ";", "$", "cpcBid", "=", "new", "CpcBid", "(", ")", ";", "$", "money", "=", "new", "Money", "(", ")", ";", "$", "money", "->", "setMicroAmount", "(", "3000000", ")", ";", "$", "cpcBid", "->", "setBid", "(", "$", "money", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBids", "(", "[", "$", "cpcBid", "]", ")", ";", "$", "adGroup", "->", "setBiddingStrategyConfiguration", "(", "$", "biddingStrategyConfiguration", ")", ";", "// Create an ad group operation.", "$", "operation", "=", "new", "AdGroupOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "adGroup", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the ad group on the server and print out some information.", "$", "result", "=", "$", "adGroupService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "adGroup", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Ad group with name '%s' and ID %d was added.\\n\"", ",", "$", "adGroup", "->", "getName", "(", ")", ",", "$", "adGroup", "->", "getId", "(", ")", ")", ";", "return", "$", "adGroup", ";", "}" ]
Creates the ad group.
[ "Creates", "the", "ad", "group", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php#L174-L223
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php
AddDynamicSearchAdsCampaign.createExpandedDSA
private static function createExpandedDSA( AdWordsServices $adWordsServices, AdWordsSession $session, AdGroup $adGroup ) { $adGroupAdService = $adWordsServices->get($session, AdGroupAdService::class); // Create the expanded Dynamic Search Ad. This ad will have its headline // and final URL auto-generated at serving time according to domain name // specific information provided by DynamicSearchAdsSetting at the // campaign level. $expandedDSA = new ExpandedDynamicSearchAd(); // Set the ad description. $expandedDSA->setDescription('Buy your tickets now!'); $expandedDSA->setDescription2('Discount ends soon'); // Create the ad group ad. $adGroupAd = new AdGroupAd(); $adGroupAd->setAdGroupId($adGroup->getId()); $adGroupAd->setAd($expandedDSA); // Optional: Set the status. $adGroupAd->setStatus(AdGroupAdStatus::PAUSED); // Create the operation. $operation = new AdGroupAdOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($adGroupAd); // Create the ad on the server and print some information. $result = $adGroupAdService->mutate([$operation]); $newAdGroupAd = $result->getValue()[0]; $expandedDSA = $newAdGroupAd->getAd(); printf( "Expanded Dynamic Search Ad with ID %d, description '%s', and" . " description 2 '%s' was added.%s", $expandedDSA->getId(), $expandedDSA->getDescription(), $expandedDSA->getDescription2(), PHP_EOL ); }
php
private static function createExpandedDSA( AdWordsServices $adWordsServices, AdWordsSession $session, AdGroup $adGroup ) { $adGroupAdService = $adWordsServices->get($session, AdGroupAdService::class); // Create the expanded Dynamic Search Ad. This ad will have its headline // and final URL auto-generated at serving time according to domain name // specific information provided by DynamicSearchAdsSetting at the // campaign level. $expandedDSA = new ExpandedDynamicSearchAd(); // Set the ad description. $expandedDSA->setDescription('Buy your tickets now!'); $expandedDSA->setDescription2('Discount ends soon'); // Create the ad group ad. $adGroupAd = new AdGroupAd(); $adGroupAd->setAdGroupId($adGroup->getId()); $adGroupAd->setAd($expandedDSA); // Optional: Set the status. $adGroupAd->setStatus(AdGroupAdStatus::PAUSED); // Create the operation. $operation = new AdGroupAdOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($adGroupAd); // Create the ad on the server and print some information. $result = $adGroupAdService->mutate([$operation]); $newAdGroupAd = $result->getValue()[0]; $expandedDSA = $newAdGroupAd->getAd(); printf( "Expanded Dynamic Search Ad with ID %d, description '%s', and" . " description 2 '%s' was added.%s", $expandedDSA->getId(), $expandedDSA->getDescription(), $expandedDSA->getDescription2(), PHP_EOL ); }
[ "private", "static", "function", "createExpandedDSA", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "AdGroup", "$", "adGroup", ")", "{", "$", "adGroupAdService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "AdGroupAdService", "::", "class", ")", ";", "// Create the expanded Dynamic Search Ad. This ad will have its headline", "// and final URL auto-generated at serving time according to domain name", "// specific information provided by DynamicSearchAdsSetting at the", "// campaign level.", "$", "expandedDSA", "=", "new", "ExpandedDynamicSearchAd", "(", ")", ";", "// Set the ad description.", "$", "expandedDSA", "->", "setDescription", "(", "'Buy your tickets now!'", ")", ";", "$", "expandedDSA", "->", "setDescription2", "(", "'Discount ends soon'", ")", ";", "// Create the ad group ad.", "$", "adGroupAd", "=", "new", "AdGroupAd", "(", ")", ";", "$", "adGroupAd", "->", "setAdGroupId", "(", "$", "adGroup", "->", "getId", "(", ")", ")", ";", "$", "adGroupAd", "->", "setAd", "(", "$", "expandedDSA", ")", ";", "// Optional: Set the status.", "$", "adGroupAd", "->", "setStatus", "(", "AdGroupAdStatus", "::", "PAUSED", ")", ";", "// Create the operation.", "$", "operation", "=", "new", "AdGroupAdOperation", "(", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "adGroupAd", ")", ";", "// Create the ad on the server and print some information.", "$", "result", "=", "$", "adGroupAdService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "newAdGroupAd", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "$", "expandedDSA", "=", "$", "newAdGroupAd", "->", "getAd", "(", ")", ";", "printf", "(", "\"Expanded Dynamic Search Ad with ID %d, description '%s', and\"", ".", "\" description 2 '%s' was added.%s\"", ",", "$", "expandedDSA", "->", "getId", "(", ")", ",", "$", "expandedDSA", "->", "getDescription", "(", ")", ",", "$", "expandedDSA", "->", "getDescription2", "(", ")", ",", "PHP_EOL", ")", ";", "}" ]
Creates the expanded Dynamic Search Ad.
[ "Creates", "the", "expanded", "Dynamic", "Search", "Ad", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php#L228-L269
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php
AddDynamicSearchAdsCampaign.addWebPageCriteria
private static function addWebPageCriteria( AdWordsServices $adWordsServices, AdWordsSession $session, AdGroup $adGroup ) { $adGroupCriterionService = $adWordsServices->get($session, AdGroupCriterionService::class); // Create a webpage criterion for special offers. $param = new WebpageParameter(); $param->setCriterionName('Special offers'); // Create a webpage criterion for special offers. $urlCondition = new WebpageCondition(); $urlCondition->setOperand(WebpageConditionOperand::URL); $urlCondition->setArgument('/specialoffers'); $titleCondition = new WebpageCondition(); $titleCondition->setOperand(WebpageConditionOperand::PAGE_TITLE); $titleCondition->setArgument('Special Offer'); $param->setConditions([$urlCondition, $titleCondition]); $webpage = new Webpage(); $webpage->setParameter($param); // Create a biddable ad group criterion. $biddableAdGroupCriterion = new BiddableAdGroupCriterion(); $biddableAdGroupCriterion->setAdGroupId($adGroup->getId()); $biddableAdGroupCriterion->setCriterion($webpage); $biddableAdGroupCriterion->setUserStatus(UserStatus::PAUSED); // Set a custom bid for this criterion. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); // Optional: set a custom bid. $cpcBid = new CpcBid(); $money = new Money(); $money->setMicroAmount(10000000); $cpcBid->setBid($money); $biddingStrategyConfiguration->setBids([$cpcBid]); $biddableAdGroupCriterion->setBiddingStrategyConfiguration( $biddingStrategyConfiguration ); $operation = new AdGroupCriterionOperation(); $operation->setOperand($biddableAdGroupCriterion); $operation->setOperator(Operator::ADD); // Create the criterion on the server and print out some information. $result = $adGroupCriterionService->mutate([$operation]); $adGroupCriterion = $result->getValue()[0]; printf( "Web page criterion with ID %d was added to ad group ID %d.\n", $adGroupCriterion->getCriterion()->getId(), $adGroupCriterion->getAdGroupId() ); }
php
private static function addWebPageCriteria( AdWordsServices $adWordsServices, AdWordsSession $session, AdGroup $adGroup ) { $adGroupCriterionService = $adWordsServices->get($session, AdGroupCriterionService::class); // Create a webpage criterion for special offers. $param = new WebpageParameter(); $param->setCriterionName('Special offers'); // Create a webpage criterion for special offers. $urlCondition = new WebpageCondition(); $urlCondition->setOperand(WebpageConditionOperand::URL); $urlCondition->setArgument('/specialoffers'); $titleCondition = new WebpageCondition(); $titleCondition->setOperand(WebpageConditionOperand::PAGE_TITLE); $titleCondition->setArgument('Special Offer'); $param->setConditions([$urlCondition, $titleCondition]); $webpage = new Webpage(); $webpage->setParameter($param); // Create a biddable ad group criterion. $biddableAdGroupCriterion = new BiddableAdGroupCriterion(); $biddableAdGroupCriterion->setAdGroupId($adGroup->getId()); $biddableAdGroupCriterion->setCriterion($webpage); $biddableAdGroupCriterion->setUserStatus(UserStatus::PAUSED); // Set a custom bid for this criterion. $biddingStrategyConfiguration = new BiddingStrategyConfiguration(); // Optional: set a custom bid. $cpcBid = new CpcBid(); $money = new Money(); $money->setMicroAmount(10000000); $cpcBid->setBid($money); $biddingStrategyConfiguration->setBids([$cpcBid]); $biddableAdGroupCriterion->setBiddingStrategyConfiguration( $biddingStrategyConfiguration ); $operation = new AdGroupCriterionOperation(); $operation->setOperand($biddableAdGroupCriterion); $operation->setOperator(Operator::ADD); // Create the criterion on the server and print out some information. $result = $adGroupCriterionService->mutate([$operation]); $adGroupCriterion = $result->getValue()[0]; printf( "Web page criterion with ID %d was added to ad group ID %d.\n", $adGroupCriterion->getCriterion()->getId(), $adGroupCriterion->getAdGroupId() ); }
[ "private", "static", "function", "addWebPageCriteria", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ",", "AdGroup", "$", "adGroup", ")", "{", "$", "adGroupCriterionService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "AdGroupCriterionService", "::", "class", ")", ";", "// Create a webpage criterion for special offers.", "$", "param", "=", "new", "WebpageParameter", "(", ")", ";", "$", "param", "->", "setCriterionName", "(", "'Special offers'", ")", ";", "// Create a webpage criterion for special offers.", "$", "urlCondition", "=", "new", "WebpageCondition", "(", ")", ";", "$", "urlCondition", "->", "setOperand", "(", "WebpageConditionOperand", "::", "URL", ")", ";", "$", "urlCondition", "->", "setArgument", "(", "'/specialoffers'", ")", ";", "$", "titleCondition", "=", "new", "WebpageCondition", "(", ")", ";", "$", "titleCondition", "->", "setOperand", "(", "WebpageConditionOperand", "::", "PAGE_TITLE", ")", ";", "$", "titleCondition", "->", "setArgument", "(", "'Special Offer'", ")", ";", "$", "param", "->", "setConditions", "(", "[", "$", "urlCondition", ",", "$", "titleCondition", "]", ")", ";", "$", "webpage", "=", "new", "Webpage", "(", ")", ";", "$", "webpage", "->", "setParameter", "(", "$", "param", ")", ";", "// Create a biddable ad group criterion.", "$", "biddableAdGroupCriterion", "=", "new", "BiddableAdGroupCriterion", "(", ")", ";", "$", "biddableAdGroupCriterion", "->", "setAdGroupId", "(", "$", "adGroup", "->", "getId", "(", ")", ")", ";", "$", "biddableAdGroupCriterion", "->", "setCriterion", "(", "$", "webpage", ")", ";", "$", "biddableAdGroupCriterion", "->", "setUserStatus", "(", "UserStatus", "::", "PAUSED", ")", ";", "// Set a custom bid for this criterion.", "$", "biddingStrategyConfiguration", "=", "new", "BiddingStrategyConfiguration", "(", ")", ";", "// Optional: set a custom bid.", "$", "cpcBid", "=", "new", "CpcBid", "(", ")", ";", "$", "money", "=", "new", "Money", "(", ")", ";", "$", "money", "->", "setMicroAmount", "(", "10000000", ")", ";", "$", "cpcBid", "->", "setBid", "(", "$", "money", ")", ";", "$", "biddingStrategyConfiguration", "->", "setBids", "(", "[", "$", "cpcBid", "]", ")", ";", "$", "biddableAdGroupCriterion", "->", "setBiddingStrategyConfiguration", "(", "$", "biddingStrategyConfiguration", ")", ";", "$", "operation", "=", "new", "AdGroupCriterionOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "biddableAdGroupCriterion", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "// Create the criterion on the server and print out some information.", "$", "result", "=", "$", "adGroupCriterionService", "->", "mutate", "(", "[", "$", "operation", "]", ")", ";", "$", "adGroupCriterion", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Web page criterion with ID %d was added to ad group ID %d.\\n\"", ",", "$", "adGroupCriterion", "->", "getCriterion", "(", ")", "->", "getId", "(", ")", ",", "$", "adGroupCriterion", "->", "getAdGroupId", "(", ")", ")", ";", "}" ]
Adds a web page criteria to target Dynamic Search Ads.
[ "Adds", "a", "web", "page", "criteria", "to", "target", "Dynamic", "Search", "Ads", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddDynamicSearchAdsCampaign.php#L274-L330
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/Query/v201809/ServiceQueryWhereBuilder.php
ServiceQueryWhereBuilder.createWithField
public static function createWithField( $field, ServiceQueryBuilder $queryBuilder ) { $validationResult = QueryValidator::validateFieldName($field); if ($validationResult->isFailed()) { throw new InvalidArgumentException( 'The field name for building the WHERE clause is invalid.' . ' Validation fail reason: ' . $validationResult->getFailReason() ); } return new self($queryBuilder, new ExpressionBuilder($field)); }
php
public static function createWithField( $field, ServiceQueryBuilder $queryBuilder ) { $validationResult = QueryValidator::validateFieldName($field); if ($validationResult->isFailed()) { throw new InvalidArgumentException( 'The field name for building the WHERE clause is invalid.' . ' Validation fail reason: ' . $validationResult->getFailReason() ); } return new self($queryBuilder, new ExpressionBuilder($field)); }
[ "public", "static", "function", "createWithField", "(", "$", "field", ",", "ServiceQueryBuilder", "$", "queryBuilder", ")", "{", "$", "validationResult", "=", "QueryValidator", "::", "validateFieldName", "(", "$", "field", ")", ";", "if", "(", "$", "validationResult", "->", "isFailed", "(", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The field name for building the WHERE clause is invalid.'", ".", "' Validation fail reason: '", ".", "$", "validationResult", "->", "getFailReason", "(", ")", ")", ";", "}", "return", "new", "self", "(", "$", "queryBuilder", ",", "new", "ExpressionBuilder", "(", "$", "field", ")", ")", ";", "}" ]
Creates a where builder object to start a logic expression with a field name. @param string $field name of the field to be used as the left-hand operand of a logic expression @param ServiceQueryBuilder $queryBuilder the query builder object for continuation of building a complete AWQL string @return ServiceQueryWhereBuilder a where builder object to build a logic expression starting with the given field name
[ "Creates", "a", "where", "builder", "object", "to", "start", "a", "logic", "expression", "with", "a", "field", "name", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/Query/v201809/ServiceQueryWhereBuilder.php#L71-L84
train
googleads/googleads-php-lib
src/Google/AdsApi/Common/Util/LogMessageScrubbers.php
LogMessageScrubbers.scrubRequestHttpHeaders
public static function scrubRequestHttpHeaders( $httpHeaders, array $headersToScrub ) { foreach ($headersToScrub as $header) { $regex = sprintf(self::$HTTP_REQUEST_HEADER_REGEX, $header); $httpHeaders = preg_replace($regex, '\1' . self::$REDACTED, $httpHeaders, 1); } return $httpHeaders; }
php
public static function scrubRequestHttpHeaders( $httpHeaders, array $headersToScrub ) { foreach ($headersToScrub as $header) { $regex = sprintf(self::$HTTP_REQUEST_HEADER_REGEX, $header); $httpHeaders = preg_replace($regex, '\1' . self::$REDACTED, $httpHeaders, 1); } return $httpHeaders; }
[ "public", "static", "function", "scrubRequestHttpHeaders", "(", "$", "httpHeaders", ",", "array", "$", "headersToScrub", ")", "{", "foreach", "(", "$", "headersToScrub", "as", "$", "header", ")", "{", "$", "regex", "=", "sprintf", "(", "self", "::", "$", "HTTP_REQUEST_HEADER_REGEX", ",", "$", "header", ")", ";", "$", "httpHeaders", "=", "preg_replace", "(", "$", "regex", ",", "'\\1'", ".", "self", "::", "$", "REDACTED", ",", "$", "httpHeaders", ",", "1", ")", ";", "}", "return", "$", "httpHeaders", ";", "}" ]
Scrubs the specified header values, replacing all occurrences in the specified request HTTP headers with a redacted token. @param string $httpHeaders @param string[] $headersToScrub which HTTP headers to scrub @return string the HTTP headers with any sensitive info removed
[ "Scrubs", "the", "specified", "header", "values", "replacing", "all", "occurrences", "in", "the", "specified", "request", "HTTP", "headers", "with", "a", "redacted", "token", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/Common/Util/LogMessageScrubbers.php#L64-L74
train
googleads/googleads-php-lib
src/Google/AdsApi/Common/Util/LogMessageScrubbers.php
LogMessageScrubbers.scrubRequestSoapHeaders
public static function scrubRequestSoapHeaders( $soapXml, array $headersToScrub ) { foreach ($headersToScrub as $header) { $regex = sprintf(self::$SOAP_REQUEST_HEADER_TAG_REGEX, $header); $soapXml = preg_replace($regex, '\1' . self::$REDACTED . '\2', $soapXml, 1); } return $soapXml; }
php
public static function scrubRequestSoapHeaders( $soapXml, array $headersToScrub ) { foreach ($headersToScrub as $header) { $regex = sprintf(self::$SOAP_REQUEST_HEADER_TAG_REGEX, $header); $soapXml = preg_replace($regex, '\1' . self::$REDACTED . '\2', $soapXml, 1); } return $soapXml; }
[ "public", "static", "function", "scrubRequestSoapHeaders", "(", "$", "soapXml", ",", "array", "$", "headersToScrub", ")", "{", "foreach", "(", "$", "headersToScrub", "as", "$", "header", ")", "{", "$", "regex", "=", "sprintf", "(", "self", "::", "$", "SOAP_REQUEST_HEADER_TAG_REGEX", ",", "$", "header", ")", ";", "$", "soapXml", "=", "preg_replace", "(", "$", "regex", ",", "'\\1'", ".", "self", "::", "$", "REDACTED", ".", "'\\2'", ",", "$", "soapXml", ",", "1", ")", ";", "}", "return", "$", "soapXml", ";", "}" ]
Scrubs the specified header values, replacing their occurrences in the specified request SOAP XML with a redacted token. @param string $soapXml @param string[] $headersToScrub which SOAP headers to scrub @return string the SOAP XML with any sensitive info removed from its headers
[ "Scrubs", "the", "specified", "header", "values", "replacing", "their", "occurrences", "in", "the", "specified", "request", "SOAP", "XML", "with", "a", "redacted", "token", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/Common/Util/LogMessageScrubbers.php#L85-L95
train
googleads/googleads-php-lib
src/Google/AdsApi/Common/Util/LogMessageScrubbers.php
LogMessageScrubbers.scrubRequestSoapBodyTags
public static function scrubRequestSoapBodyTags( $soapXml, array $tagsToScrub ) { foreach ($tagsToScrub as $tag) { $regex = sprintf(self::$SOAP_REQUEST_BODY_TAG_REGEX, $tag); $soapXml = preg_replace($regex, '\1' . self::$REDACTED . '\2', $soapXml, 1); } return $soapXml; }
php
public static function scrubRequestSoapBodyTags( $soapXml, array $tagsToScrub ) { foreach ($tagsToScrub as $tag) { $regex = sprintf(self::$SOAP_REQUEST_BODY_TAG_REGEX, $tag); $soapXml = preg_replace($regex, '\1' . self::$REDACTED . '\2', $soapXml, 1); } return $soapXml; }
[ "public", "static", "function", "scrubRequestSoapBodyTags", "(", "$", "soapXml", ",", "array", "$", "tagsToScrub", ")", "{", "foreach", "(", "$", "tagsToScrub", "as", "$", "tag", ")", "{", "$", "regex", "=", "sprintf", "(", "self", "::", "$", "SOAP_REQUEST_BODY_TAG_REGEX", ",", "$", "tag", ")", ";", "$", "soapXml", "=", "preg_replace", "(", "$", "regex", ",", "'\\1'", ".", "self", "::", "$", "REDACTED", ".", "'\\2'", ",", "$", "soapXml", ",", "1", ")", ";", "}", "return", "$", "soapXml", ";", "}" ]
Scrubs the values of specified tags, replacing their occurrences in the specified request SOAP XML with a redacted token. @param string $soapXml @param string[] $tagsToScrub which SOAP tags to scrub @return string the SOAP XML with any sensitive info removed from its headers
[ "Scrubs", "the", "values", "of", "specified", "tags", "replacing", "their", "occurrences", "in", "the", "specified", "request", "SOAP", "XML", "with", "a", "redacted", "token", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/Common/Util/LogMessageScrubbers.php#L106-L116
train
googleads/googleads-php-lib
src/Google/AdsApi/Common/Util/LogMessageScrubbers.php
LogMessageScrubbers.scrubHttpHeadersArray
public static function scrubHttpHeadersArray( array $httpHeaders, array $headersToScrub ) { foreach ($headersToScrub as $header) { $httpHeaders[$header] = self::$REDACTED; } return $httpHeaders; }
php
public static function scrubHttpHeadersArray( array $httpHeaders, array $headersToScrub ) { foreach ($headersToScrub as $header) { $httpHeaders[$header] = self::$REDACTED; } return $httpHeaders; }
[ "public", "static", "function", "scrubHttpHeadersArray", "(", "array", "$", "httpHeaders", ",", "array", "$", "headersToScrub", ")", "{", "foreach", "(", "$", "headersToScrub", "as", "$", "header", ")", "{", "$", "httpHeaders", "[", "$", "header", "]", "=", "self", "::", "$", "REDACTED", ";", "}", "return", "$", "httpHeaders", ";", "}" ]
Scrubs an array of HTTP headers by replacing their values with a redacted token. @param string[] $httpHeaders @param string[] $headersToScrub which HTTP headers to scrub @return string[] the list of HTTP headers with any sensitive info removed
[ "Scrubs", "an", "array", "of", "HTTP", "headers", "by", "replacing", "their", "values", "with", "a", "redacted", "token", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/Common/Util/LogMessageScrubbers.php#L126-L135
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/v201809/ch/CustomerSyncService.php
CustomerSyncService.get
public function get(\Google\AdsApi\AdWords\v201809\ch\CustomerSyncSelector $selector) { return $this->__soapCall('get', array(array('selector' => $selector)))->getRval(); }
php
public function get(\Google\AdsApi\AdWords\v201809\ch\CustomerSyncSelector $selector) { return $this->__soapCall('get', array(array('selector' => $selector)))->getRval(); }
[ "public", "function", "get", "(", "\\", "Google", "\\", "AdsApi", "\\", "AdWords", "\\", "v201809", "\\", "ch", "\\", "CustomerSyncSelector", "$", "selector", ")", "{", "return", "$", "this", "->", "__soapCall", "(", "'get'", ",", "array", "(", "array", "(", "'selector'", "=>", "$", "selector", ")", ")", ")", "->", "getRval", "(", ")", ";", "}" ]
Returns information about changed entities inside a customer's account. changed at each level. All Campaigns that are requested in the selector will be returned, regardless of whether or not they have changed, but unchanged AdGroups will be ignored. @param \Google\AdsApi\AdWords\v201809\ch\CustomerSyncSelector $selector @return \Google\AdsApi\AdWords\v201809\ch\CustomerChangeData @throws \Google\AdsApi\AdWords\v201809\cm\ApiException
[ "Returns", "information", "about", "changed", "entities", "inside", "a", "customer", "s", "account", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/v201809/ch/CustomerSyncService.php#L81-L84
train
googleads/googleads-php-lib
src/Google/AdsApi/AdWords/v201809/mcm/ManagedCustomerService.php
ManagedCustomerService.getPendingInvitations
public function getPendingInvitations(\Google\AdsApi\AdWords\v201809\mcm\PendingInvitationSelector $selector) { return $this->__soapCall('getPendingInvitations', array(array('selector' => $selector)))->getRval(); }
php
public function getPendingInvitations(\Google\AdsApi\AdWords\v201809\mcm\PendingInvitationSelector $selector) { return $this->__soapCall('getPendingInvitations', array(array('selector' => $selector)))->getRval(); }
[ "public", "function", "getPendingInvitations", "(", "\\", "Google", "\\", "AdsApi", "\\", "AdWords", "\\", "v201809", "\\", "mcm", "\\", "PendingInvitationSelector", "$", "selector", ")", "{", "return", "$", "this", "->", "__soapCall", "(", "'getPendingInvitations'", ",", "array", "(", "array", "(", "'selector'", "=>", "$", "selector", ")", ")", ")", "->", "getRval", "(", ")", ";", "}" ]
Returns the pending invitations for the customer IDs in the selector. @param \Google\AdsApi\AdWords\v201809\mcm\PendingInvitationSelector $selector @return \Google\AdsApi\AdWords\v201809\mcm\PendingInvitation[] @throws \Google\AdsApi\AdWords\v201809\cm\ApiException
[ "Returns", "the", "pending", "invitations", "for", "the", "customer", "IDs", "in", "the", "selector", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/src/Google/AdsApi/AdWords/v201809/mcm/ManagedCustomerService.php#L113-L116
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddMultiAssetResponsiveDisplayAd.php
AddMultiAssetResponsiveDisplayAd.uploadImageAsset
private static function uploadImageAsset(AssetService $assetService, $url) { // Creates an image asset and upload it to the server. $imageAsset = new ImageAsset(); // Optional: Provide a unique friendly name to identify your asset. If // you specify the assetName field, then both the asset name and the // image being uploaded should be unique, and should not match another // ACTIVE asset in this customer account. // $imageAsset->setAssetName('Image asset #' . uniqid()); $imageAsset->setImageData(file_get_contents($url)); // Create an asset operation. $operation = new AssetOperation(); $operation->setOperand($imageAsset); $operation->setOperator(Operator::ADD); return $assetService->mutate([$operation])->getValue()[0]->getAssetId(); }
php
private static function uploadImageAsset(AssetService $assetService, $url) { // Creates an image asset and upload it to the server. $imageAsset = new ImageAsset(); // Optional: Provide a unique friendly name to identify your asset. If // you specify the assetName field, then both the asset name and the // image being uploaded should be unique, and should not match another // ACTIVE asset in this customer account. // $imageAsset->setAssetName('Image asset #' . uniqid()); $imageAsset->setImageData(file_get_contents($url)); // Create an asset operation. $operation = new AssetOperation(); $operation->setOperand($imageAsset); $operation->setOperator(Operator::ADD); return $assetService->mutate([$operation])->getValue()[0]->getAssetId(); }
[ "private", "static", "function", "uploadImageAsset", "(", "AssetService", "$", "assetService", ",", "$", "url", ")", "{", "// Creates an image asset and upload it to the server.", "$", "imageAsset", "=", "new", "ImageAsset", "(", ")", ";", "// Optional: Provide a unique friendly name to identify your asset. If", "// you specify the assetName field, then both the asset name and the", "// image being uploaded should be unique, and should not match another", "// ACTIVE asset in this customer account.", "// $imageAsset->setAssetName('Image asset #' . uniqid());", "$", "imageAsset", "->", "setImageData", "(", "file_get_contents", "(", "$", "url", ")", ")", ";", "// Create an asset operation.", "$", "operation", "=", "new", "AssetOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "imageAsset", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "return", "$", "assetService", "->", "mutate", "(", "[", "$", "operation", "]", ")", "->", "getValue", "(", ")", "[", "0", "]", "->", "getAssetId", "(", ")", ";", "}" ]
Upload an image asset using AssetService and provided URL.
[ "Upload", "an", "image", "asset", "using", "AssetService", "and", "provided", "URL", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddMultiAssetResponsiveDisplayAd.php#L192-L209
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddUniversalAppCampaign.php
AddUniversalAppCampaign.createBudget
private static function createBudget( AdWordsServices $adWordsServices, AdWordsSession $session ) { $budgetService = $adWordsServices->get($session, BudgetService::class); // Create the shared budget (required). $budget = new Budget(); $budget->setName('Interplanetary Cruise Budget #' . uniqid()); $money = new Money(); $money->setMicroAmount(50000000); $budget->setAmount($money); $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD); // Universal App campaigns don't support shared budgets. $budget->setIsExplicitlyShared(false); $operations = []; // Create a budget operation. $operation = new BudgetOperation(); $operation->setOperand($budget); $operation->setOperator(Operator::ADD); $operations[] = $operation; // Create the budget on the server. $result = $budgetService->mutate($operations); $budget = $result->getValue()[0]; printf( "Budget with name '%s' and ID %d was created.\n", $budget->getName(), $budget->getBudgetId() ); return $budget->getBudgetId(); }
php
private static function createBudget( AdWordsServices $adWordsServices, AdWordsSession $session ) { $budgetService = $adWordsServices->get($session, BudgetService::class); // Create the shared budget (required). $budget = new Budget(); $budget->setName('Interplanetary Cruise Budget #' . uniqid()); $money = new Money(); $money->setMicroAmount(50000000); $budget->setAmount($money); $budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD); // Universal App campaigns don't support shared budgets. $budget->setIsExplicitlyShared(false); $operations = []; // Create a budget operation. $operation = new BudgetOperation(); $operation->setOperand($budget); $operation->setOperator(Operator::ADD); $operations[] = $operation; // Create the budget on the server. $result = $budgetService->mutate($operations); $budget = $result->getValue()[0]; printf( "Budget with name '%s' and ID %d was created.\n", $budget->getName(), $budget->getBudgetId() ); return $budget->getBudgetId(); }
[ "private", "static", "function", "createBudget", "(", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ")", "{", "$", "budgetService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "BudgetService", "::", "class", ")", ";", "// Create the shared budget (required).", "$", "budget", "=", "new", "Budget", "(", ")", ";", "$", "budget", "->", "setName", "(", "'Interplanetary Cruise Budget #'", ".", "uniqid", "(", ")", ")", ";", "$", "money", "=", "new", "Money", "(", ")", ";", "$", "money", "->", "setMicroAmount", "(", "50000000", ")", ";", "$", "budget", "->", "setAmount", "(", "$", "money", ")", ";", "$", "budget", "->", "setDeliveryMethod", "(", "BudgetBudgetDeliveryMethod", "::", "STANDARD", ")", ";", "// Universal App campaigns don't support shared budgets.", "$", "budget", "->", "setIsExplicitlyShared", "(", "false", ")", ";", "$", "operations", "=", "[", "]", ";", "// Create a budget operation.", "$", "operation", "=", "new", "BudgetOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "budget", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operations", "[", "]", "=", "$", "operation", ";", "// Create the budget on the server.", "$", "result", "=", "$", "budgetService", "->", "mutate", "(", "$", "operations", ")", ";", "$", "budget", "=", "$", "result", "->", "getValue", "(", ")", "[", "0", "]", ";", "printf", "(", "\"Budget with name '%s' and ID %d was created.\\n\"", ",", "$", "budget", "->", "getName", "(", ")", ",", "$", "budget", "->", "getBudgetId", "(", ")", ")", ";", "return", "$", "budget", "->", "getBudgetId", "(", ")", ";", "}" ]
Creates the budget for the campaign.
[ "Creates", "the", "budget", "for", "the", "campaign", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddUniversalAppCampaign.php#L179-L215
train
googleads/googleads-php-lib
examples/AdWords/v201809/AdvancedOperations/AddUniversalAppCampaign.php
AddUniversalAppCampaign.setCampaignTargetingCriteria
private static function setCampaignTargetingCriteria( $campaignId, AdWordsServices $adWordsServices, AdWordsSession $session ) { $campaignCriterionService = $adWordsServices->get($session, CampaignCriterionService::class); $campaignCriteria = []; // Create locations. The IDs can be found in the documentation or retrieved // with the LocationCriterionService. $california = new Location(); $california->setId(21137); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $california); $mexico = new Location(); $mexico->setId(2484); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $mexico); // Create languages. The IDs can be found in the documentation or retrieved // with the ConstantDataService. $english = new Language(); $english->setId(1000); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $english); $spanish = new Language(); $spanish->setId(1003); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $spanish); // Create operations to add each of the criteria above. $operations = []; foreach ($campaignCriteria as $campaignCriterion) { $operation = new CampaignCriterionOperation(); $operation->setOperand($campaignCriterion); $operation->setOperator(Operator::ADD); $operations[] = $operation; } // Set the campaign targets. $result = $campaignCriterionService->mutate($operations); // Display added campaign targets. foreach ($result->getValue() as $campaignCriterion) { printf( "Campaign criterion of type '%s' and ID %d was added.\n", $campaignCriterion->getCriterion()->getType(), $campaignCriterion->getCriterion()->getId() ); } }
php
private static function setCampaignTargetingCriteria( $campaignId, AdWordsServices $adWordsServices, AdWordsSession $session ) { $campaignCriterionService = $adWordsServices->get($session, CampaignCriterionService::class); $campaignCriteria = []; // Create locations. The IDs can be found in the documentation or retrieved // with the LocationCriterionService. $california = new Location(); $california->setId(21137); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $california); $mexico = new Location(); $mexico->setId(2484); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $mexico); // Create languages. The IDs can be found in the documentation or retrieved // with the ConstantDataService. $english = new Language(); $english->setId(1000); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $english); $spanish = new Language(); $spanish->setId(1003); $campaignCriteria[] = new CampaignCriterion($campaignId, null, $spanish); // Create operations to add each of the criteria above. $operations = []; foreach ($campaignCriteria as $campaignCriterion) { $operation = new CampaignCriterionOperation(); $operation->setOperand($campaignCriterion); $operation->setOperator(Operator::ADD); $operations[] = $operation; } // Set the campaign targets. $result = $campaignCriterionService->mutate($operations); // Display added campaign targets. foreach ($result->getValue() as $campaignCriterion) { printf( "Campaign criterion of type '%s' and ID %d was added.\n", $campaignCriterion->getCriterion()->getType(), $campaignCriterion->getCriterion()->getId() ); } }
[ "private", "static", "function", "setCampaignTargetingCriteria", "(", "$", "campaignId", ",", "AdWordsServices", "$", "adWordsServices", ",", "AdWordsSession", "$", "session", ")", "{", "$", "campaignCriterionService", "=", "$", "adWordsServices", "->", "get", "(", "$", "session", ",", "CampaignCriterionService", "::", "class", ")", ";", "$", "campaignCriteria", "=", "[", "]", ";", "// Create locations. The IDs can be found in the documentation or retrieved", "// with the LocationCriterionService.", "$", "california", "=", "new", "Location", "(", ")", ";", "$", "california", "->", "setId", "(", "21137", ")", ";", "$", "campaignCriteria", "[", "]", "=", "new", "CampaignCriterion", "(", "$", "campaignId", ",", "null", ",", "$", "california", ")", ";", "$", "mexico", "=", "new", "Location", "(", ")", ";", "$", "mexico", "->", "setId", "(", "2484", ")", ";", "$", "campaignCriteria", "[", "]", "=", "new", "CampaignCriterion", "(", "$", "campaignId", ",", "null", ",", "$", "mexico", ")", ";", "// Create languages. The IDs can be found in the documentation or retrieved", "// with the ConstantDataService.", "$", "english", "=", "new", "Language", "(", ")", ";", "$", "english", "->", "setId", "(", "1000", ")", ";", "$", "campaignCriteria", "[", "]", "=", "new", "CampaignCriterion", "(", "$", "campaignId", ",", "null", ",", "$", "english", ")", ";", "$", "spanish", "=", "new", "Language", "(", ")", ";", "$", "spanish", "->", "setId", "(", "1003", ")", ";", "$", "campaignCriteria", "[", "]", "=", "new", "CampaignCriterion", "(", "$", "campaignId", ",", "null", ",", "$", "spanish", ")", ";", "// Create operations to add each of the criteria above.", "$", "operations", "=", "[", "]", ";", "foreach", "(", "$", "campaignCriteria", "as", "$", "campaignCriterion", ")", "{", "$", "operation", "=", "new", "CampaignCriterionOperation", "(", ")", ";", "$", "operation", "->", "setOperand", "(", "$", "campaignCriterion", ")", ";", "$", "operation", "->", "setOperator", "(", "Operator", "::", "ADD", ")", ";", "$", "operations", "[", "]", "=", "$", "operation", ";", "}", "// Set the campaign targets.", "$", "result", "=", "$", "campaignCriterionService", "->", "mutate", "(", "$", "operations", ")", ";", "// Display added campaign targets.", "foreach", "(", "$", "result", "->", "getValue", "(", ")", "as", "$", "campaignCriterion", ")", "{", "printf", "(", "\"Campaign criterion of type '%s' and ID %d was added.\\n\"", ",", "$", "campaignCriterion", "->", "getCriterion", "(", ")", "->", "getType", "(", ")", ",", "$", "campaignCriterion", "->", "getCriterion", "(", ")", "->", "getId", "(", ")", ")", ";", "}", "}" ]
Sets the campaign's targeting criteria.
[ "Sets", "the", "campaign", "s", "targeting", "criteria", "." ]
d552b800ad53c400b1a50c7852e7ad184245d2ea
https://github.com/googleads/googleads-php-lib/blob/d552b800ad53c400b1a50c7852e7ad184245d2ea/examples/AdWords/v201809/AdvancedOperations/AddUniversalAppCampaign.php#L220-L268
train
moneyphp/money
src/Exception/UnresolvableCurrencyPairException.php
UnresolvableCurrencyPairException.createFromCurrencies
public static function createFromCurrencies(Currency $baseCurrency, Currency $counterCurrency) { $message = sprintf( 'Cannot resolve a currency pair for currencies: %s/%s', $baseCurrency->getCode(), $counterCurrency->getCode() ); return new self($message); }
php
public static function createFromCurrencies(Currency $baseCurrency, Currency $counterCurrency) { $message = sprintf( 'Cannot resolve a currency pair for currencies: %s/%s', $baseCurrency->getCode(), $counterCurrency->getCode() ); return new self($message); }
[ "public", "static", "function", "createFromCurrencies", "(", "Currency", "$", "baseCurrency", ",", "Currency", "$", "counterCurrency", ")", "{", "$", "message", "=", "sprintf", "(", "'Cannot resolve a currency pair for currencies: %s/%s'", ",", "$", "baseCurrency", "->", "getCode", "(", ")", ",", "$", "counterCurrency", "->", "getCode", "(", ")", ")", ";", "return", "new", "self", "(", "$", "message", ")", ";", "}" ]
Creates an exception from Currency objects. @param Currency $baseCurrency @param Currency $counterCurrency @return UnresolvableCurrencyPairException
[ "Creates", "an", "exception", "from", "Currency", "objects", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Exception/UnresolvableCurrencyPairException.php#L23-L32
train
moneyphp/money
src/CurrencyPair.php
CurrencyPair.equals
public function equals(CurrencyPair $other) { return $this->baseCurrency->equals($other->baseCurrency) && $this->counterCurrency->equals($other->counterCurrency) && $this->conversionRatio === $other->conversionRatio ; }
php
public function equals(CurrencyPair $other) { return $this->baseCurrency->equals($other->baseCurrency) && $this->counterCurrency->equals($other->counterCurrency) && $this->conversionRatio === $other->conversionRatio ; }
[ "public", "function", "equals", "(", "CurrencyPair", "$", "other", ")", "{", "return", "$", "this", "->", "baseCurrency", "->", "equals", "(", "$", "other", "->", "baseCurrency", ")", "&&", "$", "this", "->", "counterCurrency", "->", "equals", "(", "$", "other", "->", "counterCurrency", ")", "&&", "$", "this", "->", "conversionRatio", "===", "$", "other", "->", "conversionRatio", ";", "}" ]
Checks if an other CurrencyPair has the same parameters as this. @param CurrencyPair $other @return bool
[ "Checks", "if", "an", "other", "CurrencyPair", "has", "the", "same", "parameters", "as", "this", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/CurrencyPair.php#L117-L124
train
moneyphp/money
src/Money.php
Money.equals
public function equals(Money $other) { return $this->isSameCurrency($other) && $this->amount === $other->amount; }
php
public function equals(Money $other) { return $this->isSameCurrency($other) && $this->amount === $other->amount; }
[ "public", "function", "equals", "(", "Money", "$", "other", ")", "{", "return", "$", "this", "->", "isSameCurrency", "(", "$", "other", ")", "&&", "$", "this", "->", "amount", "===", "$", "other", "->", "amount", ";", "}" ]
Checks whether the value represented by this object equals to the other. @param Money $other @return bool
[ "Checks", "whether", "the", "value", "represented", "by", "this", "object", "equals", "to", "the", "other", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L128-L131
train
moneyphp/money
src/Money.php
Money.compare
public function compare(Money $other) { $this->assertSameCurrency($other); return $this->getCalculator()->compare($this->amount, $other->amount); }
php
public function compare(Money $other) { $this->assertSameCurrency($other); return $this->getCalculator()->compare($this->amount, $other->amount); }
[ "public", "function", "compare", "(", "Money", "$", "other", ")", "{", "$", "this", "->", "assertSameCurrency", "(", "$", "other", ")", ";", "return", "$", "this", "->", "getCalculator", "(", ")", "->", "compare", "(", "$", "this", "->", "amount", ",", "$", "other", "->", "amount", ")", ";", "}" ]
Returns an integer less than, equal to, or greater than zero if the value of this object is considered to be respectively less than, equal to, or greater than the other. @param Money $other @return int
[ "Returns", "an", "integer", "less", "than", "equal", "to", "or", "greater", "than", "zero", "if", "the", "value", "of", "this", "object", "is", "considered", "to", "be", "respectively", "less", "than", "equal", "to", "or", "greater", "than", "the", "other", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L142-L147
train
moneyphp/money
src/Money.php
Money.add
public function add(Money ...$addends) { $amount = $this->amount; $calculator = $this->getCalculator(); foreach ($addends as $addend) { $this->assertSameCurrency($addend); $amount = $calculator->add($amount, $addend->amount); } return new self($amount, $this->currency); }
php
public function add(Money ...$addends) { $amount = $this->amount; $calculator = $this->getCalculator(); foreach ($addends as $addend) { $this->assertSameCurrency($addend); $amount = $calculator->add($amount, $addend->amount); } return new self($amount, $this->currency); }
[ "public", "function", "add", "(", "Money", "...", "$", "addends", ")", "{", "$", "amount", "=", "$", "this", "->", "amount", ";", "$", "calculator", "=", "$", "this", "->", "getCalculator", "(", ")", ";", "foreach", "(", "$", "addends", "as", "$", "addend", ")", "{", "$", "this", "->", "assertSameCurrency", "(", "$", "addend", ")", ";", "$", "amount", "=", "$", "calculator", "->", "add", "(", "$", "amount", ",", "$", "addend", "->", "amount", ")", ";", "}", "return", "new", "self", "(", "$", "amount", ",", "$", "this", "->", "currency", ")", ";", "}" ]
Returns a new Money object that represents the sum of this and an other Money object. @param Money[] $addends @return Money
[ "Returns", "a", "new", "Money", "object", "that", "represents", "the", "sum", "of", "this", "and", "an", "other", "Money", "object", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L221-L233
train
moneyphp/money
src/Money.php
Money.subtract
public function subtract(Money ...$subtrahends) { $amount = $this->amount; $calculator = $this->getCalculator(); foreach ($subtrahends as $subtrahend) { $this->assertSameCurrency($subtrahend); $amount = $calculator->subtract($amount, $subtrahend->amount); } return new self($amount, $this->currency); }
php
public function subtract(Money ...$subtrahends) { $amount = $this->amount; $calculator = $this->getCalculator(); foreach ($subtrahends as $subtrahend) { $this->assertSameCurrency($subtrahend); $amount = $calculator->subtract($amount, $subtrahend->amount); } return new self($amount, $this->currency); }
[ "public", "function", "subtract", "(", "Money", "...", "$", "subtrahends", ")", "{", "$", "amount", "=", "$", "this", "->", "amount", ";", "$", "calculator", "=", "$", "this", "->", "getCalculator", "(", ")", ";", "foreach", "(", "$", "subtrahends", "as", "$", "subtrahend", ")", "{", "$", "this", "->", "assertSameCurrency", "(", "$", "subtrahend", ")", ";", "$", "amount", "=", "$", "calculator", "->", "subtract", "(", "$", "amount", ",", "$", "subtrahend", "->", "amount", ")", ";", "}", "return", "new", "self", "(", "$", "amount", ",", "$", "this", "->", "currency", ")", ";", "}" ]
Returns a new Money object that represents the difference of this and an other Money object. @param Money[] $subtrahends @return Money
[ "Returns", "a", "new", "Money", "object", "that", "represents", "the", "difference", "of", "this", "and", "an", "other", "Money", "object", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L243-L255
train
moneyphp/money
src/Money.php
Money.assertOperand
private function assertOperand($operand) { if (!is_numeric($operand)) { throw new \InvalidArgumentException(sprintf( 'Operand should be a numeric value, "%s" given.', is_object($operand) ? get_class($operand) : gettype($operand) )); } }
php
private function assertOperand($operand) { if (!is_numeric($operand)) { throw new \InvalidArgumentException(sprintf( 'Operand should be a numeric value, "%s" given.', is_object($operand) ? get_class($operand) : gettype($operand) )); } }
[ "private", "function", "assertOperand", "(", "$", "operand", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "operand", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Operand should be a numeric value, \"%s\" given.'", ",", "is_object", "(", "$", "operand", ")", "?", "get_class", "(", "$", "operand", ")", ":", "gettype", "(", "$", "operand", ")", ")", ")", ";", "}", "}" ]
Asserts that the operand is integer or float. @param float|int|string $operand @throws \InvalidArgumentException If $operand is neither integer nor float
[ "Asserts", "that", "the", "operand", "is", "integer", "or", "float", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L264-L272
train
moneyphp/money
src/Money.php
Money.assertRoundingMode
private function assertRoundingMode($roundingMode) { if (!in_array( $roundingMode, [ self::ROUND_HALF_DOWN, self::ROUND_HALF_EVEN, self::ROUND_HALF_ODD, self::ROUND_HALF_UP, self::ROUND_UP, self::ROUND_DOWN, self::ROUND_HALF_POSITIVE_INFINITY, self::ROUND_HALF_NEGATIVE_INFINITY, ], true )) { throw new \InvalidArgumentException( 'Rounding mode should be Money::ROUND_HALF_DOWN | '. 'Money::ROUND_HALF_EVEN | Money::ROUND_HALF_ODD | '. 'Money::ROUND_HALF_UP | Money::ROUND_UP | Money::ROUND_DOWN'. 'Money::ROUND_HALF_POSITIVE_INFINITY | Money::ROUND_HALF_NEGATIVE_INFINITY' ); } }
php
private function assertRoundingMode($roundingMode) { if (!in_array( $roundingMode, [ self::ROUND_HALF_DOWN, self::ROUND_HALF_EVEN, self::ROUND_HALF_ODD, self::ROUND_HALF_UP, self::ROUND_UP, self::ROUND_DOWN, self::ROUND_HALF_POSITIVE_INFINITY, self::ROUND_HALF_NEGATIVE_INFINITY, ], true )) { throw new \InvalidArgumentException( 'Rounding mode should be Money::ROUND_HALF_DOWN | '. 'Money::ROUND_HALF_EVEN | Money::ROUND_HALF_ODD | '. 'Money::ROUND_HALF_UP | Money::ROUND_UP | Money::ROUND_DOWN'. 'Money::ROUND_HALF_POSITIVE_INFINITY | Money::ROUND_HALF_NEGATIVE_INFINITY' ); } }
[ "private", "function", "assertRoundingMode", "(", "$", "roundingMode", ")", "{", "if", "(", "!", "in_array", "(", "$", "roundingMode", ",", "[", "self", "::", "ROUND_HALF_DOWN", ",", "self", "::", "ROUND_HALF_EVEN", ",", "self", "::", "ROUND_HALF_ODD", ",", "self", "::", "ROUND_HALF_UP", ",", "self", "::", "ROUND_UP", ",", "self", "::", "ROUND_DOWN", ",", "self", "::", "ROUND_HALF_POSITIVE_INFINITY", ",", "self", "::", "ROUND_HALF_NEGATIVE_INFINITY", ",", "]", ",", "true", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Rounding mode should be Money::ROUND_HALF_DOWN | '", ".", "'Money::ROUND_HALF_EVEN | Money::ROUND_HALF_ODD | '", ".", "'Money::ROUND_HALF_UP | Money::ROUND_UP | Money::ROUND_DOWN'", ".", "'Money::ROUND_HALF_POSITIVE_INFINITY | Money::ROUND_HALF_NEGATIVE_INFINITY'", ")", ";", "}", "}" ]
Asserts that rounding mode is a valid integer value. @param int $roundingMode @throws \InvalidArgumentException If $roundingMode is not valid
[ "Asserts", "that", "rounding", "mode", "is", "a", "valid", "integer", "value", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L281-L297
train
moneyphp/money
src/Money.php
Money.multiply
public function multiply($multiplier, $roundingMode = self::ROUND_HALF_UP) { $this->assertOperand($multiplier); $this->assertRoundingMode($roundingMode); $product = $this->round($this->getCalculator()->multiply($this->amount, $multiplier), $roundingMode); return $this->newInstance($product); }
php
public function multiply($multiplier, $roundingMode = self::ROUND_HALF_UP) { $this->assertOperand($multiplier); $this->assertRoundingMode($roundingMode); $product = $this->round($this->getCalculator()->multiply($this->amount, $multiplier), $roundingMode); return $this->newInstance($product); }
[ "public", "function", "multiply", "(", "$", "multiplier", ",", "$", "roundingMode", "=", "self", "::", "ROUND_HALF_UP", ")", "{", "$", "this", "->", "assertOperand", "(", "$", "multiplier", ")", ";", "$", "this", "->", "assertRoundingMode", "(", "$", "roundingMode", ")", ";", "$", "product", "=", "$", "this", "->", "round", "(", "$", "this", "->", "getCalculator", "(", ")", "->", "multiply", "(", "$", "this", "->", "amount", ",", "$", "multiplier", ")", ",", "$", "roundingMode", ")", ";", "return", "$", "this", "->", "newInstance", "(", "$", "product", ")", ";", "}" ]
Returns a new Money object that represents the multiplied value by the given factor. @param float|int|string $multiplier @param int $roundingMode @return Money
[ "Returns", "a", "new", "Money", "object", "that", "represents", "the", "multiplied", "value", "by", "the", "given", "factor", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L308-L316
train
moneyphp/money
src/Money.php
Money.divide
public function divide($divisor, $roundingMode = self::ROUND_HALF_UP) { $this->assertOperand($divisor); $this->assertRoundingMode($roundingMode); $divisor = (string) Number::fromNumber($divisor); if ($this->getCalculator()->compare($divisor, '0') === 0) { throw new \InvalidArgumentException('Division by zero'); } $quotient = $this->round($this->getCalculator()->divide($this->amount, $divisor), $roundingMode); return $this->newInstance($quotient); }
php
public function divide($divisor, $roundingMode = self::ROUND_HALF_UP) { $this->assertOperand($divisor); $this->assertRoundingMode($roundingMode); $divisor = (string) Number::fromNumber($divisor); if ($this->getCalculator()->compare($divisor, '0') === 0) { throw new \InvalidArgumentException('Division by zero'); } $quotient = $this->round($this->getCalculator()->divide($this->amount, $divisor), $roundingMode); return $this->newInstance($quotient); }
[ "public", "function", "divide", "(", "$", "divisor", ",", "$", "roundingMode", "=", "self", "::", "ROUND_HALF_UP", ")", "{", "$", "this", "->", "assertOperand", "(", "$", "divisor", ")", ";", "$", "this", "->", "assertRoundingMode", "(", "$", "roundingMode", ")", ";", "$", "divisor", "=", "(", "string", ")", "Number", "::", "fromNumber", "(", "$", "divisor", ")", ";", "if", "(", "$", "this", "->", "getCalculator", "(", ")", "->", "compare", "(", "$", "divisor", ",", "'0'", ")", "===", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Division by zero'", ")", ";", "}", "$", "quotient", "=", "$", "this", "->", "round", "(", "$", "this", "->", "getCalculator", "(", ")", "->", "divide", "(", "$", "this", "->", "amount", ",", "$", "divisor", ")", ",", "$", "roundingMode", ")", ";", "return", "$", "this", "->", "newInstance", "(", "$", "quotient", ")", ";", "}" ]
Returns a new Money object that represents the divided value by the given factor. @param float|int|string $divisor @param int $roundingMode @return Money
[ "Returns", "a", "new", "Money", "object", "that", "represents", "the", "divided", "value", "by", "the", "given", "factor", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L327-L341
train
moneyphp/money
src/Money.php
Money.mod
public function mod(Money $divisor) { $this->assertSameCurrency($divisor); return new self($this->getCalculator()->mod($this->amount, $divisor->amount), $this->currency); }
php
public function mod(Money $divisor) { $this->assertSameCurrency($divisor); return new self($this->getCalculator()->mod($this->amount, $divisor->amount), $this->currency); }
[ "public", "function", "mod", "(", "Money", "$", "divisor", ")", "{", "$", "this", "->", "assertSameCurrency", "(", "$", "divisor", ")", ";", "return", "new", "self", "(", "$", "this", "->", "getCalculator", "(", ")", "->", "mod", "(", "$", "this", "->", "amount", ",", "$", "divisor", "->", "amount", ")", ",", "$", "this", "->", "currency", ")", ";", "}" ]
Returns a new Money object that represents the remainder after dividing the value by the given factor. @param Money $divisor @return Money
[ "Returns", "a", "new", "Money", "object", "that", "represents", "the", "remainder", "after", "dividing", "the", "value", "by", "the", "given", "factor", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L352-L357
train
moneyphp/money
src/Money.php
Money.allocate
public function allocate(array $ratios) { if (count($ratios) === 0) { throw new \InvalidArgumentException('Cannot allocate to none, ratios cannot be an empty array'); } $remainder = $this->amount; $results = []; $total = array_sum($ratios); if ($total <= 0) { throw new \InvalidArgumentException('Cannot allocate to none, sum of ratios must be greater than zero'); } foreach ($ratios as $key => $ratio) { if ($ratio < 0) { throw new \InvalidArgumentException('Cannot allocate to none, ratio must be zero or positive'); } $share = $this->getCalculator()->share($this->amount, $ratio, $total); $results[$key] = $this->newInstance($share); $remainder = $this->getCalculator()->subtract($remainder, $share); } if ($this->getCalculator()->compare($remainder, '0') === 0) { return $results; } $fractions = array_map(function ($ratio) use ($total) { $share = ($ratio / $total) * $this->amount; return $share - floor($share); }, $ratios); while ($this->getCalculator()->compare($remainder, '0') > 0) { $index = !empty($fractions) ? array_keys($fractions, max($fractions))[0] : 0; $results[$index]->amount = $this->getCalculator()->add($results[$index]->amount, '1'); $remainder = $this->getCalculator()->subtract($remainder, '1'); unset($fractions[$index]); } return $results; }
php
public function allocate(array $ratios) { if (count($ratios) === 0) { throw new \InvalidArgumentException('Cannot allocate to none, ratios cannot be an empty array'); } $remainder = $this->amount; $results = []; $total = array_sum($ratios); if ($total <= 0) { throw new \InvalidArgumentException('Cannot allocate to none, sum of ratios must be greater than zero'); } foreach ($ratios as $key => $ratio) { if ($ratio < 0) { throw new \InvalidArgumentException('Cannot allocate to none, ratio must be zero or positive'); } $share = $this->getCalculator()->share($this->amount, $ratio, $total); $results[$key] = $this->newInstance($share); $remainder = $this->getCalculator()->subtract($remainder, $share); } if ($this->getCalculator()->compare($remainder, '0') === 0) { return $results; } $fractions = array_map(function ($ratio) use ($total) { $share = ($ratio / $total) * $this->amount; return $share - floor($share); }, $ratios); while ($this->getCalculator()->compare($remainder, '0') > 0) { $index = !empty($fractions) ? array_keys($fractions, max($fractions))[0] : 0; $results[$index]->amount = $this->getCalculator()->add($results[$index]->amount, '1'); $remainder = $this->getCalculator()->subtract($remainder, '1'); unset($fractions[$index]); } return $results; }
[ "public", "function", "allocate", "(", "array", "$", "ratios", ")", "{", "if", "(", "count", "(", "$", "ratios", ")", "===", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Cannot allocate to none, ratios cannot be an empty array'", ")", ";", "}", "$", "remainder", "=", "$", "this", "->", "amount", ";", "$", "results", "=", "[", "]", ";", "$", "total", "=", "array_sum", "(", "$", "ratios", ")", ";", "if", "(", "$", "total", "<=", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Cannot allocate to none, sum of ratios must be greater than zero'", ")", ";", "}", "foreach", "(", "$", "ratios", "as", "$", "key", "=>", "$", "ratio", ")", "{", "if", "(", "$", "ratio", "<", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Cannot allocate to none, ratio must be zero or positive'", ")", ";", "}", "$", "share", "=", "$", "this", "->", "getCalculator", "(", ")", "->", "share", "(", "$", "this", "->", "amount", ",", "$", "ratio", ",", "$", "total", ")", ";", "$", "results", "[", "$", "key", "]", "=", "$", "this", "->", "newInstance", "(", "$", "share", ")", ";", "$", "remainder", "=", "$", "this", "->", "getCalculator", "(", ")", "->", "subtract", "(", "$", "remainder", ",", "$", "share", ")", ";", "}", "if", "(", "$", "this", "->", "getCalculator", "(", ")", "->", "compare", "(", "$", "remainder", ",", "'0'", ")", "===", "0", ")", "{", "return", "$", "results", ";", "}", "$", "fractions", "=", "array_map", "(", "function", "(", "$", "ratio", ")", "use", "(", "$", "total", ")", "{", "$", "share", "=", "(", "$", "ratio", "/", "$", "total", ")", "*", "$", "this", "->", "amount", ";", "return", "$", "share", "-", "floor", "(", "$", "share", ")", ";", "}", ",", "$", "ratios", ")", ";", "while", "(", "$", "this", "->", "getCalculator", "(", ")", "->", "compare", "(", "$", "remainder", ",", "'0'", ")", ">", "0", ")", "{", "$", "index", "=", "!", "empty", "(", "$", "fractions", ")", "?", "array_keys", "(", "$", "fractions", ",", "max", "(", "$", "fractions", ")", ")", "[", "0", "]", ":", "0", ";", "$", "results", "[", "$", "index", "]", "->", "amount", "=", "$", "this", "->", "getCalculator", "(", ")", "->", "add", "(", "$", "results", "[", "$", "index", "]", "->", "amount", ",", "'1'", ")", ";", "$", "remainder", "=", "$", "this", "->", "getCalculator", "(", ")", "->", "subtract", "(", "$", "remainder", ",", "'1'", ")", ";", "unset", "(", "$", "fractions", "[", "$", "index", "]", ")", ";", "}", "return", "$", "results", ";", "}" ]
Allocate the money according to a list of ratios. @param array $ratios @return Money[]
[ "Allocate", "the", "money", "according", "to", "a", "list", "of", "ratios", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L366-L407
train
moneyphp/money
src/Money.php
Money.allocateTo
public function allocateTo($n) { if (!is_int($n)) { throw new \InvalidArgumentException('Number of targets must be an integer'); } if ($n <= 0) { throw new \InvalidArgumentException('Cannot allocate to none, target must be greater than zero'); } return $this->allocate(array_fill(0, $n, 1)); }
php
public function allocateTo($n) { if (!is_int($n)) { throw new \InvalidArgumentException('Number of targets must be an integer'); } if ($n <= 0) { throw new \InvalidArgumentException('Cannot allocate to none, target must be greater than zero'); } return $this->allocate(array_fill(0, $n, 1)); }
[ "public", "function", "allocateTo", "(", "$", "n", ")", "{", "if", "(", "!", "is_int", "(", "$", "n", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Number of targets must be an integer'", ")", ";", "}", "if", "(", "$", "n", "<=", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Cannot allocate to none, target must be greater than zero'", ")", ";", "}", "return", "$", "this", "->", "allocate", "(", "array_fill", "(", "0", ",", "$", "n", ",", "1", ")", ")", ";", "}" ]
Allocate the money among N targets. @param int $n @return Money[] @throws \InvalidArgumentException If number of targets is not an integer
[ "Allocate", "the", "money", "among", "N", "targets", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Money.php#L418-L429
train
moneyphp/money
src/Currencies/ISOCurrencies.php
ISOCurrencies.numericCodeFor
public function numericCodeFor(Currency $currency) { if (!$this->contains($currency)) { throw new UnknownCurrencyException('Cannot find ISO currency '.$currency->getCode()); } return $this->getCurrencies()[$currency->getCode()]['numericCode']; }
php
public function numericCodeFor(Currency $currency) { if (!$this->contains($currency)) { throw new UnknownCurrencyException('Cannot find ISO currency '.$currency->getCode()); } return $this->getCurrencies()[$currency->getCode()]['numericCode']; }
[ "public", "function", "numericCodeFor", "(", "Currency", "$", "currency", ")", "{", "if", "(", "!", "$", "this", "->", "contains", "(", "$", "currency", ")", ")", "{", "throw", "new", "UnknownCurrencyException", "(", "'Cannot find ISO currency '", ".", "$", "currency", "->", "getCode", "(", ")", ")", ";", "}", "return", "$", "this", "->", "getCurrencies", "(", ")", "[", "$", "currency", "->", "getCode", "(", ")", "]", "[", "'numericCode'", "]", ";", "}" ]
Returns the numeric code for a currency. @param Currency $currency @return int @throws UnknownCurrencyException If currency is not available in the current context
[ "Returns", "the", "numeric", "code", "for", "a", "currency", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Currencies/ISOCurrencies.php#L52-L59
train
moneyphp/money
src/Currencies/ISOCurrencies.php
ISOCurrencies.getCurrencies
private function getCurrencies() { if (null === self::$currencies) { self::$currencies = $this->loadCurrencies(); } return self::$currencies; }
php
private function getCurrencies() { if (null === self::$currencies) { self::$currencies = $this->loadCurrencies(); } return self::$currencies; }
[ "private", "function", "getCurrencies", "(", ")", "{", "if", "(", "null", "===", "self", "::", "$", "currencies", ")", "{", "self", "::", "$", "currencies", "=", "$", "this", "->", "loadCurrencies", "(", ")", ";", "}", "return", "self", "::", "$", "currencies", ";", "}" ]
Returns a map of known currencies indexed by code. @return array
[ "Returns", "a", "map", "of", "known", "currencies", "indexed", "by", "code", "." ]
d38c9011121f5a4d4c79c19ce77528f8643143e8
https://github.com/moneyphp/money/blob/d38c9011121f5a4d4c79c19ce77528f8643143e8/src/Currencies/ISOCurrencies.php#L81-L88
train
rashidlaasri/LaravelInstaller
src/Controllers/UpdateController.php
UpdateController.overview
public function overview() { $migrations = $this->getMigrations(); $dbMigrations = $this->getExecutedMigrations(); return view('vendor.installer.update.overview', ['numberOfUpdatesPending' => count($migrations) - count($dbMigrations)]); }
php
public function overview() { $migrations = $this->getMigrations(); $dbMigrations = $this->getExecutedMigrations(); return view('vendor.installer.update.overview', ['numberOfUpdatesPending' => count($migrations) - count($dbMigrations)]); }
[ "public", "function", "overview", "(", ")", "{", "$", "migrations", "=", "$", "this", "->", "getMigrations", "(", ")", ";", "$", "dbMigrations", "=", "$", "this", "->", "getExecutedMigrations", "(", ")", ";", "return", "view", "(", "'vendor.installer.update.overview'", ",", "[", "'numberOfUpdatesPending'", "=>", "count", "(", "$", "migrations", ")", "-", "count", "(", "$", "dbMigrations", ")", "]", ")", ";", "}" ]
Display the updater overview page. @return \Illuminate\View\View
[ "Display", "the", "updater", "overview", "page", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Controllers/UpdateController.php#L28-L34
train
rashidlaasri/LaravelInstaller
src/Controllers/UpdateController.php
UpdateController.database
public function database() { $databaseManager = new DatabaseManager; $response = $databaseManager->migrateAndSeed(); return redirect()->route('LaravelUpdater::final') ->with(['message' => $response]); }
php
public function database() { $databaseManager = new DatabaseManager; $response = $databaseManager->migrateAndSeed(); return redirect()->route('LaravelUpdater::final') ->with(['message' => $response]); }
[ "public", "function", "database", "(", ")", "{", "$", "databaseManager", "=", "new", "DatabaseManager", ";", "$", "response", "=", "$", "databaseManager", "->", "migrateAndSeed", "(", ")", ";", "return", "redirect", "(", ")", "->", "route", "(", "'LaravelUpdater::final'", ")", "->", "with", "(", "[", "'message'", "=>", "$", "response", "]", ")", ";", "}" ]
Migrate and seed the database. @return \Illuminate\View\View
[ "Migrate", "and", "seed", "the", "database", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Controllers/UpdateController.php#L41-L48
train
rashidlaasri/LaravelInstaller
src/Helpers/InstalledFileManager.php
InstalledFileManager.create
public function create() { $installedLogFile = storage_path('installed'); $dateStamp = date("Y/m/d h:i:sa"); if (!file_exists($installedLogFile)) { $message = trans('installer_messages.installed.success_log_message') . $dateStamp . "\n"; file_put_contents($installedLogFile, $message); } else { $message = trans('installer_messages.updater.log.success_message') . $dateStamp; file_put_contents($installedLogFile, $message.PHP_EOL , FILE_APPEND | LOCK_EX); } return $message; }
php
public function create() { $installedLogFile = storage_path('installed'); $dateStamp = date("Y/m/d h:i:sa"); if (!file_exists($installedLogFile)) { $message = trans('installer_messages.installed.success_log_message') . $dateStamp . "\n"; file_put_contents($installedLogFile, $message); } else { $message = trans('installer_messages.updater.log.success_message') . $dateStamp; file_put_contents($installedLogFile, $message.PHP_EOL , FILE_APPEND | LOCK_EX); } return $message; }
[ "public", "function", "create", "(", ")", "{", "$", "installedLogFile", "=", "storage_path", "(", "'installed'", ")", ";", "$", "dateStamp", "=", "date", "(", "\"Y/m/d h:i:sa\"", ")", ";", "if", "(", "!", "file_exists", "(", "$", "installedLogFile", ")", ")", "{", "$", "message", "=", "trans", "(", "'installer_messages.installed.success_log_message'", ")", ".", "$", "dateStamp", ".", "\"\\n\"", ";", "file_put_contents", "(", "$", "installedLogFile", ",", "$", "message", ")", ";", "}", "else", "{", "$", "message", "=", "trans", "(", "'installer_messages.updater.log.success_message'", ")", ".", "$", "dateStamp", ";", "file_put_contents", "(", "$", "installedLogFile", ",", "$", "message", ".", "PHP_EOL", ",", "FILE_APPEND", "|", "LOCK_EX", ")", ";", "}", "return", "$", "message", ";", "}" ]
Create installed file. @return int
[ "Create", "installed", "file", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/InstalledFileManager.php#L12-L31
train
rashidlaasri/LaravelInstaller
src/Controllers/RequirementsController.php
RequirementsController.requirements
public function requirements() { $phpSupportInfo = $this->requirements->checkPHPversion( config('installer.core.minPhpVersion') ); $requirements = $this->requirements->check( config('installer.requirements') ); return view('vendor.installer.requirements', compact('requirements', 'phpSupportInfo')); }
php
public function requirements() { $phpSupportInfo = $this->requirements->checkPHPversion( config('installer.core.minPhpVersion') ); $requirements = $this->requirements->check( config('installer.requirements') ); return view('vendor.installer.requirements', compact('requirements', 'phpSupportInfo')); }
[ "public", "function", "requirements", "(", ")", "{", "$", "phpSupportInfo", "=", "$", "this", "->", "requirements", "->", "checkPHPversion", "(", "config", "(", "'installer.core.minPhpVersion'", ")", ")", ";", "$", "requirements", "=", "$", "this", "->", "requirements", "->", "check", "(", "config", "(", "'installer.requirements'", ")", ")", ";", "return", "view", "(", "'vendor.installer.requirements'", ",", "compact", "(", "'requirements'", ",", "'phpSupportInfo'", ")", ")", ";", "}" ]
Display the requirements page. @return \Illuminate\View\View
[ "Display", "the", "requirements", "page", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Controllers/RequirementsController.php#L28-L38
train
rashidlaasri/LaravelInstaller
src/Helpers/FinalInstallManager.php
FinalInstallManager.runFinal
public function runFinal() { $outputLog = new BufferedOutput; $this->generateKey($outputLog); $this->publishVendorAssets($outputLog); return $outputLog->fetch(); }
php
public function runFinal() { $outputLog = new BufferedOutput; $this->generateKey($outputLog); $this->publishVendorAssets($outputLog); return $outputLog->fetch(); }
[ "public", "function", "runFinal", "(", ")", "{", "$", "outputLog", "=", "new", "BufferedOutput", ";", "$", "this", "->", "generateKey", "(", "$", "outputLog", ")", ";", "$", "this", "->", "publishVendorAssets", "(", "$", "outputLog", ")", ";", "return", "$", "outputLog", "->", "fetch", "(", ")", ";", "}" ]
Run final commands. @return string
[ "Run", "final", "commands", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/FinalInstallManager.php#L16-L24
train
rashidlaasri/LaravelInstaller
src/Helpers/FinalInstallManager.php
FinalInstallManager.publishVendorAssets
private static function publishVendorAssets(BufferedOutput $outputLog) { try{ if (config('installer.final.publish')){ Artisan::call('vendor:publish', ['--all' => true], $outputLog); } } catch(Exception $e){ return static::response($e->getMessage(), $outputLog); } return $outputLog; }
php
private static function publishVendorAssets(BufferedOutput $outputLog) { try{ if (config('installer.final.publish')){ Artisan::call('vendor:publish', ['--all' => true], $outputLog); } } catch(Exception $e){ return static::response($e->getMessage(), $outputLog); } return $outputLog; }
[ "private", "static", "function", "publishVendorAssets", "(", "BufferedOutput", "$", "outputLog", ")", "{", "try", "{", "if", "(", "config", "(", "'installer.final.publish'", ")", ")", "{", "Artisan", "::", "call", "(", "'vendor:publish'", ",", "[", "'--all'", "=>", "true", "]", ",", "$", "outputLog", ")", ";", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "static", "::", "response", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "outputLog", ")", ";", "}", "return", "$", "outputLog", ";", "}" ]
Publish vendor assets. @param \Symfony\Component\Console\Output\BufferedOutput $outputLog @return \Symfony\Component\Console\Output\BufferedOutput|array
[ "Publish", "vendor", "assets", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/FinalInstallManager.php#L52-L64
train
rashidlaasri/LaravelInstaller
src/Middleware/canUpdate.php
canUpdate.alreadyUpdated
public function alreadyUpdated() { $migrations = $this->getMigrations(); $dbMigrations = $this->getExecutedMigrations(); // If the count of migrations and dbMigrations is equal, // then the update as already been updated. if (count($migrations) == count($dbMigrations)) { return true; } // Continue, the app needs an update return false; }
php
public function alreadyUpdated() { $migrations = $this->getMigrations(); $dbMigrations = $this->getExecutedMigrations(); // If the count of migrations and dbMigrations is equal, // then the update as already been updated. if (count($migrations) == count($dbMigrations)) { return true; } // Continue, the app needs an update return false; }
[ "public", "function", "alreadyUpdated", "(", ")", "{", "$", "migrations", "=", "$", "this", "->", "getMigrations", "(", ")", ";", "$", "dbMigrations", "=", "$", "this", "->", "getExecutedMigrations", "(", ")", ";", "// If the count of migrations and dbMigrations is equal,\r", "// then the update as already been updated.\r", "if", "(", "count", "(", "$", "migrations", ")", "==", "count", "(", "$", "dbMigrations", ")", ")", "{", "return", "true", ";", "}", "// Continue, the app needs an update\r", "return", "false", ";", "}" ]
If application is already updated. @return bool
[ "If", "application", "is", "already", "updated", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Middleware/canUpdate.php#L50-L63
train
rashidlaasri/LaravelInstaller
src/Helpers/PermissionsChecker.php
PermissionsChecker.check
public function check(array $folders) { foreach($folders as $folder => $permission) { if(!($this->getPermission($folder) >= $permission)) { $this->addFileAndSetErrors($folder, $permission, false); } else { $this->addFile($folder, $permission, true); } } return $this->results; }
php
public function check(array $folders) { foreach($folders as $folder => $permission) { if(!($this->getPermission($folder) >= $permission)) { $this->addFileAndSetErrors($folder, $permission, false); } else { $this->addFile($folder, $permission, true); } } return $this->results; }
[ "public", "function", "check", "(", "array", "$", "folders", ")", "{", "foreach", "(", "$", "folders", "as", "$", "folder", "=>", "$", "permission", ")", "{", "if", "(", "!", "(", "$", "this", "->", "getPermission", "(", "$", "folder", ")", ">=", "$", "permission", ")", ")", "{", "$", "this", "->", "addFileAndSetErrors", "(", "$", "folder", ",", "$", "permission", ",", "false", ")", ";", "}", "else", "{", "$", "this", "->", "addFile", "(", "$", "folder", ",", "$", "permission", ",", "true", ")", ";", "}", "}", "return", "$", "this", "->", "results", ";", "}" ]
Check for the folders permissions. @param array $folders @return array
[ "Check", "for", "the", "folders", "permissions", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/PermissionsChecker.php#L30-L44
train
rashidlaasri/LaravelInstaller
src/Helpers/PermissionsChecker.php
PermissionsChecker.addFile
private function addFile($folder, $permission, $isSet) { array_push($this->results['permissions'], [ 'folder' => $folder, 'permission' => $permission, 'isSet' => $isSet ]); }
php
private function addFile($folder, $permission, $isSet) { array_push($this->results['permissions'], [ 'folder' => $folder, 'permission' => $permission, 'isSet' => $isSet ]); }
[ "private", "function", "addFile", "(", "$", "folder", ",", "$", "permission", ",", "$", "isSet", ")", "{", "array_push", "(", "$", "this", "->", "results", "[", "'permissions'", "]", ",", "[", "'folder'", "=>", "$", "folder", ",", "'permission'", "=>", "$", "permission", ",", "'isSet'", "=>", "$", "isSet", "]", ")", ";", "}" ]
Add the file to the list of results. @param $folder @param $permission @param $isSet
[ "Add", "the", "file", "to", "the", "list", "of", "results", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/PermissionsChecker.php#L64-L71
train
rashidlaasri/LaravelInstaller
src/Helpers/PermissionsChecker.php
PermissionsChecker.addFileAndSetErrors
private function addFileAndSetErrors($folder, $permission, $isSet) { $this->addFile($folder, $permission, $isSet); $this->results['errors'] = true; }
php
private function addFileAndSetErrors($folder, $permission, $isSet) { $this->addFile($folder, $permission, $isSet); $this->results['errors'] = true; }
[ "private", "function", "addFileAndSetErrors", "(", "$", "folder", ",", "$", "permission", ",", "$", "isSet", ")", "{", "$", "this", "->", "addFile", "(", "$", "folder", ",", "$", "permission", ",", "$", "isSet", ")", ";", "$", "this", "->", "results", "[", "'errors'", "]", "=", "true", ";", "}" ]
Add the file and set the errors. @param $folder @param $permission @param $isSet
[ "Add", "the", "file", "and", "set", "the", "errors", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/PermissionsChecker.php#L80-L85
train
rashidlaasri/LaravelInstaller
src/Helpers/RequirementsChecker.php
RequirementsChecker.check
public function check(array $requirements) { $results = []; foreach($requirements as $type => $requirement) { switch ($type) { // check php requirements case 'php': foreach($requirements[$type] as $requirement) { $results['requirements'][$type][$requirement] = true; if(!extension_loaded($requirement)) { $results['requirements'][$type][$requirement] = false; $results['errors'] = true; } } break; // check apache requirements case 'apache': foreach ($requirements[$type] as $requirement) { // if function doesn't exist we can't check apache modules if(function_exists('apache_get_modules')) { $results['requirements'][$type][$requirement] = true; if(!in_array($requirement,apache_get_modules())) { $results['requirements'][$type][$requirement] = false; $results['errors'] = true; } } } break; } } return $results; }
php
public function check(array $requirements) { $results = []; foreach($requirements as $type => $requirement) { switch ($type) { // check php requirements case 'php': foreach($requirements[$type] as $requirement) { $results['requirements'][$type][$requirement] = true; if(!extension_loaded($requirement)) { $results['requirements'][$type][$requirement] = false; $results['errors'] = true; } } break; // check apache requirements case 'apache': foreach ($requirements[$type] as $requirement) { // if function doesn't exist we can't check apache modules if(function_exists('apache_get_modules')) { $results['requirements'][$type][$requirement] = true; if(!in_array($requirement,apache_get_modules())) { $results['requirements'][$type][$requirement] = false; $results['errors'] = true; } } } break; } } return $results; }
[ "public", "function", "check", "(", "array", "$", "requirements", ")", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "requirements", "as", "$", "type", "=>", "$", "requirement", ")", "{", "switch", "(", "$", "type", ")", "{", "// check php requirements\r", "case", "'php'", ":", "foreach", "(", "$", "requirements", "[", "$", "type", "]", "as", "$", "requirement", ")", "{", "$", "results", "[", "'requirements'", "]", "[", "$", "type", "]", "[", "$", "requirement", "]", "=", "true", ";", "if", "(", "!", "extension_loaded", "(", "$", "requirement", ")", ")", "{", "$", "results", "[", "'requirements'", "]", "[", "$", "type", "]", "[", "$", "requirement", "]", "=", "false", ";", "$", "results", "[", "'errors'", "]", "=", "true", ";", "}", "}", "break", ";", "// check apache requirements\r", "case", "'apache'", ":", "foreach", "(", "$", "requirements", "[", "$", "type", "]", "as", "$", "requirement", ")", "{", "// if function doesn't exist we can't check apache modules\r", "if", "(", "function_exists", "(", "'apache_get_modules'", ")", ")", "{", "$", "results", "[", "'requirements'", "]", "[", "$", "type", "]", "[", "$", "requirement", "]", "=", "true", ";", "if", "(", "!", "in_array", "(", "$", "requirement", ",", "apache_get_modules", "(", ")", ")", ")", "{", "$", "results", "[", "'requirements'", "]", "[", "$", "type", "]", "[", "$", "requirement", "]", "=", "false", ";", "$", "results", "[", "'errors'", "]", "=", "true", ";", "}", "}", "}", "break", ";", "}", "}", "return", "$", "results", ";", "}" ]
Check for the server requirements. @param array $requirements @return array
[ "Check", "for", "the", "server", "requirements", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/RequirementsChecker.php#L21-L63
train
rashidlaasri/LaravelInstaller
src/Helpers/RequirementsChecker.php
RequirementsChecker.checkPHPversion
public function checkPHPversion(string $minPhpVersion = null) { $minVersionPhp = $minPhpVersion; $currentPhpVersion = $this->getPhpVersionInfo(); $supported = false; if ($minPhpVersion == null) { $minVersionPhp = $this->getMinPhpVersion(); } if (version_compare($currentPhpVersion['version'], $minVersionPhp) >= 0) { $supported = true; } $phpStatus = [ 'full' => $currentPhpVersion['full'], 'current' => $currentPhpVersion['version'], 'minimum' => $minVersionPhp, 'supported' => $supported ]; return $phpStatus; }
php
public function checkPHPversion(string $minPhpVersion = null) { $minVersionPhp = $minPhpVersion; $currentPhpVersion = $this->getPhpVersionInfo(); $supported = false; if ($minPhpVersion == null) { $minVersionPhp = $this->getMinPhpVersion(); } if (version_compare($currentPhpVersion['version'], $minVersionPhp) >= 0) { $supported = true; } $phpStatus = [ 'full' => $currentPhpVersion['full'], 'current' => $currentPhpVersion['version'], 'minimum' => $minVersionPhp, 'supported' => $supported ]; return $phpStatus; }
[ "public", "function", "checkPHPversion", "(", "string", "$", "minPhpVersion", "=", "null", ")", "{", "$", "minVersionPhp", "=", "$", "minPhpVersion", ";", "$", "currentPhpVersion", "=", "$", "this", "->", "getPhpVersionInfo", "(", ")", ";", "$", "supported", "=", "false", ";", "if", "(", "$", "minPhpVersion", "==", "null", ")", "{", "$", "minVersionPhp", "=", "$", "this", "->", "getMinPhpVersion", "(", ")", ";", "}", "if", "(", "version_compare", "(", "$", "currentPhpVersion", "[", "'version'", "]", ",", "$", "minVersionPhp", ")", ">=", "0", ")", "{", "$", "supported", "=", "true", ";", "}", "$", "phpStatus", "=", "[", "'full'", "=>", "$", "currentPhpVersion", "[", "'full'", "]", ",", "'current'", "=>", "$", "currentPhpVersion", "[", "'version'", "]", ",", "'minimum'", "=>", "$", "minVersionPhp", ",", "'supported'", "=>", "$", "supported", "]", ";", "return", "$", "phpStatus", ";", "}" ]
Check PHP version requirement. @return array
[ "Check", "PHP", "version", "requirement", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/RequirementsChecker.php#L70-L92
train
rashidlaasri/LaravelInstaller
src/Helpers/RequirementsChecker.php
RequirementsChecker.getPhpVersionInfo
private static function getPhpVersionInfo() { $currentVersionFull = PHP_VERSION; preg_match("#^\d+(\.\d+)*#", $currentVersionFull, $filtered); $currentVersion = $filtered[0]; return [ 'full' => $currentVersionFull, 'version' => $currentVersion ]; }
php
private static function getPhpVersionInfo() { $currentVersionFull = PHP_VERSION; preg_match("#^\d+(\.\d+)*#", $currentVersionFull, $filtered); $currentVersion = $filtered[0]; return [ 'full' => $currentVersionFull, 'version' => $currentVersion ]; }
[ "private", "static", "function", "getPhpVersionInfo", "(", ")", "{", "$", "currentVersionFull", "=", "PHP_VERSION", ";", "preg_match", "(", "\"#^\\d+(\\.\\d+)*#\"", ",", "$", "currentVersionFull", ",", "$", "filtered", ")", ";", "$", "currentVersion", "=", "$", "filtered", "[", "0", "]", ";", "return", "[", "'full'", "=>", "$", "currentVersionFull", ",", "'version'", "=>", "$", "currentVersion", "]", ";", "}" ]
Get current Php version information @return array
[ "Get", "current", "Php", "version", "information" ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/RequirementsChecker.php#L99-L109
train
rashidlaasri/LaravelInstaller
src/Providers/LaravelInstallerServiceProvider.php
LaravelInstallerServiceProvider.publishFiles
protected function publishFiles() { $this->publishes([ __DIR__.'/../Config/installer.php' => base_path('config/installer.php'), ], 'laravelinstaller'); $this->publishes([ __DIR__.'/../assets' => public_path('installer'), ], 'laravelinstaller'); $this->publishes([ __DIR__.'/../Views' => base_path('resources/views/vendor/installer'), ], 'laravelinstaller'); $this->publishes([ __DIR__.'/../Lang' => base_path('resources/lang'), ], 'laravelinstaller'); }
php
protected function publishFiles() { $this->publishes([ __DIR__.'/../Config/installer.php' => base_path('config/installer.php'), ], 'laravelinstaller'); $this->publishes([ __DIR__.'/../assets' => public_path('installer'), ], 'laravelinstaller'); $this->publishes([ __DIR__.'/../Views' => base_path('resources/views/vendor/installer'), ], 'laravelinstaller'); $this->publishes([ __DIR__.'/../Lang' => base_path('resources/lang'), ], 'laravelinstaller'); }
[ "protected", "function", "publishFiles", "(", ")", "{", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../Config/installer.php'", "=>", "base_path", "(", "'config/installer.php'", ")", ",", "]", ",", "'laravelinstaller'", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../assets'", "=>", "public_path", "(", "'installer'", ")", ",", "]", ",", "'laravelinstaller'", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../Views'", "=>", "base_path", "(", "'resources/views/vendor/installer'", ")", ",", "]", ",", "'laravelinstaller'", ")", ";", "$", "this", "->", "publishes", "(", "[", "__DIR__", ".", "'/../Lang'", "=>", "base_path", "(", "'resources/lang'", ")", ",", "]", ",", "'laravelinstaller'", ")", ";", "}" ]
Publish config file for the installer. @return void
[ "Publish", "config", "file", "for", "the", "installer", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Providers/LaravelInstallerServiceProvider.php#L46-L63
train
rashidlaasri/LaravelInstaller
src/Helpers/EnvironmentManager.php
EnvironmentManager.getEnvContent
public function getEnvContent() { if (!file_exists($this->envPath)) { if (file_exists($this->envExamplePath)) { copy($this->envExamplePath, $this->envPath); } else { touch($this->envPath); } } return file_get_contents($this->envPath); }
php
public function getEnvContent() { if (!file_exists($this->envPath)) { if (file_exists($this->envExamplePath)) { copy($this->envExamplePath, $this->envPath); } else { touch($this->envPath); } } return file_get_contents($this->envPath); }
[ "public", "function", "getEnvContent", "(", ")", "{", "if", "(", "!", "file_exists", "(", "$", "this", "->", "envPath", ")", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "envExamplePath", ")", ")", "{", "copy", "(", "$", "this", "->", "envExamplePath", ",", "$", "this", "->", "envPath", ")", ";", "}", "else", "{", "touch", "(", "$", "this", "->", "envPath", ")", ";", "}", "}", "return", "file_get_contents", "(", "$", "this", "->", "envPath", ")", ";", "}" ]
Get the content of the .env file. @return string
[ "Get", "the", "content", "of", "the", ".", "env", "file", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/EnvironmentManager.php#L34-L45
train
rashidlaasri/LaravelInstaller
src/Helpers/EnvironmentManager.php
EnvironmentManager.saveFileClassic
public function saveFileClassic(Request $input) { $message = trans('installer_messages.environment.success'); try { file_put_contents($this->envPath, $input->get('envConfig')); } catch(Exception $e) { $message = trans('installer_messages.environment.errors'); } return $message; }
php
public function saveFileClassic(Request $input) { $message = trans('installer_messages.environment.success'); try { file_put_contents($this->envPath, $input->get('envConfig')); } catch(Exception $e) { $message = trans('installer_messages.environment.errors'); } return $message; }
[ "public", "function", "saveFileClassic", "(", "Request", "$", "input", ")", "{", "$", "message", "=", "trans", "(", "'installer_messages.environment.success'", ")", ";", "try", "{", "file_put_contents", "(", "$", "this", "->", "envPath", ",", "$", "input", "->", "get", "(", "'envConfig'", ")", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "message", "=", "trans", "(", "'installer_messages.environment.errors'", ")", ";", "}", "return", "$", "message", ";", "}" ]
Save the edited content to the .env file. @param Request $input @return string
[ "Save", "the", "edited", "content", "to", "the", ".", "env", "file", "." ]
7c0ee781aedc4115b0691c1f5d062ef49f8997eb
https://github.com/rashidlaasri/LaravelInstaller/blob/7c0ee781aedc4115b0691c1f5d062ef49f8997eb/src/Helpers/EnvironmentManager.php#L71-L83
train
phalcon/zephir
Library/BranchGraphNode.php
BranchGraphNode.insert
public function insert(self $branch) { if (!\in_array($branch, $this->branches)) { $this->branches[] = $branch; } }
php
public function insert(self $branch) { if (!\in_array($branch, $this->branches)) { $this->branches[] = $branch; } }
[ "public", "function", "insert", "(", "self", "$", "branch", ")", "{", "if", "(", "!", "\\", "in_array", "(", "$", "branch", ",", "$", "this", "->", "branches", ")", ")", "{", "$", "this", "->", "branches", "[", "]", "=", "$", "branch", ";", "}", "}" ]
Inserts a node in the branch graph. @param BranchGraphNode $branch
[ "Inserts", "a", "node", "in", "the", "branch", "graph", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/BranchGraphNode.php#L45-L50
train
phalcon/zephir
Library/BranchGraphNode.php
BranchGraphNode.show
public function show($padding = 0) { echo str_repeat(' ', $padding), $this->branch->getUniqueId(), ':' , $this->increase; if (\count($this->branches)) { echo ':', PHP_EOL; foreach ($this->branches as $node) { $node->show($padding + 1); } } else { echo PHP_EOL; } }
php
public function show($padding = 0) { echo str_repeat(' ', $padding), $this->branch->getUniqueId(), ':' , $this->increase; if (\count($this->branches)) { echo ':', PHP_EOL; foreach ($this->branches as $node) { $node->show($padding + 1); } } else { echo PHP_EOL; } }
[ "public", "function", "show", "(", "$", "padding", "=", "0", ")", "{", "echo", "str_repeat", "(", "' '", ",", "$", "padding", ")", ",", "$", "this", "->", "branch", "->", "getUniqueId", "(", ")", ",", "':'", ",", "$", "this", "->", "increase", ";", "if", "(", "\\", "count", "(", "$", "this", "->", "branches", ")", ")", "{", "echo", "':'", ",", "PHP_EOL", ";", "foreach", "(", "$", "this", "->", "branches", "as", "$", "node", ")", "{", "$", "node", "->", "show", "(", "$", "padding", "+", "1", ")", ";", "}", "}", "else", "{", "echo", "PHP_EOL", ";", "}", "}" ]
Generates an ASCII visualization of the branch. @param int $padding
[ "Generates", "an", "ASCII", "visualization", "of", "the", "branch", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/BranchGraphNode.php#L65-L76
train
phalcon/zephir
Library/Expression/Reference.php
Reference.setExpectReturn
public function setExpectReturn($expecting, Variable $expectingVariable = null) { $this->expecting = $expecting; $this->expectingVariable = $expectingVariable; }
php
public function setExpectReturn($expecting, Variable $expectingVariable = null) { $this->expecting = $expecting; $this->expectingVariable = $expectingVariable; }
[ "public", "function", "setExpectReturn", "(", "$", "expecting", ",", "Variable", "$", "expectingVariable", "=", "null", ")", "{", "$", "this", "->", "expecting", "=", "$", "expecting", ";", "$", "this", "->", "expectingVariable", "=", "$", "expectingVariable", ";", "}" ]
Sets if the variable must be resolved into a direct variable symbol create a temporary value or ignore the return value. @param bool $expecting @param Variable $expectingVariable
[ "Sets", "if", "the", "variable", "must", "be", "resolved", "into", "a", "direct", "variable", "symbol", "create", "a", "temporary", "value", "or", "ignore", "the", "return", "value", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/Expression/Reference.php#L42-L46
train
phalcon/zephir
Library/Expression/Reference.php
Reference.compile
public function compile($expression, CompilationContext $compilationContext) { /* * Resolves the symbol that expects the value */ if ($this->expecting) { if ($this->expectingVariable) { $symbolVariable = $this->expectingVariable; if ('variable' != $symbolVariable->getType()) { throw new CompilerException('Cannot use variable type: '.$symbolVariable->getType().' to store a reference', $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('variable', $compilationContext, $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('variable', $compilationContext, $expression); } $leftExpr = new Expression($expression['left']); $leftExpr->setReadOnly($this->readOnly); $left = $leftExpr->compile($compilationContext); switch ($left->getType()) { case 'variable': case 'string': case 'object': case 'array': case 'callable': break; default: throw new CompilerException('Cannot obtain a reference from type: '.$left->getType(), $expression); } $leftVariable = $compilationContext->symbolTable->getVariableForRead($left->getCode(), $compilationContext, $expression); switch ($leftVariable->getType()) { case 'variable': case 'string': case 'object': case 'array': case 'callable': break; default: throw new CompilerException('Cannot obtain reference from variable type: '.$leftVariable->getType(), $expression); } $symbolVariable->setMustInitNull(true); $compilationContext->symbolTable->mustGrownStack(true); $symbolVariable->increaseVariantIfNull(); $compilationContext->codePrinter->output('ZEPHIR_MAKE_REFERENCE('.$symbolVariable->getName().', '.$leftVariable->getName().');'); return new CompiledExpression('reference', $symbolVariable->getRealName(), $expression); }
php
public function compile($expression, CompilationContext $compilationContext) { /* * Resolves the symbol that expects the value */ if ($this->expecting) { if ($this->expectingVariable) { $symbolVariable = $this->expectingVariable; if ('variable' != $symbolVariable->getType()) { throw new CompilerException('Cannot use variable type: '.$symbolVariable->getType().' to store a reference', $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('variable', $compilationContext, $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('variable', $compilationContext, $expression); } $leftExpr = new Expression($expression['left']); $leftExpr->setReadOnly($this->readOnly); $left = $leftExpr->compile($compilationContext); switch ($left->getType()) { case 'variable': case 'string': case 'object': case 'array': case 'callable': break; default: throw new CompilerException('Cannot obtain a reference from type: '.$left->getType(), $expression); } $leftVariable = $compilationContext->symbolTable->getVariableForRead($left->getCode(), $compilationContext, $expression); switch ($leftVariable->getType()) { case 'variable': case 'string': case 'object': case 'array': case 'callable': break; default: throw new CompilerException('Cannot obtain reference from variable type: '.$leftVariable->getType(), $expression); } $symbolVariable->setMustInitNull(true); $compilationContext->symbolTable->mustGrownStack(true); $symbolVariable->increaseVariantIfNull(); $compilationContext->codePrinter->output('ZEPHIR_MAKE_REFERENCE('.$symbolVariable->getName().', '.$leftVariable->getName().');'); return new CompiledExpression('reference', $symbolVariable->getRealName(), $expression); }
[ "public", "function", "compile", "(", "$", "expression", ",", "CompilationContext", "$", "compilationContext", ")", "{", "/*\n * Resolves the symbol that expects the value\n */", "if", "(", "$", "this", "->", "expecting", ")", "{", "if", "(", "$", "this", "->", "expectingVariable", ")", "{", "$", "symbolVariable", "=", "$", "this", "->", "expectingVariable", ";", "if", "(", "'variable'", "!=", "$", "symbolVariable", "->", "getType", "(", ")", ")", "{", "throw", "new", "CompilerException", "(", "'Cannot use variable type: '", ".", "$", "symbolVariable", "->", "getType", "(", ")", ".", "' to store a reference'", ",", "$", "expression", ")", ";", "}", "}", "else", "{", "$", "symbolVariable", "=", "$", "compilationContext", "->", "symbolTable", "->", "getTempVariableForWrite", "(", "'variable'", ",", "$", "compilationContext", ",", "$", "expression", ")", ";", "}", "}", "else", "{", "$", "symbolVariable", "=", "$", "compilationContext", "->", "symbolTable", "->", "getTempVariableForWrite", "(", "'variable'", ",", "$", "compilationContext", ",", "$", "expression", ")", ";", "}", "$", "leftExpr", "=", "new", "Expression", "(", "$", "expression", "[", "'left'", "]", ")", ";", "$", "leftExpr", "->", "setReadOnly", "(", "$", "this", "->", "readOnly", ")", ";", "$", "left", "=", "$", "leftExpr", "->", "compile", "(", "$", "compilationContext", ")", ";", "switch", "(", "$", "left", "->", "getType", "(", ")", ")", "{", "case", "'variable'", ":", "case", "'string'", ":", "case", "'object'", ":", "case", "'array'", ":", "case", "'callable'", ":", "break", ";", "default", ":", "throw", "new", "CompilerException", "(", "'Cannot obtain a reference from type: '", ".", "$", "left", "->", "getType", "(", ")", ",", "$", "expression", ")", ";", "}", "$", "leftVariable", "=", "$", "compilationContext", "->", "symbolTable", "->", "getVariableForRead", "(", "$", "left", "->", "getCode", "(", ")", ",", "$", "compilationContext", ",", "$", "expression", ")", ";", "switch", "(", "$", "leftVariable", "->", "getType", "(", ")", ")", "{", "case", "'variable'", ":", "case", "'string'", ":", "case", "'object'", ":", "case", "'array'", ":", "case", "'callable'", ":", "break", ";", "default", ":", "throw", "new", "CompilerException", "(", "'Cannot obtain reference from variable type: '", ".", "$", "leftVariable", "->", "getType", "(", ")", ",", "$", "expression", ")", ";", "}", "$", "symbolVariable", "->", "setMustInitNull", "(", "true", ")", ";", "$", "compilationContext", "->", "symbolTable", "->", "mustGrownStack", "(", "true", ")", ";", "$", "symbolVariable", "->", "increaseVariantIfNull", "(", ")", ";", "$", "compilationContext", "->", "codePrinter", "->", "output", "(", "'ZEPHIR_MAKE_REFERENCE('", ".", "$", "symbolVariable", "->", "getName", "(", ")", ".", "', '", ".", "$", "leftVariable", "->", "getName", "(", ")", ".", "');'", ")", ";", "return", "new", "CompiledExpression", "(", "'reference'", ",", "$", "symbolVariable", "->", "getRealName", "(", ")", ",", "$", "expression", ")", ";", "}" ]
Compiles a reference to a value. @param array $expression @param CompilationContext $compilationContext @return CompiledExpression
[ "Compiles", "a", "reference", "to", "a", "value", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/Expression/Reference.php#L164-L216
train
phalcon/zephir
Library/BranchGraph.php
BranchGraph.addLeaf
public function addLeaf(Branch $branch) { if (isset($this->branchMap[$branch->getUniqueId()])) { $branchNode = $this->branchMap[$branch->getUniqueId()]; } else { $branchNode = new BranchGraphNode($branch); } $branchNode->increase(); $tempBranch = $branch->getParentBranch(); while ($tempBranch) { if (isset($this->branchMap[$tempBranch->getUniqueId()])) { $parentBranchNode = $this->branchMap[$tempBranch->getUniqueId()]; } else { $parentBranchNode = new BranchGraphNode($tempBranch); $this->branchMap[$tempBranch->getUniqueId()] = $parentBranchNode; } $parentBranchNode->insert($branchNode); $branchNode = $parentBranchNode; $tempBranch = $tempBranch->getParentBranch(); if (!$tempBranch) { $this->root = $parentBranchNode; } } }
php
public function addLeaf(Branch $branch) { if (isset($this->branchMap[$branch->getUniqueId()])) { $branchNode = $this->branchMap[$branch->getUniqueId()]; } else { $branchNode = new BranchGraphNode($branch); } $branchNode->increase(); $tempBranch = $branch->getParentBranch(); while ($tempBranch) { if (isset($this->branchMap[$tempBranch->getUniqueId()])) { $parentBranchNode = $this->branchMap[$tempBranch->getUniqueId()]; } else { $parentBranchNode = new BranchGraphNode($tempBranch); $this->branchMap[$tempBranch->getUniqueId()] = $parentBranchNode; } $parentBranchNode->insert($branchNode); $branchNode = $parentBranchNode; $tempBranch = $tempBranch->getParentBranch(); if (!$tempBranch) { $this->root = $parentBranchNode; } } }
[ "public", "function", "addLeaf", "(", "Branch", "$", "branch", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "branchMap", "[", "$", "branch", "->", "getUniqueId", "(", ")", "]", ")", ")", "{", "$", "branchNode", "=", "$", "this", "->", "branchMap", "[", "$", "branch", "->", "getUniqueId", "(", ")", "]", ";", "}", "else", "{", "$", "branchNode", "=", "new", "BranchGraphNode", "(", "$", "branch", ")", ";", "}", "$", "branchNode", "->", "increase", "(", ")", ";", "$", "tempBranch", "=", "$", "branch", "->", "getParentBranch", "(", ")", ";", "while", "(", "$", "tempBranch", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "branchMap", "[", "$", "tempBranch", "->", "getUniqueId", "(", ")", "]", ")", ")", "{", "$", "parentBranchNode", "=", "$", "this", "->", "branchMap", "[", "$", "tempBranch", "->", "getUniqueId", "(", ")", "]", ";", "}", "else", "{", "$", "parentBranchNode", "=", "new", "BranchGraphNode", "(", "$", "tempBranch", ")", ";", "$", "this", "->", "branchMap", "[", "$", "tempBranch", "->", "getUniqueId", "(", ")", "]", "=", "$", "parentBranchNode", ";", "}", "$", "parentBranchNode", "->", "insert", "(", "$", "branchNode", ")", ";", "$", "branchNode", "=", "$", "parentBranchNode", ";", "$", "tempBranch", "=", "$", "tempBranch", "->", "getParentBranch", "(", ")", ";", "if", "(", "!", "$", "tempBranch", ")", "{", "$", "this", "->", "root", "=", "$", "parentBranchNode", ";", "}", "}", "}" ]
Adds a leaf to the branch tree. @param Branch $branch
[ "Adds", "a", "leaf", "to", "the", "branch", "tree", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/BranchGraph.php#L30-L54
train
phalcon/zephir
Library/SymbolTable.php
SymbolTable.hasVariable
public function hasVariable($name, CompilationContext $compilationContext = null) { return false !== $this->getVariable($name, $compilationContext ?: $this->compilationContext); }
php
public function hasVariable($name, CompilationContext $compilationContext = null) { return false !== $this->getVariable($name, $compilationContext ?: $this->compilationContext); }
[ "public", "function", "hasVariable", "(", "$", "name", ",", "CompilationContext", "$", "compilationContext", "=", "null", ")", "{", "return", "false", "!==", "$", "this", "->", "getVariable", "(", "$", "name", ",", "$", "compilationContext", "?", ":", "$", "this", "->", "compilationContext", ")", ";", "}" ]
Check if a variable is declared in the current symbol table. @param string $name @param CompilationContext $compilationContext @return bool
[ "Check", "if", "a", "variable", "is", "declared", "in", "the", "current", "symbol", "table", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/SymbolTable.php#L115-L118
train
phalcon/zephir
Library/SymbolTable.php
SymbolTable.addVariable
public function addVariable($type, $name, CompilationContext $compilationContext) { $currentBranch = $compilationContext->branchManager->getCurrentBranch(); $branchId = $currentBranch->getUniqueId(); if ($this->globalsManager->isSuperGlobal($name) || 'zephir_fcall_cache_entry' == $type) { $branchId = 1; } $varName = $name; if ($branchId > 1 && Branch::TYPE_ROOT != $currentBranch->getType()) { $varName = $name.Variable::BRANCH_MAGIC.$branchId; } $variable = new Variable($type, $varName, $currentBranch); /* * Checks whether a variable can be optimized to be static or not */ if ('variable' == $type && $this->localContext && $this->localContext->shouldBeLocal($name)) { $variable->setLocalOnly(true); } if (!isset($this->branchVariables[$branchId])) { $this->branchVariables[$branchId] = []; } $this->branchVariables[$branchId][$name] = $variable; return $variable; }
php
public function addVariable($type, $name, CompilationContext $compilationContext) { $currentBranch = $compilationContext->branchManager->getCurrentBranch(); $branchId = $currentBranch->getUniqueId(); if ($this->globalsManager->isSuperGlobal($name) || 'zephir_fcall_cache_entry' == $type) { $branchId = 1; } $varName = $name; if ($branchId > 1 && Branch::TYPE_ROOT != $currentBranch->getType()) { $varName = $name.Variable::BRANCH_MAGIC.$branchId; } $variable = new Variable($type, $varName, $currentBranch); /* * Checks whether a variable can be optimized to be static or not */ if ('variable' == $type && $this->localContext && $this->localContext->shouldBeLocal($name)) { $variable->setLocalOnly(true); } if (!isset($this->branchVariables[$branchId])) { $this->branchVariables[$branchId] = []; } $this->branchVariables[$branchId][$name] = $variable; return $variable; }
[ "public", "function", "addVariable", "(", "$", "type", ",", "$", "name", ",", "CompilationContext", "$", "compilationContext", ")", "{", "$", "currentBranch", "=", "$", "compilationContext", "->", "branchManager", "->", "getCurrentBranch", "(", ")", ";", "$", "branchId", "=", "$", "currentBranch", "->", "getUniqueId", "(", ")", ";", "if", "(", "$", "this", "->", "globalsManager", "->", "isSuperGlobal", "(", "$", "name", ")", "||", "'zephir_fcall_cache_entry'", "==", "$", "type", ")", "{", "$", "branchId", "=", "1", ";", "}", "$", "varName", "=", "$", "name", ";", "if", "(", "$", "branchId", ">", "1", "&&", "Branch", "::", "TYPE_ROOT", "!=", "$", "currentBranch", "->", "getType", "(", ")", ")", "{", "$", "varName", "=", "$", "name", ".", "Variable", "::", "BRANCH_MAGIC", ".", "$", "branchId", ";", "}", "$", "variable", "=", "new", "Variable", "(", "$", "type", ",", "$", "varName", ",", "$", "currentBranch", ")", ";", "/*\n * Checks whether a variable can be optimized to be static or not\n */", "if", "(", "'variable'", "==", "$", "type", "&&", "$", "this", "->", "localContext", "&&", "$", "this", "->", "localContext", "->", "shouldBeLocal", "(", "$", "name", ")", ")", "{", "$", "variable", "->", "setLocalOnly", "(", "true", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "branchVariables", "[", "$", "branchId", "]", ")", ")", "{", "$", "this", "->", "branchVariables", "[", "$", "branchId", "]", "=", "[", "]", ";", "}", "$", "this", "->", "branchVariables", "[", "$", "branchId", "]", "[", "$", "name", "]", "=", "$", "variable", ";", "return", "$", "variable", ";", "}" ]
Adds a variable to the symbol table. @param int $type @param string $name @param CompilationContext $compilationContext @return Variable
[ "Adds", "a", "variable", "to", "the", "symbol", "table", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/SymbolTable.php#L136-L165
train
phalcon/zephir
Library/SymbolTable.php
SymbolTable.getVariable
public function getVariable($name, $compilationContext = null) { /* Check if the variable already is referencing a branch */ $pos = strpos($name, Variable::BRANCH_MAGIC); if ($pos > -1) { $branchId = (int) (substr($name, $pos + \strlen(Variable::BRANCH_MAGIC))); $name = substr($name, 0, $pos); } else { $branch = $this->resolveVariableToBranch($name, $compilationContext ?: $this->compilationContext); if (!$branch) { return false; } $branchId = $branch->getUniqueId(); } if (!isset($this->branchVariables[$branchId]) || !isset($this->branchVariables[$branchId][$name])) { return false; } return $this->branchVariables[$branchId][$name]; }
php
public function getVariable($name, $compilationContext = null) { /* Check if the variable already is referencing a branch */ $pos = strpos($name, Variable::BRANCH_MAGIC); if ($pos > -1) { $branchId = (int) (substr($name, $pos + \strlen(Variable::BRANCH_MAGIC))); $name = substr($name, 0, $pos); } else { $branch = $this->resolveVariableToBranch($name, $compilationContext ?: $this->compilationContext); if (!$branch) { return false; } $branchId = $branch->getUniqueId(); } if (!isset($this->branchVariables[$branchId]) || !isset($this->branchVariables[$branchId][$name])) { return false; } return $this->branchVariables[$branchId][$name]; }
[ "public", "function", "getVariable", "(", "$", "name", ",", "$", "compilationContext", "=", "null", ")", "{", "/* Check if the variable already is referencing a branch */", "$", "pos", "=", "strpos", "(", "$", "name", ",", "Variable", "::", "BRANCH_MAGIC", ")", ";", "if", "(", "$", "pos", ">", "-", "1", ")", "{", "$", "branchId", "=", "(", "int", ")", "(", "substr", "(", "$", "name", ",", "$", "pos", "+", "\\", "strlen", "(", "Variable", "::", "BRANCH_MAGIC", ")", ")", ")", ";", "$", "name", "=", "substr", "(", "$", "name", ",", "0", ",", "$", "pos", ")", ";", "}", "else", "{", "$", "branch", "=", "$", "this", "->", "resolveVariableToBranch", "(", "$", "name", ",", "$", "compilationContext", "?", ":", "$", "this", "->", "compilationContext", ")", ";", "if", "(", "!", "$", "branch", ")", "{", "return", "false", ";", "}", "$", "branchId", "=", "$", "branch", "->", "getUniqueId", "(", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "branchVariables", "[", "$", "branchId", "]", ")", "||", "!", "isset", "(", "$", "this", "->", "branchVariables", "[", "$", "branchId", "]", "[", "$", "name", "]", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "branchVariables", "[", "$", "branchId", "]", "[", "$", "name", "]", ";", "}" ]
Returns a variable in the symbol table. @param $name @param CompilationContext $compilationContext @return bool|\Zephir\Variable
[ "Returns", "a", "variable", "in", "the", "symbol", "table", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/SymbolTable.php#L192-L211
train
phalcon/zephir
Library/SymbolTable.php
SymbolTable.getVariables
public function getVariables() { $ret = []; foreach ($this->branchVariables as $branchId => $vars) { foreach ($vars as $var) { $ret[$var->getName()] = $var; } } return $ret; }
php
public function getVariables() { $ret = []; foreach ($this->branchVariables as $branchId => $vars) { foreach ($vars as $var) { $ret[$var->getName()] = $var; } } return $ret; }
[ "public", "function", "getVariables", "(", ")", "{", "$", "ret", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "branchVariables", "as", "$", "branchId", "=>", "$", "vars", ")", "{", "foreach", "(", "$", "vars", "as", "$", "var", ")", "{", "$", "ret", "[", "$", "var", "->", "getName", "(", ")", "]", "=", "$", "var", ";", "}", "}", "return", "$", "ret", ";", "}" ]
Returns all the variables defined in the symbol table. @return Variable[]
[ "Returns", "all", "the", "variables", "defined", "in", "the", "symbol", "table", "." ]
2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773
https://github.com/phalcon/zephir/blob/2a5b0f3c9d936a0a7d8477adda6cb8aa0fe28773/Library/SymbolTable.php#L218-L228
train