_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q258700
Container.resolved
test
public function resolved(string $id): bool { if (!$this->has($id)) { throw new class extends \LogicException implements NotFoundExceptionInterface {}; } return !$this->container[$id] instanceof \Closure; }
php
{ "resource": "" }
q258701
Encoder.getWriter
test
protected function getWriter() { $writer = new \XMLWriter(); $writer->openMemory(); if ($this->indent) { $writer->setIndent(true); $writer->startDocument('1.0', 'UTF-8'); } else { $writer->setIndent(false); $writer->startDocument(); } return $writer; }
php
{ "resource": "" }
q258702
Encoder.finalizeWrite
test
protected function finalizeWrite(\XMLWriter $writer) { $writer->endDocument(); $result = $writer->outputMemory(true); if (!$this->indent) { // Remove the XML declaration for an even // more compact result. if (!strncmp($result, '<'.'?xml', 5)) { $pos = strpos($result, '?'.'>'); if ($pos !== false) { $result = (string) substr($result, $pos + 2); } } // Remove leading & trailing whitespace. $result = trim($result); } return $result; }
php
{ "resource": "" }
q258703
Decoder.getReader
test
protected function getReader($URI, $request) { if (!is_string($URI)) { throw new \InvalidArgumentException('Not a string'); } if (!is_bool($request)) { throw new \InvalidArgumentException('Not a boolean'); } $this->currentNode = null; $reader = new \XMLReader(); $reader->open($URI, null, LIBXML_NONET | LIBXML_NOENT); if ($this->validate) { $schema = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR; $schema .= $request ? 'request.rng' : 'response.rng'; $reader->setRelaxNGSchema($schema); } return $reader; }
php
{ "resource": "" }
q258704
Decoder.readNode
test
protected function readNode($reader) { if ($this->currentNode !== null) { return $this->currentNode; } $this->currentNode = new \fpoirotte\XRL\Node($reader, $this->validate, true); return $this->currentNode; }
php
{ "resource": "" }
q258705
Decoder.expectStartTag
test
protected function expectStartTag($reader, $expectedTag) { $node = $this->readNode($reader); $type = $node->nodeType; if ($type !== \XMLReader::ELEMENT) { $type = isset(self::$types[$type]) ? self::$types[$type] : "#$type"; throw new \InvalidArgumentException( "Expected an opening $expectedTag tag ". "but got a node of type $type instead" ); } $readTag = $node->name; if ($readTag !== $expectedTag) { throw new \InvalidArgumentException( "Got opening tag for $readTag instead of $expectedTag" ); } $this->prepareNextNode(); }
php
{ "resource": "" }
q258706
Decoder.expectEndTag
test
protected function expectEndTag($reader, $expectedTag) { $node = $this->readNode($reader); $type = $node->nodeType; if ($type !== \XMLReader::END_ELEMENT) { $type = isset(self::$types[$type]) ? self::$types[$type] : "#$type"; throw new \InvalidArgumentException( "Expected a closing $expectedTag tag ". "but got a node of type $type instead" ); } $readTag = $node->name; if ($readTag !== $expectedTag) { throw new \InvalidArgumentException( "Got closing tag for $readTag instead of $expectedTag" ); } $this->prepareNextNode(); }
php
{ "resource": "" }
q258707
Decoder.parseText
test
protected function parseText($reader) { $node = $this->readNode($reader); $type = $node->nodeType; if ($type !== \XMLReader::TEXT) { $type = isset(self::$types[$type]) ? self::$types[$type] : "#$type"; throw new \InvalidArgumentException( "Expected a text node, but got ". "a node of type $type instead" ); } $value = $node->value; $this->prepareNextNode(); return $value; }
php
{ "resource": "" }
q258708
Decoder.checkType
test
protected static function checkType(array $allowedTypes, $type, $value) { if (count($allowedTypes) && !in_array($type, $allowedTypes)) { $allowed = implode(', ', $allowedTypes); throw new \InvalidArgumentException( "Expected one of: $allowed; got $type" ); } return $value; }
php
{ "resource": "" }
q258709
Builder.checkbox
test
public function checkbox( string $id, string $title, array $additionalArguments = null ): Field { $formControl = $this->builder->checkbox($id)->value('true'); $this->optionStore->getBoolean($id) ? $formControl->check() : $formControl->uncheck(); $additionalArguments = array_merge( [ 'type' => 'boolean', 'sanitize_callback' => function ($value): bool { return 'true' === sanitize_text_field($value); }, ], (array) $additionalArguments ); return new Field( $id, $title, $formControl, (array) $additionalArguments ); }
php
{ "resource": "" }
q258710
Builder.email
test
public function email( string $id, string $title, array $additionalArguments = null ): Field { $formControl = $this->builder->email($id) ->addClass('regular-text') ->value( $this->optionStore->getString($id) ); $additionalArguments = array_merge( [ 'sanitize_callback' => 'sanitize_email', ], (array) $additionalArguments ); return new Field( $id, $title, $formControl, (array) $additionalArguments ); }
php
{ "resource": "" }
q258711
Builder.select
test
public function select( string $id, string $title, array $options, array $additionalArguments = null ): Field { $formControl = $this->builder->select($id, $options) ->select( $this->optionStore->getString($id) ); $additionalArguments = array_merge( [ 'sanitize_callback' => function ($value) use ($options): string { $value = sanitize_text_field($value); return array_key_exists($value, $options) ? $value : ''; }, ], (array) $additionalArguments ); return new Field( $id, $title, $formControl, (array) $additionalArguments ); }
php
{ "resource": "" }
q258712
Registrar.run
test
public function run() { array_map( function (SectionInterface $section) { $this->registerSection($section); $this->registerFields($section); $this->registerSettings($section); }, $this->sections ); }
php
{ "resource": "" }
q258713
Registrar.registerSection
test
private function registerSection(SectionInterface $section) { add_settings_section( $section->getId(), $section->getTitle(), $section->getRenderClosure(), $this->pageSlug ); }
php
{ "resource": "" }
q258714
Registrar.registerFields
test
private function registerFields(SectionInterface $section) { array_map( function (FieldInterface $field) use ($section) { add_settings_field( $field->getId(), $field->getTitle(), $field->getRenderClosure(), $this->pageSlug, $section->getId(), $field->getAdditionalArguments() ); }, $section->getFields() ); }
php
{ "resource": "" }
q258715
Registrar.registerSettings
test
private function registerSettings(SectionInterface $section) { array_map( function (FieldInterface $field) { register_setting( $this->pageSlug, $field->getId(), $field->getAdditionalArguments() ); }, $section->getFields() ); }
php
{ "resource": "" }
q258716
Captcha.display
test
public function display($attributes = [], $options = []) { $isMultiple = (bool)$this->options->get('multiple', $options); if (!array_key_exists('id', $attributes)) { $attributes['id'] = $this->randomCaptchaId(); } $html = ''; if (!$isMultiple && array_get($attributes, 'add-js', true)) { $html .= '<script src="' . $this->getJsLink($options) . '" async defer></script>'; } unset($attributes['add-js']); $attributeOptions = $this->options->get('attributes', $options); if (!empty($attributeOptions)) { $attributes = array_merge($attributeOptions, $attributes); } if ($isMultiple) { array_push($this->captchaAttributes, $attributes); } else { $attributes['data-sitekey'] = $this->config->get('captcha.sitekey'); } return $html . '<div class="g-recaptcha"' . $this->buildAttributes($attributes) . '></div>'; }
php
{ "resource": "" }
q258717
Captcha.getJsLink
test
public function getJsLink($options = []) { $query = []; if ($this->options->get('multiple', $options)) { $query = [ 'onload' => $this->callbackName, 'render' => 'explicit', ]; } $lang = $this->options->get('lang', $options); if ($lang) { $query['hl'] = $lang; } return static::CAPTCHA_CLIENT_API . '?' . http_build_query($query, null, '&amp;'); }
php
{ "resource": "" }
q258718
Captcha.displayMultiple
test
public function displayMultiple($options = []) { if (!$this->options->get('multiple', $options)) { return ''; } $renderHtml = ''; foreach ($this->captchaAttributes as $captchaAttribute){ $renderHtml .= "{$this->widgetIdName}[\"{$captchaAttribute['id']}\"]={$this->buildCaptchaHtml($captchaAttribute)}"; } return "<script type=\"text/javascript\">var {$this->widgetIdName}={};var {$this->callbackName}=function(){{$renderHtml}};</script>"; }
php
{ "resource": "" }
q258719
Captcha.buildCaptchaHtml
test
protected function buildCaptchaHtml(array $captchaAttribute) { $options = array_merge( ['sitekey' => $this->config->get('captcha.sitekey')], $this->config->get('captcha.attributes', []) ); foreach ($captchaAttribute as $key => $value) { $options[str_replace('data-', '', $key)] = $value; } $options = json_encode($options); return "grecaptcha.render('{$captchaAttribute['id']}',{$options});"; }
php
{ "resource": "" }
q258720
MoovlyService.uploadAsset
test
public function uploadAsset(\SplFileInfo $file, Library $library = null): MoovlyObject { $supportedExtensions = array_merge( self::SUPPORTED_AUDIO_EXTENSION, self::SUPPORTED_IMAGE_EXTENSIONS, self::SUPPORTED_VIDEO_EXTENSIONS ); $assetExtensions = array_merge( self::SUPPORTED_AUDIO_EXTENSION, self::SUPPORTED_IMAGE_EXTENSIONS ); if (!in_array($file->getExtension(), $supportedExtensions)) { throw new BadAssetException($file); } if (in_array($file->getExtension(), $assetExtensions)) { try { $object = $this->client->uploadAsset($file, is_null($library) ? null : $library->getId()); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return ObjectFactory::createFromAPIResponse($object); } try { $object = $this->client->uploadAsset($file, is_null($library) ? null : $library->getId()); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return ObjectFactory::createFromAPIResponse($object); }
php
{ "resource": "" }
q258721
MoovlyService.getProject
test
public function getProject(string $projectId): Project { try { $project = ProjectFactory::createFromAPIResponse( $this->client->getProject($projectId) ); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return $project; }
php
{ "resource": "" }
q258722
MoovlyService.getProjects
test
public function getProjects(?string $filter = 'unarchived'): array { if (is_null($filter)) { $filter = 'unarchived'; } try { $response = $this->client->getProjects($filter); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } $projects = array_map(function (array $project) { return ProjectFactory::createFromAPIResponse($project); }, $response); return $projects; }
php
{ "resource": "" }
q258723
MoovlyService.createTemplate
test
public function createTemplate(Project $project): Template { try { $template = TemplateFactory::createFromAPIResponse( $this->client->createTemplate($project->getId()) ); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return $template; }
php
{ "resource": "" }
q258724
MoovlyService.getTemplate
test
public function getTemplate(string $templateId): Template { try { $template = TemplateFactory::createFromAPIResponse($this->client->getTemplate($templateId)); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return $template; }
php
{ "resource": "" }
q258725
MoovlyService.getTemplates
test
public function getTemplates(): array { try { $response = $this->client->getTemplates(); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } $templates = array_map(function (array $template) { return TemplateFactory::createFromAPIResponse($template); }, $response); return $templates; }
php
{ "resource": "" }
q258726
MoovlyService.createJob
test
public function createJob(Job $job): Job { $validQualities = ['480p', '720p', '1080p']; $options = array_merge([ 'quality' => '480p', 'create_moov' => false, 'auto_render' => true, ], $job->getOptions()); if (!in_array($options['quality'], $validQualities)) { throw new BadRequestException( sprintf( 'The given quality (%s) for a job is invalid, please use a valid one (%s).', $options['quality'], implode(', ', $validQualities) ) ); } if (!is_null($job->getId())) { throw new BadRequestException( 'The given job already has an id. This either means you set this manually, or this is a job already ' . ' registered in Moovly. In the first case, stop assigning a job id, in the latter case, just ' . ' read the job.' ); } if (is_null($job->getTemplate())) { throw new BadRequestException( 'You have not supplied a template in the job request. Please run $job->setTemplate() before calling' . ' $service->createJob().' ); } $values = array_map(function (Value $value) { return [ 'external_id' => $value->getExternalId(), 'title' => $value->getTitle(), 'template_variables' => $value->getTemplateVariables() ]; }, $job->getValues()); try { $result = JobFactory::createFromAPIResponse( $this->client->createJob($job->getTemplate()->getId(), $options, $values) ); $result ->setTemplate($job->getTemplate()) ->setOptions($job->getOptions()) ->setValues($this->mergeJobValues($job->getValues(), $result->getValues())) ; } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return $result; }
php
{ "resource": "" }
q258727
MoovlyService.getJob
test
public function getJob(string $jobId): Job { try { $job = JobFactory::createFromAPIResponse($this->client->getJob($jobId)); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return $job; }
php
{ "resource": "" }
q258728
MoovlyService.getJobsByTemplate
test
public function getJobsByTemplate(Template $template): array { try { $response = $this->client->getJobsByTemplate($template->getId()); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } $jobs = array_map(function (array $job) { return JobFactory::createFromAPIResponse($job); }, $response); return $jobs; }
php
{ "resource": "" }
q258729
MoovlyService.getCurrentUser
test
public function getCurrentUser(): User { try { $user = UserFactory::createFromAPIResponse($this->client->getUser()); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return $user; }
php
{ "resource": "" }
q258730
MoovlyService.getPersonalLibraryForUser
test
public function getPersonalLibraryForUser(): Library { try { $library = LibraryFactory::createFromAPIResponse($this->client->getUserPersonalLibrary()); } catch (ClientException $ce) { $response = $ce->getResponse(); throw ExceptionFactory::create($response, $ce); } return $library; }
php
{ "resource": "" }
q258731
MoovlyService.mergeJobValues
test
private function mergeJobValues(array $preRequestValues, array $postRequestValues) { $result = array_map(function (Value $postValue) use ($preRequestValues) { $preValues = array_filter($preRequestValues, function (Value $preValue) use ($postValue) { return $postValue->getExternalId() === $preValue->getExternalId(); }); /** @var Value $preValue */ $preValue = $preValues[0]; $postValue ->setTemplateVariables($preValue->getTemplateVariables()) ->setTitle($preValue->getTitle()) ; return $postValue; }, $postRequestValues); return $result; }
php
{ "resource": "" }
q258732
LdapUserProvider.getLdapUser
test
public function getLdapUser($attribute, $value) { try { $query = $this->ldap->buildLdapQuery() ->select($this->getAttributesToSelect()) ->from($this->options['ldap_object_type']) ->where([$attribute => $value]); if (!is_null($this->options['search_base'])) { $query->setBaseDn($this->options['search_base']); } return $query->getLdapQuery()->getSingleResult(); } catch (EmptyResultException $e) { throw new UsernameNotFoundException(sprintf('Username "%s" was not found.', $value)); } catch (MultiResultException $e) { throw new UsernameNotFoundException(sprintf('Multiple results for "%s" were found.', $value)); } }
php
{ "resource": "" }
q258733
LdapToolsExtension.setLdapConfigDefinition
test
protected function setLdapConfigDefinition(ContainerBuilder $container, array $config) { $ldapCfg = ['general' => $config['general']]; // Only tag the cache warmer if there are domains listed in the config... if (isset($config['domains']) && !empty($config['domains'])) { $ldapCfg['domains'] = $config['domains']; $container->getDefinition('ldap_tools.cache_warmer.ldap_tools_cache_warmer')->addTag('kernel.cache_warmer'); } else { $container->getDefinition('data_collector.ldap_tools')->replaceArgument(0, null); } $definition = $container->getDefinition('LdapTools\Configuration'); $definition->addMethodCall('loadFromArray', [$ldapCfg]); $definition->addMethodCall('setEventDispatcher', [new Reference('ldap_tools.event_dispatcher')]); $loggerChain = $container->getDefinition('ldap_tools.log.logger_chain'); if ($config['logging']) { $loggerChain->addMethodCall('addLogger', [new Reference('ldap_tools.log.logger')]); } if ($config['profiling']) { $loggerChain->addMethodCall('addLogger', [new Reference('ldap_tools.log.profiler')]); } if ($config['logging'] || $config['profiling']) { $definition->addMethodCall('setLogger', [new Reference('ldap_tools.log.logger_chain')]); } }
php
{ "resource": "" }
q258734
LdapUserChecker.checkLdapErrorCode
test
public function checkLdapErrorCode(UserInterface $user, $code, $ldapType) { if ($ldapType == LdapConnection::TYPE_AD && $code == ResponseCode::AccountLocked) { $ex = new LockedException('User account is locked.'); $ex->setUser($user); throw $ex; } if ($ldapType == LdapConnection::TYPE_AD && $code == ResponseCode::AccountPasswordMustChange) { $ex = new CredentialsExpiredException('User credentials have expired.'); $ex->setUser($user); throw $ex; } if ($ldapType == LdapConnection::TYPE_AD && $code == ResponseCode::AccountDisabled) { $ex = new DisabledException('User account is disabled.'); $ex->setUser($user); throw $ex; } }
php
{ "resource": "" }
q258735
LdapObjectType.setAllowedTypes
test
protected function setAllowedTypes(OptionsResolver $resolver) { $allowed = ['ldap_query_builder', ['\Closure', 'LdapTools\Query\LdapQueryBuilder', 'null']]; $reflection = new \ReflectionClass(get_class($resolver)); $parameters = $reflection->getMethod('addAllowedTypes')->getParameters(); if ($parameters[0]->isArray()) { $resolver->setAllowedTypes([$allowed[0] => $allowed[1]]); } else { $resolver->setAllowedTypes(...$allowed); } }
php
{ "resource": "" }
q258736
LdapAuthenticationTrait.setLdapCredentialsIfNeeded
test
protected function setLdapCredentialsIfNeeded($username, $password, UserProviderInterface $userProvider) { // Only care about this in the context of the LDAP user provider... if (!$userProvider instanceof LdapUserProvider) { return; } // Only if the username/password are not defined in the config.... $config = $this->ldap->getConnection()->getConfig(); if (!(empty($config->getUsername()) && (empty($config->getPassword() && $config->getPassword() !== '0')))) { return; } $config->setUsername($username); $config->setPassword($password); }
php
{ "resource": "" }
q258737
LdapAuthenticationTrait.switchDomainIfNeeded
test
protected function switchDomainIfNeeded($domain) { if (!empty($domain) && $this->ldap->getDomainContext() !== $domain) { $this->ldap->switchDomain($domain); } }
php
{ "resource": "" }
q258738
LdapAuthenticationTrait.switchDomainBackIfNeeded
test
protected function switchDomainBackIfNeeded($domain) { if ($domain !== $this->ldap->getDomainContext()) { $this->ldap->switchDomain($domain); } }
php
{ "resource": "" }
q258739
LdapAuthenticationTrait.hideOrThrow
test
protected function hideOrThrow(\Exception $e, $hideUserNotFoundExceptions) { if ($hideUserNotFoundExceptions) { throw new BadCredentialsException('Bad credentials.', 0, $e); } // Specifically show LdapTools related exceptions, ignore others. // Custom auth exception messages don't exist until Symfony 2.8, 2.7 is still under support... if (!$hideUserNotFoundExceptions && $e instanceof Exception && class_exists('Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException')) { throw new CustomUserMessageAuthenticationException($e->getMessage(), [], $e->getCode()); } throw $e; }
php
{ "resource": "" }
q258740
LdapFormLoginListener.getUsernamePasswordToken
test
protected function getUsernamePasswordToken(Request $request) { if ($this->options['post_only']) { $username = trim($this->getParameterFromBag($request->request, $this->options['username_parameter'])); $password = $this->getParameterFromBag($request->request, $this->options['password_parameter']); } else { $username = trim($this->getParameterFromRequest($request, $this->options['username_parameter'])); $password = $this->getParameterFromRequest($request, $this->options['password_parameter']); } $request->getSession()->set(Security::LAST_USERNAME, $username); $token = new UsernamePasswordToken($username, $password, $this->providerKey); $this->addDomainToTokenIfPresent($request, $token); return $token; }
php
{ "resource": "" }
q258741
LdapFormLoginListener.addDomainToTokenIfPresent
test
protected function addDomainToTokenIfPresent(Request $request, UsernamePasswordToken $token) { if ($this->options['post_only'] && $request->request->has($this->options['domain_parameter'])) { $token->setAttribute( 'ldap_domain', trim($this->getParameterFromBag($request->request, $this->options['domain_parameter'])) ); } elseif ($domain = trim($this->getParameterFromRequest($request, $this->options['domain_parameter']))) { $token->setAttribute('ldap_domain', $domain); } }
php
{ "resource": "" }
q258742
LdapObjectSubscriber.transformValueForDb
test
protected function transformValueForDb(LifecycleEventArgs $args) { $entity = $this->getObjectFromLifeCycleArgs($args); $om = $this->getOmFromLifeCycleArgs($args); $properties = $this->getLdapObjectAnnotationProperties($entity, $om); foreach ($properties as $info) { if ($info['property']->getValue($entity)) { $this->setLdapValueForProperty($info['property'], $info['annotation'], $entity); } } }
php
{ "resource": "" }
q258743
LdapObjectSubscriber.getLdapObjectAnnotationProperties
test
protected function getLdapObjectAnnotationProperties($entity, $om) { $properties = $om->getClassMetadata(get_class($entity))->getReflectionProperties(); $ldapObjectProps = []; foreach ($properties as $prop) { $annotation = $this->reader->getPropertyAnnotation($prop, self::ANNOTATION); if (!empty($annotation)) { $ldapObjectProps[] = ['annotation' => $annotation, 'property' => $prop]; } } return $ldapObjectProps; }
php
{ "resource": "" }
q258744
LdapObjectSubscriber.setLdapObjectForProperty
test
protected function setLdapObjectForProperty(\ReflectionProperty $property, LdapObjectAnnotation $annotation, $entity) { if (empty($property->getValue($entity))) { return; } $domain = $this->ldap->getDomainContext(); $switchDomain = $annotation->domain ?: null; if ($switchDomain) { $this->ldap->switchDomain($annotation->domain); } $results = $this->queryLdapForObjects($property, $annotation, $entity); $property->setValue($entity, $results); if ($switchDomain) { $this->ldap->switchDomain($domain); } }
php
{ "resource": "" }
q258745
LdapObjectSubscriber.setLdapValueForProperty
test
protected function setLdapValueForProperty(\ReflectionProperty $property, LdapObjectAnnotation $annotation, $entity) { $value = $property->getValue($entity); if ($value instanceof LdapObject) { $ldapValues = $value->get($annotation->id); } elseif ($value instanceof LdapObjectCollection) { $ldapValues = []; foreach ($value->toArray() as $ldapObject) { $ldapValues[] = $ldapObject->get($annotation->id); } } else { throw new \InvalidArgumentException(sprintf( 'Class "%s" is not valid. Expected a LdapObject or LdapObjectCollection', get_class($value) )); } $property->setValue($entity, $ldapValues); }
php
{ "resource": "" }
q258746
LdapToolsBundle.build
test
public function build(ContainerBuilder $container) { parent::build($container); $extension = $container->getExtension('security'); $extension->addSecurityListenerFactory(new LdapFormLoginFactory()); $container->addCompilerPass(new EventRegisterPass()); $container->addCompilerPass(new LdifUrlLoaderPass()); }
php
{ "resource": "" }
q258747
LdapObjectChoiceTrait.getLdapValuesForChoices
test
protected function getLdapValuesForChoices(LdapObject ...$choices) { $values = []; foreach ($choices as $i => $ldapObject) { $values[$i] = (string) $ldapObject->get($this->id); } return $values; }
php
{ "resource": "" }
q258748
LdapObjectChoiceTrait.getLdapObjectsByQuery
test
protected function getLdapObjectsByQuery($values = []) { if (!$this->ldapQueryBuilder) { $query = $this->ldap->buildLdapQuery() ->select([$this->id, $this->labelAttribute]) ->from($this->type); } else { $query = clone $this->ldapQueryBuilder; } if (!empty($values)) { foreach ($values as $value) { $query->orWhere([$this->id => $value]); } } if ($this->queryCallback) { $closure = $this->queryCallback; $closure($query); } return $query->getLdapQuery()->getResult(); }
php
{ "resource": "" }
q258749
LdapProfilerLogger.getOperations
test
public function getOperations($domain = null) { if (!is_null($domain) && !isset($this->opsByDomain[$domain])) { return []; } elseif (!is_null($domain)) { return $this->opsByDomain[$domain]; } return $this->allOperations; }
php
{ "resource": "" }
q258750
LdapRoleMapper.setRoles
test
public function setRoles(LdapUserInterface $user) { $roles = []; if ($this->options['default_role']) { $roles[] = $this->options['default_role']; } if (!empty($this->options['roles'])) { $groups = $this->getGroupsForUser($user); foreach ($this->options['roles'] as $role => $roleGroups) { if ($this->hasGroupForRoles($roleGroups, $groups)) { $roles[] = $role; } } } $user->setRoles($roles); return $user; }
php
{ "resource": "" }
q258751
LdapRoleMapper.hasGroupForRoles
test
protected function hasGroupForRoles(array $roleGroups, LdapObjectCollection $ldapGroups) { foreach ($roleGroups as $roleGroup) { if (LdapUtilities::isValidLdapObjectDn($roleGroup)) { $attribute = 'dn'; } elseif (preg_match(LdapUtilities::MATCH_GUID, $roleGroup)) { $attribute = $this->options['role_attributes']['guid']; } elseif (preg_match(LdapUtilities::MATCH_SID, $roleGroup)) { $attribute = $this->options['role_attributes']['sid']; } else { $attribute = $this->options['role_attributes']['name']; } if ($this->hasGroupWithAttributeValue($ldapGroups, $attribute, $roleGroup)) { return true; } } return false; }
php
{ "resource": "" }
q258752
LdapRoleMapper.hasGroupWithAttributeValue
test
protected function hasGroupWithAttributeValue(LdapObjectCollection $groups, $attribute, $value) { $value = strtolower($value); /** @var \LdapTools\Object\LdapObject $group */ foreach ($groups as $group) { if ($group->has($attribute) && strtolower($group->get($attribute)) === $value) { return true; } } return false; }
php
{ "resource": "" }
q258753
LdapLogger.log
test
protected function log(LogOperation $log) { $message = $this->getLogMessage($log); if (!is_null($log->getError())) { $this->logger->error($message); } else { $this->logger->debug($message); } }
php
{ "resource": "" }
q258754
MediaTrait.saveMedia
test
public function saveMedia($file, $group = 'default', $type = 'single', $options = []) { $this->file = $file; $this->group = $group; $this->type = $type; $this->options = $options; $this->setup(); $this->parseOptions(); if ($this->type == 'single') { $this->removeExistingMedia(); } $result = $this->databasePut(); $this->storagePut(); return $result; }
php
{ "resource": "" }
q258755
MediaTrait.updateMediaById
test
public function updateMediaById($id, $options) { $this->options = $options; $this->parseOptions(); $model = config('media.config.model'); $this->media = $model::find($id); $this->media->alt = $this->getAlt(); $this->media->title = $this->getTitle(); $this->media->name = $this->getName(); $this->media->weight = $this->getWeight(); $this->media->save(); }
php
{ "resource": "" }
q258756
MediaTrait.getMedia
test
public function getMedia($group = NULL) { if (is_null($group)) { return $this->media()->orderBy('weight', 'ASC')->get(); } return $this->getMediaByGroup($group); }
php
{ "resource": "" }
q258757
MediaTrait.removeMedia
test
private function removeMedia($media) { $this->setup(); if (File::delete($this->public_path . $this->files_directory . $media->filename)) { $media->delete(); return TRUE; } return FALSE; }
php
{ "resource": "" }
q258758
MediaTrait.parseOptions
test
private function parseOptions() { $default_options = [ 'alt' => NULL, 'title' => NULL, 'name' => NULL, 'weight' => NULL, ]; $this->options += $default_options; $this->options = (object) $this->options; }
php
{ "resource": "" }
q258759
MediaTrait.getFilename
test
private function getFilename() { switch (config('media.config.rename')) { case 'transliterate': $this->filename_new = \Transliteration::clean_filename($this->filename_original); break; case 'unique': $this->filename_new = md5(microtime() . str_random(5)) .'.'. $this->filename_original; break; case 'nothing': $this->filename_new = $this->file->getClientOriginalName(); break; } return $this->fileExistsRename(); }
php
{ "resource": "" }
q258760
MediaTrait.fileExistsRename
test
private function fileExistsRename() { if (!File::exists($this->directory . $this->filename_new)) { return $this->filename_new; } return $this->fileRename(); }
php
{ "resource": "" }
q258761
MediaTrait.fileRename
test
private function fileRename() { $filename = $this->filename_new; $extension = '.' . File::extension($this->filename_new); $basename = rtrim($filename, $extension); $increment = 0; while (File::exists($this->directory . $filename)) { $filename = $basename . '_' . ++$increment . $extension; } return $this->filename_new = $filename; }
php
{ "resource": "" }
q258762
MediaTrait.getAlt
test
private function getAlt() { if (!is_null($this->options->alt)) { return $this->options->alt; } if (!is_null($this->media)) { return $this->media->alt; } return ''; }
php
{ "resource": "" }
q258763
MediaTrait.getTitle
test
private function getTitle() { if (!is_null($this->options->title)) { return $this->options->title; } if (!is_null($this->media)) { return $this->media->title; } return ''; }
php
{ "resource": "" }
q258764
MediaTrait.getName
test
private function getName() { if (!is_null($this->options->name)) { return $this->options->name; } if (!is_null($this->media)) { return $this->media->name; } return ''; }
php
{ "resource": "" }
q258765
MediaTrait.getWeight
test
private function getWeight() { if (!is_null($this->options->weight)) { return $this->options->weight; } if (!is_null($this->media)) { return $this->media->weight; } return $this->media()->where('group', $this->group)->count(); }
php
{ "resource": "" }
q258766
MediaTrait.databasePut
test
private function databasePut() { $media = [ 'filename' => $this->directory_uri . $this->filename_new, 'mime' => $this->file->getMimeType(), 'size' => $this->file->getSize(), 'title' => $this->getTitle(), 'alt' => $this->getAlt(), 'name' => $this->getName(), 'group' => $this->group, 'status' => TRUE, 'weight' => $this->getWeight(), ]; $model = config('media.config.model'); return $this->media()->save(new $model($media)); }
php
{ "resource": "" }
q258767
MediaTrait.removeExistingMedia
test
private function removeExistingMedia() { $existing_media = $this->getMedia($this->group); if (!$existing_media->isEmpty()) { return $this->deleteMedia($this->group); } return 0; }
php
{ "resource": "" }
q258768
MediaTrait.storagePut
test
private function storagePut() { if ($this->makeDirectory($this->directory)) { $this->file->move($this->directory, $this->filename_new); } }
php
{ "resource": "" }
q258769
MediaTrait.storageClone
test
private function storageClone() { if ($this->makeDirectory($this->directory)) { return File::copy($this->public_path . $this->files_directory . $this->media->filename, $this->directory . $this->filename_new); } return false; }
php
{ "resource": "" }
q258770
MediaTrait.makeDirectory
test
private function makeDirectory($directory) { if (File::isDirectory($directory)) { return TRUE; } return File::makeDirectory($directory, 0755, TRUE); }
php
{ "resource": "" }
q258771
MediaTrait.cloneMedia
test
public function cloneMedia($media, $clone_storage = false, $clone_attributes = []) { $this->media = $media->replicate(); $this->setup(); $this->filename_new = basename($media->filename); if ($clone_storage) { $this->fileExistsRename(); $this->storageClone(); } $this->media->fill($clone_attributes); $this->media->filename = $this->directory_uri . $this->filename_new; return $this->media()->save($this->media); }
php
{ "resource": "" }
q258772
PricingServiceProvider.bootConfig
test
protected function bootConfig() { $path = __DIR__ . '/config/pricing.php'; $this->mergeConfigFrom($path, 'pricing'); if (function_exists('config_path')) { $this->publishes([$path => config_path('pricing.php')]); } }
php
{ "resource": "" }
q258773
BladeSvgSage.register
test
public function register() { sage()->singleton(BladeSvgSage::class, function () { return $this; }); sage()->singleton(SvgFactory::class, function () { return new SvgFactory($this->config()); }); }
php
{ "resource": "" }
q258774
BladeSvgSage.directives
test
public function directives() { /** Create @icon() Blade directive */ sage('blade')->compiler()->directive('icon', function ($expression) { return "<?php echo e(App\svg_image({$expression})) ?>"; }); /** Create @svg() Blade directive */ sage('blade')->compiler()->directive('svg', function ($expression) { return "<?php echo e(App\svg_image({$expression})) ?>"; }); /** Create @spritesheet Blade directive */ sage('blade')->compiler()->directive('spritesheet', function () { return "<?php echo e(App\svg_spritesheet()) ?>"; }); }
php
{ "resource": "" }
q258775
BladeSvgSage.config
test
protected function config() { if (! file_exists($config = __DIR__.'/../config/config.php')) { return; } $config = collect(apply_filters('bladesvg', require($config))); return $config->merge([ 'svg_path' => $this->path($config->get('svg_path')), 'spritesheet_path' => $this->path($config->get('spritesheet_path')) ])->all(); }
php
{ "resource": "" }
q258776
BladeSvgSage.svg
test
public function svg($name = '', $class = '', $attrs = []) { if (empty($name)) { return; } return sage(SvgFactory::class)->svg($name, $class, $attrs); }
php
{ "resource": "" }
q258777
taoQtiCommon_helpers_ResultTransmitter.transmitItemVariable
test
public function transmitItemVariable($variables, $transmissionId, $itemUri = '', $testUri = '') { $itemVariableSet = []; if (is_array($variables) === false) { $variables = [$variables]; } foreach ($variables as $variable) { $identifier = $variable->getIdentifier(); if ($variable instanceof OutcomeVariable) { $value = $variable->getValue(); $resultVariable = new taoResultServer_models_classes_OutcomeVariable(); $resultVariable->setIdentifier($identifier); $resultVariable->setBaseType(BaseType::getNameByConstant($variable->getBaseType())); $resultVariable->setCardinality(Cardinality::getNameByConstant($variable->getCardinality())); $resultVariable->setValue(self::transformValue($value)); $itemVariableSet[] = $resultVariable; } else if ($variable instanceof ResponseVariable) { // ResponseVariable. $value = $variable->getValue(); $resultVariable = new taoResultServer_models_classes_ResponseVariable(); $resultVariable->setIdentifier($identifier); $resultVariable->setBaseType(BaseType::getNameByConstant($variable->getBaseType())); $resultVariable->setCardinality(Cardinality::getNameByConstant($variable->getCardinality())); $resultVariable->setCandidateResponse(self::transformValue($value)); // The fact that the response is correct must not be sent for built-in // response variables 'duration' and 'numAttempts'. if (!in_array($identifier, array('duration', 'numAttempts', 'comment'))) { $resultVariable->setCorrectResponse($variable->isCorrect()); } $itemVariableSet[] = $resultVariable; } } try { common_Logger::d("Sending Item Variables to result server."); $this->getResultStorage()->storeItemVariables($testUri, $itemUri, $itemVariableSet, $transmissionId); } catch (Exception $e) { $msg = "An error occured while transmitting one or more Outcome/Response Variable(s) to the target result server."; $code = taoQtiCommon_helpers_ResultTransmissionException::OUTCOME; throw new taoQtiCommon_helpers_ResultTransmissionException($msg, $code); } }
php
{ "resource": "" }
q258778
taoQtiCommon_helpers_ResultTransmitter.transformValue
test
private static function transformValue($value) { if (gettype($value) === 'object') { if ($value instanceof QtiFile) { return taoQtiCommon_helpers_Utils::qtiFileToString($value); } else { return $value->__toString(); } } else { return $value; } }
php
{ "resource": "" }
q258779
taoQtiCommon_helpers_PciStateOutput.addVariable
test
public function addVariable(Variable $variable) { $output = &$this->getOutput(); $varName = $variable->getIdentifier(); $marshaller = new taoQtiCommon_helpers_PciJsonMarshaller(); $output[$varName] = $marshaller->marshall($variable->getValue(), taoQtiCommon_helpers_PciJsonMarshaller::MARSHALL_ARRAY); }
php
{ "resource": "" }
q258780
taoQtiCommon_helpers_Utils.isQtiFilePlaceHolder
test
static public function isQtiFilePlaceHolder(Variable $variable) { $correctBaseType = $variable->getBaseType() === BaseType::FILE; $correctCardinality = $variable->getCardinality() === Cardinality::SINGLE; if ($correctBaseType === true && $correctCardinality === true) { $value = $variable->getValue(); $notNull = $value !== null; $mime = taoQtiCommon_helpers_PciJsonMarshaller::FILE_PLACEHOLDER_MIMETYPE; if ($notNull === true && $value->getMimeType() === $mime) { return true; } } return false; }
php
{ "resource": "" }
q258781
taoQtiCommon_helpers_Utils.isQtiFile
test
static public function isQtiFile(Variable $variable, $considerNull = true) { $correctBaseType = $variable->getBaseType() === BaseType::FILE; $correctCardinality = $variable->getCardinality() === Cardinality::SINGLE; $nullConsideration = ($considerNull === true) ? true : $variable->getValue() !== null; return $correctBaseType === true && $correctCardinality === true && $nullConsideration === true; }
php
{ "resource": "" }
q258782
taoQtiCommon_helpers_Utils.toQtiDatatype
test
static public function toQtiDatatype($cardinality, $basetype, $value) { // @todo support all baseTypes $datatype = null; if (is_string($value) && empty($value) === false && $cardinality !== 'record' && ($basetype === 'identifier' || $basetype === 'pair' || $basetype === 'directedPair' || $basetype === 'boolean')) { if ($cardinality !== 'simple') { $value = trim($value, "<>[]"); $value = explode(';', $value); } else { $value = array($value); } if (count($value) === 1 && empty($value[0]) === true) { $value = array(); } $value = array_map( function($val) { return trim($val); }, $value ); $qtiBasetype = BaseType::getConstantByName($basetype); $datatype = ($cardinality === 'ordered') ? new OrderedContainer($qtiBasetype) : new MultipleContainer($qtiBasetype); foreach ($value as $val) { try { switch ($basetype) { case 'identifier': $datatype[] = new QtiIdentifier($val); break; case 'pair': $pair = explode("\x20", $val); if (count($pair) === 2) { $datatype[] = new QtiPair($pair[0], $pair[1]); } break; case 'directedPair': $pair = explode("\x20", $val); if (count($pair) === 2) { $datatype[] = new QtiDirectedPair($pair[0], $pair[1]); } break; case 'boolean': if ($val === 'true') { $datatype[] = new QtiBoolean(true); } elseif ($val === 'false') { $datatype[] = new QtiBoolean(false); } else { $datatype[] = new QtiBoolean($val); } break; } } catch (InvalidArgumentException $e) { $datatype = null; break; } } $datatype = ($cardinality === 'single') ? (isset($datatype[0]) ? $datatype[0] : null) : $datatype; } return $datatype; }
php
{ "resource": "" }
q258783
ObjectRevision.createFromObject
test
public function createFromObject(RevisionableInterface $obj) { $prevRev = $this->lastObjectRevision($obj); $this->setTargetType($obj->objType()); $this->setTargetId($obj->id()); $this->setRevNum($prevRev->revNum() + 1); $this->setRevTs('now'); if (is_callable([$obj, 'lastModifiedBy'])) { $this->setRevUser($obj->lastModifiedBy()); } $this->setDataObj($obj->data()); $this->setDataPrev($prevRev->dataObj()); $diff = $this->createDiff(); $this->setDataDiff($diff); return $this; }
php
{ "resource": "" }
q258784
ObjectRevision.recursiveDiff
test
public function recursiveDiff(array $array1, array $array2) { $diff = []; // Compare array1 foreach ($array1 as $key => $value) { if (!array_key_exists($key, $array2)) { $diff[0][$key] = $value; } elseif (is_array($value)) { if (!is_array($array2[$key])) { $diff[0][$key] = $value; $diff[1][$key] = $array2[$key]; } else { $new = $this->recursiveDiff($value, $array2[$key]); if ($new !== false) { if (isset($new[0])) { $diff[0][$key] = $new[0]; } if (isset($new[1])) { $diff[1][$key] = $new[1]; } } } } elseif ($array2[$key] !== $value) { $diff[0][$key] = $value; $diff[1][$key] = $array2[$key]; } } // Compare array2 foreach ($array2 as $key => $value) { if (!array_key_exists($key, $array1)) { $diff[1][$key] = $value; } } return $diff; }
php
{ "resource": "" }
q258785
UserData.setIp
test
public function setIp($ip) { if ($ip === null) { $this->ip = null; return $this; } if (is_string($ip)) { $ip = ip2long($ip); } elseif (is_numeric($ip)) { $ip = intval($ip); } else { $ip = 0; } $this->ip = $ip; return $this; }
php
{ "resource": "" }
q258786
UserData.setLang
test
public function setLang($lang) { if ($lang !== null) { if (!is_string($lang)) { throw new InvalidArgumentException( 'Language must be a string' ); } } $this->lang = $lang; return $this; }
php
{ "resource": "" }
q258787
UserData.setOrigin
test
public function setOrigin($origin) { if ($origin !== null) { if (!is_string($origin)) { throw new InvalidArgumentException( 'Origin must be a string.' ); } } $this->origin = $origin; return $this; }
php
{ "resource": "" }
q258788
UserData.resolveOrigin
test
public function resolveOrigin() { $host = getenv('HTTP_HOST'); $uri = ''; if ($host) { $uri = 'http'; if (getenv('HTTPS') === 'on') { $uri .= 's'; } $uri .= '://'.$host; } $uri .= getenv('REQUEST_URI'); return $uri; }
php
{ "resource": "" }
q258789
UserData.setTs
test
public function setTs($timestamp) { if ($timestamp === null) { $this->ts = null; return $this; } if (is_string($timestamp)) { try { $timestamp = new DateTime($timestamp); } catch (Exception $e) { throw new InvalidArgumentException(sprintf( 'Invalid timestamp: %s', $e->getMessage() ), 0, $e); } } if (!$timestamp instanceof DateTimeInterface) { throw new InvalidArgumentException( 'Invalid timestamp value. Must be a date/time string or a DateTime object.' ); } $this->ts = $timestamp; return $this; }
php
{ "resource": "" }
q258790
UserData.preSave
test
protected function preSave() { $result = parent::preSave(); $this->setTs('now'); if (getenv('REMOTE_ADDR')) { $this->setIp(getenv('REMOTE_ADDR')); } if (!isset($this->origin)) { $this->setOrigin($this->resolveOrigin()); } return $result; }
php
{ "resource": "" }
q258791
ObjectSchedule.process
test
public function process( callable $callback = null, callable $successCallback = null, callable $failureCallback = null ) { if ($this->processed() === true) { // Do not process twice, ever. return null; } if ($this->targetType() === null) { $this->logger->error('Can not process object schedule: no object type defined.'); return false; } if ($this->targetId() === null) { $this->logger->error(sprintf( 'Can not process object schedule: no object "%s" ID defined.', $this->targetType() )); return false; } if (empty($this->dataDiff())) { $this->logger->error('Can not process object schedule: no changes (diff) defined.'); return false; } $obj = $this->modelFactory()->create($this->targetType()); $obj->load($this->targetId()); if (!$obj->id()) { $this->logger->error(sprintf( 'Can not load "%s" object %s', $this->targetType(), $this->targetId() )); } $obj->setData($this->dataDiff()); $update = $obj->update(array_keys($this->dataDiff())); if ($update) { $this->setProcessed(true); $this->setProcessedDate('now'); $this->update(['processed', 'processed_date']); if ($successCallback !== null) { $successCallback($this); } } else { if ($failureCallback !== null) { $failureCallback($this); } } if ($callback !== null) { $callback($this); } return $update; }
php
{ "resource": "" }
q258792
ObjectRoute.preUpdate
test
protected function preUpdate(array $properties = null) { $this->setCreationDate('now'); $this->setLastModificationDate('now'); return parent::preUpdate($properties); }
php
{ "resource": "" }
q258793
ObjectRoute.isSlugUnique
test
public function isSlugUnique() { $proto = $this->modelFactory()->get(self::class); $loader = $this->collectionLoader(); $loader ->reset() ->setModel($proto) ->addFilter('active', true) ->addFilter('slug', $this->slug()) ->addFilter('lang', $this->lang()) ->addOrder('creation_date', 'desc') ->setPage(1) ->setNumPerPage(1); $routes = $loader->load()->objects(); if (!$routes) { return true; } $obj = reset($routes); if (!$obj->id()) { return true; } if ($obj->id() === $this->id()) { return true; } if ($obj->routeObjId() === $this->routeObjId() && $obj->routeObjType() === $this->routeObjType() && $obj->lang() === $this->lang() ) { $this->setId($obj->id()); return true; } return false; }
php
{ "resource": "" }
q258794
ObjectRoute.generateUniqueSlug
test
public function generateUniqueSlug() { if (!$this->isSlugUnique()) { if (!$this->originalSlug) { $this->originalSlug = $this->slug(); } $this->slugInc++; $this->setSlug($this->originalSlug.'-'.$this->slugInc); return $this->generateUniqueSlug(); } return $this; }
php
{ "resource": "" }
q258795
ObjectRoute.setSlug
test
public function setSlug($slug) { if ($slug === null) { $this->slug = null; return $this; } if (!is_string($slug)) { throw new InvalidArgumentException( 'Slug is not a string' ); } $this->slug = $slug; return $this; }
php
{ "resource": "" }
q258796
ObjectRoute.setCreationDate
test
public function setCreationDate($time) { if (empty($time) && !is_numeric($time)) { $this->creationDate = null; return $this; } if (is_string($time)) { try { $time = new DateTime($time); } catch (Exception $e) { throw new InvalidArgumentException(sprintf( 'Invalid Creation Date: %s', $e->getMessage() ), $e->getCode(), $e); } } if (!$time instanceof DateTimeInterface) { throw new InvalidArgumentException( 'Creation Date must be a date/time string or an instance of DateTimeInterface' ); } $this->creationDate = $time; return $this; }
php
{ "resource": "" }
q258797
ObjectRoute.setLastModificationDate
test
public function setLastModificationDate($time) { if (empty($time) && !is_numeric($time)) { $this->lastModificationDate = null; return $this; } if (is_string($time)) { try { $time = new DateTime($time); } catch (Exception $e) { throw new InvalidArgumentException(sprintf( 'Invalid Updated Date: %s', $e->getMessage() ), $e->getCode(), $e); } } if (!$time instanceof DateTimeInterface) { throw new InvalidArgumentException( 'Updated Date must be a date/time string or an instance of DateTimeInterface' ); } $this->lastModificationDate = $time; return $this; }
php
{ "resource": "" }
q258798
ObjectRoute.setRouteOptions
test
public function setRouteOptions($options) { if (is_string($options)) { $options = json_decode($options, true); } $this->routeOptions = $options; return $this; }
php
{ "resource": "" }
q258799
HierarchicalTrait.setMaster
test
public function setMaster($master) { $master = $this->objFromIdent($master); if ($master instanceof ModelInterface) { if ($master->id() === $this->id()) { throw new UnexpectedValueException(sprintf( 'Can not be ones own parent: %s', $master->id() )); } } $this->master = $master; $this->resetHierarchy(); return $this; }
php
{ "resource": "" }