_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q247700 | FormContext.fillInWithValueOfFieldOfCurrentUser | validation | public function fillInWithValueOfFieldOfCurrentUser($field, $user_field)
{
if (!empty($this->user) && !$this->user->uid) {
throw new \Exception('Anonymous user have no fields');
}
$entity = new EntityDrupalWrapper('user');
$wrapper = $entity->wrapper($this->user->uid);
$user_field = $entity->getFieldNameByLocator($user_field);
if (empty($wrapper->{$user_field})) {
throw new \InvalidArgumentException(sprintf('User entity has no "%s" field.', $user_field));
}
$value = $wrapper->{$user_field}->value();
if (empty($value)) {
throw new \UnexpectedValueException('The value of "%s" field is empty.', $user_field);
}
$this->fillField($field, $value);
} | php | {
"resource": ""
} |
q247701 | FormContext.radioAction | validation | public function radioAction($customized, $selector)
{
$field = $this->getWorkingElement()->findField($selector);
$customized = (bool) $customized;
if ($field !== null && !$customized) {
$field->selectOption($field->getAttribute('value'));
return;
}
// Find all labels of a radio button or only first, if it is not custom.
foreach ($this->findLabels($selector) as $label) {
// Check a custom label for visibility.
if ($customized && !$label->isVisible()) {
continue;
}
$label->click();
return;
}
$this->throwNoSuchElementException($selector, $field);
} | php | {
"resource": ""
} |
q247702 | FormContext.shouldSeeThumbnail | validation | public function shouldSeeThumbnail()
{
$thumb = false;
foreach (['.upload-preview', '.media-thumbnail img', '.image-preview img'] as $selector) {
if ($thumb) {
break;
}
$thumb = $this->findByCss($selector);
}
if (null === $thumb) {
throw new \Exception('An expected image tag was not found.');
}
$file = explode('?', $thumb->getAttribute('src'));
$file = reset($file);
$curl = new CurlService();
list(, $info) = $curl->execute('GET', $file);
if (empty($info) || strpos($info['content_type'], 'image/') === false) {
throw new FileNotFoundException(sprintf('%s did not return an image', $file));
}
} | php | {
"resource": ""
} |
q247703 | HttpHeaders.add | validation | public function add($name, $values, bool $append = false): void
{
$normalizedName = self::normalizeHeaderName($name);
if (!$append || !$this->containsKey($normalizedName)) {
parent::add($normalizedName, (array)$values);
} else {
$currentValues = [];
$this->tryGet($normalizedName, $currentValues);
parent::add($normalizedName, array_merge($currentValues, (array)$values));
}
} | php | {
"resource": ""
} |
q247704 | HttpHeaders.tryGetFirst | validation | public function tryGetFirst($name, &$value): bool
{
try {
$value = $this->get($name)[0];
return true;
} catch (OutOfBoundsException $ex) {
return false;
}
} | php | {
"resource": ""
} |
q247705 | HttpHeaderParser.isJson | validation | public function isJson(HttpHeaders $headers): bool
{
$contentType = null;
$headers->tryGetFirst('Content-Type', $contentType);
return preg_match("/application\/json/i", $contentType) === 1;
} | php | {
"resource": ""
} |
q247706 | HttpHeaderParser.isMultipart | validation | public function isMultipart(HttpHeaders $headers): bool
{
$contentType = null;
$headers->tryGetFirst('Content-Type', $contentType);
return preg_match("/multipart\//i", $contentType) === 1;
} | php | {
"resource": ""
} |
q247707 | MultipartBody.createDefaultBoundary | validation | private static function createDefaultBoundary(): string
{
try {
// The following creates a UUID v4
$string = random_bytes(16);
$string[6] = chr(ord($string[6]) & 0x0f | 0x40);
$string[8] = chr(ord($string[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($string), 4));
} catch (Exception $ex) {
throw new RuntimeException('Failed to generate random bytes', 0, $ex);
}
} | php | {
"resource": ""
} |
q247708 | MultipartBody.createStreamFromString | validation | private function createStreamFromString(string $string): Stream
{
$stream = new Stream(fopen('php://temp', 'r+b'));
$stream->write($string);
$stream->rewind();
return $stream;
} | php | {
"resource": ""
} |
q247709 | RequestHeaderParser.parseAcceptCharsetHeader | validation | public function parseAcceptCharsetHeader(HttpHeaders $headers): array
{
$headerValues = [];
if (!$headers->tryGet('Accept-Charset', $headerValues)) {
return [];
}
$parsedHeaderValues = [];
$numHeaderValues = count($headerValues);
for ($i = 0;$i < $numHeaderValues;$i++) {
$parsedHeaderParameters = $this->parseParameters($headers, 'Accept-Charset', $i);
// The first value should always be the charset
$charset = $parsedHeaderParameters->getKeys()[0];
$parsedHeaderValues[] = new AcceptCharsetHeaderValue($charset, $parsedHeaderParameters);
}
return $parsedHeaderValues;
} | php | {
"resource": ""
} |
q247710 | RequestHeaderParser.parseAcceptHeader | validation | public function parseAcceptHeader(HttpHeaders $headers): array
{
$headerValues = [];
if (!$headers->tryGet('Accept', $headerValues)) {
return [];
}
$parsedHeaderValues = [];
$numHeaderValues = count($headerValues);
for ($i = 0;$i < $numHeaderValues;$i++) {
$parsedHeaderParameters = $this->parseParameters($headers, 'Accept', $i);
// The first value should always be the media type
$mediaType = $parsedHeaderParameters->getKeys()[0];
$parsedHeaderValues[] = new AcceptMediaTypeHeaderValue($mediaType, $parsedHeaderParameters);
}
return $parsedHeaderValues;
} | php | {
"resource": ""
} |
q247711 | RequestHeaderParser.parseAcceptLanguageHeader | validation | public function parseAcceptLanguageHeader(HttpHeaders $headers): array
{
$headerValues = [];
if (!$headers->tryGet('Accept-Language', $headerValues)) {
return [];
}
$parsedHeaderValues = [];
$numHeaderValues = count($headerValues);
for ($i = 0;$i < $numHeaderValues;$i++) {
$parsedHeaderParameters = $this->parseParameters($headers, 'Accept-Language', $i);
// The first value should always be the language
$language = $parsedHeaderParameters->getKeys()[0];
$parsedHeaderValues[] = new AcceptLanguageHeaderValue($language, $parsedHeaderParameters);
}
return $parsedHeaderValues;
} | php | {
"resource": ""
} |
q247712 | RequestHeaderParser.parseContentTypeHeader | validation | public function parseContentTypeHeader(HttpHeaders $headers): ?ContentTypeHeaderValue
{
if (!$headers->containsKey('Content-Type')) {
return null;
}
$contentTypeHeaderParameters = $this->parseParameters($headers, 'Content-Type');
$contentType = $contentTypeHeaderParameters->getKeys()[0];
return new ContentTypeHeaderValue($contentType, $contentTypeHeaderParameters);
} | php | {
"resource": ""
} |
q247713 | EncodingMatcher.getBestEncodingMatch | validation | public function getBestEncodingMatch(
IMediaTypeFormatter $formatter,
array $acceptCharsetHeaders,
?MediaTypeHeaderValue $mediaTypeHeader
): ?string {
$rankedAcceptCharsetHeaders = $this->rankAcceptCharsetHeaders($acceptCharsetHeaders);
foreach ($rankedAcceptCharsetHeaders as $acceptCharsetHeader) {
foreach ($formatter->getSupportedEncodings() as $supportedEncoding) {
$charset = $acceptCharsetHeader->getCharset();
if ($charset === '*' || strcasecmp($charset, $supportedEncoding) === 0) {
return $supportedEncoding;
}
}
}
if ($mediaTypeHeader === null || $mediaTypeHeader->getCharset() === null) {
return null;
}
// Fall back to the charset in the media type header
foreach ($formatter->getSupportedEncodings() as $supportedEncoding) {
$charset = $mediaTypeHeader->getCharset();
if ($charset === '*' || strcasecmp($charset, $supportedEncoding) === 0) {
return $supportedEncoding;
}
}
return null;
} | php | {
"resource": ""
} |
q247714 | EncodingMatcher.compareAcceptCharsetHeaders | validation | private function compareAcceptCharsetHeaders(AcceptCharsetHeaderValue $a, AcceptCharsetHeaderValue $b): int
{
$aQuality = $a->getQuality();
$bQuality = $b->getQuality();
if ($aQuality < $bQuality) {
return 1;
}
if ($aQuality > $bQuality) {
return -1;
}
$aValue = $a->getCharset();
$bValue = $b->getCharset();
if ($aValue === '*') {
if ($bValue === '*') {
return 0;
}
return 1;
}
if ($bValue === '*') {
return -1;
}
return 0;
} | php | {
"resource": ""
} |
q247715 | EncodingMatcher.rankAcceptCharsetHeaders | validation | private function rankAcceptCharsetHeaders(array $charsetHeaders): array
{
usort($charsetHeaders, [$this, 'compareAcceptCharsetHeaders']);
$rankedCharsetHeaders = array_filter($charsetHeaders, [$this, 'filterZeroScores']);
// Have to return the values because the keys aren't updated in array_filter()
return array_values($rankedCharsetHeaders);
} | php | {
"resource": ""
} |
q247716 | HttpBodyParser.readAsFormInput | validation | public function readAsFormInput(?IHttpBody $body): IDictionary
{
if ($body === null) {
return new HashTable();
}
$parsedFormInputCacheKey = spl_object_hash($body);
if (isset($this->parsedFormInputCache[$parsedFormInputCacheKey])) {
return $this->parsedFormInputCache[$parsedFormInputCacheKey];
}
$formInputArray = [];
parse_str($body->readAsString(), $formInputArray);
$kvps = [];
foreach ($formInputArray as $key => $value) {
$kvps[] = new KeyValuePair($key, $value);
}
// Cache this for next time
$formInputs = new HashTable($kvps);
$this->parsedFormInputCache[$parsedFormInputCacheKey] = $formInputs;
return $formInputs;
} | php | {
"resource": ""
} |
q247717 | HttpBodyParser.readAsJson | validation | public function readAsJson(?IHttpBody $body): array
{
if ($body === null) {
return [];
}
$json = json_decode($body->readAsString(), true);
if ($json === null) {
throw new RuntimeException('Body could not be decoded as JSON');
}
return $json;
} | php | {
"resource": ""
} |
q247718 | HttpBodyParser.readAsMultipart | validation | public function readAsMultipart(?IHttpBody $body, string $boundary): ?MultipartBody
{
if ($body === null) {
return null;
}
$rawBodyParts = explode("--$boundary", $body->readAsString());
// The first part will be empty, and the last will be "--". Remove them.
array_shift($rawBodyParts);
array_pop($rawBodyParts);
$parsedBodyParts = [];
foreach ($rawBodyParts as $rawBodyPart) {
$headerStartIndex = strlen("\r\n");
$headerEndIndex = strpos($rawBodyPart, "\r\n\r\n");
$bodyStartIndex = $headerEndIndex + strlen("\r\n\r\n");
$bodyEndIndex = strlen($rawBodyPart) - strlen("\r\n");
$rawHeaders = explode("\r\n", substr($rawBodyPart, $headerStartIndex, $headerEndIndex - $headerStartIndex));
$parsedHeaders = new HttpHeaders();
foreach ($rawHeaders as $headerLine) {
[$headerName, $headerValue] = explode(':', $headerLine, 2);
$parsedHeaders->add(trim($headerName), trim($headerValue));
}
$body = new StringBody(substr($rawBodyPart, $bodyStartIndex, $bodyEndIndex - $bodyStartIndex));
$parsedBodyParts[] = new MultipartBodyPart($parsedHeaders, $body);
}
return new MultipartBody($parsedBodyParts, $boundary);
} | php | {
"resource": ""
} |
q247719 | MediaTypeFormatter.encodingIsSupported | validation | protected function encodingIsSupported(string $encoding): bool
{
$lowercaseSupportedEncodings = array_map('strtolower', $this->getSupportedEncodings());
$lowercaseEncoding = strtolower($encoding);
return in_array($lowercaseEncoding, $lowercaseSupportedEncodings, true);
} | php | {
"resource": ""
} |
q247720 | RequestParser.getClientIPAddress | validation | public function getClientIPAddress(IHttpRequestMessage $request): ?string
{
$clientIPAddress = null;
$request->getProperties()->tryGet(self::CLIENT_IP_ADDRESS_PROPERTY, $clientIPAddress);
return $clientIPAddress;
} | php | {
"resource": ""
} |
q247721 | ResponseHeaderFormatter.getSetCookieHeaderValue | validation | private function getSetCookieHeaderValue(Cookie $cookie): string
{
$headerValue = "{$cookie->getName()}=" . urlencode($cookie->getValue());
if (($expiration = $cookie->getExpiration()) !== null) {
$headerValue .= '; Expires=' . $expiration->format(self::EXPIRATION_DATE_FORMAT);
}
if (($maxAge = $cookie->getMaxAge()) !== null) {
$headerValue .= "; Max-Age=$maxAge";
}
if (($domain = $cookie->getDomain()) !== null) {
$headerValue .= '; Domain=' . urlencode($domain);
}
if (($path = $cookie->getPath()) !== null) {
$headerValue .= '; Path=' . urlencode($path);
}
if ($cookie->isSecure()) {
$headerValue .= '; Secure';
}
if ($cookie->isHttpOnly()) {
$headerValue .= '; HttpOnly';
}
if (($sameSite = $cookie->getSameSite()) !== null) {
$headerValue .= '; SameSite=' . urlencode($sameSite);
}
return $headerValue;
} | php | {
"resource": ""
} |
q247722 | ContentNegotiator.createDefaultResponseContentNegotiationResult | validation | private function createDefaultResponseContentNegotiationResult(
string $type,
?string $language,
array $acceptCharsetHeaders
): ContentNegotiationResult {
// Default to the first registered media type formatter that can write the input type
$selectedMediaTypeFormatter = null;
foreach ($this->mediaTypeFormatters as $mediaTypeFormatter) {
if ($mediaTypeFormatter->canWriteType($type)) {
$selectedMediaTypeFormatter = $mediaTypeFormatter;
break;
}
}
if ($selectedMediaTypeFormatter === null) {
return new ContentNegotiationResult(null, null, null, $language);
}
$encoding = $this->encodingMatcher->getBestEncodingMatch(
$selectedMediaTypeFormatter,
$acceptCharsetHeaders,
null
);
return new ContentNegotiationResult(
$selectedMediaTypeFormatter,
$selectedMediaTypeFormatter->getDefaultMediaType(),
$encoding,
$language
);
} | php | {
"resource": ""
} |
q247723 | MessageContext.assertNoErrorMessages | validation | public function assertNoErrorMessages()
{
foreach ($this->getMessagesContainers('error') as $element) {
// Some modules are inserted an empty container for errors before
// they are arise. The "Clientside Validation" - one of them.
$text = trim($element->getText());
if ('' !== $text) {
throw new \RuntimeException(sprintf(
'The page "%s" contains following error messages: "%s".',
self::$pageUrl,
$text
));
}
}
/** @var NodeElement $formElement */
foreach ($this->getSession()->getPage()->findAll('css', 'input, select, textarea') as $formElement) {
if ($formElement->hasClass('error')) {
throw new \Exception(sprintf(
'Element "#%s" has an error class.',
$formElement->getAttribute('id')
));
}
}
} | php | {
"resource": ""
} |
q247724 | Uri.filterPath | validation | private static function filterPath(?string $path): ?string
{
if ($path === null) {
return null;
}
/** @link https://tools.ietf.org/html/rfc3986#section-3.3 */
return preg_replace_callback(
'/(?:[^a-zA-Z0-9_\-\.~:@&=\+\$,\/;%]+|%(?![A-Fa-f0-9]{2}))/',
function ($match) {
return rawurlencode($match[0]);
},
$path
);
} | php | {
"resource": ""
} |
q247725 | Uri.filterQueryString | validation | private static function filterQueryString(?string $queryString): ?string
{
if ($queryString === null) {
return null;
}
/** @link https://tools.ietf.org/html/rfc3986#section-3.4 */
return preg_replace_callback(
'/(?:[^a-zA-Z0-9_\-\.~!\$&\'\(\)\*\+,;=%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/',
function ($match) {
return rawurlencode($match[0]);
},
$queryString
);
} | php | {
"resource": ""
} |
q247726 | Uri.isUsingStandardPort | validation | private function isUsingStandardPort(): bool
{
return $this->port === null ||
(($this->scheme === 'http' && $this->port === 80) || ($this->scheme === 'https' && $this->port === 443));
} | php | {
"resource": ""
} |
q247727 | RequestFactory.createRequestFromSuperglobals | validation | public function createRequestFromSuperglobals(array $server): IHttpRequestMessage
{
$method = $server['REQUEST_METHOD'] ?? 'GET';
// Permit the overriding of the request method for POST requests
if ($method === 'POST' && isset($server['X-HTTP-METHOD-OVERRIDE'])) {
$method = $server['X-HTTP-METHOD-OVERRIDE'];
}
$uri = $this->createUriFromSuperglobals($server);
$headers = $this->createHeadersFromSuperglobals($server);
$body = new StreamBody(new Stream(fopen('php://input', 'rb')));
$properties = $this->createProperties($server);
return new Request($method, $uri, $headers, $body, $properties);
} | php | {
"resource": ""
} |
q247728 | RequestFactory.createHeadersFromSuperglobals | validation | protected function createHeadersFromSuperglobals(array $server): HttpHeaders
{
$headers = new HttpHeaders();
foreach ($server as $name => $values) {
// If this header supports multiple values and has unquoted string delimiters...
$containsMultipleValues = isset(self::$headersThatPermitMultipleValues[$name])
&& count($explodedValues = preg_split('/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/', $values)) > 1;
if ($containsMultipleValues) {
foreach ($explodedValues as $value) {
$this->addHeaderValue($headers, $name, $value, true);
}
} else {
$this->addHeaderValue($headers, $name, $values, false);
}
}
return $headers;
} | php | {
"resource": ""
} |
q247729 | RequestFactory.getClientIPAddress | validation | protected function getClientIPAddress(array $server): ?string
{
$serverRemoteAddress = $server['REMOTE_ADDR'] ?? null;
if ($this->isUsingTrustedProxy($server)) {
return $serverRemoteAddress ?? null;
}
$ipAddresses = [];
// RFC 7239
if (isset($server[$this->trustedHeaderNames['HTTP_FORWARDED']])) {
$header = $server[$this->trustedHeaderNames['HTTP_FORWARDED']];
preg_match_all("/for=(?:\"?\[?)([a-z0-9:\.\-\/_]*)/", $header, $matches);
$ipAddresses = $matches[1];
} elseif (isset($server[$this->trustedHeaderNames['HTTP_CLIENT_IP']])) {
$ipAddresses = explode(',', $server[$this->trustedHeaderNames['HTTP_CLIENT_IP']]);
$ipAddresses = array_map('trim', $ipAddresses);
}
if ($serverRemoteAddress !== null) {
$ipAddresses[] = $serverRemoteAddress;
}
$fallbackIPAddresses = count($ipAddresses) === 0 ? [] : [$ipAddresses[0]];
foreach ($ipAddresses as $index => $ipAddress) {
// Check for valid IP address
if (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
unset($ipAddresses[$index]);
}
// Don't accept trusted proxies
if (in_array($ipAddress, $this->trustedProxyIPAddresses, true)) {
unset($ipAddresses[$index]);
}
}
$clientIPAddresses = count($ipAddresses) === 0 ? $fallbackIPAddresses : array_reverse($ipAddresses);
return $clientIPAddresses[0] ?? null;
} | php | {
"resource": ""
} |
q247730 | RequestFactory.addHeaderValue | validation | private function addHeaderValue(HttpHeaders $headers, string $name, $value, bool $append): void
{
$decodedValue = trim((string)(isset(self::$headersToUrlDecode[$name]) ? urldecode($value) : $value));
if (isset(self::$specialCaseHeaders[$name])) {
$headers->add($name, $decodedValue, $append);
} elseif (strpos($name, 'HTTP_') === 0) {
// Drop the "HTTP_"
$normalizedName = substr($name, 5);
$headers->add($normalizedName, $decodedValue, $append);
}
} | php | {
"resource": ""
} |
q247731 | RawTqContext.getDrupalSelector | validation | public function getDrupalSelector($name)
{
$selectors = $this->getDrupalParameter('selectors');
if (!isset($selectors[$name])) {
throw new \Exception(sprintf('No such selector configured: %s', $name));
}
return $selectors[$name];
} | php | {
"resource": ""
} |
q247732 | Wysiwyg.getInstance | validation | protected function getInstance($selector = '')
{
if (empty($this->object)) {
throw new \RuntimeException('Editor instance was not set.');
}
if (empty($this->selector) && empty($selector)) {
throw new \RuntimeException('No such editor was not selected.');
}
$this->setSelector($selector);
if (empty($this->instances[$this->selector])) {
$instanceId = $this->context->element('field', $this->selector)->getAttribute('id');
$instance = sprintf($this->object, $instanceId);
if (!$this->context->executeJs("return !!$instance")) {
throw new \Exception(sprintf('Editor "%s" was not found.', $instanceId));
}
$this->instances[$this->selector] = $instance;
}
return $this->instances[$this->selector];
} | php | {
"resource": ""
} |
q247733 | MediaTypeFormatterMatcher.getBestMediaTypeFormatterMatch | validation | private function getBestMediaTypeFormatterMatch(
string $type,
array $formatters,
array $mediaTypeHeaders,
string $ioType
): ?MediaTypeFormatterMatch {
// Rank the media type headers if they are rankable
if (count($mediaTypeHeaders) > 0 && $mediaTypeHeaders[0] instanceof IHeaderValueWithQualityScore) {
$mediaTypeHeaders = $this->rankAcceptMediaTypeHeaders($mediaTypeHeaders);
}
foreach ($mediaTypeHeaders as $mediaTypeHeader) {
[$mediaType, $mediaSubType] = explode('/', $mediaTypeHeader->getMediaType());
foreach ($formatters as $formatter) {
foreach ($formatter->getSupportedMediaTypes() as $supportedMediaType) {
if ($ioType === self::FORMATTER_TYPE_INPUT && !$formatter->canReadType($type)) {
continue;
}
if ($ioType === self::FORMATTER_TYPE_OUTPUT && !$formatter->canWriteType($type)) {
continue;
}
[$supportedType, $supportedSubType] = explode('/', $supportedMediaType);
// Checks if the type is a wildcard or a match and the sub-type is a wildcard or a match
if (
$mediaType === '*' ||
($mediaSubType === '*' && $mediaType === $supportedType) ||
($mediaType === $supportedType && $mediaSubType === $supportedSubType)
) {
return new MediaTypeFormatterMatch($formatter, $supportedMediaType, $mediaTypeHeader);
}
}
}
}
return null;
} | php | {
"resource": ""
} |
q247734 | MediaTypeFormatterMatcher.compareAcceptMediaTypeHeaders | validation | private function compareAcceptMediaTypeHeaders(AcceptMediaTypeHeaderValue $a, AcceptMediaTypeHeaderValue $b): int
{
$aQuality = $a->getQuality();
$bQuality = $b->getQuality();
if ($aQuality < $bQuality) {
return 1;
}
if ($aQuality > $bQuality) {
return -1;
}
$aType = $a->getType();
$bType = $b->getType();
$aSubType = $a->getSubType();
$bSubType = $b->getSubType();
if ($aType === '*') {
if ($bType === '*') {
return 0;
}
return 1;
}
if ($aSubType === '*') {
if ($bSubType === '*') {
return 0;
}
return 1;
}
// If we've gotten here, then $a had no wildcards
if ($bType === '*' || $bSubType === '*') {
return -1;
}
return 0;
} | php | {
"resource": ""
} |
q247735 | MediaTypeFormatterMatcher.rankAcceptMediaTypeHeaders | validation | private function rankAcceptMediaTypeHeaders(array $mediaTypeHeaders): array
{
usort($mediaTypeHeaders, [$this, 'compareAcceptMediaTypeHeaders']);
$rankedMediaTypeHeaders = array_filter($mediaTypeHeaders, [$this, 'filterZeroScores']);
// Have to return the values because the keys aren't updated in array_filter()
return array_values($rankedMediaTypeHeaders);
} | php | {
"resource": ""
} |
q247736 | RedirectContext.visitPage | validation | public function visitPage($path, $code = 200)
{
if (!$this->assertStatusCode($path, $code)) {
throw new \Exception(sprintf('The page "%s" is not accessible!', $path));
}
self::debug(['Visited page: %s'], [$path]);
$this->visitPath($path);
} | php | {
"resource": ""
} |
q247737 | BaseEntity.getCurrentId | validation | public function getCurrentId()
{
// We have programmatically bootstrapped Drupal core, so able to use such functionality.
$args = arg();
return count($args) > 1 && $this->entityType() === $args[0] && $args[1] > 0 ? (int) $args[1] : 0;
} | php | {
"resource": ""
} |
q247738 | TqContext.iSwitchToWindow | validation | public function iSwitchToWindow()
{
$windows = $this->getWindowNames();
// If the window was not switched yet, then store it name and working element for future switching back.
if (empty($this->mainWindow)) {
$this->mainWindow['name'] = array_shift($windows);
$this->mainWindow['element'] = $this->getWorkingElement();
$window = reset($windows);
} else {
$window = $this->mainWindow['name'];
$element = $this->mainWindow['element'];
$this->mainWindow = [];
}
$this->getSession()->switchToWindow($window);
$this->setWorkingElement(isset($element) ? $element : $this->getBodyElement());
} | php | {
"resource": ""
} |
q247739 | TqContext.useScreenResolution | validation | public function useScreenResolution($width_height)
{
list($width, $height) = explode('x', $width_height);
$this->getSessionDriver()->resizeWindow((int) $width, (int) $height);
} | php | {
"resource": ""
} |
q247740 | TqContext.beforeStep | validation | public function beforeStep(Scope\StepScope $scope)
{
self::$pageUrl = $this->getCurrentUrl();
// To allow Drupal use its internal, web-based functionality, such as "arg()" or "current_path()" etc.
$_GET['q'] = ltrim(parse_url(static::$pageUrl)['path'], '/');
drupal_path_initialize();
} | php | {
"resource": ""
} |
q247741 | TqContext.afterStep | validation | public function afterStep(Scope\StepScope $scope)
{
// If "mainWindow" variable is not empty that means that additional window has been opened.
// Then, if number of opened windows equals to one, we need to switch back to original window,
// otherwise an error will occur: "Window not found. The browser window may have been closed".
// This happens due to auto closing window by JavaScript (CKFinder does this after choosing a file).
if (!empty($this->mainWindow) && count($this->getWindowNames()) == 1) {
$this->iSwitchToWindow();
}
if (self::hasTag('javascript') && self::isStepImpliesJsEvent($scope)) {
$this->waitAjaxAndAnimations();
}
} | php | {
"resource": ""
} |
q247742 | Request.getRequestTarget | validation | private function getRequestTarget(): string
{
switch ($this->requestTargetType) {
case RequestTargetTypes::ORIGIN_FORM:
$requestTarget = $this->uri->getPath();
/** @link https://tools.ietf.org/html/rfc7230#section-5.3.1 */
if ($requestTarget === null || $requestTarget === '') {
$requestTarget = '/';
}
if (($queryString = $this->uri->getQueryString()) !== null && $queryString !== '') {
$requestTarget .= "?$queryString";
}
return $requestTarget;
case RequestTargetTypes::ABSOLUTE_FORM:
return (string)$this->uri;
case RequestTargetTypes::AUTHORITY_FORM:
return $this->uri->getAuthority(false) ?? '';
case RequestTargetTypes::ASTERISK_FORM:
return '*';
default:
// Shouldn't happen
return '';
}
} | php | {
"resource": ""
} |
q247743 | UriParser.parseQueryString | validation | public function parseQueryString(Uri $uri): IImmutableDictionary
{
if (($queryString = $uri->getQueryString()) === null) {
return new ImmutableHashTable([]);
}
if (!isset($this->parsedQueryStringCache[$queryString])) {
$parsedQueryString = [];
parse_str($queryString, $parsedQueryString);
$kvps = [];
foreach ($parsedQueryString as $key => $value) {
$kvps[] = new KeyValuePair($key, $value);
}
$this->parsedQueryStringCache[$queryString] = new ImmutableHashTable($kvps);
}
return $this->parsedQueryStringCache[$queryString];
} | php | {
"resource": ""
} |
q247744 | ProducerAdapter.produce | validation | public function produce(Message $message)
{
$type = $message->getType();
$body = array('ticket' => $message->getTicket());
try {
$this->logger->debug(sprintf('Publish message for job %s to sonata backend', $message->getTicket()), [
'type' => $type,
'body' => $body
]);
$queue = $this->registry->get($message->getType())->getQueue();
$this->backendProvider->getBackend($queue)->createAndPublish($type, $body);
} catch (\Exception $e) {
$this->logger->error(sprintf('Failed to publish message (Error: %s)', $e->getMessage()), ['exception' => $e]);
if (!$e instanceof \RuntimeException) {
$e = new \RuntimeException($e->getMessage(), $e->getCode(), $e);
}
throw $e;
}
} | php | {
"resource": ""
} |
q247745 | SerializationHelper.serializeParameters | validation | public function serializeParameters($type, array $parameters)
{
$jobType = $this->registry->get($type);
$indices = $jobType->getIndicesOfSerializableParameters();
if (count($indices) < count($parameters)) {
throw new \InvalidArgumentException(sprintf('More parameters provided for serialization than defined for job "%s"', $type));
}
$i = 0;
$serializedParameters = array();
foreach ($parameters as $parameter) {
if (null == $parameter) {
$serializedParameters[] = null;
} else {
$serializedParameters[] = $this->serializer->serialize($parameter, 'json', $this->getParamSerializationContext($jobType, $indices[$i]));
}
$i++;
}
$data = json_encode($serializedParameters);
if (false === $data) {
throw new \RuntimeException(sprintf('Serialization failed with error "%s"', json_last_error_msg()));
}
return $data;
} | php | {
"resource": ""
} |
q247746 | SerializationHelper.deserializeParameters | validation | public function deserializeParameters($type, $data)
{
$jobType = $this->registry->get($type);
$indices = $jobType->getIndicesOfSerializableParameters();
$serializedParameters = json_decode($data, 1);
if (false === $serializedParameters) {
throw new \RuntimeException(sprintf('Deserialization failed with error "%s"', json_last_error_msg()));
}
if (count($indices) < count($serializedParameters)) {
throw new \InvalidArgumentException(sprintf('The serialized data contains more parameters than defined for job "%s"', $type));
}
$parameters = array();
foreach ($serializedParameters as $index => $data) {
if (null === $data) {
$parameters[] = null;
} else {
$parameters[] = $this->serializer->deserialize($data, $jobType->getParameterType($indices[$index]), 'json', $this->getParamDeserializationContext($jobType, $indices[$index]));
}
}
return $parameters;
} | php | {
"resource": ""
} |
q247747 | SerializationHelper.serializeReturnValue | validation | public function serializeReturnValue($type, $value)
{
$jobType = $this->registry->get($type);
return $this->serializer->serialize($value, 'json', $this->getResponseSerializationContext($jobType));
} | php | {
"resource": ""
} |
q247748 | SerializationHelper.deserializeReturnValue | validation | public function deserializeReturnValue($type, $data)
{
$jobType = $this->registry->get($type);
return $this->serializer->deserialize($data, $jobType->getReturnType(), 'json', $this->getResponseDeserializationContext($jobType));
} | php | {
"resource": ""
} |
q247749 | JobController.doStop | validation | public function doStop()
{
if ($this->controller->doStop()) {
$this->job->setStatus(Status::CANCELLED());
return true;
}
return false;
} | php | {
"resource": ""
} |
q247750 | HandlerFactoryRegistry.createHandlers | validation | public function createHandlers(JobInterface $job, $level, $bubble)
{
$handlers = [];
foreach ($this->factories as $factory) {
$handlers[] = $factory->createHandler($job, $level, $bubble);
}
return $handlers;
} | php | {
"resource": ""
} |
q247751 | BaseHandlerFactory.initHandler | validation | protected function initHandler(HandlerInterface $handler)
{
if ($this->formatter != null) {
$handler->setFormatter($this->formatter);
}
foreach ($this->processors as $processor) {
$handler->pushProcessor($processor);
}
return $handler;
} | php | {
"resource": ""
} |
q247752 | JobDeserializationSubscriber.onPreDeserialize | validation | public function onPreDeserialize(PreDeserializeEvent $event)
{
$type = $event->getType();
if (isset($type['name']) && ($type['name'] == Job::class || is_subclass_of($type['name'], Job::class))) {
$data = $event->getData();
if (isset($data['type']) && isset($data['parameters']) && is_array($data['parameters']) && count($data['parameters']) > 0) {
array_push($data['parameters'], ['abc.job.type' => $data['type']]);
$event->setData($data);
}
}
} | php | {
"resource": ""
} |
q247753 | JobHelper.updateJob | validation | public function updateJob(EntityJobInterface $job, Status $status, $processingTime = 0, $response = null)
{
$job->setStatus($status);
$job->setProcessingTime($job->getProcessingTime() + ($processingTime === null ? 0 : $processingTime));
$job->setResponse($response);
if (Status::isTerminated($status)) {
$job->setTerminatedAt(new \DateTime());
}
if ($job->hasSchedules() && Status::isTerminated($status)) {
foreach ($job->getSchedules() as $schedule) {
if (method_exists($schedule, 'setIsActive')) {
$schedule->setIsActive(false);
}
}
}
} | php | {
"resource": ""
} |
q247754 | JobHelper.copyJob | validation | public function copyJob(JobInterface $from, \Abc\Bundle\JobBundle\Model\JobInterface $to)
{
$to->setType($from->getType());
$to->setResponse($from->getResponse());
$to->setParameters($from->getParameters());
if (null != $from->getStatus()) {
$to->setStatus($from->getStatus());
}
foreach ($from->getSchedules() as $schedule) {
$to->addSchedule($schedule);
}
return $to;
} | php | {
"resource": ""
} |
q247755 | Invoker.invoke | validation | public function invoke(JobInterface $job, ContextInterface $context)
{
$jobType = $this->registry->get($job->getType());
$callableArray = $jobType->getCallable();
$parameters = static::resolveParameters($jobType, $context, $job->getParameters());
if (is_array($callableArray) && $callable = $callableArray[0]) {
if ($callable instanceof JobAwareInterface) {
$callable->setJob($job);
}
if ($callable instanceof ManagerAwareInterface) {
$callable->setManager($this->manager);
}
if ($callable instanceof ControllerAwareInterface) {
$callable->setController($this->controllerFactory->create($job));
}
if ($callable instanceof LoggerAwareInterface && $context->has('abc.logger')) {
$callable->setLogger($context->get('abc.logger'));
}
}
return call_user_func_array($callableArray, $parameters);
} | php | {
"resource": ""
} |
q247756 | ProducerAdapter.consumeJob | validation | public function consumeJob(PlainMessage $message){
$ticket = $message->ticket;
$type = $message->type;
$this->logger->debug('Consume message from bernard backend', [
'message' => $message
]);
$this->manager->onMessage(new Message($type, $ticket));
} | php | {
"resource": ""
} |
q247757 | DoctrineOrmServiceProvider.register | validation | public function register(Container $container)
{
$container['doctrine.orm.em'] = $this->getOrmEmDefinition($container);
$container['doctrine.orm.em.config'] = $this->getOrmEmConfigDefinition($container);
$container['doctrine.orm.em.default_options'] = $this->getOrmEmDefaultOptions();
$container['doctrine.orm.ems'] = $this->getOrmEmsDefinition($container);
$container['doctrine.orm.ems.config'] = $this->getOrmEmsConfigServiceProvider($container);
$container['doctrine.orm.ems.options.initializer'] = $this->getOrmEmsOptionsInitializerDefinition($container);
$container['doctrine.orm.entity.listener_resolver.default'] = $this->getOrmEntityListenerResolverDefinition($container);
$container['doctrine.orm.manager_registry'] = $this->getOrmManagerRegistryDefintion($container);
$container['doctrine.orm.mapping_driver.factory.annotation'] = $this->getOrmMappingDriverFactoryAnnotation($container);
$container['doctrine.orm.mapping_driver.factory.class_map'] = $this->getOrmMappingDriverFactoryClassMap($container);
$container['doctrine.orm.mapping_driver.factory.php'] = $this->getOrmMappingDriverFactoryPhp($container);
$container['doctrine.orm.mapping_driver.factory.simple_xml'] = $this->getOrmMappingDriverFactorySimpleXml($container);
$container['doctrine.orm.mapping_driver.factory.simple_yaml'] = $this->getOrmMappingDriverFactorySimpleYaml($container);
$container['doctrine.orm.mapping_driver.factory.static_php'] = $this->getOrmMappingDriverFactoryStaticPhp($container);
$container['doctrine.orm.mapping_driver.factory.xml'] = $this->getOrmMappingDriverFactoryXml($container);
$container['doctrine.orm.mapping_driver.factory.yaml'] = $this->getOrmMappingDriverFactoryYaml($container);
$container['doctrine.orm.mapping_driver_chain'] = $this->getOrmMappingDriverChainDefinition($container);
$container['doctrine.orm.repository.factory.default'] = $this->getOrmRepositoryFactoryDefinition($container);
$container['doctrine.orm.strategy.naming.default'] = $this->getOrmNamingStrategyDefinition($container);
$container['doctrine.orm.strategy.quote.default'] = $this->getOrmQuoteStrategyDefinition($container);
} | php | {
"resource": ""
} |
q247758 | ClassMetadata.setParameterType | validation | public function setParameterType($method, $name, $type)
{
if (!isset($this->parameterTypes[$method])) {
throw new \InvalidArgumentException(sprintf('A method with name "%s" is not defined', $name, $method));
}
if (!array_key_exists($name, $this->parameterTypes[$method])) {
throw new \InvalidArgumentException(sprintf('A parameter with name "%s" for method "%s" is not defined', $name, $method));
}
$this->parameterTypes[$method][$name] = $type;
} | php | {
"resource": ""
} |
q247759 | Microtime.fromDateTime | validation | public static function fromDateTime(\DateTimeInterface $date)
{
$str = $date->format('U') . str_pad($date->format('u'), 6, '0');
$m = new self();
$m->int = (int)$str;
$m->sec = (int)substr($str, 0, 10);
$m->usec = (int)substr($str, -6);
return $m;
} | php | {
"resource": ""
} |
q247760 | AbstractMessage.unFreeze | validation | private function unFreeze()
{
$this->isFrozen = false;
$this->isReplay = null;
foreach (static::schema()->getFields() as $field) {
if ($field->getType()->isMessage()) {
/** @var self $value */
$value = $this->get($field->getName());
if (empty($value)) {
continue;
}
if ($value instanceof Message) {
$value->unFreeze();
continue;
}
/** @var self $v */
foreach ($value as $v) {
$v->unFreeze();
}
}
}
} | php | {
"resource": ""
} |
q247761 | AbstractMessage.populateDefault | validation | private function populateDefault(Field $field)
{
if ($this->has($field->getName())) {
return true;
}
$default = $field->getDefault($this);
if (null === $default) {
return false;
}
if ($field->isASingleValue()) {
$this->data[$field->getName()] = $default;
unset($this->clearedFields[$field->getName()]);
return true;
}
if (empty($default)) {
return false;
}
/*
* sets have a special handling to deal with unique values
*/
if ($field->isASet()) {
$this->addToSet($field->getName(), $default);
return true;
}
$this->data[$field->getName()] = $default;
unset($this->clearedFields[$field->getName()]);
return true;
} | php | {
"resource": ""
} |
q247762 | SmsGatewayServiceProvider.boot | validation | public function boot()
{
$this->app->when(SmsGatewayChannel::class)
->needs(SmsGatewayClient::class)
->give(function () {
$config = $this->app['config']['services.smsgateway'];
return new SmsGatewayClient(
new HttpClient,
$config['email'],
$config['password'],
$config['device']
);
});
} | php | {
"resource": ""
} |
q247763 | Field.isCompatibleForMerge | validation | public function isCompatibleForMerge(Field $other)
{
if ($this->name !== $other->name) {
return false;
}
if ($this->type !== $other->type) {
return false;
}
if ($this->rule !== $other->rule) {
return false;
}
if ($this->className !== $other->className) {
return false;
}
if (!array_intersect($this->anyOfClassNames, $other->anyOfClassNames)) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q247764 | Field.isCompatibleForOverride | validation | public function isCompatibleForOverride(Field $other)
{
if (!$this->overridable) {
return false;
}
if ($this->name !== $other->name) {
return false;
}
if ($this->type !== $other->type) {
return false;
}
if ($this->rule !== $other->rule) {
return false;
}
if ($this->required !== $other->required) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q247765 | Schema.getHandlerMethodName | validation | public function getHandlerMethodName($withMajor = true)
{
if (true === $withMajor) {
return lcfirst($this->classShortName);
}
return lcfirst(str_replace('V' . $this->id->getVersion()->getMajor(), '', $this->classShortName));
} | php | {
"resource": ""
} |
q247766 | Schema.createMessage | validation | public function createMessage(array $data = [])
{
/** @var Message $className */
$className = $this->className;
if (empty($data)) {
return $className::create();
}
return $className::fromArray($data);
} | php | {
"resource": ""
} |
q247767 | MessageResolver.resolveId | validation | public static function resolveId(SchemaId $id): string
{
$curieMajor = $id->getCurieMajor();
if (isset(self::$curies[$curieMajor])) {
return self::$classes[self::$curies[$curieMajor]];
}
$curie = $id->getCurie()->toString();
if (isset(self::$curies[$curie])) {
return self::$classes[self::$curies[$curie]];
}
throw new NoMessageForSchemaId($id);
} | php | {
"resource": ""
} |
q247768 | MessageResolver.resolveCurie | validation | public static function resolveCurie($curie): string
{
$key = (string)$curie;
if (isset(self::$curies[$key])) {
return self::$classes[self::$curies[$key]];
}
throw new NoMessageForCurie(SchemaCurie::fromString($key));
} | php | {
"resource": ""
} |
q247769 | MessageResolver.registerMap | validation | public static function registerMap(array $map)
{
@trigger_error(sprintf('"%s" is deprecated. Use "registerManifest" instead.', __CLASS__), E_USER_DEPRECATED);
$nextId = count(self::$curies) + 30000;
foreach ($map as $curie => $class) {
++$nextId;
self::$curies[$curie] = $nextId;
self::$classes[$nextId] = $class;
}
} | php | {
"resource": ""
} |
q247770 | MessageResolver.findOneUsingMixin | validation | public static function findOneUsingMixin($mixin): Schema
{
$schemas = self::findAllUsingMixin($mixin);
if (1 !== count($schemas)) {
throw new MoreThanOneMessageForMixin($mixin, $schemas);
}
return current($schemas);
} | php | {
"resource": ""
} |
q247771 | MessageResolver.findAllUsingMixin | validation | public static function findAllUsingMixin($mixin): array
{
if ($mixin instanceof Mixin) {
$key = $mixin->getId()->getCurieMajor();
} else {
$key = $mixin;
}
if (!isset(self::$resolvedMixins[$key])) {
$schemas = [];
foreach ((self::$mixins[$key] ?? []) as $id) {
$schemas[] = self::$classes[$id]::schema();
}
self::$resolvedMixins[$key] = $schemas;
}
if (empty(self::$resolvedMixins[$key])) {
throw new NoMessageForMixin($mixin);
}
return self::$resolvedMixins[$key];
} | php | {
"resource": ""
} |
q247772 | MappingFactory.applyAnalyzer | validation | protected function applyAnalyzer(array $mapping, Field $field, \stdClass $rootObject, $path = null)
{
if (null === $this->defaultAnalyzer) {
return $mapping;
}
if (!isset($mapping['type']) || 'text' !== $mapping['type']) {
return $mapping;
}
if (isset($mapping['index']) && false === $mapping['index']) {
return $mapping;
}
if (isset($mapping['analyzer'])) {
return $mapping;
}
$mapping['analyzer'] = $this->defaultAnalyzer;
return $mapping;
} | php | {
"resource": ""
} |
q247773 | SmsGatewayChannel.buildParams | validation | protected function buildParams(SmsGatewayMessage $message, $to)
{
$optionalFields = array_filter([
'expires_at' => data_get($message, 'expiresAt'),
'send_at' => data_get($message, 'sendAt'),
]);
return array_merge([
'number' => $to,
'message' => trim($message->content),
], $optionalFields);
} | php | {
"resource": ""
} |
q247774 | ConnectionManager.getConnectionFactory | validation | protected function getConnectionFactory($type)
{
if (false === isset($this->connectionFactories[$type])) {
throw new \InvalidArgumentException("Missing connection factory \"$type\"");
}
return $this->connectionFactories[$type];
} | php | {
"resource": ""
} |
q247775 | ErrorAction.run | validation | public function run()
{
if (($exception = Yii::$app->getErrorHandler()->exception) === null) {
return '';
}
if ($exception instanceof \HttpException) {
$code = $exception->statusCode;
} else {
$code = $exception->getCode();
}
if ($exception instanceof Exception) {
$name = $exception->getName();
} else {
$name = $this->defaultName ?: Yii::t('yii', 'Error');
}
if ($code) {
$name .= " (#$code)";
}
if ($exception instanceof UserException) {
$message = $exception->getMessage();
} else {
$message = $this->defaultMessage ?: Yii::t('yii', 'An internal server error occurred.');
}
if (Yii::$app->getRequest()->getIsAjax()) {
$rr = new RequestResponse();
$rr->success = false;
$rr->message = "$name: $message";
return (array)$rr;
} else {
if (\Yii::$app->user->can(CmsManager::PERMISSION_ADMIN_ACCESS)) {
$this->controller->layout = \Yii::$app->cms->moduleAdmin->layout;
return $this->controller->render('@app/views/error/error', [
'message' => nl2br(Html::encode($message))
]);
} else {
$this->controller->layout = '@app/views/layouts/unauthorized';
return $this->controller->render('@app/views/error/unauthorized-403', [
'message' => nl2br(Html::encode($message))
]);
}
}
} | php | {
"resource": ""
} |
q247776 | ModelAbstract.hydrate | validation | protected function hydrate($propertyName)
{
if (isset($this->yuccaMappingManager) && (false === isset($this->yuccaInitialized[$propertyName])) && (false === empty($this->yuccaIdentifier))) {
$values = $this->yuccaMappingManager->getMapper(get_class($this))->load($this->yuccaIdentifier, $propertyName, $this->yuccaShardingKey);
foreach ($values as $property => $value) {
if (false === isset($this->yuccaInitialized[$property])) {
$this->$property = $value;
$this->yuccaInitialized[$property] = true;
}
}
}
$this->yuccaInitialized[$propertyName] = true;
return $this;
} | php | {
"resource": ""
} |
q247777 | EditableIterator.retrieve | validation | protected function retrieve()
{
if (false === $this->retrieved) {
$this->updatedDatas = $this->getArray();
$this->retrieved = true;
}
} | php | {
"resource": ""
} |
q247778 | AdminAsset.registerAssetFiles | validation | public function registerAssetFiles($view)
{
if (\Yii::$app->request->isPjax) {
return parent::registerAssetFiles($view);
}
parent::registerAssetFiles($view);
} | php | {
"resource": ""
} |
q247779 | AdminPanelWidget.init | validation | public function init()
{
Html::addCssClass($this->options, ['panel', 'sx-panel', $this->color]);
$options = ArrayHelper::merge($this->options, [
'id' => $this->id,
]);
echo Html::beginTag('div', $options);
echo Html::beginTag('div', $this->headingOptions);
echo <<<HTML
<div class="pull-left">
<h2>
{$this->name}
</h2>
</div>
<div class="panel-actions panel-hidden-actions">
{$this->actions}
</div>
HTML;
echo Html::endTag('div');
echo Html::beginTag('div', $this->bodyOptions);
//echo '<div class="panel-content">' . $this->content;
echo $this->content;
} | php | {
"resource": ""
} |
q247780 | IteratorToArrayTransformer.transform | validation | public function transform($iterator)
{
if (null === $iterator) {
return array();
}
if (is_array($iterator)) {
return $iterator;
}
if (!$iterator instanceof Iterator) {
throw new TransformationFailedException('Expected a Yucca\Component\Iterator\Iterator object.');
}
return $iterator->getArray();
} | php | {
"resource": ""
} |
q247781 | Mapper.load | validation | public function load(array $identifier, $propertyName, $shardingKey = null)
{
if (isset($identifier[$propertyName])) {
return array($propertyName=>$identifier[$propertyName]);
}
$field = $this->getFieldNameFromProperty($propertyName);
$sources = $this->getSourcesFromPropertyName($propertyName);
foreach ($sources as $sourceName) {
$source = $this->sourceManager->getSource($sourceName);
if ($source->canHandle($field)) {
$mappedIdentifiers = array();
foreach ($identifier as $id => $value) {
$fieldName = $this->getFieldNameFromProperty($id);
if ($source->canHandle($fieldName)) {
$mappedIdentifiers[$fieldName] = $value;
}
}
$datas = $source->load($mappedIdentifiers, false, $shardingKey);
$mappedDatas = $this->mapFieldsToProperties($datas, $sourceName);
return $mappedDatas;
}
}
throw new \Exception("No source support field $field from property $propertyName in {$this->name}");
} | php | {
"resource": ""
} |
q247782 | SchemaManager.fetchOne | validation | public function fetchOne($tableName, array $identifier, $shardingKey = null, $forceFromMaster = true)
{
return $this->fetch($tableName, $identifier, $shardingKey, array('*'), false, $forceFromMaster);
} | php | {
"resource": ""
} |
q247783 | Iterator.current | validation | public function current()
{
if (true === $this->wantNewModel) {
return $this->entityManager->load($this->modelClassName, $this->selector->current());
} else {
$this->initializeModel($this->selector->current(), $this->selector->currentShardingKey());
$this->entityManager->resetModel($this->model, $this->selector->current());
return $this->model;
}
} | php | {
"resource": ""
} |
q247784 | SelectorAbstract.current | validation | public function current()
{
$this->prepareQuery();
if (false !== current($this->idsArray)) {
return current($this->idsArray);
} else {
throw new PointerException('Can\'t retrieve the current element');
}
} | php | {
"resource": ""
} |
q247785 | SelectorAbstract.currentShardingKey | validation | public function currentShardingKey()
{
return isset($this->options[SelectorSourceInterface::SHARDING_KEY]) ? $this->options[SelectorSourceInterface::SHARDING_KEY] : null;
} | php | {
"resource": ""
} |
q247786 | PHPExcel.create | validation | public function create( $name )
{
$sheet = $this->container->createSheet();
$sheet->setTitle( $name );
return new \Aimeos\MW\Container\Content\PHPExcel( $sheet, $name, $this->getOptions() );
} | php | {
"resource": ""
} |
q247787 | PHPExcel.get | validation | public function get( $name )
{
if( ( $sheet = $this->container->getSheetByName( $name ) ) === null ) {
throw new \Aimeos\MW\Container\Exception( sprintf( 'No sheet "%1$s" available', $name ) );
}
return new \Aimeos\MW\Container\Content\PHPExcel( $sheet, $sheet->getTitle(), $this->getOptions() );
} | php | {
"resource": ""
} |
q247788 | PHPExcel.close | validation | public function close()
{
$writer = \PHPExcel_IOFactory::createWriter( $this->container, $this->format );
$writer->save( $this->resourcepath );
} | php | {
"resource": ""
} |
q247789 | PHPExcel.current | validation | public function current()
{
$sheet = $this->iterator->current();
return new \Aimeos\MW\Container\Content\PHPExcel( $sheet, $sheet->getTitle(), $this->getOptions() );
} | php | {
"resource": ""
} |
q247790 | PHPExcel.add | validation | public function add( $data )
{
$columnNum = 0;
$rowNum = $this->iterator->current()->getRowIndex();
foreach( (array) $data as $value ) {
$this->sheet->setCellValueByColumnAndRow( $columnNum++, $rowNum, $value );
}
$this->iterator->next();
} | php | {
"resource": ""
} |
q247791 | PHPExcel.current | validation | public function current()
{
if( $this->iterator->valid() === false ) {
return null;
}
$iterator = $this->iterator->current()->getCellIterator();
$iterator->setIterateOnlyExistingCells( false );
$result = [];
foreach( $iterator as $cell ) {
$result[] = $cell->getValue();
}
return $result;
} | php | {
"resource": ""
} |
q247792 | TelegramBot.send | validation | static function send($channel_code = null) {
try {
if(is_numeric($channel_code)) {
$channel_id = $channel_code;
} else {
$channel_id = env('telegram.' . $channel_code);
$channel_id = $channel_id ? : env('telegram');
}
if(!$channel_id) {
echo 'No channel';
return;
}
if(is_array($channel_code)) {
foreach($channel_code as $_code) {
self::send($_code);
}
return;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HEADER, 0);
$partials = [];
$current = '';
foreach(static::$messages as $message) {
//если еще есть куда складывать
if(mb_strlen($current) + mb_strlen($message) < self::MAX) {
$current .= PHP_EOL . $message;
} else {
//если складывать некуда, то сбросим текущий слот в очередь
$partials[] = $current;
//очистим его
$current = '';
if(mb_strlen($message) > self::MAX) {
$strlen = mb_strlen($message);
while($strlen) {
$partials[] = mb_substr($message, 0, self::MAX, "UTF-8");
$message = mb_substr($message, self::MAX, mb_strlen($message), "UTF-8");
$strlen = mb_strlen($message);
}
} else {
$current = $message;
}
}
}
$partials[] = $current;
foreach($partials as $partial) {
$params = http_build_query([
'disable_web_page_preview' => 'true',
'parse_mode' => 'HTML',
'chat_id' => $channel_id,
'text' => $partial,
]);
$url = 'https://api.telegram.org/bot' . env('telegram.key') . '/sendMessage?';
curl_setopt($ch, CURLOPT_URL, $url . $params);
curl_exec($ch);
}
curl_close($ch);
} catch(\Exception $e) {
echo $e->getMessage();
}
} | php | {
"resource": ""
} |
q247793 | Simple.lock | validation | public function lock()
{
// query whether or not, the PID has already been set
if ($this->pid === $this->getSerial()) {
return;
}
// if not, initialize the PID
$this->pid = $this->getSerial();
// open the PID file
$this->fh = fopen($filename = $this->getPidFilename(), 'a+');
// try to lock the PID file exclusive
if (!flock($this->fh, LOCK_EX|LOCK_NB)) {
throw new ImportAlreadyRunningException(sprintf('PID file %s is already in use', $filename));
}
// append the PID to the PID file
if (fwrite($this->fh, $this->pid . PHP_EOL) === false) {
throw new \Exception(sprintf('Can\'t write PID %s to PID file %s', $this->pid, $filename));
}
} | php | {
"resource": ""
} |
q247794 | Simple.unlock | validation | public function unlock()
{
try {
// remove the PID from the PID file if set
if ($this->pid === $this->getSerial() && is_resource($this->fh)) {
// remove the PID from the file
$this->removeLineFromFile($this->pid, $this->fh);
// finally unlock/close the PID file
flock($this->fh, LOCK_UN);
fclose($this->fh);
// if the PID file is empty, delete the file
if (filesize($filename = $this->getPidFilename()) === 0) {
unlink($filename);
}
}
} catch (FileNotFoundException $fnfe) {
$this->getSystemLogger()->notice(sprintf('PID file %s doesn\'t exist', $this->getPidFilename()));
} catch (LineNotFoundException $lnfe) {
$this->getSystemLogger()->notice(sprintf('PID %s is can not be found in PID file %s', $this->pid, $this->getPidFilename()));
} catch (\Exception $e) {
throw new \Exception(sprintf('Can\'t remove PID %s from PID file %s', $this->pid, $this->getPidFilename()), null, $e);
}
} | php | {
"resource": ""
} |
q247795 | Simple.removeLineFromFile | validation | public function removeLineFromFile($line, $fh)
{
// initialize the array for the PIDs found in the PID file
$lines = array();
// initialize the flag if the line has been found
$found = false;
// rewind the file pointer
rewind($fh);
// read the lines with the PIDs from the PID file
while (($buffer = fgets($fh, 4096)) !== false) {
// remove the new line
$buffer = trim($buffer);
// if the line is the one to be removed, ignore the line
if ($line === $buffer) {
$found = true;
continue;
}
// add the found PID to the array
$lines[] = $buffer;
}
// query whether or not, we found the line
if (!$found) {
throw new LineNotFoundException(sprintf('Line %s can not be found', $line));
}
// empty the file and rewind the file pointer
ftruncate($fh, 0);
rewind($fh);
// append the existing lines to the file
foreach ($lines as $ln) {
if (fwrite($fh, $ln . PHP_EOL) === false) {
throw new \Exception(sprintf('Can\'t write %s to file', $ln));
}
}
} | php | {
"resource": ""
} |
q247796 | Simple.stop | validation | public function stop($reason)
{
// log a message that the operation has been stopped
$this->log($reason, LogLevel::INFO);
// stop processing the plugins by setting the flag to TRUE
$this->stopped = true;
} | php | {
"resource": ""
} |
q247797 | Simple.log | validation | public function log($msg, $logLevel = null)
{
// initialize the formatter helper
$helper = new FormatterHelper();
// map the log level to the console style
$style = $this->mapLogLevelToStyle($logLevel);
// format the message, according to the passed log level and write it to the console
$this->getOutput()->writeln($logLevel ? $helper->formatBlock($msg, $style) : $msg);
// log the message if a log level has been passed
if ($logLevel && $systemLogger = $this->getSystemLogger()) {
$systemLogger->log($logLevel, $msg);
}
} | php | {
"resource": ""
} |
q247798 | Simple.mapLogLevelToStyle | validation | protected function mapLogLevelToStyle($logLevel)
{
// query whether or not the log level is mapped
if (isset($this->logLevelStyleMapping[$logLevel])) {
return $this->logLevelStyleMapping[$logLevel];
}
// return the default style => info
return Simple::DEFAULT_STYLE;
} | php | {
"resource": ""
} |
q247799 | SluggableBehavior.slug | validation | public function slug(Entity $entity)
{
$config = $this->config();
$value = $entity->get($config['field']);
$entity->set($config['slug'], strtolower(Inflector::slug($value, $config['replacement'])));
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.