repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
eyewitness/eye
app/Monitors/Custom.php
Custom.saveHistory
public function saveHistory($status) { try { History::create(['type' => 'custom', 'meta' => $this->getSafeName(), 'value' => $this->getValue(), 'record' => [ 'status' => $status ], ]); } catch (Exception $e) { $this->eye->logger()->error('Custom witness history save failed', $e, $this->getSafeName()); } }
php
public function saveHistory($status) { try { History::create(['type' => 'custom', 'meta' => $this->getSafeName(), 'value' => $this->getValue(), 'record' => [ 'status' => $status ], ]); } catch (Exception $e) { $this->eye->logger()->error('Custom witness history save failed', $e, $this->getSafeName()); } }
[ "public", "function", "saveHistory", "(", "$", "status", ")", "{", "try", "{", "History", "::", "create", "(", "[", "'type'", "=>", "'custom'", ",", "'meta'", "=>", "$", "this", "->", "getSafeName", "(", ")", ",", "'value'", "=>", "$", "this", "->", ...
Save the custom witness history. @param bool $status @return void
[ "Save", "the", "custom", "witness", "history", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Monitors/Custom.php#L179-L192
eyewitness/eye
app/Monitors/Custom.php
Custom.checkHealth
public function checkHealth($status) { if ($status) { if ($this->eye->status()->isSick('custom_'.$this->getSafeName())) { $this->recovering(); $this->eye->notifier()->alert(new Passed($this)); } $this->eye->status()->setHealthy('custom_'.$this->getSafeName()); return true; } if ($this->eye->status()->isHealthy('custom_'.$this->getSafeName())) { $this->failing(); $this->eye->notifier()->alert(new Failed($this)); } $this->eye->status()->setSick('custom_'.$this->getSafeName()); return false; }
php
public function checkHealth($status) { if ($status) { if ($this->eye->status()->isSick('custom_'.$this->getSafeName())) { $this->recovering(); $this->eye->notifier()->alert(new Passed($this)); } $this->eye->status()->setHealthy('custom_'.$this->getSafeName()); return true; } if ($this->eye->status()->isHealthy('custom_'.$this->getSafeName())) { $this->failing(); $this->eye->notifier()->alert(new Failed($this)); } $this->eye->status()->setSick('custom_'.$this->getSafeName()); return false; }
[ "public", "function", "checkHealth", "(", "$", "status", ")", "{", "if", "(", "$", "status", ")", "{", "if", "(", "$", "this", "->", "eye", "->", "status", "(", ")", "->", "isSick", "(", "'custom_'", ".", "$", "this", "->", "getSafeName", "(", ")",...
Check the health of the custom witness. @param bool $status @return bool
[ "Check", "the", "health", "of", "the", "custom", "witness", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Monitors/Custom.php#L200-L221
eyewitness/eye
app/Logger.php
Logger.error
public function error($message, $e, $data = null) { if ($e instanceOf Exception) { $e = $e->getMessage(); } Log::error('Eyewitness: '.$message, ['exception' => $e, 'data' => $data]); }
php
public function error($message, $e, $data = null) { if ($e instanceOf Exception) { $e = $e->getMessage(); } Log::error('Eyewitness: '.$message, ['exception' => $e, 'data' => $data]); }
[ "public", "function", "error", "(", "$", "message", ",", "$", "e", ",", "$", "data", "=", "null", ")", "{", "if", "(", "$", "e", "instanceOf", "Exception", ")", "{", "$", "e", "=", "$", "e", "->", "getMessage", "(", ")", ";", "}", "Log", "::", ...
Capture an error relating to Eyewitness. @param string $message @param string|\Exception $e @param string|null $data @return void
[ "Capture", "an", "error", "relating", "to", "Eyewitness", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Logger.php#L18-L26
eyewitness/eye
app/Logger.php
Logger.debug
public function debug($message, $data = null) { if (config('eyewitness.debug', false)) { Log::debug('Eyewitness: '.$message, ['data' => $data]); } }
php
public function debug($message, $data = null) { if (config('eyewitness.debug', false)) { Log::debug('Eyewitness: '.$message, ['data' => $data]); } }
[ "public", "function", "debug", "(", "$", "message", ",", "$", "data", "=", "null", ")", "{", "if", "(", "config", "(", "'eyewitness.debug'", ",", "false", ")", ")", "{", "Log", "::", "debug", "(", "'Eyewitness: '", ".", "$", "message", ",", "[", "'da...
Capture a debug issue relating to Eyewitness. @param string $message @param string|null $data @return void
[ "Capture", "a", "debug", "issue", "relating", "to", "Eyewitness", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Logger.php#L35-L40
eyewitness/eye
app/Commands/InstallCommand.php
InstallCommand.handle
public function handle() { if ($this->eye->checkConfig() && ! $this->handleUpgrade()) { $this->info('Aborted. No changes were made. If you need assistance please contact us anytime at: support@eyewitness.io'); return; } $this->displayInitialInstallMessage(); $this->callSilent('vendor:publish', ['--provider' => 'Eyewitness\Eye\EyeServiceProvider', '--force' => true]); $this->call('migrate'); $this->call('eyewitness:regenerate', ['--force' => true]); try { $this->eye->scheduler()->install(); } catch (Exception $e) { $this->error('The scheduling installation failed: '.$e->getMessage()); } $this->displayPollingMessage(); $this->call('eyewitness:poll', ['--force' => true]); $this->displayOutcome(); }
php
public function handle() { if ($this->eye->checkConfig() && ! $this->handleUpgrade()) { $this->info('Aborted. No changes were made. If you need assistance please contact us anytime at: support@eyewitness.io'); return; } $this->displayInitialInstallMessage(); $this->callSilent('vendor:publish', ['--provider' => 'Eyewitness\Eye\EyeServiceProvider', '--force' => true]); $this->call('migrate'); $this->call('eyewitness:regenerate', ['--force' => true]); try { $this->eye->scheduler()->install(); } catch (Exception $e) { $this->error('The scheduling installation failed: '.$e->getMessage()); } $this->displayPollingMessage(); $this->call('eyewitness:poll', ['--force' => true]); $this->displayOutcome(); }
[ "public", "function", "handle", "(", ")", "{", "if", "(", "$", "this", "->", "eye", "->", "checkConfig", "(", ")", "&&", "!", "$", "this", "->", "handleUpgrade", "(", ")", ")", "{", "$", "this", "->", "info", "(", "'Aborted. No changes were made. If you ...
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Commands/InstallCommand.php#L50-L74
eyewitness/eye
app/Commands/InstallCommand.php
InstallCommand.displayOutcome
protected function displayOutcome() { $this->info('______________________________________'); $this->info(' '); $this->info('You can now visit: "'.config('app.url').'/'.config('eyewitness.base_uri').'" to see your dashboard (you will need your keys above to login).'); $this->info(' '); }
php
protected function displayOutcome() { $this->info('______________________________________'); $this->info(' '); $this->info('You can now visit: "'.config('app.url').'/'.config('eyewitness.base_uri').'" to see your dashboard (you will need your keys above to login).'); $this->info(' '); }
[ "protected", "function", "displayOutcome", "(", ")", "{", "$", "this", "->", "info", "(", "'______________________________________'", ")", ";", "$", "this", "->", "info", "(", "' '", ")", ";", "$", "this", "->", "info", "(", "'You can now visit: \"'", ".", "...
Display the outcome of the installation. @return void
[ "Display", "the", "outcome", "of", "the", "installation", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Commands/InstallCommand.php#L107-L113
eyewitness/eye
app/Commands/InstallCommand.php
InstallCommand.handleUpgrade
protected function handleUpgrade() { $this->error('______________________________________'); $this->error('It appears that the Eyewitness package has already been installed. You only need to run the installer once per application.'); $this->error('If you continue, this command will overwrite your eyewitness config file with the latest version, and you will lose all your current settings.'); $this->error('You can run "artisan eyewitness:regenerate" if you just want to update to new keys.'); $this->error('______________________________________'); return $this->confirm('Do you wish to continue?'); }
php
protected function handleUpgrade() { $this->error('______________________________________'); $this->error('It appears that the Eyewitness package has already been installed. You only need to run the installer once per application.'); $this->error('If you continue, this command will overwrite your eyewitness config file with the latest version, and you will lose all your current settings.'); $this->error('You can run "artisan eyewitness:regenerate" if you just want to update to new keys.'); $this->error('______________________________________'); return $this->confirm('Do you wish to continue?'); }
[ "protected", "function", "handleUpgrade", "(", ")", "{", "$", "this", "->", "error", "(", "'______________________________________'", ")", ";", "$", "this", "->", "error", "(", "'It appears that the Eyewitness package has already been installed. You only need to run the install...
Display the upgrade steps. @return bool
[ "Display", "the", "upgrade", "steps", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Commands/InstallCommand.php#L120-L129
eyewitness/eye
app/Http/Controllers/SchedulerController.php
SchedulerController.show
public function show($id) { $scheduler = Scheduler::findOrFail($id); return view('eyewitness::scheduler.show')->withEye(app(Eye::class)) ->withScheduler($scheduler) ->withHistories($scheduler->history()->simplePaginate(config('eyewitness.pagination_size', 50))) ->withTransformer(new ChartTransformer); }
php
public function show($id) { $scheduler = Scheduler::findOrFail($id); return view('eyewitness::scheduler.show')->withEye(app(Eye::class)) ->withScheduler($scheduler) ->withHistories($scheduler->history()->simplePaginate(config('eyewitness.pagination_size', 50))) ->withTransformer(new ChartTransformer); }
[ "public", "function", "show", "(", "$", "id", ")", "{", "$", "scheduler", "=", "Scheduler", "::", "findOrFail", "(", "$", "id", ")", ";", "return", "view", "(", "'eyewitness::scheduler.show'", ")", "->", "withEye", "(", "app", "(", "Eye", "::", "class", ...
Show the scheduler. @param integer $id @return \Illuminate\Http\Response
[ "Show", "the", "scheduler", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Http/Controllers/SchedulerController.php#L22-L30
eyewitness/eye
app/Http/Controllers/SchedulerController.php
SchedulerController.update
public function update(Request $request, $id) { $scheduler = Scheduler::findOrFail($id); $this->validate($request, [ 'alert_on_missed' => 'required|boolean', 'alert_on_fail' => 'required|boolean', 'alert_run_time_greater_than' => 'required|numeric|min:0|max:9999', 'alert_run_time_less_than' => 'required|numeric|min:0|max:9999', 'alert_last_run_greater_than' => 'required|numeric|min:0|max:9999999', ]); $scheduler->fill($request->only([ 'alert_on_missed', 'alert_on_fail', 'alert_run_time_greater_than', 'alert_run_time_less_than', 'alert_last_run_greater_than' ])); $scheduler->save(); return redirect(route('eyewitness.schedulers.show', $scheduler->id).'#settings')->withSuccess('The scheduler configuration has been updated.'); }
php
public function update(Request $request, $id) { $scheduler = Scheduler::findOrFail($id); $this->validate($request, [ 'alert_on_missed' => 'required|boolean', 'alert_on_fail' => 'required|boolean', 'alert_run_time_greater_than' => 'required|numeric|min:0|max:9999', 'alert_run_time_less_than' => 'required|numeric|min:0|max:9999', 'alert_last_run_greater_than' => 'required|numeric|min:0|max:9999999', ]); $scheduler->fill($request->only([ 'alert_on_missed', 'alert_on_fail', 'alert_run_time_greater_than', 'alert_run_time_less_than', 'alert_last_run_greater_than' ])); $scheduler->save(); return redirect(route('eyewitness.schedulers.show', $scheduler->id).'#settings')->withSuccess('The scheduler configuration has been updated.'); }
[ "public", "function", "update", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "scheduler", "=", "Scheduler", "::", "findOrFail", "(", "$", "id", ")", ";", "$", "this", "->", "validate", "(", "$", "request", ",", "[", "'alert_on_missed'...
Update the scheduler. @param Request $request @param integer $id @return \Illuminate\Http\Response
[ "Update", "the", "scheduler", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Http/Controllers/SchedulerController.php#L39-L62
eyewitness/eye
app/Http/Controllers/SchedulerController.php
SchedulerController.destroy
public function destroy($id) { $scheduler = Scheduler::findOrFail($id); $scheduler->history()->delete(); $scheduler->delete(); return redirect(route('eyewitness.dashboard').'#scheduler')->withSuccess('The scheduler has been deleted.'); }
php
public function destroy($id) { $scheduler = Scheduler::findOrFail($id); $scheduler->history()->delete(); $scheduler->delete(); return redirect(route('eyewitness.dashboard').'#scheduler')->withSuccess('The scheduler has been deleted.'); }
[ "public", "function", "destroy", "(", "$", "id", ")", "{", "$", "scheduler", "=", "Scheduler", "::", "findOrFail", "(", "$", "id", ")", ";", "$", "scheduler", "->", "history", "(", ")", "->", "delete", "(", ")", ";", "$", "scheduler", "->", "delete",...
Destroy the scheduler. @param integer $id @return \Illuminate\Http\Response
[ "Destroy", "the", "scheduler", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Http/Controllers/SchedulerController.php#L70-L78
eyewitness/eye
app/Commands/CustomCommand.php
CustomCommand.handle
public function handle() { $this->info('Starting Custom Witness command...'); foreach ($this->eye->getCustomWitnesses(true) as $witness) { $this->info('Running: '.$witness->getSafeName()); $status = $this->runWitness($witness); $witness->saveHistory($status); $witness->checkHealth($status); } $this->info('Custom Witness command complete...'); }
php
public function handle() { $this->info('Starting Custom Witness command...'); foreach ($this->eye->getCustomWitnesses(true) as $witness) { $this->info('Running: '.$witness->getSafeName()); $status = $this->runWitness($witness); $witness->saveHistory($status); $witness->checkHealth($status); } $this->info('Custom Witness command complete...'); }
[ "public", "function", "handle", "(", ")", "{", "$", "this", "->", "info", "(", "'Starting Custom Witness command...'", ")", ";", "foreach", "(", "$", "this", "->", "eye", "->", "getCustomWitnesses", "(", "true", ")", "as", "$", "witness", ")", "{", "$", ...
Execute the custom console command. @return void
[ "Execute", "the", "custom", "console", "command", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Commands/CustomCommand.php#L57-L70
eyewitness/eye
app/Commands/CustomCommand.php
CustomCommand.runWitness
protected function runWitness($witness) { try { $status = $witness->run(); $status = ($status) ?: false; } catch (Throwable $t) { $status = false; } return $status; }
php
protected function runWitness($witness) { try { $status = $witness->run(); $status = ($status) ?: false; } catch (Throwable $t) { $status = false; } return $status; }
[ "protected", "function", "runWitness", "(", "$", "witness", ")", "{", "try", "{", "$", "status", "=", "$", "witness", "->", "run", "(", ")", ";", "$", "status", "=", "(", "$", "status", ")", "?", ":", "false", ";", "}", "catch", "(", "Throwable", ...
Run the custom witness. @param \Eyewitness\Eye\Monitors\Custom $witness @return bool
[ "Run", "the", "custom", "witness", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Commands/CustomCommand.php#L78-L88
eyewitness/eye
app/Monitors/Composer.php
Composer.poll
public function poll() { $latest = $this->eye->api()->composer(); if (is_null($latest)) { return; } History::where('type', 'composer')->delete(); History::create([ 'type' => 'composer', 'meta' => 'composer', 'record' => $latest ]); if ($latest === []) { if ($this->eye->status()->isSick('composer')) { $this->eye->notifier()->alert(new Safe); } $this->eye->status()->setHealthy('composer'); } else { if ($this->eye->status()->isHealthy('composer')) { $this->eye->notifier()->alert(new Risk); } $this->eye->status()->setSick('composer'); } }
php
public function poll() { $latest = $this->eye->api()->composer(); if (is_null($latest)) { return; } History::where('type', 'composer')->delete(); History::create([ 'type' => 'composer', 'meta' => 'composer', 'record' => $latest ]); if ($latest === []) { if ($this->eye->status()->isSick('composer')) { $this->eye->notifier()->alert(new Safe); } $this->eye->status()->setHealthy('composer'); } else { if ($this->eye->status()->isHealthy('composer')) { $this->eye->notifier()->alert(new Risk); } $this->eye->status()->setSick('composer'); } }
[ "public", "function", "poll", "(", ")", "{", "$", "latest", "=", "$", "this", "->", "eye", "->", "api", "(", ")", "->", "composer", "(", ")", ";", "if", "(", "is_null", "(", "$", "latest", ")", ")", "{", "return", ";", "}", "History", "::", "wh...
Poll the Composer for its checks. @return void
[ "Poll", "the", "Composer", "for", "its", "checks", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Monitors/Composer.php#L16-L45
eyewitness/eye
app/Notifications/Messages/Scheduler/Missed.php
Missed.meta
public function meta() { try { $last = e($this->meta['scheduler']->last_run->diffForHumans()); } catch (Exception $e) { $last = 'Never'; } return [ 'Command' => e($this->meta['scheduler']->command), 'Schedule' => e($this->meta['scheduler']->schedule), 'Last Run' => $last ]; }
php
public function meta() { try { $last = e($this->meta['scheduler']->last_run->diffForHumans()); } catch (Exception $e) { $last = 'Never'; } return [ 'Command' => e($this->meta['scheduler']->command), 'Schedule' => e($this->meta['scheduler']->schedule), 'Last Run' => $last ]; }
[ "public", "function", "meta", "(", ")", "{", "try", "{", "$", "last", "=", "e", "(", "$", "this", "->", "meta", "[", "'scheduler'", "]", "->", "last_run", "->", "diffForHumans", "(", ")", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "...
Any meta information for the message. @return array
[ "Any", "meta", "information", "for", "the", "message", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Notifications/Messages/Scheduler/Missed.php#L35-L48
eyewitness/eye
app/Notifications/Drivers/Database.php
Database.fire
public function fire($recipient, $message) { try { History::create([ 'title' => $message->title(), 'isError' => $message->isError(), 'description' => $message->plainDescription(), 'severity' => $message->severity(), 'type' => $message->type(), 'meta' => $message->meta(), 'acknowledged' => 0, ]); } catch (Exception $e) { app(Eye::class)->logger()->error('Unable to send Database notification', $e); } }
php
public function fire($recipient, $message) { try { History::create([ 'title' => $message->title(), 'isError' => $message->isError(), 'description' => $message->plainDescription(), 'severity' => $message->severity(), 'type' => $message->type(), 'meta' => $message->meta(), 'acknowledged' => 0, ]); } catch (Exception $e) { app(Eye::class)->logger()->error('Unable to send Database notification', $e); } }
[ "public", "function", "fire", "(", "$", "recipient", ",", "$", "message", ")", "{", "try", "{", "History", "::", "create", "(", "[", "'title'", "=>", "$", "message", "->", "title", "(", ")", ",", "'isError'", "=>", "$", "message", "->", "isError", "(...
Fire a notification. @param \Eyewitness\Eye\Repo\Notifications\Recipient $recipient @param \Eyewitness\Eye\Notifications\Messages\MessageInterface $message @return void
[ "Fire", "a", "notification", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/app/Notifications/Drivers/Database.php#L18-L33
eyewitness/eye
database/migrations/2017_12_01_000007_create_eyewitness_io_history_scheduler_table.php
CreateEyewitnessIoHistorySchedulerTable.up
public function up() { Schema::connection(config('eyewitness.eyewitness_database_connection'))->create('eyewitness_io_history_scheduler', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('scheduler_id')->unsigned()->index(); $table->decimal('time_to_run', 10, 4)->nullable()->default(null); $table->integer('exitcode')->index()->nullable()->default(null); $table->text('output')->nullable()->default(null); $table->boolean('overdue')->default(false); $table->timestamp('expected_completion')->index()->nullable()->default(null); $table->timestamp('created_at')->useCurrent()->index(); }); }
php
public function up() { Schema::connection(config('eyewitness.eyewitness_database_connection'))->create('eyewitness_io_history_scheduler', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('scheduler_id')->unsigned()->index(); $table->decimal('time_to_run', 10, 4)->nullable()->default(null); $table->integer('exitcode')->index()->nullable()->default(null); $table->text('output')->nullable()->default(null); $table->boolean('overdue')->default(false); $table->timestamp('expected_completion')->index()->nullable()->default(null); $table->timestamp('created_at')->useCurrent()->index(); }); }
[ "public", "function", "up", "(", ")", "{", "Schema", "::", "connection", "(", "config", "(", "'eyewitness.eyewitness_database_connection'", ")", ")", "->", "create", "(", "'eyewitness_io_history_scheduler'", ",", "function", "(", "Blueprint", "$", "table", ")", "{...
Run the migrations. @return void
[ "Run", "the", "migrations", "." ]
train
https://github.com/eyewitness/eye/blob/5f81f75209a68953242a0c6b33f4c860bb1b392a/database/migrations/2017_12_01_000007_create_eyewitness_io_history_scheduler_table.php#L14-L26
minkphp/MinkGoutteDriver
src/GoutteDriver.php
GoutteDriver.setBasicAuth
public function setBasicAuth($user, $password) { if (false === $user) { $this->getClient()->resetAuth(); return; } $this->getClient()->setAuth($user, $password); }
php
public function setBasicAuth($user, $password) { if (false === $user) { $this->getClient()->resetAuth(); return; } $this->getClient()->setAuth($user, $password); }
[ "public", "function", "setBasicAuth", "(", "$", "user", ",", "$", "password", ")", "{", "if", "(", "false", "===", "$", "user", ")", "{", "$", "this", "->", "getClient", "(", ")", "->", "resetAuth", "(", ")", ";", "return", ";", "}", "$", "this", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/minkphp/MinkGoutteDriver/blob/7a4b2d49511865e23d61463514fa2754d42ec658/src/GoutteDriver.php#L36-L45
minkphp/MinkGoutteDriver
src/Goutte/Client.php
Client.filterResponse
protected function filterResponse($response) { $contentType = $response->getHeader('Content-Type'); if (!$contentType || false === strpos($contentType, 'charset=')) { if (preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9]+)/i', $response->getContent(), $matches)) { $headers = $response->getHeaders(); $headers['Content-Type'] = $contentType.';charset='.$matches[1]; $response = new Response($response->getContent(), $response->getStatus(), $headers); } } return parent::filterResponse($response); }
php
protected function filterResponse($response) { $contentType = $response->getHeader('Content-Type'); if (!$contentType || false === strpos($contentType, 'charset=')) { if (preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9]+)/i', $response->getContent(), $matches)) { $headers = $response->getHeaders(); $headers['Content-Type'] = $contentType.';charset='.$matches[1]; $response = new Response($response->getContent(), $response->getStatus(), $headers); } } return parent::filterResponse($response); }
[ "protected", "function", "filterResponse", "(", "$", "response", ")", "{", "$", "contentType", "=", "$", "response", "->", "getHeader", "(", "'Content-Type'", ")", ";", "if", "(", "!", "$", "contentType", "||", "false", "===", "strpos", "(", "$", "contentT...
Reads response meta tags to guess content-type charset. @param Response $response @return Response
[ "Reads", "response", "meta", "tags", "to", "guess", "content", "-", "type", "charset", "." ]
train
https://github.com/minkphp/MinkGoutteDriver/blob/7a4b2d49511865e23d61463514fa2754d42ec658/src/Goutte/Client.php#L28-L42
Codeception/AspectMock
src/AspectMock/Kernel.php
Kernel.loadPhpFiles
public function loadPhpFiles($dir) { $files = Finder::create()->files()->name('*.php')->in($dir); foreach ($files as $file) { $this->loadFile($file->getRealpath()); } }
php
public function loadPhpFiles($dir) { $files = Finder::create()->files()->name('*.php')->in($dir); foreach ($files as $file) { $this->loadFile($file->getRealpath()); } }
[ "public", "function", "loadPhpFiles", "(", "$", "dir", ")", "{", "$", "files", "=", "Finder", "::", "create", "(", ")", "->", "files", "(", ")", "->", "name", "(", "'*.php'", ")", "->", "in", "(", "$", "dir", ")", ";", "foreach", "(", "$", "files...
Scans a directory provided and includes all PHP files from it. All files will be parsed and aspects will be added. @param $dir
[ "Scans", "a", "directory", "provided", "and", "includes", "all", "PHP", "files", "from", "it", ".", "All", "files", "will", "be", "parsed", "and", "aspects", "will", "be", "added", "." ]
train
https://github.com/Codeception/AspectMock/blob/349b60cde56236056acd158e46aee3f93baf1f67/src/AspectMock/Kernel.php#L40-L47
Codeception/AspectMock
src/AspectMock/Proxy/Verifier.php
Verifier.verifyInvoked
public function verifyInvoked($name, $params = null) { $calls = $this->getCallsForMethod($name); $separator = $this->callSyntax($name); if (empty($calls)) throw new fail(sprintf($this->invokedFail, $this->className.$separator.$name, '')); if (is_array($params)) { foreach ($calls as $args) { if ($this->onlyExpectedArguments($params, $args) === $params) return; } $params = ArgumentsFormatter::toString($params); $gotParams = ArgumentsFormatter::toString($calls[0]); throw new fail(sprintf($this->invokedFail, $this->className.$separator.$name."($params)", $this->className.$separator.$name."($gotParams)")); } else if(is_callable($params)) { $params($calls); } }
php
public function verifyInvoked($name, $params = null) { $calls = $this->getCallsForMethod($name); $separator = $this->callSyntax($name); if (empty($calls)) throw new fail(sprintf($this->invokedFail, $this->className.$separator.$name, '')); if (is_array($params)) { foreach ($calls as $args) { if ($this->onlyExpectedArguments($params, $args) === $params) return; } $params = ArgumentsFormatter::toString($params); $gotParams = ArgumentsFormatter::toString($calls[0]); throw new fail(sprintf($this->invokedFail, $this->className.$separator.$name."($params)", $this->className.$separator.$name."($gotParams)")); } else if(is_callable($params)) { $params($calls); } }
[ "public", "function", "verifyInvoked", "(", "$", "name", ",", "$", "params", "=", "null", ")", "{", "$", "calls", "=", "$", "this", "->", "getCallsForMethod", "(", "$", "name", ")", ";", "$", "separator", "=", "$", "this", "->", "callSyntax", "(", "$...
Verifies a method was invoked at least once. In second argument you can specify with which params method expected to be invoked; ``` php <?php $user->verifyInvoked('save'); $user->verifyInvoked('setName',['davert']); ?> ``` @param $name @param null $params @throws \PHPUnit\Framework\ExpectationFailedException @param array $params @throws fail
[ "Verifies", "a", "method", "was", "invoked", "at", "least", "once", ".", "In", "second", "argument", "you", "can", "specify", "with", "which", "params", "method", "expected", "to", "be", "invoked", ";" ]
train
https://github.com/Codeception/AspectMock/blob/349b60cde56236056acd158e46aee3f93baf1f67/src/AspectMock/Proxy/Verifier.php#L59-L77
Codeception/AspectMock
src/AspectMock/Proxy/Verifier.php
Verifier.verifyInvokedMultipleTimes
public function verifyInvokedMultipleTimes($name, $times, $params = null) { if ($times == 0) return $this->verifyNeverInvoked($name, $params); $calls = $this->getCallsForMethod($name); $separator = $this->callSyntax($name); if (empty($calls)) throw new fail(sprintf($this->notInvokedMultipleTimesFail, $this->className.$separator.$name, $times)); if (is_array($params)) { $equals = 0; foreach ($calls as $args) { if ($this->onlyExpectedArguments($params, $args) === $params) { $equals++; } } if ($equals == $times) return; $params = ArgumentsFormatter::toString($params); throw new fail(sprintf($this->invokedMultipleTimesFail, $this->className.$separator.$name."($params)", $times, $equals)); } else if(is_callable($params)) { $params($calls); } $num_calls = count($calls); if ($num_calls != $times) throw new fail(sprintf($this->invokedMultipleTimesFail, $this->className.$separator.$name, $times, $num_calls)); }
php
public function verifyInvokedMultipleTimes($name, $times, $params = null) { if ($times == 0) return $this->verifyNeverInvoked($name, $params); $calls = $this->getCallsForMethod($name); $separator = $this->callSyntax($name); if (empty($calls)) throw new fail(sprintf($this->notInvokedMultipleTimesFail, $this->className.$separator.$name, $times)); if (is_array($params)) { $equals = 0; foreach ($calls as $args) { if ($this->onlyExpectedArguments($params, $args) === $params) { $equals++; } } if ($equals == $times) return; $params = ArgumentsFormatter::toString($params); throw new fail(sprintf($this->invokedMultipleTimesFail, $this->className.$separator.$name."($params)", $times, $equals)); } else if(is_callable($params)) { $params($calls); } $num_calls = count($calls); if ($num_calls != $times) throw new fail(sprintf($this->invokedMultipleTimesFail, $this->className.$separator.$name, $times, $num_calls)); }
[ "public", "function", "verifyInvokedMultipleTimes", "(", "$", "name", ",", "$", "times", ",", "$", "params", "=", "null", ")", "{", "if", "(", "$", "times", "==", "0", ")", "return", "$", "this", "->", "verifyNeverInvoked", "(", "$", "name", ",", "$", ...
Verifies that method was called exactly $times times. ``` php <?php $user->verifyInvokedMultipleTimes('save',2); $user->verifyInvokedMultipleTimes('dispatchEvent',3,['before_validate']); $user->verifyInvokedMultipleTimes('dispatchEvent',4,['after_save']); ?> ``` @param $name @param $times @param array $params @throws \PHPUnit\Framework\ExpectationFailedException
[ "Verifies", "that", "method", "was", "called", "exactly", "$times", "times", "." ]
train
https://github.com/Codeception/AspectMock/blob/349b60cde56236056acd158e46aee3f93baf1f67/src/AspectMock/Proxy/Verifier.php#L106-L129
Codeception/AspectMock
src/AspectMock/Proxy/Verifier.php
Verifier.verifyNeverInvoked
public function verifyNeverInvoked($name, $params = null) { $calls = $this->getCallsForMethod($name); $separator = $this->callSyntax($name); if (is_array($params)) { if (empty($calls)) { return; } foreach ($calls as $args) { if ($this->onlyExpectedArguments($params, $args) === $params) { throw new fail(sprintf($this->neverInvoked, $this->className)); } } return; } if (count($calls)) { throw new fail(sprintf($this->neverInvoked, $this->className.$separator.$name)); } }
php
public function verifyNeverInvoked($name, $params = null) { $calls = $this->getCallsForMethod($name); $separator = $this->callSyntax($name); if (is_array($params)) { if (empty($calls)) { return; } foreach ($calls as $args) { if ($this->onlyExpectedArguments($params, $args) === $params) { throw new fail(sprintf($this->neverInvoked, $this->className)); } } return; } if (count($calls)) { throw new fail(sprintf($this->neverInvoked, $this->className.$separator.$name)); } }
[ "public", "function", "verifyNeverInvoked", "(", "$", "name", ",", "$", "params", "=", "null", ")", "{", "$", "calls", "=", "$", "this", "->", "getCallsForMethod", "(", "$", "name", ")", ";", "$", "separator", "=", "$", "this", "->", "callSyntax", "(",...
Verifies that method was not called. In second argument with which arguments is not expected to be called. ``` php <?php $user->setName('davert'); $user->verifyNeverInvoked('setName'); // fail $user->verifyNeverInvoked('setName',['davert']); // fail $user->verifyNeverInvoked('setName',['bob']); // success $user->verifyNeverInvoked('setName',[]); // success ?> ``` @param $name @param null $params @throws \PHPUnit\Framework\ExpectationFailedException
[ "Verifies", "that", "method", "was", "not", "called", ".", "In", "second", "argument", "with", "which", "arguments", "is", "not", "expected", "to", "be", "called", "." ]
train
https://github.com/Codeception/AspectMock/blob/349b60cde56236056acd158e46aee3f93baf1f67/src/AspectMock/Proxy/Verifier.php#L149-L169
oat-sa/tao-core
models/classes/http/HttpFlowTrait.php
HttpFlowTrait.redirect
public function redirect($url, $statusCode = 302) { $context = Context::getInstance(); header(HTTPToolkit::statusCodeHeader($statusCode)); header(HTTPToolkit::locationHeader($url)); throw new InterruptedActionException( 'Interrupted action after a redirection', $context->getModuleName(), $context->getActionName() ); }
php
public function redirect($url, $statusCode = 302) { $context = Context::getInstance(); header(HTTPToolkit::statusCodeHeader($statusCode)); header(HTTPToolkit::locationHeader($url)); throw new InterruptedActionException( 'Interrupted action after a redirection', $context->getModuleName(), $context->getActionName() ); }
[ "public", "function", "redirect", "(", "$", "url", ",", "$", "statusCode", "=", "302", ")", "{", "$", "context", "=", "Context", "::", "getInstance", "(", ")", ";", "header", "(", "HTTPToolkit", "::", "statusCodeHeader", "(", "$", "statusCode", ")", ")",...
Redirect using the TAO FlowController implementation @see {@link oat\model\routing\FlowController} @param string $url @param int $statusCode @throws InterruptedActionException
[ "Redirect", "using", "the", "TAO", "FlowController", "implementation" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/HttpFlowTrait.php#L58-L70
oat-sa/tao-core
models/classes/http/HttpFlowTrait.php
HttpFlowTrait.forwardUrl
public function forwardUrl($url) { $uri = new Uri($url); $query = $uri->getQuery(); $queryParams = []; if (strlen($query) > 0) { parse_str($query, $queryParams); } switch ($this->getPsrRequest()->getMethod()) { case 'GET' : $params = $this->getPsrRequest()->getQueryParams(); break; case 'POST' : $params = $this->getPsrRequest()->getParsedBody(); break; default: $params = []; } $request = $this->getPsrRequest() ->withUri($uri) ->withQueryParams((array) $queryParams); //resolve the given URL for routing $resolver = new Resolver($request); $this->propagate($resolver); //update the context to the new route $context = \Context::getInstance(); $context->setExtensionName($resolver->getExtensionId()); $context->setModuleName($resolver->getControllerShortName()); $context->setActionName($resolver->getMethodName()); $context->getRequest()->addParameters($queryParams); $request = $request ->withAttribute('extension', $resolver->getExtensionId()) ->withAttribute('controller', $resolver->getControllerShortName()) ->withAttribute('method', $resolver->getMethodName()); //execute the new action $enforcer = new ActionEnforcer( $resolver->getExtensionId(), $resolver->getControllerClass(), $resolver->getMethodName(), $params ); $this->propagate($enforcer); $enforcer( $request, $this->response->withHeader( 'X-Tao-Forward', $resolver->getExtensionId() . '/' . $resolver->getControllerShortName() . '/' . $resolver->getMethodName() ) ); throw new InterruptedActionException( 'Interrupted action after a forwardUrl', $context->getModuleName(), $context->getActionName() ); }
php
public function forwardUrl($url) { $uri = new Uri($url); $query = $uri->getQuery(); $queryParams = []; if (strlen($query) > 0) { parse_str($query, $queryParams); } switch ($this->getPsrRequest()->getMethod()) { case 'GET' : $params = $this->getPsrRequest()->getQueryParams(); break; case 'POST' : $params = $this->getPsrRequest()->getParsedBody(); break; default: $params = []; } $request = $this->getPsrRequest() ->withUri($uri) ->withQueryParams((array) $queryParams); //resolve the given URL for routing $resolver = new Resolver($request); $this->propagate($resolver); //update the context to the new route $context = \Context::getInstance(); $context->setExtensionName($resolver->getExtensionId()); $context->setModuleName($resolver->getControllerShortName()); $context->setActionName($resolver->getMethodName()); $context->getRequest()->addParameters($queryParams); $request = $request ->withAttribute('extension', $resolver->getExtensionId()) ->withAttribute('controller', $resolver->getControllerShortName()) ->withAttribute('method', $resolver->getMethodName()); //execute the new action $enforcer = new ActionEnforcer( $resolver->getExtensionId(), $resolver->getControllerClass(), $resolver->getMethodName(), $params ); $this->propagate($enforcer); $enforcer( $request, $this->response->withHeader( 'X-Tao-Forward', $resolver->getExtensionId() . '/' . $resolver->getControllerShortName() . '/' . $resolver->getMethodName() ) ); throw new InterruptedActionException( 'Interrupted action after a forwardUrl', $context->getModuleName(), $context->getActionName() ); }
[ "public", "function", "forwardUrl", "(", "$", "url", ")", "{", "$", "uri", "=", "new", "Uri", "(", "$", "url", ")", ";", "$", "query", "=", "$", "uri", "->", "getQuery", "(", ")", ";", "$", "queryParams", "=", "[", "]", ";", "if", "(", "strlen"...
Forward the action to execute regarding a URL The forward runs into tha same HTTP request unlike redirect. @param string $url the url to forward to @throws InterruptedActionException @throws \ResolverException @throws \common_exception_InconsistentData @throws \common_exception_InvalidArgumentType @throws \common_ext_ManifestNotFoundException
[ "Forward", "the", "action", "to", "execute", "regarding", "a", "URL", "The", "forward", "runs", "into", "tha", "same", "HTTP", "request", "unlike", "redirect", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/HttpFlowTrait.php#L83-L145
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.searchInstances
public function searchInstances($propertyFilters = [], core_kernel_classes_Class $topClazz = null, $options = []) { $returnValue = []; if (!is_null($topClazz)) { $returnValue = $topClazz->searchInstances($propertyFilters, $options); } return (array) $returnValue; }
php
public function searchInstances($propertyFilters = [], core_kernel_classes_Class $topClazz = null, $options = []) { $returnValue = []; if (!is_null($topClazz)) { $returnValue = $topClazz->searchInstances($propertyFilters, $options); } return (array) $returnValue; }
[ "public", "function", "searchInstances", "(", "$", "propertyFilters", "=", "[", "]", ",", "core_kernel_classes_Class", "$", "topClazz", "=", "null", ",", "$", "options", "=", "[", "]", ")", "{", "$", "returnValue", "=", "[", "]", ";", "if", "(", "!", "...
search the instances matching the filters in parameters @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param array propertyFilters @param core_kernel_classes_Class $topClazz @param array options @return \core_kernel_classes_Resource[]
[ "search", "the", "instances", "matching", "the", "filters", "in", "parameters" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L58-L66
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.createInstance
public function createInstance(core_kernel_classes_Class $clazz, $label = '') { if (empty($label)) { $label = $this->createUniqueLabel($clazz); } return core_kernel_classes_ResourceFactory::create($clazz, $label, ''); }
php
public function createInstance(core_kernel_classes_Class $clazz, $label = '') { if (empty($label)) { $label = $this->createUniqueLabel($clazz); } return core_kernel_classes_ResourceFactory::create($clazz, $label, ''); }
[ "public", "function", "createInstance", "(", "core_kernel_classes_Class", "$", "clazz", ",", "$", "label", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "label", ")", ")", "{", "$", "label", "=", "$", "this", "->", "createUniqueLabel", "(", "$", "...
Instantiate an RDFs Class @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Class $clazz @param string label @return core_kernel_classes_Resource @throws \common_exception_Error
[ "Instantiate", "an", "RDFs", "Class" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L78-L84
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.createUniqueLabel
public function createUniqueLabel(core_kernel_classes_Class $clazz, $subClassing = false) { if ($subClassing) { $labelBase = $clazz->getLabel() . '_' ; $count = count($clazz->getSubClasses()) +1; } else { $labelBase = $clazz->getLabel() . ' ' ; $count = count($clazz->getInstances()) +1; } $options = [ 'lang' => \common_session_SessionManager::getSession()->getDataLanguage(), 'like' => false, 'recursive' => false ]; do { $exist = false; $label = $labelBase . $count; $result = $clazz->searchInstances(array(OntologyRdfs::RDFS_LABEL => $label), $options); if (count($result) > 0) { $exist = true; $count ++; } } while ($exist); return (string) $label; }
php
public function createUniqueLabel(core_kernel_classes_Class $clazz, $subClassing = false) { if ($subClassing) { $labelBase = $clazz->getLabel() . '_' ; $count = count($clazz->getSubClasses()) +1; } else { $labelBase = $clazz->getLabel() . ' ' ; $count = count($clazz->getInstances()) +1; } $options = [ 'lang' => \common_session_SessionManager::getSession()->getDataLanguage(), 'like' => false, 'recursive' => false ]; do { $exist = false; $label = $labelBase . $count; $result = $clazz->searchInstances(array(OntologyRdfs::RDFS_LABEL => $label), $options); if (count($result) > 0) { $exist = true; $count ++; } } while ($exist); return (string) $label; }
[ "public", "function", "createUniqueLabel", "(", "core_kernel_classes_Class", "$", "clazz", ",", "$", "subClassing", "=", "false", ")", "{", "if", "(", "$", "subClassing", ")", "{", "$", "labelBase", "=", "$", "clazz", "->", "getLabel", "(", ")", ".", "'_'"...
Short description of method createUniqueLabel @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Class $clazz @param boolean $subClassing @throws \common_exception_Error @return string
[ "Short", "description", "of", "method", "createUniqueLabel" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L96-L123
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.createSubClass
public function createSubClass(core_kernel_classes_Class $parentClazz, $label = '') { if (empty($label)) { $label = $this->createUniqueLabel($parentClazz, true); } return $parentClazz->createSubClass($label, ''); }
php
public function createSubClass(core_kernel_classes_Class $parentClazz, $label = '') { if (empty($label)) { $label = $this->createUniqueLabel($parentClazz, true); } return $parentClazz->createSubClass($label, ''); }
[ "public", "function", "createSubClass", "(", "core_kernel_classes_Class", "$", "parentClazz", ",", "$", "label", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "label", ")", ")", "{", "$", "label", "=", "$", "this", "->", "createUniqueLabel", "(", "$...
Subclass an RDFS Class @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Class $parentClazz @param string $label @return core_kernel_classes_Class @throws \common_exception_Error
[ "Subclass", "an", "RDFS", "Class" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L135-L141
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.bindProperties
public function bindProperties(core_kernel_classes_Resource $instance, $properties = []) { $binder = new \tao_models_classes_dataBinding_GenerisInstanceDataBinder($instance); $binder->bind($properties); return $instance; }
php
public function bindProperties(core_kernel_classes_Resource $instance, $properties = []) { $binder = new \tao_models_classes_dataBinding_GenerisInstanceDataBinder($instance); $binder->bind($properties); return $instance; }
[ "public", "function", "bindProperties", "(", "core_kernel_classes_Resource", "$", "instance", ",", "$", "properties", "=", "[", "]", ")", "{", "$", "binder", "=", "new", "\\", "tao_models_classes_dataBinding_GenerisInstanceDataBinder", "(", "$", "instance", ")", ";"...
bind the given RDFS properties to the RDFS resource in parameter @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Resource $instance @param array properties @return core_kernel_classes_Resource @throws \tao_models_classes_dataBinding_GenerisInstanceDataBindingException
[ "bind", "the", "given", "RDFS", "properties", "to", "the", "RDFS", "resource", "in", "parameter" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L153-L159
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.cloneInstance
public function cloneInstance(core_kernel_classes_Resource $instance, core_kernel_classes_Class $clazz = null) { if (is_null($clazz)) { $types = $instance->getTypes(); $clazz = current($types); } $returnValue = $this->createInstance($clazz); if (!is_null($returnValue)) { $properties = $clazz->getProperties(true); foreach ($properties as $property) { $this->cloneInstanceProperty($instance, $returnValue, $property); } $label = $instance->getLabel(); $cloneLabel = "$label bis"; if (preg_match("/bis(\s[0-9]+)?$/", $label)) { $cloneNumber = (int)preg_replace("/^(.?)*bis/", "", $label); $cloneNumber++; $cloneLabel = preg_replace("/bis(\s[0-9]+)?$/", "", $label)."bis $cloneNumber" ; } $returnValue->setLabel($cloneLabel); } return $returnValue; }
php
public function cloneInstance(core_kernel_classes_Resource $instance, core_kernel_classes_Class $clazz = null) { if (is_null($clazz)) { $types = $instance->getTypes(); $clazz = current($types); } $returnValue = $this->createInstance($clazz); if (!is_null($returnValue)) { $properties = $clazz->getProperties(true); foreach ($properties as $property) { $this->cloneInstanceProperty($instance, $returnValue, $property); } $label = $instance->getLabel(); $cloneLabel = "$label bis"; if (preg_match("/bis(\s[0-9]+)?$/", $label)) { $cloneNumber = (int)preg_replace("/^(.?)*bis/", "", $label); $cloneNumber++; $cloneLabel = preg_replace("/bis(\s[0-9]+)?$/", "", $label)."bis $cloneNumber" ; } $returnValue->setLabel($cloneLabel); } return $returnValue; }
[ "public", "function", "cloneInstance", "(", "core_kernel_classes_Resource", "$", "instance", ",", "core_kernel_classes_Class", "$", "clazz", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "clazz", ")", ")", "{", "$", "types", "=", "$", "instance", "-...
duplicate a resource @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Resource $instance @param core_kernel_classes_Class $clazz @return core_kernel_classes_Resource @throws \League\Flysystem\FileExistsException @throws \common_Exception @throws \common_exception_Error
[ "duplicate", "a", "resource" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L173-L198
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.cloneClazz
public function cloneClazz( core_kernel_classes_Class $sourceClazz, core_kernel_classes_Class $newParentClazz = null, core_kernel_classes_Class $topLevelClazz = null ) { $returnValue = null; if (!is_null($sourceClazz) && !is_null($newParentClazz)) { if ((is_null($topLevelClazz))) { $properties = $sourceClazz->getProperties(false); } else { $properties = $this->getClazzProperties($sourceClazz, $topLevelClazz); } //check for duplicated properties $newParentProperties = $newParentClazz->getProperties(true); foreach ($properties as $index => $property) { foreach ($newParentProperties as $newParentProperty) { if ($property->getUri() == $newParentProperty->getUri()) { unset($properties[$index]); break; } } } //create a new class $returnValue = $this->createSubClass($newParentClazz, $sourceClazz->getLabel()); //assign the properties of the source class foreach ($properties as $property) { $property->setDomain($returnValue); } } return $returnValue; }
php
public function cloneClazz( core_kernel_classes_Class $sourceClazz, core_kernel_classes_Class $newParentClazz = null, core_kernel_classes_Class $topLevelClazz = null ) { $returnValue = null; if (!is_null($sourceClazz) && !is_null($newParentClazz)) { if ((is_null($topLevelClazz))) { $properties = $sourceClazz->getProperties(false); } else { $properties = $this->getClazzProperties($sourceClazz, $topLevelClazz); } //check for duplicated properties $newParentProperties = $newParentClazz->getProperties(true); foreach ($properties as $index => $property) { foreach ($newParentProperties as $newParentProperty) { if ($property->getUri() == $newParentProperty->getUri()) { unset($properties[$index]); break; } } } //create a new class $returnValue = $this->createSubClass($newParentClazz, $sourceClazz->getLabel()); //assign the properties of the source class foreach ($properties as $property) { $property->setDomain($returnValue); } } return $returnValue; }
[ "public", "function", "cloneClazz", "(", "core_kernel_classes_Class", "$", "sourceClazz", ",", "core_kernel_classes_Class", "$", "newParentClazz", "=", "null", ",", "core_kernel_classes_Class", "$", "topLevelClazz", "=", "null", ")", "{", "$", "returnValue", "=", "nul...
Clone a Class and move it under the newParentClazz @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Class $sourceClazz @param core_kernel_classes_Class $newParentClazz @param core_kernel_classes_Class $topLevelClazz @return core_kernel_classes_Class|null @throws \common_exception_Error
[ "Clone", "a", "Class", "and", "move", "it", "under", "the", "newParentClazz" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L259-L293
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.changeClass
public function changeClass(core_kernel_classes_Resource $instance, core_kernel_classes_Class $destinationClass) { if ($instance->isClass()) { try { /** @var core_kernel_classes_Class $instance */ return $instance->editPropertyValues($this->getProperty(OntologyRdfs::RDFS_SUBCLASSOF), $destinationClass); } catch (\Exception $e) { return false; } } else { try { foreach ($instance->getTypes() as $type) { $instance->removeType($type); } $instance->setType($destinationClass); foreach ($instance->getTypes() as $type) { if ($type->getUri() == $destinationClass->getUri()) { return true; } } } catch (\common_Exception $ce) { print $ce; return false; } } }
php
public function changeClass(core_kernel_classes_Resource $instance, core_kernel_classes_Class $destinationClass) { if ($instance->isClass()) { try { /** @var core_kernel_classes_Class $instance */ return $instance->editPropertyValues($this->getProperty(OntologyRdfs::RDFS_SUBCLASSOF), $destinationClass); } catch (\Exception $e) { return false; } } else { try { foreach ($instance->getTypes() as $type) { $instance->removeType($type); } $instance->setType($destinationClass); foreach ($instance->getTypes() as $type) { if ($type->getUri() == $destinationClass->getUri()) { return true; } } } catch (\common_Exception $ce) { print $ce; return false; } } }
[ "public", "function", "changeClass", "(", "core_kernel_classes_Resource", "$", "instance", ",", "core_kernel_classes_Class", "$", "destinationClass", ")", "{", "if", "(", "$", "instance", "->", "isClass", "(", ")", ")", "{", "try", "{", "/** @var core_kernel_classes...
Change the Class (RDF_TYPE) of a resource @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Resource $instance @param core_kernel_classes_Class $destinationClass @return boolean
[ "Change", "the", "Class", "(", "RDF_TYPE", ")", "of", "a", "resource" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L304-L329
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.getPropertyDiff
public function getPropertyDiff(core_kernel_classes_Class $sourceClass, core_kernel_classes_Class $destinationClass) { $returnValue = array(); $sourceProperties = $sourceClass->getProperties(true); $destinationProperties = $destinationClass->getProperties(true); foreach ($sourceProperties as $sourcePropertyUri => $sourceProperty) { if (!array_key_exists($sourcePropertyUri, $destinationProperties)) { $sourceProperty->getLabel(); array_push($returnValue, $sourceProperty); } } return (array) $returnValue; }
php
public function getPropertyDiff(core_kernel_classes_Class $sourceClass, core_kernel_classes_Class $destinationClass) { $returnValue = array(); $sourceProperties = $sourceClass->getProperties(true); $destinationProperties = $destinationClass->getProperties(true); foreach ($sourceProperties as $sourcePropertyUri => $sourceProperty) { if (!array_key_exists($sourcePropertyUri, $destinationProperties)) { $sourceProperty->getLabel(); array_push($returnValue, $sourceProperty); } } return (array) $returnValue; }
[ "public", "function", "getPropertyDiff", "(", "core_kernel_classes_Class", "$", "sourceClass", ",", "core_kernel_classes_Class", "$", "destinationClass", ")", "{", "$", "returnValue", "=", "array", "(", ")", ";", "$", "sourceProperties", "=", "$", "sourceClass", "->...
get the properties of the source class that are not in the destination @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Class $sourceClass @param core_kernel_classes_Class $destinationClass @return array
[ "get", "the", "properties", "of", "the", "source", "class", "that", "are", "not", "in", "the", "destination" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L407-L419
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.getTranslatedProperties
public function getTranslatedProperties(core_kernel_classes_Resource $instance, $lang) { $returnValue = array(); try { foreach ($instance->getTypes() as $clazz) { foreach ($clazz->getProperties(true) as $property) { if ($property->isLgDependent() || $property->getUri() == OntologyRdfs::RDFS_LABEL) { $collection = $instance->getPropertyValuesByLg($property, $lang); if ($collection->count() > 0) { if ($collection->count() == 1) { $returnValue[$property->getUri()] = (string)$collection->get(0); } else { $propData = array(); foreach ($collection->getIterator() as $collectionItem) { $propData[] = (string)$collectionItem; } $returnValue[$property->getUri()] = $propData; } } } } } } catch (\Exception $e) { print $e; } return (array) $returnValue; }
php
public function getTranslatedProperties(core_kernel_classes_Resource $instance, $lang) { $returnValue = array(); try { foreach ($instance->getTypes() as $clazz) { foreach ($clazz->getProperties(true) as $property) { if ($property->isLgDependent() || $property->getUri() == OntologyRdfs::RDFS_LABEL) { $collection = $instance->getPropertyValuesByLg($property, $lang); if ($collection->count() > 0) { if ($collection->count() == 1) { $returnValue[$property->getUri()] = (string)$collection->get(0); } else { $propData = array(); foreach ($collection->getIterator() as $collectionItem) { $propData[] = (string)$collectionItem; } $returnValue[$property->getUri()] = $propData; } } } } } } catch (\Exception $e) { print $e; } return (array) $returnValue; }
[ "public", "function", "getTranslatedProperties", "(", "core_kernel_classes_Resource", "$", "instance", ",", "$", "lang", ")", "{", "$", "returnValue", "=", "array", "(", ")", ";", "try", "{", "foreach", "(", "$", "instance", "->", "getTypes", "(", ")", "as",...
get the properties of an instance for a specific language @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Resource $instance @param string $lang @return array
[ "get", "the", "properties", "of", "an", "instance", "for", "a", "specific", "language" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L430-L458
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.toArray
public function toArray(core_kernel_classes_Class $clazz) { $returnValue = array(); $properties = $clazz->getProperties(false); foreach ($clazz->getInstances(false) as $instance) { $data = array(); foreach ($properties as $property) { $data[$property->getLabel()] = null; $values = $instance->getPropertyValues($property); if (count($values) > 1) { $data[$property->getLabel()] = $values; } elseif (count($values) == 1) { $data[$property->getLabel()] = $values[0]; } } array_push($returnValue, $data); } return (array) $returnValue; }
php
public function toArray(core_kernel_classes_Class $clazz) { $returnValue = array(); $properties = $clazz->getProperties(false); foreach ($clazz->getInstances(false) as $instance) { $data = array(); foreach ($properties as $property) { $data[$property->getLabel()] = null; $values = $instance->getPropertyValues($property); if (count($values) > 1) { $data[$property->getLabel()] = $values; } elseif (count($values) == 1) { $data[$property->getLabel()] = $values[0]; } } array_push($returnValue, $data); } return (array) $returnValue; }
[ "public", "function", "toArray", "(", "core_kernel_classes_Class", "$", "clazz", ")", "{", "$", "returnValue", "=", "array", "(", ")", ";", "$", "properties", "=", "$", "clazz", "->", "getProperties", "(", "false", ")", ";", "foreach", "(", "$", "clazz", ...
Format an RDFS Class to an array @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Class $clazz @return array
[ "Format", "an", "RDFS", "Class", "to", "an", "array" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L468-L486
oat-sa/tao-core
models/classes/GenerisServiceTrait.php
GenerisServiceTrait.toTree
public function toTree(core_kernel_classes_Class $clazz, array $options = array()) { $searchOptions = []; // show instances yes/no $instances = (isset($options['instances'])) ? $options['instances'] : true; // cut of the class and only display the children? $chunk = (isset($options['chunk'])) ? $options['chunk'] : false; // probably which subtrees should be opened $browse = (isset($options['browse'])) ? $options['browse'] : array(); // limit of instances shown by subclass if no search label is given // if a search string is given, this is the total limit of results, independent of classes $limit = (isset($options['limit'])) ? $options['limit'] : 0; // offset for limit $offset = (isset($options['offset'])) ? $options['offset'] : 0; // A unique node URI to be returned from as a tree leaf. $uniqueNode = (isset($options['uniqueNode'])) ? $options['uniqueNode'] : null; if (isset($options['order']) && isset($options['orderdir'])) { $searchOptions['order'] = [$options['order'] => $options['orderdir']]; } if ($uniqueNode !== null) { $instance = new \core_kernel_classes_Resource($uniqueNode); $results[] = TreeHelper::buildResourceNode($instance, $clazz); $returnValue = $results; } else { // Let's walk the tree with super walker! ~~~ p==[w]õ__ array_walk($browse, function (&$item) { $item = \tao_helpers_Uri::decode($item); }); $openNodes = TreeHelper::getNodesToOpen($browse, $clazz); if (!in_array($clazz->getUri(), $openNodes)) { $openNodes[] = $clazz->getUri(); } $factory = new GenerisTreeFactory($instances, $openNodes, $limit, $offset, $browse, $this->getDefaultFilters(), $searchOptions); $tree = $factory->buildTree($clazz); $returnValue = $chunk ? (isset($tree['children']) ? $tree['children'] : array()) : $tree; } return $returnValue; }
php
public function toTree(core_kernel_classes_Class $clazz, array $options = array()) { $searchOptions = []; // show instances yes/no $instances = (isset($options['instances'])) ? $options['instances'] : true; // cut of the class and only display the children? $chunk = (isset($options['chunk'])) ? $options['chunk'] : false; // probably which subtrees should be opened $browse = (isset($options['browse'])) ? $options['browse'] : array(); // limit of instances shown by subclass if no search label is given // if a search string is given, this is the total limit of results, independent of classes $limit = (isset($options['limit'])) ? $options['limit'] : 0; // offset for limit $offset = (isset($options['offset'])) ? $options['offset'] : 0; // A unique node URI to be returned from as a tree leaf. $uniqueNode = (isset($options['uniqueNode'])) ? $options['uniqueNode'] : null; if (isset($options['order']) && isset($options['orderdir'])) { $searchOptions['order'] = [$options['order'] => $options['orderdir']]; } if ($uniqueNode !== null) { $instance = new \core_kernel_classes_Resource($uniqueNode); $results[] = TreeHelper::buildResourceNode($instance, $clazz); $returnValue = $results; } else { // Let's walk the tree with super walker! ~~~ p==[w]õ__ array_walk($browse, function (&$item) { $item = \tao_helpers_Uri::decode($item); }); $openNodes = TreeHelper::getNodesToOpen($browse, $clazz); if (!in_array($clazz->getUri(), $openNodes)) { $openNodes[] = $clazz->getUri(); } $factory = new GenerisTreeFactory($instances, $openNodes, $limit, $offset, $browse, $this->getDefaultFilters(), $searchOptions); $tree = $factory->buildTree($clazz); $returnValue = $chunk ? (isset($tree['children']) ? $tree['children'] : array()) : $tree; } return $returnValue; }
[ "public", "function", "toTree", "(", "core_kernel_classes_Class", "$", "clazz", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "searchOptions", "=", "[", "]", ";", "// show instances yes/no", "$", "instances", "=", "(", "isset", "(", ...
Format an RDFS Class to an array to be interpreted by the client tree This is a closed array format. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param core_kernel_classes_Class $clazz @param array $options @return array @throws \common_exception_Error
[ "Format", "an", "RDFS", "Class", "to", "an", "array", "to", "be", "interpreted", "by", "the", "client", "tree", "This", "is", "a", "closed", "array", "format", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/GenerisServiceTrait.php#L499-L542
oat-sa/tao-core
models/classes/search/index/OntologyIndexService.php
OntologyIndexService.createIndex
static public function createIndex(\core_kernel_classes_Property $property, $identifier, \core_kernel_classes_Resource $tokenizer, $isFuzzyMatching, $isDefaultSearchable) { $class = new \core_kernel_classes_Class(OntologyIndex::RDF_TYPE); $existingIndex = self::getIndexById($identifier); if (!is_null($existingIndex)) { throw new \common_Exception('Index '.$identifier.' already in use'); } // verify identifier is unused $resource = $class->createInstanceWithProperties(array( OntologyRdfs::RDFS_LABEL => $identifier, OntologyIndex::PROPERTY_INDEX_IDENTIFIER => $identifier, OntologyIndex::PROPERTY_INDEX_TOKENIZER => $tokenizer, OntologyIndex::PROPERTY_INDEX_FUZZY_MATCHING => $isFuzzyMatching ? GenerisRdf::GENERIS_TRUE : GenerisRdf::GENERIS_FALSE, OntologyIndex::PROPERTY_DEFAULT_SEARCH => $isDefaultSearchable ? GenerisRdf::GENERIS_TRUE : GenerisRdf::GENERIS_FALSE )); $property->setPropertyValue(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX), $resource); return new OntologyIndex($resource); }
php
static public function createIndex(\core_kernel_classes_Property $property, $identifier, \core_kernel_classes_Resource $tokenizer, $isFuzzyMatching, $isDefaultSearchable) { $class = new \core_kernel_classes_Class(OntologyIndex::RDF_TYPE); $existingIndex = self::getIndexById($identifier); if (!is_null($existingIndex)) { throw new \common_Exception('Index '.$identifier.' already in use'); } // verify identifier is unused $resource = $class->createInstanceWithProperties(array( OntologyRdfs::RDFS_LABEL => $identifier, OntologyIndex::PROPERTY_INDEX_IDENTIFIER => $identifier, OntologyIndex::PROPERTY_INDEX_TOKENIZER => $tokenizer, OntologyIndex::PROPERTY_INDEX_FUZZY_MATCHING => $isFuzzyMatching ? GenerisRdf::GENERIS_TRUE : GenerisRdf::GENERIS_FALSE, OntologyIndex::PROPERTY_DEFAULT_SEARCH => $isDefaultSearchable ? GenerisRdf::GENERIS_TRUE : GenerisRdf::GENERIS_FALSE )); $property->setPropertyValue(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX), $resource); return new OntologyIndex($resource); }
[ "static", "public", "function", "createIndex", "(", "\\", "core_kernel_classes_Property", "$", "property", ",", "$", "identifier", ",", "\\", "core_kernel_classes_Resource", "$", "tokenizer", ",", "$", "isFuzzyMatching", ",", "$", "isDefaultSearchable", ")", "{", "$...
Create a new index @param \core_kernel_classes_Property $property @param unknown $identifier @param \core_kernel_classes_Resource $tokenizer @param unknown $isFuzzyMatching @param unknown $isDefaultSearchable @return OntologyIndex
[ "Create", "a", "new", "index" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/search/index/OntologyIndexService.php#L45-L62
oat-sa/tao-core
models/classes/search/index/OntologyIndexService.php
OntologyIndexService.getIndexById
static public function getIndexById($identifier) { $indexClass = new core_kernel_classes_Class(OntologyIndex::RDF_TYPE); $resources = $indexClass->searchInstances(array( OntologyIndex::PROPERTY_INDEX_IDENTIFIER => $identifier ),array('like' => false) ); if (count($resources) > 1) { throw new \common_exception_InconsistentData("Several index exist with the identifier ".$identifier); } return count($resources) > 0 ? new OntologyIndex(array_shift($resources)) : null; }
php
static public function getIndexById($identifier) { $indexClass = new core_kernel_classes_Class(OntologyIndex::RDF_TYPE); $resources = $indexClass->searchInstances(array( OntologyIndex::PROPERTY_INDEX_IDENTIFIER => $identifier ),array('like' => false) ); if (count($resources) > 1) { throw new \common_exception_InconsistentData("Several index exist with the identifier ".$identifier); } return count($resources) > 0 ? new OntologyIndex(array_shift($resources)) : null; }
[ "static", "public", "function", "getIndexById", "(", "$", "identifier", ")", "{", "$", "indexClass", "=", "new", "core_kernel_classes_Class", "(", "OntologyIndex", "::", "RDF_TYPE", ")", ";", "$", "resources", "=", "$", "indexClass", "->", "searchInstances", "("...
Get an index by its unique index id @param string $identifier @throws \common_exception_InconsistentData @return OntologyIndex
[ "Get", "an", "index", "by", "its", "unique", "index", "id" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/search/index/OntologyIndexService.php#L71-L84
oat-sa/tao-core
models/classes/search/index/OntologyIndexService.php
OntologyIndexService.getIndexes
static public function getIndexes(\core_kernel_classes_Property $property) { $indexUris = $property->getPropertyValues(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX)); $indexes = array(); foreach ($indexUris as $indexUri) { $indexes[] = new OntologyIndex($indexUri); } return $indexes; }
php
static public function getIndexes(\core_kernel_classes_Property $property) { $indexUris = $property->getPropertyValues(new \core_kernel_classes_Property(OntologyIndex::PROPERTY_INDEX)); $indexes = array(); foreach ($indexUris as $indexUri) { $indexes[] = new OntologyIndex($indexUri); } return $indexes; }
[ "static", "public", "function", "getIndexes", "(", "\\", "core_kernel_classes_Property", "$", "property", ")", "{", "$", "indexUris", "=", "$", "property", "->", "getPropertyValues", "(", "new", "\\", "core_kernel_classes_Property", "(", "OntologyIndex", "::", "PROP...
Get all indexes of a property @param \core_kernel_classes_Property $property @return multitype:OntologyIndex
[ "Get", "all", "indexes", "of", "a", "property" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/search/index/OntologyIndexService.php#L92-L101
oat-sa/tao-core
models/classes/search/index/OntologyIndexService.php
OntologyIndexService.getIndexesByClass
static public function getIndexesByClass(\core_kernel_classes_Class $class, $recursive = true) { $returnedIndexes = array(); // Get properties to the root class hierarchy. $properties = $class->getProperties(true); foreach ($properties as $prop) { $propUri = $prop->getUri(); $indexes = self::getIndexes($prop); if (count($indexes) > 0) { if (isset($returnedIndexes[$propUri]) === false) { $returnedIndexes[$propUri] = array(); } foreach ($indexes as $index) { $returnedIndexes[$propUri][] = new OntologyIndex($index->getUri()); } } } return $returnedIndexes; }
php
static public function getIndexesByClass(\core_kernel_classes_Class $class, $recursive = true) { $returnedIndexes = array(); // Get properties to the root class hierarchy. $properties = $class->getProperties(true); foreach ($properties as $prop) { $propUri = $prop->getUri(); $indexes = self::getIndexes($prop); if (count($indexes) > 0) { if (isset($returnedIndexes[$propUri]) === false) { $returnedIndexes[$propUri] = array(); } foreach ($indexes as $index) { $returnedIndexes[$propUri][] = new OntologyIndex($index->getUri()); } } } return $returnedIndexes; }
[ "static", "public", "function", "getIndexesByClass", "(", "\\", "core_kernel_classes_Class", "$", "class", ",", "$", "recursive", "=", "true", ")", "{", "$", "returnedIndexes", "=", "array", "(", ")", ";", "// Get properties to the root class hierarchy.", "$", "prop...
Get the Search Indexes of a given $class. The returned array is an associative array where keys are the Property URI the Search Index belongs to, and the values are core_kernel_classes_Resource objects corresponding to Search Index definitions. @param \core_kernel_classes_Class $class @param boolean $recursive Whether or not to look for Search Indexes that belong to sub-classes of $class. Default is true. @return OntologyIndex[] An array of Search Index to $class.
[ "Get", "the", "Search", "Indexes", "of", "a", "given", "$class", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/search/index/OntologyIndexService.php#L114-L137
oat-sa/tao-core
actions/form/class.Users.php
tao_actions_form_Users.initForm
protected function initForm() { parent::initForm(); $this->form->setName($this->formName); $actions = tao_helpers_form_FormFactory::getCommonActions('top'); $this->form->setActions($actions, 'top'); $this->form->setActions($actions, 'bottom'); }
php
protected function initForm() { parent::initForm(); $this->form->setName($this->formName); $actions = tao_helpers_form_FormFactory::getCommonActions('top'); $this->form->setActions($actions, 'top'); $this->form->setActions($actions, 'bottom'); }
[ "protected", "function", "initForm", "(", ")", "{", "parent", "::", "initForm", "(", ")", ";", "$", "this", "->", "form", "->", "setName", "(", "$", "this", "->", "formName", ")", ";", "$", "actions", "=", "tao_helpers_form_FormFactory", "::", "getCommonAc...
Short description of method initForm @access protected @author Joel Bout, <joel.bout@tudor.lu> @return mixed
[ "Short", "description", "of", "method", "initForm" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Users.php#L134-L143
oat-sa/tao-core
actions/form/class.Users.php
tao_actions_form_Users.initElements
protected function initElements() { if(!isset($this->options['mode'])){ throw new Exception("Please set a mode into container options "); } parent::initElements(); //login field $loginElement = $this->form->getElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_LOGIN)); if($this->options['mode'] === 'add'){ $loginElement->addValidators(array( tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('Callback', array( 'object' => tao_models_classes_UserService::singleton(), 'method' => 'loginAvailable', 'message' => __('This Login is already in use') )) )); } else{ $loginElement->setAttributes(array('readonly' => 'readonly', 'disabled' => 'disabled')); } //set default lang to the languages fields $langService = tao_models_classes_LanguageService::singleton(); $userLangService = \oat\oatbox\service\ServiceManager::getServiceManager()->get(UserLanguageServiceInterface::class); if ($userLangService->isDataLanguageEnabled()) { $dataLangElt = $this->form->getElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_DEFLG)); $dataLangElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); $dataUsage = new core_kernel_classes_Resource(tao_models_classes_LanguageService::INSTANCE_LANGUAGE_USAGE_DATA); $dataOptions = array(); foreach($langService->getAvailableLanguagesByUsage($dataUsage) as $lang){ $dataOptions[tao_helpers_Uri::encode($lang->getUri())] = $lang->getLabel(); } $dataLangElt->setOptions($dataOptions); } $uiLangElt = $this->form->getElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_UILG)); $uiLangElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); $guiUsage = new core_kernel_classes_Resource(tao_models_classes_LanguageService::INSTANCE_LANGUAGE_USAGE_GUI); $guiOptions = array(); foreach($langService->getAvailableLanguagesByUsage($guiUsage) as $lang){ $guiOptions[tao_helpers_Uri::encode($lang->getUri())] = $lang->getLabel(); } $uiLangElt->setOptions($guiOptions); // roles field $property = new core_kernel_classes_Property(GenerisRdf::PROPERTY_USER_ROLES); $roles = $property->getRange()->getInstances(true); $rolesOptions = array(); foreach ($roles as $r){ $rolesOptions[tao_helpers_Uri::encode($r->getUri())] = $r->getLabel(); } asort($rolesOptions); $userService = tao_models_classes_UserService::singleton(); $rolesOptions = $userService->getPermittedRoles($userService->getCurrentUser(), $rolesOptions); $rolesElt = $this->form->getElement(tao_helpers_Uri::encode($property->getUri())); $rolesElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); $rolesElt->setOptions($rolesOptions); // password field $this->form->removeElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_PASSWORD)); if($this->options['mode'] === 'add'){ $pass1Element = tao_helpers_form_FormFactory::getElement('password1', 'Hiddenbox'); $pass1Element->setDescription(__('Password')); $pass1Element->addValidator( tao_helpers_form_FormFactory::getValidator( 'NotEmpty' ) ); $pass1Element->addValidators( PasswordConstraintsService::singleton()->getValidators() ); $pass1Element->setBreakOnFirstError( false ); $this->form->addElement($pass1Element); $pass2Element = tao_helpers_form_FormFactory::getElement('password2', 'Hiddenbox'); $pass2Element->setDescription(__('Repeat password')); $pass2Element->addValidators(array( tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('Password', array('password2_ref' => $pass1Element)), )); $this->form->addElement($pass2Element); } else { if (ApplicationHelper::isDemo()) { $warning = tao_helpers_form_FormFactory::getElement('warningpass', 'Label'); $warning->setValue(__('Unable to change passwords in demo mode')); $this->form->addElement($warning); $this->form->createGroup("pass_group", __("Change the password"), array('warningpass')); } else { $pass2Element = tao_helpers_form_FormFactory::getElement('password2', 'Hiddenbox'); $pass2Element->setDescription(__('New password')); $pass2Element->addValidators( PasswordConstraintsService::singleton()->getValidators() ); $pass2Element->setBreakOnFirstError(false); $this->form->addElement($pass2Element); $pass3Element = tao_helpers_form_FormFactory::getElement('password3', 'Hiddenbox'); $pass3Element->setDescription(__('Repeat new password')); $pass3Element->addValidators(array( tao_helpers_form_FormFactory::getValidator('Password', array('password2_ref' => $pass2Element)), )); $this->form->addElement($pass3Element); $this->form->createGroup("pass_group", __("Change the password"), array('password2', 'password3')); if (empty($_POST[$pass2Element->getName()]) && empty($_POST[$pass3Element->getName()])) { $pass2Element->setForcedValid(); $pass3Element->setForcedValid(); } } } }
php
protected function initElements() { if(!isset($this->options['mode'])){ throw new Exception("Please set a mode into container options "); } parent::initElements(); //login field $loginElement = $this->form->getElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_LOGIN)); if($this->options['mode'] === 'add'){ $loginElement->addValidators(array( tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('Callback', array( 'object' => tao_models_classes_UserService::singleton(), 'method' => 'loginAvailable', 'message' => __('This Login is already in use') )) )); } else{ $loginElement->setAttributes(array('readonly' => 'readonly', 'disabled' => 'disabled')); } //set default lang to the languages fields $langService = tao_models_classes_LanguageService::singleton(); $userLangService = \oat\oatbox\service\ServiceManager::getServiceManager()->get(UserLanguageServiceInterface::class); if ($userLangService->isDataLanguageEnabled()) { $dataLangElt = $this->form->getElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_DEFLG)); $dataLangElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); $dataUsage = new core_kernel_classes_Resource(tao_models_classes_LanguageService::INSTANCE_LANGUAGE_USAGE_DATA); $dataOptions = array(); foreach($langService->getAvailableLanguagesByUsage($dataUsage) as $lang){ $dataOptions[tao_helpers_Uri::encode($lang->getUri())] = $lang->getLabel(); } $dataLangElt->setOptions($dataOptions); } $uiLangElt = $this->form->getElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_UILG)); $uiLangElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); $guiUsage = new core_kernel_classes_Resource(tao_models_classes_LanguageService::INSTANCE_LANGUAGE_USAGE_GUI); $guiOptions = array(); foreach($langService->getAvailableLanguagesByUsage($guiUsage) as $lang){ $guiOptions[tao_helpers_Uri::encode($lang->getUri())] = $lang->getLabel(); } $uiLangElt->setOptions($guiOptions); // roles field $property = new core_kernel_classes_Property(GenerisRdf::PROPERTY_USER_ROLES); $roles = $property->getRange()->getInstances(true); $rolesOptions = array(); foreach ($roles as $r){ $rolesOptions[tao_helpers_Uri::encode($r->getUri())] = $r->getLabel(); } asort($rolesOptions); $userService = tao_models_classes_UserService::singleton(); $rolesOptions = $userService->getPermittedRoles($userService->getCurrentUser(), $rolesOptions); $rolesElt = $this->form->getElement(tao_helpers_Uri::encode($property->getUri())); $rolesElt->addValidator(tao_helpers_form_FormFactory::getValidator('NotEmpty')); $rolesElt->setOptions($rolesOptions); // password field $this->form->removeElement(tao_helpers_Uri::encode(GenerisRdf::PROPERTY_USER_PASSWORD)); if($this->options['mode'] === 'add'){ $pass1Element = tao_helpers_form_FormFactory::getElement('password1', 'Hiddenbox'); $pass1Element->setDescription(__('Password')); $pass1Element->addValidator( tao_helpers_form_FormFactory::getValidator( 'NotEmpty' ) ); $pass1Element->addValidators( PasswordConstraintsService::singleton()->getValidators() ); $pass1Element->setBreakOnFirstError( false ); $this->form->addElement($pass1Element); $pass2Element = tao_helpers_form_FormFactory::getElement('password2', 'Hiddenbox'); $pass2Element->setDescription(__('Repeat password')); $pass2Element->addValidators(array( tao_helpers_form_FormFactory::getValidator('NotEmpty'), tao_helpers_form_FormFactory::getValidator('Password', array('password2_ref' => $pass1Element)), )); $this->form->addElement($pass2Element); } else { if (ApplicationHelper::isDemo()) { $warning = tao_helpers_form_FormFactory::getElement('warningpass', 'Label'); $warning->setValue(__('Unable to change passwords in demo mode')); $this->form->addElement($warning); $this->form->createGroup("pass_group", __("Change the password"), array('warningpass')); } else { $pass2Element = tao_helpers_form_FormFactory::getElement('password2', 'Hiddenbox'); $pass2Element->setDescription(__('New password')); $pass2Element->addValidators( PasswordConstraintsService::singleton()->getValidators() ); $pass2Element->setBreakOnFirstError(false); $this->form->addElement($pass2Element); $pass3Element = tao_helpers_form_FormFactory::getElement('password3', 'Hiddenbox'); $pass3Element->setDescription(__('Repeat new password')); $pass3Element->addValidators(array( tao_helpers_form_FormFactory::getValidator('Password', array('password2_ref' => $pass2Element)), )); $this->form->addElement($pass3Element); $this->form->createGroup("pass_group", __("Change the password"), array('password2', 'password3')); if (empty($_POST[$pass2Element->getName()]) && empty($_POST[$pass3Element->getName()])) { $pass2Element->setForcedValid(); $pass3Element->setForcedValid(); } } } }
[ "protected", "function", "initElements", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "options", "[", "'mode'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "\"Please set a mode into container options \"", ")", ";", "}", "parent",...
Short description of method initElements @access protected @author Joel Bout, <joel.bout@tudor.lu>
[ "Short", "description", "of", "method", "initElements" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Users.php#L151-L264
oat-sa/tao-core
models/classes/menu/Action.php
Action.inferLegacyIcon
private function inferLegacyIcon(){ $ext = $this->getExtensionId(); $name = strtolower(\tao_helpers_Display::textCleaner($this->data['name'])); $file = $ext . '/views/img/actions/' . $name . '.png'; $src = 'actions/' . $name . '.png'; if(file_exists(ROOT_PATH . $file)) { return Icon::fromArray(array('src' => $src), $ext); } else if (file_exists(ROOT_PATH . 'tao/views/img/actions/' . $name . '.png')){ return Icon::fromArray(array('src' => $src), 'tao'); } else { return Icon::fromArray(array('src' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAAAnRSTlMA/1uRIrUAAAAKSURBVHjaY/gPAAEBAQAcsIyZAAAAAElFTkSuQmCC'), 'tao'); } }
php
private function inferLegacyIcon(){ $ext = $this->getExtensionId(); $name = strtolower(\tao_helpers_Display::textCleaner($this->data['name'])); $file = $ext . '/views/img/actions/' . $name . '.png'; $src = 'actions/' . $name . '.png'; if(file_exists(ROOT_PATH . $file)) { return Icon::fromArray(array('src' => $src), $ext); } else if (file_exists(ROOT_PATH . 'tao/views/img/actions/' . $name . '.png')){ return Icon::fromArray(array('src' => $src), 'tao'); } else { return Icon::fromArray(array('src' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAAAnRSTlMA/1uRIrUAAAAKSURBVHjaY/gPAAEBAQAcsIyZAAAAAElFTkSuQmCC'), 'tao'); } }
[ "private", "function", "inferLegacyIcon", "(", ")", "{", "$", "ext", "=", "$", "this", "->", "getExtensionId", "(", ")", ";", "$", "name", "=", "strtolower", "(", "\\", "tao_helpers_Display", "::", "textCleaner", "(", "$", "this", "->", "data", "[", "'na...
Try to get the action's icon the old way. I/O impact (file_exists) is limited as the results can be serialized. @return Icon the icon with the src property set to the icon URL.
[ "Try", "to", "get", "the", "action", "s", "icon", "the", "old", "way", ".", "I", "/", "O", "impact", "(", "file_exists", ")", "is", "limited", "as", "the", "results", "can", "be", "serialized", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/menu/Action.php#L158-L170
oat-sa/tao-core
models/classes/menu/Action.php
Action.hasAccess
public function hasAccess() { \common_Logger::w('Call to deprecated method ' . __METHOD__ . ' in ' . __CLASS__); $access = true; if (!empty($this->data['url'])) { $access = tao_models_classes_accessControl_AclProxy::hasAccess( $this->data['action'], $this->data['controller'], $this->data['extension'] ); } return $access; }
php
public function hasAccess() { \common_Logger::w('Call to deprecated method ' . __METHOD__ . ' in ' . __CLASS__); $access = true; if (!empty($this->data['url'])) { $access = tao_models_classes_accessControl_AclProxy::hasAccess( $this->data['action'], $this->data['controller'], $this->data['extension'] ); } return $access; }
[ "public", "function", "hasAccess", "(", ")", "{", "\\", "common_Logger", "::", "w", "(", "'Call to deprecated method '", ".", "__METHOD__", ".", "' in '", ".", "__CLASS__", ")", ";", "$", "access", "=", "true", ";", "if", "(", "!", "empty", "(", "$", "th...
Check whether the current is allowed to see this action (against ACL). @deprecated Wrong layer. Should be called at the level of the controller @return bool true if access is granted
[ "Check", "whether", "the", "current", "is", "allowed", "to", "see", "this", "action", "(", "against", "ACL", ")", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/menu/Action.php#L177-L190
oat-sa/tao-core
install/services/class.CheckDatabaseConnectionService.php
tao_install_services_CheckDatabaseConnectionService.execute
public function execute(){ $ext = self::buildComponent($this->getData()); $report = $ext->check(); $this->setResult(self::buildResult($this->getData(), $report, $ext)); }
php
public function execute(){ $ext = self::buildComponent($this->getData()); $report = $ext->check(); $this->setResult(self::buildResult($this->getData(), $report, $ext)); }
[ "public", "function", "execute", "(", ")", "{", "$", "ext", "=", "self", "::", "buildComponent", "(", "$", "this", "->", "getData", "(", ")", ")", ";", "$", "report", "=", "$", "ext", "->", "check", "(", ")", ";", "$", "this", "->", "setResult", ...
Executes the main logic of the service. @return tao_install_services_Data The result of the service execution.
[ "Executes", "the", "main", "logic", "of", "the", "service", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/services/class.CheckDatabaseConnectionService.php#L52-L56
oat-sa/tao-core
models/classes/import/ImportHandlerHelperTrait.php
ImportHandlerHelperTrait.fetchUploadedFile
protected function fetchUploadedFile($form) { $file = ''; // for backward compatibility if ($form instanceof \tao_helpers_form_Form) { $fileInfo = $form->getValue('source'); /** @var string $file */ $file = $form->getValue('importFile') ?: $fileInfo['uploaded_file']; // key "importFile" used in CSV import } else if (isset($form['uploaded_file'])) { /** @var File $file */ $file = $this->getUploadService()->getUploadDir()->getFile($form['uploaded_file']); } if (!$file) { throw new \common_exception_Error('No source file for import'); } return $file; }
php
protected function fetchUploadedFile($form) { $file = ''; // for backward compatibility if ($form instanceof \tao_helpers_form_Form) { $fileInfo = $form->getValue('source'); /** @var string $file */ $file = $form->getValue('importFile') ?: $fileInfo['uploaded_file']; // key "importFile" used in CSV import } else if (isset($form['uploaded_file'])) { /** @var File $file */ $file = $this->getUploadService()->getUploadDir()->getFile($form['uploaded_file']); } if (!$file) { throw new \common_exception_Error('No source file for import'); } return $file; }
[ "protected", "function", "fetchUploadedFile", "(", "$", "form", ")", "{", "$", "file", "=", "''", ";", "// for backward compatibility", "if", "(", "$", "form", "instanceof", "\\", "tao_helpers_form_Form", ")", "{", "$", "fileInfo", "=", "$", "form", "->", "g...
Helps to get the uploaded file data during upload or during processing of the import task. @param array|\tao_helpers_form_Form $form @return File|string @throws \common_exception_Error
[ "Helps", "to", "get", "the", "uploaded", "file", "data", "during", "upload", "or", "during", "processing", "of", "the", "import", "task", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/import/ImportHandlerHelperTrait.php#L38-L58
oat-sa/tao-core
models/classes/taskQueue/TaskLog/TaskLogCollection.php
TaskLogCollection.createFromArray
public static function createFromArray(array $rows) { $logs = []; foreach ($rows as $row) { $logs[] = TaskLogEntity::createFromArray($row); } return new static($logs); }
php
public static function createFromArray(array $rows) { $logs = []; foreach ($rows as $row) { $logs[] = TaskLogEntity::createFromArray($row); } return new static($logs); }
[ "public", "static", "function", "createFromArray", "(", "array", "$", "rows", ")", "{", "$", "logs", "=", "[", "]", ";", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "$", "logs", "[", "]", "=", "TaskLogEntity", "::", "createFromArray", "(...
@param array $rows @return TaskLogCollection @throws \Exception
[ "@param", "array", "$rows", "@return", "TaskLogCollection" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLog/TaskLogCollection.php#L45-L54
oat-sa/tao-core
models/classes/export/JsonLdExport.php
JsonLdExport.jsonSerialize
public function jsonSerialize() { $data = [ '@context' => [], '@id' => $this->uri, ]; $types = $this->types; if (!empty($types)) { $data['@type'] = $this->transfromArray($types); } if (!$this->triples instanceof \core_kernel_classes_ContainerCollection) { return $data; } $triples = $this->triples->toArray(); $map = []; foreach ($triples as $key => $triple) { if (in_array($triple->predicate, $this->blackList)) { continue; } if (!isset($map[$triple->predicate])) { $id = $this->generateId($triple->predicate); if (in_array($id, $map)) { $nr = 0; while (in_array($id . '_' . $nr, $map)) { $nr++; } $id = $id . '_' . $nr; } $map[$triple->predicate] = $id; $data['@context'][$id] = $triple->predicate; } $key = $map[$triple->predicate]; if (isset($data[$key])) { if (!is_array($data[$key])) { $data[$key] = array($data[$key]); } $data[$key][] = $this->encodeValue($triple->object, $triple->predicate); } else { $data[$key] = $this->encodeValue($triple->object, $triple->predicate); } } // Enforce serialization to object if context is empty $data['@context'] = (object) $data['@context']; return $data; }
php
public function jsonSerialize() { $data = [ '@context' => [], '@id' => $this->uri, ]; $types = $this->types; if (!empty($types)) { $data['@type'] = $this->transfromArray($types); } if (!$this->triples instanceof \core_kernel_classes_ContainerCollection) { return $data; } $triples = $this->triples->toArray(); $map = []; foreach ($triples as $key => $triple) { if (in_array($triple->predicate, $this->blackList)) { continue; } if (!isset($map[$triple->predicate])) { $id = $this->generateId($triple->predicate); if (in_array($id, $map)) { $nr = 0; while (in_array($id . '_' . $nr, $map)) { $nr++; } $id = $id . '_' . $nr; } $map[$triple->predicate] = $id; $data['@context'][$id] = $triple->predicate; } $key = $map[$triple->predicate]; if (isset($data[$key])) { if (!is_array($data[$key])) { $data[$key] = array($data[$key]); } $data[$key][] = $this->encodeValue($triple->object, $triple->predicate); } else { $data[$key] = $this->encodeValue($triple->object, $triple->predicate); } } // Enforce serialization to object if context is empty $data['@context'] = (object) $data['@context']; return $data; }
[ "public", "function", "jsonSerialize", "(", ")", "{", "$", "data", "=", "[", "'@context'", "=>", "[", "]", ",", "'@id'", "=>", "$", "this", "->", "uri", ",", "]", ";", "$", "types", "=", "$", "this", "->", "types", ";", "if", "(", "!", "empty", ...
(non-PHPdoc) @see JsonSerializable::jsonSerialize()
[ "(", "non", "-", "PHPdoc", ")" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/export/JsonLdExport.php#L120-L170
oat-sa/tao-core
models/classes/export/JsonLdExport.php
JsonLdExport.transfromArray
private function transfromArray($values) { if (count($values) > 1) { $encoded = array(); foreach ($values as $value) { $encoded[] = $this->encodeValue($value); } return $encoded; } else { return $this->encodeValue(reset($values)); } }
php
private function transfromArray($values) { if (count($values) > 1) { $encoded = array(); foreach ($values as $value) { $encoded[] = $this->encodeValue($value); } return $encoded; } else { return $this->encodeValue(reset($values)); } }
[ "private", "function", "transfromArray", "(", "$", "values", ")", "{", "if", "(", "count", "(", "$", "values", ")", ">", "1", ")", "{", "$", "encoded", "=", "array", "(", ")", ";", "foreach", "(", "$", "values", "as", "$", "value", ")", "{", "$",...
Encode a values array @param array $values @return mixed
[ "Encode", "a", "values", "array" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/export/JsonLdExport.php#L188-L199
oat-sa/tao-core
models/classes/export/JsonLdExport.php
JsonLdExport.encodeValue
protected function encodeValue($value, $propertyUri = '') { $value = $this->applyEncoder($value, $propertyUri); return is_string($value) ? $value : ((is_object($value) && $value instanceof \core_kernel_classes_Resource) ? $value->getUri() : (string) $value ); }
php
protected function encodeValue($value, $propertyUri = '') { $value = $this->applyEncoder($value, $propertyUri); return is_string($value) ? $value : ((is_object($value) && $value instanceof \core_kernel_classes_Resource) ? $value->getUri() : (string) $value ); }
[ "protected", "function", "encodeValue", "(", "$", "value", ",", "$", "propertyUri", "=", "''", ")", "{", "$", "value", "=", "$", "this", "->", "applyEncoder", "(", "$", "value", ",", "$", "propertyUri", ")", ";", "return", "is_string", "(", "$", "value...
Encode the value in a json-ld compatible way @param mixed $value @param string $propertyUri (optional) The URI of the property the $value is related to. @return string
[ "Encode", "the", "value", "in", "a", "json", "-", "ld", "compatible", "way" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/export/JsonLdExport.php#L208-L218
oat-sa/tao-core
models/classes/export/JsonLdExport.php
JsonLdExport.generateId
protected function generateId($uri) { $property = new \core_kernel_classes_Property($uri); $label = strtolower(trim($property->getLabel())); $label = preg_replace(array('/\s/', '[^a-z\-]'), array('-', ''), $label); return empty($label) ? 'key' : $label; }
php
protected function generateId($uri) { $property = new \core_kernel_classes_Property($uri); $label = strtolower(trim($property->getLabel())); $label = preg_replace(array('/\s/', '[^a-z\-]'), array('-', ''), $label); return empty($label) ? 'key' : $label; }
[ "protected", "function", "generateId", "(", "$", "uri", ")", "{", "$", "property", "=", "new", "\\", "core_kernel_classes_Property", "(", "$", "uri", ")", ";", "$", "label", "=", "strtolower", "(", "trim", "(", "$", "property", "->", "getLabel", "(", ")"...
Generate a key for the property to use during export @param string $uri @return string
[ "Generate", "a", "key", "for", "the", "property", "to", "use", "during", "export" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/export/JsonLdExport.php#L226-L232
oat-sa/tao-core
models/classes/export/JsonLdExport.php
JsonLdExport.applyEncoder
protected function applyEncoder($value, $propertyUri = '') { if (empty($propertyUri) === false) { $encoders = $this->getEncoders(); if (isset($encoders[$propertyUri]) === true) { $encodedValue = call_user_func($encoders[$propertyUri], $value); return $encodedValue; } } return $value; }
php
protected function applyEncoder($value, $propertyUri = '') { if (empty($propertyUri) === false) { $encoders = $this->getEncoders(); if (isset($encoders[$propertyUri]) === true) { $encodedValue = call_user_func($encoders[$propertyUri], $value); return $encodedValue; } } return $value; }
[ "protected", "function", "applyEncoder", "(", "$", "value", ",", "$", "propertyUri", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "propertyUri", ")", "===", "false", ")", "{", "$", "encoders", "=", "$", "this", "->", "getEncoders", "(", ")", ";...
Attempt to apply a specific value encoder. @param mixed $value @param string (optional) The URI of the property the $value belongs to. @return mixed
[ "Attempt", "to", "apply", "a", "specific", "value", "encoder", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/export/JsonLdExport.php#L241-L253
oat-sa/tao-core
models/classes/taskQueue/TaskLog/Entity/TaskLogEntity.php
TaskLogEntity.getFileNameFromReport
public function getFileNameFromReport() { $filename = ''; if ($this->getStatus()->isFailed() || is_null($this->getReport())) { return $filename; } /** @var Report $successReport */ foreach ($this->getReport()->getSuccesses() as $successReport) { $data = $successReport->getData(); if (is_string($data)) { $filename = $data; break; } if (is_array($data) && isset($data['uriResource'])) { $filename = $data['uriResource']; } } return $filename; }
php
public function getFileNameFromReport() { $filename = ''; if ($this->getStatus()->isFailed() || is_null($this->getReport())) { return $filename; } /** @var Report $successReport */ foreach ($this->getReport()->getSuccesses() as $successReport) { $data = $successReport->getData(); if (is_string($data)) { $filename = $data; break; } if (is_array($data) && isset($data['uriResource'])) { $filename = $data['uriResource']; } } return $filename; }
[ "public", "function", "getFileNameFromReport", "(", ")", "{", "$", "filename", "=", "''", ";", "if", "(", "$", "this", "->", "getStatus", "(", ")", "->", "isFailed", "(", ")", "||", "is_null", "(", "$", "this", "->", "getReport", "(", ")", ")", ")", ...
Returns the file name from the generated report. NOTE: it is not 100% sure that the returned string is really a file name because different reports set different values as data. So this return value can be any kind of string. Please check the file whether it exist or not before usage. @return string
[ "Returns", "the", "file", "name", "from", "the", "generated", "report", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLog/Entity/TaskLogEntity.php#L224-L246
oat-sa/tao-core
models/classes/modules/AbstractModuleRegistry.php
AbstractModuleRegistry.register
public function register(DynamicModule $module) { if(!is_null($module) && ! empty($module->getModule()) ) { self::getRegistry()->set($module->getModule(), $module->toArray()); return true; } return false; }
php
public function register(DynamicModule $module) { if(!is_null($module) && ! empty($module->getModule()) ) { self::getRegistry()->set($module->getModule(), $module->toArray()); return true; } return false; }
[ "public", "function", "register", "(", "DynamicModule", "$", "module", ")", "{", "if", "(", "!", "is_null", "(", "$", "module", ")", "&&", "!", "empty", "(", "$", "module", "->", "getModule", "(", ")", ")", ")", "{", "self", "::", "getRegistry", "(",...
Register a plugin @param DynamicModule $module the plugin to register @return boolean true if registered
[ "Register", "a", "plugin" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/modules/AbstractModuleRegistry.php#L36-L45
oat-sa/tao-core
models/classes/oauth/nonce/KvNonceStore.php
KvNonceStore.isValid
public function isValid($id) { $ttl = $this->hasOption(self::OPTION_TTL) ? $this->getOption(self::OPTION_TTL) : self::DEFAULT_TTL; if ($this->getPersistence()->supportsFeature(\common_persistence_KeyValuePersistence::FEATURE_NX)) { return $this->getPersistence()->set(self::PREFIX.$id, 't', $ttl, true); } else { if ($this->getPersistence()->exists(self::PREFIX.$id)) { return false; } return $this->getPersistence()->set(self::PREFIX.$id, 't', $ttl); } }
php
public function isValid($id) { $ttl = $this->hasOption(self::OPTION_TTL) ? $this->getOption(self::OPTION_TTL) : self::DEFAULT_TTL; if ($this->getPersistence()->supportsFeature(\common_persistence_KeyValuePersistence::FEATURE_NX)) { return $this->getPersistence()->set(self::PREFIX.$id, 't', $ttl, true); } else { if ($this->getPersistence()->exists(self::PREFIX.$id)) { return false; } return $this->getPersistence()->set(self::PREFIX.$id, 't', $ttl); } }
[ "public", "function", "isValid", "(", "$", "id", ")", "{", "$", "ttl", "=", "$", "this", "->", "hasOption", "(", "self", "::", "OPTION_TTL", ")", "?", "$", "this", "->", "getOption", "(", "self", "::", "OPTION_TTL", ")", ":", "self", "::", "DEFAULT_T...
(non-PHPdoc) @see \oat\tao\model\oauth\nonce\NonceStore::isValid()
[ "(", "non", "-", "PHPdoc", ")" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/oauth/nonce/KvNonceStore.php#L39-L50
oat-sa/tao-core
models/classes/requiredAction/implementation/TimeRule.php
TimeRule.completed
public function completed() { $resource = $this->getActionExecution(); if ($resource === null) { $requiredActionClass = new \core_kernel_classes_Class(self::CLASS_URI); $resource = $requiredActionClass->createInstanceWithProperties(array( self::PROPERTY_SUBJECT => $this->getUser()->getIdentifier(), self::PROPERTY_NAME => $this->requiredAction->getName(), self::PROPERTY_EXECUTION_TIME => time(), )); } $timeProperty = (new \core_kernel_classes_Property(self::PROPERTY_EXECUTION_TIME)); $resource->editPropertyValues($timeProperty, time()); return $resource; }
php
public function completed() { $resource = $this->getActionExecution(); if ($resource === null) { $requiredActionClass = new \core_kernel_classes_Class(self::CLASS_URI); $resource = $requiredActionClass->createInstanceWithProperties(array( self::PROPERTY_SUBJECT => $this->getUser()->getIdentifier(), self::PROPERTY_NAME => $this->requiredAction->getName(), self::PROPERTY_EXECUTION_TIME => time(), )); } $timeProperty = (new \core_kernel_classes_Property(self::PROPERTY_EXECUTION_TIME)); $resource->editPropertyValues($timeProperty, time()); return $resource; }
[ "public", "function", "completed", "(", ")", "{", "$", "resource", "=", "$", "this", "->", "getActionExecution", "(", ")", ";", "if", "(", "$", "resource", "===", "null", ")", "{", "$", "requiredActionClass", "=", "new", "\\", "core_kernel_classes_Class", ...
Mark rule as executed and save time of completed. @return \core_kernel_classes_Resource
[ "Mark", "rule", "as", "executed", "and", "save", "time", "of", "completed", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/TimeRule.php#L90-L104
oat-sa/tao-core
models/classes/requiredAction/implementation/TimeRule.php
TimeRule.checkTime
protected function checkTime() { $result = false; $lastExecution = $this->getExecutionTime(); $interval = $this->getInterval(); $anonymous = \common_session_SessionManager::isAnonymous(); if ($lastExecution === null && !$anonymous) { $result = true; } elseif($lastExecution !== null && $interval !== null && !$anonymous) { $mustBeExecutedAt = clone($lastExecution); $mustBeExecutedAt->add($interval); $now = new DateTime('now'); $result = ($mustBeExecutedAt < $now); } return $result; }
php
protected function checkTime() { $result = false; $lastExecution = $this->getExecutionTime(); $interval = $this->getInterval(); $anonymous = \common_session_SessionManager::isAnonymous(); if ($lastExecution === null && !$anonymous) { $result = true; } elseif($lastExecution !== null && $interval !== null && !$anonymous) { $mustBeExecutedAt = clone($lastExecution); $mustBeExecutedAt->add($interval); $now = new DateTime('now'); $result = ($mustBeExecutedAt < $now); } return $result; }
[ "protected", "function", "checkTime", "(", ")", "{", "$", "result", "=", "false", ";", "$", "lastExecution", "=", "$", "this", "->", "getExecutionTime", "(", ")", ";", "$", "interval", "=", "$", "this", "->", "getInterval", "(", ")", ";", "$", "anonymo...
Check if it is time to perform an action. If `$this->lastExecution` is null (action has never been executed) or since the last execution took time more than specified interval (`$this->interval`) then action must be performed. @return bool
[ "Check", "if", "it", "is", "time", "to", "perform", "an", "action", ".", "If", "$this", "-", ">", "lastExecution", "is", "null", "(", "action", "has", "never", "been", "executed", ")", "or", "since", "the", "last", "execution", "took", "time", "more", ...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/TimeRule.php#L126-L144
oat-sa/tao-core
models/classes/requiredAction/implementation/TimeRule.php
TimeRule.getExecutionTime
protected function getExecutionTime() { if ($this->executionTime === null) { $resource = $this->getActionExecution(); if ($resource !== null) { /** @var \core_kernel_classes_Resource $resource */ $time = (string) $resource->getOnePropertyValue(new \core_kernel_classes_Property(self::PROPERTY_EXECUTION_TIME)); if (!empty($time)) { $this->executionTime = new DateTime('@' . $time); } } } return $this->executionTime; }
php
protected function getExecutionTime() { if ($this->executionTime === null) { $resource = $this->getActionExecution(); if ($resource !== null) { /** @var \core_kernel_classes_Resource $resource */ $time = (string) $resource->getOnePropertyValue(new \core_kernel_classes_Property(self::PROPERTY_EXECUTION_TIME)); if (!empty($time)) { $this->executionTime = new DateTime('@' . $time); } } } return $this->executionTime; }
[ "protected", "function", "getExecutionTime", "(", ")", "{", "if", "(", "$", "this", "->", "executionTime", "===", "null", ")", "{", "$", "resource", "=", "$", "this", "->", "getActionExecution", "(", ")", ";", "if", "(", "$", "resource", "!==", "null", ...
Get last execution time. If an action was not executed before returns `null` @return DateTime|null
[ "Get", "last", "execution", "time", ".", "If", "an", "action", "was", "not", "executed", "before", "returns", "null" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/implementation/TimeRule.php#L150-L164
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.run
public function run() { $this->outVerbose("Connecting..."); if ($this->connect($this->options['user'], $this->options['password'])){ $this->outVerbose("Connected to TAO API."); switch ($this->options['action']){ case 'setConfig': $this->setCurrentAction($this->options['action']); $this->actionSetConfig(); break; case 'install': $this->setCurrentAction($this->options['action']); $this->actionInstall(); break; } $this->disconnect(); } else{ $this->error("Could not connect to TAO API. Please check your user name and password.", true); } }
php
public function run() { $this->outVerbose("Connecting..."); if ($this->connect($this->options['user'], $this->options['password'])){ $this->outVerbose("Connected to TAO API."); switch ($this->options['action']){ case 'setConfig': $this->setCurrentAction($this->options['action']); $this->actionSetConfig(); break; case 'install': $this->setCurrentAction($this->options['action']); $this->actionInstall(); break; } $this->disconnect(); } else{ $this->error("Could not connect to TAO API. Please check your user name and password.", true); } }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "outVerbose", "(", "\"Connecting...\"", ")", ";", "if", "(", "$", "this", "->", "connect", "(", "$", "this", "->", "options", "[", "'user'", "]", ",", "$", "this", "->", "options", "[", ...
Instructions to execute to handle the action to perform. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return void
[ "Instructions", "to", "execute", "to", "handle", "the", "action", "to", "perform", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L89-L114
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.checkInput
public function checkInput() { $this->options = array('verbose' => false, 'action' => null, 'user' => null, 'password' => null); $this->options = array_merge($this->options, $this->parameters); // Check common inputs. if ($this->options['user'] == null){ $this->error("Please provide a Generis 'user'.", true); } else{ if ($this->options['password'] == null){ $this->error("Please provide a Generis 'password'.", true); } else{ if ($this->options['action'] == null){ $this->error("Please provide the 'action' parameter.", true); } else{ switch ($this->options['action']){ case 'setConfig': $this->checkSetConfigInput(); break; case 'install': $this->checkInstallInput(); break; default: $this->error("Please provide a valid 'action' parameter.", true); break; } } } } }
php
public function checkInput() { $this->options = array('verbose' => false, 'action' => null, 'user' => null, 'password' => null); $this->options = array_merge($this->options, $this->parameters); // Check common inputs. if ($this->options['user'] == null){ $this->error("Please provide a Generis 'user'.", true); } else{ if ($this->options['password'] == null){ $this->error("Please provide a Generis 'password'.", true); } else{ if ($this->options['action'] == null){ $this->error("Please provide the 'action' parameter.", true); } else{ switch ($this->options['action']){ case 'setConfig': $this->checkSetConfigInput(); break; case 'install': $this->checkInstallInput(); break; default: $this->error("Please provide a valid 'action' parameter.", true); break; } } } } }
[ "public", "function", "checkInput", "(", ")", "{", "$", "this", "->", "options", "=", "array", "(", "'verbose'", "=>", "false", ",", "'action'", "=>", "null", ",", "'user'", "=>", "null", ",", "'password'", "=>", "null", ")", ";", "$", "this", "->", ...
Checks the input parameters when the script is called from the CLI. It check parameters common to any action (user, password, action) and to the appropriate checking method for the other parameters. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return void
[ "Checks", "the", "input", "parameters", "when", "the", "script", "is", "called", "from", "the", "CLI", ".", "It", "check", "parameters", "common", "to", "any", "action", "(", "user", "password", "action", ")", "and", "to", "the", "appropriate", "checking", ...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L137-L177
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.actionSetConfig
public function actionSetConfig() { // The values accepted in the 'loaded', 'loadAtStartup' and 'ghost' columns of // the extensions table are 0 | 1. $configValue = $this->options['configValue']; $configParam = $this->options['configParameter']; $extensionId = $this->options['extension']; try{ $ext = common_ext_ExtensionsManager::singleton()->getExtensionById($extensionId); $currentConfig = $ext->getConfiguration(); if ($currentConfig == null){ $this->error("The extension '${extensionId} is not referenced.", true); } else{ // Change the configuration with the new value. switch ($configParam){ case 'loaded': $currentConfig->loaded = $configValue; break; case 'loadAtStartup': $currentConfig->loadedAtStartUp = $configValue; break; case 'ghost': $currentConfig->ghost = $configValue; break; default: $this->error("Unknown configuration parameter '${configParam}'.", true); break; } $currentConfig->save($ext); $this->outVerbose("Configuration parameter '${configParam}' successfully updated to " . (($configValue == true) ? 1 : 0) . " for extension '${extensionId}'."); } } catch (common_ext_ExtensionException $e){ $this->error("The extension '${extensionId}' does not exist or has no manifest.", true); } }
php
public function actionSetConfig() { // The values accepted in the 'loaded', 'loadAtStartup' and 'ghost' columns of // the extensions table are 0 | 1. $configValue = $this->options['configValue']; $configParam = $this->options['configParameter']; $extensionId = $this->options['extension']; try{ $ext = common_ext_ExtensionsManager::singleton()->getExtensionById($extensionId); $currentConfig = $ext->getConfiguration(); if ($currentConfig == null){ $this->error("The extension '${extensionId} is not referenced.", true); } else{ // Change the configuration with the new value. switch ($configParam){ case 'loaded': $currentConfig->loaded = $configValue; break; case 'loadAtStartup': $currentConfig->loadedAtStartUp = $configValue; break; case 'ghost': $currentConfig->ghost = $configValue; break; default: $this->error("Unknown configuration parameter '${configParam}'.", true); break; } $currentConfig->save($ext); $this->outVerbose("Configuration parameter '${configParam}' successfully updated to " . (($configValue == true) ? 1 : 0) . " for extension '${extensionId}'."); } } catch (common_ext_ExtensionException $e){ $this->error("The extension '${extensionId}' does not exist or has no manifest.", true); } }
[ "public", "function", "actionSetConfig", "(", ")", "{", "// The values accepted in the 'loaded', 'loadAtStartup' and 'ghost' columns of", "// the extensions table are 0 | 1.", "$", "configValue", "=", "$", "this", "->", "options", "[", "'configValue'", "]", ";", "$", "configP...
Sets a configuration parameter of an extension. The configuration to change is provided with the 'configParameter' CLI argument and its is provided with the 'configValue' CLI argument. The extension on which want to change a parameter value is provided with the 'extension' CLI Parameters that can be changed are: - loaded (boolean) - loadAtStartup (boolean) - ghost (boolean) @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return void
[ "Sets", "a", "configuration", "parameter", "of", "an", "extension", ".", "The", "configuration", "to", "change", "is", "provided", "with", "the", "configParameter", "CLI", "argument", "and", "its", "is", "provided", "with", "the", "configValue", "CLI", "argument...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L227-L272
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.checkSetConfigInput
public function checkSetConfigInput() { $availableParameters = array('loaded', 'loadAtStartup', 'ghost'); $defaults = array('extension' => null, 'configParameter' => null, 'configValue' => null); $this->options = array_merge($defaults, $this->options); if ($this->options['configParameter'] == null){ $this->error("Please provide the 'configParam' parameter.", true); } else if (!in_array($this->options['configParameter'], $availableParameters)){ $this->error("Please provide a valid 'configParam' parameter value (" . implode("|", $availableParameters) . ").", true); } else if ($this->options['configValue'] === null){ $this->error("Please provide the 'configValue' parameter.", true); } else if ($this->options['extension'] == null){ $this->error("Please provide the 'extension' parameter.", true); } }
php
public function checkSetConfigInput() { $availableParameters = array('loaded', 'loadAtStartup', 'ghost'); $defaults = array('extension' => null, 'configParameter' => null, 'configValue' => null); $this->options = array_merge($defaults, $this->options); if ($this->options['configParameter'] == null){ $this->error("Please provide the 'configParam' parameter.", true); } else if (!in_array($this->options['configParameter'], $availableParameters)){ $this->error("Please provide a valid 'configParam' parameter value (" . implode("|", $availableParameters) . ").", true); } else if ($this->options['configValue'] === null){ $this->error("Please provide the 'configValue' parameter.", true); } else if ($this->options['extension'] == null){ $this->error("Please provide the 'extension' parameter.", true); } }
[ "public", "function", "checkSetConfigInput", "(", ")", "{", "$", "availableParameters", "=", "array", "(", "'loaded'", ",", "'loadAtStartup'", ",", "'ghost'", ")", ";", "$", "defaults", "=", "array", "(", "'extension'", "=>", "null", ",", "'configParameter'", ...
Check additional inputs for the 'setConfig' action. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return void
[ "Check", "additional", "inputs", "for", "the", "setConfig", "action", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L345-L367
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.error
public function error($message, $stopExec = false) { if ($stopExec == true){ $this->disconnect(); } $this->err($message, $stopExec); }
php
public function error($message, $stopExec = false) { if ($stopExec == true){ $this->disconnect(); } $this->err($message, $stopExec); }
[ "public", "function", "error", "(", "$", "message", ",", "$", "stopExec", "=", "false", ")", "{", "if", "(", "$", "stopExec", "==", "true", ")", "{", "$", "this", "->", "disconnect", "(", ")", ";", "}", "$", "this", "->", "err", "(", "$", "messag...
Display an error message. If the stopExec parameter is set to true, the of the script stops and the currently connected user is disconnected if It overrides the Runner->err method for this purpose. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param string message The error message to display. @param boolean stopExec If set to false, the execution of the script stops. @return mixed
[ "Display", "an", "error", "message", ".", "If", "the", "stopExec", "parameter", "is", "set", "to", "true", "the", "of", "the", "script", "stops", "and", "the", "currently", "connected", "user", "is", "disconnected", "if", "It", "overrides", "the", "Runner", ...
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L411-L420
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.connect
public function connect($user, $password) { $returnValue = (bool) false; $userService = tao_models_classes_UserService::singleton(); $returnValue = $userService->loginUser($user, $password); $this->setConnected($returnValue); return (bool) $returnValue; }
php
public function connect($user, $password) { $returnValue = (bool) false; $userService = tao_models_classes_UserService::singleton(); $returnValue = $userService->loginUser($user, $password); $this->setConnected($returnValue); return (bool) $returnValue; }
[ "public", "function", "connect", "(", "$", "user", ",", "$", "password", ")", "{", "$", "returnValue", "=", "(", "bool", ")", "false", ";", "$", "userService", "=", "tao_models_classes_UserService", "::", "singleton", "(", ")", ";", "$", "returnValue", "="...
Connect to the generis API by using the CLI arguments 'user' and It returns true or false depending on the connection establishement. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @param string user @param string password @return boolean
[ "Connect", "to", "the", "generis", "API", "by", "using", "the", "CLI", "arguments", "user", "and", "It", "returns", "true", "or", "false", "depending", "on", "the", "connection", "establishement", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L432-L443
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.disconnect
public function disconnect() { if ($this->isConnected()){ $this->outVerbose("Disconnecting user..."); $userService = tao_models_classes_UserService::singleton(); if ($userService->logout() == true){ $this->outVerbose("User gracefully disconnected from TAO API."); $this->setConnected(false); } else{ $this->error("User could not be disconnected from TAO API."); } } }
php
public function disconnect() { if ($this->isConnected()){ $this->outVerbose("Disconnecting user..."); $userService = tao_models_classes_UserService::singleton(); if ($userService->logout() == true){ $this->outVerbose("User gracefully disconnected from TAO API."); $this->setConnected(false); } else{ $this->error("User could not be disconnected from TAO API."); } } }
[ "public", "function", "disconnect", "(", ")", "{", "if", "(", "$", "this", "->", "isConnected", "(", ")", ")", "{", "$", "this", "->", "outVerbose", "(", "\"Disconnecting user...\"", ")", ";", "$", "userService", "=", "tao_models_classes_UserService", "::", ...
Disconnect the currently connected user. @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return mixed
[ "Disconnect", "the", "currently", "connected", "user", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L452-L467
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.actionInstall
public function actionInstall() { $extensionId = $this->options['extension']; // ID of the extension to install. $importLocalData = $this->options['data']; // Import local data (local.rdf) or not ? try{ // Retrieve the extension's information. $this->outVerbose("Locating extension '${extensionId}'..."); $extensionManager = common_ext_ExtensionsManager::singleton(); $ext = $extensionManager->getExtensionById($extensionId); $this->outVerbose("Extension located."); try{ // Install the extension. $this->outVerbose("Installing extension '${extensionId}'..."); $installer = new tao_install_ExtensionInstaller($ext, $importLocalData); $installer->install(); $this->outVerbose("Extension successfully installed."); } catch (common_ext_ForbiddenActionException $e){ $this->error("A forbidden action was undertaken: " . $e->getMessage() . " .", true); } catch (common_ext_AlreadyInstalledException $e){ $this->error("Extension '" . $e->getExtensionId() . "' is already installed.", true); } catch (common_ext_MissingExtensionException $e){ $this->error("Extension '" . $extensionId . " is dependant on extension '" . $e->getExtensionId() . "' but is missing. Install '" . $e->getExtensionId() . "' first.", true); } } catch (common_ext_ExtensionException $e){ $this->error("An unexpected error occured: " . $e->getMessage(), true); } }
php
public function actionInstall() { $extensionId = $this->options['extension']; // ID of the extension to install. $importLocalData = $this->options['data']; // Import local data (local.rdf) or not ? try{ // Retrieve the extension's information. $this->outVerbose("Locating extension '${extensionId}'..."); $extensionManager = common_ext_ExtensionsManager::singleton(); $ext = $extensionManager->getExtensionById($extensionId); $this->outVerbose("Extension located."); try{ // Install the extension. $this->outVerbose("Installing extension '${extensionId}'..."); $installer = new tao_install_ExtensionInstaller($ext, $importLocalData); $installer->install(); $this->outVerbose("Extension successfully installed."); } catch (common_ext_ForbiddenActionException $e){ $this->error("A forbidden action was undertaken: " . $e->getMessage() . " .", true); } catch (common_ext_AlreadyInstalledException $e){ $this->error("Extension '" . $e->getExtensionId() . "' is already installed.", true); } catch (common_ext_MissingExtensionException $e){ $this->error("Extension '" . $extensionId . " is dependant on extension '" . $e->getExtensionId() . "' but is missing. Install '" . $e->getExtensionId() . "' first.", true); } } catch (common_ext_ExtensionException $e){ $this->error("An unexpected error occured: " . $e->getMessage(), true); } }
[ "public", "function", "actionInstall", "(", ")", "{", "$", "extensionId", "=", "$", "this", "->", "options", "[", "'extension'", "]", ";", "// ID of the extension to install.", "$", "importLocalData", "=", "$", "this", "->", "options", "[", "'data'", "]", ";",...
Short description of method actionInstall @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return void
[ "Short", "description", "of", "method", "actionInstall" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L476-L509
oat-sa/tao-core
scripts/class.TaoExtensions.php
tao_scripts_TaoExtensions.checkInstallInput
public function checkInstallInput() { $defaults = array('extension' => null, 'data' => true); $this->options = array_merge($defaults, $this->options); if ($this->options['extension'] == null){ $this->error("Please provide the 'extension' parameter.", true); } }
php
public function checkInstallInput() { $defaults = array('extension' => null, 'data' => true); $this->options = array_merge($defaults, $this->options); if ($this->options['extension'] == null){ $this->error("Please provide the 'extension' parameter.", true); } }
[ "public", "function", "checkInstallInput", "(", ")", "{", "$", "defaults", "=", "array", "(", "'extension'", "=>", "null", ",", "'data'", "=>", "true", ")", ";", "$", "this", "->", "options", "=", "array_merge", "(", "$", "defaults", ",", "$", "this", ...
Short description of method checkInstallInput @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return void
[ "Short", "description", "of", "method", "checkInstallInput" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/class.TaoExtensions.php#L518-L530
oat-sa/tao-core
models/classes/class.Parser.php
tao_models_classes_Parser.validate
public function validate($schema = '') { //You know sometimes you think you have enough time, but it is not always true ... //(timeout in hudson with the generis-hard test suite) helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $content = $this->getContent(); if (!empty($content)) { try { libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $this->valid = $dom->loadXML($content); if ($this->valid && !empty($schema)) { $this->valid = $dom->schemaValidate($schema); } if (!$this->valid) { $this->addErrors(libxml_get_errors()); } libxml_clear_errors(); } catch(DOMException $de) { $this->addError($de); } } helpers_TimeOutHelper::reset(); return (bool) $this->valid; }
php
public function validate($schema = '') { //You know sometimes you think you have enough time, but it is not always true ... //(timeout in hudson with the generis-hard test suite) helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::MEDIUM); $content = $this->getContent(); if (!empty($content)) { try { libxml_use_internal_errors(true); $dom = new DomDocument(); $dom->formatOutput = true; $dom->preserveWhiteSpace = false; $this->valid = $dom->loadXML($content); if ($this->valid && !empty($schema)) { $this->valid = $dom->schemaValidate($schema); } if (!$this->valid) { $this->addErrors(libxml_get_errors()); } libxml_clear_errors(); } catch(DOMException $de) { $this->addError($de); } } helpers_TimeOutHelper::reset(); return (bool) $this->valid; }
[ "public", "function", "validate", "(", "$", "schema", "=", "''", ")", "{", "//You know sometimes you think you have enough time, but it is not always true ...", "//(timeout in hudson with the generis-hard test suite)", "helpers_TimeOutHelper", "::", "setTimeOutLimit", "(", "helpers_T...
Short description of method validate @access public @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param string schema @return boolean
[ "Short", "description", "of", "method", "validate" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/class.Parser.php#L171-L204
oat-sa/tao-core
models/classes/class.Parser.php
tao_models_classes_Parser.validateMultiple
public function validateMultiple($xsds = array()) { $returnValue = ''; foreach ($xsds as $xsd) { $this->errors = array(); if ($this->validate($xsd)) { $returnValue = $xsd; break; } } return $returnValue; }
php
public function validateMultiple($xsds = array()) { $returnValue = ''; foreach ($xsds as $xsd) { $this->errors = array(); if ($this->validate($xsd)) { $returnValue = $xsd; break; } } return $returnValue; }
[ "public", "function", "validateMultiple", "(", "$", "xsds", "=", "array", "(", ")", ")", "{", "$", "returnValue", "=", "''", ";", "foreach", "(", "$", "xsds", "as", "$", "xsd", ")", "{", "$", "this", "->", "errors", "=", "array", "(", ")", ";", "...
Excecute parser validation and stops at the first valid one, and returns the identified schema @param array $xsds @return string
[ "Excecute", "parser", "validation", "and", "stops", "at", "the", "first", "valid", "one", "and", "returns", "the", "identified", "schema" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/class.Parser.php#L212-L225
oat-sa/tao-core
models/classes/class.Parser.php
tao_models_classes_Parser.displayErrors
public function displayErrors($htmlOutput = true){ $returnValue = (string) ''; foreach($this->errors as $error){ $returnValue .= $error['message']; if(isset($error['file']) && isset($error['line'])){ $returnValue .= ' in file '.$error['file'].', line '.$error['line']; } $returnValue .= PHP_EOL; } if($htmlOutput){ $returnValue = nl2br($returnValue); } return (string) $returnValue; }
php
public function displayErrors($htmlOutput = true){ $returnValue = (string) ''; foreach($this->errors as $error){ $returnValue .= $error['message']; if(isset($error['file']) && isset($error['line'])){ $returnValue .= ' in file '.$error['file'].', line '.$error['line']; } $returnValue .= PHP_EOL; } if($htmlOutput){ $returnValue = nl2br($returnValue); } return (string) $returnValue; }
[ "public", "function", "displayErrors", "(", "$", "htmlOutput", "=", "true", ")", "{", "$", "returnValue", "=", "(", "string", ")", "''", ";", "foreach", "(", "$", "this", "->", "errors", "as", "$", "error", ")", "{", "$", "returnValue", ".=", "$", "e...
Short description of method displayErrors @access public @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param boolean htmlOutput @return string
[ "Short", "description", "of", "method", "displayErrors" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/class.Parser.php#L258-L275
oat-sa/tao-core
models/classes/class.Parser.php
tao_models_classes_Parser.addError
protected function addError($error){ $this->valid = false; if($error instanceof Exception){ $this->errors[] = array( 'file' => $error->getFile(), 'line' => $error->getLine(), 'message' => "[".get_class($error)."] ".$error->getMessage() ); }elseif($error instanceof LibXMLError){ $this->errors[] = array( 'file' => $error->file, 'line' => $error->line, 'message' => "[".get_class($error)."] ".$error->message ); }elseif(is_string($error)){ $this->errors[] = array( 'message' => $error ); } }
php
protected function addError($error){ $this->valid = false; if($error instanceof Exception){ $this->errors[] = array( 'file' => $error->getFile(), 'line' => $error->getLine(), 'message' => "[".get_class($error)."] ".$error->getMessage() ); }elseif($error instanceof LibXMLError){ $this->errors[] = array( 'file' => $error->file, 'line' => $error->line, 'message' => "[".get_class($error)."] ".$error->message ); }elseif(is_string($error)){ $this->errors[] = array( 'message' => $error ); } }
[ "protected", "function", "addError", "(", "$", "error", ")", "{", "$", "this", "->", "valid", "=", "false", ";", "if", "(", "$", "error", "instanceof", "Exception", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "array", "(", "'file'", "=>", ...
Short description of method addError @access protected @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param mixed error @return mixed
[ "Short", "description", "of", "method", "addError" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/class.Parser.php#L285-L306
oat-sa/tao-core
models/classes/class.Parser.php
tao_models_classes_Parser.getContent
public function getContent($refresh = false) { if ($this->content === null || $refresh) { try{ switch ($this->sourceType) { case self::SOURCE_FILE: //check file if(!file_exists($this->source)){ throw new Exception("File {$this->source} not found."); } if(!is_readable($this->source)){ throw new Exception("Unable to read file {$this->source}."); } if(!preg_match("/\.{$this->fileExtension}$/", basename($this->source))){ throw new Exception("Wrong file extension in ".basename($this->source).", {$this->fileExtension} extension is expected"); } if(!tao_helpers_File::securityCheck($this->source)){ throw new Exception("{$this->source} seems to contain some security issues"); } $this->content = file_get_contents($this->source); break; case self::SOURCE_URL: //only same domain if(!preg_match("/^".preg_quote(BASE_URL, '/')."/", $this->source)){ throw new Exception("The given uri must be in the domain {$_SERVER['HTTP_HOST']}"); } $this->content = tao_helpers_Request::load($this->source, true); break; case self::SOURCE_STRING: $this->content = $this->source; break; case self::SOURCE_FLYFILE: if (! $this->source->exists()) { throw new Exception('Source file does not exists ("' . $this->source->getBasename() . '").'); } if (! $this->content = $this->source->read()) { throw new Exception('Unable to read file ("' . $this->source->getBasename() . '").'); } break; } } catch(Exception $e) { $this->addError($e); } } return $this->content; }
php
public function getContent($refresh = false) { if ($this->content === null || $refresh) { try{ switch ($this->sourceType) { case self::SOURCE_FILE: //check file if(!file_exists($this->source)){ throw new Exception("File {$this->source} not found."); } if(!is_readable($this->source)){ throw new Exception("Unable to read file {$this->source}."); } if(!preg_match("/\.{$this->fileExtension}$/", basename($this->source))){ throw new Exception("Wrong file extension in ".basename($this->source).", {$this->fileExtension} extension is expected"); } if(!tao_helpers_File::securityCheck($this->source)){ throw new Exception("{$this->source} seems to contain some security issues"); } $this->content = file_get_contents($this->source); break; case self::SOURCE_URL: //only same domain if(!preg_match("/^".preg_quote(BASE_URL, '/')."/", $this->source)){ throw new Exception("The given uri must be in the domain {$_SERVER['HTTP_HOST']}"); } $this->content = tao_helpers_Request::load($this->source, true); break; case self::SOURCE_STRING: $this->content = $this->source; break; case self::SOURCE_FLYFILE: if (! $this->source->exists()) { throw new Exception('Source file does not exists ("' . $this->source->getBasename() . '").'); } if (! $this->content = $this->source->read()) { throw new Exception('Unable to read file ("' . $this->source->getBasename() . '").'); } break; } } catch(Exception $e) { $this->addError($e); } } return $this->content; }
[ "public", "function", "getContent", "(", "$", "refresh", "=", "false", ")", "{", "if", "(", "$", "this", "->", "content", "===", "null", "||", "$", "refresh", ")", "{", "try", "{", "switch", "(", "$", "this", "->", "sourceType", ")", "{", "case", "...
Get XML content. @access protected @author Aleh Hutnikau, <hutnikau@1pt.com> @param boolean $refresh load content again. @return string
[ "Get", "XML", "content", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/class.Parser.php#L316-L362
oat-sa/tao-core
models/classes/class.Parser.php
tao_models_classes_Parser.getReport
public function getReport(){ if($this->isValid()){ return common_report_Report::createSuccess(''); }else{ $report = new common_report_Report(''); foreach($this->getErrors() as $error){ $report->add(common_report_Report::createFailure($error['message'])); } return $report; } }
php
public function getReport(){ if($this->isValid()){ return common_report_Report::createSuccess(''); }else{ $report = new common_report_Report(''); foreach($this->getErrors() as $error){ $report->add(common_report_Report::createFailure($error['message'])); } return $report; } }
[ "public", "function", "getReport", "(", ")", "{", "if", "(", "$", "this", "->", "isValid", "(", ")", ")", "{", "return", "common_report_Report", "::", "createSuccess", "(", "''", ")", ";", "}", "else", "{", "$", "report", "=", "new", "common_report_Repor...
Creates a report without title of the parsing result @return common_report_Report
[ "Creates", "a", "report", "without", "title", "of", "the", "parsing", "result" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/class.Parser.php#L394-L404
oat-sa/tao-core
install/utils/class.CustomProceduresParser.php
tao_install_utils_CustomProceduresParser.parse
public function parse(){ $this->setStatements(array()); $file = $this->getFile(); if (!file_exists($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' does not exist."); } else if (!is_readable($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' is not readable."); } else if(!preg_match("/\.sql$/", basename($file))){ throw new tao_install_utils_SQLParsingException("File '${file}' is not a valid SQL file. Extension '.sql' not found."); } $content = @file_get_contents($file); if ($content !== false){ $matches = array(); $functions = explode(';;', $content); foreach ($functions as $f){ $this->addStatement($f); } } else{ throw new tao_install_utils_SQLParsingException("SQL file '${file}' cannot be read. An unknown error occured while reading it."); } }
php
public function parse(){ $this->setStatements(array()); $file = $this->getFile(); if (!file_exists($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' does not exist."); } else if (!is_readable($file)){ throw new tao_install_utils_SQLParsingException("SQL file '${file}' is not readable."); } else if(!preg_match("/\.sql$/", basename($file))){ throw new tao_install_utils_SQLParsingException("File '${file}' is not a valid SQL file. Extension '.sql' not found."); } $content = @file_get_contents($file); if ($content !== false){ $matches = array(); $functions = explode(';;', $content); foreach ($functions as $f){ $this->addStatement($f); } } else{ throw new tao_install_utils_SQLParsingException("SQL file '${file}' cannot be read. An unknown error occured while reading it."); } }
[ "public", "function", "parse", "(", ")", "{", "$", "this", "->", "setStatements", "(", "array", "(", ")", ")", ";", "$", "file", "=", "$", "this", "->", "getFile", "(", ")", ";", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "...
Parse a SQL file containing mySQL compliant Procedures or Functions. @return void @throws tao_install_utils_SQLParsingException
[ "Parse", "a", "SQL", "file", "containing", "mySQL", "compliant", "Procedures", "or", "Functions", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/install/utils/class.CustomProceduresParser.php#L39-L67
oat-sa/tao-core
actions/form/class.Role.php
tao_actions_form_Role.initElements
public function initElements() { parent::initElements(); $encodedIncludesRolePropertyUri = tao_helpers_Uri::encode(GenerisRdf::PROPERTY_ROLE_INCLUDESROLE); $encodedInstanceUri = tao_helpers_Uri::encode($this->getInstance()->getUri()); $rolesElement = $this->form->getElement($encodedIncludesRolePropertyUri); if (!is_null($rolesElement)) { $rolesOptions = $rolesElement->getOptions(); // remove the role itself in the list of includable roles // to avoid cyclic inclusions (even if the system supports it). if (array_key_exists($encodedInstanceUri, $rolesOptions)){ unset($rolesOptions[$encodedInstanceUri]); } $rolesElement->setOptions($rolesOptions); } }
php
public function initElements() { parent::initElements(); $encodedIncludesRolePropertyUri = tao_helpers_Uri::encode(GenerisRdf::PROPERTY_ROLE_INCLUDESROLE); $encodedInstanceUri = tao_helpers_Uri::encode($this->getInstance()->getUri()); $rolesElement = $this->form->getElement($encodedIncludesRolePropertyUri); if (!is_null($rolesElement)) { $rolesOptions = $rolesElement->getOptions(); // remove the role itself in the list of includable roles // to avoid cyclic inclusions (even if the system supports it). if (array_key_exists($encodedInstanceUri, $rolesOptions)){ unset($rolesOptions[$encodedInstanceUri]); } $rolesElement->setOptions($rolesOptions); } }
[ "public", "function", "initElements", "(", ")", "{", "parent", "::", "initElements", "(", ")", ";", "$", "encodedIncludesRolePropertyUri", "=", "tao_helpers_Uri", "::", "encode", "(", "GenerisRdf", "::", "PROPERTY_ROLE_INCLUDESROLE", ")", ";", "$", "encodedInstanceU...
Short description of method initElements @access public @author Joel Bout, <joel@taotesting.com> @return mixed
[ "Short", "description", "of", "method", "initElements" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/form/class.Role.php#L49-L69
oat-sa/tao-core
models/classes/requiredAction/RequiredActionAbstract.php
RequiredActionAbstract.completed
public function completed($context = null) { $rules = $this->getRules(); foreach ($rules as $rule) { $rule->completed($context); } }
php
public function completed($context = null) { $rules = $this->getRules(); foreach ($rules as $rule) { $rule->completed($context); } }
[ "public", "function", "completed", "(", "$", "context", "=", "null", ")", "{", "$", "rules", "=", "$", "this", "->", "getRules", "(", ")", ";", "foreach", "(", "$", "rules", "as", "$", "rule", ")", "{", "$", "rule", "->", "completed", "(", "$", "...
Mark action as completed. @param null $context @return mixed
[ "Mark", "action", "as", "completed", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/RequiredActionAbstract.php#L84-L90
oat-sa/tao-core
models/classes/requiredAction/RequiredActionAbstract.php
RequiredActionAbstract.checkRules
protected function checkRules($context = null) { $rules = $this->getRules(); $result = false; foreach ($rules as $rule) { if ($rule->check($context)) { $result = true; break; } } return $result; }
php
protected function checkRules($context = null) { $rules = $this->getRules(); $result = false; foreach ($rules as $rule) { if ($rule->check($context)) { $result = true; break; } } return $result; }
[ "protected", "function", "checkRules", "(", "$", "context", "=", "null", ")", "{", "$", "rules", "=", "$", "this", "->", "getRules", "(", ")", ";", "$", "result", "=", "false", ";", "foreach", "(", "$", "rules", "as", "$", "rule", ")", "{", "if", ...
Check rules whether action must be performed. If at least one rule returns true the action will be performed. If result is `true` then action must be performed. @param null $context @return bool
[ "Check", "rules", "whether", "action", "must", "be", "performed", ".", "If", "at", "least", "one", "rule", "returns", "true", "the", "action", "will", "be", "performed", ".", "If", "result", "is", "true", "then", "action", "must", "be", "performed", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/requiredAction/RequiredActionAbstract.php#L142-L155
oat-sa/tao-core
models/classes/lock/implementation/OntoLock.php
OntoLock.setLock
public function setLock(core_kernel_classes_Resource $resource, $ownerId) { $lock = $this->getLockData($resource); if (is_null($lock)) { $lock = new OntoLockData($resource, $ownerId, microtime(true)); $resource->setPropertyValue($this->getLockProperty(), $lock->toJson()); } elseif ($lock->getOwnerId() != $ownerId) { throw new ResourceLockedException($lock); } }
php
public function setLock(core_kernel_classes_Resource $resource, $ownerId) { $lock = $this->getLockData($resource); if (is_null($lock)) { $lock = new OntoLockData($resource, $ownerId, microtime(true)); $resource->setPropertyValue($this->getLockProperty(), $lock->toJson()); } elseif ($lock->getOwnerId() != $ownerId) { throw new ResourceLockedException($lock); } }
[ "public", "function", "setLock", "(", "core_kernel_classes_Resource", "$", "resource", ",", "$", "ownerId", ")", "{", "$", "lock", "=", "$", "this", "->", "getLockData", "(", "$", "resource", ")", ";", "if", "(", "is_null", "(", "$", "lock", ")", ")", ...
(non-PHPdoc) @see \oat\tao\model\lock\LockSystem::setLock()
[ "(", "non", "-", "PHPdoc", ")" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/lock/implementation/OntoLock.php#L56-L65
oat-sa/tao-core
models/classes/lock/implementation/OntoLock.php
OntoLock.isLocked
public function isLocked(core_kernel_classes_Resource $resource) { $values = $resource->getPropertyValues($this->getLockProperty()); if ((is_array($values)) && (count($values)>0)) { return true; } return false; }
php
public function isLocked(core_kernel_classes_Resource $resource) { $values = $resource->getPropertyValues($this->getLockProperty()); if ((is_array($values)) && (count($values)>0)) { return true; } return false; }
[ "public", "function", "isLocked", "(", "core_kernel_classes_Resource", "$", "resource", ")", "{", "$", "values", "=", "$", "resource", "->", "getPropertyValues", "(", "$", "this", "->", "getLockProperty", "(", ")", ")", ";", "if", "(", "(", "is_array", "(", ...
return true is the resource is locked, else otherwise @return boolean
[ "return", "true", "is", "the", "resource", "is", "locked", "else", "otherwise" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/lock/implementation/OntoLock.php#L71-L79
oat-sa/tao-core
models/classes/lock/implementation/OntoLock.php
OntoLock.releaseLock
public function releaseLock(core_kernel_classes_Resource $resource, $ownerId) { $lock = $resource->getPropertyValues( $this->getLockProperty () ); if (count ( $lock ) == 0) { return false; } elseif (count ( $lock ) > 1) { throw new common_exception_InconsistentData('Bad data in lock'); } else { $lockdata = OntoLockData::getLockData ( array_pop ( $lock ) ); if ($lockdata->getOwnerId() == $ownerId) { $resource->removePropertyValues( $this->getLockProperty() ); return true; } else { throw new common_exception_Unauthorized ( "The resource is owned by " . $lockdata->getOwnerId ()); } } }
php
public function releaseLock(core_kernel_classes_Resource $resource, $ownerId) { $lock = $resource->getPropertyValues( $this->getLockProperty () ); if (count ( $lock ) == 0) { return false; } elseif (count ( $lock ) > 1) { throw new common_exception_InconsistentData('Bad data in lock'); } else { $lockdata = OntoLockData::getLockData ( array_pop ( $lock ) ); if ($lockdata->getOwnerId() == $ownerId) { $resource->removePropertyValues( $this->getLockProperty() ); return true; } else { throw new common_exception_Unauthorized ( "The resource is owned by " . $lockdata->getOwnerId ()); } } }
[ "public", "function", "releaseLock", "(", "core_kernel_classes_Resource", "$", "resource", ",", "$", "ownerId", ")", "{", "$", "lock", "=", "$", "resource", "->", "getPropertyValues", "(", "$", "this", "->", "getLockProperty", "(", ")", ")", ";", "if", "(", ...
release the lock if owned by @user @param core_kernel_classes_Resource $resource @param core_kernel_classes_Resource $user @throws common_exception_InconsistentData @throw common_Exception no lock to release
[ "release", "the", "lock", "if", "owned", "by", "@user" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/lock/implementation/OntoLock.php#L89-L105
oat-sa/tao-core
models/classes/lock/implementation/OntoLock.php
OntoLock.getLockData
public function getLockData(core_kernel_classes_Resource $resource) { $values = $resource->getPropertyValues($this->getLockProperty()); if ((is_array($values)) && (count($values)==1)) { return OntoLockData::getLockData(array_pop($values)); } else { return null; } }
php
public function getLockData(core_kernel_classes_Resource $resource) { $values = $resource->getPropertyValues($this->getLockProperty()); if ((is_array($values)) && (count($values)==1)) { return OntoLockData::getLockData(array_pop($values)); } else { return null; } }
[ "public", "function", "getLockData", "(", "core_kernel_classes_Resource", "$", "resource", ")", "{", "$", "values", "=", "$", "resource", "->", "getPropertyValues", "(", "$", "this", "->", "getLockProperty", "(", ")", ")", ";", "if", "(", "(", "is_array", "(...
Return lock details @param core_kernel_classes_Resource $resource @throws common_exception_InconsistentData @return tao_helpers_lock_LockData
[ "Return", "lock", "details" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/lock/implementation/OntoLock.php#L122-L131
oat-sa/tao-core
helpers/translation/class.RDFFileReader.php
tao_helpers_translation_RDFFileReader.read
public function read() { $translationUnits = array(); try{ $translationFile = $this->getTranslationFile(); } catch (tao_helpers_translation_TranslationException $e){ $translationFile = new tao_helpers_translation_RDFTranslationFile(); } $this->setTranslationFile($translationFile); $inputFile = $this->getFilePath(); if (file_exists($inputFile)){ if (is_file($inputFile)){ if (is_readable($inputFile)){ try{ $doc = new DOMDocument('1.0', 'UTF-8'); $doc->load($inputFile); $xpath = new DOMXPath($doc); $rdfNS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; $xmlNS = 'http://www.w3.org/XML/1998/namespace'; $xpath->registerNamespace('rdf', $rdfNS); $rootNodes = $xpath->query('//rdf:RDF'); if ($rootNodes->length == 1){ // Try to get annotations from the root node. $sibling = $rootNodes->item(0)->previousSibling; while ($sibling !== null){ if ($sibling instanceof DOMNode && $sibling->nodeType == XML_COMMENT_NODE){ $annotations = tao_helpers_translation_RDFUtils::unserializeAnnotations($sibling->data); $translationFile->setAnnotations($annotations); if (isset($annotations['sourceLanguage'])){ $translationFile->setSourceLanguage($annotations['sourceLanguage']); } if (isset($annotations['targetLanguage'])){ $translationFile->setTargetLanguage($annotations['targetLanguage']); } break; } $sibling = $sibling->previousSibling; } $descriptions = $xpath->query('//rdf:Description'); foreach ($descriptions as $description){ if ($description->hasAttributeNS($rdfNS, 'about')){ $subject = $description->getAttributeNS($rdfNS, 'about'); // Let's retrieve properties. foreach ($description->childNodes as $property){ if ($property->nodeType == XML_ELEMENT_NODE){ // Retrieve namespace uri of this node. if ($property->namespaceURI != null){ $predicate = $property->namespaceURI . $property->localName; // Retrieve an hypothetic target language. $lang = tao_helpers_translation_Utils::getDefaultLanguage(); if ($property->hasAttributeNS($xmlNS, 'lang')){ $lang = $property->getAttributeNS($xmlNS, 'lang'); } $object = $property->nodeValue; $tu = new tao_helpers_translation_RDFTranslationUnit(''); $tu->setTargetLanguage($lang); $tu->setTarget($object); $tu->setSubject($subject); $tu->setPredicate($predicate); // Try to get annotations. $sibling = $property->previousSibling; while ($sibling !== null){ if ($sibling instanceof DOMNode && $sibling->nodeType == XML_COMMENT_NODE){ // We should have the annotations we are looking for. $annotations = tao_helpers_translation_RDFUtils::unserializeAnnotations($sibling->data); $tu->setAnnotations($annotations); // Set the found sources and sourcelanguages if found. if (isset($annotations['source'])){ $tu->setSource($annotations['source']); } } $sibling = $sibling->previousSibling; } $translationUnits[] = $tu; } } } } } $this->getTranslationFile()->addTranslationUnits($translationUnits); }else{ throw new tao_helpers_translation_TranslationException("'${inputFile}' has no rdf:RDF root node or more than one rdf:RDF root node."); } } catch (DOMException $e){ throw new tao_helpers_translation_TranslationException("'${inputFile}' cannot be parsed."); } }else{ throw new tao_helpers_translation_TranslationException("'${inputFile}' cannot be read. Check your system permissions."); } }else{ throw new tao_helpers_translation_TranslationException("'${inputFile}' is not a file."); } }else{ throw new tao_helpers_translation_TranslationException("The file '${inputFile}' does not exist."); } }
php
public function read() { $translationUnits = array(); try{ $translationFile = $this->getTranslationFile(); } catch (tao_helpers_translation_TranslationException $e){ $translationFile = new tao_helpers_translation_RDFTranslationFile(); } $this->setTranslationFile($translationFile); $inputFile = $this->getFilePath(); if (file_exists($inputFile)){ if (is_file($inputFile)){ if (is_readable($inputFile)){ try{ $doc = new DOMDocument('1.0', 'UTF-8'); $doc->load($inputFile); $xpath = new DOMXPath($doc); $rdfNS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; $xmlNS = 'http://www.w3.org/XML/1998/namespace'; $xpath->registerNamespace('rdf', $rdfNS); $rootNodes = $xpath->query('//rdf:RDF'); if ($rootNodes->length == 1){ // Try to get annotations from the root node. $sibling = $rootNodes->item(0)->previousSibling; while ($sibling !== null){ if ($sibling instanceof DOMNode && $sibling->nodeType == XML_COMMENT_NODE){ $annotations = tao_helpers_translation_RDFUtils::unserializeAnnotations($sibling->data); $translationFile->setAnnotations($annotations); if (isset($annotations['sourceLanguage'])){ $translationFile->setSourceLanguage($annotations['sourceLanguage']); } if (isset($annotations['targetLanguage'])){ $translationFile->setTargetLanguage($annotations['targetLanguage']); } break; } $sibling = $sibling->previousSibling; } $descriptions = $xpath->query('//rdf:Description'); foreach ($descriptions as $description){ if ($description->hasAttributeNS($rdfNS, 'about')){ $subject = $description->getAttributeNS($rdfNS, 'about'); // Let's retrieve properties. foreach ($description->childNodes as $property){ if ($property->nodeType == XML_ELEMENT_NODE){ // Retrieve namespace uri of this node. if ($property->namespaceURI != null){ $predicate = $property->namespaceURI . $property->localName; // Retrieve an hypothetic target language. $lang = tao_helpers_translation_Utils::getDefaultLanguage(); if ($property->hasAttributeNS($xmlNS, 'lang')){ $lang = $property->getAttributeNS($xmlNS, 'lang'); } $object = $property->nodeValue; $tu = new tao_helpers_translation_RDFTranslationUnit(''); $tu->setTargetLanguage($lang); $tu->setTarget($object); $tu->setSubject($subject); $tu->setPredicate($predicate); // Try to get annotations. $sibling = $property->previousSibling; while ($sibling !== null){ if ($sibling instanceof DOMNode && $sibling->nodeType == XML_COMMENT_NODE){ // We should have the annotations we are looking for. $annotations = tao_helpers_translation_RDFUtils::unserializeAnnotations($sibling->data); $tu->setAnnotations($annotations); // Set the found sources and sourcelanguages if found. if (isset($annotations['source'])){ $tu->setSource($annotations['source']); } } $sibling = $sibling->previousSibling; } $translationUnits[] = $tu; } } } } } $this->getTranslationFile()->addTranslationUnits($translationUnits); }else{ throw new tao_helpers_translation_TranslationException("'${inputFile}' has no rdf:RDF root node or more than one rdf:RDF root node."); } } catch (DOMException $e){ throw new tao_helpers_translation_TranslationException("'${inputFile}' cannot be parsed."); } }else{ throw new tao_helpers_translation_TranslationException("'${inputFile}' cannot be read. Check your system permissions."); } }else{ throw new tao_helpers_translation_TranslationException("'${inputFile}' is not a file."); } }else{ throw new tao_helpers_translation_TranslationException("The file '${inputFile}' does not exist."); } }
[ "public", "function", "read", "(", ")", "{", "$", "translationUnits", "=", "array", "(", ")", ";", "try", "{", "$", "translationFile", "=", "$", "this", "->", "getTranslationFile", "(", ")", ";", "}", "catch", "(", "tao_helpers_translation_TranslationException...
Short description of method read @access public @author Jerome Bogaerts, <jerome.bogaerts@tudor.lu> @return mixed
[ "Short", "description", "of", "method", "read" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.RDFFileReader.php#L47-L166
oat-sa/tao-core
models/classes/taskQueue/TaskLog/DataTablePayload.php
DataTablePayload.customiseRowBy
public function customiseRowBy(\Closure $func, $overrideDefault = false) { $this->rowCustomiser = $func; $this->overrideDefaultPayload = $overrideDefault; return $this; }
php
public function customiseRowBy(\Closure $func, $overrideDefault = false) { $this->rowCustomiser = $func; $this->overrideDefaultPayload = $overrideDefault; return $this; }
[ "public", "function", "customiseRowBy", "(", "\\", "Closure", "$", "func", ",", "$", "overrideDefault", "=", "false", ")", "{", "$", "this", "->", "rowCustomiser", "=", "$", "func", ";", "$", "this", "->", "overrideDefaultPayload", "=", "$", "overrideDefault...
You can pass an anonymous function to customise the final payload: either to change the value of a field or to add extra field(s); The function will be bind to the task log entity (TaskLogEntity) so $this can be used inside of the closure. The return value needs to be an array. For example: <code> $payload->customiseRowBy(function (){ $row['extraField'] = 'value'; $row['extraField2'] = $this->getParameters()['some_parameter_key']; $row['createdAt'] = \tao_helpers_Date::displayeDate($this->getCreatedAt()); return $row; }); </code> @param \Closure $func @param boolean $overrideDefault Override default payload, return only data returned by $func @return DataTablePayload
[ "You", "can", "pass", "an", "anonymous", "function", "to", "customise", "the", "final", "payload", ":", "either", "to", "change", "the", "value", "of", "a", "field", "or", "to", "add", "extra", "field", "(", "s", ")", ";" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLog/DataTablePayload.php#L87-L93
oat-sa/tao-core
models/classes/taskQueue/TaskLog/DataTablePayload.php
DataTablePayload.getCustomisedData
private function getCustomisedData(CollectionInterface $collection) { $data = []; if (!is_null($this->rowCustomiser)) { foreach ($collection as $taskLogEntity) { $newCustomiser = $this->rowCustomiser->bindTo($taskLogEntity, $taskLogEntity); $customizedPayload = (array) $newCustomiser(); if ($this->overrideDefaultPayload) { $data[] = $customizedPayload; } else { $data[] = array_merge($taskLogEntity->toArray(), $customizedPayload); } } } return $data; }
php
private function getCustomisedData(CollectionInterface $collection) { $data = []; if (!is_null($this->rowCustomiser)) { foreach ($collection as $taskLogEntity) { $newCustomiser = $this->rowCustomiser->bindTo($taskLogEntity, $taskLogEntity); $customizedPayload = (array) $newCustomiser(); if ($this->overrideDefaultPayload) { $data[] = $customizedPayload; } else { $data[] = array_merge($taskLogEntity->toArray(), $customizedPayload); } } } return $data; }
[ "private", "function", "getCustomisedData", "(", "CollectionInterface", "$", "collection", ")", "{", "$", "data", "=", "[", "]", ";", "if", "(", "!", "is_null", "(", "$", "this", "->", "rowCustomiser", ")", ")", "{", "foreach", "(", "$", "collection", "a...
Get customised data if we have a customiser set @param CollectionInterface|EntityInterface[] $collection @return array
[ "Get", "customised", "data", "if", "we", "have", "a", "customiser", "set" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLog/DataTablePayload.php#L136-L155
oat-sa/tao-core
models/classes/taskQueue/TaskLog/DataTablePayload.php
DataTablePayload.applyDataTableFilters
private function applyDataTableFilters() { $filters = $this->request->getFilters(); foreach ($filters as $fieldName => $filterValue) { if (empty($filterValue)) { continue; } if (is_array($filterValue)) { $this->taskLogFilter->in($fieldName, $filterValue); continue; } $this->taskLogFilter->eq($fieldName, (string) $filterValue); } }
php
private function applyDataTableFilters() { $filters = $this->request->getFilters(); foreach ($filters as $fieldName => $filterValue) { if (empty($filterValue)) { continue; } if (is_array($filterValue)) { $this->taskLogFilter->in($fieldName, $filterValue); continue; } $this->taskLogFilter->eq($fieldName, (string) $filterValue); } }
[ "private", "function", "applyDataTableFilters", "(", ")", "{", "$", "filters", "=", "$", "this", "->", "request", "->", "getFilters", "(", ")", ";", "foreach", "(", "$", "filters", "as", "$", "fieldName", "=>", "$", "filterValue", ")", "{", "if", "(", ...
Add filter values from request to the taskLogFilter.
[ "Add", "filter", "values", "from", "request", "to", "the", "taskLogFilter", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/taskQueue/TaskLog/DataTablePayload.php#L168-L184
oat-sa/tao-core
models/classes/media/sourceStrategy/HttpSource.php
HttpSource.download
public function download($link) { $url = str_replace('\/', '/', $link); $fileName = \tao_helpers_File::createTempDir() . basename($link); common_Logger::d('Downloading ' . $url); helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::NO_TIMEOUT); $fp = fopen($fileName, 'w+'); $curlHandler = curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url); curl_setopt($curlHandler, CURLOPT_FILE, $fp); curl_setopt($curlHandler, CURLOPT_TIMEOUT, 50); curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, true); //if there is an http auth on the local domain, it's mandatory to auth with curl if (USE_HTTP_AUTH) { $addAuth = false; $domains = array('localhost', '127.0.0.1', ROOT_URL); foreach ($domains as $domain) { if (preg_match("/" . preg_quote($domain, '/') . "/", $url)) { $addAuth = true; } } if ($addAuth) { curl_setopt($curlHandler, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curlHandler, CURLOPT_USERPWD, USE_HTTP_USER . ":" . USE_HTTP_PASS); } } curl_exec($curlHandler); $httpCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); $success = $httpCode == 200; curl_close($curlHandler); fclose($fp); helpers_TimeOutHelper::reset(); return $fileName; }
php
public function download($link) { $url = str_replace('\/', '/', $link); $fileName = \tao_helpers_File::createTempDir() . basename($link); common_Logger::d('Downloading ' . $url); helpers_TimeOutHelper::setTimeOutLimit(helpers_TimeOutHelper::NO_TIMEOUT); $fp = fopen($fileName, 'w+'); $curlHandler = curl_init(); curl_setopt($curlHandler, CURLOPT_URL, $url); curl_setopt($curlHandler, CURLOPT_FILE, $fp); curl_setopt($curlHandler, CURLOPT_TIMEOUT, 50); curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, true); //if there is an http auth on the local domain, it's mandatory to auth with curl if (USE_HTTP_AUTH) { $addAuth = false; $domains = array('localhost', '127.0.0.1', ROOT_URL); foreach ($domains as $domain) { if (preg_match("/" . preg_quote($domain, '/') . "/", $url)) { $addAuth = true; } } if ($addAuth) { curl_setopt($curlHandler, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curlHandler, CURLOPT_USERPWD, USE_HTTP_USER . ":" . USE_HTTP_PASS); } } curl_exec($curlHandler); $httpCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE); $success = $httpCode == 200; curl_close($curlHandler); fclose($fp); helpers_TimeOutHelper::reset(); return $fileName; }
[ "public", "function", "download", "(", "$", "link", ")", "{", "$", "url", "=", "str_replace", "(", "'\\/'", ",", "'/'", ",", "$", "link", ")", ";", "$", "fileName", "=", "\\", "tao_helpers_File", "::", "createTempDir", "(", ")", ".", "basename", "(", ...
(non-PHPdoc) @see \oat\tao\model\media\MediaBrowser::download()
[ "(", "non", "-", "PHPdoc", ")" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/media/sourceStrategy/HttpSource.php#L47-L87
oat-sa/tao-core
models/classes/http/Controller.php
Controller.setCookie
protected function setCookie($name, $value = null, $expire = null, $domainPath = null, $https = null, $httpOnly = null) { return setcookie($name, $value, $expire, $domainPath, $https, $httpOnly); }
php
protected function setCookie($name, $value = null, $expire = null, $domainPath = null, $https = null, $httpOnly = null) { return setcookie($name, $value, $expire, $domainPath, $https, $httpOnly); }
[ "protected", "function", "setCookie", "(", "$", "name", ",", "$", "value", "=", "null", ",", "$", "expire", "=", "null", ",", "$", "domainPath", "=", "null", ",", "$", "https", "=", "null", ",", "$", "httpOnly", "=", "null", ")", "{", "return", "se...
Set cookie by setting the HTTP response header "set-cookie" @param $name @param null $value @param null $expire @param null $domainPath @param null $https @param null $httpOnly @return bool
[ "Set", "cookie", "by", "setting", "the", "HTTP", "response", "header", "set", "-", "cookie" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/Controller.php#L97-L100
oat-sa/tao-core
models/classes/http/Controller.php
Controller.setContentHeader
protected function setContentHeader($contentType, $charset = 'UTF-8') { $this->response = $this->getPsrResponse()->withHeader('content-type', $contentType . ';' . $charset); return $this; }
php
protected function setContentHeader($contentType, $charset = 'UTF-8') { $this->response = $this->getPsrResponse()->withHeader('content-type', $contentType . ';' . $charset); return $this; }
[ "protected", "function", "setContentHeader", "(", "$", "contentType", ",", "$", "charset", "=", "'UTF-8'", ")", "{", "$", "this", "->", "response", "=", "$", "this", "->", "getPsrResponse", "(", ")", "->", "withHeader", "(", "'content-type'", ",", "$", "co...
Set content-type by setting the HTTP response header "content-type" @param $contentType @param string $charset @return $this
[ "Set", "content", "-", "type", "by", "setting", "the", "HTTP", "response", "header", "content", "-", "type" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/http/Controller.php#L109-L113
oat-sa/tao-core
helpers/form/class.FormFactory.php
tao_helpers_form_FormFactory.getForm
public static function getForm($name = '', array $options = array()) { $returnValue = null; //use the right implementation (depending the render mode) //@todo refactor this and use a FormElementFactory switch(self::$renderMode){ case 'xhtml': $myForm = new tao_helpers_form_xhtml_Form($name, $options); $myForm->setDecorators(array( 'element' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div')), 'group' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-group')), 'error' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-error')), 'actions-bottom' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-toolbar')), //'actions-top' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-toolbar')) )); $myForm->setActions(self::getCommonActions(), 'bottom'); break; default: throw new common_Exception("render mode {self::$renderMode} not yet supported"); } $returnValue = $myForm; return $returnValue; }
php
public static function getForm($name = '', array $options = array()) { $returnValue = null; //use the right implementation (depending the render mode) //@todo refactor this and use a FormElementFactory switch(self::$renderMode){ case 'xhtml': $myForm = new tao_helpers_form_xhtml_Form($name, $options); $myForm->setDecorators(array( 'element' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div')), 'group' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-group')), 'error' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-error')), 'actions-bottom' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-toolbar')), //'actions-top' => new tao_helpers_form_xhtml_TagWrapper(array('tag' => 'div', 'cssClass' => 'form-toolbar')) )); $myForm->setActions(self::getCommonActions(), 'bottom'); break; default: throw new common_Exception("render mode {self::$renderMode} not yet supported"); } $returnValue = $myForm; return $returnValue; }
[ "public", "static", "function", "getForm", "(", "$", "name", "=", "''", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "returnValue", "=", "null", ";", "//use the right implementation (depending the render mode)", "//@todo refactor this and use...
Factors an instance of Form @access public @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param string $name @param array $options @return tao_helpers_form_Form @throws common_Exception
[ "Factors", "an", "instance", "of", "Form" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/class.FormFactory.php#L74-L108
oat-sa/tao-core
helpers/form/class.FormFactory.php
tao_helpers_form_FormFactory.getElement
public static function getElement($name = '', $widgetId = '') { $eltClass = null; $definition = WidgetRegistry::getWidgetDefinitionById($widgetId); if (is_null($definition) || !isset($definition['renderers'][self::$renderMode])) { // could be a "pseudo" widget that has not been registered $candidate = "tao_helpers_form_elements_xhtml_{$widgetId}"; if (class_exists($candidate)) { $eltClass = $candidate; } } else { $eltClass = $definition['renderers'][self::$renderMode]; } if (!is_null($eltClass)) { $returnValue = new $eltClass($name); if(!$returnValue instanceof tao_helpers_form_FormElement){ throw new common_Exception("$eltClass must be a tao_helpers_form_FormElement"); } } else { $returnValue = null; common_Logger::w("Widget type with id ".$widgetId." not yet supported", array('FORM')); } return $returnValue; }
php
public static function getElement($name = '', $widgetId = '') { $eltClass = null; $definition = WidgetRegistry::getWidgetDefinitionById($widgetId); if (is_null($definition) || !isset($definition['renderers'][self::$renderMode])) { // could be a "pseudo" widget that has not been registered $candidate = "tao_helpers_form_elements_xhtml_{$widgetId}"; if (class_exists($candidate)) { $eltClass = $candidate; } } else { $eltClass = $definition['renderers'][self::$renderMode]; } if (!is_null($eltClass)) { $returnValue = new $eltClass($name); if(!$returnValue instanceof tao_helpers_form_FormElement){ throw new common_Exception("$eltClass must be a tao_helpers_form_FormElement"); } } else { $returnValue = null; common_Logger::w("Widget type with id ".$widgetId." not yet supported", array('FORM')); } return $returnValue; }
[ "public", "static", "function", "getElement", "(", "$", "name", "=", "''", ",", "$", "widgetId", "=", "''", ")", "{", "$", "eltClass", "=", "null", ";", "$", "definition", "=", "WidgetRegistry", "::", "getWidgetDefinitionById", "(", "$", "widgetId", ")", ...
Create dynamically a Form Element instance of the defined type @access public @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param string $name @param string $widgetId @return tao_helpers_form_FormElement @throws common_Exception @throws Exception
[ "Create", "dynamically", "a", "Form", "Element", "instance", "of", "the", "defined", "type" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/class.FormFactory.php#L121-L148
oat-sa/tao-core
helpers/form/class.FormFactory.php
tao_helpers_form_FormFactory.getValidator
public static function getValidator($name, $options = array()) { $returnValue = null; $clazz = 'tao_helpers_form_validators_'.$name; if(class_exists($clazz)){ $returnValue = new $clazz($options); } else { common_Logger::w('Unknown validator '.$name, array('TAO', 'FORM')); } return $returnValue; }
php
public static function getValidator($name, $options = array()) { $returnValue = null; $clazz = 'tao_helpers_form_validators_'.$name; if(class_exists($clazz)){ $returnValue = new $clazz($options); } else { common_Logger::w('Unknown validator '.$name, array('TAO', 'FORM')); } return $returnValue; }
[ "public", "static", "function", "getValidator", "(", "$", "name", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "returnValue", "=", "null", ";", "$", "clazz", "=", "'tao_helpers_form_validators_'", ".", "$", "name", ";", "if", "(", "class_e...
Get an instance of a Validator @access public @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param string $name @param array $options @return tao_helpers_form_Validator
[ "Get", "an", "instance", "of", "a", "Validator" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/class.FormFactory.php#L174-L190
oat-sa/tao-core
helpers/form/class.FormFactory.php
tao_helpers_form_FormFactory.getCommonActions
public static function getCommonActions($context = 'bottom', $save = true) { $returnValue = array(); switch($context){ case 'top': case 'bottom': default: $actions = tao_helpers_form_FormFactory::getElement('save', 'Free'); $value = ''; if($save){ $button = tao_helpers_form_FormFactory::getElement('Save','Button'); $button->setIcon('icon-save'); $button->setValue(__('Save')); $button->setType('submit'); $button->addClass('form-submitter btn-success small'); $value .= $button->render(); } $actions->setValue($value); $returnValue[] = $actions; break; } return $returnValue; }
php
public static function getCommonActions($context = 'bottom', $save = true) { $returnValue = array(); switch($context){ case 'top': case 'bottom': default: $actions = tao_helpers_form_FormFactory::getElement('save', 'Free'); $value = ''; if($save){ $button = tao_helpers_form_FormFactory::getElement('Save','Button'); $button->setIcon('icon-save'); $button->setValue(__('Save')); $button->setType('submit'); $button->addClass('form-submitter btn-success small'); $value .= $button->render(); } $actions->setValue($value); $returnValue[] = $actions; break; } return $returnValue; }
[ "public", "static", "function", "getCommonActions", "(", "$", "context", "=", "'bottom'", ",", "$", "save", "=", "true", ")", "{", "$", "returnValue", "=", "array", "(", ")", ";", "switch", "(", "$", "context", ")", "{", "case", "'top'", ":", "case", ...
Get the common actions: save and revert @access public @author Bertrand Chevrier, <bertrand.chevrier@tudor.lu> @param string $context @param boolean $save @return array
[ "Get", "the", "common", "actions", ":", "save", "and", "revert" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/class.FormFactory.php#L201-L229
oat-sa/tao-core
scripts/tools/ExtractCsvDuplicates.php
ExtractCsvDuplicates.process
protected function process() { $sourceFp = $this->getSourceFp(); $destinationFp = $this->getDestinationFp(); $index = $this->getIndex(); // Extract duplicates in a separate file. $duplicateCount = 0; foreach ($index as $identifier => $positions) { if (count($positions) > 1) { // We have a duplicate. foreach ($positions as $pos) { rewind($sourceFp); fseek($sourceFp, $pos); $sourceData = fgetcsv($sourceFp); fputcsv($destinationFp, $sourceData); $duplicateCount++; } } } return new Report( Report::TYPE_INFO, "${duplicateCount} duplicate records extracted in file '" . realpath($this->getDestination()) . "'." ); }
php
protected function process() { $sourceFp = $this->getSourceFp(); $destinationFp = $this->getDestinationFp(); $index = $this->getIndex(); // Extract duplicates in a separate file. $duplicateCount = 0; foreach ($index as $identifier => $positions) { if (count($positions) > 1) { // We have a duplicate. foreach ($positions as $pos) { rewind($sourceFp); fseek($sourceFp, $pos); $sourceData = fgetcsv($sourceFp); fputcsv($destinationFp, $sourceData); $duplicateCount++; } } } return new Report( Report::TYPE_INFO, "${duplicateCount} duplicate records extracted in file '" . realpath($this->getDestination()) . "'." ); }
[ "protected", "function", "process", "(", ")", "{", "$", "sourceFp", "=", "$", "this", "->", "getSourceFp", "(", ")", ";", "$", "destinationFp", "=", "$", "this", "->", "getDestinationFp", "(", ")", ";", "$", "index", "=", "$", "this", "->", "getIndex",...
Duplicate extraction logic. Extract duplicate rows from the source CSV file to the destination CSV file. @see \oat\tao\scripts\tools\AbstractIndexedCsv
[ "Duplicate", "extraction", "logic", "." ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/scripts/tools/ExtractCsvDuplicates.php#L40-L65
oat-sa/tao-core
helpers/translation/class.RDFExtractor.php
tao_helpers_translation_RDFExtractor.extract
public function extract() { foreach ($this->getPaths() as $path){ // In the RDFExtractor, we expect the paths to points directly to the file. if (!file_exists($path)){ throw new tao_helpers_translation_TranslationException("No RDF file to parse at '${path}'."); } else if (!is_readable($path)){ throw new tao_helpers_translation_TranslationException("'${path}' is not readable. Please check file system rights."); } else{ try{ $tus = array(); $rdfNS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; $rdfsNS = 'http://www.w3.org/2000/01/rdf-schema#'; $xmlNS = 'http://www.w3.org/XML/1998/namespace'; // http://www.w3.org/TR/REC-xml-names/#NT-NCName $translatableProperties = $this->translatableProperties; // Try to parse the file as a DOMDocument. $doc = new DOMDocument('1.0', 'UTF-8'); $doc->load(realpath($path)); if ($doc->documentElement->hasAttributeNS($xmlNS, 'base')) { $this->xmlBase[$path] = $doc->documentElement->getAttributeNodeNS($xmlNS, 'base')->value; } $descriptions = $doc->getElementsByTagNameNS($rdfNS, 'Description'); foreach ($descriptions as $description){ if ($description->hasAttributeNS($rdfNS, 'about')){ $about = $description->getAttributeNodeNS($rdfNS, 'about')->value; // At the moment only get rdfs:label and rdfs:comment // c.f. array $translatableProperties // In the future, this should be configured in the constructor // or by methods. $children = array(); foreach ($translatableProperties as $prop){ $uri = explode('#', $prop); if (count($uri) == 2){ $uri[0] .= '#'; $nodeList = $description->getElementsByTagNameNS($uri[0], $uri[1]); for ($i = 0; $i < $nodeList->length; $i++) { $children[] = $nodeList->item($i); } } } foreach ($children as $child) { // Only process if it has a language attribute. $tus = $this->processUnit($child, $xmlNS, $about, $tus); } } else{ // Description about nothing. continue; } } $this->setTranslationUnits($tus); } catch (DOMException $e){ throw new tao_helpers_translation_TranslationException("Unable to parse RDF file at '${path}'. DOM returns '" . $e->getMessage() . "'."); } } } }
php
public function extract() { foreach ($this->getPaths() as $path){ // In the RDFExtractor, we expect the paths to points directly to the file. if (!file_exists($path)){ throw new tao_helpers_translation_TranslationException("No RDF file to parse at '${path}'."); } else if (!is_readable($path)){ throw new tao_helpers_translation_TranslationException("'${path}' is not readable. Please check file system rights."); } else{ try{ $tus = array(); $rdfNS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; $rdfsNS = 'http://www.w3.org/2000/01/rdf-schema#'; $xmlNS = 'http://www.w3.org/XML/1998/namespace'; // http://www.w3.org/TR/REC-xml-names/#NT-NCName $translatableProperties = $this->translatableProperties; // Try to parse the file as a DOMDocument. $doc = new DOMDocument('1.0', 'UTF-8'); $doc->load(realpath($path)); if ($doc->documentElement->hasAttributeNS($xmlNS, 'base')) { $this->xmlBase[$path] = $doc->documentElement->getAttributeNodeNS($xmlNS, 'base')->value; } $descriptions = $doc->getElementsByTagNameNS($rdfNS, 'Description'); foreach ($descriptions as $description){ if ($description->hasAttributeNS($rdfNS, 'about')){ $about = $description->getAttributeNodeNS($rdfNS, 'about')->value; // At the moment only get rdfs:label and rdfs:comment // c.f. array $translatableProperties // In the future, this should be configured in the constructor // or by methods. $children = array(); foreach ($translatableProperties as $prop){ $uri = explode('#', $prop); if (count($uri) == 2){ $uri[0] .= '#'; $nodeList = $description->getElementsByTagNameNS($uri[0], $uri[1]); for ($i = 0; $i < $nodeList->length; $i++) { $children[] = $nodeList->item($i); } } } foreach ($children as $child) { // Only process if it has a language attribute. $tus = $this->processUnit($child, $xmlNS, $about, $tus); } } else{ // Description about nothing. continue; } } $this->setTranslationUnits($tus); } catch (DOMException $e){ throw new tao_helpers_translation_TranslationException("Unable to parse RDF file at '${path}'. DOM returns '" . $e->getMessage() . "'."); } } } }
[ "public", "function", "extract", "(", ")", "{", "foreach", "(", "$", "this", "->", "getPaths", "(", ")", "as", "$", "path", ")", "{", "// In the RDFExtractor, we expect the paths to points directly to the file.", "if", "(", "!", "file_exists", "(", "$", "path", ...
Short description of method extract @access public @author Joel Bout, <joel.bout@tudor.lu> @return mixed
[ "Short", "description", "of", "method", "extract" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.RDFExtractor.php#L63-L131
oat-sa/tao-core
helpers/translation/class.RDFExtractor.php
tao_helpers_translation_RDFExtractor.getXmlBase
public function getXmlBase($path) { $returnValue = (string) ''; if (!isset($this->xmlBase[$path])) { throw new tao_helpers_translation_TranslationException('Missing xmlBase for file '.$path); } $returnValue = $this->xmlBase[$path]; return (string) $returnValue; }
php
public function getXmlBase($path) { $returnValue = (string) ''; if (!isset($this->xmlBase[$path])) { throw new tao_helpers_translation_TranslationException('Missing xmlBase for file '.$path); } $returnValue = $this->xmlBase[$path]; return (string) $returnValue; }
[ "public", "function", "getXmlBase", "(", "$", "path", ")", "{", "$", "returnValue", "=", "(", "string", ")", "''", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "xmlBase", "[", "$", "path", "]", ")", ")", "{", "throw", "new", "tao_helpers_t...
Short description of method getXmlBase @access public @author Joel Bout, <joel.bout@tudor.lu> @param string path @return string
[ "Short", "description", "of", "method", "getXmlBase" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/translation/class.RDFExtractor.php#L190-L202
oat-sa/tao-core
actions/class.QueueAction.php
tao_actions_QueueAction.getReportAttachment
protected function getReportAttachment(common_report_Report $report) { $filename = null; /** @var common_report_Report $success */ foreach ($report->getSuccesses() as $success) { if (!is_null($filename = $success->getData())) { if (is_array($filename)) { $filename = $filename['uriResource']; } break; } } return $filename; }
php
protected function getReportAttachment(common_report_Report $report) { $filename = null; /** @var common_report_Report $success */ foreach ($report->getSuccesses() as $success) { if (!is_null($filename = $success->getData())) { if (is_array($filename)) { $filename = $filename['uriResource']; } break; } } return $filename; }
[ "protected", "function", "getReportAttachment", "(", "common_report_Report", "$", "report", ")", "{", "$", "filename", "=", "null", ";", "/** @var common_report_Report $success */", "foreach", "(", "$", "report", "->", "getSuccesses", "(", ")", "as", "$", "success",...
Extracts the path of the file attached to a report @param common_report_Report $report @return mixed|null
[ "Extracts", "the", "path", "of", "the", "file", "attached", "to", "a", "report" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.QueueAction.php#L98-L111
oat-sa/tao-core
actions/class.QueueAction.php
tao_actions_QueueAction.getFile
protected function getFile($fileUri) { /* @var \oat\oatbox\filesystem\FileSystemService $fileSystemService */ $fileSystemService = $this->getServiceLocator()->get(\oat\oatbox\filesystem\FileSystemService::SERVICE_ID); $storageService = $fileSystemService->getFileSystem(Queue::FILE_SYSTEM_ID); return $storageService->readStream($fileUri); }
php
protected function getFile($fileUri) { /* @var \oat\oatbox\filesystem\FileSystemService $fileSystemService */ $fileSystemService = $this->getServiceLocator()->get(\oat\oatbox\filesystem\FileSystemService::SERVICE_ID); $storageService = $fileSystemService->getFileSystem(Queue::FILE_SYSTEM_ID); return $storageService->readStream($fileUri); }
[ "protected", "function", "getFile", "(", "$", "fileUri", ")", "{", "/* @var \\oat\\oatbox\\filesystem\\FileSystemService $fileSystemService */", "$", "fileSystemService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "\\", "oat", "\\", "oatb...
Gets file from URI @param string $fileUri @return File
[ "Gets", "file", "from", "URI" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/actions/class.QueueAction.php#L118-L125
oat-sa/tao-core
helpers/form/class.GenerisTreeForm.php
tao_helpers_form_GenerisTreeForm.buildTree
public static function buildTree(core_kernel_classes_Resource $resource, core_kernel_classes_Property $property) { $tree = new self($resource, $property); $range = $property->getRange(); $tree->setData('rootNode', $range->getUri()); $tree->setData('dataUrl', _url('getData', 'GenerisTree', 'tao')); $tree->setData('saveUrl', _url('setValues', 'GenerisTree', 'tao')); $values = $resource->getPropertyValues($property); $tree->setData('values', $values); $openNodeUris = TreeHelper::getNodesToOpen($values, $range); $tree->setData('openNodes', $openNodeUris); return $tree; }
php
public static function buildTree(core_kernel_classes_Resource $resource, core_kernel_classes_Property $property) { $tree = new self($resource, $property); $range = $property->getRange(); $tree->setData('rootNode', $range->getUri()); $tree->setData('dataUrl', _url('getData', 'GenerisTree', 'tao')); $tree->setData('saveUrl', _url('setValues', 'GenerisTree', 'tao')); $values = $resource->getPropertyValues($property); $tree->setData('values', $values); $openNodeUris = TreeHelper::getNodesToOpen($values, $range); $tree->setData('openNodes', $openNodeUris); return $tree; }
[ "public", "static", "function", "buildTree", "(", "core_kernel_classes_Resource", "$", "resource", ",", "core_kernel_classes_Property", "$", "property", ")", "{", "$", "tree", "=", "new", "self", "(", "$", "resource", ",", "$", "property", ")", ";", "$", "rang...
Generates a form to define the values of a specific property for a resource @param core_kernel_classes_Resource $resource @param core_kernel_classes_Property $property @return tao_helpers_form_GenerisTreeForm
[ "Generates", "a", "form", "to", "define", "the", "values", "of", "a", "specific", "property", "for", "a", "resource" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/class.GenerisTreeForm.php#L44-L57
oat-sa/tao-core
helpers/form/class.GenerisTreeForm.php
tao_helpers_form_GenerisTreeForm.buildReverseTree
public static function buildReverseTree(core_kernel_classes_Resource $resource, core_kernel_classes_Property $property) { $tree = new self($resource, $property); $domainCollection = $property->getDomain(); if (!$domainCollection->isEmpty()) { $domain = $domainCollection->get(0); $tree->setData('rootNode', $domain->getUri()); $tree->setData('dataUrl', _url('getData', 'GenerisTree', 'tao')); $tree->setData('saveUrl', _url('setReverseValues', 'GenerisTree', 'tao')); $values = array_keys($domain->searchInstances(array( $property->getUri() => $resource ), array('recursive' => true, 'like' => false))); $tree->setData('values', $values); $openNodeUris = TreeHelper::getNodesToOpen($values, $domain); $tree->setData('openNodes', $openNodeUris); } return $tree; }
php
public static function buildReverseTree(core_kernel_classes_Resource $resource, core_kernel_classes_Property $property) { $tree = new self($resource, $property); $domainCollection = $property->getDomain(); if (!$domainCollection->isEmpty()) { $domain = $domainCollection->get(0); $tree->setData('rootNode', $domain->getUri()); $tree->setData('dataUrl', _url('getData', 'GenerisTree', 'tao')); $tree->setData('saveUrl', _url('setReverseValues', 'GenerisTree', 'tao')); $values = array_keys($domain->searchInstances(array( $property->getUri() => $resource ), array('recursive' => true, 'like' => false))); $tree->setData('values', $values); $openNodeUris = TreeHelper::getNodesToOpen($values, $domain); $tree->setData('openNodes', $openNodeUris); } return $tree; }
[ "public", "static", "function", "buildReverseTree", "(", "core_kernel_classes_Resource", "$", "resource", ",", "core_kernel_classes_Property", "$", "property", ")", "{", "$", "tree", "=", "new", "self", "(", "$", "resource", ",", "$", "property", ")", ";", "$", ...
Generates a form to define the reverse values of a specific property for a resource This allows to set/remove multiple triples that share the same object @param core_kernel_classes_Resource $resource @param core_kernel_classes_Property $property @return tao_helpers_form_GenerisTreeForm
[ "Generates", "a", "form", "to", "define", "the", "reverse", "values", "of", "a", "specific", "property", "for", "a", "resource", "This", "allows", "to", "set", "/", "remove", "multiple", "triples", "that", "share", "the", "same", "object" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/helpers/form/class.GenerisTreeForm.php#L67-L86
oat-sa/tao-core
models/classes/metadata/import/OntologyMetadataImporter.php
OntologyMetadataImporter.import
public function import(array $data, $dryrun = false) { try { /** @var Injector[] $injectors */ $injectors = $this->getInjectors(); } catch (InconsistencyConfigException $e) { return \common_report_Report::createFailure('Config problem: ' . $e->getMessage()); } // Global report $report = \common_report_Report::createInfo('Report of metadata import.'); // Foreach line of dateSource foreach ($data as $uri => $dataSource) { try { // Check if resource exists $resource = $this->getResource($uri); if (! $resource->exists()) { throw new MetadataImportException('Unable to find resource associated to uri : "' . $uri . '"'); } $lineReport = \common_report_Report::createInfo('Report by line.'); $dataSource = array_change_key_case($dataSource); // Foreach injector to map a target source /** @var Injector $injector */ foreach ($injectors as $name => $injector) { $injectorReport = null; try { $dataRead = $injector->read($dataSource); $injector->write($resource, $dataRead, $dryrun); $injectorReport = \common_report_Report::createSuccess('Injector "' . $name . '" successfully ran.'); } catch (MetadataInjectorReadException $e) { $injectorReport = \common_report_Report::createFailure( 'Injector "' . $name . '" failed to run at read: ' . $e->getMessage() ); } catch (MetadataInjectorWriteException $e) { $injectorReport = \common_report_Report::createFailure( 'Injector "' . $name . '" failed to run at write: ' . $e->getMessage() ); } // Skip if there are no report (no data to read for this injector) if (! is_null($injectorReport)) { $lineReport->add($injectorReport); } } } catch (MetadataImportException $e) { $lineReport = \common_report_Report::createFailure($e->getMessage()); } $report->add($lineReport); } return $report; }
php
public function import(array $data, $dryrun = false) { try { /** @var Injector[] $injectors */ $injectors = $this->getInjectors(); } catch (InconsistencyConfigException $e) { return \common_report_Report::createFailure('Config problem: ' . $e->getMessage()); } // Global report $report = \common_report_Report::createInfo('Report of metadata import.'); // Foreach line of dateSource foreach ($data as $uri => $dataSource) { try { // Check if resource exists $resource = $this->getResource($uri); if (! $resource->exists()) { throw new MetadataImportException('Unable to find resource associated to uri : "' . $uri . '"'); } $lineReport = \common_report_Report::createInfo('Report by line.'); $dataSource = array_change_key_case($dataSource); // Foreach injector to map a target source /** @var Injector $injector */ foreach ($injectors as $name => $injector) { $injectorReport = null; try { $dataRead = $injector->read($dataSource); $injector->write($resource, $dataRead, $dryrun); $injectorReport = \common_report_Report::createSuccess('Injector "' . $name . '" successfully ran.'); } catch (MetadataInjectorReadException $e) { $injectorReport = \common_report_Report::createFailure( 'Injector "' . $name . '" failed to run at read: ' . $e->getMessage() ); } catch (MetadataInjectorWriteException $e) { $injectorReport = \common_report_Report::createFailure( 'Injector "' . $name . '" failed to run at write: ' . $e->getMessage() ); } // Skip if there are no report (no data to read for this injector) if (! is_null($injectorReport)) { $lineReport->add($injectorReport); } } } catch (MetadataImportException $e) { $lineReport = \common_report_Report::createFailure($e->getMessage()); } $report->add($lineReport); } return $report; }
[ "public", "function", "import", "(", "array", "$", "data", ",", "$", "dryrun", "=", "false", ")", "{", "try", "{", "/** @var Injector[] $injectors */", "$", "injectors", "=", "$", "this", "->", "getInjectors", "(", ")", ";", "}", "catch", "(", "Inconsisten...
Main method to import Iterator data to Ontology object @param array $data @param boolean $dryrun If set to true no data will be written @return \common_report_Report
[ "Main", "method", "to", "import", "Iterator", "data", "to", "Ontology", "object" ]
train
https://github.com/oat-sa/tao-core/blob/067ef1ddc1a273a6f59be1cc6d07ada7c6033cd0/models/classes/metadata/import/OntologyMetadataImporter.php#L55-L113