repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
claroline/Distribution | plugin/exo/Serializer/Attempt/AnswerSerializer.php | AnswerSerializer.serialize | public function serialize(Answer $answer, array $options = [])
{
$serialized = [
'id' => $answer->getUuid(),
'questionId' => $answer->getQuestionId(),
'tries' => $answer->getTries(),
'usedHints' => array_map(function ($hintId) use ($options) {
return $options['hints'][$hintId];
}, $answer->getUsedHints()),
];
if (!empty($answer->getData())) {
$serialized['data'] = json_decode($answer->getData(), true);
}
// Adds user score
if (in_array(Transfer::INCLUDE_USER_SCORE, $options)) {
$serialized = array_merge($serialized, [
'score' => $answer->getScore(),
'feedback' => $answer->getFeedback(),
]);
}
return $serialized;
} | php | public function serialize(Answer $answer, array $options = [])
{
$serialized = [
'id' => $answer->getUuid(),
'questionId' => $answer->getQuestionId(),
'tries' => $answer->getTries(),
'usedHints' => array_map(function ($hintId) use ($options) {
return $options['hints'][$hintId];
}, $answer->getUsedHints()),
];
if (!empty($answer->getData())) {
$serialized['data'] = json_decode($answer->getData(), true);
}
// Adds user score
if (in_array(Transfer::INCLUDE_USER_SCORE, $options)) {
$serialized = array_merge($serialized, [
'score' => $answer->getScore(),
'feedback' => $answer->getFeedback(),
]);
}
return $serialized;
} | [
"public",
"function",
"serialize",
"(",
"Answer",
"$",
"answer",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"serialized",
"=",
"[",
"'id'",
"=>",
"$",
"answer",
"->",
"getUuid",
"(",
")",
",",
"'questionId'",
"=>",
"$",
"answer",
"->... | Converts an Answer into a JSON-encodable structure.
@param Answer $answer
@param array $options
@return array | [
"Converts",
"an",
"Answer",
"into",
"a",
"JSON",
"-",
"encodable",
"structure",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/Attempt/AnswerSerializer.php#L28-L51 | train |
claroline/Distribution | plugin/exo/Serializer/Attempt/AnswerSerializer.php | AnswerSerializer.deserialize | public function deserialize($data, Answer $answer = null, array $options = [])
{
$answer = $answer ?: new Answer();
$this->sipe('id', 'setUuid', $data, $answer);
$this->sipe('questionId', 'setQuestionId', $data, $answer);
$this->sipe('tries', 'setTries', $data, $answer);
$this->sipe('score', 'setScore', $data, $answer);
$this->sipe('feedback', 'setFeedback', $data, $answer);
if (isset($data['usedHints'])) {
foreach ($data['usedHints'] as $usedHint) {
$answer->addUsedHint($usedHint['id']);
}
}
if (!empty($data['data'])) {
$answer->setData(json_encode($data['data']));
}
return $answer;
} | php | public function deserialize($data, Answer $answer = null, array $options = [])
{
$answer = $answer ?: new Answer();
$this->sipe('id', 'setUuid', $data, $answer);
$this->sipe('questionId', 'setQuestionId', $data, $answer);
$this->sipe('tries', 'setTries', $data, $answer);
$this->sipe('score', 'setScore', $data, $answer);
$this->sipe('feedback', 'setFeedback', $data, $answer);
if (isset($data['usedHints'])) {
foreach ($data['usedHints'] as $usedHint) {
$answer->addUsedHint($usedHint['id']);
}
}
if (!empty($data['data'])) {
$answer->setData(json_encode($data['data']));
}
return $answer;
} | [
"public",
"function",
"deserialize",
"(",
"$",
"data",
",",
"Answer",
"$",
"answer",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"answer",
"=",
"$",
"answer",
"?",
":",
"new",
"Answer",
"(",
")",
";",
"$",
"this",
"->... | Converts raw data into a Answer entity.
@param array $data
@param Answer $answer
@param array $options
@return Answer | [
"Converts",
"raw",
"data",
"into",
"a",
"Answer",
"entity",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/Attempt/AnswerSerializer.php#L62-L82 | train |
claroline/Distribution | plugin/exo/Serializer/StepSerializer.php | StepSerializer.serialize | public function serialize(Step $step, array $options = [])
{
$serialized = [
'id' => $step->getUuid(),
'parameters' => $this->serializeParameters($step),
'picking' => $this->serializePicking($step),
'items' => $this->serializeItems($step, $options),
];
if (!empty($step->getTitle())) {
$serialized['title'] = $step->getTitle();
}
if (!empty($step->getDescription())) {
$serialized['description'] = $step->getDescription();
}
return $serialized;
} | php | public function serialize(Step $step, array $options = [])
{
$serialized = [
'id' => $step->getUuid(),
'parameters' => $this->serializeParameters($step),
'picking' => $this->serializePicking($step),
'items' => $this->serializeItems($step, $options),
];
if (!empty($step->getTitle())) {
$serialized['title'] = $step->getTitle();
}
if (!empty($step->getDescription())) {
$serialized['description'] = $step->getDescription();
}
return $serialized;
} | [
"public",
"function",
"serialize",
"(",
"Step",
"$",
"step",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"serialized",
"=",
"[",
"'id'",
"=>",
"$",
"step",
"->",
"getUuid",
"(",
")",
",",
"'parameters'",
"=>",
"$",
"this",
"->",
"se... | Converts a Step into a JSON-encodable structure.
@param Step $step
@param array $options
@return array | [
"Converts",
"a",
"Step",
"into",
"a",
"JSON",
"-",
"encodable",
"structure",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/StepSerializer.php#L50-L67 | train |
claroline/Distribution | plugin/exo/Serializer/StepSerializer.php | StepSerializer.deserialize | public function deserialize($data, Step $step = null, array $options = [])
{
$step = $step ?: new Step();
$this->sipe('id', 'setUuid', $data, $step);
$this->sipe('title', 'setTitle', $data, $step);
$this->sipe('description', 'setDescription', $data, $step);
if (in_array(Transfer::REFRESH_UUID, $options)) {
$step->refreshUuid();
}
if (!empty($data['parameters'])) {
$this->deserializeParameters($step, $data['parameters']);
}
if (!empty($data['picking'])) {
$this->deserializePicking($step, $data['picking']);
}
if (!empty($data['items'])) {
$this->deserializeItems($step, $data['items'], $options);
}
return $step;
} | php | public function deserialize($data, Step $step = null, array $options = [])
{
$step = $step ?: new Step();
$this->sipe('id', 'setUuid', $data, $step);
$this->sipe('title', 'setTitle', $data, $step);
$this->sipe('description', 'setDescription', $data, $step);
if (in_array(Transfer::REFRESH_UUID, $options)) {
$step->refreshUuid();
}
if (!empty($data['parameters'])) {
$this->deserializeParameters($step, $data['parameters']);
}
if (!empty($data['picking'])) {
$this->deserializePicking($step, $data['picking']);
}
if (!empty($data['items'])) {
$this->deserializeItems($step, $data['items'], $options);
}
return $step;
} | [
"public",
"function",
"deserialize",
"(",
"$",
"data",
",",
"Step",
"$",
"step",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"step",
"=",
"$",
"step",
"?",
":",
"new",
"Step",
"(",
")",
";",
"$",
"this",
"->",
"sipe... | Converts raw data into a Step entity.
@param array $data
@param Step $step
@param array $options
@return Step | [
"Converts",
"raw",
"data",
"into",
"a",
"Step",
"entity",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/StepSerializer.php#L78-L103 | train |
claroline/Distribution | plugin/exo/Serializer/StepSerializer.php | StepSerializer.deserializeParameters | private function deserializeParameters(Step $step, array $parameters)
{
$this->sipe('maxAttempts', 'setMaxAttempts', $parameters, $step);
$this->sipe('duration', 'setDuration', $parameters, $step);
} | php | private function deserializeParameters(Step $step, array $parameters)
{
$this->sipe('maxAttempts', 'setMaxAttempts', $parameters, $step);
$this->sipe('duration', 'setDuration', $parameters, $step);
} | [
"private",
"function",
"deserializeParameters",
"(",
"Step",
"$",
"step",
",",
"array",
"$",
"parameters",
")",
"{",
"$",
"this",
"->",
"sipe",
"(",
"'maxAttempts'",
",",
"'setMaxAttempts'",
",",
"$",
"parameters",
",",
"$",
"step",
")",
";",
"$",
"this",
... | Deserializes Step parameters.
@param Step $step
@param array $parameters | [
"Deserializes",
"Step",
"parameters",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/StepSerializer.php#L126-L130 | train |
claroline/Distribution | plugin/exo/Serializer/StepSerializer.php | StepSerializer.serializeItems | public function serializeItems(Step $step, array $options = [])
{
return array_values(array_map(function (StepItem $stepQuestion) use ($options) {
$serialized = $this->itemSerializer->serialize($stepQuestion->getQuestion(), $options);
$serialized['meta']['mandatory'] = $stepQuestion->isMandatory();
return $serialized;
}, $step->getStepQuestions()->toArray()));
} | php | public function serializeItems(Step $step, array $options = [])
{
return array_values(array_map(function (StepItem $stepQuestion) use ($options) {
$serialized = $this->itemSerializer->serialize($stepQuestion->getQuestion(), $options);
$serialized['meta']['mandatory'] = $stepQuestion->isMandatory();
return $serialized;
}, $step->getStepQuestions()->toArray()));
} | [
"public",
"function",
"serializeItems",
"(",
"Step",
"$",
"step",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"array_values",
"(",
"array_map",
"(",
"function",
"(",
"StepItem",
"$",
"stepQuestion",
")",
"use",
"(",
"$",
"options",
"... | Serializes Step items.
Forwards the item serialization to ItemSerializer.
@param Step $step
@param array $options
@return array | [
"Serializes",
"Step",
"items",
".",
"Forwards",
"the",
"item",
"serialization",
"to",
"ItemSerializer",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/StepSerializer.php#L165-L173 | train |
claroline/Distribution | plugin/exo/Serializer/StepSerializer.php | StepSerializer.deserializeItems | public function deserializeItems(Step $step, array $items = [], array $options = [])
{
$stepQuestions = $step->getStepQuestions()->toArray();
foreach ($items as $index => $itemData) {
$item = null;
$stepQuestion = null;
// Searches for an existing item entity.
foreach ($stepQuestions as $entityIndex => $entityStepQuestion) {
/** @var StepItem $entityStepQuestion */
if ($entityStepQuestion->getQuestion()->getUuid() === $itemData['id']) {
$stepQuestion = $entityStepQuestion;
$item = $stepQuestion->getQuestion();
unset($stepQuestions[$entityIndex]);
break;
}
}
$entity = $this->itemSerializer->deserialize($itemData, $item, $options);
if (empty($stepQuestion)) {
// Creation of a new item (we need to link it to the Step)
$stepQuestion = $step->addQuestion($entity);
} else {
// Update order of the Item in the Step
$stepQuestion->setOrder($index);
}
if (isset($itemData['meta']['mandatory'])) {
$stepQuestion->setMandatory($itemData['meta']['mandatory']);
}
}
// Remaining items are no longer in the Step
if (0 < count($stepQuestions)) {
foreach ($stepQuestions as $stepQuestionToRemove) {
$step->removeStepQuestion($stepQuestionToRemove);
}
}
} | php | public function deserializeItems(Step $step, array $items = [], array $options = [])
{
$stepQuestions = $step->getStepQuestions()->toArray();
foreach ($items as $index => $itemData) {
$item = null;
$stepQuestion = null;
// Searches for an existing item entity.
foreach ($stepQuestions as $entityIndex => $entityStepQuestion) {
/** @var StepItem $entityStepQuestion */
if ($entityStepQuestion->getQuestion()->getUuid() === $itemData['id']) {
$stepQuestion = $entityStepQuestion;
$item = $stepQuestion->getQuestion();
unset($stepQuestions[$entityIndex]);
break;
}
}
$entity = $this->itemSerializer->deserialize($itemData, $item, $options);
if (empty($stepQuestion)) {
// Creation of a new item (we need to link it to the Step)
$stepQuestion = $step->addQuestion($entity);
} else {
// Update order of the Item in the Step
$stepQuestion->setOrder($index);
}
if (isset($itemData['meta']['mandatory'])) {
$stepQuestion->setMandatory($itemData['meta']['mandatory']);
}
}
// Remaining items are no longer in the Step
if (0 < count($stepQuestions)) {
foreach ($stepQuestions as $stepQuestionToRemove) {
$step->removeStepQuestion($stepQuestionToRemove);
}
}
} | [
"public",
"function",
"deserializeItems",
"(",
"Step",
"$",
"step",
",",
"array",
"$",
"items",
"=",
"[",
"]",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"stepQuestions",
"=",
"$",
"step",
"->",
"getStepQuestions",
"(",
")",
"->",
"t... | Deserializes Step items.
Forwards the item deserialization to ItemSerializer.
@param Step $step
@param array $items
@param array $options | [
"Deserializes",
"Step",
"items",
".",
"Forwards",
"the",
"item",
"deserialization",
"to",
"ItemSerializer",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/StepSerializer.php#L183-L223 | train |
claroline/Distribution | plugin/claco-form/Serializer/EntryUserSerializer.php | EntryUserSerializer.serialize | public function serialize(EntryUser $entryUser, array $options = [])
{
$serialized = [
'id' => $entryUser->getUuid(),
'autoId' => $entryUser->getId(),
'entry' => [
'id' => $entryUser->getEntry()->getUuid(),
],
'user' => [
'id' => $entryUser->getUser()->getUuid(),
],
'shared' => $entryUser->isShared(),
'notifyEdition' => $entryUser->getNotifyEdition(),
'notifyComment' => $entryUser->getNotifyComment(),
'notifyVote' => $entryUser->getNotifyVote(),
];
return $serialized;
} | php | public function serialize(EntryUser $entryUser, array $options = [])
{
$serialized = [
'id' => $entryUser->getUuid(),
'autoId' => $entryUser->getId(),
'entry' => [
'id' => $entryUser->getEntry()->getUuid(),
],
'user' => [
'id' => $entryUser->getUser()->getUuid(),
],
'shared' => $entryUser->isShared(),
'notifyEdition' => $entryUser->getNotifyEdition(),
'notifyComment' => $entryUser->getNotifyComment(),
'notifyVote' => $entryUser->getNotifyVote(),
];
return $serialized;
} | [
"public",
"function",
"serialize",
"(",
"EntryUser",
"$",
"entryUser",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"serialized",
"=",
"[",
"'id'",
"=>",
"$",
"entryUser",
"->",
"getUuid",
"(",
")",
",",
"'autoId'",
"=>",
"$",
"entryUser... | Serializes an EntryUser entity for the JSON api.
@param EntryUser $entryUser - the entry user to serialize
@param array $options - a list of serialization options
@return array - the serialized representation of the entry user | [
"Serializes",
"an",
"EntryUser",
"entity",
"for",
"the",
"JSON",
"api",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/claco-form/Serializer/EntryUserSerializer.php#L25-L43 | train |
claroline/Distribution | plugin/agenda/Controller/API/EventController.php | EventController.listAction | public function listAction(Request $request, $class)
{
$query = $request->query->all();
$hiddenFilters = isset($query['hiddenFilters']) ? $query['hiddenFilters'] : [];
$query['hiddenFilters'] = array_merge($hiddenFilters, $this->getDefaultHiddenFilters());
//get start & end date and add them to the hidden filters list
$query['hiddenFilters']['createdAfter'] = $query['start'];
//we want to be able to fetch events that start a months before and ends a month after
$date = new \DateTime($query['end']);
$interval = new \DateInterval('P2M');
$date->add($interval);
$end = $date->format('Y-m-d');
$query['hiddenFilters']['endBefore'] = $end;
$data = $this->finder->search(
$class,
$query,
$this->options['list']
);
return new JsonResponse($data['data']);
} | php | public function listAction(Request $request, $class)
{
$query = $request->query->all();
$hiddenFilters = isset($query['hiddenFilters']) ? $query['hiddenFilters'] : [];
$query['hiddenFilters'] = array_merge($hiddenFilters, $this->getDefaultHiddenFilters());
//get start & end date and add them to the hidden filters list
$query['hiddenFilters']['createdAfter'] = $query['start'];
//we want to be able to fetch events that start a months before and ends a month after
$date = new \DateTime($query['end']);
$interval = new \DateInterval('P2M');
$date->add($interval);
$end = $date->format('Y-m-d');
$query['hiddenFilters']['endBefore'] = $end;
$data = $this->finder->search(
$class,
$query,
$this->options['list']
);
return new JsonResponse($data['data']);
} | [
"public",
"function",
"listAction",
"(",
"Request",
"$",
"request",
",",
"$",
"class",
")",
"{",
"$",
"query",
"=",
"$",
"request",
"->",
"query",
"->",
"all",
"(",
")",
";",
"$",
"hiddenFilters",
"=",
"isset",
"(",
"$",
"query",
"[",
"'hiddenFilters'"... | tweaked for fullcalendar.
@param Request $request
@param string $class
@return JsonResponse | [
"tweaked",
"for",
"fullcalendar",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/agenda/Controller/API/EventController.php#L48-L72 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.getWorkspaceTeamParameters | public function getWorkspaceTeamParameters(Workspace $workspace)
{
$teamParams = $this->workspaceTeamParamsRepo->findOneBy(['workspace' => $workspace]);
if (empty($teamParams)) {
$teamParams = new WorkspaceTeamParameters();
$teamParams->setWorkspace($workspace);
}
return $teamParams;
} | php | public function getWorkspaceTeamParameters(Workspace $workspace)
{
$teamParams = $this->workspaceTeamParamsRepo->findOneBy(['workspace' => $workspace]);
if (empty($teamParams)) {
$teamParams = new WorkspaceTeamParameters();
$teamParams->setWorkspace($workspace);
}
return $teamParams;
} | [
"public",
"function",
"getWorkspaceTeamParameters",
"(",
"Workspace",
"$",
"workspace",
")",
"{",
"$",
"teamParams",
"=",
"$",
"this",
"->",
"workspaceTeamParamsRepo",
"->",
"findOneBy",
"(",
"[",
"'workspace'",
"=>",
"$",
"workspace",
"]",
")",
";",
"if",
"("... | Gets team parameters for a workspace.
@param Workspace $workspace
@return WorkspaceTeamParameters | [
"Gets",
"team",
"parameters",
"for",
"a",
"workspace",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L77-L87 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.deleteTeams | public function deleteTeams(array $teams)
{
$this->om->startFlushSuite();
foreach ($teams as $team) {
$this->deleteTeam($team);
}
$this->om->endFlushSuite();
} | php | public function deleteTeams(array $teams)
{
$this->om->startFlushSuite();
foreach ($teams as $team) {
$this->deleteTeam($team);
}
$this->om->endFlushSuite();
} | [
"public",
"function",
"deleteTeams",
"(",
"array",
"$",
"teams",
")",
"{",
"$",
"this",
"->",
"om",
"->",
"startFlushSuite",
"(",
")",
";",
"foreach",
"(",
"$",
"teams",
"as",
"$",
"team",
")",
"{",
"$",
"this",
"->",
"deleteTeam",
"(",
"$",
"team",
... | Deletes multiple teams.
@param array $teams | [
"Deletes",
"multiple",
"teams",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L170-L179 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.deleteTeam | public function deleteTeam(Team $team)
{
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
if (!is_null($teamManagerRole)) {
$this->om->remove($teamManagerRole);
}
if (!is_null($teamRole)) {
$this->om->remove($teamRole);
}
$teamDirectory = $team->getDirectory();
if ($team->isDirDeletable() && !is_null($teamDirectory)) {
$this->resourceManager->delete($teamDirectory->getResourceNode());
}
$this->om->remove($team);
$this->om->flush();
} | php | public function deleteTeam(Team $team)
{
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
if (!is_null($teamManagerRole)) {
$this->om->remove($teamManagerRole);
}
if (!is_null($teamRole)) {
$this->om->remove($teamRole);
}
$teamDirectory = $team->getDirectory();
if ($team->isDirDeletable() && !is_null($teamDirectory)) {
$this->resourceManager->delete($teamDirectory->getResourceNode());
}
$this->om->remove($team);
$this->om->flush();
} | [
"public",
"function",
"deleteTeam",
"(",
"Team",
"$",
"team",
")",
"{",
"$",
"teamRole",
"=",
"$",
"team",
"->",
"getRole",
"(",
")",
";",
"$",
"teamManagerRole",
"=",
"$",
"team",
"->",
"getTeamManagerRole",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
... | Deletes a team.
@param Team $team | [
"Deletes",
"a",
"team",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L186-L204 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.computeValidTeamName | public function computeValidTeamName(Workspace $workspace, $teamName, $index = 0)
{
$name = 0 === $index ? $teamName : $teamName.' '.$index;
$teams = $this->teamRepo->findBy(['workspace' => $workspace, 'name' => $name]);
while (count($teams) > 0) {
++$index;
$name = $teamName.' '.$index;
$teams = $this->teamRepo->findBy(['workspace' => $workspace, 'name' => $name]);
}
return ['name' => $name, 'index' => $index];
} | php | public function computeValidTeamName(Workspace $workspace, $teamName, $index = 0)
{
$name = 0 === $index ? $teamName : $teamName.' '.$index;
$teams = $this->teamRepo->findBy(['workspace' => $workspace, 'name' => $name]);
while (count($teams) > 0) {
++$index;
$name = $teamName.' '.$index;
$teams = $this->teamRepo->findBy(['workspace' => $workspace, 'name' => $name]);
}
return ['name' => $name, 'index' => $index];
} | [
"public",
"function",
"computeValidTeamName",
"(",
"Workspace",
"$",
"workspace",
",",
"$",
"teamName",
",",
"$",
"index",
"=",
"0",
")",
"{",
"$",
"name",
"=",
"0",
"===",
"$",
"index",
"?",
"$",
"teamName",
":",
"$",
"teamName",
".",
"' '",
".",
"$... | Checks if name already exists and returns a incremented version if it does.
@param Workspace $workspace
@param string $teamName
@param int $index
@return array | [
"Checks",
"if",
"name",
"already",
"exists",
"and",
"returns",
"a",
"incremented",
"version",
"if",
"it",
"does",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L215-L228 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.createTeamRole | public function createTeamRole(Team $team, $isManager = false)
{
$workspace = $team->getWorkspace();
$teamName = $team->getName();
$roleName = $this->computeValidRoleName(
strtoupper(str_replace(' ', '_', $isManager ? $teamName.'_MANAGER' : $teamName)),
$workspace->getUuid()
);
$roleKey = $this->computeValidRoleTranslationKey($workspace, $isManager ? $teamName.' manager' : $teamName);
$role = $this->roleManager->createWorkspaceRole($roleName, $roleKey, $workspace);
$root = $this->resourceManager->getWorkspaceRoot($workspace);
$this->rightsManager->editPerms(['open' => true], $role, $root);
$orderedTool = $this->om
->getRepository('ClarolineCoreBundle:Tool\OrderedTool')
->findOneBy(['workspace' => $workspace, 'name' => 'resource_manager']);
if (!empty($orderedTool)) {
$this->toolRightsManager->setToolRights($orderedTool, $role, 1);
}
$this->setRightsForOldTeams($workspace, $role);
return $role;
} | php | public function createTeamRole(Team $team, $isManager = false)
{
$workspace = $team->getWorkspace();
$teamName = $team->getName();
$roleName = $this->computeValidRoleName(
strtoupper(str_replace(' ', '_', $isManager ? $teamName.'_MANAGER' : $teamName)),
$workspace->getUuid()
);
$roleKey = $this->computeValidRoleTranslationKey($workspace, $isManager ? $teamName.' manager' : $teamName);
$role = $this->roleManager->createWorkspaceRole($roleName, $roleKey, $workspace);
$root = $this->resourceManager->getWorkspaceRoot($workspace);
$this->rightsManager->editPerms(['open' => true], $role, $root);
$orderedTool = $this->om
->getRepository('ClarolineCoreBundle:Tool\OrderedTool')
->findOneBy(['workspace' => $workspace, 'name' => 'resource_manager']);
if (!empty($orderedTool)) {
$this->toolRightsManager->setToolRights($orderedTool, $role, 1);
}
$this->setRightsForOldTeams($workspace, $role);
return $role;
} | [
"public",
"function",
"createTeamRole",
"(",
"Team",
"$",
"team",
",",
"$",
"isManager",
"=",
"false",
")",
"{",
"$",
"workspace",
"=",
"$",
"team",
"->",
"getWorkspace",
"(",
")",
";",
"$",
"teamName",
"=",
"$",
"team",
"->",
"getName",
"(",
")",
";... | Creates role for team members.
@param Team $team
@param bool $isManager
@return Role | [
"Creates",
"role",
"for",
"team",
"members",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L238-L261 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.createTeamDirectory | public function createTeamDirectory(Team $team, User $user, ResourceNode $resource = null, array $creatableResources = [])
{
$workspace = $team->getWorkspace();
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
$rootDirectory = $this->resourceManager->getWorkspaceRoot($workspace);
$directoryType = $this->resourceManager->getResourceTypeByName('directory');
$resourceTypes = $this->resourceManager->getAllResourceTypes();
$directory = $this->resourceManager->createResource(
'Claroline\CoreBundle\Entity\Resource\Directory',
$team->getName()
);
$teamRoleName = $teamRole->getName();
$teamManagerRoleName = $teamManagerRole->getName();
$rights = [];
$rights[$teamRoleName] = [];
$rights[$teamRoleName]['role'] = $teamRole;
$rights[$teamRoleName]['create'] = [];
$rights[$teamManagerRoleName] = [];
$rights[$teamManagerRoleName]['role'] = $teamManagerRole;
$rights[$teamManagerRoleName]['create'] = [];
foreach ($resourceTypes as $resourceType) {
$rights[$teamManagerRoleName]['create'][] = ['name' => $resourceType->getName()];
}
foreach ($creatableResources as $creatableResource) {
$rights[$teamRoleName]['create'][] = ['name' => $creatableResource];
}
$decoders = $directoryType->getMaskDecoders();
foreach ($decoders as $decoder) {
$decoderName = $decoder->getName();
if ('create' !== $decoderName) {
$rights[$teamManagerRoleName][$decoderName] = true;
}
if ('administrate' !== $decoderName && 'delete' !== $decoderName && 'create' !== $decoderName) {
$rights[$teamRoleName][$decoderName] = true;
}
}
$teamDirectory = $this->resourceManager->create(
$directory,
$directoryType,
$user,
$workspace,
$rootDirectory,
null,
$rights
);
// TODO : manage rights
if (!is_null($resource)) {
$this->resourceManager->copy(
$resource,
$teamDirectory->getResourceNode(),
$user,
true,
false
);
}
return $teamDirectory;
} | php | public function createTeamDirectory(Team $team, User $user, ResourceNode $resource = null, array $creatableResources = [])
{
$workspace = $team->getWorkspace();
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
$rootDirectory = $this->resourceManager->getWorkspaceRoot($workspace);
$directoryType = $this->resourceManager->getResourceTypeByName('directory');
$resourceTypes = $this->resourceManager->getAllResourceTypes();
$directory = $this->resourceManager->createResource(
'Claroline\CoreBundle\Entity\Resource\Directory',
$team->getName()
);
$teamRoleName = $teamRole->getName();
$teamManagerRoleName = $teamManagerRole->getName();
$rights = [];
$rights[$teamRoleName] = [];
$rights[$teamRoleName]['role'] = $teamRole;
$rights[$teamRoleName]['create'] = [];
$rights[$teamManagerRoleName] = [];
$rights[$teamManagerRoleName]['role'] = $teamManagerRole;
$rights[$teamManagerRoleName]['create'] = [];
foreach ($resourceTypes as $resourceType) {
$rights[$teamManagerRoleName]['create'][] = ['name' => $resourceType->getName()];
}
foreach ($creatableResources as $creatableResource) {
$rights[$teamRoleName]['create'][] = ['name' => $creatableResource];
}
$decoders = $directoryType->getMaskDecoders();
foreach ($decoders as $decoder) {
$decoderName = $decoder->getName();
if ('create' !== $decoderName) {
$rights[$teamManagerRoleName][$decoderName] = true;
}
if ('administrate' !== $decoderName && 'delete' !== $decoderName && 'create' !== $decoderName) {
$rights[$teamRoleName][$decoderName] = true;
}
}
$teamDirectory = $this->resourceManager->create(
$directory,
$directoryType,
$user,
$workspace,
$rootDirectory,
null,
$rights
);
// TODO : manage rights
if (!is_null($resource)) {
$this->resourceManager->copy(
$resource,
$teamDirectory->getResourceNode(),
$user,
true,
false
);
}
return $teamDirectory;
} | [
"public",
"function",
"createTeamDirectory",
"(",
"Team",
"$",
"team",
",",
"User",
"$",
"user",
",",
"ResourceNode",
"$",
"resource",
"=",
"null",
",",
"array",
"$",
"creatableResources",
"=",
"[",
"]",
")",
"{",
"$",
"workspace",
"=",
"$",
"team",
"->"... | Creates team directory.
@param Team $team
@param User $user
@param ResourceNode $resource
@param array $creatableResources
@return Directory | [
"Creates",
"team",
"directory",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L273-L338 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.getTeamsByUserAndWorkspace | public function getTeamsByUserAndWorkspace(User $user, Workspace $workspace)
{
return $this->teamRepo->findTeamsByUserAndWorkspace($user, $workspace);
} | php | public function getTeamsByUserAndWorkspace(User $user, Workspace $workspace)
{
return $this->teamRepo->findTeamsByUserAndWorkspace($user, $workspace);
} | [
"public",
"function",
"getTeamsByUserAndWorkspace",
"(",
"User",
"$",
"user",
",",
"Workspace",
"$",
"workspace",
")",
"{",
"return",
"$",
"this",
"->",
"teamRepo",
"->",
"findTeamsByUserAndWorkspace",
"(",
"$",
"user",
",",
"$",
"workspace",
")",
";",
"}"
] | Gets user teams in a workspace.
@param User $user
@param Workspace $workspace
@return array | [
"Gets",
"user",
"teams",
"in",
"a",
"workspace",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L348-L351 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.initializeTeamRights | public function initializeTeamRights(Team $team)
{
$workspace = $team->getWorkspace();
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
$resourceNode = !is_null($team->getDirectory()) ? $team->getDirectory()->getResourceNode() : null;
if (!is_null($resourceNode)) {
$workspaceRoles = $this->roleManager->getRolesByWorkspace($workspace);
$rights = [];
foreach ($workspaceRoles as $role) {
if (!in_array($role->getUuid(), [$teamRole->getUuid(), $teamManagerRole->getUuid()])) {
$rights[$role->getName()] = [
'role' => $role,
'create' => [],
'open' => $team->isPublic(),
];
}
}
$this->applyRightsToResourceNode($resourceNode, $rights);
}
} | php | public function initializeTeamRights(Team $team)
{
$workspace = $team->getWorkspace();
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
$resourceNode = !is_null($team->getDirectory()) ? $team->getDirectory()->getResourceNode() : null;
if (!is_null($resourceNode)) {
$workspaceRoles = $this->roleManager->getRolesByWorkspace($workspace);
$rights = [];
foreach ($workspaceRoles as $role) {
if (!in_array($role->getUuid(), [$teamRole->getUuid(), $teamManagerRole->getUuid()])) {
$rights[$role->getName()] = [
'role' => $role,
'create' => [],
'open' => $team->isPublic(),
];
}
}
$this->applyRightsToResourceNode($resourceNode, $rights);
}
} | [
"public",
"function",
"initializeTeamRights",
"(",
"Team",
"$",
"team",
")",
"{",
"$",
"workspace",
"=",
"$",
"team",
"->",
"getWorkspace",
"(",
")",
";",
"$",
"teamRole",
"=",
"$",
"team",
"->",
"getRole",
"(",
")",
";",
"$",
"teamManagerRole",
"=",
"... | Sets rights to team directory for all workspace roles.
@param Team $team | [
"Sets",
"rights",
"to",
"team",
"directory",
"for",
"all",
"workspace",
"roles",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L358-L380 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.updateTeamDirectoryPerms | public function updateTeamDirectoryPerms(Team $team)
{
$directory = $team->getDirectory();
if (!is_null($directory)) {
$this->om->startFlushSuite();
$workspace = $team->getWorkspace();
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
$workspaceRoles = $this->roleManager->getRolesByWorkspace($workspace);
foreach ($workspaceRoles as $role) {
if (!in_array($role->getUuid(), [$teamRole->getUuid(), $teamManagerRole->getUuid()])) {
$rights = ['open' => $team->isPublic()];
$this->rightsManager->editPerms($rights, $role, $directory->getResourceNode(), true);
}
}
$this->om->endFlushSuite();
}
} | php | public function updateTeamDirectoryPerms(Team $team)
{
$directory = $team->getDirectory();
if (!is_null($directory)) {
$this->om->startFlushSuite();
$workspace = $team->getWorkspace();
$teamRole = $team->getRole();
$teamManagerRole = $team->getTeamManagerRole();
$workspaceRoles = $this->roleManager->getRolesByWorkspace($workspace);
foreach ($workspaceRoles as $role) {
if (!in_array($role->getUuid(), [$teamRole->getUuid(), $teamManagerRole->getUuid()])) {
$rights = ['open' => $team->isPublic()];
$this->rightsManager->editPerms($rights, $role, $directory->getResourceNode(), true);
}
}
$this->om->endFlushSuite();
}
} | [
"public",
"function",
"updateTeamDirectoryPerms",
"(",
"Team",
"$",
"team",
")",
"{",
"$",
"directory",
"=",
"$",
"team",
"->",
"getDirectory",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"directory",
")",
")",
"{",
"$",
"this",
"->",
"om",
"... | Updates permissions of team directory..
@param Team $team | [
"Updates",
"permissions",
"of",
"team",
"directory",
".."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L387-L407 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.initializeTeamPerms | public function initializeTeamPerms(Team $team, array $roles)
{
$directory = $team->getDirectory();
if (!is_null($directory)) {
$this->om->startFlushSuite();
$node = $directory->getResourceNode();
foreach ($roles as $role) {
if ($role === $team->getRole()) {
$perms = ['open' => true, 'edit' => true, 'export' => true, 'copy' => true];
$creatable = $this->om->getRepository('ClarolineCoreBundle:Resource\ResourceType')->findAll();
} elseif ($role === $team->getTeamManagerRole()) {
$perms = ['open' => true, 'edit' => true, 'export' => true, 'copy' => true, 'delete' => true, 'administrate' => true];
$creatable = $this->om->getRepository('ClarolineCoreBundle:Resource\ResourceType')->findAll();
} elseif ($team->isPublic()) {
$perms = ['open' => true];
$creatable = [];
}
$this->rightsManager->editPerms($perms, $role, $node, true, $creatable, true);
}
$this->om->endFlushSuite();
}
} | php | public function initializeTeamPerms(Team $team, array $roles)
{
$directory = $team->getDirectory();
if (!is_null($directory)) {
$this->om->startFlushSuite();
$node = $directory->getResourceNode();
foreach ($roles as $role) {
if ($role === $team->getRole()) {
$perms = ['open' => true, 'edit' => true, 'export' => true, 'copy' => true];
$creatable = $this->om->getRepository('ClarolineCoreBundle:Resource\ResourceType')->findAll();
} elseif ($role === $team->getTeamManagerRole()) {
$perms = ['open' => true, 'edit' => true, 'export' => true, 'copy' => true, 'delete' => true, 'administrate' => true];
$creatable = $this->om->getRepository('ClarolineCoreBundle:Resource\ResourceType')->findAll();
} elseif ($team->isPublic()) {
$perms = ['open' => true];
$creatable = [];
}
$this->rightsManager->editPerms($perms, $role, $node, true, $creatable, true);
}
$this->om->endFlushSuite();
}
} | [
"public",
"function",
"initializeTeamPerms",
"(",
"Team",
"$",
"team",
",",
"array",
"$",
"roles",
")",
"{",
"$",
"directory",
"=",
"$",
"team",
"->",
"getDirectory",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"directory",
")",
")",
"{",
"$"... | Initializes directory permissions. Used in command.
@param Team $team
@param array $roles | [
"Initializes",
"directory",
"permissions",
".",
"Used",
"in",
"command",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L415-L440 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.registerManagersToTeam | public function registerManagersToTeam(Team $team, array $users)
{
$teamManagerRole = $team->getTeamManagerRole();
if (!is_null($teamManagerRole) && 0 < count($users)) {
$this->om->startFlushSuite();
$team->setTeamManager($users[0]);
foreach ($users as $user) {
$this->roleManager->associateRole($user, $teamManagerRole);
}
$this->om->persist($team);
$this->om->endFlushSuite();
}
} | php | public function registerManagersToTeam(Team $team, array $users)
{
$teamManagerRole = $team->getTeamManagerRole();
if (!is_null($teamManagerRole) && 0 < count($users)) {
$this->om->startFlushSuite();
$team->setTeamManager($users[0]);
foreach ($users as $user) {
$this->roleManager->associateRole($user, $teamManagerRole);
}
$this->om->persist($team);
$this->om->endFlushSuite();
}
} | [
"public",
"function",
"registerManagersToTeam",
"(",
"Team",
"$",
"team",
",",
"array",
"$",
"users",
")",
"{",
"$",
"teamManagerRole",
"=",
"$",
"team",
"->",
"getTeamManagerRole",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"teamManagerRole",
")"... | Registers users as team managers.
@param Team $team
@param array $users | [
"Registers",
"users",
"as",
"team",
"managers",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L492-L507 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.unregisterManagersFromTeam | public function unregisterManagersFromTeam(Team $team, array $users)
{
$teamManagerRole = $team->getTeamManagerRole();
if (!is_null($teamManagerRole)) {
$this->om->startFlushSuite();
$teamManager = $team->getTeamManager();
foreach ($users as $user) {
$this->roleManager->dissociateRole($user, $teamManagerRole);
if ($teamManager && $teamManager->getid() === $user->getId()) {
$team->setTeamManager(null);
}
}
$this->om->persist($team);
$this->om->endFlushSuite();
}
} | php | public function unregisterManagersFromTeam(Team $team, array $users)
{
$teamManagerRole = $team->getTeamManagerRole();
if (!is_null($teamManagerRole)) {
$this->om->startFlushSuite();
$teamManager = $team->getTeamManager();
foreach ($users as $user) {
$this->roleManager->dissociateRole($user, $teamManagerRole);
if ($teamManager && $teamManager->getid() === $user->getId()) {
$team->setTeamManager(null);
}
}
$this->om->persist($team);
$this->om->endFlushSuite();
}
} | [
"public",
"function",
"unregisterManagersFromTeam",
"(",
"Team",
"$",
"team",
",",
"array",
"$",
"users",
")",
"{",
"$",
"teamManagerRole",
"=",
"$",
"team",
"->",
"getTeamManagerRole",
"(",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"teamManagerRole",
... | Unregisters team managers.
@param Team $team
@param array $users | [
"Unregisters",
"team",
"managers",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L515-L534 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.emptyTeams | public function emptyTeams(array $teams)
{
$this->om->startFlushSuite();
foreach ($teams as $team) {
$users = $team->getRole()->getUsers()->toArray();
$this->unregisterUsersFromTeam($team, $users);
}
$this->om->endFlushSuite();
} | php | public function emptyTeams(array $teams)
{
$this->om->startFlushSuite();
foreach ($teams as $team) {
$users = $team->getRole()->getUsers()->toArray();
$this->unregisterUsersFromTeam($team, $users);
}
$this->om->endFlushSuite();
} | [
"public",
"function",
"emptyTeams",
"(",
"array",
"$",
"teams",
")",
"{",
"$",
"this",
"->",
"om",
"->",
"startFlushSuite",
"(",
")",
";",
"foreach",
"(",
"$",
"teams",
"as",
"$",
"team",
")",
"{",
"$",
"users",
"=",
"$",
"team",
"->",
"getRole",
"... | Empty teams from all members.
@param array $teams | [
"Empty",
"teams",
"from",
"all",
"members",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L541-L550 | train |
claroline/Distribution | plugin/team/Manager/TeamManager.php | TeamManager.computeValidRoleTranslationKey | private function computeValidRoleTranslationKey(Workspace $workspace, $key)
{
$i = 1;
$translationKey = $key;
$role = $this->roleManager->getRoleByTranslationKeyAndWorkspace($translationKey, $workspace);
while (!is_null($role)) {
$translationKey = $key.' ('.$i.')';
$role = $this->roleManager->getRoleByTranslationKeyAndWorkspace($translationKey, $workspace);
++$i;
}
return $translationKey;
} | php | private function computeValidRoleTranslationKey(Workspace $workspace, $key)
{
$i = 1;
$translationKey = $key;
$role = $this->roleManager->getRoleByTranslationKeyAndWorkspace($translationKey, $workspace);
while (!is_null($role)) {
$translationKey = $key.' ('.$i.')';
$role = $this->roleManager->getRoleByTranslationKeyAndWorkspace($translationKey, $workspace);
++$i;
}
return $translationKey;
} | [
"private",
"function",
"computeValidRoleTranslationKey",
"(",
"Workspace",
"$",
"workspace",
",",
"$",
"key",
")",
"{",
"$",
"i",
"=",
"1",
";",
"$",
"translationKey",
"=",
"$",
"key",
";",
"$",
"role",
"=",
"$",
"this",
"->",
"roleManager",
"->",
"getRo... | Checks and updates role translation key for unicity.
@param Workspace $workspace
@param string $key
@return string | [
"Checks",
"and",
"updates",
"role",
"translation",
"key",
"for",
"unicity",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/team/Manager/TeamManager.php#L621-L634 | train |
claroline/Distribution | main/app/API/Finder/AbstractFinder.php | AbstractFinder.setObjectManager | public function setObjectManager(
ObjectManager $om,
EntityManager $em,
StrictDispatcher $eventDispatcher
) {
$this->om = $om;
$this->_em = $em;
$this->eventDispatcher = $eventDispatcher;
} | php | public function setObjectManager(
ObjectManager $om,
EntityManager $em,
StrictDispatcher $eventDispatcher
) {
$this->om = $om;
$this->_em = $em;
$this->eventDispatcher = $eventDispatcher;
} | [
"public",
"function",
"setObjectManager",
"(",
"ObjectManager",
"$",
"om",
",",
"EntityManager",
"$",
"em",
",",
"StrictDispatcher",
"$",
"eventDispatcher",
")",
"{",
"$",
"this",
"->",
"om",
"=",
"$",
"om",
";",
"$",
"this",
"->",
"_em",
"=",
"$",
"em",... | AbstractFinder constructor.
@DI\InjectParams({
"om" = @DI\Inject("claroline.persistence.object_manager"),
"em" = @DI\Inject("doctrine.orm.entity_manager"),
"eventDispatcher" = @DI\Inject("claroline.event.event_dispatcher")
})
@param ObjectManager $om
@param EntityManager $em
@param StrictDispatcher $eventDispatcher | [
"AbstractFinder",
"constructor",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/API/Finder/AbstractFinder.php#L49-L57 | train |
claroline/Distribution | main/app/API/Finder/AbstractFinder.php | AbstractFinder.delete | public function delete(array $filters = [])
{
/** @var QueryBuilder $qb */
$qb = $this->om->createQueryBuilder();
$qb->delete($this->getClass(), 'obj');
// filter query - let's the finder implementation process the filters to configure query
$query = $this->configureQueryBuilder($qb, $filters);
if ($query instanceof QueryBuilder) {
$qb = $query;
}
if (!($query instanceof NativeQuery)) {
// order query if implementation has not done it
$query = $qb->getQuery();
}
$query->getResult();
} | php | public function delete(array $filters = [])
{
/** @var QueryBuilder $qb */
$qb = $this->om->createQueryBuilder();
$qb->delete($this->getClass(), 'obj');
// filter query - let's the finder implementation process the filters to configure query
$query = $this->configureQueryBuilder($qb, $filters);
if ($query instanceof QueryBuilder) {
$qb = $query;
}
if (!($query instanceof NativeQuery)) {
// order query if implementation has not done it
$query = $qb->getQuery();
}
$query->getResult();
} | [
"public",
"function",
"delete",
"(",
"array",
"$",
"filters",
"=",
"[",
"]",
")",
"{",
"/** @var QueryBuilder $qb */",
"$",
"qb",
"=",
"$",
"this",
"->",
"om",
"->",
"createQueryBuilder",
"(",
")",
";",
"$",
"qb",
"->",
"delete",
"(",
"$",
"this",
"->"... | Might not be fully functional with the unions. | [
"Might",
"not",
"be",
"fully",
"functional",
"with",
"the",
"unions",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/API/Finder/AbstractFinder.php#L72-L91 | train |
claroline/Distribution | main/app/Persistence/ObjectManager.php | ObjectManager.rollBack | public function rollBack()
{
$this->assertIsSupported($this->supportsTransactions, __METHOD__);
$this->wrapped->getConnection()->rollBack();
} | php | public function rollBack()
{
$this->assertIsSupported($this->supportsTransactions, __METHOD__);
$this->wrapped->getConnection()->rollBack();
} | [
"public",
"function",
"rollBack",
"(",
")",
"{",
"$",
"this",
"->",
"assertIsSupported",
"(",
"$",
"this",
"->",
"supportsTransactions",
",",
"__METHOD__",
")",
";",
"$",
"this",
"->",
"wrapped",
"->",
"getConnection",
"(",
")",
"->",
"rollBack",
"(",
")",... | Rollbacks a transaction.
@throws UnsupportedMethodException if the method is not supported by
the underlying object manager | [
"Rollbacks",
"a",
"transaction",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/Persistence/ObjectManager.php#L199-L203 | train |
claroline/Distribution | main/app/Persistence/ObjectManager.php | ObjectManager.findList | public function findList($class, $property, array $list, $orderStrict = false)
{
if (0 === count($list)) {
return [];
}
$dql = "SELECT object FROM {$class} object WHERE object.{$property} IN (:list)";
$query = $this->wrapped->createQuery($dql);
$query->setParameter('list', $list);
$objects = $query->getResult();
if (($entityCount = count($objects)) !== ($idCount = count($list))) {
$this->monolog->warning("{$entityCount} out of {$idCount} ids don't match any existing object");
}
if ($orderStrict) {
// Sort objects to have the same order as given $ids array
$sortIds = array_flip($list);
usort($objects, function ($a, $b) use ($sortIds) {
return $sortIds[$a->getId()] - $sortIds[$b->getId()];
});
}
return $objects;
} | php | public function findList($class, $property, array $list, $orderStrict = false)
{
if (0 === count($list)) {
return [];
}
$dql = "SELECT object FROM {$class} object WHERE object.{$property} IN (:list)";
$query = $this->wrapped->createQuery($dql);
$query->setParameter('list', $list);
$objects = $query->getResult();
if (($entityCount = count($objects)) !== ($idCount = count($list))) {
$this->monolog->warning("{$entityCount} out of {$idCount} ids don't match any existing object");
}
if ($orderStrict) {
// Sort objects to have the same order as given $ids array
$sortIds = array_flip($list);
usort($objects, function ($a, $b) use ($sortIds) {
return $sortIds[$a->getId()] - $sortIds[$b->getId()];
});
}
return $objects;
} | [
"public",
"function",
"findList",
"(",
"$",
"class",
",",
"$",
"property",
",",
"array",
"$",
"list",
",",
"$",
"orderStrict",
"=",
"false",
")",
"{",
"if",
"(",
"0",
"===",
"count",
"(",
"$",
"list",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
... | Finds a set of objects.
@param $class
@param $property
@param array $list
@param bool $orderStrict keep the same order as ids array
@return array [object]
@throws MissingObjectException if any of the requested objects cannot be found
@internal param string $objectClass
@todo make this method compatible with odm implementations | [
"Finds",
"a",
"set",
"of",
"objects",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/Persistence/ObjectManager.php#L269-L293 | train |
claroline/Distribution | main/app/Persistence/ObjectManager.php | ObjectManager.count | public function count($class)
{
$dql = "SELECT COUNT(object) FROM {$class} object";
$query = $this->wrapped->createQuery($dql);
return (int) $query->getSingleScalarResult();
} | php | public function count($class)
{
$dql = "SELECT COUNT(object) FROM {$class} object";
$query = $this->wrapped->createQuery($dql);
return (int) $query->getSingleScalarResult();
} | [
"public",
"function",
"count",
"(",
"$",
"class",
")",
"{",
"$",
"dql",
"=",
"\"SELECT COUNT(object) FROM {$class} object\"",
";",
"$",
"query",
"=",
"$",
"this",
"->",
"wrapped",
"->",
"createQuery",
"(",
"$",
"dql",
")",
";",
"return",
"(",
"int",
")",
... | Counts objects of a given class.
@param string $class
@return int
@todo make this method compatible with odm implementations | [
"Counts",
"objects",
"of",
"a",
"given",
"class",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/Persistence/ObjectManager.php#L304-L310 | train |
claroline/Distribution | main/core/Library/View/Serializer/Serializer.php | Serializer.getClass | private function getClass($array, &$objects)
{
foreach ($array as $el) {
if (is_object($el)) {
$objects = $array;
$class = get_class($el);
} else {
if (is_array($el)) {
$class = $this->getClass($el, $objects);
}
}
}
return $class;
} | php | private function getClass($array, &$objects)
{
foreach ($array as $el) {
if (is_object($el)) {
$objects = $array;
$class = get_class($el);
} else {
if (is_array($el)) {
$class = $this->getClass($el, $objects);
}
}
}
return $class;
} | [
"private",
"function",
"getClass",
"(",
"$",
"array",
",",
"&",
"$",
"objects",
")",
"{",
"foreach",
"(",
"$",
"array",
"as",
"$",
"el",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"el",
")",
")",
"{",
"$",
"objects",
"=",
"$",
"array",
";",
"$... | it is the only thing I'll support. | [
"it",
"is",
"the",
"only",
"thing",
"I",
"ll",
"support",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Library/View/Serializer/Serializer.php#L196-L211 | train |
claroline/Distribution | plugin/path/Entity/Path/Path.php | Path.getStructure | public function getStructure()
{
$isPublished = $this->isPublished();
if ($isPublished && !$this->modified) {
// Rebuild the structure of the Path from generated data
// This permits to merge modifications made on generated data into the Path
$structure = json_encode($this); // See `jsonSerialize` to know how it's populated
} else {
// There are unpublished data so get the structure generated by the editor
$structure = $this->structure;
}
return $structure;
} | php | public function getStructure()
{
$isPublished = $this->isPublished();
if ($isPublished && !$this->modified) {
// Rebuild the structure of the Path from generated data
// This permits to merge modifications made on generated data into the Path
$structure = json_encode($this); // See `jsonSerialize` to know how it's populated
} else {
// There are unpublished data so get the structure generated by the editor
$structure = $this->structure;
}
return $structure;
} | [
"public",
"function",
"getStructure",
"(",
")",
"{",
"$",
"isPublished",
"=",
"$",
"this",
"->",
"isPublished",
"(",
")",
";",
"if",
"(",
"$",
"isPublished",
"&&",
"!",
"$",
"this",
"->",
"modified",
")",
"{",
"// Rebuild the structure of the Path from generat... | Get a JSON version of the Path.
@return string | [
"Get",
"a",
"JSON",
"version",
"of",
"the",
"Path",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/path/Entity/Path/Path.php#L127-L140 | train |
claroline/Distribution | plugin/path/Entity/Path/Path.php | Path.addStep | public function addStep(Step $step)
{
if (!$this->steps->contains($step)) {
$this->steps->add($step);
}
return $this;
} | php | public function addStep(Step $step)
{
if (!$this->steps->contains($step)) {
$this->steps->add($step);
}
return $this;
} | [
"public",
"function",
"addStep",
"(",
"Step",
"$",
"step",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"steps",
"->",
"contains",
"(",
"$",
"step",
")",
")",
"{",
"$",
"this",
"->",
"steps",
"->",
"add",
"(",
"$",
"step",
")",
";",
"}",
"retur... | Add step.
@param Step $step
@return Path | [
"Add",
"step",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/path/Entity/Path/Path.php#L149-L156 | train |
claroline/Distribution | plugin/path/Entity/Path/Path.php | Path.getRootSteps | public function getRootSteps()
{
$roots = [];
if (!empty($this->steps)) {
foreach ($this->steps as $step) {
if (null === $step->getParent()) {
// Root step found
$roots[] = $step;
}
}
}
return $roots;
} | php | public function getRootSteps()
{
$roots = [];
if (!empty($this->steps)) {
foreach ($this->steps as $step) {
if (null === $step->getParent()) {
// Root step found
$roots[] = $step;
}
}
}
return $roots;
} | [
"public",
"function",
"getRootSteps",
"(",
")",
"{",
"$",
"roots",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"steps",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"steps",
"as",
"$",
"step",
")",
"{",
"if",
"(",
... | Get root step of the path.
@return Step[] | [
"Get",
"root",
"step",
"of",
"the",
"path",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/path/Entity/Path/Path.php#L273-L287 | train |
claroline/Distribution | plugin/path/Entity/Path/Path.php | Path.initializeStructure | public function initializeStructure()
{
$structure = [
'id' => $this->getId(),
'name' => $this->getName(),
'description' => $this->getDescription(),
'manualProgressionAllowed' => $this->manualProgressionAllowed,
'steps' => [],
];
$this->setStructure(json_encode($structure));
return $this;
} | php | public function initializeStructure()
{
$structure = [
'id' => $this->getId(),
'name' => $this->getName(),
'description' => $this->getDescription(),
'manualProgressionAllowed' => $this->manualProgressionAllowed,
'steps' => [],
];
$this->setStructure(json_encode($structure));
return $this;
} | [
"public",
"function",
"initializeStructure",
"(",
")",
"{",
"$",
"structure",
"=",
"[",
"'id'",
"=>",
"$",
"this",
"->",
"getId",
"(",
")",
",",
"'name'",
"=>",
"$",
"this",
"->",
"getName",
"(",
")",
",",
"'description'",
"=>",
"$",
"this",
"->",
"g... | Initialize JSON structure.
@return Path
@deprecated | [
"Initialize",
"JSON",
"structure",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/path/Entity/Path/Path.php#L296-L309 | train |
claroline/Distribution | main/core/Security/Voter/WorkspaceVoter.php | WorkspaceVoter.checkCreation | private function checkCreation(TokenInterface $token)
{
if ($this->hasAdminToolAccess($token, 'workspace_management') || $this->isWorkspaceCreator($token)) {
return VoterInterface::ACCESS_GRANTED;
}
return VoterInterface::ACCESS_DENIED;
} | php | private function checkCreation(TokenInterface $token)
{
if ($this->hasAdminToolAccess($token, 'workspace_management') || $this->isWorkspaceCreator($token)) {
return VoterInterface::ACCESS_GRANTED;
}
return VoterInterface::ACCESS_DENIED;
} | [
"private",
"function",
"checkCreation",
"(",
"TokenInterface",
"$",
"token",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"hasAdminToolAccess",
"(",
"$",
"token",
",",
"'workspace_management'",
")",
"||",
"$",
"this",
"->",
"isWorkspaceCreator",
"(",
"$",
"token",
... | workspace creator handling ? | [
"workspace",
"creator",
"handling",
"?"
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Security/Voter/WorkspaceVoter.php#L75-L82 | train |
claroline/Distribution | plugin/tag/Manager/TagManager.php | TagManager.getUowScheduledTag | private function getUowScheduledTag($name, User $user = null)
{
$scheduledForInsert = $this->om->getUnitOfWork()->getScheduledEntityInsertions();
foreach ($scheduledForInsert as $entity) {
/** @var Tag $entity */
if ($entity instanceof Tag
&& $name === $entity->getName()
&& $user === $entity->getUser()) {
return $entity;
}
}
return null;
} | php | private function getUowScheduledTag($name, User $user = null)
{
$scheduledForInsert = $this->om->getUnitOfWork()->getScheduledEntityInsertions();
foreach ($scheduledForInsert as $entity) {
/** @var Tag $entity */
if ($entity instanceof Tag
&& $name === $entity->getName()
&& $user === $entity->getUser()) {
return $entity;
}
}
return null;
} | [
"private",
"function",
"getUowScheduledTag",
"(",
"$",
"name",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"$",
"scheduledForInsert",
"=",
"$",
"this",
"->",
"om",
"->",
"getUnitOfWork",
"(",
")",
"->",
"getScheduledEntityInsertions",
"(",
")",
";",
"... | Avoids duplicate creation of a tag when inside a flushSuite.
The only way to do that is to search in the current UOW if a tag with the same name
is already scheduled for insertion.
@param string $name
@param User $user
@return Tag|null | [
"Avoids",
"duplicate",
"creation",
"of",
"a",
"tag",
"when",
"inside",
"a",
"flushSuite",
".",
"The",
"only",
"way",
"to",
"do",
"that",
"is",
"to",
"search",
"in",
"the",
"current",
"UOW",
"if",
"a",
"tag",
"with",
"the",
"same",
"name",
"is",
"alread... | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/tag/Manager/TagManager.php#L114-L127 | train |
claroline/Distribution | main/core/Library/Utilities/ThumbnailCreator.php | ThumbnailCreator.fromVideo | public function fromVideo($originalPath, $destinationPath, $newWidth, $newHeight)
{
if (!$this->isGdLoaded || !$this->isFfmpegLoaded) {
$message = '';
if (!$this->isGdLoaded) {
$message .= 'The GD extension is missing \n';
}
if (!$this->isFfmpegLoaded) {
$message .= 'The Ffmpeg extension is missing \n';
}
throw new UnloadedExtensionException($message);
}
$media = new \ffmpeg_movie($originalPath);
$frameCount = $media->getFrameCount();
$frame = $media->getFrame(round($frameCount / 2));
if ($frame) {
$image = $frame->toGDImage();
$this->resize($newWidth, $newHeight, $image, $destinationPath);
return $destinationPath;
}
$exception = new ExtensionNotSupportedException();
$exception->setExtension(pathinfo($originalPath, PATHINFO_EXTENSION));
throw $exception;
} | php | public function fromVideo($originalPath, $destinationPath, $newWidth, $newHeight)
{
if (!$this->isGdLoaded || !$this->isFfmpegLoaded) {
$message = '';
if (!$this->isGdLoaded) {
$message .= 'The GD extension is missing \n';
}
if (!$this->isFfmpegLoaded) {
$message .= 'The Ffmpeg extension is missing \n';
}
throw new UnloadedExtensionException($message);
}
$media = new \ffmpeg_movie($originalPath);
$frameCount = $media->getFrameCount();
$frame = $media->getFrame(round($frameCount / 2));
if ($frame) {
$image = $frame->toGDImage();
$this->resize($newWidth, $newHeight, $image, $destinationPath);
return $destinationPath;
}
$exception = new ExtensionNotSupportedException();
$exception->setExtension(pathinfo($originalPath, PATHINFO_EXTENSION));
throw $exception;
} | [
"public",
"function",
"fromVideo",
"(",
"$",
"originalPath",
",",
"$",
"destinationPath",
",",
"$",
"newWidth",
",",
"$",
"newHeight",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isGdLoaded",
"||",
"!",
"$",
"this",
"->",
"isFfmpegLoaded",
")",
"{",
... | Create an thumbnail from a video. Returns null if the creation failed.
@param string $originalPath the path of the orignal video
@param string $destinationPath the path were the thumbnail will be copied
@param int $newWidth the width of the thumbnail
@param int $newHeight the width of the thumbnail
@return string | [
"Create",
"an",
"thumbnail",
"from",
"a",
"video",
".",
"Returns",
"null",
"if",
"the",
"creation",
"failed",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Library/Utilities/ThumbnailCreator.php#L60-L88 | train |
claroline/Distribution | plugin/slideshow/Serializer/SlideshowSerializer.php | SlideshowSerializer.serialize | public function serialize(Slideshow $slideshow)
{
return [
'id' => $slideshow->getUuid(),
'autoPlay' => $slideshow->getAutoPlay(),
'interval' => $slideshow->getInterval(),
'display' => [
'description' => $slideshow->getDescription(),
'showOverview' => $slideshow->getShowOverview(),
'showControls' => $slideshow->getShowControls(),
],
'slides' => array_map(function (Slide $slide) {
$content = null;
// TODO : enhance to allow more than files
if (!empty($slide->getContent())) {
/** @var PublicFile $file */
$file = $this->om
->getRepository(PublicFile::class)
->findOneBy(['url' => $slide->getContent()]);
if ($file) {
$content = $this->fileSerializer->serialize($file);
}
}
return [
'id' => $slide->getUuid(),
'content' => $content,
'meta' => [
'title' => $slide->getTitle(),
'description' => $slide->getDescription(),
],
];
}, $slideshow->getSlides()->toArray()),
];
} | php | public function serialize(Slideshow $slideshow)
{
return [
'id' => $slideshow->getUuid(),
'autoPlay' => $slideshow->getAutoPlay(),
'interval' => $slideshow->getInterval(),
'display' => [
'description' => $slideshow->getDescription(),
'showOverview' => $slideshow->getShowOverview(),
'showControls' => $slideshow->getShowControls(),
],
'slides' => array_map(function (Slide $slide) {
$content = null;
// TODO : enhance to allow more than files
if (!empty($slide->getContent())) {
/** @var PublicFile $file */
$file = $this->om
->getRepository(PublicFile::class)
->findOneBy(['url' => $slide->getContent()]);
if ($file) {
$content = $this->fileSerializer->serialize($file);
}
}
return [
'id' => $slide->getUuid(),
'content' => $content,
'meta' => [
'title' => $slide->getTitle(),
'description' => $slide->getDescription(),
],
];
}, $slideshow->getSlides()->toArray()),
];
} | [
"public",
"function",
"serialize",
"(",
"Slideshow",
"$",
"slideshow",
")",
"{",
"return",
"[",
"'id'",
"=>",
"$",
"slideshow",
"->",
"getUuid",
"(",
")",
",",
"'autoPlay'",
"=>",
"$",
"slideshow",
"->",
"getAutoPlay",
"(",
")",
",",
"'interval'",
"=>",
... | Serializes a Slideshow entity for the JSON api.
@param Slideshow $slideshow
@return array | [
"Serializes",
"a",
"Slideshow",
"entity",
"for",
"the",
"JSON",
"api",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/slideshow/Serializer/SlideshowSerializer.php#L70-L105 | train |
claroline/Distribution | plugin/slideshow/Serializer/SlideshowSerializer.php | SlideshowSerializer.deserialize | public function deserialize($data, Slideshow $slideshow, array $options = [])
{
$this->sipe('autoPlay', 'setAutoPlay', $data, $slideshow);
$this->sipe('interval', 'setInterval', $data, $slideshow);
$this->sipe('display.description', 'setDescription', $data, $slideshow);
$this->sipe('display.showOverview', 'setShowOverview', $data, $slideshow);
$this->sipe('display.showControls', 'setShowControls', $data, $slideshow);
if (isset($data['slides'])) {
// we will remove updated slides from this list
// remaining ones will be deleted
$existingSlides = $slideshow->getSlides()->toArray();
foreach ($data['slides'] as $slideOrder => $slideData) {
$slide = new Slide();
/**
* check if slide already exists.
*
* @var int
* @var Slide $existing
*/
foreach ($existingSlides as $index => $existing) {
if (isset($existing) && $existing->getUuid() === $slideData['id']) {
// slide found
$slide = $existing;
unset($existingSlides[$index]);
break;
}
}
$slide->setOrder($slideOrder);
if (!in_array(Options::REFRESH_UUID, $options)) {
$this->sipe('id', 'setUuid', $data, $slideshow);
}
$this->sipe('meta.title', 'setTitle', $slideData, $slide);
$this->sipe('meta.description', 'setDescription', $slideData, $slide);
// TODO : enhance to allow more than files (eg. HTML)
$this->sipe('content.url', 'setContent', $slideData, $slide);
$slideshow->addSlide($slide);
}
// Delete slides which no longer exist
$slidesToDelete = array_values($existingSlides);
foreach ($slidesToDelete as $toDelete) {
$slideshow->removeSlide($toDelete);
}
}
return $slideshow;
} | php | public function deserialize($data, Slideshow $slideshow, array $options = [])
{
$this->sipe('autoPlay', 'setAutoPlay', $data, $slideshow);
$this->sipe('interval', 'setInterval', $data, $slideshow);
$this->sipe('display.description', 'setDescription', $data, $slideshow);
$this->sipe('display.showOverview', 'setShowOverview', $data, $slideshow);
$this->sipe('display.showControls', 'setShowControls', $data, $slideshow);
if (isset($data['slides'])) {
// we will remove updated slides from this list
// remaining ones will be deleted
$existingSlides = $slideshow->getSlides()->toArray();
foreach ($data['slides'] as $slideOrder => $slideData) {
$slide = new Slide();
/**
* check if slide already exists.
*
* @var int
* @var Slide $existing
*/
foreach ($existingSlides as $index => $existing) {
if (isset($existing) && $existing->getUuid() === $slideData['id']) {
// slide found
$slide = $existing;
unset($existingSlides[$index]);
break;
}
}
$slide->setOrder($slideOrder);
if (!in_array(Options::REFRESH_UUID, $options)) {
$this->sipe('id', 'setUuid', $data, $slideshow);
}
$this->sipe('meta.title', 'setTitle', $slideData, $slide);
$this->sipe('meta.description', 'setDescription', $slideData, $slide);
// TODO : enhance to allow more than files (eg. HTML)
$this->sipe('content.url', 'setContent', $slideData, $slide);
$slideshow->addSlide($slide);
}
// Delete slides which no longer exist
$slidesToDelete = array_values($existingSlides);
foreach ($slidesToDelete as $toDelete) {
$slideshow->removeSlide($toDelete);
}
}
return $slideshow;
} | [
"public",
"function",
"deserialize",
"(",
"$",
"data",
",",
"Slideshow",
"$",
"slideshow",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"sipe",
"(",
"'autoPlay'",
",",
"'setAutoPlay'",
",",
"$",
"data",
",",
"$",
"slideshow... | Deserializes Slideshow data into entities.
@param array $data
@param Slideshow $slideshow
@return Slideshow | [
"Deserializes",
"Slideshow",
"data",
"into",
"entities",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/slideshow/Serializer/SlideshowSerializer.php#L115-L169 | train |
claroline/Distribution | plugin/exo/Controller/Api/AttemptController.php | AttemptController.startAction | public function startAction(Exercise $exercise, User $user = null)
{
$this->assertHasPermission('OPEN', $exercise);
if (!$this->isAdmin($exercise) && !$this->attemptManager->canPass($exercise, $user)) {
return new JsonResponse([
'message' => $exercise->getAttemptsReachedMessage(),
'accessErrors' => $this->attemptManager->getErrors($exercise, $user),
'lastAttempt' => $this->paperManager->serialize(
$this->attemptManager->getLastPaper($exercise, $user)
),
], 403);
}
return new JsonResponse($this->paperManager->serialize(
$this->attemptManager->startOrContinue($exercise, $user)
));
} | php | public function startAction(Exercise $exercise, User $user = null)
{
$this->assertHasPermission('OPEN', $exercise);
if (!$this->isAdmin($exercise) && !$this->attemptManager->canPass($exercise, $user)) {
return new JsonResponse([
'message' => $exercise->getAttemptsReachedMessage(),
'accessErrors' => $this->attemptManager->getErrors($exercise, $user),
'lastAttempt' => $this->paperManager->serialize(
$this->attemptManager->getLastPaper($exercise, $user)
),
], 403);
}
return new JsonResponse($this->paperManager->serialize(
$this->attemptManager->startOrContinue($exercise, $user)
));
} | [
"public",
"function",
"startAction",
"(",
"Exercise",
"$",
"exercise",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"assertHasPermission",
"(",
"'OPEN'",
",",
"$",
"exercise",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"isAdmin... | Opens an exercise, creating a new paper or re-using an unfinished one.
Also check that max attempts are not reached if needed.
@EXT\Route("", name="exercise_attempt_start")
@EXT\Method("POST")
@EXT\ParamConverter("user", converter="current_user", options={"allowAnonymous"=true})
@param Exercise $exercise
@param User $user
@return JsonResponse | [
"Opens",
"an",
"exercise",
"creating",
"a",
"new",
"paper",
"or",
"re",
"-",
"using",
"an",
"unfinished",
"one",
".",
"Also",
"check",
"that",
"max",
"attempts",
"are",
"not",
"reached",
"if",
"needed",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/AttemptController.php#L98-L115 | train |
claroline/Distribution | plugin/exo/Controller/Api/AttemptController.php | AttemptController.submitAnswersAction | public function submitAnswersAction(Paper $paper, User $user = null, Request $request)
{
$this->assertHasPermission('OPEN', $paper->getExercise());
$this->assertHasPaperAccess($paper, $user);
$errors = [];
$data = $this->decodeRequestData($request);
if (empty($data) || !is_array($data)) {
$errors[] = [
'path' => '',
'message' => 'Invalid JSON data',
];
} else {
try {
$this->attemptManager->submit($paper, $data, $request->getClientIp());
} catch (InvalidDataException $e) {
$errors = $e->getErrors();
}
}
if (!empty($errors)) {
return new JsonResponse($errors, 422);
} else {
return new JsonResponse(null, 204);
}
} | php | public function submitAnswersAction(Paper $paper, User $user = null, Request $request)
{
$this->assertHasPermission('OPEN', $paper->getExercise());
$this->assertHasPaperAccess($paper, $user);
$errors = [];
$data = $this->decodeRequestData($request);
if (empty($data) || !is_array($data)) {
$errors[] = [
'path' => '',
'message' => 'Invalid JSON data',
];
} else {
try {
$this->attemptManager->submit($paper, $data, $request->getClientIp());
} catch (InvalidDataException $e) {
$errors = $e->getErrors();
}
}
if (!empty($errors)) {
return new JsonResponse($errors, 422);
} else {
return new JsonResponse(null, 204);
}
} | [
"public",
"function",
"submitAnswersAction",
"(",
"Paper",
"$",
"paper",
",",
"User",
"$",
"user",
"=",
"null",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"assertHasPermission",
"(",
"'OPEN'",
",",
"$",
"paper",
"->",
"getExercise",
"(",
... | Submits answers to an Exercise.
@EXT\Route("/{id}", name="exercise_attempt_submit")
@EXT\Method("PUT")
@EXT\ParamConverter("paper", class="UJMExoBundle:Attempt\Paper", options={"mapping": {"id": "uuid"}})
@EXT\ParamConverter("user", converter="current_user", options={"allowAnonymous"=true})
@param User $user
@param Paper $paper
@param Request $request
@return JsonResponse | [
"Submits",
"answers",
"to",
"an",
"Exercise",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/AttemptController.php#L131-L158 | train |
claroline/Distribution | plugin/exo/Controller/Api/AttemptController.php | AttemptController.finishAction | public function finishAction(Paper $paper, User $user = null)
{
$this->assertHasPermission('OPEN', $paper->getExercise());
$this->assertHasPaperAccess($paper, $user);
$this->attemptManager->end($paper, true, !empty($user));
$userEvaluation = !empty($user) ?
$this->resourceEvalManager->getResourceUserEvaluation($paper->getExercise()->getResourceNode(), $user) :
null;
return new JsonResponse(
[
'paper' => $this->paperManager->serialize($paper),
'userEvaluation' => !empty($userEvaluation) ? $this->userEvalSerializer->serialize($userEvaluation) : null,
],
200
);
} | php | public function finishAction(Paper $paper, User $user = null)
{
$this->assertHasPermission('OPEN', $paper->getExercise());
$this->assertHasPaperAccess($paper, $user);
$this->attemptManager->end($paper, true, !empty($user));
$userEvaluation = !empty($user) ?
$this->resourceEvalManager->getResourceUserEvaluation($paper->getExercise()->getResourceNode(), $user) :
null;
return new JsonResponse(
[
'paper' => $this->paperManager->serialize($paper),
'userEvaluation' => !empty($userEvaluation) ? $this->userEvalSerializer->serialize($userEvaluation) : null,
],
200
);
} | [
"public",
"function",
"finishAction",
"(",
"Paper",
"$",
"paper",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"assertHasPermission",
"(",
"'OPEN'",
",",
"$",
"paper",
"->",
"getExercise",
"(",
")",
")",
";",
"$",
"this",
"->",
... | Flags a paper as finished.
@EXT\Route("/{id}/end", name="exercise_attempt_finish")
@EXT\Method("PUT")
@EXT\ParamConverter("paper", class="UJMExoBundle:Attempt\Paper", options={"mapping": {"id": "uuid"}})
@EXT\ParamConverter("user", converter="current_user", options={"allowAnonymous"=true})
@param Paper $paper
@param User $user
@return JsonResponse | [
"Flags",
"a",
"paper",
"as",
"finished",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/AttemptController.php#L173-L190 | train |
claroline/Distribution | plugin/exo/Controller/Api/AttemptController.php | AttemptController.useHintAction | public function useHintAction(Paper $paper, $questionId, $hintId, User $user = null, Request $request)
{
$this->assertHasPermission('OPEN', $paper->getExercise());
$this->assertHasPaperAccess($paper, $user);
try {
$hint = $this->attemptManager->useHint($paper, $questionId, $hintId, $request->getClientIp());
} catch (\Exception $e) {
return new JsonResponse([[
'path' => '',
'message' => $e->getMessage(),
]], 422);
}
return new JsonResponse($hint);
} | php | public function useHintAction(Paper $paper, $questionId, $hintId, User $user = null, Request $request)
{
$this->assertHasPermission('OPEN', $paper->getExercise());
$this->assertHasPaperAccess($paper, $user);
try {
$hint = $this->attemptManager->useHint($paper, $questionId, $hintId, $request->getClientIp());
} catch (\Exception $e) {
return new JsonResponse([[
'path' => '',
'message' => $e->getMessage(),
]], 422);
}
return new JsonResponse($hint);
} | [
"public",
"function",
"useHintAction",
"(",
"Paper",
"$",
"paper",
",",
"$",
"questionId",
",",
"$",
"hintId",
",",
"User",
"$",
"user",
"=",
"null",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"this",
"->",
"assertHasPermission",
"(",
"'OPEN'",
",",
... | Returns the content of a question hint, and records the fact that it has
been consulted within the context of a given paper.
@EXT\Route("/{id}/{questionId}/hints/{hintId}", name="exercise_attempt_hint_show")
@EXT\Method("GET")
@EXT\ParamConverter("user", converter="current_user", options={"allowAnonymous"=true})
@EXT\ParamConverter("paper", class="UJMExoBundle:Attempt\Paper", options={"mapping": {"id": "uuid"}})
@param Paper $paper
@param string $questionId
@param string $hintId
@param User $user
@param Request $request
@return JsonResponse | [
"Returns",
"the",
"content",
"of",
"a",
"question",
"hint",
"and",
"records",
"the",
"fact",
"that",
"it",
"has",
"been",
"consulted",
"within",
"the",
"context",
"of",
"a",
"given",
"paper",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/AttemptController.php#L209-L224 | train |
claroline/Distribution | plugin/exo/Controller/Api/AttemptController.php | AttemptController.assertHasPaperAccess | private function assertHasPaperAccess(Paper $paper, User $user = null)
{
if (!$this->attemptManager->canUpdate($paper, $user)) {
throw new AccessDeniedException();
}
} | php | private function assertHasPaperAccess(Paper $paper, User $user = null)
{
if (!$this->attemptManager->canUpdate($paper, $user)) {
throw new AccessDeniedException();
}
} | [
"private",
"function",
"assertHasPaperAccess",
"(",
"Paper",
"$",
"paper",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"attemptManager",
"->",
"canUpdate",
"(",
"$",
"paper",
",",
"$",
"user",
")",
")",
"{",
"t... | Checks whether a User has access to a Paper.
@param Paper $paper
@param User $user
@throws AccessDeniedException | [
"Checks",
"whether",
"a",
"User",
"has",
"access",
"to",
"a",
"Paper",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/AttemptController.php#L234-L239 | train |
claroline/Distribution | plugin/exo/Repository/AnswerRepository.php | AnswerRepository.findByQuestion | public function findByQuestion(Item $question, Exercise $exercise = null, $finishedPapersOnly = false)
{
$qb = $this->createQueryBuilder('a')
->join('a.paper', 'p', 'WITH', 'p.exercise = :exercise')
->where('a.questionId = :question')
->setParameters([
'exercise' => $exercise,
'question' => $question->getUuid(),
]);
if ($finishedPapersOnly) {
$qb->andWhere('p.end IS NOT NULL');
}
return $qb->getQuery()->getResult();
} | php | public function findByQuestion(Item $question, Exercise $exercise = null, $finishedPapersOnly = false)
{
$qb = $this->createQueryBuilder('a')
->join('a.paper', 'p', 'WITH', 'p.exercise = :exercise')
->where('a.questionId = :question')
->setParameters([
'exercise' => $exercise,
'question' => $question->getUuid(),
]);
if ($finishedPapersOnly) {
$qb->andWhere('p.end IS NOT NULL');
}
return $qb->getQuery()->getResult();
} | [
"public",
"function",
"findByQuestion",
"(",
"Item",
"$",
"question",
",",
"Exercise",
"$",
"exercise",
"=",
"null",
",",
"$",
"finishedPapersOnly",
"=",
"false",
")",
"{",
"$",
"qb",
"=",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'a'",
")",
"->",
"... | Returns all answers to a question.
It can be limited to only one exercise.
@param Item $question
@param Exercise $exercise
@param bool $finishedPapersOnly
@return Answer[] | [
"Returns",
"all",
"answers",
"to",
"a",
"question",
".",
"It",
"can",
"be",
"limited",
"to",
"only",
"one",
"exercise",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Repository/AnswerRepository.php#L25-L40 | train |
claroline/Distribution | main/app/API/Transfer/Adapter/CsvAdapter.php | CsvAdapter.decodeSchema | public function decodeSchema($content, Explanation $explanation)
{
$data = [];
$lines = str_getcsv($content, PHP_EOL);
$header = array_shift($lines);
$headers = array_filter(
str_getcsv($header, ';'),
function ($header) {
return '' !== $header;
}
);
foreach ($lines as $line) {
$properties = str_getcsv($line, ';');
$data[] = $this->buildObjectFromLine($properties, $headers, $explanation);
}
return $data;
} | php | public function decodeSchema($content, Explanation $explanation)
{
$data = [];
$lines = str_getcsv($content, PHP_EOL);
$header = array_shift($lines);
$headers = array_filter(
str_getcsv($header, ';'),
function ($header) {
return '' !== $header;
}
);
foreach ($lines as $line) {
$properties = str_getcsv($line, ';');
$data[] = $this->buildObjectFromLine($properties, $headers, $explanation);
}
return $data;
} | [
"public",
"function",
"decodeSchema",
"(",
"$",
"content",
",",
"Explanation",
"$",
"explanation",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"$",
"lines",
"=",
"str_getcsv",
"(",
"$",
"content",
",",
"PHP_EOL",
")",
";",
"$",
"header",
"=",
"array_shi... | Create a php array object from the schema according to the data passed on.
Each line is a new object.
@param string $content
@param Explanation $explanation | [
"Create",
"a",
"php",
"array",
"object",
"from",
"the",
"schema",
"according",
"to",
"the",
"data",
"passed",
"on",
".",
"Each",
"line",
"is",
"a",
"new",
"object",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/API/Transfer/Adapter/CsvAdapter.php#L40-L58 | train |
claroline/Distribution | main/app/API/Transfer/Adapter/CsvAdapter.php | CsvAdapter.getCsvSerialized | private function getCsvSerialized(\stdClass $object, $path)
{
//it's easier to work with objects here
$parts = explode('.', $path);
$first = array_shift($parts);
if (property_exists($object, $first) && is_object($object->{$first})) {
return $this->getCsvSerialized($object->{$first}, implode($parts, '.'));
}
if (property_exists($object, $first) && is_array($object->{$first})) {
return $this->getCsvArraySerialized($object->{$first}, implode($parts, '.'));
}
if (property_exists($object, $first) && !is_array($object->$first)) {
return $object->{$first};
}
} | php | private function getCsvSerialized(\stdClass $object, $path)
{
//it's easier to work with objects here
$parts = explode('.', $path);
$first = array_shift($parts);
if (property_exists($object, $first) && is_object($object->{$first})) {
return $this->getCsvSerialized($object->{$first}, implode($parts, '.'));
}
if (property_exists($object, $first) && is_array($object->{$first})) {
return $this->getCsvArraySerialized($object->{$first}, implode($parts, '.'));
}
if (property_exists($object, $first) && !is_array($object->$first)) {
return $object->{$first};
}
} | [
"private",
"function",
"getCsvSerialized",
"(",
"\\",
"stdClass",
"$",
"object",
",",
"$",
"path",
")",
"{",
"//it's easier to work with objects here",
"$",
"parts",
"=",
"explode",
"(",
"'.'",
",",
"$",
"path",
")",
";",
"$",
"first",
"=",
"array_shift",
"(... | Returns the property of the object according to the path for the csv export.
@param \stdClass $object
@param string $path
@return string | [
"Returns",
"the",
"property",
"of",
"the",
"object",
"according",
"to",
"the",
"path",
"for",
"the",
"csv",
"export",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/API/Transfer/Adapter/CsvAdapter.php#L164-L181 | train |
claroline/Distribution | main/app/API/Transfer/Adapter/CsvAdapter.php | CsvAdapter.getCsvArraySerialized | private function getCsvArraySerialized(array $elements, $path)
{
$data = [];
foreach ($elements as $element) {
$data[] = $this->getCsvSerialized($element, $path);
}
return implode($data, ',');
} | php | private function getCsvArraySerialized(array $elements, $path)
{
$data = [];
foreach ($elements as $element) {
$data[] = $this->getCsvSerialized($element, $path);
}
return implode($data, ',');
} | [
"private",
"function",
"getCsvArraySerialized",
"(",
"array",
"$",
"elements",
",",
"$",
"path",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"elements",
"as",
"$",
"element",
")",
"{",
"$",
"data",
"[",
"]",
"=",
"$",
"this",
"-... | Returns the serialized array for the csv export.
@param array $elements - the array to serialize
@param string $path - the property path inside the array
@return string | [
"Returns",
"the",
"serialized",
"array",
"for",
"the",
"csv",
"export",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/app/API/Transfer/Adapter/CsvAdapter.php#L191-L200 | train |
claroline/Distribution | plugin/dropzone/Entity/Dropzone.php | Dropzone.setForceCommentInCorrection | public function setForceCommentInCorrection($forceCommentInCorrection)
{
if (true === $this->getAllowCommentInCorrection()) {
$this->forceCommentInCorrection = $forceCommentInCorrection;
} else {
$this->forceCommentInCorrection = false;
}
} | php | public function setForceCommentInCorrection($forceCommentInCorrection)
{
if (true === $this->getAllowCommentInCorrection()) {
$this->forceCommentInCorrection = $forceCommentInCorrection;
} else {
$this->forceCommentInCorrection = false;
}
} | [
"public",
"function",
"setForceCommentInCorrection",
"(",
"$",
"forceCommentInCorrection",
")",
"{",
"if",
"(",
"true",
"===",
"$",
"this",
"->",
"getAllowCommentInCorrection",
"(",
")",
")",
"{",
"$",
"this",
"->",
"forceCommentInCorrection",
"=",
"$",
"forceComm... | when there is no comment allowed, the comment can't be mandatory.
@param bool $forceCommentInCorrection | [
"when",
"there",
"is",
"no",
"comment",
"allowed",
"the",
"comment",
"can",
"t",
"be",
"mandatory",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/dropzone/Entity/Dropzone.php#L357-L364 | train |
claroline/Distribution | plugin/dropzone/Entity/Dropzone.php | Dropzone.addCriterion | public function addCriterion(Criterion $criterion)
{
$criterion->setDropzone($this);
$this->peerReviewCriteria[] = $criterion;
return $this;
} | php | public function addCriterion(Criterion $criterion)
{
$criterion->setDropzone($this);
$this->peerReviewCriteria[] = $criterion;
return $this;
} | [
"public",
"function",
"addCriterion",
"(",
"Criterion",
"$",
"criterion",
")",
"{",
"$",
"criterion",
"->",
"setDropzone",
"(",
"$",
"this",
")",
";",
"$",
"this",
"->",
"peerReviewCriteria",
"[",
"]",
"=",
"$",
"criterion",
";",
"return",
"$",
"this",
"... | Add criterion.
@param \Icap\DropzoneBundle\Entity\Criterion $criterion
@return Dropzone | [
"Add",
"criterion",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/dropzone/Entity/Dropzone.php#L878-L884 | train |
claroline/Distribution | plugin/dropzone/Entity/Dropzone.php | Dropzone.setAutoCloseState | public function setAutoCloseState($autoCloseState)
{
$authorizedValues = [self::AUTO_CLOSED_STATE_CLOSED, self::AUTO_CLOSED_STATE_WAITING];
if (in_array($autoCloseState, $authorizedValues)) {
$this->autoCloseState = $autoCloseState;
}
} | php | public function setAutoCloseState($autoCloseState)
{
$authorizedValues = [self::AUTO_CLOSED_STATE_CLOSED, self::AUTO_CLOSED_STATE_WAITING];
if (in_array($autoCloseState, $authorizedValues)) {
$this->autoCloseState = $autoCloseState;
}
} | [
"public",
"function",
"setAutoCloseState",
"(",
"$",
"autoCloseState",
")",
"{",
"$",
"authorizedValues",
"=",
"[",
"self",
"::",
"AUTO_CLOSED_STATE_CLOSED",
",",
"self",
"::",
"AUTO_CLOSED_STATE_WAITING",
"]",
";",
"if",
"(",
"in_array",
"(",
"$",
"autoCloseState... | Param that indicate if all drop have already been auto closed or not.
@param string $autoCloseState | [
"Param",
"that",
"indicate",
"if",
"all",
"drop",
"have",
"already",
"been",
"auto",
"closed",
"or",
"not",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/dropzone/Entity/Dropzone.php#L907-L913 | train |
claroline/Distribution | plugin/exo/Controller/Api/Item/ItemController.php | ItemController.listAction | public function listAction(Request $request)
{
return new JsonResponse(
$this->finder->search(
'UJM\ExoBundle\Entity\Item\Item',
$request->query->all(),
[Transfer::INCLUDE_SOLUTIONS, Transfer::INCLUDE_ADMIN_META]
)
);
} | php | public function listAction(Request $request)
{
return new JsonResponse(
$this->finder->search(
'UJM\ExoBundle\Entity\Item\Item',
$request->query->all(),
[Transfer::INCLUDE_SOLUTIONS, Transfer::INCLUDE_ADMIN_META]
)
);
} | [
"public",
"function",
"listAction",
"(",
"Request",
"$",
"request",
")",
"{",
"return",
"new",
"JsonResponse",
"(",
"$",
"this",
"->",
"finder",
"->",
"search",
"(",
"'UJM\\ExoBundle\\Entity\\Item\\Item'",
",",
"$",
"request",
"->",
"query",
"->",
"all",
"(",
... | Searches for questions.
@EXT\Route("", name="question_list")
@EXT\Method("GET")
@param Request $request
@return JsonResponse | [
"Searches",
"for",
"questions",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/Item/ItemController.php#L69-L78 | train |
claroline/Distribution | plugin/exo/Controller/Api/Item/ItemController.php | ItemController.createAction | public function createAction(Request $request)
{
$errors = [];
$question = null;
$data = $this->decodeRequestData($request);
if (empty($data)) {
// Invalid or empty JSON data received
$errors[] = [
'path' => '',
'message' => 'Invalid JSON data',
];
} else {
// Try to update question with data
try {
$question = $this->manager->create($data);
} catch (InvalidDataException $e) {
$errors = $e->getErrors();
}
}
if (empty($errors)) {
// Item updated
return new JsonResponse(
$this->manager->serialize($question, [Transfer::INCLUDE_SOLUTIONS, Transfer::INCLUDE_ADMIN_META])
);
} else {
// Invalid data received
return new JsonResponse($errors, 422);
}
} | php | public function createAction(Request $request)
{
$errors = [];
$question = null;
$data = $this->decodeRequestData($request);
if (empty($data)) {
// Invalid or empty JSON data received
$errors[] = [
'path' => '',
'message' => 'Invalid JSON data',
];
} else {
// Try to update question with data
try {
$question = $this->manager->create($data);
} catch (InvalidDataException $e) {
$errors = $e->getErrors();
}
}
if (empty($errors)) {
// Item updated
return new JsonResponse(
$this->manager->serialize($question, [Transfer::INCLUDE_SOLUTIONS, Transfer::INCLUDE_ADMIN_META])
);
} else {
// Invalid data received
return new JsonResponse($errors, 422);
}
} | [
"public",
"function",
"createAction",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"errors",
"=",
"[",
"]",
";",
"$",
"question",
"=",
"null",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"decodeRequestData",
"(",
"$",
"request",
")",
";",
"if",
"(",
... | Creates a new Item.
@EXT\Route("", name="question_create")
@EXT\Method("POST")
@param Request $request
@return JsonResponse | [
"Creates",
"a",
"new",
"Item",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/Item/ItemController.php#L90-L120 | train |
claroline/Distribution | plugin/exo/Controller/Api/Item/ItemController.php | ItemController.updateAction | public function updateAction(Item $question, Request $request)
{
$errors = [];
$data = $this->decodeRequestData($request);
if (empty($data)) {
// Invalid or empty JSON data received
$errors[] = [
'path' => '',
'message' => 'Invalid JSON data',
];
} else {
// Try to update question with data
try {
$question = $this->manager->update($question, $data);
} catch (InvalidDataException $e) {
$errors = $e->getErrors();
}
}
if (empty($errors)) {
// Item updated
return new JsonResponse(
$this->manager->serialize($question, [Transfer::INCLUDE_SOLUTIONS, Transfer::INCLUDE_ADMIN_META])
);
} else {
// Invalid data received
return new JsonResponse($errors, 422);
}
} | php | public function updateAction(Item $question, Request $request)
{
$errors = [];
$data = $this->decodeRequestData($request);
if (empty($data)) {
// Invalid or empty JSON data received
$errors[] = [
'path' => '',
'message' => 'Invalid JSON data',
];
} else {
// Try to update question with data
try {
$question = $this->manager->update($question, $data);
} catch (InvalidDataException $e) {
$errors = $e->getErrors();
}
}
if (empty($errors)) {
// Item updated
return new JsonResponse(
$this->manager->serialize($question, [Transfer::INCLUDE_SOLUTIONS, Transfer::INCLUDE_ADMIN_META])
);
} else {
// Invalid data received
return new JsonResponse($errors, 422);
}
} | [
"public",
"function",
"updateAction",
"(",
"Item",
"$",
"question",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"errors",
"=",
"[",
"]",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"decodeRequestData",
"(",
"$",
"request",
")",
";",
"if",
"(",
"empt... | Updates a Item.
@EXT\Route("/{id}", name="question_update")
@EXT\Method("PUT")
@EXT\ParamConverter("question", class="UJMExoBundle:Item\Item", options={"mapping": {"id": "uuid"}})
@param Item $question
@param Request $request
@return JsonResponse | [
"Updates",
"a",
"Item",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Controller/Api/Item/ItemController.php#L134-L163 | train |
claroline/Distribution | main/core/Listener/DoctrineDebug.php | DoctrineDebug.onFlush | public function onFlush(OnFlushEventArgs $eventArgs)
{
//reduce the amount of flushes to increase performances !
//you can also activate the log from the claroline.persistence.object_manager service when you use it
//if you want additional informations about transactions
if ($this->activateLog) {
$this->log('onFlush event fired !!!', LogLevel::DEBUG);
if (self::DEBUG_NONE !== $this->debugLevel) {
$stack = debug_backtrace();
foreach ($stack as $call) {
if (isset($call['file'])) {
$file = $call['file'];
if (self::DEBUG_CLAROLINE === $this->debugLevel) {
if (strpos($file, 'claroline')) {
$this->logTrace($call);
}
} elseif (self::DEBUG_ALL === $this->debugLevel) {
$this->logTrace($call);
} elseif (self::DEBUG_VENDOR === $this->debugLevel) {
if (strpos($file, $this->debugVendor)) {
$this->logTrace($call);
}
}
}
}
$this->log('Data printed !');
}
}
} | php | public function onFlush(OnFlushEventArgs $eventArgs)
{
//reduce the amount of flushes to increase performances !
//you can also activate the log from the claroline.persistence.object_manager service when you use it
//if you want additional informations about transactions
if ($this->activateLog) {
$this->log('onFlush event fired !!!', LogLevel::DEBUG);
if (self::DEBUG_NONE !== $this->debugLevel) {
$stack = debug_backtrace();
foreach ($stack as $call) {
if (isset($call['file'])) {
$file = $call['file'];
if (self::DEBUG_CLAROLINE === $this->debugLevel) {
if (strpos($file, 'claroline')) {
$this->logTrace($call);
}
} elseif (self::DEBUG_ALL === $this->debugLevel) {
$this->logTrace($call);
} elseif (self::DEBUG_VENDOR === $this->debugLevel) {
if (strpos($file, $this->debugVendor)) {
$this->logTrace($call);
}
}
}
}
$this->log('Data printed !');
}
}
} | [
"public",
"function",
"onFlush",
"(",
"OnFlushEventArgs",
"$",
"eventArgs",
")",
"{",
"//reduce the amount of flushes to increase performances !",
"//you can also activate the log from the claroline.persistence.object_manager service when you use it",
"//if you want additional informations abo... | Gets all the entities to flush.
@param OnFlushEventArgs $eventArgs Event args | [
"Gets",
"all",
"the",
"entities",
"to",
"flush",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Listener/DoctrineDebug.php#L47-L78 | train |
claroline/Distribution | plugin/forum/Serializer/SubjectSerializer.php | SubjectSerializer.serialize | public function serialize(Subject $subject, array $options = [])
{
$first = $this->messageRepo->findOneBy([
'subject' => $subject,
'first' => true,
]);
return [
'id' => $subject->getUuid(),
'forum' => [
'id' => $subject->getForum()->getUuid(),
],
'tags' => $this->serializeTags($subject),
'content' => $first ? $first->getContent() : null,
'title' => $subject->getTitle(),
'meta' => $this->serializeMeta($subject, $options),
'restrictions' => $this->serializeRestrictions($subject, $options),
'poster' => $subject->getPoster() ? $this->fileSerializer->serialize($subject->getPoster()) : null,
];
} | php | public function serialize(Subject $subject, array $options = [])
{
$first = $this->messageRepo->findOneBy([
'subject' => $subject,
'first' => true,
]);
return [
'id' => $subject->getUuid(),
'forum' => [
'id' => $subject->getForum()->getUuid(),
],
'tags' => $this->serializeTags($subject),
'content' => $first ? $first->getContent() : null,
'title' => $subject->getTitle(),
'meta' => $this->serializeMeta($subject, $options),
'restrictions' => $this->serializeRestrictions($subject, $options),
'poster' => $subject->getPoster() ? $this->fileSerializer->serialize($subject->getPoster()) : null,
];
} | [
"public",
"function",
"serialize",
"(",
"Subject",
"$",
"subject",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"first",
"=",
"$",
"this",
"->",
"messageRepo",
"->",
"findOneBy",
"(",
"[",
"'subject'",
"=>",
"$",
"subject",
",",
"'first'... | Serializes a Subject entity.
@param Subject $subject
@param array $options
@return array | [
"Serializes",
"a",
"Subject",
"entity",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/forum/Serializer/SubjectSerializer.php#L102-L121 | train |
claroline/Distribution | main/migration/Generator/Generator.php | Generator.getSchemas | public function getSchemas()
{
if (count($this->schemas) === 0) {
$this->schemas['metadata'] = $this->em->getMetadataFactory()->getAllMetadata();
$this->schemas['fromSchema'] = $this->em->getConnection()->getSchemaManager()->createSchema();
$this->schemas['toSchema'] = $this->schemaTool->getSchemaFromMetadata($this->schemas['metadata']);
}
// cloning schemas is much more ligther than re-generating them for each platform
return array(
'fromSchema' => clone $this->schemas['fromSchema'],
'toSchema' => clone $this->schemas['toSchema'],
'metadata' => $this->schemas['metadata'],
);
} | php | public function getSchemas()
{
if (count($this->schemas) === 0) {
$this->schemas['metadata'] = $this->em->getMetadataFactory()->getAllMetadata();
$this->schemas['fromSchema'] = $this->em->getConnection()->getSchemaManager()->createSchema();
$this->schemas['toSchema'] = $this->schemaTool->getSchemaFromMetadata($this->schemas['metadata']);
}
// cloning schemas is much more ligther than re-generating them for each platform
return array(
'fromSchema' => clone $this->schemas['fromSchema'],
'toSchema' => clone $this->schemas['toSchema'],
'metadata' => $this->schemas['metadata'],
);
} | [
"public",
"function",
"getSchemas",
"(",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"schemas",
")",
"===",
"0",
")",
"{",
"$",
"this",
"->",
"schemas",
"[",
"'metadata'",
"]",
"=",
"$",
"this",
"->",
"em",
"->",
"getMetadataFactory",
"(",
... | Returns the "from" an "to" schemas and the metadata used to generate them.
Note: this method is public for testing purposes only
@return array | [
"Returns",
"the",
"from",
"an",
"to",
"schemas",
"and",
"the",
"metadata",
"used",
"to",
"generate",
"them",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/migration/Generator/Generator.php#L76-L90 | train |
claroline/Distribution | main/core/Listener/Tool/ResourcesListener.php | ResourcesListener.onDisplayDesktop | public function onDisplayDesktop(DisplayToolEvent $event)
{
$content = $this->templating->render(
'ClarolineCoreBundle:tool:resources.html.twig', [
'context' => [
'type' => Widget::CONTEXT_DESKTOP,
],
'root' => null,
]
);
$event->setContent($content);
$event->stopPropagation();
} | php | public function onDisplayDesktop(DisplayToolEvent $event)
{
$content = $this->templating->render(
'ClarolineCoreBundle:tool:resources.html.twig', [
'context' => [
'type' => Widget::CONTEXT_DESKTOP,
],
'root' => null,
]
);
$event->setContent($content);
$event->stopPropagation();
} | [
"public",
"function",
"onDisplayDesktop",
"(",
"DisplayToolEvent",
"$",
"event",
")",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"templating",
"->",
"render",
"(",
"'ClarolineCoreBundle:tool:resources.html.twig'",
",",
"[",
"'context'",
"=>",
"[",
"'type'",
"=>"... | Displays resources on Desktop.
@DI\Observe("open_tool_desktop_resource_manager")
@param DisplayToolEvent $event | [
"Displays",
"resources",
"on",
"Desktop",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Listener/Tool/ResourcesListener.php#L71-L84 | train |
claroline/Distribution | main/core/Listener/Tool/ResourcesListener.php | ResourcesListener.onDisplayWorkspace | public function onDisplayWorkspace(DisplayToolEvent $event)
{
$workspace = $event->getWorkspace();
$content = $this->templating->render(
'ClarolineCoreBundle:tool:resources.html.twig', [
'workspace' => $workspace,
'context' => [
'type' => Widget::CONTEXT_WORKSPACE,
'data' => $this->serializer->serialize($workspace),
],
'root' => $this->serializer->serialize(
$this->resourceRepository->findWorkspaceRoot($workspace)
),
]
);
$event->setContent($content);
$event->stopPropagation();
} | php | public function onDisplayWorkspace(DisplayToolEvent $event)
{
$workspace = $event->getWorkspace();
$content = $this->templating->render(
'ClarolineCoreBundle:tool:resources.html.twig', [
'workspace' => $workspace,
'context' => [
'type' => Widget::CONTEXT_WORKSPACE,
'data' => $this->serializer->serialize($workspace),
],
'root' => $this->serializer->serialize(
$this->resourceRepository->findWorkspaceRoot($workspace)
),
]
);
$event->setContent($content);
$event->stopPropagation();
} | [
"public",
"function",
"onDisplayWorkspace",
"(",
"DisplayToolEvent",
"$",
"event",
")",
"{",
"$",
"workspace",
"=",
"$",
"event",
"->",
"getWorkspace",
"(",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"templating",
"->",
"render",
"(",
"'ClarolineCoreB... | Displays resources on Workspace.
@DI\Observe("open_tool_workspace_resource_manager")
@param DisplayToolEvent $event | [
"Displays",
"resources",
"on",
"Workspace",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Listener/Tool/ResourcesListener.php#L93-L112 | train |
claroline/Distribution | main/core/Manager/Workspace/Transfer/OrderedToolTransfer.php | OrderedToolTransfer.deserialize | public function deserialize(array $data, OrderedTool $orderedTool, array $options = [], Workspace $workspace = null, FileBag $bag = null)
{
$om = $this->container->get('claroline.persistence.object_manager');
$tool = $om->getRepository(Tool::class)->findOneByName($data['tool']);
if ($tool) {
$orderedTool->setWorkspace($workspace);
$orderedTool->setTool($tool);
$orderedTool->setName($data['name']);
$orderedTool->setOrder($data['position']);
foreach ($data['restrictions'] as $restriction) {
if (isset($restriction['role']['name'])) {
$role = $om->getRepository(Role::class)->findOneBy(['name' => $restriction['role']['name']]);
} else {
$role = $om->getRepository(Role::class)->findOneBy([
'translationKey' => $restriction['role']['translationKey'],
'workspace' => $workspace->getId(),
]);
}
$rights = new ToolRights();
$rights->setRole($role);
$rights->setMask($restriction['mask']);
$rights->setOrderedTool($orderedTool);
$om->persist($rights);
}
//use event instead maybe ? or tagged service
$serviceName = 'claroline.transfer.'.$orderedTool->getTool()->getName();
if ($this->container->has($serviceName)) {
$importer = $this->container->get($serviceName);
if (method_exists($importer, 'setLogger')) {
$importer->setLogger($this->logger);
}
if (isset($data['data'])) {
$importer->deserialize($data['data'], $orderedTool->getWorkspace(), [Options::REFRESH_UUID], $bag);
}
}
}
} | php | public function deserialize(array $data, OrderedTool $orderedTool, array $options = [], Workspace $workspace = null, FileBag $bag = null)
{
$om = $this->container->get('claroline.persistence.object_manager');
$tool = $om->getRepository(Tool::class)->findOneByName($data['tool']);
if ($tool) {
$orderedTool->setWorkspace($workspace);
$orderedTool->setTool($tool);
$orderedTool->setName($data['name']);
$orderedTool->setOrder($data['position']);
foreach ($data['restrictions'] as $restriction) {
if (isset($restriction['role']['name'])) {
$role = $om->getRepository(Role::class)->findOneBy(['name' => $restriction['role']['name']]);
} else {
$role = $om->getRepository(Role::class)->findOneBy([
'translationKey' => $restriction['role']['translationKey'],
'workspace' => $workspace->getId(),
]);
}
$rights = new ToolRights();
$rights->setRole($role);
$rights->setMask($restriction['mask']);
$rights->setOrderedTool($orderedTool);
$om->persist($rights);
}
//use event instead maybe ? or tagged service
$serviceName = 'claroline.transfer.'.$orderedTool->getTool()->getName();
if ($this->container->has($serviceName)) {
$importer = $this->container->get($serviceName);
if (method_exists($importer, 'setLogger')) {
$importer->setLogger($this->logger);
}
if (isset($data['data'])) {
$importer->deserialize($data['data'], $orderedTool->getWorkspace(), [Options::REFRESH_UUID], $bag);
}
}
}
} | [
"public",
"function",
"deserialize",
"(",
"array",
"$",
"data",
",",
"OrderedTool",
"$",
"orderedTool",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"Workspace",
"$",
"workspace",
"=",
"null",
",",
"FileBag",
"$",
"bag",
"=",
"null",
")",
"{",
"$"... | only work for creation... other not supported. It's not a true Serializer anyway atm | [
"only",
"work",
"for",
"creation",
"...",
"other",
"not",
"supported",
".",
"It",
"s",
"not",
"a",
"true",
"Serializer",
"anyway",
"atm"
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Manager/Workspace/Transfer/OrderedToolTransfer.php#L102-L143 | train |
claroline/Distribution | main/core/Listener/Tool/AnalyticsListener.php | AnalyticsListener.onDisplayWorkspace | public function onDisplayWorkspace(DisplayToolEvent $event)
{
$workspace = $event->getWorkspace();
$content = $this->templating->render(
'ClarolineCoreBundle:workspace:analytics.html.twig', [
'workspace' => $workspace,
]
);
$event->setContent($content);
$event->stopPropagation();
} | php | public function onDisplayWorkspace(DisplayToolEvent $event)
{
$workspace = $event->getWorkspace();
$content = $this->templating->render(
'ClarolineCoreBundle:workspace:analytics.html.twig', [
'workspace' => $workspace,
]
);
$event->setContent($content);
$event->stopPropagation();
} | [
"public",
"function",
"onDisplayWorkspace",
"(",
"DisplayToolEvent",
"$",
"event",
")",
"{",
"$",
"workspace",
"=",
"$",
"event",
"->",
"getWorkspace",
"(",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"templating",
"->",
"render",
"(",
"'ClarolineCoreB... | Displays analytics on Workspace.
@DI\Observe("open_tool_workspace_analytics")
@param DisplayToolEvent $event | [
"Displays",
"analytics",
"on",
"Workspace",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Listener/Tool/AnalyticsListener.php#L48-L60 | train |
claroline/Distribution | plugin/exo/Serializer/Item/Type/BooleanQuestionSerializer.php | BooleanQuestionSerializer.serialize | public function serialize(BooleanQuestion $question, array $options = [])
{
// Serializes choices
$choices = $this->serializeChoices($question, $options);
if (in_array(Transfer::SHUFFLE_ANSWERS, $options)) {
shuffle($choices);
}
$serialized = ['choices' => $choices];
if (in_array(Transfer::INCLUDE_SOLUTIONS, $options)) {
$serialized['solutions'] = $this->serializeSolutions($question);
}
return $serialized;
} | php | public function serialize(BooleanQuestion $question, array $options = [])
{
// Serializes choices
$choices = $this->serializeChoices($question, $options);
if (in_array(Transfer::SHUFFLE_ANSWERS, $options)) {
shuffle($choices);
}
$serialized = ['choices' => $choices];
if (in_array(Transfer::INCLUDE_SOLUTIONS, $options)) {
$serialized['solutions'] = $this->serializeSolutions($question);
}
return $serialized;
} | [
"public",
"function",
"serialize",
"(",
"BooleanQuestion",
"$",
"question",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// Serializes choices",
"$",
"choices",
"=",
"$",
"this",
"->",
"serializeChoices",
"(",
"$",
"question",
",",
"$",
"options",... | Converts a Boolean question into a JSON-encodable structure.
@param BooleanQuestion $question
@param array $options
@return array | [
"Converts",
"a",
"Boolean",
"question",
"into",
"a",
"JSON",
"-",
"encodable",
"structure",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/Item/Type/BooleanQuestionSerializer.php#L47-L63 | train |
claroline/Distribution | plugin/exo/Serializer/Item/Type/BooleanQuestionSerializer.php | BooleanQuestionSerializer.deserialize | public function deserialize($data, BooleanQuestion $question = null, array $options = [])
{
if (empty($question)) {
$question = new BooleanQuestion();
}
$this->deserializeChoices($question, $data['choices'], $data['solutions'], $options);
return $question;
} | php | public function deserialize($data, BooleanQuestion $question = null, array $options = [])
{
if (empty($question)) {
$question = new BooleanQuestion();
}
$this->deserializeChoices($question, $data['choices'], $data['solutions'], $options);
return $question;
} | [
"public",
"function",
"deserialize",
"(",
"$",
"data",
",",
"BooleanQuestion",
"$",
"question",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"question",
")",
")",
"{",
"$",
"question",
"=",
"new",
... | Converts raw data into a Boolean question entity.
@param array $data
@param BooleanQuestion $question
@param array $options
@return BooleanQuestion | [
"Converts",
"raw",
"data",
"into",
"a",
"Boolean",
"question",
"entity",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/Item/Type/BooleanQuestionSerializer.php#L74-L83 | train |
claroline/Distribution | plugin/exo/Serializer/Item/Type/BooleanQuestionSerializer.php | BooleanQuestionSerializer.serializeChoices | private function serializeChoices(BooleanQuestion $question, array $options = [])
{
return array_map(function (BooleanChoice $choice) use ($options) {
$choiceData = $this->contentSerializer->serialize($choice, $options);
$choiceData['id'] = $choice->getUuid();
return $choiceData;
}, $question->getChoices()->toArray());
} | php | private function serializeChoices(BooleanQuestion $question, array $options = [])
{
return array_map(function (BooleanChoice $choice) use ($options) {
$choiceData = $this->contentSerializer->serialize($choice, $options);
$choiceData['id'] = $choice->getUuid();
return $choiceData;
}, $question->getChoices()->toArray());
} | [
"private",
"function",
"serializeChoices",
"(",
"BooleanQuestion",
"$",
"question",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"array_map",
"(",
"function",
"(",
"BooleanChoice",
"$",
"choice",
")",
"use",
"(",
"$",
"options",
")",
"{... | Serializes the Question choices.
@param BooleanQuestion $question
@param array $options
@return array | [
"Serializes",
"the",
"Question",
"choices",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/Item/Type/BooleanQuestionSerializer.php#L93-L101 | train |
claroline/Distribution | plugin/result/Repository/MarkRepository.php | MarkRepository.findByResult | public function findByResult(Result $result)
{
$dql = '
SELECT
u.id,
CONCAT(u.firstName, \' \', u.lastName) AS name,
m.value AS mark,
m.id AS markId
FROM Claroline\ResultBundle\Entity\Mark m
JOIN m.user u
WHERE m.result = :result
ORDER BY u.lastName ASC
';
$query = $this->_em->createQuery($dql);
$query->setParameter('result', $result);
return $query->getArrayResult();
} | php | public function findByResult(Result $result)
{
$dql = '
SELECT
u.id,
CONCAT(u.firstName, \' \', u.lastName) AS name,
m.value AS mark,
m.id AS markId
FROM Claroline\ResultBundle\Entity\Mark m
JOIN m.user u
WHERE m.result = :result
ORDER BY u.lastName ASC
';
$query = $this->_em->createQuery($dql);
$query->setParameter('result', $result);
return $query->getArrayResult();
} | [
"public",
"function",
"findByResult",
"(",
"Result",
"$",
"result",
")",
"{",
"$",
"dql",
"=",
"'\n SELECT\n u.id,\n CONCAT(u.firstName, \\' \\', u.lastName) AS name,\n m.value AS mark,\n m.id AS markId\n FROM ... | Returns an array representation of the marks associated
with a given result.
@param Result $result
@return array | [
"Returns",
"an",
"array",
"representation",
"of",
"the",
"marks",
"associated",
"with",
"a",
"given",
"result",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/result/Repository/MarkRepository.php#L28-L46 | train |
claroline/Distribution | plugin/result/Repository/MarkRepository.php | MarkRepository.findByResultAndUser | public function findByResultAndUser(Result $result, User $user)
{
$dql = '
SELECT
u.id,
CONCAT(u.firstName, \' \', u.lastName) AS name,
m.value AS mark,
m.id AS markId
FROM Claroline\ResultBundle\Entity\Mark m
JOIN m.user u
WHERE m.result = :result
AND u = :user
ORDER BY u.lastName ASC
';
$query = $this->_em->createQuery($dql);
$query->setParameters([
'result' => $result,
'user' => $user,
]);
return $query->getArrayResult();
} | php | public function findByResultAndUser(Result $result, User $user)
{
$dql = '
SELECT
u.id,
CONCAT(u.firstName, \' \', u.lastName) AS name,
m.value AS mark,
m.id AS markId
FROM Claroline\ResultBundle\Entity\Mark m
JOIN m.user u
WHERE m.result = :result
AND u = :user
ORDER BY u.lastName ASC
';
$query = $this->_em->createQuery($dql);
$query->setParameters([
'result' => $result,
'user' => $user,
]);
return $query->getArrayResult();
} | [
"public",
"function",
"findByResultAndUser",
"(",
"Result",
"$",
"result",
",",
"User",
"$",
"user",
")",
"{",
"$",
"dql",
"=",
"'\n SELECT\n u.id,\n CONCAT(u.firstName, \\' \\', u.lastName) AS name,\n m.value AS mark,\n ... | Returns an array representation of the mark associated
with a result for a given user.
@param Result $result
@param User $user
@return array | [
"Returns",
"an",
"array",
"representation",
"of",
"the",
"mark",
"associated",
"with",
"a",
"result",
"for",
"a",
"given",
"user",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/result/Repository/MarkRepository.php#L57-L79 | train |
claroline/Distribution | plugin/competency/Repository/AbilityProgressRepository.php | AbilityProgressRepository.findByAbilitiesAndStatus | public function findByAbilitiesAndStatus(User $user, array $abilities, $status)
{
return $this->createQueryBuilder('ap')
->select('ap')
->where('ap.user = :user')
->andWhere('ap.ability IN (:abilities)')
->andWhere('ap.status = :status')
->orderBy('ap.id')
->setParameters([
':user' => $user,
':abilities' => $abilities,
':status' => $status,
])
->getQuery()
->getResult();
} | php | public function findByAbilitiesAndStatus(User $user, array $abilities, $status)
{
return $this->createQueryBuilder('ap')
->select('ap')
->where('ap.user = :user')
->andWhere('ap.ability IN (:abilities)')
->andWhere('ap.status = :status')
->orderBy('ap.id')
->setParameters([
':user' => $user,
':abilities' => $abilities,
':status' => $status,
])
->getQuery()
->getResult();
} | [
"public",
"function",
"findByAbilitiesAndStatus",
"(",
"User",
"$",
"user",
",",
"array",
"$",
"abilities",
",",
"$",
"status",
")",
"{",
"return",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'ap'",
")",
"->",
"select",
"(",
"'ap'",
")",
"->",
"where",
... | Returns progress entities for a given user which are related to
a set of abilities and have a particular status.
@param User $user
@param array $abilities
@param string $status
@return array | [
"Returns",
"progress",
"entities",
"for",
"a",
"given",
"user",
"which",
"are",
"related",
"to",
"a",
"set",
"of",
"abilities",
"and",
"have",
"a",
"particular",
"status",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/competency/Repository/AbilityProgressRepository.php#L20-L35 | train |
claroline/Distribution | main/core/Controller/APINew/WidgetController.php | WidgetController.listAction | public function listAction($context = null)
{
return new JsonResponse([
'widgets' => array_map(function (Widget $widget) {
return $this->serializer->serialize($widget);
}, $this->widgetManager->getAvailable($context)),
'dataSources' => array_map(function (DataSource $dataSource) {
return $this->serializer->serialize($dataSource);
}, $this->dataSourceManager->getAvailable($context)),
]);
} | php | public function listAction($context = null)
{
return new JsonResponse([
'widgets' => array_map(function (Widget $widget) {
return $this->serializer->serialize($widget);
}, $this->widgetManager->getAvailable($context)),
'dataSources' => array_map(function (DataSource $dataSource) {
return $this->serializer->serialize($dataSource);
}, $this->dataSourceManager->getAvailable($context)),
]);
} | [
"public",
"function",
"listAction",
"(",
"$",
"context",
"=",
"null",
")",
"{",
"return",
"new",
"JsonResponse",
"(",
"[",
"'widgets'",
"=>",
"array_map",
"(",
"function",
"(",
"Widget",
"$",
"widget",
")",
"{",
"return",
"$",
"this",
"->",
"serializer",
... | Lists available widgets for a given context.
@EXT\Route("/{context}", name="apiv2_widget_available", defaults={"context"=null})
@EXT\Method("GET")
@param string $context
@return JsonResponse | [
"Lists",
"available",
"widgets",
"for",
"a",
"given",
"context",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Controller/APINew/WidgetController.php#L72-L82 | train |
claroline/Distribution | plugin/result/Repository/ResultRepository.php | ResultRepository.findByUserAndWorkspace | public function findByUserAndWorkspace(User $user, Workspace $workspace)
{
$dql = '
SELECT
n.name AS title,
m.value AS mark,
r.total AS total
FROM Claroline\ResultBundle\Entity\Result r
JOIN r.resourceNode n
JOIN n.workspace w
JOIN r.marks m
JOIN m.user u
WHERE w = :workspace
AND u = :user
ORDER BY n.creationDate DESC, n.id
';
$query = $this->_em->createQuery($dql);
$query->setParameters([
'workspace' => $workspace,
'user' => $user,
]);
return $query->getArrayResult();
} | php | public function findByUserAndWorkspace(User $user, Workspace $workspace)
{
$dql = '
SELECT
n.name AS title,
m.value AS mark,
r.total AS total
FROM Claroline\ResultBundle\Entity\Result r
JOIN r.resourceNode n
JOIN n.workspace w
JOIN r.marks m
JOIN m.user u
WHERE w = :workspace
AND u = :user
ORDER BY n.creationDate DESC, n.id
';
$query = $this->_em->createQuery($dql);
$query->setParameters([
'workspace' => $workspace,
'user' => $user,
]);
return $query->getArrayResult();
} | [
"public",
"function",
"findByUserAndWorkspace",
"(",
"User",
"$",
"user",
",",
"Workspace",
"$",
"workspace",
")",
"{",
"$",
"dql",
"=",
"'\n SELECT\n n.name AS title,\n m.value AS mark,\n r.total AS total\n FROM Clar... | Returns an array representation of all the results associated
with a user in a given workspace.
@param User $user
@param Workspace $workspace
@return array | [
"Returns",
"an",
"array",
"representation",
"of",
"all",
"the",
"results",
"associated",
"with",
"a",
"user",
"in",
"a",
"given",
"workspace",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/result/Repository/ResultRepository.php#L29-L53 | train |
claroline/Distribution | main/core/API/Serializer/Resource/ResourceEvaluationSerializer.php | ResourceEvaluationSerializer.serialize | public function serialize(ResourceEvaluation $resourceEvaluation)
{
$serialized = [
'id' => $resourceEvaluation->getId(),
'date' => $resourceEvaluation->getDate() ? $resourceEvaluation->getDate()->format('Y-m-d H:i') : null,
'status' => $resourceEvaluation->getStatus(),
'duration' => $resourceEvaluation->getDuration(),
'score' => $resourceEvaluation->getScore(),
'scoreMin' => $resourceEvaluation->getScoreMin(),
'scoreMax' => $resourceEvaluation->getScoreMax(),
'customScore' => $resourceEvaluation->getCustomScore(),
'progression' => $resourceEvaluation->getProgression(),
'comment' => $resourceEvaluation->getComment(),
'data' => $resourceEvaluation->getData(),
'resourceUserEvaluation' => $this->resourceUserEvaluationSerializer->serialize($resourceEvaluation->getResourceUserEvaluation()),
];
return $serialized;
} | php | public function serialize(ResourceEvaluation $resourceEvaluation)
{
$serialized = [
'id' => $resourceEvaluation->getId(),
'date' => $resourceEvaluation->getDate() ? $resourceEvaluation->getDate()->format('Y-m-d H:i') : null,
'status' => $resourceEvaluation->getStatus(),
'duration' => $resourceEvaluation->getDuration(),
'score' => $resourceEvaluation->getScore(),
'scoreMin' => $resourceEvaluation->getScoreMin(),
'scoreMax' => $resourceEvaluation->getScoreMax(),
'customScore' => $resourceEvaluation->getCustomScore(),
'progression' => $resourceEvaluation->getProgression(),
'comment' => $resourceEvaluation->getComment(),
'data' => $resourceEvaluation->getData(),
'resourceUserEvaluation' => $this->resourceUserEvaluationSerializer->serialize($resourceEvaluation->getResourceUserEvaluation()),
];
return $serialized;
} | [
"public",
"function",
"serialize",
"(",
"ResourceEvaluation",
"$",
"resourceEvaluation",
")",
"{",
"$",
"serialized",
"=",
"[",
"'id'",
"=>",
"$",
"resourceEvaluation",
"->",
"getId",
"(",
")",
",",
"'date'",
"=>",
"$",
"resourceEvaluation",
"->",
"getDate",
"... | Serializes a ResourceEvaluation entity for the JSON api.
@param ResourceEvaluation $resourceEvaluation
@return array - the serialized representation of the resource evaluation | [
"Serializes",
"a",
"ResourceEvaluation",
"entity",
"for",
"the",
"JSON",
"api",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/API/Serializer/Resource/ResourceEvaluationSerializer.php#L37-L55 | train |
claroline/Distribution | plugin/competency/Manager/ResourceManager.php | ResourceManager.loadLinkedCompetencies | public function loadLinkedCompetencies(ResourceNode $resource)
{
$abilities = $this->abilityRepo->findByResource($resource);
$competencies = $this->competencyRepo->findByResource($resource);
$result = [];
foreach ($abilities as $ability) {
$result[] = $this->loadAbility($ability);
}
foreach ($competencies as $competency) {
$result[] = $this->loadCompetency($competency);
}
return $result;
} | php | public function loadLinkedCompetencies(ResourceNode $resource)
{
$abilities = $this->abilityRepo->findByResource($resource);
$competencies = $this->competencyRepo->findByResource($resource);
$result = [];
foreach ($abilities as $ability) {
$result[] = $this->loadAbility($ability);
}
foreach ($competencies as $competency) {
$result[] = $this->loadCompetency($competency);
}
return $result;
} | [
"public",
"function",
"loadLinkedCompetencies",
"(",
"ResourceNode",
"$",
"resource",
")",
"{",
"$",
"abilities",
"=",
"$",
"this",
"->",
"abilityRepo",
"->",
"findByResource",
"(",
"$",
"resource",
")",
";",
"$",
"competencies",
"=",
"$",
"this",
"->",
"com... | Returns an array representation of all the competencies and abilities
linked to a given resource, along with their path in their competency
framework. Competencies and abilities are distinguished from each other
by the "type" key.
@param ResourceNode $resource
@return array | [
"Returns",
"an",
"array",
"representation",
"of",
"all",
"the",
"competencies",
"and",
"abilities",
"linked",
"to",
"a",
"given",
"resource",
"along",
"with",
"their",
"path",
"in",
"their",
"competency",
"framework",
".",
"Competencies",
"and",
"abilities",
"ar... | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/competency/Manager/ResourceManager.php#L44-L59 | train |
claroline/Distribution | plugin/competency/Manager/ResourceManager.php | ResourceManager.removeLink | public function removeLink(ResourceNode $resource, $target)
{
if (!$target instanceof Ability && !$target instanceof Competency) {
throw new \InvalidArgumentException(
'Second argument must be a Competency or an Ability instance'
);
}
if (!$target->isLinkedToResource($resource)) {
throw new \LogicException(
"There's no link between resource {$resource->getId()} and target {$target->getId()}"
);
}
$target->removeResource($resource);
$this->om->flush();
} | php | public function removeLink(ResourceNode $resource, $target)
{
if (!$target instanceof Ability && !$target instanceof Competency) {
throw new \InvalidArgumentException(
'Second argument must be a Competency or an Ability instance'
);
}
if (!$target->isLinkedToResource($resource)) {
throw new \LogicException(
"There's no link between resource {$resource->getId()} and target {$target->getId()}"
);
}
$target->removeResource($resource);
$this->om->flush();
} | [
"public",
"function",
"removeLink",
"(",
"ResourceNode",
"$",
"resource",
",",
"$",
"target",
")",
"{",
"if",
"(",
"!",
"$",
"target",
"instanceof",
"Ability",
"&&",
"!",
"$",
"target",
"instanceof",
"Competency",
")",
"{",
"throw",
"new",
"\\",
"InvalidAr... | Removes a link between a resource and an ability or a competency.
@param ResourceNode $resource
@param Ability|Competency $target
@throws \InvalidArgumentException if the target isn't an instance of Ability or Competency
@throws \LogicException if the link doesn't exists | [
"Removes",
"a",
"link",
"between",
"a",
"resource",
"and",
"an",
"ability",
"or",
"a",
"competency",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/competency/Manager/ResourceManager.php#L102-L118 | train |
claroline/Distribution | main/core/API/Serializer/Resource/ResourceNodeSerializer.php | ResourceNodeSerializer.serialize | public function serialize(ResourceNode $resourceNode, array $options = [])
{
$serializedNode = [
//also used for the export. It's not pretty.
'autoId' => $resourceNode->getId(),
'id' => $resourceNode->getUuid(),
'name' => $resourceNode->getName(),
'path' => $resourceNode->getAncestors(),
'meta' => $this->serializeMeta($resourceNode, $options),
'permissions' => $this->rightsManager->getCurrentPermissionArray($resourceNode),
'poster' => $this->serializePoster($resourceNode),
'thumbnail' => $this->serializeThumbnail($resourceNode),
// TODO : it should not be available in minimal mode
// for now I need it to compute simple access rights (for display)
// we should compute simple access here to avoid exposing this big object
'rights' => $this->rightsManager->getRights($resourceNode, $options),
];
// TODO : it should not (I think) be available in minimal mode
// for now I need it to compute rights
if ($resourceNode->getWorkspace() && !in_array(Options::REFRESH_UUID, $options)) {
$serializedNode['workspace'] = [ // TODO : use workspace serializer with minimal option
'id' => $resourceNode->getWorkspace()->getUuid(),
'autoId' => $resourceNode->getWorkspace()->getId(), // because open url does not work with uuid
'name' => $resourceNode->getWorkspace()->getName(),
'code' => $resourceNode->getWorkspace()->getCode(),
];
}
if (!in_array(Options::SERIALIZE_MINIMAL, $options)) {
$serializedNode = array_merge($serializedNode, [
'display' => $this->serializeDisplay($resourceNode),
'restrictions' => $this->serializeRestrictions($resourceNode),
]);
}
//maybe don't remove me, it's used by the export system
$parent = $resourceNode->getParent();
if (!empty($parent)) {
$serializedNode['parent'] = [
'id' => $parent->getUuid(),
'autoId' => $parent->getId(), // TODO : remove me
'name' => $parent->getName(),
];
}
if (!in_array(Options::SERIALIZE_MINIMAL, $options)) {
$serializedNode['comments'] = array_map(function (ResourceComment $comment) {
return $this->serializer->serialize($comment);
}, $resourceNode->getComments()->toArray());
}
$serializedNode = $this->decorate($resourceNode, $serializedNode, $options);
return $serializedNode;
} | php | public function serialize(ResourceNode $resourceNode, array $options = [])
{
$serializedNode = [
//also used for the export. It's not pretty.
'autoId' => $resourceNode->getId(),
'id' => $resourceNode->getUuid(),
'name' => $resourceNode->getName(),
'path' => $resourceNode->getAncestors(),
'meta' => $this->serializeMeta($resourceNode, $options),
'permissions' => $this->rightsManager->getCurrentPermissionArray($resourceNode),
'poster' => $this->serializePoster($resourceNode),
'thumbnail' => $this->serializeThumbnail($resourceNode),
// TODO : it should not be available in minimal mode
// for now I need it to compute simple access rights (for display)
// we should compute simple access here to avoid exposing this big object
'rights' => $this->rightsManager->getRights($resourceNode, $options),
];
// TODO : it should not (I think) be available in minimal mode
// for now I need it to compute rights
if ($resourceNode->getWorkspace() && !in_array(Options::REFRESH_UUID, $options)) {
$serializedNode['workspace'] = [ // TODO : use workspace serializer with minimal option
'id' => $resourceNode->getWorkspace()->getUuid(),
'autoId' => $resourceNode->getWorkspace()->getId(), // because open url does not work with uuid
'name' => $resourceNode->getWorkspace()->getName(),
'code' => $resourceNode->getWorkspace()->getCode(),
];
}
if (!in_array(Options::SERIALIZE_MINIMAL, $options)) {
$serializedNode = array_merge($serializedNode, [
'display' => $this->serializeDisplay($resourceNode),
'restrictions' => $this->serializeRestrictions($resourceNode),
]);
}
//maybe don't remove me, it's used by the export system
$parent = $resourceNode->getParent();
if (!empty($parent)) {
$serializedNode['parent'] = [
'id' => $parent->getUuid(),
'autoId' => $parent->getId(), // TODO : remove me
'name' => $parent->getName(),
];
}
if (!in_array(Options::SERIALIZE_MINIMAL, $options)) {
$serializedNode['comments'] = array_map(function (ResourceComment $comment) {
return $this->serializer->serialize($comment);
}, $resourceNode->getComments()->toArray());
}
$serializedNode = $this->decorate($resourceNode, $serializedNode, $options);
return $serializedNode;
} | [
"public",
"function",
"serialize",
"(",
"ResourceNode",
"$",
"resourceNode",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"serializedNode",
"=",
"[",
"//also used for the export. It's not pretty.",
"'autoId'",
"=>",
"$",
"resourceNode",
"->",
"getId... | Serializes a ResourceNode entity for the JSON api.
@param ResourceNode $resourceNode - the node to serialize
@param array $options
@return array - the serialized representation of the node | [
"Serializes",
"a",
"ResourceNode",
"entity",
"for",
"the",
"JSON",
"api",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/API/Serializer/Resource/ResourceNodeSerializer.php#L109-L166 | train |
claroline/Distribution | main/core/API/Serializer/Resource/ResourceNodeSerializer.php | ResourceNodeSerializer.decorate | private function decorate(ResourceNode $resourceNode, array $serializedNode, array $options = [])
{
// avoid plugins override the standard node properties
$unauthorizedKeys = array_keys($serializedNode);
// 'thumbnail' is a key that can be overridden by another plugin. For example: UrlBundle
// TODO : find a cleaner way to do it
if (false !== ($key = array_search('thumbnail', $unauthorizedKeys))) {
unset($unauthorizedKeys[$key]);
}
/** @var DecorateResourceNodeEvent $event */
$event = $this->eventDispatcher->dispatch(
'serialize_resource_node',
'Resource\DecorateResourceNode',
[
$resourceNode,
$unauthorizedKeys,
$options,
]
);
return array_merge($serializedNode, $event->getInjectedData());
} | php | private function decorate(ResourceNode $resourceNode, array $serializedNode, array $options = [])
{
// avoid plugins override the standard node properties
$unauthorizedKeys = array_keys($serializedNode);
// 'thumbnail' is a key that can be overridden by another plugin. For example: UrlBundle
// TODO : find a cleaner way to do it
if (false !== ($key = array_search('thumbnail', $unauthorizedKeys))) {
unset($unauthorizedKeys[$key]);
}
/** @var DecorateResourceNodeEvent $event */
$event = $this->eventDispatcher->dispatch(
'serialize_resource_node',
'Resource\DecorateResourceNode',
[
$resourceNode,
$unauthorizedKeys,
$options,
]
);
return array_merge($serializedNode, $event->getInjectedData());
} | [
"private",
"function",
"decorate",
"(",
"ResourceNode",
"$",
"resourceNode",
",",
"array",
"$",
"serializedNode",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// avoid plugins override the standard node properties",
"$",
"unauthorizedKeys",
"=",
"array_keys... | Dispatches an event to let plugins add some custom data to the serialized node.
For example, SocialMedia adds the number of likes.
@param ResourceNode $resourceNode - the original node entity
@param array $serializedNode - the serialized version of the node
@param array $options
@return array - the decorated node | [
"Dispatches",
"an",
"event",
"to",
"let",
"plugins",
"add",
"some",
"custom",
"data",
"to",
"the",
"serialized",
"node",
".",
"For",
"example",
"SocialMedia",
"adds",
"the",
"number",
"of",
"likes",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/API/Serializer/Resource/ResourceNodeSerializer.php#L178-L201 | train |
claroline/Distribution | main/core/API/Serializer/Resource/ResourceNodeSerializer.php | ResourceNodeSerializer.serializePoster | private function serializePoster(ResourceNode $resourceNode)
{
if (!empty($resourceNode->getPoster())) {
/** @var PublicFile $file */
$file = $this->om
->getRepository(PublicFile::class)
->findOneBy(['url' => $resourceNode->getPoster()]);
if ($file) {
return $this->fileSerializer->serialize($file);
}
}
return null;
} | php | private function serializePoster(ResourceNode $resourceNode)
{
if (!empty($resourceNode->getPoster())) {
/** @var PublicFile $file */
$file = $this->om
->getRepository(PublicFile::class)
->findOneBy(['url' => $resourceNode->getPoster()]);
if ($file) {
return $this->fileSerializer->serialize($file);
}
}
return null;
} | [
"private",
"function",
"serializePoster",
"(",
"ResourceNode",
"$",
"resourceNode",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"resourceNode",
"->",
"getPoster",
"(",
")",
")",
")",
"{",
"/** @var PublicFile $file */",
"$",
"file",
"=",
"$",
"this",
"->",
... | Serialize the resource poster.
@param ResourceNode $resourceNode
@return array|null | [
"Serialize",
"the",
"resource",
"poster",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/API/Serializer/Resource/ResourceNodeSerializer.php#L210-L224 | train |
claroline/Distribution | main/core/API/Serializer/Resource/ResourceNodeSerializer.php | ResourceNodeSerializer.serializeThumbnail | private function serializeThumbnail(ResourceNode $resourceNode)
{
if (!empty($resourceNode->getThumbnail())) {
/** @var PublicFile $file */
$file = $this->om
->getRepository(PublicFile::class)
->findOneBy(['url' => $resourceNode->getThumbnail()]);
if ($file) {
return $this->fileSerializer->serialize($file);
}
}
return null;
} | php | private function serializeThumbnail(ResourceNode $resourceNode)
{
if (!empty($resourceNode->getThumbnail())) {
/** @var PublicFile $file */
$file = $this->om
->getRepository(PublicFile::class)
->findOneBy(['url' => $resourceNode->getThumbnail()]);
if ($file) {
return $this->fileSerializer->serialize($file);
}
}
return null;
} | [
"private",
"function",
"serializeThumbnail",
"(",
"ResourceNode",
"$",
"resourceNode",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"resourceNode",
"->",
"getThumbnail",
"(",
")",
")",
")",
"{",
"/** @var PublicFile $file */",
"$",
"file",
"=",
"$",
"this",
... | Serialize the resource thumbnail.
@param ResourceNode $resourceNode
@return array|null | [
"Serialize",
"the",
"resource",
"thumbnail",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/API/Serializer/Resource/ResourceNodeSerializer.php#L233-L247 | train |
claroline/Distribution | main/core/Listener/Administration/ScheduledTaskListener.php | ScheduledTaskListener.onDisplayTool | public function onDisplayTool(OpenAdministrationToolEvent $event)
{
$content = $this->templating->render(
'ClarolineCoreBundle:administration:scheduled_tasks.html.twig', [
'isCronConfigured' => $this->configHandler->hasParameter('is_cron_configured') && $this->configHandler->getParameter('is_cron_configured'),
]
);
$event->setResponse(new Response($content));
$event->stopPropagation();
} | php | public function onDisplayTool(OpenAdministrationToolEvent $event)
{
$content = $this->templating->render(
'ClarolineCoreBundle:administration:scheduled_tasks.html.twig', [
'isCronConfigured' => $this->configHandler->hasParameter('is_cron_configured') && $this->configHandler->getParameter('is_cron_configured'),
]
);
$event->setResponse(new Response($content));
$event->stopPropagation();
} | [
"public",
"function",
"onDisplayTool",
"(",
"OpenAdministrationToolEvent",
"$",
"event",
")",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"templating",
"->",
"render",
"(",
"'ClarolineCoreBundle:administration:scheduled_tasks.html.twig'",
",",
"[",
"'isCronConfigured'",
... | Displays scheduled tasks administration tool.
@DI\Observe("administration_tool_tasks_scheduling")
@param OpenAdministrationToolEvent $event | [
"Displays",
"scheduled",
"tasks",
"administration",
"tool",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Listener/Administration/ScheduledTaskListener.php#L50-L60 | train |
claroline/Distribution | plugin/announcement/Listener/Resource/AnnouncementListener.php | AnnouncementListener.load | public function load(LoadResourceEvent $event)
{
$resource = $event->getResource();
$workspace = $resource->getResourceNode()->getWorkspace();
$event->setData([
'announcement' => $this->serializer->serialize($resource),
'workspaceRoles' => array_map(function (Role $role) {
return $this->serializer->serialize($role, [Options::SERIALIZE_MINIMAL]);
}, $workspace->getRoles()->toArray()),
]);
$event->stopPropagation();
} | php | public function load(LoadResourceEvent $event)
{
$resource = $event->getResource();
$workspace = $resource->getResourceNode()->getWorkspace();
$event->setData([
'announcement' => $this->serializer->serialize($resource),
'workspaceRoles' => array_map(function (Role $role) {
return $this->serializer->serialize($role, [Options::SERIALIZE_MINIMAL]);
}, $workspace->getRoles()->toArray()),
]);
$event->stopPropagation();
} | [
"public",
"function",
"load",
"(",
"LoadResourceEvent",
"$",
"event",
")",
"{",
"$",
"resource",
"=",
"$",
"event",
"->",
"getResource",
"(",
")",
";",
"$",
"workspace",
"=",
"$",
"resource",
"->",
"getResourceNode",
"(",
")",
"->",
"getWorkspace",
"(",
... | Loads an Announcement resource.
@DI\Observe("resource.claroline_announcement_aggregate.load")
@param LoadResourceEvent $event | [
"Loads",
"an",
"Announcement",
"resource",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/announcement/Listener/Resource/AnnouncementListener.php#L88-L101 | train |
claroline/Distribution | plugin/dropzone/Manager/CorrectionManager.php | CorrectionManager.calculateCorrectionTotalGrade | public function calculateCorrectionTotalGrade(Dropzone $dropzone, Correction $correction)
{
$nbCriteria = count($dropzone->getPeerReviewCriteria());
$maxGrade = $dropzone->getTotalCriteriaColumn() - 1;
$sumGrades = 0;
foreach ($correction->getGrades() as $grade) {
($grade->getValue() > $maxGrade) ? $sumGrades += $maxGrade : $sumGrades += $grade->getValue();
}
$totalGrade = 0;
if (0 !== $nbCriteria) {
$totalGrade = $sumGrades / ($nbCriteria);
$totalGrade = ($totalGrade * 20) / ($maxGrade);
}
return $totalGrade;
} | php | public function calculateCorrectionTotalGrade(Dropzone $dropzone, Correction $correction)
{
$nbCriteria = count($dropzone->getPeerReviewCriteria());
$maxGrade = $dropzone->getTotalCriteriaColumn() - 1;
$sumGrades = 0;
foreach ($correction->getGrades() as $grade) {
($grade->getValue() > $maxGrade) ? $sumGrades += $maxGrade : $sumGrades += $grade->getValue();
}
$totalGrade = 0;
if (0 !== $nbCriteria) {
$totalGrade = $sumGrades / ($nbCriteria);
$totalGrade = ($totalGrade * 20) / ($maxGrade);
}
return $totalGrade;
} | [
"public",
"function",
"calculateCorrectionTotalGrade",
"(",
"Dropzone",
"$",
"dropzone",
",",
"Correction",
"$",
"correction",
")",
"{",
"$",
"nbCriteria",
"=",
"count",
"(",
"$",
"dropzone",
"->",
"getPeerReviewCriteria",
"(",
")",
")",
";",
"$",
"maxGrade",
... | Calculate the grad of a copy.
@param Dropzone $dropzone
@param Correction $correction
@return float|int | [
"Calculate",
"the",
"grad",
"of",
"a",
"copy",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/dropzone/Manager/CorrectionManager.php#L42-L58 | train |
claroline/Distribution | plugin/exo/Manager/AttemptManager.php | AttemptManager.canPass | public function canPass(Exercise $exercise, User $user = null)
{
// TODO : max attempts by day
$canPass = true;
if ($user) {
$max = $exercise->getMaxAttempts();
if ($max > 0) {
$nbFinishedPapers = $this->paperManager->countUserFinishedPapers($exercise, $user);
if ($nbFinishedPapers >= $max) {
$canPass = false;
}
}
}
return $canPass;
} | php | public function canPass(Exercise $exercise, User $user = null)
{
// TODO : max attempts by day
$canPass = true;
if ($user) {
$max = $exercise->getMaxAttempts();
if ($max > 0) {
$nbFinishedPapers = $this->paperManager->countUserFinishedPapers($exercise, $user);
if ($nbFinishedPapers >= $max) {
$canPass = false;
}
}
}
return $canPass;
} | [
"public",
"function",
"canPass",
"(",
"Exercise",
"$",
"exercise",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"// TODO : max attempts by day",
"$",
"canPass",
"=",
"true",
";",
"if",
"(",
"$",
"user",
")",
"{",
"$",
"max",
"=",
"$",
"exercise",
"... | Checks if a user is allowed to pass a quiz or not.
Based on the maximum attempt allowed and the number of already done by the user.
@param Exercise $exercise
@param User $user
@return bool | [
"Checks",
"if",
"a",
"user",
"is",
"allowed",
"to",
"pass",
"a",
"quiz",
"or",
"not",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Manager/AttemptManager.php#L108-L124 | train |
claroline/Distribution | plugin/exo/Manager/AttemptManager.php | AttemptManager.canUpdate | public function canUpdate(Paper $paper, User $user = null)
{
return empty($paper->getEnd())
&& $user === $paper->getUser();
} | php | public function canUpdate(Paper $paper, User $user = null)
{
return empty($paper->getEnd())
&& $user === $paper->getUser();
} | [
"public",
"function",
"canUpdate",
"(",
"Paper",
"$",
"paper",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"return",
"empty",
"(",
"$",
"paper",
"->",
"getEnd",
"(",
")",
")",
"&&",
"$",
"user",
"===",
"$",
"paper",
"->",
"getUser",
"(",
")",
... | Checks if a user can submit answers to a paper or use hints.
A user can submit to a paper only if it is its own and the paper is not closed (= no end).
ATTENTION : As is, anonymous have access to all the other anonymous Papers !!!
@param Paper $paper
@param User $user
@return bool | [
"Checks",
"if",
"a",
"user",
"can",
"submit",
"answers",
"to",
"a",
"paper",
"or",
"use",
"hints",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Manager/AttemptManager.php#L158-L162 | train |
claroline/Distribution | plugin/exo/Manager/AttemptManager.php | AttemptManager.startOrContinue | public function startOrContinue(Exercise $exercise, User $user = null)
{
$paper = null; // The paper to use for the new attempt
// If it's not an anonymous, load the previous unfinished papers
$unfinishedPapers = (null !== $user) ? $this->paperRepository->findUnfinishedPapers($exercise, $user) : [];
if (!empty($unfinishedPapers)) {
if ($exercise->isInterruptible()) {
// Continue a previous attempt
$paper = $unfinishedPapers[0];
} else {
// Close the paper
$this->end($unfinishedPapers[0], false);
}
}
// Start a new attempt is needed
if (empty($paper)) {
// Get the last paper for generation
$lastPaper = $this->getLastPaper($exercise, $user);
// Generate a new paper
$paper = $this->paperGenerator->create($exercise, $user, $lastPaper);
// Save the new paper
$this->om->persist($paper);
$this->om->flush();
}
return $paper;
} | php | public function startOrContinue(Exercise $exercise, User $user = null)
{
$paper = null; // The paper to use for the new attempt
// If it's not an anonymous, load the previous unfinished papers
$unfinishedPapers = (null !== $user) ? $this->paperRepository->findUnfinishedPapers($exercise, $user) : [];
if (!empty($unfinishedPapers)) {
if ($exercise->isInterruptible()) {
// Continue a previous attempt
$paper = $unfinishedPapers[0];
} else {
// Close the paper
$this->end($unfinishedPapers[0], false);
}
}
// Start a new attempt is needed
if (empty($paper)) {
// Get the last paper for generation
$lastPaper = $this->getLastPaper($exercise, $user);
// Generate a new paper
$paper = $this->paperGenerator->create($exercise, $user, $lastPaper);
// Save the new paper
$this->om->persist($paper);
$this->om->flush();
}
return $paper;
} | [
"public",
"function",
"startOrContinue",
"(",
"Exercise",
"$",
"exercise",
",",
"User",
"$",
"user",
"=",
"null",
")",
"{",
"$",
"paper",
"=",
"null",
";",
"// The paper to use for the new attempt",
"// If it's not an anonymous, load the previous unfinished papers",
"$",
... | Starts or continues an exercise paper.
Returns an unfinished paper if the user has one (and exercise allows continue)
or creates a new paper in the other cases.
Note : an anonymous user will never be able to continue a paper
@param Exercise $exercise - the exercise to play
@param User $user - the user who wants to play the exercise
@return Paper - a new paper or an unfinished one | [
"Starts",
"or",
"continues",
"an",
"exercise",
"paper",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Manager/AttemptManager.php#L176-L206 | train |
claroline/Distribution | plugin/exo/Manager/AttemptManager.php | AttemptManager.submit | public function submit(Paper $paper, array $answers, $clientIp)
{
$submitted = [];
$this->om->startFlushSuite();
foreach ($answers as $answerData) {
$question = $paper->getQuestion($answerData['questionId']);
if (empty($question)) {
throw new InvalidDataException('Submitted answers are invalid', [[
'path' => '/questionId',
'message' => 'question is not part of the attempt',
]]);
}
$existingAnswer = $paper->getAnswer($answerData['questionId']);
$decodedQuestion = $this->itemSerializer->deserialize($question, new Item());
try {
if (empty($existingAnswer)) {
$answer = $this->answerManager->create($decodedQuestion, $answerData);
} else {
$answer = $this->answerManager->update($decodedQuestion, $existingAnswer, $answerData);
}
} catch (InvalidDataException $e) {
throw new InvalidDataException('Submitted answers are invalid', $e->getErrors());
}
$answer->setIp($clientIp);
$answer->setTries($answer->getTries() + 1);
// Calculate new answer score
$score = $this->itemManager->calculateScore($decodedQuestion, $answer);
$answer->setScore($score);
$paper->addAnswer($answer);
$submitted[] = $answer;
}
$this->om->persist($paper);
$this->om->endFlushSuite();
return $submitted;
} | php | public function submit(Paper $paper, array $answers, $clientIp)
{
$submitted = [];
$this->om->startFlushSuite();
foreach ($answers as $answerData) {
$question = $paper->getQuestion($answerData['questionId']);
if (empty($question)) {
throw new InvalidDataException('Submitted answers are invalid', [[
'path' => '/questionId',
'message' => 'question is not part of the attempt',
]]);
}
$existingAnswer = $paper->getAnswer($answerData['questionId']);
$decodedQuestion = $this->itemSerializer->deserialize($question, new Item());
try {
if (empty($existingAnswer)) {
$answer = $this->answerManager->create($decodedQuestion, $answerData);
} else {
$answer = $this->answerManager->update($decodedQuestion, $existingAnswer, $answerData);
}
} catch (InvalidDataException $e) {
throw new InvalidDataException('Submitted answers are invalid', $e->getErrors());
}
$answer->setIp($clientIp);
$answer->setTries($answer->getTries() + 1);
// Calculate new answer score
$score = $this->itemManager->calculateScore($decodedQuestion, $answer);
$answer->setScore($score);
$paper->addAnswer($answer);
$submitted[] = $answer;
}
$this->om->persist($paper);
$this->om->endFlushSuite();
return $submitted;
} | [
"public",
"function",
"submit",
"(",
"Paper",
"$",
"paper",
",",
"array",
"$",
"answers",
",",
"$",
"clientIp",
")",
"{",
"$",
"submitted",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"om",
"->",
"startFlushSuite",
"(",
")",
";",
"foreach",
"(",
"$",
"a... | Submits user answers to a paper.
@param Paper $paper
@param array $answers
@param string $clientIp
@throws InvalidDataException - if there is any invalid answer
@return Answer[] | [
"Submits",
"user",
"answers",
"to",
"a",
"paper",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Manager/AttemptManager.php#L228-L272 | train |
claroline/Distribution | plugin/exo/Manager/AttemptManager.php | AttemptManager.end | public function end(Paper $paper, $finished = true, $generateEvaluation = true)
{
$this->om->startFlushSuite();
if (!$paper->getEnd()) {
$paper->setEnd(new \DateTime());
}
$paper->setInterrupted(!$finished);
$totalScoreOn = $paper->getExercise()->getTotalScoreOn();
$score = $this->paperManager->calculateScore($paper, $totalScoreOn);
$paper->setScore($score);
if ($generateEvaluation) {
$this->paperManager->generateResourceEvaluation($paper, $finished);
}
$this->om->persist($paper);
$this->om->endFlushSuite();
$this->paperManager->checkPaperEvaluated($paper);
} | php | public function end(Paper $paper, $finished = true, $generateEvaluation = true)
{
$this->om->startFlushSuite();
if (!$paper->getEnd()) {
$paper->setEnd(new \DateTime());
}
$paper->setInterrupted(!$finished);
$totalScoreOn = $paper->getExercise()->getTotalScoreOn();
$score = $this->paperManager->calculateScore($paper, $totalScoreOn);
$paper->setScore($score);
if ($generateEvaluation) {
$this->paperManager->generateResourceEvaluation($paper, $finished);
}
$this->om->persist($paper);
$this->om->endFlushSuite();
$this->paperManager->checkPaperEvaluated($paper);
} | [
"public",
"function",
"end",
"(",
"Paper",
"$",
"paper",
",",
"$",
"finished",
"=",
"true",
",",
"$",
"generateEvaluation",
"=",
"true",
")",
"{",
"$",
"this",
"->",
"om",
"->",
"startFlushSuite",
"(",
")",
";",
"if",
"(",
"!",
"$",
"paper",
"->",
... | Ends a user paper.
Sets the end date of the paper and calculates its score.
@param Paper $paper
@param bool $finished
@param bool $generateEvaluation | [
"Ends",
"a",
"user",
"paper",
".",
"Sets",
"the",
"end",
"date",
"of",
"the",
"paper",
"and",
"calculates",
"its",
"score",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Manager/AttemptManager.php#L282-L302 | train |
claroline/Distribution | plugin/exo/Manager/AttemptManager.php | AttemptManager.useHint | public function useHint(Paper $paper, $questionId, $hintId, $clientIp)
{
$question = $paper->getQuestion($questionId);
if (empty($question)) {
throw new \LogicException("Question {$questionId} and paper {$paper->getId()} are not related");
}
$hint = null;
foreach ($question['hints'] as $questionHint) {
if ($hintId === $questionHint['id']) {
$hint = $questionHint;
break;
}
}
if (empty($hint)) {
// Hint is not related to a question of the current attempt
throw new \LogicException("Hint {$hintId} and paper {$paper->getId()} are not related");
}
// Retrieve or create the answer for the question
$answer = $paper->getAnswer($question['id']);
if (empty($answer)) {
$answer = new Answer();
$answer->setTries(0); // Using an hint is not a try. This will be updated when user will submit his answer
$answer->setQuestionId($question['id']);
$answer->setIp($clientIp);
// Link the new answer to the paper
$paper->addAnswer($answer);
}
$answer->addUsedHint($hintId);
// Calculate new answer score
$decodedQuestion = $this->itemSerializer->deserialize($question, new Item());
$score = $this->itemManager->calculateScore($decodedQuestion, $answer);
$answer->setScore($score);
$this->om->persist($answer);
$this->om->flush();
return $hint;
} | php | public function useHint(Paper $paper, $questionId, $hintId, $clientIp)
{
$question = $paper->getQuestion($questionId);
if (empty($question)) {
throw new \LogicException("Question {$questionId} and paper {$paper->getId()} are not related");
}
$hint = null;
foreach ($question['hints'] as $questionHint) {
if ($hintId === $questionHint['id']) {
$hint = $questionHint;
break;
}
}
if (empty($hint)) {
// Hint is not related to a question of the current attempt
throw new \LogicException("Hint {$hintId} and paper {$paper->getId()} are not related");
}
// Retrieve or create the answer for the question
$answer = $paper->getAnswer($question['id']);
if (empty($answer)) {
$answer = new Answer();
$answer->setTries(0); // Using an hint is not a try. This will be updated when user will submit his answer
$answer->setQuestionId($question['id']);
$answer->setIp($clientIp);
// Link the new answer to the paper
$paper->addAnswer($answer);
}
$answer->addUsedHint($hintId);
// Calculate new answer score
$decodedQuestion = $this->itemSerializer->deserialize($question, new Item());
$score = $this->itemManager->calculateScore($decodedQuestion, $answer);
$answer->setScore($score);
$this->om->persist($answer);
$this->om->flush();
return $hint;
} | [
"public",
"function",
"useHint",
"(",
"Paper",
"$",
"paper",
",",
"$",
"questionId",
",",
"$",
"hintId",
",",
"$",
"clientIp",
")",
"{",
"$",
"question",
"=",
"$",
"paper",
"->",
"getQuestion",
"(",
"$",
"questionId",
")",
";",
"if",
"(",
"empty",
"(... | Flags an hint has used in the user paper and returns the hint content.
@param Paper $paper
@param string $questionId
@param string $hintId
@param string $clientIp
@return mixed | [
"Flags",
"an",
"hint",
"has",
"used",
"in",
"the",
"user",
"paper",
"and",
"returns",
"the",
"hint",
"content",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Manager/AttemptManager.php#L314-L360 | train |
claroline/Distribution | plugin/exo/Serializer/Misc/KeywordSerializer.php | KeywordSerializer.serialize | public function serialize(Keyword $keyword, array $options = [])
{
$serialized = [
'text' => $keyword->getText(),
'caseSensitive' => $keyword->isCaseSensitive(),
'score' => $keyword->getScore(),
];
if ($keyword->getFeedback()) {
$serialized['feedback'] = $keyword->getFeedback();
}
return $serialized;
} | php | public function serialize(Keyword $keyword, array $options = [])
{
$serialized = [
'text' => $keyword->getText(),
'caseSensitive' => $keyword->isCaseSensitive(),
'score' => $keyword->getScore(),
];
if ($keyword->getFeedback()) {
$serialized['feedback'] = $keyword->getFeedback();
}
return $serialized;
} | [
"public",
"function",
"serialize",
"(",
"Keyword",
"$",
"keyword",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"serialized",
"=",
"[",
"'text'",
"=>",
"$",
"keyword",
"->",
"getText",
"(",
")",
",",
"'caseSensitive'",
"=>",
"$",
"keywor... | Converts a Keyword into a JSON-encodable structure.
@param Keyword $keyword
@param array $options
@return array | [
"Converts",
"a",
"Keyword",
"into",
"a",
"JSON",
"-",
"encodable",
"structure",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Serializer/Misc/KeywordSerializer.php#L27-L40 | train |
claroline/Distribution | main/core/Listener/Resource/Types/DirectoryListener.php | DirectoryListener.onAdd | public function onAdd(ResourceActionEvent $event)
{
$data = $event->getData();
$parent = $event->getResourceNode();
$add = $this->actionManager->get($parent, 'add');
// checks if the current user can add
$collection = new ResourceCollection([$parent], ['type' => $data['resourceNode']['meta']['type']]);
if (!$this->actionManager->hasPermission($add, $collection)) {
throw new ResourceAccessException($collection->getErrorsForDisplay(), $collection->getResources());
}
$options = $event->getOptions();
$options[] = Options::IGNORE_CRUD_POST_EVENT;
// create the resource node
/** @var ResourceNode $resourceNode */
$resourceNode = $this->crud->create(ResourceNode::class, $data['resourceNode'], $options);
$resourceNode->setParent($parent);
$resourceNode->setWorkspace($parent->getWorkspace());
// initialize custom resource Entity
$resourceClass = $resourceNode->getResourceType()->getClass();
/** @var AbstractResource $resource */
$resource = $this->crud->create($resourceClass, !empty($data['resource']) ? $data['resource'] : [], $options);
$resource->setResourceNode($resourceNode);
// maybe do it in the serializer (if it can be done without intermediate flush)
if (!empty($data['resourceNode']['rights'])) {
foreach ($data['resourceNode']['rights'] as $rights) {
/** @var Role $role */
$role = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneBy(['name' => $rights['name']]);
$this->rightsManager->editPerms($rights['permissions'], $role, $resourceNode);
}
} else {
// todo : initialize default rights
}
$this->crud->dispatch('create', 'post', [$resource, $options]);
$this->om->persist($resource);
$this->om->persist($resourceNode);
// todo : dispatch creation event
$this->om->flush();
// todo : dispatch get/load action instead
$event->setResponse(new JsonResponse(
[
'resourceNode' => $this->serializer->serialize($resourceNode),
'resource' => $this->serializer->serialize($resource),
],
201
));
} | php | public function onAdd(ResourceActionEvent $event)
{
$data = $event->getData();
$parent = $event->getResourceNode();
$add = $this->actionManager->get($parent, 'add');
// checks if the current user can add
$collection = new ResourceCollection([$parent], ['type' => $data['resourceNode']['meta']['type']]);
if (!$this->actionManager->hasPermission($add, $collection)) {
throw new ResourceAccessException($collection->getErrorsForDisplay(), $collection->getResources());
}
$options = $event->getOptions();
$options[] = Options::IGNORE_CRUD_POST_EVENT;
// create the resource node
/** @var ResourceNode $resourceNode */
$resourceNode = $this->crud->create(ResourceNode::class, $data['resourceNode'], $options);
$resourceNode->setParent($parent);
$resourceNode->setWorkspace($parent->getWorkspace());
// initialize custom resource Entity
$resourceClass = $resourceNode->getResourceType()->getClass();
/** @var AbstractResource $resource */
$resource = $this->crud->create($resourceClass, !empty($data['resource']) ? $data['resource'] : [], $options);
$resource->setResourceNode($resourceNode);
// maybe do it in the serializer (if it can be done without intermediate flush)
if (!empty($data['resourceNode']['rights'])) {
foreach ($data['resourceNode']['rights'] as $rights) {
/** @var Role $role */
$role = $this->om->getRepository('ClarolineCoreBundle:Role')->findOneBy(['name' => $rights['name']]);
$this->rightsManager->editPerms($rights['permissions'], $role, $resourceNode);
}
} else {
// todo : initialize default rights
}
$this->crud->dispatch('create', 'post', [$resource, $options]);
$this->om->persist($resource);
$this->om->persist($resourceNode);
// todo : dispatch creation event
$this->om->flush();
// todo : dispatch get/load action instead
$event->setResponse(new JsonResponse(
[
'resourceNode' => $this->serializer->serialize($resourceNode),
'resource' => $this->serializer->serialize($resource),
],
201
));
} | [
"public",
"function",
"onAdd",
"(",
"ResourceActionEvent",
"$",
"event",
")",
"{",
"$",
"data",
"=",
"$",
"event",
"->",
"getData",
"(",
")",
";",
"$",
"parent",
"=",
"$",
"event",
"->",
"getResourceNode",
"(",
")",
";",
"$",
"add",
"=",
"$",
"this",... | Adds a new resource inside a directory.
@DI\Observe("resource.directory.add")
@param ResourceActionEvent $event | [
"Adds",
"a",
"new",
"resource",
"inside",
"a",
"directory",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Listener/Resource/Types/DirectoryListener.php#L101-L158 | train |
claroline/Distribution | main/core/Listener/Resource/Types/DirectoryListener.php | DirectoryListener.onOpen | public function onOpen(OpenResourceEvent $event)
{
$directory = $event->getResource();
$content = $this->templating->render(
'ClarolineCoreBundle:directory:index.html.twig', [
'directory' => $directory,
'_resource' => $directory,
]
);
$response = new Response($content);
$event->setResponse($response);
$event->stopPropagation();
} | php | public function onOpen(OpenResourceEvent $event)
{
$directory = $event->getResource();
$content = $this->templating->render(
'ClarolineCoreBundle:directory:index.html.twig', [
'directory' => $directory,
'_resource' => $directory,
]
);
$response = new Response($content);
$event->setResponse($response);
$event->stopPropagation();
} | [
"public",
"function",
"onOpen",
"(",
"OpenResourceEvent",
"$",
"event",
")",
"{",
"$",
"directory",
"=",
"$",
"event",
"->",
"getResource",
"(",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"templating",
"->",
"render",
"(",
"'ClarolineCoreBundle:direct... | Opens a directory.
@DI\Observe("open_directory")
@param OpenResourceEvent $event | [
"Opens",
"a",
"directory",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Listener/Resource/Types/DirectoryListener.php#L195-L210 | train |
claroline/Distribution | main/core/Manager/ProgressionManager.php | ProgressionManager.fetchItems | public function fetchItems(Workspace $workspace, User $user = null, $levelMax = 1)
{
$workspaceRoot = $this->finder->get(ResourceNode::class)->find([
'workspace' => $workspace->getUuid(),
'parent' => null,
])[0];
$roles = $user ? $user->getRoles() : ['ROLE_ANONYMOUS'];
$filters = [
'active' => true,
'published' => true,
'hidden' => false,
'resourceTypeEnabled' => true,
'workspace' => $workspace->getUuid(),
];
$sortBy = [
'property' => 'name',
'direction' => 1,
];
if (!in_array('ROLE_ADMIN', $roles)) {
$filters['roles'] = $roles;
}
// Get all resource nodes available for current user in the workspace
$visibleNodes = $this->finder->get(ResourceNode::class)->find($filters);
$filters['parent'] = $workspaceRoot;
// Get all root resource nodes available for current user in the workspace
$rootNodes = $this->finder->get(ResourceNode::class)->find($filters, $sortBy);
$visibleNodesArray = [];
$childrenNodesArray = [];
foreach ($visibleNodes as $node) {
$visibleNodesArray[$node->getUuid()] = $node;
if ($node->getParent()) {
$parentId = $node->getParent()->getUuid();
if (!isset($childrenNodesArray[$parentId])) {
$childrenNodesArray[$parentId] = [];
}
$childrenNodesArray[$parentId][] = $node;
}
}
$items = [];
$this->formatNodes($items, $rootNodes, $visibleNodesArray, $childrenNodesArray, $user, $levelMax, 0);
return $items;
} | php | public function fetchItems(Workspace $workspace, User $user = null, $levelMax = 1)
{
$workspaceRoot = $this->finder->get(ResourceNode::class)->find([
'workspace' => $workspace->getUuid(),
'parent' => null,
])[0];
$roles = $user ? $user->getRoles() : ['ROLE_ANONYMOUS'];
$filters = [
'active' => true,
'published' => true,
'hidden' => false,
'resourceTypeEnabled' => true,
'workspace' => $workspace->getUuid(),
];
$sortBy = [
'property' => 'name',
'direction' => 1,
];
if (!in_array('ROLE_ADMIN', $roles)) {
$filters['roles'] = $roles;
}
// Get all resource nodes available for current user in the workspace
$visibleNodes = $this->finder->get(ResourceNode::class)->find($filters);
$filters['parent'] = $workspaceRoot;
// Get all root resource nodes available for current user in the workspace
$rootNodes = $this->finder->get(ResourceNode::class)->find($filters, $sortBy);
$visibleNodesArray = [];
$childrenNodesArray = [];
foreach ($visibleNodes as $node) {
$visibleNodesArray[$node->getUuid()] = $node;
if ($node->getParent()) {
$parentId = $node->getParent()->getUuid();
if (!isset($childrenNodesArray[$parentId])) {
$childrenNodesArray[$parentId] = [];
}
$childrenNodesArray[$parentId][] = $node;
}
}
$items = [];
$this->formatNodes($items, $rootNodes, $visibleNodesArray, $childrenNodesArray, $user, $levelMax, 0);
return $items;
} | [
"public",
"function",
"fetchItems",
"(",
"Workspace",
"$",
"workspace",
",",
"User",
"$",
"user",
"=",
"null",
",",
"$",
"levelMax",
"=",
"1",
")",
"{",
"$",
"workspaceRoot",
"=",
"$",
"this",
"->",
"finder",
"->",
"get",
"(",
"ResourceNode",
"::",
"cl... | Retrieves list of resource nodes accessible by user and formatted for the progression tool.
@param Workspace $workspace
@param User|null $user
@param int $levelMax
@return array | [
"Retrieves",
"list",
"of",
"resource",
"nodes",
"accessible",
"by",
"user",
"and",
"formatted",
"for",
"the",
"progression",
"tool",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Manager/ProgressionManager.php#L67-L114 | train |
claroline/Distribution | main/core/Manager/ProgressionManager.php | ProgressionManager.formatNodes | private function formatNodes(
array &$items,
array $nodes,
array $visibleNodes,
array $childrenNodes,
User $user = null,
$levelMax = 1,
$level = 0
) {
foreach ($nodes as $node) {
$evaluation = $user ?
$this->resourceEvalManager->getResourceUserEvaluation($node, $user, false) :
null;
$item = $this->serializer->serialize($node, [Options::SERIALIZE_MINIMAL, Options::IS_RECURSIVE]);
$item['level'] = $level;
$item['openingUrl'] = ['claro_resource_show_short', ['id' => $item['id']]];
$item['validated'] = !is_null($evaluation) && 0 < $evaluation->getNbOpenings();
$items[] = $item;
if ((is_null($levelMax) || $level < $levelMax) && isset($childrenNodes[$node->getUuid()])) {
$children = [];
usort($childrenNodes[$node->getUuid()], function ($a, $b) {
return strcmp($a->getName(), $b->getName());
});
foreach ($childrenNodes[$node->getUuid()] as $child) {
// Checks if node is visible
if (isset($visibleNodes[$child->getUuid()])) {
$children[] = $visibleNodes[$child->getUuid()];
}
}
if (0 < count($children)) {
$this->formatNodes($items, $children, $visibleNodes, $childrenNodes, $user, $levelMax, $level + 1);
}
}
}
} | php | private function formatNodes(
array &$items,
array $nodes,
array $visibleNodes,
array $childrenNodes,
User $user = null,
$levelMax = 1,
$level = 0
) {
foreach ($nodes as $node) {
$evaluation = $user ?
$this->resourceEvalManager->getResourceUserEvaluation($node, $user, false) :
null;
$item = $this->serializer->serialize($node, [Options::SERIALIZE_MINIMAL, Options::IS_RECURSIVE]);
$item['level'] = $level;
$item['openingUrl'] = ['claro_resource_show_short', ['id' => $item['id']]];
$item['validated'] = !is_null($evaluation) && 0 < $evaluation->getNbOpenings();
$items[] = $item;
if ((is_null($levelMax) || $level < $levelMax) && isset($childrenNodes[$node->getUuid()])) {
$children = [];
usort($childrenNodes[$node->getUuid()], function ($a, $b) {
return strcmp($a->getName(), $b->getName());
});
foreach ($childrenNodes[$node->getUuid()] as $child) {
// Checks if node is visible
if (isset($visibleNodes[$child->getUuid()])) {
$children[] = $visibleNodes[$child->getUuid()];
}
}
if (0 < count($children)) {
$this->formatNodes($items, $children, $visibleNodes, $childrenNodes, $user, $levelMax, $level + 1);
}
}
}
} | [
"private",
"function",
"formatNodes",
"(",
"array",
"&",
"$",
"items",
",",
"array",
"$",
"nodes",
",",
"array",
"$",
"visibleNodes",
",",
"array",
"$",
"childrenNodes",
",",
"User",
"$",
"user",
"=",
"null",
",",
"$",
"levelMax",
"=",
"1",
",",
"$",
... | Recursive function that filters visible nodes and adds serialized version to list after adding some extra params.
@param array $items
@param array $nodes
@param array $visibleNodes
@param array $childrenNodes
@param User|null $user
@param int $levelMax
@param int $level | [
"Recursive",
"function",
"that",
"filters",
"visible",
"nodes",
"and",
"adds",
"serialized",
"version",
"to",
"list",
"after",
"adding",
"some",
"extra",
"params",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Manager/ProgressionManager.php#L127-L164 | train |
claroline/Distribution | plugin/claco-form/Serializer/CategorySerializer.php | CategorySerializer.serialize | public function serialize(Category $category, array $options = [])
{
$serialized = [
'id' => $category->getUuid(),
'name' => $category->getName(),
'details' => $category->getDetails(),
];
if (!in_array(Options::SERIALIZE_MINIMAL, $options)) {
$serialized = array_merge($serialized, [
'managers' => array_map(function (User $manager) {
return $this->userSerializer->serialize($manager, [Options::SERIALIZE_MINIMAL]);
}, $category->getManagers()),
]);
$serialized = array_merge($serialized, [
'fieldsValues' => array_map(function (FieldChoiceCategory $fcc) {
return $this->fieldChoiceCategorySerializer->serialize($fcc);
}, $this->fieldChoiceCategoryRepo->findBy(['category' => $category])),
]);
}
return $serialized;
} | php | public function serialize(Category $category, array $options = [])
{
$serialized = [
'id' => $category->getUuid(),
'name' => $category->getName(),
'details' => $category->getDetails(),
];
if (!in_array(Options::SERIALIZE_MINIMAL, $options)) {
$serialized = array_merge($serialized, [
'managers' => array_map(function (User $manager) {
return $this->userSerializer->serialize($manager, [Options::SERIALIZE_MINIMAL]);
}, $category->getManagers()),
]);
$serialized = array_merge($serialized, [
'fieldsValues' => array_map(function (FieldChoiceCategory $fcc) {
return $this->fieldChoiceCategorySerializer->serialize($fcc);
}, $this->fieldChoiceCategoryRepo->findBy(['category' => $category])),
]);
}
return $serialized;
} | [
"public",
"function",
"serialize",
"(",
"Category",
"$",
"category",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"serialized",
"=",
"[",
"'id'",
"=>",
"$",
"category",
"->",
"getUuid",
"(",
")",
",",
"'name'",
"=>",
"$",
"category",
"... | Serializes a Category entity for the JSON api.
@param Category $category - the category to serialize
@param array $options - a list of serialization options
@return array - the serialized representation of the category | [
"Serializes",
"a",
"Category",
"entity",
"for",
"the",
"JSON",
"api",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/claco-form/Serializer/CategorySerializer.php#L70-L92 | train |
claroline/Distribution | main/core/API/Serializer/MessageSerializer.php | MessageSerializer.serialize | public function serialize(AbstractMessage $message, array $options = [])
{
return [
'id' => $message->getUuid(),
'content' => $message->getContent(),
'meta' => $this->serializeMeta($message),
'parent' => $this->serializeParent($message),
'children' => array_map(function (AbstractMessage $child) use ($options) {
return $this->serialize($child, $options);
}, $message->getChildren()->toArray()),
];
} | php | public function serialize(AbstractMessage $message, array $options = [])
{
return [
'id' => $message->getUuid(),
'content' => $message->getContent(),
'meta' => $this->serializeMeta($message),
'parent' => $this->serializeParent($message),
'children' => array_map(function (AbstractMessage $child) use ($options) {
return $this->serialize($child, $options);
}, $message->getChildren()->toArray()),
];
} | [
"public",
"function",
"serialize",
"(",
"AbstractMessage",
"$",
"message",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"[",
"'id'",
"=>",
"$",
"message",
"->",
"getUuid",
"(",
")",
",",
"'content'",
"=>",
"$",
"message",
"->",
"get... | Serializes a AbstractMessage entity.
@param AbstractMessage $message
@param array $options
@return array | [
"Serializes",
"a",
"AbstractMessage",
"entity",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/API/Serializer/MessageSerializer.php#L56-L67 | train |
claroline/Distribution | main/core/Entity/Model/OrganizationsTrait.php | OrganizationsTrait.removeOrganization | public function removeOrganization($organization)
{
$this->hasOrganizationsProperty();
if ($this->organizations->contains($organization)) {
$this->organizations->removeElement($organization);
}
} | php | public function removeOrganization($organization)
{
$this->hasOrganizationsProperty();
if ($this->organizations->contains($organization)) {
$this->organizations->removeElement($organization);
}
} | [
"public",
"function",
"removeOrganization",
"(",
"$",
"organization",
")",
"{",
"$",
"this",
"->",
"hasOrganizationsProperty",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"organizations",
"->",
"contains",
"(",
"$",
"organization",
")",
")",
"{",
"$",
"th... | Removes an organization. | [
"Removes",
"an",
"organization",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/main/core/Entity/Model/OrganizationsTrait.php#L25-L32 | train |
claroline/Distribution | plugin/lesson/Controller/API/ChapterController.php | ChapterController.getAction | public function getAction(Request $request, Lesson $lesson, $chapterSlug)
{
$this->checkPermission('OPEN', $lesson->getResourceNode(), [], true);
$chapter = $this->chapterRepository->getChapterBySlug($chapterSlug, $lesson->getId());
if (is_null($chapter)) {
throw new NotFoundHttpException();
}
return new JsonResponse($this->chapterSerializer->serialize($chapter));
} | php | public function getAction(Request $request, Lesson $lesson, $chapterSlug)
{
$this->checkPermission('OPEN', $lesson->getResourceNode(), [], true);
$chapter = $this->chapterRepository->getChapterBySlug($chapterSlug, $lesson->getId());
if (is_null($chapter)) {
throw new NotFoundHttpException();
}
return new JsonResponse($this->chapterSerializer->serialize($chapter));
} | [
"public",
"function",
"getAction",
"(",
"Request",
"$",
"request",
",",
"Lesson",
"$",
"lesson",
",",
"$",
"chapterSlug",
")",
"{",
"$",
"this",
"->",
"checkPermission",
"(",
"'OPEN'",
",",
"$",
"lesson",
"->",
"getResourceNode",
"(",
")",
",",
"[",
"]",... | Get chapter by its slug.
@EXT\Route("/chapters/{chapterSlug}", name="apiv2_lesson_chapter_get")
@EXT\Method("GET")
@param Request $request
@param Lesson $lesson
@param string $chapterSlug
@return JsonResponse | [
"Get",
"chapter",
"by",
"its",
"slug",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/lesson/Controller/API/ChapterController.php#L81-L92 | train |
claroline/Distribution | plugin/lesson/Controller/API/ChapterController.php | ChapterController.createAction | public function createAction(Request $request, Lesson $lesson, Chapter $parent)
{
$this->checkPermission('EDIT', $lesson->getResourceNode(), [], true);
$newChapter = $this->chapterManager->createChapter($lesson, json_decode($request->getContent(), true), $parent);
return new JsonResponse($this->chapterSerializer->serialize($newChapter));
} | php | public function createAction(Request $request, Lesson $lesson, Chapter $parent)
{
$this->checkPermission('EDIT', $lesson->getResourceNode(), [], true);
$newChapter = $this->chapterManager->createChapter($lesson, json_decode($request->getContent(), true), $parent);
return new JsonResponse($this->chapterSerializer->serialize($newChapter));
} | [
"public",
"function",
"createAction",
"(",
"Request",
"$",
"request",
",",
"Lesson",
"$",
"lesson",
",",
"Chapter",
"$",
"parent",
")",
"{",
"$",
"this",
"->",
"checkPermission",
"(",
"'EDIT'",
",",
"$",
"lesson",
"->",
"getResourceNode",
"(",
")",
",",
... | Create new chapter.
@EXT\Route("/chapters/{slug}", name="apiv2_lesson_chapter_create")
@EXT\Method("POST")
@EXT\ParamConverter("parent", class="IcapLessonBundle:Chapter", options={"mapping": {"slug": "slug"}})
@param Request $request
@param Lesson $lesson
@param Chapter $parent
@return JsonResponse | [
"Create",
"new",
"chapter",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/lesson/Controller/API/ChapterController.php#L107-L114 | train |
claroline/Distribution | plugin/lesson/Controller/API/ChapterController.php | ChapterController.editAction | public function editAction(Request $request, Lesson $lesson, Chapter $chapter)
{
$this->checkPermission('EDIT', $lesson->getResourceNode(), [], true);
$this->chapterManager->updateChapter($lesson, $chapter, json_decode($request->getContent(), true));
return new JsonResponse($this->chapterSerializer->serialize($chapter));
} | php | public function editAction(Request $request, Lesson $lesson, Chapter $chapter)
{
$this->checkPermission('EDIT', $lesson->getResourceNode(), [], true);
$this->chapterManager->updateChapter($lesson, $chapter, json_decode($request->getContent(), true));
return new JsonResponse($this->chapterSerializer->serialize($chapter));
} | [
"public",
"function",
"editAction",
"(",
"Request",
"$",
"request",
",",
"Lesson",
"$",
"lesson",
",",
"Chapter",
"$",
"chapter",
")",
"{",
"$",
"this",
"->",
"checkPermission",
"(",
"'EDIT'",
",",
"$",
"lesson",
"->",
"getResourceNode",
"(",
")",
",",
"... | Update existing chapter.
@EXT\Route("/chapters/{slug}", name="apiv2_lesson_chapter_update")
@EXT\Method("PUT")
@EXT\ParamConverter("chapter", class="IcapLessonBundle:Chapter", options={"mapping": {"slug": "slug"}})
@param Request $request
@param Lesson $lesson
@param Chapter $chapter
@return JsonResponse | [
"Update",
"existing",
"chapter",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/lesson/Controller/API/ChapterController.php#L129-L136 | train |
claroline/Distribution | plugin/lesson/Controller/API/ChapterController.php | ChapterController.deleteAction | public function deleteAction(Request $request, Lesson $lesson, Chapter $chapter)
{
$previousChapter = $this->chapterRepository->getPreviousChapter($chapter);
$previousSlug = $previousChapter ? $previousChapter->getSlug() : null;
$this->checkPermission('EDIT', $lesson->getResourceNode(), [], true);
$payload = json_decode($request->getContent(), true);
$deleteChildren = $payload['deleteChildren'];
$this->chapterManager->deleteChapter($lesson, $chapter, $deleteChildren);
return new JsonResponse([
'tree' => $this->chapterManager->serializeChapterTree($lesson),
'slug' => $previousSlug,
]);
} | php | public function deleteAction(Request $request, Lesson $lesson, Chapter $chapter)
{
$previousChapter = $this->chapterRepository->getPreviousChapter($chapter);
$previousSlug = $previousChapter ? $previousChapter->getSlug() : null;
$this->checkPermission('EDIT', $lesson->getResourceNode(), [], true);
$payload = json_decode($request->getContent(), true);
$deleteChildren = $payload['deleteChildren'];
$this->chapterManager->deleteChapter($lesson, $chapter, $deleteChildren);
return new JsonResponse([
'tree' => $this->chapterManager->serializeChapterTree($lesson),
'slug' => $previousSlug,
]);
} | [
"public",
"function",
"deleteAction",
"(",
"Request",
"$",
"request",
",",
"Lesson",
"$",
"lesson",
",",
"Chapter",
"$",
"chapter",
")",
"{",
"$",
"previousChapter",
"=",
"$",
"this",
"->",
"chapterRepository",
"->",
"getPreviousChapter",
"(",
"$",
"chapter",
... | Delete existing chapter.
@EXT\Route("/chapters/{chapterSlug}/delete", name="apiv2_lesson_chapter_delete")
@EXT\Method("DELETE")
@EXT\ParamConverter("chapter", class="IcapLessonBundle:Chapter", options={"mapping": {"chapterSlug": "slug"}})
@param Request $request
@param Lesson $lesson
@param Chapter $chapter
@return JsonResponse | [
"Delete",
"existing",
"chapter",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/lesson/Controller/API/ChapterController.php#L151-L167 | train |
claroline/Distribution | plugin/lesson/Controller/API/ChapterController.php | ChapterController.getTreeAction | public function getTreeAction(Lesson $lesson)
{
$this->checkPermission('OPEN', $lesson->getResourceNode(), [], true);
return new JsonResponse($this->chapterManager->serializeChapterTree($lesson));
} | php | public function getTreeAction(Lesson $lesson)
{
$this->checkPermission('OPEN', $lesson->getResourceNode(), [], true);
return new JsonResponse($this->chapterManager->serializeChapterTree($lesson));
} | [
"public",
"function",
"getTreeAction",
"(",
"Lesson",
"$",
"lesson",
")",
"{",
"$",
"this",
"->",
"checkPermission",
"(",
"'OPEN'",
",",
"$",
"lesson",
"->",
"getResourceNode",
"(",
")",
",",
"[",
"]",
",",
"true",
")",
";",
"return",
"new",
"JsonRespons... | Get chapter tree.
@EXT\Route("/tree", name="apiv2_lesson_tree_get")
@EXT\Method("GET")
@param Lesson $lesson
@return JsonResponse | [
"Get",
"chapter",
"tree",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/lesson/Controller/API/ChapterController.php#L179-L184 | train |
claroline/Distribution | plugin/exo/Library/Json/JsonSchema.php | JsonSchema.validate | public function validate($data, $uri)
{
return $this->getValidator()->validate($data, $this->getSchema($uri));
} | php | public function validate($data, $uri)
{
return $this->getValidator()->validate($data, $this->getSchema($uri));
} | [
"public",
"function",
"validate",
"(",
"$",
"data",
",",
"$",
"uri",
")",
"{",
"return",
"$",
"this",
"->",
"getValidator",
"(",
")",
"->",
"validate",
"(",
"$",
"data",
",",
"$",
"this",
"->",
"getSchema",
"(",
"$",
"uri",
")",
")",
";",
"}"
] | Validates data against the schema located at URI.
@param mixed $data - the data to validate
@param string $uri - the URI of the schema to use
@return array | [
"Validates",
"data",
"against",
"the",
"schema",
"located",
"at",
"URI",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Library/Json/JsonSchema.php#L57-L60 | train |
claroline/Distribution | plugin/exo/Library/Json/JsonSchema.php | JsonSchema.getValidator | private function getValidator()
{
if (null === $this->validator) {
$hook = function ($uri) {
return $this->uriToFile($uri);
};
$this->validator = SchemaValidator::buildDefault($hook);
}
return $this->validator;
} | php | private function getValidator()
{
if (null === $this->validator) {
$hook = function ($uri) {
return $this->uriToFile($uri);
};
$this->validator = SchemaValidator::buildDefault($hook);
}
return $this->validator;
} | [
"private",
"function",
"getValidator",
"(",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"validator",
")",
"{",
"$",
"hook",
"=",
"function",
"(",
"$",
"uri",
")",
"{",
"return",
"$",
"this",
"->",
"uriToFile",
"(",
"$",
"uri",
")",
";",
... | Get schema validator.
@return SchemaValidator | [
"Get",
"schema",
"validator",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Library/Json/JsonSchema.php#L67-L78 | train |
claroline/Distribution | plugin/exo/Library/Json/JsonSchema.php | JsonSchema.getSchema | private function getSchema($uri)
{
if (empty($this->schemas[$uri])) {
$this->schemas[$uri] = Utils::loadJsonFromFile($this->uriToFile($uri));
}
return $this->schemas[$uri];
} | php | private function getSchema($uri)
{
if (empty($this->schemas[$uri])) {
$this->schemas[$uri] = Utils::loadJsonFromFile($this->uriToFile($uri));
}
return $this->schemas[$uri];
} | [
"private",
"function",
"getSchema",
"(",
"$",
"uri",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"schemas",
"[",
"$",
"uri",
"]",
")",
")",
"{",
"$",
"this",
"->",
"schemas",
"[",
"$",
"uri",
"]",
"=",
"Utils",
"::",
"loadJsonFromFile",
... | Loads schema from URI.
@param $uri
@return mixed
@throws \JVal\Exception\JsonDecodeException | [
"Loads",
"schema",
"from",
"URI",
"."
] | a2d9762eddba5732447a2915c977a3ce859103b6 | https://github.com/claroline/Distribution/blob/a2d9762eddba5732447a2915c977a3ce859103b6/plugin/exo/Library/Json/JsonSchema.php#L89-L96 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.