_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q261800
Array2Xml.convert
test
protected function convert(\DOMDocument $DOMDocument, \DOMElement $ParentDOMElement, array $array) { foreach ($array as $_child_key => $_child_value) { if (is_string($_child_key)) { // Allows duplicate string keys. $_child_key = preg_replace('/^[0-9]+_/u', '', $_child_key); } if (is_array($_child_value)) { // Nested tag. $_ChildDOMElement = $DOMDocument->createElement($_child_key); $ParentDOMElement->appendChild($_ChildDOMElement); $this->convert($DOMDocument, $_ChildDOMElement, $_child_value); // } elseif (is_scalar($_child_value)) { // Must be scalar. // String keys become attributes; numeric keys text nodes. $_child_value = (string) $_child_value; // Force string. if (is_string($_child_key)) { $_ChildDOMAttr = $DOMDocument->createAttribute($_child_key); $ParentDOMElement->appendChild($_ChildDOMAttr); $_ChildDOMAttr->value = $this->c::escAttr($_child_value); } else { $_ChildDOMText = $DOMDocument->createTextNode($_child_value); $ParentDOMElement->appendChild($_ChildDOMText); } } else { // Fail on unexpected values. throw $this->c::issue('Unexpected non-scalar child value.'); } } // unset($_child_key, $_child_value, $_ChildDOMElement, $_ChildDOMAttr, $_ChildDOMText); }
php
{ "resource": "" }
q261801
DefaultMarkerClusterHelper.renderMarker
test
protected function renderMarker(Marker $marker, Map $map) { return sprintf( '%s.markers.%s = %s', $this->getJsContainerName($map), $marker->getJavascriptVariable(), $this->markerHelper->render($marker, $map) ); }
php
{ "resource": "" }
q261802
Keygen.license
test
public function license(): string { $key = mb_strtoupper($this->c::uuidV4()); return $key = implode('-', str_split($key, 8)); }
php
{ "resource": "" }
q261803
CoreExtensionHelper.getLibraries
test
protected function getLibraries(Map $map) { $libraries = $map->getLibraries(); $encodedPolylines = $map->getEncodedPolylines(); if (!empty($encodedPolylines)) { $libraries[] = 'geometry'; } return array_unique($libraries); }
php
{ "resource": "" }
q261804
Sql.escapeOrder
test
public function escapeOrder(string $order): string { $string = mb_strtoupper($order); return in_array($order, ['ASC', 'DESC'], true) ? $order : 'ASC'; }
php
{ "resource": "" }
q261805
Serializer.serializeClosure
test
public function serializeClosure(\Closure $Closure, bool $faster = false): string { // NOTE: No marker; i.e., so this can be called stand-alone if necessary. return $this->{$faster ? 'ClosureTokenSerializer' : 'ClosureAstSerializer'}->serialize($Closure); }
php
{ "resource": "" }
q261806
Serializer.unserializeClosure
test
public function unserializeClosure(string $string, bool $faster = false): \Closure { if (mb_strpos($string, $this::CLOSURE) === 0) { $string = mb_substr($string, mb_strlen($this::CLOSURE)); } return $this->{$faster ? 'ClosureTokenSerializer' : 'ClosureAstSerializer'}->unserialize($string); }
php
{ "resource": "" }
q261807
Serializer.maybeSerialize
test
public function maybeSerialize($value, bool $strict = true): string { if (!$strict) { if (is_string($value)) { return $string = $value; } elseif (is_bool($value)) { return $string = (string) (int) $value; } elseif (is_int($value) || is_float($value)) { return $string = (string) $value; } else { // Serialize. return $string = $this->__invoke($value); } } else { // Default. if (is_string($value)) { return $string = $value; } else { // Serialize. return $string = $this->__invoke($value); } } }
php
{ "resource": "" }
q261808
Serializer.maybeUnserialize
test
public function maybeUnserialize($value) { if ($value && $this->isSerialized($value)) { if (mb_strpos($value, $this::CLOSURE) === 0) { return $this->unserializeClosure($value); } else { return unserialize($value); } } else { return $value; // Not applicable. } }
php
{ "resource": "" }
q261809
OEmbed.embedlyMarkup
test
protected function embedlyMarkup(string $url, \StdClass $embed): string { $markup = ''; // Initialize HTML markup. if (!$url || empty($embed->type) || empty($embed->provider_name)) { return $markup; // Not possible; i.e., empty string. } $provider_slug = $this->c::nameToSlug($embed->provider_name); $classes = '_-embedly _-'.$embed->type.' _-'.$provider_slug; switch ($embed->type) { // See: <http://jas.xyz/1O7ymwT> case 'rich': case 'video': if (!empty($embed->html)) { $markup = '<div class="'.$this->c::escAttr($classes).'">'. $embed->html. '</div>'; } break; case 'photo': if (!empty($embed->url) && isset($embed->width, $embed->height)) { $markup = '<div class="'.$this->c::escAttr($classes).'">'. '<a href="'.$this->c::escUrl($url).'" title="'.$this->c::escAttr($embed->title ?? '').'">'. '<img src="'.$this->c::escUrl($embed->url).'" width="'.$this->c::escAttr((string) $embed->width).'" height="'.$this->c::escAttr((string) $embed->height).'" alt="" />'. '</a>'. '</div>'; } break; case 'link': if (!empty($embed->thumbnail_url) && isset($embed->thumbnail_width, $embed->thumbnail_height)) { $markup = '<div class="'.$this->c::escAttr($classes).'">'. '<a href="'.$this->c::escUrl($url).'" title="'.$this->c::escAttr($embed->title ?? '').'">'. '<img src="'.$this->c::escUrl($embed->thumbnail_url).'" width="'.$this->c::escAttr((string) $embed->thumbnail_width).'" height="'.$this->c::escAttr((string) $embed->thumbnail_height).'" alt="" />'. '</a>'. '</div>'; } break; } return $markup; }
php
{ "resource": "" }
q261810
OEmbed.getEmbedlyCache
test
protected function getEmbedlyCache(string $url) { $cache_dir = $this->cache_dir.'/embedly'; $cache_dir .= '/'.$this->c::sha1ModShardId($url); $cache_file = $cache_dir.'/'.sha1($url); if (is_file($cache_file)) { $embed = file_get_contents($cache_file); $embed = unserialize($embed); if ($embed instanceof \StdClass) { return $embed; } } }
php
{ "resource": "" }
q261811
OEmbed.viaWordPress
test
protected function viaWordPress(string $string): string { if (!$this->c::isWordPress() || !$this->c::canCallFunc('wp_oembed_get') || !$this->c::canCallFunc('wp_embed_defaults')) { throw $this->c::issue('Unable to oEmbed via WordPress.'); } $oembed_args = array_merge(wp_embed_defaults(), ['discover' => false]); $string = preg_replace_callback('/^\s*(https?:\/\/[^\s"]+)\s*$/uim', function ($m) use ($oembed_args) { $oembed = wp_oembed_get($m[1], $oembed_args); return $oembed ? $oembed : $m[0]; }, $string); return $string; }
php
{ "resource": "" }
q261812
EncodedPolylineHelper.render
test
public function render(EncodedPolyline $encodedPolyline, Map $map) { $this->jsonBuilder ->reset() ->setValue('[map]', $map->getJavascriptVariable(), false) ->setValue('[path]', $this->encodingHelper->renderDecodePath($encodedPolyline->getValue()), false) ->setValues($encodedPolyline->getOptions()); return sprintf( '%s = new google.maps.Polyline(%s);'.PHP_EOL, $encodedPolyline->getJavascriptVariable(), $this->jsonBuilder->build() ); }
php
{ "resource": "" }
q261813
Bound.setSouthWest
test
public function setSouthWest() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof Coordinate)) { $this->southWest = $args[0]; } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) { if ($this->southWest === null) { $this->southWest = new Coordinate(); } $this->southWest->setLatitude($args[0]); $this->southWest->setLongitude($args[1]); if (isset($args[2]) && is_bool($args[2])) { $this->southWest->setNoWrap($args[2]); } } elseif (!isset($args[0])) { $this->southWest = null; } else { throw BaseException::invalidBoundSouthWest(); } }
php
{ "resource": "" }
q261814
Bound.setNorthEast
test
public function setNorthEast() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof Coordinate)) { $this->northEast = $args[0]; } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) { if ($this->northEast === null) { $this->northEast = new Coordinate(); } $this->northEast->setLatitude($args[0]); $this->northEast->setLongitude($args[1]); if (isset($args[2]) && is_bool($args[2])) { $this->northEast->setNoWrap($args[2]); } } elseif (!isset($args[0])) { $this->northEast = null; } else { throw BaseException::invalidBoundNorthEast(); } }
php
{ "resource": "" }
q261815
Bound.getCenter
test
public function getCenter() { $centerLatitude = ($this->getSouthWest()->getLatitude() + $this->getNorthEast()->getLatitude()) / 2; $centerLongitude = ($this->getSouthWest()->getLongitude() + $this->getNorthEast()->getLongitude()) / 2; return new Coordinate($centerLatitude, $centerLongitude); }
php
{ "resource": "" }
q261816
FileSize.abbrBytes
test
public function abbrBytes(string $string): int { if (!preg_match('/^(?<value>[0-9\.]+)\s*(?<modifier>bytes|byte|kbs|kb|k|mb|m|gb|g|tb|t)$/ui', $string, $_m)) { return 0; // Default value of `0`, failure. } $value = (float) $_m['value']; $modifier = mb_strtolower($_m['modifier']); // unset($_m); // Housekeeping. switch ($modifier) { case 't': case 'tb': $value *= 1024; // Fall through. // no break case 'g': case 'gb': $value *= 1024; // Fall through. // no break case 'm': case 'mb': $value *= 1024; // Fall through. // no break case 'k': case 'kb': case 'kbs': $value *= 1024; } return (int) $value; }
php
{ "resource": "" }
q261817
FileSize.remoteBytes
test
public function remoteBytes(string $url, bool $report_failure = false, int $expires_after = 86400): int { if (!$url) { // If no URL, no file size. return $report_failure ? -1 : 0; } if (($bytes = $this->c::dirCacheGet(__METHOD__, $url)) !== null) { return $bytes; // Cached this already. } // Get from an existing cache if at all possible. $r = $this->c::remoteResponse('HEAD::'.$url, [ 'max_con_secs' => 5, 'max_stream_secs' => 5, ]); if ($r->code === 200 && isset($r->headers['content-length'])) { $bytes = (int) $r->headers['content-length']; } else { $bytes = $report_failure ? -1 : 0; // Not possible. } $this->c::dirCacheSet(__METHOD__, $url, $bytes, $expires_after); return $bytes; // Cached for future reference. }
php
{ "resource": "" }
q261818
UrlParse.un
test
public function un(array $parts): string { $scheme = ''; $host = $port = ''; $user = $pass = ''; $path = $query = $fragment = ''; $parts = array_map('strval', $parts); if (isset($parts['scheme'][0])) { if ($parts['scheme'] === '//') { $scheme = $parts['scheme']; } else { $scheme = $parts['scheme'].'://'; } } // Supports cross-protocol scheme. if (isset($parts['host'][0])) { $host = $parts['host']; } if (isset($parts['port'][0])) { $port = ':'.$parts['port']; } if (isset($parts['user'][0])) { $user = $parts['user']; } if (isset($parts['pass'][0])) { $pass = ':'.$parts['pass']; } if (isset($user[0]) || isset($pass[0])) { $pass .= '@'; // `user@`, `:pass@`, or `user:pass@`. } if (isset($parts['path'][0])) { $path = '/'.$this->c::mbLTrim($parts['path'], '/'); } if (isset($parts['query'][0])) { $query = '?'.$parts['query']; } if (isset($parts['fragment'][0])) { $fragment = '#'.$parts['fragment']; } return $scheme.$user.$pass.$host.$port.$path.$query.$fragment; }
php
{ "resource": "" }
q261819
CoordinateHelper.render
test
public function render(Coordinate $coordinate) { return sprintf( '%s = new google.maps.LatLng(%s, %s, %s);'.PHP_EOL, $coordinate->getJavascriptVariable(), $coordinate->getLatitude(), $coordinate->getLongitude(), json_encode($coordinate->isNoWrap()) ); }
php
{ "resource": "" }
q261820
MarkerImageHelper.render
test
public function render(MarkerImage $markerImage) { return sprintf( '%s = new google.maps.MarkerImage("%s", %s, %s, %s, %s);'.PHP_EOL, $markerImage->getJavascriptVariable(), $markerImage->getUrl(), $markerImage->hasSize() ? $markerImage->getSize()->getJavascriptVariable() : 'null', $markerImage->hasOrigin() ? $markerImage->getOrigin()->getJavascriptVariable() : 'null', $markerImage->hasAnchor() ? $markerImage->getAnchor()->getJavascriptVariable() : 'null', $markerImage->hasScaledSize() ? $markerImage->getScaledSize()->getJavascriptVariable() : 'null' ); }
php
{ "resource": "" }
q261821
XmlParser.parse
test
public function parse($xml, array $pluralizationRules = array()) { $parsedXml = json_decode(json_encode(new \SimpleXMLElement($xml)), true); return $this->pluralize($parsedXml, $pluralizationRules); }
php
{ "resource": "" }
q261822
XmlParser.pluralize
test
protected function pluralize(array $xml, array $rules) { foreach ($xml as $attribute => $value) { if (isset($rules[$attribute])) { $xml[$rules[$attribute]] = $value; unset($xml[$attribute]); $attribute = $rules[$attribute]; if (!is_array($value) || is_string(key($value))) { $xml[$attribute] = array($value); } } if (is_array($xml[$attribute])) { $xml[$attribute] = $this->pluralize($xml[$attribute], $rules); } } return $this->normalize($xml); }
php
{ "resource": "" }
q261823
DistanceMatrixException.invalidDistanceMatrixRequestTravelMode
test
public static function invalidDistanceMatrixRequestTravelMode() { $travelModes = array_diff(TravelMode::getTravelModes(), array(TravelMode::TRANSIT)); return new static(sprintf( 'The distance matrix request travel mode can only be : %s.', implode(', ', $travelModes) )); }
php
{ "resource": "" }
q261824
UrlHost.parse
test
public function parse(string $host, bool $no_port = false): array { $host = mb_strtolower($host); // `abc.xyz.example.com:80`. $name = preg_replace('/\:[0-9]+$/u', '', $host); // `abc.xyz.example.com`. $port = (explode(':', $host, 2) + ['', ''])[1]; // `80`; i.e., port number. $name_parts = explode('.', $name); // `[abc,xyz,example,com]`. $subs = array_slice($name_parts, 0, -2); // `[abc,xyz]`. $sub = implode('.', $subs); // `abc.xyz`. $root_name = implode('.', array_slice($name_parts, -2)); // `example.com`. $root_port = $port; // This is nothing more than a copy of the `$port`; `80`. $root = $root_name.(isset($root_port[0]) ? ':'.$root_port : ''); // `example.com:80`. $root_basename = implode('.', array_slice($name_parts, -2, 1)); // `example`. $tld = implode('.', array_slice($name_parts, -1)); // `com`, `net`, `org`, etc. return compact('name', 'port', 'sub', 'subs', 'root', 'root_name', 'root_port', 'root_basename', 'tld'); }
php
{ "resource": "" }
q261825
UrlHost.unParse
test
public function unParse(array $parts): string { $name = $port= ''; if (isset($parts['name'][0])) { $name = $parts['name']; } if (isset($parts['port'][0])) { $port = ':'.$parts['port']; } return $name.$port; }
php
{ "resource": "" }
q261826
Marker.setPosition
test
public function setPosition() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof Coordinate)) { $this->position = $args[0]; } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) { $this->position->setLatitude($args[0]); $this->position->setLongitude($args[1]); if (isset($args[2]) && is_bool($args[2])) { $this->position->setNoWrap($args[2]); } } elseif (!isset($args[0])) { $this->position = null; } else { throw OverlayException::invalidMarkerPosition(); } }
php
{ "resource": "" }
q261827
Marker.setAnimation
test
public function setAnimation($animation = null) { if (!in_array($animation, Animation::getAnimations()) && ($animation !== null)) { throw OverlayException::invalidMarkerAnimation(); } $this->animation = $animation; }
php
{ "resource": "" }
q261828
Marker.setIcon
test
public function setIcon() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof MarkerImage)) { if ($args[0]->getUrl() === null) { throw OverlayException::invalidMarkerIconUrl(); } $this->icon = $args[0]; } elseif (isset($args[0]) && is_string($args[0])) { if ($this->icon === null) { $this->icon = new MarkerImage(); } $this->icon->setUrl($args[0]); } elseif (!isset($args[0])) { $this->icon = null; } else { throw OverlayException::invalidMarkerIcon(); } }
php
{ "resource": "" }
q261829
Marker.setShadow
test
public function setShadow() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof MarkerImage)) { if ($args[0]->getUrl() === null) { throw OverlayException::invalidMarkerShadowUrl(); } $this->shadow = $args[0]; } elseif (isset($args[0]) && is_string($args[0])) { if ($this->shadow === null) { $this->shadow = new MarkerImage(); } $this->shadow->setUrl($args[0]); } elseif (!isset($args[0])) { $this->shadow = null; } else { throw OverlayException::invalidMarkerShadow(); } }
php
{ "resource": "" }
q261830
Marker.setShape
test
public function setShape() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof MarkerShape)) { if (!$args[0]->hasCoordinates()) { throw OverlayException::invalidMarkerShapeCoordinates(); } $this->shape = $args[0]; } elseif ((isset($args[0]) && is_string($args[0])) && (isset($args[1]) && is_array($args[1]))) { if ($this->shape === null) { $this->shape = new MarkerShape(); } $this->shape->setType($args[0]); $this->shape->setCoordinates($args[1]); } elseif (!isset($args[0])) { $this->shape = null; } else { throw OverlayException::invalidMarkerShape(); } }
php
{ "resource": "" }
q261831
Markdown.headerIdCallback
test
public function headerIdCallback(string $raw): string { $id = mb_strtolower($raw); $id = preg_replace('/[^\w]+/u', '-', $id); $id = 'j2h.'.$this->c::mbTrim($id, '', '-'); $this->header_id_counter[$id] = $this->header_id_counter[$id] ?? 0; ++$this->header_id_counter[$id]; // Increment counter. if ($this->header_id_counter[$id] > 1) { $id .= '-'.$this->header_id_counter[$id]; } return $id; // `id=""` attribute value. }
php
{ "resource": "" }
q261832
Markdown.firstImageUrl
test
public function firstImageUrl(string $markdown): string { $regex = '/(?<=^|[\s;,])\!\[[^\v[\]]*\]\((?<url>https?\:\/\/[^\s()]+?\.(?:png|jpeg|jpg|gif))\)(?=$|[\s.!?;,])/ui'; return $url = $markdown && preg_match($regex, $markdown, $_m) ? $_m['url'] : ''; }
php
{ "resource": "" }
q261833
HtmlStrip.attributes
test
public function attributes($value, array $args = []) { if (is_array($value) || is_object($value)) { foreach ($value as $_key => &$_value) { $_value = $this->attributes($_value, $args); } // unset($_key, $_value); return $value; } if (!($string = (string) $value)) { return $string; // Nothing to do. } $default_args = [ 'allowed_attributes' => [], ]; $args = array_merge($default_args, $args); $args = array_intersect_key($args, $default_args); $allowed_attributes = // Force lowercase. array_map('mb_strtolower', (array) $args['allowed_attributes']); $regex_tags = '/(?<open>\<[\w\-]+)(?<attrs>[^>]+)(?<close>\>)/ui'; $regex_attrs = '/\s+(?<attr>[\w\-]+)(?:\s*\=\s*(["\']).*?\\2|\s*\=[^\s]*)?/uis'; return preg_replace_callback($regex_tags, function ($m) use ($allowed_attributes, $regex_attrs) { return $m['open'].preg_replace_callback($regex_attrs, function ($m) use ($allowed_attributes) { return in_array(mb_strtolower($m['attr']), $allowed_attributes, true) ? $m[0] : ''; }, $m['attrs']).$m['close']; // With modified attributes. }, $string); // Removes attributes; leaving only those allowed explicitly. }
php
{ "resource": "" }
q261834
Rectangle.setBound
test
public function setBound() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof Bound)) { if (!$args[0]->hasCoordinates()) { throw OverlayException::invalidRectangleBoundCoordinates(); } $this->bound = $args[0]; } elseif ((isset($args[0]) && ($args[0] instanceof Coordinate)) && (isset($args[1]) && ($args[1] instanceof Coordinate)) ) { $this->bound->setSouthWest($args[0]); $this->bound->setNorthEast($args[1]); } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1])) && (isset($args[2]) && is_numeric($args[2])) && (isset($args[3]) && is_numeric($args[3])) ) { $this->bound->setSouthWest(new Coordinate($args[0], $args[1])); $this->bound->setNorthEast(new Coordinate($args[2], $args[3])); if (isset($args[4]) && is_bool($args[4])) { $this->bound->getSouthWest()->setNoWrap($args[4]); } if (isset($args[5]) && is_bool($args[5])) { $this->bound->getNorthEast()->setNoWrap($args[5]); } } else { throw OverlayException::invalidRectangleBound(); } }
php
{ "resource": "" }
q261835
Error.message
test
public function message(string $slug = ''): string { $slug = $slug ?: $this->slug(); $messages = $this->messages($slug); return $messages[0] ?? $this->default_message; }
php
{ "resource": "" }
q261836
Error.messages
test
public function messages(string $slug = '', bool $by_slug = false): array { if (!$slug) { // All messages (i.e., for all slugs)? // if ($by_slug) { // All messages keyed by slug? return $this->errors ?: [$this->default_slug => $this->default_message]; // } else { // Merge all messages into a single array. $messages = []; // Initialize array. foreach ($this->errors as $_slug => $_messages) { $messages = array_merge($messages, $_messages); } // unset($_slug, $_messages); // Housekeeping. return $messages ?: [$this->default_message]; } } else { // For a specific slug. $messages = $this->errors[$slug] ?? []; return $messages ?: [$this->default_message]; } }
php
{ "resource": "" }
q261837
Error.data
test
public function data(string $slug = '', bool $by_slug = false) { if (!$slug) { // All data (i.e., for all slugs)? // if ($by_slug) { // All data keyed by slug? return $this->error_data ?: [$this->default_slug => null]; // } else { // Data for the first slug. // NOTE: Different than `messages()`. $slug = $this->slug(); // First slug. return $this->error_data[$slug] ?? null; } } else { return $this->error_data[$slug] ?? null; } }
php
{ "resource": "" }
q261838
Error.add
test
public function add(string $slug, string $message = '', $data = null) { $slug = $slug ?: $this->default_slug; if (!$message && $slug === $this->default_slug) { $message = $this->default_message; } elseif (!$message) { // If empty, base it on slug. $message = mb_strtolower($this->c::slugToName($slug)); $message = $this->c::mbUcFirst($message).'.'; } $this->errors[$slug][] = $message; if (isset($data) || !array_key_exists($slug, $this->error_data)) { $this->error_data[$slug] = $data; } }
php
{ "resource": "" }
q261839
Polygon.addCoordinate
test
public function addCoordinate() { $args = func_get_args(); if (isset($args[0]) && ($args[0] instanceof Coordinate)) { $this->coordinates[] = $args[0]; } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) { $coordinate = new Coordinate($args[0], $args[1]); if (isset($args[2]) && is_bool($args[2])) { $coordinate->setNoWrap($args[2]); } $this->coordinates[] = $coordinate; } else { throw OverlayException::invalidPolygonCoordinate(); } }
php
{ "resource": "" }
q261840
PrettyMin.load
test
public function load($html) { if ($html instanceof \DOMDocument) { $d = $html; } elseif ($html instanceof \DOMElement) { $d = $html->ownerDocument; } elseif ($html instanceof \SplFileInfo) { $d = new \DOMDocument(); $d->preserveWhiteSpace = false; $d->validateOnParse = true; $d->loadHTMLFile($html->getPathname()); } else { $d = new \DOMDocument(); $d->preserveWhiteSpace = false; $d->validateOnParse = true; $d->loadHTML($html); } $d->formatOutput = false; $d->normalizeDocument(); $this->doc = $d; return $this; }
php
{ "resource": "" }
q261841
PrettyMin.minify
test
public function minify($options = []) { $resolver = new OptionsResolver(); $resolver->setDefaults([ 'minify_js' => $this->options['minify_js'], 'minify_css' => $this->options['minify_css'], 'remove_comments' => $this->options['remove_comments'], 'remove_empty_attributes' => $this->options['remove_empty_attributes'] ]); $options = $resolver->resolve($options); if ($options['minify_js']) { $this->minifyJavascript(); } if ($options['minify_css']) { $this->minifyCss(); } if ($options['remove_comments']) { $this->removeComments(); } if ($options['remove_empty_attributes']) { $this->removeEmptyAttributes(); } $this->removeWhitespace(); return $this; }
php
{ "resource": "" }
q261842
PrettyMin.indentRecursive
test
protected function indentRecursive(\DOMNode $currentNode, $depth) { $indent_characters = $this->options['indent_characters']; $indentCurrent = true; $indentChildren = true; $indentClosingTag = false; if(($currentNode->nodeType == XML_TEXT_NODE)) { $indentCurrent = false; } if (in_array($currentNode->nodeName, $this->options['keep_whitespace_in'])) { $indentCurrent = true; $indentChildren = false; $indentClosingTag = (strpos($currentNode->nodeValue, "\n") !== false); } if (in_array($currentNode->nodeName, $this->options['keep_whitespace_around'])) { $indentCurrent = false; } if($indentCurrent && $depth > 0) { // Indenting a node consists of inserting before it a new text node // containing a newline followed by a number of tabs corresponding // to the node depth. $textNode = $currentNode->ownerDocument->createTextNode("\n" . str_repeat($indent_characters, $depth)); $currentNode->parentNode->insertBefore($textNode, $currentNode); } if($indentCurrent && $currentNode->childNodes && $indentChildren) { foreach($currentNode->childNodes as $childNode) { $indentClosingTag = $this->indentRecursive($childNode, $depth + 1); } } if($indentClosingTag) { // If children have been indented, then the closing tag // of the current node must also be indented. if ($currentNode->lastChild && ($currentNode->lastChild->nodeType == XML_CDATA_SECTION_NODE || $currentNode->lastChild->nodeType == XML_TEXT_NODE) && preg_match('/\n\s?$/', $currentNode->lastChild->textContent)) { $currentNode->lastChild->nodeValue = preg_replace('/\n\s?$/', "\n" . str_repeat("\t", $depth), $currentNode->lastChild->nodeValue); } else { $textNode = $currentNode->ownerDocument->createTextNode("\n" . str_repeat("\t", $depth)); $currentNode->appendChild($textNode); } } return $indentCurrent; }
php
{ "resource": "" }
q261843
InjectOrganizationReferenceListener.postLoad
test
public function postLoad(LifecycleEventArgs $args) { $document = $args->getDocument(); if ($document instanceof UserInterface) { $repository = $args->getDocumentManager()->getRepository('Organizations\Entity\Organization'); $userId = $document->getId(); $reference = new OrganizationReference($userId, $repository); $document->setOrganization($reference); } }
php
{ "resource": "" }
q261844
InviteEmployeeController.createSetPasswordViewModel
test
protected function createSetPasswordViewModel() { $organization = $this->getOrganizationEntity(); $result = $this->forward()->dispatch('Auth\Controller\Password', array('action' => 'index')); $model = new ViewModel( array( 'organization' => $organization->getOrganizationName()->getName() ) ); if (!$result->getVariable('valid', false)) { $model->setVariable('form', $result->getVariable('form')); } return $model; }
php
{ "resource": "" }
q261845
InviteEmployeeController.getOrganizationEntity
test
protected function getOrganizationEntity() { /* @var $orgRepo \Organizations\Repository\Organization */ $orgRepo = $this->orgRepo; $organiationId = $this->params()->fromQuery('organization'); $organization = $orgRepo->find($organiationId); return $organization; }
php
{ "resource": "" }
q261846
InviteEmployeeController.createErrorViewModel
test
protected function createErrorViewModel($message) { /* @var $response \Zend\Http\Response */ $response = $this->getResponse(); $response->setStatusCode(500); $model = new ViewModel(array('message' => $message)); $model->setTemplate('organizations/error/invite'); return $model; }
php
{ "resource": "" }
q261847
FrontendAsset.add
test
public function add($file, $params = 'footer', $onUnknownExtension = false) { RoumenAsset::add($this->elixir($file), $params, $onUnknownExtension); }
php
{ "resource": "" }
q261848
FrontendAsset.reverseStylesOrder
test
public function reverseStylesOrder($params = 'footer') { if (isset(RoumenAsset::$scripts[$params])) { RoumenAsset::$scripts[$params] = array_reverse(RoumenAsset::$scripts[$params], true); } }
php
{ "resource": "" }
q261849
FrontendAsset.addFirst
test
public function addFirst($file, $params = 'footer', $onUnknownExtension = false) { RoumenAsset::addFirst($this->elixir($file), $params, $onUnknownExtension); }
php
{ "resource": "" }
q261850
FrontendAsset.addAfter
test
public function addAfter($file1, $file2, $params = 'footer', $onUnknownExtension = false) { RoumenAsset::addAfter($this->elixir($file1), $this->elixir($file2), $params, $onUnknownExtension); }
php
{ "resource": "" }
q261851
FrontendAsset.addMeta
test
public function addMeta($meta, $data = []) { if (is_string($meta)) { $meta = [$meta => $data]; } foreach ($meta as $key => $data) { self::$meta[$key] = $data; } }
php
{ "resource": "" }
q261852
FrontendAsset.meta
test
public function meta() { foreach(self::$meta as $name => $attributes) { echo Html::meta() ->name(array_has($attributes, 'config.noname') ? false : $name) ->addAttributes(array_except($attributes, ['config'])); echo "\n"; } }
php
{ "resource": "" }
q261853
FrontendAsset.controller
test
public function controller($file_extensions, $file) { // Only look in a single file extension folder. if (!is_array($file_extensions)) { $file_extensions = [$file_extensions]; } // Replace dots with slashes. $file = str_replace('.', '/', $file); if (substr($file, -1) === '*') { $folder = dirname(substr($file, 0, -1)); $base_folder = basename(substr($file, 0, -1)); foreach ($file_extensions as $extension) { $extension_folder = $folder.'/'.$extension.'/'.$base_folder; $folder_contents = scandir(resource_path().'/views/'.$extension_folder); foreach ($folder_contents as $folder_file) { if ($folder_file == '.' || $folder_file == '..') { continue; } $full_path = resource_path().'/views/'.$extension_folder.'/'.$folder_file; $file_name = $extension_folder.'/'.$folder_file; $this->loadFile($file_name, $extension, $full_path); } } return; } // Go through each file extension folder. foreach ($file_extensions as $extension) { $file_name = $file.'.'.$extension; $local_file_path = dirname(resource_path().'/views/'.$file_name); $local_file_path .= '/'.$extension.'/'.basename($file_name); $full_path = ''; if (env('APP_ENV') == 'local') { if (file_exists($local_file_path)) { $full_path = $local_file_path; } else { $full_path = public_path().'/assets/'.$file_name; } } $this->loadFile($file_name, $extension, $full_path); } }
php
{ "resource": "" }
q261854
FrontendAsset.loadFile
test
public function loadFile($file_name, $extension, $full_path = '') { if (array_has(config('rev-manifest', []), $file_name) || (!empty($full_path) && file_exists($full_path))) { if (env('APP_ASSET_INLINE', false)) { if (!isset($this->loaded_inline[$full_path])) { $contents = file_get_contents($full_path); $contents = '/* '.$file_name." */ \n\n".$contents; if ($extension == 'js') { $this->addScript($contents, 'inline'); } else { $this->addStyle($contents); } $this->loaded_inline[$full_path] = true; } } else { $this->add($file_name, 'ready'); } } }
php
{ "resource": "" }
q261855
PaginationQuery.createQuery
test
public function createQuery($params, $queryBuilder) { if ($params instanceof Parameters) { $value = $params->toArray(); } else { $value = $params; } /* * if user is recruiter or admin * filter query based on permissions.view */ $auth = $this->authService; $user = $auth->getUser(); $ignored = [null,'guest',UserInterface::ROLE_USER]; if (!in_array($user->getRole(), $ignored)) { $queryBuilder->field('permissions.view')->equals($user->getId()); } if (isset($params['q']) && $params['q'] && $params['q'] != 'en/organizations/profile') { $queryBuilder->text($params['q'])->language('none'); } if (!isset($value['sort'])) { $value['sort'] = '-date'; } $queryBuilder->sort($this->filterSort($value['sort'])); if (isset($params['type']) && $params['type'] === 'profile') { //@TODO: we should use aggregate query here $queryBuilder->field('profileSetting') ->in([Organization::PROFILE_ALWAYS_ENABLE,Organization::PROFILE_ACTIVE_JOBS]) ; $filters = $this->getOrganizationProfileFilters($queryBuilder); if (count($filters) > 0) { $queryBuilder->field('id')->notIn($filters); } } return $queryBuilder; }
php
{ "resource": "" }
q261856
InvitationHandler.process
test
public function process($email) { $translator = $this->getTranslator(); if (!$this->validateEmail($email)) { return array( 'ok' => false, 'message' => $translator->translate('Email address is invalid.') ); } $userAndToken = $this->loadOrCreateUser($email); try { $mailer = $this->getMailerPlugin(); $mailer('Organizations/InviteEmployee', $userAndToken, true); } catch (\Exception $e) { return array( 'ok' => false, 'message' => $translator->translate(trim('Sending invitation mail failed. '.$e->getMessage())) ); } $user = $userAndToken['user']; /* @var $user \Auth\Entity\User * @var $info \Auth\Entity\InfoInterface */ $info = $user->getInfo(); return array( 'ok' => true, 'result' => array( 'userId' => $user->getId(), 'userName' => $info->getDisplayName(), 'userEmail' => $email ) ); }
php
{ "resource": "" }
q261857
InvitationHandler.validateEmail
test
protected function validateEmail($email) { if (!$email) { return false; } $validator = $this->getEmailValidator(); return $validator->isValid($email); }
php
{ "resource": "" }
q261858
InvitationHandler.loadOrCreateUser
test
protected function loadOrCreateUser($email) { $repository = $this->getUserRepository(); $generator = $this->getUserTokenGenerator(); /* @var $user \Auth\Entity\User */ $user = $repository->findByEmail( $email, /*do not check isDraft flag */ null ); if (!$user) { $user = $repository->create(); $user->setEmail($email) ->setLogin($email) ->setRole(\Auth\Entity\User::ROLE_RECRUITER) ->setIsDraft(true); $info = $user->getInfo(); /* @var $info \Auth\Entity\InfoInterface */ $info->setEmail($email); } $token = $generator->generate( $user, /* daysToLive */ 7 ); // will store user! return array('user' => $user, 'token' => $token); }
php
{ "resource": "" }
q261859
OrganizationReference.load
test
protected function load() { if (null !== $this->_type) { return; } // Is the user the owner of the referenced organization? $org = $this->_repository->findByUser($this->_userId); if ($org) { $this->_type = self::TYPE_OWNER; $this->_organization = $org; return; } // Is the user employed by the referenced organization? $org = $this->_repository->findByEmployee($this->_userId); if ($org) { $this->_type = self::TYPE_EMPLOYEE; $this->_organization = $org; return; } // It seems the user is not associated with an organization. $this->_type = self::TYPE_NONE; }
php
{ "resource": "" }
q261860
OrganizationReference.proxy
test
protected function proxy($method) { if (!$this->hasAssociation()) { return $this; } $args = array_slice(func_get_args(), 1); $return = call_user_func_array(array($this->_organization, $method), $args); return ($return === $this->_organization) ? $this : $return; }
php
{ "resource": "" }
q261861
Organization.getHiringOrganizationsCursor
test
public function getHiringOrganizationsCursor(OrganizationInterface $organization) { $qb = $this->createQueryBuilder(); $qb->field('parent')->equals($organization->getId()); $qb->field('isDraft')->equals(false); $q = $qb->getQuery(); $cursor = $q->execute(); return $cursor; }
php
{ "resource": "" }
q261862
Organization.findByName
test
public function findByName($name, $create = true) { $query = $this->dm->createQueryBuilder('Organizations\Entity\OrganizationName')->hydrate(false)->field('name')->equals($name)->select("_id"); $result = $query->getQuery()->execute()->toArray(false); if (empty($result) && $create) { $repositoryNames = $this->dm->getRepository('Organizations\Entity\OrganizationName'); $entityName = $repositoryNames->create(); $entityName->setName($name); $entity = $this->create(); $entity->setOrganizationName($entityName); $this->store($entity); $organizations = array($entity); } else { $idName = $result[0]['_id']; $organizations = $this->findBy(array('organizationName' => $idName)); } return $organizations; }
php
{ "resource": "" }
q261863
Organization.findByUser
test
public function findByUser($userOrId) { $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId; $qb = $this->createQueryBuilder(); /* * HiringOrganizations also could be associated to the user, but we * do not want them to be queried here, so the query needs to check the * "parent" field, too. */ // $qb->addAnd( // $qb->expr()->field('user')->equals($userId) // ->addOr( // $qb->expr()->addOr($qb->expr()->field('parent')->exists(false)) // ->addOr($qb->expr()->field('parent')->equals(null)) // ) // ); $qb->addAnd($qb->expr()->field('user')->equals($userId)) ->addAnd( $qb->expr()->addOr($qb->expr()->field('parent')->exists(false)) ->addOr($qb->expr()->field('parent')->equals(null)) ); $q = $qb->getQuery(); $entity = $q->getSingleResult(); return $entity; }
php
{ "resource": "" }
q261864
Organization.findByEmployee
test
public function findByEmployee($userOrId) { $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId; /* * Employees collection is only set on main organization, * so here, we do not have to query the "parent" field. * * Only search for "assigned" employees. */ $entity = $this->findOneBy( array( 'employees.user' => new \MongoId($userId), 'employees.status' => EmployeeInterface::STATUS_ASSIGNED ) ); return $entity; }
php
{ "resource": "" }
q261865
Organization.createWithName
test
public function createWithName($name) { $entity = parent::create(); $repositoryNames = $this->dm->getRepository('Organizations\Entity\OrganizationName'); $entityName = $repositoryNames->create(); $entityName->setName($name); $entity->setOrganizationName($entityName); return $entity; }
php
{ "resource": "" }
q261866
Organization.findDraft
test
public function findDraft($user) { if ($user instanceof UserInterface) { $user = $user->getId(); } $document = $this->findOneBy( array( 'isDraft' => true, 'user' => $user ) ); if (!empty($document)) { return $document; } return null; }
php
{ "resource": "" }
q261867
OrganizationsContactFieldset.init
test
public function init() { $this->setName('contact'); $this->add( array( 'name' => 'street', 'options' => array( 'label' => /* @translate */ 'Street' ) ) ); $this->add( array( 'name' => 'houseNumber', 'options' => array( 'label' => /* @translate */ 'House Number' ) ) ); $this->add( array( 'name' => 'postalcode', 'options' => array( 'label' => /* @translate */ 'Postal Code' ) ) ); $this->add( array( 'name' => 'city', 'options' => array( 'label' => /* @translate */ 'City' ) ) ); $this->add( [ 'name' => 'country', 'options' => [ 'label' => /* @translate */ 'Country' ] ] ); $this->add( array( 'name' => 'phone', 'options' => array( 'label' => /* @translate */ 'Phone' ) ) ); $this->add( array( 'name' => 'fax', 'options' => array( 'label' => /* @translate */ 'Fax' ) ) ); }
php
{ "resource": "" }
q261868
Organization.isEmployee
test
public function isEmployee(UserInterface $user) { return $this->refs && in_array($user->getId(), $this->refs->getEmployeeIds()); }
php
{ "resource": "" }
q261869
Organization.updatePermissions
test
public function updatePermissions() { if ($this->isHiringOrganization()) { $organization = $this->getParent(); $owner = $organization->getUser(); $this->setUser($owner); } else { $organization = $this; } /* @var $employees null | ArrayCollection | \Doctrine\ODM\MongoDB\PersistentCollection */ $employees = $organization->getEmployees(); $perms = $this->getPermissions(); foreach ($employees as $emp) { /* @var $emp \Organizations\Entity\Employee */ $perms->grant($emp->getUser(), PermissionsInterface::PERMISSION_CHANGE, false); } $perms->build(); }
php
{ "resource": "" }
q261870
Organization.setOrganizationName
test
public function setOrganizationName(OrganizationName $organizationName) { if (isset($this->organizationName)) { $this->organizationName->refCounterDec()->refCompanyCounterDec(); } $this->organizationName = $organizationName; $this->organizationName->refCounterInc()->refCompanyCounterInc(); $this->_organizationName = $organizationName->getName(); return $this; }
php
{ "resource": "" }
q261871
Organization.setPermissions
test
public function setPermissions(PermissionsInterface $permissions) { // Assure the user has always all rights. if ($this->user) { $permissions->grant($this->user, Permissions::PERMISSION_ALL); } $this->permissions = $permissions; return $this; }
php
{ "resource": "" }
q261872
Organization.getImage
test
public function getImage($key = ImageSet::ORIGINAL) { if (is_bool($key)) { $key = $key ? ImageSet::THUMBNAIL : ImageSet::ORIGINAL; } return $this->getImages()->get($key, false) ?: $this->image; }
php
{ "resource": "" }
q261873
Organization.setContact
test
public function setContact(EntityInterface $contact = null) { if (!$contact instanceof OrganizationContact) { $contact = new OrganizationContact($contact); } $this->contact = $contact; return $this; }
php
{ "resource": "" }
q261874
Organization.getEmployees
test
public function getEmployees() { if ($this->isHiringOrganization()) { // Always return empty list, as we never have employees in this case. return new ArrayCollection(); } if (!$this->employees) { $this->setEmployees(new ArrayCollection()); } return $this->employees; }
php
{ "resource": "" }
q261875
Organization.getEmployee
test
public function getEmployee($userOrId) { $employees = $this->getEmployees(); $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId; foreach ($employees as $employee) { if ($employee->getUser()->getId() == $userId) { return $employee; } } return null; }
php
{ "resource": "" }
q261876
Organization.getEmployeesByRole
test
public function getEmployeesByRole($role) { $employees = new ArrayCollection(); /* @var \Organizations\Entity\Employee $employee */ foreach ($this->getEmployees() as $employee) { if ($role === $employee->getRole()) { $employees->add($employee); } } return $employees; }
php
{ "resource": "" }
q261877
EmployeeInvitationFactory.setCreationOptions
test
public function setCreationOptions(array $options=null) { if (!isset($options['user']) || !$options['user'] instanceof UserInterface) { throw new \InvalidArgumentException('An user interface is required!'); } if (!isset($options['token']) || !is_string($options['token'])) { $options['token'] = false; } if (!isset($options['template']) || !is_string($options['template'])) { $options['template'] = 'organizations/mail/invite-employee'; } $this->options = $options; }
php
{ "resource": "" }
q261878
EmployeesFieldset.init
test
public function init() { $this->setName('employees'); $this->add( array( 'name' => 'inviteemployee', 'type' => 'Organizations/InviteEmployeeBar', 'options' => [ 'description' => /*@translate*/ 'Invite an employee via email address.', ] ) ); $this->add( array( 'type' => 'Collection', 'name' => 'employees', 'options' => array( 'count' => 0, 'should_create_template' => true, 'use_labeled_items' => false, 'allow_add' => true, 'allow_remove' => true, 'renderFieldset' => true, 'target_element' => array( 'type' => 'Organizations/EmployeeFieldset' ) ), ) ); }
php
{ "resource": "" }
q261879
IndexController.getFormular
test
protected function getFormular($organization) { /* @var $container \Organizations\Form\Organizations */ //$services = $this->serviceLocator; $forms = $this->formManager; $container = $forms->get( 'Organizations/Form', array( 'mode' => $organization->getId() ? 'edit' : 'new' ) ); $container->setEntity($organization); $container->setParam('id', $organization->getId()); // $container->setParam('applyId',$job->applyId); if ('__my__' != $this->params('id', '')) { $container->disableForm('employeesManagement') ->disableForm('workflowSettings'); } else { $container ->disableForm('organizationLogo') ->disableForm('descriptionForm'); } return $container; }
php
{ "resource": "" }
q261880
Manager.getUri
test
public function getUri(OrganizationImage $image) { if ($this->options->getEnabled()) { return sprintf('%s/%s', $this->options->getUriPath(), $this->getImageSubPath($image)); } return $image->getUri(); }
php
{ "resource": "" }
q261881
Manager.store
test
public function store(OrganizationImage $image) { $resource = $image->getResource(); $path = $this->getImagePath($image); $this->createDirectoryRecursively(dirname($path)); file_put_contents($path, $resource); }
php
{ "resource": "" }
q261882
OrganizationHydrator.extract
test
public function extract($object) { $result = array(); foreach (self::getReflProperties($object) as $property) { $propertyName = $property->getName(); if (!$this->filterComposite->filter($propertyName)) { continue; } $getter = 'get' . ucfirst($propertyName); $value = method_exists($object, $getter) ? $object->$getter() : $property->getValue($object); $result[$propertyName] = $this->extractValue($propertyName, $value); } return $result; }
php
{ "resource": "" }
q261883
OrganizationHydrator.hydrateValue
test
public function hydrateValue($name, $value, $data = null) { if ($this->hasStrategy($name)) { $strategy = $this->getStrategy($name); $value = $strategy->hydrate($value, $this->data, $this->object); } return $value; }
php
{ "resource": "" }
q261884
CheckJobCreatePermissionListener.checkCreatePermission
test
public function checkCreatePermission(AssertionEvent $e) { /* @var $role \Auth\Entity\User * @var $organization \Organizations\Entity\OrganizationReference */ $role = $e->getRole(); if (!$role instanceof UserInterface) { return false; } $organization = $role->getOrganization(); if (!$organization->hasAssociation() || $organization->isOwner() ) { return true; } $employees = $organization->getEmployees(); foreach ($employees as $emp) { /* @var $emp \Organizations\Entity\EmployeeInterface */ if ($emp->getUser()->getId() == $role->getId() && $emp->getPermissions()->isAllowed(EmployeePermissionsInterface::JOBS_CREATE) ) { return true; } } return false; }
php
{ "resource": "" }
q261885
LogoImageFactory.configureForm
test
protected function configureForm($form, AbstractOptions $options) { $size = $options->getCompanyLogoMaxSize(); $type = $options->getCompanyLogoMimeType(); $form->get($this->fileName)->setViewHelper('formImageUpload') ->setMaxSize($size) ->setAllowedTypes($type) ->setForm($form); $form->setIsDescriptionsEnabled(true); $form->setDescription( /*@translate*/ 'Choose a Logo. This logo will be shown in the job opening and the application form.' ); //$form->setHydrator(new ImageHydrator()); }
php
{ "resource": "" }
q261886
Api.ensureCorrectOrderNumber
test
public function ensureCorrectOrderNumber($orderNumber) { if (strlen($orderNumber) > self::ORDER_NUMBER_MAXIMUM_LENGHT) { throw new LogicException('Payment number can\'t have more than 12 characters'); } // add 0 to the left in case length of the order number is less than 4 $orderNumber = str_pad($orderNumber, self::ORDER_NUMBER_MINIMUM_LENGTH, '0', STR_PAD_LEFT); if (!preg_match('/^[0-9]{4}[a-z0-9]{0,12}$/i', $orderNumber)) { throw new LogicException('The payment gateway doesn\'t allow order numbers with this format.'); } return $orderNumber; }
php
{ "resource": "" }
q261887
Api.encrypt_3DES
test
private function encrypt_3DES($merchantOrder, $key) { $ciphertext = null; if ( function_exists( 'mcrypt_encrypt' ) && version_compare(phpversion(), '7.1', '<') ) { // default IV $bytes = array(0,0,0,0,0,0,0,0); //byte [] IV = {0, 0, 0, 0, 0, 0, 0, 0} $iv = implode(array_map("chr", $bytes)); $ciphertext = mcrypt_encrypt(MCRYPT_3DES, $key, $merchantOrder, MCRYPT_MODE_CBC, $iv); } elseif(function_exists( 'openssl_encrypt' ) && version_compare(phpversion(), '7.1', '>=') ) { $l = ceil(strlen($merchantOrder) / 8) * 8; $ciphertext = substr(openssl_encrypt($merchantOrder . str_repeat("\0", $l - strlen($merchantOrder)), 'des-ede3-cbc', $key, OPENSSL_RAW_DATA, "\0\0\0\0\0\0\0\0"), 0, $l); } return $ciphertext; }
php
{ "resource": "" }
q261888
Api.createMerchantSignatureNotif
test
function createMerchantSignatureNotif($key, $data) { $key = $this->decodeBase64($key); $decodec = $this->base64_url_decode($data); $orderData = json_decode($decodec, true); $key = $this->encrypt_3DES($orderData['Ds_Order'], $key); $res = $this->mac256($data, $key); return $this->base64_url_encode($res); }
php
{ "resource": "" }
q261889
Api.validateNotificationSignature
test
public function validateNotificationSignature(array $notification) { $notification = ArrayObject::ensureArrayObject($notification); $notification->validateNotEmpty('Ds_Signature'); $notification->validateNotEmpty('Ds_MerchantParameters'); $data = $notification["Ds_MerchantParameters"]; $key = $this->options['secret_key']; $signedResponse = $this->createMerchantSignatureNotif($key, $data); return $signedResponse == $notification['Ds_Signature']; }
php
{ "resource": "" }
q261890
Api.sign
test
public function sign(array $params) { $base64DecodedKey = base64_decode($this->options['secret_key']); $key = $this->encrypt_3DES($params['Ds_Merchant_Order'], $base64DecodedKey); $res = $this->mac256( $this->createMerchantParameters($params), $key ); return base64_encode($res); }
php
{ "resource": "" }
q261891
HTTPClient.request
test
public function request( $method, $uri = '', array $options = [] ) { // // Add authentication options // // Username and password if ( !empty( $this->authentication_options['username'] ) && !empty( $this->authentication_options['password'] ) ) { $options['auth'] = [ $this->authentication_options['username'], $this->authentication_options['password'], ]; } // HTTP token else if ( !empty( $this->authentication_options['http_token'] ) ) { $options['headers']['Authorization'] = 'Token token=' . $this->authentication_options['http_token']; } // OAuth2 token else if ( !empty( $this->authentication_options['oauth2_token'] ) ) { $options['headers']['Authorization'] = 'Bearer ' . $this->authentication_options['oauth2_token']; } else { throw new \RuntimeException('No authentication options available'); } try { $response = parent::request( $method, $uri, $options ); } catch ( \GuzzleHttp\Exception\TransferException $e ) { $response = $e->getResponse(); } return $response; }
php
{ "resource": "" }
q261892
Ticket.getTicketArticles
test
public function getTicketArticles() { $this->clearError(); if ( empty( $this->getID() ) ) { return []; } $ticket_articles = $this->getClient()->resource( ResourceType::TICKET_ARTICLE )->getForTicket( $this->getID() ); if ( !is_array($ticket_articles) ) { $this->setError( $ticket_articles->getError() ); return []; } return $ticket_articles; }
php
{ "resource": "" }
q261893
Client.request
test
private function request ( $method, $url, array $url_parameters = [], array $options = [] ) { $method = mb_strtoupper($method); if (!empty($url_parameters)) { $options['query'] = $url_parameters; } // Set JSON headers $options['headers']['Accept'] = 'application/json'; $options['headers']['Content-Type'] = 'application/json; charset=utf-8'; // Set "on behalf of user" header if ( mb_strlen($this->on_behalf_of_user) ) { $options['headers']['X-On-Behalf-Of'] = $this->on_behalf_of_user; } $http_client_response = $this->http_client->request( $method, $url, $options ); if ( !is_object($http_client_response) ) { throw new \RuntimeException('Unable to create HTTP client request.'); } // Turn HTTP client's response into our own. $response = new Response( $http_client_response->getStatusCode(), $http_client_response->getReasonPhrase(), $http_client_response->getBody(), $http_client_response->getHeaders() ); $this->setLastResponse($response); return $response; }
php
{ "resource": "" }
q261894
Client.post
test
public function post( $url, array $data = [], array $url_parameters = [] ) { $response = $this->request( 'POST', $url, $url_parameters, [ 'json' => $data, ] ); return $response; }
php
{ "resource": "" }
q261895
Client.put
test
public function put( $url, array $data = [], array $url_parameters = [] ) { $response = $this->request( 'PUT', $url, $url_parameters, [ 'json' => $data, ] ); return $response; }
php
{ "resource": "" }
q261896
TicketArticle.getForTicket
test
public function getForTicket($ticket_id) { if ( !empty( $this->getValues() ) ) { throw new \RuntimeException('Object already contains values, getForTicket() not possible, use a new object'); } $this->clearError(); $ticket_id = intval($ticket_id); if ( empty($ticket_id) ) { throw new \RuntimeException('Missing ticket ID'); } $url = $this->getURL( 'get_for_ticket', [ 'ticket_id' => $ticket_id, ] ); $response = $this->getClient()->get( $url, [ 'expand' => true, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); return $this; } // Return array of TicketArticle objects. $ticket_articles = []; foreach ( $response->getData() as $ticket_article_data ) { $ticket_article = $this->getClient()->resource( get_class($this) ); $ticket_article->setRemoteData($ticket_article_data); $ticket_articles[] = $ticket_article; } return $ticket_articles; }
php
{ "resource": "" }
q261897
AbstractResource.getValue
test
public function getValue($key) { if ( array_key_exists( $key, $this->values ) ) { return $this->values[$key]; } $remote_data = $this->getRemoteData(); if ( array_key_exists( $key, $remote_data ) ) { return $remote_data[$key]; } return null; }
php
{ "resource": "" }
q261898
AbstractResource.get
test
public function get($object_id) { if ( !empty( $this->getValues() ) ) { throw new AlreadyFetchedObjectException('Object already contains values, get() not possible, use a new object'); } if ( empty($object_id) ) { throw new \RuntimeException('Missing object ID'); } $url = $this->getURL( 'get', [ 'object_id' => $object_id, ] ); $response = $this->getClient()->get( $url, [ 'expand' => true, ] ); if ( $response->hasError() ) { $this->setError( $response->getError() ); } else { $this->clearError(); $this->setRemoteData( $response->getData() ); } return $this; }
php
{ "resource": "" }
q261899
AbstractResource.all
test
public function all( $page = null, $objects_per_page = null ) { if ( !empty( $this->getValues() ) ) { throw new AlreadyFetchedObjectException('Object already contains values, all() not possible, use a new object'); } if ( isset($page) && $page <= 0 ) { throw new \RuntimeException('Parameter page must be > 0'); } if ( isset($objects_per_page) && $objects_per_page <= 0 ) { throw new \RuntimeException('Parameter objects_per_page must be > 0'); } if ( ( isset($page) && !isset($objects_per_page) ) || ( !isset($page) && isset($objects_per_page) ) ) { throw new \RuntimeException('Parameters page and objects_per_page must both be given'); } if ( !isset($page) || !isset($objects_per_page) ) { return $this->allWithoutPagination(); } $url_parameters = [ 'expand' => true, ]; if ( isset($page) && isset($objects_per_page) ) { $url_parameters['page'] = $page; $url_parameters['per_page'] = $objects_per_page; } $url = $this->getURL('all'); $response = $this->getClient()->get( $url, $url_parameters ); if ( $response->hasError() ) { $this->setError( $response->getError() ); return $this; } $this->clearError(); // Return array of resource objects if no $object_id was given. // Note: the resource object (this object) used to execute get() will be left empty in this case. $objects = []; foreach ( $response->getData() as $object_data ) { $object = $this->getClient()->resource( get_class($this) ); $object->setRemoteData($object_data); $objects[] = $object; } return $objects; }
php
{ "resource": "" }