repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
TheDMSGroup/mautic-contact-client
Helper/TokenHelper.php
TokenHelper.handleMustacheErrors
private function handleMustacheErrors($errno, $errstr, $errfile, $errline) { if (!empty($this->lastTemplate)) { if (function_exists('newrelic_add_custom_parameter')) { call_user_func( 'newrelic_add_custom_parameter', 'contactclientToken', $this->lastTemplate ); } } if (!empty($this->context)) { if (function_exists('newrelic_add_custom_parameter')) { call_user_func( 'newrelic_add_custom_parameter', 'contactclientContext', json_encode($this->context) ); } } $this->logger->error( 'Contact Client '.$this->contactClient->getId(). ': Warning issued with Template: '.$this->lastTemplate.' Context: '.json_encode($this->context) ); return true; }
php
private function handleMustacheErrors($errno, $errstr, $errfile, $errline) { if (!empty($this->lastTemplate)) { if (function_exists('newrelic_add_custom_parameter')) { call_user_func( 'newrelic_add_custom_parameter', 'contactclientToken', $this->lastTemplate ); } } if (!empty($this->context)) { if (function_exists('newrelic_add_custom_parameter')) { call_user_func( 'newrelic_add_custom_parameter', 'contactclientContext', json_encode($this->context) ); } } $this->logger->error( 'Contact Client '.$this->contactClient->getId(). ': Warning issued with Template: '.$this->lastTemplate.' Context: '.json_encode($this->context) ); return true; }
[ "private", "function", "handleMustacheErrors", "(", "$", "errno", ",", "$", "errstr", ",", "$", "errfile", ",", "$", "errline", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "lastTemplate", ")", ")", "{", "if", "(", "function_exists", "(", "'newrelic_add_custom_parameter'", ")", ")", "{", "call_user_func", "(", "'newrelic_add_custom_parameter'", ",", "'contactclientToken'", ",", "$", "this", "->", "lastTemplate", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "context", ")", ")", "{", "if", "(", "function_exists", "(", "'newrelic_add_custom_parameter'", ")", ")", "{", "call_user_func", "(", "'newrelic_add_custom_parameter'", ",", "'contactclientContext'", ",", "json_encode", "(", "$", "this", "->", "context", ")", ")", ";", "}", "}", "$", "this", "->", "logger", "->", "error", "(", "'Contact Client '", ".", "$", "this", "->", "contactClient", "->", "getId", "(", ")", ".", "': Warning issued with Template: '", ".", "$", "this", "->", "lastTemplate", ".", "' Context: '", ".", "json_encode", "(", "$", "this", "->", "context", ")", ")", ";", "return", "true", ";", "}" ]
Capture Mustache warnings to be logged for debugging. @param $errno @param $errstr @param $errfile @param $errline @return bool
[ "Capture", "Mustache", "warnings", "to", "be", "logged", "for", "debugging", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1480-L1506
TheDMSGroup/mautic-contact-client
Helper/TokenHelper.php
TokenHelper.eventTokenDecode
private function eventTokenDecode($string) { list($campaignIdString, $eventIdString, $contactIdString) = explode('0', $string); return [ $this->baseDecode($campaignIdString), $this->baseDecode($eventIdString), $this->baseDecode($contactIdString), ]; }
php
private function eventTokenDecode($string) { list($campaignIdString, $eventIdString, $contactIdString) = explode('0', $string); return [ $this->baseDecode($campaignIdString), $this->baseDecode($eventIdString), $this->baseDecode($contactIdString), ]; }
[ "private", "function", "eventTokenDecode", "(", "$", "string", ")", "{", "list", "(", "$", "campaignIdString", ",", "$", "eventIdString", ",", "$", "contactIdString", ")", "=", "explode", "(", "'0'", ",", "$", "string", ")", ";", "return", "[", "$", "this", "->", "baseDecode", "(", "$", "campaignIdString", ")", ",", "$", "this", "->", "baseDecode", "(", "$", "eventIdString", ")", ",", "$", "this", "->", "baseDecode", "(", "$", "contactIdString", ")", ",", "]", ";", "}" ]
Take a string from eventTokenEncode and reverse it to an array. NOTE: Not currently in use, but likely to be used in the future. @param $string @return array
[ "Take", "a", "string", "from", "eventTokenEncode", "and", "reverse", "it", "to", "an", "array", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1517-L1526
TheDMSGroup/mautic-contact-client
Helper/TokenHelper.php
TokenHelper.baseDecode
private function baseDecode($string) { $b = 61; $base = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $limit = strlen($string); $result = strpos($base, $string[0]); for ($i = 1; $i < $limit; ++$i) { $result = $b * $result + strpos($base, $string[$i]); } return $result; }
php
private function baseDecode($string) { $b = 61; $base = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $limit = strlen($string); $result = strpos($base, $string[0]); for ($i = 1; $i < $limit; ++$i) { $result = $b * $result + strpos($base, $string[$i]); } return $result; }
[ "private", "function", "baseDecode", "(", "$", "string", ")", "{", "$", "b", "=", "61", ";", "$", "base", "=", "'123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'", ";", "$", "limit", "=", "strlen", "(", "$", "string", ")", ";", "$", "result", "=", "strpos", "(", "$", "base", ",", "$", "string", "[", "0", "]", ")", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "$", "limit", ";", "++", "$", "i", ")", "{", "$", "result", "=", "$", "b", "*", "$", "result", "+", "strpos", "(", "$", "base", ",", "$", "string", "[", "$", "i", "]", ")", ";", "}", "return", "$", "result", ";", "}" ]
@param $string @return bool|float|int
[ "@param", "$string" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/TokenHelper.php#L1533-L1544
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.__isset
public function __isset($key) { $format = $this->validateFormat($key); if (!$format) { list($op, $format) = $this->validateDiff($key); } return (bool) $format; }
php
public function __isset($key) { $format = $this->validateFormat($key); if (!$format) { list($op, $format) = $this->validateDiff($key); } return (bool) $format; }
[ "public", "function", "__isset", "(", "$", "key", ")", "{", "$", "format", "=", "$", "this", "->", "validateFormat", "(", "$", "key", ")", ";", "if", "(", "!", "$", "format", ")", "{", "list", "(", "$", "op", ",", "$", "format", ")", "=", "$", "this", "->", "validateDiff", "(", "$", "key", ")", ";", "}", "return", "(", "bool", ")", "$", "format", ";", "}" ]
@param $key @return bool
[ "@param", "$key" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L145-L154
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.validateFormat
private function validateFormat($format) { if (isset($this->formatsDate[$format])) { return $this->formatsDate[$format]; } if (isset($this->formatsTime[$format])) { return $this->formatsTime[$format]; } $format = strtolower($format); if (isset($this->formatsDate[$format])) { return $this->formatsDate[$format]; } if (isset($this->formatsTime[$format])) { return $this->formatsTime[$format]; } }
php
private function validateFormat($format) { if (isset($this->formatsDate[$format])) { return $this->formatsDate[$format]; } if (isset($this->formatsTime[$format])) { return $this->formatsTime[$format]; } $format = strtolower($format); if (isset($this->formatsDate[$format])) { return $this->formatsDate[$format]; } if (isset($this->formatsTime[$format])) { return $this->formatsTime[$format]; } }
[ "private", "function", "validateFormat", "(", "$", "format", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "formatsDate", "[", "$", "format", "]", ")", ")", "{", "return", "$", "this", "->", "formatsDate", "[", "$", "format", "]", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "formatsTime", "[", "$", "format", "]", ")", ")", "{", "return", "$", "this", "->", "formatsTime", "[", "$", "format", "]", ";", "}", "$", "format", "=", "strtolower", "(", "$", "format", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "formatsDate", "[", "$", "format", "]", ")", ")", "{", "return", "$", "this", "->", "formatsDate", "[", "$", "format", "]", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "formatsTime", "[", "$", "format", "]", ")", ")", "{", "return", "$", "this", "->", "formatsTime", "[", "$", "format", "]", ";", "}", "}" ]
@param $format @return mixed|string
[ "@param", "$format" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L161-L176
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.validateDiff
private function validateDiff($format) { $keywords = [ 'from', 'since', 'age', 'till', 'until', ]; $op = null; foreach ($keywords as $keyword) { $len = strlen($keyword); if (substr($format, -$len) === $keyword) { $op = $keyword; $format = substr($format, 0, strlen($format) - $len); if (!$format && 'age' == $op) { $format = 'years'; } break; } } return [$op, isset($this->formatInterval[$format]) ? $this->formatInterval[$format] : null]; }
php
private function validateDiff($format) { $keywords = [ 'from', 'since', 'age', 'till', 'until', ]; $op = null; foreach ($keywords as $keyword) { $len = strlen($keyword); if (substr($format, -$len) === $keyword) { $op = $keyword; $format = substr($format, 0, strlen($format) - $len); if (!$format && 'age' == $op) { $format = 'years'; } break; } } return [$op, isset($this->formatInterval[$format]) ? $this->formatInterval[$format] : null]; }
[ "private", "function", "validateDiff", "(", "$", "format", ")", "{", "$", "keywords", "=", "[", "'from'", ",", "'since'", ",", "'age'", ",", "'till'", ",", "'until'", ",", "]", ";", "$", "op", "=", "null", ";", "foreach", "(", "$", "keywords", "as", "$", "keyword", ")", "{", "$", "len", "=", "strlen", "(", "$", "keyword", ")", ";", "if", "(", "substr", "(", "$", "format", ",", "-", "$", "len", ")", "===", "$", "keyword", ")", "{", "$", "op", "=", "$", "keyword", ";", "$", "format", "=", "substr", "(", "$", "format", ",", "0", ",", "strlen", "(", "$", "format", ")", "-", "$", "len", ")", ";", "if", "(", "!", "$", "format", "&&", "'age'", "==", "$", "op", ")", "{", "$", "format", "=", "'years'", ";", "}", "break", ";", "}", "}", "return", "[", "$", "op", ",", "isset", "(", "$", "this", "->", "formatInterval", "[", "$", "format", "]", ")", "?", "$", "this", "->", "formatInterval", "[", "$", "format", "]", ":", "null", "]", ";", "}" ]
@param $format @return array
[ "@param", "$format" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L183-L206
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.parse
private function parse($date, $timezone = null) { if (!($date instanceof \DateTime)) { if (false === strtotime($date)) { throw new \Exception('Invalid date not parsed.'); } if (!$timezone) { $timezone = $this->timezoneSource; } $date = new \DateTime($date, new \DateTimeZone($timezone)); } return $date; }
php
private function parse($date, $timezone = null) { if (!($date instanceof \DateTime)) { if (false === strtotime($date)) { throw new \Exception('Invalid date not parsed.'); } if (!$timezone) { $timezone = $this->timezoneSource; } $date = new \DateTime($date, new \DateTimeZone($timezone)); } return $date; }
[ "private", "function", "parse", "(", "$", "date", ",", "$", "timezone", "=", "null", ")", "{", "if", "(", "!", "(", "$", "date", "instanceof", "\\", "DateTime", ")", ")", "{", "if", "(", "false", "===", "strtotime", "(", "$", "date", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Invalid date not parsed.'", ")", ";", "}", "if", "(", "!", "$", "timezone", ")", "{", "$", "timezone", "=", "$", "this", "->", "timezoneSource", ";", "}", "$", "date", "=", "new", "\\", "DateTime", "(", "$", "date", ",", "new", "\\", "DateTimeZone", "(", "$", "timezone", ")", ")", ";", "}", "return", "$", "date", ";", "}" ]
Parse a string into a DateTime. @param string $date @param string $timezone @return \DateTime @throws \Exception
[ "Parse", "a", "string", "into", "a", "DateTime", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L316-L331
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.getIntervalUnits
private function getIntervalUnits(\DateTime $date1, \DateTime $date2, string $intervalFormat) { $result = 0; try { $interval = new \DateInterval($intervalFormat); $periods = new \DatePeriod($date1, $interval, $date2); $result = max(0, iterator_count($periods) - 1); } catch (\Exception $e) { } return $result; }
php
private function getIntervalUnits(\DateTime $date1, \DateTime $date2, string $intervalFormat) { $result = 0; try { $interval = new \DateInterval($intervalFormat); $periods = new \DatePeriod($date1, $interval, $date2); $result = max(0, iterator_count($periods) - 1); } catch (\Exception $e) { } return $result; }
[ "private", "function", "getIntervalUnits", "(", "\\", "DateTime", "$", "date1", ",", "\\", "DateTime", "$", "date2", ",", "string", "$", "intervalFormat", ")", "{", "$", "result", "=", "0", ";", "try", "{", "$", "interval", "=", "new", "\\", "DateInterval", "(", "$", "intervalFormat", ")", ";", "$", "periods", "=", "new", "\\", "DatePeriod", "(", "$", "date1", ",", "$", "interval", ",", "$", "date2", ")", ";", "$", "result", "=", "max", "(", "0", ",", "iterator_count", "(", "$", "periods", ")", "-", "1", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "return", "$", "result", ";", "}" ]
@param \DateTime $date1 @param \DateTime $date2 @param string $intervalFormat @return int
[ "@param", "\\", "DateTime", "$date1", "@param", "\\", "DateTime", "$date2", "@param", "string", "$intervalFormat" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L340-L352
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.format
public function format($date, $format = 'iso8601', $validate = true) { $result = null; try { if ($validate) { $format = $this->validateFormat($format); } $result = $this->parse($date)->format($format); } catch (\Exception $e) { } return $result; }
php
public function format($date, $format = 'iso8601', $validate = true) { $result = null; try { if ($validate) { $format = $this->validateFormat($format); } $result = $this->parse($date)->format($format); } catch (\Exception $e) { } return $result; }
[ "public", "function", "format", "(", "$", "date", ",", "$", "format", "=", "'iso8601'", ",", "$", "validate", "=", "true", ")", "{", "$", "result", "=", "null", ";", "try", "{", "if", "(", "$", "validate", ")", "{", "$", "format", "=", "$", "this", "->", "validateFormat", "(", "$", "format", ")", ";", "}", "$", "result", "=", "$", "this", "->", "parse", "(", "$", "date", ")", "->", "format", "(", "$", "format", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "return", "$", "result", ";", "}" ]
@param $date @param string $format @param bool $validate @return null|string
[ "@param", "$date", "@param", "string", "$format", "@param", "bool", "$validate" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L361-L373
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.getFormatsDateTime
public function getFormatsDateTime($prefix = true) { $formats = $this->formatsDate; // Add other common suggestions foreach ($this->formatInterval as $key => $value) { foreach (['till', 'since'] as $op) { if ('age' == $key) { $op = ''; } $formats[$key.$op] = $value; } } foreach ($this->formatsTime as $key => $value) { $formats[$key] = $value; } return $this->prefixWithHelperName($formats, $prefix); }
php
public function getFormatsDateTime($prefix = true) { $formats = $this->formatsDate; // Add other common suggestions foreach ($this->formatInterval as $key => $value) { foreach (['till', 'since'] as $op) { if ('age' == $key) { $op = ''; } $formats[$key.$op] = $value; } } foreach ($this->formatsTime as $key => $value) { $formats[$key] = $value; } return $this->prefixWithHelperName($formats, $prefix); }
[ "public", "function", "getFormatsDateTime", "(", "$", "prefix", "=", "true", ")", "{", "$", "formats", "=", "$", "this", "->", "formatsDate", ";", "// Add other common suggestions", "foreach", "(", "$", "this", "->", "formatInterval", "as", "$", "key", "=>", "$", "value", ")", "{", "foreach", "(", "[", "'till'", ",", "'since'", "]", "as", "$", "op", ")", "{", "if", "(", "'age'", "==", "$", "key", ")", "{", "$", "op", "=", "''", ";", "}", "$", "formats", "[", "$", "key", ".", "$", "op", "]", "=", "$", "value", ";", "}", "}", "foreach", "(", "$", "this", "->", "formatsTime", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "formats", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "this", "->", "prefixWithHelperName", "(", "$", "formats", ",", "$", "prefix", ")", ";", "}" ]
@param bool $prefix @return array
[ "@param", "bool", "$prefix" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L380-L397
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.prefixWithHelperName
private function prefixWithHelperName($array, $prefix = true) { if ($prefix) { $newArray = []; foreach ($array as $key => $value) { $newArray['date.'.$key] = $value; } $array = $newArray; } return $array; }
php
private function prefixWithHelperName($array, $prefix = true) { if ($prefix) { $newArray = []; foreach ($array as $key => $value) { $newArray['date.'.$key] = $value; } $array = $newArray; } return $array; }
[ "private", "function", "prefixWithHelperName", "(", "$", "array", ",", "$", "prefix", "=", "true", ")", "{", "if", "(", "$", "prefix", ")", "{", "$", "newArray", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "newArray", "[", "'date.'", ".", "$", "key", "]", "=", "$", "value", ";", "}", "$", "array", "=", "$", "newArray", ";", "}", "return", "$", "array", ";", "}" ]
@param $array @param bool $prefix @return array
[ "@param", "$array", "@param", "bool", "$prefix" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L405-L416
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.getFormatsDate
public function getFormatsDate($prefix = true) { $formats = $this->formatsDate; // Add other common suggestions foreach ($this->formatInterval as $key => $value) { foreach (['hours', 'minutes', 'seconds'] as $exclusion) { if ($key == $exclusion) { continue; } } foreach (['till', 'since'] as $op) { if ('age' == $key) { $op = ''; } $formats[$key.$op] = $value; } } return $this->prefixWithHelperName($formats, $prefix); }
php
public function getFormatsDate($prefix = true) { $formats = $this->formatsDate; // Add other common suggestions foreach ($this->formatInterval as $key => $value) { foreach (['hours', 'minutes', 'seconds'] as $exclusion) { if ($key == $exclusion) { continue; } } foreach (['till', 'since'] as $op) { if ('age' == $key) { $op = ''; } $formats[$key.$op] = $value; } } return $this->prefixWithHelperName($formats, $prefix); }
[ "public", "function", "getFormatsDate", "(", "$", "prefix", "=", "true", ")", "{", "$", "formats", "=", "$", "this", "->", "formatsDate", ";", "// Add other common suggestions", "foreach", "(", "$", "this", "->", "formatInterval", "as", "$", "key", "=>", "$", "value", ")", "{", "foreach", "(", "[", "'hours'", ",", "'minutes'", ",", "'seconds'", "]", "as", "$", "exclusion", ")", "{", "if", "(", "$", "key", "==", "$", "exclusion", ")", "{", "continue", ";", "}", "}", "foreach", "(", "[", "'till'", ",", "'since'", "]", "as", "$", "op", ")", "{", "if", "(", "'age'", "==", "$", "key", ")", "{", "$", "op", "=", "''", ";", "}", "$", "formats", "[", "$", "key", ".", "$", "op", "]", "=", "$", "value", ";", "}", "}", "return", "$", "this", "->", "prefixWithHelperName", "(", "$", "formats", ",", "$", "prefix", ")", ";", "}" ]
@param bool $prefix @return array
[ "@param", "bool", "$prefix" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L423-L442
TheDMSGroup/mautic-contact-client
Helper/DateFormatHelper.php
DateFormatHelper.getFormatsTime
public function getFormatsTime($prefix = true) { $formats = $this->formatsTime; // Add other common suggestions foreach ($this->formatInterval as $key => $value) { foreach (['months', 'years', 'days', 'age'] as $exclusion) { if ($key == $exclusion) { continue; } } foreach (['from', 'till'] as $op) { $formats[$key.$op] = $value; } } return $this->prefixWithHelperName($formats, $prefix); }
php
public function getFormatsTime($prefix = true) { $formats = $this->formatsTime; // Add other common suggestions foreach ($this->formatInterval as $key => $value) { foreach (['months', 'years', 'days', 'age'] as $exclusion) { if ($key == $exclusion) { continue; } } foreach (['from', 'till'] as $op) { $formats[$key.$op] = $value; } } return $this->prefixWithHelperName($formats, $prefix); }
[ "public", "function", "getFormatsTime", "(", "$", "prefix", "=", "true", ")", "{", "$", "formats", "=", "$", "this", "->", "formatsTime", ";", "// Add other common suggestions", "foreach", "(", "$", "this", "->", "formatInterval", "as", "$", "key", "=>", "$", "value", ")", "{", "foreach", "(", "[", "'months'", ",", "'years'", ",", "'days'", ",", "'age'", "]", "as", "$", "exclusion", ")", "{", "if", "(", "$", "key", "==", "$", "exclusion", ")", "{", "continue", ";", "}", "}", "foreach", "(", "[", "'from'", ",", "'till'", "]", "as", "$", "op", ")", "{", "$", "formats", "[", "$", "key", ".", "$", "op", "]", "=", "$", "value", ";", "}", "}", "return", "$", "this", "->", "prefixWithHelperName", "(", "$", "formats", ",", "$", "prefix", ")", ";", "}" ]
@param bool $prefix @return array
[ "@param", "bool", "$prefix" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/DateFormatHelper.php#L449-L465
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.setContactClient
public function setContactClient(ContactClient $contactClient) { $this->contactClient = $contactClient; $this->setPayload($this->contactClient->getApiPayload()); return $this; }
php
public function setContactClient(ContactClient $contactClient) { $this->contactClient = $contactClient; $this->setPayload($this->contactClient->getApiPayload()); return $this; }
[ "public", "function", "setContactClient", "(", "ContactClient", "$", "contactClient", ")", "{", "$", "this", "->", "contactClient", "=", "$", "contactClient", ";", "$", "this", "->", "setPayload", "(", "$", "this", "->", "contactClient", "->", "getApiPayload", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
@param ContactClient $contactClient @return $this @throws ContactClientException
[ "@param", "ContactClient", "$contactClient" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L213-L219
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.setPayload
private function setPayload($payload = null) { if (!$payload && $this->contactClient) { $payload = $this->contactClient->getApiPayload(); } if (!$payload) { throw new ContactClientException( 'API instructions not set.', 0, null, Stat::TYPE_INVALID, false, null, $this->contactClient ? $this->contactClient->toArray() : null ); } $jsonHelper = new JSONHelper(); try { $this->payload = $jsonHelper->decodeObject($payload, 'Payload'); } catch (\Exception $e) { throw new ContactClientException( 'API instructions malformed.', 0, $e, Stat::TYPE_INVALID, false, null, $this->contactClient ? $this->contactClient->toArray() : null ); } $this->setSettings(!empty($this->payload->settings) ? $this->payload->settings : null); return $this; }
php
private function setPayload($payload = null) { if (!$payload && $this->contactClient) { $payload = $this->contactClient->getApiPayload(); } if (!$payload) { throw new ContactClientException( 'API instructions not set.', 0, null, Stat::TYPE_INVALID, false, null, $this->contactClient ? $this->contactClient->toArray() : null ); } $jsonHelper = new JSONHelper(); try { $this->payload = $jsonHelper->decodeObject($payload, 'Payload'); } catch (\Exception $e) { throw new ContactClientException( 'API instructions malformed.', 0, $e, Stat::TYPE_INVALID, false, null, $this->contactClient ? $this->contactClient->toArray() : null ); } $this->setSettings(!empty($this->payload->settings) ? $this->payload->settings : null); return $this; }
[ "private", "function", "setPayload", "(", "$", "payload", "=", "null", ")", "{", "if", "(", "!", "$", "payload", "&&", "$", "this", "->", "contactClient", ")", "{", "$", "payload", "=", "$", "this", "->", "contactClient", "->", "getApiPayload", "(", ")", ";", "}", "if", "(", "!", "$", "payload", ")", "{", "throw", "new", "ContactClientException", "(", "'API instructions not set.'", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_INVALID", ",", "false", ",", "null", ",", "$", "this", "->", "contactClient", "?", "$", "this", "->", "contactClient", "->", "toArray", "(", ")", ":", "null", ")", ";", "}", "$", "jsonHelper", "=", "new", "JSONHelper", "(", ")", ";", "try", "{", "$", "this", "->", "payload", "=", "$", "jsonHelper", "->", "decodeObject", "(", "$", "payload", ",", "'Payload'", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "ContactClientException", "(", "'API instructions malformed.'", ",", "0", ",", "$", "e", ",", "Stat", "::", "TYPE_INVALID", ",", "false", ",", "null", ",", "$", "this", "->", "contactClient", "?", "$", "this", "->", "contactClient", "->", "toArray", "(", ")", ":", "null", ")", ";", "}", "$", "this", "->", "setSettings", "(", "!", "empty", "(", "$", "this", "->", "payload", "->", "settings", ")", "?", "$", "this", "->", "payload", "->", "settings", ":", "null", ")", ";", "return", "$", "this", ";", "}" ]
Take the stored JSON string and parse for use. @param string|null $payload @return $this @throws ContactClientException
[ "Take", "the", "stored", "JSON", "string", "and", "parse", "for", "use", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L230-L264
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.setSettings
private function setSettings($settings) { if ($settings) { foreach ($this->settings as $key => &$value) { if (!empty($settings->{$key}) && $settings->{$key}) { $value = $settings->{$key}; } } } }
php
private function setSettings($settings) { if ($settings) { foreach ($this->settings as $key => &$value) { if (!empty($settings->{$key}) && $settings->{$key}) { $value = $settings->{$key}; } } } }
[ "private", "function", "setSettings", "(", "$", "settings", ")", "{", "if", "(", "$", "settings", ")", "{", "foreach", "(", "$", "this", "->", "settings", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "if", "(", "!", "empty", "(", "$", "settings", "->", "{", "$", "key", "}", ")", "&&", "$", "settings", "->", "{", "$", "key", "}", ")", "{", "$", "value", "=", "$", "settings", "->", "{", "$", "key", "}", ";", "}", "}", "}", "}" ]
Retrieve API settings from the payload to override our defaults. @param object $settings
[ "Retrieve", "API", "settings", "from", "the", "payload", "to", "override", "our", "defaults", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L271-L280
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.evaluateSchedule
public function evaluateSchedule() { $this->scheduleModel->reset() ->setContactClient($this->contactClient) ->setTimezone() ->evaluateDay() ->evaluateTime() ->evaluateExclusions(); return new \DateTime(); }
php
public function evaluateSchedule() { $this->scheduleModel->reset() ->setContactClient($this->contactClient) ->setTimezone() ->evaluateDay() ->evaluateTime() ->evaluateExclusions(); return new \DateTime(); }
[ "public", "function", "evaluateSchedule", "(", ")", "{", "$", "this", "->", "scheduleModel", "->", "reset", "(", ")", "->", "setContactClient", "(", "$", "this", "->", "contactClient", ")", "->", "setTimezone", "(", ")", "->", "evaluateDay", "(", ")", "->", "evaluateTime", "(", ")", "->", "evaluateExclusions", "(", ")", ";", "return", "new", "\\", "DateTime", "(", ")", ";", "}" ]
Returns the expected send time for limit evaluation. Throws an exception if an open slot is not available. @return \DateTime @throws ContactClientException
[ "Returns", "the", "expected", "send", "time", "for", "limit", "evaluation", ".", "Throws", "an", "exception", "if", "an", "open", "slot", "is", "not", "available", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L310-L320
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.run
public function run() { $this->validateOperations(); $this->prepareTransport(); $this->prepareTokenHelper(); $this->preparePayloadAuth(); try { $this->runApiOperations(); } catch (\Exception $e) { if ( $this->start && $e instanceof ContactClientException && Stat::TYPE_AUTH === $e->getStatType() ) { // We failed the pre-auth run due to an auth-related issue. Flush the tokenHelper. $this->prepareTokenHelper(); // Try a standard run from the top assuming authentication is needed again. $this->start = 0; $this->runApiOperations(); } else { throw $e; } } return $this; }
php
public function run() { $this->validateOperations(); $this->prepareTransport(); $this->prepareTokenHelper(); $this->preparePayloadAuth(); try { $this->runApiOperations(); } catch (\Exception $e) { if ( $this->start && $e instanceof ContactClientException && Stat::TYPE_AUTH === $e->getStatType() ) { // We failed the pre-auth run due to an auth-related issue. Flush the tokenHelper. $this->prepareTokenHelper(); // Try a standard run from the top assuming authentication is needed again. $this->start = 0; $this->runApiOperations(); } else { throw $e; } } return $this; }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "validateOperations", "(", ")", ";", "$", "this", "->", "prepareTransport", "(", ")", ";", "$", "this", "->", "prepareTokenHelper", "(", ")", ";", "$", "this", "->", "preparePayloadAuth", "(", ")", ";", "try", "{", "$", "this", "->", "runApiOperations", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "this", "->", "start", "&&", "$", "e", "instanceof", "ContactClientException", "&&", "Stat", "::", "TYPE_AUTH", "===", "$", "e", "->", "getStatType", "(", ")", ")", "{", "// We failed the pre-auth run due to an auth-related issue. Flush the tokenHelper.", "$", "this", "->", "prepareTokenHelper", "(", ")", ";", "// Try a standard run from the top assuming authentication is needed again.", "$", "this", "->", "start", "=", "0", ";", "$", "this", "->", "runApiOperations", "(", ")", ";", "}", "else", "{", "throw", "$", "e", ";", "}", "}", "return", "$", "this", ";", "}" ]
Step through all operations defined. @return $this @throws ContactClientException
[ "Step", "through", "all", "operations", "defined", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L329-L355
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.prepareTokenHelper
private function prepareTokenHelper() { $this->tokenHelper->newSession( $this->contactClient, $this->contact, $this->payload, $this->campaign, $this->event ); // Add any additional tokens here that are only needed for API payloads. $this->tokenHelper->addContext( [ 'api_date' => $this->tokenHelper->getDateFormatHelper()->format(new \DateTime()), ] ); }
php
private function prepareTokenHelper() { $this->tokenHelper->newSession( $this->contactClient, $this->contact, $this->payload, $this->campaign, $this->event ); // Add any additional tokens here that are only needed for API payloads. $this->tokenHelper->addContext( [ 'api_date' => $this->tokenHelper->getDateFormatHelper()->format(new \DateTime()), ] ); }
[ "private", "function", "prepareTokenHelper", "(", ")", "{", "$", "this", "->", "tokenHelper", "->", "newSession", "(", "$", "this", "->", "contactClient", ",", "$", "this", "->", "contact", ",", "$", "this", "->", "payload", ",", "$", "this", "->", "campaign", ",", "$", "this", "->", "event", ")", ";", "// Add any additional tokens here that are only needed for API payloads.", "$", "this", "->", "tokenHelper", "->", "addContext", "(", "[", "'api_date'", "=>", "$", "this", "->", "tokenHelper", "->", "getDateFormatHelper", "(", ")", "->", "format", "(", "new", "\\", "DateTime", "(", ")", ")", ",", "]", ")", ";", "}" ]
Apply our context to create a new tokenhelper session.
[ "Apply", "our", "context", "to", "create", "a", "new", "tokenhelper", "session", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L389-L404
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.preparePayloadAuth
private function preparePayloadAuth() { $this->apiPayloadAuth->reset() ->setTest($this->test) ->setContactClient($this->contactClient) ->setOperations($this->payload->operations); $this->start = $this->apiPayloadAuth->getStartOperation(); if ($this->start) { $context = $this->apiPayloadAuth->getPreviousPayloadAuthTokens(); $this->tokenHelper->addContext($context); } }
php
private function preparePayloadAuth() { $this->apiPayloadAuth->reset() ->setTest($this->test) ->setContactClient($this->contactClient) ->setOperations($this->payload->operations); $this->start = $this->apiPayloadAuth->getStartOperation(); if ($this->start) { $context = $this->apiPayloadAuth->getPreviousPayloadAuthTokens(); $this->tokenHelper->addContext($context); } }
[ "private", "function", "preparePayloadAuth", "(", ")", "{", "$", "this", "->", "apiPayloadAuth", "->", "reset", "(", ")", "->", "setTest", "(", "$", "this", "->", "test", ")", "->", "setContactClient", "(", "$", "this", "->", "contactClient", ")", "->", "setOperations", "(", "$", "this", "->", "payload", "->", "operations", ")", ";", "$", "this", "->", "start", "=", "$", "this", "->", "apiPayloadAuth", "->", "getStartOperation", "(", ")", ";", "if", "(", "$", "this", "->", "start", ")", "{", "$", "context", "=", "$", "this", "->", "apiPayloadAuth", "->", "getPreviousPayloadAuthTokens", "(", ")", ";", "$", "this", "->", "tokenHelper", "->", "addContext", "(", "$", "context", ")", ";", "}", "}" ]
Prepare the APIPayloadAuth model and get the starting operation ID it reccomends.
[ "Prepare", "the", "APIPayloadAuth", "model", "and", "get", "the", "starting", "operation", "ID", "it", "reccomends", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L409-L421
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.savePayloadAuthTokens
private function savePayloadAuthTokens($operationId) { if ( $this->valid && $this->apiPayloadAuth->hasAuthRequest($operationId) ) { $fieldSets = $this->getAggregateActualResponses(null, $operationId); $this->apiPayloadAuth->savePayloadAuthTokens($operationId, $fieldSets); } }
php
private function savePayloadAuthTokens($operationId) { if ( $this->valid && $this->apiPayloadAuth->hasAuthRequest($operationId) ) { $fieldSets = $this->getAggregateActualResponses(null, $operationId); $this->apiPayloadAuth->savePayloadAuthTokens($operationId, $fieldSets); } }
[ "private", "function", "savePayloadAuthTokens", "(", "$", "operationId", ")", "{", "if", "(", "$", "this", "->", "valid", "&&", "$", "this", "->", "apiPayloadAuth", "->", "hasAuthRequest", "(", "$", "operationId", ")", ")", "{", "$", "fieldSets", "=", "$", "this", "->", "getAggregateActualResponses", "(", "null", ",", "$", "operationId", ")", ";", "$", "this", "->", "apiPayloadAuth", "->", "savePayloadAuthTokens", "(", "$", "operationId", ",", "$", "fieldSets", ")", ";", "}", "}" ]
If we just made a successful run with an auth operation, without skipping said operation, preserve the applicable auth tokens for future use. @param $operationId
[ "If", "we", "just", "made", "a", "successful", "run", "with", "an", "auth", "operation", "without", "skipping", "said", "operation", "preserve", "the", "applicable", "auth", "tokens", "for", "future", "use", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L507-L516
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.getAggregateActualResponses
public function getAggregateActualResponses($key = null, $operationId = null, $types = ['headers', 'body']) { if ($this->valid && isset($this->aggregateActualResponses)) { if (null !== $key) { foreach ($types as $type) { if (null !== $operationId) { if (isset($this->aggregateActualResponses[$operationId][$type][$key])) { return $this->aggregateActualResponses[$operationId][$type][$key]; } } else { foreach (array_reverse($this->aggregateActualResponses) as $values) { if (isset($values[$type][$key])) { return $values[$type][$key]; } } } } } else { // Get the entire result, separated by types. $result = []; foreach ($types as $type) { if (isset($this->aggregateActualResponses[$operationId][$type])) { $result[$type] = $this->aggregateActualResponses[$operationId][$type]; } } return $result; } } return null; }
php
public function getAggregateActualResponses($key = null, $operationId = null, $types = ['headers', 'body']) { if ($this->valid && isset($this->aggregateActualResponses)) { if (null !== $key) { foreach ($types as $type) { if (null !== $operationId) { if (isset($this->aggregateActualResponses[$operationId][$type][$key])) { return $this->aggregateActualResponses[$operationId][$type][$key]; } } else { foreach (array_reverse($this->aggregateActualResponses) as $values) { if (isset($values[$type][$key])) { return $values[$type][$key]; } } } } } else { // Get the entire result, separated by types. $result = []; foreach ($types as $type) { if (isset($this->aggregateActualResponses[$operationId][$type])) { $result[$type] = $this->aggregateActualResponses[$operationId][$type]; } } return $result; } } return null; }
[ "public", "function", "getAggregateActualResponses", "(", "$", "key", "=", "null", ",", "$", "operationId", "=", "null", ",", "$", "types", "=", "[", "'headers'", ",", "'body'", "]", ")", "{", "if", "(", "$", "this", "->", "valid", "&&", "isset", "(", "$", "this", "->", "aggregateActualResponses", ")", ")", "{", "if", "(", "null", "!==", "$", "key", ")", "{", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "if", "(", "null", "!==", "$", "operationId", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", "[", "$", "key", "]", ")", ")", "{", "return", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", "[", "$", "key", "]", ";", "}", "}", "else", "{", "foreach", "(", "array_reverse", "(", "$", "this", "->", "aggregateActualResponses", ")", "as", "$", "values", ")", "{", "if", "(", "isset", "(", "$", "values", "[", "$", "type", "]", "[", "$", "key", "]", ")", ")", "{", "return", "$", "values", "[", "$", "type", "]", "[", "$", "key", "]", ";", "}", "}", "}", "}", "}", "else", "{", "// Get the entire result, separated by types.", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", ")", ")", "{", "$", "result", "[", "$", "type", "]", "=", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", ";", "}", "}", "return", "$", "result", ";", "}", "}", "return", "null", ";", "}" ]
Get the most recent non-empty response value by field name, ignoring validity. Provide key, or operationId or both. @param string $key @param int $operationId @param array $types Types to check for (header/body/etc)
[ "Get", "the", "most", "recent", "non", "-", "empty", "response", "value", "by", "field", "name", "ignoring", "validity", ".", "Provide", "key", "or", "operationId", "or", "both", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L526-L557
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.setAggregateActualResponses
public function setAggregateActualResponses($responseActual, $operationId, $types = ['headers', 'body']) { if (!isset($this->aggregateActualResponses[$operationId])) { $this->aggregateActualResponses[$operationId] = []; } foreach ($types as $type) { if (!isset($this->aggregateActualResponses[$operationId][$type])) { $this->aggregateActualResponses[$operationId][$type] = []; } if (isset($responseActual[$type])) { $this->aggregateActualResponses[$operationId][$type] = array_merge( $this->aggregateActualResponses[$operationId][$type], $responseActual[$type] ); } } return $this; }
php
public function setAggregateActualResponses($responseActual, $operationId, $types = ['headers', 'body']) { if (!isset($this->aggregateActualResponses[$operationId])) { $this->aggregateActualResponses[$operationId] = []; } foreach ($types as $type) { if (!isset($this->aggregateActualResponses[$operationId][$type])) { $this->aggregateActualResponses[$operationId][$type] = []; } if (isset($responseActual[$type])) { $this->aggregateActualResponses[$operationId][$type] = array_merge( $this->aggregateActualResponses[$operationId][$type], $responseActual[$type] ); } } return $this; }
[ "public", "function", "setAggregateActualResponses", "(", "$", "responseActual", ",", "$", "operationId", ",", "$", "types", "=", "[", "'headers'", ",", "'body'", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", ")", ")", "{", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "=", "[", "]", ";", "}", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", ")", ")", "{", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", "=", "[", "]", ";", "}", "if", "(", "isset", "(", "$", "responseActual", "[", "$", "type", "]", ")", ")", "{", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", "=", "array_merge", "(", "$", "this", "->", "aggregateActualResponses", "[", "$", "operationId", "]", "[", "$", "type", "]", ",", "$", "responseActual", "[", "$", "type", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
@param array $responseActual Actual response array, including headers and body @param null $operationId @param array $types types of data we wish to aggregate @return $this
[ "@param", "array", "$responseActual", "Actual", "response", "array", "including", "headers", "and", "body", "@param", "null", "$operationId", "@param", "array", "$types", "types", "of", "data", "we", "wish", "to", "aggregate" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L566-L584
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.applyResponseMap
public function applyResponseMap($updateTokens = false) { $responseMap = $this->getResponseMap(); // Check the responseMap to discern where field values should go. if (count($responseMap)) { foreach ($responseMap as $alias => $value) { $oldValue = $this->contact->getFieldValue($alias); if ($oldValue !== $value) { $this->contact->addUpdatedField($alias, $value, $oldValue); if ($updateTokens) { $this->tokenHelper->addContext([$alias => $value]); } $this->setLogs('Updating Contact: '.$alias.' = '.$value, 'fieldsUpdated'); $this->updatedFields = true; } } } return $this->updatedFields; }
php
public function applyResponseMap($updateTokens = false) { $responseMap = $this->getResponseMap(); // Check the responseMap to discern where field values should go. if (count($responseMap)) { foreach ($responseMap as $alias => $value) { $oldValue = $this->contact->getFieldValue($alias); if ($oldValue !== $value) { $this->contact->addUpdatedField($alias, $value, $oldValue); if ($updateTokens) { $this->tokenHelper->addContext([$alias => $value]); } $this->setLogs('Updating Contact: '.$alias.' = '.$value, 'fieldsUpdated'); $this->updatedFields = true; } } } return $this->updatedFields; }
[ "public", "function", "applyResponseMap", "(", "$", "updateTokens", "=", "false", ")", "{", "$", "responseMap", "=", "$", "this", "->", "getResponseMap", "(", ")", ";", "// Check the responseMap to discern where field values should go.", "if", "(", "count", "(", "$", "responseMap", ")", ")", "{", "foreach", "(", "$", "responseMap", "as", "$", "alias", "=>", "$", "value", ")", "{", "$", "oldValue", "=", "$", "this", "->", "contact", "->", "getFieldValue", "(", "$", "alias", ")", ";", "if", "(", "$", "oldValue", "!==", "$", "value", ")", "{", "$", "this", "->", "contact", "->", "addUpdatedField", "(", "$", "alias", ",", "$", "value", ",", "$", "oldValue", ")", ";", "if", "(", "$", "updateTokens", ")", "{", "$", "this", "->", "tokenHelper", "->", "addContext", "(", "[", "$", "alias", "=>", "$", "value", "]", ")", ";", "}", "$", "this", "->", "setLogs", "(", "'Updating Contact: '", ".", "$", "alias", ".", "' = '", ".", "$", "value", ",", "'fieldsUpdated'", ")", ";", "$", "this", "->", "updatedFields", "=", "true", ";", "}", "}", "}", "return", "$", "this", "->", "updatedFields", ";", "}" ]
Apply the responsemap to update a contact entity. @param bool $updateTokens @return bool
[ "Apply", "the", "responsemap", "to", "update", "a", "contact", "entity", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L593-L612
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.updatePayload
private function updatePayload() { if ($this->contactClient) { $this->sortPayloadFields(); $jsonHelper = new JSONHelper(); $payloadJSON = $jsonHelper->encode($this->payload, 'Payload'); $this->contactClient->setAPIPayload($payloadJSON); } }
php
private function updatePayload() { if ($this->contactClient) { $this->sortPayloadFields(); $jsonHelper = new JSONHelper(); $payloadJSON = $jsonHelper->encode($this->payload, 'Payload'); $this->contactClient->setAPIPayload($payloadJSON); } }
[ "private", "function", "updatePayload", "(", ")", "{", "if", "(", "$", "this", "->", "contactClient", ")", "{", "$", "this", "->", "sortPayloadFields", "(", ")", ";", "$", "jsonHelper", "=", "new", "JSONHelper", "(", ")", ";", "$", "payloadJSON", "=", "$", "jsonHelper", "->", "encode", "(", "$", "this", "->", "payload", ",", "'Payload'", ")", ";", "$", "this", "->", "contactClient", "->", "setAPIPayload", "(", "$", "payloadJSON", ")", ";", "}", "}" ]
Update the payload with the parent ContactClient because we've updated the response expectation.
[ "Update", "the", "payload", "with", "the", "parent", "ContactClient", "because", "we", "ve", "updated", "the", "response", "expectation", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L627-L635
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.sortPayloadFields
private function sortPayloadFields() { if (isset($this->payload->operations)) { foreach ($this->payload->operations as $id => $operation) { foreach (['request', 'response'] as $opType) { if (isset($operation->{$opType})) { foreach (['headers', 'body'] as $fieldType) { if (is_array($operation->{$opType}->{$fieldType})) { usort( $operation->{$opType}->{$fieldType}, function ($a, $b) { return strnatcmp( isset($a->key) ? $a->key : null, isset($b->key) ? $b->key : null ); } ); } } } } } } }
php
private function sortPayloadFields() { if (isset($this->payload->operations)) { foreach ($this->payload->operations as $id => $operation) { foreach (['request', 'response'] as $opType) { if (isset($operation->{$opType})) { foreach (['headers', 'body'] as $fieldType) { if (is_array($operation->{$opType}->{$fieldType})) { usort( $operation->{$opType}->{$fieldType}, function ($a, $b) { return strnatcmp( isset($a->key) ? $a->key : null, isset($b->key) ? $b->key : null ); } ); } } } } } } }
[ "private", "function", "sortPayloadFields", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "payload", "->", "operations", ")", ")", "{", "foreach", "(", "$", "this", "->", "payload", "->", "operations", "as", "$", "id", "=>", "$", "operation", ")", "{", "foreach", "(", "[", "'request'", ",", "'response'", "]", "as", "$", "opType", ")", "{", "if", "(", "isset", "(", "$", "operation", "->", "{", "$", "opType", "}", ")", ")", "{", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "fieldType", ")", "{", "if", "(", "is_array", "(", "$", "operation", "->", "{", "$", "opType", "}", "->", "{", "$", "fieldType", "}", ")", ")", "{", "usort", "(", "$", "operation", "->", "{", "$", "opType", "}", "->", "{", "$", "fieldType", "}", ",", "function", "(", "$", "a", ",", "$", "b", ")", "{", "return", "strnatcmp", "(", "isset", "(", "$", "a", "->", "key", ")", "?", "$", "a", "->", "key", ":", "null", ",", "isset", "(", "$", "b", "->", "key", ")", "?", "$", "b", "->", "key", ":", "null", ")", ";", "}", ")", ";", "}", "}", "}", "}", "}", "}", "}" ]
Sort the fields by keys, so that the user doesn't have to. Only applies when AutoUpdate is enabled.
[ "Sort", "the", "fields", "by", "keys", "so", "that", "the", "user", "doesn", "t", "have", "to", ".", "Only", "applies", "when", "AutoUpdate", "is", "enabled", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L641-L664
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.getOverrides
public function getOverrides() { $result = []; if (isset($this->payload->operations)) { foreach ($this->payload->operations as $id => $operation) { if (isset($operation->request)) { // API Payloads can optionally have their URLs overriden per request. if (isset($operation->request->overridableUrl) && true === $operation->request->overridableUrl) { $result['payload.operation.'.$id.'.request.url'] = [ 'key' => 'payload.operation.'.$id.'.request.url', 'value' => !empty($operation->request->url) ? $operation->request->url : '', ]; } foreach (['headers', 'body'] as $type) { if (isset($operation->request->{$type})) { foreach ($operation->request->{$type} as $field) { if (isset($field->overridable) && true === $field->overridable) { // Remove irrelevant data, since this result will need to be light-weight. unset($field->default_value); unset($field->test_value); unset($field->test_only); unset($field->overridable); unset($field->required); $result[(string) $field->key] = $field; } } } } } } } ksort($result); return array_values($result); }
php
public function getOverrides() { $result = []; if (isset($this->payload->operations)) { foreach ($this->payload->operations as $id => $operation) { if (isset($operation->request)) { // API Payloads can optionally have their URLs overriden per request. if (isset($operation->request->overridableUrl) && true === $operation->request->overridableUrl) { $result['payload.operation.'.$id.'.request.url'] = [ 'key' => 'payload.operation.'.$id.'.request.url', 'value' => !empty($operation->request->url) ? $operation->request->url : '', ]; } foreach (['headers', 'body'] as $type) { if (isset($operation->request->{$type})) { foreach ($operation->request->{$type} as $field) { if (isset($field->overridable) && true === $field->overridable) { // Remove irrelevant data, since this result will need to be light-weight. unset($field->default_value); unset($field->test_value); unset($field->test_only); unset($field->overridable); unset($field->required); $result[(string) $field->key] = $field; } } } } } } } ksort($result); return array_values($result); }
[ "public", "function", "getOverrides", "(", ")", "{", "$", "result", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "payload", "->", "operations", ")", ")", "{", "foreach", "(", "$", "this", "->", "payload", "->", "operations", "as", "$", "id", "=>", "$", "operation", ")", "{", "if", "(", "isset", "(", "$", "operation", "->", "request", ")", ")", "{", "// API Payloads can optionally have their URLs overriden per request.", "if", "(", "isset", "(", "$", "operation", "->", "request", "->", "overridableUrl", ")", "&&", "true", "===", "$", "operation", "->", "request", "->", "overridableUrl", ")", "{", "$", "result", "[", "'payload.operation.'", ".", "$", "id", ".", "'.request.url'", "]", "=", "[", "'key'", "=>", "'payload.operation.'", ".", "$", "id", ".", "'.request.url'", ",", "'value'", "=>", "!", "empty", "(", "$", "operation", "->", "request", "->", "url", ")", "?", "$", "operation", "->", "request", "->", "url", ":", "''", ",", "]", ";", "}", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "operation", "->", "request", "->", "{", "$", "type", "}", ")", ")", "{", "foreach", "(", "$", "operation", "->", "request", "->", "{", "$", "type", "}", "as", "$", "field", ")", "{", "if", "(", "isset", "(", "$", "field", "->", "overridable", ")", "&&", "true", "===", "$", "field", "->", "overridable", ")", "{", "// Remove irrelevant data, since this result will need to be light-weight.", "unset", "(", "$", "field", "->", "default_value", ")", ";", "unset", "(", "$", "field", "->", "test_value", ")", ";", "unset", "(", "$", "field", "->", "test_only", ")", ";", "unset", "(", "$", "field", "->", "overridable", ")", ";", "unset", "(", "$", "field", "->", "required", ")", ";", "$", "result", "[", "(", "string", ")", "$", "field", "->", "key", "]", "=", "$", "field", ";", "}", "}", "}", "}", "}", "}", "}", "ksort", "(", "$", "result", ")", ";", "return", "array_values", "(", "$", "result", ")", ";", "}" ]
Retrieve from the payload all outgoing fields that are set to overridable. @return array
[ "Retrieve", "from", "the", "payload", "all", "outgoing", "fields", "that", "are", "set", "to", "overridable", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L703-L737
TheDMSGroup/mautic-contact-client
Model/ApiPayload.php
ApiPayload.setOverrides
public function setOverrides($overrides) { $fieldsOverridden = []; if (isset($this->payload->operations)) { foreach ($this->payload->operations as $id => &$operation) { // API Payloads can optionally have their URLs overriden per request. $key = 'payload.operation.'.$id.'.request.url'; if ( isset($operation->request->overridableUrl) && true === $operation->request->overridableUrl && !empty($overrides[$key]) ) { $fieldsOverridden[$key] = [ 'key' => $key, 'value' => $overrides[$key], ]; $operation->request->url = $overrides[$key]; } if (isset($operation->request)) { foreach (['headers', 'body'] as $type) { if (isset($operation->request->{$type})) { foreach ($operation->request->{$type} as &$field) { if ( isset($field->overridable) && true === $field->overridable && isset($field->key) && isset($overrides[$field->key]) && null !== $overrides[$field->key] ) { $field->value = $overrides[$field->key]; $fieldsOverridden[$field->key] = $overrides[$field->key]; } } } } } } } if ($fieldsOverridden) { $this->setLogs($fieldsOverridden, 'fieldsOverridden'); } return $this; }
php
public function setOverrides($overrides) { $fieldsOverridden = []; if (isset($this->payload->operations)) { foreach ($this->payload->operations as $id => &$operation) { // API Payloads can optionally have their URLs overriden per request. $key = 'payload.operation.'.$id.'.request.url'; if ( isset($operation->request->overridableUrl) && true === $operation->request->overridableUrl && !empty($overrides[$key]) ) { $fieldsOverridden[$key] = [ 'key' => $key, 'value' => $overrides[$key], ]; $operation->request->url = $overrides[$key]; } if (isset($operation->request)) { foreach (['headers', 'body'] as $type) { if (isset($operation->request->{$type})) { foreach ($operation->request->{$type} as &$field) { if ( isset($field->overridable) && true === $field->overridable && isset($field->key) && isset($overrides[$field->key]) && null !== $overrides[$field->key] ) { $field->value = $overrides[$field->key]; $fieldsOverridden[$field->key] = $overrides[$field->key]; } } } } } } } if ($fieldsOverridden) { $this->setLogs($fieldsOverridden, 'fieldsOverridden'); } return $this; }
[ "public", "function", "setOverrides", "(", "$", "overrides", ")", "{", "$", "fieldsOverridden", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "payload", "->", "operations", ")", ")", "{", "foreach", "(", "$", "this", "->", "payload", "->", "operations", "as", "$", "id", "=>", "&", "$", "operation", ")", "{", "// API Payloads can optionally have their URLs overriden per request.", "$", "key", "=", "'payload.operation.'", ".", "$", "id", ".", "'.request.url'", ";", "if", "(", "isset", "(", "$", "operation", "->", "request", "->", "overridableUrl", ")", "&&", "true", "===", "$", "operation", "->", "request", "->", "overridableUrl", "&&", "!", "empty", "(", "$", "overrides", "[", "$", "key", "]", ")", ")", "{", "$", "fieldsOverridden", "[", "$", "key", "]", "=", "[", "'key'", "=>", "$", "key", ",", "'value'", "=>", "$", "overrides", "[", "$", "key", "]", ",", "]", ";", "$", "operation", "->", "request", "->", "url", "=", "$", "overrides", "[", "$", "key", "]", ";", "}", "if", "(", "isset", "(", "$", "operation", "->", "request", ")", ")", "{", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "operation", "->", "request", "->", "{", "$", "type", "}", ")", ")", "{", "foreach", "(", "$", "operation", "->", "request", "->", "{", "$", "type", "}", "as", "&", "$", "field", ")", "{", "if", "(", "isset", "(", "$", "field", "->", "overridable", ")", "&&", "true", "===", "$", "field", "->", "overridable", "&&", "isset", "(", "$", "field", "->", "key", ")", "&&", "isset", "(", "$", "overrides", "[", "$", "field", "->", "key", "]", ")", "&&", "null", "!==", "$", "overrides", "[", "$", "field", "->", "key", "]", ")", "{", "$", "field", "->", "value", "=", "$", "overrides", "[", "$", "field", "->", "key", "]", ";", "$", "fieldsOverridden", "[", "$", "field", "->", "key", "]", "=", "$", "overrides", "[", "$", "field", "->", "key", "]", ";", "}", "}", "}", "}", "}", "}", "}", "if", "(", "$", "fieldsOverridden", ")", "{", "$", "this", "->", "setLogs", "(", "$", "fieldsOverridden", ",", "'fieldsOverridden'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Override the default field values, if allowed. @param array $overrides @return $this
[ "Override", "the", "default", "field", "values", "if", "allowed", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayload.php#L779-L822
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.getErrors
public function getErrors($clean = true) { $errors = $this->errors; if ($clean) { foreach ($errors as $key => $error) { $errors[$key] = trim(strip_tags($error)); if (empty($errors[$key])) { unset($errors[$key]); } } } return $errors; }
php
public function getErrors($clean = true) { $errors = $this->errors; if ($clean) { foreach ($errors as $key => $error) { $errors[$key] = trim(strip_tags($error)); if (empty($errors[$key])) { unset($errors[$key]); } } } return $errors; }
[ "public", "function", "getErrors", "(", "$", "clean", "=", "true", ")", "{", "$", "errors", "=", "$", "this", "->", "errors", ";", "if", "(", "$", "clean", ")", "{", "foreach", "(", "$", "errors", "as", "$", "key", "=>", "$", "error", ")", "{", "$", "errors", "[", "$", "key", "]", "=", "trim", "(", "strip_tags", "(", "$", "error", ")", ")", ";", "if", "(", "empty", "(", "$", "errors", "[", "$", "key", "]", ")", ")", "{", "unset", "(", "$", "errors", "[", "$", "key", "]", ")", ";", "}", "}", "}", "return", "$", "errors", ";", "}" ]
@param bool $clean @return array
[ "@param", "bool", "$clean" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L53-L66
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.filter
public function filter($json, array $context = [], $noRulesResult = true) { // Pre-validate the string. if (!strlen($json)) { if (!$noRulesResult) { $this->setError('No rules to evaluate.'); } return $noRulesResult; } $query = $this->decodeJSON($json); // Post validate the json. if (!isset($query->rules) || !is_array($query->rules) || count($query->rules) < 1) { if (!$noRulesResult) { $this->setError('No rules to evaluate.'); } return $noRulesResult; } return $this->loopThroughRules($query->rules, $context, isset($query->condition) ? $query->condition : 'AND'); }
php
public function filter($json, array $context = [], $noRulesResult = true) { // Pre-validate the string. if (!strlen($json)) { if (!$noRulesResult) { $this->setError('No rules to evaluate.'); } return $noRulesResult; } $query = $this->decodeJSON($json); // Post validate the json. if (!isset($query->rules) || !is_array($query->rules) || count($query->rules) < 1) { if (!$noRulesResult) { $this->setError('No rules to evaluate.'); } return $noRulesResult; } return $this->loopThroughRules($query->rules, $context, isset($query->condition) ? $query->condition : 'AND'); }
[ "public", "function", "filter", "(", "$", "json", ",", "array", "$", "context", "=", "[", "]", ",", "$", "noRulesResult", "=", "true", ")", "{", "// Pre-validate the string.", "if", "(", "!", "strlen", "(", "$", "json", ")", ")", "{", "if", "(", "!", "$", "noRulesResult", ")", "{", "$", "this", "->", "setError", "(", "'No rules to evaluate.'", ")", ";", "}", "return", "$", "noRulesResult", ";", "}", "$", "query", "=", "$", "this", "->", "decodeJSON", "(", "$", "json", ")", ";", "// Post validate the json.", "if", "(", "!", "isset", "(", "$", "query", "->", "rules", ")", "||", "!", "is_array", "(", "$", "query", "->", "rules", ")", "||", "count", "(", "$", "query", "->", "rules", ")", "<", "1", ")", "{", "if", "(", "!", "$", "noRulesResult", ")", "{", "$", "this", "->", "setError", "(", "'No rules to evaluate.'", ")", ";", "}", "return", "$", "noRulesResult", ";", "}", "return", "$", "this", "->", "loopThroughRules", "(", "$", "query", "->", "rules", ",", "$", "context", ",", "isset", "(", "$", "query", "->", "condition", ")", "?", "$", "query", "->", "condition", ":", "'AND'", ")", ";", "}" ]
Use a jQuery Query Builder JSON to evaluate the context. @param string $json @param array $context An array of data to be evaluated @param bool|string $noRulesResult the result should the rules be missing/invalid, leave as true to succeed by default @return bool return true if the context passes the filters of $json @throws Exception
[ "Use", "a", "jQuery", "Query", "Builder", "JSON", "to", "evaluate", "the", "context", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L80-L103
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.decodeJSON
private function decodeJSON($json) { $query = json_decode($json); if (json_last_error()) { throw new \Exception('JSON parsing threw an error: '.json_last_error_msg()); } if (!is_object($query)) { throw new \Exception('The query is not valid JSON'); } return $query; }
php
private function decodeJSON($json) { $query = json_decode($json); if (json_last_error()) { throw new \Exception('JSON parsing threw an error: '.json_last_error_msg()); } if (!is_object($query)) { throw new \Exception('The query is not valid JSON'); } return $query; }
[ "private", "function", "decodeJSON", "(", "$", "json", ")", "{", "$", "query", "=", "json_decode", "(", "$", "json", ")", ";", "if", "(", "json_last_error", "(", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'JSON parsing threw an error: '", ".", "json_last_error_msg", "(", ")", ")", ";", "}", "if", "(", "!", "is_object", "(", "$", "query", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'The query is not valid JSON'", ")", ";", "}", "return", "$", "query", ";", "}" ]
Decode the given JSON. @param $json @return mixed @throws Exception
[ "Decode", "the", "given", "JSON", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L119-L130
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.loopThroughRules
protected function loopThroughRules(array $rules, array $context = [], $condition = 'AND') { $result = true; $condition = strtolower($condition); $this->validateCondition($condition); foreach ($rules as $rule) { $result = $this->evaluate($rule, $context); if ($result && $this->isNested($rule)) { $result = $this->loopThroughRules($rule->rules, $context, $condition); } // Conditions upon which we can stop evaluation. if ('and' == $condition && !$result) { break; } else { if ('or' == $condition && $result) { break; } } } return $result; }
php
protected function loopThroughRules(array $rules, array $context = [], $condition = 'AND') { $result = true; $condition = strtolower($condition); $this->validateCondition($condition); foreach ($rules as $rule) { $result = $this->evaluate($rule, $context); if ($result && $this->isNested($rule)) { $result = $this->loopThroughRules($rule->rules, $context, $condition); } // Conditions upon which we can stop evaluation. if ('and' == $condition && !$result) { break; } else { if ('or' == $condition && $result) { break; } } } return $result; }
[ "protected", "function", "loopThroughRules", "(", "array", "$", "rules", ",", "array", "$", "context", "=", "[", "]", ",", "$", "condition", "=", "'AND'", ")", "{", "$", "result", "=", "true", ";", "$", "condition", "=", "strtolower", "(", "$", "condition", ")", ";", "$", "this", "->", "validateCondition", "(", "$", "condition", ")", ";", "foreach", "(", "$", "rules", "as", "$", "rule", ")", "{", "$", "result", "=", "$", "this", "->", "evaluate", "(", "$", "rule", ",", "$", "context", ")", ";", "if", "(", "$", "result", "&&", "$", "this", "->", "isNested", "(", "$", "rule", ")", ")", "{", "$", "result", "=", "$", "this", "->", "loopThroughRules", "(", "$", "rule", "->", "rules", ",", "$", "context", ",", "$", "condition", ")", ";", "}", "// Conditions upon which we can stop evaluation.", "if", "(", "'and'", "==", "$", "condition", "&&", "!", "$", "result", ")", "{", "break", ";", "}", "else", "{", "if", "(", "'or'", "==", "$", "condition", "&&", "$", "result", ")", "{", "break", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Called by parse, loops through all the rules to find out if nested or not. @param array $rules @param array $context @param string $condition @return bool @throws Exception @throws \Exception
[ "Called", "by", "parse", "loops", "through", "all", "the", "rules", "to", "find", "out", "if", "nested", "or", "not", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L144-L165
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.validateCondition
protected function validateCondition($condition) { $condition = trim(strtolower($condition)); if ('and' !== $condition && 'or' !== $condition) { throw new \Exception("Condition can only be one of: 'and', 'or'."); } return $condition; }
php
protected function validateCondition($condition) { $condition = trim(strtolower($condition)); if ('and' !== $condition && 'or' !== $condition) { throw new \Exception("Condition can only be one of: 'and', 'or'."); } return $condition; }
[ "protected", "function", "validateCondition", "(", "$", "condition", ")", "{", "$", "condition", "=", "trim", "(", "strtolower", "(", "$", "condition", ")", ")", ";", "if", "(", "'and'", "!==", "$", "condition", "&&", "'or'", "!==", "$", "condition", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Condition can only be one of: 'and', 'or'.\"", ")", ";", "}", "return", "$", "condition", ";", "}" ]
Make sure that a condition is either 'or' or 'and'. @param $condition @return string @throws \Exception
[ "Make", "sure", "that", "a", "condition", "is", "either", "or", "or", "and", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L176-L185
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.getValueFromRule
protected function getValueFromRule($rule) { $value = $this->getRuleValue($rule); if (isset($this->operators[$rule->operator]['accept_values']) && $this->operators[$rule->operator]['accept_values'] === false) { return $this->operatorValueWhenNotAcceptingOne($rule); } return $this->getCorrectValue($rule->operator, $rule, $value); }
php
protected function getValueFromRule($rule) { $value = $this->getRuleValue($rule); if (isset($this->operators[$rule->operator]['accept_values']) && $this->operators[$rule->operator]['accept_values'] === false) { return $this->operatorValueWhenNotAcceptingOne($rule); } return $this->getCorrectValue($rule->operator, $rule, $value); }
[ "protected", "function", "getValueFromRule", "(", "$", "rule", ")", "{", "$", "value", "=", "$", "this", "->", "getRuleValue", "(", "$", "rule", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "operators", "[", "$", "rule", "->", "operator", "]", "[", "'accept_values'", "]", ")", "&&", "$", "this", "->", "operators", "[", "$", "rule", "->", "operator", "]", "[", "'accept_values'", "]", "===", "false", ")", "{", "return", "$", "this", "->", "operatorValueWhenNotAcceptingOne", "(", "$", "rule", ")", ";", "}", "return", "$", "this", "->", "getCorrectValue", "(", "$", "rule", "->", "operator", ",", "$", "rule", ",", "$", "value", ")", ";", "}" ]
Ensure that the value is correct for the rule, try and set it if it's not. @param $rule @return mixed|null|string @throws Exception
[ "Ensure", "that", "the", "value", "is", "correct", "for", "the", "rule", "try", "and", "set", "it", "if", "it", "s", "not", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L236-L246
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.checkRuleCorrect
protected function checkRuleCorrect($rule) { if (!isset($rule->value)) { // We will assume a missing value for the rule is to be interpreted as empty. $rule->value = null; } if (!isset($rule->id, $rule->field, $rule->type, $rule->input, $rule->operator)) { return false; } if (!isset($this->operators[$rule->operator])) { return false; } return true; }
php
protected function checkRuleCorrect($rule) { if (!isset($rule->value)) { // We will assume a missing value for the rule is to be interpreted as empty. $rule->value = null; } if (!isset($rule->id, $rule->field, $rule->type, $rule->input, $rule->operator)) { return false; } if (!isset($this->operators[$rule->operator])) { return false; } return true; }
[ "protected", "function", "checkRuleCorrect", "(", "$", "rule", ")", "{", "if", "(", "!", "isset", "(", "$", "rule", "->", "value", ")", ")", "{", "// We will assume a missing value for the rule is to be interpreted as empty.", "$", "rule", "->", "value", "=", "null", ";", "}", "if", "(", "!", "isset", "(", "$", "rule", "->", "id", ",", "$", "rule", "->", "field", ",", "$", "rule", "->", "type", ",", "$", "rule", "->", "input", ",", "$", "rule", "->", "operator", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "operators", "[", "$", "rule", "->", "operator", "]", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if a given rule is correct. Just before making a query for a rule, we want to make sure that the field, operator and value are set. @param $rule @return bool true if values are correct
[ "Check", "if", "a", "given", "rule", "is", "correct", ".", "Just", "before", "making", "a", "query", "for", "a", "rule", "we", "want", "to", "make", "sure", "that", "the", "field", "operator", "and", "value", "are", "set", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L275-L289
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.getCorrectValue
protected function getCorrectValue($operator, $rule, $value) { $requireArray = $this->operatorRequiresArray($operator); return $this->enforceArrayOrString($requireArray, $value, $rule->field); }
php
protected function getCorrectValue($operator, $rule, $value) { $requireArray = $this->operatorRequiresArray($operator); return $this->enforceArrayOrString($requireArray, $value, $rule->field); }
[ "protected", "function", "getCorrectValue", "(", "$", "operator", ",", "$", "rule", ",", "$", "value", ")", "{", "$", "requireArray", "=", "$", "this", "->", "operatorRequiresArray", "(", "$", "operator", ")", ";", "return", "$", "this", "->", "enforceArrayOrString", "(", "$", "requireArray", ",", "$", "value", ",", "$", "rule", "->", "field", ")", ";", "}" ]
Ensure that the value for a field is correct. @param string $operator @param $rule @param $value @return mixed @throws \Exception
[ "Ensure", "that", "the", "value", "for", "a", "field", "is", "correct", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L318-L323
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.enforceArrayOrString
protected function enforceArrayOrString($requireArray, $value, $field) { $this->checkFieldIsAnArray($requireArray, $value, $field); if (!$requireArray && is_array($value)) { return $this->convertArrayToFlatValue($field, $value); } return $value; }
php
protected function enforceArrayOrString($requireArray, $value, $field) { $this->checkFieldIsAnArray($requireArray, $value, $field); if (!$requireArray && is_array($value)) { return $this->convertArrayToFlatValue($field, $value); } return $value; }
[ "protected", "function", "enforceArrayOrString", "(", "$", "requireArray", ",", "$", "value", ",", "$", "field", ")", "{", "$", "this", "->", "checkFieldIsAnArray", "(", "$", "requireArray", ",", "$", "value", ",", "$", "field", ")", ";", "if", "(", "!", "$", "requireArray", "&&", "is_array", "(", "$", "value", ")", ")", "{", "return", "$", "this", "->", "convertArrayToFlatValue", "(", "$", "field", ",", "$", "value", ")", ";", "}", "return", "$", "value", ";", "}" ]
Enforce whether the value for a given field is the correct type. @param bool $requireArray value must be an array @param mixed $value the value we are checking against @param string $field the field that we are enforcing @return mixed value after enforcement @throws \Exception if value is not a correct type
[ "Enforce", "whether", "the", "value", "for", "a", "given", "field", "is", "the", "correct", "type", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L348-L357
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.getValueFromContext
protected function getValueFromContext($rule, $context) { // Fields are only nested one level deep and flattened thereafter. $parts = explode('.', $rule->field); $key = array_shift($parts); if (isset($context[$key]) && count($parts)) { $context = $context[$key]; $key = implode('.', $parts); } else { $key = $rule->field; } return isset($context[$key]) ? $context[$key] : false; }
php
protected function getValueFromContext($rule, $context) { // Fields are only nested one level deep and flattened thereafter. $parts = explode('.', $rule->field); $key = array_shift($parts); if (isset($context[$key]) && count($parts)) { $context = $context[$key]; $key = implode('.', $parts); } else { $key = $rule->field; } return isset($context[$key]) ? $context[$key] : false; }
[ "protected", "function", "getValueFromContext", "(", "$", "rule", ",", "$", "context", ")", "{", "// Fields are only nested one level deep and flattened thereafter.", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "rule", "->", "field", ")", ";", "$", "key", "=", "array_shift", "(", "$", "parts", ")", ";", "if", "(", "isset", "(", "$", "context", "[", "$", "key", "]", ")", "&&", "count", "(", "$", "parts", ")", ")", "{", "$", "context", "=", "$", "context", "[", "$", "key", "]", ";", "$", "key", "=", "implode", "(", "'.'", ",", "$", "parts", ")", ";", "}", "else", "{", "$", "key", "=", "$", "rule", "->", "field", ";", "}", "return", "isset", "(", "$", "context", "[", "$", "key", "]", ")", "?", "$", "context", "[", "$", "key", "]", ":", "false", ";", "}" ]
Take a (potentially nested) field name and get the literal value from the contextual array. @param $rule @param $context @return bool
[ "Take", "a", "(", "potentially", "nested", ")", "field", "name", "and", "get", "the", "literal", "value", "from", "the", "contextual", "array", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L407-L420
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.evaluateRuleAgainstContext
protected function evaluateRuleAgainstContext($rule, $contextValue, $ruleValue) { $operator = strtolower($rule->operator); switch ($operator) { case 'in': return in_array($contextValue, $ruleValue); break; case 'not_in': return !in_array($contextValue, $ruleValue); break; case 'between': $min = min($ruleValue); $max = max($ruleValue); return $contextValue == $min || $contextValue == $max || ($contextValue > $min && $contextValue < $max); break; case 'is_null': return null === $contextValue; break; case 'is_not_null': return null !== $contextValue; break; case 'equal': return $contextValue == $ruleValue; break; case 'not_equal': return $contextValue !== $ruleValue; break; case 'less': return $contextValue < $ruleValue; break; case 'less_or_equal': return $contextValue <= $ruleValue; break; case 'greater': return $contextValue > $ruleValue; break; case 'greater_or_equal': return $contextValue >= $ruleValue; break; case 'begins_with': return 0 === strpos($contextValue, $ruleValue); break; case 'not_begins_with': return 0 !== strpos($contextValue, $ruleValue); break; case 'contains': return strpos($contextValue, $ruleValue) > -1; break; case 'not_contains': return false === strpos($contextValue, $ruleValue); break; case 'ends_with': return substr($contextValue, -strlen($ruleValue)) === $ruleValue; break; case 'not_ends_with': return substr($contextValue, -strlen($ruleValue)) !== $ruleValue; break; case 'is_empty': return empty(trim($contextValue)); break; case 'is_not_empty': return !empty(trim($contextValue)); break; case 'regex': if ( '/' !== substr($ruleValue, 0, 1) && '/' !== substr($ruleValue, -1, 1) ) { $ruleValue = '/'.$ruleValue.'/'; } try { return 1 === preg_match($ruleValue, $contextValue); } catch (\Exception $e) { $this->setError('Invalid regex pattern.'); return false; } break; } }
php
protected function evaluateRuleAgainstContext($rule, $contextValue, $ruleValue) { $operator = strtolower($rule->operator); switch ($operator) { case 'in': return in_array($contextValue, $ruleValue); break; case 'not_in': return !in_array($contextValue, $ruleValue); break; case 'between': $min = min($ruleValue); $max = max($ruleValue); return $contextValue == $min || $contextValue == $max || ($contextValue > $min && $contextValue < $max); break; case 'is_null': return null === $contextValue; break; case 'is_not_null': return null !== $contextValue; break; case 'equal': return $contextValue == $ruleValue; break; case 'not_equal': return $contextValue !== $ruleValue; break; case 'less': return $contextValue < $ruleValue; break; case 'less_or_equal': return $contextValue <= $ruleValue; break; case 'greater': return $contextValue > $ruleValue; break; case 'greater_or_equal': return $contextValue >= $ruleValue; break; case 'begins_with': return 0 === strpos($contextValue, $ruleValue); break; case 'not_begins_with': return 0 !== strpos($contextValue, $ruleValue); break; case 'contains': return strpos($contextValue, $ruleValue) > -1; break; case 'not_contains': return false === strpos($contextValue, $ruleValue); break; case 'ends_with': return substr($contextValue, -strlen($ruleValue)) === $ruleValue; break; case 'not_ends_with': return substr($contextValue, -strlen($ruleValue)) !== $ruleValue; break; case 'is_empty': return empty(trim($contextValue)); break; case 'is_not_empty': return !empty(trim($contextValue)); break; case 'regex': if ( '/' !== substr($ruleValue, 0, 1) && '/' !== substr($ruleValue, -1, 1) ) { $ruleValue = '/'.$ruleValue.'/'; } try { return 1 === preg_match($ruleValue, $contextValue); } catch (\Exception $e) { $this->setError('Invalid regex pattern.'); return false; } break; } }
[ "protected", "function", "evaluateRuleAgainstContext", "(", "$", "rule", ",", "$", "contextValue", ",", "$", "ruleValue", ")", "{", "$", "operator", "=", "strtolower", "(", "$", "rule", "->", "operator", ")", ";", "switch", "(", "$", "operator", ")", "{", "case", "'in'", ":", "return", "in_array", "(", "$", "contextValue", ",", "$", "ruleValue", ")", ";", "break", ";", "case", "'not_in'", ":", "return", "!", "in_array", "(", "$", "contextValue", ",", "$", "ruleValue", ")", ";", "break", ";", "case", "'between'", ":", "$", "min", "=", "min", "(", "$", "ruleValue", ")", ";", "$", "max", "=", "max", "(", "$", "ruleValue", ")", ";", "return", "$", "contextValue", "==", "$", "min", "||", "$", "contextValue", "==", "$", "max", "||", "(", "$", "contextValue", ">", "$", "min", "&&", "$", "contextValue", "<", "$", "max", ")", ";", "break", ";", "case", "'is_null'", ":", "return", "null", "===", "$", "contextValue", ";", "break", ";", "case", "'is_not_null'", ":", "return", "null", "!==", "$", "contextValue", ";", "break", ";", "case", "'equal'", ":", "return", "$", "contextValue", "==", "$", "ruleValue", ";", "break", ";", "case", "'not_equal'", ":", "return", "$", "contextValue", "!==", "$", "ruleValue", ";", "break", ";", "case", "'less'", ":", "return", "$", "contextValue", "<", "$", "ruleValue", ";", "break", ";", "case", "'less_or_equal'", ":", "return", "$", "contextValue", "<=", "$", "ruleValue", ";", "break", ";", "case", "'greater'", ":", "return", "$", "contextValue", ">", "$", "ruleValue", ";", "break", ";", "case", "'greater_or_equal'", ":", "return", "$", "contextValue", ">=", "$", "ruleValue", ";", "break", ";", "case", "'begins_with'", ":", "return", "0", "===", "strpos", "(", "$", "contextValue", ",", "$", "ruleValue", ")", ";", "break", ";", "case", "'not_begins_with'", ":", "return", "0", "!==", "strpos", "(", "$", "contextValue", ",", "$", "ruleValue", ")", ";", "break", ";", "case", "'contains'", ":", "return", "strpos", "(", "$", "contextValue", ",", "$", "ruleValue", ")", ">", "-", "1", ";", "break", ";", "case", "'not_contains'", ":", "return", "false", "===", "strpos", "(", "$", "contextValue", ",", "$", "ruleValue", ")", ";", "break", ";", "case", "'ends_with'", ":", "return", "substr", "(", "$", "contextValue", ",", "-", "strlen", "(", "$", "ruleValue", ")", ")", "===", "$", "ruleValue", ";", "break", ";", "case", "'not_ends_with'", ":", "return", "substr", "(", "$", "contextValue", ",", "-", "strlen", "(", "$", "ruleValue", ")", ")", "!==", "$", "ruleValue", ";", "break", ";", "case", "'is_empty'", ":", "return", "empty", "(", "trim", "(", "$", "contextValue", ")", ")", ";", "break", ";", "case", "'is_not_empty'", ":", "return", "!", "empty", "(", "trim", "(", "$", "contextValue", ")", ")", ";", "break", ";", "case", "'regex'", ":", "if", "(", "'/'", "!==", "substr", "(", "$", "ruleValue", ",", "0", ",", "1", ")", "&&", "'/'", "!==", "substr", "(", "$", "ruleValue", ",", "-", "1", ",", "1", ")", ")", "{", "$", "ruleValue", "=", "'/'", ".", "$", "ruleValue", ".", "'/'", ";", "}", "try", "{", "return", "1", "===", "preg_match", "(", "$", "ruleValue", ",", "$", "contextValue", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "setError", "(", "'Invalid regex pattern.'", ")", ";", "return", "false", ";", "}", "break", ";", "}", "}" ]
Convert an incomming rule from jQuery QueryBuilder to the Doctrine Querybuilder. (This used to be part of evaluate, where the name made sense, but I pulled it out to reduce some duplicated code inside JoinSupportingQueryBuilder) @param $rule @param $contextValue @param $ruleValue @return bool @throws \Exception
[ "Convert", "an", "incomming", "rule", "from", "jQuery", "QueryBuilder", "to", "the", "Doctrine", "Querybuilder", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L436-L516
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.isNested
protected function isNested($rule) { if (isset($rule->rules) && is_array($rule->rules) && count($rule->rules) > 0) { return true; } return false; }
php
protected function isNested($rule) { if (isset($rule->rules) && is_array($rule->rules) && count($rule->rules) > 0) { return true; } return false; }
[ "protected", "function", "isNested", "(", "$", "rule", ")", "{", "if", "(", "isset", "(", "$", "rule", "->", "rules", ")", "&&", "is_array", "(", "$", "rule", "->", "rules", ")", "&&", "count", "(", "$", "rule", "->", "rules", ")", ">", "0", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Determine if we have nested rules to evaluate. @param $rule @return bool
[ "Determine", "if", "we", "have", "nested", "rules", "to", "evaluate", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L525-L532
TheDMSGroup/mautic-contact-client
Helper/FilterHelper.php
FilterHelper.expoundContext
private function expoundContext(&$context) { foreach ($context as $key => &$value) { if (is_array($value) || is_object($value)) { $this->expoundContext($value); } $t = &$context; $keys = explode('.', $key); if (count($keys) > 1) { foreach ($keys as $subKey) { if (!isset($t[$subKey])) { $t[$subKey] = []; } $t = &$t[$subKey]; } $t = $value; unset($context[$key]); } } }
php
private function expoundContext(&$context) { foreach ($context as $key => &$value) { if (is_array($value) || is_object($value)) { $this->expoundContext($value); } $t = &$context; $keys = explode('.', $key); if (count($keys) > 1) { foreach ($keys as $subKey) { if (!isset($t[$subKey])) { $t[$subKey] = []; } $t = &$t[$subKey]; } $t = $value; unset($context[$key]); } } }
[ "private", "function", "expoundContext", "(", "&", "$", "context", ")", "{", "foreach", "(", "$", "context", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "||", "is_object", "(", "$", "value", ")", ")", "{", "$", "this", "->", "expoundContext", "(", "$", "value", ")", ";", "}", "$", "t", "=", "&", "$", "context", ";", "$", "keys", "=", "explode", "(", "'.'", ",", "$", "key", ")", ";", "if", "(", "count", "(", "$", "keys", ")", ">", "1", ")", "{", "foreach", "(", "$", "keys", "as", "$", "subKey", ")", "{", "if", "(", "!", "isset", "(", "$", "t", "[", "$", "subKey", "]", ")", ")", "{", "$", "t", "[", "$", "subKey", "]", "=", "[", "]", ";", "}", "$", "t", "=", "&", "$", "t", "[", "$", "subKey", "]", ";", "}", "$", "t", "=", "$", "value", ";", "unset", "(", "$", "context", "[", "$", "key", "]", ")", ";", "}", "}", "}" ]
/* Kept for posterity. A mechanism to expound the dot-notated fields to a nested array recursively. Not currently used because our contextual arrays are flattened externally after the first level. @param $context
[ "/", "*", "Kept", "for", "posterity", ".", "A", "mechanism", "to", "expound", "the", "dot", "-", "notated", "fields", "to", "a", "nested", "array", "recursively", ".", "Not", "currently", "used", "because", "our", "contextual", "arrays", "are", "flattened", "externally", "after", "the", "first", "level", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Helper/FilterHelper.php#L540-L559
TheDMSGroup/mautic-contact-client
Model/ApiPayloadRequest.php
ApiPayloadRequest.send
public function send() { // The URI has already been overriden (if applicable) by this point. $uri = isset($this->request->url) ? $this->request->url : null; if ($this->test && !empty($this->request->testUrl)) { $uri = $this->request->testUrl; } $uri = trim($this->renderTokens($uri)); if (empty($uri)) { throw new ContactClientException( 'No URL was specified for an API operation.', 0, null, Stat::TYPE_ERROR, false ); } $this->setLogs($uri, 'uri'); $request = $this->request; $transport = $this->transport; $options = []; $manual = isset($request->manual) && $request->manual && isset($request->template) && !empty(trim($request->template)); // Retrieve/filter/tokenize the Request Body Field values if present. $requestFields = []; if (!$manual && !empty($request->body) && !is_string($request->body)) { $requestFields = $this->fieldValues($request->body); } $requestFormat = strtolower(isset($request->format) ? $request->format : 'form'); $this->setLogs($requestFormat, 'format'); switch ($requestFormat) { case 'form': default: $options['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; if ($requestFields) { $options['form_params'] = $requestFields; } break; case 'json': $options['headers']['Content-Type'] = 'application/json; charset=utf-8'; if ($requestFields) { $options['json'] = $requestFields; } break; case 'text': $options['headers']['Content-Type'] = 'text/plain; charset=utf-8'; if ($requestFields) { // User specified to send raw text, but used key value pairs. // We will present this as YAML, since it's the most text-like response. $yaml = Yaml::dump($requestFields); if ($yaml) { $options['body'] = $yaml; } } break; case 'xml': $options['headers']['Content-Type'] = 'application/xml; charset=utf-8'; if ($requestFields) { $doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $root = $doc->createElement(self::XML_ROOT_ELEM); $doc->appendChild($root); foreach ($requestFields as $key => $value) { $element = $doc->createElement($key); $element->appendChild( $doc->createTextNode($value) ); $root->appendChild($element); } $xml = $doc->saveXML(); if ($xml) { $options['body'] = $xml; } } break; case 'yaml': $options['headers']['Content-Type'] = 'application/x-yaml; charset=utf-8'; if ($requestFields) { $yaml = Yaml::dump($requestFields); if ($yaml) { $options['body'] = $yaml; } } break; } // Add the manual template if provided and manual mode is enabled. if ($manual) { $templateFields = $this->templateFieldValues($request->body); $body = $this->renderTokens($request->template, $templateFields); if (!empty(trim($body))) { $options['body'] = $body; // Prevent double-encoding JSON. unset($options['json']); } } else { if (is_string($request->body) && !empty(trim($request->body))) { // For backward compatibility, support body as a string. $body = $this->renderTokens($request->body); if (!empty(trim($body))) { $options['body'] = $body; } } } // Header Field overrides. if (!empty($request->headers)) { $headers = $this->fieldValues($request->headers); if (!empty($headers)) { if (isset($options['headers'])) { $options['headers'] = array_merge($options['headers'], $headers); } else { $options['headers'] = $headers; } } } $method = trim(strtolower(isset($request->method) ? $request->method : 'post')); $this->setLogs($method, 'method'); $startTime = microtime(true); switch ($method) { case 'delete': $this->setLogs($options, 'options'); $transport->delete($uri, $options); break; case 'get': if ($requestFields) { $options['query'] = $requestFields; // GET will not typically support form params in addition. unset($options['form_params']); } $this->setLogs($options, 'options'); $transport->get($uri, $options); break; case 'head': $this->setLogs($options, 'options'); $transport->head($uri, $options); break; case 'patch': $this->setLogs($options, 'options'); $transport->patch($uri, $options); break; case 'post': default: $this->setLogs($options, 'options'); $transport->post($uri, $options); break; case 'put': $this->setLogs($options, 'options'); $transport->put($uri, $options); break; } $transportRecords = $transport->getRecords(); if ($transportRecords) { $debug = []; foreach ($transportRecords as $transportRecord) { if ( isset($transportRecord['channel']) && 'guzzle.to.curl' == $transportRecord['channel'] && isset($transportRecord['message']) ) { $debug[] = $transportRecord['message']; } } if ($debug) { $this->setLogs($debug, 'debug'); } } $this->setLogs(microtime(true) - $startTime, 'duration'); if ($this->test) { $this->setLogs($this->tokenHelper->getContext(true), 'availableTokens'); } }
php
public function send() { // The URI has already been overriden (if applicable) by this point. $uri = isset($this->request->url) ? $this->request->url : null; if ($this->test && !empty($this->request->testUrl)) { $uri = $this->request->testUrl; } $uri = trim($this->renderTokens($uri)); if (empty($uri)) { throw new ContactClientException( 'No URL was specified for an API operation.', 0, null, Stat::TYPE_ERROR, false ); } $this->setLogs($uri, 'uri'); $request = $this->request; $transport = $this->transport; $options = []; $manual = isset($request->manual) && $request->manual && isset($request->template) && !empty(trim($request->template)); // Retrieve/filter/tokenize the Request Body Field values if present. $requestFields = []; if (!$manual && !empty($request->body) && !is_string($request->body)) { $requestFields = $this->fieldValues($request->body); } $requestFormat = strtolower(isset($request->format) ? $request->format : 'form'); $this->setLogs($requestFormat, 'format'); switch ($requestFormat) { case 'form': default: $options['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; if ($requestFields) { $options['form_params'] = $requestFields; } break; case 'json': $options['headers']['Content-Type'] = 'application/json; charset=utf-8'; if ($requestFields) { $options['json'] = $requestFields; } break; case 'text': $options['headers']['Content-Type'] = 'text/plain; charset=utf-8'; if ($requestFields) { // User specified to send raw text, but used key value pairs. // We will present this as YAML, since it's the most text-like response. $yaml = Yaml::dump($requestFields); if ($yaml) { $options['body'] = $yaml; } } break; case 'xml': $options['headers']['Content-Type'] = 'application/xml; charset=utf-8'; if ($requestFields) { $doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $root = $doc->createElement(self::XML_ROOT_ELEM); $doc->appendChild($root); foreach ($requestFields as $key => $value) { $element = $doc->createElement($key); $element->appendChild( $doc->createTextNode($value) ); $root->appendChild($element); } $xml = $doc->saveXML(); if ($xml) { $options['body'] = $xml; } } break; case 'yaml': $options['headers']['Content-Type'] = 'application/x-yaml; charset=utf-8'; if ($requestFields) { $yaml = Yaml::dump($requestFields); if ($yaml) { $options['body'] = $yaml; } } break; } // Add the manual template if provided and manual mode is enabled. if ($manual) { $templateFields = $this->templateFieldValues($request->body); $body = $this->renderTokens($request->template, $templateFields); if (!empty(trim($body))) { $options['body'] = $body; // Prevent double-encoding JSON. unset($options['json']); } } else { if (is_string($request->body) && !empty(trim($request->body))) { // For backward compatibility, support body as a string. $body = $this->renderTokens($request->body); if (!empty(trim($body))) { $options['body'] = $body; } } } // Header Field overrides. if (!empty($request->headers)) { $headers = $this->fieldValues($request->headers); if (!empty($headers)) { if (isset($options['headers'])) { $options['headers'] = array_merge($options['headers'], $headers); } else { $options['headers'] = $headers; } } } $method = trim(strtolower(isset($request->method) ? $request->method : 'post')); $this->setLogs($method, 'method'); $startTime = microtime(true); switch ($method) { case 'delete': $this->setLogs($options, 'options'); $transport->delete($uri, $options); break; case 'get': if ($requestFields) { $options['query'] = $requestFields; // GET will not typically support form params in addition. unset($options['form_params']); } $this->setLogs($options, 'options'); $transport->get($uri, $options); break; case 'head': $this->setLogs($options, 'options'); $transport->head($uri, $options); break; case 'patch': $this->setLogs($options, 'options'); $transport->patch($uri, $options); break; case 'post': default: $this->setLogs($options, 'options'); $transport->post($uri, $options); break; case 'put': $this->setLogs($options, 'options'); $transport->put($uri, $options); break; } $transportRecords = $transport->getRecords(); if ($transportRecords) { $debug = []; foreach ($transportRecords as $transportRecord) { if ( isset($transportRecord['channel']) && 'guzzle.to.curl' == $transportRecord['channel'] && isset($transportRecord['message']) ) { $debug[] = $transportRecord['message']; } } if ($debug) { $this->setLogs($debug, 'debug'); } } $this->setLogs(microtime(true) - $startTime, 'duration'); if ($this->test) { $this->setLogs($this->tokenHelper->getContext(true), 'availableTokens'); } }
[ "public", "function", "send", "(", ")", "{", "// The URI has already been overriden (if applicable) by this point.", "$", "uri", "=", "isset", "(", "$", "this", "->", "request", "->", "url", ")", "?", "$", "this", "->", "request", "->", "url", ":", "null", ";", "if", "(", "$", "this", "->", "test", "&&", "!", "empty", "(", "$", "this", "->", "request", "->", "testUrl", ")", ")", "{", "$", "uri", "=", "$", "this", "->", "request", "->", "testUrl", ";", "}", "$", "uri", "=", "trim", "(", "$", "this", "->", "renderTokens", "(", "$", "uri", ")", ")", ";", "if", "(", "empty", "(", "$", "uri", ")", ")", "{", "throw", "new", "ContactClientException", "(", "'No URL was specified for an API operation.'", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_ERROR", ",", "false", ")", ";", "}", "$", "this", "->", "setLogs", "(", "$", "uri", ",", "'uri'", ")", ";", "$", "request", "=", "$", "this", "->", "request", ";", "$", "transport", "=", "$", "this", "->", "transport", ";", "$", "options", "=", "[", "]", ";", "$", "manual", "=", "isset", "(", "$", "request", "->", "manual", ")", "&&", "$", "request", "->", "manual", "&&", "isset", "(", "$", "request", "->", "template", ")", "&&", "!", "empty", "(", "trim", "(", "$", "request", "->", "template", ")", ")", ";", "// Retrieve/filter/tokenize the Request Body Field values if present.", "$", "requestFields", "=", "[", "]", ";", "if", "(", "!", "$", "manual", "&&", "!", "empty", "(", "$", "request", "->", "body", ")", "&&", "!", "is_string", "(", "$", "request", "->", "body", ")", ")", "{", "$", "requestFields", "=", "$", "this", "->", "fieldValues", "(", "$", "request", "->", "body", ")", ";", "}", "$", "requestFormat", "=", "strtolower", "(", "isset", "(", "$", "request", "->", "format", ")", "?", "$", "request", "->", "format", ":", "'form'", ")", ";", "$", "this", "->", "setLogs", "(", "$", "requestFormat", ",", "'format'", ")", ";", "switch", "(", "$", "requestFormat", ")", "{", "case", "'form'", ":", "default", ":", "$", "options", "[", "'headers'", "]", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded; charset=utf-8'", ";", "if", "(", "$", "requestFields", ")", "{", "$", "options", "[", "'form_params'", "]", "=", "$", "requestFields", ";", "}", "break", ";", "case", "'json'", ":", "$", "options", "[", "'headers'", "]", "[", "'Content-Type'", "]", "=", "'application/json; charset=utf-8'", ";", "if", "(", "$", "requestFields", ")", "{", "$", "options", "[", "'json'", "]", "=", "$", "requestFields", ";", "}", "break", ";", "case", "'text'", ":", "$", "options", "[", "'headers'", "]", "[", "'Content-Type'", "]", "=", "'text/plain; charset=utf-8'", ";", "if", "(", "$", "requestFields", ")", "{", "// User specified to send raw text, but used key value pairs.", "// We will present this as YAML, since it's the most text-like response.", "$", "yaml", "=", "Yaml", "::", "dump", "(", "$", "requestFields", ")", ";", "if", "(", "$", "yaml", ")", "{", "$", "options", "[", "'body'", "]", "=", "$", "yaml", ";", "}", "}", "break", ";", "case", "'xml'", ":", "$", "options", "[", "'headers'", "]", "[", "'Content-Type'", "]", "=", "'application/xml; charset=utf-8'", ";", "if", "(", "$", "requestFields", ")", "{", "$", "doc", "=", "new", "DomDocument", "(", "'1.0'", ")", ";", "$", "doc", "->", "preserveWhiteSpace", "=", "false", ";", "$", "doc", "->", "formatOutput", "=", "true", ";", "$", "root", "=", "$", "doc", "->", "createElement", "(", "self", "::", "XML_ROOT_ELEM", ")", ";", "$", "doc", "->", "appendChild", "(", "$", "root", ")", ";", "foreach", "(", "$", "requestFields", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "element", "=", "$", "doc", "->", "createElement", "(", "$", "key", ")", ";", "$", "element", "->", "appendChild", "(", "$", "doc", "->", "createTextNode", "(", "$", "value", ")", ")", ";", "$", "root", "->", "appendChild", "(", "$", "element", ")", ";", "}", "$", "xml", "=", "$", "doc", "->", "saveXML", "(", ")", ";", "if", "(", "$", "xml", ")", "{", "$", "options", "[", "'body'", "]", "=", "$", "xml", ";", "}", "}", "break", ";", "case", "'yaml'", ":", "$", "options", "[", "'headers'", "]", "[", "'Content-Type'", "]", "=", "'application/x-yaml; charset=utf-8'", ";", "if", "(", "$", "requestFields", ")", "{", "$", "yaml", "=", "Yaml", "::", "dump", "(", "$", "requestFields", ")", ";", "if", "(", "$", "yaml", ")", "{", "$", "options", "[", "'body'", "]", "=", "$", "yaml", ";", "}", "}", "break", ";", "}", "// Add the manual template if provided and manual mode is enabled.", "if", "(", "$", "manual", ")", "{", "$", "templateFields", "=", "$", "this", "->", "templateFieldValues", "(", "$", "request", "->", "body", ")", ";", "$", "body", "=", "$", "this", "->", "renderTokens", "(", "$", "request", "->", "template", ",", "$", "templateFields", ")", ";", "if", "(", "!", "empty", "(", "trim", "(", "$", "body", ")", ")", ")", "{", "$", "options", "[", "'body'", "]", "=", "$", "body", ";", "// Prevent double-encoding JSON.", "unset", "(", "$", "options", "[", "'json'", "]", ")", ";", "}", "}", "else", "{", "if", "(", "is_string", "(", "$", "request", "->", "body", ")", "&&", "!", "empty", "(", "trim", "(", "$", "request", "->", "body", ")", ")", ")", "{", "// For backward compatibility, support body as a string.", "$", "body", "=", "$", "this", "->", "renderTokens", "(", "$", "request", "->", "body", ")", ";", "if", "(", "!", "empty", "(", "trim", "(", "$", "body", ")", ")", ")", "{", "$", "options", "[", "'body'", "]", "=", "$", "body", ";", "}", "}", "}", "// Header Field overrides.", "if", "(", "!", "empty", "(", "$", "request", "->", "headers", ")", ")", "{", "$", "headers", "=", "$", "this", "->", "fieldValues", "(", "$", "request", "->", "headers", ")", ";", "if", "(", "!", "empty", "(", "$", "headers", ")", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'headers'", "]", ")", ")", "{", "$", "options", "[", "'headers'", "]", "=", "array_merge", "(", "$", "options", "[", "'headers'", "]", ",", "$", "headers", ")", ";", "}", "else", "{", "$", "options", "[", "'headers'", "]", "=", "$", "headers", ";", "}", "}", "}", "$", "method", "=", "trim", "(", "strtolower", "(", "isset", "(", "$", "request", "->", "method", ")", "?", "$", "request", "->", "method", ":", "'post'", ")", ")", ";", "$", "this", "->", "setLogs", "(", "$", "method", ",", "'method'", ")", ";", "$", "startTime", "=", "microtime", "(", "true", ")", ";", "switch", "(", "$", "method", ")", "{", "case", "'delete'", ":", "$", "this", "->", "setLogs", "(", "$", "options", ",", "'options'", ")", ";", "$", "transport", "->", "delete", "(", "$", "uri", ",", "$", "options", ")", ";", "break", ";", "case", "'get'", ":", "if", "(", "$", "requestFields", ")", "{", "$", "options", "[", "'query'", "]", "=", "$", "requestFields", ";", "// GET will not typically support form params in addition.", "unset", "(", "$", "options", "[", "'form_params'", "]", ")", ";", "}", "$", "this", "->", "setLogs", "(", "$", "options", ",", "'options'", ")", ";", "$", "transport", "->", "get", "(", "$", "uri", ",", "$", "options", ")", ";", "break", ";", "case", "'head'", ":", "$", "this", "->", "setLogs", "(", "$", "options", ",", "'options'", ")", ";", "$", "transport", "->", "head", "(", "$", "uri", ",", "$", "options", ")", ";", "break", ";", "case", "'patch'", ":", "$", "this", "->", "setLogs", "(", "$", "options", ",", "'options'", ")", ";", "$", "transport", "->", "patch", "(", "$", "uri", ",", "$", "options", ")", ";", "break", ";", "case", "'post'", ":", "default", ":", "$", "this", "->", "setLogs", "(", "$", "options", ",", "'options'", ")", ";", "$", "transport", "->", "post", "(", "$", "uri", ",", "$", "options", ")", ";", "break", ";", "case", "'put'", ":", "$", "this", "->", "setLogs", "(", "$", "options", ",", "'options'", ")", ";", "$", "transport", "->", "put", "(", "$", "uri", ",", "$", "options", ")", ";", "break", ";", "}", "$", "transportRecords", "=", "$", "transport", "->", "getRecords", "(", ")", ";", "if", "(", "$", "transportRecords", ")", "{", "$", "debug", "=", "[", "]", ";", "foreach", "(", "$", "transportRecords", "as", "$", "transportRecord", ")", "{", "if", "(", "isset", "(", "$", "transportRecord", "[", "'channel'", "]", ")", "&&", "'guzzle.to.curl'", "==", "$", "transportRecord", "[", "'channel'", "]", "&&", "isset", "(", "$", "transportRecord", "[", "'message'", "]", ")", ")", "{", "$", "debug", "[", "]", "=", "$", "transportRecord", "[", "'message'", "]", ";", "}", "}", "if", "(", "$", "debug", ")", "{", "$", "this", "->", "setLogs", "(", "$", "debug", ",", "'debug'", ")", ";", "}", "}", "$", "this", "->", "setLogs", "(", "microtime", "(", "true", ")", "-", "$", "startTime", ",", "'duration'", ")", ";", "if", "(", "$", "this", "->", "test", ")", "{", "$", "this", "->", "setLogs", "(", "$", "this", "->", "tokenHelper", "->", "getContext", "(", "true", ")", ",", "'availableTokens'", ")", ";", "}", "}" ]
Given a uri and request object, formulate options and make the request. @throws ContactClientException
[ "Given", "a", "uri", "and", "request", "object", "formulate", "options", "and", "make", "the", "request", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadRequest.php#L64-L251
TheDMSGroup/mautic-contact-client
Model/ApiPayloadRequest.php
ApiPayloadRequest.renderTokens
private function renderTokens($template = '', $context = []) { if ($context) { $this->tokenHelper->addContext($context); } return $this->tokenHelper->render($template); }
php
private function renderTokens($template = '', $context = []) { if ($context) { $this->tokenHelper->addContext($context); } return $this->tokenHelper->render($template); }
[ "private", "function", "renderTokens", "(", "$", "template", "=", "''", ",", "$", "context", "=", "[", "]", ")", "{", "if", "(", "$", "context", ")", "{", "$", "this", "->", "tokenHelper", "->", "addContext", "(", "$", "context", ")", ";", "}", "return", "$", "this", "->", "tokenHelper", "->", "render", "(", "$", "template", ")", ";", "}" ]
@param string|array|object $template @param array $context @return string
[ "@param", "string|array|object", "$template", "@param", "array", "$context" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadRequest.php#L259-L266
TheDMSGroup/mautic-contact-client
Model/ApiPayloadRequest.php
ApiPayloadRequest.templateFieldValues
private function templateFieldValues($fields) { $result = []; foreach ($fields as $field) { if (!$this->test && (isset($field->test_only) ? $field->test_only : false)) { // Skip this field as it is for test mode only. continue; } $key = isset($field->key) ? trim($field->key) : ''; if ('' === $key) { // Skip if we have an empty key. continue; } // Exclude default_value (may add this functionality in the future if desired). $valueSources = ['value', 'default_value']; if ($this->test) { $valueSources = ['test_value', 'value', 'default_value']; } $value = null; foreach ($valueSources as $valueSource) { if (isset($field->{$valueSource}) && null !== $field->{$valueSource} && '' !== $field->{$valueSource}) { $value = $this->renderTokens($field->{$valueSource}); if (null !== $value && '' !== $value) { break; } } } if (null === $value || '' === $value) { // The field value is empty. if (true === (isset($field->required) ? $field->required : false)) { // The field is required. Abort. throw new ContactClientException( 'A required Client template field is empty: '.$field->value.' ('.$field->key.' in client configuration)', 0, null, Stat::TYPE_FIELDS, false, $field->key ); } } $result[$key] = $value; // Support pure mustache tags as keys as well (for templates only). if (1 === preg_match('/^{{\s*[\w\.]+\s*}}$/', trim($field->value))) { $mustacheTag = trim(str_replace(['{', '}'], '', $field->value)); if (empty($result[$mustacheTag])) { $result[$mustacheTag] = $value; } } } return $result; }
php
private function templateFieldValues($fields) { $result = []; foreach ($fields as $field) { if (!$this->test && (isset($field->test_only) ? $field->test_only : false)) { // Skip this field as it is for test mode only. continue; } $key = isset($field->key) ? trim($field->key) : ''; if ('' === $key) { // Skip if we have an empty key. continue; } // Exclude default_value (may add this functionality in the future if desired). $valueSources = ['value', 'default_value']; if ($this->test) { $valueSources = ['test_value', 'value', 'default_value']; } $value = null; foreach ($valueSources as $valueSource) { if (isset($field->{$valueSource}) && null !== $field->{$valueSource} && '' !== $field->{$valueSource}) { $value = $this->renderTokens($field->{$valueSource}); if (null !== $value && '' !== $value) { break; } } } if (null === $value || '' === $value) { // The field value is empty. if (true === (isset($field->required) ? $field->required : false)) { // The field is required. Abort. throw new ContactClientException( 'A required Client template field is empty: '.$field->value.' ('.$field->key.' in client configuration)', 0, null, Stat::TYPE_FIELDS, false, $field->key ); } } $result[$key] = $value; // Support pure mustache tags as keys as well (for templates only). if (1 === preg_match('/^{{\s*[\w\.]+\s*}}$/', trim($field->value))) { $mustacheTag = trim(str_replace(['{', '}'], '', $field->value)); if (empty($result[$mustacheTag])) { $result[$mustacheTag] = $value; } } } return $result; }
[ "private", "function", "templateFieldValues", "(", "$", "fields", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "fields", "as", "$", "field", ")", "{", "if", "(", "!", "$", "this", "->", "test", "&&", "(", "isset", "(", "$", "field", "->", "test_only", ")", "?", "$", "field", "->", "test_only", ":", "false", ")", ")", "{", "// Skip this field as it is for test mode only.", "continue", ";", "}", "$", "key", "=", "isset", "(", "$", "field", "->", "key", ")", "?", "trim", "(", "$", "field", "->", "key", ")", ":", "''", ";", "if", "(", "''", "===", "$", "key", ")", "{", "// Skip if we have an empty key.", "continue", ";", "}", "// Exclude default_value (may add this functionality in the future if desired).", "$", "valueSources", "=", "[", "'value'", ",", "'default_value'", "]", ";", "if", "(", "$", "this", "->", "test", ")", "{", "$", "valueSources", "=", "[", "'test_value'", ",", "'value'", ",", "'default_value'", "]", ";", "}", "$", "value", "=", "null", ";", "foreach", "(", "$", "valueSources", "as", "$", "valueSource", ")", "{", "if", "(", "isset", "(", "$", "field", "->", "{", "$", "valueSource", "}", ")", "&&", "null", "!==", "$", "field", "->", "{", "$", "valueSource", "}", "&&", "''", "!==", "$", "field", "->", "{", "$", "valueSource", "}", ")", "{", "$", "value", "=", "$", "this", "->", "renderTokens", "(", "$", "field", "->", "{", "$", "valueSource", "}", ")", ";", "if", "(", "null", "!==", "$", "value", "&&", "''", "!==", "$", "value", ")", "{", "break", ";", "}", "}", "}", "if", "(", "null", "===", "$", "value", "||", "''", "===", "$", "value", ")", "{", "// The field value is empty.", "if", "(", "true", "===", "(", "isset", "(", "$", "field", "->", "required", ")", "?", "$", "field", "->", "required", ":", "false", ")", ")", "{", "// The field is required. Abort.", "throw", "new", "ContactClientException", "(", "'A required Client template field is empty: '", ".", "$", "field", "->", "value", ".", "' ('", ".", "$", "field", "->", "key", ".", "' in client configuration)'", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_FIELDS", ",", "false", ",", "$", "field", "->", "key", ")", ";", "}", "}", "$", "result", "[", "$", "key", "]", "=", "$", "value", ";", "// Support pure mustache tags as keys as well (for templates only).", "if", "(", "1", "===", "preg_match", "(", "'/^{{\\s*[\\w\\.]+\\s*}}$/'", ",", "trim", "(", "$", "field", "->", "value", ")", ")", ")", "{", "$", "mustacheTag", "=", "trim", "(", "str_replace", "(", "[", "'{'", ",", "'}'", "]", ",", "''", ",", "$", "field", "->", "value", ")", ")", ";", "if", "(", "empty", "(", "$", "result", "[", "$", "mustacheTag", "]", ")", ")", "{", "$", "result", "[", "$", "mustacheTag", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Tokenize/parse fields from the API Payload for template context. @param $fields @return array @throws ContactClientException
[ "Tokenize", "/", "parse", "fields", "from", "the", "API", "Payload", "for", "template", "context", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadRequest.php#L334-L387
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.findLimit
public function findLimit( ContactClient $contactClient, $rules = [], $timezone = null, \DateTime $dateSend = null ) { $filters = []; $result = null; foreach ($rules as $rule) { $orx = []; $value = $rule['value']; $scope = $rule['scope']; $duration = $rule['duration']; $quantity = $rule['quantity']; // Scope UTM Source if ($scope & self::SCOPE_UTM_SOURCE) { $utmSource = trim($value); if (!empty($utmSource)) { $orx['utm_source'] = trim($value); } } // Scope Category if ($scope & self::SCOPE_CATEGORY) { $category = intval($value); if ($category) { $orx['category_id'] = $category; } } // Match duration (always, including global scope) $filters[] = [ 'orx' => $orx, 'date_added' => $this->oldestDateAdded($duration, $timezone, $dateSend)->getTimestamp(), 'contactclient_id' => $contactClient->getId(), ]; // Run the query to get the count. $count = $this->applyFilters($filters, true); if ($count > $quantity) { // Return the object, plus the count generated by the query. $result = [ 'rule' => $rule, 'count' => $count, ]; break; } } return $result; }
php
public function findLimit( ContactClient $contactClient, $rules = [], $timezone = null, \DateTime $dateSend = null ) { $filters = []; $result = null; foreach ($rules as $rule) { $orx = []; $value = $rule['value']; $scope = $rule['scope']; $duration = $rule['duration']; $quantity = $rule['quantity']; // Scope UTM Source if ($scope & self::SCOPE_UTM_SOURCE) { $utmSource = trim($value); if (!empty($utmSource)) { $orx['utm_source'] = trim($value); } } // Scope Category if ($scope & self::SCOPE_CATEGORY) { $category = intval($value); if ($category) { $orx['category_id'] = $category; } } // Match duration (always, including global scope) $filters[] = [ 'orx' => $orx, 'date_added' => $this->oldestDateAdded($duration, $timezone, $dateSend)->getTimestamp(), 'contactclient_id' => $contactClient->getId(), ]; // Run the query to get the count. $count = $this->applyFilters($filters, true); if ($count > $quantity) { // Return the object, plus the count generated by the query. $result = [ 'rule' => $rule, 'count' => $count, ]; break; } } return $result; }
[ "public", "function", "findLimit", "(", "ContactClient", "$", "contactClient", ",", "$", "rules", "=", "[", "]", ",", "$", "timezone", "=", "null", ",", "\\", "DateTime", "$", "dateSend", "=", "null", ")", "{", "$", "filters", "=", "[", "]", ";", "$", "result", "=", "null", ";", "foreach", "(", "$", "rules", "as", "$", "rule", ")", "{", "$", "orx", "=", "[", "]", ";", "$", "value", "=", "$", "rule", "[", "'value'", "]", ";", "$", "scope", "=", "$", "rule", "[", "'scope'", "]", ";", "$", "duration", "=", "$", "rule", "[", "'duration'", "]", ";", "$", "quantity", "=", "$", "rule", "[", "'quantity'", "]", ";", "// Scope UTM Source", "if", "(", "$", "scope", "&", "self", "::", "SCOPE_UTM_SOURCE", ")", "{", "$", "utmSource", "=", "trim", "(", "$", "value", ")", ";", "if", "(", "!", "empty", "(", "$", "utmSource", ")", ")", "{", "$", "orx", "[", "'utm_source'", "]", "=", "trim", "(", "$", "value", ")", ";", "}", "}", "// Scope Category", "if", "(", "$", "scope", "&", "self", "::", "SCOPE_CATEGORY", ")", "{", "$", "category", "=", "intval", "(", "$", "value", ")", ";", "if", "(", "$", "category", ")", "{", "$", "orx", "[", "'category_id'", "]", "=", "$", "category", ";", "}", "}", "// Match duration (always, including global scope)", "$", "filters", "[", "]", "=", "[", "'orx'", "=>", "$", "orx", ",", "'date_added'", "=>", "$", "this", "->", "oldestDateAdded", "(", "$", "duration", ",", "$", "timezone", ",", "$", "dateSend", ")", "->", "getTimestamp", "(", ")", ",", "'contactclient_id'", "=>", "$", "contactClient", "->", "getId", "(", ")", ",", "]", ";", "// Run the query to get the count.", "$", "count", "=", "$", "this", "->", "applyFilters", "(", "$", "filters", ",", "true", ")", ";", "if", "(", "$", "count", ">", "$", "quantity", ")", "{", "// Return the object, plus the count generated by the query.", "$", "result", "=", "[", "'rule'", "=>", "$", "rule", ",", "'count'", "=>", "$", "count", ",", "]", ";", "break", ";", "}", "}", "return", "$", "result", ";", "}" ]
Given a matching pattern and a contact, find any exceeded limits (aka caps/budgets). @param ContactClient $contactClient @param array $rules @param null $timezone @param \DateTime|null $dateSend @return array|null @throws \Exception
[ "Given", "a", "matching", "pattern", "and", "a", "contact", "find", "any", "exceeded", "limits", "(", "aka", "caps", "/", "budgets", ")", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L57-L108
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.oldestDateAdded
public function oldestDateAdded($duration, string $timezone = null, \DateTime $dateSend = null) { if (!$timezone) { $timezone = date_default_timezone_get(); } if (is_string($timezone)) { $timezone = new \DateTimeZone($timezone); } if ($dateSend) { $oldest = clone $dateSend; $oldest->setTimezone($timezone); } else { $oldest = new \DateTime('now', $timezone); } if (0 !== strpos($duration, 'P')) { // Non-rolling interval, go to previous interval segment. // Will only work for simple (singular) intervals. switch (strtoupper(substr($duration, -1))) { case 'Y': $oldest->modify('next year jan 1 midnight'); break; case 'M': $oldest->modify('first day of next month midnight'); break; case 'W': $oldest->modify('sunday next week midnight'); break; case 'D': $oldest->modify('tomorrow midnight'); break; } // Add P so that we can now use standard interval $duration = 'P'.$duration; } try { $interval = new \DateInterval($duration); } catch (\Exception $e) { // Default to monthly if the interval is faulty. $interval = new \DateInterval('P1M'); } $oldest->sub($interval); return $oldest; }
php
public function oldestDateAdded($duration, string $timezone = null, \DateTime $dateSend = null) { if (!$timezone) { $timezone = date_default_timezone_get(); } if (is_string($timezone)) { $timezone = new \DateTimeZone($timezone); } if ($dateSend) { $oldest = clone $dateSend; $oldest->setTimezone($timezone); } else { $oldest = new \DateTime('now', $timezone); } if (0 !== strpos($duration, 'P')) { // Non-rolling interval, go to previous interval segment. // Will only work for simple (singular) intervals. switch (strtoupper(substr($duration, -1))) { case 'Y': $oldest->modify('next year jan 1 midnight'); break; case 'M': $oldest->modify('first day of next month midnight'); break; case 'W': $oldest->modify('sunday next week midnight'); break; case 'D': $oldest->modify('tomorrow midnight'); break; } // Add P so that we can now use standard interval $duration = 'P'.$duration; } try { $interval = new \DateInterval($duration); } catch (\Exception $e) { // Default to monthly if the interval is faulty. $interval = new \DateInterval('P1M'); } $oldest->sub($interval); return $oldest; }
[ "public", "function", "oldestDateAdded", "(", "$", "duration", ",", "string", "$", "timezone", "=", "null", ",", "\\", "DateTime", "$", "dateSend", "=", "null", ")", "{", "if", "(", "!", "$", "timezone", ")", "{", "$", "timezone", "=", "date_default_timezone_get", "(", ")", ";", "}", "if", "(", "is_string", "(", "$", "timezone", ")", ")", "{", "$", "timezone", "=", "new", "\\", "DateTimeZone", "(", "$", "timezone", ")", ";", "}", "if", "(", "$", "dateSend", ")", "{", "$", "oldest", "=", "clone", "$", "dateSend", ";", "$", "oldest", "->", "setTimezone", "(", "$", "timezone", ")", ";", "}", "else", "{", "$", "oldest", "=", "new", "\\", "DateTime", "(", "'now'", ",", "$", "timezone", ")", ";", "}", "if", "(", "0", "!==", "strpos", "(", "$", "duration", ",", "'P'", ")", ")", "{", "// Non-rolling interval, go to previous interval segment.", "// Will only work for simple (singular) intervals.", "switch", "(", "strtoupper", "(", "substr", "(", "$", "duration", ",", "-", "1", ")", ")", ")", "{", "case", "'Y'", ":", "$", "oldest", "->", "modify", "(", "'next year jan 1 midnight'", ")", ";", "break", ";", "case", "'M'", ":", "$", "oldest", "->", "modify", "(", "'first day of next month midnight'", ")", ";", "break", ";", "case", "'W'", ":", "$", "oldest", "->", "modify", "(", "'sunday next week midnight'", ")", ";", "break", ";", "case", "'D'", ":", "$", "oldest", "->", "modify", "(", "'tomorrow midnight'", ")", ";", "break", ";", "}", "// Add P so that we can now use standard interval", "$", "duration", "=", "'P'", ".", "$", "duration", ";", "}", "try", "{", "$", "interval", "=", "new", "\\", "DateInterval", "(", "$", "duration", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Default to monthly if the interval is faulty.", "$", "interval", "=", "new", "\\", "DateInterval", "(", "'P1M'", ")", ";", "}", "$", "oldest", "->", "sub", "(", "$", "interval", ")", ";", "return", "$", "oldest", ";", "}" ]
Support non-rolling durations when P is not prefixing. @param $duration @param string|null $timezone @param \DateTime|null $dateSend @return \DateTime @throws \Exception
[ "Support", "non", "-", "rolling", "durations", "when", "P", "is", "not", "prefixing", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L121-L164
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.applyFilters
private function applyFilters($filters = [], $returnCount = false) { $result = null; // Convert our filters into a query. if ($filters) { $alias = $this->getTableAlias(); $query = $this->slaveQueryBuilder(); if ($returnCount) { $query->select('COUNT(*)'); } else { // Selecting only the id and contact_id for covering index benefits. $query->select($alias.'.id, '.$alias.'.contact_id'); $query->setMaxResults(1); } $query->from(MAUTIC_TABLE_PREFIX.$this->getTableName(), $alias); foreach ($filters as $k => $set) { // Expect orx, anx, or neither. if (isset($set['orx'])) { if (!empty($set['orx'])) { $expr = $query->expr()->orX(); } $properties = $set['orx']; } elseif (isset($set['andx'])) { if (!empty($set['andx'])) { $expr = $query->expr()->andX(); } $properties = $set['andx']; } else { if (!isset($expr)) { $expr = $query->expr()->andX(); } $properties = $set; } if (isset($expr) && !empty($properties)) { foreach ($properties as $property => $value) { if (is_array($value)) { $expr->add( $query->expr()->andX( $query->expr()->isNotNull($alias.'.'.$property), $query->expr()->in($alias.'.'.$property, $value) ) ); } elseif (is_int($value) || is_string($value)) { if (!empty($value)) { $expr->add( $query->expr()->andX( $query->expr()->isNotNull($alias.'.'.$property), $query->expr()->eq($alias.'.'.$property, ':'.$property.$k) ) ); } else { $expr->add( $query->expr()->eq($alias.'.'.$property, ':'.$property.$k) ); } if (in_array($property, ['category_id', 'contact_id', 'campaign_id', 'contactclient_id'])) { // Explicit integers for faster queries. $query->setParameter($property.$k, (int) $value, \PDO::PARAM_INT); } else { $query->setParameter($property.$k, $value); } } } } if (isset($set['exclusive_expire_date'])) { // Expiration/Exclusions will require an extra outer AND expression. if (!isset($exprOuter)) { $exprOuter = $query->expr()->orX(); $expireDate = $set['exclusive_expire_date']; } if (isset($expr)) { $exprOuter->add( $query->expr()->orX($expr) ); } } elseif (isset($set['contactclient_id']) && isset($set['date_added'])) { $query->add( 'where', $query->expr()->andX( $query->expr()->eq($alias.'.contactclient_id', ':contactClientId'.$k), $query->expr()->gte($alias.'.date_added', 'FROM_UNIXTIME(:dateAdded'.$k.')'), (isset($expr) ? $expr : null) ) ); $query->setParameter('contactClientId'.$k, (int) $set['contactclient_id'], \PDO::PARAM_INT); $query->setParameter('dateAdded'.$k, $set['date_added']); } } // Expiration can always be applied globally. if (isset($exprOuter) && isset($expireDate)) { $query->add( 'where', $query->expr()->andX( $query->expr()->isNotNull($alias.'.exclusive_expire_date'), $query->expr()->gte($alias.'.exclusive_expire_date', 'FROM_UNIXTIME(:exclusiveExpireDate)'), $exprOuter ) ); $query->setParameter('exclusiveExpireDate', $expireDate); } $result = $query->execute()->fetch(); if ($returnCount) { $result = intval(reset($result)); } } return $result; }
php
private function applyFilters($filters = [], $returnCount = false) { $result = null; // Convert our filters into a query. if ($filters) { $alias = $this->getTableAlias(); $query = $this->slaveQueryBuilder(); if ($returnCount) { $query->select('COUNT(*)'); } else { // Selecting only the id and contact_id for covering index benefits. $query->select($alias.'.id, '.$alias.'.contact_id'); $query->setMaxResults(1); } $query->from(MAUTIC_TABLE_PREFIX.$this->getTableName(), $alias); foreach ($filters as $k => $set) { // Expect orx, anx, or neither. if (isset($set['orx'])) { if (!empty($set['orx'])) { $expr = $query->expr()->orX(); } $properties = $set['orx']; } elseif (isset($set['andx'])) { if (!empty($set['andx'])) { $expr = $query->expr()->andX(); } $properties = $set['andx']; } else { if (!isset($expr)) { $expr = $query->expr()->andX(); } $properties = $set; } if (isset($expr) && !empty($properties)) { foreach ($properties as $property => $value) { if (is_array($value)) { $expr->add( $query->expr()->andX( $query->expr()->isNotNull($alias.'.'.$property), $query->expr()->in($alias.'.'.$property, $value) ) ); } elseif (is_int($value) || is_string($value)) { if (!empty($value)) { $expr->add( $query->expr()->andX( $query->expr()->isNotNull($alias.'.'.$property), $query->expr()->eq($alias.'.'.$property, ':'.$property.$k) ) ); } else { $expr->add( $query->expr()->eq($alias.'.'.$property, ':'.$property.$k) ); } if (in_array($property, ['category_id', 'contact_id', 'campaign_id', 'contactclient_id'])) { // Explicit integers for faster queries. $query->setParameter($property.$k, (int) $value, \PDO::PARAM_INT); } else { $query->setParameter($property.$k, $value); } } } } if (isset($set['exclusive_expire_date'])) { // Expiration/Exclusions will require an extra outer AND expression. if (!isset($exprOuter)) { $exprOuter = $query->expr()->orX(); $expireDate = $set['exclusive_expire_date']; } if (isset($expr)) { $exprOuter->add( $query->expr()->orX($expr) ); } } elseif (isset($set['contactclient_id']) && isset($set['date_added'])) { $query->add( 'where', $query->expr()->andX( $query->expr()->eq($alias.'.contactclient_id', ':contactClientId'.$k), $query->expr()->gte($alias.'.date_added', 'FROM_UNIXTIME(:dateAdded'.$k.')'), (isset($expr) ? $expr : null) ) ); $query->setParameter('contactClientId'.$k, (int) $set['contactclient_id'], \PDO::PARAM_INT); $query->setParameter('dateAdded'.$k, $set['date_added']); } } // Expiration can always be applied globally. if (isset($exprOuter) && isset($expireDate)) { $query->add( 'where', $query->expr()->andX( $query->expr()->isNotNull($alias.'.exclusive_expire_date'), $query->expr()->gte($alias.'.exclusive_expire_date', 'FROM_UNIXTIME(:exclusiveExpireDate)'), $exprOuter ) ); $query->setParameter('exclusiveExpireDate', $expireDate); } $result = $query->execute()->fetch(); if ($returnCount) { $result = intval(reset($result)); } } return $result; }
[ "private", "function", "applyFilters", "(", "$", "filters", "=", "[", "]", ",", "$", "returnCount", "=", "false", ")", "{", "$", "result", "=", "null", ";", "// Convert our filters into a query.", "if", "(", "$", "filters", ")", "{", "$", "alias", "=", "$", "this", "->", "getTableAlias", "(", ")", ";", "$", "query", "=", "$", "this", "->", "slaveQueryBuilder", "(", ")", ";", "if", "(", "$", "returnCount", ")", "{", "$", "query", "->", "select", "(", "'COUNT(*)'", ")", ";", "}", "else", "{", "// Selecting only the id and contact_id for covering index benefits.", "$", "query", "->", "select", "(", "$", "alias", ".", "'.id, '", ".", "$", "alias", ".", "'.contact_id'", ")", ";", "$", "query", "->", "setMaxResults", "(", "1", ")", ";", "}", "$", "query", "->", "from", "(", "MAUTIC_TABLE_PREFIX", ".", "$", "this", "->", "getTableName", "(", ")", ",", "$", "alias", ")", ";", "foreach", "(", "$", "filters", "as", "$", "k", "=>", "$", "set", ")", "{", "// Expect orx, anx, or neither.", "if", "(", "isset", "(", "$", "set", "[", "'orx'", "]", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "set", "[", "'orx'", "]", ")", ")", "{", "$", "expr", "=", "$", "query", "->", "expr", "(", ")", "->", "orX", "(", ")", ";", "}", "$", "properties", "=", "$", "set", "[", "'orx'", "]", ";", "}", "elseif", "(", "isset", "(", "$", "set", "[", "'andx'", "]", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "set", "[", "'andx'", "]", ")", ")", "{", "$", "expr", "=", "$", "query", "->", "expr", "(", ")", "->", "andX", "(", ")", ";", "}", "$", "properties", "=", "$", "set", "[", "'andx'", "]", ";", "}", "else", "{", "if", "(", "!", "isset", "(", "$", "expr", ")", ")", "{", "$", "expr", "=", "$", "query", "->", "expr", "(", ")", "->", "andX", "(", ")", ";", "}", "$", "properties", "=", "$", "set", ";", "}", "if", "(", "isset", "(", "$", "expr", ")", "&&", "!", "empty", "(", "$", "properties", ")", ")", "{", "foreach", "(", "$", "properties", "as", "$", "property", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "expr", "->", "add", "(", "$", "query", "->", "expr", "(", ")", "->", "andX", "(", "$", "query", "->", "expr", "(", ")", "->", "isNotNull", "(", "$", "alias", ".", "'.'", ".", "$", "property", ")", ",", "$", "query", "->", "expr", "(", ")", "->", "in", "(", "$", "alias", ".", "'.'", ".", "$", "property", ",", "$", "value", ")", ")", ")", ";", "}", "elseif", "(", "is_int", "(", "$", "value", ")", "||", "is_string", "(", "$", "value", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "expr", "->", "add", "(", "$", "query", "->", "expr", "(", ")", "->", "andX", "(", "$", "query", "->", "expr", "(", ")", "->", "isNotNull", "(", "$", "alias", ".", "'.'", ".", "$", "property", ")", ",", "$", "query", "->", "expr", "(", ")", "->", "eq", "(", "$", "alias", ".", "'.'", ".", "$", "property", ",", "':'", ".", "$", "property", ".", "$", "k", ")", ")", ")", ";", "}", "else", "{", "$", "expr", "->", "add", "(", "$", "query", "->", "expr", "(", ")", "->", "eq", "(", "$", "alias", ".", "'.'", ".", "$", "property", ",", "':'", ".", "$", "property", ".", "$", "k", ")", ")", ";", "}", "if", "(", "in_array", "(", "$", "property", ",", "[", "'category_id'", ",", "'contact_id'", ",", "'campaign_id'", ",", "'contactclient_id'", "]", ")", ")", "{", "// Explicit integers for faster queries.", "$", "query", "->", "setParameter", "(", "$", "property", ".", "$", "k", ",", "(", "int", ")", "$", "value", ",", "\\", "PDO", "::", "PARAM_INT", ")", ";", "}", "else", "{", "$", "query", "->", "setParameter", "(", "$", "property", ".", "$", "k", ",", "$", "value", ")", ";", "}", "}", "}", "}", "if", "(", "isset", "(", "$", "set", "[", "'exclusive_expire_date'", "]", ")", ")", "{", "// Expiration/Exclusions will require an extra outer AND expression.", "if", "(", "!", "isset", "(", "$", "exprOuter", ")", ")", "{", "$", "exprOuter", "=", "$", "query", "->", "expr", "(", ")", "->", "orX", "(", ")", ";", "$", "expireDate", "=", "$", "set", "[", "'exclusive_expire_date'", "]", ";", "}", "if", "(", "isset", "(", "$", "expr", ")", ")", "{", "$", "exprOuter", "->", "add", "(", "$", "query", "->", "expr", "(", ")", "->", "orX", "(", "$", "expr", ")", ")", ";", "}", "}", "elseif", "(", "isset", "(", "$", "set", "[", "'contactclient_id'", "]", ")", "&&", "isset", "(", "$", "set", "[", "'date_added'", "]", ")", ")", "{", "$", "query", "->", "add", "(", "'where'", ",", "$", "query", "->", "expr", "(", ")", "->", "andX", "(", "$", "query", "->", "expr", "(", ")", "->", "eq", "(", "$", "alias", ".", "'.contactclient_id'", ",", "':contactClientId'", ".", "$", "k", ")", ",", "$", "query", "->", "expr", "(", ")", "->", "gte", "(", "$", "alias", ".", "'.date_added'", ",", "'FROM_UNIXTIME(:dateAdded'", ".", "$", "k", ".", "')'", ")", ",", "(", "isset", "(", "$", "expr", ")", "?", "$", "expr", ":", "null", ")", ")", ")", ";", "$", "query", "->", "setParameter", "(", "'contactClientId'", ".", "$", "k", ",", "(", "int", ")", "$", "set", "[", "'contactclient_id'", "]", ",", "\\", "PDO", "::", "PARAM_INT", ")", ";", "$", "query", "->", "setParameter", "(", "'dateAdded'", ".", "$", "k", ",", "$", "set", "[", "'date_added'", "]", ")", ";", "}", "}", "// Expiration can always be applied globally.", "if", "(", "isset", "(", "$", "exprOuter", ")", "&&", "isset", "(", "$", "expireDate", ")", ")", "{", "$", "query", "->", "add", "(", "'where'", ",", "$", "query", "->", "expr", "(", ")", "->", "andX", "(", "$", "query", "->", "expr", "(", ")", "->", "isNotNull", "(", "$", "alias", ".", "'.exclusive_expire_date'", ")", ",", "$", "query", "->", "expr", "(", ")", "->", "gte", "(", "$", "alias", ".", "'.exclusive_expire_date'", ",", "'FROM_UNIXTIME(:exclusiveExpireDate)'", ")", ",", "$", "exprOuter", ")", ")", ";", "$", "query", "->", "setParameter", "(", "'exclusiveExpireDate'", ",", "$", "expireDate", ")", ";", "}", "$", "result", "=", "$", "query", "->", "execute", "(", ")", "->", "fetch", "(", ")", ";", "if", "(", "$", "returnCount", ")", "{", "$", "result", "=", "intval", "(", "reset", "(", "$", "result", ")", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
@param array $filters @param bool $returnCount @return mixed|null
[ "@param", "array", "$filters", "@param", "bool", "$returnCount" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L172-L281
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.slaveQueryBuilder
private function slaveQueryBuilder() { /** @var Connection $connection */ $connection = $this->getEntityManager()->getConnection(); if ($connection instanceof MasterSlaveConnection) { // Prefer a slave connection if available. $connection->connect('slave'); } return new QueryBuilder($connection); }
php
private function slaveQueryBuilder() { /** @var Connection $connection */ $connection = $this->getEntityManager()->getConnection(); if ($connection instanceof MasterSlaveConnection) { // Prefer a slave connection if available. $connection->connect('slave'); } return new QueryBuilder($connection); }
[ "private", "function", "slaveQueryBuilder", "(", ")", "{", "/** @var Connection $connection */", "$", "connection", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getConnection", "(", ")", ";", "if", "(", "$", "connection", "instanceof", "MasterSlaveConnection", ")", "{", "// Prefer a slave connection if available.", "$", "connection", "->", "connect", "(", "'slave'", ")", ";", "}", "return", "new", "QueryBuilder", "(", "$", "connection", ")", ";", "}" ]
Create a DBAL QueryBuilder preferring a slave connection if available. @return QueryBuilder
[ "Create", "a", "DBAL", "QueryBuilder", "preferring", "a", "slave", "connection", "if", "available", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L288-L298
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.findDuplicate
public function findDuplicate( Contact $contact, ContactClient $contactClient, $rules = [], string $utmSource = null, string $timezone = null, \DateTime $dateSend = null ) { // Generate our filters based on the rules provided. $filters = []; foreach ($rules as $rule) { $orx = []; $matching = $rule['matching']; $scope = $rule['scope']; $duration = $rule['duration']; // Match explicit if ($matching & self::MATCHING_EXPLICIT) { $orx['contact_id'] = (int) $contact->getId(); } // Match email if ($matching & self::MATCHING_EMAIL) { $email = trim($contact->getEmail()); if ($email) { $orx['email'] = $email; } } // Match phone if ($matching & self::MATCHING_PHONE) { $phone = $this->phoneValidate($contact->getPhone()); if (!empty($phone)) { $orx['phone'] = $phone; } } // Match mobile if ($matching & self::MATCHING_MOBILE) { $mobile = $this->phoneValidate($contact->getMobile()); if (!empty($mobile)) { $orx['mobile'] = $mobile; } } // Match address if ($matching & self::MATCHING_ADDRESS) { $address1 = trim(ucwords($contact->getAddress1())); if (!empty($address1)) { $city = trim(ucwords($contact->getCity())); $zipcode = trim(ucwords($contact->getZipcode())); // Only support this level of matching if we have enough for a valid address. if (!empty($zipcode) || !empty($city)) { $orx['address1'] = $address1; $address2 = trim(ucwords($contact->getAddress2())); if (!empty($address2)) { $orx['address2'] = $address2; } if (!empty($city)) { $orx['city'] = $city; } $state = trim(ucwords($contact->getState())); if (!empty($state)) { $orx['state'] = $state; } if (!empty($zipcode)) { $orx['zipcode'] = $zipcode; } $country = trim(ucwords($contact->getCountry())); if (!empty($country)) { $orx['country'] = $country; } } } } // Scope UTM Source if ($scope & self::SCOPE_UTM_SOURCE) { if (!empty($utmSource)) { $orx['utm_source'] = $utmSource; } } // Scope Category if ($scope & self::SCOPE_CATEGORY) { $category = $contactClient->getCategory(); if ($category) { $category = (int) $category->getId(); if (!empty($category)) { $orx['category_id'] = $category; } } } if ($orx) { // Match duration (always), once all other aspects of the query are ready. $filters[] = [ 'orx' => $orx, 'date_added' => $this->oldestDateAdded($duration, $timezone, $dateSend)->getTimestamp(), 'contactclient_id' => $contactClient->getId(), ]; } } return $this->applyFilters($filters); }
php
public function findDuplicate( Contact $contact, ContactClient $contactClient, $rules = [], string $utmSource = null, string $timezone = null, \DateTime $dateSend = null ) { // Generate our filters based on the rules provided. $filters = []; foreach ($rules as $rule) { $orx = []; $matching = $rule['matching']; $scope = $rule['scope']; $duration = $rule['duration']; // Match explicit if ($matching & self::MATCHING_EXPLICIT) { $orx['contact_id'] = (int) $contact->getId(); } // Match email if ($matching & self::MATCHING_EMAIL) { $email = trim($contact->getEmail()); if ($email) { $orx['email'] = $email; } } // Match phone if ($matching & self::MATCHING_PHONE) { $phone = $this->phoneValidate($contact->getPhone()); if (!empty($phone)) { $orx['phone'] = $phone; } } // Match mobile if ($matching & self::MATCHING_MOBILE) { $mobile = $this->phoneValidate($contact->getMobile()); if (!empty($mobile)) { $orx['mobile'] = $mobile; } } // Match address if ($matching & self::MATCHING_ADDRESS) { $address1 = trim(ucwords($contact->getAddress1())); if (!empty($address1)) { $city = trim(ucwords($contact->getCity())); $zipcode = trim(ucwords($contact->getZipcode())); // Only support this level of matching if we have enough for a valid address. if (!empty($zipcode) || !empty($city)) { $orx['address1'] = $address1; $address2 = trim(ucwords($contact->getAddress2())); if (!empty($address2)) { $orx['address2'] = $address2; } if (!empty($city)) { $orx['city'] = $city; } $state = trim(ucwords($contact->getState())); if (!empty($state)) { $orx['state'] = $state; } if (!empty($zipcode)) { $orx['zipcode'] = $zipcode; } $country = trim(ucwords($contact->getCountry())); if (!empty($country)) { $orx['country'] = $country; } } } } // Scope UTM Source if ($scope & self::SCOPE_UTM_SOURCE) { if (!empty($utmSource)) { $orx['utm_source'] = $utmSource; } } // Scope Category if ($scope & self::SCOPE_CATEGORY) { $category = $contactClient->getCategory(); if ($category) { $category = (int) $category->getId(); if (!empty($category)) { $orx['category_id'] = $category; } } } if ($orx) { // Match duration (always), once all other aspects of the query are ready. $filters[] = [ 'orx' => $orx, 'date_added' => $this->oldestDateAdded($duration, $timezone, $dateSend)->getTimestamp(), 'contactclient_id' => $contactClient->getId(), ]; } } return $this->applyFilters($filters); }
[ "public", "function", "findDuplicate", "(", "Contact", "$", "contact", ",", "ContactClient", "$", "contactClient", ",", "$", "rules", "=", "[", "]", ",", "string", "$", "utmSource", "=", "null", ",", "string", "$", "timezone", "=", "null", ",", "\\", "DateTime", "$", "dateSend", "=", "null", ")", "{", "// Generate our filters based on the rules provided.", "$", "filters", "=", "[", "]", ";", "foreach", "(", "$", "rules", "as", "$", "rule", ")", "{", "$", "orx", "=", "[", "]", ";", "$", "matching", "=", "$", "rule", "[", "'matching'", "]", ";", "$", "scope", "=", "$", "rule", "[", "'scope'", "]", ";", "$", "duration", "=", "$", "rule", "[", "'duration'", "]", ";", "// Match explicit", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_EXPLICIT", ")", "{", "$", "orx", "[", "'contact_id'", "]", "=", "(", "int", ")", "$", "contact", "->", "getId", "(", ")", ";", "}", "// Match email", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_EMAIL", ")", "{", "$", "email", "=", "trim", "(", "$", "contact", "->", "getEmail", "(", ")", ")", ";", "if", "(", "$", "email", ")", "{", "$", "orx", "[", "'email'", "]", "=", "$", "email", ";", "}", "}", "// Match phone", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_PHONE", ")", "{", "$", "phone", "=", "$", "this", "->", "phoneValidate", "(", "$", "contact", "->", "getPhone", "(", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "phone", ")", ")", "{", "$", "orx", "[", "'phone'", "]", "=", "$", "phone", ";", "}", "}", "// Match mobile", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_MOBILE", ")", "{", "$", "mobile", "=", "$", "this", "->", "phoneValidate", "(", "$", "contact", "->", "getMobile", "(", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "mobile", ")", ")", "{", "$", "orx", "[", "'mobile'", "]", "=", "$", "mobile", ";", "}", "}", "// Match address", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_ADDRESS", ")", "{", "$", "address1", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getAddress1", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "address1", ")", ")", "{", "$", "city", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getCity", "(", ")", ")", ")", ";", "$", "zipcode", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getZipcode", "(", ")", ")", ")", ";", "// Only support this level of matching if we have enough for a valid address.", "if", "(", "!", "empty", "(", "$", "zipcode", ")", "||", "!", "empty", "(", "$", "city", ")", ")", "{", "$", "orx", "[", "'address1'", "]", "=", "$", "address1", ";", "$", "address2", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getAddress2", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "address2", ")", ")", "{", "$", "orx", "[", "'address2'", "]", "=", "$", "address2", ";", "}", "if", "(", "!", "empty", "(", "$", "city", ")", ")", "{", "$", "orx", "[", "'city'", "]", "=", "$", "city", ";", "}", "$", "state", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getState", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "state", ")", ")", "{", "$", "orx", "[", "'state'", "]", "=", "$", "state", ";", "}", "if", "(", "!", "empty", "(", "$", "zipcode", ")", ")", "{", "$", "orx", "[", "'zipcode'", "]", "=", "$", "zipcode", ";", "}", "$", "country", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getCountry", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "country", ")", ")", "{", "$", "orx", "[", "'country'", "]", "=", "$", "country", ";", "}", "}", "}", "}", "// Scope UTM Source", "if", "(", "$", "scope", "&", "self", "::", "SCOPE_UTM_SOURCE", ")", "{", "if", "(", "!", "empty", "(", "$", "utmSource", ")", ")", "{", "$", "orx", "[", "'utm_source'", "]", "=", "$", "utmSource", ";", "}", "}", "// Scope Category", "if", "(", "$", "scope", "&", "self", "::", "SCOPE_CATEGORY", ")", "{", "$", "category", "=", "$", "contactClient", "->", "getCategory", "(", ")", ";", "if", "(", "$", "category", ")", "{", "$", "category", "=", "(", "int", ")", "$", "category", "->", "getId", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "category", ")", ")", "{", "$", "orx", "[", "'category_id'", "]", "=", "$", "category", ";", "}", "}", "}", "if", "(", "$", "orx", ")", "{", "// Match duration (always), once all other aspects of the query are ready.", "$", "filters", "[", "]", "=", "[", "'orx'", "=>", "$", "orx", ",", "'date_added'", "=>", "$", "this", "->", "oldestDateAdded", "(", "$", "duration", ",", "$", "timezone", ",", "$", "dateSend", ")", "->", "getTimestamp", "(", ")", ",", "'contactclient_id'", "=>", "$", "contactClient", "->", "getId", "(", ")", ",", "]", ";", "}", "}", "return", "$", "this", "->", "applyFilters", "(", "$", "filters", ")", ";", "}" ]
Given a matching pattern and a contact, discern if there is a match in the cache. Used for exclusivity and duplicate checking. @param Contact $contact @param ContactClient $contactClient @param array $rules @param string $utmSource @param string|null $timezone @param \DateTime|null $dateSend @return mixed|null @throws \Exception
[ "Given", "a", "matching", "pattern", "and", "a", "contact", "discern", "if", "there", "is", "a", "match", "in", "the", "cache", ".", "Used", "for", "exclusivity", "and", "duplicate", "checking", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L315-L426
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.phoneValidate
private function phoneValidate($phone) { $result = null; $phone = trim($phone); if (!empty($phone)) { if (!$this->phoneHelper) { $this->phoneHelper = new PhoneNumberHelper(); } try { $phone = $this->phoneHelper->format($phone); if (!empty($phone)) { $result = $phone; } } catch (\Exception $e) { } } return $result; }
php
private function phoneValidate($phone) { $result = null; $phone = trim($phone); if (!empty($phone)) { if (!$this->phoneHelper) { $this->phoneHelper = new PhoneNumberHelper(); } try { $phone = $this->phoneHelper->format($phone); if (!empty($phone)) { $result = $phone; } } catch (\Exception $e) { } } return $result; }
[ "private", "function", "phoneValidate", "(", "$", "phone", ")", "{", "$", "result", "=", "null", ";", "$", "phone", "=", "trim", "(", "$", "phone", ")", ";", "if", "(", "!", "empty", "(", "$", "phone", ")", ")", "{", "if", "(", "!", "$", "this", "->", "phoneHelper", ")", "{", "$", "this", "->", "phoneHelper", "=", "new", "PhoneNumberHelper", "(", ")", ";", "}", "try", "{", "$", "phone", "=", "$", "this", "->", "phoneHelper", "->", "format", "(", "$", "phone", ")", ";", "if", "(", "!", "empty", "(", "$", "phone", ")", ")", "{", "$", "result", "=", "$", "phone", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "}", "return", "$", "result", ";", "}" ]
@param $phone @return string
[ "@param", "$phone" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L433-L451
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.findExclusive
public function findExclusive( Contact $contact, ContactClient $contactClient, \DateTime $dateSend = null, $matching = self::MATCHING_EXPLICIT | self::MATCHING_EMAIL | self::MATCHING_PHONE | self::MATCHING_MOBILE, $scope = self::SCOPE_GLOBAL | self::SCOPE_CATEGORY ) { // Generate our filters based on all rules possibly in play. $filters = []; // Match explicit if ($matching & self::MATCHING_EXPLICIT) { $filters[] = [ 'andx' => [ 'contact_id' => (int) $contact->getId(), 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_EXPLICIT), ], ]; } // Match email if ($matching & self::MATCHING_EMAIL) { $email = trim($contact->getEmail()); if ($email) { $filters[] = [ 'andx' => [ 'email' => $email, 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_EMAIL), ], ]; } } // Match phone if ($matching & self::MATCHING_PHONE) { $phone = $this->phoneValidate($contact->getPhone()); if (!empty($phone)) { $filters[] = [ 'andx' => [ 'phone' => $phone, 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_MOBILE), ], ]; } } // Match mobile if ($matching & self::MATCHING_MOBILE) { $mobile = $this->phoneValidate($contact->getMobile()); if (!empty($mobile)) { $filters[] = [ 'andx' => [ 'phone' => $mobile, 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_PHONE), ], ]; } } // Due to high overhead, we've left out address-based exclusivity for now. // Match address if ($matching & self::MATCHING_ADDRESS) { $address1 = trim(ucwords($contact->getAddress1())); if (!empty($address1)) { $filter = []; $city = trim(ucwords($contact->getCity())); $zipcode = trim(ucwords($contact->getZipcode())); // Only support this level of matching if we have enough for a valid address. if (!empty($zipcode) || !empty($city)) { $filter['address1'] = $address1; $address2 = trim(ucwords($contact->getAddress2())); if (!empty($address2)) { $filter['address2'] = $address2; } if (!empty($city)) { $filter['city'] = $city; } $state = trim(ucwords($contact->getState())); if (!empty($state)) { $filter['state'] = $state; } if (!empty($zipcode)) { $filter['zipcode'] = $zipcode; } $country = trim(ucwords($contact->getCountry())); if (!empty($country)) { $filter['country'] = $country; } $filter['exclusive_pattern'] = $this->bitwiseIn($matching, self::MATCHING_ADDRESS); $filters[] = [ 'andx' => $filter, ]; } } } // Scope Global (added to all filters) if ($scope & self::SCOPE_GLOBAL) { $scopePattern = $this->bitwiseIn($scope, self::SCOPE_GLOBAL); foreach ($filters as &$filter) { $filter['andx']['exclusive_scope'] = $scopePattern; } unset($filter); } // Scope Category (duplicates all filters with category specificity) if ($scope & self::SCOPE_CATEGORY) { $category = $contactClient->getCategory(); if ($category) { $category = (int) $category->getId(); if ($category) { $scopePattern = $this->bitwiseIn($scope, self::SCOPE_CATEGORY); $newFilters = []; foreach ($filters as $filter) { // Add existing filter. $newFilters[serialize($filter)] = $filter; // Create a new category-locked filter equivalent. $newFilter = $filter; $newFilter['andx']['category_id'] = $category; $newFilter['andx']['exclusive_scope'] = $scopePattern; $newFilters[serialize($newFilter)] = $newFilter; } $filters = array_values($newFilters); } } } // Add expiration to all filters. $this->addExpiration($filters, $dateSend); return $this->applyFilters($filters); }
php
public function findExclusive( Contact $contact, ContactClient $contactClient, \DateTime $dateSend = null, $matching = self::MATCHING_EXPLICIT | self::MATCHING_EMAIL | self::MATCHING_PHONE | self::MATCHING_MOBILE, $scope = self::SCOPE_GLOBAL | self::SCOPE_CATEGORY ) { // Generate our filters based on all rules possibly in play. $filters = []; // Match explicit if ($matching & self::MATCHING_EXPLICIT) { $filters[] = [ 'andx' => [ 'contact_id' => (int) $contact->getId(), 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_EXPLICIT), ], ]; } // Match email if ($matching & self::MATCHING_EMAIL) { $email = trim($contact->getEmail()); if ($email) { $filters[] = [ 'andx' => [ 'email' => $email, 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_EMAIL), ], ]; } } // Match phone if ($matching & self::MATCHING_PHONE) { $phone = $this->phoneValidate($contact->getPhone()); if (!empty($phone)) { $filters[] = [ 'andx' => [ 'phone' => $phone, 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_MOBILE), ], ]; } } // Match mobile if ($matching & self::MATCHING_MOBILE) { $mobile = $this->phoneValidate($contact->getMobile()); if (!empty($mobile)) { $filters[] = [ 'andx' => [ 'phone' => $mobile, 'exclusive_pattern' => $this->bitwiseIn($matching, self::MATCHING_PHONE), ], ]; } } // Due to high overhead, we've left out address-based exclusivity for now. // Match address if ($matching & self::MATCHING_ADDRESS) { $address1 = trim(ucwords($contact->getAddress1())); if (!empty($address1)) { $filter = []; $city = trim(ucwords($contact->getCity())); $zipcode = trim(ucwords($contact->getZipcode())); // Only support this level of matching if we have enough for a valid address. if (!empty($zipcode) || !empty($city)) { $filter['address1'] = $address1; $address2 = trim(ucwords($contact->getAddress2())); if (!empty($address2)) { $filter['address2'] = $address2; } if (!empty($city)) { $filter['city'] = $city; } $state = trim(ucwords($contact->getState())); if (!empty($state)) { $filter['state'] = $state; } if (!empty($zipcode)) { $filter['zipcode'] = $zipcode; } $country = trim(ucwords($contact->getCountry())); if (!empty($country)) { $filter['country'] = $country; } $filter['exclusive_pattern'] = $this->bitwiseIn($matching, self::MATCHING_ADDRESS); $filters[] = [ 'andx' => $filter, ]; } } } // Scope Global (added to all filters) if ($scope & self::SCOPE_GLOBAL) { $scopePattern = $this->bitwiseIn($scope, self::SCOPE_GLOBAL); foreach ($filters as &$filter) { $filter['andx']['exclusive_scope'] = $scopePattern; } unset($filter); } // Scope Category (duplicates all filters with category specificity) if ($scope & self::SCOPE_CATEGORY) { $category = $contactClient->getCategory(); if ($category) { $category = (int) $category->getId(); if ($category) { $scopePattern = $this->bitwiseIn($scope, self::SCOPE_CATEGORY); $newFilters = []; foreach ($filters as $filter) { // Add existing filter. $newFilters[serialize($filter)] = $filter; // Create a new category-locked filter equivalent. $newFilter = $filter; $newFilter['andx']['category_id'] = $category; $newFilter['andx']['exclusive_scope'] = $scopePattern; $newFilters[serialize($newFilter)] = $newFilter; } $filters = array_values($newFilters); } } } // Add expiration to all filters. $this->addExpiration($filters, $dateSend); return $this->applyFilters($filters); }
[ "public", "function", "findExclusive", "(", "Contact", "$", "contact", ",", "ContactClient", "$", "contactClient", ",", "\\", "DateTime", "$", "dateSend", "=", "null", ",", "$", "matching", "=", "self", "::", "MATCHING_EXPLICIT", "|", "self", "::", "MATCHING_EMAIL", "|", "self", "::", "MATCHING_PHONE", "|", "self", "::", "MATCHING_MOBILE", ",", "$", "scope", "=", "self", "::", "SCOPE_GLOBAL", "|", "self", "::", "SCOPE_CATEGORY", ")", "{", "// Generate our filters based on all rules possibly in play.", "$", "filters", "=", "[", "]", ";", "// Match explicit", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_EXPLICIT", ")", "{", "$", "filters", "[", "]", "=", "[", "'andx'", "=>", "[", "'contact_id'", "=>", "(", "int", ")", "$", "contact", "->", "getId", "(", ")", ",", "'exclusive_pattern'", "=>", "$", "this", "->", "bitwiseIn", "(", "$", "matching", ",", "self", "::", "MATCHING_EXPLICIT", ")", ",", "]", ",", "]", ";", "}", "// Match email", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_EMAIL", ")", "{", "$", "email", "=", "trim", "(", "$", "contact", "->", "getEmail", "(", ")", ")", ";", "if", "(", "$", "email", ")", "{", "$", "filters", "[", "]", "=", "[", "'andx'", "=>", "[", "'email'", "=>", "$", "email", ",", "'exclusive_pattern'", "=>", "$", "this", "->", "bitwiseIn", "(", "$", "matching", ",", "self", "::", "MATCHING_EMAIL", ")", ",", "]", ",", "]", ";", "}", "}", "// Match phone", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_PHONE", ")", "{", "$", "phone", "=", "$", "this", "->", "phoneValidate", "(", "$", "contact", "->", "getPhone", "(", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "phone", ")", ")", "{", "$", "filters", "[", "]", "=", "[", "'andx'", "=>", "[", "'phone'", "=>", "$", "phone", ",", "'exclusive_pattern'", "=>", "$", "this", "->", "bitwiseIn", "(", "$", "matching", ",", "self", "::", "MATCHING_MOBILE", ")", ",", "]", ",", "]", ";", "}", "}", "// Match mobile", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_MOBILE", ")", "{", "$", "mobile", "=", "$", "this", "->", "phoneValidate", "(", "$", "contact", "->", "getMobile", "(", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "mobile", ")", ")", "{", "$", "filters", "[", "]", "=", "[", "'andx'", "=>", "[", "'phone'", "=>", "$", "mobile", ",", "'exclusive_pattern'", "=>", "$", "this", "->", "bitwiseIn", "(", "$", "matching", ",", "self", "::", "MATCHING_PHONE", ")", ",", "]", ",", "]", ";", "}", "}", "// Due to high overhead, we've left out address-based exclusivity for now.", "// Match address", "if", "(", "$", "matching", "&", "self", "::", "MATCHING_ADDRESS", ")", "{", "$", "address1", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getAddress1", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "address1", ")", ")", "{", "$", "filter", "=", "[", "]", ";", "$", "city", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getCity", "(", ")", ")", ")", ";", "$", "zipcode", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getZipcode", "(", ")", ")", ")", ";", "// Only support this level of matching if we have enough for a valid address.", "if", "(", "!", "empty", "(", "$", "zipcode", ")", "||", "!", "empty", "(", "$", "city", ")", ")", "{", "$", "filter", "[", "'address1'", "]", "=", "$", "address1", ";", "$", "address2", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getAddress2", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "address2", ")", ")", "{", "$", "filter", "[", "'address2'", "]", "=", "$", "address2", ";", "}", "if", "(", "!", "empty", "(", "$", "city", ")", ")", "{", "$", "filter", "[", "'city'", "]", "=", "$", "city", ";", "}", "$", "state", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getState", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "state", ")", ")", "{", "$", "filter", "[", "'state'", "]", "=", "$", "state", ";", "}", "if", "(", "!", "empty", "(", "$", "zipcode", ")", ")", "{", "$", "filter", "[", "'zipcode'", "]", "=", "$", "zipcode", ";", "}", "$", "country", "=", "trim", "(", "ucwords", "(", "$", "contact", "->", "getCountry", "(", ")", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "country", ")", ")", "{", "$", "filter", "[", "'country'", "]", "=", "$", "country", ";", "}", "$", "filter", "[", "'exclusive_pattern'", "]", "=", "$", "this", "->", "bitwiseIn", "(", "$", "matching", ",", "self", "::", "MATCHING_ADDRESS", ")", ";", "$", "filters", "[", "]", "=", "[", "'andx'", "=>", "$", "filter", ",", "]", ";", "}", "}", "}", "// Scope Global (added to all filters)", "if", "(", "$", "scope", "&", "self", "::", "SCOPE_GLOBAL", ")", "{", "$", "scopePattern", "=", "$", "this", "->", "bitwiseIn", "(", "$", "scope", ",", "self", "::", "SCOPE_GLOBAL", ")", ";", "foreach", "(", "$", "filters", "as", "&", "$", "filter", ")", "{", "$", "filter", "[", "'andx'", "]", "[", "'exclusive_scope'", "]", "=", "$", "scopePattern", ";", "}", "unset", "(", "$", "filter", ")", ";", "}", "// Scope Category (duplicates all filters with category specificity)", "if", "(", "$", "scope", "&", "self", "::", "SCOPE_CATEGORY", ")", "{", "$", "category", "=", "$", "contactClient", "->", "getCategory", "(", ")", ";", "if", "(", "$", "category", ")", "{", "$", "category", "=", "(", "int", ")", "$", "category", "->", "getId", "(", ")", ";", "if", "(", "$", "category", ")", "{", "$", "scopePattern", "=", "$", "this", "->", "bitwiseIn", "(", "$", "scope", ",", "self", "::", "SCOPE_CATEGORY", ")", ";", "$", "newFilters", "=", "[", "]", ";", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "// Add existing filter.", "$", "newFilters", "[", "serialize", "(", "$", "filter", ")", "]", "=", "$", "filter", ";", "// Create a new category-locked filter equivalent.", "$", "newFilter", "=", "$", "filter", ";", "$", "newFilter", "[", "'andx'", "]", "[", "'category_id'", "]", "=", "$", "category", ";", "$", "newFilter", "[", "'andx'", "]", "[", "'exclusive_scope'", "]", "=", "$", "scopePattern", ";", "$", "newFilters", "[", "serialize", "(", "$", "newFilter", ")", "]", "=", "$", "newFilter", ";", "}", "$", "filters", "=", "array_values", "(", "$", "newFilters", ")", ";", "}", "}", "}", "// Add expiration to all filters.", "$", "this", "->", "addExpiration", "(", "$", "filters", ",", "$", "dateSend", ")", ";", "return", "$", "this", "->", "applyFilters", "(", "$", "filters", ")", ";", "}" ]
Check the entire cache for matching contacts given all possible Exclusivity rules. Only the first 4 matching rules are allowed for exclusivity (by default). Only the first two scopes are allowed for exclusivity. @param Contact $contact @param ContactClient $contactClient @param \DateTime|null $dateSend @param int $matching @param int $scope @return mixed|null @throws \Exception
[ "Check", "the", "entire", "cache", "for", "matching", "contacts", "given", "all", "possible", "Exclusivity", "rules", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L469-L606
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.bitwiseIn
private function bitwiseIn( $max, $matching ) { $result = []; for ($i = 1; $i <= $max; ++$i) { if ($i & $matching) { $result[] = $i; } } return $result; }
php
private function bitwiseIn( $max, $matching ) { $result = []; for ($i = 1; $i <= $max; ++$i) { if ($i & $matching) { $result[] = $i; } } return $result; }
[ "private", "function", "bitwiseIn", "(", "$", "max", ",", "$", "matching", ")", "{", "$", "result", "=", "[", "]", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<=", "$", "max", ";", "++", "$", "i", ")", "{", "if", "(", "$", "i", "&", "$", "matching", ")", "{", "$", "result", "[", "]", "=", "$", "i", ";", "}", "}", "return", "$", "result", ";", "}" ]
Given bitwise operators, and the value we want to match against, generate a minimal array for an IN query. @param int $max @param $matching @return array
[ "Given", "bitwise", "operators", "and", "the", "value", "we", "want", "to", "match", "against", "generate", "a", "minimal", "array", "for", "an", "IN", "query", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L617-L629
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.addExpiration
private function addExpiration( &$filters = [], \DateTime $dateSend = null ) { if ($filters) { $expiration = $dateSend ? $dateSend : new \DateTime(); $expiration = $expiration->getTimestamp(); foreach ($filters as &$filter) { $filter['exclusive_expire_date'] = $expiration; } } }
php
private function addExpiration( &$filters = [], \DateTime $dateSend = null ) { if ($filters) { $expiration = $dateSend ? $dateSend : new \DateTime(); $expiration = $expiration->getTimestamp(); foreach ($filters as &$filter) { $filter['exclusive_expire_date'] = $expiration; } } }
[ "private", "function", "addExpiration", "(", "&", "$", "filters", "=", "[", "]", ",", "\\", "DateTime", "$", "dateSend", "=", "null", ")", "{", "if", "(", "$", "filters", ")", "{", "$", "expiration", "=", "$", "dateSend", "?", "$", "dateSend", ":", "new", "\\", "DateTime", "(", ")", ";", "$", "expiration", "=", "$", "expiration", "->", "getTimestamp", "(", ")", ";", "foreach", "(", "$", "filters", "as", "&", "$", "filter", ")", "{", "$", "filter", "[", "'exclusive_expire_date'", "]", "=", "$", "expiration", ";", "}", "}", "}" ]
Add Exclusion Expiration date. @param array $filters @param \DateTime|null $dateSend @throws \Exception
[ "Add", "Exclusion", "Expiration", "date", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L639-L650
TheDMSGroup/mautic-contact-client
Entity/CacheRepository.php
CacheRepository.reduceExclusivityIndex
public function reduceExclusivityIndex() { $q = $this->getEntityManager()->getConnection()->createQueryBuilder(); $q->update(MAUTIC_TABLE_PREFIX.$this->getTableName()); $q->where( $q->expr()->isNotNull('exclusive_expire_date'), $q->expr()->lte('exclusive_expire_date', 'NOW()') ); $q->set('exclusive_expire_date', 'NULL'); $q->set('exclusive_pattern', 'NULL'); $q->set('exclusive_scope', 'NULL'); $q->execute(); }
php
public function reduceExclusivityIndex() { $q = $this->getEntityManager()->getConnection()->createQueryBuilder(); $q->update(MAUTIC_TABLE_PREFIX.$this->getTableName()); $q->where( $q->expr()->isNotNull('exclusive_expire_date'), $q->expr()->lte('exclusive_expire_date', 'NOW()') ); $q->set('exclusive_expire_date', 'NULL'); $q->set('exclusive_pattern', 'NULL'); $q->set('exclusive_scope', 'NULL'); $q->execute(); }
[ "public", "function", "reduceExclusivityIndex", "(", ")", "{", "$", "q", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getConnection", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "$", "q", "->", "update", "(", "MAUTIC_TABLE_PREFIX", ".", "$", "this", "->", "getTableName", "(", ")", ")", ";", "$", "q", "->", "where", "(", "$", "q", "->", "expr", "(", ")", "->", "isNotNull", "(", "'exclusive_expire_date'", ")", ",", "$", "q", "->", "expr", "(", ")", "->", "lte", "(", "'exclusive_expire_date'", ",", "'NOW()'", ")", ")", ";", "$", "q", "->", "set", "(", "'exclusive_expire_date'", ",", "'NULL'", ")", ";", "$", "q", "->", "set", "(", "'exclusive_pattern'", ",", "'NULL'", ")", ";", "$", "q", "->", "set", "(", "'exclusive_scope'", ",", "'NULL'", ")", ";", "$", "q", "->", "execute", "(", ")", ";", "}" ]
Update exclusivity rows to reduce the index size and thus reduce processing required to check exclusivity.
[ "Update", "exclusivity", "rows", "to", "reduce", "the", "index", "size", "and", "thus", "reduce", "processing", "required", "to", "check", "exclusivity", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/CacheRepository.php#L673-L685
TheDMSGroup/mautic-contact-client
Entity/FileRepository.php
FileRepository.getCountByDate
public function getCountByDate( \DateTime $date = null, $contactClientId, $statuses = [File::STATUS_READY, File::STATUS_SENT, File::STATUS_ERROR], $test = false ) { $start = clone $date; $end = clone $date; $q = $this->getEntityManager()->getConnection()->createQueryBuilder(); $q->select('COUNT(*)') ->from(MAUTIC_TABLE_PREFIX.$this->getTableName()); $start->setTime(0, 0, 0); $end->setTime(0, 0, 0)->modify('+1 day'); $timezone = new \DateTimeZone(date_default_timezone_get()); $start->setTimezone($timezone); $end->setTimezone($timezone); $q->where( $q->expr()->eq('contactclient_id', (int) $contactClientId), $q->expr()->gte('date_added', ':start'), $q->expr()->lt('date_added', ':end'), $q->expr()->eq('test', $test ? 1 : 0) ); $q->setParameter('start', $start->format('Y-m-d H:i:s')); $q->setParameter('end', $end->format('Y-m-d H:i:s')); $q->andWhere('status IN (\''.implode('\',\'', $statuses).'\')'); return (int) $q->execute()->fetchColumn(); }
php
public function getCountByDate( \DateTime $date = null, $contactClientId, $statuses = [File::STATUS_READY, File::STATUS_SENT, File::STATUS_ERROR], $test = false ) { $start = clone $date; $end = clone $date; $q = $this->getEntityManager()->getConnection()->createQueryBuilder(); $q->select('COUNT(*)') ->from(MAUTIC_TABLE_PREFIX.$this->getTableName()); $start->setTime(0, 0, 0); $end->setTime(0, 0, 0)->modify('+1 day'); $timezone = new \DateTimeZone(date_default_timezone_get()); $start->setTimezone($timezone); $end->setTimezone($timezone); $q->where( $q->expr()->eq('contactclient_id', (int) $contactClientId), $q->expr()->gte('date_added', ':start'), $q->expr()->lt('date_added', ':end'), $q->expr()->eq('test', $test ? 1 : 0) ); $q->setParameter('start', $start->format('Y-m-d H:i:s')); $q->setParameter('end', $end->format('Y-m-d H:i:s')); $q->andWhere('status IN (\''.implode('\',\'', $statuses).'\')'); return (int) $q->execute()->fetchColumn(); }
[ "public", "function", "getCountByDate", "(", "\\", "DateTime", "$", "date", "=", "null", ",", "$", "contactClientId", ",", "$", "statuses", "=", "[", "File", "::", "STATUS_READY", ",", "File", "::", "STATUS_SENT", ",", "File", "::", "STATUS_ERROR", "]", ",", "$", "test", "=", "false", ")", "{", "$", "start", "=", "clone", "$", "date", ";", "$", "end", "=", "clone", "$", "date", ";", "$", "q", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getConnection", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "$", "q", "->", "select", "(", "'COUNT(*)'", ")", "->", "from", "(", "MAUTIC_TABLE_PREFIX", ".", "$", "this", "->", "getTableName", "(", ")", ")", ";", "$", "start", "->", "setTime", "(", "0", ",", "0", ",", "0", ")", ";", "$", "end", "->", "setTime", "(", "0", ",", "0", ",", "0", ")", "->", "modify", "(", "'+1 day'", ")", ";", "$", "timezone", "=", "new", "\\", "DateTimeZone", "(", "date_default_timezone_get", "(", ")", ")", ";", "$", "start", "->", "setTimezone", "(", "$", "timezone", ")", ";", "$", "end", "->", "setTimezone", "(", "$", "timezone", ")", ";", "$", "q", "->", "where", "(", "$", "q", "->", "expr", "(", ")", "->", "eq", "(", "'contactclient_id'", ",", "(", "int", ")", "$", "contactClientId", ")", ",", "$", "q", "->", "expr", "(", ")", "->", "gte", "(", "'date_added'", ",", "':start'", ")", ",", "$", "q", "->", "expr", "(", ")", "->", "lt", "(", "'date_added'", ",", "':end'", ")", ",", "$", "q", "->", "expr", "(", ")", "->", "eq", "(", "'test'", ",", "$", "test", "?", "1", ":", "0", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'start'", ",", "$", "start", "->", "format", "(", "'Y-m-d H:i:s'", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'end'", ",", "$", "end", "->", "format", "(", "'Y-m-d H:i:s'", ")", ")", ";", "$", "q", "->", "andWhere", "(", "'status IN (\\''", ".", "implode", "(", "'\\',\\''", ",", "$", "statuses", ")", ".", "'\\')'", ")", ";", "return", "(", "int", ")", "$", "q", "->", "execute", "(", ")", "->", "fetchColumn", "(", ")", ";", "}" ]
Gets the number of files (ready/sent by default) on a given date. @param \DateTime|null $date @param $contactClientId @param array $statuses @param bool $test @return int
[ "Gets", "the", "number", "of", "files", "(", "ready", "/", "sent", "by", "default", ")", "on", "a", "given", "date", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/FileRepository.php#L31-L60
TheDMSGroup/mautic-contact-client
Entity/ContactClientRepository.php
ContactClientRepository.getEntities
public function getEntities(array $args = []) { $alias = $this->getTableAlias(); $q = $this->_em ->createQueryBuilder() ->select($alias) ->from('MauticContactClientBundle:ContactClient', $alias, $alias.'.id'); if (empty($args['iterator_mode'])) { $q->leftJoin($alias.'.category', 'c'); } $args['qb'] = $q; return parent::getEntities($args); }
php
public function getEntities(array $args = []) { $alias = $this->getTableAlias(); $q = $this->_em ->createQueryBuilder() ->select($alias) ->from('MauticContactClientBundle:ContactClient', $alias, $alias.'.id'); if (empty($args['iterator_mode'])) { $q->leftJoin($alias.'.category', 'c'); } $args['qb'] = $q; return parent::getEntities($args); }
[ "public", "function", "getEntities", "(", "array", "$", "args", "=", "[", "]", ")", "{", "$", "alias", "=", "$", "this", "->", "getTableAlias", "(", ")", ";", "$", "q", "=", "$", "this", "->", "_em", "->", "createQueryBuilder", "(", ")", "->", "select", "(", "$", "alias", ")", "->", "from", "(", "'MauticContactClientBundle:ContactClient'", ",", "$", "alias", ",", "$", "alias", ".", "'.id'", ")", ";", "if", "(", "empty", "(", "$", "args", "[", "'iterator_mode'", "]", ")", ")", "{", "$", "q", "->", "leftJoin", "(", "$", "alias", ".", "'.category'", ",", "'c'", ")", ";", "}", "$", "args", "[", "'qb'", "]", "=", "$", "q", ";", "return", "parent", "::", "getEntities", "(", "$", "args", ")", ";", "}" ]
Get a list of entities. @param array $args @return \Doctrine\ORM\Tools\Pagination\Paginator
[ "Get", "a", "list", "of", "entities", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/ContactClientRepository.php#L28-L44
TheDMSGroup/mautic-contact-client
Entity/ContactClientRepository.php
ContactClientRepository.addCatchAllWhereClause
protected function addCatchAllWhereClause($q, $filter) { $alias = $this->getTableAlias(); return $this->addStandardCatchAllWhereClause( $q, $filter, [$alias.'.name', $alias.'.website', $alias.'.description'] ); }
php
protected function addCatchAllWhereClause($q, $filter) { $alias = $this->getTableAlias(); return $this->addStandardCatchAllWhereClause( $q, $filter, [$alias.'.name', $alias.'.website', $alias.'.description'] ); }
[ "protected", "function", "addCatchAllWhereClause", "(", "$", "q", ",", "$", "filter", ")", "{", "$", "alias", "=", "$", "this", "->", "getTableAlias", "(", ")", ";", "return", "$", "this", "->", "addStandardCatchAllWhereClause", "(", "$", "q", ",", "$", "filter", ",", "[", "$", "alias", ".", "'.name'", ",", "$", "alias", ".", "'.website'", ",", "$", "alias", ".", "'.description'", "]", ")", ";", "}" ]
@param \Doctrine\ORM\QueryBuilder|\Doctrine\DBAL\Query\QueryBuilder $q @param $filter @return array
[ "@param", "\\", "Doctrine", "\\", "ORM", "\\", "QueryBuilder|", "\\", "Doctrine", "\\", "DBAL", "\\", "Query", "\\", "QueryBuilder", "$q", "@param", "$filter" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/ContactClientRepository.php#L82-L91
TheDMSGroup/mautic-contact-client
Entity/StatRepository.php
StatRepository.getStats
public function getStats($contactClientId, $type, $fromDate = null, $toDate = null) { $q = $this->createQueryBuilder('s'); $expr = $q->expr()->andX( $q->expr()->eq('IDENTITY(s.contactclient)', (int) $contactClientId), $q->expr()->eq('s.type', ':type') ); if ($fromDate) { $expr->add( $q->expr()->gte('s.dateAdded', ':fromDate') ); $q->setParameter('fromDate', $fromDate); } if ($toDate) { $expr->add( $q->expr()->lte('s.dateAdded', ':toDate') ); $q->setParameter('toDate', $toDate); } $q->where($expr) ->setParameter('type', $type); return $q->getQuery()->getArrayResult(); }
php
public function getStats($contactClientId, $type, $fromDate = null, $toDate = null) { $q = $this->createQueryBuilder('s'); $expr = $q->expr()->andX( $q->expr()->eq('IDENTITY(s.contactclient)', (int) $contactClientId), $q->expr()->eq('s.type', ':type') ); if ($fromDate) { $expr->add( $q->expr()->gte('s.dateAdded', ':fromDate') ); $q->setParameter('fromDate', $fromDate); } if ($toDate) { $expr->add( $q->expr()->lte('s.dateAdded', ':toDate') ); $q->setParameter('toDate', $toDate); } $q->where($expr) ->setParameter('type', $type); return $q->getQuery()->getArrayResult(); }
[ "public", "function", "getStats", "(", "$", "contactClientId", ",", "$", "type", ",", "$", "fromDate", "=", "null", ",", "$", "toDate", "=", "null", ")", "{", "$", "q", "=", "$", "this", "->", "createQueryBuilder", "(", "'s'", ")", ";", "$", "expr", "=", "$", "q", "->", "expr", "(", ")", "->", "andX", "(", "$", "q", "->", "expr", "(", ")", "->", "eq", "(", "'IDENTITY(s.contactclient)'", ",", "(", "int", ")", "$", "contactClientId", ")", ",", "$", "q", "->", "expr", "(", ")", "->", "eq", "(", "'s.type'", ",", "':type'", ")", ")", ";", "if", "(", "$", "fromDate", ")", "{", "$", "expr", "->", "add", "(", "$", "q", "->", "expr", "(", ")", "->", "gte", "(", "'s.dateAdded'", ",", "':fromDate'", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'fromDate'", ",", "$", "fromDate", ")", ";", "}", "if", "(", "$", "toDate", ")", "{", "$", "expr", "->", "add", "(", "$", "q", "->", "expr", "(", ")", "->", "lte", "(", "'s.dateAdded'", ",", "':toDate'", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'toDate'", ",", "$", "toDate", ")", ";", "}", "$", "q", "->", "where", "(", "$", "expr", ")", "->", "setParameter", "(", "'type'", ",", "$", "type", ")", ";", "return", "$", "q", "->", "getQuery", "(", ")", "->", "getArrayResult", "(", ")", ";", "}" ]
Fetch the base stat data from the database. @param $contactClientId @param $type @param null $fromDate @param null $toDate @return array
[ "Fetch", "the", "base", "stat", "data", "from", "the", "database", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/StatRepository.php#L31-L57
TheDMSGroup/mautic-contact-client
Entity/StatRepository.php
StatRepository.getSourcesByClient
public function getSourcesByClient( $contactClientId, \DateTime $dateFrom = null, \DateTime $dateTo = null, $type = null ) { $q = $this->getEntityManager()->getConnection()->createQueryBuilder(); $q->select('distinct(s.utm_source)') ->from(MAUTIC_TABLE_PREFIX.'contactclient_stats', 's') ->where( $q->expr()->eq('s.contactclient_id', (int) $contactClientId) ); if (empty($type)) { $q->andWhere('s.type !=""'); } else { $q->andWhere('s.type = :type') ->setParameter('type', $type); } if ($dateFrom && $dateTo) { $q->andWhere('s.date_added BETWEEN FROM_UNIXTIME(:dateFrom) AND FROM_UNIXTIME(:dateTo)') ->setParameter('dateFrom', $dateFrom->getTimestamp(), \PDO::PARAM_INT) ->setParameter('dateTo', $dateTo->getTimestamp(), \PDO::PARAM_INT); } $utmSources = []; foreach ($q->execute()->fetchAll() as $row) { $utmSources[] = $row['utm_source']; } return $utmSources; }
php
public function getSourcesByClient( $contactClientId, \DateTime $dateFrom = null, \DateTime $dateTo = null, $type = null ) { $q = $this->getEntityManager()->getConnection()->createQueryBuilder(); $q->select('distinct(s.utm_source)') ->from(MAUTIC_TABLE_PREFIX.'contactclient_stats', 's') ->where( $q->expr()->eq('s.contactclient_id', (int) $contactClientId) ); if (empty($type)) { $q->andWhere('s.type !=""'); } else { $q->andWhere('s.type = :type') ->setParameter('type', $type); } if ($dateFrom && $dateTo) { $q->andWhere('s.date_added BETWEEN FROM_UNIXTIME(:dateFrom) AND FROM_UNIXTIME(:dateTo)') ->setParameter('dateFrom', $dateFrom->getTimestamp(), \PDO::PARAM_INT) ->setParameter('dateTo', $dateTo->getTimestamp(), \PDO::PARAM_INT); } $utmSources = []; foreach ($q->execute()->fetchAll() as $row) { $utmSources[] = $row['utm_source']; } return $utmSources; }
[ "public", "function", "getSourcesByClient", "(", "$", "contactClientId", ",", "\\", "DateTime", "$", "dateFrom", "=", "null", ",", "\\", "DateTime", "$", "dateTo", "=", "null", ",", "$", "type", "=", "null", ")", "{", "$", "q", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getConnection", "(", ")", "->", "createQueryBuilder", "(", ")", ";", "$", "q", "->", "select", "(", "'distinct(s.utm_source)'", ")", "->", "from", "(", "MAUTIC_TABLE_PREFIX", ".", "'contactclient_stats'", ",", "'s'", ")", "->", "where", "(", "$", "q", "->", "expr", "(", ")", "->", "eq", "(", "'s.contactclient_id'", ",", "(", "int", ")", "$", "contactClientId", ")", ")", ";", "if", "(", "empty", "(", "$", "type", ")", ")", "{", "$", "q", "->", "andWhere", "(", "'s.type !=\"\"'", ")", ";", "}", "else", "{", "$", "q", "->", "andWhere", "(", "'s.type = :type'", ")", "->", "setParameter", "(", "'type'", ",", "$", "type", ")", ";", "}", "if", "(", "$", "dateFrom", "&&", "$", "dateTo", ")", "{", "$", "q", "->", "andWhere", "(", "'s.date_added BETWEEN FROM_UNIXTIME(:dateFrom) AND FROM_UNIXTIME(:dateTo)'", ")", "->", "setParameter", "(", "'dateFrom'", ",", "$", "dateFrom", "->", "getTimestamp", "(", ")", ",", "\\", "PDO", "::", "PARAM_INT", ")", "->", "setParameter", "(", "'dateTo'", ",", "$", "dateTo", "->", "getTimestamp", "(", ")", ",", "\\", "PDO", "::", "PARAM_INT", ")", ";", "}", "$", "utmSources", "=", "[", "]", ";", "foreach", "(", "$", "q", "->", "execute", "(", ")", "->", "fetchAll", "(", ")", "as", "$", "row", ")", "{", "$", "utmSources", "[", "]", "=", "$", "row", "[", "'utm_source'", "]", ";", "}", "return", "$", "utmSources", ";", "}" ]
@param $contactClientId @param \DateTime|null $dateFrom @param \DateTime|null $dateTo @param string|null $type @return array
[ "@param", "$contactClientId", "@param", "\\", "DateTime|null", "$dateFrom", "@param", "\\", "DateTime|null", "$dateTo", "@param", "string|null", "$type" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/StatRepository.php#L67-L100
TheDMSGroup/mautic-contact-client
Command/FilesCommand.php
FilesCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $options = $input->getOptions(); /** @var ContactClientModel $clientModel */ $clientModel = $container->get('mautic.contactclient.model.contactclient'); /** @var FilePayload $payloadModel */ $payloadModel = $container->get('mautic.contactclient.model.filepayload'); $em = $container->get('doctrine')->getManager(); $translator = $container->get('translator'); if (!$this->checkRunStatus($input, $output, $options['client'].$options['mode'])) { return 0; } if (!empty($options['client']) && !is_numeric($options['client'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client').'</error>'); return 1; } $mode = isset($options['mode']) ? strtolower(trim($options['mode'])) : 'both'; if (!in_array($mode, ['both', 'build', 'send'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.files.error.mode').'</error>'); return 1; } $filter = []; if (!empty($options['client'])) { $filter['where'][] = [ 'column' => 'f.id', 'expr' => 'eq', 'value' => (int) $options['client'], ]; } $filter['where'][] = [ 'column' => 'f.type', 'expr' => 'eq', 'value' => 'file', ]; $filter['where'][] = [ 'col' => 'f.isPublished', 'expr' => 'eq', 'val' => 1, ]; $clients = $clientModel->getEntities( [ 'filter' => $filter, 'iterator_mode' => true, ] ); while (false !== ($client = $clients->next())) { $client = reset($client); // The client must still be published, and must still be set to send files. if ( true === $client->getIsPublished() && 'file' == $client->getType() ) { $clientId = $client->getId(); $clientName = $client->getName(); try { $payloadModel->reset() ->setContactClient($client) ->setTest($options['test']); if (in_array($mode, ['build', 'both'])) { $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.files.building', ['%clientId%' => $clientId, '%clientName%' => $clientName] ).'</info>' ); $payloadModel->run('build'); } if (in_array($mode, ['send', 'both'])) { $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.files.sending', ['%clientId%' => $clientId, '%clientName%' => $clientName] ).'</info>' ); $payloadModel->run('send'); } if (isset($options['verbose']) && $options['verbose']) { $output->writeln('<info>'.$payloadModel->getLogsYAML().'</info>'); } } catch (\Exception $e) { $output->writeln( $translator->trans( 'mautic.contactclient.files.error', ['%clientId%' => $clientId, '%clientName%' => $clientName, '%message%' => $e->getMessage()] ) ); } } $em->detach($client); unset($client); } unset($clients); $this->completeRun(); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $options = $input->getOptions(); /** @var ContactClientModel $clientModel */ $clientModel = $container->get('mautic.contactclient.model.contactclient'); /** @var FilePayload $payloadModel */ $payloadModel = $container->get('mautic.contactclient.model.filepayload'); $em = $container->get('doctrine')->getManager(); $translator = $container->get('translator'); if (!$this->checkRunStatus($input, $output, $options['client'].$options['mode'])) { return 0; } if (!empty($options['client']) && !is_numeric($options['client'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client').'</error>'); return 1; } $mode = isset($options['mode']) ? strtolower(trim($options['mode'])) : 'both'; if (!in_array($mode, ['both', 'build', 'send'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.files.error.mode').'</error>'); return 1; } $filter = []; if (!empty($options['client'])) { $filter['where'][] = [ 'column' => 'f.id', 'expr' => 'eq', 'value' => (int) $options['client'], ]; } $filter['where'][] = [ 'column' => 'f.type', 'expr' => 'eq', 'value' => 'file', ]; $filter['where'][] = [ 'col' => 'f.isPublished', 'expr' => 'eq', 'val' => 1, ]; $clients = $clientModel->getEntities( [ 'filter' => $filter, 'iterator_mode' => true, ] ); while (false !== ($client = $clients->next())) { $client = reset($client); // The client must still be published, and must still be set to send files. if ( true === $client->getIsPublished() && 'file' == $client->getType() ) { $clientId = $client->getId(); $clientName = $client->getName(); try { $payloadModel->reset() ->setContactClient($client) ->setTest($options['test']); if (in_array($mode, ['build', 'both'])) { $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.files.building', ['%clientId%' => $clientId, '%clientName%' => $clientName] ).'</info>' ); $payloadModel->run('build'); } if (in_array($mode, ['send', 'both'])) { $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.files.sending', ['%clientId%' => $clientId, '%clientName%' => $clientName] ).'</info>' ); $payloadModel->run('send'); } if (isset($options['verbose']) && $options['verbose']) { $output->writeln('<info>'.$payloadModel->getLogsYAML().'</info>'); } } catch (\Exception $e) { $output->writeln( $translator->trans( 'mautic.contactclient.files.error', ['%clientId%' => $clientId, '%clientName%' => $clientName, '%message%' => $e->getMessage()] ) ); } } $em->detach($client); unset($client); } unset($clients); $this->completeRun(); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "container", "=", "$", "this", "->", "getContainer", "(", ")", ";", "$", "options", "=", "$", "input", "->", "getOptions", "(", ")", ";", "/** @var ContactClientModel $clientModel */", "$", "clientModel", "=", "$", "container", "->", "get", "(", "'mautic.contactclient.model.contactclient'", ")", ";", "/** @var FilePayload $payloadModel */", "$", "payloadModel", "=", "$", "container", "->", "get", "(", "'mautic.contactclient.model.filepayload'", ")", ";", "$", "em", "=", "$", "container", "->", "get", "(", "'doctrine'", ")", "->", "getManager", "(", ")", ";", "$", "translator", "=", "$", "container", "->", "get", "(", "'translator'", ")", ";", "if", "(", "!", "$", "this", "->", "checkRunStatus", "(", "$", "input", ",", "$", "output", ",", "$", "options", "[", "'client'", "]", ".", "$", "options", "[", "'mode'", "]", ")", ")", "{", "return", "0", ";", "}", "if", "(", "!", "empty", "(", "$", "options", "[", "'client'", "]", ")", "&&", "!", "is_numeric", "(", "$", "options", "[", "'client'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.error.client'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "$", "mode", "=", "isset", "(", "$", "options", "[", "'mode'", "]", ")", "?", "strtolower", "(", "trim", "(", "$", "options", "[", "'mode'", "]", ")", ")", ":", "'both'", ";", "if", "(", "!", "in_array", "(", "$", "mode", ",", "[", "'both'", ",", "'build'", ",", "'send'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.files.error.mode'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "$", "filter", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "options", "[", "'client'", "]", ")", ")", "{", "$", "filter", "[", "'where'", "]", "[", "]", "=", "[", "'column'", "=>", "'f.id'", ",", "'expr'", "=>", "'eq'", ",", "'value'", "=>", "(", "int", ")", "$", "options", "[", "'client'", "]", ",", "]", ";", "}", "$", "filter", "[", "'where'", "]", "[", "]", "=", "[", "'column'", "=>", "'f.type'", ",", "'expr'", "=>", "'eq'", ",", "'value'", "=>", "'file'", ",", "]", ";", "$", "filter", "[", "'where'", "]", "[", "]", "=", "[", "'col'", "=>", "'f.isPublished'", ",", "'expr'", "=>", "'eq'", ",", "'val'", "=>", "1", ",", "]", ";", "$", "clients", "=", "$", "clientModel", "->", "getEntities", "(", "[", "'filter'", "=>", "$", "filter", ",", "'iterator_mode'", "=>", "true", ",", "]", ")", ";", "while", "(", "false", "!==", "(", "$", "client", "=", "$", "clients", "->", "next", "(", ")", ")", ")", "{", "$", "client", "=", "reset", "(", "$", "client", ")", ";", "// The client must still be published, and must still be set to send files.", "if", "(", "true", "===", "$", "client", "->", "getIsPublished", "(", ")", "&&", "'file'", "==", "$", "client", "->", "getType", "(", ")", ")", "{", "$", "clientId", "=", "$", "client", "->", "getId", "(", ")", ";", "$", "clientName", "=", "$", "client", "->", "getName", "(", ")", ";", "try", "{", "$", "payloadModel", "->", "reset", "(", ")", "->", "setContactClient", "(", "$", "client", ")", "->", "setTest", "(", "$", "options", "[", "'test'", "]", ")", ";", "if", "(", "in_array", "(", "$", "mode", ",", "[", "'build'", ",", "'both'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.files.building'", ",", "[", "'%clientId%'", "=>", "$", "clientId", ",", "'%clientName%'", "=>", "$", "clientName", "]", ")", ".", "'</info>'", ")", ";", "$", "payloadModel", "->", "run", "(", "'build'", ")", ";", "}", "if", "(", "in_array", "(", "$", "mode", ",", "[", "'send'", ",", "'both'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.files.sending'", ",", "[", "'%clientId%'", "=>", "$", "clientId", ",", "'%clientName%'", "=>", "$", "clientName", "]", ")", ".", "'</info>'", ")", ";", "$", "payloadModel", "->", "run", "(", "'send'", ")", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'verbose'", "]", ")", "&&", "$", "options", "[", "'verbose'", "]", ")", "{", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "payloadModel", "->", "getLogsYAML", "(", ")", ".", "'</info>'", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "output", "->", "writeln", "(", "$", "translator", "->", "trans", "(", "'mautic.contactclient.files.error'", ",", "[", "'%clientId%'", "=>", "$", "clientId", ",", "'%clientName%'", "=>", "$", "clientName", ",", "'%message%'", "=>", "$", "e", "->", "getMessage", "(", ")", "]", ")", ")", ";", "}", "}", "$", "em", "->", "detach", "(", "$", "client", ")", ";", "unset", "(", "$", "client", ")", ";", "}", "unset", "(", "$", "clients", ")", ";", "$", "this", "->", "completeRun", "(", ")", ";", "return", "0", ";", "}" ]
Send appropriate client files.
[ "Send", "appropriate", "client", "files", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Command/FilesCommand.php#L63-L171
TheDMSGroup/mautic-contact-client
Controller/ContactClientAccessTrait.php
ContactClientAccessTrait.checkContactClientAccess
protected function checkContactClientAccess($contactClientId, $action, $isPlugin = false, $integration = '') { if (!$contactClientId instanceof ContactClient) { //make sure the user has view access to this contactClient $contactClientModel = $this->getModel('contactClient'); $contactClient = $contactClientModel->getEntity((int) $contactClientId); } else { $contactClient = $contactClientId; $contactClientId = $contactClient->getId(); } if (null === $contactClient || !$contactClient->getId()) { if (method_exists($this, 'postActionRedirect')) { //set the return URL $page = $this->get('session')->get( $isPlugin ? 'mautic.'.$integration.'.page' : 'mautic.contactClient.page', 1 ); $returnUrl = $this->generateUrl( $isPlugin ? 'mautic_plugin_timeline_index' : 'mautic_contact_index', ['page' => $page] ); return $this->postActionRedirect( [ 'returnUrl' => $returnUrl, 'viewParameters' => ['page' => $page], 'contentTemplate' => $isPlugin ? 'MauticContactClientBundle:ContactClient:pluginIndex' : 'MauticContactClientBundle:ContactClient:index', 'passthroughVars' => [ 'activeLink' => $isPlugin ? '#mautic_plugin_timeline_index' : '#mautic_contact_index', 'mauticContent' => 'contactClientTimeline', ], 'flashes' => [ [ 'type' => 'error', 'msg' => 'mautic.contactClient.contactClient.error.notfound', 'msgVars' => ['%id%' => $contactClientId], ], ], ] ); } else { return $this->notFound('mautic.contact.error.notfound'); } } elseif (!$this->get('mautic.security')->hasEntityAccess( 'contactclient:items:'.$action.'own', 'contactclient:items:'.$action.'other', $contactClient->getPermissionUser() ) ) { return $this->accessDenied(); } else { return $contactClient; } }
php
protected function checkContactClientAccess($contactClientId, $action, $isPlugin = false, $integration = '') { if (!$contactClientId instanceof ContactClient) { //make sure the user has view access to this contactClient $contactClientModel = $this->getModel('contactClient'); $contactClient = $contactClientModel->getEntity((int) $contactClientId); } else { $contactClient = $contactClientId; $contactClientId = $contactClient->getId(); } if (null === $contactClient || !$contactClient->getId()) { if (method_exists($this, 'postActionRedirect')) { //set the return URL $page = $this->get('session')->get( $isPlugin ? 'mautic.'.$integration.'.page' : 'mautic.contactClient.page', 1 ); $returnUrl = $this->generateUrl( $isPlugin ? 'mautic_plugin_timeline_index' : 'mautic_contact_index', ['page' => $page] ); return $this->postActionRedirect( [ 'returnUrl' => $returnUrl, 'viewParameters' => ['page' => $page], 'contentTemplate' => $isPlugin ? 'MauticContactClientBundle:ContactClient:pluginIndex' : 'MauticContactClientBundle:ContactClient:index', 'passthroughVars' => [ 'activeLink' => $isPlugin ? '#mautic_plugin_timeline_index' : '#mautic_contact_index', 'mauticContent' => 'contactClientTimeline', ], 'flashes' => [ [ 'type' => 'error', 'msg' => 'mautic.contactClient.contactClient.error.notfound', 'msgVars' => ['%id%' => $contactClientId], ], ], ] ); } else { return $this->notFound('mautic.contact.error.notfound'); } } elseif (!$this->get('mautic.security')->hasEntityAccess( 'contactclient:items:'.$action.'own', 'contactclient:items:'.$action.'other', $contactClient->getPermissionUser() ) ) { return $this->accessDenied(); } else { return $contactClient; } }
[ "protected", "function", "checkContactClientAccess", "(", "$", "contactClientId", ",", "$", "action", ",", "$", "isPlugin", "=", "false", ",", "$", "integration", "=", "''", ")", "{", "if", "(", "!", "$", "contactClientId", "instanceof", "ContactClient", ")", "{", "//make sure the user has view access to this contactClient", "$", "contactClientModel", "=", "$", "this", "->", "getModel", "(", "'contactClient'", ")", ";", "$", "contactClient", "=", "$", "contactClientModel", "->", "getEntity", "(", "(", "int", ")", "$", "contactClientId", ")", ";", "}", "else", "{", "$", "contactClient", "=", "$", "contactClientId", ";", "$", "contactClientId", "=", "$", "contactClient", "->", "getId", "(", ")", ";", "}", "if", "(", "null", "===", "$", "contactClient", "||", "!", "$", "contactClient", "->", "getId", "(", ")", ")", "{", "if", "(", "method_exists", "(", "$", "this", ",", "'postActionRedirect'", ")", ")", "{", "//set the return URL", "$", "page", "=", "$", "this", "->", "get", "(", "'session'", ")", "->", "get", "(", "$", "isPlugin", "?", "'mautic.'", ".", "$", "integration", ".", "'.page'", ":", "'mautic.contactClient.page'", ",", "1", ")", ";", "$", "returnUrl", "=", "$", "this", "->", "generateUrl", "(", "$", "isPlugin", "?", "'mautic_plugin_timeline_index'", ":", "'mautic_contact_index'", ",", "[", "'page'", "=>", "$", "page", "]", ")", ";", "return", "$", "this", "->", "postActionRedirect", "(", "[", "'returnUrl'", "=>", "$", "returnUrl", ",", "'viewParameters'", "=>", "[", "'page'", "=>", "$", "page", "]", ",", "'contentTemplate'", "=>", "$", "isPlugin", "?", "'MauticContactClientBundle:ContactClient:pluginIndex'", ":", "'MauticContactClientBundle:ContactClient:index'", ",", "'passthroughVars'", "=>", "[", "'activeLink'", "=>", "$", "isPlugin", "?", "'#mautic_plugin_timeline_index'", ":", "'#mautic_contact_index'", ",", "'mauticContent'", "=>", "'contactClientTimeline'", ",", "]", ",", "'flashes'", "=>", "[", "[", "'type'", "=>", "'error'", ",", "'msg'", "=>", "'mautic.contactClient.contactClient.error.notfound'", ",", "'msgVars'", "=>", "[", "'%id%'", "=>", "$", "contactClientId", "]", ",", "]", ",", "]", ",", "]", ")", ";", "}", "else", "{", "return", "$", "this", "->", "notFound", "(", "'mautic.contact.error.notfound'", ")", ";", "}", "}", "elseif", "(", "!", "$", "this", "->", "get", "(", "'mautic.security'", ")", "->", "hasEntityAccess", "(", "'contactclient:items:'", ".", "$", "action", ".", "'own'", ",", "'contactclient:items:'", ".", "$", "action", ".", "'other'", ",", "$", "contactClient", "->", "getPermissionUser", "(", ")", ")", ")", "{", "return", "$", "this", "->", "accessDenied", "(", ")", ";", "}", "else", "{", "return", "$", "contactClient", ";", "}", "}" ]
Determines if the user has access to the contactClient. @param $contactClientId @param $action @param bool $isPlugin @param string $integration @return ContactClient
[ "Determines", "if", "the", "user", "has", "access", "to", "the", "contactClient", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/ContactClientAccessTrait.php#L33-L87
TheDMSGroup/mautic-contact-client
Controller/ContactClientAccessTrait.php
ContactClientAccessTrait.checkContactClientFileAccess
protected function checkContactClientFileAccess($fileId, $action, $isPlugin = false, $integration = '') { if (!$fileId instanceof File) { /** @var FileRepository $fileRepository */ $fileRepository = $this->getDoctrine()->getEntityManager()->getRepository( 'MauticContactClientBundle:File' ); /** @var File $file */ $file = $fileRepository->getEntity((int) $fileId); } else { /** @var File $file */ $file = $fileId; $fileId = $file->getId(); } if (null === $file || !$file->getId()) { if (method_exists($this, 'postActionRedirect')) { //set the return URL $page = $this->get('session')->get( $isPlugin ? 'mautic.'.$integration.'.page' : 'mautic.contactClient.page', 1 ); $returnUrl = $this->generateUrl( $isPlugin ? 'mautic_plugin_timeline_index' : 'mautic_contact_index', ['page' => $page] ); return $this->postActionRedirect( [ 'returnUrl' => $returnUrl, 'viewParameters' => ['page' => $page], 'contentTemplate' => $isPlugin ? 'MauticContactClientBundle:ContactClient:pluginIndex' : 'MauticContactClientBundle:ContactClient:index', 'passthroughVars' => [ 'activeLink' => $isPlugin ? '#mautic_plugin_timeline_index' : '#mautic_contact_index', 'mauticContent' => 'contactClientTimeline', ], 'flashes' => [ [ 'type' => 'error', 'msg' => 'mautic.contactClient.contactClient.error.notfound', 'msgVars' => ['%id%' => $fileId], ], ], ] ); } else { return $this->notFound('mautic.contact.error.notfound'); } } elseif (!$this->get('mautic.security')->hasEntityAccess( 'contactclient:files:'.$action.'own', 'contactclient:files:'.$action.'other', 0 // @todo - Add ownership access when ownership exists by way of a File model extending FormModel. )) { return $this->accessDenied(); } else { return $file; } }
php
protected function checkContactClientFileAccess($fileId, $action, $isPlugin = false, $integration = '') { if (!$fileId instanceof File) { /** @var FileRepository $fileRepository */ $fileRepository = $this->getDoctrine()->getEntityManager()->getRepository( 'MauticContactClientBundle:File' ); /** @var File $file */ $file = $fileRepository->getEntity((int) $fileId); } else { /** @var File $file */ $file = $fileId; $fileId = $file->getId(); } if (null === $file || !$file->getId()) { if (method_exists($this, 'postActionRedirect')) { //set the return URL $page = $this->get('session')->get( $isPlugin ? 'mautic.'.$integration.'.page' : 'mautic.contactClient.page', 1 ); $returnUrl = $this->generateUrl( $isPlugin ? 'mautic_plugin_timeline_index' : 'mautic_contact_index', ['page' => $page] ); return $this->postActionRedirect( [ 'returnUrl' => $returnUrl, 'viewParameters' => ['page' => $page], 'contentTemplate' => $isPlugin ? 'MauticContactClientBundle:ContactClient:pluginIndex' : 'MauticContactClientBundle:ContactClient:index', 'passthroughVars' => [ 'activeLink' => $isPlugin ? '#mautic_plugin_timeline_index' : '#mautic_contact_index', 'mauticContent' => 'contactClientTimeline', ], 'flashes' => [ [ 'type' => 'error', 'msg' => 'mautic.contactClient.contactClient.error.notfound', 'msgVars' => ['%id%' => $fileId], ], ], ] ); } else { return $this->notFound('mautic.contact.error.notfound'); } } elseif (!$this->get('mautic.security')->hasEntityAccess( 'contactclient:files:'.$action.'own', 'contactclient:files:'.$action.'other', 0 // @todo - Add ownership access when ownership exists by way of a File model extending FormModel. )) { return $this->accessDenied(); } else { return $file; } }
[ "protected", "function", "checkContactClientFileAccess", "(", "$", "fileId", ",", "$", "action", ",", "$", "isPlugin", "=", "false", ",", "$", "integration", "=", "''", ")", "{", "if", "(", "!", "$", "fileId", "instanceof", "File", ")", "{", "/** @var FileRepository $fileRepository */", "$", "fileRepository", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getEntityManager", "(", ")", "->", "getRepository", "(", "'MauticContactClientBundle:File'", ")", ";", "/** @var File $file */", "$", "file", "=", "$", "fileRepository", "->", "getEntity", "(", "(", "int", ")", "$", "fileId", ")", ";", "}", "else", "{", "/** @var File $file */", "$", "file", "=", "$", "fileId", ";", "$", "fileId", "=", "$", "file", "->", "getId", "(", ")", ";", "}", "if", "(", "null", "===", "$", "file", "||", "!", "$", "file", "->", "getId", "(", ")", ")", "{", "if", "(", "method_exists", "(", "$", "this", ",", "'postActionRedirect'", ")", ")", "{", "//set the return URL", "$", "page", "=", "$", "this", "->", "get", "(", "'session'", ")", "->", "get", "(", "$", "isPlugin", "?", "'mautic.'", ".", "$", "integration", ".", "'.page'", ":", "'mautic.contactClient.page'", ",", "1", ")", ";", "$", "returnUrl", "=", "$", "this", "->", "generateUrl", "(", "$", "isPlugin", "?", "'mautic_plugin_timeline_index'", ":", "'mautic_contact_index'", ",", "[", "'page'", "=>", "$", "page", "]", ")", ";", "return", "$", "this", "->", "postActionRedirect", "(", "[", "'returnUrl'", "=>", "$", "returnUrl", ",", "'viewParameters'", "=>", "[", "'page'", "=>", "$", "page", "]", ",", "'contentTemplate'", "=>", "$", "isPlugin", "?", "'MauticContactClientBundle:ContactClient:pluginIndex'", ":", "'MauticContactClientBundle:ContactClient:index'", ",", "'passthroughVars'", "=>", "[", "'activeLink'", "=>", "$", "isPlugin", "?", "'#mautic_plugin_timeline_index'", ":", "'#mautic_contact_index'", ",", "'mauticContent'", "=>", "'contactClientTimeline'", ",", "]", ",", "'flashes'", "=>", "[", "[", "'type'", "=>", "'error'", ",", "'msg'", "=>", "'mautic.contactClient.contactClient.error.notfound'", ",", "'msgVars'", "=>", "[", "'%id%'", "=>", "$", "fileId", "]", ",", "]", ",", "]", ",", "]", ")", ";", "}", "else", "{", "return", "$", "this", "->", "notFound", "(", "'mautic.contact.error.notfound'", ")", ";", "}", "}", "elseif", "(", "!", "$", "this", "->", "get", "(", "'mautic.security'", ")", "->", "hasEntityAccess", "(", "'contactclient:files:'", ".", "$", "action", ".", "'own'", ",", "'contactclient:files:'", ".", "$", "action", ".", "'other'", ",", "0", "// @todo - Add ownership access when ownership exists by way of a File model extending FormModel.", ")", ")", "{", "return", "$", "this", "->", "accessDenied", "(", ")", ";", "}", "else", "{", "return", "$", "file", ";", "}", "}" ]
Determines if the user has access to a File. @param $fileId @param $action @param bool $isPlugin @param string $integration @return File
[ "Determines", "if", "the", "user", "has", "access", "to", "a", "File", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/ContactClientAccessTrait.php#L99-L156
TheDMSGroup/mautic-contact-client
Controller/ContactClientAccessTrait.php
ContactClientAccessTrait.checkAllAccess
protected function checkAllAccess($action, $limit) { /** @var ContactClientModel $model */ $model = $this->getModel('contactClient'); //make sure the user has view access to contactClients $repo = $model->getRepository(); // order by lastactive, filter $contactClients = $repo->getEntities( [ 'filter' => [], 'oderBy' => 'r.last_active', 'orderByDir' => 'DESC', 'limit' => $limit, 'hydration_mode' => 'HYDRATE_ARRAY', ] ); if (null === $contactClients) { return $this->accessDenied(); } foreach ($contactClients as $contactClient) { if (!$this->get('mautic.security')->hasEntityAccess( 'contactclient:items:'.$action.'own', 'contactclient:items:'.$action.'other', $contactClient['createdBy'] ) ) { unset($contactClient); } } return $contactClients; }
php
protected function checkAllAccess($action, $limit) { /** @var ContactClientModel $model */ $model = $this->getModel('contactClient'); //make sure the user has view access to contactClients $repo = $model->getRepository(); // order by lastactive, filter $contactClients = $repo->getEntities( [ 'filter' => [], 'oderBy' => 'r.last_active', 'orderByDir' => 'DESC', 'limit' => $limit, 'hydration_mode' => 'HYDRATE_ARRAY', ] ); if (null === $contactClients) { return $this->accessDenied(); } foreach ($contactClients as $contactClient) { if (!$this->get('mautic.security')->hasEntityAccess( 'contactclient:items:'.$action.'own', 'contactclient:items:'.$action.'other', $contactClient['createdBy'] ) ) { unset($contactClient); } } return $contactClients; }
[ "protected", "function", "checkAllAccess", "(", "$", "action", ",", "$", "limit", ")", "{", "/** @var ContactClientModel $model */", "$", "model", "=", "$", "this", "->", "getModel", "(", "'contactClient'", ")", ";", "//make sure the user has view access to contactClients", "$", "repo", "=", "$", "model", "->", "getRepository", "(", ")", ";", "// order by lastactive, filter", "$", "contactClients", "=", "$", "repo", "->", "getEntities", "(", "[", "'filter'", "=>", "[", "]", ",", "'oderBy'", "=>", "'r.last_active'", ",", "'orderByDir'", "=>", "'DESC'", ",", "'limit'", "=>", "$", "limit", ",", "'hydration_mode'", "=>", "'HYDRATE_ARRAY'", ",", "]", ")", ";", "if", "(", "null", "===", "$", "contactClients", ")", "{", "return", "$", "this", "->", "accessDenied", "(", ")", ";", "}", "foreach", "(", "$", "contactClients", "as", "$", "contactClient", ")", "{", "if", "(", "!", "$", "this", "->", "get", "(", "'mautic.security'", ")", "->", "hasEntityAccess", "(", "'contactclient:items:'", ".", "$", "action", ".", "'own'", ",", "'contactclient:items:'", ".", "$", "action", ".", "'other'", ",", "$", "contactClient", "[", "'createdBy'", "]", ")", ")", "{", "unset", "(", "$", "contactClient", ")", ";", "}", "}", "return", "$", "contactClients", ";", "}" ]
Returns contactClients the user has access to. @param $action @return array|\Symfony\Component\HttpFoundation\RedirectResponse
[ "Returns", "contactClients", "the", "user", "has", "access", "to", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/ContactClientAccessTrait.php#L165-L200
TheDMSGroup/mautic-contact-client
Controller/ContactClientController.php
ContactClientController.indexAction
public function indexAction($page = 1) { // When the user inserts a numeric value, assume they want to find the entity by ID. $session = $this->get('session'); $search = $this->request->get('search', $session->get('mautic.'.$this->getSessionBase().'.filter', '')); if (isset($search) && is_numeric(trim($search))) { $search = '%'.trim($search).'% OR ids:'.trim($search); $query = $this->request->query->all(); $query['search'] = $search; $this->request = $this->request->duplicate($query); $session->set('mautic.'.$this->getSessionBase().'.filter', $search); } elseif (false === strpos($search, '%') && strlen($search) > 0 && false === strpos($search, 'OR ids:')) { $search = '%'.trim($search, ' \t\n\r\0\x0B"%').'%'; $search = strpos($search, ' ') ? '"'.$search.'"' : $search; $query = $this->request->query->all(); $query['search'] = $search; $this->request = $this->request->duplicate($query); $session->set('mautic.'.$this->getSessionBase().'.filter', $search); } return parent::indexStandard($page); }
php
public function indexAction($page = 1) { // When the user inserts a numeric value, assume they want to find the entity by ID. $session = $this->get('session'); $search = $this->request->get('search', $session->get('mautic.'.$this->getSessionBase().'.filter', '')); if (isset($search) && is_numeric(trim($search))) { $search = '%'.trim($search).'% OR ids:'.trim($search); $query = $this->request->query->all(); $query['search'] = $search; $this->request = $this->request->duplicate($query); $session->set('mautic.'.$this->getSessionBase().'.filter', $search); } elseif (false === strpos($search, '%') && strlen($search) > 0 && false === strpos($search, 'OR ids:')) { $search = '%'.trim($search, ' \t\n\r\0\x0B"%').'%'; $search = strpos($search, ' ') ? '"'.$search.'"' : $search; $query = $this->request->query->all(); $query['search'] = $search; $this->request = $this->request->duplicate($query); $session->set('mautic.'.$this->getSessionBase().'.filter', $search); } return parent::indexStandard($page); }
[ "public", "function", "indexAction", "(", "$", "page", "=", "1", ")", "{", "// When the user inserts a numeric value, assume they want to find the entity by ID.", "$", "session", "=", "$", "this", "->", "get", "(", "'session'", ")", ";", "$", "search", "=", "$", "this", "->", "request", "->", "get", "(", "'search'", ",", "$", "session", "->", "get", "(", "'mautic.'", ".", "$", "this", "->", "getSessionBase", "(", ")", ".", "'.filter'", ",", "''", ")", ")", ";", "if", "(", "isset", "(", "$", "search", ")", "&&", "is_numeric", "(", "trim", "(", "$", "search", ")", ")", ")", "{", "$", "search", "=", "'%'", ".", "trim", "(", "$", "search", ")", ".", "'% OR ids:'", ".", "trim", "(", "$", "search", ")", ";", "$", "query", "=", "$", "this", "->", "request", "->", "query", "->", "all", "(", ")", ";", "$", "query", "[", "'search'", "]", "=", "$", "search", ";", "$", "this", "->", "request", "=", "$", "this", "->", "request", "->", "duplicate", "(", "$", "query", ")", ";", "$", "session", "->", "set", "(", "'mautic.'", ".", "$", "this", "->", "getSessionBase", "(", ")", ".", "'.filter'", ",", "$", "search", ")", ";", "}", "elseif", "(", "false", "===", "strpos", "(", "$", "search", ",", "'%'", ")", "&&", "strlen", "(", "$", "search", ")", ">", "0", "&&", "false", "===", "strpos", "(", "$", "search", ",", "'OR ids:'", ")", ")", "{", "$", "search", "=", "'%'", ".", "trim", "(", "$", "search", ",", "' \\t\\n\\r\\0\\x0B\"%'", ")", ".", "'%'", ";", "$", "search", "=", "strpos", "(", "$", "search", ",", "' '", ")", "?", "'\"'", ".", "$", "search", ".", "'\"'", ":", "$", "search", ";", "$", "query", "=", "$", "this", "->", "request", "->", "query", "->", "all", "(", ")", ";", "$", "query", "[", "'search'", "]", "=", "$", "search", ";", "$", "this", "->", "request", "=", "$", "this", "->", "request", "->", "duplicate", "(", "$", "query", ")", ";", "$", "session", "->", "set", "(", "'mautic.'", ".", "$", "this", "->", "getSessionBase", "(", ")", ".", "'.filter'", ",", "$", "search", ")", ";", "}", "return", "parent", "::", "indexStandard", "(", "$", "page", ")", ";", "}" ]
@param int $page @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
[ "@param", "int", "$page" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/ContactClientController.php#L43-L64
TheDMSGroup/mautic-contact-client
Controller/ContactClientController.php
ContactClientController.customizeViewArguments
public function customizeViewArguments($args, $view) { if ('view' == $view) { $session = $this->get('session'); /** @var \MauticPlugin\MauticContactClientBundle\Entity\ContactClient $item */ $item = $args['viewParameters']['item']; // Setup page forms in session if ('POST' == $this->request->getMethod() && $this->request->request->has('contactclient_chart')) { $chartFilterValues = $this->request->request->get('contactclient_chart'); } else { $chartFilterValues = $session->get('mautic.contactclient.'.$item->getId().'.chartfilter') ? $session->get('mautic.contactclient.'.$item->getId().'.chartfilter') : [ 'date_from' => $this->get('mautic.helper.core_parameters')->getParameter( 'default_daterange_filter', 'midnight -1 month' ), 'date_to' => 'midnight tomorrow -1 second', 'type' => '', ]; } if ($this->request->query->has('campaign')) { $chartFilterValues['campaign'] = $this->request->query->get('campaign'); } if (!isset($chartFilterValues['campaign']) || empty($chartFilterValues['campaign'])) { $chartFilterValues['campaign'] = null; } $session->set('mautic.contactclient.'.$item->getId().'.chartfilter', $chartFilterValues); //Setup for the chart and stats datatable /** @var \MauticPlugin\MauticContactClientBundle\Model\ContactClientModel $model */ $model = $this->getModel('contactclient'); $unit = $model->getTimeUnitFromDateRange( new \DateTime($chartFilterValues['date_from']), new \DateTime($chartFilterValues['date_to']) ); $auditLog = $this->getAuditlogs($item); $files = $this->getFiles($item); if (in_array($chartFilterValues['type'], [''])) { $stats = $model->getStats( $item, $unit, new \DateTime($chartFilterValues['date_from']), new \DateTime($chartFilterValues['date_to']), $chartFilterValues['campaign'] ); } else { $stats = $model->getStatsBySource( $item, $unit, $chartFilterValues['type'], new \DateTime($chartFilterValues['date_from']), new \DateTime($chartFilterValues['date_to']), $chartFilterValues['campaign'] ); } $chartFilterForm = $this->get('form.factory')->create( 'contactclient_chart', $chartFilterValues, [ 'action' => $this->generateUrl( 'mautic_contactclient_action', [ 'objectAction' => 'view', 'objectId' => $item->getId(), ] ), ] ); $args['viewParameters']['auditlog'] = $auditLog; $args['viewParameters']['files'] = $files; $args['viewParameters']['stats'] = $stats; $args['viewParameters']['chartFilterForm'] = $chartFilterForm->createView(); //unset($chartFilterValues['campaign']); $session->set('mautic.contactclient.'.$item->getId().'.chartfilter', $chartFilterValues); } return $args; }
php
public function customizeViewArguments($args, $view) { if ('view' == $view) { $session = $this->get('session'); /** @var \MauticPlugin\MauticContactClientBundle\Entity\ContactClient $item */ $item = $args['viewParameters']['item']; // Setup page forms in session if ('POST' == $this->request->getMethod() && $this->request->request->has('contactclient_chart')) { $chartFilterValues = $this->request->request->get('contactclient_chart'); } else { $chartFilterValues = $session->get('mautic.contactclient.'.$item->getId().'.chartfilter') ? $session->get('mautic.contactclient.'.$item->getId().'.chartfilter') : [ 'date_from' => $this->get('mautic.helper.core_parameters')->getParameter( 'default_daterange_filter', 'midnight -1 month' ), 'date_to' => 'midnight tomorrow -1 second', 'type' => '', ]; } if ($this->request->query->has('campaign')) { $chartFilterValues['campaign'] = $this->request->query->get('campaign'); } if (!isset($chartFilterValues['campaign']) || empty($chartFilterValues['campaign'])) { $chartFilterValues['campaign'] = null; } $session->set('mautic.contactclient.'.$item->getId().'.chartfilter', $chartFilterValues); //Setup for the chart and stats datatable /** @var \MauticPlugin\MauticContactClientBundle\Model\ContactClientModel $model */ $model = $this->getModel('contactclient'); $unit = $model->getTimeUnitFromDateRange( new \DateTime($chartFilterValues['date_from']), new \DateTime($chartFilterValues['date_to']) ); $auditLog = $this->getAuditlogs($item); $files = $this->getFiles($item); if (in_array($chartFilterValues['type'], [''])) { $stats = $model->getStats( $item, $unit, new \DateTime($chartFilterValues['date_from']), new \DateTime($chartFilterValues['date_to']), $chartFilterValues['campaign'] ); } else { $stats = $model->getStatsBySource( $item, $unit, $chartFilterValues['type'], new \DateTime($chartFilterValues['date_from']), new \DateTime($chartFilterValues['date_to']), $chartFilterValues['campaign'] ); } $chartFilterForm = $this->get('form.factory')->create( 'contactclient_chart', $chartFilterValues, [ 'action' => $this->generateUrl( 'mautic_contactclient_action', [ 'objectAction' => 'view', 'objectId' => $item->getId(), ] ), ] ); $args['viewParameters']['auditlog'] = $auditLog; $args['viewParameters']['files'] = $files; $args['viewParameters']['stats'] = $stats; $args['viewParameters']['chartFilterForm'] = $chartFilterForm->createView(); //unset($chartFilterValues['campaign']); $session->set('mautic.contactclient.'.$item->getId().'.chartfilter', $chartFilterValues); } return $args; }
[ "public", "function", "customizeViewArguments", "(", "$", "args", ",", "$", "view", ")", "{", "if", "(", "'view'", "==", "$", "view", ")", "{", "$", "session", "=", "$", "this", "->", "get", "(", "'session'", ")", ";", "/** @var \\MauticPlugin\\MauticContactClientBundle\\Entity\\ContactClient $item */", "$", "item", "=", "$", "args", "[", "'viewParameters'", "]", "[", "'item'", "]", ";", "// Setup page forms in session", "if", "(", "'POST'", "==", "$", "this", "->", "request", "->", "getMethod", "(", ")", "&&", "$", "this", "->", "request", "->", "request", "->", "has", "(", "'contactclient_chart'", ")", ")", "{", "$", "chartFilterValues", "=", "$", "this", "->", "request", "->", "request", "->", "get", "(", "'contactclient_chart'", ")", ";", "}", "else", "{", "$", "chartFilterValues", "=", "$", "session", "->", "get", "(", "'mautic.contactclient.'", ".", "$", "item", "->", "getId", "(", ")", ".", "'.chartfilter'", ")", "?", "$", "session", "->", "get", "(", "'mautic.contactclient.'", ".", "$", "item", "->", "getId", "(", ")", ".", "'.chartfilter'", ")", ":", "[", "'date_from'", "=>", "$", "this", "->", "get", "(", "'mautic.helper.core_parameters'", ")", "->", "getParameter", "(", "'default_daterange_filter'", ",", "'midnight -1 month'", ")", ",", "'date_to'", "=>", "'midnight tomorrow -1 second'", ",", "'type'", "=>", "''", ",", "]", ";", "}", "if", "(", "$", "this", "->", "request", "->", "query", "->", "has", "(", "'campaign'", ")", ")", "{", "$", "chartFilterValues", "[", "'campaign'", "]", "=", "$", "this", "->", "request", "->", "query", "->", "get", "(", "'campaign'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "chartFilterValues", "[", "'campaign'", "]", ")", "||", "empty", "(", "$", "chartFilterValues", "[", "'campaign'", "]", ")", ")", "{", "$", "chartFilterValues", "[", "'campaign'", "]", "=", "null", ";", "}", "$", "session", "->", "set", "(", "'mautic.contactclient.'", ".", "$", "item", "->", "getId", "(", ")", ".", "'.chartfilter'", ",", "$", "chartFilterValues", ")", ";", "//Setup for the chart and stats datatable", "/** @var \\MauticPlugin\\MauticContactClientBundle\\Model\\ContactClientModel $model */", "$", "model", "=", "$", "this", "->", "getModel", "(", "'contactclient'", ")", ";", "$", "unit", "=", "$", "model", "->", "getTimeUnitFromDateRange", "(", "new", "\\", "DateTime", "(", "$", "chartFilterValues", "[", "'date_from'", "]", ")", ",", "new", "\\", "DateTime", "(", "$", "chartFilterValues", "[", "'date_to'", "]", ")", ")", ";", "$", "auditLog", "=", "$", "this", "->", "getAuditlogs", "(", "$", "item", ")", ";", "$", "files", "=", "$", "this", "->", "getFiles", "(", "$", "item", ")", ";", "if", "(", "in_array", "(", "$", "chartFilterValues", "[", "'type'", "]", ",", "[", "''", "]", ")", ")", "{", "$", "stats", "=", "$", "model", "->", "getStats", "(", "$", "item", ",", "$", "unit", ",", "new", "\\", "DateTime", "(", "$", "chartFilterValues", "[", "'date_from'", "]", ")", ",", "new", "\\", "DateTime", "(", "$", "chartFilterValues", "[", "'date_to'", "]", ")", ",", "$", "chartFilterValues", "[", "'campaign'", "]", ")", ";", "}", "else", "{", "$", "stats", "=", "$", "model", "->", "getStatsBySource", "(", "$", "item", ",", "$", "unit", ",", "$", "chartFilterValues", "[", "'type'", "]", ",", "new", "\\", "DateTime", "(", "$", "chartFilterValues", "[", "'date_from'", "]", ")", ",", "new", "\\", "DateTime", "(", "$", "chartFilterValues", "[", "'date_to'", "]", ")", ",", "$", "chartFilterValues", "[", "'campaign'", "]", ")", ";", "}", "$", "chartFilterForm", "=", "$", "this", "->", "get", "(", "'form.factory'", ")", "->", "create", "(", "'contactclient_chart'", ",", "$", "chartFilterValues", ",", "[", "'action'", "=>", "$", "this", "->", "generateUrl", "(", "'mautic_contactclient_action'", ",", "[", "'objectAction'", "=>", "'view'", ",", "'objectId'", "=>", "$", "item", "->", "getId", "(", ")", ",", "]", ")", ",", "]", ")", ";", "$", "args", "[", "'viewParameters'", "]", "[", "'auditlog'", "]", "=", "$", "auditLog", ";", "$", "args", "[", "'viewParameters'", "]", "[", "'files'", "]", "=", "$", "files", ";", "$", "args", "[", "'viewParameters'", "]", "[", "'stats'", "]", "=", "$", "stats", ";", "$", "args", "[", "'viewParameters'", "]", "[", "'chartFilterForm'", "]", "=", "$", "chartFilterForm", "->", "createView", "(", ")", ";", "//unset($chartFilterValues['campaign']);", "$", "session", "->", "set", "(", "'mautic.contactclient.'", ".", "$", "item", "->", "getId", "(", ")", ".", "'.chartfilter'", ",", "$", "chartFilterValues", ")", ";", "}", "return", "$", "args", ";", "}" ]
@param $args @param $view @return array
[ "@param", "$args", "@param", "$view" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/ContactClientController.php#L145-L233
TheDMSGroup/mautic-contact-client
Controller/ContactClientController.php
ContactClientController.getUpdateSelectParams
protected function getUpdateSelectParams( $updateSelect, $entity, $nameMethod = 'getName', $groupMethod = 'getLanguage' ) { $options = [ 'updateSelect' => $updateSelect, 'id' => $entity->getId(), 'name' => $entity->$nameMethod(), ]; return $options; }
php
protected function getUpdateSelectParams( $updateSelect, $entity, $nameMethod = 'getName', $groupMethod = 'getLanguage' ) { $options = [ 'updateSelect' => $updateSelect, 'id' => $entity->getId(), 'name' => $entity->$nameMethod(), ]; return $options; }
[ "protected", "function", "getUpdateSelectParams", "(", "$", "updateSelect", ",", "$", "entity", ",", "$", "nameMethod", "=", "'getName'", ",", "$", "groupMethod", "=", "'getLanguage'", ")", "{", "$", "options", "=", "[", "'updateSelect'", "=>", "$", "updateSelect", ",", "'id'", "=>", "$", "entity", "->", "getId", "(", ")", ",", "'name'", "=>", "$", "entity", "->", "$", "nameMethod", "(", ")", ",", "]", ";", "return", "$", "options", ";", "}" ]
Return array of options update select response. @param string $updateSelect HTML id of the select @param object $entity @param string $nameMethod name of the entity method holding the name @param string $groupMethod name of the entity method holding the select group @return array
[ "Return", "array", "of", "options", "update", "select", "response", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/ContactClientController.php#L296-L309
TheDMSGroup/mautic-contact-client
Controller/TransactionsController.php
TransactionsController.exportAction
public function exportAction(Request $request, $objectId) { $entityManager = $this->getDoctrine()->getManager(); if (empty($objectId)) { return $this->accessDenied(); } // If contactclient:export:disable is true, deny access // since Admin permissions are always true, exclude the check for them if (!$this->get('mautic.security')->isAdmin() && $this->get('mautic.security')->isGranted( 'contactclient:export:disable' )) { return $this->accessDenied(); } $contactClient = $this->checkContactClientAccess($objectId, 'view'); if ($contactClient instanceof Response) { return $contactClient; } // send a stream csv file of the timeline $name = 'ContactClientExport'; $headers = [ 'id', 'type', 'message', 'date_added', 'contact_id', 'utm_source', 'email', 'phone', 'firstname', 'lastname', 'request_format', 'request_method', 'request_headers', 'request_body', 'request_duration', 'status', 'response_headers', 'response_body_raw', 'response_format', 'valid', ]; $session = $this->get('session'); $chartFilter = $session->get('mautic.contactclient.'.$contactClient->getId().'.chartfilter'); $params = [ 'dateTo' => new \DateTime($chartFilter['date_to']), 'dateFrom' => new \DateTime($chartFilter['date_from']), 'campaignId' => $chartFilter['campaign'], 'message' => !empty($request->query->get('message')) ? $request->query->get('message') : null, 'type' => !empty($request->query->get('type')) ? $request->query->get('type') : null, 'utm_source' => !empty($request->query->get('utm_source')) ? $request->query->get('utm_source') : null, 'contact_id' => !empty($request->query->get('contact_id')) ? $request->query->get('contact_id') : null, 'start' => 0, 'limit' => 1000, // batch limit, not total limit ]; /** @var EventRepository $eventRepository */ $eventRepository = $entityManager->getRepository( 'MauticContactClientBundle:Event' ); $count = $eventRepository->getEventsForTimelineExport($contactClient->getId(), $params, true); ini_set('max_execution_time', 0); $response = new StreamedResponse(); $response->setCallback( function () use ($params, $headers, $contactClient, $count, $eventRepository, $entityManager) { $handle = fopen('php://output', 'w+'); fputcsv($handle, $headers); $iterator = 0; while ($iterator < $count[0]['count']) { $timelineData = $eventRepository->getEventsForTimelineExport( $contactClient->getId(), $params, false ); foreach ($timelineData as $data) { // depracating use of YAML for event logs, but need to be backward compatible $csvRows = $data['logs'][0] === '{' ? $this->parseLogJSONBlob( $data ) : $this->parseLogYAMLBlob( $data ); // a single data row can be multiple operations and subsequent rows foreach ($csvRows as $csvRow) { fputcsv($handle, array_values($csvRow)); } } $iterator = $iterator + $params['limit']; $params['start'] = $data['id']; // memory management $entityManager->flush(); $entityManager->clear(); } fclose($handle); } ); $fileName = $name.'.csv'; $response->setStatusCode(200); $response->headers->set('Content-Type', 'application/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="'.$fileName.'"'); return $response; }
php
public function exportAction(Request $request, $objectId) { $entityManager = $this->getDoctrine()->getManager(); if (empty($objectId)) { return $this->accessDenied(); } // If contactclient:export:disable is true, deny access // since Admin permissions are always true, exclude the check for them if (!$this->get('mautic.security')->isAdmin() && $this->get('mautic.security')->isGranted( 'contactclient:export:disable' )) { return $this->accessDenied(); } $contactClient = $this->checkContactClientAccess($objectId, 'view'); if ($contactClient instanceof Response) { return $contactClient; } // send a stream csv file of the timeline $name = 'ContactClientExport'; $headers = [ 'id', 'type', 'message', 'date_added', 'contact_id', 'utm_source', 'email', 'phone', 'firstname', 'lastname', 'request_format', 'request_method', 'request_headers', 'request_body', 'request_duration', 'status', 'response_headers', 'response_body_raw', 'response_format', 'valid', ]; $session = $this->get('session'); $chartFilter = $session->get('mautic.contactclient.'.$contactClient->getId().'.chartfilter'); $params = [ 'dateTo' => new \DateTime($chartFilter['date_to']), 'dateFrom' => new \DateTime($chartFilter['date_from']), 'campaignId' => $chartFilter['campaign'], 'message' => !empty($request->query->get('message')) ? $request->query->get('message') : null, 'type' => !empty($request->query->get('type')) ? $request->query->get('type') : null, 'utm_source' => !empty($request->query->get('utm_source')) ? $request->query->get('utm_source') : null, 'contact_id' => !empty($request->query->get('contact_id')) ? $request->query->get('contact_id') : null, 'start' => 0, 'limit' => 1000, // batch limit, not total limit ]; /** @var EventRepository $eventRepository */ $eventRepository = $entityManager->getRepository( 'MauticContactClientBundle:Event' ); $count = $eventRepository->getEventsForTimelineExport($contactClient->getId(), $params, true); ini_set('max_execution_time', 0); $response = new StreamedResponse(); $response->setCallback( function () use ($params, $headers, $contactClient, $count, $eventRepository, $entityManager) { $handle = fopen('php://output', 'w+'); fputcsv($handle, $headers); $iterator = 0; while ($iterator < $count[0]['count']) { $timelineData = $eventRepository->getEventsForTimelineExport( $contactClient->getId(), $params, false ); foreach ($timelineData as $data) { // depracating use of YAML for event logs, but need to be backward compatible $csvRows = $data['logs'][0] === '{' ? $this->parseLogJSONBlob( $data ) : $this->parseLogYAMLBlob( $data ); // a single data row can be multiple operations and subsequent rows foreach ($csvRows as $csvRow) { fputcsv($handle, array_values($csvRow)); } } $iterator = $iterator + $params['limit']; $params['start'] = $data['id']; // memory management $entityManager->flush(); $entityManager->clear(); } fclose($handle); } ); $fileName = $name.'.csv'; $response->setStatusCode(200); $response->headers->set('Content-Type', 'application/csv; charset=utf-8'); $response->headers->set('Content-Disposition', 'attachment; filename="'.$fileName.'"'); return $response; }
[ "public", "function", "exportAction", "(", "Request", "$", "request", ",", "$", "objectId", ")", "{", "$", "entityManager", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "if", "(", "empty", "(", "$", "objectId", ")", ")", "{", "return", "$", "this", "->", "accessDenied", "(", ")", ";", "}", "// If contactclient:export:disable is true, deny access", "// since Admin permissions are always true, exclude the check for them", "if", "(", "!", "$", "this", "->", "get", "(", "'mautic.security'", ")", "->", "isAdmin", "(", ")", "&&", "$", "this", "->", "get", "(", "'mautic.security'", ")", "->", "isGranted", "(", "'contactclient:export:disable'", ")", ")", "{", "return", "$", "this", "->", "accessDenied", "(", ")", ";", "}", "$", "contactClient", "=", "$", "this", "->", "checkContactClientAccess", "(", "$", "objectId", ",", "'view'", ")", ";", "if", "(", "$", "contactClient", "instanceof", "Response", ")", "{", "return", "$", "contactClient", ";", "}", "// send a stream csv file of the timeline", "$", "name", "=", "'ContactClientExport'", ";", "$", "headers", "=", "[", "'id'", ",", "'type'", ",", "'message'", ",", "'date_added'", ",", "'contact_id'", ",", "'utm_source'", ",", "'email'", ",", "'phone'", ",", "'firstname'", ",", "'lastname'", ",", "'request_format'", ",", "'request_method'", ",", "'request_headers'", ",", "'request_body'", ",", "'request_duration'", ",", "'status'", ",", "'response_headers'", ",", "'response_body_raw'", ",", "'response_format'", ",", "'valid'", ",", "]", ";", "$", "session", "=", "$", "this", "->", "get", "(", "'session'", ")", ";", "$", "chartFilter", "=", "$", "session", "->", "get", "(", "'mautic.contactclient.'", ".", "$", "contactClient", "->", "getId", "(", ")", ".", "'.chartfilter'", ")", ";", "$", "params", "=", "[", "'dateTo'", "=>", "new", "\\", "DateTime", "(", "$", "chartFilter", "[", "'date_to'", "]", ")", ",", "'dateFrom'", "=>", "new", "\\", "DateTime", "(", "$", "chartFilter", "[", "'date_from'", "]", ")", ",", "'campaignId'", "=>", "$", "chartFilter", "[", "'campaign'", "]", ",", "'message'", "=>", "!", "empty", "(", "$", "request", "->", "query", "->", "get", "(", "'message'", ")", ")", "?", "$", "request", "->", "query", "->", "get", "(", "'message'", ")", ":", "null", ",", "'type'", "=>", "!", "empty", "(", "$", "request", "->", "query", "->", "get", "(", "'type'", ")", ")", "?", "$", "request", "->", "query", "->", "get", "(", "'type'", ")", ":", "null", ",", "'utm_source'", "=>", "!", "empty", "(", "$", "request", "->", "query", "->", "get", "(", "'utm_source'", ")", ")", "?", "$", "request", "->", "query", "->", "get", "(", "'utm_source'", ")", ":", "null", ",", "'contact_id'", "=>", "!", "empty", "(", "$", "request", "->", "query", "->", "get", "(", "'contact_id'", ")", ")", "?", "$", "request", "->", "query", "->", "get", "(", "'contact_id'", ")", ":", "null", ",", "'start'", "=>", "0", ",", "'limit'", "=>", "1000", ",", "// batch limit, not total limit", "]", ";", "/** @var EventRepository $eventRepository */", "$", "eventRepository", "=", "$", "entityManager", "->", "getRepository", "(", "'MauticContactClientBundle:Event'", ")", ";", "$", "count", "=", "$", "eventRepository", "->", "getEventsForTimelineExport", "(", "$", "contactClient", "->", "getId", "(", ")", ",", "$", "params", ",", "true", ")", ";", "ini_set", "(", "'max_execution_time'", ",", "0", ")", ";", "$", "response", "=", "new", "StreamedResponse", "(", ")", ";", "$", "response", "->", "setCallback", "(", "function", "(", ")", "use", "(", "$", "params", ",", "$", "headers", ",", "$", "contactClient", ",", "$", "count", ",", "$", "eventRepository", ",", "$", "entityManager", ")", "{", "$", "handle", "=", "fopen", "(", "'php://output'", ",", "'w+'", ")", ";", "fputcsv", "(", "$", "handle", ",", "$", "headers", ")", ";", "$", "iterator", "=", "0", ";", "while", "(", "$", "iterator", "<", "$", "count", "[", "0", "]", "[", "'count'", "]", ")", "{", "$", "timelineData", "=", "$", "eventRepository", "->", "getEventsForTimelineExport", "(", "$", "contactClient", "->", "getId", "(", ")", ",", "$", "params", ",", "false", ")", ";", "foreach", "(", "$", "timelineData", "as", "$", "data", ")", "{", "// depracating use of YAML for event logs, but need to be backward compatible", "$", "csvRows", "=", "$", "data", "[", "'logs'", "]", "[", "0", "]", "===", "'{'", "?", "$", "this", "->", "parseLogJSONBlob", "(", "$", "data", ")", ":", "$", "this", "->", "parseLogYAMLBlob", "(", "$", "data", ")", ";", "// a single data row can be multiple operations and subsequent rows", "foreach", "(", "$", "csvRows", "as", "$", "csvRow", ")", "{", "fputcsv", "(", "$", "handle", ",", "array_values", "(", "$", "csvRow", ")", ")", ";", "}", "}", "$", "iterator", "=", "$", "iterator", "+", "$", "params", "[", "'limit'", "]", ";", "$", "params", "[", "'start'", "]", "=", "$", "data", "[", "'id'", "]", ";", "// memory management", "$", "entityManager", "->", "flush", "(", ")", ";", "$", "entityManager", "->", "clear", "(", ")", ";", "}", "fclose", "(", "$", "handle", ")", ";", "}", ")", ";", "$", "fileName", "=", "$", "name", ".", "'.csv'", ";", "$", "response", "->", "setStatusCode", "(", "200", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'application/csv; charset=utf-8'", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Disposition'", ",", "'attachment; filename=\"'", ".", "$", "fileName", ".", "'\"'", ")", ";", "return", "$", "response", ";", "}" ]
@param Request $request @param $objectId @return array|\MauticPlugin\MauticContactClientBundle\Entity\ContactClient|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|StreamedResponse
[ "@param", "Request", "$request", "@param", "$objectId" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/TransactionsController.php#L34-L139
TheDMSGroup/mautic-contact-client
Controller/TransactionsController.php
TransactionsController.parseLogJSONBlob
private function parseLogJSONBlob($data) { $json = json_decode($data['logs'], true); unset($data['logs']); $rows = []; $data['request_format'] = ''; $data['request_method'] = ''; $data['request_headers'] = ''; $data['request_body'] = ''; $data['request_duration'] = ''; $data['response_status'] = ''; $data['response_headers'] = ''; $data['response_body_raw'] = ''; $data['response_format'] = ''; $data['valid'] = ''; if (isset($json['operations'])) { foreach ($json['operations'] as $id => $operation) { if (is_numeric($id)) { $row = $data; $row['request_format'] = isset($operation['request']['format']) ? $operation['request']['format'] : ''; $row['request_method'] = isset($operation['request']['method']) ? $operation['request']['method'] : ''; $row['request_headers'] = ''; $row['request_body'] = ''; if (isset($operation['request']['options'])) { if (isset($operation['request']['options']['headers'])) { $row['request_headers'] = implode('; ', $operation['request']['options']['headers']); unset($operation['request']['options']['headers']); } $string = ''; foreach ($operation['request']['options'] as $key => $option) { $string .= "$key: ".implode(',', $option).'; '; } $row['request_body'] = $string; } $row['request_duration'] = isset($operation['request']['duration']) ? $operation['request']['duration'] : ''; $row['response_status'] = isset($operation['response']['status']) ? $operation['response']['status'] : ''; $row['response_headers'] = isset($operation['response']['headers']) ? implode( '; ', $operation['response']['headers'] ) : ''; $row['response_body_raw'] = isset($operation['response']['bodyRaw']) ? $operation['response']['bodyRaw'] : ''; $row['response_format'] = isset($operation['response']['format']) ? $operation['response']['format'] : ''; $row['valid'] = isset($operation['valid']) ? $operation['valid'] : ''; $rows[$id] = $row; } } } else { $rows[0] = $data; } return $rows; }
php
private function parseLogJSONBlob($data) { $json = json_decode($data['logs'], true); unset($data['logs']); $rows = []; $data['request_format'] = ''; $data['request_method'] = ''; $data['request_headers'] = ''; $data['request_body'] = ''; $data['request_duration'] = ''; $data['response_status'] = ''; $data['response_headers'] = ''; $data['response_body_raw'] = ''; $data['response_format'] = ''; $data['valid'] = ''; if (isset($json['operations'])) { foreach ($json['operations'] as $id => $operation) { if (is_numeric($id)) { $row = $data; $row['request_format'] = isset($operation['request']['format']) ? $operation['request']['format'] : ''; $row['request_method'] = isset($operation['request']['method']) ? $operation['request']['method'] : ''; $row['request_headers'] = ''; $row['request_body'] = ''; if (isset($operation['request']['options'])) { if (isset($operation['request']['options']['headers'])) { $row['request_headers'] = implode('; ', $operation['request']['options']['headers']); unset($operation['request']['options']['headers']); } $string = ''; foreach ($operation['request']['options'] as $key => $option) { $string .= "$key: ".implode(',', $option).'; '; } $row['request_body'] = $string; } $row['request_duration'] = isset($operation['request']['duration']) ? $operation['request']['duration'] : ''; $row['response_status'] = isset($operation['response']['status']) ? $operation['response']['status'] : ''; $row['response_headers'] = isset($operation['response']['headers']) ? implode( '; ', $operation['response']['headers'] ) : ''; $row['response_body_raw'] = isset($operation['response']['bodyRaw']) ? $operation['response']['bodyRaw'] : ''; $row['response_format'] = isset($operation['response']['format']) ? $operation['response']['format'] : ''; $row['valid'] = isset($operation['valid']) ? $operation['valid'] : ''; $rows[$id] = $row; } } } else { $rows[0] = $data; } return $rows; }
[ "private", "function", "parseLogJSONBlob", "(", "$", "data", ")", "{", "$", "json", "=", "json_decode", "(", "$", "data", "[", "'logs'", "]", ",", "true", ")", ";", "unset", "(", "$", "data", "[", "'logs'", "]", ")", ";", "$", "rows", "=", "[", "]", ";", "$", "data", "[", "'request_format'", "]", "=", "''", ";", "$", "data", "[", "'request_method'", "]", "=", "''", ";", "$", "data", "[", "'request_headers'", "]", "=", "''", ";", "$", "data", "[", "'request_body'", "]", "=", "''", ";", "$", "data", "[", "'request_duration'", "]", "=", "''", ";", "$", "data", "[", "'response_status'", "]", "=", "''", ";", "$", "data", "[", "'response_headers'", "]", "=", "''", ";", "$", "data", "[", "'response_body_raw'", "]", "=", "''", ";", "$", "data", "[", "'response_format'", "]", "=", "''", ";", "$", "data", "[", "'valid'", "]", "=", "''", ";", "if", "(", "isset", "(", "$", "json", "[", "'operations'", "]", ")", ")", "{", "foreach", "(", "$", "json", "[", "'operations'", "]", "as", "$", "id", "=>", "$", "operation", ")", "{", "if", "(", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "row", "=", "$", "data", ";", "$", "row", "[", "'request_format'", "]", "=", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'format'", "]", ")", "?", "$", "operation", "[", "'request'", "]", "[", "'format'", "]", ":", "''", ";", "$", "row", "[", "'request_method'", "]", "=", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'method'", "]", ")", "?", "$", "operation", "[", "'request'", "]", "[", "'method'", "]", ":", "''", ";", "$", "row", "[", "'request_headers'", "]", "=", "''", ";", "$", "row", "[", "'request_body'", "]", "=", "''", ";", "if", "(", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "[", "'headers'", "]", ")", ")", "{", "$", "row", "[", "'request_headers'", "]", "=", "implode", "(", "'; '", ",", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "[", "'headers'", "]", ")", ";", "unset", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "[", "'headers'", "]", ")", ";", "}", "$", "string", "=", "''", ";", "foreach", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "as", "$", "key", "=>", "$", "option", ")", "{", "$", "string", ".=", "\"$key: \"", ".", "implode", "(", "','", ",", "$", "option", ")", ".", "'; '", ";", "}", "$", "row", "[", "'request_body'", "]", "=", "$", "string", ";", "}", "$", "row", "[", "'request_duration'", "]", "=", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'duration'", "]", ")", "?", "$", "operation", "[", "'request'", "]", "[", "'duration'", "]", ":", "''", ";", "$", "row", "[", "'response_status'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'status'", "]", ")", "?", "$", "operation", "[", "'response'", "]", "[", "'status'", "]", ":", "''", ";", "$", "row", "[", "'response_headers'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'headers'", "]", ")", "?", "implode", "(", "'; '", ",", "$", "operation", "[", "'response'", "]", "[", "'headers'", "]", ")", ":", "''", ";", "$", "row", "[", "'response_body_raw'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'bodyRaw'", "]", ")", "?", "$", "operation", "[", "'response'", "]", "[", "'bodyRaw'", "]", ":", "''", ";", "$", "row", "[", "'response_format'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'format'", "]", ")", "?", "$", "operation", "[", "'response'", "]", "[", "'format'", "]", ":", "''", ";", "$", "row", "[", "'valid'", "]", "=", "isset", "(", "$", "operation", "[", "'valid'", "]", ")", "?", "$", "operation", "[", "'valid'", "]", ":", "''", ";", "$", "rows", "[", "$", "id", "]", "=", "$", "row", ";", "}", "}", "}", "else", "{", "$", "rows", "[", "0", "]", "=", "$", "data", ";", "}", "return", "$", "rows", ";", "}" ]
@param $data @return array
[ "@param", "$data" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/TransactionsController.php#L146-L199
TheDMSGroup/mautic-contact-client
Controller/TransactionsController.php
TransactionsController.parseLogYAMLBlob
private function parseLogYAMLBlob($data) { $yaml = Yaml::parse($data['logs']); unset($data['logs']); $rows = []; $data['request_format'] = ''; $data['request_method'] = ''; $data['request_headers'] = ''; $data['request_body'] = ''; $data['request_duration'] = ''; $data['response_status'] = ''; $data['response_headers'] = ''; $data['response_body_raw'] = ''; $data['response_format'] = ''; $data['valid'] = ''; if (isset($yaml['operations'])) { foreach ($yaml['operations'] as $id => $operation) { if (is_numeric($id)) { $row = $data; $row['request_format'] = isset($operation['request']['format']) ? $operation['request']['format'] : ''; $row['request_method'] = isset($operation['request']['method']) ? $operation['request']['method'] : ''; $row['request_headers'] = ''; $row['request_body'] = ''; if (isset($operation['request']['options'])) { if (isset($operation['request']['options']['headers'])) { $row['request_headers'] = implode('; ', $operation['request']['options']['headers']); unset($operation['request']['options']['headers']); } $string = ''; foreach ($operation['request']['options'] as $key => $option) { $string .= $key.': '.implode(',', $option).'; '; } $row['request_body'] = $string; } $row['request_duration'] = isset($operation['request']['duration']) ? $operation['request']['duration'] : ''; $row['response_status'] = isset($operation['response']['status']) ? $operation['response']['status'] : ''; $row['response_headers'] = isset($operation['response']['headers']) ? implode( '; ', $operation['response']['headers'] ) : ''; $row['response_body_raw'] = isset($operation['response']['bodyRaw']) ? $operation['response']['bodyRaw'] : ''; $row['response_format'] = isset($operation['response']['format']) ? $operation['response']['format'] : ''; $row['valid'] = isset($operation['valid']) ? $operation['valid'] : ''; $rows[$id] = $row; } } } else { $rows[0] = $data; } return $rows; }
php
private function parseLogYAMLBlob($data) { $yaml = Yaml::parse($data['logs']); unset($data['logs']); $rows = []; $data['request_format'] = ''; $data['request_method'] = ''; $data['request_headers'] = ''; $data['request_body'] = ''; $data['request_duration'] = ''; $data['response_status'] = ''; $data['response_headers'] = ''; $data['response_body_raw'] = ''; $data['response_format'] = ''; $data['valid'] = ''; if (isset($yaml['operations'])) { foreach ($yaml['operations'] as $id => $operation) { if (is_numeric($id)) { $row = $data; $row['request_format'] = isset($operation['request']['format']) ? $operation['request']['format'] : ''; $row['request_method'] = isset($operation['request']['method']) ? $operation['request']['method'] : ''; $row['request_headers'] = ''; $row['request_body'] = ''; if (isset($operation['request']['options'])) { if (isset($operation['request']['options']['headers'])) { $row['request_headers'] = implode('; ', $operation['request']['options']['headers']); unset($operation['request']['options']['headers']); } $string = ''; foreach ($operation['request']['options'] as $key => $option) { $string .= $key.': '.implode(',', $option).'; '; } $row['request_body'] = $string; } $row['request_duration'] = isset($operation['request']['duration']) ? $operation['request']['duration'] : ''; $row['response_status'] = isset($operation['response']['status']) ? $operation['response']['status'] : ''; $row['response_headers'] = isset($operation['response']['headers']) ? implode( '; ', $operation['response']['headers'] ) : ''; $row['response_body_raw'] = isset($operation['response']['bodyRaw']) ? $operation['response']['bodyRaw'] : ''; $row['response_format'] = isset($operation['response']['format']) ? $operation['response']['format'] : ''; $row['valid'] = isset($operation['valid']) ? $operation['valid'] : ''; $rows[$id] = $row; } } } else { $rows[0] = $data; } return $rows; }
[ "private", "function", "parseLogYAMLBlob", "(", "$", "data", ")", "{", "$", "yaml", "=", "Yaml", "::", "parse", "(", "$", "data", "[", "'logs'", "]", ")", ";", "unset", "(", "$", "data", "[", "'logs'", "]", ")", ";", "$", "rows", "=", "[", "]", ";", "$", "data", "[", "'request_format'", "]", "=", "''", ";", "$", "data", "[", "'request_method'", "]", "=", "''", ";", "$", "data", "[", "'request_headers'", "]", "=", "''", ";", "$", "data", "[", "'request_body'", "]", "=", "''", ";", "$", "data", "[", "'request_duration'", "]", "=", "''", ";", "$", "data", "[", "'response_status'", "]", "=", "''", ";", "$", "data", "[", "'response_headers'", "]", "=", "''", ";", "$", "data", "[", "'response_body_raw'", "]", "=", "''", ";", "$", "data", "[", "'response_format'", "]", "=", "''", ";", "$", "data", "[", "'valid'", "]", "=", "''", ";", "if", "(", "isset", "(", "$", "yaml", "[", "'operations'", "]", ")", ")", "{", "foreach", "(", "$", "yaml", "[", "'operations'", "]", "as", "$", "id", "=>", "$", "operation", ")", "{", "if", "(", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "row", "=", "$", "data", ";", "$", "row", "[", "'request_format'", "]", "=", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'format'", "]", ")", "?", "$", "operation", "[", "'request'", "]", "[", "'format'", "]", ":", "''", ";", "$", "row", "[", "'request_method'", "]", "=", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'method'", "]", ")", "?", "$", "operation", "[", "'request'", "]", "[", "'method'", "]", ":", "''", ";", "$", "row", "[", "'request_headers'", "]", "=", "''", ";", "$", "row", "[", "'request_body'", "]", "=", "''", ";", "if", "(", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "[", "'headers'", "]", ")", ")", "{", "$", "row", "[", "'request_headers'", "]", "=", "implode", "(", "'; '", ",", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "[", "'headers'", "]", ")", ";", "unset", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "[", "'headers'", "]", ")", ";", "}", "$", "string", "=", "''", ";", "foreach", "(", "$", "operation", "[", "'request'", "]", "[", "'options'", "]", "as", "$", "key", "=>", "$", "option", ")", "{", "$", "string", ".=", "$", "key", ".", "': '", ".", "implode", "(", "','", ",", "$", "option", ")", ".", "'; '", ";", "}", "$", "row", "[", "'request_body'", "]", "=", "$", "string", ";", "}", "$", "row", "[", "'request_duration'", "]", "=", "isset", "(", "$", "operation", "[", "'request'", "]", "[", "'duration'", "]", ")", "?", "$", "operation", "[", "'request'", "]", "[", "'duration'", "]", ":", "''", ";", "$", "row", "[", "'response_status'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'status'", "]", ")", "?", "$", "operation", "[", "'response'", "]", "[", "'status'", "]", ":", "''", ";", "$", "row", "[", "'response_headers'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'headers'", "]", ")", "?", "implode", "(", "'; '", ",", "$", "operation", "[", "'response'", "]", "[", "'headers'", "]", ")", ":", "''", ";", "$", "row", "[", "'response_body_raw'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'bodyRaw'", "]", ")", "?", "$", "operation", "[", "'response'", "]", "[", "'bodyRaw'", "]", ":", "''", ";", "$", "row", "[", "'response_format'", "]", "=", "isset", "(", "$", "operation", "[", "'response'", "]", "[", "'format'", "]", ")", "?", "$", "operation", "[", "'response'", "]", "[", "'format'", "]", ":", "''", ";", "$", "row", "[", "'valid'", "]", "=", "isset", "(", "$", "operation", "[", "'valid'", "]", ")", "?", "$", "operation", "[", "'valid'", "]", ":", "''", ";", "$", "rows", "[", "$", "id", "]", "=", "$", "row", ";", "}", "}", "}", "else", "{", "$", "rows", "[", "0", "]", "=", "$", "data", ";", "}", "return", "$", "rows", ";", "}" ]
@param $data @return array
[ "@param", "$data" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Controller/TransactionsController.php#L206-L259
TheDMSGroup/mautic-contact-client
Model/ApiPayloadAuth.php
ApiPayloadAuth.getStartOperation
public function getStartOperation() { $id = 0; if ($this->hasAuthRequest()) { // Step through operations, skipping any at the beginning that can be skipped. foreach ($this->operations as $id => $operation) { if ($id == count($this->operations) - 1) { // This is the last request so it cannot be skipped. break; } if (!$this->hasAuthRequest($id)) { // This is not an auth request so it should never be skipped. break; } if ($this->operationUpdatesContact($operation)) { // This operation should never be skipped because it can update the contact. break; } $this->determineOperationRequirements(); if (isset($this->requiredPayloadTokens[$id])) { // This step can be skipped if we have these tokens. $this->loadPreviousPayloadAuthTokens(); foreach ($this->requiredPayloadTokens[$id] as $token) { if (!isset($this->previousPayloadAuthTokens[$token])) { // We cannot skip this operation because a required token isn't in the database yet. break; } } } else { // This step is indicated as auth, but no tokens from it are used in the following payload. // Assume the client hasn't been fully configured and do not skip this operation. break; } } } return $id; }
php
public function getStartOperation() { $id = 0; if ($this->hasAuthRequest()) { // Step through operations, skipping any at the beginning that can be skipped. foreach ($this->operations as $id => $operation) { if ($id == count($this->operations) - 1) { // This is the last request so it cannot be skipped. break; } if (!$this->hasAuthRequest($id)) { // This is not an auth request so it should never be skipped. break; } if ($this->operationUpdatesContact($operation)) { // This operation should never be skipped because it can update the contact. break; } $this->determineOperationRequirements(); if (isset($this->requiredPayloadTokens[$id])) { // This step can be skipped if we have these tokens. $this->loadPreviousPayloadAuthTokens(); foreach ($this->requiredPayloadTokens[$id] as $token) { if (!isset($this->previousPayloadAuthTokens[$token])) { // We cannot skip this operation because a required token isn't in the database yet. break; } } } else { // This step is indicated as auth, but no tokens from it are used in the following payload. // Assume the client hasn't been fully configured and do not skip this operation. break; } } } return $id; }
[ "public", "function", "getStartOperation", "(", ")", "{", "$", "id", "=", "0", ";", "if", "(", "$", "this", "->", "hasAuthRequest", "(", ")", ")", "{", "// Step through operations, skipping any at the beginning that can be skipped.", "foreach", "(", "$", "this", "->", "operations", "as", "$", "id", "=>", "$", "operation", ")", "{", "if", "(", "$", "id", "==", "count", "(", "$", "this", "->", "operations", ")", "-", "1", ")", "{", "// This is the last request so it cannot be skipped.", "break", ";", "}", "if", "(", "!", "$", "this", "->", "hasAuthRequest", "(", "$", "id", ")", ")", "{", "// This is not an auth request so it should never be skipped.", "break", ";", "}", "if", "(", "$", "this", "->", "operationUpdatesContact", "(", "$", "operation", ")", ")", "{", "// This operation should never be skipped because it can update the contact.", "break", ";", "}", "$", "this", "->", "determineOperationRequirements", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "requiredPayloadTokens", "[", "$", "id", "]", ")", ")", "{", "// This step can be skipped if we have these tokens.", "$", "this", "->", "loadPreviousPayloadAuthTokens", "(", ")", ";", "foreach", "(", "$", "this", "->", "requiredPayloadTokens", "[", "$", "id", "]", "as", "$", "token", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "previousPayloadAuthTokens", "[", "$", "token", "]", ")", ")", "{", "// We cannot skip this operation because a required token isn't in the database yet.", "break", ";", "}", "}", "}", "else", "{", "// This step is indicated as auth, but no tokens from it are used in the following payload.", "// Assume the client hasn't been fully configured and do not skip this operation.", "break", ";", "}", "}", "}", "return", "$", "id", ";", "}" ]
Step forward through operations to find the one we MUST start with. @return array
[ "Step", "forward", "through", "operations", "to", "find", "the", "one", "we", "MUST", "start", "with", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadAuth.php#L130-L170
TheDMSGroup/mautic-contact-client
Model/ApiPayloadAuth.php
ApiPayloadAuth.hasAuthRequest
public function hasAuthRequest($operationId = null) { if (null === $this->authRequestOperations) { $this->authRequestOperations = []; if (count($this->operations) > 1) { foreach ($this->operations as $id => $operation) { if ( isset($operation->request) && isset($operation->request->auth) && $operation->request->auth ) { $this->authRequestOperations[$id] = $id; } } } } return $operationId ? isset($this->authRequestOperations[$operationId]) : boolval($this->authRequestOperations); }
php
public function hasAuthRequest($operationId = null) { if (null === $this->authRequestOperations) { $this->authRequestOperations = []; if (count($this->operations) > 1) { foreach ($this->operations as $id => $operation) { if ( isset($operation->request) && isset($operation->request->auth) && $operation->request->auth ) { $this->authRequestOperations[$id] = $id; } } } } return $operationId ? isset($this->authRequestOperations[$operationId]) : boolval($this->authRequestOperations); }
[ "public", "function", "hasAuthRequest", "(", "$", "operationId", "=", "null", ")", "{", "if", "(", "null", "===", "$", "this", "->", "authRequestOperations", ")", "{", "$", "this", "->", "authRequestOperations", "=", "[", "]", ";", "if", "(", "count", "(", "$", "this", "->", "operations", ")", ">", "1", ")", "{", "foreach", "(", "$", "this", "->", "operations", "as", "$", "id", "=>", "$", "operation", ")", "{", "if", "(", "isset", "(", "$", "operation", "->", "request", ")", "&&", "isset", "(", "$", "operation", "->", "request", "->", "auth", ")", "&&", "$", "operation", "->", "request", "->", "auth", ")", "{", "$", "this", "->", "authRequestOperations", "[", "$", "id", "]", "=", "$", "id", ";", "}", "}", "}", "}", "return", "$", "operationId", "?", "isset", "(", "$", "this", "->", "authRequestOperations", "[", "$", "operationId", "]", ")", ":", "boolval", "(", "$", "this", "->", "authRequestOperations", ")", ";", "}" ]
@param null $operationId @return bool
[ "@param", "null", "$operationId" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadAuth.php#L177-L195
TheDMSGroup/mautic-contact-client
Model/ApiPayloadAuth.php
ApiPayloadAuth.operationUpdatesContact
private function operationUpdatesContact($operation) { if (isset($operation->response)) { foreach (['headers', 'body'] as $fieldType) { if (is_array($operation->response->{$fieldType})) { foreach ($operation->response->{$fieldType} as $field) { if ( isset($field->destination) && '' !== $field->destination ) { return true; } } } } } return false; }
php
private function operationUpdatesContact($operation) { if (isset($operation->response)) { foreach (['headers', 'body'] as $fieldType) { if (is_array($operation->response->{$fieldType})) { foreach ($operation->response->{$fieldType} as $field) { if ( isset($field->destination) && '' !== $field->destination ) { return true; } } } } } return false; }
[ "private", "function", "operationUpdatesContact", "(", "$", "operation", ")", "{", "if", "(", "isset", "(", "$", "operation", "->", "response", ")", ")", "{", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "fieldType", ")", "{", "if", "(", "is_array", "(", "$", "operation", "->", "response", "->", "{", "$", "fieldType", "}", ")", ")", "{", "foreach", "(", "$", "operation", "->", "response", "->", "{", "$", "fieldType", "}", "as", "$", "field", ")", "{", "if", "(", "isset", "(", "$", "field", "->", "destination", ")", "&&", "''", "!==", "$", "field", "->", "destination", ")", "{", "return", "true", ";", "}", "}", "}", "}", "}", "return", "false", ";", "}" ]
@param $operation @return bool
[ "@param", "$operation" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadAuth.php#L202-L220
TheDMSGroup/mautic-contact-client
Model/ApiPayloadAuth.php
ApiPayloadAuth.determineOperationRequirements
private function determineOperationRequirements() { if (null === $this->requiredPayloadTokens) { $this->requiredPayloadTokens = []; $valueSources = ['value', 'default_value']; if ($this->test) { $valueSources = ['test_value', 'value', 'default_value']; } foreach ($this->operations as $id => $operation) { if (isset($operation->request)) { // Check the request for payload tokens dependent on previous operations. foreach (['headers', 'body'] as $fieldType) { if (is_array($operation->request->{$fieldType})) { foreach ($operation->request->{$fieldType} as $field) { foreach ($valueSources as $valueSource) { if (!empty($field->{$valueSource})) { $tokens = $this->tokenHelper->getTokens($field->{$valueSource}); if ($tokens) { // Check for tokens that use the payload of a previous operation. foreach ($tokens as $token) { $parts = explode('.', $token); if ( isset($parts[0]) && 'payload' === $parts[0] && isset($parts[1]) && 'operations' === $parts[1] && isset($parts[2]) && is_numeric($parts[2]) && isset($parts[3]) && 'response' === $parts[3] && in_array($parts[4], ['headers', 'body']) && isset($parts[5]) ) { if (!isset($this->requiredPayloadTokens[$parts[2]])) { $this->requiredPayloadTokens[$parts[2]] = []; } $this->requiredPayloadTokens[$parts[2]][] = $token; } } } } } } } } } } } }
php
private function determineOperationRequirements() { if (null === $this->requiredPayloadTokens) { $this->requiredPayloadTokens = []; $valueSources = ['value', 'default_value']; if ($this->test) { $valueSources = ['test_value', 'value', 'default_value']; } foreach ($this->operations as $id => $operation) { if (isset($operation->request)) { // Check the request for payload tokens dependent on previous operations. foreach (['headers', 'body'] as $fieldType) { if (is_array($operation->request->{$fieldType})) { foreach ($operation->request->{$fieldType} as $field) { foreach ($valueSources as $valueSource) { if (!empty($field->{$valueSource})) { $tokens = $this->tokenHelper->getTokens($field->{$valueSource}); if ($tokens) { // Check for tokens that use the payload of a previous operation. foreach ($tokens as $token) { $parts = explode('.', $token); if ( isset($parts[0]) && 'payload' === $parts[0] && isset($parts[1]) && 'operations' === $parts[1] && isset($parts[2]) && is_numeric($parts[2]) && isset($parts[3]) && 'response' === $parts[3] && in_array($parts[4], ['headers', 'body']) && isset($parts[5]) ) { if (!isset($this->requiredPayloadTokens[$parts[2]])) { $this->requiredPayloadTokens[$parts[2]] = []; } $this->requiredPayloadTokens[$parts[2]][] = $token; } } } } } } } } } } } }
[ "private", "function", "determineOperationRequirements", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "requiredPayloadTokens", ")", "{", "$", "this", "->", "requiredPayloadTokens", "=", "[", "]", ";", "$", "valueSources", "=", "[", "'value'", ",", "'default_value'", "]", ";", "if", "(", "$", "this", "->", "test", ")", "{", "$", "valueSources", "=", "[", "'test_value'", ",", "'value'", ",", "'default_value'", "]", ";", "}", "foreach", "(", "$", "this", "->", "operations", "as", "$", "id", "=>", "$", "operation", ")", "{", "if", "(", "isset", "(", "$", "operation", "->", "request", ")", ")", "{", "// Check the request for payload tokens dependent on previous operations.", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "fieldType", ")", "{", "if", "(", "is_array", "(", "$", "operation", "->", "request", "->", "{", "$", "fieldType", "}", ")", ")", "{", "foreach", "(", "$", "operation", "->", "request", "->", "{", "$", "fieldType", "}", "as", "$", "field", ")", "{", "foreach", "(", "$", "valueSources", "as", "$", "valueSource", ")", "{", "if", "(", "!", "empty", "(", "$", "field", "->", "{", "$", "valueSource", "}", ")", ")", "{", "$", "tokens", "=", "$", "this", "->", "tokenHelper", "->", "getTokens", "(", "$", "field", "->", "{", "$", "valueSource", "}", ")", ";", "if", "(", "$", "tokens", ")", "{", "// Check for tokens that use the payload of a previous operation.", "foreach", "(", "$", "tokens", "as", "$", "token", ")", "{", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "token", ")", ";", "if", "(", "isset", "(", "$", "parts", "[", "0", "]", ")", "&&", "'payload'", "===", "$", "parts", "[", "0", "]", "&&", "isset", "(", "$", "parts", "[", "1", "]", ")", "&&", "'operations'", "===", "$", "parts", "[", "1", "]", "&&", "isset", "(", "$", "parts", "[", "2", "]", ")", "&&", "is_numeric", "(", "$", "parts", "[", "2", "]", ")", "&&", "isset", "(", "$", "parts", "[", "3", "]", ")", "&&", "'response'", "===", "$", "parts", "[", "3", "]", "&&", "in_array", "(", "$", "parts", "[", "4", "]", ",", "[", "'headers'", ",", "'body'", "]", ")", "&&", "isset", "(", "$", "parts", "[", "5", "]", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "requiredPayloadTokens", "[", "$", "parts", "[", "2", "]", "]", ")", ")", "{", "$", "this", "->", "requiredPayloadTokens", "[", "$", "parts", "[", "2", "]", "]", "=", "[", "]", ";", "}", "$", "this", "->", "requiredPayloadTokens", "[", "$", "parts", "[", "2", "]", "]", "[", "]", "=", "$", "token", ";", "}", "}", "}", "}", "}", "}", "}", "}", "}", "}", "}", "}" ]
Discern the tokens that are required by operation ID.
[ "Discern", "the", "tokens", "that", "are", "required", "by", "operation", "ID", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadAuth.php#L225-L275
TheDMSGroup/mautic-contact-client
Model/ApiPayloadAuth.php
ApiPayloadAuth.loadPreviousPayloadAuthTokens
private function loadPreviousPayloadAuthTokens() { if (!$this->previousPayloadAuthTokens) { $this->previousPayloadAuthTokens = $this->getAuthRepository()->getPreviousPayloadAuthTokensByContactClient( $this->contactClient->getId(), null, $this->test ); } }
php
private function loadPreviousPayloadAuthTokens() { if (!$this->previousPayloadAuthTokens) { $this->previousPayloadAuthTokens = $this->getAuthRepository()->getPreviousPayloadAuthTokensByContactClient( $this->contactClient->getId(), null, $this->test ); } }
[ "private", "function", "loadPreviousPayloadAuthTokens", "(", ")", "{", "if", "(", "!", "$", "this", "->", "previousPayloadAuthTokens", ")", "{", "$", "this", "->", "previousPayloadAuthTokens", "=", "$", "this", "->", "getAuthRepository", "(", ")", "->", "getPreviousPayloadAuthTokensByContactClient", "(", "$", "this", "->", "contactClient", "->", "getId", "(", ")", ",", "null", ",", "$", "this", "->", "test", ")", ";", "}", "}" ]
Load up the previously stored payload tokens.
[ "Load", "up", "the", "previously", "stored", "payload", "tokens", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadAuth.php#L280-L289
TheDMSGroup/mautic-contact-client
Model/ApiPayloadAuth.php
ApiPayloadAuth.savePayloadAuthTokens
public function savePayloadAuthTokens($operationId, $fieldSets) { if (!$fieldSets) { return; } $repo = $this->getAuthRepository(); $repo->flushPreviousAuthTokens($this->contactClient->getId(), $operationId, $this->test); $entities = []; foreach ($fieldSets as $type => $fields) { foreach ($fields as $field => $val) { if ($field && $val) { $auth = new Auth(); $auth->setContactClient($this->contactClient->getId()); $auth->setOperation($operationId); $auth->setType($type); $auth->setField($field); $auth->setVal(substr($val, 0, 256)); $auth->setTest($this->test); $entities[] = $auth; } } } $repo->saveEntities($entities); }
php
public function savePayloadAuthTokens($operationId, $fieldSets) { if (!$fieldSets) { return; } $repo = $this->getAuthRepository(); $repo->flushPreviousAuthTokens($this->contactClient->getId(), $operationId, $this->test); $entities = []; foreach ($fieldSets as $type => $fields) { foreach ($fields as $field => $val) { if ($field && $val) { $auth = new Auth(); $auth->setContactClient($this->contactClient->getId()); $auth->setOperation($operationId); $auth->setType($type); $auth->setField($field); $auth->setVal(substr($val, 0, 256)); $auth->setTest($this->test); $entities[] = $auth; } } } $repo->saveEntities($entities); }
[ "public", "function", "savePayloadAuthTokens", "(", "$", "operationId", ",", "$", "fieldSets", ")", "{", "if", "(", "!", "$", "fieldSets", ")", "{", "return", ";", "}", "$", "repo", "=", "$", "this", "->", "getAuthRepository", "(", ")", ";", "$", "repo", "->", "flushPreviousAuthTokens", "(", "$", "this", "->", "contactClient", "->", "getId", "(", ")", ",", "$", "operationId", ",", "$", "this", "->", "test", ")", ";", "$", "entities", "=", "[", "]", ";", "foreach", "(", "$", "fieldSets", "as", "$", "type", "=>", "$", "fields", ")", "{", "foreach", "(", "$", "fields", "as", "$", "field", "=>", "$", "val", ")", "{", "if", "(", "$", "field", "&&", "$", "val", ")", "{", "$", "auth", "=", "new", "Auth", "(", ")", ";", "$", "auth", "->", "setContactClient", "(", "$", "this", "->", "contactClient", "->", "getId", "(", ")", ")", ";", "$", "auth", "->", "setOperation", "(", "$", "operationId", ")", ";", "$", "auth", "->", "setType", "(", "$", "type", ")", ";", "$", "auth", "->", "setField", "(", "$", "field", ")", ";", "$", "auth", "->", "setVal", "(", "substr", "(", "$", "val", ",", "0", ",", "256", ")", ")", ";", "$", "auth", "->", "setTest", "(", "$", "this", "->", "test", ")", ";", "$", "entities", "[", "]", "=", "$", "auth", ";", "}", "}", "}", "$", "repo", "->", "saveEntities", "(", "$", "entities", ")", ";", "}" ]
Given an array from the response object (headers and body) save as new Auth entities. Flush previous entries for this operation. @param $operationId @param $fieldSets
[ "Given", "an", "array", "from", "the", "response", "object", "(", "headers", "and", "body", ")", "save", "as", "new", "Auth", "entities", ".", "Flush", "previous", "entries", "for", "this", "operation", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadAuth.php#L318-L342
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.createForm
public function createForm($entity, $formFactory, $action = null, $options = []) { if (!$entity instanceof ContactClient) { throw new MethodNotAllowedHttpException(['ContactClient']); } if (!empty($action)) { $options['action'] = $action; } // Prevent clone action from complaining about extra fields. $options['allow_extra_fields'] = true; return $formFactory->create('contactclient', $entity, $options); }
php
public function createForm($entity, $formFactory, $action = null, $options = []) { if (!$entity instanceof ContactClient) { throw new MethodNotAllowedHttpException(['ContactClient']); } if (!empty($action)) { $options['action'] = $action; } // Prevent clone action from complaining about extra fields. $options['allow_extra_fields'] = true; return $formFactory->create('contactclient', $entity, $options); }
[ "public", "function", "createForm", "(", "$", "entity", ",", "$", "formFactory", ",", "$", "action", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "!", "$", "entity", "instanceof", "ContactClient", ")", "{", "throw", "new", "MethodNotAllowedHttpException", "(", "[", "'ContactClient'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "action", ")", ")", "{", "$", "options", "[", "'action'", "]", "=", "$", "action", ";", "}", "// Prevent clone action from complaining about extra fields.", "$", "options", "[", "'allow_extra_fields'", "]", "=", "true", ";", "return", "$", "formFactory", "->", "create", "(", "'contactclient'", ",", "$", "entity", ",", "$", "options", ")", ";", "}" ]
{@inheritdoc} @param object $entity @param \Symfony\Component\Form\FormFactory $formFactory @param string $action @param array $options @throws NotFoundHttpException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L103-L117
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.saveEntity
public function saveEntity($entity, $unlock = true) { parent::saveEntity($entity, $unlock); $this->getRepository()->saveEntity($entity); }
php
public function saveEntity($entity, $unlock = true) { parent::saveEntity($entity, $unlock); $this->getRepository()->saveEntity($entity); }
[ "public", "function", "saveEntity", "(", "$", "entity", ",", "$", "unlock", "=", "true", ")", "{", "parent", "::", "saveEntity", "(", "$", "entity", ",", "$", "unlock", ")", ";", "$", "this", "->", "getRepository", "(", ")", "->", "saveEntity", "(", "$", "entity", ")", ";", "}" ]
{@inheritdoc} @param ContactClient $entity @param bool|false $unlock
[ "{", "@inheritdoc", "}" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L139-L144
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.addStat
public function addStat( ContactClient $contactClient = null, $type = null, Contact $contact = null, $attribution = 0, $utmSource = '', $campaignId = 0, $eventId = 0 ) { $stat = new Stat(); $stat->setDateAdded(new \DateTime()); if ($type) { $stat->setType($type); } if ($contactClient) { $stat->setContactClientId($contactClient->getId()); } if ($contact) { $stat->setContactId($contact->getId()); } if ($attribution) { $stat->setAttribution($attribution); } if ($utmSource) { $stat->setUtmSource($utmSource); } $stat->setCampaignId($campaignId); $stat->setEventId($eventId); $this->getStatRepository()->saveEntity($stat); // dispatch Stat PostSave event try { $event = new ContactClientStatEvent( $contactClient, $campaignId, $eventId, $contact, $this->em ); $this->dispatcher->dispatch( ContactClientEvents::STAT_SAVE, $event ); } catch (\Exception $e) { } }
php
public function addStat( ContactClient $contactClient = null, $type = null, Contact $contact = null, $attribution = 0, $utmSource = '', $campaignId = 0, $eventId = 0 ) { $stat = new Stat(); $stat->setDateAdded(new \DateTime()); if ($type) { $stat->setType($type); } if ($contactClient) { $stat->setContactClientId($contactClient->getId()); } if ($contact) { $stat->setContactId($contact->getId()); } if ($attribution) { $stat->setAttribution($attribution); } if ($utmSource) { $stat->setUtmSource($utmSource); } $stat->setCampaignId($campaignId); $stat->setEventId($eventId); $this->getStatRepository()->saveEntity($stat); // dispatch Stat PostSave event try { $event = new ContactClientStatEvent( $contactClient, $campaignId, $eventId, $contact, $this->em ); $this->dispatcher->dispatch( ContactClientEvents::STAT_SAVE, $event ); } catch (\Exception $e) { } }
[ "public", "function", "addStat", "(", "ContactClient", "$", "contactClient", "=", "null", ",", "$", "type", "=", "null", ",", "Contact", "$", "contact", "=", "null", ",", "$", "attribution", "=", "0", ",", "$", "utmSource", "=", "''", ",", "$", "campaignId", "=", "0", ",", "$", "eventId", "=", "0", ")", "{", "$", "stat", "=", "new", "Stat", "(", ")", ";", "$", "stat", "->", "setDateAdded", "(", "new", "\\", "DateTime", "(", ")", ")", ";", "if", "(", "$", "type", ")", "{", "$", "stat", "->", "setType", "(", "$", "type", ")", ";", "}", "if", "(", "$", "contactClient", ")", "{", "$", "stat", "->", "setContactClientId", "(", "$", "contactClient", "->", "getId", "(", ")", ")", ";", "}", "if", "(", "$", "contact", ")", "{", "$", "stat", "->", "setContactId", "(", "$", "contact", "->", "getId", "(", ")", ")", ";", "}", "if", "(", "$", "attribution", ")", "{", "$", "stat", "->", "setAttribution", "(", "$", "attribution", ")", ";", "}", "if", "(", "$", "utmSource", ")", "{", "$", "stat", "->", "setUtmSource", "(", "$", "utmSource", ")", ";", "}", "$", "stat", "->", "setCampaignId", "(", "$", "campaignId", ")", ";", "$", "stat", "->", "setEventId", "(", "$", "eventId", ")", ";", "$", "this", "->", "getStatRepository", "(", ")", "->", "saveEntity", "(", "$", "stat", ")", ";", "// dispatch Stat PostSave event", "try", "{", "$", "event", "=", "new", "ContactClientStatEvent", "(", "$", "contactClient", ",", "$", "campaignId", ",", "$", "eventId", ",", "$", "contact", ",", "$", "this", "->", "em", ")", ";", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "ContactClientEvents", "::", "STAT_SAVE", ",", "$", "event", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "}" ]
Add a stat entry. @param ContactClient|null $contactClient @param null $type @param Contact|null $contact @param int $attribution @param string $utmSource @param int $campaignId @param int $eventId
[ "Add", "a", "stat", "entry", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L167-L208
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.getStatRepository
public function getStatRepository() { if (!$this->em->isOpen()) { $this->em = $this->em->create( $this->em->getConnection(), $this->em->getConfiguration(), $this->em->getEventManager() ); } return $this->em->getRepository('MauticContactClientBundle:Stat'); }
php
public function getStatRepository() { if (!$this->em->isOpen()) { $this->em = $this->em->create( $this->em->getConnection(), $this->em->getConfiguration(), $this->em->getEventManager() ); } return $this->em->getRepository('MauticContactClientBundle:Stat'); }
[ "public", "function", "getStatRepository", "(", ")", "{", "if", "(", "!", "$", "this", "->", "em", "->", "isOpen", "(", ")", ")", "{", "$", "this", "->", "em", "=", "$", "this", "->", "em", "->", "create", "(", "$", "this", "->", "em", "->", "getConnection", "(", ")", ",", "$", "this", "->", "em", "->", "getConfiguration", "(", ")", ",", "$", "this", "->", "em", "->", "getEventManager", "(", ")", ")", ";", "}", "return", "$", "this", "->", "em", "->", "getRepository", "(", "'MauticContactClientBundle:Stat'", ")", ";", "}" ]
{@inheritdoc} @return \MauticPlugin\MauticContactClientBundle\Entity\StatRepository
[ "{", "@inheritdoc", "}" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L215-L226
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.addEvent
public function addEvent( ContactClient $contactClient = null, $type = null, Contact $contact = null, $logs = null, $message = null, $integrationEntityId = null ) { $event = new EventEntity(); $event->setDateAdded(new \DateTime()); if ($type) { $event->setType($type); } if ($contactClient) { $event->setContactClientId($contactClient->getId()); } if ($contact) { $event->setContact($contact); } if ($logs) { $event->setLogs($logs); } if ($message) { $event->setMessage($message); } if ($integrationEntityId) { $event->setIntegrationEntityId($integrationEntityId); } $this->getEventRepository()->saveEntity($event); }
php
public function addEvent( ContactClient $contactClient = null, $type = null, Contact $contact = null, $logs = null, $message = null, $integrationEntityId = null ) { $event = new EventEntity(); $event->setDateAdded(new \DateTime()); if ($type) { $event->setType($type); } if ($contactClient) { $event->setContactClientId($contactClient->getId()); } if ($contact) { $event->setContact($contact); } if ($logs) { $event->setLogs($logs); } if ($message) { $event->setMessage($message); } if ($integrationEntityId) { $event->setIntegrationEntityId($integrationEntityId); } $this->getEventRepository()->saveEntity($event); }
[ "public", "function", "addEvent", "(", "ContactClient", "$", "contactClient", "=", "null", ",", "$", "type", "=", "null", ",", "Contact", "$", "contact", "=", "null", ",", "$", "logs", "=", "null", ",", "$", "message", "=", "null", ",", "$", "integrationEntityId", "=", "null", ")", "{", "$", "event", "=", "new", "EventEntity", "(", ")", ";", "$", "event", "->", "setDateAdded", "(", "new", "\\", "DateTime", "(", ")", ")", ";", "if", "(", "$", "type", ")", "{", "$", "event", "->", "setType", "(", "$", "type", ")", ";", "}", "if", "(", "$", "contactClient", ")", "{", "$", "event", "->", "setContactClientId", "(", "$", "contactClient", "->", "getId", "(", ")", ")", ";", "}", "if", "(", "$", "contact", ")", "{", "$", "event", "->", "setContact", "(", "$", "contact", ")", ";", "}", "if", "(", "$", "logs", ")", "{", "$", "event", "->", "setLogs", "(", "$", "logs", ")", ";", "}", "if", "(", "$", "message", ")", "{", "$", "event", "->", "setMessage", "(", "$", "message", ")", ";", "}", "if", "(", "$", "integrationEntityId", ")", "{", "$", "event", "->", "setIntegrationEntityId", "(", "$", "integrationEntityId", ")", ";", "}", "$", "this", "->", "getEventRepository", "(", ")", "->", "saveEntity", "(", "$", "event", ")", ";", "}" ]
Add transactional log in contactclient_events. @param ContactClient|null $contactClient @param string $type @param Contact|null $contact @param null $logs @param null $message @param null $integrationEntityId
[ "Add", "transactional", "log", "in", "contactclient_events", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L238-L268
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.getStats
public function getStats( ContactClient $contactClient, $unit, \DateTime $dateFrom = null, \DateTime $dateTo = null, $campaignId = null, $dateFormat = null, $canViewOthers = true ) { $query = new ChartQuery($this->em->getConnection(), $dateFrom, $dateTo, $unit); $unit = (null === $unit) ? $this->getTimeUnitFromDateRange($dateFrom, $dateTo) : $unit; $chart = new LineChart($unit, $dateFrom, $dateTo, $dateFormat); $stat = new Stat(); $params = ['contactclient_id' => $contactClient->getId()]; if ($campaignId) { $params['campaign_id'] = $campaignId; } foreach ($stat->getAllTypes() as $type) { $params['type'] = $type; $q = $query->prepareTimeDataQuery( 'contactclient_stats', 'date_added', $params ); if (!in_array($unit, ['H', 'i', 's'])) { // For some reason, Mautic only sets UTC in Query Date builder // if its an intra-day date range ¯\_(ツ)_/¯ // so we have to do it here. $userTZ = new \DateTime('now'); $userTzName = $userTZ->getTimezone()->getName(); $paramDateTo = $q->getParameter('dateTo'); $paramDateFrom = $q->getParameter('dateFrom'); $paramDateTo = new \DateTime($paramDateTo); $paramDateTo->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateTo', $paramDateTo->format('Y-m-d H:i:s')); $paramDateFrom = new \DateTime($paramDateFrom); $paramDateFrom->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateFrom', $paramDateFrom->format('Y-m-d H:i:s')); $select = $q->getQueryPart('select')[0]; $newSelect = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $select ); $q->resetQueryPart('select'); $q->select($newSelect); // AND adjust the group By, since its using db timezone Date values $groupBy = $q->getQueryPart('groupBy')[0]; $newGroupBy = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $groupBy ); $q->resetQueryPart('groupBy'); $q->groupBy($newGroupBy); } if (!$canViewOthers) { $this->limitQueryToCreator($q); } $data = $query->loadAndBuildTimeData($q); foreach ($data as $val) { if (0 !== $val) { $chart->setDataset($this->translator->trans('mautic.contactclient.graph.'.$type), $data); break; } } } return $chart->render(); }
php
public function getStats( ContactClient $contactClient, $unit, \DateTime $dateFrom = null, \DateTime $dateTo = null, $campaignId = null, $dateFormat = null, $canViewOthers = true ) { $query = new ChartQuery($this->em->getConnection(), $dateFrom, $dateTo, $unit); $unit = (null === $unit) ? $this->getTimeUnitFromDateRange($dateFrom, $dateTo) : $unit; $chart = new LineChart($unit, $dateFrom, $dateTo, $dateFormat); $stat = new Stat(); $params = ['contactclient_id' => $contactClient->getId()]; if ($campaignId) { $params['campaign_id'] = $campaignId; } foreach ($stat->getAllTypes() as $type) { $params['type'] = $type; $q = $query->prepareTimeDataQuery( 'contactclient_stats', 'date_added', $params ); if (!in_array($unit, ['H', 'i', 's'])) { // For some reason, Mautic only sets UTC in Query Date builder // if its an intra-day date range ¯\_(ツ)_/¯ // so we have to do it here. $userTZ = new \DateTime('now'); $userTzName = $userTZ->getTimezone()->getName(); $paramDateTo = $q->getParameter('dateTo'); $paramDateFrom = $q->getParameter('dateFrom'); $paramDateTo = new \DateTime($paramDateTo); $paramDateTo->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateTo', $paramDateTo->format('Y-m-d H:i:s')); $paramDateFrom = new \DateTime($paramDateFrom); $paramDateFrom->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateFrom', $paramDateFrom->format('Y-m-d H:i:s')); $select = $q->getQueryPart('select')[0]; $newSelect = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $select ); $q->resetQueryPart('select'); $q->select($newSelect); // AND adjust the group By, since its using db timezone Date values $groupBy = $q->getQueryPart('groupBy')[0]; $newGroupBy = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $groupBy ); $q->resetQueryPart('groupBy'); $q->groupBy($newGroupBy); } if (!$canViewOthers) { $this->limitQueryToCreator($q); } $data = $query->loadAndBuildTimeData($q); foreach ($data as $val) { if (0 !== $val) { $chart->setDataset($this->translator->trans('mautic.contactclient.graph.'.$type), $data); break; } } } return $chart->render(); }
[ "public", "function", "getStats", "(", "ContactClient", "$", "contactClient", ",", "$", "unit", ",", "\\", "DateTime", "$", "dateFrom", "=", "null", ",", "\\", "DateTime", "$", "dateTo", "=", "null", ",", "$", "campaignId", "=", "null", ",", "$", "dateFormat", "=", "null", ",", "$", "canViewOthers", "=", "true", ")", "{", "$", "query", "=", "new", "ChartQuery", "(", "$", "this", "->", "em", "->", "getConnection", "(", ")", ",", "$", "dateFrom", ",", "$", "dateTo", ",", "$", "unit", ")", ";", "$", "unit", "=", "(", "null", "===", "$", "unit", ")", "?", "$", "this", "->", "getTimeUnitFromDateRange", "(", "$", "dateFrom", ",", "$", "dateTo", ")", ":", "$", "unit", ";", "$", "chart", "=", "new", "LineChart", "(", "$", "unit", ",", "$", "dateFrom", ",", "$", "dateTo", ",", "$", "dateFormat", ")", ";", "$", "stat", "=", "new", "Stat", "(", ")", ";", "$", "params", "=", "[", "'contactclient_id'", "=>", "$", "contactClient", "->", "getId", "(", ")", "]", ";", "if", "(", "$", "campaignId", ")", "{", "$", "params", "[", "'campaign_id'", "]", "=", "$", "campaignId", ";", "}", "foreach", "(", "$", "stat", "->", "getAllTypes", "(", ")", "as", "$", "type", ")", "{", "$", "params", "[", "'type'", "]", "=", "$", "type", ";", "$", "q", "=", "$", "query", "->", "prepareTimeDataQuery", "(", "'contactclient_stats'", ",", "'date_added'", ",", "$", "params", ")", ";", "if", "(", "!", "in_array", "(", "$", "unit", ",", "[", "'H'", ",", "'i'", ",", "'s'", "]", ")", ")", "{", "// For some reason, Mautic only sets UTC in Query Date builder", "// if its an intra-day date range ¯\\_(ツ)_/¯", "// so we have to do it here.", "$", "userTZ", "=", "new", "\\", "DateTime", "(", "'now'", ")", ";", "$", "userTzName", "=", "$", "userTZ", "->", "getTimezone", "(", ")", "->", "getName", "(", ")", ";", "$", "paramDateTo", "=", "$", "q", "->", "getParameter", "(", "'dateTo'", ")", ";", "$", "paramDateFrom", "=", "$", "q", "->", "getParameter", "(", "'dateFrom'", ")", ";", "$", "paramDateTo", "=", "new", "\\", "DateTime", "(", "$", "paramDateTo", ")", ";", "$", "paramDateTo", "->", "setTimeZone", "(", "new", "\\", "DateTimeZone", "(", "'UTC'", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'dateTo'", ",", "$", "paramDateTo", "->", "format", "(", "'Y-m-d H:i:s'", ")", ")", ";", "$", "paramDateFrom", "=", "new", "\\", "DateTime", "(", "$", "paramDateFrom", ")", ";", "$", "paramDateFrom", "->", "setTimeZone", "(", "new", "\\", "DateTimeZone", "(", "'UTC'", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'dateFrom'", ",", "$", "paramDateFrom", "->", "format", "(", "'Y-m-d H:i:s'", ")", ")", ";", "$", "select", "=", "$", "q", "->", "getQueryPart", "(", "'select'", ")", "[", "0", "]", ";", "$", "newSelect", "=", "str_replace", "(", "'t.date_added,'", ",", "\"CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),\"", ",", "$", "select", ")", ";", "$", "q", "->", "resetQueryPart", "(", "'select'", ")", ";", "$", "q", "->", "select", "(", "$", "newSelect", ")", ";", "// AND adjust the group By, since its using db timezone Date values", "$", "groupBy", "=", "$", "q", "->", "getQueryPart", "(", "'groupBy'", ")", "[", "0", "]", ";", "$", "newGroupBy", "=", "str_replace", "(", "'t.date_added,'", ",", "\"CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),\"", ",", "$", "groupBy", ")", ";", "$", "q", "->", "resetQueryPart", "(", "'groupBy'", ")", ";", "$", "q", "->", "groupBy", "(", "$", "newGroupBy", ")", ";", "}", "if", "(", "!", "$", "canViewOthers", ")", "{", "$", "this", "->", "limitQueryToCreator", "(", "$", "q", ")", ";", "}", "$", "data", "=", "$", "query", "->", "loadAndBuildTimeData", "(", "$", "q", ")", ";", "foreach", "(", "$", "data", "as", "$", "val", ")", "{", "if", "(", "0", "!==", "$", "val", ")", "{", "$", "chart", "->", "setDataset", "(", "$", "this", "->", "translator", "->", "trans", "(", "'mautic.contactclient.graph.'", ".", "$", "type", ")", ",", "$", "data", ")", ";", "break", ";", "}", "}", "}", "return", "$", "chart", "->", "render", "(", ")", ";", "}" ]
@param ContactClient $contactClient @param $unit @param \DateTime|null $dateFrom @param \DateTime|null $dateTo @param null $campaignId @param null $dateFormat @param bool $canViewOthers @return array
[ "@param", "ContactClient", "$contactClient", "@param", "$unit", "@param", "\\", "DateTime|null", "$dateFrom", "@param", "\\", "DateTime|null", "$dateTo", "@param", "null", "$campaignId", "@param", "null", "$dateFormat", "@param", "bool", "$canViewOthers" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L291-L367
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.getTimeUnitFromDateRange
public function getTimeUnitFromDateRange($dateFrom, $dateTo) { $dayDiff = $dateTo->diff($dateFrom)->format('%a'); $unit = 'd'; if ($dayDiff <= 1) { $unit = 'H'; $sameDay = $dateTo->format('d') == $dateFrom->format('d') ? 1 : 0; $hourDiff = $dateTo->diff($dateFrom)->format('%h'); $minuteDiff = $dateTo->diff($dateFrom)->format('%i'); if ($sameDay && !intval($hourDiff) && intval($minuteDiff)) { $unit = 'i'; } $secondDiff = $dateTo->diff($dateFrom)->format('%s'); if (!intval($minuteDiff) && intval($secondDiff)) { $unit = 'm'; } } if ($dayDiff > 31) { $unit = 'W'; } if ($dayDiff > 63) { $unit = 'm'; } if ($dayDiff > 1000) { $unit = 'Y'; } return $unit; }
php
public function getTimeUnitFromDateRange($dateFrom, $dateTo) { $dayDiff = $dateTo->diff($dateFrom)->format('%a'); $unit = 'd'; if ($dayDiff <= 1) { $unit = 'H'; $sameDay = $dateTo->format('d') == $dateFrom->format('d') ? 1 : 0; $hourDiff = $dateTo->diff($dateFrom)->format('%h'); $minuteDiff = $dateTo->diff($dateFrom)->format('%i'); if ($sameDay && !intval($hourDiff) && intval($minuteDiff)) { $unit = 'i'; } $secondDiff = $dateTo->diff($dateFrom)->format('%s'); if (!intval($minuteDiff) && intval($secondDiff)) { $unit = 'm'; } } if ($dayDiff > 31) { $unit = 'W'; } if ($dayDiff > 63) { $unit = 'm'; } if ($dayDiff > 1000) { $unit = 'Y'; } return $unit; }
[ "public", "function", "getTimeUnitFromDateRange", "(", "$", "dateFrom", ",", "$", "dateTo", ")", "{", "$", "dayDiff", "=", "$", "dateTo", "->", "diff", "(", "$", "dateFrom", ")", "->", "format", "(", "'%a'", ")", ";", "$", "unit", "=", "'d'", ";", "if", "(", "$", "dayDiff", "<=", "1", ")", "{", "$", "unit", "=", "'H'", ";", "$", "sameDay", "=", "$", "dateTo", "->", "format", "(", "'d'", ")", "==", "$", "dateFrom", "->", "format", "(", "'d'", ")", "?", "1", ":", "0", ";", "$", "hourDiff", "=", "$", "dateTo", "->", "diff", "(", "$", "dateFrom", ")", "->", "format", "(", "'%h'", ")", ";", "$", "minuteDiff", "=", "$", "dateTo", "->", "diff", "(", "$", "dateFrom", ")", "->", "format", "(", "'%i'", ")", ";", "if", "(", "$", "sameDay", "&&", "!", "intval", "(", "$", "hourDiff", ")", "&&", "intval", "(", "$", "minuteDiff", ")", ")", "{", "$", "unit", "=", "'i'", ";", "}", "$", "secondDiff", "=", "$", "dateTo", "->", "diff", "(", "$", "dateFrom", ")", "->", "format", "(", "'%s'", ")", ";", "if", "(", "!", "intval", "(", "$", "minuteDiff", ")", "&&", "intval", "(", "$", "secondDiff", ")", ")", "{", "$", "unit", "=", "'m'", ";", "}", "}", "if", "(", "$", "dayDiff", ">", "31", ")", "{", "$", "unit", "=", "'W'", ";", "}", "if", "(", "$", "dayDiff", ">", "63", ")", "{", "$", "unit", "=", "'m'", ";", "}", "if", "(", "$", "dayDiff", ">", "1000", ")", "{", "$", "unit", "=", "'Y'", ";", "}", "return", "$", "unit", ";", "}" ]
Returns appropriate time unit from a date range so the line/bar charts won't be too full/empty. @param $dateFrom @param $dateTo @return string
[ "Returns", "appropriate", "time", "unit", "from", "a", "date", "range", "so", "the", "line", "/", "bar", "charts", "won", "t", "be", "too", "full", "/", "empty", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L377-L407
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.limitQueryToCreator
public function limitQueryToCreator(QueryBuilder $q) { $q->join('t', MAUTIC_TABLE_PREFIX.'contactclient', 'm', 'e.id = t.contactclient_id') ->andWhere('m.created_by = :userId') ->setParameter('userId', $this->userHelper->getUser()->getId()); }
php
public function limitQueryToCreator(QueryBuilder $q) { $q->join('t', MAUTIC_TABLE_PREFIX.'contactclient', 'm', 'e.id = t.contactclient_id') ->andWhere('m.created_by = :userId') ->setParameter('userId', $this->userHelper->getUser()->getId()); }
[ "public", "function", "limitQueryToCreator", "(", "QueryBuilder", "$", "q", ")", "{", "$", "q", "->", "join", "(", "'t'", ",", "MAUTIC_TABLE_PREFIX", ".", "'contactclient'", ",", "'m'", ",", "'e.id = t.contactclient_id'", ")", "->", "andWhere", "(", "'m.created_by = :userId'", ")", "->", "setParameter", "(", "'userId'", ",", "$", "this", "->", "userHelper", "->", "getUser", "(", ")", "->", "getId", "(", ")", ")", ";", "}" ]
Joins the email table and limits created_by to currently logged in user. @param QueryBuilder $q
[ "Joins", "the", "email", "table", "and", "limits", "created_by", "to", "currently", "logged", "in", "user", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L414-L419
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.getStatsBySource
public function getStatsBySource( ContactClient $contactClient, $unit, $type, \DateTime $dateFrom = null, \DateTime $dateTo = null, $campaignId = null, $dateFormat = null, $canViewOthers = true ) { $unit = (null === $unit) ? $this->getTimeUnitFromDateRange($dateFrom, $dateTo) : $unit; $dateToAdjusted = clone $dateTo; $dateToAdjusted->setTime(23, 59, 59); $chart = new LineChart($unit, $dateFrom, $dateToAdjusted, $dateFormat); $query = new ChartQuery($this->em->getConnection(), $dateFrom, $dateToAdjusted, $unit); $utmSources = $this->getStatRepository()->getSourcesByClient( $contactClient->getId(), $dateFrom, $dateToAdjusted, $type ); //if (isset($campaignId)) { if (!empty($campaignId)) { $params['campaign_id'] = (int) $campaignId; } $params['contactclient_id'] = $contactClient->getId(); $userTZ = new \DateTime('now'); $userTzName = $userTZ->getTimezone()->getName(); if ('revenue' != $type) { $params['type'] = $type; foreach ($utmSources as $utmSource) { $params['utm_source'] = empty($utmSource) ? ['expression' => 'isNull'] : $utmSource; $q = $query->prepareTimeDataQuery( 'contactclient_stats', 'date_added', $params ); if (!in_array($unit, ['H', 'i', 's'])) { // For some reason, Mautic only sets UTC in Query Date builder // if its an intra-day date range ¯\_(ツ)_/¯ // so we have to do it here. $paramDateTo = $q->getParameter('dateTo'); $paramDateFrom = $q->getParameter('dateFrom'); $paramDateTo = new \DateTime($paramDateTo); $paramDateTo->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateTo', $paramDateTo->format('Y-m-d H:i:s')); $paramDateFrom = new \DateTime($paramDateFrom); $paramDateFrom->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateFrom', $paramDateFrom->format('Y-m-d H:i:s')); $select = $q->getQueryPart('select')[0]; $newSelect = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $select ); $q->resetQueryPart('select'); $q->select($newSelect); // AND adjust the group By, since its using db timezone Date values $groupBy = $q->getQueryPart('groupBy')[0]; $newGroupBy = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $groupBy ); $q->resetQueryPart('groupBy'); $q->groupBy($newGroupBy); } if (!$canViewOthers) { $this->limitQueryToCreator($q); } $data = $query->loadAndBuildTimeData($q); foreach ($data as $val) { if (0 !== $val) { if (empty($utmSource)) { $utmSource = 'No Source'; } $chart->setDataset($utmSource, $data); break; } } } } else { $params['type'] = Stat::TYPE_CONVERTED; // Add attribution to the chart. $q = $query->prepareTimeDataQuery( 'contactclient_stats', 'date_added', $params ); if (!$canViewOthers) { $this->limitQueryToCreator($q); } $dbUnit = $query->getTimeUnitFromDateRange($dateFrom, $dateTo); $dbUnit = $query->translateTimeUnit($dbUnit); $dateConstruct = "DATE_FORMAT(CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'), '$dbUnit.')"; foreach ($utmSources as $utmSource) { $q->select($dateConstruct.' AS date, ROUND(SUM(t.attribution), 2) AS count') ->groupBy($dateConstruct); if (empty($utmSource)) { // utmSource can be a NULL value $q->andWhere('utm_source IS NULL'); } else { $q->andWhere('utm_source = :utmSource') ->setParameter('utmSource', $utmSource); } $data = $query->loadAndBuildTimeData($q); foreach ($data as $val) { if (0 !== $val) { if (empty($utmSource)) { $utmSource = 'No Source'; } $chart->setDataset($utmSource, $data); break; } } } } return $chart->render(); }
php
public function getStatsBySource( ContactClient $contactClient, $unit, $type, \DateTime $dateFrom = null, \DateTime $dateTo = null, $campaignId = null, $dateFormat = null, $canViewOthers = true ) { $unit = (null === $unit) ? $this->getTimeUnitFromDateRange($dateFrom, $dateTo) : $unit; $dateToAdjusted = clone $dateTo; $dateToAdjusted->setTime(23, 59, 59); $chart = new LineChart($unit, $dateFrom, $dateToAdjusted, $dateFormat); $query = new ChartQuery($this->em->getConnection(), $dateFrom, $dateToAdjusted, $unit); $utmSources = $this->getStatRepository()->getSourcesByClient( $contactClient->getId(), $dateFrom, $dateToAdjusted, $type ); //if (isset($campaignId)) { if (!empty($campaignId)) { $params['campaign_id'] = (int) $campaignId; } $params['contactclient_id'] = $contactClient->getId(); $userTZ = new \DateTime('now'); $userTzName = $userTZ->getTimezone()->getName(); if ('revenue' != $type) { $params['type'] = $type; foreach ($utmSources as $utmSource) { $params['utm_source'] = empty($utmSource) ? ['expression' => 'isNull'] : $utmSource; $q = $query->prepareTimeDataQuery( 'contactclient_stats', 'date_added', $params ); if (!in_array($unit, ['H', 'i', 's'])) { // For some reason, Mautic only sets UTC in Query Date builder // if its an intra-day date range ¯\_(ツ)_/¯ // so we have to do it here. $paramDateTo = $q->getParameter('dateTo'); $paramDateFrom = $q->getParameter('dateFrom'); $paramDateTo = new \DateTime($paramDateTo); $paramDateTo->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateTo', $paramDateTo->format('Y-m-d H:i:s')); $paramDateFrom = new \DateTime($paramDateFrom); $paramDateFrom->setTimeZone(new \DateTimeZone('UTC')); $q->setParameter('dateFrom', $paramDateFrom->format('Y-m-d H:i:s')); $select = $q->getQueryPart('select')[0]; $newSelect = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $select ); $q->resetQueryPart('select'); $q->select($newSelect); // AND adjust the group By, since its using db timezone Date values $groupBy = $q->getQueryPart('groupBy')[0]; $newGroupBy = str_replace( 't.date_added,', "CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),", $groupBy ); $q->resetQueryPart('groupBy'); $q->groupBy($newGroupBy); } if (!$canViewOthers) { $this->limitQueryToCreator($q); } $data = $query->loadAndBuildTimeData($q); foreach ($data as $val) { if (0 !== $val) { if (empty($utmSource)) { $utmSource = 'No Source'; } $chart->setDataset($utmSource, $data); break; } } } } else { $params['type'] = Stat::TYPE_CONVERTED; // Add attribution to the chart. $q = $query->prepareTimeDataQuery( 'contactclient_stats', 'date_added', $params ); if (!$canViewOthers) { $this->limitQueryToCreator($q); } $dbUnit = $query->getTimeUnitFromDateRange($dateFrom, $dateTo); $dbUnit = $query->translateTimeUnit($dbUnit); $dateConstruct = "DATE_FORMAT(CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'), '$dbUnit.')"; foreach ($utmSources as $utmSource) { $q->select($dateConstruct.' AS date, ROUND(SUM(t.attribution), 2) AS count') ->groupBy($dateConstruct); if (empty($utmSource)) { // utmSource can be a NULL value $q->andWhere('utm_source IS NULL'); } else { $q->andWhere('utm_source = :utmSource') ->setParameter('utmSource', $utmSource); } $data = $query->loadAndBuildTimeData($q); foreach ($data as $val) { if (0 !== $val) { if (empty($utmSource)) { $utmSource = 'No Source'; } $chart->setDataset($utmSource, $data); break; } } } } return $chart->render(); }
[ "public", "function", "getStatsBySource", "(", "ContactClient", "$", "contactClient", ",", "$", "unit", ",", "$", "type", ",", "\\", "DateTime", "$", "dateFrom", "=", "null", ",", "\\", "DateTime", "$", "dateTo", "=", "null", ",", "$", "campaignId", "=", "null", ",", "$", "dateFormat", "=", "null", ",", "$", "canViewOthers", "=", "true", ")", "{", "$", "unit", "=", "(", "null", "===", "$", "unit", ")", "?", "$", "this", "->", "getTimeUnitFromDateRange", "(", "$", "dateFrom", ",", "$", "dateTo", ")", ":", "$", "unit", ";", "$", "dateToAdjusted", "=", "clone", "$", "dateTo", ";", "$", "dateToAdjusted", "->", "setTime", "(", "23", ",", "59", ",", "59", ")", ";", "$", "chart", "=", "new", "LineChart", "(", "$", "unit", ",", "$", "dateFrom", ",", "$", "dateToAdjusted", ",", "$", "dateFormat", ")", ";", "$", "query", "=", "new", "ChartQuery", "(", "$", "this", "->", "em", "->", "getConnection", "(", ")", ",", "$", "dateFrom", ",", "$", "dateToAdjusted", ",", "$", "unit", ")", ";", "$", "utmSources", "=", "$", "this", "->", "getStatRepository", "(", ")", "->", "getSourcesByClient", "(", "$", "contactClient", "->", "getId", "(", ")", ",", "$", "dateFrom", ",", "$", "dateToAdjusted", ",", "$", "type", ")", ";", "//if (isset($campaignId)) {", "if", "(", "!", "empty", "(", "$", "campaignId", ")", ")", "{", "$", "params", "[", "'campaign_id'", "]", "=", "(", "int", ")", "$", "campaignId", ";", "}", "$", "params", "[", "'contactclient_id'", "]", "=", "$", "contactClient", "->", "getId", "(", ")", ";", "$", "userTZ", "=", "new", "\\", "DateTime", "(", "'now'", ")", ";", "$", "userTzName", "=", "$", "userTZ", "->", "getTimezone", "(", ")", "->", "getName", "(", ")", ";", "if", "(", "'revenue'", "!=", "$", "type", ")", "{", "$", "params", "[", "'type'", "]", "=", "$", "type", ";", "foreach", "(", "$", "utmSources", "as", "$", "utmSource", ")", "{", "$", "params", "[", "'utm_source'", "]", "=", "empty", "(", "$", "utmSource", ")", "?", "[", "'expression'", "=>", "'isNull'", "]", ":", "$", "utmSource", ";", "$", "q", "=", "$", "query", "->", "prepareTimeDataQuery", "(", "'contactclient_stats'", ",", "'date_added'", ",", "$", "params", ")", ";", "if", "(", "!", "in_array", "(", "$", "unit", ",", "[", "'H'", ",", "'i'", ",", "'s'", "]", ")", ")", "{", "// For some reason, Mautic only sets UTC in Query Date builder", "// if its an intra-day date range ¯\\_(ツ)_/¯", "// so we have to do it here.", "$", "paramDateTo", "=", "$", "q", "->", "getParameter", "(", "'dateTo'", ")", ";", "$", "paramDateFrom", "=", "$", "q", "->", "getParameter", "(", "'dateFrom'", ")", ";", "$", "paramDateTo", "=", "new", "\\", "DateTime", "(", "$", "paramDateTo", ")", ";", "$", "paramDateTo", "->", "setTimeZone", "(", "new", "\\", "DateTimeZone", "(", "'UTC'", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'dateTo'", ",", "$", "paramDateTo", "->", "format", "(", "'Y-m-d H:i:s'", ")", ")", ";", "$", "paramDateFrom", "=", "new", "\\", "DateTime", "(", "$", "paramDateFrom", ")", ";", "$", "paramDateFrom", "->", "setTimeZone", "(", "new", "\\", "DateTimeZone", "(", "'UTC'", ")", ")", ";", "$", "q", "->", "setParameter", "(", "'dateFrom'", ",", "$", "paramDateFrom", "->", "format", "(", "'Y-m-d H:i:s'", ")", ")", ";", "$", "select", "=", "$", "q", "->", "getQueryPart", "(", "'select'", ")", "[", "0", "]", ";", "$", "newSelect", "=", "str_replace", "(", "'t.date_added,'", ",", "\"CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),\"", ",", "$", "select", ")", ";", "$", "q", "->", "resetQueryPart", "(", "'select'", ")", ";", "$", "q", "->", "select", "(", "$", "newSelect", ")", ";", "// AND adjust the group By, since its using db timezone Date values", "$", "groupBy", "=", "$", "q", "->", "getQueryPart", "(", "'groupBy'", ")", "[", "0", "]", ";", "$", "newGroupBy", "=", "str_replace", "(", "'t.date_added,'", ",", "\"CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'),\"", ",", "$", "groupBy", ")", ";", "$", "q", "->", "resetQueryPart", "(", "'groupBy'", ")", ";", "$", "q", "->", "groupBy", "(", "$", "newGroupBy", ")", ";", "}", "if", "(", "!", "$", "canViewOthers", ")", "{", "$", "this", "->", "limitQueryToCreator", "(", "$", "q", ")", ";", "}", "$", "data", "=", "$", "query", "->", "loadAndBuildTimeData", "(", "$", "q", ")", ";", "foreach", "(", "$", "data", "as", "$", "val", ")", "{", "if", "(", "0", "!==", "$", "val", ")", "{", "if", "(", "empty", "(", "$", "utmSource", ")", ")", "{", "$", "utmSource", "=", "'No Source'", ";", "}", "$", "chart", "->", "setDataset", "(", "$", "utmSource", ",", "$", "data", ")", ";", "break", ";", "}", "}", "}", "}", "else", "{", "$", "params", "[", "'type'", "]", "=", "Stat", "::", "TYPE_CONVERTED", ";", "// Add attribution to the chart.", "$", "q", "=", "$", "query", "->", "prepareTimeDataQuery", "(", "'contactclient_stats'", ",", "'date_added'", ",", "$", "params", ")", ";", "if", "(", "!", "$", "canViewOthers", ")", "{", "$", "this", "->", "limitQueryToCreator", "(", "$", "q", ")", ";", "}", "$", "dbUnit", "=", "$", "query", "->", "getTimeUnitFromDateRange", "(", "$", "dateFrom", ",", "$", "dateTo", ")", ";", "$", "dbUnit", "=", "$", "query", "->", "translateTimeUnit", "(", "$", "dbUnit", ")", ";", "$", "dateConstruct", "=", "\"DATE_FORMAT(CONVERT_TZ(t.date_added, @@global.time_zone, '$userTzName'), '$dbUnit.')\"", ";", "foreach", "(", "$", "utmSources", "as", "$", "utmSource", ")", "{", "$", "q", "->", "select", "(", "$", "dateConstruct", ".", "' AS date, ROUND(SUM(t.attribution), 2) AS count'", ")", "->", "groupBy", "(", "$", "dateConstruct", ")", ";", "if", "(", "empty", "(", "$", "utmSource", ")", ")", "{", "// utmSource can be a NULL value", "$", "q", "->", "andWhere", "(", "'utm_source IS NULL'", ")", ";", "}", "else", "{", "$", "q", "->", "andWhere", "(", "'utm_source = :utmSource'", ")", "->", "setParameter", "(", "'utmSource'", ",", "$", "utmSource", ")", ";", "}", "$", "data", "=", "$", "query", "->", "loadAndBuildTimeData", "(", "$", "q", ")", ";", "foreach", "(", "$", "data", "as", "$", "val", ")", "{", "if", "(", "0", "!==", "$", "val", ")", "{", "if", "(", "empty", "(", "$", "utmSource", ")", ")", "{", "$", "utmSource", "=", "'No Source'", ";", "}", "$", "chart", "->", "setDataset", "(", "$", "utmSource", ",", "$", "data", ")", ";", "break", ";", "}", "}", "}", "}", "return", "$", "chart", "->", "render", "(", ")", ";", "}" ]
@param ContactClient $contactClient @param $unit @param $type @param \DateTime|null $dateFrom @param \DateTime|null $dateTo @param null $campaignId @param null $dateFormat @param bool $canViewOthers @return array
[ "@param", "ContactClient", "$contactClient", "@param", "$unit", "@param", "$type", "@param", "\\", "DateTime|null", "$dateFrom", "@param", "\\", "DateTime|null", "$dateTo", "@param", "null", "$campaignId", "@param", "null", "$dateFormat", "@param", "bool", "$canViewOthers" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L433-L558
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.getFiles
public function getFiles( ContactClient $contactClient, array $filters = [], array $orderBy = [], $page = 1, $limit = 25 ) { $args = array_merge($filters, $orderBy); $args['page'] = $page; $args['limit'] = $limit; /** @var \MauticPlugin\MauticContactClientBundle\Entity\FileRepository $repo */ $repo = $this->em->getRepository('MauticContactClientBundle:File'); return $repo->getEntities($args); }
php
public function getFiles( ContactClient $contactClient, array $filters = [], array $orderBy = [], $page = 1, $limit = 25 ) { $args = array_merge($filters, $orderBy); $args['page'] = $page; $args['limit'] = $limit; /** @var \MauticPlugin\MauticContactClientBundle\Entity\FileRepository $repo */ $repo = $this->em->getRepository('MauticContactClientBundle:File'); return $repo->getEntities($args); }
[ "public", "function", "getFiles", "(", "ContactClient", "$", "contactClient", ",", "array", "$", "filters", "=", "[", "]", ",", "array", "$", "orderBy", "=", "[", "]", ",", "$", "page", "=", "1", ",", "$", "limit", "=", "25", ")", "{", "$", "args", "=", "array_merge", "(", "$", "filters", ",", "$", "orderBy", ")", ";", "$", "args", "[", "'page'", "]", "=", "$", "page", ";", "$", "args", "[", "'limit'", "]", "=", "$", "limit", ";", "/** @var \\MauticPlugin\\MauticContactClientBundle\\Entity\\FileRepository $repo */", "$", "repo", "=", "$", "this", "->", "em", "->", "getRepository", "(", "'MauticContactClientBundle:File'", ")", ";", "return", "$", "repo", "->", "getEntities", "(", "$", "args", ")", ";", "}" ]
@param ContactClient $contactClient @param array $filters @param array $orderBy @param int $page @param int $limit @return array|\Doctrine\ORM\Internal\Hydration\IterableResult|\Doctrine\ORM\Tools\Pagination\Paginator
[ "@param", "ContactClient", "$contactClient", "@param", "array", "$filters", "@param", "array", "$orderBy", "@param", "int", "$page", "@param", "int", "$limit" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L569-L584
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.getEngagements
public function getEngagements( ContactClient $contactClient, $filters = [], $orderBy = [], $page = 1, $limit = 25, $forTimeline = true ) { /** @var \MauticPlugin\MauticContactClientBundle\Event\ContactClientTimelineEvent $event */ $event = $this->dispatcher->dispatch( ContactClientEvents::TIMELINE_ON_GENERATE, new ContactClientTimelineEvent( $contactClient, $filters, $orderBy, $page, $limit, $forTimeline, $this->coreParametersHelper->getParameter('site_url') ) ); return $event; }
php
public function getEngagements( ContactClient $contactClient, $filters = [], $orderBy = [], $page = 1, $limit = 25, $forTimeline = true ) { /** @var \MauticPlugin\MauticContactClientBundle\Event\ContactClientTimelineEvent $event */ $event = $this->dispatcher->dispatch( ContactClientEvents::TIMELINE_ON_GENERATE, new ContactClientTimelineEvent( $contactClient, $filters, $orderBy, $page, $limit, $forTimeline, $this->coreParametersHelper->getParameter('site_url') ) ); return $event; }
[ "public", "function", "getEngagements", "(", "ContactClient", "$", "contactClient", ",", "$", "filters", "=", "[", "]", ",", "$", "orderBy", "=", "[", "]", ",", "$", "page", "=", "1", ",", "$", "limit", "=", "25", ",", "$", "forTimeline", "=", "true", ")", "{", "/** @var \\MauticPlugin\\MauticContactClientBundle\\Event\\ContactClientTimelineEvent $event */", "$", "event", "=", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "ContactClientEvents", "::", "TIMELINE_ON_GENERATE", ",", "new", "ContactClientTimelineEvent", "(", "$", "contactClient", ",", "$", "filters", ",", "$", "orderBy", ",", "$", "page", ",", "$", "limit", ",", "$", "forTimeline", ",", "$", "this", "->", "coreParametersHelper", "->", "getParameter", "(", "'site_url'", ")", ")", ")", ";", "return", "$", "event", ";", "}" ]
Get timeline/engagement data. @param ContactClient|null $contactClient @param array $filters @param array $orderBy @param int $page @param int $limit @param bool $forTimeline @return array
[ "Get", "timeline", "/", "engagement", "data", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L598-L621
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.getEngagementCount
public function getEngagementCount( ContactClient $contactClient, \DateTime $dateFrom = null, \DateTime $dateTo = null, $unit = 'm', ChartQuery $chartQuery = null ) { $event = new ContactClientTimelineEvent($contactClient); $event->setCountOnly($dateFrom, $dateTo, $unit, $chartQuery); $this->dispatcher->dispatch(ContactClientEvents::TIMELINE_ON_GENERATE, $event); return $event->getEventCounter(); }
php
public function getEngagementCount( ContactClient $contactClient, \DateTime $dateFrom = null, \DateTime $dateTo = null, $unit = 'm', ChartQuery $chartQuery = null ) { $event = new ContactClientTimelineEvent($contactClient); $event->setCountOnly($dateFrom, $dateTo, $unit, $chartQuery); $this->dispatcher->dispatch(ContactClientEvents::TIMELINE_ON_GENERATE, $event); return $event->getEventCounter(); }
[ "public", "function", "getEngagementCount", "(", "ContactClient", "$", "contactClient", ",", "\\", "DateTime", "$", "dateFrom", "=", "null", ",", "\\", "DateTime", "$", "dateTo", "=", "null", ",", "$", "unit", "=", "'m'", ",", "ChartQuery", "$", "chartQuery", "=", "null", ")", "{", "$", "event", "=", "new", "ContactClientTimelineEvent", "(", "$", "contactClient", ")", ";", "$", "event", "->", "setCountOnly", "(", "$", "dateFrom", ",", "$", "dateTo", ",", "$", "unit", ",", "$", "chartQuery", ")", ";", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "ContactClientEvents", "::", "TIMELINE_ON_GENERATE", ",", "$", "event", ")", ";", "return", "$", "event", "->", "getEventCounter", "(", ")", ";", "}" ]
Get engagement counts by time unit. @param ContactClient $contactClient @param \DateTime|null $dateFrom @param \DateTime|null $dateTo @param string $unit @param ChartQuery|null $chartQuery @return array
[ "Get", "engagement", "counts", "by", "time", "unit", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L647-L660
TheDMSGroup/mautic-contact-client
Model/ContactClientModel.php
ContactClientModel.dispatchEvent
protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null) { if (!$entity instanceof ContactClient) { throw new MethodNotAllowedHttpException(['ContactClient']); } switch ($action) { case 'pre_save': $name = ContactClientEvents::PRE_SAVE; break; case 'post_save': $name = ContactClientEvents::POST_SAVE; break; case 'pre_delete': $name = ContactClientEvents::PRE_DELETE; break; case 'post_delete': $name = ContactClientEvents::POST_DELETE; break; default: return null; } if ($this->dispatcher->hasListeners($name)) { if (empty($event)) { $event = new ContactClientEvent($entity, $isNew); $event->setEntityManager($this->em); } $this->dispatcher->dispatch($name, $event); return $event; } else { return null; } }
php
protected function dispatchEvent($action, &$entity, $isNew = false, Event $event = null) { if (!$entity instanceof ContactClient) { throw new MethodNotAllowedHttpException(['ContactClient']); } switch ($action) { case 'pre_save': $name = ContactClientEvents::PRE_SAVE; break; case 'post_save': $name = ContactClientEvents::POST_SAVE; break; case 'pre_delete': $name = ContactClientEvents::PRE_DELETE; break; case 'post_delete': $name = ContactClientEvents::POST_DELETE; break; default: return null; } if ($this->dispatcher->hasListeners($name)) { if (empty($event)) { $event = new ContactClientEvent($entity, $isNew); $event->setEntityManager($this->em); } $this->dispatcher->dispatch($name, $event); return $event; } else { return null; } }
[ "protected", "function", "dispatchEvent", "(", "$", "action", ",", "&", "$", "entity", ",", "$", "isNew", "=", "false", ",", "Event", "$", "event", "=", "null", ")", "{", "if", "(", "!", "$", "entity", "instanceof", "ContactClient", ")", "{", "throw", "new", "MethodNotAllowedHttpException", "(", "[", "'ContactClient'", "]", ")", ";", "}", "switch", "(", "$", "action", ")", "{", "case", "'pre_save'", ":", "$", "name", "=", "ContactClientEvents", "::", "PRE_SAVE", ";", "break", ";", "case", "'post_save'", ":", "$", "name", "=", "ContactClientEvents", "::", "POST_SAVE", ";", "break", ";", "case", "'pre_delete'", ":", "$", "name", "=", "ContactClientEvents", "::", "PRE_DELETE", ";", "break", ";", "case", "'post_delete'", ":", "$", "name", "=", "ContactClientEvents", "::", "POST_DELETE", ";", "break", ";", "default", ":", "return", "null", ";", "}", "if", "(", "$", "this", "->", "dispatcher", "->", "hasListeners", "(", "$", "name", ")", ")", "{", "if", "(", "empty", "(", "$", "event", ")", ")", "{", "$", "event", "=", "new", "ContactClientEvent", "(", "$", "entity", ",", "$", "isNew", ")", ";", "$", "event", "->", "setEntityManager", "(", "$", "this", "->", "em", ")", ";", "}", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "$", "name", ",", "$", "event", ")", ";", "return", "$", "event", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
{@inheritdoc} @return bool|ContactClientEvent @throws \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
[ "{", "@inheritdoc", "}" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ContactClientModel.php#L692-L727
TheDMSGroup/mautic-contact-client
Model/ApiPayloadOperation.php
ApiPayloadOperation.run
public function run() { if (empty($this->request)) { $this->setLogs('Skipping empty operation: '.$this->name, 'notice'); return true; } $this->setLogs($this->name, 'name'); $this->setLogs(($this->test ? 'TEST' : 'PROD'), 'mode'); // Send the API request. $apiRequest = new ApiRequest($this->request, $this->transport, $this->tokenHelper, $this->test); $apiRequest->send(); $this->setLogs($apiRequest->getLogs(), 'request'); // Parse the API response. $apiResponse = new ApiResponse( $this->responseExpected, $this->successDefinition, $this->transport, $this->test ); $this->responseActual = $apiResponse->parse()->getResponse(); $this->setLogs($apiResponse->getLogs(), 'response'); // Validate the API response with the given success definition. $valid = false; try { $valid = $apiResponse->validate(); } catch (\Exception $e) { } $this->setValid($valid); $this->setLogs($valid, 'valid'); if ($this->updatePayload && $this->test) { $this->updatePayloadResponse(); } // Allow any exception encountered during validation to bubble upward. if (!empty($e)) { throw $e; } return $this; }
php
public function run() { if (empty($this->request)) { $this->setLogs('Skipping empty operation: '.$this->name, 'notice'); return true; } $this->setLogs($this->name, 'name'); $this->setLogs(($this->test ? 'TEST' : 'PROD'), 'mode'); // Send the API request. $apiRequest = new ApiRequest($this->request, $this->transport, $this->tokenHelper, $this->test); $apiRequest->send(); $this->setLogs($apiRequest->getLogs(), 'request'); // Parse the API response. $apiResponse = new ApiResponse( $this->responseExpected, $this->successDefinition, $this->transport, $this->test ); $this->responseActual = $apiResponse->parse()->getResponse(); $this->setLogs($apiResponse->getLogs(), 'response'); // Validate the API response with the given success definition. $valid = false; try { $valid = $apiResponse->validate(); } catch (\Exception $e) { } $this->setValid($valid); $this->setLogs($valid, 'valid'); if ($this->updatePayload && $this->test) { $this->updatePayloadResponse(); } // Allow any exception encountered during validation to bubble upward. if (!empty($e)) { throw $e; } return $this; }
[ "public", "function", "run", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "request", ")", ")", "{", "$", "this", "->", "setLogs", "(", "'Skipping empty operation: '", ".", "$", "this", "->", "name", ",", "'notice'", ")", ";", "return", "true", ";", "}", "$", "this", "->", "setLogs", "(", "$", "this", "->", "name", ",", "'name'", ")", ";", "$", "this", "->", "setLogs", "(", "(", "$", "this", "->", "test", "?", "'TEST'", ":", "'PROD'", ")", ",", "'mode'", ")", ";", "// Send the API request.", "$", "apiRequest", "=", "new", "ApiRequest", "(", "$", "this", "->", "request", ",", "$", "this", "->", "transport", ",", "$", "this", "->", "tokenHelper", ",", "$", "this", "->", "test", ")", ";", "$", "apiRequest", "->", "send", "(", ")", ";", "$", "this", "->", "setLogs", "(", "$", "apiRequest", "->", "getLogs", "(", ")", ",", "'request'", ")", ";", "// Parse the API response.", "$", "apiResponse", "=", "new", "ApiResponse", "(", "$", "this", "->", "responseExpected", ",", "$", "this", "->", "successDefinition", ",", "$", "this", "->", "transport", ",", "$", "this", "->", "test", ")", ";", "$", "this", "->", "responseActual", "=", "$", "apiResponse", "->", "parse", "(", ")", "->", "getResponse", "(", ")", ";", "$", "this", "->", "setLogs", "(", "$", "apiResponse", "->", "getLogs", "(", ")", ",", "'response'", ")", ";", "// Validate the API response with the given success definition.", "$", "valid", "=", "false", ";", "try", "{", "$", "valid", "=", "$", "apiResponse", "->", "validate", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "}", "$", "this", "->", "setValid", "(", "$", "valid", ")", ";", "$", "this", "->", "setLogs", "(", "$", "valid", ",", "'valid'", ")", ";", "if", "(", "$", "this", "->", "updatePayload", "&&", "$", "this", "->", "test", ")", "{", "$", "this", "->", "updatePayloadResponse", "(", ")", ";", "}", "// Allow any exception encountered during validation to bubble upward.", "if", "(", "!", "empty", "(", "$", "e", ")", ")", "{", "throw", "$", "e", ";", "}", "return", "$", "this", ";", "}" ]
Run this single API Operation. @return $this|bool @throws \Exception
[ "Run", "this", "single", "API", "Operation", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadOperation.php#L120-L162
TheDMSGroup/mautic-contact-client
Model/ApiPayloadOperation.php
ApiPayloadOperation.updatePayloadResponse
public function updatePayloadResponse() { $result = $this->responseExpected; $updates = false; foreach (['headers', 'body'] as $type) { if (isset($this->responseActual[$type])) { $fieldKeys = []; foreach ($result->{$type} as $id => $value) { if (isset($value->key) && is_numeric($id)) { $fieldKeys[$value->key] = intval($id); } } foreach ($this->responseActual[$type] as $key => $value) { // Check if this type of response was not expected (headers / body). if (!isset($result->{$type})) { $result->{$type} = []; } // Check if header/body field is unexpected. $fieldId = isset($fieldKeys[$key]) ? $fieldKeys[$key] : -1; if ($fieldId == -1) { // This is a new field. $newField = new stdClass(); $newField->key = $key; $newField->example = $value; $result->{$type}[] = $newField; $this->setLogs('New '.$type.' field "'.$key.'" added with example: '.$value, 'autoUpdate'); $updates = true; } else { if (!empty($value)) { if (empty($result->{$type}[$fieldId]->example)) { // This is an existing field, but requires an updated example. $result->{$type}[$fieldId]->example = $value; $updates = true; $this->setLogs( 'Existing '.$type.' field '.$key.' now has an example: '.$value, 'autoUpdate' ); } else { if ($this->test && (!isset($result->{$type}[$fieldId]->example) || $result->{$type}[$fieldId]->example !== $value)) { // Updating our example because a test was run. $result->{$type}[$fieldId]->example = $value; $updates = true; $this->setLogs( 'Existing '.$type.' field '.$key.' has a new example: '.$value, 'autoUpdate' ); } } } } } } } // Check for auto format detection during a run. if ( $this->test && isset($this->responseActual['format']) && isset($result->format) && 'auto' == $result->format && 'auto' !== $this->responseActual['format'] ) { $updates = true; $result->format = $this->responseActual['format']; $this->setLogs( 'Response type has been automatically determined to be: '.$result->format, 'autoUpdate' ); } if ($updates) { $this->operation->response = $result; } }
php
public function updatePayloadResponse() { $result = $this->responseExpected; $updates = false; foreach (['headers', 'body'] as $type) { if (isset($this->responseActual[$type])) { $fieldKeys = []; foreach ($result->{$type} as $id => $value) { if (isset($value->key) && is_numeric($id)) { $fieldKeys[$value->key] = intval($id); } } foreach ($this->responseActual[$type] as $key => $value) { // Check if this type of response was not expected (headers / body). if (!isset($result->{$type})) { $result->{$type} = []; } // Check if header/body field is unexpected. $fieldId = isset($fieldKeys[$key]) ? $fieldKeys[$key] : -1; if ($fieldId == -1) { // This is a new field. $newField = new stdClass(); $newField->key = $key; $newField->example = $value; $result->{$type}[] = $newField; $this->setLogs('New '.$type.' field "'.$key.'" added with example: '.$value, 'autoUpdate'); $updates = true; } else { if (!empty($value)) { if (empty($result->{$type}[$fieldId]->example)) { // This is an existing field, but requires an updated example. $result->{$type}[$fieldId]->example = $value; $updates = true; $this->setLogs( 'Existing '.$type.' field '.$key.' now has an example: '.$value, 'autoUpdate' ); } else { if ($this->test && (!isset($result->{$type}[$fieldId]->example) || $result->{$type}[$fieldId]->example !== $value)) { // Updating our example because a test was run. $result->{$type}[$fieldId]->example = $value; $updates = true; $this->setLogs( 'Existing '.$type.' field '.$key.' has a new example: '.$value, 'autoUpdate' ); } } } } } } } // Check for auto format detection during a run. if ( $this->test && isset($this->responseActual['format']) && isset($result->format) && 'auto' == $result->format && 'auto' !== $this->responseActual['format'] ) { $updates = true; $result->format = $this->responseActual['format']; $this->setLogs( 'Response type has been automatically determined to be: '.$result->format, 'autoUpdate' ); } if ($updates) { $this->operation->response = $result; } }
[ "public", "function", "updatePayloadResponse", "(", ")", "{", "$", "result", "=", "$", "this", "->", "responseExpected", ";", "$", "updates", "=", "false", ";", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "responseActual", "[", "$", "type", "]", ")", ")", "{", "$", "fieldKeys", "=", "[", "]", ";", "foreach", "(", "$", "result", "->", "{", "$", "type", "}", "as", "$", "id", "=>", "$", "value", ")", "{", "if", "(", "isset", "(", "$", "value", "->", "key", ")", "&&", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "fieldKeys", "[", "$", "value", "->", "key", "]", "=", "intval", "(", "$", "id", ")", ";", "}", "}", "foreach", "(", "$", "this", "->", "responseActual", "[", "$", "type", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "// Check if this type of response was not expected (headers / body).", "if", "(", "!", "isset", "(", "$", "result", "->", "{", "$", "type", "}", ")", ")", "{", "$", "result", "->", "{", "$", "type", "}", "=", "[", "]", ";", "}", "// Check if header/body field is unexpected.", "$", "fieldId", "=", "isset", "(", "$", "fieldKeys", "[", "$", "key", "]", ")", "?", "$", "fieldKeys", "[", "$", "key", "]", ":", "-", "1", ";", "if", "(", "$", "fieldId", "==", "-", "1", ")", "{", "// This is a new field.", "$", "newField", "=", "new", "stdClass", "(", ")", ";", "$", "newField", "->", "key", "=", "$", "key", ";", "$", "newField", "->", "example", "=", "$", "value", ";", "$", "result", "->", "{", "$", "type", "}", "[", "]", "=", "$", "newField", ";", "$", "this", "->", "setLogs", "(", "'New '", ".", "$", "type", ".", "' field \"'", ".", "$", "key", ".", "'\" added with example: '", ".", "$", "value", ",", "'autoUpdate'", ")", ";", "$", "updates", "=", "true", ";", "}", "else", "{", "if", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "if", "(", "empty", "(", "$", "result", "->", "{", "$", "type", "}", "[", "$", "fieldId", "]", "->", "example", ")", ")", "{", "// This is an existing field, but requires an updated example.", "$", "result", "->", "{", "$", "type", "}", "[", "$", "fieldId", "]", "->", "example", "=", "$", "value", ";", "$", "updates", "=", "true", ";", "$", "this", "->", "setLogs", "(", "'Existing '", ".", "$", "type", ".", "' field '", ".", "$", "key", ".", "' now has an example: '", ".", "$", "value", ",", "'autoUpdate'", ")", ";", "}", "else", "{", "if", "(", "$", "this", "->", "test", "&&", "(", "!", "isset", "(", "$", "result", "->", "{", "$", "type", "}", "[", "$", "fieldId", "]", "->", "example", ")", "||", "$", "result", "->", "{", "$", "type", "}", "[", "$", "fieldId", "]", "->", "example", "!==", "$", "value", ")", ")", "{", "// Updating our example because a test was run.", "$", "result", "->", "{", "$", "type", "}", "[", "$", "fieldId", "]", "->", "example", "=", "$", "value", ";", "$", "updates", "=", "true", ";", "$", "this", "->", "setLogs", "(", "'Existing '", ".", "$", "type", ".", "' field '", ".", "$", "key", ".", "' has a new example: '", ".", "$", "value", ",", "'autoUpdate'", ")", ";", "}", "}", "}", "}", "}", "}", "}", "// Check for auto format detection during a run.", "if", "(", "$", "this", "->", "test", "&&", "isset", "(", "$", "this", "->", "responseActual", "[", "'format'", "]", ")", "&&", "isset", "(", "$", "result", "->", "format", ")", "&&", "'auto'", "==", "$", "result", "->", "format", "&&", "'auto'", "!==", "$", "this", "->", "responseActual", "[", "'format'", "]", ")", "{", "$", "updates", "=", "true", ";", "$", "result", "->", "format", "=", "$", "this", "->", "responseActual", "[", "'format'", "]", ";", "$", "this", "->", "setLogs", "(", "'Response type has been automatically determined to be: '", ".", "$", "result", "->", "format", ",", "'autoUpdate'", ")", ";", "}", "if", "(", "$", "updates", ")", "{", "$", "this", "->", "operation", "->", "response", "=", "$", "result", ";", "}", "}" ]
Automatically updates a response with filled in data from the parsed response object from the API.
[ "Automatically", "updates", "a", "response", "with", "filled", "in", "data", "from", "the", "parsed", "response", "object", "from", "the", "API", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadOperation.php#L167-L238
TheDMSGroup/mautic-contact-client
Model/ApiPayloadOperation.php
ApiPayloadOperation.getResponseMap
public function getResponseMap() { $mappedFields = []; foreach (['headers', 'body'] as $type) { if (isset($this->responseExpected->{$type}) && isset($this->responseActual[$type])) { foreach ($this->responseExpected->{$type} as $value) { if (!empty($value->destination) && !empty($value->key) && !empty($this->responseActual[$type][$value->key])) { // We have a non-empty value with a mapped destination. $mappedFields[$value->destination] = $this->responseActual[$type][$value->key]; } } } } return $mappedFields; }
php
public function getResponseMap() { $mappedFields = []; foreach (['headers', 'body'] as $type) { if (isset($this->responseExpected->{$type}) && isset($this->responseActual[$type])) { foreach ($this->responseExpected->{$type} as $value) { if (!empty($value->destination) && !empty($value->key) && !empty($this->responseActual[$type][$value->key])) { // We have a non-empty value with a mapped destination. $mappedFields[$value->destination] = $this->responseActual[$type][$value->key]; } } } } return $mappedFields; }
[ "public", "function", "getResponseMap", "(", ")", "{", "$", "mappedFields", "=", "[", "]", ";", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "responseExpected", "->", "{", "$", "type", "}", ")", "&&", "isset", "(", "$", "this", "->", "responseActual", "[", "$", "type", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "responseExpected", "->", "{", "$", "type", "}", "as", "$", "value", ")", "{", "if", "(", "!", "empty", "(", "$", "value", "->", "destination", ")", "&&", "!", "empty", "(", "$", "value", "->", "key", ")", "&&", "!", "empty", "(", "$", "this", "->", "responseActual", "[", "$", "type", "]", "[", "$", "value", "->", "key", "]", ")", ")", "{", "// We have a non-empty value with a mapped destination.", "$", "mappedFields", "[", "$", "value", "->", "destination", "]", "=", "$", "this", "->", "responseActual", "[", "$", "type", "]", "[", "$", "value", "->", "key", "]", ";", "}", "}", "}", "}", "return", "$", "mappedFields", ";", "}" ]
Get filled responses that have Contact destinations defined. @return array
[ "Get", "filled", "responses", "that", "have", "Contact", "destinations", "defined", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadOperation.php#L314-L329
TheDMSGroup/mautic-contact-client
Model/ApiPayloadOperation.php
ApiPayloadOperation.getExternalId
public function getExternalId() { $externalIds = array_flip($this->externalIds); $id = null; $idIndex = null; foreach (['headers', 'body'] as $type) { if (isset($this->responseActual[$type]) && isset($this->responseActual[$type])) { foreach ($this->responseActual[$type] as $key => $value) { $key = preg_replace('/[^a-z0-9]/', '', strtolower($key)); if (isset($externalIds[$key]) && (null === $idIndex || $externalIds[$key] < $idIndex)) { $idIndex = $externalIds[$key]; $id = $value; if (0 == $idIndex) { break; } } } } } return $id; }
php
public function getExternalId() { $externalIds = array_flip($this->externalIds); $id = null; $idIndex = null; foreach (['headers', 'body'] as $type) { if (isset($this->responseActual[$type]) && isset($this->responseActual[$type])) { foreach ($this->responseActual[$type] as $key => $value) { $key = preg_replace('/[^a-z0-9]/', '', strtolower($key)); if (isset($externalIds[$key]) && (null === $idIndex || $externalIds[$key] < $idIndex)) { $idIndex = $externalIds[$key]; $id = $value; if (0 == $idIndex) { break; } } } } } return $id; }
[ "public", "function", "getExternalId", "(", ")", "{", "$", "externalIds", "=", "array_flip", "(", "$", "this", "->", "externalIds", ")", ";", "$", "id", "=", "null", ";", "$", "idIndex", "=", "null", ";", "foreach", "(", "[", "'headers'", ",", "'body'", "]", "as", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "responseActual", "[", "$", "type", "]", ")", "&&", "isset", "(", "$", "this", "->", "responseActual", "[", "$", "type", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "responseActual", "[", "$", "type", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "key", "=", "preg_replace", "(", "'/[^a-z0-9]/'", ",", "''", ",", "strtolower", "(", "$", "key", ")", ")", ";", "if", "(", "isset", "(", "$", "externalIds", "[", "$", "key", "]", ")", "&&", "(", "null", "===", "$", "idIndex", "||", "$", "externalIds", "[", "$", "key", "]", "<", "$", "idIndex", ")", ")", "{", "$", "idIndex", "=", "$", "externalIds", "[", "$", "key", "]", ";", "$", "id", "=", "$", "value", ";", "if", "(", "0", "==", "$", "idIndex", ")", "{", "break", ";", "}", "}", "}", "}", "}", "return", "$", "id", ";", "}" ]
Given the response fields, attempt to assume an external ID for future correlation. Find the best possible fit.
[ "Given", "the", "response", "fields", "attempt", "to", "assume", "an", "external", "ID", "for", "future", "correlation", ".", "Find", "the", "best", "possible", "fit", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadOperation.php#L335-L356
TheDMSGroup/mautic-contact-client
Entity/ContactClient.php
ContactClient.setDncChecks
public function setDncChecks($dnc_checks) { if (is_array($dnc_checks)) { $dnc_checks = implode(',', $dnc_checks); } $this->isChanged('dncChecks', $dnc_checks); $this->dnc_checks = $dnc_checks; return $this; }
php
public function setDncChecks($dnc_checks) { if (is_array($dnc_checks)) { $dnc_checks = implode(',', $dnc_checks); } $this->isChanged('dncChecks', $dnc_checks); $this->dnc_checks = $dnc_checks; return $this; }
[ "public", "function", "setDncChecks", "(", "$", "dnc_checks", ")", "{", "if", "(", "is_array", "(", "$", "dnc_checks", ")", ")", "{", "$", "dnc_checks", "=", "implode", "(", "','", ",", "$", "dnc_checks", ")", ";", "}", "$", "this", "->", "isChanged", "(", "'dncChecks'", ",", "$", "dnc_checks", ")", ";", "$", "this", "->", "dnc_checks", "=", "$", "dnc_checks", ";", "return", "$", "this", ";", "}" ]
@param $dnc_checks @return $this
[ "@param", "$dnc_checks" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Entity/ContactClient.php#L887-L896
TheDMSGroup/mautic-contact-client
Model/ApiPayloadResponse.php
ApiPayloadResponse.parse
public function parse() { $result = []; $result['status'] = $this->service->getStatusCode(); $this->setLogs($result['status'], 'status'); // Format the head response. $result['headers'] = $this->service->getHeaders(); if ($result['headers']) { $result['headers'] = $this->getResponseArray($result['headers'], 'headers'); } $result['headersRaw'] = implode('; ', $result['headers']); $this->setLogs($result['headers'], 'headers'); $result['bodySize'] = $this->service->getBody()->getSize(); $this->setLogs($result['bodySize'], 'size'); $result['bodyRaw'] = $this->service->getBody()->getContents(); $this->setLogs($result['bodyRaw'], 'bodyRaw'); // Format the body response. $responseExpectedFormat = trim( strtolower(isset($this->responseExpected->format) ? $this->responseExpected->format : 'auto') ); // Move the expected format to the top of the detection array. if ('auto' !== $responseExpectedFormat) { $key = array_search($responseExpectedFormat, $this->contentTypes); if (false !== $key) { $this->contentTypes = array_flip( array_merge([$this->contentTypes[$key] => '-'], array_flip($this->contentTypes)) ); } } $this->setLogs($responseExpectedFormat, 'format'); $result['format'] = $responseExpectedFormat; // If auto mode, discern content type in a very forgiving manner from the header. if ('auto' === $result['format']) { foreach ($result['headers'] as $keaderType => $header) { if ('contenttype' === str_replace(['-', '_', ' '], '', strtolower($keaderType))) { foreach ($this->contentTypes as $key => $contentType) { if (strpos(strtolower($header), $contentType)) { $result['format'] = $contentType; // Move this type to the top of the detection array. $this->contentTypes = array_flip( array_merge([$this->contentTypes[$key] => '-'], array_flip($this->contentTypes)) ); $this->setLogs($contentType, 'headerFormat'); break; } } break; } } } $result['body'] = []; // Attempt to parse with a proffered list of types. foreach ($this->contentTypes as $contentType) { $attemptBody = $this->getResponseArray($result['bodyRaw'], $contentType); if ($attemptBody) { $result['body'] = $attemptBody; $result['format'] = $contentType; $this->setLogs($contentType, 'bodyFormat'); break; } $this->setLogs($contentType, 'bodyFormatsAttempted'); // If in test-mode do not cycle through all types unless we are truly in auto mode. if (!$this->test && 'auto' === $responseExpectedFormat) { break; } } $this->setLogs($result['body'], 'body'); $this->valid = (bool) $result['status']; $this->responseActual = $result; return $this; }
php
public function parse() { $result = []; $result['status'] = $this->service->getStatusCode(); $this->setLogs($result['status'], 'status'); // Format the head response. $result['headers'] = $this->service->getHeaders(); if ($result['headers']) { $result['headers'] = $this->getResponseArray($result['headers'], 'headers'); } $result['headersRaw'] = implode('; ', $result['headers']); $this->setLogs($result['headers'], 'headers'); $result['bodySize'] = $this->service->getBody()->getSize(); $this->setLogs($result['bodySize'], 'size'); $result['bodyRaw'] = $this->service->getBody()->getContents(); $this->setLogs($result['bodyRaw'], 'bodyRaw'); // Format the body response. $responseExpectedFormat = trim( strtolower(isset($this->responseExpected->format) ? $this->responseExpected->format : 'auto') ); // Move the expected format to the top of the detection array. if ('auto' !== $responseExpectedFormat) { $key = array_search($responseExpectedFormat, $this->contentTypes); if (false !== $key) { $this->contentTypes = array_flip( array_merge([$this->contentTypes[$key] => '-'], array_flip($this->contentTypes)) ); } } $this->setLogs($responseExpectedFormat, 'format'); $result['format'] = $responseExpectedFormat; // If auto mode, discern content type in a very forgiving manner from the header. if ('auto' === $result['format']) { foreach ($result['headers'] as $keaderType => $header) { if ('contenttype' === str_replace(['-', '_', ' '], '', strtolower($keaderType))) { foreach ($this->contentTypes as $key => $contentType) { if (strpos(strtolower($header), $contentType)) { $result['format'] = $contentType; // Move this type to the top of the detection array. $this->contentTypes = array_flip( array_merge([$this->contentTypes[$key] => '-'], array_flip($this->contentTypes)) ); $this->setLogs($contentType, 'headerFormat'); break; } } break; } } } $result['body'] = []; // Attempt to parse with a proffered list of types. foreach ($this->contentTypes as $contentType) { $attemptBody = $this->getResponseArray($result['bodyRaw'], $contentType); if ($attemptBody) { $result['body'] = $attemptBody; $result['format'] = $contentType; $this->setLogs($contentType, 'bodyFormat'); break; } $this->setLogs($contentType, 'bodyFormatsAttempted'); // If in test-mode do not cycle through all types unless we are truly in auto mode. if (!$this->test && 'auto' === $responseExpectedFormat) { break; } } $this->setLogs($result['body'], 'body'); $this->valid = (bool) $result['status']; $this->responseActual = $result; return $this; }
[ "public", "function", "parse", "(", ")", "{", "$", "result", "=", "[", "]", ";", "$", "result", "[", "'status'", "]", "=", "$", "this", "->", "service", "->", "getStatusCode", "(", ")", ";", "$", "this", "->", "setLogs", "(", "$", "result", "[", "'status'", "]", ",", "'status'", ")", ";", "// Format the head response.", "$", "result", "[", "'headers'", "]", "=", "$", "this", "->", "service", "->", "getHeaders", "(", ")", ";", "if", "(", "$", "result", "[", "'headers'", "]", ")", "{", "$", "result", "[", "'headers'", "]", "=", "$", "this", "->", "getResponseArray", "(", "$", "result", "[", "'headers'", "]", ",", "'headers'", ")", ";", "}", "$", "result", "[", "'headersRaw'", "]", "=", "implode", "(", "'; '", ",", "$", "result", "[", "'headers'", "]", ")", ";", "$", "this", "->", "setLogs", "(", "$", "result", "[", "'headers'", "]", ",", "'headers'", ")", ";", "$", "result", "[", "'bodySize'", "]", "=", "$", "this", "->", "service", "->", "getBody", "(", ")", "->", "getSize", "(", ")", ";", "$", "this", "->", "setLogs", "(", "$", "result", "[", "'bodySize'", "]", ",", "'size'", ")", ";", "$", "result", "[", "'bodyRaw'", "]", "=", "$", "this", "->", "service", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "$", "this", "->", "setLogs", "(", "$", "result", "[", "'bodyRaw'", "]", ",", "'bodyRaw'", ")", ";", "// Format the body response.", "$", "responseExpectedFormat", "=", "trim", "(", "strtolower", "(", "isset", "(", "$", "this", "->", "responseExpected", "->", "format", ")", "?", "$", "this", "->", "responseExpected", "->", "format", ":", "'auto'", ")", ")", ";", "// Move the expected format to the top of the detection array.", "if", "(", "'auto'", "!==", "$", "responseExpectedFormat", ")", "{", "$", "key", "=", "array_search", "(", "$", "responseExpectedFormat", ",", "$", "this", "->", "contentTypes", ")", ";", "if", "(", "false", "!==", "$", "key", ")", "{", "$", "this", "->", "contentTypes", "=", "array_flip", "(", "array_merge", "(", "[", "$", "this", "->", "contentTypes", "[", "$", "key", "]", "=>", "'-'", "]", ",", "array_flip", "(", "$", "this", "->", "contentTypes", ")", ")", ")", ";", "}", "}", "$", "this", "->", "setLogs", "(", "$", "responseExpectedFormat", ",", "'format'", ")", ";", "$", "result", "[", "'format'", "]", "=", "$", "responseExpectedFormat", ";", "// If auto mode, discern content type in a very forgiving manner from the header.", "if", "(", "'auto'", "===", "$", "result", "[", "'format'", "]", ")", "{", "foreach", "(", "$", "result", "[", "'headers'", "]", "as", "$", "keaderType", "=>", "$", "header", ")", "{", "if", "(", "'contenttype'", "===", "str_replace", "(", "[", "'-'", ",", "'_'", ",", "' '", "]", ",", "''", ",", "strtolower", "(", "$", "keaderType", ")", ")", ")", "{", "foreach", "(", "$", "this", "->", "contentTypes", "as", "$", "key", "=>", "$", "contentType", ")", "{", "if", "(", "strpos", "(", "strtolower", "(", "$", "header", ")", ",", "$", "contentType", ")", ")", "{", "$", "result", "[", "'format'", "]", "=", "$", "contentType", ";", "// Move this type to the top of the detection array.", "$", "this", "->", "contentTypes", "=", "array_flip", "(", "array_merge", "(", "[", "$", "this", "->", "contentTypes", "[", "$", "key", "]", "=>", "'-'", "]", ",", "array_flip", "(", "$", "this", "->", "contentTypes", ")", ")", ")", ";", "$", "this", "->", "setLogs", "(", "$", "contentType", ",", "'headerFormat'", ")", ";", "break", ";", "}", "}", "break", ";", "}", "}", "}", "$", "result", "[", "'body'", "]", "=", "[", "]", ";", "// Attempt to parse with a proffered list of types.", "foreach", "(", "$", "this", "->", "contentTypes", "as", "$", "contentType", ")", "{", "$", "attemptBody", "=", "$", "this", "->", "getResponseArray", "(", "$", "result", "[", "'bodyRaw'", "]", ",", "$", "contentType", ")", ";", "if", "(", "$", "attemptBody", ")", "{", "$", "result", "[", "'body'", "]", "=", "$", "attemptBody", ";", "$", "result", "[", "'format'", "]", "=", "$", "contentType", ";", "$", "this", "->", "setLogs", "(", "$", "contentType", ",", "'bodyFormat'", ")", ";", "break", ";", "}", "$", "this", "->", "setLogs", "(", "$", "contentType", ",", "'bodyFormatsAttempted'", ")", ";", "// If in test-mode do not cycle through all types unless we are truly in auto mode.", "if", "(", "!", "$", "this", "->", "test", "&&", "'auto'", "===", "$", "responseExpectedFormat", ")", "{", "break", ";", "}", "}", "$", "this", "->", "setLogs", "(", "$", "result", "[", "'body'", "]", ",", "'body'", ")", ";", "$", "this", "->", "valid", "=", "(", "bool", ")", "$", "result", "[", "'status'", "]", ";", "$", "this", "->", "responseActual", "=", "$", "result", ";", "return", "$", "this", ";", "}" ]
Parse the response and capture key=value pairs. @return $this @throws \Exception
[ "Parse", "the", "response", "and", "capture", "key", "=", "value", "pairs", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadResponse.php#L81-L160
TheDMSGroup/mautic-contact-client
Model/ApiPayloadResponse.php
ApiPayloadResponse.getResponseArray
private function getResponseArray($data, $responseExpectedFormat = 'json') { $result = $hierarchy = []; try { switch ($responseExpectedFormat) { case 'headers': foreach ($data as $key => $array) { $result[$key] = implode('; ', $array); } break; case 'xml': case 'html': if ( false !== strpos($data, '<') && false !== strpos($data, '>') ) { $doc = new DOMDocument(); $doc->recover = true; $data = trim($data); // Ensure UTF-8 encoding is handled correctly. if (1 !== preg_match('/^<\??xml .*encoding=["|\']?UTF-8["|\']?.*>/iU', $data, $matches)) { // Possibly missing UTF-8 specification. $opening = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; $replaceCount = 0; $data = preg_replace( '/^<\??xml(.*)\?*>/iU', $opening, $data, 1, $replaceCount ); if (!$replaceCount) { // Missing opening XML block entirely. $data = $opening.$data; } } if ('html' == $responseExpectedFormat) { @$doc->loadHTML($data); } else { @$doc->loadXML($data); } $hierarchy = $this->domDocumentArray($doc); } break; case 'json': $jsonHelper = new JSONHelper(); $hierarchy = $jsonHelper->decodeArray($data, 'API Response', true); break; case 'text': // Handle the most common patterns of a multi-line delimited expression. foreach (explode("\n", $data) as $line) { if (!empty($line)) { foreach ([':', '=', ';'] as $delimiter) { $elements = explode($delimiter, $line); if (2 == count($elements)) { // Strip outer whitespace. foreach ($elements as &$element) { $element = trim($element); } unset($element); // Strip enclosures. foreach ($elements as &$element) { foreach (['"', "'"] as $enclosure) { if ( 0 === strpos($element, $enclosure) && strrpos($element, $enclosure) === strlen($element) - 1 ) { $element = trim($element, $enclosure); continue; } } } unset($element); list($key, $value) = $elements; $result[$key] = $value; break; } } } } // Fall back to a raw string (no key-value pairs at all) if (!$result) { foreach (explode("\n", $data) as $l => $line) { $result['line '.($l + 1)] = $line; } } break; case 'yaml': $yaml = Yaml::parse($data, true); if (is_array($yaml) || is_object($yaml)) { $hierarchy = $yaml; } break; } } catch (\Exception $e) { // Sub-parsing may fail, but we only care about acceptable values when validating. // Logging will capture the full response for debugging. } // Flatten hierarchical data, if needed. if ($hierarchy) { if (!is_array($hierarchy) && !is_object($hierarchy)) { $hierarchy = [$hierarchy]; } $result = $this->flattenStructure($hierarchy); } // Stringify all values. foreach ($result as $key => &$value) { if (true === $value) { $value = 'true'; } elseif (false === $value) { $value = 'false'; } $value = (string) $value; } return $result; }
php
private function getResponseArray($data, $responseExpectedFormat = 'json') { $result = $hierarchy = []; try { switch ($responseExpectedFormat) { case 'headers': foreach ($data as $key => $array) { $result[$key] = implode('; ', $array); } break; case 'xml': case 'html': if ( false !== strpos($data, '<') && false !== strpos($data, '>') ) { $doc = new DOMDocument(); $doc->recover = true; $data = trim($data); // Ensure UTF-8 encoding is handled correctly. if (1 !== preg_match('/^<\??xml .*encoding=["|\']?UTF-8["|\']?.*>/iU', $data, $matches)) { // Possibly missing UTF-8 specification. $opening = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; $replaceCount = 0; $data = preg_replace( '/^<\??xml(.*)\?*>/iU', $opening, $data, 1, $replaceCount ); if (!$replaceCount) { // Missing opening XML block entirely. $data = $opening.$data; } } if ('html' == $responseExpectedFormat) { @$doc->loadHTML($data); } else { @$doc->loadXML($data); } $hierarchy = $this->domDocumentArray($doc); } break; case 'json': $jsonHelper = new JSONHelper(); $hierarchy = $jsonHelper->decodeArray($data, 'API Response', true); break; case 'text': // Handle the most common patterns of a multi-line delimited expression. foreach (explode("\n", $data) as $line) { if (!empty($line)) { foreach ([':', '=', ';'] as $delimiter) { $elements = explode($delimiter, $line); if (2 == count($elements)) { // Strip outer whitespace. foreach ($elements as &$element) { $element = trim($element); } unset($element); // Strip enclosures. foreach ($elements as &$element) { foreach (['"', "'"] as $enclosure) { if ( 0 === strpos($element, $enclosure) && strrpos($element, $enclosure) === strlen($element) - 1 ) { $element = trim($element, $enclosure); continue; } } } unset($element); list($key, $value) = $elements; $result[$key] = $value; break; } } } } // Fall back to a raw string (no key-value pairs at all) if (!$result) { foreach (explode("\n", $data) as $l => $line) { $result['line '.($l + 1)] = $line; } } break; case 'yaml': $yaml = Yaml::parse($data, true); if (is_array($yaml) || is_object($yaml)) { $hierarchy = $yaml; } break; } } catch (\Exception $e) { // Sub-parsing may fail, but we only care about acceptable values when validating. // Logging will capture the full response for debugging. } // Flatten hierarchical data, if needed. if ($hierarchy) { if (!is_array($hierarchy) && !is_object($hierarchy)) { $hierarchy = [$hierarchy]; } $result = $this->flattenStructure($hierarchy); } // Stringify all values. foreach ($result as $key => &$value) { if (true === $value) { $value = 'true'; } elseif (false === $value) { $value = 'false'; } $value = (string) $value; } return $result; }
[ "private", "function", "getResponseArray", "(", "$", "data", ",", "$", "responseExpectedFormat", "=", "'json'", ")", "{", "$", "result", "=", "$", "hierarchy", "=", "[", "]", ";", "try", "{", "switch", "(", "$", "responseExpectedFormat", ")", "{", "case", "'headers'", ":", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "array", ")", "{", "$", "result", "[", "$", "key", "]", "=", "implode", "(", "'; '", ",", "$", "array", ")", ";", "}", "break", ";", "case", "'xml'", ":", "case", "'html'", ":", "if", "(", "false", "!==", "strpos", "(", "$", "data", ",", "'<'", ")", "&&", "false", "!==", "strpos", "(", "$", "data", ",", "'>'", ")", ")", "{", "$", "doc", "=", "new", "DOMDocument", "(", ")", ";", "$", "doc", "->", "recover", "=", "true", ";", "$", "data", "=", "trim", "(", "$", "data", ")", ";", "// Ensure UTF-8 encoding is handled correctly.", "if", "(", "1", "!==", "preg_match", "(", "'/^<\\??xml .*encoding=[\"|\\']?UTF-8[\"|\\']?.*>/iU'", ",", "$", "data", ",", "$", "matches", ")", ")", "{", "// Possibly missing UTF-8 specification.", "$", "opening", "=", "'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>'", ";", "$", "replaceCount", "=", "0", ";", "$", "data", "=", "preg_replace", "(", "'/^<\\??xml(.*)\\?*>/iU'", ",", "$", "opening", ",", "$", "data", ",", "1", ",", "$", "replaceCount", ")", ";", "if", "(", "!", "$", "replaceCount", ")", "{", "// Missing opening XML block entirely.", "$", "data", "=", "$", "opening", ".", "$", "data", ";", "}", "}", "if", "(", "'html'", "==", "$", "responseExpectedFormat", ")", "{", "@", "$", "doc", "->", "loadHTML", "(", "$", "data", ")", ";", "}", "else", "{", "@", "$", "doc", "->", "loadXML", "(", "$", "data", ")", ";", "}", "$", "hierarchy", "=", "$", "this", "->", "domDocumentArray", "(", "$", "doc", ")", ";", "}", "break", ";", "case", "'json'", ":", "$", "jsonHelper", "=", "new", "JSONHelper", "(", ")", ";", "$", "hierarchy", "=", "$", "jsonHelper", "->", "decodeArray", "(", "$", "data", ",", "'API Response'", ",", "true", ")", ";", "break", ";", "case", "'text'", ":", "// Handle the most common patterns of a multi-line delimited expression.", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "data", ")", "as", "$", "line", ")", "{", "if", "(", "!", "empty", "(", "$", "line", ")", ")", "{", "foreach", "(", "[", "':'", ",", "'='", ",", "';'", "]", "as", "$", "delimiter", ")", "{", "$", "elements", "=", "explode", "(", "$", "delimiter", ",", "$", "line", ")", ";", "if", "(", "2", "==", "count", "(", "$", "elements", ")", ")", "{", "// Strip outer whitespace.", "foreach", "(", "$", "elements", "as", "&", "$", "element", ")", "{", "$", "element", "=", "trim", "(", "$", "element", ")", ";", "}", "unset", "(", "$", "element", ")", ";", "// Strip enclosures.", "foreach", "(", "$", "elements", "as", "&", "$", "element", ")", "{", "foreach", "(", "[", "'\"'", ",", "\"'\"", "]", "as", "$", "enclosure", ")", "{", "if", "(", "0", "===", "strpos", "(", "$", "element", ",", "$", "enclosure", ")", "&&", "strrpos", "(", "$", "element", ",", "$", "enclosure", ")", "===", "strlen", "(", "$", "element", ")", "-", "1", ")", "{", "$", "element", "=", "trim", "(", "$", "element", ",", "$", "enclosure", ")", ";", "continue", ";", "}", "}", "}", "unset", "(", "$", "element", ")", ";", "list", "(", "$", "key", ",", "$", "value", ")", "=", "$", "elements", ";", "$", "result", "[", "$", "key", "]", "=", "$", "value", ";", "break", ";", "}", "}", "}", "}", "// Fall back to a raw string (no key-value pairs at all)", "if", "(", "!", "$", "result", ")", "{", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "data", ")", "as", "$", "l", "=>", "$", "line", ")", "{", "$", "result", "[", "'line '", ".", "(", "$", "l", "+", "1", ")", "]", "=", "$", "line", ";", "}", "}", "break", ";", "case", "'yaml'", ":", "$", "yaml", "=", "Yaml", "::", "parse", "(", "$", "data", ",", "true", ")", ";", "if", "(", "is_array", "(", "$", "yaml", ")", "||", "is_object", "(", "$", "yaml", ")", ")", "{", "$", "hierarchy", "=", "$", "yaml", ";", "}", "break", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// Sub-parsing may fail, but we only care about acceptable values when validating.", "// Logging will capture the full response for debugging.", "}", "// Flatten hierarchical data, if needed.", "if", "(", "$", "hierarchy", ")", "{", "if", "(", "!", "is_array", "(", "$", "hierarchy", ")", "&&", "!", "is_object", "(", "$", "hierarchy", ")", ")", "{", "$", "hierarchy", "=", "[", "$", "hierarchy", "]", ";", "}", "$", "result", "=", "$", "this", "->", "flattenStructure", "(", "$", "hierarchy", ")", ";", "}", "// Stringify all values.", "foreach", "(", "$", "result", "as", "$", "key", "=>", "&", "$", "value", ")", "{", "if", "(", "true", "===", "$", "value", ")", "{", "$", "value", "=", "'true'", ";", "}", "elseif", "(", "false", "===", "$", "value", ")", "{", "$", "value", "=", "'false'", ";", "}", "$", "value", "=", "(", "string", ")", "$", "value", ";", "}", "return", "$", "result", ";", "}" ]
Given a headers array or body of text and a format, parse to a flat key=value array. @param mixed $data @param string $responseExpectedFormat @return array|bool return false if there is an error or we are unable to parse @throws \Exception
[ "Given", "a", "headers", "array", "or", "body", "of", "text", "and", "a", "format", "parse", "to", "a", "flat", "key", "=", "value", "array", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadResponse.php#L172-L294
TheDMSGroup/mautic-contact-client
Model/ApiPayloadResponse.php
ApiPayloadResponse.flattenStructure
private function flattenStructure($subject, &$result = [], $prefix = '', $delimiter = '.') { foreach ($subject as $key => $value) { if (is_array($value) || is_object($value)) { $this->flattenStructure($value, $result, $prefix ? $prefix.$delimiter.$key : $key); } else { if ($prefix) { $key = $prefix.$delimiter.$key; } // Do not nullify existing key/value pairs if already present. if (empty($value) && false !== $value && !isset($result[$key])) { $result[$key] = null; } else { // Handle repeated arrays without unique keys. $originalKey = $key; $count = 0; while (isset($result[$key])) { $key = $originalKey.$delimiter.$count; ++$count; } $result[$key] = $value; } } } return $result; }
php
private function flattenStructure($subject, &$result = [], $prefix = '', $delimiter = '.') { foreach ($subject as $key => $value) { if (is_array($value) || is_object($value)) { $this->flattenStructure($value, $result, $prefix ? $prefix.$delimiter.$key : $key); } else { if ($prefix) { $key = $prefix.$delimiter.$key; } // Do not nullify existing key/value pairs if already present. if (empty($value) && false !== $value && !isset($result[$key])) { $result[$key] = null; } else { // Handle repeated arrays without unique keys. $originalKey = $key; $count = 0; while (isset($result[$key])) { $key = $originalKey.$delimiter.$count; ++$count; } $result[$key] = $value; } } } return $result; }
[ "private", "function", "flattenStructure", "(", "$", "subject", ",", "&", "$", "result", "=", "[", "]", ",", "$", "prefix", "=", "''", ",", "$", "delimiter", "=", "'.'", ")", "{", "foreach", "(", "$", "subject", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "||", "is_object", "(", "$", "value", ")", ")", "{", "$", "this", "->", "flattenStructure", "(", "$", "value", ",", "$", "result", ",", "$", "prefix", "?", "$", "prefix", ".", "$", "delimiter", ".", "$", "key", ":", "$", "key", ")", ";", "}", "else", "{", "if", "(", "$", "prefix", ")", "{", "$", "key", "=", "$", "prefix", ".", "$", "delimiter", ".", "$", "key", ";", "}", "// Do not nullify existing key/value pairs if already present.", "if", "(", "empty", "(", "$", "value", ")", "&&", "false", "!==", "$", "value", "&&", "!", "isset", "(", "$", "result", "[", "$", "key", "]", ")", ")", "{", "$", "result", "[", "$", "key", "]", "=", "null", ";", "}", "else", "{", "// Handle repeated arrays without unique keys.", "$", "originalKey", "=", "$", "key", ";", "$", "count", "=", "0", ";", "while", "(", "isset", "(", "$", "result", "[", "$", "key", "]", ")", ")", "{", "$", "key", "=", "$", "originalKey", ".", "$", "delimiter", ".", "$", "count", ";", "++", "$", "count", ";", "}", "$", "result", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Recursively flatten an structure to an array including only key/value pairs. @param $subject @param array $result @param string $prefix @param string $delimiter @return array
[ "Recursively", "flatten", "an", "structure", "to", "an", "array", "including", "only", "key", "/", "value", "pairs", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadResponse.php#L351-L377
TheDMSGroup/mautic-contact-client
Model/ApiPayloadResponse.php
ApiPayloadResponse.validate
public function validate() { if ($this->valid) { if (!$this->responseActual) { throw new ContactClientException( 'There was no response to parse.', 0, null, Stat::TYPE_ERROR, true ); } $filter = new FilterHelper(); try { $this->valid = $filter->filter($this->successDefinition, $this->responseActual, -404); // If there is no success definition, than do the default test of a 200 ok status check. // -404 is just a falsy value to signify this from the filter helper. if (-404 === $this->valid) { if (!$this->responseActual['status'] || Codes::HTTP_OK != $this->responseActual['status']) { throw new ContactClientException( 'Status code is not 200. Default validation failure.', 0, null, Stat::TYPE_REJECT, false ); } } } catch (\Exception $e) { throw new ContactClientException( 'Error in validation: '.$e->getMessage(), 0, $e, Stat::TYPE_REJECT, false, null, $filter->getErrors() ); } if (!$this->valid) { // Response codes that indicate a server error where the lead likely was not delivered. if ( is_int($this->responseActual['status']) && in_array( $this->responseActual['status'], [ Codes::HTTP_NOT_FOUND, Codes::HTTP_METHOD_NOT_ALLOWED, Codes::HTTP_REQUEST_TIMEOUT, Codes::HTTP_CONFLICT, Codes::HTTP_GONE, Codes::HTTP_LENGTH_REQUIRED, Codes::HTTP_REQUEST_ENTITY_TOO_LARGE, Codes::HTTP_REQUEST_URI_TOO_LONG, Codes::HTTP_UNSUPPORTED_MEDIA_TYPE, Codes::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, Codes::HTTP_TOO_MANY_REQUESTS, Codes::HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, Codes::HTTP_INTERNAL_SERVER_ERROR, Codes::HTTP_NOT_IMPLEMENTED, Codes::HTTP_BAD_GATEWAY, Codes::HTTP_SERVICE_UNAVAILABLE, Codes::HTTP_GATEWAY_TIMEOUT, Codes::HTTP_VERSION_NOT_SUPPORTED, Codes::HTTP_INSUFFICIENT_STORAGE, Codes::HTTP_LOOP_DETECTED, Codes::HTTP_NOT_EXTENDED, ] ) ) { // These can be retried in the hopes that they are due to a temporary condition. throw new ContactClientException( 'Client responded with a '.$this->responseActual['status'].' server error code. The data likely did not reach the destination due to a temporary condition.', 0, null, Stat::TYPE_ERROR, true ); } // Response codes known to be returned when there is invalid auth. if ( is_int($this->responseActual['status']) && in_array( $this->responseActual['status'], [ Codes::HTTP_BAD_REQUEST, Codes::HTTP_UNAUTHORIZED, Codes::HTTP_PAYMENT_REQUIRED, Codes::HTTP_FORBIDDEN, Codes::HTTP_PROXY_AUTHENTICATION_REQUIRED, ] ) ) { // These can be retried only during pre-auth run. throw new ContactClientException( 'Client responded with a '.$this->responseActual['status'].' server error code. The data likely did not reach the destination due to invalid auth.', 0, null, Stat::TYPE_AUTH, false ); } } if (!$this->valid && !isset($e)) { throw new ContactClientException( 'Failed validation: '.implode(', ', $filter->getErrors()), 0, null, Stat::TYPE_REJECT, false, null, $filter->getErrors() ); } } return $this->valid; }
php
public function validate() { if ($this->valid) { if (!$this->responseActual) { throw new ContactClientException( 'There was no response to parse.', 0, null, Stat::TYPE_ERROR, true ); } $filter = new FilterHelper(); try { $this->valid = $filter->filter($this->successDefinition, $this->responseActual, -404); // If there is no success definition, than do the default test of a 200 ok status check. // -404 is just a falsy value to signify this from the filter helper. if (-404 === $this->valid) { if (!$this->responseActual['status'] || Codes::HTTP_OK != $this->responseActual['status']) { throw new ContactClientException( 'Status code is not 200. Default validation failure.', 0, null, Stat::TYPE_REJECT, false ); } } } catch (\Exception $e) { throw new ContactClientException( 'Error in validation: '.$e->getMessage(), 0, $e, Stat::TYPE_REJECT, false, null, $filter->getErrors() ); } if (!$this->valid) { // Response codes that indicate a server error where the lead likely was not delivered. if ( is_int($this->responseActual['status']) && in_array( $this->responseActual['status'], [ Codes::HTTP_NOT_FOUND, Codes::HTTP_METHOD_NOT_ALLOWED, Codes::HTTP_REQUEST_TIMEOUT, Codes::HTTP_CONFLICT, Codes::HTTP_GONE, Codes::HTTP_LENGTH_REQUIRED, Codes::HTTP_REQUEST_ENTITY_TOO_LARGE, Codes::HTTP_REQUEST_URI_TOO_LONG, Codes::HTTP_UNSUPPORTED_MEDIA_TYPE, Codes::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE, Codes::HTTP_TOO_MANY_REQUESTS, Codes::HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, Codes::HTTP_INTERNAL_SERVER_ERROR, Codes::HTTP_NOT_IMPLEMENTED, Codes::HTTP_BAD_GATEWAY, Codes::HTTP_SERVICE_UNAVAILABLE, Codes::HTTP_GATEWAY_TIMEOUT, Codes::HTTP_VERSION_NOT_SUPPORTED, Codes::HTTP_INSUFFICIENT_STORAGE, Codes::HTTP_LOOP_DETECTED, Codes::HTTP_NOT_EXTENDED, ] ) ) { // These can be retried in the hopes that they are due to a temporary condition. throw new ContactClientException( 'Client responded with a '.$this->responseActual['status'].' server error code. The data likely did not reach the destination due to a temporary condition.', 0, null, Stat::TYPE_ERROR, true ); } // Response codes known to be returned when there is invalid auth. if ( is_int($this->responseActual['status']) && in_array( $this->responseActual['status'], [ Codes::HTTP_BAD_REQUEST, Codes::HTTP_UNAUTHORIZED, Codes::HTTP_PAYMENT_REQUIRED, Codes::HTTP_FORBIDDEN, Codes::HTTP_PROXY_AUTHENTICATION_REQUIRED, ] ) ) { // These can be retried only during pre-auth run. throw new ContactClientException( 'Client responded with a '.$this->responseActual['status'].' server error code. The data likely did not reach the destination due to invalid auth.', 0, null, Stat::TYPE_AUTH, false ); } } if (!$this->valid && !isset($e)) { throw new ContactClientException( 'Failed validation: '.implode(', ', $filter->getErrors()), 0, null, Stat::TYPE_REJECT, false, null, $filter->getErrors() ); } } return $this->valid; }
[ "public", "function", "validate", "(", ")", "{", "if", "(", "$", "this", "->", "valid", ")", "{", "if", "(", "!", "$", "this", "->", "responseActual", ")", "{", "throw", "new", "ContactClientException", "(", "'There was no response to parse.'", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_ERROR", ",", "true", ")", ";", "}", "$", "filter", "=", "new", "FilterHelper", "(", ")", ";", "try", "{", "$", "this", "->", "valid", "=", "$", "filter", "->", "filter", "(", "$", "this", "->", "successDefinition", ",", "$", "this", "->", "responseActual", ",", "-", "404", ")", ";", "// If there is no success definition, than do the default test of a 200 ok status check.", "// -404 is just a falsy value to signify this from the filter helper.", "if", "(", "-", "404", "===", "$", "this", "->", "valid", ")", "{", "if", "(", "!", "$", "this", "->", "responseActual", "[", "'status'", "]", "||", "Codes", "::", "HTTP_OK", "!=", "$", "this", "->", "responseActual", "[", "'status'", "]", ")", "{", "throw", "new", "ContactClientException", "(", "'Status code is not 200. Default validation failure.'", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_REJECT", ",", "false", ")", ";", "}", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "ContactClientException", "(", "'Error in validation: '", ".", "$", "e", "->", "getMessage", "(", ")", ",", "0", ",", "$", "e", ",", "Stat", "::", "TYPE_REJECT", ",", "false", ",", "null", ",", "$", "filter", "->", "getErrors", "(", ")", ")", ";", "}", "if", "(", "!", "$", "this", "->", "valid", ")", "{", "// Response codes that indicate a server error where the lead likely was not delivered.", "if", "(", "is_int", "(", "$", "this", "->", "responseActual", "[", "'status'", "]", ")", "&&", "in_array", "(", "$", "this", "->", "responseActual", "[", "'status'", "]", ",", "[", "Codes", "::", "HTTP_NOT_FOUND", ",", "Codes", "::", "HTTP_METHOD_NOT_ALLOWED", ",", "Codes", "::", "HTTP_REQUEST_TIMEOUT", ",", "Codes", "::", "HTTP_CONFLICT", ",", "Codes", "::", "HTTP_GONE", ",", "Codes", "::", "HTTP_LENGTH_REQUIRED", ",", "Codes", "::", "HTTP_REQUEST_ENTITY_TOO_LARGE", ",", "Codes", "::", "HTTP_REQUEST_URI_TOO_LONG", ",", "Codes", "::", "HTTP_UNSUPPORTED_MEDIA_TYPE", ",", "Codes", "::", "HTTP_REQUESTED_RANGE_NOT_SATISFIABLE", ",", "Codes", "::", "HTTP_TOO_MANY_REQUESTS", ",", "Codes", "::", "HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE", ",", "Codes", "::", "HTTP_INTERNAL_SERVER_ERROR", ",", "Codes", "::", "HTTP_NOT_IMPLEMENTED", ",", "Codes", "::", "HTTP_BAD_GATEWAY", ",", "Codes", "::", "HTTP_SERVICE_UNAVAILABLE", ",", "Codes", "::", "HTTP_GATEWAY_TIMEOUT", ",", "Codes", "::", "HTTP_VERSION_NOT_SUPPORTED", ",", "Codes", "::", "HTTP_INSUFFICIENT_STORAGE", ",", "Codes", "::", "HTTP_LOOP_DETECTED", ",", "Codes", "::", "HTTP_NOT_EXTENDED", ",", "]", ")", ")", "{", "// These can be retried in the hopes that they are due to a temporary condition.", "throw", "new", "ContactClientException", "(", "'Client responded with a '", ".", "$", "this", "->", "responseActual", "[", "'status'", "]", ".", "' server error code. The data likely did not reach the destination due to a temporary condition.'", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_ERROR", ",", "true", ")", ";", "}", "// Response codes known to be returned when there is invalid auth.", "if", "(", "is_int", "(", "$", "this", "->", "responseActual", "[", "'status'", "]", ")", "&&", "in_array", "(", "$", "this", "->", "responseActual", "[", "'status'", "]", ",", "[", "Codes", "::", "HTTP_BAD_REQUEST", ",", "Codes", "::", "HTTP_UNAUTHORIZED", ",", "Codes", "::", "HTTP_PAYMENT_REQUIRED", ",", "Codes", "::", "HTTP_FORBIDDEN", ",", "Codes", "::", "HTTP_PROXY_AUTHENTICATION_REQUIRED", ",", "]", ")", ")", "{", "// These can be retried only during pre-auth run.", "throw", "new", "ContactClientException", "(", "'Client responded with a '", ".", "$", "this", "->", "responseActual", "[", "'status'", "]", ".", "' server error code. The data likely did not reach the destination due to invalid auth.'", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_AUTH", ",", "false", ")", ";", "}", "}", "if", "(", "!", "$", "this", "->", "valid", "&&", "!", "isset", "(", "$", "e", ")", ")", "{", "throw", "new", "ContactClientException", "(", "'Failed validation: '", ".", "implode", "(", "', '", ",", "$", "filter", "->", "getErrors", "(", ")", ")", ",", "0", ",", "null", ",", "Stat", "::", "TYPE_REJECT", ",", "false", ",", "null", ",", "$", "filter", "->", "getErrors", "(", ")", ")", ";", "}", "}", "return", "$", "this", "->", "valid", ";", "}" ]
Given the recent response, evaluate it for success based on the expected success validator. @return bool @throws ContactClientException
[ "Given", "the", "recent", "response", "evaluate", "it", "for", "success", "based", "on", "the", "expected", "success", "validator", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/ApiPayloadResponse.php#L386-L508
TheDMSGroup/mautic-contact-client
Command/SendContactCommand.php
SendContactCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $options = $input->getOptions(); $container = $this->getContainer(); $translator = $container->get('translator'); if (!$this->checkRunStatus($input, $output, $options['client'].$options['contact'])) { return 0; } if (!$options['client'] || !is_numeric($options['client'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client').'</error>'); return 1; } if (!$options['contact'] || !is_numeric($options['contact'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.error.contact').'</error>'); return 1; } /** @var ClientModel $clientModel */ $clientModel = $container->get('mautic.contactclient.model.contactclient'); /** @var ContactClient $client */ $client = $clientModel->getEntity($options['client']); if (!$client) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client.load').'</error>' ); return 1; } if (false === $client->getIsPublished() && !$options['force']) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client.publish').'</error>' ); return 1; } /** @var \Mautic\LeadBundle\Model\LeadModel $contactModel */ $contactModel = $container->get('mautic.lead.model.lead'); /** @var \Mautic\LeadBundle\Entity\Lead $contact */ $contact = $contactModel->getEntity($options['contact']); if (!$contact) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.contact.load').'</error>' ); return 1; } if (in_array($client->getType(), ['api', 'file'])) { // Load the integration helper for our general ClientIntegration /** @var IntegrationHelper $integrationHelper */ $integrationHelper = $container->get('mautic.helper.integration'); /** @var ClientIntegration $integrationObject */ $integrationObject = $integrationHelper->getIntegrationObject('Client'); if ( !$integrationObject || (false === $integrationObject->getIntegrationSettings()->getIsPublished() && !$options['force']) ) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.plugin.publish').'</error>' ); return 1; } $integrationObject->sendContact($client, $contact, (bool) $options['test'], (bool) $options['force']); if ($integrationObject->getValid()) { $output->writeln( '<info>'.$translator->trans('mautic.contactclient.sendcontact.contact.accepted').'</info>' ); if (isset($options['verbose']) && $options['verbose']) { $output->writeln('<info>'.$integrationObject->getLogsYAML().'</info>'); } } else { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.contact.rejected').'</error>' ); if (isset($options['verbose']) && $options['verbose']) { $output->writeln('<info>'.$integrationObject->getLogsYAML().'</info>'); } } } else { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.client.type').'</error>'); return 1; } $this->completeRun(); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $options = $input->getOptions(); $container = $this->getContainer(); $translator = $container->get('translator'); if (!$this->checkRunStatus($input, $output, $options['client'].$options['contact'])) { return 0; } if (!$options['client'] || !is_numeric($options['client'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client').'</error>'); return 1; } if (!$options['contact'] || !is_numeric($options['contact'])) { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.error.contact').'</error>'); return 1; } /** @var ClientModel $clientModel */ $clientModel = $container->get('mautic.contactclient.model.contactclient'); /** @var ContactClient $client */ $client = $clientModel->getEntity($options['client']); if (!$client) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client.load').'</error>' ); return 1; } if (false === $client->getIsPublished() && !$options['force']) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.client.publish').'</error>' ); return 1; } /** @var \Mautic\LeadBundle\Model\LeadModel $contactModel */ $contactModel = $container->get('mautic.lead.model.lead'); /** @var \Mautic\LeadBundle\Entity\Lead $contact */ $contact = $contactModel->getEntity($options['contact']); if (!$contact) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.contact.load').'</error>' ); return 1; } if (in_array($client->getType(), ['api', 'file'])) { // Load the integration helper for our general ClientIntegration /** @var IntegrationHelper $integrationHelper */ $integrationHelper = $container->get('mautic.helper.integration'); /** @var ClientIntegration $integrationObject */ $integrationObject = $integrationHelper->getIntegrationObject('Client'); if ( !$integrationObject || (false === $integrationObject->getIntegrationSettings()->getIsPublished() && !$options['force']) ) { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.error.plugin.publish').'</error>' ); return 1; } $integrationObject->sendContact($client, $contact, (bool) $options['test'], (bool) $options['force']); if ($integrationObject->getValid()) { $output->writeln( '<info>'.$translator->trans('mautic.contactclient.sendcontact.contact.accepted').'</info>' ); if (isset($options['verbose']) && $options['verbose']) { $output->writeln('<info>'.$integrationObject->getLogsYAML().'</info>'); } } else { $output->writeln( '<error>'.$translator->trans('mautic.contactclient.sendcontact.contact.rejected').'</error>' ); if (isset($options['verbose']) && $options['verbose']) { $output->writeln('<info>'.$integrationObject->getLogsYAML().'</info>'); } } } else { $output->writeln('<error>'.$translator->trans('mautic.contactclient.sendcontact.client.type').'</error>'); return 1; } $this->completeRun(); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "options", "=", "$", "input", "->", "getOptions", "(", ")", ";", "$", "container", "=", "$", "this", "->", "getContainer", "(", ")", ";", "$", "translator", "=", "$", "container", "->", "get", "(", "'translator'", ")", ";", "if", "(", "!", "$", "this", "->", "checkRunStatus", "(", "$", "input", ",", "$", "output", ",", "$", "options", "[", "'client'", "]", ".", "$", "options", "[", "'contact'", "]", ")", ")", "{", "return", "0", ";", "}", "if", "(", "!", "$", "options", "[", "'client'", "]", "||", "!", "is_numeric", "(", "$", "options", "[", "'client'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.error.client'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "if", "(", "!", "$", "options", "[", "'contact'", "]", "||", "!", "is_numeric", "(", "$", "options", "[", "'contact'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.error.contact'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "/** @var ClientModel $clientModel */", "$", "clientModel", "=", "$", "container", "->", "get", "(", "'mautic.contactclient.model.contactclient'", ")", ";", "/** @var ContactClient $client */", "$", "client", "=", "$", "clientModel", "->", "getEntity", "(", "$", "options", "[", "'client'", "]", ")", ";", "if", "(", "!", "$", "client", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.error.client.load'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "if", "(", "false", "===", "$", "client", "->", "getIsPublished", "(", ")", "&&", "!", "$", "options", "[", "'force'", "]", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.error.client.publish'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "/** @var \\Mautic\\LeadBundle\\Model\\LeadModel $contactModel */", "$", "contactModel", "=", "$", "container", "->", "get", "(", "'mautic.lead.model.lead'", ")", ";", "/** @var \\Mautic\\LeadBundle\\Entity\\Lead $contact */", "$", "contact", "=", "$", "contactModel", "->", "getEntity", "(", "$", "options", "[", "'contact'", "]", ")", ";", "if", "(", "!", "$", "contact", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.error.contact.load'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "if", "(", "in_array", "(", "$", "client", "->", "getType", "(", ")", ",", "[", "'api'", ",", "'file'", "]", ")", ")", "{", "// Load the integration helper for our general ClientIntegration", "/** @var IntegrationHelper $integrationHelper */", "$", "integrationHelper", "=", "$", "container", "->", "get", "(", "'mautic.helper.integration'", ")", ";", "/** @var ClientIntegration $integrationObject */", "$", "integrationObject", "=", "$", "integrationHelper", "->", "getIntegrationObject", "(", "'Client'", ")", ";", "if", "(", "!", "$", "integrationObject", "||", "(", "false", "===", "$", "integrationObject", "->", "getIntegrationSettings", "(", ")", "->", "getIsPublished", "(", ")", "&&", "!", "$", "options", "[", "'force'", "]", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.error.plugin.publish'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "$", "integrationObject", "->", "sendContact", "(", "$", "client", ",", "$", "contact", ",", "(", "bool", ")", "$", "options", "[", "'test'", "]", ",", "(", "bool", ")", "$", "options", "[", "'force'", "]", ")", ";", "if", "(", "$", "integrationObject", "->", "getValid", "(", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.contact.accepted'", ")", ".", "'</info>'", ")", ";", "if", "(", "isset", "(", "$", "options", "[", "'verbose'", "]", ")", "&&", "$", "options", "[", "'verbose'", "]", ")", "{", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "integrationObject", "->", "getLogsYAML", "(", ")", ".", "'</info>'", ")", ";", "}", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.contact.rejected'", ")", ".", "'</error>'", ")", ";", "if", "(", "isset", "(", "$", "options", "[", "'verbose'", "]", ")", "&&", "$", "options", "[", "'verbose'", "]", ")", "{", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "integrationObject", "->", "getLogsYAML", "(", ")", ".", "'</info>'", ")", ";", "}", "}", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<error>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.sendcontact.client.type'", ")", ".", "'</error>'", ")", ";", "return", "1", ";", "}", "$", "this", "->", "completeRun", "(", ")", ";", "return", "0", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Command/SendContactCommand.php#L66-L161
TheDMSGroup/mautic-contact-client
Command/MaintenanceCommand.php
MaintenanceCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $translator = $container->get('translator'); if (!$this->checkRunStatus($input, $output)) { return 0; } /** @var Cache $cacheModel */ $cacheModel = $container->get('mautic.contactclient.model.cache'); $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.maintenance.running' ).'</info>' ); $cacheModel->getRepository() ->deleteExpired() ->reduceExclusivityIndex(); $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.maintenance.complete' ).'</info>' ); $this->completeRun(); return 0; }
php
protected function execute(InputInterface $input, OutputInterface $output) { $container = $this->getContainer(); $translator = $container->get('translator'); if (!$this->checkRunStatus($input, $output)) { return 0; } /** @var Cache $cacheModel */ $cacheModel = $container->get('mautic.contactclient.model.cache'); $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.maintenance.running' ).'</info>' ); $cacheModel->getRepository() ->deleteExpired() ->reduceExclusivityIndex(); $output->writeln( '<info>'.$translator->trans( 'mautic.contactclient.maintenance.complete' ).'</info>' ); $this->completeRun(); return 0; }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "container", "=", "$", "this", "->", "getContainer", "(", ")", ";", "$", "translator", "=", "$", "container", "->", "get", "(", "'translator'", ")", ";", "if", "(", "!", "$", "this", "->", "checkRunStatus", "(", "$", "input", ",", "$", "output", ")", ")", "{", "return", "0", ";", "}", "/** @var Cache $cacheModel */", "$", "cacheModel", "=", "$", "container", "->", "get", "(", "'mautic.contactclient.model.cache'", ")", ";", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.maintenance.running'", ")", ".", "'</info>'", ")", ";", "$", "cacheModel", "->", "getRepository", "(", ")", "->", "deleteExpired", "(", ")", "->", "reduceExclusivityIndex", "(", ")", ";", "$", "output", "->", "writeln", "(", "'<info>'", ".", "$", "translator", "->", "trans", "(", "'mautic.contactclient.maintenance.complete'", ")", ".", "'</info>'", ")", ";", "$", "this", "->", "completeRun", "(", ")", ";", "return", "0", ";", "}" ]
@param InputInterface $input @param OutputInterface $output @return int|null @throws \Exception
[ "@param", "InputInterface", "$input", "@param", "OutputInterface", "$output" ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Command/MaintenanceCommand.php#L45-L72
TheDMSGroup/mautic-contact-client
Model/Schedule.php
Schedule.findOpening
public function findOpening($startDay = 0, $endDay = 7, $fileRate = 1, $all = false, $startTime = null) { $openings = []; for ($day = $startDay; $day <= $endDay; ++$day) { if (0 === $day) { // Current day. if ($startTime && $startTime instanceof \DateTime) { $date = clone $startTime; } else { $date = new \DateTime(); } } else { // Future days. // Use noon to begin to evaluate days in the future to avoiding timezones during day checks. $date = new \DateTime('noon +'.$day.' day'); } try { // Initialize the range (will expand as appropriate later). $start = clone $date; $end = clone $date; // Evaluate that the client is open this day of the week. $hours = $this->evaluateDay(true, $date); // Evaluate that the client isn't closed by an excluded date rule. $this->evaluateExclusions($date); // Push the end time to the correct time for this client's hours. $timeTill = !empty($hours->timeTill) ? $hours->timeTill : '23:59'; $end->setTimezone($this->timezone); $end->modify($timeTill.':59'); // Current day: Evaluate that there is still time today to send. if (0 == $day && $this->now > $end) { // Continue to the next day. continue; } // Pull the start time to the correct time for this day and schedule. $timeFrom = !empty($hours->timeFrom) ? $hours->timeFrom : '00:00'; $start->setTimezone($this->timezone); $start->modify($timeFrom); if ('file' === $this->contactClient->getType()) { // Evaluate if we have exceeded allowed file count for this day. $fileCount = $this->evaluateFileRate($fileRate, $date); // If we have already built a file in this day and can send more... if ($fileCount > 0 && $fileRate > 1) { // Push the start time to the next available slot in this day. $daySeconds = $end->format('U') - $start->format('U'); if ('00:00' === $timeFrom && '23:59' === $timeTill) { // Avoid sending 2 files at midnight. $segmentSeconds = intval($daySeconds / $fileRate); } else { // Send at opening and closing times, spreading the rest of the day evenly. $segmentSeconds = intval($daySeconds / ($fileRate - 1)); } // Push start time to the next segment. $start->modify('+'.($segmentSeconds * $fileCount).' seconds'); } } // Start time should not be in the past. if (0 === $day && $start < $this->now) { // Must be done after rate has been applied. $start = $this->now; } $openings[] = [$start, $end]; if (!$all) { break; } } catch (\Exception $e) { if ($e instanceof ContactClientException) { // Expected. } else { throw $e; } } } return $openings; }
php
public function findOpening($startDay = 0, $endDay = 7, $fileRate = 1, $all = false, $startTime = null) { $openings = []; for ($day = $startDay; $day <= $endDay; ++$day) { if (0 === $day) { // Current day. if ($startTime && $startTime instanceof \DateTime) { $date = clone $startTime; } else { $date = new \DateTime(); } } else { // Future days. // Use noon to begin to evaluate days in the future to avoiding timezones during day checks. $date = new \DateTime('noon +'.$day.' day'); } try { // Initialize the range (will expand as appropriate later). $start = clone $date; $end = clone $date; // Evaluate that the client is open this day of the week. $hours = $this->evaluateDay(true, $date); // Evaluate that the client isn't closed by an excluded date rule. $this->evaluateExclusions($date); // Push the end time to the correct time for this client's hours. $timeTill = !empty($hours->timeTill) ? $hours->timeTill : '23:59'; $end->setTimezone($this->timezone); $end->modify($timeTill.':59'); // Current day: Evaluate that there is still time today to send. if (0 == $day && $this->now > $end) { // Continue to the next day. continue; } // Pull the start time to the correct time for this day and schedule. $timeFrom = !empty($hours->timeFrom) ? $hours->timeFrom : '00:00'; $start->setTimezone($this->timezone); $start->modify($timeFrom); if ('file' === $this->contactClient->getType()) { // Evaluate if we have exceeded allowed file count for this day. $fileCount = $this->evaluateFileRate($fileRate, $date); // If we have already built a file in this day and can send more... if ($fileCount > 0 && $fileRate > 1) { // Push the start time to the next available slot in this day. $daySeconds = $end->format('U') - $start->format('U'); if ('00:00' === $timeFrom && '23:59' === $timeTill) { // Avoid sending 2 files at midnight. $segmentSeconds = intval($daySeconds / $fileRate); } else { // Send at opening and closing times, spreading the rest of the day evenly. $segmentSeconds = intval($daySeconds / ($fileRate - 1)); } // Push start time to the next segment. $start->modify('+'.($segmentSeconds * $fileCount).' seconds'); } } // Start time should not be in the past. if (0 === $day && $start < $this->now) { // Must be done after rate has been applied. $start = $this->now; } $openings[] = [$start, $end]; if (!$all) { break; } } catch (\Exception $e) { if ($e instanceof ContactClientException) { // Expected. } else { throw $e; } } } return $openings; }
[ "public", "function", "findOpening", "(", "$", "startDay", "=", "0", ",", "$", "endDay", "=", "7", ",", "$", "fileRate", "=", "1", ",", "$", "all", "=", "false", ",", "$", "startTime", "=", "null", ")", "{", "$", "openings", "=", "[", "]", ";", "for", "(", "$", "day", "=", "$", "startDay", ";", "$", "day", "<=", "$", "endDay", ";", "++", "$", "day", ")", "{", "if", "(", "0", "===", "$", "day", ")", "{", "// Current day.", "if", "(", "$", "startTime", "&&", "$", "startTime", "instanceof", "\\", "DateTime", ")", "{", "$", "date", "=", "clone", "$", "startTime", ";", "}", "else", "{", "$", "date", "=", "new", "\\", "DateTime", "(", ")", ";", "}", "}", "else", "{", "// Future days.", "// Use noon to begin to evaluate days in the future to avoiding timezones during day checks.", "$", "date", "=", "new", "\\", "DateTime", "(", "'noon +'", ".", "$", "day", ".", "' day'", ")", ";", "}", "try", "{", "// Initialize the range (will expand as appropriate later).", "$", "start", "=", "clone", "$", "date", ";", "$", "end", "=", "clone", "$", "date", ";", "// Evaluate that the client is open this day of the week.", "$", "hours", "=", "$", "this", "->", "evaluateDay", "(", "true", ",", "$", "date", ")", ";", "// Evaluate that the client isn't closed by an excluded date rule.", "$", "this", "->", "evaluateExclusions", "(", "$", "date", ")", ";", "// Push the end time to the correct time for this client's hours.", "$", "timeTill", "=", "!", "empty", "(", "$", "hours", "->", "timeTill", ")", "?", "$", "hours", "->", "timeTill", ":", "'23:59'", ";", "$", "end", "->", "setTimezone", "(", "$", "this", "->", "timezone", ")", ";", "$", "end", "->", "modify", "(", "$", "timeTill", ".", "':59'", ")", ";", "// Current day: Evaluate that there is still time today to send.", "if", "(", "0", "==", "$", "day", "&&", "$", "this", "->", "now", ">", "$", "end", ")", "{", "// Continue to the next day.", "continue", ";", "}", "// Pull the start time to the correct time for this day and schedule.", "$", "timeFrom", "=", "!", "empty", "(", "$", "hours", "->", "timeFrom", ")", "?", "$", "hours", "->", "timeFrom", ":", "'00:00'", ";", "$", "start", "->", "setTimezone", "(", "$", "this", "->", "timezone", ")", ";", "$", "start", "->", "modify", "(", "$", "timeFrom", ")", ";", "if", "(", "'file'", "===", "$", "this", "->", "contactClient", "->", "getType", "(", ")", ")", "{", "// Evaluate if we have exceeded allowed file count for this day.", "$", "fileCount", "=", "$", "this", "->", "evaluateFileRate", "(", "$", "fileRate", ",", "$", "date", ")", ";", "// If we have already built a file in this day and can send more...", "if", "(", "$", "fileCount", ">", "0", "&&", "$", "fileRate", ">", "1", ")", "{", "// Push the start time to the next available slot in this day.", "$", "daySeconds", "=", "$", "end", "->", "format", "(", "'U'", ")", "-", "$", "start", "->", "format", "(", "'U'", ")", ";", "if", "(", "'00:00'", "===", "$", "timeFrom", "&&", "'23:59'", "===", "$", "timeTill", ")", "{", "// Avoid sending 2 files at midnight.", "$", "segmentSeconds", "=", "intval", "(", "$", "daySeconds", "/", "$", "fileRate", ")", ";", "}", "else", "{", "// Send at opening and closing times, spreading the rest of the day evenly.", "$", "segmentSeconds", "=", "intval", "(", "$", "daySeconds", "/", "(", "$", "fileRate", "-", "1", ")", ")", ";", "}", "// Push start time to the next segment.", "$", "start", "->", "modify", "(", "'+'", ".", "(", "$", "segmentSeconds", "*", "$", "fileCount", ")", ".", "' seconds'", ")", ";", "}", "}", "// Start time should not be in the past.", "if", "(", "0", "===", "$", "day", "&&", "$", "start", "<", "$", "this", "->", "now", ")", "{", "// Must be done after rate has been applied.", "$", "start", "=", "$", "this", "->", "now", ";", "}", "$", "openings", "[", "]", "=", "[", "$", "start", ",", "$", "end", "]", ";", "if", "(", "!", "$", "all", ")", "{", "break", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "if", "(", "$", "e", "instanceof", "ContactClientException", ")", "{", "// Expected.", "}", "else", "{", "throw", "$", "e", ";", "}", "}", "}", "return", "$", "openings", ";", "}" ]
Given the hours of operation, timezone and excluded dates of the client... Find the next appropriate time to send them contacts. @param int $startDay Set to 1 to start the seek tomorrow, 0 for today @param int $endDay Maximum number of days forward to seek for an opening @param int $fileRate Maximum number of files to build per day (applies to file seek only) @param bool $all Indicates we want all the openings in the range of days @param string $startTime Optional start time to begin forward search on the current day as a string @return array @throws \Exception
[ "Given", "the", "hours", "of", "operation", "timezone", "and", "excluded", "dates", "of", "the", "client", "...", "Find", "the", "next", "appropriate", "time", "to", "send", "them", "contacts", "." ]
train
https://github.com/TheDMSGroup/mautic-contact-client/blob/5874413494d1c73bc18749c0e75c87e7ccc6d65a/Model/Schedule.php#L110-L193