_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q245800 | EntityListener.execute | validation | protected function execute(LifecycleEventArgs $args, $action)
{
// Circular reference error workaround
// @todo Look into fixing this
$this->tokenStorage = $this->container->get('security.token_storage');
$this->configService = $this->container->get('ds_config.service.config');
$this->auditService = $this->container->get('ds_audit.service.audit');
//
$entity = $args->getEntity();
if ($entity instanceof Audit) {
return;
}
if (!$entity instanceof Auditable) {
return;
}
$token = $this->tokenStorage->getToken();
if (!$token) {
return;
}
$user = $token->getUser();
$edits = $args->getEntityManager()->getUnitOfWork()->getEntityChangeSet($entity);
$properties = $this->auditService->getProperties($entity);
foreach (array_keys($edits) as $key) {
if (!in_array($key, $properties)) {
unset($edits[$key]);
}
}
$audit = $this->auditService->createInstance();
$audit
->setOwner($this->configService->get('ds_audit.audit.owner'))
->setOwnerUuid($this->configService->get('ds_audit.audit.owner_uuid'))
->setUserUuid($user->getUuid())
->setIdentity($user->getIdentity()->getType())
->setIdentityUuid($user->getIdentity()->getUuid())
->setAction($action)
->setData([
'entity' => basename(str_replace('\\', '/', get_class($entity))),
'entityUuid' => $entity->getUuid(),
'edits' => $edits
]);
$manager = $this->auditService->getManager();
$manager->persist($audit);
$manager->flush();
} | php | {
"resource": ""
} |
q245801 | TranslationService.translate | validation | public function translate(Translatable $model)
{
$properties = $this->getProperties($model);
foreach ($properties as $property) {
$get = 'get'.$property->getName();
$set = 'set'.$property->getName();
$values = [];
foreach ($model->getTranslations() as $translation) {
$values[$translation->getLocale()] = $translation->$get();
}
$model->$set($values);
}
} | php | {
"resource": ""
} |
q245802 | TranslationService.transfer | validation | public function transfer(Translatable $model)
{
$properties = $this->getProperties($model);
foreach ($properties as $property) {
$get = 'get'.$property->getName();
$set = 'set'.$property->getName();
$values = $model->$get();
if (null !== $values) {
foreach ($values as $locale => $value) {
$model->translate($locale, false)->$set($value);
}
}
}
$model->mergeNewTranslations();
} | php | {
"resource": ""
} |
q245803 | TranslationService.getProperties | validation | public function getProperties(Translatable $model): array
{
$class = get_class($model);
if (substr($class, 0, 15) === 'Proxies\\__CG__\\') {
$class = substr($class, 15);
}
$properties = [];
$reflection = new ReflectionClass($class);
foreach ($reflection->getProperties() as $property) {
$annotation = $this->annotationReader->getPropertyAnnotation($property, Translate::class);
if (!$annotation) {
continue;
}
$properties[] = $property;
}
return $properties;
} | php | {
"resource": ""
} |
q245804 | PreUpdateListener.preUpdate | validation | public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Parameter) {
return;
}
$entity->setValue(serialize($entity->getValue()));
} | php | {
"resource": ""
} |
q245805 | ExceptionListener.kernelException | validation | public function kernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if (!$exception instanceof NoPermissionsException) {
return;
}
// In the event a user requests a list of entities and has no permissions,
// an empty list is returned.
$response = new JsonResponse([]);
$event->setResponse($response);
} | php | {
"resource": ""
} |
q245806 | RolesListener.created | validation | public function created(JWTCreatedEvent $event)
{
$data = $event->getData();
$user = $event->getUser();
$roles = [];
// @todo remove condition when both user types are homogenized
if ($user instanceof User) {
$roles = $user->getIdentity()->getRoles();
} else {
if (null !== $user->getIdentityUuid()) {
switch ($user->getIdentity()) {
case Identity::ANONYMOUS:
$identity = $this->api->get('identities.anonymous')->get($user->getIdentityUuid());
break;
case Identity::INDIVIDUAL:
$identity = $this->api->get('identities.individual')->get($user->getIdentityUuid());
break;
case Identity::ORGANIZATION:
$identity = $this->api->get('identities.organization')->get($user->getIdentityUuid());
break;
case Identity::STAFF:
$identity = $this->api->get('identities.staff')->get($user->getIdentityUuid());
break;
case Identity::SYSTEM:
$identity = $this->api->get('identities.system')->get($user->getIdentityUuid());
break;
default:
throw new DomainException('User identity is not valid.');
}
foreach ($identity->getRoles() as $role) {
// @todo Remove substr once we remove iri-based api foreign keys
$roles[] = substr($role, -36);
}
}
}
$this->accessor->setValue($data, $this->property, $roles);
$event->setData($data);
} | php | {
"resource": ""
} |
q245807 | FormService.getForms | validation | public function getForms($id)
{
$forms = [];
$form = $this->getForm($id);
$form
->setMethod('POST')
->setPrimary(true);
$forms[] = $form;
switch ($form->getType()) {
case Form::TYPE_FORMIO:
$components = $form->getSchema();
$resolverCollection = $this->resolverCollection;
$extract = function(&$container, $key, &$component) use (&$extract, &$forms, $resolverCollection) {
switch (true) {
case property_exists($component, 'components'):
foreach ($component->components as $key => &$subComponent) {
$extract($component->components, $key, $subComponent);
}
break;
case property_exists($component, 'columns'):
foreach ($component->columns as &$column) {
foreach ($column->components as $key => &$subComponent) {
$extract($column->components, $key, $subComponent);
}
}
break;
case property_exists($component, 'properties')
&& is_object($component->properties)
&& property_exists($component->properties, 'ds_form'):
$form = $this->getForm($component->properties->ds_form);
$data = [];
if (property_exists($component, 'defaultValue')) {
try {
$data = $resolverCollection->resolve($component->defaultValue);
} catch (UnresolvedException $exception) {
$data = [];
} catch (UnmatchedException $exception) {
// Leave default value as-is
}
}
$form->setData($data);
$forms[] = $form;
unset($container[$key]);
break;
}
};
foreach ($components as $key => &$component) {
$extract($components, $key, $component);
}
$form->setSchema(array_values($components));
break;
case Form::TYPE_SYMFONY:
break;
default:
throw new DomainException('Form type does not exist.');
}
return $forms;
} | php | {
"resource": ""
} |
q245808 | FormService.resolve | validation | public function resolve(Form $form)
{
switch ($form->getType()) {
case Form::TYPE_FORMIO:
$components = $form->getSchema();
$resolverCollection = $this->resolverCollection;
$resolve = function(&$component) use (&$resolve, $resolverCollection) {
switch (true) {
case property_exists($component, 'components'):
foreach ($component->components as &$subComponent) {
$resolve($subComponent);
}
break;
case property_exists($component, 'columns'):
foreach ($component->columns as &$column) {
foreach ($column->components as &$subComponent) {
$resolve($subComponent);
}
}
break;
case property_exists($component, 'defaultValue'):
if (null !== $component->defaultValue) {
try {
$component->defaultValue = $resolverCollection->resolve($component->defaultValue);
} catch (UnresolvedException $exception) {
$component->defaultValue = null;
} catch (UnmatchedException $exception) {
// Leave default value as-is
}
}
break;
}
};
foreach ($components as &$component) {
$resolve($component);
}
$form->setSchema($components);
break;
case Form::TYPE_SYMFONY:
break;
default:
throw new DomainException('Form type does not exist.');
}
return $form;
} | php | {
"resource": ""
} |
q245809 | PermissionCollection.getParent | validation | public function getParent($permission) {
$permission = $this->cast($permission);
foreach ($this->toArray() as $element) {
if (Permission::ENTITY === $element->getType() && 0 === strpos($permission->getValue(), $element->getValue())) {
return $element;
}
}
} | php | {
"resource": ""
} |
q245810 | PermissionCollection.cast | validation | protected function cast($element) {
if ($element instanceof Permission) {
return $element;
}
if (!is_array($element)) {
throw new InvalidArgumentException('Element is not an array.');
}
foreach (['attributes', 'type', 'value', 'title'] as $key) {
if (!array_key_exists($key, $element)) {
throw new InvalidArgumentException('Element is missing key "'.$key.'".');
}
}
$permission = new Permission($element['key'], $element['attributes'], $element['type'], $element['value'], $element['title']);
return $permission;
} | php | {
"resource": ""
} |
q245811 | PostLoadListener.postLoad | validation | public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Encryptable) {
return;
}
$entity->setEncrypted(true);
$this->encryptionService->decrypt($entity);
} | php | {
"resource": ""
} |
q245812 | AnonymousUuid.setAnonymousUuid | validation | public function setAnonymousUuid(?string $anonymousUuid)
{
$this->anonymousUuid = $anonymousUuid;
$this->_anonymousUuid = true;
return $this;
} | php | {
"resource": ""
} |
q245813 | IdentityUuid.setIdentityUuid | validation | public function setIdentityUuid(?string $identityUuid)
{
if (null !== $identityUuid) {
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $identityUuid)) {
throw new InvalidArgumentException('Identity uuid is not valid.');
}
}
$this->identityUuid = $identityUuid;
return $this;
} | php | {
"resource": ""
} |
q245814 | AuditService.getProperties | validation | public function getProperties(Auditable $entity)
{
$reflection = new ReflectionObject($entity);
$properties = [];
foreach ($reflection->getProperties() as $key => $property) {
if (!$this->annotationReader->getPropertyAnnotation($property, AuditAnnotation::class)) {
continue;
}
$properties[] = $property->name;
}
return $properties;
} | php | {
"resource": ""
} |
q245815 | LocaleService.getProperties | validation | public function getProperties(Localizable $model): array
{
$class = get_class($model);
if (substr($class, 0, 15) === 'Proxies\\__CG__\\') {
$class = substr($class, 15);
}
$properties = [];
$reflection = new ReflectionClass($class);
foreach ($reflection->getProperties() as $property) {
$annotation = $this->annotationReader->getPropertyAnnotation($property, Locale::class);
if (!$annotation) {
continue;
}
$properties[] = $property;
}
return $properties;
} | php | {
"resource": ""
} |
q245816 | ProcessDefinitionService.getCount | validation | public function getCount(Parameters $parameters = null)
{
$options = [
'headers' => [
'Accept' => 'application/json'
]
];
$result = $this->execute('GET', static::RESOURCE_COUNT, $options);
return $result->count;
} | php | {
"resource": ""
} |
q245817 | ProcessDefinitionService.get | validation | public function get($id, Parameters $parameters = null)
{
if (null !== $id) {
$resource = str_replace('{id}', $id, static::RESOURCE_OBJECT);
} else {
$key = $parameters->getKey();
$tenantId = $parameters->getTenantId();
switch (true) {
case null !== $key && null !== $tenantId:
$resource = str_replace(['{key}', '{tenant-id}'], [$key, $tenantId], static::RESOURCE_OBJECT_BY_KEY_AND_TENANT_ID);
break;
case null !== $key:
$resource = str_replace('{key}', $key, static::RESOURCE_OBJECT_BY_KEY);
break;
default:
throw new LogicException('"Key" and/or "TenantId" parameters are not defined.');
}
}
$options = [
'headers' => [
'Accept' => 'application/json'
]
];
$object = $this->execute('GET', $resource, $options);
$model = static::toModel($object);
return $model;
} | php | {
"resource": ""
} |
q245818 | ProcessDefinitionService.getXml | validation | public function getXml($id, Parameters $parameters = null)
{
if (null !== $id) {
$resource = str_replace('{id}', $id, static::RESOURCE_OBJECT_XML);
} else {
$key = $parameters->getKey();
$tenantId = $parameters->getTenantId();
switch (true) {
case null !== $key && null !== $tenantId:
$resource = str_replace(['{key}', '{tenant-id}'], [$key, $tenantId], static::RESOURCE_OBJECT_XML_BY_KEY_AND_TENANT_ID);
break;
case null !== $key:
$resource = str_replace('{key}', $key, static::RESOURCE_OBJECT_XML_BY_KEY);
break;
default:
throw new LogicException('"Key" and/or "TenantId" parameters are not defined.');
}
}
$options = [
'headers' => [
'Accept' => 'application/json'
]
];
$object = $this->execute('GET', $resource, $options);
$model = new Xml;
$model
->setId($object->id)
->setXml(new SimpleXMLElement($object->bpmn20Xml));
return $model;
} | php | {
"resource": ""
} |
q245819 | ProcessDefinitionService.start | validation | public function start($id, Parameters $parameters = null)
{
if (null !== $id) {
$resource = str_replace('{id}', $id, static::RESOURCE_OBJECT_START);
} else {
$key = $parameters->getKey();
$tenantId = $parameters->getTenantId();
switch (true) {
case null !== $key && null !== $tenantId:
$resource = str_replace(['{key}', '{tenant-id}'], [$key, $tenantId], static::RESOURCE_OBJECT_START_BY_KEY_AND_TENANT_ID);
break;
case null !== $key:
$resource = str_replace('{key}', $key, static::RESOURCE_OBJECT_START_BY_KEY);
break;
default:
throw new LogicException('"Key" and/or "TenantId" parameters are not defined.');
}
}
$options = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
]
];
if ($parameters) {
$parameters = (array) $parameters->toObject(true);
foreach ($parameters as $name => $value) {
switch ($name) {
case 'variables':
foreach ($value as $variable) {
$options['json'][$name][$variable->name] = [
'value' => Variable::TYPE_JSON === $variable->type ? json_encode($variable->value) : $variable->value,
'type' => $variable->type
];
}
break;
case 'key':
break;
default:
$options['json'][$name] = $value;
}
}
}
$object = $this->execute('POST', $resource, $options);
$model = ProcessInstanceService::toModel($object);
return $model;
} | php | {
"resource": ""
} |
q245820 | ProcessDefinitionService.getStartForm | validation | public function getStartForm($id, Parameters $parameters = null)
{
if (null !== $id) {
$resource = str_replace('{id}', $id, static::RESOURCE_OBJECT_START_FORM);
} else {
$key = $parameters->getKey();
$tenantId = $parameters->getTenantId();
switch (true) {
case null !== $key && null !== $tenantId:
$resource = str_replace(['{key}', '{tenant-id}'], [$key, $tenantId], static::RESOURCE_OBJECT_START_FORM_BY_KEY_AND_TENANT_ID);
break;
case null !== $key:
$resource = str_replace('{key}', $key, static::RESOURCE_OBJECT_START_FORM_BY_KEY);
break;
default:
throw new LogicException('"Key" and/or "TenantId" parameters are not defined.');
}
}
$options = [
'headers' => [
'Accept' => 'application/json'
]
];
$result = $this->execute('GET', $resource, $options);
return $result->key;
} | php | {
"resource": ""
} |
q245821 | EncryptionService.encrypt | validation | public function encrypt(Encryptable $model): EncryptionService
{
if ($model->getEncrypted()) {
return $this;
}
$properties = $this->getProperties($model);
foreach ($properties as $property) {
$property->setAccessible(true);
$property->setValue($model, $this->cipherService->encrypt($property->getValue($model)));
}
$model->setEncrypted(true);
return $this;
} | php | {
"resource": ""
} |
q245822 | EncryptionService.getProperties | validation | private function getProperties(Encryptable $model): array
{
$properties = [];
$reflection = new ReflectionObject($model);
foreach ($reflection->getProperties() as $property) {
$annotation = $this->annotationReader->getPropertyAnnotation($property, Encrypt::class);
if (!$annotation) {
continue;
}
if (null !== $annotation->applicable && !$this->expressionLanguage->evaluate($annotation->applicable, ['object' => $model])) {
continue;
}
$properties[] = $property;
}
return $properties;
} | php | {
"resource": ""
} |
q245823 | TenantListener.created | validation | public function created(JWTCreatedEvent $event)
{
$payload = $event->getData();
$user = $event->getUser();
$payload[$this->attribute] = $user->getTenant();
$event->setData($payload);
} | php | {
"resource": ""
} |
q245824 | TenantListener.decoded | validation | public function decoded(JWTDecodedEvent $event)
{
$payload = $event->getPayload();
// Make property accessor paths compatible by converting payload to recursive associative array
$payload = json_decode(json_encode($payload), true);
if (!array_key_exists($this->attribute, $payload)) {
$event->markAsInvalid();
}
$uuid = $payload[$this->attribute];
$tenant = $this->tenantService->getRepository()->findBy(['uuid' => $uuid]);
if (!$tenant) {
$event->markAsInvalid();
}
} | php | {
"resource": ""
} |
q245825 | ClientListener.created | validation | public function created(JWTCreatedEvent $event)
{
$data = $event->getData();
$this->accessor->setValue($data, $this->property, $this->getSignature());
$event->setData($data);
} | php | {
"resource": ""
} |
q245826 | ClientListener.decoded | validation | public function decoded(JWTDecodedEvent $event)
{
$payload = $event->getPayload();
// Make property accessor paths compatible by converting payload to recursive associative array
$payload = json_decode(json_encode($payload), true);
if (!$this->accessor->isReadable($payload, $this->property)) {
$event->markAsInvalid();
} elseif ($this->validate && $this->accessor->getValue($payload, $this->property) !== $this->getSignature()) {
$event->markAsInvalid();
}
} | php | {
"resource": ""
} |
q245827 | ClientListener.getSignature | validation | protected function getSignature(): string
{
$request = $this->requestStack->getCurrentRequest();
$signature = substr(md5($request->server->get('HTTP_USER_AGENT')), 0, $this->length);
return $signature;
} | php | {
"resource": ""
} |
q245828 | StaffUuid.setStaffUuid | validation | public function setStaffUuid(?string $staffUuid)
{
$this->staffUuid = $staffUuid;
$this->_staffUuid = true;
return $this;
} | php | {
"resource": ""
} |
q245829 | MaxResults.setMaxResults | validation | public function setMaxResults(?int $maxResults)
{
$this->maxResults = $maxResults;
$this->_maxResults = null !== $maxResults;
return $this;
} | php | {
"resource": ""
} |
q245830 | WithVariablesInReturn.setWithVariablesInReturn | validation | public function setWithVariablesInReturn(?bool $withVariablesInReturn)
{
$this->withVariablesInReturn = $withVariablesInReturn;
$this->_withVariablesInReturn = null !== $withVariablesInReturn;
return $this;
} | php | {
"resource": ""
} |
q245831 | SubmissionService.exists | validation | public function exists($form, Parameters $parameters = null): bool
{
$object = $this->execute('GET', 'http://www.mocky.io/v2/592c6f7311000029066df850');
if ($object && property_exists($object, '_id') && $object->_id) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q245832 | OwnerUuid.setOwnerUuid | validation | public function setOwnerUuid(?string $ownerUuid)
{
if (null !== $ownerUuid) {
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $ownerUuid)) {
throw new InvalidArgumentException('Owner uuid is not valid.');
}
}
$this->ownerUuid = $ownerUuid;
return $this;
} | php | {
"resource": ""
} |
q245833 | TaskService.submit | validation | public function submit($id, array $variables)
{
foreach ($variables as $variable) {
if (!$variable instanceof Variable) {
throw new InvalidArgumentException('Array of variables is not valid.');
}
}
$resource = str_replace('{id}', $id, static::RESOURCE_SUBMIT);
$options = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
]
];
foreach ($variables as $variable) {
// @todo Standardize variable toObject logic (see ProcessInstanceService::start)
$options['json']['variables'][$variable->getName()] = [
'value' => Variable::TYPE_JSON === $variable->getType() ? json_encode($variable->getValue()) : $variable->getValue(),
'type' => $variable->getType()
];
}
$this->execute('POST', $resource, $options);
} | php | {
"resource": ""
} |
q245834 | Parameters.replace | validation | public static function replace(string $string, array $data = []): string
{
$expressionLanguage = new ExpressionLanguage;
preg_match_all('/\%([a-z0-9_\[\]\"\.]+)\%/i', $string, $matches);
$placeholders = array_unique($matches[1]);
$translations = [];
foreach ($placeholders as $placeholder) {
$translations['%'.$placeholder.'%'] = $expressionLanguage->evaluate($placeholder, $data);
}
$string = strtr($string, $translations);
return $string;
} | php | {
"resource": ""
} |
q245835 | EncryptListener.postLoad | validation | public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Parameter) {
return;
}
$key = $entity->getKey();
$encrypt = $this->parameterCollection->get($key)['encrypt'];
$entity->setEncrypt($encrypt);
} | php | {
"resource": ""
} |
q245836 | AccessService.getPermissions | validation | public function getPermissions(User $user)
{
$permissions = new ArrayCollection;
// Generic identity permissions
$accesses = $this->repository->findBy([
'assignee' => $user->getIdentity()->getType(),
'assigneeUuid' => null
]);
foreach ($accesses as $access) {
foreach ($access->getPermissions() as $permission) {
$permissions->add($permission);
}
}
// Specific identity permissions
$accesses = $this->repository->findBy([
'assignee' => $user->getIdentity()->getType(),
'assigneeUuid' => $user->getIdentity()->getUuid()
]);
foreach ($accesses as $access) {
foreach ($access->getPermissions() as $permission) {
$permissions->add($permission);
}
}
// Roles permissions
$accesses = $this->repository->findBy([
'assignee' => 'Role',
'assigneeUuid' => $user->getIdentity()->getRoles()
]);
foreach ($accesses as $access) {
foreach ($access->getPermissions() as $permission) {
$permissions->add($permission);
}
}
return $permissions;
} | php | {
"resource": ""
} |
q245837 | RoleService.getList | validation | public function getList(): array
{
$objects = $this->execute('GET', static::RESOURCE_LIST);
$list = [];
foreach ($objects as $name => $object) {
$model = static::toModel($object);
$list[] = $model;
}
return $list;
} | php | {
"resource": ""
} |
q245838 | DeserializeValues.setDeserializeValues | validation | public function setDeserializeValues(?bool $deserializeValues)
{
$this->deserializeValues = $deserializeValues;
$this->_deserializeValues = null !== $deserializeValues;
return $this;
} | php | {
"resource": ""
} |
q245839 | IdentityService.generateIdentity | validation | public function generateIdentity(Identitiable $model, bool $overwrite = false)
{
if (null === $model->getIdentity() || $overwrite) {
$user = $this->tokenStorage->getToken()->getUser();
$model
->setIdentity($user->getIdentity()->getType())
->setIdentityUuid($user->getIdentity()->getUuid());
}
return $this;
} | php | {
"resource": ""
} |
q245840 | TranslateListener.kernelRequest | validation | public function kernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$entity = $request->attributes->get('_api_resource_class');
if (null === $entity) {
return;
}
if (!in_array(Translatable::class, class_implements($entity), true)) {
return;
}
$model = $request->attributes->get('data');
if ('post' === $request->attributes->get('_api_collection_operation_name')) {
$this->translationService->transfer($model);
} else if ('put' === $request->attributes->get('_api_item_operation_name')) {
$this->translationService->transfer($model);
$this->translationService->translate($model);
}
} | php | {
"resource": ""
} |
q245841 | TranslateListener.postLoad | validation | public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Translatable) {
return;
}
$this->translationService->translate($entity);
} | php | {
"resource": ""
} |
q245842 | PermissionsListener.kernelRequest | validation | public function kernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->isMethod(Request::METHOD_PUT)) {
return;
}
if (!$request->attributes->has('data')) {
return;
}
$data = $request->attributes->get('data');
if (!$data instanceof Access) {
return;
}
$access = $data;
$manager = $this->accessService->getManager();
foreach ($access->getPermissions() as $permission) {
$manager->remove($permission);
}
$manager->flush();
} | php | {
"resource": ""
} |
q245843 | CipherService.encrypt | validation | public function encrypt($data, string $key = null): string
{
$key = $this->createKey($key);
$data = Crypto::encrypt(serialize($data), $key);
return $data;
} | php | {
"resource": ""
} |
q245844 | CipherService.decrypt | validation | public function decrypt(string $data, string $key = null)
{
$key = $this->createKey($key);
$data = unserialize(Crypto::decrypt($data, $key));
return $data;
} | php | {
"resource": ""
} |
q245845 | Yaml.parse | validation | protected function parse($path): array
{
$fixtures = array_key_exists('FIXTURES', $_ENV) ? $_ENV['FIXTURES'] : 'dev';
$files = glob(str_replace('{fixtures}', $fixtures, $path));
if (!$files) {
throw new LogicException('Fixtures path "'.$path.'" yields no files.');
}
$objects = [];
foreach ($files as $file) {
foreach (Objects::parseFile($file) as $object) {
$objects[] = $object;
}
}
return $objects;
} | php | {
"resource": ""
} |
q245846 | EntityUuid.setEntityUuid | validation | public function setEntityUuid(?string $entityUuid)
{
if (null !== $entityUuid) {
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $entityUuid)) {
throw new InvalidArgumentException('Entity uuid is not valid.');
}
}
$this->entityUuid = $entityUuid;
return $this;
} | php | {
"resource": ""
} |
q245847 | AppsTrait.createApp | validation | public function createApp(string $client_name, string $redirect_uris, string $scopes, string $website = ''): array
{
$params = compact('client_name', 'redirect_uris', 'scopes', 'website');
return $this->post('/apps', $params);
} | php | {
"resource": ""
} |
q245848 | StatusesTrait.statuses | validation | public function statuses(int $account_id, int $limit = 40, int $since_id = null): array
{
$url = "/accounts/${account_id}/statuses";
$query = [
'limit' => $limit,
'since_id' => $since_id,
];
return $this->get($url, $query);
} | php | {
"resource": ""
} |
q245849 | StatusesTrait.createStatus | validation | public function createStatus(string $status, array $options = null): array
{
$url = '/statuses';
if (empty($options)) {
$options = [];
}
$params = array_merge(['status' => $status,], $options);
return $this->post($url, $params);
} | php | {
"resource": ""
} |
q245850 | MultiSelect.registerPlugin | validation | protected function registerPlugin()
{
$view = $this->getView();
MultiSelectAsset::register($view);
$id = $this->options['id'];
$options = $this->clientOptions !== false && !empty($this->clientOptions)
? Json::encode($this->clientOptions)
: '';
$js = "jQuery('#$id').multiselect($options);";
$view->registerJs($js);
} | php | {
"resource": ""
} |
q245851 | QRCode.geo | validation | public function geo($sLat, $sLon, $iHeight)
{
$this->sData .= 'GEO:' . $sLat . ',' . $sLon . ',' . $iHeight . "\n";
return $this;
} | php | {
"resource": ""
} |
q245852 | QRCode.get | validation | public function get($iSize = 150, $sECLevel = 'L', $iMargin = 1)
{
return self::API_URL . $iSize . 'x' . $iSize . '&cht=qr&chld=' . $sECLevel . '|' . $iMargin . '&chl=' . $this->sData;
} | php | {
"resource": ""
} |
q245853 | Api.prepare | validation | public function prepare(Command $command, Node $node)
{
$this->setCommand($command);
$this->setNode($node);
return $this;
} | php | {
"resource": ""
} |
q245854 | IndexTrait.withScalarValue | validation | public function withScalarValue($value)
{
$this->match = $value;
$this->lowerBound = null;
$this->upperBound = null;
return $this;
} | php | {
"resource": ""
} |
q245855 | IndexTrait.withRangeValue | validation | public function withRangeValue($lowerBound, $upperBound)
{
$this->lowerBound = $lowerBound;
$this->upperBound = $upperBound;
$this->match = null;
return $this;
} | php | {
"resource": ""
} |
q245856 | Builder.buildCluster | validation | public function buildCluster(array $hosts = ['localhost'])
{
$nodes = [];
foreach ($hosts as $host) {
$nodes[] = $this->atHost($host)->build();
}
return $nodes;
} | php | {
"resource": ""
} |
q245857 | Builder.validate | validation | protected function validate()
{
// verify we have a host address and port
if (!$this->config->getHost() || !$this->config->getPort()) {
throw new Node\Builder\Exception('Node host address and port number are required.');
}
if ($this->config->getUser() && $this->config->getCertificate()) {
throw new Node\Builder\Exception('Connect with password OR certificate authentication, not both.');
}
if ($this->config->isAuth() && !$this->config->getCaDirectory() && !$this->config->getCaFile()) {
throw new Node\Builder\Exception('Certificate authority file is required for authentication.');
}
} | php | {
"resource": ""
} |
q245858 | Builder.buildLocalhost | validation | public function buildLocalhost(array $ports = [8087])
{
$nodes = [];
$this->atHost('localhost');
foreach ($ports as $port) {
$nodes[] = $this->onPort($port)->build();
}
return $nodes;
} | php | {
"resource": ""
} |
q245859 | Builder.required | validation | protected function required($objectName)
{
$method = "get{$objectName}";
$class = "Basho\\Riak\\{$objectName}";
$value = $this->$method();
if (is_null($value)) {
throw new Builder\Exception("Expected non-empty value for {$objectName}");
}
if (is_object($value) && $value instanceof $class === false) {
throw new Builder\Exception("Expected instance of {$class}, received instance of " . get_class($value));
}
if (is_array($value) && count($value) == 0) {
throw new Builder\Exception("Expected non-empty array value for {$objectName}");
}
} | php | {
"resource": ""
} |
q245860 | Location.fromString | validation | public static function fromString($location_string)
{
preg_match('/^\/types\/([^\/]+)\/buckets\/([^\/]+)\/keys\/([^\/]+)$/', $location_string, $matches);
return new self($matches[3], new Bucket($matches[2], $matches[1]));
} | php | {
"resource": ""
} |
q245861 | ObjectTrait.buildObject | validation | public function buildObject($data = NULL, $headers = NULL)
{
$this->object = new RObject($data, $headers);
return $this;
} | php | {
"resource": ""
} |
q245862 | ObjectTrait.buildJsonObject | validation | public function buildJsonObject($data)
{
$this->object = new RObject();
$this->object->setData($data);
$this->object->setContentType(Http::CONTENT_TYPE_JSON);
return $this;
} | php | {
"resource": ""
} |
q245863 | Riak.pickNode | validation | protected function pickNode()
{
$nodes = $this->getNodes();
$index = mt_rand(0, count($nodes) - 1);
return array_keys($nodes)[$index];
} | php | {
"resource": ""
} |
q245864 | Riak.execute | validation | public function execute(Command $command)
{
$response = $this->getActiveNode()->execute($command, $this->api);
// if more than 1 node configured, lets try a different node up to max connection attempts
if (empty($response) && count($this->nodes) > 1 && $this->attempts < $this->getConfigValue('max_connect_attempts')) {
$response = $this->pickNewNode()->execute($command);
} elseif (empty($response) && $this->attempts >= $this->getConfigValue('max_connect_attempts')) {
throw new Exception('Nodes unreachable. Error Msg: ' . $this->api->getError());
} elseif ($response == false) {
throw new Exception('Command failed to execute against Riak. Error Msg: ' . $this->api->getError());
}
return $response;
} | php | {
"resource": ""
} |
q245865 | Riak.pickNewNode | validation | public function pickNewNode()
{
// mark current active node as inactive and increment attempts
$this->getActiveNode()->setInactive(true);
$this->attempts++;
$this->inactiveNodes[$this->getActiveNodeIndex()] = $this->getActiveNode();
// move active node to inactive nodes structure to prevent selecting again
unset($this->nodes[$this->getActiveNodeIndex()]);
$this->setActiveNodeIndex($this->pickNode());
return $this;
} | php | {
"resource": ""
} |
q245866 | Http.prepare | validation | public function prepare(Command $command, Node $node)
{
if ($this->connection) {
$this->resetConnection();
}
// call parent prepare method to setup object members
parent::prepare($command, $node);
// set the API path to be used
$this->buildPath();
// general connection preparation
$this->prepareConnection();
// request specific connection preparation
$this->prepareRequest();
return $this;
} | php | {
"resource": ""
} |
q245867 | Http.createIndexQueryPath | validation | private function createIndexQueryPath(Bucket $bucket)
{
/** @var Command\Indexes\Query $command */
$command = $this->command;
if($command->isMatchQuery()) {
$path = sprintf('/types/%s/buckets/%s/index/%s/%s', $bucket->getType(),
$bucket->getName(),
$command->getIndexName(),
$command->getMatchValue());
}
elseif($command->isRangeQuery()) {
$path = sprintf('/types/%s/buckets/%s/index/%s/%s/%s', $bucket->getType(),
$bucket->getName(),
$command->getIndexName(),
$command->getLowerBound(),
$command->getUpperBound());
}
else
{
throw new Api\Exception("Invalid Secondary Index Query.");
}
return $path;
} | php | {
"resource": ""
} |
q245868 | Http.prepareRequestData | validation | protected function prepareRequestData()
{
// if POST or PUT, add parameters to post data, else add to uri
if (in_array($this->command->getMethod(), ['POST', 'PUT'])) {
$this->requestBody = $this->command->getEncodedData();
$this->options[CURLOPT_POSTFIELDS] = $this->requestBody;
}
return $this;
} | php | {
"resource": ""
} |
q245869 | Http.prepareRequestUrl | validation | protected function prepareRequestUrl()
{
$protocol = $this->node->useTls() ? 'https' : 'http';
$this->requestURL = sprintf('%s://%s%s?%s', $protocol, $this->node->getUri(), $this->path, $this->query);
// set the built request URL on the connection
$this->options[CURLOPT_URL] = $this->requestURL;
return $this;
} | php | {
"resource": ""
} |
q245870 | Http.prepareRequestParameters | validation | protected function prepareRequestParameters()
{
if ($this->command->hasParameters()) {
// build query using RFC 3986 (spaces become %20 instead of '+')
$this->query = http_build_query($this->command->getParameters(), '', '&', PHP_QUERY_RFC3986);
}
return $this;
} | php | {
"resource": ""
} |
q245871 | Http.prepareRequestHeaders | validation | protected function prepareRequestHeaders()
{
$curl_headers = [];
foreach ($this->headers as $key => $value) {
$curl_headers[] = sprintf('%s: %s', $key, $value);
}
// if we have an object, set appropriate object headers
$object = $this->command->getObject();
if ($object) {
if ($object->getVclock()) {
$curl_headers[] = sprintf('%s: %s', static::VCLOCK_KEY, $object->getVclock());
}
if ($object->getContentType()) {
$charset = '';
if ($object->getCharset()) {
$charset = sprintf('; charset=%s', $object->getCharset());
}
$curl_headers[] = sprintf('%s: %s', static::CONTENT_TYPE_KEY, $object->getContentType(), $charset);
}
// setup index headers
$translator = new Api\Http\Translator\SecondaryIndex();
$indexHeaders = $translator->createHeadersFromIndexes($object->getIndexes());
foreach ($indexHeaders as $value) {
$curl_headers[] = sprintf('%s: %s', $value[0], $value[1]);
}
// setup metadata headers
foreach($object->getMetaData() as $key => $value) {
$curl_headers[] = sprintf('%s%s: %s', static::METADATA_PREFIX, $key, $value);
}
}
// set the request headers on the connection
$this->options[CURLOPT_HTTPHEADER] = $curl_headers;
// dump local headers to start fresh
$this->headers = [];
return $this;
} | php | {
"resource": ""
} |
q245872 | Http.prepareRequestMethod | validation | protected function prepareRequestMethod()
{
switch ($this->command->getMethod()) {
case "POST":
$this->options[CURLOPT_POST] = 1;
break;
case "PUT":
$this->options[CURLOPT_CUSTOMREQUEST] = 'PUT';
break;
case "DELETE":
$this->options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
break;
case "HEAD":
$this->options[CURLOPT_NOBODY] = 1;
break;
default:
// reset http method to get in case its changed
$this->options[CURLOPT_HTTPGET] = 1;
}
return $this;
} | php | {
"resource": ""
} |
q245873 | Http.responseHeaderCallback | validation | public function responseHeaderCallback($ch, $header)
{
if (strpos($header, ':')) {
list ($key, $value) = explode(':', $header, 2);
$value = trim($value);
if (!empty($value)) {
if (!isset($this->responseHeaders[$key])) {
$this->responseHeaders[$key] = $value;
} elseif (is_array($this->responseHeaders[$key])) {
$this->responseHeaders[$key] = array_merge($this->responseHeaders[$key], [$value]);
} else {
$this->responseHeaders[$key] = array_merge([$this->responseHeaders[$key]], [$value]);
}
}
}
return strlen($header);
} | php | {
"resource": ""
} |
q245874 | HeadersTrait.getHeader | validation | protected function getHeader($key)
{
return isset($this->headers[$key]) ? $this->headers[$key] : NULL;
} | php | {
"resource": ""
} |
q245875 | Email.getComputedAttachments | validation | public function getComputedAttachments(): array
{
if (! $this->hasAttachments()) {
return [];
}
$attachments = $this->getAttachments();
// Process the attachments dir if any, and include the files in that folder
$dir = $this->getAttachmentsDir();
$path = $dir['path'] ?? null;
$recursive = $dir['recursive'] ?? false;
if (is_string($path) && is_dir($path)) {
$files = $recursive ? new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
) : new DirectoryIterator($path);
/* @var \SplFileInfo $fileInfo */
foreach ($files as $fileInfo) {
if ($fileInfo->isDir()) {
continue;
}
$attachments[] = $fileInfo->getPathname();
}
}
return $attachments;
} | php | {
"resource": ""
} |
q245876 | MailServiceAbstractFactory.attachMailListeners | validation | private function attachMailListeners(
EventsCapableInterface $service,
ContainerInterface $container,
array $mailOptions
): void {
$listeners = (array) ($mailOptions['mail_listeners'] ?? []);
if (empty($listeners)) {
return;
}
$definitions = [];
$eventManager = $service->getEventManager();
foreach ($listeners as $listener) {
$this->addDefinitions($definitions, $listener, $eventManager);
}
// Attach lazy event listeners if any
if (! empty($definitions)) {
(new LazyListenerAggregate($definitions, $container))->attach($eventManager);
}
} | php | {
"resource": ""
} |
q245877 | MailService.send | validation | public function send($email, array $options = []): ResultInterface
{
// Try to resolve the email to be sent
if (is_string($email)) {
$email = $this->emailBuilder->build($email, $options);
} elseif (is_array($email)) {
$email = $this->emailBuilder->build(Email::class, $email);
} elseif (! $email instanceof Email) {
throw Exception\InvalidArgumentException::fromValidTypes(
['string', 'array', Email::class],
$email,
'email'
);
}
// Trigger the pre render event and then render the email's body in case it has to be composed from a template
$this->events->triggerEvent($this->createMailEvent($email, MailEvent::EVENT_MAIL_PRE_RENDER));
$this->renderEmailBody($email);
// Trigger pre send event, and cancel email sending if any listener returned false
$eventResp = $this->events->triggerEvent($this->createMailEvent($email, MailEvent::EVENT_MAIL_PRE_SEND));
if ($eventResp->contains(false)) {
return new MailResult($email, false);
}
try {
// Build the message object to send
$message = MessageFactory::createMessageFromEmail($email)->setBody(
$this->buildBody($email->getBody(), $email->getCharset())
);
$this->attachFiles($message, $email);
$this->addCustomHeaders($message, $email);
// Try to send the message
$this->transport->send($message);
// Trigger post send event
$result = new MailResult($email);
$this->events->triggerEvent($this->createMailEvent($email, MailEvent::EVENT_MAIL_POST_SEND, $result));
return $result;
} catch (Throwable $e) {
// Trigger error event, notifying listeners of the error
$this->events->triggerEvent($this->createMailEvent($email, MailEvent::EVENT_MAIL_SEND_ERROR, new MailResult(
$email,
false,
$e
)));
throw new Exception\MailException('An error occurred while trying to send the email', $e->getCode(), $e);
}
} | php | {
"resource": ""
} |
q245878 | MailService.createMailEvent | validation | private function createMailEvent(
Email $email,
string $name,
ResultInterface $result = null
): MailEvent {
$event = new MailEvent($email, $name);
if ($result !== null) {
$event->setResult($result);
}
return $event;
} | php | {
"resource": ""
} |
q245879 | MailService.buildBody | validation | private function buildBody($body, string $charset): Mime\Message
{
if ($body instanceof Mime\Message) {
return $body;
}
// If the body is a string, wrap it into a Mime\Part
if (is_string($body)) {
$mimePart = new Mime\Part($body);
$mimePart->type = $body !== strip_tags($body) ? Mime\Mime::TYPE_HTML : Mime\Mime::TYPE_TEXT;
$body = $mimePart;
}
$body->charset = $charset;
$message = new Mime\Message();
$message->setParts([$body]);
return $message;
} | php | {
"resource": ""
} |
q245880 | MailService.attachFiles | validation | private function attachFiles(Message $message, Email $email)
{
if (! $email->hasAttachments()) {
return;
}
$attachments = $email->getComputedAttachments();
// Get old message parts
/** @var Mime\Message $mimeMessage */
$mimeMessage = $message->getBody();
$oldParts = $mimeMessage->getParts();
// Generate a new Mime\Part for each attachment
$attachmentParts = [];
$info = null;
foreach ($attachments as $key => $attachment) {
// If the attachment is an array with "parser_name" and "value" keys, cast it into an Attachment object
if (is_array($attachment) && isset($attachment['parser_name'], $attachment['value'])) {
$attachment = Attachment::fromArray($attachment);
}
$parserName = $this->resolveParserNameFromAttachment($attachment);
if (! $this->attachmentParserManager->has($parserName)) {
throw new Exception\ServiceNotCreatedException(
sprintf('The attachment parser "%s" could not be found', $parserName)
);
}
/** @var AttachmentParserInterface $parser */
$parser = $this->attachmentParserManager->get($parserName);
$attachmentValue = $attachment instanceof Attachment ? $attachment->getValue() : $attachment;
$part = $parser->parse($attachmentValue, is_string($key) ? $key : null);
$part->charset = $email->getCharset();
$attachmentParts[] = $part;
}
// Create a new body for the message, merging the attachment parts and all the old parts
$body = new Mime\Message();
$body->setParts(array_merge($oldParts, $attachmentParts));
$message->setBody($body);
} | php | {
"resource": ""
} |
q245881 | MailViewRendererFactory.createHelperPluginManager | validation | private function createHelperPluginManager(ContainerInterface $container): HelperPluginManager
{
$factory = new ViewHelperManagerFactory();
/** @var HelperPluginManager $helperManager */
$helperManager = $factory($container, ViewHelperManagerFactory::PLUGIN_MANAGER_CLASS);
$config = new Config($this->getSpecificConfig($container, 'view_helpers'));
$config->configureServiceManager($helperManager);
return $helperManager;
} | php | {
"resource": ""
} |
q245882 | LoggerCallback.buildCallback | validation | private function buildCallback(BuildInfo $output)
{
$message = "";
if ($output->getError()) {
$this->logger->error(sprintf("Error when creating job: %s\n", $output->getError()), array('static' => false, 'static-id' => null));
return;
}
if ($output->getStream()) {
$message = $output->getStream();
}
if ($output->getStatus()) {
$message = $output->getStatus();
if ($output->getProgress()) {
$message .= " " . $output->getProgress();
}
}
// Force new line
if (!$output->getId() && !preg_match('#\n#', $message)) {
$message .= "\n";
}
$this->logger->debug($message, array(
'static' => $output->getId() !== null,
'static-id' => $output->getId(),
));
} | php | {
"resource": ""
} |
q245883 | Naming.getProjectName | validation | public function getProjectName($projectPath)
{
$project = basename(realpath($projectPath));
$project = Transliterator::transliterate($project, '-');
return $project;
} | php | {
"resource": ""
} |
q245884 | ServiceManager.start | validation | public function start(Job $build)
{
foreach ($build->getServices() as $service) {
try {
$this->docker->getImageManager()->find(sprintf('%s:%s', $service->getRepository(), $service->getTag()));
} catch (ClientErrorException $e) {
if ($e->getResponse()->getStatusCode() == 404) {
$buildStream = $this->docker->getImageManager()->create(null, [
'fromImage' => sprintf('%s:%s', $service->getRepository(), $service->getTag())
], ImageManager::FETCH_STREAM);
$buildStream->onFrame($this->logger->getBuildCallback());
$buildStream->wait();
} else {
throw $e;
}
}
$serviceConfig = $service->getConfig();
$containerConfig = new ContainerConfig();
$containerConfig->setImage(sprintf('%s:%s', $service->getRepository(), $service->getTag()));
$containerConfig->setLabels([
'com.jolici.container=true'
]);
if (isset($serviceConfig['Env'])) {
$containerConfig->setEnv($serviceConfig['Env']);
}
$containerCreateResult = $this->docker->getContainerManager()->create($containerConfig);
$this->docker->getContainerManager()->start($containerCreateResult->getId());
$service->setContainer($containerCreateResult->getId());
}
} | php | {
"resource": ""
} |
q245885 | ServiceManager.stop | validation | public function stop(Job $job, $timeout = 10)
{
foreach ($job->getServices() as $service) {
if ($service->getContainer()) {
try {
$this->docker->getContainerManager()->stop($service->getContainer(), [
't' => $timeout
]);
} catch (ClientErrorException $e) {
if ($e->getResponse()->getStatusCode() != 304) {
throw $e;
}
}
$this->docker->getContainerManager()->remove($service->getContainer(), [
'v' => true,
'force' => true
]);
$service->setContainer(null);
}
}
} | php | {
"resource": ""
} |
q245886 | Matrix.setDimension | validation | public function setDimension($name, array $values)
{
if (empty($values)) {
$values = array(null);
}
$this->dimensions[$name] = $values;
} | php | {
"resource": ""
} |
q245887 | Matrix.compute | validation | public function compute()
{
$dimensions = $this->dimensions;
if (empty($dimensions)) {
return array();
}
// Pop first dimension
$values = reset($dimensions);
$name = key($dimensions);
unset($dimensions[$name]);
// Create all possiblites for the first dimension
$posibilities = array();
foreach ($values as $v) {
$posibilities[] = array($name => $v);
}
// If only one dimension return simple all the possibilites created (break point of recursivity)
if (empty($dimensions)) {
return $posibilities;
}
// If not create a new matrix with remaining dimension
$matrix = new Matrix();
foreach ($dimensions as $name => $values) {
$matrix->setDimension($name, $values);
}
$result = $matrix->compute();
$newResult = array();
foreach ($result as $value) {
foreach ($posibilities as $possiblity) {
$newResult[] = $value + $possiblity;
}
}
return $newResult;
} | php | {
"resource": ""
} |
q245888 | Filesystem.copy | validation | public function copy($originFile, $targetFile, $override = false)
{
parent::copy($originFile, $targetFile, $override);
$this->chmod($targetFile, fileperms($originFile));
} | php | {
"resource": ""
} |
q245889 | TravisCiBuildStrategy.getConfigValue | validation | private function getConfigValue($config, $language, $key)
{
if (!isset($config[$key]) || empty($config[$key])) {
if (isset($this->defaults[$language][$key])) {
return $this->defaults[$language][$key];
}
return array();
}
if (!is_array($config[$key])) {
return array($config[$key]);
}
return $config[$key];
} | php | {
"resource": ""
} |
q245890 | TravisCiBuildStrategy.getServices | validation | protected function getServices($config)
{
$services = array();
$travisServices = isset($config['services']) && is_array($config['services']) ? $config['services'] : array();
foreach ($travisServices as $service) {
if (isset($this->servicesMapping[$service])) {
$services[] = new Service(
$service,
$this->servicesMapping[$service]['repository'],
$this->servicesMapping[$service]['tag'],
$this->servicesMapping[$service]['config']
);
}
}
return $services;
} | php | {
"resource": ""
} |
q245891 | TravisCiBuildStrategy.parseEnvironmentLine | validation | private function parseEnvironmentLine($environmentLine)
{
$variables = array();@
$variableLines = explode(' ', $environmentLine ?: '');
foreach ($variableLines as $variableLine) {
if (!empty($variableLine)) {
list($key, $value) = $this->parseEnvironementVariable($variableLine);
$variables[$key] = $value;
}
}
return $variables;
} | php | {
"resource": ""
} |
q245892 | Vacuum.clean | validation | public function clean($projectPath, $keep = 1, $force = false)
{
$builds = $this->getJobsToRemove($projectPath, $keep);
$this->cleanDirectories($builds);
$this->cleanContainers($builds);
$this->cleanImages($builds, $force);
} | php | {
"resource": ""
} |
q245893 | Vacuum.cleanDirectories | validation | public function cleanDirectories($jobs = array())
{
foreach ($jobs as $job) {
$this->filesystem->remove($job->getDirectory());
}
} | php | {
"resource": ""
} |
q245894 | Vacuum.getJobsToRemove | validation | public function getJobsToRemove($projectPath, $keep = 1)
{
$currentJobs = $this->strategy->getJobs($projectPath);
$existingJobs = $this->getJobs($projectPath);
$uniqList = array();
$removes = array();
$ordered = array();
foreach ($currentJobs as $job) {
$uniqList[] = $job->getUniq();
}
// Remove not existant image (old build configuration)
foreach ($existingJobs as $job) {
if (!in_array($job->getUniq(), $uniqList)) {
$removes[] = $job;
} else {
$ordered[$job->getUniq()][$job->getCreated()->format('U')] = $job;
}
}
// Remove old image
foreach ($ordered as $jobs) {
ksort($jobs);
$keeped = count($jobs);
while ($keeped > $keep) {
$removes[] = array_shift($jobs);
$keeped--;
}
}
return $removes;
} | php | {
"resource": ""
} |
q245895 | Vacuum.getJobs | validation | protected function getJobs($projectPath)
{
$jobs = array();
$project = $this->naming->getProjectName($projectPath);
$repositoryRegex = sprintf('#^%s_([a-z]+?)/%s:\d+-\d+$#', Job::BASE_NAME, $project);
foreach ($this->docker->getImageManager()->findAll() as $image) {
foreach ($image->getRepoTags() as $name) {
if (preg_match($repositoryRegex, $name, $matches)) {
$jobs[] = $this->getJobFromImage($image, $name, $matches[1], $project);
}
}
}
return $jobs;
} | php | {
"resource": ""
} |
q245896 | Vacuum.getJobFromImage | validation | protected function getJobFromImage(ImageItem $image, $imageName, $strategy, $project)
{
$tag = explode(':', $imageName)[1];
list($uniq, $timestamp) = explode('-', $tag);
return new Job($project, $strategy, $uniq, array('image' => $image), "", \DateTime::createFromFormat('U', $timestamp));
} | php | {
"resource": ""
} |
q245897 | Executor.create | validation | public function create(Job $job)
{
$context = new Context($this->buildPath . DIRECTORY_SEPARATOR . $job->getDirectory());
$buildStream = $this->docker->getImageManager()->build($context->toStream(), [
't' => $job->getName(),
'q' => $this->quietBuild,
'nocache' => !$this->usecache
], ImageManager::FETCH_STREAM);
$buildStream->onFrame($this->logger->getBuildCallback());
$buildStream->wait();
try {
return $this->docker->getImageManager()->find($job->getName());
} catch (ClientErrorException $e) {
if ($e->getResponse()->getStatusCode() == 404) {
return false;
}
throw $e;
}
} | php | {
"resource": ""
} |
q245898 | Executor.run | validation | public function run(Job $job, $command)
{
if (is_string($command)) {
$command = ['/bin/bash', '-c', $command];
}
$image = $this->docker->getImageManager()->find($job->getName());
$hostConfig = new HostConfig();
$config = new ContainerConfig();
$config->setCmd($command);
$config->setImage($image->getId());
$config->setHostConfig($hostConfig);
$config->setLabels(new \ArrayObject([
'com.jolici.container=true'
]));
$config->setAttachStderr(true);
$config->setAttachStdout(true);
$links = [];
foreach ($job->getServices() as $service) {
if ($service->getContainer()) {
$serviceContainer = $this->docker->getContainerManager()->find($service->getContainer());
$links[] = sprintf('%s:%s', $serviceContainer->getName(), $service->getName());
}
}
$hostConfig->setLinks($links);
$containerCreateResult = $this->docker->getContainerManager()->create($config);
$attachStream = $this->docker->getContainerManager()->attach($containerCreateResult->getId(), [
'stream' => true,
'stdout' => true,
'stderr' => true,
], ContainerManager::FETCH_STREAM);
$attachStream->onStdout($this->logger->getRunStdoutCallback());
$attachStream->onStderr($this->logger->getRunStderrCallback());
$this->docker->getContainerManager()->start($containerCreateResult->getId());
$attachStream->wait();
$containerWait = $this->docker->getContainerManager()->wait($containerCreateResult->getId());
return $containerWait->getStatusCode();
} | php | {
"resource": ""
} |
q245899 | Container.getTravisCiStrategy | validation | public function getTravisCiStrategy()
{
$builder = new DockerfileBuilder();
$generator = new Generator();
$generator->setTemplateDirs(array(
__DIR__."/../../../resources/templates",
));
$generator->setMustOverwriteIfExists(true);
$generator->addBuilder($builder);
return new TravisCiBuildStrategy($builder, $this->getBuildPath(), $this->getNaming(), $this->getFilesystem());
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.