repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
thekordy/ticketit
src/Models/Ticket.php
Ticket.scopeAgentUserTickets
public function scopeAgentUserTickets($query, $id) { return $query->where(function ($subquery) use ($id) { $subquery->where('agent_id', $id)->orWhere('user_id', $id); }); }
php
public function scopeAgentUserTickets($query, $id) { return $query->where(function ($subquery) use ($id) { $subquery->where('agent_id', $id)->orWhere('user_id', $id); }); }
[ "public", "function", "scopeAgentUserTickets", "(", "$", "query", ",", "$", "id", ")", "{", "return", "$", "query", "->", "where", "(", "function", "(", "$", "subquery", ")", "use", "(", "$", "id", ")", "{", "$", "subquery", "->", "where", "(", "'agent_id'", ",", "$", "id", ")", "->", "orWhere", "(", "'user_id'", ",", "$", "id", ")", ";", "}", ")", ";", "}" ]
Get all agent tickets. @param $query @param $id @return mixed
[ "Get", "all", "agent", "tickets", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Models/Ticket.php#L184-L189
train
thekordy/ticketit
src/Models/Ticket.php
Ticket.autoSelectAgent
public function autoSelectAgent() { $cat_id = $this->category_id; $agents = Category::find($cat_id)->agents()->with(['agentOpenTickets' => function ($query) { $query->addSelect(['id', 'agent_id']); }])->get(); $count = 0; $lowest_tickets = 1000000; // If no agent selected, select the admin $first_admin = Agent::admins()->first(); $selected_agent_id = $first_admin->id; foreach ($agents as $agent) { if ($count == 0) { $lowest_tickets = $agent->agentOpenTickets->count(); $selected_agent_id = $agent->id; } else { $tickets_count = $agent->agentOpenTickets->count(); if ($tickets_count < $lowest_tickets) { $lowest_tickets = $tickets_count; $selected_agent_id = $agent->id; } } $count++; } $this->agent_id = $selected_agent_id; return $this; }
php
public function autoSelectAgent() { $cat_id = $this->category_id; $agents = Category::find($cat_id)->agents()->with(['agentOpenTickets' => function ($query) { $query->addSelect(['id', 'agent_id']); }])->get(); $count = 0; $lowest_tickets = 1000000; // If no agent selected, select the admin $first_admin = Agent::admins()->first(); $selected_agent_id = $first_admin->id; foreach ($agents as $agent) { if ($count == 0) { $lowest_tickets = $agent->agentOpenTickets->count(); $selected_agent_id = $agent->id; } else { $tickets_count = $agent->agentOpenTickets->count(); if ($tickets_count < $lowest_tickets) { $lowest_tickets = $tickets_count; $selected_agent_id = $agent->id; } } $count++; } $this->agent_id = $selected_agent_id; return $this; }
[ "public", "function", "autoSelectAgent", "(", ")", "{", "$", "cat_id", "=", "$", "this", "->", "category_id", ";", "$", "agents", "=", "Category", "::", "find", "(", "$", "cat_id", ")", "->", "agents", "(", ")", "->", "with", "(", "[", "'agentOpenTickets'", "=>", "function", "(", "$", "query", ")", "{", "$", "query", "->", "addSelect", "(", "[", "'id'", ",", "'agent_id'", "]", ")", ";", "}", "]", ")", "->", "get", "(", ")", ";", "$", "count", "=", "0", ";", "$", "lowest_tickets", "=", "1000000", ";", "// If no agent selected, select the admin", "$", "first_admin", "=", "Agent", "::", "admins", "(", ")", "->", "first", "(", ")", ";", "$", "selected_agent_id", "=", "$", "first_admin", "->", "id", ";", "foreach", "(", "$", "agents", "as", "$", "agent", ")", "{", "if", "(", "$", "count", "==", "0", ")", "{", "$", "lowest_tickets", "=", "$", "agent", "->", "agentOpenTickets", "->", "count", "(", ")", ";", "$", "selected_agent_id", "=", "$", "agent", "->", "id", ";", "}", "else", "{", "$", "tickets_count", "=", "$", "agent", "->", "agentOpenTickets", "->", "count", "(", ")", ";", "if", "(", "$", "tickets_count", "<", "$", "lowest_tickets", ")", "{", "$", "lowest_tickets", "=", "$", "tickets_count", ";", "$", "selected_agent_id", "=", "$", "agent", "->", "id", ";", "}", "}", "$", "count", "++", ";", "}", "$", "this", "->", "agent_id", "=", "$", "selected_agent_id", ";", "return", "$", "this", ";", "}" ]
Sets the agent with the lowest tickets assigned in specific category. @return Ticket
[ "Sets", "the", "agent", "with", "the", "lowest", "tickets", "assigned", "in", "specific", "category", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Models/Ticket.php#L196-L223
train
thekordy/ticketit
src/Controllers/AdministratorsController.php
AdministratorsController.addAdministrators
public function addAdministrators($user_ids) { $users = Agent::find($user_ids); foreach ($users as $user) { $user->ticketit_admin = true; $user->save(); $users_list[] = $user->name; } return $users_list; }
php
public function addAdministrators($user_ids) { $users = Agent::find($user_ids); foreach ($users as $user) { $user->ticketit_admin = true; $user->save(); $users_list[] = $user->name; } return $users_list; }
[ "public", "function", "addAdministrators", "(", "$", "user_ids", ")", "{", "$", "users", "=", "Agent", "::", "find", "(", "$", "user_ids", ")", ";", "foreach", "(", "$", "users", "as", "$", "user", ")", "{", "$", "user", "->", "ticketit_admin", "=", "true", ";", "$", "user", "->", "save", "(", ")", ";", "$", "users_list", "[", "]", "=", "$", "user", "->", "name", ";", "}", "return", "$", "users_list", ";", "}" ]
Assign users as administrators. @param $user_ids @return array
[ "Assign", "users", "as", "administrators", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/AdministratorsController.php#L62-L72
train
thekordy/ticketit
src/Controllers/AdministratorsController.php
AdministratorsController.removeAdministrator
public function removeAdministrator($id) { $administrator = Agent::find($id); $administrator->ticketit_admin = false; $administrator->save(); // Remove him from tickets categories as well if (version_compare(app()->version(), '5.2.0', '>=')) { $administrator_cats = $administrator->categories->pluck('id')->toArray(); } else { // if Laravel 5.1 $administrator_cats = $administrator->categories->lists('id')->toArray(); } $administrator->categories()->detach($administrator_cats); return $administrator; }
php
public function removeAdministrator($id) { $administrator = Agent::find($id); $administrator->ticketit_admin = false; $administrator->save(); // Remove him from tickets categories as well if (version_compare(app()->version(), '5.2.0', '>=')) { $administrator_cats = $administrator->categories->pluck('id')->toArray(); } else { // if Laravel 5.1 $administrator_cats = $administrator->categories->lists('id')->toArray(); } $administrator->categories()->detach($administrator_cats); return $administrator; }
[ "public", "function", "removeAdministrator", "(", "$", "id", ")", "{", "$", "administrator", "=", "Agent", "::", "find", "(", "$", "id", ")", ";", "$", "administrator", "->", "ticketit_admin", "=", "false", ";", "$", "administrator", "->", "save", "(", ")", ";", "// Remove him from tickets categories as well", "if", "(", "version_compare", "(", "app", "(", ")", "->", "version", "(", ")", ",", "'5.2.0'", ",", "'>='", ")", ")", "{", "$", "administrator_cats", "=", "$", "administrator", "->", "categories", "->", "pluck", "(", "'id'", ")", "->", "toArray", "(", ")", ";", "}", "else", "{", "// if Laravel 5.1", "$", "administrator_cats", "=", "$", "administrator", "->", "categories", "->", "lists", "(", "'id'", ")", "->", "toArray", "(", ")", ";", "}", "$", "administrator", "->", "categories", "(", ")", "->", "detach", "(", "$", "administrator_cats", ")", ";", "return", "$", "administrator", ";", "}" ]
Remove user from the administrators. @param $id @return mixed
[ "Remove", "user", "from", "the", "administrators", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/AdministratorsController.php#L81-L97
train
thekordy/ticketit
src/Controllers/AdministratorsController.php
AdministratorsController.syncAdministratorCategories
public function syncAdministratorCategories($id, Request $request) { $form_cats = ($request->input('administrator_cats') == null) ? [] : $request->input('administrator_cats'); $administrator = Agent::find($id); $administrator->categories()->sync($form_cats); }
php
public function syncAdministratorCategories($id, Request $request) { $form_cats = ($request->input('administrator_cats') == null) ? [] : $request->input('administrator_cats'); $administrator = Agent::find($id); $administrator->categories()->sync($form_cats); }
[ "public", "function", "syncAdministratorCategories", "(", "$", "id", ",", "Request", "$", "request", ")", "{", "$", "form_cats", "=", "(", "$", "request", "->", "input", "(", "'administrator_cats'", ")", "==", "null", ")", "?", "[", "]", ":", "$", "request", "->", "input", "(", "'administrator_cats'", ")", ";", "$", "administrator", "=", "Agent", "::", "find", "(", "$", "id", ")", ";", "$", "administrator", "->", "categories", "(", ")", "->", "sync", "(", "$", "form_cats", ")", ";", "}" ]
Sync Administrator categories with the selected categories got from update form. @param $id @param Request $request
[ "Sync", "Administrator", "categories", "with", "the", "selected", "categories", "got", "from", "update", "form", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/AdministratorsController.php#L105-L110
train
thekordy/ticketit
src/Controllers/ConfigurationsController.php
ConfigurationsController.index
public function index() { $configurations = Configuration::all(); $configurations_by_sections = ['init' => [], 'email' => [], 'tickets' => [], 'perms' => [], 'editor' => [], 'other' => []]; $init_section = ['main_route', 'main_route_path', 'admin_route', 'admin_route_path', 'master_template', 'bootstrap_version', 'routes']; $email_section = ['status_notification', 'comment_notification', 'queue_emails', 'assigned_notification', 'email.template', 'email.header', 'email.signoff', 'email.signature', 'email.dashboard', 'email.google_plus_link', 'email.facebook_link', 'email.twitter_link', 'email.footer', 'email.footer_link', 'email.color_body_bg', 'email.color_header_bg', 'email.color_content_bg', 'email.color_footer_bg', 'email.color_button_bg', ]; $tickets_section = ['default_status_id', 'default_close_status_id', 'default_reopen_status_id', 'paginate_items']; $perms_section = ['agent_restrict', 'close_ticket_perm', 'reopen_ticket_perm']; $editor_section = ['editor_enabled', 'include_font_awesome', 'editor_html_highlighter', 'codemirror_theme', 'summernote_locale', 'summernote_options_json_file', 'purifier_config', ]; // Split them into configurations sections for tabs foreach ($configurations as $config_item) { //trim long values (ex serialised arrays) $config_item->value = $config_item->getShortContent(25, 'value'); $config_item->default = $config_item->getShortContent(25, 'default'); if (in_array($config_item->slug, $init_section)) { $configurations_by_sections['init'][] = $config_item; } elseif (in_array($config_item->slug, $email_section)) { $configurations_by_sections['email'][] = $config_item; } elseif (in_array($config_item->slug, $tickets_section)) { $configurations_by_sections['tickets'][] = $config_item; } elseif (in_array($config_item->slug, $perms_section)) { $configurations_by_sections['perms'][] = $config_item; } elseif (in_array($config_item->slug, $editor_section)) { $configurations_by_sections['editor'][] = $config_item; } else { $configurations_by_sections['other'][] = $config_item; } } return view('ticketit::admin.configuration.index', compact('configurations', 'configurations_by_sections')); }
php
public function index() { $configurations = Configuration::all(); $configurations_by_sections = ['init' => [], 'email' => [], 'tickets' => [], 'perms' => [], 'editor' => [], 'other' => []]; $init_section = ['main_route', 'main_route_path', 'admin_route', 'admin_route_path', 'master_template', 'bootstrap_version', 'routes']; $email_section = ['status_notification', 'comment_notification', 'queue_emails', 'assigned_notification', 'email.template', 'email.header', 'email.signoff', 'email.signature', 'email.dashboard', 'email.google_plus_link', 'email.facebook_link', 'email.twitter_link', 'email.footer', 'email.footer_link', 'email.color_body_bg', 'email.color_header_bg', 'email.color_content_bg', 'email.color_footer_bg', 'email.color_button_bg', ]; $tickets_section = ['default_status_id', 'default_close_status_id', 'default_reopen_status_id', 'paginate_items']; $perms_section = ['agent_restrict', 'close_ticket_perm', 'reopen_ticket_perm']; $editor_section = ['editor_enabled', 'include_font_awesome', 'editor_html_highlighter', 'codemirror_theme', 'summernote_locale', 'summernote_options_json_file', 'purifier_config', ]; // Split them into configurations sections for tabs foreach ($configurations as $config_item) { //trim long values (ex serialised arrays) $config_item->value = $config_item->getShortContent(25, 'value'); $config_item->default = $config_item->getShortContent(25, 'default'); if (in_array($config_item->slug, $init_section)) { $configurations_by_sections['init'][] = $config_item; } elseif (in_array($config_item->slug, $email_section)) { $configurations_by_sections['email'][] = $config_item; } elseif (in_array($config_item->slug, $tickets_section)) { $configurations_by_sections['tickets'][] = $config_item; } elseif (in_array($config_item->slug, $perms_section)) { $configurations_by_sections['perms'][] = $config_item; } elseif (in_array($config_item->slug, $editor_section)) { $configurations_by_sections['editor'][] = $config_item; } else { $configurations_by_sections['other'][] = $config_item; } } return view('ticketit::admin.configuration.index', compact('configurations', 'configurations_by_sections')); }
[ "public", "function", "index", "(", ")", "{", "$", "configurations", "=", "Configuration", "::", "all", "(", ")", ";", "$", "configurations_by_sections", "=", "[", "'init'", "=>", "[", "]", ",", "'email'", "=>", "[", "]", ",", "'tickets'", "=>", "[", "]", ",", "'perms'", "=>", "[", "]", ",", "'editor'", "=>", "[", "]", ",", "'other'", "=>", "[", "]", "]", ";", "$", "init_section", "=", "[", "'main_route'", ",", "'main_route_path'", ",", "'admin_route'", ",", "'admin_route_path'", ",", "'master_template'", ",", "'bootstrap_version'", ",", "'routes'", "]", ";", "$", "email_section", "=", "[", "'status_notification'", ",", "'comment_notification'", ",", "'queue_emails'", ",", "'assigned_notification'", ",", "'email.template'", ",", "'email.header'", ",", "'email.signoff'", ",", "'email.signature'", ",", "'email.dashboard'", ",", "'email.google_plus_link'", ",", "'email.facebook_link'", ",", "'email.twitter_link'", ",", "'email.footer'", ",", "'email.footer_link'", ",", "'email.color_body_bg'", ",", "'email.color_header_bg'", ",", "'email.color_content_bg'", ",", "'email.color_footer_bg'", ",", "'email.color_button_bg'", ",", "]", ";", "$", "tickets_section", "=", "[", "'default_status_id'", ",", "'default_close_status_id'", ",", "'default_reopen_status_id'", ",", "'paginate_items'", "]", ";", "$", "perms_section", "=", "[", "'agent_restrict'", ",", "'close_ticket_perm'", ",", "'reopen_ticket_perm'", "]", ";", "$", "editor_section", "=", "[", "'editor_enabled'", ",", "'include_font_awesome'", ",", "'editor_html_highlighter'", ",", "'codemirror_theme'", ",", "'summernote_locale'", ",", "'summernote_options_json_file'", ",", "'purifier_config'", ",", "]", ";", "// Split them into configurations sections for tabs", "foreach", "(", "$", "configurations", "as", "$", "config_item", ")", "{", "//trim long values (ex serialised arrays)", "$", "config_item", "->", "value", "=", "$", "config_item", "->", "getShortContent", "(", "25", ",", "'value'", ")", ";", "$", "config_item", "->", "default", "=", "$", "config_item", "->", "getShortContent", "(", "25", ",", "'default'", ")", ";", "if", "(", "in_array", "(", "$", "config_item", "->", "slug", ",", "$", "init_section", ")", ")", "{", "$", "configurations_by_sections", "[", "'init'", "]", "[", "]", "=", "$", "config_item", ";", "}", "elseif", "(", "in_array", "(", "$", "config_item", "->", "slug", ",", "$", "email_section", ")", ")", "{", "$", "configurations_by_sections", "[", "'email'", "]", "[", "]", "=", "$", "config_item", ";", "}", "elseif", "(", "in_array", "(", "$", "config_item", "->", "slug", ",", "$", "tickets_section", ")", ")", "{", "$", "configurations_by_sections", "[", "'tickets'", "]", "[", "]", "=", "$", "config_item", ";", "}", "elseif", "(", "in_array", "(", "$", "config_item", "->", "slug", ",", "$", "perms_section", ")", ")", "{", "$", "configurations_by_sections", "[", "'perms'", "]", "[", "]", "=", "$", "config_item", ";", "}", "elseif", "(", "in_array", "(", "$", "config_item", "->", "slug", ",", "$", "editor_section", ")", ")", "{", "$", "configurations_by_sections", "[", "'editor'", "]", "[", "]", "=", "$", "config_item", ";", "}", "else", "{", "$", "configurations_by_sections", "[", "'other'", "]", "[", "]", "=", "$", "config_item", ";", "}", "}", "return", "view", "(", "'ticketit::admin.configuration.index'", ",", "compact", "(", "'configurations'", ",", "'configurations_by_sections'", ")", ")", ";", "}" ]
Display a listing of the Setting. @return Response
[ "Display", "a", "listing", "of", "the", "Setting", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/ConfigurationsController.php#L20-L57
train
thekordy/ticketit
src/Controllers/ConfigurationsController.php
ConfigurationsController.store
public function store(Request $request) { $this->validate($request, [ 'slug' => 'required', 'default' => 'required', 'value' => 'required', ]); $input = $request->all(); $configuration = new Configuration(); $configuration->create($input); Session::flash('configuration', 'Setting saved successfully.'); \Cache::forget('ticketit::settings'); // refresh cached settings return redirect()->action('\Kordy\Ticketit\Controllers\ConfigurationsController@index'); }
php
public function store(Request $request) { $this->validate($request, [ 'slug' => 'required', 'default' => 'required', 'value' => 'required', ]); $input = $request->all(); $configuration = new Configuration(); $configuration->create($input); Session::flash('configuration', 'Setting saved successfully.'); \Cache::forget('ticketit::settings'); // refresh cached settings return redirect()->action('\Kordy\Ticketit\Controllers\ConfigurationsController@index'); }
[ "public", "function", "store", "(", "Request", "$", "request", ")", "{", "$", "this", "->", "validate", "(", "$", "request", ",", "[", "'slug'", "=>", "'required'", ",", "'default'", "=>", "'required'", ",", "'value'", "=>", "'required'", ",", "]", ")", ";", "$", "input", "=", "$", "request", "->", "all", "(", ")", ";", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "configuration", "->", "create", "(", "$", "input", ")", ";", "Session", "::", "flash", "(", "'configuration'", ",", "'Setting saved successfully.'", ")", ";", "\\", "Cache", "::", "forget", "(", "'ticketit::settings'", ")", ";", "// refresh cached settings", "return", "redirect", "(", ")", "->", "action", "(", "'\\Kordy\\Ticketit\\Controllers\\ConfigurationsController@index'", ")", ";", "}" ]
Store a newly created Configuration in storage. @param Request $request @return \Illuminate\Http\RedirectResponse
[ "Store", "a", "newly", "created", "Configuration", "in", "storage", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/ConfigurationsController.php#L76-L92
train
thekordy/ticketit
src/Controllers/ConfigurationsController.php
ConfigurationsController.edit
public function edit($id) { $configuration = Configuration::findOrFail($id); $should_serialize = Setting::is_serialized($configuration->value); $default_serialized = Setting::is_serialized($configuration->default); return view('ticketit::admin.configuration.edit', compact('configuration', 'should_serialize', 'default_serialized')); }
php
public function edit($id) { $configuration = Configuration::findOrFail($id); $should_serialize = Setting::is_serialized($configuration->value); $default_serialized = Setting::is_serialized($configuration->default); return view('ticketit::admin.configuration.edit', compact('configuration', 'should_serialize', 'default_serialized')); }
[ "public", "function", "edit", "(", "$", "id", ")", "{", "$", "configuration", "=", "Configuration", "::", "findOrFail", "(", "$", "id", ")", ";", "$", "should_serialize", "=", "Setting", "::", "is_serialized", "(", "$", "configuration", "->", "value", ")", ";", "$", "default_serialized", "=", "Setting", "::", "is_serialized", "(", "$", "configuration", "->", "default", ")", ";", "return", "view", "(", "'ticketit::admin.configuration.edit'", ",", "compact", "(", "'configuration'", ",", "'should_serialize'", ",", "'default_serialized'", ")", ")", ";", "}" ]
Show the form for editing the specified Configuration. @param int $id @return Response
[ "Show", "the", "form", "for", "editing", "the", "specified", "Configuration", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/ConfigurationsController.php#L101-L108
train
thekordy/ticketit
src/Controllers/ConfigurationsController.php
ConfigurationsController.update
public function update(Request $request, $id) { $configuration = Configuration::findOrFail($id); $value = $request->value; if ($request->serialize) { //if(!Hash::check($request->password, Auth::user()->password)){ if (!Auth::attempt($request->only('password'), false, false)) { return back()->withErrors([trans('ticketit::admin.config-edit-auth-failed')]); } if (false === eval('$value = serialize('.$value.');')) { return back()->withErrors([trans('ticketit::admin.config-edit-eval-error')]); } } $configuration->update(['value' => $value, 'lang' => $request->lang]); Session::flash('configuration', trans('ticketit::lang.configuration-name-has-been-modified', ['name' => $request->name])); // refresh cached settings \Cache::forget('ticketit::settings'); \Cache::forget('ticketit::settings.'.$configuration->slug); //return redirect(route('ticketit::admin.configuration.index')); return redirect()->action('\Kordy\Ticketit\Controllers\ConfigurationsController@index'); }
php
public function update(Request $request, $id) { $configuration = Configuration::findOrFail($id); $value = $request->value; if ($request->serialize) { //if(!Hash::check($request->password, Auth::user()->password)){ if (!Auth::attempt($request->only('password'), false, false)) { return back()->withErrors([trans('ticketit::admin.config-edit-auth-failed')]); } if (false === eval('$value = serialize('.$value.');')) { return back()->withErrors([trans('ticketit::admin.config-edit-eval-error')]); } } $configuration->update(['value' => $value, 'lang' => $request->lang]); Session::flash('configuration', trans('ticketit::lang.configuration-name-has-been-modified', ['name' => $request->name])); // refresh cached settings \Cache::forget('ticketit::settings'); \Cache::forget('ticketit::settings.'.$configuration->slug); //return redirect(route('ticketit::admin.configuration.index')); return redirect()->action('\Kordy\Ticketit\Controllers\ConfigurationsController@index'); }
[ "public", "function", "update", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "configuration", "=", "Configuration", "::", "findOrFail", "(", "$", "id", ")", ";", "$", "value", "=", "$", "request", "->", "value", ";", "if", "(", "$", "request", "->", "serialize", ")", "{", "//if(!Hash::check($request->password, Auth::user()->password)){", "if", "(", "!", "Auth", "::", "attempt", "(", "$", "request", "->", "only", "(", "'password'", ")", ",", "false", ",", "false", ")", ")", "{", "return", "back", "(", ")", "->", "withErrors", "(", "[", "trans", "(", "'ticketit::admin.config-edit-auth-failed'", ")", "]", ")", ";", "}", "if", "(", "false", "===", "eval", "(", "'$value = serialize('", ".", "$", "value", ".", "');'", ")", ")", "{", "return", "back", "(", ")", "->", "withErrors", "(", "[", "trans", "(", "'ticketit::admin.config-edit-eval-error'", ")", "]", ")", ";", "}", "}", "$", "configuration", "->", "update", "(", "[", "'value'", "=>", "$", "value", ",", "'lang'", "=>", "$", "request", "->", "lang", "]", ")", ";", "Session", "::", "flash", "(", "'configuration'", ",", "trans", "(", "'ticketit::lang.configuration-name-has-been-modified'", ",", "[", "'name'", "=>", "$", "request", "->", "name", "]", ")", ")", ";", "// refresh cached settings", "\\", "Cache", "::", "forget", "(", "'ticketit::settings'", ")", ";", "\\", "Cache", "::", "forget", "(", "'ticketit::settings.'", ".", "$", "configuration", "->", "slug", ")", ";", "//return redirect(route('ticketit::admin.configuration.index'));", "return", "redirect", "(", ")", "->", "action", "(", "'\\Kordy\\Ticketit\\Controllers\\ConfigurationsController@index'", ")", ";", "}" ]
Update the specified Configuration in storage. @param int $id @param Request $request @return $this|\Illuminate\Http\RedirectResponse
[ "Update", "the", "specified", "Configuration", "in", "storage", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/ConfigurationsController.php#L118-L142
train
thekordy/ticketit
src/Seeds/SettingsTableSeeder.php
SettingsTableSeeder.run
public function run() { $defaults = []; $defaults = $this->cleanupAndMerge($this->getDefaults(), $this->config); foreach ($defaults as $slug => $column) { $setting = Setting::bySlug($slug); if ($setting->count()) { $setting->first()->update([ 'default' => $column, ]); } else { Setting::create([ 'lang' => null, 'slug' => $slug, 'value' => $column, 'default' => $column, ]); } } }
php
public function run() { $defaults = []; $defaults = $this->cleanupAndMerge($this->getDefaults(), $this->config); foreach ($defaults as $slug => $column) { $setting = Setting::bySlug($slug); if ($setting->count()) { $setting->first()->update([ 'default' => $column, ]); } else { Setting::create([ 'lang' => null, 'slug' => $slug, 'value' => $column, 'default' => $column, ]); } } }
[ "public", "function", "run", "(", ")", "{", "$", "defaults", "=", "[", "]", ";", "$", "defaults", "=", "$", "this", "->", "cleanupAndMerge", "(", "$", "this", "->", "getDefaults", "(", ")", ",", "$", "this", "->", "config", ")", ";", "foreach", "(", "$", "defaults", "as", "$", "slug", "=>", "$", "column", ")", "{", "$", "setting", "=", "Setting", "::", "bySlug", "(", "$", "slug", ")", ";", "if", "(", "$", "setting", "->", "count", "(", ")", ")", "{", "$", "setting", "->", "first", "(", ")", "->", "update", "(", "[", "'default'", "=>", "$", "column", ",", "]", ")", ";", "}", "else", "{", "Setting", "::", "create", "(", "[", "'lang'", "=>", "null", ",", "'slug'", "=>", "$", "slug", ",", "'value'", "=>", "$", "column", ",", "'default'", "=>", "$", "column", ",", "]", ")", ";", "}", "}", "}" ]
Seed the Plans table.
[ "Seed", "the", "Plans", "table", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Seeds/SettingsTableSeeder.php#L16-L38
train
thekordy/ticketit
src/Controllers/NotificationsController.php
NotificationsController.sendNotification
public function sendNotification($template, $data, $ticket, $notification_owner, $subject, $type) { /** * @var User */ $to = null; if ($type != 'agent') { $to = $ticket->user; if ($ticket->user->email != $notification_owner->email) { $to = $ticket->user; } if ($ticket->agent->email != $notification_owner->email) { $to = $ticket->agent; } } else { $to = $ticket->agent; } if (LaravelVersion::lt('5.4')) { $mail_callback = function ($m) use ($to, $notification_owner, $subject) { $m->to($to->email, $to->name); $m->replyTo($notification_owner->email, $notification_owner->name); $m->subject($subject); }; if (Setting::grab('queue_emails') == 'yes') { Mail::queue($template, $data, $mail_callback); } else { Mail::send($template, $data, $mail_callback); } } elseif (LaravelVersion::min('5.4')) { $mail = new \Kordy\Ticketit\Mail\TicketitNotification($template, $data, $notification_owner, $subject); if (Setting::grab('queue_emails') == 'yes') { Mail::to($to)->queue($mail); } else { Mail::to($to)->send($mail); } } }
php
public function sendNotification($template, $data, $ticket, $notification_owner, $subject, $type) { /** * @var User */ $to = null; if ($type != 'agent') { $to = $ticket->user; if ($ticket->user->email != $notification_owner->email) { $to = $ticket->user; } if ($ticket->agent->email != $notification_owner->email) { $to = $ticket->agent; } } else { $to = $ticket->agent; } if (LaravelVersion::lt('5.4')) { $mail_callback = function ($m) use ($to, $notification_owner, $subject) { $m->to($to->email, $to->name); $m->replyTo($notification_owner->email, $notification_owner->name); $m->subject($subject); }; if (Setting::grab('queue_emails') == 'yes') { Mail::queue($template, $data, $mail_callback); } else { Mail::send($template, $data, $mail_callback); } } elseif (LaravelVersion::min('5.4')) { $mail = new \Kordy\Ticketit\Mail\TicketitNotification($template, $data, $notification_owner, $subject); if (Setting::grab('queue_emails') == 'yes') { Mail::to($to)->queue($mail); } else { Mail::to($to)->send($mail); } } }
[ "public", "function", "sendNotification", "(", "$", "template", ",", "$", "data", ",", "$", "ticket", ",", "$", "notification_owner", ",", "$", "subject", ",", "$", "type", ")", "{", "/**\n * @var User\n */", "$", "to", "=", "null", ";", "if", "(", "$", "type", "!=", "'agent'", ")", "{", "$", "to", "=", "$", "ticket", "->", "user", ";", "if", "(", "$", "ticket", "->", "user", "->", "email", "!=", "$", "notification_owner", "->", "email", ")", "{", "$", "to", "=", "$", "ticket", "->", "user", ";", "}", "if", "(", "$", "ticket", "->", "agent", "->", "email", "!=", "$", "notification_owner", "->", "email", ")", "{", "$", "to", "=", "$", "ticket", "->", "agent", ";", "}", "}", "else", "{", "$", "to", "=", "$", "ticket", "->", "agent", ";", "}", "if", "(", "LaravelVersion", "::", "lt", "(", "'5.4'", ")", ")", "{", "$", "mail_callback", "=", "function", "(", "$", "m", ")", "use", "(", "$", "to", ",", "$", "notification_owner", ",", "$", "subject", ")", "{", "$", "m", "->", "to", "(", "$", "to", "->", "email", ",", "$", "to", "->", "name", ")", ";", "$", "m", "->", "replyTo", "(", "$", "notification_owner", "->", "email", ",", "$", "notification_owner", "->", "name", ")", ";", "$", "m", "->", "subject", "(", "$", "subject", ")", ";", "}", ";", "if", "(", "Setting", "::", "grab", "(", "'queue_emails'", ")", "==", "'yes'", ")", "{", "Mail", "::", "queue", "(", "$", "template", ",", "$", "data", ",", "$", "mail_callback", ")", ";", "}", "else", "{", "Mail", "::", "send", "(", "$", "template", ",", "$", "data", ",", "$", "mail_callback", ")", ";", "}", "}", "elseif", "(", "LaravelVersion", "::", "min", "(", "'5.4'", ")", ")", "{", "$", "mail", "=", "new", "\\", "Kordy", "\\", "Ticketit", "\\", "Mail", "\\", "TicketitNotification", "(", "$", "template", ",", "$", "data", ",", "$", "notification_owner", ",", "$", "subject", ")", ";", "if", "(", "Setting", "::", "grab", "(", "'queue_emails'", ")", "==", "'yes'", ")", "{", "Mail", "::", "to", "(", "$", "to", ")", "->", "queue", "(", "$", "mail", ")", ";", "}", "else", "{", "Mail", "::", "to", "(", "$", "to", ")", "->", "send", "(", "$", "mail", ")", ";", "}", "}", "}" ]
Send email notifications from the action owner to other involved users. @param string $template @param array $data @param object $ticket @param object $notification_owner
[ "Send", "email", "notifications", "from", "the", "action", "owner", "to", "other", "involved", "users", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/NotificationsController.php#L79-L123
train
thekordy/ticketit
src/Controllers/TicketsController.php
TicketsController.store
public function store(Request $request) { $this->validate($request, [ 'subject' => 'required|min:3', 'content' => 'required|min:6', 'priority_id' => 'required|exists:ticketit_priorities,id', 'category_id' => 'required|exists:ticketit_categories,id', ]); $ticket = new Ticket(); $ticket->subject = $request->subject; $ticket->setPurifiedContent($request->get('content')); $ticket->priority_id = $request->priority_id; $ticket->category_id = $request->category_id; $ticket->status_id = Setting::grab('default_status_id'); $ticket->user_id = auth()->user()->id; $ticket->autoSelectAgent(); $ticket->save(); session()->flash('status', trans('ticketit::lang.the-ticket-has-been-created')); return redirect()->action('\Kordy\Ticketit\Controllers\TicketsController@index'); }
php
public function store(Request $request) { $this->validate($request, [ 'subject' => 'required|min:3', 'content' => 'required|min:6', 'priority_id' => 'required|exists:ticketit_priorities,id', 'category_id' => 'required|exists:ticketit_categories,id', ]); $ticket = new Ticket(); $ticket->subject = $request->subject; $ticket->setPurifiedContent($request->get('content')); $ticket->priority_id = $request->priority_id; $ticket->category_id = $request->category_id; $ticket->status_id = Setting::grab('default_status_id'); $ticket->user_id = auth()->user()->id; $ticket->autoSelectAgent(); $ticket->save(); session()->flash('status', trans('ticketit::lang.the-ticket-has-been-created')); return redirect()->action('\Kordy\Ticketit\Controllers\TicketsController@index'); }
[ "public", "function", "store", "(", "Request", "$", "request", ")", "{", "$", "this", "->", "validate", "(", "$", "request", ",", "[", "'subject'", "=>", "'required|min:3'", ",", "'content'", "=>", "'required|min:6'", ",", "'priority_id'", "=>", "'required|exists:ticketit_priorities,id'", ",", "'category_id'", "=>", "'required|exists:ticketit_categories,id'", ",", "]", ")", ";", "$", "ticket", "=", "new", "Ticket", "(", ")", ";", "$", "ticket", "->", "subject", "=", "$", "request", "->", "subject", ";", "$", "ticket", "->", "setPurifiedContent", "(", "$", "request", "->", "get", "(", "'content'", ")", ")", ";", "$", "ticket", "->", "priority_id", "=", "$", "request", "->", "priority_id", ";", "$", "ticket", "->", "category_id", "=", "$", "request", "->", "category_id", ";", "$", "ticket", "->", "status_id", "=", "Setting", "::", "grab", "(", "'default_status_id'", ")", ";", "$", "ticket", "->", "user_id", "=", "auth", "(", ")", "->", "user", "(", ")", "->", "id", ";", "$", "ticket", "->", "autoSelectAgent", "(", ")", ";", "$", "ticket", "->", "save", "(", ")", ";", "session", "(", ")", "->", "flash", "(", "'status'", ",", "trans", "(", "'ticketit::lang.the-ticket-has-been-created'", ")", ")", ";", "return", "redirect", "(", ")", "->", "action", "(", "'\\Kordy\\Ticketit\\Controllers\\TicketsController@index'", ")", ";", "}" ]
Store a newly created ticket and auto assign an agent for it. @param Request $request @return \Illuminate\Http\RedirectResponse
[ "Store", "a", "newly", "created", "ticket", "and", "auto", "assign", "an", "agent", "for", "it", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/TicketsController.php#L206-L233
train
thekordy/ticketit
src/Controllers/TicketsController.php
TicketsController.complete
public function complete($id) { if ($this->permToClose($id) == 'yes') { $ticket = $this->tickets->findOrFail($id); $ticket->completed_at = Carbon::now(); if (Setting::grab('default_close_status_id')) { $ticket->status_id = Setting::grab('default_close_status_id'); } $subject = $ticket->subject; $ticket->save(); session()->flash('status', trans('ticketit::lang.the-ticket-has-been-completed', ['name' => $subject])); return redirect()->route(Setting::grab('main_route').'.index'); } return redirect()->route(Setting::grab('main_route').'.index') ->with('warning', trans('ticketit::lang.you-are-not-permitted-to-do-this')); }
php
public function complete($id) { if ($this->permToClose($id) == 'yes') { $ticket = $this->tickets->findOrFail($id); $ticket->completed_at = Carbon::now(); if (Setting::grab('default_close_status_id')) { $ticket->status_id = Setting::grab('default_close_status_id'); } $subject = $ticket->subject; $ticket->save(); session()->flash('status', trans('ticketit::lang.the-ticket-has-been-completed', ['name' => $subject])); return redirect()->route(Setting::grab('main_route').'.index'); } return redirect()->route(Setting::grab('main_route').'.index') ->with('warning', trans('ticketit::lang.you-are-not-permitted-to-do-this')); }
[ "public", "function", "complete", "(", "$", "id", ")", "{", "if", "(", "$", "this", "->", "permToClose", "(", "$", "id", ")", "==", "'yes'", ")", "{", "$", "ticket", "=", "$", "this", "->", "tickets", "->", "findOrFail", "(", "$", "id", ")", ";", "$", "ticket", "->", "completed_at", "=", "Carbon", "::", "now", "(", ")", ";", "if", "(", "Setting", "::", "grab", "(", "'default_close_status_id'", ")", ")", "{", "$", "ticket", "->", "status_id", "=", "Setting", "::", "grab", "(", "'default_close_status_id'", ")", ";", "}", "$", "subject", "=", "$", "ticket", "->", "subject", ";", "$", "ticket", "->", "save", "(", ")", ";", "session", "(", ")", "->", "flash", "(", "'status'", ",", "trans", "(", "'ticketit::lang.the-ticket-has-been-completed'", ",", "[", "'name'", "=>", "$", "subject", "]", ")", ")", ";", "return", "redirect", "(", ")", "->", "route", "(", "Setting", "::", "grab", "(", "'main_route'", ")", ".", "'.index'", ")", ";", "}", "return", "redirect", "(", ")", "->", "route", "(", "Setting", "::", "grab", "(", "'main_route'", ")", ".", "'.index'", ")", "->", "with", "(", "'warning'", ",", "trans", "(", "'ticketit::lang.you-are-not-permitted-to-do-this'", ")", ")", ";", "}" ]
Mark ticket as complete. @param int $id @return Response
[ "Mark", "ticket", "as", "complete", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/TicketsController.php#L332-L352
train
thekordy/ticketit
src/Controllers/TicketsController.php
TicketsController.reopen
public function reopen($id) { if ($this->permToReopen($id) == 'yes') { $ticket = $this->tickets->findOrFail($id); $ticket->completed_at = null; if (Setting::grab('default_reopen_status_id')) { $ticket->status_id = Setting::grab('default_reopen_status_id'); } $subject = $ticket->subject; $ticket->save(); session()->flash('status', trans('ticketit::lang.the-ticket-has-been-reopened', ['name' => $subject])); return redirect()->route(Setting::grab('main_route').'.index'); } return redirect()->route(Setting::grab('main_route').'.index') ->with('warning', trans('ticketit::lang.you-are-not-permitted-to-do-this')); }
php
public function reopen($id) { if ($this->permToReopen($id) == 'yes') { $ticket = $this->tickets->findOrFail($id); $ticket->completed_at = null; if (Setting::grab('default_reopen_status_id')) { $ticket->status_id = Setting::grab('default_reopen_status_id'); } $subject = $ticket->subject; $ticket->save(); session()->flash('status', trans('ticketit::lang.the-ticket-has-been-reopened', ['name' => $subject])); return redirect()->route(Setting::grab('main_route').'.index'); } return redirect()->route(Setting::grab('main_route').'.index') ->with('warning', trans('ticketit::lang.you-are-not-permitted-to-do-this')); }
[ "public", "function", "reopen", "(", "$", "id", ")", "{", "if", "(", "$", "this", "->", "permToReopen", "(", "$", "id", ")", "==", "'yes'", ")", "{", "$", "ticket", "=", "$", "this", "->", "tickets", "->", "findOrFail", "(", "$", "id", ")", ";", "$", "ticket", "->", "completed_at", "=", "null", ";", "if", "(", "Setting", "::", "grab", "(", "'default_reopen_status_id'", ")", ")", "{", "$", "ticket", "->", "status_id", "=", "Setting", "::", "grab", "(", "'default_reopen_status_id'", ")", ";", "}", "$", "subject", "=", "$", "ticket", "->", "subject", ";", "$", "ticket", "->", "save", "(", ")", ";", "session", "(", ")", "->", "flash", "(", "'status'", ",", "trans", "(", "'ticketit::lang.the-ticket-has-been-reopened'", ",", "[", "'name'", "=>", "$", "subject", "]", ")", ")", ";", "return", "redirect", "(", ")", "->", "route", "(", "Setting", "::", "grab", "(", "'main_route'", ")", ".", "'.index'", ")", ";", "}", "return", "redirect", "(", ")", "->", "route", "(", "Setting", "::", "grab", "(", "'main_route'", ")", ".", "'.index'", ")", "->", "with", "(", "'warning'", ",", "trans", "(", "'ticketit::lang.you-are-not-permitted-to-do-this'", ")", ")", ";", "}" ]
Reopen ticket from complete status. @param int $id @return Response
[ "Reopen", "ticket", "from", "complete", "status", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/TicketsController.php#L361-L381
train
thekordy/ticketit
src/Controllers/TicketsController.php
TicketsController.monthlyPerfomance
public function monthlyPerfomance($period = 2) { $categories = Category::all(); foreach ($categories as $cat) { $records['categories'][] = $cat->name; } for ($m = $period; $m >= 0; $m--) { $from = Carbon::now(); $from->day = 1; $from->subMonth($m); $to = Carbon::now(); $to->day = 1; $to->subMonth($m); $to->endOfMonth(); $records['interval'][$from->format('F Y')] = []; foreach ($categories as $cat) { $records['interval'][$from->format('F Y')][] = round($this->intervalPerformance($from, $to, $cat->id), 1); } } return $records; }
php
public function monthlyPerfomance($period = 2) { $categories = Category::all(); foreach ($categories as $cat) { $records['categories'][] = $cat->name; } for ($m = $period; $m >= 0; $m--) { $from = Carbon::now(); $from->day = 1; $from->subMonth($m); $to = Carbon::now(); $to->day = 1; $to->subMonth($m); $to->endOfMonth(); $records['interval'][$from->format('F Y')] = []; foreach ($categories as $cat) { $records['interval'][$from->format('F Y')][] = round($this->intervalPerformance($from, $to, $cat->id), 1); } } return $records; }
[ "public", "function", "monthlyPerfomance", "(", "$", "period", "=", "2", ")", "{", "$", "categories", "=", "Category", "::", "all", "(", ")", ";", "foreach", "(", "$", "categories", "as", "$", "cat", ")", "{", "$", "records", "[", "'categories'", "]", "[", "]", "=", "$", "cat", "->", "name", ";", "}", "for", "(", "$", "m", "=", "$", "period", ";", "$", "m", ">=", "0", ";", "$", "m", "--", ")", "{", "$", "from", "=", "Carbon", "::", "now", "(", ")", ";", "$", "from", "->", "day", "=", "1", ";", "$", "from", "->", "subMonth", "(", "$", "m", ")", ";", "$", "to", "=", "Carbon", "::", "now", "(", ")", ";", "$", "to", "->", "day", "=", "1", ";", "$", "to", "->", "subMonth", "(", "$", "m", ")", ";", "$", "to", "->", "endOfMonth", "(", ")", ";", "$", "records", "[", "'interval'", "]", "[", "$", "from", "->", "format", "(", "'F Y'", ")", "]", "=", "[", "]", ";", "foreach", "(", "$", "categories", "as", "$", "cat", ")", "{", "$", "records", "[", "'interval'", "]", "[", "$", "from", "->", "format", "(", "'F Y'", ")", "]", "[", "]", "=", "round", "(", "$", "this", "->", "intervalPerformance", "(", "$", "from", ",", "$", "to", ",", "$", "cat", "->", "id", ")", ",", "1", ")", ";", "}", "}", "return", "$", "records", ";", "}" ]
Calculate average closing period of days per category for number of months. @param int $period @return \Illuminate\Database\Eloquent\Collection|static[]
[ "Calculate", "average", "closing", "period", "of", "days", "per", "category", "for", "number", "of", "months", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/TicketsController.php#L451-L473
train
thekordy/ticketit
src/Controllers/TicketsController.php
TicketsController.ticketPerformance
public function ticketPerformance($ticket) { if ($ticket->completed_at == null) { return false; } $created = new Carbon($ticket->created_at); $completed = new Carbon($ticket->completed_at); $length = $created->diff($completed)->days; return $length; }
php
public function ticketPerformance($ticket) { if ($ticket->completed_at == null) { return false; } $created = new Carbon($ticket->created_at); $completed = new Carbon($ticket->completed_at); $length = $created->diff($completed)->days; return $length; }
[ "public", "function", "ticketPerformance", "(", "$", "ticket", ")", "{", "if", "(", "$", "ticket", "->", "completed_at", "==", "null", ")", "{", "return", "false", ";", "}", "$", "created", "=", "new", "Carbon", "(", "$", "ticket", "->", "created_at", ")", ";", "$", "completed", "=", "new", "Carbon", "(", "$", "ticket", "->", "completed_at", ")", ";", "$", "length", "=", "$", "created", "->", "diff", "(", "$", "completed", ")", "->", "days", ";", "return", "$", "length", ";", "}" ]
Calculate the date length it took to solve a ticket. @param Ticket $ticket @return int|false
[ "Calculate", "the", "date", "length", "it", "took", "to", "solve", "a", "ticket", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/TicketsController.php#L482-L493
train
thekordy/ticketit
src/Controllers/TicketsController.php
TicketsController.intervalPerformance
public function intervalPerformance($from, $to, $cat_id = false) { if ($cat_id) { $tickets = Ticket::where('category_id', $cat_id)->whereBetween('completed_at', [$from, $to])->get(); } else { $tickets = Ticket::whereBetween('completed_at', [$from, $to])->get(); } if (empty($tickets->first())) { return false; } $performance_count = 0; $counter = 0; foreach ($tickets as $ticket) { $performance_count += $this->ticketPerformance($ticket); $counter++; } $performance_average = $performance_count / $counter; return $performance_average; }
php
public function intervalPerformance($from, $to, $cat_id = false) { if ($cat_id) { $tickets = Ticket::where('category_id', $cat_id)->whereBetween('completed_at', [$from, $to])->get(); } else { $tickets = Ticket::whereBetween('completed_at', [$from, $to])->get(); } if (empty($tickets->first())) { return false; } $performance_count = 0; $counter = 0; foreach ($tickets as $ticket) { $performance_count += $this->ticketPerformance($ticket); $counter++; } $performance_average = $performance_count / $counter; return $performance_average; }
[ "public", "function", "intervalPerformance", "(", "$", "from", ",", "$", "to", ",", "$", "cat_id", "=", "false", ")", "{", "if", "(", "$", "cat_id", ")", "{", "$", "tickets", "=", "Ticket", "::", "where", "(", "'category_id'", ",", "$", "cat_id", ")", "->", "whereBetween", "(", "'completed_at'", ",", "[", "$", "from", ",", "$", "to", "]", ")", "->", "get", "(", ")", ";", "}", "else", "{", "$", "tickets", "=", "Ticket", "::", "whereBetween", "(", "'completed_at'", ",", "[", "$", "from", ",", "$", "to", "]", ")", "->", "get", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "tickets", "->", "first", "(", ")", ")", ")", "{", "return", "false", ";", "}", "$", "performance_count", "=", "0", ";", "$", "counter", "=", "0", ";", "foreach", "(", "$", "tickets", "as", "$", "ticket", ")", "{", "$", "performance_count", "+=", "$", "this", "->", "ticketPerformance", "(", "$", "ticket", ")", ";", "$", "counter", "++", ";", "}", "$", "performance_average", "=", "$", "performance_count", "/", "$", "counter", ";", "return", "$", "performance_average", ";", "}" ]
Calculate the average date length it took to solve tickets within date period. @param $from @param $to @return int
[ "Calculate", "the", "average", "date", "length", "it", "took", "to", "solve", "tickets", "within", "date", "period", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/TicketsController.php#L503-L524
train
thekordy/ticketit
src/Controllers/InstallController.php
InstallController.settingsSeeder
public function settingsSeeder($master = false) { $cli_path = 'config/ticketit.php'; // if seeder run from cli, use the cli path $provider_path = '../config/ticketit.php'; // if seeder run from provider, use the provider path $config_settings = []; $settings_file_path = false; if (File::isFile($cli_path)) { $settings_file_path = $cli_path; } elseif (File::isFile($provider_path)) { $settings_file_path = $provider_path; } if ($settings_file_path) { $config_settings = include $settings_file_path; File::move($settings_file_path, $settings_file_path.'.backup'); } $seeder = new SettingsTableSeeder(); if ($master) { $config_settings['master_template'] = $master; } $seeder->config = $config_settings; $seeder->run(); }
php
public function settingsSeeder($master = false) { $cli_path = 'config/ticketit.php'; // if seeder run from cli, use the cli path $provider_path = '../config/ticketit.php'; // if seeder run from provider, use the provider path $config_settings = []; $settings_file_path = false; if (File::isFile($cli_path)) { $settings_file_path = $cli_path; } elseif (File::isFile($provider_path)) { $settings_file_path = $provider_path; } if ($settings_file_path) { $config_settings = include $settings_file_path; File::move($settings_file_path, $settings_file_path.'.backup'); } $seeder = new SettingsTableSeeder(); if ($master) { $config_settings['master_template'] = $master; } $seeder->config = $config_settings; $seeder->run(); }
[ "public", "function", "settingsSeeder", "(", "$", "master", "=", "false", ")", "{", "$", "cli_path", "=", "'config/ticketit.php'", ";", "// if seeder run from cli, use the cli path", "$", "provider_path", "=", "'../config/ticketit.php'", ";", "// if seeder run from provider, use the provider path", "$", "config_settings", "=", "[", "]", ";", "$", "settings_file_path", "=", "false", ";", "if", "(", "File", "::", "isFile", "(", "$", "cli_path", ")", ")", "{", "$", "settings_file_path", "=", "$", "cli_path", ";", "}", "elseif", "(", "File", "::", "isFile", "(", "$", "provider_path", ")", ")", "{", "$", "settings_file_path", "=", "$", "provider_path", ";", "}", "if", "(", "$", "settings_file_path", ")", "{", "$", "config_settings", "=", "include", "$", "settings_file_path", ";", "File", "::", "move", "(", "$", "settings_file_path", ",", "$", "settings_file_path", ".", "'.backup'", ")", ";", "}", "$", "seeder", "=", "new", "SettingsTableSeeder", "(", ")", ";", "if", "(", "$", "master", ")", "{", "$", "config_settings", "[", "'master_template'", "]", "=", "$", "master", ";", "}", "$", "seeder", "->", "config", "=", "$", "config_settings", ";", "$", "seeder", "->", "run", "(", ")", ";", "}" ]
Run the settings table seeder. @param string $master
[ "Run", "the", "settings", "table", "seeder", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/InstallController.php#L145-L166
train
thekordy/ticketit
src/Controllers/InstallController.php
InstallController.inactiveMigrations
public function inactiveMigrations() { $inactiveMigrations = []; $migration_arr = []; // Package Migrations $tables = $this->migrations_tables; // Application active migrations $migrations = DB::select('select * from '.DB::getTablePrefix().'migrations'); foreach ($migrations as $migration_parent) { // Count active package migrations $migration_arr[] = $migration_parent->migration; } foreach ($tables as $table) { if (!in_array($table, $migration_arr)) { $inactiveMigrations[] = $table; } } return $inactiveMigrations; }
php
public function inactiveMigrations() { $inactiveMigrations = []; $migration_arr = []; // Package Migrations $tables = $this->migrations_tables; // Application active migrations $migrations = DB::select('select * from '.DB::getTablePrefix().'migrations'); foreach ($migrations as $migration_parent) { // Count active package migrations $migration_arr[] = $migration_parent->migration; } foreach ($tables as $table) { if (!in_array($table, $migration_arr)) { $inactiveMigrations[] = $table; } } return $inactiveMigrations; }
[ "public", "function", "inactiveMigrations", "(", ")", "{", "$", "inactiveMigrations", "=", "[", "]", ";", "$", "migration_arr", "=", "[", "]", ";", "// Package Migrations", "$", "tables", "=", "$", "this", "->", "migrations_tables", ";", "// Application active migrations", "$", "migrations", "=", "DB", "::", "select", "(", "'select * from '", ".", "DB", "::", "getTablePrefix", "(", ")", ".", "'migrations'", ")", ";", "foreach", "(", "$", "migrations", "as", "$", "migration_parent", ")", "{", "// Count active package migrations", "$", "migration_arr", "[", "]", "=", "$", "migration_parent", "->", "migration", ";", "}", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "if", "(", "!", "in_array", "(", "$", "table", ",", "$", "migration_arr", ")", ")", "{", "$", "inactiveMigrations", "[", "]", "=", "$", "table", ";", "}", "}", "return", "$", "inactiveMigrations", ";", "}" ]
Get all Ticketit Package migrations that were not migrated. @return array
[ "Get", "all", "Ticketit", "Package", "migrations", "that", "were", "not", "migrated", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/InstallController.php#L211-L233
train
thekordy/ticketit
src/Controllers/InstallController.php
InstallController.inactiveSettings
public function inactiveSettings() { $seeder = new SettingsTableSeeder(); // Package Settings // if Laravel v5.2 or 5.3 if (version_compare(app()->version(), '5.2.0', '>=')) { $installed_settings = DB::table('ticketit_settings')->pluck('value', 'slug'); } else { // if Laravel 5.1 $installed_settings = DB::table('ticketit_settings')->lists('value', 'slug'); } if (!is_array($installed_settings)) { $installed_settings = $installed_settings->toArray(); } // Application active migrations $default_Settings = $seeder->getDefaults(); if (count($installed_settings) == count($default_Settings)) { return false; } $inactive_settings = array_diff_key($default_Settings, $installed_settings); return $inactive_settings; }
php
public function inactiveSettings() { $seeder = new SettingsTableSeeder(); // Package Settings // if Laravel v5.2 or 5.3 if (version_compare(app()->version(), '5.2.0', '>=')) { $installed_settings = DB::table('ticketit_settings')->pluck('value', 'slug'); } else { // if Laravel 5.1 $installed_settings = DB::table('ticketit_settings')->lists('value', 'slug'); } if (!is_array($installed_settings)) { $installed_settings = $installed_settings->toArray(); } // Application active migrations $default_Settings = $seeder->getDefaults(); if (count($installed_settings) == count($default_Settings)) { return false; } $inactive_settings = array_diff_key($default_Settings, $installed_settings); return $inactive_settings; }
[ "public", "function", "inactiveSettings", "(", ")", "{", "$", "seeder", "=", "new", "SettingsTableSeeder", "(", ")", ";", "// Package Settings", "// if Laravel v5.2 or 5.3", "if", "(", "version_compare", "(", "app", "(", ")", "->", "version", "(", ")", ",", "'5.2.0'", ",", "'>='", ")", ")", "{", "$", "installed_settings", "=", "DB", "::", "table", "(", "'ticketit_settings'", ")", "->", "pluck", "(", "'value'", ",", "'slug'", ")", ";", "}", "else", "{", "// if Laravel 5.1", "$", "installed_settings", "=", "DB", "::", "table", "(", "'ticketit_settings'", ")", "->", "lists", "(", "'value'", ",", "'slug'", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "installed_settings", ")", ")", "{", "$", "installed_settings", "=", "$", "installed_settings", "->", "toArray", "(", ")", ";", "}", "// Application active migrations", "$", "default_Settings", "=", "$", "seeder", "->", "getDefaults", "(", ")", ";", "if", "(", "count", "(", "$", "installed_settings", ")", "==", "count", "(", "$", "default_Settings", ")", ")", "{", "return", "false", ";", "}", "$", "inactive_settings", "=", "array_diff_key", "(", "$", "default_Settings", ",", "$", "installed_settings", ")", ";", "return", "$", "inactive_settings", ";", "}" ]
Check if all Ticketit Package settings that were not installed to setting table. @return bool
[ "Check", "if", "all", "Ticketit", "Package", "settings", "that", "were", "not", "installed", "to", "setting", "table", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Controllers/InstallController.php#L240-L266
train
thekordy/ticketit
src/Traits/ContentEllipse.php
ContentEllipse.getShortContent
public function getShortContent($maxlength = 50, $attr = 'content') { $content = $this->{$attr}; if (strlen($content) > $maxlength) { return substr($content, 0, $maxlength).'...'; } return $content; }
php
public function getShortContent($maxlength = 50, $attr = 'content') { $content = $this->{$attr}; if (strlen($content) > $maxlength) { return substr($content, 0, $maxlength).'...'; } return $content; }
[ "public", "function", "getShortContent", "(", "$", "maxlength", "=", "50", ",", "$", "attr", "=", "'content'", ")", "{", "$", "content", "=", "$", "this", "->", "{", "$", "attr", "}", ";", "if", "(", "strlen", "(", "$", "content", ")", ">", "$", "maxlength", ")", "{", "return", "substr", "(", "$", "content", ",", "0", ",", "$", "maxlength", ")", ".", "'...'", ";", "}", "return", "$", "content", ";", "}" ]
Cuts the content of a comment or a ticket content if it's too long. @param int $maxlength @return string
[ "Cuts", "the", "content", "of", "a", "comment", "or", "a", "ticket", "content", "if", "it", "s", "too", "long", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Traits/ContentEllipse.php#L14-L22
train
thekordy/ticketit
src/Traits/Purifiable.php
Purifiable.setPurifiedContent
public function setPurifiedContent($rawHtml) { $this->content = Purifier::clean($rawHtml, ['HTML.Allowed' => '']); $this->html = Purifier::clean($rawHtml, Setting::grab('purifier_config')); return $this; }
php
public function setPurifiedContent($rawHtml) { $this->content = Purifier::clean($rawHtml, ['HTML.Allowed' => '']); $this->html = Purifier::clean($rawHtml, Setting::grab('purifier_config')); return $this; }
[ "public", "function", "setPurifiedContent", "(", "$", "rawHtml", ")", "{", "$", "this", "->", "content", "=", "Purifier", "::", "clean", "(", "$", "rawHtml", ",", "[", "'HTML.Allowed'", "=>", "''", "]", ")", ";", "$", "this", "->", "html", "=", "Purifier", "::", "clean", "(", "$", "rawHtml", ",", "Setting", "::", "grab", "(", "'purifier_config'", ")", ")", ";", "return", "$", "this", ";", "}" ]
Updates the content and html attribute of the given model. @param string $rawHtml @return \Illuminate\Database\Eloquent\Model $this
[ "Updates", "the", "content", "and", "html", "attribute", "of", "the", "given", "model", "." ]
55fc54152a2e9d941e114f8c242b7db209c2a47e
https://github.com/thekordy/ticketit/blob/55fc54152a2e9d941e114f8c242b7db209c2a47e/src/Traits/Purifiable.php#L17-L23
train
FGRibreau/mailchecker
platform/php/MailChecker.php
MailChecker.isBlacklisted
public static function isBlacklisted($email) { $parts = explode("@", $email); $domain = end($parts); foreach (self::allDomainSuffixes($domain) as $domainSuffix) { if (in_array($domainSuffix, self::$blacklist)) { return true; } } return false; }
php
public static function isBlacklisted($email) { $parts = explode("@", $email); $domain = end($parts); foreach (self::allDomainSuffixes($domain) as $domainSuffix) { if (in_array($domainSuffix, self::$blacklist)) { return true; } } return false; }
[ "public", "static", "function", "isBlacklisted", "(", "$", "email", ")", "{", "$", "parts", "=", "explode", "(", "\"@\"", ",", "$", "email", ")", ";", "$", "domain", "=", "end", "(", "$", "parts", ")", ";", "foreach", "(", "self", "::", "allDomainSuffixes", "(", "$", "domain", ")", "as", "$", "domainSuffix", ")", "{", "if", "(", "in_array", "(", "$", "domainSuffix", ",", "self", "::", "$", "blacklist", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check if an email is blacklisted or not @param String $email @return boolean true if $email is blacklisted
[ "Check", "if", "an", "email", "is", "blacklisted", "or", "not" ]
1b566c5aee7e9d862bb31a1e7f3cb343a7a1a0c1
https://github.com/FGRibreau/mailchecker/blob/1b566c5aee7e9d862bb31a1e7f3cb343a7a1a0c1/platform/php/MailChecker.php#L39-L50
train
gumlet/php-image-resize
lib/ImageResize.php
ImageResize.createFromString
public static function createFromString($image_data) { if (empty($image_data) || $image_data === null) { throw new ImageResizeException('image_data must not be empty'); } $resize = new self('data://application/octet-stream;base64,' . base64_encode($image_data)); return $resize; }
php
public static function createFromString($image_data) { if (empty($image_data) || $image_data === null) { throw new ImageResizeException('image_data must not be empty'); } $resize = new self('data://application/octet-stream;base64,' . base64_encode($image_data)); return $resize; }
[ "public", "static", "function", "createFromString", "(", "$", "image_data", ")", "{", "if", "(", "empty", "(", "$", "image_data", ")", "||", "$", "image_data", "===", "null", ")", "{", "throw", "new", "ImageResizeException", "(", "'image_data must not be empty'", ")", ";", "}", "$", "resize", "=", "new", "self", "(", "'data://application/octet-stream;base64,'", ".", "base64_encode", "(", "$", "image_data", ")", ")", ";", "return", "$", "resize", ";", "}" ]
Create instance from a strng @param string $image_data @return ImageResize @throws ImageResizeException
[ "Create", "instance", "from", "a", "strng" ]
c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765
https://github.com/gumlet/php-image-resize/blob/c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765/lib/ImageResize.php#L61-L68
train
gumlet/php-image-resize
lib/ImageResize.php
ImageResize.output
public function output($image_type = null, $quality = null) { $image_type = $image_type ?: $this->source_type; header('Content-Type: ' . image_type_to_mime_type($image_type)); $this->save(null, $image_type, $quality); }
php
public function output($image_type = null, $quality = null) { $image_type = $image_type ?: $this->source_type; header('Content-Type: ' . image_type_to_mime_type($image_type)); $this->save(null, $image_type, $quality); }
[ "public", "function", "output", "(", "$", "image_type", "=", "null", ",", "$", "quality", "=", "null", ")", "{", "$", "image_type", "=", "$", "image_type", "?", ":", "$", "this", "->", "source_type", ";", "header", "(", "'Content-Type: '", ".", "image_type_to_mime_type", "(", "$", "image_type", ")", ")", ";", "$", "this", "->", "save", "(", "null", ",", "$", "image_type", ",", "$", "quality", ")", ";", "}" ]
Outputs image to browser @param string $image_type @param integer $quality
[ "Outputs", "image", "to", "browser" ]
c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765
https://github.com/gumlet/php-image-resize/blob/c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765/lib/ImageResize.php#L401-L408
train
gumlet/php-image-resize
lib/ImageResize.php
ImageResize.resizeToBestFit
public function resizeToBestFit($max_width, $max_height, $allow_enlarge = false) { if ($this->getSourceWidth() <= $max_width && $this->getSourceHeight() <= $max_height && $allow_enlarge === false) { return $this; } $ratio = $this->getSourceHeight() / $this->getSourceWidth(); $width = $max_width; $height = $width * $ratio; if ($height > $max_height) { $height = $max_height; $width = $height / $ratio; } return $this->resize($width, $height, $allow_enlarge); }
php
public function resizeToBestFit($max_width, $max_height, $allow_enlarge = false) { if ($this->getSourceWidth() <= $max_width && $this->getSourceHeight() <= $max_height && $allow_enlarge === false) { return $this; } $ratio = $this->getSourceHeight() / $this->getSourceWidth(); $width = $max_width; $height = $width * $ratio; if ($height > $max_height) { $height = $max_height; $width = $height / $ratio; } return $this->resize($width, $height, $allow_enlarge); }
[ "public", "function", "resizeToBestFit", "(", "$", "max_width", ",", "$", "max_height", ",", "$", "allow_enlarge", "=", "false", ")", "{", "if", "(", "$", "this", "->", "getSourceWidth", "(", ")", "<=", "$", "max_width", "&&", "$", "this", "->", "getSourceHeight", "(", ")", "<=", "$", "max_height", "&&", "$", "allow_enlarge", "===", "false", ")", "{", "return", "$", "this", ";", "}", "$", "ratio", "=", "$", "this", "->", "getSourceHeight", "(", ")", "/", "$", "this", "->", "getSourceWidth", "(", ")", ";", "$", "width", "=", "$", "max_width", ";", "$", "height", "=", "$", "width", "*", "$", "ratio", ";", "if", "(", "$", "height", ">", "$", "max_height", ")", "{", "$", "height", "=", "$", "max_height", ";", "$", "width", "=", "$", "height", "/", "$", "ratio", ";", "}", "return", "$", "this", "->", "resize", "(", "$", "width", ",", "$", "height", ",", "$", "allow_enlarge", ")", ";", "}" ]
Resizes image to best fit inside the given dimensions @param integer $max_width @param integer $max_height @param boolean $allow_enlarge @return static
[ "Resizes", "image", "to", "best", "fit", "inside", "the", "given", "dimensions" ]
c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765
https://github.com/gumlet/php-image-resize/blob/c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765/lib/ImageResize.php#L500-L516
train
gumlet/php-image-resize
lib/ImageResize.php
ImageResize.resize
public function resize($width, $height, $allow_enlarge = false) { if (!$allow_enlarge) { // if the user hasn't explicitly allowed enlarging, // but either of the dimensions are larger then the original, // then just use original dimensions - this logic may need rethinking if ($width > $this->getSourceWidth() || $height > $this->getSourceHeight()) { $width = $this->getSourceWidth(); $height = $this->getSourceHeight(); } } $this->source_x = 0; $this->source_y = 0; $this->dest_w = $width; $this->dest_h = $height; $this->source_w = $this->getSourceWidth(); $this->source_h = $this->getSourceHeight(); return $this; }
php
public function resize($width, $height, $allow_enlarge = false) { if (!$allow_enlarge) { // if the user hasn't explicitly allowed enlarging, // but either of the dimensions are larger then the original, // then just use original dimensions - this logic may need rethinking if ($width > $this->getSourceWidth() || $height > $this->getSourceHeight()) { $width = $this->getSourceWidth(); $height = $this->getSourceHeight(); } } $this->source_x = 0; $this->source_y = 0; $this->dest_w = $width; $this->dest_h = $height; $this->source_w = $this->getSourceWidth(); $this->source_h = $this->getSourceHeight(); return $this; }
[ "public", "function", "resize", "(", "$", "width", ",", "$", "height", ",", "$", "allow_enlarge", "=", "false", ")", "{", "if", "(", "!", "$", "allow_enlarge", ")", "{", "// if the user hasn't explicitly allowed enlarging,", "// but either of the dimensions are larger then the original,", "// then just use original dimensions - this logic may need rethinking", "if", "(", "$", "width", ">", "$", "this", "->", "getSourceWidth", "(", ")", "||", "$", "height", ">", "$", "this", "->", "getSourceHeight", "(", ")", ")", "{", "$", "width", "=", "$", "this", "->", "getSourceWidth", "(", ")", ";", "$", "height", "=", "$", "this", "->", "getSourceHeight", "(", ")", ";", "}", "}", "$", "this", "->", "source_x", "=", "0", ";", "$", "this", "->", "source_y", "=", "0", ";", "$", "this", "->", "dest_w", "=", "$", "width", ";", "$", "this", "->", "dest_h", "=", "$", "height", ";", "$", "this", "->", "source_w", "=", "$", "this", "->", "getSourceWidth", "(", ")", ";", "$", "this", "->", "source_h", "=", "$", "this", "->", "getSourceHeight", "(", ")", ";", "return", "$", "this", ";", "}" ]
Resizes image according to the given width and height @param integer $width @param integer $height @param boolean $allow_enlarge @return static
[ "Resizes", "image", "according", "to", "the", "given", "width", "and", "height" ]
c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765
https://github.com/gumlet/php-image-resize/blob/c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765/lib/ImageResize.php#L542-L565
train
gumlet/php-image-resize
lib/ImageResize.php
ImageResize.crop
public function crop($width, $height, $allow_enlarge = false, $position = self::CROPCENTER) { if (!$allow_enlarge) { // this logic is slightly different to resize(), // it will only reset dimensions to the original // if that particular dimenstion is larger if ($width > $this->getSourceWidth()) { $width = $this->getSourceWidth(); } if ($height > $this->getSourceHeight()) { $height = $this->getSourceHeight(); } } $ratio_source = $this->getSourceWidth() / $this->getSourceHeight(); $ratio_dest = $width / $height; if ($ratio_dest < $ratio_source) { $this->resizeToHeight($height, $allow_enlarge); $excess_width = ($this->getDestWidth() - $width) / $this->getDestWidth() * $this->getSourceWidth(); $this->source_w = $this->getSourceWidth() - $excess_width; $this->source_x = $this->getCropPosition($excess_width, $position); $this->dest_w = $width; } else { $this->resizeToWidth($width, $allow_enlarge); $excess_height = ($this->getDestHeight() - $height) / $this->getDestHeight() * $this->getSourceHeight(); $this->source_h = $this->getSourceHeight() - $excess_height; $this->source_y = $this->getCropPosition($excess_height, $position); $this->dest_h = $height; } return $this; }
php
public function crop($width, $height, $allow_enlarge = false, $position = self::CROPCENTER) { if (!$allow_enlarge) { // this logic is slightly different to resize(), // it will only reset dimensions to the original // if that particular dimenstion is larger if ($width > $this->getSourceWidth()) { $width = $this->getSourceWidth(); } if ($height > $this->getSourceHeight()) { $height = $this->getSourceHeight(); } } $ratio_source = $this->getSourceWidth() / $this->getSourceHeight(); $ratio_dest = $width / $height; if ($ratio_dest < $ratio_source) { $this->resizeToHeight($height, $allow_enlarge); $excess_width = ($this->getDestWidth() - $width) / $this->getDestWidth() * $this->getSourceWidth(); $this->source_w = $this->getSourceWidth() - $excess_width; $this->source_x = $this->getCropPosition($excess_width, $position); $this->dest_w = $width; } else { $this->resizeToWidth($width, $allow_enlarge); $excess_height = ($this->getDestHeight() - $height) / $this->getDestHeight() * $this->getSourceHeight(); $this->source_h = $this->getSourceHeight() - $excess_height; $this->source_y = $this->getCropPosition($excess_height, $position); $this->dest_h = $height; } return $this; }
[ "public", "function", "crop", "(", "$", "width", ",", "$", "height", ",", "$", "allow_enlarge", "=", "false", ",", "$", "position", "=", "self", "::", "CROPCENTER", ")", "{", "if", "(", "!", "$", "allow_enlarge", ")", "{", "// this logic is slightly different to resize(),", "// it will only reset dimensions to the original", "// if that particular dimenstion is larger", "if", "(", "$", "width", ">", "$", "this", "->", "getSourceWidth", "(", ")", ")", "{", "$", "width", "=", "$", "this", "->", "getSourceWidth", "(", ")", ";", "}", "if", "(", "$", "height", ">", "$", "this", "->", "getSourceHeight", "(", ")", ")", "{", "$", "height", "=", "$", "this", "->", "getSourceHeight", "(", ")", ";", "}", "}", "$", "ratio_source", "=", "$", "this", "->", "getSourceWidth", "(", ")", "/", "$", "this", "->", "getSourceHeight", "(", ")", ";", "$", "ratio_dest", "=", "$", "width", "/", "$", "height", ";", "if", "(", "$", "ratio_dest", "<", "$", "ratio_source", ")", "{", "$", "this", "->", "resizeToHeight", "(", "$", "height", ",", "$", "allow_enlarge", ")", ";", "$", "excess_width", "=", "(", "$", "this", "->", "getDestWidth", "(", ")", "-", "$", "width", ")", "/", "$", "this", "->", "getDestWidth", "(", ")", "*", "$", "this", "->", "getSourceWidth", "(", ")", ";", "$", "this", "->", "source_w", "=", "$", "this", "->", "getSourceWidth", "(", ")", "-", "$", "excess_width", ";", "$", "this", "->", "source_x", "=", "$", "this", "->", "getCropPosition", "(", "$", "excess_width", ",", "$", "position", ")", ";", "$", "this", "->", "dest_w", "=", "$", "width", ";", "}", "else", "{", "$", "this", "->", "resizeToWidth", "(", "$", "width", ",", "$", "allow_enlarge", ")", ";", "$", "excess_height", "=", "(", "$", "this", "->", "getDestHeight", "(", ")", "-", "$", "height", ")", "/", "$", "this", "->", "getDestHeight", "(", ")", "*", "$", "this", "->", "getSourceHeight", "(", ")", ";", "$", "this", "->", "source_h", "=", "$", "this", "->", "getSourceHeight", "(", ")", "-", "$", "excess_height", ";", "$", "this", "->", "source_y", "=", "$", "this", "->", "getCropPosition", "(", "$", "excess_height", ",", "$", "position", ")", ";", "$", "this", "->", "dest_h", "=", "$", "height", ";", "}", "return", "$", "this", ";", "}" ]
Crops image according to the given width, height and crop position @param integer $width @param integer $height @param boolean $allow_enlarge @param integer $position @return static
[ "Crops", "image", "according", "to", "the", "given", "width", "height", "and", "crop", "position" ]
c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765
https://github.com/gumlet/php-image-resize/blob/c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765/lib/ImageResize.php#L576-L616
train
gumlet/php-image-resize
lib/ImageResize.php
ImageResize.freecrop
public function freecrop($width, $height, $x = false, $y = false) { if ($x === false || $y === false) { return $this->crop($width, $height); } $this->source_x = $x; $this->source_y = $y; if ($width > $this->getSourceWidth() - $x) { $this->source_w = $this->getSourceWidth() - $x; } else { $this->source_w = $width; } if ($height > $this->getSourceHeight() - $y) { $this->source_h = $this->getSourceHeight() - $y; } else { $this->source_h = $height; } $this->dest_w = $width; $this->dest_h = $height; return $this; }
php
public function freecrop($width, $height, $x = false, $y = false) { if ($x === false || $y === false) { return $this->crop($width, $height); } $this->source_x = $x; $this->source_y = $y; if ($width > $this->getSourceWidth() - $x) { $this->source_w = $this->getSourceWidth() - $x; } else { $this->source_w = $width; } if ($height > $this->getSourceHeight() - $y) { $this->source_h = $this->getSourceHeight() - $y; } else { $this->source_h = $height; } $this->dest_w = $width; $this->dest_h = $height; return $this; }
[ "public", "function", "freecrop", "(", "$", "width", ",", "$", "height", ",", "$", "x", "=", "false", ",", "$", "y", "=", "false", ")", "{", "if", "(", "$", "x", "===", "false", "||", "$", "y", "===", "false", ")", "{", "return", "$", "this", "->", "crop", "(", "$", "width", ",", "$", "height", ")", ";", "}", "$", "this", "->", "source_x", "=", "$", "x", ";", "$", "this", "->", "source_y", "=", "$", "y", ";", "if", "(", "$", "width", ">", "$", "this", "->", "getSourceWidth", "(", ")", "-", "$", "x", ")", "{", "$", "this", "->", "source_w", "=", "$", "this", "->", "getSourceWidth", "(", ")", "-", "$", "x", ";", "}", "else", "{", "$", "this", "->", "source_w", "=", "$", "width", ";", "}", "if", "(", "$", "height", ">", "$", "this", "->", "getSourceHeight", "(", ")", "-", "$", "y", ")", "{", "$", "this", "->", "source_h", "=", "$", "this", "->", "getSourceHeight", "(", ")", "-", "$", "y", ";", "}", "else", "{", "$", "this", "->", "source_h", "=", "$", "height", ";", "}", "$", "this", "->", "dest_w", "=", "$", "width", ";", "$", "this", "->", "dest_h", "=", "$", "height", ";", "return", "$", "this", ";", "}" ]
Crops image according to the given width, height, x and y @param integer $width @param integer $height @param integer $x @param integer $y @return static
[ "Crops", "image", "according", "to", "the", "given", "width", "height", "x", "and", "y" ]
c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765
https://github.com/gumlet/php-image-resize/blob/c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765/lib/ImageResize.php#L627-L650
train
gumlet/php-image-resize
lib/ImageResize.php
ImageResize.imageFlip
public function imageFlip($image, $mode) { switch($mode) { case self::IMG_FLIP_HORIZONTAL: { $max_x = imagesx($image) - 1; $half_x = $max_x / 2; $sy = imagesy($image); $temp_image = imageistruecolor($image)? imagecreatetruecolor(1, $sy): imagecreate(1, $sy); for ($x = 0; $x < $half_x; ++$x) { imagecopy($temp_image, $image, 0, 0, $x, 0, 1, $sy); imagecopy($image, $image, $x, 0, $max_x - $x, 0, 1, $sy); imagecopy($image, $temp_image, $max_x - $x, 0, 0, 0, 1, $sy); } break; } case self::IMG_FLIP_VERTICAL: { $sx = imagesx($image); $max_y = imagesy($image) - 1; $half_y = $max_y / 2; $temp_image = imageistruecolor($image)? imagecreatetruecolor($sx, 1): imagecreate($sx, 1); for ($y = 0; $y < $half_y; ++$y) { imagecopy($temp_image, $image, 0, 0, 0, $y, $sx, 1); imagecopy($image, $image, 0, $y, 0, $max_y - $y, $sx, 1); imagecopy($image, $temp_image, 0, $max_y - $y, 0, 0, $sx, 1); } break; } case self::IMG_FLIP_BOTH: { $sx = imagesx($image); $sy = imagesy($image); $temp_image = imagerotate($image, 180, 0); imagecopy($image, $temp_image, 0, 0, 0, 0, $sx, $sy); break; } default: return null; } imagedestroy($temp_image); }
php
public function imageFlip($image, $mode) { switch($mode) { case self::IMG_FLIP_HORIZONTAL: { $max_x = imagesx($image) - 1; $half_x = $max_x / 2; $sy = imagesy($image); $temp_image = imageistruecolor($image)? imagecreatetruecolor(1, $sy): imagecreate(1, $sy); for ($x = 0; $x < $half_x; ++$x) { imagecopy($temp_image, $image, 0, 0, $x, 0, 1, $sy); imagecopy($image, $image, $x, 0, $max_x - $x, 0, 1, $sy); imagecopy($image, $temp_image, $max_x - $x, 0, 0, 0, 1, $sy); } break; } case self::IMG_FLIP_VERTICAL: { $sx = imagesx($image); $max_y = imagesy($image) - 1; $half_y = $max_y / 2; $temp_image = imageistruecolor($image)? imagecreatetruecolor($sx, 1): imagecreate($sx, 1); for ($y = 0; $y < $half_y; ++$y) { imagecopy($temp_image, $image, 0, 0, 0, $y, $sx, 1); imagecopy($image, $image, 0, $y, 0, $max_y - $y, $sx, 1); imagecopy($image, $temp_image, 0, $max_y - $y, 0, 0, $sx, 1); } break; } case self::IMG_FLIP_BOTH: { $sx = imagesx($image); $sy = imagesy($image); $temp_image = imagerotate($image, 180, 0); imagecopy($image, $temp_image, 0, 0, 0, 0, $sx, $sy); break; } default: return null; } imagedestroy($temp_image); }
[ "public", "function", "imageFlip", "(", "$", "image", ",", "$", "mode", ")", "{", "switch", "(", "$", "mode", ")", "{", "case", "self", "::", "IMG_FLIP_HORIZONTAL", ":", "{", "$", "max_x", "=", "imagesx", "(", "$", "image", ")", "-", "1", ";", "$", "half_x", "=", "$", "max_x", "/", "2", ";", "$", "sy", "=", "imagesy", "(", "$", "image", ")", ";", "$", "temp_image", "=", "imageistruecolor", "(", "$", "image", ")", "?", "imagecreatetruecolor", "(", "1", ",", "$", "sy", ")", ":", "imagecreate", "(", "1", ",", "$", "sy", ")", ";", "for", "(", "$", "x", "=", "0", ";", "$", "x", "<", "$", "half_x", ";", "++", "$", "x", ")", "{", "imagecopy", "(", "$", "temp_image", ",", "$", "image", ",", "0", ",", "0", ",", "$", "x", ",", "0", ",", "1", ",", "$", "sy", ")", ";", "imagecopy", "(", "$", "image", ",", "$", "image", ",", "$", "x", ",", "0", ",", "$", "max_x", "-", "$", "x", ",", "0", ",", "1", ",", "$", "sy", ")", ";", "imagecopy", "(", "$", "image", ",", "$", "temp_image", ",", "$", "max_x", "-", "$", "x", ",", "0", ",", "0", ",", "0", ",", "1", ",", "$", "sy", ")", ";", "}", "break", ";", "}", "case", "self", "::", "IMG_FLIP_VERTICAL", ":", "{", "$", "sx", "=", "imagesx", "(", "$", "image", ")", ";", "$", "max_y", "=", "imagesy", "(", "$", "image", ")", "-", "1", ";", "$", "half_y", "=", "$", "max_y", "/", "2", ";", "$", "temp_image", "=", "imageistruecolor", "(", "$", "image", ")", "?", "imagecreatetruecolor", "(", "$", "sx", ",", "1", ")", ":", "imagecreate", "(", "$", "sx", ",", "1", ")", ";", "for", "(", "$", "y", "=", "0", ";", "$", "y", "<", "$", "half_y", ";", "++", "$", "y", ")", "{", "imagecopy", "(", "$", "temp_image", ",", "$", "image", ",", "0", ",", "0", ",", "0", ",", "$", "y", ",", "$", "sx", ",", "1", ")", ";", "imagecopy", "(", "$", "image", ",", "$", "image", ",", "0", ",", "$", "y", ",", "0", ",", "$", "max_y", "-", "$", "y", ",", "$", "sx", ",", "1", ")", ";", "imagecopy", "(", "$", "image", ",", "$", "temp_image", ",", "0", ",", "$", "max_y", "-", "$", "y", ",", "0", ",", "0", ",", "$", "sx", ",", "1", ")", ";", "}", "break", ";", "}", "case", "self", "::", "IMG_FLIP_BOTH", ":", "{", "$", "sx", "=", "imagesx", "(", "$", "image", ")", ";", "$", "sy", "=", "imagesy", "(", "$", "image", ")", ";", "$", "temp_image", "=", "imagerotate", "(", "$", "image", ",", "180", ",", "0", ")", ";", "imagecopy", "(", "$", "image", ",", "$", "temp_image", ",", "0", ",", "0", ",", "0", ",", "0", ",", "$", "sx", ",", "$", "sy", ")", ";", "break", ";", "}", "default", ":", "return", "null", ";", "}", "imagedestroy", "(", "$", "temp_image", ")", ";", "}" ]
Flips an image using a given mode if PHP version is lower than 5.5 @param resource $image @param integer $mode @return null
[ "Flips", "an", "image", "using", "a", "given", "mode", "if", "PHP", "version", "is", "lower", "than", "5", ".", "5" ]
c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765
https://github.com/gumlet/php-image-resize/blob/c71fe1c9bcfc22b0ce0f9d3b0ea460daf821f765/lib/ImageResize.php#L724-L762
train
delight-im/PHP-Auth
src/Auth.php
Auth.register
public function register($email, $password, $username = null, callable $callback = null) { $this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75); $this->throttle([ 'createNewAccount', $this->getIpAddress() ], 1, (60 * 60 * 12), 5, true); $newUserId = $this->createUserInternal(false, $email, $password, $username, $callback); $this->throttle([ 'createNewAccount', $this->getIpAddress() ], 1, (60 * 60 * 12), 5, false); return $newUserId; }
php
public function register($email, $password, $username = null, callable $callback = null) { $this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75); $this->throttle([ 'createNewAccount', $this->getIpAddress() ], 1, (60 * 60 * 12), 5, true); $newUserId = $this->createUserInternal(false, $email, $password, $username, $callback); $this->throttle([ 'createNewAccount', $this->getIpAddress() ], 1, (60 * 60 * 12), 5, false); return $newUserId; }
[ "public", "function", "register", "(", "$", "email", ",", "$", "password", ",", "$", "username", "=", "null", ",", "callable", "$", "callback", "=", "null", ")", "{", "$", "this", "->", "throttle", "(", "[", "'enumerateUsers'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "1", ",", "(", "60", "*", "60", ")", ",", "75", ")", ";", "$", "this", "->", "throttle", "(", "[", "'createNewAccount'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "1", ",", "(", "60", "*", "60", "*", "12", ")", ",", "5", ",", "true", ")", ";", "$", "newUserId", "=", "$", "this", "->", "createUserInternal", "(", "false", ",", "$", "email", ",", "$", "password", ",", "$", "username", ",", "$", "callback", ")", ";", "$", "this", "->", "throttle", "(", "[", "'createNewAccount'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "1", ",", "(", "60", "*", "60", "*", "12", ")", ",", "5", ",", "false", ")", ";", "return", "$", "newUserId", ";", "}" ]
Attempts to sign up a user If you want the user's account to be activated by default, pass `null` as the callback If you want to make the user verify their email address first, pass an anonymous function as the callback The callback function must have the following signature: `function ($selector, $token)` Both pieces of information must be sent to the user, usually embedded in a link When the user wants to verify their email address as a next step, both pieces will be required again @param string $email the email address to register @param string $password the password for the new account @param string|null $username (optional) the username that will be displayed @param callable|null $callback (optional) the function that sends the confirmation email to the user @return int the ID of the user that has been created (if any) @throws InvalidEmailException if the email address was invalid @throws InvalidPasswordException if the password was invalid @throws UserAlreadyExistsException if a user with the specified email address already exists @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded @throws AuthError if an internal problem occurred (do *not* catch) @see confirmEmail @see confirmEmailAndSignIn
[ "Attempts", "to", "sign", "up", "a", "user" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L230-L239
train
delight-im/PHP-Auth
src/Auth.php
Auth.login
public function login($email, $password, $rememberDuration = null, callable $onBeforeSuccess = null) { $this->throttle([ 'attemptToLogin', 'email', $email ], 500, (60 * 60 * 24), null, true); $this->authenticateUserInternal($password, $email, null, $rememberDuration, $onBeforeSuccess); }
php
public function login($email, $password, $rememberDuration = null, callable $onBeforeSuccess = null) { $this->throttle([ 'attemptToLogin', 'email', $email ], 500, (60 * 60 * 24), null, true); $this->authenticateUserInternal($password, $email, null, $rememberDuration, $onBeforeSuccess); }
[ "public", "function", "login", "(", "$", "email", ",", "$", "password", ",", "$", "rememberDuration", "=", "null", ",", "callable", "$", "onBeforeSuccess", "=", "null", ")", "{", "$", "this", "->", "throttle", "(", "[", "'attemptToLogin'", ",", "'email'", ",", "$", "email", "]", ",", "500", ",", "(", "60", "*", "60", "*", "24", ")", ",", "null", ",", "true", ")", ";", "$", "this", "->", "authenticateUserInternal", "(", "$", "password", ",", "$", "email", ",", "null", ",", "$", "rememberDuration", ",", "$", "onBeforeSuccess", ")", ";", "}" ]
Attempts to sign in a user with their email address and password @param string $email the user's email address @param string $password the user's password @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year @param callable|null $onBeforeSuccess (optional) a function that receives the user's ID as its single parameter and is executed before successful authentication; must return `true` to proceed or `false` to cancel @throws InvalidEmailException if the email address was invalid or could not be found @throws InvalidPasswordException if the password was invalid @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email @throws AttemptCancelledException if the attempt has been cancelled by the supplied callback that is executed before success @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded @throws AuthError if an internal problem occurred (do *not* catch)
[ "Attempts", "to", "sign", "in", "a", "user", "with", "their", "email", "address", "and", "password" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L296-L300
train
delight-im/PHP-Auth
src/Auth.php
Auth.loginWithUsername
public function loginWithUsername($username, $password, $rememberDuration = null, callable $onBeforeSuccess = null) { $this->throttle([ 'attemptToLogin', 'username', $username ], 500, (60 * 60 * 24), null, true); $this->authenticateUserInternal($password, null, $username, $rememberDuration, $onBeforeSuccess); }
php
public function loginWithUsername($username, $password, $rememberDuration = null, callable $onBeforeSuccess = null) { $this->throttle([ 'attemptToLogin', 'username', $username ], 500, (60 * 60 * 24), null, true); $this->authenticateUserInternal($password, null, $username, $rememberDuration, $onBeforeSuccess); }
[ "public", "function", "loginWithUsername", "(", "$", "username", ",", "$", "password", ",", "$", "rememberDuration", "=", "null", ",", "callable", "$", "onBeforeSuccess", "=", "null", ")", "{", "$", "this", "->", "throttle", "(", "[", "'attemptToLogin'", ",", "'username'", ",", "$", "username", "]", ",", "500", ",", "(", "60", "*", "60", "*", "24", ")", ",", "null", ",", "true", ")", ";", "$", "this", "->", "authenticateUserInternal", "(", "$", "password", ",", "null", ",", "$", "username", ",", "$", "rememberDuration", ",", "$", "onBeforeSuccess", ")", ";", "}" ]
Attempts to sign in a user with their username and password When using this method to authenticate users, you should ensure that usernames are unique Consistently using {@see registerWithUniqueUsername} instead of {@see register} can be helpful @param string $username the user's username @param string $password the user's password @param int|null $rememberDuration (optional) the duration in seconds to keep the user logged in ("remember me"), e.g. `60 * 60 * 24 * 365.25` for one year @param callable|null $onBeforeSuccess (optional) a function that receives the user's ID as its single parameter and is executed before successful authentication; must return `true` to proceed or `false` to cancel @throws UnknownUsernameException if the specified username does not exist @throws AmbiguousUsernameException if the specified username is ambiguous, i.e. there are multiple users with that name @throws InvalidPasswordException if the password was invalid @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email @throws AttemptCancelledException if the attempt has been cancelled by the supplied callback that is executed before success @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded @throws AuthError if an internal problem occurred (do *not* catch)
[ "Attempts", "to", "sign", "in", "a", "user", "with", "their", "username", "and", "password" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L321-L325
train
delight-im/PHP-Auth
src/Auth.php
Auth.reconfirmPassword
public function reconfirmPassword($password) { if ($this->isLoggedIn()) { try { $password = self::validatePassword($password); } catch (InvalidPasswordException $e) { return false; } $this->throttle([ 'reconfirmPassword', $this->getIpAddress() ], 3, (60 * 60), 4, true); try { $expectedHash = $this->db->selectValue( 'SELECT password FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $this->getUserId() ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if (!empty($expectedHash)) { $validated = \password_verify($password, $expectedHash); if (!$validated) { $this->throttle([ 'reconfirmPassword', $this->getIpAddress() ], 3, (60 * 60), 4, false); } return $validated; } else { throw new NotLoggedInException(); } } else { throw new NotLoggedInException(); } }
php
public function reconfirmPassword($password) { if ($this->isLoggedIn()) { try { $password = self::validatePassword($password); } catch (InvalidPasswordException $e) { return false; } $this->throttle([ 'reconfirmPassword', $this->getIpAddress() ], 3, (60 * 60), 4, true); try { $expectedHash = $this->db->selectValue( 'SELECT password FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $this->getUserId() ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if (!empty($expectedHash)) { $validated = \password_verify($password, $expectedHash); if (!$validated) { $this->throttle([ 'reconfirmPassword', $this->getIpAddress() ], 3, (60 * 60), 4, false); } return $validated; } else { throw new NotLoggedInException(); } } else { throw new NotLoggedInException(); } }
[ "public", "function", "reconfirmPassword", "(", "$", "password", ")", "{", "if", "(", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "try", "{", "$", "password", "=", "self", "::", "validatePassword", "(", "$", "password", ")", ";", "}", "catch", "(", "InvalidPasswordException", "$", "e", ")", "{", "return", "false", ";", "}", "$", "this", "->", "throttle", "(", "[", "'reconfirmPassword'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "3", ",", "(", "60", "*", "60", ")", ",", "4", ",", "true", ")", ";", "try", "{", "$", "expectedHash", "=", "$", "this", "->", "db", "->", "selectValue", "(", "'SELECT password FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' WHERE id = ?'", ",", "[", "$", "this", "->", "getUserId", "(", ")", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "expectedHash", ")", ")", "{", "$", "validated", "=", "\\", "password_verify", "(", "$", "password", ",", "$", "expectedHash", ")", ";", "if", "(", "!", "$", "validated", ")", "{", "$", "this", "->", "throttle", "(", "[", "'reconfirmPassword'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "3", ",", "(", "60", "*", "60", ")", ",", "4", ",", "false", ")", ";", "}", "return", "$", "validated", ";", "}", "else", "{", "throw", "new", "NotLoggedInException", "(", ")", ";", "}", "}", "else", "{", "throw", "new", "NotLoggedInException", "(", ")", ";", "}", "}" ]
Attempts to confirm the currently signed-in user's password again Whenever you want to confirm the user's identity again, e.g. before the user is allowed to perform some "dangerous" action, you should use this method to confirm that the user is who they claim to be. For example, when a user has been remembered by a long-lived cookie and thus {@see isRemembered} returns `true`, this means that the user has not entered their password for quite some time anymore. @param string $password the user's password @return bool whether the supplied password has been correct @throws NotLoggedInException if the user is not currently signed in @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded @throws AuthError if an internal problem occurred (do *not* catch)
[ "Attempts", "to", "confirm", "the", "currently", "signed", "-", "in", "user", "s", "password", "again" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L344-L381
train
delight-im/PHP-Auth
src/Auth.php
Auth.logOut
public function logOut() { // if the user has been signed in if ($this->isLoggedIn()) { // retrieve any locally existing remember directive $rememberDirectiveSelector = $this->getRememberDirectiveSelector(); // if such a remember directive exists if (isset($rememberDirectiveSelector)) { // delete the local remember directive $this->deleteRememberDirectiveForUserById( $this->getUserId(), $rememberDirectiveSelector ); } // remove all session variables maintained by this library unset($_SESSION[self::SESSION_FIELD_LOGGED_IN]); unset($_SESSION[self::SESSION_FIELD_USER_ID]); unset($_SESSION[self::SESSION_FIELD_EMAIL]); unset($_SESSION[self::SESSION_FIELD_USERNAME]); unset($_SESSION[self::SESSION_FIELD_STATUS]); unset($_SESSION[self::SESSION_FIELD_ROLES]); unset($_SESSION[self::SESSION_FIELD_REMEMBERED]); unset($_SESSION[self::SESSION_FIELD_LAST_RESYNC]); unset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]); } }
php
public function logOut() { // if the user has been signed in if ($this->isLoggedIn()) { // retrieve any locally existing remember directive $rememberDirectiveSelector = $this->getRememberDirectiveSelector(); // if such a remember directive exists if (isset($rememberDirectiveSelector)) { // delete the local remember directive $this->deleteRememberDirectiveForUserById( $this->getUserId(), $rememberDirectiveSelector ); } // remove all session variables maintained by this library unset($_SESSION[self::SESSION_FIELD_LOGGED_IN]); unset($_SESSION[self::SESSION_FIELD_USER_ID]); unset($_SESSION[self::SESSION_FIELD_EMAIL]); unset($_SESSION[self::SESSION_FIELD_USERNAME]); unset($_SESSION[self::SESSION_FIELD_STATUS]); unset($_SESSION[self::SESSION_FIELD_ROLES]); unset($_SESSION[self::SESSION_FIELD_REMEMBERED]); unset($_SESSION[self::SESSION_FIELD_LAST_RESYNC]); unset($_SESSION[self::SESSION_FIELD_FORCE_LOGOUT]); } }
[ "public", "function", "logOut", "(", ")", "{", "// if the user has been signed in", "if", "(", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "// retrieve any locally existing remember directive", "$", "rememberDirectiveSelector", "=", "$", "this", "->", "getRememberDirectiveSelector", "(", ")", ";", "// if such a remember directive exists", "if", "(", "isset", "(", "$", "rememberDirectiveSelector", ")", ")", "{", "// delete the local remember directive", "$", "this", "->", "deleteRememberDirectiveForUserById", "(", "$", "this", "->", "getUserId", "(", ")", ",", "$", "rememberDirectiveSelector", ")", ";", "}", "// remove all session variables maintained by this library", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_LOGGED_IN", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USER_ID", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_EMAIL", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USERNAME", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_STATUS", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_ROLES", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_REMEMBERED", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_LAST_RESYNC", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_FORCE_LOGOUT", "]", ")", ";", "}", "}" ]
Logs the user out @throws AuthError if an internal problem occurred (do *not* catch)
[ "Logs", "the", "user", "out" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L388-L414
train
delight-im/PHP-Auth
src/Auth.php
Auth.logOutEverywhere
public function logOutEverywhere() { if (!$this->isLoggedIn()) { throw new NotLoggedInException(); } // schedule a forced logout in all sessions $this->forceLogoutForUserById($this->getUserId()); // and immediately apply the logout locally $this->logOut(); }
php
public function logOutEverywhere() { if (!$this->isLoggedIn()) { throw new NotLoggedInException(); } // schedule a forced logout in all sessions $this->forceLogoutForUserById($this->getUserId()); // and immediately apply the logout locally $this->logOut(); }
[ "public", "function", "logOutEverywhere", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "throw", "new", "NotLoggedInException", "(", ")", ";", "}", "// schedule a forced logout in all sessions", "$", "this", "->", "forceLogoutForUserById", "(", "$", "this", "->", "getUserId", "(", ")", ")", ";", "// and immediately apply the logout locally", "$", "this", "->", "logOut", "(", ")", ";", "}" ]
Logs the user out in all sessions @throws NotLoggedInException if the user is not currently signed in @throws AuthError if an internal problem occurred (do *not* catch)
[ "Logs", "the", "user", "out", "in", "all", "sessions" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L460-L469
train
delight-im/PHP-Auth
src/Auth.php
Auth.setRememberCookie
private function setRememberCookie($selector, $token, $expires) { $params = \session_get_cookie_params(); if (isset($selector) && isset($token)) { $content = $selector . self::COOKIE_CONTENT_SEPARATOR . $token; } else { $content = ''; } // save the cookie with the selector and token (requests a cookie to be written on the client) $cookie = new Cookie($this->rememberCookieName); $cookie->setValue($content); $cookie->setExpiryTime($expires); $cookie->setPath($params['path']); $cookie->setDomain($params['domain']); $cookie->setHttpOnly($params['httponly']); $cookie->setSecureOnly($params['secure']); $result = $cookie->save(); if ($result === false) { throw new HeadersAlreadySentError(); } // if we've been deleting the cookie above if (!isset($selector) || !isset($token)) { // attempt to delete a potential old cookie from versions v1.x.x to v6.x.x as well (requests a cookie to be written on the client) $cookie = new Cookie('auth_remember'); $cookie->setPath((!empty($params['path'])) ? $params['path'] : '/'); $cookie->setDomain($params['domain']); $cookie->setHttpOnly($params['httponly']); $cookie->setSecureOnly($params['secure']); $cookie->delete(); } }
php
private function setRememberCookie($selector, $token, $expires) { $params = \session_get_cookie_params(); if (isset($selector) && isset($token)) { $content = $selector . self::COOKIE_CONTENT_SEPARATOR . $token; } else { $content = ''; } // save the cookie with the selector and token (requests a cookie to be written on the client) $cookie = new Cookie($this->rememberCookieName); $cookie->setValue($content); $cookie->setExpiryTime($expires); $cookie->setPath($params['path']); $cookie->setDomain($params['domain']); $cookie->setHttpOnly($params['httponly']); $cookie->setSecureOnly($params['secure']); $result = $cookie->save(); if ($result === false) { throw new HeadersAlreadySentError(); } // if we've been deleting the cookie above if (!isset($selector) || !isset($token)) { // attempt to delete a potential old cookie from versions v1.x.x to v6.x.x as well (requests a cookie to be written on the client) $cookie = new Cookie('auth_remember'); $cookie->setPath((!empty($params['path'])) ? $params['path'] : '/'); $cookie->setDomain($params['domain']); $cookie->setHttpOnly($params['httponly']); $cookie->setSecureOnly($params['secure']); $cookie->delete(); } }
[ "private", "function", "setRememberCookie", "(", "$", "selector", ",", "$", "token", ",", "$", "expires", ")", "{", "$", "params", "=", "\\", "session_get_cookie_params", "(", ")", ";", "if", "(", "isset", "(", "$", "selector", ")", "&&", "isset", "(", "$", "token", ")", ")", "{", "$", "content", "=", "$", "selector", ".", "self", "::", "COOKIE_CONTENT_SEPARATOR", ".", "$", "token", ";", "}", "else", "{", "$", "content", "=", "''", ";", "}", "// save the cookie with the selector and token (requests a cookie to be written on the client)", "$", "cookie", "=", "new", "Cookie", "(", "$", "this", "->", "rememberCookieName", ")", ";", "$", "cookie", "->", "setValue", "(", "$", "content", ")", ";", "$", "cookie", "->", "setExpiryTime", "(", "$", "expires", ")", ";", "$", "cookie", "->", "setPath", "(", "$", "params", "[", "'path'", "]", ")", ";", "$", "cookie", "->", "setDomain", "(", "$", "params", "[", "'domain'", "]", ")", ";", "$", "cookie", "->", "setHttpOnly", "(", "$", "params", "[", "'httponly'", "]", ")", ";", "$", "cookie", "->", "setSecureOnly", "(", "$", "params", "[", "'secure'", "]", ")", ";", "$", "result", "=", "$", "cookie", "->", "save", "(", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "throw", "new", "HeadersAlreadySentError", "(", ")", ";", "}", "// if we've been deleting the cookie above", "if", "(", "!", "isset", "(", "$", "selector", ")", "||", "!", "isset", "(", "$", "token", ")", ")", "{", "// attempt to delete a potential old cookie from versions v1.x.x to v6.x.x as well (requests a cookie to be written on the client)", "$", "cookie", "=", "new", "Cookie", "(", "'auth_remember'", ")", ";", "$", "cookie", "->", "setPath", "(", "(", "!", "empty", "(", "$", "params", "[", "'path'", "]", ")", ")", "?", "$", "params", "[", "'path'", "]", ":", "'/'", ")", ";", "$", "cookie", "->", "setDomain", "(", "$", "params", "[", "'domain'", "]", ")", ";", "$", "cookie", "->", "setHttpOnly", "(", "$", "params", "[", "'httponly'", "]", ")", ";", "$", "cookie", "->", "setSecureOnly", "(", "$", "params", "[", "'secure'", "]", ")", ";", "$", "cookie", "->", "delete", "(", ")", ";", "}", "}" ]
Sets or updates the cookie that manages the "remember me" token @param string|null $selector the selector from the selector/token pair @param string|null $token the token from the selector/token pair @param int $expires the UNIX time in seconds which the token should expire at @throws AuthError if an internal problem occurred (do *not* catch)
[ "Sets", "or", "updates", "the", "cookie", "that", "manages", "the", "remember", "me", "token" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L530-L564
train
delight-im/PHP-Auth
src/Auth.php
Auth.deleteSessionCookie
private function deleteSessionCookie() { $params = \session_get_cookie_params(); // ask for the session cookie to be deleted (requests a cookie to be written on the client) $cookie = new Cookie(\session_name()); $cookie->setPath($params['path']); $cookie->setDomain($params['domain']); $cookie->setHttpOnly($params['httponly']); $cookie->setSecureOnly($params['secure']); $result = $cookie->delete(); if ($result === false) { throw new HeadersAlreadySentError(); } }
php
private function deleteSessionCookie() { $params = \session_get_cookie_params(); // ask for the session cookie to be deleted (requests a cookie to be written on the client) $cookie = new Cookie(\session_name()); $cookie->setPath($params['path']); $cookie->setDomain($params['domain']); $cookie->setHttpOnly($params['httponly']); $cookie->setSecureOnly($params['secure']); $result = $cookie->delete(); if ($result === false) { throw new HeadersAlreadySentError(); } }
[ "private", "function", "deleteSessionCookie", "(", ")", "{", "$", "params", "=", "\\", "session_get_cookie_params", "(", ")", ";", "// ask for the session cookie to be deleted (requests a cookie to be written on the client)", "$", "cookie", "=", "new", "Cookie", "(", "\\", "session_name", "(", ")", ")", ";", "$", "cookie", "->", "setPath", "(", "$", "params", "[", "'path'", "]", ")", ";", "$", "cookie", "->", "setDomain", "(", "$", "params", "[", "'domain'", "]", ")", ";", "$", "cookie", "->", "setHttpOnly", "(", "$", "params", "[", "'httponly'", "]", ")", ";", "$", "cookie", "->", "setSecureOnly", "(", "$", "params", "[", "'secure'", "]", ")", ";", "$", "result", "=", "$", "cookie", "->", "delete", "(", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "throw", "new", "HeadersAlreadySentError", "(", ")", ";", "}", "}" ]
Deletes the session cookie on the client @throws AuthError if an internal problem occurred (do *not* catch)
[ "Deletes", "the", "session", "cookie", "on", "the", "client" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L587-L601
train
delight-im/PHP-Auth
src/Auth.php
Auth.changePassword
public function changePassword($oldPassword, $newPassword) { if ($this->reconfirmPassword($oldPassword)) { $this->changePasswordWithoutOldPassword($newPassword); } else { throw new InvalidPasswordException(); } }
php
public function changePassword($oldPassword, $newPassword) { if ($this->reconfirmPassword($oldPassword)) { $this->changePasswordWithoutOldPassword($newPassword); } else { throw new InvalidPasswordException(); } }
[ "public", "function", "changePassword", "(", "$", "oldPassword", ",", "$", "newPassword", ")", "{", "if", "(", "$", "this", "->", "reconfirmPassword", "(", "$", "oldPassword", ")", ")", "{", "$", "this", "->", "changePasswordWithoutOldPassword", "(", "$", "newPassword", ")", ";", "}", "else", "{", "throw", "new", "InvalidPasswordException", "(", ")", ";", "}", "}" ]
Changes the currently signed-in user's password while requiring the old password for verification @param string $oldPassword the old password to verify account ownership @param string $newPassword the new password that should be set @throws NotLoggedInException if the user is not currently signed in @throws InvalidPasswordException if either the old password has been wrong or the desired new one has been invalid @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded @throws AuthError if an internal problem occurred (do *not* catch)
[ "Changes", "the", "currently", "signed", "-", "in", "user", "s", "password", "while", "requiring", "the", "old", "password", "for", "verification" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L758-L765
train
delight-im/PHP-Auth
src/Auth.php
Auth.changePasswordWithoutOldPassword
public function changePasswordWithoutOldPassword($newPassword) { if ($this->isLoggedIn()) { $newPassword = self::validatePassword($newPassword); $this->updatePasswordInternal($this->getUserId(), $newPassword); try { $this->logOutEverywhereElse(); } catch (NotLoggedInException $ignored) {} } else { throw new NotLoggedInException(); } }
php
public function changePasswordWithoutOldPassword($newPassword) { if ($this->isLoggedIn()) { $newPassword = self::validatePassword($newPassword); $this->updatePasswordInternal($this->getUserId(), $newPassword); try { $this->logOutEverywhereElse(); } catch (NotLoggedInException $ignored) {} } else { throw new NotLoggedInException(); } }
[ "public", "function", "changePasswordWithoutOldPassword", "(", "$", "newPassword", ")", "{", "if", "(", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "$", "newPassword", "=", "self", "::", "validatePassword", "(", "$", "newPassword", ")", ";", "$", "this", "->", "updatePasswordInternal", "(", "$", "this", "->", "getUserId", "(", ")", ",", "$", "newPassword", ")", ";", "try", "{", "$", "this", "->", "logOutEverywhereElse", "(", ")", ";", "}", "catch", "(", "NotLoggedInException", "$", "ignored", ")", "{", "}", "}", "else", "{", "throw", "new", "NotLoggedInException", "(", ")", ";", "}", "}" ]
Changes the currently signed-in user's password without requiring the old password for verification @param string $newPassword the new password that should be set @throws NotLoggedInException if the user is not currently signed in @throws InvalidPasswordException if the desired new password has been invalid @throws AuthError if an internal problem occurred (do *not* catch)
[ "Changes", "the", "currently", "signed", "-", "in", "user", "s", "password", "without", "requiring", "the", "old", "password", "for", "verification" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L775-L788
train
delight-im/PHP-Auth
src/Auth.php
Auth.resendConfirmationForEmail
public function resendConfirmationForEmail($email, callable $callback) { $this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75); $this->resendConfirmationForColumnValue('email', $email, $callback); }
php
public function resendConfirmationForEmail($email, callable $callback) { $this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75); $this->resendConfirmationForColumnValue('email', $email, $callback); }
[ "public", "function", "resendConfirmationForEmail", "(", "$", "email", ",", "callable", "$", "callback", ")", "{", "$", "this", "->", "throttle", "(", "[", "'enumerateUsers'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "1", ",", "(", "60", "*", "60", ")", ",", "75", ")", ";", "$", "this", "->", "resendConfirmationForColumnValue", "(", "'email'", ",", "$", "email", ",", "$", "callback", ")", ";", "}" ]
Attempts to re-send an earlier confirmation request for the user with the specified email address The callback function must have the following signature: `function ($selector, $token)` Both pieces of information must be sent to the user, usually embedded in a link When the user wants to verify their email address as a next step, both pieces will be required again @param string $email the email address of the user to re-send the confirmation request for @param callable $callback the function that sends the confirmation request to the user @throws ConfirmationRequestNotFound if no previous request has been found that could be re-sent @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded
[ "Attempts", "to", "re", "-", "send", "an", "earlier", "confirmation", "request", "for", "the", "user", "with", "the", "specified", "email", "address" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L874-L878
train
delight-im/PHP-Auth
src/Auth.php
Auth.resendConfirmationForColumnValue
private function resendConfirmationForColumnValue($columnName, $columnValue, callable $callback) { try { $latestAttempt = $this->db->selectRow( 'SELECT user_id, email FROM ' . $this->makeTableName('users_confirmations') . ' WHERE ' . $columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0', [ $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if ($latestAttempt === null) { throw new ConfirmationRequestNotFound(); } $this->throttle([ 'resendConfirmation', 'userId', $latestAttempt['user_id'] ], 1, (60 * 60 * 6)); $this->throttle([ 'resendConfirmation', $this->getIpAddress() ], 4, (60 * 60 * 24 * 7), 2); $this->createConfirmationRequest( $latestAttempt['user_id'], $latestAttempt['email'], $callback ); }
php
private function resendConfirmationForColumnValue($columnName, $columnValue, callable $callback) { try { $latestAttempt = $this->db->selectRow( 'SELECT user_id, email FROM ' . $this->makeTableName('users_confirmations') . ' WHERE ' . $columnName . ' = ? ORDER BY id DESC LIMIT 1 OFFSET 0', [ $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if ($latestAttempt === null) { throw new ConfirmationRequestNotFound(); } $this->throttle([ 'resendConfirmation', 'userId', $latestAttempt['user_id'] ], 1, (60 * 60 * 6)); $this->throttle([ 'resendConfirmation', $this->getIpAddress() ], 4, (60 * 60 * 24 * 7), 2); $this->createConfirmationRequest( $latestAttempt['user_id'], $latestAttempt['email'], $callback ); }
[ "private", "function", "resendConfirmationForColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ",", "callable", "$", "callback", ")", "{", "try", "{", "$", "latestAttempt", "=", "$", "this", "->", "db", "->", "selectRow", "(", "'SELECT user_id, email FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users_confirmations'", ")", ".", "' WHERE '", ".", "$", "columnName", ".", "' = ? ORDER BY id DESC LIMIT 1 OFFSET 0'", ",", "[", "$", "columnValue", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "if", "(", "$", "latestAttempt", "===", "null", ")", "{", "throw", "new", "ConfirmationRequestNotFound", "(", ")", ";", "}", "$", "this", "->", "throttle", "(", "[", "'resendConfirmation'", ",", "'userId'", ",", "$", "latestAttempt", "[", "'user_id'", "]", "]", ",", "1", ",", "(", "60", "*", "60", "*", "6", ")", ")", ";", "$", "this", "->", "throttle", "(", "[", "'resendConfirmation'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "4", ",", "(", "60", "*", "60", "*", "24", "*", "7", ")", ",", "2", ")", ";", "$", "this", "->", "createConfirmationRequest", "(", "$", "latestAttempt", "[", "'user_id'", "]", ",", "$", "latestAttempt", "[", "'email'", "]", ",", "$", "callback", ")", ";", "}" ]
Attempts to re-send an earlier confirmation request The callback function must have the following signature: `function ($selector, $token)` Both pieces of information must be sent to the user, usually embedded in a link When the user wants to verify their email address as a next step, both pieces will be required again You must never pass untrusted input to the parameter that takes the column name @param string $columnName the name of the column to filter by @param mixed $columnValue the value to look for in the selected column @param callable $callback the function that sends the confirmation request to the user @throws ConfirmationRequestNotFound if no previous request has been found that could be re-sent @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded @throws AuthError if an internal problem occurred (do *not* catch)
[ "Attempts", "to", "re", "-", "send", "an", "earlier", "confirmation", "request" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L920-L943
train
delight-im/PHP-Auth
src/Auth.php
Auth.forgotPassword
public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) { $email = self::validateEmailAddress($email); $this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75); if ($requestExpiresAfter === null) { // use six hours as the default $requestExpiresAfter = 60 * 60 * 6; } else { $requestExpiresAfter = (int) $requestExpiresAfter; } if ($maxOpenRequests === null) { // use two requests per user as the default $maxOpenRequests = 2; } else { $maxOpenRequests = (int) $maxOpenRequests; } $userData = $this->getUserDataByEmailAddress( $email, [ 'id', 'verified', 'resettable' ] ); // ensure that the account has been verified before initiating a password reset if ((int) $userData['verified'] !== 1) { throw new EmailNotVerifiedException(); } // do not allow a password reset if the user has explicitly disabled this feature if ((int) $userData['resettable'] !== 1) { throw new ResetDisabledException(); } $openRequests = (int) $this->getOpenPasswordResetRequests($userData['id']); if ($openRequests < $maxOpenRequests) { $this->throttle([ 'requestPasswordReset', $this->getIpAddress() ], 4, (60 * 60 * 24 * 7), 2); $this->throttle([ 'requestPasswordReset', 'user', $userData['id'] ], 4, (60 * 60 * 24 * 7), 2); $this->createPasswordResetRequest($userData['id'], $requestExpiresAfter, $callback); } else { throw new TooManyRequestsException('', $requestExpiresAfter); } }
php
public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) { $email = self::validateEmailAddress($email); $this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75); if ($requestExpiresAfter === null) { // use six hours as the default $requestExpiresAfter = 60 * 60 * 6; } else { $requestExpiresAfter = (int) $requestExpiresAfter; } if ($maxOpenRequests === null) { // use two requests per user as the default $maxOpenRequests = 2; } else { $maxOpenRequests = (int) $maxOpenRequests; } $userData = $this->getUserDataByEmailAddress( $email, [ 'id', 'verified', 'resettable' ] ); // ensure that the account has been verified before initiating a password reset if ((int) $userData['verified'] !== 1) { throw new EmailNotVerifiedException(); } // do not allow a password reset if the user has explicitly disabled this feature if ((int) $userData['resettable'] !== 1) { throw new ResetDisabledException(); } $openRequests = (int) $this->getOpenPasswordResetRequests($userData['id']); if ($openRequests < $maxOpenRequests) { $this->throttle([ 'requestPasswordReset', $this->getIpAddress() ], 4, (60 * 60 * 24 * 7), 2); $this->throttle([ 'requestPasswordReset', 'user', $userData['id'] ], 4, (60 * 60 * 24 * 7), 2); $this->createPasswordResetRequest($userData['id'], $requestExpiresAfter, $callback); } else { throw new TooManyRequestsException('', $requestExpiresAfter); } }
[ "public", "function", "forgotPassword", "(", "$", "email", ",", "callable", "$", "callback", ",", "$", "requestExpiresAfter", "=", "null", ",", "$", "maxOpenRequests", "=", "null", ")", "{", "$", "email", "=", "self", "::", "validateEmailAddress", "(", "$", "email", ")", ";", "$", "this", "->", "throttle", "(", "[", "'enumerateUsers'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "1", ",", "(", "60", "*", "60", ")", ",", "75", ")", ";", "if", "(", "$", "requestExpiresAfter", "===", "null", ")", "{", "// use six hours as the default", "$", "requestExpiresAfter", "=", "60", "*", "60", "*", "6", ";", "}", "else", "{", "$", "requestExpiresAfter", "=", "(", "int", ")", "$", "requestExpiresAfter", ";", "}", "if", "(", "$", "maxOpenRequests", "===", "null", ")", "{", "// use two requests per user as the default", "$", "maxOpenRequests", "=", "2", ";", "}", "else", "{", "$", "maxOpenRequests", "=", "(", "int", ")", "$", "maxOpenRequests", ";", "}", "$", "userData", "=", "$", "this", "->", "getUserDataByEmailAddress", "(", "$", "email", ",", "[", "'id'", ",", "'verified'", ",", "'resettable'", "]", ")", ";", "// ensure that the account has been verified before initiating a password reset", "if", "(", "(", "int", ")", "$", "userData", "[", "'verified'", "]", "!==", "1", ")", "{", "throw", "new", "EmailNotVerifiedException", "(", ")", ";", "}", "// do not allow a password reset if the user has explicitly disabled this feature", "if", "(", "(", "int", ")", "$", "userData", "[", "'resettable'", "]", "!==", "1", ")", "{", "throw", "new", "ResetDisabledException", "(", ")", ";", "}", "$", "openRequests", "=", "(", "int", ")", "$", "this", "->", "getOpenPasswordResetRequests", "(", "$", "userData", "[", "'id'", "]", ")", ";", "if", "(", "$", "openRequests", "<", "$", "maxOpenRequests", ")", "{", "$", "this", "->", "throttle", "(", "[", "'requestPasswordReset'", ",", "$", "this", "->", "getIpAddress", "(", ")", "]", ",", "4", ",", "(", "60", "*", "60", "*", "24", "*", "7", ")", ",", "2", ")", ";", "$", "this", "->", "throttle", "(", "[", "'requestPasswordReset'", ",", "'user'", ",", "$", "userData", "[", "'id'", "]", "]", ",", "4", ",", "(", "60", "*", "60", "*", "24", "*", "7", ")", ",", "2", ")", ";", "$", "this", "->", "createPasswordResetRequest", "(", "$", "userData", "[", "'id'", "]", ",", "$", "requestExpiresAfter", ",", "$", "callback", ")", ";", "}", "else", "{", "throw", "new", "TooManyRequestsException", "(", "''", ",", "$", "requestExpiresAfter", ")", ";", "}", "}" ]
Initiates a password reset request for the user with the specified email address The callback function must have the following signature: `function ($selector, $token)` Both pieces of information must be sent to the user, usually embedded in a link When the user wants to proceed to the second step of the password reset, both pieces will be required again @param string $email the email address of the user who wants to request the password reset @param callable $callback the function that sends the password reset information to the user @param int|null $requestExpiresAfter (optional) the interval in seconds after which the request should expire @param int|null $maxOpenRequests (optional) the maximum number of unexpired and unused requests per user @throws InvalidEmailException if the email address was invalid or could not be found @throws EmailNotVerifiedException if the email address has not been verified yet via confirmation email @throws ResetDisabledException if the user has explicitly disabled password resets for their account @throws TooManyRequestsException if the number of allowed attempts/requests has been exceeded @throws AuthError if an internal problem occurred (do *not* catch)
[ "Initiates", "a", "password", "reset", "request", "for", "the", "user", "with", "the", "specified", "email", "address" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L966-L1013
train
delight-im/PHP-Auth
src/Auth.php
Auth.getOpenPasswordResetRequests
private function getOpenPasswordResetRequests($userId) { try { $requests = $this->db->selectValue( 'SELECT COUNT(*) FROM ' . $this->makeTableName('users_resets') . ' WHERE user = ? AND expires > ?', [ $userId, \time() ] ); if (!empty($requests)) { return $requests; } else { return 0; } } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
php
private function getOpenPasswordResetRequests($userId) { try { $requests = $this->db->selectValue( 'SELECT COUNT(*) FROM ' . $this->makeTableName('users_resets') . ' WHERE user = ? AND expires > ?', [ $userId, \time() ] ); if (!empty($requests)) { return $requests; } else { return 0; } } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
[ "private", "function", "getOpenPasswordResetRequests", "(", "$", "userId", ")", "{", "try", "{", "$", "requests", "=", "$", "this", "->", "db", "->", "selectValue", "(", "'SELECT COUNT(*) FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users_resets'", ")", ".", "' WHERE user = ? AND expires > ?'", ",", "[", "$", "userId", ",", "\\", "time", "(", ")", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "requests", ")", ")", "{", "return", "$", "requests", ";", "}", "else", "{", "return", "0", ";", "}", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Returns the number of open requests for a password reset by the specified user @param int $userId the ID of the user to check the requests for @return int the number of open requests for a password reset @throws AuthError if an internal problem occurred (do *not* catch)
[ "Returns", "the", "number", "of", "open", "requests", "for", "a", "password", "reset", "by", "the", "specified", "user" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1159-L1179
train
delight-im/PHP-Auth
src/Auth.php
Auth.createPasswordResetRequest
private function createPasswordResetRequest($userId, $expiresAfter, callable $callback) { $selector = self::createRandomString(20); $token = self::createRandomString(20); $tokenHashed = \password_hash($token, \PASSWORD_DEFAULT); $expiresAt = \time() + $expiresAfter; try { $this->db->insert( $this->makeTableNameComponents('users_resets'), [ 'user' => $userId, 'selector' => $selector, 'token' => $tokenHashed, 'expires' => $expiresAt ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if (\is_callable($callback)) { $callback($selector, $token); } else { throw new MissingCallbackError(); } }
php
private function createPasswordResetRequest($userId, $expiresAfter, callable $callback) { $selector = self::createRandomString(20); $token = self::createRandomString(20); $tokenHashed = \password_hash($token, \PASSWORD_DEFAULT); $expiresAt = \time() + $expiresAfter; try { $this->db->insert( $this->makeTableNameComponents('users_resets'), [ 'user' => $userId, 'selector' => $selector, 'token' => $tokenHashed, 'expires' => $expiresAt ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if (\is_callable($callback)) { $callback($selector, $token); } else { throw new MissingCallbackError(); } }
[ "private", "function", "createPasswordResetRequest", "(", "$", "userId", ",", "$", "expiresAfter", ",", "callable", "$", "callback", ")", "{", "$", "selector", "=", "self", "::", "createRandomString", "(", "20", ")", ";", "$", "token", "=", "self", "::", "createRandomString", "(", "20", ")", ";", "$", "tokenHashed", "=", "\\", "password_hash", "(", "$", "token", ",", "\\", "PASSWORD_DEFAULT", ")", ";", "$", "expiresAt", "=", "\\", "time", "(", ")", "+", "$", "expiresAfter", ";", "try", "{", "$", "this", "->", "db", "->", "insert", "(", "$", "this", "->", "makeTableNameComponents", "(", "'users_resets'", ")", ",", "[", "'user'", "=>", "$", "userId", ",", "'selector'", "=>", "$", "selector", ",", "'token'", "=>", "$", "tokenHashed", ",", "'expires'", "=>", "$", "expiresAt", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "if", "(", "\\", "is_callable", "(", "$", "callback", ")", ")", "{", "$", "callback", "(", "$", "selector", ",", "$", "token", ")", ";", "}", "else", "{", "throw", "new", "MissingCallbackError", "(", ")", ";", "}", "}" ]
Creates a new password reset request The callback function must have the following signature: `function ($selector, $token)` Both pieces of information must be sent to the user, usually embedded in a link When the user wants to proceed to the second step of the password reset, both pieces will be required again @param int $userId the ID of the user who requested the reset @param int $expiresAfter the interval in seconds after which the request should expire @param callable $callback the function that sends the password reset information to the user @throws AuthError if an internal problem occurred (do *not* catch)
[ "Creates", "a", "new", "password", "reset", "request" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1197-L1224
train
delight-im/PHP-Auth
src/Auth.php
Auth.setPasswordResetEnabled
public function setPasswordResetEnabled($enabled) { $enabled = (bool) $enabled; if ($this->isLoggedIn()) { try { $this->db->update( $this->makeTableNameComponents('users'), [ 'resettable' => $enabled ? 1 : 0 ], [ 'id' => $this->getUserId() ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } } else { throw new NotLoggedInException(); } }
php
public function setPasswordResetEnabled($enabled) { $enabled = (bool) $enabled; if ($this->isLoggedIn()) { try { $this->db->update( $this->makeTableNameComponents('users'), [ 'resettable' => $enabled ? 1 : 0 ], [ 'id' => $this->getUserId() ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } } else { throw new NotLoggedInException(); } }
[ "public", "function", "setPasswordResetEnabled", "(", "$", "enabled", ")", "{", "$", "enabled", "=", "(", "bool", ")", "$", "enabled", ";", "if", "(", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "try", "{", "$", "this", "->", "db", "->", "update", "(", "$", "this", "->", "makeTableNameComponents", "(", "'users'", ")", ",", "[", "'resettable'", "=>", "$", "enabled", "?", "1", ":", "0", "]", ",", "[", "'id'", "=>", "$", "this", "->", "getUserId", "(", ")", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}", "else", "{", "throw", "new", "NotLoggedInException", "(", ")", ";", "}", "}" ]
Sets whether password resets should be permitted for the account of the currently signed-in user @param bool $enabled whether password resets should be enabled for the user's account @throws NotLoggedInException if the user is not currently signed in @throws AuthError if an internal problem occurred (do *not* catch)
[ "Sets", "whether", "password", "resets", "should", "be", "permitted", "for", "the", "account", "of", "the", "currently", "signed", "-", "in", "user" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1353-L1375
train
delight-im/PHP-Auth
src/Auth.php
Auth.isPasswordResetEnabled
public function isPasswordResetEnabled() { if ($this->isLoggedIn()) { try { $enabled = $this->db->selectValue( 'SELECT resettable FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $this->getUserId() ] ); return (int) $enabled === 1; } catch (Error $e) { throw new DatabaseError($e->getMessage()); } } else { throw new NotLoggedInException(); } }
php
public function isPasswordResetEnabled() { if ($this->isLoggedIn()) { try { $enabled = $this->db->selectValue( 'SELECT resettable FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $this->getUserId() ] ); return (int) $enabled === 1; } catch (Error $e) { throw new DatabaseError($e->getMessage()); } } else { throw new NotLoggedInException(); } }
[ "public", "function", "isPasswordResetEnabled", "(", ")", "{", "if", "(", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "try", "{", "$", "enabled", "=", "$", "this", "->", "db", "->", "selectValue", "(", "'SELECT resettable FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' WHERE id = ?'", ",", "[", "$", "this", "->", "getUserId", "(", ")", "]", ")", ";", "return", "(", "int", ")", "$", "enabled", "===", "1", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}", "else", "{", "throw", "new", "NotLoggedInException", "(", ")", ";", "}", "}" ]
Returns whether password resets are permitted for the account of the currently signed-in user @return bool @throws NotLoggedInException if the user is not currently signed in @throws AuthError if an internal problem occurred (do *not* catch)
[ "Returns", "whether", "password", "resets", "are", "permitted", "for", "the", "account", "of", "the", "currently", "signed", "-", "in", "user" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1384-L1401
train
delight-im/PHP-Auth
src/Auth.php
Auth.isLoggedIn
public function isLoggedIn() { return isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_LOGGED_IN]) && $_SESSION[self::SESSION_FIELD_LOGGED_IN] === true; }
php
public function isLoggedIn() { return isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_LOGGED_IN]) && $_SESSION[self::SESSION_FIELD_LOGGED_IN] === true; }
[ "public", "function", "isLoggedIn", "(", ")", "{", "return", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_LOGGED_IN", "]", ")", "&&", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_LOGGED_IN", "]", "===", "true", ";", "}" ]
Returns whether the user is currently logged in by reading from the session @return boolean whether the user is logged in or not
[ "Returns", "whether", "the", "user", "is", "currently", "logged", "in", "by", "reading", "from", "the", "session" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1408-L1410
train
delight-im/PHP-Auth
src/Auth.php
Auth.getUserId
public function getUserId() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_USER_ID])) { return $_SESSION[self::SESSION_FIELD_USER_ID]; } else { return null; } }
php
public function getUserId() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_USER_ID])) { return $_SESSION[self::SESSION_FIELD_USER_ID]; } else { return null; } }
[ "public", "function", "getUserId", "(", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USER_ID", "]", ")", ")", "{", "return", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USER_ID", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the currently signed-in user's ID by reading from the session @return int the user ID
[ "Returns", "the", "currently", "signed", "-", "in", "user", "s", "ID", "by", "reading", "from", "the", "session" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1426-L1433
train
delight-im/PHP-Auth
src/Auth.php
Auth.getEmail
public function getEmail() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_EMAIL])) { return $_SESSION[self::SESSION_FIELD_EMAIL]; } else { return null; } }
php
public function getEmail() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_EMAIL])) { return $_SESSION[self::SESSION_FIELD_EMAIL]; } else { return null; } }
[ "public", "function", "getEmail", "(", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_EMAIL", "]", ")", ")", "{", "return", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_EMAIL", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the currently signed-in user's email address by reading from the session @return string the email address
[ "Returns", "the", "currently", "signed", "-", "in", "user", "s", "email", "address", "by", "reading", "from", "the", "session" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1449-L1456
train
delight-im/PHP-Auth
src/Auth.php
Auth.getUsername
public function getUsername() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_USERNAME])) { return $_SESSION[self::SESSION_FIELD_USERNAME]; } else { return null; } }
php
public function getUsername() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_USERNAME])) { return $_SESSION[self::SESSION_FIELD_USERNAME]; } else { return null; } }
[ "public", "function", "getUsername", "(", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USERNAME", "]", ")", ")", "{", "return", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USERNAME", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the currently signed-in user's display name by reading from the session @return string the display name
[ "Returns", "the", "currently", "signed", "-", "in", "user", "s", "display", "name", "by", "reading", "from", "the", "session" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1463-L1470
train
delight-im/PHP-Auth
src/Auth.php
Auth.getStatus
public function getStatus() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_STATUS])) { return $_SESSION[self::SESSION_FIELD_STATUS]; } else { return null; } }
php
public function getStatus() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_STATUS])) { return $_SESSION[self::SESSION_FIELD_STATUS]; } else { return null; } }
[ "public", "function", "getStatus", "(", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_STATUS", "]", ")", ")", "{", "return", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_STATUS", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the currently signed-in user's status by reading from the session @return int the status as one of the constants from the {@see Status} class
[ "Returns", "the", "currently", "signed", "-", "in", "user", "s", "status", "by", "reading", "from", "the", "session" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1477-L1484
train
delight-im/PHP-Auth
src/Auth.php
Auth.hasRole
public function hasRole($role) { if (empty($role) || !\is_numeric($role)) { return false; } if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_ROLES])) { $role = (int) $role; return (((int) $_SESSION[self::SESSION_FIELD_ROLES]) & $role) === $role; } else { return false; } }
php
public function hasRole($role) { if (empty($role) || !\is_numeric($role)) { return false; } if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_ROLES])) { $role = (int) $role; return (((int) $_SESSION[self::SESSION_FIELD_ROLES]) & $role) === $role; } else { return false; } }
[ "public", "function", "hasRole", "(", "$", "role", ")", "{", "if", "(", "empty", "(", "$", "role", ")", "||", "!", "\\", "is_numeric", "(", "$", "role", ")", ")", "{", "return", "false", ";", "}", "if", "(", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_ROLES", "]", ")", ")", "{", "$", "role", "=", "(", "int", ")", "$", "role", ";", "return", "(", "(", "(", "int", ")", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_ROLES", "]", ")", "&", "$", "role", ")", "===", "$", "role", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Returns whether the currently signed-in user has the specified role @param int $role the role as one of the constants from the {@see Role} class @return bool @see Role
[ "Returns", "whether", "the", "currently", "signed", "-", "in", "user", "has", "the", "specified", "role" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1566-L1579
train
delight-im/PHP-Auth
src/Auth.php
Auth.isRemembered
public function isRemembered() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_REMEMBERED])) { return $_SESSION[self::SESSION_FIELD_REMEMBERED]; } else { return null; } }
php
public function isRemembered() { if (isset($_SESSION) && isset($_SESSION[self::SESSION_FIELD_REMEMBERED])) { return $_SESSION[self::SESSION_FIELD_REMEMBERED]; } else { return null; } }
[ "public", "function", "isRemembered", "(", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", ")", "&&", "isset", "(", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_REMEMBERED", "]", ")", ")", "{", "return", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_REMEMBERED", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns whether the currently signed-in user has been remembered by a long-lived cookie @return bool whether they have been remembered
[ "Returns", "whether", "the", "currently", "signed", "-", "in", "user", "has", "been", "remembered", "by", "a", "long", "-", "lived", "cookie" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1635-L1642
train
delight-im/PHP-Auth
src/Auth.php
Auth.createUuid
public static function createUuid() { $data = \openssl_random_pseudo_bytes(16); // set the version to 0100 $data[6] = \chr(\ord($data[6]) & 0x0f | 0x40); // set bits 6-7 to 10 $data[8] = \chr(\ord($data[8]) & 0x3f | 0x80); return \vsprintf('%s%s-%s-%s-%s-%s%s%s', \str_split(\bin2hex($data), 4)); }
php
public static function createUuid() { $data = \openssl_random_pseudo_bytes(16); // set the version to 0100 $data[6] = \chr(\ord($data[6]) & 0x0f | 0x40); // set bits 6-7 to 10 $data[8] = \chr(\ord($data[8]) & 0x3f | 0x80); return \vsprintf('%s%s-%s-%s-%s-%s%s%s', \str_split(\bin2hex($data), 4)); }
[ "public", "static", "function", "createUuid", "(", ")", "{", "$", "data", "=", "\\", "openssl_random_pseudo_bytes", "(", "16", ")", ";", "// set the version to 0100", "$", "data", "[", "6", "]", "=", "\\", "chr", "(", "\\", "ord", "(", "$", "data", "[", "6", "]", ")", "&", "0x0f", "|", "0x40", ")", ";", "// set bits 6-7 to 10", "$", "data", "[", "8", "]", "=", "\\", "chr", "(", "\\", "ord", "(", "$", "data", "[", "8", "]", ")", "&", "0x3f", "|", "0x80", ")", ";", "return", "\\", "vsprintf", "(", "'%s%s-%s-%s-%s-%s%s%s'", ",", "\\", "str_split", "(", "\\", "bin2hex", "(", "$", "data", ")", ",", "4", ")", ")", ";", "}" ]
Creates a UUID v4 as per RFC 4122 The UUID contains 128 bits of data (where 122 are random), i.e. 36 characters @return string the UUID @author Jack @ Stack Overflow
[ "Creates", "a", "UUID", "v4", "as", "per", "RFC", "4122" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1787-L1796
train
delight-im/PHP-Auth
src/Auth.php
Auth.createCookieName
public static function createCookieName($descriptor, $seed = null) { // use the supplied seed or the current UNIX time in seconds $seed = ($seed !== null) ? $seed : \time(); foreach (self::COOKIE_PREFIXES as $cookiePrefix) { // if the seed contains a certain cookie prefix if (\strpos($seed, $cookiePrefix) === 0) { // prepend the same prefix to the descriptor $descriptor = $cookiePrefix . $descriptor; } } // generate a unique token based on the name(space) of this library and on the seed $token = Base64::encodeUrlSafeWithoutPadding( \md5( __NAMESPACE__ . "\n" . $seed, true ) ); return $descriptor . '_' . $token; }
php
public static function createCookieName($descriptor, $seed = null) { // use the supplied seed or the current UNIX time in seconds $seed = ($seed !== null) ? $seed : \time(); foreach (self::COOKIE_PREFIXES as $cookiePrefix) { // if the seed contains a certain cookie prefix if (\strpos($seed, $cookiePrefix) === 0) { // prepend the same prefix to the descriptor $descriptor = $cookiePrefix . $descriptor; } } // generate a unique token based on the name(space) of this library and on the seed $token = Base64::encodeUrlSafeWithoutPadding( \md5( __NAMESPACE__ . "\n" . $seed, true ) ); return $descriptor . '_' . $token; }
[ "public", "static", "function", "createCookieName", "(", "$", "descriptor", ",", "$", "seed", "=", "null", ")", "{", "// use the supplied seed or the current UNIX time in seconds", "$", "seed", "=", "(", "$", "seed", "!==", "null", ")", "?", "$", "seed", ":", "\\", "time", "(", ")", ";", "foreach", "(", "self", "::", "COOKIE_PREFIXES", "as", "$", "cookiePrefix", ")", "{", "// if the seed contains a certain cookie prefix", "if", "(", "\\", "strpos", "(", "$", "seed", ",", "$", "cookiePrefix", ")", "===", "0", ")", "{", "// prepend the same prefix to the descriptor", "$", "descriptor", "=", "$", "cookiePrefix", ".", "$", "descriptor", ";", "}", "}", "// generate a unique token based on the name(space) of this library and on the seed", "$", "token", "=", "Base64", "::", "encodeUrlSafeWithoutPadding", "(", "\\", "md5", "(", "__NAMESPACE__", ".", "\"\\n\"", ".", "$", "seed", ",", "true", ")", ")", ";", "return", "$", "descriptor", ".", "'_'", ".", "$", "token", ";", "}" ]
Generates a unique cookie name for the given descriptor based on the supplied seed @param string $descriptor a short label describing the purpose of the cookie, e.g. 'session' @param string|null $seed (optional) the data to deterministically generate the name from @return string
[ "Generates", "a", "unique", "cookie", "name", "for", "the", "given", "descriptor", "based", "on", "the", "supplied", "seed" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1805-L1826
train
delight-im/PHP-Auth
src/Auth.php
Auth.getRememberDirectiveSelector
private function getRememberDirectiveSelector() { if (isset($_COOKIE[$this->rememberCookieName])) { $selectorAndToken = \explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[$this->rememberCookieName], 2); return $selectorAndToken[0]; } else { return null; } }
php
private function getRememberDirectiveSelector() { if (isset($_COOKIE[$this->rememberCookieName])) { $selectorAndToken = \explode(self::COOKIE_CONTENT_SEPARATOR, $_COOKIE[$this->rememberCookieName], 2); return $selectorAndToken[0]; } else { return null; } }
[ "private", "function", "getRememberDirectiveSelector", "(", ")", "{", "if", "(", "isset", "(", "$", "_COOKIE", "[", "$", "this", "->", "rememberCookieName", "]", ")", ")", "{", "$", "selectorAndToken", "=", "\\", "explode", "(", "self", "::", "COOKIE_CONTENT_SEPARATOR", ",", "$", "_COOKIE", "[", "$", "this", "->", "rememberCookieName", "]", ",", "2", ")", ";", "return", "$", "selectorAndToken", "[", "0", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the selector of a potential locally existing remember directive @return string|null
[ "Returns", "the", "selector", "of", "a", "potential", "locally", "existing", "remember", "directive" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1846-L1855
train
delight-im/PHP-Auth
src/Auth.php
Auth.getRememberDirectiveExpiry
private function getRememberDirectiveExpiry() { // if the user is currently signed in if ($this->isLoggedIn()) { // determine the selector of any currently existing remember directive $existingSelector = $this->getRememberDirectiveSelector(); // if there is currently a remember directive whose selector we have just retrieved if (isset($existingSelector)) { // fetch the expiry date for the given selector $existingExpiry = $this->db->selectValue( 'SELECT expires FROM ' . $this->makeTableName('users_remembered') . ' WHERE selector = ? AND user = ?', [ $existingSelector, $this->getUserId() ] ); // if an expiration date has been found if (isset($existingExpiry)) { // return the date return (int) $existingExpiry; } } } return null; }
php
private function getRememberDirectiveExpiry() { // if the user is currently signed in if ($this->isLoggedIn()) { // determine the selector of any currently existing remember directive $existingSelector = $this->getRememberDirectiveSelector(); // if there is currently a remember directive whose selector we have just retrieved if (isset($existingSelector)) { // fetch the expiry date for the given selector $existingExpiry = $this->db->selectValue( 'SELECT expires FROM ' . $this->makeTableName('users_remembered') . ' WHERE selector = ? AND user = ?', [ $existingSelector, $this->getUserId() ] ); // if an expiration date has been found if (isset($existingExpiry)) { // return the date return (int) $existingExpiry; } } } return null; }
[ "private", "function", "getRememberDirectiveExpiry", "(", ")", "{", "// if the user is currently signed in", "if", "(", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "// determine the selector of any currently existing remember directive", "$", "existingSelector", "=", "$", "this", "->", "getRememberDirectiveSelector", "(", ")", ";", "// if there is currently a remember directive whose selector we have just retrieved", "if", "(", "isset", "(", "$", "existingSelector", ")", ")", "{", "// fetch the expiry date for the given selector", "$", "existingExpiry", "=", "$", "this", "->", "db", "->", "selectValue", "(", "'SELECT expires FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users_remembered'", ")", ".", "' WHERE selector = ? AND user = ?'", ",", "[", "$", "existingSelector", ",", "$", "this", "->", "getUserId", "(", ")", "]", ")", ";", "// if an expiration date has been found", "if", "(", "isset", "(", "$", "existingExpiry", ")", ")", "{", "// return the date", "return", "(", "int", ")", "$", "existingExpiry", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns the expiry date of a potential locally existing remember directive @return int|null
[ "Returns", "the", "expiry", "date", "of", "a", "potential", "locally", "existing", "remember", "directive" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Auth.php#L1862-L1888
train
delight-im/PHP-Auth
src/UserManager.php
UserManager.createRandomString
public static function createRandomString($maxLength = 24) { // calculate how many bytes of randomness we need for the specified string length $bytes = \floor((int) $maxLength / 4) * 3; // get random data $data = \openssl_random_pseudo_bytes($bytes); // return the Base64-encoded result return Base64::encodeUrlSafe($data); }
php
public static function createRandomString($maxLength = 24) { // calculate how many bytes of randomness we need for the specified string length $bytes = \floor((int) $maxLength / 4) * 3; // get random data $data = \openssl_random_pseudo_bytes($bytes); // return the Base64-encoded result return Base64::encodeUrlSafe($data); }
[ "public", "static", "function", "createRandomString", "(", "$", "maxLength", "=", "24", ")", "{", "// calculate how many bytes of randomness we need for the specified string length", "$", "bytes", "=", "\\", "floor", "(", "(", "int", ")", "$", "maxLength", "/", "4", ")", "*", "3", ";", "// get random data", "$", "data", "=", "\\", "openssl_random_pseudo_bytes", "(", "$", "bytes", ")", ";", "// return the Base64-encoded result", "return", "Base64", "::", "encodeUrlSafe", "(", "$", "data", ")", ";", "}" ]
Creates a random string with the given maximum length With the default parameter, the output should contain at least as much randomness as a UUID @param int $maxLength the maximum length of the output string (integer multiple of 4) @return string the new random string
[ "Creates", "a", "random", "string", "with", "the", "given", "maximum", "length" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/UserManager.php#L61-L70
train
delight-im/PHP-Auth
src/UserManager.php
UserManager.updatePasswordInternal
protected function updatePasswordInternal($userId, $newPassword) { $newPassword = \password_hash($newPassword, \PASSWORD_DEFAULT); try { $affected = $this->db->update( $this->makeTableNameComponents('users'), [ 'password' => $newPassword ], [ 'id' => $userId ] ); if ($affected === 0) { throw new UnknownIdException(); } } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
php
protected function updatePasswordInternal($userId, $newPassword) { $newPassword = \password_hash($newPassword, \PASSWORD_DEFAULT); try { $affected = $this->db->update( $this->makeTableNameComponents('users'), [ 'password' => $newPassword ], [ 'id' => $userId ] ); if ($affected === 0) { throw new UnknownIdException(); } } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
[ "protected", "function", "updatePasswordInternal", "(", "$", "userId", ",", "$", "newPassword", ")", "{", "$", "newPassword", "=", "\\", "password_hash", "(", "$", "newPassword", ",", "\\", "PASSWORD_DEFAULT", ")", ";", "try", "{", "$", "affected", "=", "$", "this", "->", "db", "->", "update", "(", "$", "this", "->", "makeTableNameComponents", "(", "'users'", ")", ",", "[", "'password'", "=>", "$", "newPassword", "]", ",", "[", "'id'", "=>", "$", "userId", "]", ")", ";", "if", "(", "$", "affected", "===", "0", ")", "{", "throw", "new", "UnknownIdException", "(", ")", ";", "}", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Updates the given user's password by setting it to the new specified password @param int $userId the ID of the user whose password should be updated @param string $newPassword the new password @throws UnknownIdException if no user with the specified ID has been found @throws AuthError if an internal problem occurred (do *not* catch)
[ "Updates", "the", "given", "user", "s", "password", "by", "setting", "it", "to", "the", "new", "specified", "password" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/UserManager.php#L199-L216
train
delight-im/PHP-Auth
src/UserManager.php
UserManager.onLoginSuccessful
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered) { // re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client) Session::regenerate(true); // save the user data in the session variables maintained by this library $_SESSION[self::SESSION_FIELD_LOGGED_IN] = true; $_SESSION[self::SESSION_FIELD_USER_ID] = (int) $userId; $_SESSION[self::SESSION_FIELD_EMAIL] = $email; $_SESSION[self::SESSION_FIELD_USERNAME] = $username; $_SESSION[self::SESSION_FIELD_STATUS] = (int) $status; $_SESSION[self::SESSION_FIELD_ROLES] = (int) $roles; $_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = (int) $forceLogout; $_SESSION[self::SESSION_FIELD_REMEMBERED] = $remembered; $_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time(); }
php
protected function onLoginSuccessful($userId, $email, $username, $status, $roles, $forceLogout, $remembered) { // re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client) Session::regenerate(true); // save the user data in the session variables maintained by this library $_SESSION[self::SESSION_FIELD_LOGGED_IN] = true; $_SESSION[self::SESSION_FIELD_USER_ID] = (int) $userId; $_SESSION[self::SESSION_FIELD_EMAIL] = $email; $_SESSION[self::SESSION_FIELD_USERNAME] = $username; $_SESSION[self::SESSION_FIELD_STATUS] = (int) $status; $_SESSION[self::SESSION_FIELD_ROLES] = (int) $roles; $_SESSION[self::SESSION_FIELD_FORCE_LOGOUT] = (int) $forceLogout; $_SESSION[self::SESSION_FIELD_REMEMBERED] = $remembered; $_SESSION[self::SESSION_FIELD_LAST_RESYNC] = \time(); }
[ "protected", "function", "onLoginSuccessful", "(", "$", "userId", ",", "$", "email", ",", "$", "username", ",", "$", "status", ",", "$", "roles", ",", "$", "forceLogout", ",", "$", "remembered", ")", "{", "// re-generate the session ID to prevent session fixation attacks (requests a cookie to be written on the client)", "Session", "::", "regenerate", "(", "true", ")", ";", "// save the user data in the session variables maintained by this library", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_LOGGED_IN", "]", "=", "true", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USER_ID", "]", "=", "(", "int", ")", "$", "userId", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_EMAIL", "]", "=", "$", "email", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_USERNAME", "]", "=", "$", "username", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_STATUS", "]", "=", "(", "int", ")", "$", "status", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_ROLES", "]", "=", "(", "int", ")", "$", "roles", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_FORCE_LOGOUT", "]", "=", "(", "int", ")", "$", "forceLogout", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_REMEMBERED", "]", "=", "$", "remembered", ";", "$", "_SESSION", "[", "self", "::", "SESSION_FIELD_LAST_RESYNC", "]", "=", "\\", "time", "(", ")", ";", "}" ]
Called when a user has successfully logged in This may happen via the standard login, via the "remember me" feature, or due to impersonation by administrators @param int $userId the ID of the user @param string $email the email address of the user @param string $username the display name (if any) of the user @param int $status the status of the user as one of the constants from the {@see Status} class @param int $roles the roles of the user as a bitmask using constants from the {@see Role} class @param int $forceLogout the counter that keeps track of forced logouts that need to be performed in the current session @param bool $remembered whether the user has been remembered (instead of them having authenticated actively) @throws AuthError if an internal problem occurred (do *not* catch)
[ "Called", "when", "a", "user", "has", "successfully", "logged", "in" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/UserManager.php#L232-L246
train
delight-im/PHP-Auth
src/UserManager.php
UserManager.validatePassword
protected static function validatePassword($password) { if (empty($password)) { throw new InvalidPasswordException(); } $password = \trim($password); if (\strlen($password) < 1) { throw new InvalidPasswordException(); } return $password; }
php
protected static function validatePassword($password) { if (empty($password)) { throw new InvalidPasswordException(); } $password = \trim($password); if (\strlen($password) < 1) { throw new InvalidPasswordException(); } return $password; }
[ "protected", "static", "function", "validatePassword", "(", "$", "password", ")", "{", "if", "(", "empty", "(", "$", "password", ")", ")", "{", "throw", "new", "InvalidPasswordException", "(", ")", ";", "}", "$", "password", "=", "\\", "trim", "(", "$", "password", ")", ";", "if", "(", "\\", "strlen", "(", "$", "password", ")", "<", "1", ")", "{", "throw", "new", "InvalidPasswordException", "(", ")", ";", "}", "return", "$", "password", ";", "}" ]
Validates a password @param string $password the password to validate @return string the sanitized password @throws InvalidPasswordException if the password has been invalid
[ "Validates", "a", "password" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/UserManager.php#L314-L326
train
delight-im/PHP-Auth
src/UserManager.php
UserManager.createConfirmationRequest
protected function createConfirmationRequest($userId, $email, callable $callback) { $selector = self::createRandomString(16); $token = self::createRandomString(16); $tokenHashed = \password_hash($token, \PASSWORD_DEFAULT); $expires = \time() + 60 * 60 * 24; try { $this->db->insert( $this->makeTableNameComponents('users_confirmations'), [ 'user_id' => (int) $userId, 'email' => $email, 'selector' => $selector, 'token' => $tokenHashed, 'expires' => $expires ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if (\is_callable($callback)) { $callback($selector, $token); } else { throw new MissingCallbackError(); } }
php
protected function createConfirmationRequest($userId, $email, callable $callback) { $selector = self::createRandomString(16); $token = self::createRandomString(16); $tokenHashed = \password_hash($token, \PASSWORD_DEFAULT); $expires = \time() + 60 * 60 * 24; try { $this->db->insert( $this->makeTableNameComponents('users_confirmations'), [ 'user_id' => (int) $userId, 'email' => $email, 'selector' => $selector, 'token' => $tokenHashed, 'expires' => $expires ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if (\is_callable($callback)) { $callback($selector, $token); } else { throw new MissingCallbackError(); } }
[ "protected", "function", "createConfirmationRequest", "(", "$", "userId", ",", "$", "email", ",", "callable", "$", "callback", ")", "{", "$", "selector", "=", "self", "::", "createRandomString", "(", "16", ")", ";", "$", "token", "=", "self", "::", "createRandomString", "(", "16", ")", ";", "$", "tokenHashed", "=", "\\", "password_hash", "(", "$", "token", ",", "\\", "PASSWORD_DEFAULT", ")", ";", "$", "expires", "=", "\\", "time", "(", ")", "+", "60", "*", "60", "*", "24", ";", "try", "{", "$", "this", "->", "db", "->", "insert", "(", "$", "this", "->", "makeTableNameComponents", "(", "'users_confirmations'", ")", ",", "[", "'user_id'", "=>", "(", "int", ")", "$", "userId", ",", "'email'", "=>", "$", "email", ",", "'selector'", "=>", "$", "selector", ",", "'token'", "=>", "$", "tokenHashed", ",", "'expires'", "=>", "$", "expires", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "if", "(", "\\", "is_callable", "(", "$", "callback", ")", ")", "{", "$", "callback", "(", "$", "selector", ",", "$", "token", ")", ";", "}", "else", "{", "throw", "new", "MissingCallbackError", "(", ")", ";", "}", "}" ]
Creates a request for email confirmation The callback function must have the following signature: `function ($selector, $token)` Both pieces of information must be sent to the user, usually embedded in a link When the user wants to verify their email address as a next step, both pieces will be required again @param int $userId the user's ID @param string $email the email address to verify @param callable $callback the function that sends the confirmation email to the user @throws AuthError if an internal problem occurred (do *not* catch)
[ "Creates", "a", "request", "for", "email", "confirmation" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/UserManager.php#L344-L372
train
delight-im/PHP-Auth
src/UserManager.php
UserManager.forceLogoutForUserById
protected function forceLogoutForUserById($userId) { $this->deleteRememberDirectiveForUserById($userId); $this->db->exec( 'UPDATE ' . $this->makeTableName('users') . ' SET force_logout = force_logout + 1 WHERE id = ?', [ $userId ] ); }
php
protected function forceLogoutForUserById($userId) { $this->deleteRememberDirectiveForUserById($userId); $this->db->exec( 'UPDATE ' . $this->makeTableName('users') . ' SET force_logout = force_logout + 1 WHERE id = ?', [ $userId ] ); }
[ "protected", "function", "forceLogoutForUserById", "(", "$", "userId", ")", "{", "$", "this", "->", "deleteRememberDirectiveForUserById", "(", "$", "userId", ")", ";", "$", "this", "->", "db", "->", "exec", "(", "'UPDATE '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' SET force_logout = force_logout + 1 WHERE id = ?'", ",", "[", "$", "userId", "]", ")", ";", "}" ]
Triggers a forced logout in all sessions that belong to the specified user @param int $userId the ID of the user to sign out @throws AuthError if an internal problem occurred (do *not* catch)
[ "Triggers", "a", "forced", "logout", "in", "all", "sessions", "that", "belong", "to", "the", "specified", "user" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/UserManager.php#L407-L413
train
delight-im/PHP-Auth
src/Administration.php
Administration.createUserWithUniqueUsername
public function createUserWithUniqueUsername($email, $password, $username = null) { return $this->createUserInternal(true, $email, $password, $username, null); }
php
public function createUserWithUniqueUsername($email, $password, $username = null) { return $this->createUserInternal(true, $email, $password, $username, null); }
[ "public", "function", "createUserWithUniqueUsername", "(", "$", "email", ",", "$", "password", ",", "$", "username", "=", "null", ")", "{", "return", "$", "this", "->", "createUserInternal", "(", "true", ",", "$", "email", ",", "$", "password", ",", "$", "username", ",", "null", ")", ";", "}" ]
Creates a new user while ensuring that the username is unique @param string $email the email address to register @param string $password the password for the new account @param string|null $username (optional) the username that will be displayed @return int the ID of the user that has been created (if any) @throws InvalidEmailException if the email address was invalid @throws InvalidPasswordException if the password was invalid @throws UserAlreadyExistsException if a user with the specified email address already exists @throws DuplicateUsernameException if the specified username wasn't unique @throws AuthError if an internal problem occurred (do *not* catch)
[ "Creates", "a", "new", "user", "while", "ensuring", "that", "the", "username", "is", "unique" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L58-L60
train
delight-im/PHP-Auth
src/Administration.php
Administration.deleteUserByEmail
public function deleteUserByEmail($email) { $email = self::validateEmailAddress($email); $numberOfDeletedUsers = $this->deleteUsersByColumnValue('email', $email); if ($numberOfDeletedUsers === 0) { throw new InvalidEmailException(); } }
php
public function deleteUserByEmail($email) { $email = self::validateEmailAddress($email); $numberOfDeletedUsers = $this->deleteUsersByColumnValue('email', $email); if ($numberOfDeletedUsers === 0) { throw new InvalidEmailException(); } }
[ "public", "function", "deleteUserByEmail", "(", "$", "email", ")", "{", "$", "email", "=", "self", "::", "validateEmailAddress", "(", "$", "email", ")", ";", "$", "numberOfDeletedUsers", "=", "$", "this", "->", "deleteUsersByColumnValue", "(", "'email'", ",", "$", "email", ")", ";", "if", "(", "$", "numberOfDeletedUsers", "===", "0", ")", "{", "throw", "new", "InvalidEmailException", "(", ")", ";", "}", "}" ]
Deletes the user with the specified email address This action cannot be undone @param string $email the email address of the user to delete @throws InvalidEmailException if no user with the specified email address has been found @throws AuthError if an internal problem occurred (do *not* catch)
[ "Deletes", "the", "user", "with", "the", "specified", "email", "address" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L88-L96
train
delight-im/PHP-Auth
src/Administration.php
Administration.deleteUserByUsername
public function deleteUserByUsername($username) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->deleteUsersByColumnValue('id', (int) $userData['id']); }
php
public function deleteUserByUsername($username) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->deleteUsersByColumnValue('id', (int) $userData['id']); }
[ "public", "function", "deleteUserByUsername", "(", "$", "username", ")", "{", "$", "userData", "=", "$", "this", "->", "getUserDataByUsername", "(", "\\", "trim", "(", "$", "username", ")", ",", "[", "'id'", "]", ")", ";", "$", "this", "->", "deleteUsersByColumnValue", "(", "'id'", ",", "(", "int", ")", "$", "userData", "[", "'id'", "]", ")", ";", "}" ]
Deletes the user with the specified username This action cannot be undone @param string $username the username of the user to delete @throws UnknownUsernameException if no user with the specified username has been found @throws AmbiguousUsernameException if multiple users with the specified username have been found @throws AuthError if an internal problem occurred (do *not* catch)
[ "Deletes", "the", "user", "with", "the", "specified", "username" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L108-L115
train
delight-im/PHP-Auth
src/Administration.php
Administration.addRoleForUserById
public function addRoleForUserById($userId, $role) { $userFound = $this->addRoleForUserByColumnValue( 'id', (int) $userId, $role ); if ($userFound === false) { throw new UnknownIdException(); } }
php
public function addRoleForUserById($userId, $role) { $userFound = $this->addRoleForUserByColumnValue( 'id', (int) $userId, $role ); if ($userFound === false) { throw new UnknownIdException(); } }
[ "public", "function", "addRoleForUserById", "(", "$", "userId", ",", "$", "role", ")", "{", "$", "userFound", "=", "$", "this", "->", "addRoleForUserByColumnValue", "(", "'id'", ",", "(", "int", ")", "$", "userId", ",", "$", "role", ")", ";", "if", "(", "$", "userFound", "===", "false", ")", "{", "throw", "new", "UnknownIdException", "(", ")", ";", "}", "}" ]
Assigns the specified role to the user with the given ID A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) @param int $userId the ID of the user to assign the role to @param int $role the role as one of the constants from the {@see Role} class @throws UnknownIdException if no user with the specified ID has been found @see Role
[ "Assigns", "the", "specified", "role", "to", "the", "user", "with", "the", "given", "ID" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L128-L138
train
delight-im/PHP-Auth
src/Administration.php
Administration.addRoleForUserByEmail
public function addRoleForUserByEmail($userEmail, $role) { $userEmail = self::validateEmailAddress($userEmail); $userFound = $this->addRoleForUserByColumnValue( 'email', $userEmail, $role ); if ($userFound === false) { throw new InvalidEmailException(); } }
php
public function addRoleForUserByEmail($userEmail, $role) { $userEmail = self::validateEmailAddress($userEmail); $userFound = $this->addRoleForUserByColumnValue( 'email', $userEmail, $role ); if ($userFound === false) { throw new InvalidEmailException(); } }
[ "public", "function", "addRoleForUserByEmail", "(", "$", "userEmail", ",", "$", "role", ")", "{", "$", "userEmail", "=", "self", "::", "validateEmailAddress", "(", "$", "userEmail", ")", ";", "$", "userFound", "=", "$", "this", "->", "addRoleForUserByColumnValue", "(", "'email'", ",", "$", "userEmail", ",", "$", "role", ")", ";", "if", "(", "$", "userFound", "===", "false", ")", "{", "throw", "new", "InvalidEmailException", "(", ")", ";", "}", "}" ]
Assigns the specified role to the user with the given email address A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) @param string $userEmail the email address of the user to assign the role to @param int $role the role as one of the constants from the {@see Role} class @throws InvalidEmailException if no user with the specified email address has been found @see Role
[ "Assigns", "the", "specified", "role", "to", "the", "user", "with", "the", "given", "email", "address" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L151-L163
train
delight-im/PHP-Auth
src/Administration.php
Administration.addRoleForUserByUsername
public function addRoleForUserByUsername($username, $role) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->addRoleForUserByColumnValue( 'id', (int) $userData['id'], $role ); }
php
public function addRoleForUserByUsername($username, $role) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->addRoleForUserByColumnValue( 'id', (int) $userData['id'], $role ); }
[ "public", "function", "addRoleForUserByUsername", "(", "$", "username", ",", "$", "role", ")", "{", "$", "userData", "=", "$", "this", "->", "getUserDataByUsername", "(", "\\", "trim", "(", "$", "username", ")", ",", "[", "'id'", "]", ")", ";", "$", "this", "->", "addRoleForUserByColumnValue", "(", "'id'", ",", "(", "int", ")", "$", "userData", "[", "'id'", "]", ",", "$", "role", ")", ";", "}" ]
Assigns the specified role to the user with the given username A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) @param string $username the username of the user to assign the role to @param int $role the role as one of the constants from the {@see Role} class @throws UnknownUsernameException if no user with the specified username has been found @throws AmbiguousUsernameException if multiple users with the specified username have been found @see Role
[ "Assigns", "the", "specified", "role", "to", "the", "user", "with", "the", "given", "username" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L177-L188
train
delight-im/PHP-Auth
src/Administration.php
Administration.removeRoleForUserById
public function removeRoleForUserById($userId, $role) { $userFound = $this->removeRoleForUserByColumnValue( 'id', (int) $userId, $role ); if ($userFound === false) { throw new UnknownIdException(); } }
php
public function removeRoleForUserById($userId, $role) { $userFound = $this->removeRoleForUserByColumnValue( 'id', (int) $userId, $role ); if ($userFound === false) { throw new UnknownIdException(); } }
[ "public", "function", "removeRoleForUserById", "(", "$", "userId", ",", "$", "role", ")", "{", "$", "userFound", "=", "$", "this", "->", "removeRoleForUserByColumnValue", "(", "'id'", ",", "(", "int", ")", "$", "userId", ",", "$", "role", ")", ";", "if", "(", "$", "userFound", "===", "false", ")", "{", "throw", "new", "UnknownIdException", "(", ")", ";", "}", "}" ]
Takes away the specified role from the user with the given ID A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) @param int $userId the ID of the user to take the role away from @param int $role the role as one of the constants from the {@see Role} class @throws UnknownIdException if no user with the specified ID has been found @see Role
[ "Takes", "away", "the", "specified", "role", "from", "the", "user", "with", "the", "given", "ID" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L201-L211
train
delight-im/PHP-Auth
src/Administration.php
Administration.removeRoleForUserByEmail
public function removeRoleForUserByEmail($userEmail, $role) { $userEmail = self::validateEmailAddress($userEmail); $userFound = $this->removeRoleForUserByColumnValue( 'email', $userEmail, $role ); if ($userFound === false) { throw new InvalidEmailException(); } }
php
public function removeRoleForUserByEmail($userEmail, $role) { $userEmail = self::validateEmailAddress($userEmail); $userFound = $this->removeRoleForUserByColumnValue( 'email', $userEmail, $role ); if ($userFound === false) { throw new InvalidEmailException(); } }
[ "public", "function", "removeRoleForUserByEmail", "(", "$", "userEmail", ",", "$", "role", ")", "{", "$", "userEmail", "=", "self", "::", "validateEmailAddress", "(", "$", "userEmail", ")", ";", "$", "userFound", "=", "$", "this", "->", "removeRoleForUserByColumnValue", "(", "'email'", ",", "$", "userEmail", ",", "$", "role", ")", ";", "if", "(", "$", "userFound", "===", "false", ")", "{", "throw", "new", "InvalidEmailException", "(", ")", ";", "}", "}" ]
Takes away the specified role from the user with the given email address A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) @param string $userEmail the email address of the user to take the role away from @param int $role the role as one of the constants from the {@see Role} class @throws InvalidEmailException if no user with the specified email address has been found @see Role
[ "Takes", "away", "the", "specified", "role", "from", "the", "user", "with", "the", "given", "email", "address" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L224-L236
train
delight-im/PHP-Auth
src/Administration.php
Administration.removeRoleForUserByUsername
public function removeRoleForUserByUsername($username, $role) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->removeRoleForUserByColumnValue( 'id', (int) $userData['id'], $role ); }
php
public function removeRoleForUserByUsername($username, $role) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->removeRoleForUserByColumnValue( 'id', (int) $userData['id'], $role ); }
[ "public", "function", "removeRoleForUserByUsername", "(", "$", "username", ",", "$", "role", ")", "{", "$", "userData", "=", "$", "this", "->", "getUserDataByUsername", "(", "\\", "trim", "(", "$", "username", ")", ",", "[", "'id'", "]", ")", ";", "$", "this", "->", "removeRoleForUserByColumnValue", "(", "'id'", ",", "(", "int", ")", "$", "userData", "[", "'id'", "]", ",", "$", "role", ")", ";", "}" ]
Takes away the specified role from the user with the given username A user may have any number of roles (i.e. no role at all, a single role, or any combination of roles) @param string $username the username of the user to take the role away from @param int $role the role as one of the constants from the {@see Role} class @throws UnknownUsernameException if no user with the specified username has been found @throws AmbiguousUsernameException if multiple users with the specified username have been found @see Role
[ "Takes", "away", "the", "specified", "role", "from", "the", "user", "with", "the", "given", "username" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L250-L261
train
delight-im/PHP-Auth
src/Administration.php
Administration.doesUserHaveRole
public function doesUserHaveRole($userId, $role) { if (empty($role) || !\is_numeric($role)) { return false; } $userId = (int) $userId; $rolesBitmask = $this->db->selectValue( 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $userId ] ); if ($rolesBitmask === null) { throw new UnknownIdException(); } $role = (int) $role; return ($rolesBitmask & $role) === $role; }
php
public function doesUserHaveRole($userId, $role) { if (empty($role) || !\is_numeric($role)) { return false; } $userId = (int) $userId; $rolesBitmask = $this->db->selectValue( 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $userId ] ); if ($rolesBitmask === null) { throw new UnknownIdException(); } $role = (int) $role; return ($rolesBitmask & $role) === $role; }
[ "public", "function", "doesUserHaveRole", "(", "$", "userId", ",", "$", "role", ")", "{", "if", "(", "empty", "(", "$", "role", ")", "||", "!", "\\", "is_numeric", "(", "$", "role", ")", ")", "{", "return", "false", ";", "}", "$", "userId", "=", "(", "int", ")", "$", "userId", ";", "$", "rolesBitmask", "=", "$", "this", "->", "db", "->", "selectValue", "(", "'SELECT roles_mask FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' WHERE id = ?'", ",", "[", "$", "userId", "]", ")", ";", "if", "(", "$", "rolesBitmask", "===", "null", ")", "{", "throw", "new", "UnknownIdException", "(", ")", ";", "}", "$", "role", "=", "(", "int", ")", "$", "role", ";", "return", "(", "$", "rolesBitmask", "&", "$", "role", ")", "===", "$", "role", ";", "}" ]
Returns whether the user with the given ID has the specified role @param int $userId the ID of the user to check the roles for @param int $role the role as one of the constants from the {@see Role} class @return bool @throws UnknownIdException if no user with the specified ID has been found @see Role
[ "Returns", "whether", "the", "user", "with", "the", "given", "ID", "has", "the", "specified", "role" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L273-L292
train
delight-im/PHP-Auth
src/Administration.php
Administration.getRolesForUserById
public function getRolesForUserById($userId) { $userId = (int) $userId; $rolesBitmask = $this->db->selectValue( 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $userId ] ); if ($rolesBitmask === null) { throw new UnknownIdException(); } return \array_filter( Role::getMap(), function ($each) use ($rolesBitmask) { return ($rolesBitmask & $each) === $each; }, \ARRAY_FILTER_USE_KEY ); }
php
public function getRolesForUserById($userId) { $userId = (int) $userId; $rolesBitmask = $this->db->selectValue( 'SELECT roles_mask FROM ' . $this->makeTableName('users') . ' WHERE id = ?', [ $userId ] ); if ($rolesBitmask === null) { throw new UnknownIdException(); } return \array_filter( Role::getMap(), function ($each) use ($rolesBitmask) { return ($rolesBitmask & $each) === $each; }, \ARRAY_FILTER_USE_KEY ); }
[ "public", "function", "getRolesForUserById", "(", "$", "userId", ")", "{", "$", "userId", "=", "(", "int", ")", "$", "userId", ";", "$", "rolesBitmask", "=", "$", "this", "->", "db", "->", "selectValue", "(", "'SELECT roles_mask FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' WHERE id = ?'", ",", "[", "$", "userId", "]", ")", ";", "if", "(", "$", "rolesBitmask", "===", "null", ")", "{", "throw", "new", "UnknownIdException", "(", ")", ";", "}", "return", "\\", "array_filter", "(", "Role", "::", "getMap", "(", ")", ",", "function", "(", "$", "each", ")", "use", "(", "$", "rolesBitmask", ")", "{", "return", "(", "$", "rolesBitmask", "&", "$", "each", ")", "===", "$", "each", ";", "}", ",", "\\", "ARRAY_FILTER_USE_KEY", ")", ";", "}" ]
Returns the roles of the user with the given ID, mapping the numerical values to their descriptive names @param int $userId the ID of the user to return the roles for @return array @throws UnknownIdException if no user with the specified ID has been found @see Role
[ "Returns", "the", "roles", "of", "the", "user", "with", "the", "given", "ID", "mapping", "the", "numerical", "values", "to", "their", "descriptive", "names" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L303-L322
train
delight-im/PHP-Auth
src/Administration.php
Administration.logInAsUserByEmail
public function logInAsUserByEmail($email) { $email = self::validateEmailAddress($email); $numberOfMatchedUsers = $this->logInAsUserByColumnValue('email', $email); if ($numberOfMatchedUsers === 0) { throw new InvalidEmailException(); } }
php
public function logInAsUserByEmail($email) { $email = self::validateEmailAddress($email); $numberOfMatchedUsers = $this->logInAsUserByColumnValue('email', $email); if ($numberOfMatchedUsers === 0) { throw new InvalidEmailException(); } }
[ "public", "function", "logInAsUserByEmail", "(", "$", "email", ")", "{", "$", "email", "=", "self", "::", "validateEmailAddress", "(", "$", "email", ")", ";", "$", "numberOfMatchedUsers", "=", "$", "this", "->", "logInAsUserByColumnValue", "(", "'email'", ",", "$", "email", ")", ";", "if", "(", "$", "numberOfMatchedUsers", "===", "0", ")", "{", "throw", "new", "InvalidEmailException", "(", ")", ";", "}", "}" ]
Signs in as the user with the specified email address @param string $email the email address of the user to sign in as @throws InvalidEmailException if no user with the specified email address has been found @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet @throws AuthError if an internal problem occurred (do *not* catch)
[ "Signs", "in", "as", "the", "user", "with", "the", "specified", "email", "address" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L348-L356
train
delight-im/PHP-Auth
src/Administration.php
Administration.logInAsUserByUsername
public function logInAsUserByUsername($username) { $numberOfMatchedUsers = $this->logInAsUserByColumnValue('username', \trim($username)); if ($numberOfMatchedUsers === 0) { throw new UnknownUsernameException(); } elseif ($numberOfMatchedUsers > 1) { throw new AmbiguousUsernameException(); } }
php
public function logInAsUserByUsername($username) { $numberOfMatchedUsers = $this->logInAsUserByColumnValue('username', \trim($username)); if ($numberOfMatchedUsers === 0) { throw new UnknownUsernameException(); } elseif ($numberOfMatchedUsers > 1) { throw new AmbiguousUsernameException(); } }
[ "public", "function", "logInAsUserByUsername", "(", "$", "username", ")", "{", "$", "numberOfMatchedUsers", "=", "$", "this", "->", "logInAsUserByColumnValue", "(", "'username'", ",", "\\", "trim", "(", "$", "username", ")", ")", ";", "if", "(", "$", "numberOfMatchedUsers", "===", "0", ")", "{", "throw", "new", "UnknownUsernameException", "(", ")", ";", "}", "elseif", "(", "$", "numberOfMatchedUsers", ">", "1", ")", "{", "throw", "new", "AmbiguousUsernameException", "(", ")", ";", "}", "}" ]
Signs in as the user with the specified display name @param string $username the display name of the user to sign in as @throws UnknownUsernameException if no user with the specified username has been found @throws AmbiguousUsernameException if multiple users with the specified username have been found @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet @throws AuthError if an internal problem occurred (do *not* catch)
[ "Signs", "in", "as", "the", "user", "with", "the", "specified", "display", "name" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L367-L376
train
delight-im/PHP-Auth
src/Administration.php
Administration.changePasswordForUserById
public function changePasswordForUserById($userId, $newPassword) { $userId = (int) $userId; $newPassword = self::validatePassword($newPassword); $this->updatePasswordInternal( $userId, $newPassword ); $this->forceLogoutForUserById($userId); }
php
public function changePasswordForUserById($userId, $newPassword) { $userId = (int) $userId; $newPassword = self::validatePassword($newPassword); $this->updatePasswordInternal( $userId, $newPassword ); $this->forceLogoutForUserById($userId); }
[ "public", "function", "changePasswordForUserById", "(", "$", "userId", ",", "$", "newPassword", ")", "{", "$", "userId", "=", "(", "int", ")", "$", "userId", ";", "$", "newPassword", "=", "self", "::", "validatePassword", "(", "$", "newPassword", ")", ";", "$", "this", "->", "updatePasswordInternal", "(", "$", "userId", ",", "$", "newPassword", ")", ";", "$", "this", "->", "forceLogoutForUserById", "(", "$", "userId", ")", ";", "}" ]
Changes the password for the user with the given ID @param int $userId the ID of the user whose password to change @param string $newPassword the new password to set @throws UnknownIdException if no user with the specified ID has been found @throws InvalidPasswordException if the desired new password has been invalid @throws AuthError if an internal problem occurred (do *not* catch)
[ "Changes", "the", "password", "for", "the", "user", "with", "the", "given", "ID" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L387-L397
train
delight-im/PHP-Auth
src/Administration.php
Administration.changePasswordForUserByUsername
public function changePasswordForUserByUsername($username, $newPassword) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->changePasswordForUserById( (int) $userData['id'], $newPassword ); }
php
public function changePasswordForUserByUsername($username, $newPassword) { $userData = $this->getUserDataByUsername( \trim($username), [ 'id' ] ); $this->changePasswordForUserById( (int) $userData['id'], $newPassword ); }
[ "public", "function", "changePasswordForUserByUsername", "(", "$", "username", ",", "$", "newPassword", ")", "{", "$", "userData", "=", "$", "this", "->", "getUserDataByUsername", "(", "\\", "trim", "(", "$", "username", ")", ",", "[", "'id'", "]", ")", ";", "$", "this", "->", "changePasswordForUserById", "(", "(", "int", ")", "$", "userData", "[", "'id'", "]", ",", "$", "newPassword", ")", ";", "}" ]
Changes the password for the user with the given username @param string $username the username of the user whose password to change @param string $newPassword the new password to set @throws UnknownUsernameException if no user with the specified username has been found @throws AmbiguousUsernameException if multiple users with the specified username have been found @throws InvalidPasswordException if the desired new password has been invalid @throws AuthError if an internal problem occurred (do *not* catch)
[ "Changes", "the", "password", "for", "the", "user", "with", "the", "given", "username" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L409-L419
train
delight-im/PHP-Auth
src/Administration.php
Administration.deleteUsersByColumnValue
private function deleteUsersByColumnValue($columnName, $columnValue) { try { return $this->db->delete( $this->makeTableNameComponents('users'), [ $columnName => $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
php
private function deleteUsersByColumnValue($columnName, $columnValue) { try { return $this->db->delete( $this->makeTableNameComponents('users'), [ $columnName => $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
[ "private", "function", "deleteUsersByColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ")", "{", "try", "{", "return", "$", "this", "->", "db", "->", "delete", "(", "$", "this", "->", "makeTableNameComponents", "(", "'users'", ")", ",", "[", "$", "columnName", "=>", "$", "columnValue", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Deletes all existing users where the column with the specified name has the given value You must never pass untrusted input to the parameter that takes the column name @param string $columnName the name of the column to filter by @param mixed $columnValue the value to look for in the selected column @return int the number of deleted users @throws AuthError if an internal problem occurred (do *not* catch)
[ "Deletes", "all", "existing", "users", "where", "the", "column", "with", "the", "specified", "name", "has", "the", "given", "value" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L431-L443
train
delight-im/PHP-Auth
src/Administration.php
Administration.modifyRolesForUserByColumnValue
private function modifyRolesForUserByColumnValue($columnName, $columnValue, callable $modification) { try { $userData = $this->db->selectRow( 'SELECT id, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ?', [ $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if ($userData === null) { return false; } $newRolesBitmask = $modification($userData['roles_mask']); try { $this->db->exec( 'UPDATE ' . $this->makeTableName('users') . ' SET roles_mask = ? WHERE id = ?', [ $newRolesBitmask, (int) $userData['id'] ] ); return true; } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
php
private function modifyRolesForUserByColumnValue($columnName, $columnValue, callable $modification) { try { $userData = $this->db->selectRow( 'SELECT id, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ?', [ $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } if ($userData === null) { return false; } $newRolesBitmask = $modification($userData['roles_mask']); try { $this->db->exec( 'UPDATE ' . $this->makeTableName('users') . ' SET roles_mask = ? WHERE id = ?', [ $newRolesBitmask, (int) $userData['id'] ] ); return true; } catch (Error $e) { throw new DatabaseError($e->getMessage()); } }
[ "private", "function", "modifyRolesForUserByColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ",", "callable", "$", "modification", ")", "{", "try", "{", "$", "userData", "=", "$", "this", "->", "db", "->", "selectRow", "(", "'SELECT id, roles_mask FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' WHERE '", ".", "$", "columnName", ".", "' = ?'", ",", "[", "$", "columnValue", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "if", "(", "$", "userData", "===", "null", ")", "{", "return", "false", ";", "}", "$", "newRolesBitmask", "=", "$", "modification", "(", "$", "userData", "[", "'roles_mask'", "]", ")", ";", "try", "{", "$", "this", "->", "db", "->", "exec", "(", "'UPDATE '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' SET roles_mask = ? WHERE id = ?'", ",", "[", "$", "newRolesBitmask", ",", "(", "int", ")", "$", "userData", "[", "'id'", "]", "]", ")", ";", "return", "true", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Modifies the roles for the user where the column with the specified name has the given value You must never pass untrusted input to the parameter that takes the column name @param string $columnName the name of the column to filter by @param mixed $columnValue the value to look for in the selected column @param callable $modification the modification to apply to the existing bitmask of roles @return bool whether any user with the given column constraints has been found @throws AuthError if an internal problem occurred (do *not* catch) @see Role
[ "Modifies", "the", "roles", "for", "the", "user", "where", "the", "column", "with", "the", "specified", "name", "has", "the", "given", "value" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L458-L489
train
delight-im/PHP-Auth
src/Administration.php
Administration.addRoleForUserByColumnValue
private function addRoleForUserByColumnValue($columnName, $columnValue, $role) { $role = (int) $role; return $this->modifyRolesForUserByColumnValue( $columnName, $columnValue, function ($oldRolesBitmask) use ($role) { return $oldRolesBitmask | $role; } ); }
php
private function addRoleForUserByColumnValue($columnName, $columnValue, $role) { $role = (int) $role; return $this->modifyRolesForUserByColumnValue( $columnName, $columnValue, function ($oldRolesBitmask) use ($role) { return $oldRolesBitmask | $role; } ); }
[ "private", "function", "addRoleForUserByColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ",", "$", "role", ")", "{", "$", "role", "=", "(", "int", ")", "$", "role", ";", "return", "$", "this", "->", "modifyRolesForUserByColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ",", "function", "(", "$", "oldRolesBitmask", ")", "use", "(", "$", "role", ")", "{", "return", "$", "oldRolesBitmask", "|", "$", "role", ";", "}", ")", ";", "}" ]
Assigns the specified role to the user where the column with the specified name has the given value You must never pass untrusted input to the parameter that takes the column name @param string $columnName the name of the column to filter by @param mixed $columnValue the value to look for in the selected column @param int $role the role as one of the constants from the {@see Role} class @return bool whether any user with the given column constraints has been found @see Role
[ "Assigns", "the", "specified", "role", "to", "the", "user", "where", "the", "column", "with", "the", "specified", "name", "has", "the", "given", "value" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L503-L513
train
delight-im/PHP-Auth
src/Administration.php
Administration.removeRoleForUserByColumnValue
private function removeRoleForUserByColumnValue($columnName, $columnValue, $role) { $role = (int) $role; return $this->modifyRolesForUserByColumnValue( $columnName, $columnValue, function ($oldRolesBitmask) use ($role) { return $oldRolesBitmask & ~$role; } ); }
php
private function removeRoleForUserByColumnValue($columnName, $columnValue, $role) { $role = (int) $role; return $this->modifyRolesForUserByColumnValue( $columnName, $columnValue, function ($oldRolesBitmask) use ($role) { return $oldRolesBitmask & ~$role; } ); }
[ "private", "function", "removeRoleForUserByColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ",", "$", "role", ")", "{", "$", "role", "=", "(", "int", ")", "$", "role", ";", "return", "$", "this", "->", "modifyRolesForUserByColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ",", "function", "(", "$", "oldRolesBitmask", ")", "use", "(", "$", "role", ")", "{", "return", "$", "oldRolesBitmask", "&", "~", "$", "role", ";", "}", ")", ";", "}" ]
Takes away the specified role from the user where the column with the specified name has the given value You must never pass untrusted input to the parameter that takes the column name @param string $columnName the name of the column to filter by @param mixed $columnValue the value to look for in the selected column @param int $role the role as one of the constants from the {@see Role} class @return bool whether any user with the given column constraints has been found @see Role
[ "Takes", "away", "the", "specified", "role", "from", "the", "user", "where", "the", "column", "with", "the", "specified", "name", "has", "the", "given", "value" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L527-L537
train
delight-im/PHP-Auth
src/Administration.php
Administration.logInAsUserByColumnValue
private function logInAsUserByColumnValue($columnName, $columnValue) { try { $users = $this->db->select( 'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0', [ $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } $numberOfMatchingUsers = ($users !== null) ? \count($users) : 0; if ($numberOfMatchingUsers === 1) { $user = $users[0]; if ((int) $user['verified'] === 1) { $this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], \PHP_INT_MAX, false); } else { throw new EmailNotVerifiedException(); } } return $numberOfMatchingUsers; }
php
private function logInAsUserByColumnValue($columnName, $columnValue) { try { $users = $this->db->select( 'SELECT verified, id, email, username, status, roles_mask FROM ' . $this->makeTableName('users') . ' WHERE ' . $columnName . ' = ? LIMIT 2 OFFSET 0', [ $columnValue ] ); } catch (Error $e) { throw new DatabaseError($e->getMessage()); } $numberOfMatchingUsers = ($users !== null) ? \count($users) : 0; if ($numberOfMatchingUsers === 1) { $user = $users[0]; if ((int) $user['verified'] === 1) { $this->onLoginSuccessful($user['id'], $user['email'], $user['username'], $user['status'], $user['roles_mask'], \PHP_INT_MAX, false); } else { throw new EmailNotVerifiedException(); } } return $numberOfMatchingUsers; }
[ "private", "function", "logInAsUserByColumnValue", "(", "$", "columnName", ",", "$", "columnValue", ")", "{", "try", "{", "$", "users", "=", "$", "this", "->", "db", "->", "select", "(", "'SELECT verified, id, email, username, status, roles_mask FROM '", ".", "$", "this", "->", "makeTableName", "(", "'users'", ")", ".", "' WHERE '", ".", "$", "columnName", ".", "' = ? LIMIT 2 OFFSET 0'", ",", "[", "$", "columnValue", "]", ")", ";", "}", "catch", "(", "Error", "$", "e", ")", "{", "throw", "new", "DatabaseError", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "$", "numberOfMatchingUsers", "=", "(", "$", "users", "!==", "null", ")", "?", "\\", "count", "(", "$", "users", ")", ":", "0", ";", "if", "(", "$", "numberOfMatchingUsers", "===", "1", ")", "{", "$", "user", "=", "$", "users", "[", "0", "]", ";", "if", "(", "(", "int", ")", "$", "user", "[", "'verified'", "]", "===", "1", ")", "{", "$", "this", "->", "onLoginSuccessful", "(", "$", "user", "[", "'id'", "]", ",", "$", "user", "[", "'email'", "]", ",", "$", "user", "[", "'username'", "]", ",", "$", "user", "[", "'status'", "]", ",", "$", "user", "[", "'roles_mask'", "]", ",", "\\", "PHP_INT_MAX", ",", "false", ")", ";", "}", "else", "{", "throw", "new", "EmailNotVerifiedException", "(", ")", ";", "}", "}", "return", "$", "numberOfMatchingUsers", ";", "}" ]
Signs in as the user for which the column with the specified name has the given value You must never pass untrusted input to the parameter that takes the column name @param string $columnName the name of the column to filter by @param mixed $columnValue the value to look for in the selected column @return int the number of matched users (where only a value of one means that the login may have been successful) @throws EmailNotVerifiedException if the user has not verified their email address via a confirmation method yet @throws AuthError if an internal problem occurred (do *not* catch)
[ "Signs", "in", "as", "the", "user", "for", "which", "the", "column", "with", "the", "specified", "name", "has", "the", "given", "value" ]
4b3f2ab91c52958d1ae21651679372c3d3b2a0b3
https://github.com/delight-im/PHP-Auth/blob/4b3f2ab91c52958d1ae21651679372c3d3b2a0b3/src/Administration.php#L550-L575
train
teamtnt/tntsearch
src/Support/Highlighter.php
Highlighter._extractLocations
public function _extractLocations($words, $fulltext) { $locations = array(); foreach ($words as $word) { $wordlen = strlen($word); $loc = stripos($fulltext, $word); while ($loc !== false) { $locations[] = $loc; $loc = stripos($fulltext, $word, $loc + $wordlen); } } $locations = array_unique($locations); sort($locations); return $locations; }
php
public function _extractLocations($words, $fulltext) { $locations = array(); foreach ($words as $word) { $wordlen = strlen($word); $loc = stripos($fulltext, $word); while ($loc !== false) { $locations[] = $loc; $loc = stripos($fulltext, $word, $loc + $wordlen); } } $locations = array_unique($locations); sort($locations); return $locations; }
[ "public", "function", "_extractLocations", "(", "$", "words", ",", "$", "fulltext", ")", "{", "$", "locations", "=", "array", "(", ")", ";", "foreach", "(", "$", "words", "as", "$", "word", ")", "{", "$", "wordlen", "=", "strlen", "(", "$", "word", ")", ";", "$", "loc", "=", "stripos", "(", "$", "fulltext", ",", "$", "word", ")", ";", "while", "(", "$", "loc", "!==", "false", ")", "{", "$", "locations", "[", "]", "=", "$", "loc", ";", "$", "loc", "=", "stripos", "(", "$", "fulltext", ",", "$", "word", ",", "$", "loc", "+", "$", "wordlen", ")", ";", "}", "}", "$", "locations", "=", "array_unique", "(", "$", "locations", ")", ";", "sort", "(", "$", "locations", ")", ";", "return", "$", "locations", ";", "}" ]
find the locations of each of the words Nothing exciting here. The array_unique is required unless you decide to make the words unique before passing in @param $words @param $fulltext @return array
[ "find", "the", "locations", "of", "each", "of", "the", "words", "Nothing", "exciting", "here", ".", "The", "array_unique", "is", "required", "unless", "you", "decide", "to", "make", "the", "words", "unique", "before", "passing", "in" ]
e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf
https://github.com/teamtnt/tntsearch/blob/e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf/src/Support/Highlighter.php#L92-L107
train
teamtnt/tntsearch
src/Stemmer/PorterStemmer.php
PorterStemmer.m
private static function m($str) { $c = self::$regex_consonant; $v = self::$regex_vowel; $str = preg_replace("#^$c+#", '', $str); $str = preg_replace("#$v+$#", '', $str); preg_match_all("#($v+$c+)#", $str, $matches); return count($matches[1]); }
php
private static function m($str) { $c = self::$regex_consonant; $v = self::$regex_vowel; $str = preg_replace("#^$c+#", '', $str); $str = preg_replace("#$v+$#", '', $str); preg_match_all("#($v+$c+)#", $str, $matches); return count($matches[1]); }
[ "private", "static", "function", "m", "(", "$", "str", ")", "{", "$", "c", "=", "self", "::", "$", "regex_consonant", ";", "$", "v", "=", "self", "::", "$", "regex_vowel", ";", "$", "str", "=", "preg_replace", "(", "\"#^$c+#\"", ",", "''", ",", "$", "str", ")", ";", "$", "str", "=", "preg_replace", "(", "\"#$v+$#\"", ",", "''", ",", "$", "str", ")", ";", "preg_match_all", "(", "\"#($v+$c+)#\"", ",", "$", "str", ",", "$", "matches", ")", ";", "return", "count", "(", "$", "matches", "[", "1", "]", ")", ";", "}" ]
What, you mean it's not obvious from the name? m() measures the number of consonant sequences in $str. if c is a consonant sequence and v a vowel sequence, and <..> indicates arbitrary presence, <c><v> gives 0 <c>vc<v> gives 1 <c>vcvc<v> gives 2 <c>vcvcvc<v> gives 3 @param string $str The string to return the m count for @return int The m count
[ "What", "you", "mean", "it", "s", "not", "obvious", "from", "the", "name?" ]
e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf
https://github.com/teamtnt/tntsearch/blob/e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf/src/Stemmer/PorterStemmer.php#L372-L383
train
teamtnt/tntsearch
src/TNTGeoSearch.php
TNTGeoSearch.findNearest
public function findNearest($currentLocation, $distance, $limit = 10) { $startTimer = microtime(true); $res = $this->buildQuery($currentLocation, $distance, $limit); $stopTimer = microtime(true); return [ 'ids' => $res->pluck('doc_id'), 'distances' => $res->pluck('distance'), 'hits' => $res->count(), 'execution_time' => round($stopTimer - $startTimer, 7) * 1000 ." ms" ]; }
php
public function findNearest($currentLocation, $distance, $limit = 10) { $startTimer = microtime(true); $res = $this->buildQuery($currentLocation, $distance, $limit); $stopTimer = microtime(true); return [ 'ids' => $res->pluck('doc_id'), 'distances' => $res->pluck('distance'), 'hits' => $res->count(), 'execution_time' => round($stopTimer - $startTimer, 7) * 1000 ." ms" ]; }
[ "public", "function", "findNearest", "(", "$", "currentLocation", ",", "$", "distance", ",", "$", "limit", "=", "10", ")", "{", "$", "startTimer", "=", "microtime", "(", "true", ")", ";", "$", "res", "=", "$", "this", "->", "buildQuery", "(", "$", "currentLocation", ",", "$", "distance", ",", "$", "limit", ")", ";", "$", "stopTimer", "=", "microtime", "(", "true", ")", ";", "return", "[", "'ids'", "=>", "$", "res", "->", "pluck", "(", "'doc_id'", ")", ",", "'distances'", "=>", "$", "res", "->", "pluck", "(", "'distance'", ")", ",", "'hits'", "=>", "$", "res", "->", "count", "(", ")", ",", "'execution_time'", "=>", "round", "(", "$", "stopTimer", "-", "$", "startTimer", ",", "7", ")", "*", "1000", ".", "\" ms\"", "]", ";", "}" ]
Distance is in KM
[ "Distance", "is", "in", "KM" ]
e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf
https://github.com/teamtnt/tntsearch/blob/e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf/src/TNTGeoSearch.php#L14-L28
train
teamtnt/tntsearch
src/Stemmer/ArabicStemmer.php
ArabicStemmer.stem
public static function stem($word) { $nounStem = self::roughStem( $word, self::$_nounMay, self::$_nounPre, self::$_nounPost, self::$_nounMaxPre, self::$_nounMaxPost, self::$_nounMinStem ); $verbStem = self::roughStem( $word, self::$_verbMay, self::$_verbPre, self::$_verbPost, self::$_verbMaxPre, self::$_verbMaxPost, self::$_verbMinStem ); if (mb_strlen($nounStem, 'UTF-8') < mb_strlen($verbStem, 'UTF-8')) { $stem = $nounStem; } else { $stem = $verbStem; } return $stem; }
php
public static function stem($word) { $nounStem = self::roughStem( $word, self::$_nounMay, self::$_nounPre, self::$_nounPost, self::$_nounMaxPre, self::$_nounMaxPost, self::$_nounMinStem ); $verbStem = self::roughStem( $word, self::$_verbMay, self::$_verbPre, self::$_verbPost, self::$_verbMaxPre, self::$_verbMaxPost, self::$_verbMinStem ); if (mb_strlen($nounStem, 'UTF-8') < mb_strlen($verbStem, 'UTF-8')) { $stem = $nounStem; } else { $stem = $verbStem; } return $stem; }
[ "public", "static", "function", "stem", "(", "$", "word", ")", "{", "$", "nounStem", "=", "self", "::", "roughStem", "(", "$", "word", ",", "self", "::", "$", "_nounMay", ",", "self", "::", "$", "_nounPre", ",", "self", "::", "$", "_nounPost", ",", "self", "::", "$", "_nounMaxPre", ",", "self", "::", "$", "_nounMaxPost", ",", "self", "::", "$", "_nounMinStem", ")", ";", "$", "verbStem", "=", "self", "::", "roughStem", "(", "$", "word", ",", "self", "::", "$", "_verbMay", ",", "self", "::", "$", "_verbPre", ",", "self", "::", "$", "_verbPost", ",", "self", "::", "$", "_verbMaxPre", ",", "self", "::", "$", "_verbMaxPost", ",", "self", "::", "$", "_verbMinStem", ")", ";", "if", "(", "mb_strlen", "(", "$", "nounStem", ",", "'UTF-8'", ")", "<", "mb_strlen", "(", "$", "verbStem", ",", "'UTF-8'", ")", ")", "{", "$", "stem", "=", "$", "nounStem", ";", "}", "else", "{", "$", "stem", "=", "$", "verbStem", ";", "}", "return", "$", "stem", ";", "}" ]
Get rough stem of the given Arabic word @param string $word Arabic word you would like to get its stem @return string Arabic stem of the word @author Khaled Al-Sham'aa <khaled@ar-php.org>
[ "Get", "rough", "stem", "of", "the", "given", "Arabic", "word" ]
e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf
https://github.com/teamtnt/tntsearch/blob/e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf/src/Stemmer/ArabicStemmer.php#L46-L64
train
teamtnt/tntsearch
src/Stemmer/GermanStemmer.php
GermanStemmer.step0a
private static function step0a($word) { $vstr = implode('', self::$vowels); $word = preg_replace('#([' . $vstr . '])u([' . $vstr . '])#u', '$1U$2', $word); $word = preg_replace('#([' . $vstr . '])y([' . $vstr . '])#u', '$1Y$2', $word); return $word; }
php
private static function step0a($word) { $vstr = implode('', self::$vowels); $word = preg_replace('#([' . $vstr . '])u([' . $vstr . '])#u', '$1U$2', $word); $word = preg_replace('#([' . $vstr . '])y([' . $vstr . '])#u', '$1Y$2', $word); return $word; }
[ "private", "static", "function", "step0a", "(", "$", "word", ")", "{", "$", "vstr", "=", "implode", "(", "''", ",", "self", "::", "$", "vowels", ")", ";", "$", "word", "=", "preg_replace", "(", "'#(['", ".", "$", "vstr", ".", "'])u(['", ".", "$", "vstr", ".", "'])#u'", ",", "'$1U$2'", ",", "$", "word", ")", ";", "$", "word", "=", "preg_replace", "(", "'#(['", ".", "$", "vstr", ".", "'])y(['", ".", "$", "vstr", ".", "'])#u'", ",", "'$1Y$2'", ",", "$", "word", ")", ";", "return", "$", "word", ";", "}" ]
Replaces to protect some characters @param string $word @return string mixed
[ "Replaces", "to", "protect", "some", "characters" ]
e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf
https://github.com/teamtnt/tntsearch/blob/e846d6b6a3c8e836ea6b46ab6ffb9ec458bf1caf/src/Stemmer/GermanStemmer.php#L93-L100
train
thecodingmachine/safe
generator/src/DocPage.php
DocPage.loadAndResolveFile
public function loadAndResolveFile(): \SimpleXMLElement { $content = \file_get_contents($this->path); $strpos = \strpos($content, '?>')+2; if (!\file_exists(__DIR__.'/../doc/entities/generated.ent')) { self::buildEntities(); } $path = \realpath(__DIR__.'/../doc/entities/generated.ent'); $content = \substr($content, 0, $strpos) .'<!DOCTYPE refentry SYSTEM "'.$path.'">' .\substr($content, $strpos+1); echo 'Loading '.$this->path."\n"; $elem = \simplexml_load_string($content, \SimpleXMLElement::class, LIBXML_DTDLOAD | LIBXML_NOENT); if ($elem === false) { throw new \RuntimeException('Invalid XML file for '.$this->path); } $elem->registerXPathNamespace('docbook', 'http://docbook.org/ns/docbook'); return $elem; }
php
public function loadAndResolveFile(): \SimpleXMLElement { $content = \file_get_contents($this->path); $strpos = \strpos($content, '?>')+2; if (!\file_exists(__DIR__.'/../doc/entities/generated.ent')) { self::buildEntities(); } $path = \realpath(__DIR__.'/../doc/entities/generated.ent'); $content = \substr($content, 0, $strpos) .'<!DOCTYPE refentry SYSTEM "'.$path.'">' .\substr($content, $strpos+1); echo 'Loading '.$this->path."\n"; $elem = \simplexml_load_string($content, \SimpleXMLElement::class, LIBXML_DTDLOAD | LIBXML_NOENT); if ($elem === false) { throw new \RuntimeException('Invalid XML file for '.$this->path); } $elem->registerXPathNamespace('docbook', 'http://docbook.org/ns/docbook'); return $elem; }
[ "public", "function", "loadAndResolveFile", "(", ")", ":", "\\", "SimpleXMLElement", "{", "$", "content", "=", "\\", "file_get_contents", "(", "$", "this", "->", "path", ")", ";", "$", "strpos", "=", "\\", "strpos", "(", "$", "content", ",", "'?>'", ")", "+", "2", ";", "if", "(", "!", "\\", "file_exists", "(", "__DIR__", ".", "'/../doc/entities/generated.ent'", ")", ")", "{", "self", "::", "buildEntities", "(", ")", ";", "}", "$", "path", "=", "\\", "realpath", "(", "__DIR__", ".", "'/../doc/entities/generated.ent'", ")", ";", "$", "content", "=", "\\", "substr", "(", "$", "content", ",", "0", ",", "$", "strpos", ")", ".", "'<!DOCTYPE refentry SYSTEM \"'", ".", "$", "path", ".", "'\">'", ".", "\\", "substr", "(", "$", "content", ",", "$", "strpos", "+", "1", ")", ";", "echo", "'Loading '", ".", "$", "this", "->", "path", ".", "\"\\n\"", ";", "$", "elem", "=", "\\", "simplexml_load_string", "(", "$", "content", ",", "\\", "SimpleXMLElement", "::", "class", ",", "LIBXML_DTDLOAD", "|", "LIBXML_NOENT", ")", ";", "if", "(", "$", "elem", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Invalid XML file for '", ".", "$", "this", "->", "path", ")", ";", "}", "$", "elem", "->", "registerXPathNamespace", "(", "'docbook'", ",", "'http://docbook.org/ns/docbook'", ")", ";", "return", "$", "elem", ";", "}" ]
Loads the XML file, resolving all DTD declared entities. @return \SimpleXMLElement
[ "Loads", "the", "XML", "file", "resolving", "all", "DTD", "declared", "entities", "." ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/DocPage.php#L130-L152
train
thecodingmachine/safe
generator/src/Type.php
Type.isClass
private static function isClass(string $type): bool { if ($type === '') { throw new EmptyTypeException('Empty type passed'); } if ($type === 'stdClass') { return true; } // Classes start with uppercase letters. Otherwise, it's most likely a scalar. if ($type[0] === strtoupper($type[0])) { return true; } return false; }
php
private static function isClass(string $type): bool { if ($type === '') { throw new EmptyTypeException('Empty type passed'); } if ($type === 'stdClass') { return true; } // Classes start with uppercase letters. Otherwise, it's most likely a scalar. if ($type[0] === strtoupper($type[0])) { return true; } return false; }
[ "private", "static", "function", "isClass", "(", "string", "$", "type", ")", ":", "bool", "{", "if", "(", "$", "type", "===", "''", ")", "{", "throw", "new", "EmptyTypeException", "(", "'Empty type passed'", ")", ";", "}", "if", "(", "$", "type", "===", "'stdClass'", ")", "{", "return", "true", ";", "}", "// Classes start with uppercase letters. Otherwise, it's most likely a scalar.", "if", "(", "$", "type", "[", "0", "]", "===", "strtoupper", "(", "$", "type", "[", "0", "]", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Returns true if the type passed in parameter is a class, false if it is scalar or resource @param string $type @return bool
[ "Returns", "true", "if", "the", "type", "passed", "in", "parameter", "is", "a", "class", "false", "if", "it", "is", "scalar", "or", "resource" ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/Type.php#L14-L27
train
thecodingmachine/safe
generator/src/Method.php
Method.removeString
private function removeString(string $string, string $search): string { $search = str_replace(' ', '\s+', $search); $result = preg_replace('/[\s\,]*'.$search.'/m', '', $string); if ($result === null) { throw new \RuntimeException('An error occurred while calling preg_replace'); } return $result; }
php
private function removeString(string $string, string $search): string { $search = str_replace(' ', '\s+', $search); $result = preg_replace('/[\s\,]*'.$search.'/m', '', $string); if ($result === null) { throw new \RuntimeException('An error occurred while calling preg_replace'); } return $result; }
[ "private", "function", "removeString", "(", "string", "$", "string", ",", "string", "$", "search", ")", ":", "string", "{", "$", "search", "=", "str_replace", "(", "' '", ",", "'\\s+'", ",", "$", "search", ")", ";", "$", "result", "=", "preg_replace", "(", "'/[\\s\\,]*'", ".", "$", "search", ".", "'/m'", ",", "''", ",", "$", "string", ")", ";", "if", "(", "$", "result", "===", "null", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'An error occurred while calling preg_replace'", ")", ";", "}", "return", "$", "result", ";", "}" ]
Removes a string, even if the string is split on multiple lines. @param string $string @param string $search @return string
[ "Removes", "a", "string", "even", "if", "the", "string", "is", "split", "on", "multiple", "lines", "." ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/Method.php#L150-L158
train
thecodingmachine/safe
generator/src/Method.php
Method.isOverloaded
public function isOverloaded(): bool { foreach ($this->getParams() as $parameter) { if ($parameter->isOptionalWithNoDefault() && !$parameter->isByReference()) { return true; } } return false; }
php
public function isOverloaded(): bool { foreach ($this->getParams() as $parameter) { if ($parameter->isOptionalWithNoDefault() && !$parameter->isByReference()) { return true; } } return false; }
[ "public", "function", "isOverloaded", "(", ")", ":", "bool", "{", "foreach", "(", "$", "this", "->", "getParams", "(", ")", "as", "$", "parameter", ")", "{", "if", "(", "$", "parameter", "->", "isOptionalWithNoDefault", "(", ")", "&&", "!", "$", "parameter", "->", "isByReference", "(", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
The function is overloaded if at least one parameter is optional with no default value and this parameter is not by reference. @return bool
[ "The", "function", "is", "overloaded", "if", "at", "least", "one", "parameter", "is", "optional", "with", "no", "default", "value", "and", "this", "parameter", "is", "not", "by", "reference", "." ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/Method.php#L215-L223
train
thecodingmachine/safe
generator/src/Scanner.php
Scanner.getIgnoredFunctions
private function getIgnoredFunctions(): array { if ($this->ignoredFunctions === null) { $ignoredFunctions = require __DIR__.'/../config/ignoredFunctions.php'; $specialCaseFunctions = require __DIR__.'/../config/specialCasesFunctions.php'; $this->ignoredFunctions = array_merge($ignoredFunctions, $specialCaseFunctions); } return $this->ignoredFunctions; }
php
private function getIgnoredFunctions(): array { if ($this->ignoredFunctions === null) { $ignoredFunctions = require __DIR__.'/../config/ignoredFunctions.php'; $specialCaseFunctions = require __DIR__.'/../config/specialCasesFunctions.php'; $this->ignoredFunctions = array_merge($ignoredFunctions, $specialCaseFunctions); } return $this->ignoredFunctions; }
[ "private", "function", "getIgnoredFunctions", "(", ")", ":", "array", "{", "if", "(", "$", "this", "->", "ignoredFunctions", "===", "null", ")", "{", "$", "ignoredFunctions", "=", "require", "__DIR__", ".", "'/../config/ignoredFunctions.php'", ";", "$", "specialCaseFunctions", "=", "require", "__DIR__", ".", "'/../config/specialCasesFunctions.php'", ";", "$", "this", "->", "ignoredFunctions", "=", "array_merge", "(", "$", "ignoredFunctions", ",", "$", "specialCaseFunctions", ")", ";", "}", "return", "$", "this", "->", "ignoredFunctions", ";", "}" ]
Returns the list of functions that must be ignored. @return string[]
[ "Returns", "the", "list", "of", "functions", "that", "must", "be", "ignored", "." ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/Scanner.php#L51-L60
train
thecodingmachine/safe
generator/src/FileCreator.php
FileCreator.generateXlsFile
public function generateXlsFile(array $protoFunctions, string $path): void { $spreadsheet = new Spreadsheet(); $numb = 1; $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Function name'); $sheet->setCellValue('B1', 'Status'); foreach ($protoFunctions as $protoFunction) { if ($protoFunction) { if (strpos($protoFunction, '=') === false && strpos($protoFunction, 'json') === false) { $status = 'classic'; } elseif (strpos($protoFunction, 'json')) { $status = 'json'; } else { $status = 'opt'; } $sheet->setCellValue('A'.$numb, $protoFunction); $sheet->setCellValue('B'.$numb++, $status); } } $writer = new Xlsx($spreadsheet); $writer->save($path); }
php
public function generateXlsFile(array $protoFunctions, string $path): void { $spreadsheet = new Spreadsheet(); $numb = 1; $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Function name'); $sheet->setCellValue('B1', 'Status'); foreach ($protoFunctions as $protoFunction) { if ($protoFunction) { if (strpos($protoFunction, '=') === false && strpos($protoFunction, 'json') === false) { $status = 'classic'; } elseif (strpos($protoFunction, 'json')) { $status = 'json'; } else { $status = 'opt'; } $sheet->setCellValue('A'.$numb, $protoFunction); $sheet->setCellValue('B'.$numb++, $status); } } $writer = new Xlsx($spreadsheet); $writer->save($path); }
[ "public", "function", "generateXlsFile", "(", "array", "$", "protoFunctions", ",", "string", "$", "path", ")", ":", "void", "{", "$", "spreadsheet", "=", "new", "Spreadsheet", "(", ")", ";", "$", "numb", "=", "1", ";", "$", "sheet", "=", "$", "spreadsheet", "->", "getActiveSheet", "(", ")", ";", "$", "sheet", "->", "setCellValue", "(", "'A1'", ",", "'Function name'", ")", ";", "$", "sheet", "->", "setCellValue", "(", "'B1'", ",", "'Status'", ")", ";", "foreach", "(", "$", "protoFunctions", "as", "$", "protoFunction", ")", "{", "if", "(", "$", "protoFunction", ")", "{", "if", "(", "strpos", "(", "$", "protoFunction", ",", "'='", ")", "===", "false", "&&", "strpos", "(", "$", "protoFunction", ",", "'json'", ")", "===", "false", ")", "{", "$", "status", "=", "'classic'", ";", "}", "elseif", "(", "strpos", "(", "$", "protoFunction", ",", "'json'", ")", ")", "{", "$", "status", "=", "'json'", ";", "}", "else", "{", "$", "status", "=", "'opt'", ";", "}", "$", "sheet", "->", "setCellValue", "(", "'A'", ".", "$", "numb", ",", "$", "protoFunction", ")", ";", "$", "sheet", "->", "setCellValue", "(", "'B'", ".", "$", "numb", "++", ",", "$", "status", ")", ";", "}", "}", "$", "writer", "=", "new", "Xlsx", "(", "$", "spreadsheet", ")", ";", "$", "writer", "->", "save", "(", "$", "path", ")", ";", "}" ]
This function generate an xls file @param string[] $protoFunctions @param string $path
[ "This", "function", "generate", "an", "xls", "file" ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/FileCreator.php#L19-L43
train
thecodingmachine/safe
generator/src/FileCreator.php
FileCreator.generatePhpFile
public function generatePhpFile(array $functions, string $path): void { $path = rtrim($path, '/').'/'; $phpFunctionsByModule = []; foreach ($functions as $function) { $writePhpFunction = new WritePhpFunction($function); $phpFunctionsByModule[$function->getModuleName()][] = $writePhpFunction->getPhpFunctionalFunction(); } foreach ($phpFunctionsByModule as $module => $phpFunctions) { $lcModule = \lcfirst($module); $stream = \fopen($path.$lcModule.'.php', 'w'); if ($stream === false) { throw new \RuntimeException('Unable to write to '.$path); } \fwrite($stream, "<?php\n namespace Safe; use Safe\\Exceptions\\".self::toExceptionName($module). '; '); foreach ($phpFunctions as $phpFunction) { \fwrite($stream, $phpFunction."\n"); } \fclose($stream); } }
php
public function generatePhpFile(array $functions, string $path): void { $path = rtrim($path, '/').'/'; $phpFunctionsByModule = []; foreach ($functions as $function) { $writePhpFunction = new WritePhpFunction($function); $phpFunctionsByModule[$function->getModuleName()][] = $writePhpFunction->getPhpFunctionalFunction(); } foreach ($phpFunctionsByModule as $module => $phpFunctions) { $lcModule = \lcfirst($module); $stream = \fopen($path.$lcModule.'.php', 'w'); if ($stream === false) { throw new \RuntimeException('Unable to write to '.$path); } \fwrite($stream, "<?php\n namespace Safe; use Safe\\Exceptions\\".self::toExceptionName($module). '; '); foreach ($phpFunctions as $phpFunction) { \fwrite($stream, $phpFunction."\n"); } \fclose($stream); } }
[ "public", "function", "generatePhpFile", "(", "array", "$", "functions", ",", "string", "$", "path", ")", ":", "void", "{", "$", "path", "=", "rtrim", "(", "$", "path", ",", "'/'", ")", ".", "'/'", ";", "$", "phpFunctionsByModule", "=", "[", "]", ";", "foreach", "(", "$", "functions", "as", "$", "function", ")", "{", "$", "writePhpFunction", "=", "new", "WritePhpFunction", "(", "$", "function", ")", ";", "$", "phpFunctionsByModule", "[", "$", "function", "->", "getModuleName", "(", ")", "]", "[", "]", "=", "$", "writePhpFunction", "->", "getPhpFunctionalFunction", "(", ")", ";", "}", "foreach", "(", "$", "phpFunctionsByModule", "as", "$", "module", "=>", "$", "phpFunctions", ")", "{", "$", "lcModule", "=", "\\", "lcfirst", "(", "$", "module", ")", ";", "$", "stream", "=", "\\", "fopen", "(", "$", "path", ".", "$", "lcModule", ".", "'.php'", ",", "'w'", ")", ";", "if", "(", "$", "stream", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to write to '", ".", "$", "path", ")", ";", "}", "\\", "fwrite", "(", "$", "stream", ",", "\"<?php\\n\nnamespace Safe;\n\nuse Safe\\\\Exceptions\\\\\"", ".", "self", "::", "toExceptionName", "(", "$", "module", ")", ".", "';\n\n'", ")", ";", "foreach", "(", "$", "phpFunctions", "as", "$", "phpFunction", ")", "{", "\\", "fwrite", "(", "$", "stream", ",", "$", "phpFunction", ".", "\"\\n\"", ")", ";", "}", "\\", "fclose", "(", "$", "stream", ")", ";", "}", "}" ]
This function generate an improved php lib function in a php file @param Method[] $functions @param string $path
[ "This", "function", "generate", "an", "improved", "php", "lib", "function", "in", "a", "php", "file" ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/FileCreator.php#L51-L77
train
thecodingmachine/safe
generator/src/FileCreator.php
FileCreator.generateFunctionsList
public function generateFunctionsList(array $functions, string $path): void { $functionNames = $this->getFunctionsNameList($functions); $stream = fopen($path, 'w'); if ($stream === false) { throw new \RuntimeException('Unable to write to '.$path); } fwrite($stream, "<?php\n return [\n"); foreach ($functionNames as $functionName) { fwrite($stream, ' '.\var_export($functionName, true).",\n"); } fwrite($stream, "];\n"); fclose($stream); }
php
public function generateFunctionsList(array $functions, string $path): void { $functionNames = $this->getFunctionsNameList($functions); $stream = fopen($path, 'w'); if ($stream === false) { throw new \RuntimeException('Unable to write to '.$path); } fwrite($stream, "<?php\n return [\n"); foreach ($functionNames as $functionName) { fwrite($stream, ' '.\var_export($functionName, true).",\n"); } fwrite($stream, "];\n"); fclose($stream); }
[ "public", "function", "generateFunctionsList", "(", "array", "$", "functions", ",", "string", "$", "path", ")", ":", "void", "{", "$", "functionNames", "=", "$", "this", "->", "getFunctionsNameList", "(", "$", "functions", ")", ";", "$", "stream", "=", "fopen", "(", "$", "path", ",", "'w'", ")", ";", "if", "(", "$", "stream", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to write to '", ".", "$", "path", ")", ";", "}", "fwrite", "(", "$", "stream", ",", "\"<?php\\n\nreturn [\\n\"", ")", ";", "foreach", "(", "$", "functionNames", "as", "$", "functionName", ")", "{", "fwrite", "(", "$", "stream", ",", "' '", ".", "\\", "var_export", "(", "$", "functionName", ",", "true", ")", ".", "\",\\n\"", ")", ";", "}", "fwrite", "(", "$", "stream", ",", "\"];\\n\"", ")", ";", "fclose", "(", "$", "stream", ")", ";", "}" ]
This function generate a PHP file containing the list of functions we can handle. @param Method[] $functions @param string $path
[ "This", "function", "generate", "a", "PHP", "file", "containing", "the", "list", "of", "functions", "we", "can", "handle", "." ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/FileCreator.php#L99-L113
train
thecodingmachine/safe
generator/src/FileCreator.php
FileCreator.generateRectorFile
public function generateRectorFile(array $functions, string $path): void { $functionNames = $this->getFunctionsNameList($functions); $stream = fopen($path, 'w'); if ($stream === false) { throw new \RuntimeException('Unable to write to '.$path); } fwrite($stream, "# This rector file is replacing all core PHP functions with the equivalent \"safe\" functions # It is targetting Rector 0.4.x versions. # If you are using Rector 0.3, please upgrade your Rector version services: Rector\Rector\Function_\RenameFunctionRector: \$oldFunctionToNewFunction: "); foreach ($functionNames as $functionName) { fwrite($stream, ' '.$functionName.": 'Safe\\".$functionName."'\n"); } fclose($stream); }
php
public function generateRectorFile(array $functions, string $path): void { $functionNames = $this->getFunctionsNameList($functions); $stream = fopen($path, 'w'); if ($stream === false) { throw new \RuntimeException('Unable to write to '.$path); } fwrite($stream, "# This rector file is replacing all core PHP functions with the equivalent \"safe\" functions # It is targetting Rector 0.4.x versions. # If you are using Rector 0.3, please upgrade your Rector version services: Rector\Rector\Function_\RenameFunctionRector: \$oldFunctionToNewFunction: "); foreach ($functionNames as $functionName) { fwrite($stream, ' '.$functionName.": 'Safe\\".$functionName."'\n"); } fclose($stream); }
[ "public", "function", "generateRectorFile", "(", "array", "$", "functions", ",", "string", "$", "path", ")", ":", "void", "{", "$", "functionNames", "=", "$", "this", "->", "getFunctionsNameList", "(", "$", "functions", ")", ";", "$", "stream", "=", "fopen", "(", "$", "path", ",", "'w'", ")", ";", "if", "(", "$", "stream", "===", "false", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Unable to write to '", ".", "$", "path", ")", ";", "}", "fwrite", "(", "$", "stream", ",", "\"# This rector file is replacing all core PHP functions with the equivalent \\\"safe\\\" functions\n# It is targetting Rector 0.4.x versions.\n# If you are using Rector 0.3, please upgrade your Rector version\nservices:\n Rector\\Rector\\Function_\\RenameFunctionRector:\n \\$oldFunctionToNewFunction:\n\"", ")", ";", "foreach", "(", "$", "functionNames", "as", "$", "functionName", ")", "{", "fwrite", "(", "$", "stream", ",", "' '", ".", "$", "functionName", ".", "\": 'Safe\\\\\"", ".", "$", "functionName", ".", "\"'\\n\"", ")", ";", "}", "fclose", "(", "$", "stream", ")", ";", "}" ]
This function generate a rector yml file containing a replacer for all functions @param Method[] $functions @param string $path
[ "This", "function", "generate", "a", "rector", "yml", "file", "containing", "a", "replacer", "for", "all", "functions" ]
677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5
https://github.com/thecodingmachine/safe/blob/677c032510cd0ba4e4c6f5d6652f82e8ea4a35f5/generator/src/FileCreator.php#L121-L139
train
phpbench/phpbench
lib/Benchmark/Metadata/MetadataFactory.php
MetadataFactory.getMetadataForFile
public function getMetadataForFile(string $file): ?BenchmarkMetadata { $hierarchy = $this->reflector->reflect($file); if ($hierarchy->isEmpty()) { return null; } try { $top = $hierarchy->getTop(); } catch (\InvalidArgumentException $exception) { return null; } if (true === $top->abstract) { return null; } $metadata = $this->driver->getMetadataForHierarchy($hierarchy); $this->validateBenchmark($hierarchy, $metadata); // validate the subject and load the parameter sets foreach ($metadata->getSubjects() as $subject) { $this->validateSubject($hierarchy, $subject); $paramProviders = $subject->getParamProviders(); $parameterSets = $this->reflector->getParameterSets($metadata->getPath(), $paramProviders); foreach ($parameterSets as $parameterSet) { if (!is_array($parameterSet)) { throw new \InvalidArgumentException(sprintf( 'Each parameter set must be an array, got "%s" for %s::%s', gettype($parameterSet), $metadata->getClass(), $subject->getName() )); } } $subject->setParameterSets($parameterSets); } return $metadata; }
php
public function getMetadataForFile(string $file): ?BenchmarkMetadata { $hierarchy = $this->reflector->reflect($file); if ($hierarchy->isEmpty()) { return null; } try { $top = $hierarchy->getTop(); } catch (\InvalidArgumentException $exception) { return null; } if (true === $top->abstract) { return null; } $metadata = $this->driver->getMetadataForHierarchy($hierarchy); $this->validateBenchmark($hierarchy, $metadata); // validate the subject and load the parameter sets foreach ($metadata->getSubjects() as $subject) { $this->validateSubject($hierarchy, $subject); $paramProviders = $subject->getParamProviders(); $parameterSets = $this->reflector->getParameterSets($metadata->getPath(), $paramProviders); foreach ($parameterSets as $parameterSet) { if (!is_array($parameterSet)) { throw new \InvalidArgumentException(sprintf( 'Each parameter set must be an array, got "%s" for %s::%s', gettype($parameterSet), $metadata->getClass(), $subject->getName() )); } } $subject->setParameterSets($parameterSets); } return $metadata; }
[ "public", "function", "getMetadataForFile", "(", "string", "$", "file", ")", ":", "?", "BenchmarkMetadata", "{", "$", "hierarchy", "=", "$", "this", "->", "reflector", "->", "reflect", "(", "$", "file", ")", ";", "if", "(", "$", "hierarchy", "->", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "try", "{", "$", "top", "=", "$", "hierarchy", "->", "getTop", "(", ")", ";", "}", "catch", "(", "\\", "InvalidArgumentException", "$", "exception", ")", "{", "return", "null", ";", "}", "if", "(", "true", "===", "$", "top", "->", "abstract", ")", "{", "return", "null", ";", "}", "$", "metadata", "=", "$", "this", "->", "driver", "->", "getMetadataForHierarchy", "(", "$", "hierarchy", ")", ";", "$", "this", "->", "validateBenchmark", "(", "$", "hierarchy", ",", "$", "metadata", ")", ";", "// validate the subject and load the parameter sets", "foreach", "(", "$", "metadata", "->", "getSubjects", "(", ")", "as", "$", "subject", ")", "{", "$", "this", "->", "validateSubject", "(", "$", "hierarchy", ",", "$", "subject", ")", ";", "$", "paramProviders", "=", "$", "subject", "->", "getParamProviders", "(", ")", ";", "$", "parameterSets", "=", "$", "this", "->", "reflector", "->", "getParameterSets", "(", "$", "metadata", "->", "getPath", "(", ")", ",", "$", "paramProviders", ")", ";", "foreach", "(", "$", "parameterSets", "as", "$", "parameterSet", ")", "{", "if", "(", "!", "is_array", "(", "$", "parameterSet", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Each parameter set must be an array, got \"%s\" for %s::%s'", ",", "gettype", "(", "$", "parameterSet", ")", ",", "$", "metadata", "->", "getClass", "(", ")", ",", "$", "subject", "->", "getName", "(", ")", ")", ")", ";", "}", "}", "$", "subject", "->", "setParameterSets", "(", "$", "parameterSets", ")", ";", "}", "return", "$", "metadata", ";", "}" ]
Return a Benchmark instance for the given file or NULL if the given file contains no classes, or the class in the given file is abstract.
[ "Return", "a", "Benchmark", "instance", "for", "the", "given", "file", "or", "NULL", "if", "the", "given", "file", "contains", "no", "classes", "or", "the", "class", "in", "the", "given", "file", "is", "abstract", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Benchmark/Metadata/MetadataFactory.php#L49-L90
train
phpbench/phpbench
lib/Serializer/XmlDecoder.php
XmlDecoder.decode
public function decode(Document $document) { $suites = []; foreach ($document->query('//suite') as $suiteEl) { $suites[] = $this->processSuite($suiteEl); } return new SuiteCollection($suites); }
php
public function decode(Document $document) { $suites = []; foreach ($document->query('//suite') as $suiteEl) { $suites[] = $this->processSuite($suiteEl); } return new SuiteCollection($suites); }
[ "public", "function", "decode", "(", "Document", "$", "document", ")", "{", "$", "suites", "=", "[", "]", ";", "foreach", "(", "$", "document", "->", "query", "(", "'//suite'", ")", "as", "$", "suiteEl", ")", "{", "$", "suites", "[", "]", "=", "$", "this", "->", "processSuite", "(", "$", "suiteEl", ")", ";", "}", "return", "new", "SuiteCollection", "(", "$", "suites", ")", ";", "}" ]
Decode a PHPBench XML document into a SuiteCollection. @param Document $document @return SuiteCollection
[ "Decode", "a", "PHPBench", "XML", "document", "into", "a", "SuiteCollection", "." ]
dccc67dd52ec47123e883afdd27f8ac8b06e68b7
https://github.com/phpbench/phpbench/blob/dccc67dd52ec47123e883afdd27f8ac8b06e68b7/lib/Serializer/XmlDecoder.php#L43-L52
train